137 lines
4.2 KiB
Go
137 lines
4.2 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
"net/url"
|
|
"sea-vhost/internal/store"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
func validateWebhookURL(raw string) (*url.URL, error) {
|
|
u, e := url.Parse(raw)
|
|
if e != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" || u.RawQuery != "" || (u.Port() != "" && u.Port() != "443") || len(raw) > 2048 || strings.ContainsAny(raw, "\r\n\x00") {
|
|
return nil, errors.New("回调地址必须为 HTTPS 公网地址,端口为 443,不能包含凭据或查询参数")
|
|
}
|
|
if ip, e := netip.ParseAddr(u.Hostname()); e == nil && !publicWebhookIP(ip) {
|
|
return nil, errors.New("回调禁止使用内网或保留地址")
|
|
}
|
|
if strings.EqualFold(u.Hostname(), "localhost") {
|
|
return nil, errors.New("回调禁止使用本机地址")
|
|
}
|
|
return u, nil
|
|
}
|
|
func publicWebhookIP(ip netip.Addr) bool {
|
|
ip = ip.Unmap()
|
|
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
|
|
return false
|
|
}
|
|
for _, cidr := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "2001::/32", "2002::/16"} {
|
|
if netip.MustParsePrefix(cidr).Contains(ip) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
func webhookClient(ctx context.Context, u *url.URL) (*http.Client, error) {
|
|
resolved, e := net.DefaultResolver.LookupNetIP(ctx, "ip", u.Hostname())
|
|
if e != nil || len(resolved) == 0 {
|
|
return nil, errors.New("DNS unavailable")
|
|
}
|
|
for _, ip := range resolved {
|
|
if !publicWebhookIP(ip) {
|
|
return nil, errors.New("DNS resolved to a restricted address")
|
|
}
|
|
}
|
|
transport := &http.Transport{Proxy: nil, TLSClientConfig: &tls.Config{ServerName: u.Hostname(), MinVersion: tls.VersionTLS12}, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
|
var last error
|
|
for _, ip := range resolved {
|
|
conn, e := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), "443"))
|
|
if e == nil {
|
|
return conn, nil
|
|
}
|
|
last = e
|
|
}
|
|
return nil, last
|
|
}}
|
|
return &http.Client{Transport: transport, Timeout: 12 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, nil
|
|
}
|
|
func (s *Server) runIntegrationWebhooks(ctx context.Context) {
|
|
for ctx.Err() == nil {
|
|
_ = s.store.QueueIntegrationWebhooks(ctx)
|
|
rows, e := s.store.IntegrationWebhooks(ctx, true)
|
|
if e == nil {
|
|
for _, v := range rows {
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
s.deliverIntegrationWebhook(ctx, v)
|
|
}
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-time.After(30 * time.Second):
|
|
}
|
|
}
|
|
}
|
|
func (s *Server) deliverIntegrationWebhook(ctx context.Context, v store.IntegrationWebhook) {
|
|
task, cancel := context.WithTimeout(ctx, 15*time.Second)
|
|
defer cancel()
|
|
delivered := false
|
|
status := 0
|
|
defer func() {
|
|
done, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
|
defer cancel()
|
|
_ = s.store.FinishIntegrationWebhook(done, v, delivered, status)
|
|
}()
|
|
u, e := validateWebhookURL(v.URL)
|
|
if e != nil {
|
|
return
|
|
}
|
|
secret, e := s.secretBox.Open("integration-webhook:"+v.Prefix, v.Secret)
|
|
if e != nil {
|
|
return
|
|
}
|
|
job, e := s.store.AdminBatch(task, v.BatchID, false)
|
|
if e != nil {
|
|
return
|
|
}
|
|
job.Items = nil
|
|
body, _ := json.Marshal(map[string]any{"event": "batch.completed", "eventId": v.EventID, "batch": job})
|
|
stamp := strconv.FormatInt(time.Now().Unix(), 10)
|
|
client, e := webhookClient(task, u)
|
|
if e != nil {
|
|
return
|
|
}
|
|
defer client.CloseIdleConnections()
|
|
request, e := http.NewRequestWithContext(task, "POST", v.URL, bytes.NewReader(body))
|
|
if e != nil {
|
|
return
|
|
}
|
|
request.Header.Set("Content-Type", "application/json")
|
|
request.Header.Set("X-Sea-Event", v.EventID)
|
|
request.Header.Set("X-Sea-Timestamp", stamp)
|
|
request.Header.Set("X-Sea-Signature", "sha256="+webhookSignature(secret, stamp, v.EventID, body))
|
|
if !s.store.IntegrationKeyActive(task, v.KeyID) {
|
|
return
|
|
}
|
|
response, e := client.Do(request)
|
|
if e != nil {
|
|
return
|
|
}
|
|
defer response.Body.Close()
|
|
_, _ = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
|
status = response.StatusCode
|
|
delivered = status >= 200 && status < 300
|
|
}
|