internal/webhook/webhook.go
200 lines · 6099 bytes
1// Package webhook delivers events to registered endpoints: HMAC-signed
2// JSON POSTs with bounded retries, exponential backoff, and dead-lettering.
3package webhook
4
5import (
6 "bytes"
7 "context"
8 "crypto/hmac"
9 "crypto/sha256"
10 "encoding/hex"
11 "encoding/json"
12 "fmt"
13 "io"
14 "log/slog"
15 "net"
16 "net/http"
17 "net/url"
18 "time"
19
20 "gitbay.org/gitbay/internal/store"
21)
22
23// ValidateURL rejects URLs a webhook must not target: non-HTTP schemes and,
24// unless allowLocal, anything resolving to loopback, private, or link-local
25// addresses (SSRF).
26func ValidateURL(raw string, allowLocal bool) error {
27 u, err := url.Parse(raw)
28 if err != nil {
29 return fmt.Errorf("invalid URL: %w", err)
30 }
31 if u.Scheme != "http" && u.Scheme != "https" {
32 return fmt.Errorf("webhook URLs must be http or https")
33 }
34 if u.Hostname() == "" {
35 return fmt.Errorf("webhook URL has no host")
36 }
37 if allowLocal {
38 return nil
39 }
40 ips, err := net.LookupIP(u.Hostname())
41 if err != nil {
42 return fmt.Errorf("cannot resolve %s: %w", u.Hostname(), err)
43 }
44 if err := CheckAddrs(u.Hostname(), ips, allowLocal); err != nil {
45 return fmt.Errorf("webhook target %s resolves to a private or local address; refusing (SSRF)", u.Hostname())
46 }
47 return nil
48}
49
50// CheckAddrs refuses host when any of its resolved addresses is
51// loopback, private, shared (100.64.0.0/10), link-local, multicast or
52// unspecified, unless allowLocal. A caller resolves immediately before
53// connecting and connects only to the addresses it checked.
54func CheckAddrs(host string, ips []net.IP, allowLocal bool) error {
55 if allowLocal {
56 return nil
57 }
58 for _, ip := range ips {
59 if isForbidden(ip) {
60 return fmt.Errorf("%s resolves to private or local address %s; refusing (SSRF)", host, ip)
61 }
62 }
63 return nil
64}
65
66// cgnat is the shared address space of RFC 6598, which carriers and
67// overlay networks such as Tailscale use as private space.
68var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
69
70func isForbidden(ip net.IP) bool {
71 return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() ||
72 ip.IsMulticast() || ip.IsUnspecified() || cgnat.Contains(ip)
73}
74
75type Deliverer struct {
76 St *store.Store
77 AllowLocal bool
78 RetryBase time.Duration // first retry delay; doubles per attempt
79 MaxAttempts int
80 client *http.Client
81}
82
83// New builds a deliverer whose dialer re-checks resolved addresses at
84// connect time, so a DNS answer that changes after ValidateURL still cannot
85// reach private space.
86func New(st *store.Store, allowLocal bool, retryBase time.Duration) *Deliverer {
87 d := &Deliverer{St: st, AllowLocal: allowLocal, RetryBase: retryBase, MaxAttempts: 5}
88 dialer := &net.Dialer{Timeout: 5 * time.Second}
89 d.client = &http.Client{
90 Timeout: 10 * time.Second,
91 CheckRedirect: func(*http.Request, []*http.Request) error {
92 return http.ErrUseLastResponse // never follow redirects
93 },
94 Transport: &http.Transport{
95 DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
96 host, port, err := net.SplitHostPort(addr)
97 if err != nil {
98 return nil, err
99 }
100 ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
101 if err != nil {
102 return nil, err
103 }
104 for _, ip := range ips {
105 if !allowLocal && isForbidden(ip) {
106 return nil, fmt.Errorf("refusing connection to private address %s", ip)
107 }
108 }
109 return dialer.DialContext(ctx, network, net.JoinHostPort(ips[0].String(), port))
110 },
111 },
112 }
113 return d
114}
115
116// Run polls for due deliveries until ctx is done.
117func (d *Deliverer) Run(ctx context.Context) {
118 tick := time.NewTicker(2 * time.Second)
119 defer tick.Stop()
120 for {
121 select {
122 case <-ctx.Done():
123 return
124 case <-tick.C:
125 due, err := d.St.DueDeliveries(20)
126 if err != nil {
127 slog.Error("webhook: listing due deliveries", "err", err)
128 continue
129 }
130 for _, dl := range due {
131 d.deliver(ctx, dl)
132 }
133 }
134 }
135}
136
137type payload struct {
138 Event string `json:"event"`
139 Repo string `json:"repo"`
140 Actor string `json:"actor,omitempty"`
141 CreatedAt string `json:"created_at"`
142 Data json.RawMessage `json:"data"`
143}
144
145func (d *Deliverer) deliver(ctx context.Context, dl store.Delivery) {
146 body, err := json.Marshal(payload{
147 Event: dl.EventKind, Repo: dl.RepoPath, Actor: dl.Actor,
148 CreatedAt: dl.EventAt, Data: json.RawMessage(dl.DataJSON),
149 })
150 if err != nil {
151 d.fail(dl, 0, "marshal: "+err.Error())
152 return
153 }
154 req, err := http.NewRequestWithContext(ctx, "POST", dl.URL, bytes.NewReader(body))
155 if err != nil {
156 d.fail(dl, 0, "request: "+err.Error())
157 return
158 }
159 req.Header.Set("Content-Type", "application/json")
160 req.Header.Set("User-Agent", "gitbay-webhook")
161 req.Header.Set("X-Gitbay-Event", dl.EventKind)
162 req.Header.Set("X-Gitbay-Delivery", fmt.Sprint(dl.ID))
163 if dl.Secret != "" {
164 mac := hmac.New(sha256.New, []byte(dl.Secret))
165 mac.Write(body)
166 req.Header.Set("X-Gitbay-Signature-256", "sha256="+hex.EncodeToString(mac.Sum(nil)))
167 }
168
169 resp, err := d.client.Do(req)
170 if err != nil {
171 d.fail(dl, 0, err.Error())
172 return
173 }
174 io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
175 resp.Body.Close()
176 if resp.StatusCode >= 200 && resp.StatusCode < 300 {
177 if err := d.St.MarkDelivered(dl.ID, resp.StatusCode); err != nil {
178 slog.Error("webhook: marking delivered", "err", err)
179 }
180 return
181 }
182 d.fail(dl, resp.StatusCode, fmt.Sprintf("endpoint returned %d", resp.StatusCode))
183}
184
185// fail schedules a retry with exponential backoff, dead-lettering after
186// MaxAttempts.
187func (d *Deliverer) fail(dl store.Delivery, status int, msg string) {
188 attempt := dl.Attempts + 1 // the one that just happened
189 if attempt >= d.MaxAttempts {
190 if err := d.St.MarkAttemptFailed(dl.ID, status, msg, nil); err != nil {
191 slog.Error("webhook: dead-lettering", "err", err)
192 }
193 slog.Warn("webhook dead-lettered", "delivery", dl.ID, "url", dl.URL, "err", msg)
194 return
195 }
196 next := time.Now().Add(d.RetryBase << (attempt - 1))
197 if err := d.St.MarkAttemptFailed(dl.ID, status, msg, &next); err != nil {
198 slog.Error("webhook: scheduling retry", "err", err)
199 }
200}