48 lines
1.3 KiB
Go
48 lines
1.3 KiB
Go
package alertwebhook
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
// PublicClient reaches public addresses only and follows no redirect. It
|
|
// carries a webhook an org chose: the daemon sends from inside the instance's
|
|
// network, so the org must not aim it at the daemon's own host or LAN.
|
|
func PublicClient() *http.Client {
|
|
dialer := &net.Dialer{
|
|
Timeout: timeout,
|
|
Control: func(_, address string, _ syscall.RawConn) error {
|
|
host, _, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if ip := net.ParseIP(host); ip == nil || !public(ip) {
|
|
return fmt.Errorf("webhook address %s is not public", host)
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
return &http.Client{
|
|
Timeout: 15 * time.Second,
|
|
Transport: &http.Transport{DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
return dialer.DialContext(ctx, network, addr)
|
|
}},
|
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
|
}
|
|
}
|
|
|
|
func public(ip net.IP) bool {
|
|
switch {
|
|
case ip.IsLoopback(), ip.IsPrivate(), ip.IsUnspecified(),
|
|
ip.IsLinkLocalUnicast(), ip.IsLinkLocalMulticast(),
|
|
ip.IsInterfaceLocalMulticast(), ip.IsMulticast():
|
|
return false
|
|
}
|
|
v4 := ip.To4()
|
|
return v4 == nil || v4[0] != 100 || v4[1] < 64 || v4[1] > 127
|
|
}
|