Police OAuth egress with per-provenance address enforcement

Merged
JE
3mo ago
+1379-115

The CLI passes its own m.httpClient to every SDK OAuth entry point, and a caller-supplied client is the caller's, enforcement included — so neither basecamp-sdk#804's nor #810's SSRF address policy was live here: a malicious BC5 discovery document could still steer the device-authorization and token POSTs (carrying client_id, device_code, refresh token) into private address space. This PR makes the policy live, pinned to SDK v0.15.0 (1dd547b3 — the exact release commit, recorded via scripts/bump-sdk.sh).

Design: per-provenance lanes, selected at the call sites

One loopback-enabled client shared by every lane would let a localhost BASECAMP_LAUNCHPAD_URL grant loopback to a production BC5 flow. Instead, two lazily built, cached, error-returning lanes on the Manager (bc5Client() / launchpadClient()), each {30 s, checkAuthClientRedirect, per-lane transport}:

  • BC5 lane (policy from cfg.BaseURL; AllowLoopback iff that host is local): discovery both hops — WithIssuerHTTPClient is passed unconditionally so a local resource's local advertised issuer isn't refused by the SDK's internal default right after hop 1 succeeds — plus device authorization + polling, and refreshes of bc5-typed credentials.
  • Launchpad lane (policy from validated launchpadURL(), env override included): web-flow code exchange and launchpad-typed refreshes. Refresh lane selection is by the stored OAuthType (a policy anchor, not a claimed binding — OAuthType and TokenEndpoint persist independently).
  • Loopback derivation parses the anchor URL and lowercases the host before hostutil.IsLocalhost (which is case-sensitive); errors name the anchor without echoing its value.
  • The single injected-client seam remains, documented caller-owned/test-only; appctx now passes nil, and checkAuthClientRedirect (the credential-replay guard, preserved on both lanes) moved into internal/auth with its tests — appctx no longer owns behavior it doesn't use.

Proxy handling: per-request, fail-closed, never unguarded direct

Each lane's transport is a proxy-aware wrapper over two sub-transports — the surfguard-policed direct transport, and (opt-out mode only) a clone of http.DefaultTransport pinned to the one construction-time snapshot of httpproxy.FromEnvironment().ProxyFunc() (never http.ProxyFromEnvironment, whose process-global cache could diverge from the snapshot). Per request, against the actual request URL (discovered issuer, device, polling, persisted refresh endpoints all evaluated):

  • resolver error → the request is refused before either sub-transport runs (the one real error httpproxy produces — CGI REQUEST_METHOD + HTTP_PROXY — is tested, plus an injected-resolver unit test);
  • resolver names a proxy and BASECAMP_OAUTH_USE_PROXY=1 → proxied sub-transport, enforcement off for exactly that request, downgrade logged (deduplicated per endpoint — the device poll re-POSTs the same URL);
  • everything else → the guarded direct transport. A NO_PROXY exclusion stays enforced even in opt-out mode; there is no path to unguarded direct egress (the decisive regression test: opt-out + NO_PROXY-covered private target → surfguard.ErrBlocked, zero dials).

Default (protected) mode enforces unconditionally and warns — deduplicated, driven by effective routing rather than variable presence — when a configured proxy is ignored for OAuth traffic, naming the opt-out knob. Malformed opt-out values (yes, 2) are off, with a warning.

Error taxonomy across the CLI boundary

refreshLocked and exchangeCode used to stringify SDK errors into ErrAPI(0, …), which would discard basecamp-sdk#813's redirect status and break errors.Is(err, surfguard.ErrBlocked). They now wrap preserving code, HTTP status, retryability, and the cause chain — tested for errors.Is(ErrBlocked) and errors.As(*basecamp.Error) survival on both paths.

Deviations from the reviewed plan, on the record

  • BASECAMP_OAUTH_USE_PROXY="" (set-but-empty) is treated as unset silently, not warned: env-scrubbing (t.Setenv, direnv) is indistinguishable from intent, and warning would fire in every scrubbed environment. Non-empty malformed values warn as planned.
  • A malformed proxy URL never reaches the resolver-error branch — httpproxy.Config.init silently drops unparsable values — so that case degrades to no-proxy → guarded direct, still enforced (tested as such). The fail-closed branch exists for the errors the resolver does produce.
  • internal/commands/tools.go: Tool.Name became *string in SDK v0.15.0 — one-line deref fallout from the pin, matching the neighboring Position handling.

Follow-up tied to the next SDK re-pin

TestRefreshLocked_RedirectStatusSurvives is committed but skipped: v0.15.0 predates basecamp-sdk#813's token-endpoint redirect classification. Un-skip at the next re-pin.

Verification

go build ./..., go vet ./..., gofmt -s -l clean, full make test, make lint (0 issues), make provenance-check. Existing OAuth tests (which inject clients) unchanged and green. Manual basecamp auth login against production and against a localhost bc3 dev server still deserves a pass before merge — the end-to-end local-chain admission/refusal is covered by TestDiscoverOAuth_LocalIssuerChainFollowsBaseURL, but a live login exercises the browser/device interaction this suite can't.


Summary by cubic

Previously one injected client bypassed the SDK's SSRF policy; a malicious discovery doc could steer device/token POSTs into private address space. OAuth egress now rides per-provenance clients that enforce the address policy and preserve SDK error taxonomy.

  • BC5 lane derives policy from cfg.BaseURL (loopback only when that anchor is local) and carries discovery both hops, device auth/polling, and bc5-typed refreshes.
  • Launchpad lane derives policy from validated launchpadURL() and carries web-flow code exchange and launchpad-typed refreshes; loopback allowance does not cross lanes.
  • BASECAMP_OAUTH_USE_PROXY=1 routes only positively-proxied requests through a cloned DefaultTransport pinned to a construction-time httpproxy snapshot (downgrades logged, deduped per endpoint); otherwise the surfguard-guarded direct transport is used with NO_PROXY still enforced — no path to unguarded direct egress. Warnings are sanitized at the sink and render endpoints percent-encoded and proxies as scheme://host only.
  • Refresh/exchange wrap SDK errors without flattening, so errors.Is(err, surfguard.ErrBlocked) and typed code/status/retryability survive.
  • Lane clients block non-GET/HEAD redirects at 10 hops; appctx passes nil so internal/auth builds the policed clients and owns the redirect guard.
  • Pins github.com/basecamp/basecamp-sdk/go to v0.15.0, adds github.com/basecamp/surfguard/go, rebases onto main's basecamp/cli, x/crypto, and mcp bumps, and syncs the vendored MCP model (description/required-field tightening only, no operation changes). tools show omits the name parenthetical when Tool.Name is nil.

Rollout:

  • To proxy OAuth, set BASECAMP_OAUTH_USE_PROXY=1; any other non-empty value is off with a warning; empty is treated as unset.
  • Ensure Base URL and BASECAMP_LAUNCHPAD_URL are correct; loopback is allowed only when that lane's anchor is local.
  • Do not inject a custom OAuth http.Client in production; it disables enforcement by design.