package web import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "strings" "time" "veinsforge/internal/auth" "veinsforge/internal/data" ) func (s *Server) validateWebhookURL(ctx context.Context, raw string) error { u, err := url.Parse(raw) if err != nil || u.Host == "" { return errors.New("invalid webhook URL") } if u.Scheme != "http" && u.Scheme != "https" { return errors.New("webhook URL must use http or https") } if u.User != nil { return errors.New("webhook URL must not contain credentials") } host := u.Hostname() port := u.Port() if port == "" { if u.Scheme == "https" { port = "443" } else { port = "80" } } ips, err := net.DefaultResolver.LookupIPAddr(ctx, host) if err != nil { return errors.New("webhook host does not resolve") } for _, ip := range ips { if isPublicIP(ip.IP) { return nil } } return errors.New("webhook host is not a public address") } func (s *Server) webhookHTTPClient() *http.Client { dialer := &net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second} transport := &http.Transport{ Proxy: nil, DialContext: safeDialContext(dialer), TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 8 * time.Second, MaxIdleConns: 4, IdleConnTimeout: 30 * time.Second, } return &http.Client{ Transport: transport, Timeout: 10 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) >= 3 { return errors.New("too many redirects") } if req.URL.Scheme != "http" && req.URL.Scheme != "https" { return errors.New("redirect to unsupported scheme") } if err := s.validateWebhookURL(req.Context(), req.URL.String()); err != nil { return err } return nil }, } } func safeDialContext(dialer *net.Dialer) func(ctx context.Context, network, address string) (net.Conn, error) { return func(ctx context.Context, network, address string) (net.Conn, error) { host, port, err := net.SplitHostPort(address) if err != nil { return nil, err } ips, err := net.DefaultResolver.LookupIPAddr(ctx, host) if err != nil { return nil, err } for _, ip := range ips { if !isPublicIP(ip.IP) { continue } return dialer.DialContext(ctx, network, net.JoinHostPort(ip.IP.String(), port)) } return nil, errors.New("destination resolves only to private addresses") } } func isPublicIP(ip net.IP) bool { if ip == nil || ip.IsLoopback() || ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsPrivate() { return false } if v4 := ip.To4(); v4 != nil { if v4[0] == 0 || v4[0] == 127 || v4[0] >= 224 { return false } if v4[0] == 169 && v4[1] == 254 { return false } if v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127 { return false } if v4[0] == 192 && v4[1] == 0 && v4[2] == 0 { return false } } if len(ip) == net.IPv6len && ip[0]&0xfe == 0xfc { return false } return true } func (s *Server) dispatchWebhook(repo *data.Repo, actor *data.User, event string, payload any) { if repo == nil { return } hooks, err := s.data.ListWebhooks(context.Background(), repo.ID) if err != nil { return } actorName := "" if actor != nil { actorName = actor.Username } body := map[string]any{ "event": event, "timestamp": time.Now().UTC().Format(time.RFC3339), "repository": map[string]any{"id": repo.ID, "owner": repo.OwnerName, "name": repo.Name, "private": repo.Visibility == "private"}, "sender": map[string]any{"username": actorName}, "payload": payload, } for _, hook := range hooks { if !hook.Active || !webhookWants(hook.Events, event) { continue } select { case s.webhookSem <- struct{}{}: go func(h *data.Webhook) { defer func() { <-s.webhookSem }() s.deliverWebhook(h, body) }(hook) default: if s.logger != nil { s.logger.Printf("webhook queue full; dropping event for hook %d", hook.ID) } } } } func webhookWants(events, event string) bool { if strings.TrimSpace(events) == "" || events == "*" { return true } for _, e := range strings.Split(events, ",") { if strings.TrimSpace(e) == event { return true } } return false } func (s *Server) deliverWebhook(hook *data.Webhook, body map[string]any) { delivery, _ := auth.RandomToken(16) payload := make(map[string]any, len(body)+1) for k, v := range body { payload[k] = v } payload["delivery"] = delivery raw, err := json.Marshal(payload) if err != nil { return } mac := hmac.New(sha256.New, []byte(hook.Secret)) mac.Write(raw) signature := "sha256=" + hex.EncodeToString(mac.Sum(nil)) client := s.webhookHTTPClient() status := 0 ok := false for attempt := 0; attempt < 3; attempt++ { ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) req, err := http.NewRequestWithContext(ctx, http.MethodPost, hook.URL, bytes.NewReader(raw)) if err != nil { cancel() break } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", "veinsforge-webhook/1") req.Header.Set("X-Veinsforge-Event", fmt.Sprint(body["event"])) req.Header.Set("X-Veinsforge-Delivery", delivery) req.Header.Set("X-Veinsforge-Signature", signature) resp, err := client.Do(req) if err != nil { cancel() time.Sleep(time.Duration(attempt+1) * time.Second) continue } _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) resp.Body.Close() status = resp.StatusCode cancel() if status >= 200 && status < 300 { ok = true break } if status < 500 && status != 429 { break } time.Sleep(time.Duration(attempt+1) * time.Second) } s.data.RecordWebhookDelivery(context.Background(), hook.ID, status, ok) if !ok && s.logger != nil { s.logger.Printf("webhook %d delivery failed (status %d)", hook.ID, status) } }