Something went wrong. Try again.
Webhook-to-SSE gateway with hierarchical topic routing and signature verification
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184package main
import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "errors" "io" "net" "net/http" "net/url" "strconv" "time")
// deliveryTimeout bounds one request, from its dial to the last byte of// the response that wicket reads.const deliveryTimeout = 10 * time.Second
// responseLimit is how much of a response wicket reads before it closes// the connection. It uses only the status, and a target that answers// with an endless body must not hold the request open.const responseLimit = 64 << 10
// The statuses of a request that got no response.const ( statusConnectFailed = "connect_failed" statusTimeout = "timeout")
// newDeliveryClient returns the client that delivers. It follows no// redirect, so a target cannot send an event on to a URL that the// configuration does not name, and it uses no proxy from the// environment.func newDeliveryClient() *http.Client { return &http.Client{ Timeout: deliveryTimeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, Transport: &http.Transport{ DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: deliveryTimeout, IdleConnTimeout: 90 * time.Second, }, }}
// An attempt is what one request to a target got back.type attempt struct { // code is the response's status, or 0 when no response came. code int // failure says why no response came: statusConnectFailed or // statusTimeout. failure string retryAfter string err error}
func (a attempt) delivered() bool { return a.code >= 200 && a.code < 300 }
// retryable reports whether the target could take the delivery later:// no response came, the target failed, or it asked wicket to slow down.// Any other status, a redirect included, refuses the event for good.func (a attempt) retryable() bool { return a.code == 0 || a.code >= 500 || a.code == http.StatusTooManyRequests || a.code == http.StatusRequestTimeout}
// status is the attempt's status in a dead letter: the HTTP code, or why// no response came. It is never an error's text, which can hold the URL.func (a attempt) status() any { if a.code == 0 { return a.failure } return a.code}
// detail is the error of an attempt that got no response, for the log.func (a attempt) detail() string { if a.err == nil { return "" } return " (" + a.err.Error() + ")"}
// neverForwarded are the headers of a webhook that no target receives,// even when forward_headers names them, because they prove who the// publisher or a subscriber is.var neverForwarded = map[string]bool{"Authorization": true, "Cookie": true}
// request builds the POST of one delivery. refused names the signature// headers of every configured path, which forward_headers cannot pass on.func (t Target) request(ctx context.Context, delivery *Delivery, refused map[string]bool) (*http.Request, error) { req, err := http.NewRequestWithContext(ctx, "POST", t.URL, bytes.NewReader(delivery.Body)) if err != nil { return nil, err } event := delivery.Event if contentType, ok := event.Headers["Content-Type"]; ok { req.Header.Set("Content-Type", contentType) } req.Header.Set("User-Agent", "wicket/"+version) req.Header.Set(headerEventID, event.ID) req.Header.Set("Wicket-Path", event.Path) req.Header.Set("Wicket-Delivery-Attempt", strconv.Itoa(delivery.Attempts+1)) for _, name := range t.ForwardHeaders { name = http.CanonicalHeaderKey(name) if value, ok := event.Headers[name]; ok && !neverForwarded[name] && !refused[name] { req.Header.Set(name, value) } } if t.Sign != nil { mac := hmac.New(sha256.New, []byte(t.Sign.Secret)) mac.Write(delivery.Body) req.Header.Set(t.Sign.Header, "sha256="+hex.EncodeToString(mac.Sum(nil))) } for name, value := range t.Headers { req.Header.Set(name, value) } return req, nil}
// send makes one attempt at a delivery.func send(client *http.Client, req *http.Request) attempt { resp, err := client.Do(req) if err != nil { var netErr net.Error if errors.As(err, &netErr) && netErr.Timeout() { return attempt{failure: statusTimeout, err: unwrapURL(err)} } return attempt{failure: statusConnectFailed, err: unwrapURL(err)} } io.Copy(io.Discard, io.LimitReader(resp.Body, responseLimit)) resp.Body.Close() return attempt{code: resp.StatusCode, retryAfter: resp.Header.Get("Retry-After")}}
// unwrapURL drops the *url.Error around a request's error, whose text// holds the URL, and a target's URL can hold a secret.func unwrapURL(err error) error { var urlErr *url.Error if errors.As(err, &urlErr) { return urlErr.Err } return err}
// backoff is how long a delivery waits after its attempts-th failure:// 2^attempts times base, at most maxBackoff, then times jitter, from 0.8// to 1. The jitter comes after the cap, so the retries of deliveries that// failed at once spread out even once they all reach maxBackoff.func backoff(attempts int, base, maxBackoff time.Duration, jitter float64) time.Duration { delay := time.Duration(float64(base) * float64(uint64(1)<<min(attempts, 40))) if delay <= 0 || delay > maxBackoff { delay = maxBackoff } return time.Duration(float64(delay) * jitter)}
// parseRetryAfter reads a Retry-After header, in seconds or as an HTTP// date. A value that does not parse, or that is negative or past, is no// delay.func parseRetryAfter(value string, now time.Time) time.Duration { if seconds, err := strconv.Atoi(value); err == nil { return max(0, time.Duration(seconds)*time.Second) } if at, err := http.ParseTime(value); err == nil { return max(0, at.Sub(now)) } return 0}
// delayAfterFailure is how long a delivery waits after a failed attempt: its// backoff, or the target's Retry-After when that is longer, and at most// the target's max_backoff either way.func delayAfterFailure(t Target, attempts int, base time.Duration, jitter float64, a attempt, now time.Time) time.Duration { delay := backoff(attempts, base, t.MaxBackoff, jitter) if requested := parseRetryAfter(a.retryAfter, now); requested > delay { delay = min(requested, t.MaxBackoff) } return delay}