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