client.go73 lines, 2.3 KB
| 1 | package webhook |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "net" |
| 7 | "net/http" |
| 8 | "net/netip" |
| 9 | "net/url" |
| 10 | "syscall" |
| 11 | "time" |
| 12 | ) |
| 13 | |
| 14 | // checkURL says what's wrong with an endpoint's URL, if anything. In |
| 15 | // production, it must be https, and can't name an address in our network. |
| 16 | func checkURL(raw string, production bool) error { |
| 17 | u, err := url.Parse(raw) |
| 18 | switch { |
| 19 | case err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http"): |
| 20 | return errors.New("must be an absolute http or https URL") |
| 21 | case production && u.Scheme != "https": |
| 22 | return errors.New("must be https") |
| 23 | case u.User != nil: |
| 24 | return errors.New("must not contain a username or password") |
| 25 | } |
| 26 | if ip, err := netip.ParseAddr(u.Hostname()); err == nil { |
| 27 | return checkAddr(ip, production) |
| 28 | } |
| 29 | return nil // a name: the dialer checks what it resolves to, every time |
| 30 | } |
| 31 | |
| 32 | // checkAddr refuses addresses a webhook must never reach: link-local ones, |
| 33 | // like the cloud's metadata service, 169.254.169.254, always. Loopback and |
| 34 | // private ones, our own network, in production. |
| 35 | func checkAddr(ip netip.Addr, production bool) error { |
| 36 | ip = ip.Unmap() |
| 37 | if ip.IsUnspecified() || ip.IsLinkLocalUnicast() || ip.IsMulticast() || |
| 38 | production && (ip.IsLoopback() || ip.IsPrivate()) { |
| 39 | return fmt.Errorf("must not point at %s, an internal address", ip) |
| 40 | } |
| 41 | return nil |
| 42 | } |
| 43 | |
| 44 | // NewClient returns the client deliveries go out with. Its dialer checks the |
| 45 | // address it actually connects to, after DNS: a check of the URL alone is |
| 46 | // fooled by a name that resolves to 10.0.0.1, or that changes after we look. |
| 47 | func NewClient(production bool) *http.Client { |
| 48 | dialer := &net.Dialer{ |
| 49 | Timeout: 5 * time.Second, |
| 50 | Control: func(_, address string, _ syscall.RawConn) error { |
| 51 | ap, err := netip.ParseAddrPort(address) |
| 52 | if err != nil { |
| 53 | return err |
| 54 | } |
| 55 | return checkAddr(ap.Addr(), production) |
| 56 | }, |
| 57 | } |
| 58 | return &http.Client{ |
| 59 | // The whole delivery. A receiver should answer at once, and do its |
| 60 | // work later: slow is the same as down. |
| 61 | Timeout: 10 * time.Second, |
| 62 | // No proxy from the environment: it would connect for us, unchecked. |
| 63 | Transport: &http.Transport{ |
| 64 | DialContext: dialer.DialContext, |
| 65 | TLSHandshakeTimeout: 5 * time.Second, |
| 66 | MaxIdleConnsPerHost: 10, |
| 67 | }, |
| 68 | // A redirect is a failure, not something to follow somewhere else. |
| 69 | CheckRedirect: func(*http.Request, []*http.Request) error { |
| 70 | return http.ErrUseLastResponse |
| 71 | }, |
| 72 | } |
| 73 | } |