Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Validate outbound connections at dial time (#5048)
Gabe Kangas8cb3ae85fa4f
diff --git a/auth/indieauth/client.go b/auth/indieauth/client.goindex bb7fbef009..e151fe1e67 100644--- a/auth/indieauth/client.go+++ b/auth/indieauth/client.go@@ -22,17 +22,17 @@ func (s *Service) StartAuthFlow(authHost, userID, accessToken, displayName strinreturn nil, errors.New("Please try again later. Too many pending requests.")}- // Reject any requests to our internal network or loopback- if utils.IsHostnameInternal(authHost) {- return nil, errors.New("unable to use provided host")- }-- // Santity check the server URL+ // Sanity check the server URL.u, err := url.ParseRequestURI(authHost)if err != nil {return nil, errors.New("unable to parse server URL")}+ // Reject any requests to our internal network or loopback.+ if utils.IsHostnameInternal(u.Hostname()) {+ return nil, errors.New("unable to use provided host")+ }+// Limit to only secured connectionsif u.Scheme != schemeHTTPS {return nil, errors.New("only servers secured with https are supported")@@ -68,11 +68,9 @@ func (s *Service) HandleCallbackCode(code, state string) (*Request, *Response, edata.Set("redirect_uri", request.Callback.String())data.Set("code_verifier", request.CodeVerifier)- // Do not support redirects.- client := &http.Client{- CheckRedirect: func(req *http.Request, via []*http.Request) error {- return http.ErrUseLastResponse- },+ client := utils.GetFederationHTTPClient()+ client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {+ return http.ErrUseLastResponse}r, err := http.NewRequest("POST", request.Endpoint.String(), strings.NewReader(data.Encode())) // URL-encoded payloaddiff --git a/auth/indieauth/helpers.go b/auth/indieauth/helpers.goindex ddd1820deb..a7404b8bc6 100644--- a/auth/indieauth/helpers.go+++ b/auth/indieauth/helpers.go@@ -4,7 +4,6 @@ import ("crypto/sha256""encoding/base64""fmt"- "net/http""net/url""strings""time"@@ -12,6 +11,8 @@ import ("github.com/andybalholm/cascadia""github.com/pkg/errors""golang.org/x/net/html"++ "github.com/owncast/owncast/utils")func createAuthRequest(authDestination, userID, displayName, accessToken, baseServer string) (*Request, error) {@@ -77,8 +78,12 @@ func getAuthEndpointFromURL(urlstring string) (*url.URL, error) {if htmlDocScrapeURL.Scheme != schemeHTTPS {return nil, fmt.Errorf("url must be https")}+ if utils.IsHostnameInternal(htmlDocScrapeURL.Hostname()) {+ return nil, errors.New("unable to use provided host")+ }- r, err := http.Get(htmlDocScrapeURL.String()) // nolint:gosec+ client := utils.GetFederationHTTPClient()+ r, err := client.Get(htmlDocScrapeURL.String())if err != nil {return nil, err}diff --git a/services/activitypub/inbox/worker_test.go b/services/activitypub/inbox/worker_test.goindex 64ef7e49c6..67fae908a0 100644--- a/services/activitypub/inbox/worker_test.go+++ b/services/activitypub/inbox/worker_test.go@@ -65,6 +65,9 @@ var ()func TestMain(m *testing.M) {+ if err := os.Setenv("OWNCAST_ALLOW_INTERNAL_FEDERATION", "true"); err != nil {+ panic(err)+ }ds, err := datastore.SetupPersistence(":memory:", os.TempDir())if err != nil {panic(err)@@ -77,7 +80,7 @@ func TestMain(m *testing.M) {Persistence: persistenceSvc,Followers: followersrepository.New(testDatastore),})- m.Run()+ os.Exit(m.Run())}func TestBlockedDomains(t *testing.T) {diff --git a/services/activitypub/utils/nodeinfo.go b/services/activitypub/utils/nodeinfo.goindex 4eeb83b865..ad55cc0b08 100644--- a/services/activitypub/utils/nodeinfo.go+++ b/services/activitypub/utils/nodeinfo.go@@ -7,7 +7,6 @@ import ("io""net/http""net/url"- "time"netutils "github.com/owncast/owncast/utils")@@ -77,9 +76,7 @@ func FetchNodeInfo(serverURL string) (*NodeInfoV2, error) {return nil, fmt.Errorf("well-known nodeinfo URL %q is not allowed", wellKnownURL)}- client := &http.Client{- Timeout: 10 * time.Second,- }+ client := netutils.GetFederationHTTPClient()resp, err := client.Get(wellKnownURL)if err != nil {diff --git a/utils/netutils.go b/utils/netutils.goindex 2c69177dc1..429f858b49 100644--- a/utils/netutils.go+++ b/utils/netutils.go@@ -1,11 +1,12 @@package utilsimport (+ "context""net"+ "net/netip""os""sync"-- log "github.com/sirupsen/logrus"+ "time")var (@@ -13,6 +14,33 @@ var (allowInternalFederationOnce sync.Once)+var nonPublicIPPrefixes = []netip.Prefix{+ netip.MustParsePrefix("0.0.0.0/8"),+ netip.MustParsePrefix("10.0.0.0/8"),+ netip.MustParsePrefix("100.64.0.0/10"),+ netip.MustParsePrefix("127.0.0.0/8"),+ netip.MustParsePrefix("169.254.0.0/16"),+ netip.MustParsePrefix("172.16.0.0/12"),+ netip.MustParsePrefix("192.0.0.0/24"),+ netip.MustParsePrefix("192.0.2.0/24"),+ netip.MustParsePrefix("192.168.0.0/16"),+ netip.MustParsePrefix("192.88.99.0/24"),+ netip.MustParsePrefix("192.175.48.0/24"),+ netip.MustParsePrefix("198.18.0.0/15"),+ netip.MustParsePrefix("198.51.100.0/24"),+ netip.MustParsePrefix("203.0.113.0/24"),+ netip.MustParsePrefix("224.0.0.0/4"),+ netip.MustParsePrefix("240.0.0.0/4"),+ netip.MustParsePrefix("64:ff9b:1::/48"),+ netip.MustParsePrefix("100::/64"),+ netip.MustParsePrefix("2001::/23"),+ netip.MustParsePrefix("2001:db8::/32"),+ netip.MustParsePrefix("2002::/16"),+ netip.MustParsePrefix("fc00::/7"),+ netip.MustParsePrefix("fe80::/10"),+ netip.MustParsePrefix("ff00::/8"),+}+// AllowInternalFederation returns true if the OWNCAST_ALLOW_INTERNAL_FEDERATION// environment variable is set to "true". This is used for testing purposes only.func AllowInternalFederation() bool {@@ -23,34 +51,69 @@ func AllowInternalFederation() bool {}// IsHostnameInternal will attempt to determine if the hostname is internal to-// this server's network or is the loopback address.+// this server's network or is the loopback address. A hostname is internal+// when it has no publicly routable addresses at all; the restricted dialer+// connects only to the public subset.// Returns false if OWNCAST_ALLOW_INTERNAL_FEDERATION is set to "true".func IsHostnameInternal(hostname string) bool {- // Allow internal federation for testing purposes.- if AllowInternalFederation() {+ return isHostnameInternal(hostname, AllowInternalFederation())+}++func isHostnameInternal(hostname string, allowInternal bool) bool {+ if allowInternal {return false}- // If this is already an IP address don't try to resolve itif ip := net.ParseIP(hostname); ip != nil {return isIPAddressInternal(ip)}- ips, err := net.LookupIP(hostname)- if err != nil {- // Default to false if we can't resolve the hostname.- log.Debugln("Unable to resolve hostname:", hostname)- return false+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ ips, err := net.DefaultResolver.LookupIPAddr(ctx, hostname)+ if err != nil || len(ips) == 0 {+ return true}+ return len(publicIPAddresses(ips)) == 0+}++// publicIPAddresses returns the subset of resolved addresses that are+// publicly routable.+func publicIPAddresses(ips []net.IPAddr) []net.IPAddr {+ public := make([]net.IPAddr, 0, len(ips))for _, ip := range ips {- if isIPAddressInternal(ip) {- return true+ if !isIPAddressInternal(ip.IP) {+ public = append(public, ip)}}-- return false+ return public}+// nat64WellKnownPrefix (64:ff9b::/96, RFC 6052) is how DNS64 represents+// IPv4-only hosts to IPv6-only networks. The embedded IPv4 address is+// validated instead of blocking the prefix, so NAT64 deployments can still+// federate. The local-use prefix 64:ff9b:1::/48 stays blocked above because+// its translator prefix length is unknowable, so the embedded address+// cannot be extracted reliably.+var nat64WellKnownPrefix = netip.MustParsePrefix("64:ff9b::/96")+func isIPAddressInternal(ip net.IP) bool {- return ip.IsLoopback() || ip.IsPrivate()+ addr, ok := netip.AddrFromSlice(ip)+ if !ok {+ return true+ }+ addr = addr.Unmap()+ if nat64WellKnownPrefix.Contains(addr) {+ b := addr.As16()+ addr = netip.AddrFrom4([4]byte(b[12:16]))+ }+ if !addr.IsGlobalUnicast() {+ return true+ }+ for _, prefix := range nonPublicIPPrefixes {+ if prefix.Contains(addr) {+ return true+ }+ }+ return false}diff --git a/utils/netutils_test.go b/utils/netutils_test.goindex 9c1d6eded3..2b68496178 100644--- a/utils/netutils_test.go+++ b/utils/netutils_test.go@@ -6,27 +6,53 @@ import ()func TestIPAddressInternal(t *testing.T) {- internalLoopbackHost := "localhost"- internalLoopbackHostTest := IsHostnameInternal(internalLoopbackHost)- if !internalLoopbackHostTest {- t.Errorf("IsHostnameInternal(%s) = %v; want true", internalLoopbackHost, internalLoopbackHostTest)+ tests := []struct {+ address string+ internal bool+ }{+ {address: "0.0.0.0", internal: true},+ {address: "10.0.0.1", internal: true},+ {address: "100.64.0.1", internal: true},+ {address: "127.0.0.1", internal: true},+ {address: "169.254.169.254", internal: true},+ {address: "192.168.1.1", internal: true},+ {address: "198.18.0.1", internal: true},+ {address: "224.0.0.1", internal: true},+ {address: "::", internal: true},+ {address: "::1", internal: true},+ {address: "64:ff9b::a00:1", internal: true}, // NAT64-embedded 10.0.0.1+ {address: "64:ff9b::7f00:1", internal: true}, // NAT64-embedded 127.0.0.1+ {address: "64:ff9b::5db8:d822", internal: false}, // NAT64-embedded 93.184.216.34+ {address: "64:ff9b:1::1", internal: true}, // local-use NAT64 stays blocked+ {address: "2002:a00:1::", internal: true},+ {address: "fe80::1", internal: true},+ {address: "93.184.216.34", internal: false},+ {address: "2606:2800:220:1:248:1893:25c8:1946", internal: false},}- internalLoopbackIP := net.ParseIP("127.0.0.1")- internalLoopbackIPTest := isIPAddressInternal(internalLoopbackIP)- if !internalLoopbackIPTest {- t.Errorf("isIPAddressInternal(%s) = %v; want true", internalLoopbackIP, internalLoopbackIPTest)+ for _, test := range tests {+ t.Run(test.address, func(t *testing.T) {+ got := isIPAddressInternal(net.ParseIP(test.address))+ if got != test.internal {+ t.Fatalf("isIPAddressInternal(%s) = %v, want %v", test.address, got, test.internal)+ }+ })}+}- externalHost := "example.com"- externalHostTest := IsHostnameInternal(externalHost)- if externalHostTest {- t.Errorf("IsHostnameInternal(%s) = %v; want false", externalHost, externalHostTest)+func TestIsHostnameInternalFailsClosed(t *testing.T) {+ if !isHostnameInternal("does-not-exist.invalid", false) {+ t.Fatal("unresolvable hostname should be rejected")}+}- externalIP := net.ParseIP("93.184.216.34")- externalIPTest := isIPAddressInternal(externalIP)- if externalIPTest {- t.Errorf("isIPAddressInternal(%s) = %v; want false", externalIP, externalIPTest)+func TestPublicIPAddressesFiltersNonPublic(t *testing.T) {+ public := publicIPAddresses([]net.IPAddr{+ {IP: net.ParseIP("93.184.216.34")},+ {IP: net.ParseIP("10.0.0.1")},+ {IP: net.ParseIP("fe80::1")},+ })+ if len(public) != 1 || public[0].IP.String() != "93.184.216.34" {+ t.Fatalf("publicIPAddresses returned %v, want only 93.184.216.34", public)}}diff --git a/utils/tlsconfig.go b/utils/tlsconfig.goindex 14f0c138ff..3aa381e0ba 100644--- a/utils/tlsconfig.go+++ b/utils/tlsconfig.go@@ -1,9 +1,13 @@package utilsimport (+ "context""crypto/tls"+ "errors""fmt"+ "net""net/http"+ "net/url""os""sync""time"@@ -12,6 +16,11 @@ import (log "github.com/sirupsen/logrus")+const (+ httpScheme = "http"+ httpsScheme = "https"+)+var (insecureSkipVerify boolinsecureSkipVerifyOnce sync.Once@@ -50,38 +59,181 @@ func GetHTTPTransportWithTLS(baseTransport *http.Transport) *http.Transport {return baseTransport}-// GetRetryableHTTPClient returns an http.Client with retry logic for transient failures.-// It uses hashicorp/go-retryablehttp with exponential backoff for 502, 503, 504 errors.-func GetRetryableHTTPClient() *http.Client {- retryClient := retryablehttp.NewClient()- retryClient.RetryMax = 3- retryClient.RetryWaitMin = 100 * time.Millisecond- retryClient.RetryWaitMax = 1 * time.Second- retryClient.Logger = nil // Disable default logging+type restrictedDialer struct {+ allowInternal bool+ lookupIP func(context.Context, string) ([]net.IPAddr, error)+ dial func(context.Context, string, string) (net.Conn, error)+}++func newRestrictedDialer(allowInternal bool) *restrictedDialer {+ dialer := &net.Dialer{+ Timeout: 8 * time.Second,+ KeepAlive: 30 * time.Second,+ }+ return &restrictedDialer{+ allowInternal: allowInternal,+ lookupIP: net.DefaultResolver.LookupIPAddr,+ dial: dialer.DialContext,+ }+}++func (d *restrictedDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {+ host, port, err := net.SplitHostPort(address)+ if err != nil {+ return nil, fmt.Errorf("invalid outbound address %q: %w", address, err)+ }++ var addresses []net.IPAddr+ if ip := net.ParseIP(host); ip != nil {+ addresses = []net.IPAddr{{IP: ip}}+ } else {+ addresses, err = d.lookupIP(ctx, host)+ if err != nil {+ return nil, fmt.Errorf("unable to resolve outbound host %q: %w", host, err)+ }+ }+ if len(addresses) == 0 {+ return nil, fmt.Errorf("outbound host %q resolved to no addresses", host)+ }++ if !d.allowInternal {+ public := publicIPAddresses(addresses)+ if len(public) == 0 {+ return nil, fmt.Errorf("refusing to connect to host %q: it resolves only to non-public addresses", host)+ }+ addresses = public+ }+ addresses = interleaveAddressFamilies(addresses)- // Configure transport with connection pooling limits+ var dialErrors []error+ for i, address := range addresses {+ attemptCtx, cancel := attemptContext(ctx, len(addresses)-i)+ conn, err := d.dial(attemptCtx, network, net.JoinHostPort(address.IP.String(), port))+ cancel()+ if err == nil {+ return conn, nil+ }+ dialErrors = append(dialErrors, err)+ }++ return nil, fmt.Errorf("unable to connect to outbound host %q: %w", host, errors.Join(dialErrors...))+}++// attemptContext splits the remaining deadline evenly across the remaining+// dial attempts so one unreachable address cannot consume the entire+// request budget.+func attemptContext(ctx context.Context, attemptsLeft int) (context.Context, context.CancelFunc) {+ deadline, ok := ctx.Deadline()+ if !ok || attemptsLeft <= 1 {+ return ctx, func() {}+ }+ return context.WithTimeout(ctx, time.Until(deadline)/time.Duration(attemptsLeft))+}++// interleaveAddressFamilies alternates address families, keeping the+// resolver's preferred family first, so a broken path for one family falls+// back to the other on the next attempt instead of after every address of+// the first family has timed out.+func interleaveAddressFamilies(addresses []net.IPAddr) []net.IPAddr {+ var v4, v6 []net.IPAddr+ for _, address := range addresses {+ if address.IP.To4() != nil {+ v4 = append(v4, address)+ } else {+ v6 = append(v6, address)+ }+ }+ if len(v4) == 0 || len(v6) == 0 {+ return addresses+ }+ first, second := v6, v4+ if addresses[0].IP.To4() != nil {+ first, second = v4, v6+ }+ interleaved := make([]net.IPAddr, 0, len(addresses))+ for i := 0; i < len(first) || i < len(second); i++ {+ if i < len(first) {+ interleaved = append(interleaved, first[i])+ }+ if i < len(second) {+ interleaved = append(interleaved, second[i])+ }+ }+ return interleaved+}++func newOutboundHTTPClient(allowInternal bool) *http.Client {transport := GetHTTPTransportWithTLS(&http.Transport{- MaxIdleConns: 20, // Limit resource usage- MaxIdleConnsPerHost: 2, // Conservative per-host limit- IdleConnTimeout: 10 * time.Second, // Fast cleanup of idle connections- DisableKeepAlives: false,+ DialContext: newRestrictedDialer(allowInternal).DialContext,+ ForceAttemptHTTP2: true,+ MaxIdleConns: 20,+ MaxIdleConnsPerHost: 2,+ IdleConnTimeout: 10 * time.Second,})- retryClient.HTTPClient.Transport = transport- // Re-validate every redirect hop so a public URL can't 302 to an internal- // address (SSRF). Honors OWNCAST_ALLOW_INTERNAL_FEDERATION via- // IsHostnameInternal, so local-instance test federation still works.- retryClient.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {+ return &http.Client{+ Transport: transport,+ Timeout: 8 * time.Second,+ CheckRedirect: outboundRedirectPolicy(allowInternal),+ }+}++func outboundRedirectPolicy(allowInternal bool) func(*http.Request, []*http.Request) error {+ return func(req *http.Request, via []*http.Request) error {if len(via) >= 10 {- return fmt.Errorf("stopped after 10 redirects")+ return errors.New("stopped after 10 redirects")+ }+ if req.URL.Scheme != httpScheme && req.URL.Scheme != httpsScheme {+ return fmt.Errorf("refusing to follow redirect using %q scheme", req.URL.Scheme)}- if IsHostnameInternal(req.URL.Hostname()) {- return fmt.Errorf("refusing to follow redirect to internal host: %s", req.URL.Hostname())+ if len(via) > 0 && via[len(via)-1].URL.Scheme == httpsScheme && req.URL.Scheme != httpsScheme {+ return errors.New("refusing to follow redirect from HTTPS to HTTP")+ }+ if isHostnameInternal(req.URL.Hostname(), allowInternal) {+ return fmt.Errorf("refusing to follow redirect to non-public host: %s", req.URL.Hostname())}return nil}+}+// ValidatePublicHTTPSURL requires an HTTPS URL whose host resolves exclusively+// to publicly routable addresses.+func ValidatePublicHTTPSURL(rawURL string) error {+ parsed, err := url.ParseRequestURI(rawURL)+ if err != nil {+ return fmt.Errorf("invalid HTTPS URL: %w", err)+ }+ if parsed.Scheme != httpsScheme || parsed.Hostname() == "" {+ return errors.New("URL must use HTTPS and include a host")+ }+ if isHostnameInternal(parsed.Hostname(), false) {+ return fmt.Errorf("URL host %q is not publicly routable", parsed.Hostname())+ }+ return nil+}++// GetPublicHTTPClient returns an HTTP client that can connect only to publicly+// routable addresses and validates each redirect and resolved dial address.+func GetPublicHTTPClient() *http.Client {+ return newOutboundHTTPClient(false)+}++// GetFederationHTTPClient returns the restricted outbound client used for+// federation. The test-only internal-federation override is preserved.+func GetFederationHTTPClient() *http.Client {+ return newOutboundHTTPClient(AllowInternalFederation())+}++// GetRetryableHTTPClient returns the federation HTTP client with retry logic+// for transient 502, 503, and 504 responses.+func GetRetryableHTTPClient() *http.Client {+ retryClient := retryablehttp.NewClient()+ retryClient.RetryMax = 3+ retryClient.RetryWaitMin = 100 * time.Millisecond+ retryClient.RetryWaitMax = 1 * time.Second+ retryClient.Logger = nil+ retryClient.HTTPClient = GetFederationHTTPClient()client := retryClient.StandardClient()- client.Timeout = 8 * time.Second // Short timeout - legitimate servers respond quickly+ client.Timeout = 8 * time.Secondreturn client}diff --git a/utils/tlsconfig_test.go b/utils/tlsconfig_test.gonew file mode 100644index 0000000000..d9cd82f44f--- /dev/null+++ b/utils/tlsconfig_test.go@@ -0,0 +1,187 @@+package utils++import (+ "context"+ "errors"+ "net"+ "net/http"+ "slices"+ "testing"+ "time"+)++func TestRestrictedDialerSkipsNonPublicResolvedAddresses(t *testing.T) {+ var dialed []string+ dialer := &restrictedDialer{+ lookupIP: func(context.Context, string) ([]net.IPAddr, error) {+ return []net.IPAddr{+ {IP: net.ParseIP("169.254.169.254")},+ {IP: net.ParseIP("93.184.216.34")},+ }, nil+ },+ dial: func(_ context.Context, _ string, address string) (net.Conn, error) {+ dialed = append(dialed, address)+ client, server := net.Pipe()+ server.Close()+ return client, nil+ },+ }++ conn, err := dialer.DialContext(context.Background(), "tcp", "example.com:443")+ if err != nil {+ t.Fatalf("expected the public address to be dialed: %v", err)+ }+ conn.Close()+ if !slices.Equal(dialed, []string{"93.184.216.34:443"}) {+ t.Fatalf("dialed %v, want only the public address", dialed)+ }+}++func TestRestrictedDialerRejectsHostsWithOnlyNonPublicAddresses(t *testing.T) {+ dialCalled := false+ dialer := &restrictedDialer{+ lookupIP: func(context.Context, string) ([]net.IPAddr, error) {+ return []net.IPAddr{+ {IP: net.ParseIP("169.254.169.254")},+ {IP: net.ParseIP("10.0.0.1")},+ }, nil+ },+ dial: func(context.Context, string, string) (net.Conn, error) {+ dialCalled = true+ return nil, errors.New("unexpected dial")+ },+ }++ _, err := dialer.DialContext(context.Background(), "tcp", "example.com:443")+ if err == nil {+ t.Fatal("expected host with no public addresses to be rejected")+ }+ if dialCalled {+ t.Fatal("dial should not run when no public address is resolved")+ }+}++func TestRestrictedDialerInterleavesAddressFamilies(t *testing.T) {+ var dialed []string+ dialer := &restrictedDialer{+ lookupIP: func(context.Context, string) ([]net.IPAddr, error) {+ return []net.IPAddr{+ {IP: net.ParseIP("2606:2800:220:1::1")},+ {IP: net.ParseIP("2606:2800:220:1::2")},+ {IP: net.ParseIP("93.184.216.34")},+ }, nil+ },+ dial: func(_ context.Context, _ string, address string) (net.Conn, error) {+ dialed = append(dialed, address)+ return nil, errors.New("dial failed")+ },+ }++ if _, err := dialer.DialContext(context.Background(), "tcp", "example.com:443"); err == nil {+ t.Fatal("expected dial failure")+ }+ want := []string{"[2606:2800:220:1::1]:443", "93.184.216.34:443", "[2606:2800:220:1::2]:443"}+ if !slices.Equal(dialed, want) {+ t.Fatalf("dial order %v, want %v", dialed, want)+ }+}++func TestRestrictedDialerSplitsDeadlineAcrossAttempts(t *testing.T) {+ var deadlines []time.Time+ dialer := &restrictedDialer{+ lookupIP: func(context.Context, string) ([]net.IPAddr, error) {+ return []net.IPAddr{+ {IP: net.ParseIP("93.184.216.34")},+ {IP: net.ParseIP("93.184.216.35")},+ }, nil+ },+ dial: func(ctx context.Context, _, _ string) (net.Conn, error) {+ deadline, ok := ctx.Deadline()+ if !ok {+ t.Fatal("expected each dial attempt to carry a deadline")+ }+ deadlines = append(deadlines, deadline)+ return nil, errors.New("dial failed")+ },+ }++ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)+ defer cancel()+ if _, err := dialer.DialContext(ctx, "tcp", "example.com:443"); err == nil {+ t.Fatal("expected dial failure")+ }+ parentDeadline, _ := ctx.Deadline()+ if len(deadlines) != 2 {+ t.Fatalf("expected 2 dial attempts, got %d", len(deadlines))+ }+ // The first attempt gets roughly half the 8s budget, not all of it.+ if !deadlines[0].Before(parentDeadline.Add(-2 * time.Second)) {+ t.Fatalf("first attempt deadline %v should be well before the parent deadline %v", deadlines[0], parentDeadline)+ }+}++func TestRestrictedDialerDialsValidatedIPAddress(t *testing.T) {+ var dialedAddress string+ dialer := &restrictedDialer{+ lookupIP: func(context.Context, string) ([]net.IPAddr, error) {+ return []net.IPAddr{{IP: net.ParseIP("93.184.216.34")}}, nil+ },+ dial: func(_ context.Context, _ string, address string) (net.Conn, error) {+ dialedAddress = address+ client, server := net.Pipe()+ server.Close()+ return client, nil+ },+ }++ conn, err := dialer.DialContext(context.Background(), "tcp", "example.com:443")+ if err != nil {+ t.Fatalf("expected public address to be dialed: %v", err)+ }+ conn.Close()+ if dialedAddress != "93.184.216.34:443" {+ t.Fatalf("dialed %q instead of the validated IP address", dialedAddress)+ }+}++func TestOutboundRedirectPolicyRejectsNonPublicHost(t *testing.T) {+ req, err := http.NewRequest(http.MethodGet, "https://169.254.169.254/latest", nil)+ if err != nil {+ t.Fatal(err)+ }+ if err := outboundRedirectPolicy(false)(req, nil); err == nil {+ t.Fatal("expected redirect to link-local address to be rejected")+ }+}++func TestOutboundRedirectPolicyRejectsHTTPSDowngrade(t *testing.T) {+ req, err := http.NewRequest(http.MethodGet, "http://93.184.216.34/push", nil)+ if err != nil {+ t.Fatal(err)+ }+ previous, err := http.NewRequest(http.MethodGet, "https://93.184.216.34/push", nil)+ if err != nil {+ t.Fatal(err)+ }+ if err := outboundRedirectPolicy(false)(req, []*http.Request{previous}); err == nil {+ t.Fatal("expected HTTPS to HTTP redirect to be rejected")+ }+}++func TestValidatePublicHTTPSURL(t *testing.T) {+ if err := ValidatePublicHTTPSURL("https://93.184.216.34/push"); err != nil {+ t.Fatalf("expected public HTTPS URL to be accepted: %v", err)+ }+ for _, rawURL := range []string{+ "http://93.184.216.34/push",+ "https://127.0.0.1/push",+ "https://100.64.0.1/push",+ "https://[64:ff9b::a00:1]/push",+ } {+ t.Run(rawURL, func(t *testing.T) {+ if err := ValidatePublicHTTPSURL(rawURL); err == nil {+ t.Fatalf("expected %q to be rejected", rawURL)+ }+ })+ }+}