From a9395f4b5842c03e10c191e45b1c6ea12800d1a2 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Sun, 22 Nov 2026 15:05:19 -0500 Subject: [PATCH 1/5] Let auth login reach a beta preview on a private network A beta preview serves its API at -api.3.bc4-beta.com, which resolves to the previews load balancer on the VPN. OAuth requests refuse private addresses, so discovery failed and login fell back to Launchpad with no word of why. BASECAMP_OAUTH_ALLOW_PRIVATE=1 now admits RFC 1918 and IPv6 unique local addresses on the BC5 lane of a non-production base URL. The Launchpad lane and Basecamp's own hosts keep the default deny, as do loopback, link-local, cloud metadata and CGNAT space. Without it, a failed discovery against a base URL that resolves to a private address names the variable. --- README.md | 15 +++ internal/auth/auth.go | 8 ++ internal/auth/client.go | 211 ++++++++++++++++++++++++++++++++++- internal/auth/client_test.go | 185 +++++++++++++++++++++++++++++- internal/auth/revoke.go | 2 +- 5 files changed, 415 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 5236838db..04ff9d782 100644 --- a/README.md +++ b/README.md @@ -394,6 +394,21 @@ serving piloted clients but not yet advertising itself (discovery still 404s). It is a temporary escape hatch for that dark pilot, not a configuration surface, and will be removed once the server advertises its metadata. +OAuth requests refuse private network addresses, so a discovery document can +never steer the CLI to an internal host. A beta preview's API +(`-api.3.bc4-beta.com`) is served from a private address on the VPN; to +sign in to one, opt in for that base URL: + +```bash +BASECAMP_OAUTH_ALLOW_PRIVATE=1 BASECAMP_BASE_URL=https://-api.3.bc4-beta.com basecamp auth login +``` + +Only `1` enables it. It admits private ranges (10/8, 172.16/12, 192.168/16 and +IPv6 unique local) for a non-production base URL only; loopback, link-local, +cloud metadata and other special-use addresses stay refused, and it is ignored +for Basecamp's own hosts. Keep it set for that profile's later commands, which refresh the token +over the same route. + ## AI Agent Integration `basecamp` works with any AI agent that can run shell commands. diff --git a/internal/auth/auth.go b/internal/auth/auth.go index e0e8e4ea7..b1c12810a 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -101,6 +101,11 @@ type Manager struct { proxyOnce sync.Once proxyEnv *proxyEnvState + // allowPrivate is oauthAllowPrivateEnv as privateOptIn read it, once, + // under allowPrivateOnce. + allowPrivateOnce sync.Once + allowPrivate bool + // Warnf receives transport-policy warnings (a proxy ignored for OAuth // traffic, a malformed opt-out value). Test seam; nil means stderr. Warnf func(format string, args ...any) @@ -1539,6 +1544,9 @@ func (m *Manager) discoverOAuth(ctx context.Context, log func(string)) (*discove if res.IsFallback() { if res.FallbackReason == oauth.FallbackResourceDiscoveryFailed { log(fmt.Sprintf("warning: OAuth discovery failed for %s, using Launchpad fallback", origin)) + if hint := m.privateBaseURLHint(ctx, origin); hint != "" { + log("hint: " + hint) + } } lpURL, lpErr := m.launchpadURL() if lpErr != nil { diff --git a/internal/auth/client.go b/internal/auth/client.go index 072e819c2..dca1675e5 100644 --- a/internal/auth/client.go +++ b/internal/auth/client.go @@ -1,13 +1,17 @@ package auth import ( + "context" + "errors" "fmt" + "net" "net/http" "net/netip" "net/url" "os" "strings" "sync" + "syscall" "time" "github.com/basecamp/basecamp-sdk/go/pkg/basecamp/oauth" @@ -27,6 +31,132 @@ import ( // warning rather than guessed at. const oauthUseProxyEnv = "BASECAMP_OAUTH_USE_PROXY" +// oauthAllowPrivateEnv admits private network addresses (RFC 1918 and IPv6 +// unique local) on the BC5 OAuth lane, for a base URL served inside a private +// network: a beta preview's API host resolves to the previews load balancer, +// reachable only on the VPN. It is read like oauthUseProxyEnv: only "1" +// enables it, "" is unset, and anything else is refused with a warning. +// +// It is the operator vouching for the network of the base URL they +// configured, as a local base URL vouches for loopback, so it applies to that +// lane alone: never to the Launchpad lane, and never to a production base URL +// (firstPartyOAuthHosts), whose discovery documents must not be able to steer +// the CLI to an internal address because a variable was left set. Loopback, +// link-local, cloud metadata and CGNAT space stay refused. +const oauthAllowPrivateEnv = "BASECAMP_OAUTH_ALLOW_PRIVATE" + +// privateNetworkPrefixes is what oauthAllowPrivateEnv admits. +var privateNetworkPrefixes = []netip.Prefix{ + netip.MustParsePrefix("10.0.0.0/8"), + netip.MustParsePrefix("172.16.0.0/12"), + netip.MustParsePrefix("192.168.0.0/16"), + netip.MustParsePrefix("fc00::/7"), +} + +// privateNetworkPolicy judges an address inside privateNetworkPrefixes once +// the opt-in is on. fd00:ec2::254 is EC2's IPv6 instance metadata service, +// which sits inside the unique local range and stays refused. +var privateNetworkPolicy = surfguard.Policy{}.AllowAllPorts(). + Allow(privateNetworkPrefixes...). + Deny(netip.MustParsePrefix("fd00:ec2::254/128")) + +// privateNetworkAdmits reports whether the opt-in admits addr: it is in +// privateNetworkPrefixes and privateNetworkPolicy does not refuse it. +func privateNetworkAdmits(addr netip.Addr) bool { + addr = addr.Unmap() + for _, p := range privateNetworkPrefixes { + if p.Contains(addr) { + return !privateNetworkPolicy.Blocked(addr) + } + } + return false +} + +// privateNetworkTransport is an opted-in lane's direct transport. The lane's +// own policy judges every address, as it does without the opt-in; only an +// address it refuses that privateNetworkAdmits is let through, so everything +// else the IANA special-use tables refuse (NAT64, AMT, AS112 and the rest) +// stays refused. Each dial is judged at connect time, which is what defeats +// DNS rebinding. +func privateNetworkTransport(policy surfguard.Policy) http.RoundTripper { + t := policy.Transport() + dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, ControlContext: privateNetworkControl(policy)} + t.DialContext = dialer.DialContext + return privateNetworkRoundTripper{policy: policy, next: t} +} + +// privateNetworkControl is the opted-in lane's dial check: the lane's policy, +// and where it refuses, privateNetworkPolicy for an address +// privateNetworkAdmits. +func privateNetworkControl(policy surfguard.Policy) func(context.Context, string, string, syscall.RawConn) error { + return func(ctx context.Context, network, address string, c syscall.RawConn) error { + err := policy.ControlContext(ctx, network, address, c) + if err == nil { + return nil + } + ap, perr := netip.ParseAddrPort(address) + if perr != nil || !privateNetworkAdmits(ap.Addr()) { + return err + } + return privateNetworkPolicy.ControlContext(ctx, network, address, c) + } +} + +// privateNetworkRoundTripper refuses a request whose URL the lane's policy +// finds malformed (scheme or host) before the transport dials, as +// surfguard's own RoundTripper does. Its verdict on the address is left to +// the dial. +type privateNetworkRoundTripper struct { + policy surfguard.Policy + next *http.Transport +} + +func (r privateNetworkRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { + if req == nil || req.URL == nil { + return nil, &surfguard.Violation{Reason: surfguard.ReasonMalformedHost} + } + // surfguard's dialer rewrites a legacy numeric host (0x0a1405e5, + // 012.024.5.229) to the address it means; a plain net.Dialer would send + // it to DNS instead. No OAuth endpoint is named that way, so refuse it. + if isLegacyNumericHost(req.URL.Hostname()) { + return nil, &surfguard.Violation{Host: req.URL.Hostname(), Reason: surfguard.ReasonMalformedHost} + } + var v *surfguard.Violation + if err := r.policy.CheckURL(req.Context(), req.URL.String()); errors.As(err, &v) && + (v.Reason == surfguard.ReasonMalformedHost || v.Reason == surfguard.ReasonScheme) { + return nil, err + } + return r.next.RoundTrip(req) +} + +// isLegacyNumericHost reports whether host is an IPv4 address in a spelling +// other than dotted decimal: every dot-separated part a decimal, octal or 0x +// hex number. A DNS name's last label is never all digits, and a canonical +// literal parses as an address. +func isLegacyNumericHost(host string) bool { + if host == "" || strings.Contains(host, ":") { + return false + } + if _, err := netip.ParseAddr(host); err == nil { + return false + } + for _, part := range strings.Split(strings.ToLower(host), ".") { + digits := strings.TrimPrefix(part, "0x") + if digits == "" && part != "0x" { + return false + } + for _, c := range digits { + if (c < '0' || c > '9') && (part == digits || c < 'a' || c > 'f') { + return false + } + } + } + return true +} + +// CloseIdleConnections forwards to the transport, as http.Client expects. +func (r privateNetworkRoundTripper) CloseIdleConnections() { r.next.CloseIdleConnections() } + // oauthClientTimeout bounds each OAuth HTTP request on the lane clients — // the same 30s the pre-lane appctx client carried. const oauthClientTimeout = 30 * time.Second @@ -77,6 +207,75 @@ func oauthEndpointPolicy(anchorURL, label string) (surfguard.Policy, error) { return policy, nil } +// privateOptIn reports whether oauthAllowPrivateEnv is "1". Read once per +// Manager, so a malformed value warns once. +func (m *Manager) privateOptIn() bool { + m.allowPrivateOnce.Do(func() { + switch v := os.Getenv(oauthAllowPrivateEnv); v { + case "": + case "1": + m.allowPrivate = true + default: + m.warnf("warning: %s=%q is not understood (only \"1\" enables it); OAuth requests keep the SSRF address policy", oauthAllowPrivateEnv, v) + } + }) + return m.allowPrivate +} + +// isFirstPartyHost reports whether host names one of firstPartyOAuthHosts, +// in any case and with or without the root's trailing dot. +func isFirstPartyHost(host string) bool { + return firstPartyOAuthHosts[strings.TrimSuffix(strings.ToLower(host), ".")] +} + +// allowPrivateFor reports whether a BC5 lane anchored on baseURL admits +// private addresses: the opt-in is on and baseURL is not a production host. +func (m *Manager) allowPrivateFor(baseURL string) bool { + if !m.privateOptIn() { + return false + } + if u, err := url.Parse(baseURL); err != nil || isFirstPartyHost(u.Hostname()) { + m.warnf("warning: %s=1 is ignored for a production base URL; OAuth requests keep the SSRF address policy", oauthAllowPrivateEnv) + return false + } + return true +} + +// privateBaseURLHint explains a failed discovery whose base URL resolves only +// to addresses the opt-in would admit, naming it. It returns "" when the +// opt-in is already on, or the host is a production one, unresolvable, or +// resolves anywhere else (public, loopback, metadata). +func (m *Manager) privateBaseURLHint(ctx context.Context, origin string) string { + if m.httpClient != nil || m.allowPrivateFor(origin) { + return "" + } + u, err := url.Parse(origin) + if err != nil || isFirstPartyHost(u.Hostname()) { + return "" + } + addrs := []netip.Addr{} + if a, err := netip.ParseAddr(u.Hostname()); err == nil { + addrs = append(addrs, a) + } else { + // A diagnostic, after discovery already failed: never let a stalled + // resolver hold up the fallback. + lookupCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + if addrs, err = net.DefaultResolver.LookupNetIP(lookupCtx, "ip", u.Hostname()); err != nil { + return "" + } + } + if len(addrs) == 0 { + return "" + } + for _, a := range addrs { + if !privateNetworkAdmits(a) { + return "" + } + } + return fmt.Sprintf("the base URL resolves to a private network address, which OAuth refuses by default; if you trust it (a beta preview on the VPN), set %s=1", oauthAllowPrivateEnv) +} + // firstPartyOAuthHosts are the hosts 37signals operates that the OAuth flows // reach: the BC5 API and its issuer under both the original and the current // domains (credentials stored before the move name @@ -324,7 +523,7 @@ func (m *Manager) bc5Client() (*http.Client, error) { return m.httpClient, nil } m.bc5Lane.once.Do(func() { - m.bc5Lane.client, m.bc5Lane.err = m.buildLaneClient(m.cfg.BaseURL, "base URL") + m.bc5Lane.client, m.bc5Lane.err = m.buildLaneClient(m.cfg.BaseURL, "base URL", m.allowPrivateFor(m.cfg.BaseURL)) }) return m.bc5Lane.client, m.bc5Lane.err } @@ -343,19 +542,23 @@ func (m *Manager) launchpadClient() (*http.Client, error) { m.lpLane.err = err return } - m.lpLane.client, m.lpLane.err = m.buildLaneClient(lpURL, "Launchpad URL") + m.lpLane.client, m.lpLane.err = m.buildLaneClient(lpURL, "Launchpad URL", false) }) return m.lpLane.client, m.lpLane.err } -func (m *Manager) buildLaneClient(anchorURL, label string) (*http.Client, error) { +func (m *Manager) buildLaneClient(anchorURL, label string, allowPrivate bool) (*http.Client, error) { policy, err := oauthEndpointPolicy(anchorURL, label) if err != nil { return nil, err } + guarded := policy.RoundTripper() + if allowPrivate { + guarded = privateNetworkTransport(policy) + } st := m.proxyState() tr := &oauthTransport{ - guarded: policy.RoundTripper(), + guarded: guarded, firstParty: m.firstPartyOAuthPolicy().RoundTripper(), resolve: st.resolve, optOut: st.optOut, diff --git a/internal/auth/client_test.go b/internal/auth/client_test.go index ad9910fd7..02cca8bcd 100644 --- a/internal/auth/client_test.go +++ b/internal/auth/client_test.go @@ -29,7 +29,7 @@ import ( // need a proxy set their own values on top. func clearProxyEnv(t *testing.T) { t.Helper() - for _, v := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy", "REQUEST_METHOD", oauthUseProxyEnv} { + for _, v := range []string{"HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy", "REQUEST_METHOD", oauthUseProxyEnv, oauthAllowPrivateEnv} { t.Setenv(v, "") } } @@ -974,3 +974,186 @@ func TestLanes_FirstPartyTransportVerifiesCertificates(t *testing.T) { assert.Zero(t, reached.Load(), "no request may reach a server whose certificate failed verification") } + +// TestPrivateNetworkAdmits pins what BASECAMP_OAUTH_ALLOW_PRIVATE=1 admits: +// RFC 1918 and IPv6 unique local space, and nothing else the issuer policy +// refuses. +func TestPrivateNetworkAdmits(t *testing.T) { + for _, a := range []string{"10.20.5.229", "172.16.0.1", "192.168.1.1", "fd00::1", "::ffff:10.20.5.229"} { + assert.True(t, privateNetworkAdmits(netip.MustParseAddr(a)), a) + } + for _, a := range []string{ + "127.0.0.1", "169.254.169.254", "100.64.0.1", "fe80::1", "::1", + "fd00:ec2::254", // EC2 IPv6 instance metadata, inside fc00::/7 + "192.52.193.1", // AMT: IANA special use, not private + "192.31.196.1", // AS112 + "2001:3::1", // AMT v6 + "64:ff9b::a14:5e5", // NAT64 of 10.20.5.229 + "8.8.8.8", + } { + assert.False(t, privateNetworkAdmits(netip.MustParseAddr(a)), a) + } +} + +// TestBC5Lane_PrivateNetworkOptIn: a beta preview's API host resolves to a +// private address. The opt-in admits private space on the BC5 lane of a +// non-production base URL, and nowhere else. +func TestBC5Lane_PrivateNetworkOptIn(t *testing.T) { + const preview = "https://main-api.3.bc4-beta.com" + + t.Run("off by default", func(t *testing.T) { + clearProxyEnv(t) + assert.False(t, laneManager(t, preview).allowPrivateFor(preview)) + }) + + t.Run("on for a non-production base URL", func(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "1") + assert.True(t, laneManager(t, preview).allowPrivateFor(preview)) + }) + + for _, prod := range []string{"https://3.basecampapi.com", "https://API.basecamp.com.", "https://app.basecamp.com"} { + t.Run("ignored for "+prod, func(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "1") + var warnings []string + m := laneManager(t, prod) + m.Warnf = func(format string, args ...any) { warnings = append(warnings, fmt.Sprintf(format, args...)) } + assert.False(t, m.allowPrivateFor(prod)) + require.NotEmpty(t, warnings) + assert.Contains(t, warnings[0], "production base URL") + }) + } + + t.Run("malformed value is off, with a warning", func(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "yes") + var warnings []string + m := laneManager(t, preview) + m.Warnf = func(format string, args ...any) { warnings = append(warnings, fmt.Sprintf(format, args...)) } + assert.False(t, m.allowPrivateFor(preview)) + require.NotEmpty(t, warnings) + assert.Contains(t, warnings[0], "is not understood") + }) + + // At the client, every case here is refused before a connection is + // made, so none depends on the network around the test. + t.Run("lanes refuse what the opt-in does not admit", func(t *testing.T) { + clearProxyEnv(t) + get := func(client *http.Client, target string) error { + resp, err := doGet(t, client, target) + if resp != nil { + _ = resp.Body.Close() + } + return err + } + + m := laneManager(t, preview) + bc5, err := m.bc5Client() + require.NoError(t, err) + assert.ErrorIs(t, get(bc5, "http://10.20.5.229/"), surfguard.ErrBlocked, "off: private refused") + + t.Setenv(oauthAllowPrivateEnv, "1") + m = laneManager(t, preview) + bc5, err = m.bc5Client() + require.NoError(t, err) + for _, target := range []string{ + "http://169.254.169.254/latest/meta-data/", + "http://[fd00:ec2::254]/latest/meta-data/", + "http://192.52.193.1/", + "http://[64:ff9b::a14:5e5]/", + "http://127.0.0.1/", + } { + assert.ErrorIs(t, get(bc5, target), surfguard.ErrBlocked, "on: %s stays refused", target) + } + + lp, err := m.launchpadClient() + require.NoError(t, err) + assert.ErrorIs(t, get(lp, "http://10.20.5.229/"), surfguard.ErrBlocked, "the Launchpad lane never takes the opt-in") + }) +} + +// TestPrivateNetworkControl: the opted-in lane's dial check lets a private +// address through and still refuses the rest, including on a lane whose +// local anchor admits loopback. +func TestPrivateNetworkControl(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "1") + m := laneManager(t, "https://main-api.3.bc4-beta.com") + bc5, err := m.bc5Client() + require.NoError(t, err) + _, ok := bc5.Transport.(*oauthTransport).guarded.(privateNetworkRoundTripper) + require.True(t, ok, "an opted-in BC5 lane rides the private-network transport") + + policy, err := oauthEndpointPolicy("https://main-api.3.bc4-beta.com", "base URL") + require.NoError(t, err) + check := privateNetworkControl(policy) + dial := func(network, address string) error { return check(context.Background(), network, address, nil) } + + assert.NoError(t, dial("tcp4", "10.20.5.229:443")) + assert.NoError(t, dial("tcp6", "[fd00::1]:443")) + assert.NoError(t, dial("tcp4", "8.8.8.8:443"), "public addresses keep the lane's verdict") + for _, a := range []string{"169.254.169.254:80", "192.52.193.1:443", "127.0.0.1:443"} { + assert.ErrorIs(t, dial("tcp4", a), surfguard.ErrBlocked, a) + } + assert.ErrorIs(t, dial("tcp6", "[fd00:ec2::254]:80"), surfguard.ErrBlocked) + assert.ErrorIs(t, dial("tcp6", "[64:ff9b::a14:5e5]:443"), surfguard.ErrBlocked) + assert.ErrorIs(t, dial("udp", "10.20.5.229:443"), surfguard.ErrBlocked, "the network gate still applies") +} + +// TestPrivateBaseURLHint: a failed discovery against a base URL that resolves +// to a private address names the opt-in; one that is public, loopback, +// metadata, special use, or already opted in does not. +func TestPrivateBaseURLHint(t *testing.T) { + ctx := context.Background() + cases := []struct { + origin string + optIn string + want bool + }{ + {"https://10.20.5.229", "", true}, + {"https://[fd00::1]", "", true}, + {"https://10.20.5.229", "1", false}, + {"https://127.0.0.2", "", false}, + {"https://169.254.169.254", "", false}, + {"https://[fd00:ec2::254]", "", false}, + {"https://192.52.193.1", "", false}, + {"https://8.8.8.8", "", false}, + } + for _, tc := range cases { + t.Run(tc.origin+" opt-in="+tc.optIn, func(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, tc.optIn) + m := laneManager(t, tc.origin) + hint := m.privateBaseURLHint(ctx, tc.origin) + if tc.want { + assert.Contains(t, hint, oauthAllowPrivateEnv+"=1") + } else { + assert.Empty(t, hint) + } + }) + } +} + +// TestPrivateNetworkTransport_RefusesLegacyNumericHosts: the opted-in lane's +// dialer does not canonicalize numeric spellings as surfguard's does, so +// they are refused before it runs. +func TestPrivateNetworkTransport_RefusesLegacyNumericHosts(t *testing.T) { + for _, h := range []string{"0x0a1405e5", "012.024.5.229", "167036389", "10.0x14.5.229", "0X0A1405E5", "0x"} { + assert.True(t, isLegacyNumericHost(h), h) + } + for _, h := range []string{"10.20.5.229", "fd00::1", "main-api.3.bc4-beta.com", "cafe", "cafe.beef", "example.com", "a..b", ""} { + assert.False(t, isLegacyNumericHost(h), h) + } + + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "1") + m := laneManager(t, "https://main-api.3.bc4-beta.com") + bc5, err := m.bc5Client() + require.NoError(t, err) + resp, err := doGet(t, bc5, "http://0x0a1405e5/") + if resp != nil { + _ = resp.Body.Close() + } + assert.ErrorIs(t, err, surfguard.ErrBlocked) +} diff --git a/internal/auth/revoke.go b/internal/auth/revoke.go index d7d462eca..4c862da86 100644 --- a/internal/auth/revoke.go +++ b/internal/auth/revoke.go @@ -412,7 +412,7 @@ func (m *Manager) revocationClient(baseURL string) (*http.Client, error) { if m.httpClient != nil || baseURL == "" || baseURL == m.cfg.BaseURL { return m.bc5Client() } - return m.buildLaneClient(baseURL, "profile base URL") + return m.buildLaneClient(baseURL, "profile base URL", m.allowPrivateFor(baseURL)) } // credentialIssuer names the authorization server that minted creds. Logins From 958549b86ecfa9c769d0888cc45555476aafbc99 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Sun, 22 Nov 2026 15:54:49 -0500 Subject: [PATCH 2/5] Check an opted-in OAuth URL's shape without a DNS lookup The pre-dial check called CheckURL, which resolves the host, so every opted-in request (each device-code poll included) waited on DNS before it dialed. It now judges the URL with a resolver that answers nothing, which keeps surfguard's host-shape checks and leaves addresses to the dial. --- internal/auth/client.go | 22 ++++++++++++++++------ internal/auth/client_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/internal/auth/client.go b/internal/auth/client.go index dca1675e5..1eb0b7e5d 100644 --- a/internal/auth/client.go +++ b/internal/auth/client.go @@ -102,10 +102,10 @@ func privateNetworkControl(policy surfguard.Policy) func(context.Context, string } } -// privateNetworkRoundTripper refuses a request whose URL the lane's policy -// finds malformed (scheme or host) before the transport dials, as -// surfguard's own RoundTripper does. Its verdict on the address is left to -// the dial. +// privateNetworkRoundTripper refuses a request whose URL is malformed (scheme +// or host) before the transport dials, as surfguard's own RoundTripper does. +// The host is judged with no DNS lookup (noLookup): its addresses are left to +// the dial, so a slow resolver costs a request nothing beyond its own dial. type privateNetworkRoundTripper struct { policy surfguard.Policy next *http.Transport @@ -121,14 +121,24 @@ func (r privateNetworkRoundTripper) RoundTrip(req *http.Request) (*http.Response if isLegacyNumericHost(req.URL.Hostname()) { return nil, &surfguard.Violation{Host: req.URL.Hostname(), Reason: surfguard.ReasonMalformedHost} } + if req.URL.Scheme != "http" && req.URL.Scheme != "https" { + return nil, &surfguard.Violation{Reason: surfguard.ReasonScheme} + } var v *surfguard.Violation - if err := r.policy.CheckURL(req.Context(), req.URL.String()); errors.As(err, &v) && - (v.Reason == surfguard.ReasonMalformedHost || v.Reason == surfguard.ReasonScheme) { + if err := r.policy.WithResolver(noLookup{}).CheckURL(req.Context(), req.URL.String()); errors.As(err, &v) && v.Reason == surfguard.ReasonMalformedHost { return nil, err } return r.next.RoundTrip(req) } +// noLookup is a surfguard Resolver that answers every name with no records +// and never queries DNS, so CheckURL judges only a URL's shape and literals. +type noLookup struct{} + +func (noLookup) LookupNetIP(context.Context, string, string) ([]netip.Addr, error) { + return nil, nil +} + // isLegacyNumericHost reports whether host is an IPv4 address in a spelling // other than dotted decimal: every dot-separated part a decimal, octal or 0x // hex number. A DNS name's last label is never all digits, and a canonical diff --git a/internal/auth/client_test.go b/internal/auth/client_test.go index 02cca8bcd..80db4f891 100644 --- a/internal/auth/client_test.go +++ b/internal/auth/client_test.go @@ -1157,3 +1157,33 @@ func TestPrivateNetworkTransport_RefusesLegacyNumericHosts(t *testing.T) { } assert.ErrorIs(t, err, surfguard.ErrBlocked) } + +// TestPrivateNetworkRoundTripper_RefusesMalformedURLs: the opted-in lane +// refuses a malformed URL before dialing, as surfguard's RoundTripper does. +// Each URL is built by hand so net/url's own parsing cannot refuse it first. +func TestPrivateNetworkRoundTripper_RefusesMalformedURLs(t *testing.T) { + policy, err := oauthEndpointPolicy("https://main-api.3.bc4-beta.com", "base URL") + require.NoError(t, err) + rt := privateNetworkTransport(policy).(privateNetworkRoundTripper) + + for _, u := range []*url.URL{ + {Scheme: "ftp", Host: "10.20.5.229"}, + {Scheme: "http", Host: "[example.com]"}, + {Scheme: "http", Host: "\u24dbocalhost"}, // IDNA-normalizes to localhost + {Scheme: "http", Host: ""}, + } { + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://placeholder/", nil) + require.NoError(t, err) + req.URL = u + _, err = rt.RoundTrip(req) + assert.ErrorIs(t, err, surfguard.ErrBlocked, "%q", u.Host) + } +} + +// TestNoLookup_ShapeOnly: under noLookup, CheckURL never resolves a name: a +// well-formed one comes back unresolvable rather than judged. +func TestNoLookup_ShapeOnly(t *testing.T) { + err := surfguard.Policy{}.WithResolver(noLookup{}).CheckURL(context.Background(), "https://main-api.3.bc4-beta.com/") + assert.ErrorIs(t, err, surfguard.ErrUnresolvable) + assert.NotErrorIs(t, err, surfguard.ErrBlocked) +} From 8fa6b394a34b67c316b6b348fe67290b7e0c3ee4 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Sun, 22 Nov 2026 16:16:20 -0500 Subject: [PATCH 3/5] Admit private addresses only under the base URL's domain, and only IPv4 A security review of the opt-in found two gaps. IPv6 unique local space holds several clouds' metadata services (GCP's fd20:ce::254, OCI's fd00:c1::a9fe:a9fe, AWS's fd00:ec2:: DNS and NTP), and only EC2's metadata address was denied. The previews answer on IPv4, so the opt-in now admits RFC 1918 space alone. And the allowance covered every host on the lane, so a preview's discovery document or a redirect could point the CLI at any address on the private network. A request now reaches a private address only for the base URL's host and hosts under its parent domain (*.3.bc4-beta.com for a preview); every other host keeps the strict policy. --- README.md | 11 +++-- internal/auth/client.go | 93 ++++++++++++++++++++++++++---------- internal/auth/client_test.go | 57 ++++++++++++++++++---- 3 files changed, 123 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 04ff9d782..ae5d667d9 100644 --- a/README.md +++ b/README.md @@ -403,10 +403,13 @@ sign in to one, opt in for that base URL: BASECAMP_OAUTH_ALLOW_PRIVATE=1 BASECAMP_BASE_URL=https://-api.3.bc4-beta.com basecamp auth login ``` -Only `1` enables it. It admits private ranges (10/8, 172.16/12, 192.168/16 and -IPv6 unique local) for a non-production base URL only; loopback, link-local, -cloud metadata and other special-use addresses stay refused, and it is ignored -for Basecamp's own hosts. Keep it set for that profile's later commands, which refresh the token +Only `1` enables it. It admits RFC 1918 addresses (10/8, 172.16/12, +192.168/16) for a non-production base URL only, and only for the base URL's +host and hosts under its parent domain (`*.3.bc4-beta.com` above), so a +discovery document or redirect can't send the CLI elsewhere on the private +network. Loopback, link-local, cloud metadata, IPv6 private and other +special-use addresses stay refused, and it is ignored for Basecamp's own +hosts. Keep it set for that profile's later commands, which refresh the token over the same route. ## AI Agent Integration diff --git a/internal/auth/client.go b/internal/auth/client.go index 1eb0b7e5d..0682d3702 100644 --- a/internal/auth/client.go +++ b/internal/auth/client.go @@ -31,18 +31,22 @@ import ( // warning rather than guessed at. const oauthUseProxyEnv = "BASECAMP_OAUTH_USE_PROXY" -// oauthAllowPrivateEnv admits private network addresses (RFC 1918 and IPv6 -// unique local) on the BC5 OAuth lane, for a base URL served inside a private -// network: a beta preview's API host resolves to the previews load balancer, -// reachable only on the VPN. It is read like oauthUseProxyEnv: only "1" +// oauthAllowPrivateEnv admits RFC 1918 private addresses on the BC5 OAuth +// lane, for a base URL served inside a private network: a beta preview's API +// host resolves to the previews load balancer, reachable only on the VPN. It is read like oauthUseProxyEnv: only "1" // enables it, "" is unset, and anything else is refused with a warning. // // It is the operator vouching for the network of the base URL they // configured, as a local base URL vouches for loopback, so it applies to that // lane alone: never to the Launchpad lane, and never to a production base URL // (firstPartyOAuthHosts), whose discovery documents must not be able to steer -// the CLI to an internal address because a variable was left set. Loopback, -// link-local, cloud metadata and CGNAT space stay refused. +// the CLI to an internal address because a variable was left set. Within the +// lane it admits only hosts under the base URL's own domain (privateScope), +// so a discovery document or redirect cannot send the CLI elsewhere on the +// private network. Loopback, link-local, cloud metadata, CGNAT and all IPv6 +// space outside the lane's own policy stay refused: IPv6 unique local space +// holds several clouds' metadata services (GCP's fd20:ce::254, OCI's +// fd00:c1::a9fe:a9fe, AWS's fd00:ec2::/32), and the previews answer on IPv4. const oauthAllowPrivateEnv = "BASECAMP_OAUTH_ALLOW_PRIVATE" // privateNetworkPrefixes is what oauthAllowPrivateEnv admits. @@ -50,15 +54,11 @@ var privateNetworkPrefixes = []netip.Prefix{ netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("172.16.0.0/12"), netip.MustParsePrefix("192.168.0.0/16"), - netip.MustParsePrefix("fc00::/7"), } // privateNetworkPolicy judges an address inside privateNetworkPrefixes once -// the opt-in is on. fd00:ec2::254 is EC2's IPv6 instance metadata service, -// which sits inside the unique local range and stays refused. -var privateNetworkPolicy = surfguard.Policy{}.AllowAllPorts(). - Allow(privateNetworkPrefixes...). - Deny(netip.MustParsePrefix("fd00:ec2::254/128")) +// the opt-in is on. +var privateNetworkPolicy = surfguard.Policy{}.AllowAllPorts().Allow(privateNetworkPrefixes...) // privateNetworkAdmits reports whether the opt-in admits addr: it is in // privateNetworkPrefixes and privateNetworkPolicy does not refuse it. @@ -72,17 +72,44 @@ func privateNetworkAdmits(addr netip.Addr) bool { return false } -// privateNetworkTransport is an opted-in lane's direct transport. The lane's -// own policy judges every address, as it does without the opt-in; only an -// address it refuses that privateNetworkAdmits is let through, so everything -// else the IANA special-use tables refuse (NAT64, AMT, AS112 and the rest) -// stays refused. Each dial is judged at connect time, which is what defeats -// DNS rebinding. -func privateNetworkTransport(policy surfguard.Policy) http.RoundTripper { +// privateNetworkTransport is an opted-in lane's direct transport. A request +// to a host inScope rides a transport whose dial check is the lane's own +// policy, letting through only an address that policy refuses and +// privateNetworkAdmits, so everything else the IANA special-use tables refuse +// (NAT64, AMT, AS112 and the rest) stays refused. Each dial is judged at +// connect time, which is what defeats DNS rebinding. A request to any other +// host rides the lane's ordinary transport, as it would without the opt-in. +func privateNetworkTransport(policy surfguard.Policy, inScope func(host string) bool) http.RoundTripper { t := policy.Transport() dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, ControlContext: privateNetworkControl(policy)} t.DialContext = dialer.DialContext - return privateNetworkRoundTripper{policy: policy, next: t} + return privateNetworkRoundTripper{policy: policy, next: t, strict: policy.RoundTripper(), inScope: inScope} +} + +// privateScope returns the hosts an opted-in lane anchored on anchorURL may +// reach at a private address: the anchor's host, and hosts under its parent +// domain when that parent has at least two labels. A beta preview's API at +// main-api.3.bc4-beta.com advertises its issuer at main.3.bc4-beta.com, so +// both sit under 3.bc4-beta.com; a two-label parent (com, internal) would +// cover too much, so a host like api.internal admits only itself, as an +// address literal does. +func privateScope(anchorURL string) func(host string) bool { + norm := func(h string) string { return strings.TrimSuffix(strings.ToLower(h), ".") } + u, err := url.Parse(anchorURL) + if err != nil || u.Hostname() == "" { + return func(string) bool { return false } + } + base := norm(u.Hostname()) + suffix := "" + if _, err := netip.ParseAddr(base); err != nil { + if i := strings.IndexByte(base, '.'); i > 0 && strings.Contains(base[i+1:], ".") { + suffix = base[i:] + } + } + return func(host string) bool { + h := norm(host) + return h == base || (suffix != "" && strings.HasSuffix(h, suffix)) + } } // privateNetworkControl is the opted-in lane's dial check: the lane's policy, @@ -107,14 +134,19 @@ func privateNetworkControl(policy surfguard.Policy) func(context.Context, string // The host is judged with no DNS lookup (noLookup): its addresses are left to // the dial, so a slow resolver costs a request nothing beyond its own dial. type privateNetworkRoundTripper struct { - policy surfguard.Policy - next *http.Transport + policy surfguard.Policy + next *http.Transport + strict http.RoundTripper + inScope func(host string) bool } func (r privateNetworkRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { if req == nil || req.URL == nil { return nil, &surfguard.Violation{Reason: surfguard.ReasonMalformedHost} } + if !r.inScope(req.URL.Hostname()) { + return r.strict.RoundTrip(req) + } // surfguard's dialer rewrites a legacy numeric host (0x0a1405e5, // 012.024.5.229) to the address it means; a plain net.Dialer would send // it to DNS instead. No OAuth endpoint is named that way, so refuse it. @@ -164,8 +196,13 @@ func isLegacyNumericHost(host string) bool { return true } -// CloseIdleConnections forwards to the transport, as http.Client expects. -func (r privateNetworkRoundTripper) CloseIdleConnections() { r.next.CloseIdleConnections() } +// CloseIdleConnections forwards to both transports, as http.Client expects. +func (r privateNetworkRoundTripper) CloseIdleConnections() { + r.next.CloseIdleConnections() + if c, ok := r.strict.(interface{ CloseIdleConnections() }); ok { + c.CloseIdleConnections() + } +} // oauthClientTimeout bounds each OAuth HTTP request on the lane clients — // the same 30s the pre-lane appctx client carried. @@ -244,7 +281,11 @@ func (m *Manager) allowPrivateFor(baseURL string) bool { if !m.privateOptIn() { return false } - if u, err := url.Parse(baseURL); err != nil || isFirstPartyHost(u.Hostname()) { + u, err := url.Parse(baseURL) + if err != nil { + return false + } + if isFirstPartyHost(u.Hostname()) { m.warnf("warning: %s=1 is ignored for a production base URL; OAuth requests keep the SSRF address policy", oauthAllowPrivateEnv) return false } @@ -564,7 +605,7 @@ func (m *Manager) buildLaneClient(anchorURL, label string, allowPrivate bool) (* } guarded := policy.RoundTripper() if allowPrivate { - guarded = privateNetworkTransport(policy) + guarded = privateNetworkTransport(policy, privateScope(anchorURL)) } st := m.proxyState() tr := &oauthTransport{ diff --git a/internal/auth/client_test.go b/internal/auth/client_test.go index 80db4f891..d0e1913ca 100644 --- a/internal/auth/client_test.go +++ b/internal/auth/client_test.go @@ -976,15 +976,19 @@ func TestLanes_FirstPartyTransportVerifiesCertificates(t *testing.T) { } // TestPrivateNetworkAdmits pins what BASECAMP_OAUTH_ALLOW_PRIVATE=1 admits: -// RFC 1918 and IPv6 unique local space, and nothing else the issuer policy -// refuses. +// RFC 1918 space, and nothing else the issuer policy refuses: no IPv6 unique +// local space, which holds several clouds' metadata services. func TestPrivateNetworkAdmits(t *testing.T) { - for _, a := range []string{"10.20.5.229", "172.16.0.1", "192.168.1.1", "fd00::1", "::ffff:10.20.5.229"} { + for _, a := range []string{"10.20.5.229", "172.16.0.1", "192.168.1.1", "::ffff:10.20.5.229"} { assert.True(t, privateNetworkAdmits(netip.MustParseAddr(a)), a) } for _, a := range []string{ "127.0.0.1", "169.254.169.254", "100.64.0.1", "fe80::1", "::1", - "fd00:ec2::254", // EC2 IPv6 instance metadata, inside fc00::/7 + "fd00:ec2::254", // EC2 IPv6 instance metadata + "fd00:ec2::23", // EC2 IPv6 DNS + "fd20:ce::254", // GCP IPv6 metadata + "fd00:c1::a9fe:a9fe", // OCI IPv6 metadata + "fd00::1", "192.52.193.1", // AMT: IANA special use, not private "192.31.196.1", // AS112 "2001:3::1", // AMT v6 @@ -1091,7 +1095,8 @@ func TestPrivateNetworkControl(t *testing.T) { dial := func(network, address string) error { return check(context.Background(), network, address, nil) } assert.NoError(t, dial("tcp4", "10.20.5.229:443")) - assert.NoError(t, dial("tcp6", "[fd00::1]:443")) + assert.ErrorIs(t, dial("tcp6", "[fd00::1]:443"), surfguard.ErrBlocked, "no IPv6 unique local space") + assert.ErrorIs(t, dial("tcp6", "[fd20:ce::254]:80"), surfguard.ErrBlocked, "GCP metadata") assert.NoError(t, dial("tcp4", "8.8.8.8:443"), "public addresses keep the lane's verdict") for _, a := range []string{"169.254.169.254:80", "192.52.193.1:443", "127.0.0.1:443"} { assert.ErrorIs(t, dial("tcp4", a), surfguard.ErrBlocked, a) @@ -1112,7 +1117,7 @@ func TestPrivateBaseURLHint(t *testing.T) { want bool }{ {"https://10.20.5.229", "", true}, - {"https://[fd00::1]", "", true}, + {"https://[fd00::1]", "", false}, {"https://10.20.5.229", "1", false}, {"https://127.0.0.2", "", false}, {"https://169.254.169.254", "", false}, @@ -1164,10 +1169,10 @@ func TestPrivateNetworkTransport_RefusesLegacyNumericHosts(t *testing.T) { func TestPrivateNetworkRoundTripper_RefusesMalformedURLs(t *testing.T) { policy, err := oauthEndpointPolicy("https://main-api.3.bc4-beta.com", "base URL") require.NoError(t, err) - rt := privateNetworkTransport(policy).(privateNetworkRoundTripper) + rt := privateNetworkTransport(policy, privateScope("https://main-api.3.bc4-beta.com")).(privateNetworkRoundTripper) for _, u := range []*url.URL{ - {Scheme: "ftp", Host: "10.20.5.229"}, + {Scheme: "ftp", Host: "main.3.bc4-beta.com"}, {Scheme: "http", Host: "[example.com]"}, {Scheme: "http", Host: "\u24dbocalhost"}, // IDNA-normalizes to localhost {Scheme: "http", Host: ""}, @@ -1187,3 +1192,39 @@ func TestNoLookup_ShapeOnly(t *testing.T) { assert.ErrorIs(t, err, surfguard.ErrUnresolvable) assert.NotErrorIs(t, err, surfguard.ErrBlocked) } + +// TestPrivateScope: an opted-in lane reaches a private address only for the +// base URL's host and hosts under its parent domain. +func TestPrivateScope(t *testing.T) { + in := privateScope("https://main-api.3.bc4-beta.com") + for _, h := range []string{"main-api.3.bc4-beta.com", "main.3.bc4-beta.com", "MAIN.3.bc4-beta.com.", "pr-1-p01.3.bc4-beta.com"} { + assert.True(t, in(h), h) + } + for _, h := range []string{"bc4-beta.com", "evil3.bc4-beta.com", "intranet.37signals.internal", "10.20.5.229", "3.bc4-beta.com.evil.com"} { + assert.False(t, in(h), h) + } + + short := privateScope("https://api.internal") + assert.True(t, short("api.internal")) + assert.False(t, short("db.internal"), "a two-label parent admits only the host itself") + + literal := privateScope("https://10.20.5.229") + assert.True(t, literal("10.20.5.229")) + assert.False(t, literal("10.20.5.230")) +} + +// TestBC5Lane_PrivateOutOfScopeIsRefused: with the opt-in on, a private +// address under a host outside the base URL's domain (where a discovery +// document or redirect might point) is refused before any dial. +func TestBC5Lane_PrivateOutOfScopeIsRefused(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "1") + m := laneManager(t, "https://main-api.3.bc4-beta.com") + bc5, err := m.bc5Client() + require.NoError(t, err) + resp, err := doGet(t, bc5, "http://10.20.5.229/") + if resp != nil { + _ = resp.Body.Close() + } + assert.ErrorIs(t, err, surfguard.ErrBlocked, "an address literal outside the base URL's domain keeps the strict policy") +} From 14a6c87122b34cc5390a07dbd45d712bf1086793 Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Sun, 22 Nov 2026 16:21:03 -0500 Subject: [PATCH 4/5] Keep the private scope inside a registrable domain, and HTTPS only A second review found that a base URL directly under a public suffix (customer.co.uk) gave the whole suffix the private allowance, and that a GET redirect could reach an in-scope private host over plain HTTP. The scope now stops at the public suffix list, and a private address is admitted only over HTTPS, where a certificate vouches for the host. --- README.md | 8 ++++---- internal/auth/client.go | 32 ++++++++++++++++++-------------- internal/auth/client_test.go | 27 ++++++++++++++++++++++++++- 3 files changed, 48 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index ae5d667d9..3e2129968 100644 --- a/README.md +++ b/README.md @@ -404,10 +404,10 @@ BASECAMP_OAUTH_ALLOW_PRIVATE=1 BASECAMP_BASE_URL=https://-api.3.bc4-beta.c ``` Only `1` enables it. It admits RFC 1918 addresses (10/8, 172.16/12, -192.168/16) for a non-production base URL only, and only for the base URL's -host and hosts under its parent domain (`*.3.bc4-beta.com` above), so a -discovery document or redirect can't send the CLI elsewhere on the private -network. Loopback, link-local, cloud metadata, IPv6 private and other +192.168/16) over HTTPS, for a non-production base URL only, and only for the +base URL's host and hosts under its parent domain (`*.3.bc4-beta.com` above; +never a public suffix such as `co.uk`), so a discovery document or redirect +can't send the CLI elsewhere on the private network. Loopback, link-local, cloud metadata, IPv6 private and other special-use addresses stay refused, and it is ignored for Basecamp's own hosts. Keep it set for that profile's later commands, which refresh the token over the same route. diff --git a/internal/auth/client.go b/internal/auth/client.go index 0682d3702..009b1d360 100644 --- a/internal/auth/client.go +++ b/internal/auth/client.go @@ -17,6 +17,7 @@ import ( "github.com/basecamp/basecamp-sdk/go/pkg/basecamp/oauth" surfguard "github.com/basecamp/surfguard/go" "golang.org/x/net/http/httpproxy" + "golang.org/x/net/publicsuffix" "github.com/basecamp/basecamp-cli/internal/hostutil" "github.com/basecamp/basecamp-cli/internal/output" @@ -72,13 +73,15 @@ func privateNetworkAdmits(addr netip.Addr) bool { return false } -// privateNetworkTransport is an opted-in lane's direct transport. A request -// to a host inScope rides a transport whose dial check is the lane's own +// privateNetworkTransport is an opted-in lane's direct transport. An HTTPS +// request to a host inScope rides a transport whose dial check is the lane's own // policy, letting through only an address that policy refuses and // privateNetworkAdmits, so everything else the IANA special-use tables refuse // (NAT64, AMT, AS112 and the rest) stays refused. Each dial is judged at -// connect time, which is what defeats DNS rebinding. A request to any other -// host rides the lane's ordinary transport, as it would without the opt-in. +// connect time, which is what defeats DNS rebinding. Any other request (a +// host outside the scope, or plain HTTP, where no certificate vouches for the +// private host) rides the lane's ordinary transport, as it would without the +// opt-in. func privateNetworkTransport(policy surfguard.Policy, inScope func(host string) bool) http.RoundTripper { t := policy.Transport() dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, ControlContext: privateNetworkControl(policy)} @@ -88,10 +91,11 @@ func privateNetworkTransport(policy surfguard.Policy, inScope func(host string) // privateScope returns the hosts an opted-in lane anchored on anchorURL may // reach at a private address: the anchor's host, and hosts under its parent -// domain when that parent has at least two labels. A beta preview's API at -// main-api.3.bc4-beta.com advertises its issuer at main.3.bc4-beta.com, so -// both sit under 3.bc4-beta.com; a two-label parent (com, internal) would -// cover too much, so a host like api.internal admits only itself, as an +// domain when that parent is a registrable domain or below one. A beta +// preview's API at main-api.3.bc4-beta.com advertises its issuer at +// main.3.bc4-beta.com, so both sit under 3.bc4-beta.com. A parent that is a +// public suffix (co.uk, github.io) or a single label (internal) would take in +// hosts other parties own, so such an anchor admits only itself, as an // address literal does. func privateScope(anchorURL string) func(host string) bool { norm := func(h string) string { return strings.TrimSuffix(strings.ToLower(h), ".") } @@ -102,8 +106,11 @@ func privateScope(anchorURL string) func(host string) bool { base := norm(u.Hostname()) suffix := "" if _, err := netip.ParseAddr(base); err != nil { - if i := strings.IndexByte(base, '.'); i > 0 && strings.Contains(base[i+1:], ".") { - suffix = base[i:] + if i := strings.IndexByte(base, '.'); i > 0 { + parent := base[i+1:] + if _, err := publicsuffix.EffectiveTLDPlusOne(parent); err == nil && strings.Contains(parent, ".") { + suffix = base[i:] + } } } return func(host string) bool { @@ -144,7 +151,7 @@ func (r privateNetworkRoundTripper) RoundTrip(req *http.Request) (*http.Response if req == nil || req.URL == nil { return nil, &surfguard.Violation{Reason: surfguard.ReasonMalformedHost} } - if !r.inScope(req.URL.Hostname()) { + if req.URL.Scheme != "https" || !r.inScope(req.URL.Hostname()) { return r.strict.RoundTrip(req) } // surfguard's dialer rewrites a legacy numeric host (0x0a1405e5, @@ -153,9 +160,6 @@ func (r privateNetworkRoundTripper) RoundTrip(req *http.Request) (*http.Response if isLegacyNumericHost(req.URL.Hostname()) { return nil, &surfguard.Violation{Host: req.URL.Hostname(), Reason: surfguard.ReasonMalformedHost} } - if req.URL.Scheme != "http" && req.URL.Scheme != "https" { - return nil, &surfguard.Violation{Reason: surfguard.ReasonScheme} - } var v *surfguard.Violation if err := r.policy.WithResolver(noLookup{}).CheckURL(req.Context(), req.URL.String()); errors.As(err, &v) && v.Reason == surfguard.ReasonMalformedHost { return nil, err diff --git a/internal/auth/client_test.go b/internal/auth/client_test.go index d0e1913ca..e976719d8 100644 --- a/internal/auth/client_test.go +++ b/internal/auth/client_test.go @@ -1173,6 +1173,7 @@ func TestPrivateNetworkRoundTripper_RefusesMalformedURLs(t *testing.T) { for _, u := range []*url.URL{ {Scheme: "ftp", Host: "main.3.bc4-beta.com"}, + {Scheme: "http", Host: "10.20.5.229"}, {Scheme: "http", Host: "[example.com]"}, {Scheme: "http", Host: "\u24dbocalhost"}, // IDNA-normalizes to localhost {Scheme: "http", Host: ""}, @@ -1206,7 +1207,16 @@ func TestPrivateScope(t *testing.T) { short := privateScope("https://api.internal") assert.True(t, short("api.internal")) - assert.False(t, short("db.internal"), "a two-label parent admits only the host itself") + assert.False(t, short("db.internal"), "a single-label parent admits only the host itself") + + for anchor, other := range map[string]string{ + "https://customer.co.uk": "probe.attacker.co.uk", + "https://someone.github.io": "attacker.github.io", + } { + in := privateScope(anchor) + assert.True(t, in(strings.TrimPrefix(anchor, "https://")), anchor) + assert.False(t, in(other), "a public-suffix parent (%s) admits only the host itself", anchor) + } literal := privateScope("https://10.20.5.229") assert.True(t, literal("10.20.5.229")) @@ -1228,3 +1238,18 @@ func TestBC5Lane_PrivateOutOfScopeIsRefused(t *testing.T) { } assert.ErrorIs(t, err, surfguard.ErrBlocked, "an address literal outside the base URL's domain keeps the strict policy") } + +// TestBC5Lane_PrivateNeedsHTTPS: with the opt-in on, an in-scope host reached +// over plain HTTP keeps the strict policy: no certificate vouches for it. +func TestBC5Lane_PrivateNeedsHTTPS(t *testing.T) { + clearProxyEnv(t) + t.Setenv(oauthAllowPrivateEnv, "1") + policy, err := oauthEndpointPolicy("https://main-api.3.bc4-beta.com", "base URL") + require.NoError(t, err) + // The scope admits the literal, so only the scheme decides. + rt := privateNetworkTransport(policy, func(string) bool { return true }).(privateNetworkRoundTripper) + req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://10.20.5.229:8080/action", nil) + require.NoError(t, err) + _, err = rt.RoundTrip(req) + assert.ErrorIs(t, err, surfguard.ErrBlocked) +} From 11d27f4b4050eb39e000d851ac678658d137261a Mon Sep 17 00:00:00 2001 From: Rob Zolkos Date: Sun, 22 Nov 2026 16:41:58 -0500 Subject: [PATCH 5/5] Test the in-scope HTTPS path itself Since the private allowance became HTTPS-only, the malformed-host tests used HTTP and took the strict path, so removing the private path's own checks left them passing. The new tests send HTTPS with a sentinel in place of the strict transport, and fail when either check is removed. --- internal/auth/client_test.go | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/internal/auth/client_test.go b/internal/auth/client_test.go index e976719d8..5d9cadcd1 100644 --- a/internal/auth/client_test.go +++ b/internal/auth/client_test.go @@ -1253,3 +1253,66 @@ func TestBC5Lane_PrivateNeedsHTTPS(t *testing.T) { _, err = rt.RoundTrip(req) assert.ErrorIs(t, err, surfguard.ErrBlocked) } + +// sentinelRoundTripper records that a request reached it and answers with a +// fixed error, standing in for the strict transport. +type sentinelRoundTripper struct{ hits *atomic.Int32 } + +var errSentinel = errors.New("strict transport") + +func (s sentinelRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { + s.hits.Add(1) + return nil, errSentinel +} + +// TestPrivateNetworkRoundTripper_Routing exercises the in-scope HTTPS path +// itself, with the strict transport replaced by a sentinel so each case shows +// which path it took. None makes a connection. +func TestPrivateNetworkRoundTripper_Routing(t *testing.T) { + policy, err := oauthEndpointPolicy("https://main-api.3.bc4-beta.com", "base URL") + require.NoError(t, err) + newRT := func(inScope func(string) bool) (privateNetworkRoundTripper, *atomic.Int32) { + var hits atomic.Int32 + rt := privateNetworkTransport(policy, inScope).(privateNetworkRoundTripper) + rt.strict = sentinelRoundTripper{&hits} + return rt, &hits + } + do := func(rt privateNetworkRoundTripper, ctx context.Context, u *url.URL) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://placeholder/", nil) + require.NoError(t, err) + req.URL = u + _, err = rt.RoundTrip(req) + return err + } + all := func(string) bool { return true } + + t.Run("malformed and numeric HTTPS hosts are refused on the private path", func(t *testing.T) { + rt, hits := newRT(all) + // A refusal comes before any dial; the deadline only makes a + // regression fail quickly instead of waiting on the network. + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + for _, host := range []string{"0x0a1405e5", "012.024.5.229", "[example.com]", "ⓛocalhost", ""} { + err := do(rt, ctx, &url.URL{Scheme: "https", Host: host}) + assert.ErrorIs(t, err, surfguard.ErrBlocked, "%q", host) + } + assert.Zero(t, hits.Load(), "every case was judged on the private path") + }) + + t.Run("a well-formed in-scope HTTPS host goes to the private transport", func(t *testing.T) { + rt, hits := newRT(all) + ctx, cancel := context.WithCancel(context.Background()) + cancel() // the transport gives up before dialing + err := do(rt, ctx, &url.URL{Scheme: "https", Host: "10.20.5.229", Path: "/"}) + assert.ErrorIs(t, err, context.Canceled) + assert.NotErrorIs(t, err, surfguard.ErrBlocked) + assert.Zero(t, hits.Load()) + }) + + t.Run("out of scope or plain HTTP goes to the strict transport", func(t *testing.T) { + rt, hits := newRT(privateScope("https://main-api.3.bc4-beta.com")) + assert.ErrorIs(t, do(rt, context.Background(), &url.URL{Scheme: "https", Host: "intranet.example.com"}), errSentinel) + assert.ErrorIs(t, do(rt, context.Background(), &url.URL{Scheme: "http", Host: "main.3.bc4-beta.com"}), errSentinel) + assert.Equal(t, int32(2), hits.Load()) + }) +}