Skip to content

fix(oauth): honour the oauth block for upstreams that authorise per method (#1271) - #1273

Merged
Dumbris merged 4 commits into
mainfrom
fix/1271-oauth-block-per-method-auth
Sep 13, 2026
Merged

Dumbris merged 4 commits into
mainfrom
fix/1271-oauth-block-per-method-auth

Conversation

@Dumbris

@Dumbris Dumbris commented Sep 12, 2026

Copy link
Copy Markdown
Member

Closes #1271

Problem

An upstream that answers initialize/tools/list anonymously but 401s tools/call (Google's Gmail MCP endpoint) could never be authenticated. The HTTP/SSE ladder was headers → no-auth → OAuth; runAuthStrategies stops at the first strategy that returns nil, tryNoAuth returns nil on a successful anonymous initialize, so the OAuth strategy — with a valid token already in the store — was never reached. Every tools/call then failed with authorization required while auth status reported token_valid: true, and auth login refused with HTTP 500 server connected without OAuth - no authentication required (the three manual-login paths drew the same conclusion from a successful initialize).

Fix

  • Ladder (internal/upstream/core/connection_http.go): a configured oauth block — the documented "OAuth required" signal (config.ServerConfig.OAuth: keep even when empty to signal OAuth requirement) — makes OAuth the only strategy. The headers strategy draws the same "anonymous initialize succeeded" inference, so it is dropped too; static headers now ride on the OAuth transport, where the token store owns Authorization (consistent with the GH [Bug]: Server keeps showing "Token expired" after switching it from OAuth to a header token #1172 projection, which already treats an oauth block as decisive over a static Authorization header). Brokered (spec 074) headers-only fail-closed still takes precedence; MCPPROXY_DISABLE_OAUTH keeps the historical chain.
  • Transport (internal/transport/http.go): both OAuth constructors carry cfg.Headers (they dropped them before) and refuse a brokered per-user credential outright.
  • Manual login (connection_oauth.go): forcedAuthorizationRequired() synthesises the OAuthAuthorizationRequiredError the three login paths key on, from the live transport's handler, when initialize succeeds but OAuth is declared. oauth.ShouldUseOAuth no longer lets unrelated static headers veto a declared oauth block.
  • SSE: trySSEOAuthAuth's Start()-error branch (now reachable for declared-OAuth servers without a token) parks in PendingAuth under deferral and clears the in-progress mark before starting a flow — it used to dead-end in OAuth authorization already in progress. forceSSEOAuthFlowWithResult no longer shadows its result (both branches).
  • Paths the change exposed (found by review, all reproduced): the OAuth-strategy waiter returned nil after another client's flow completed, which runAuthStrategies read as "connected" → a client with no transport marked ready (ghost connection); it now returns an OAuth-classified retry error. tryOAuthAuth/trySSEOAuthAuth use a named oauthErr return so every exit reaches coordinator.EndFlow. StartManualOAuthQuick's reconnect watcher owned the 30-minute login context and cancelled it after ~2 s whenever a completion was already on record (exactly the re-login this PR enables) or after 2 minutes — the browser callback then got 400; completion is now detected as a token change, cancel only then, at the deadline, or on manager shutdown.
  • ErrOAuthPending detail names the oauth block as the reason the anonymous probe was skipped; the "no authentication required" refusal (servers without a block) names the remedy.

Behaviour change (documented in docs/configuration.md)

An oauth block now means "OAuth, period": a server carrying one no longer connects anonymously, and a static Authorization header is not used while the block is present — remove the block for a server that needs no sign-in. Health detail says so explicitly. Manual login on a declared-OAuth server always starts a fresh sign-in, even with a valid token stored.

Test rig

tests/oauthserver gained Options.MCPPerMethodAuth (-per-method-auth on the standalone server): initialize/ping/tools/list/notifications/* anonymous, tools/call 401 — the Gmail behaviour — plus a legacy /sse endpoint behind the same middleware.

Tests (each proven to fail without its fix)

  • internal/upstream/core/auth_strategy_oauth_block_test.go — ladder shape (oauth block, headers, brokered, env gate), forcedAuthorizationRequired.
  • internal/upstream/core/per_method_auth_e2e_test.go — real Client against the per-method rig: HTTP + SSE with a seeded token end on the OAuth strategy and tools/call succeeds; no block stays anonymous (boundary); SSE with no token parks in PendingAuth fast; manual login proceeds with a valid token; six same-name clients connecting at once — no ghost connection.
  • internal/upstream/manual_oauth_relogin_test.go — manager-level re-login: callback still finds the login waiting after the watcher's first tick.
  • internal/transport/oauth_static_headers_test.go — static headers carried, token store wins Authorization, brokered+OAuth refused.
  • internal/oauth/should_use_oauth_block_test.go, tests/oauthserver/per_method_auth_test.go.

Verification

  • go test -race ./internal/upstream/... ./internal/transport/... ./internal/oauth/... ./internal/runtime/... ./tests/oauthserver/... green; golangci-lint (CI config) 0 issues; ./scripts/test-api-e2e.sh 65/65.
  • Live: isolated mcpproxy serve against oauthserver -per-method-auth — server parks in Sign-in required (was: falsely connected), headless login via POST /api/v1/servers/{name}/login → callback 200 → Connected (2 tools), mcpproxy call tool-read succeeds, re-login with a valid token returns 200 + auth URL and its callback lands (was: HTTP 500), survives a daemon restart. auth status no longer contradicts itself.
  • Cross-review: opencode gpt-6-astra, 4 rounds (3 P2 + 1 P3 fixed, final VERDICT: CLEAN); independent adversarial pass (5 lenses, 15 confirmed items) — actionable ones fixed above, the rest are documented trade-offs or pre-existing residuals listed below.

Known residuals (not introduced here)

  • A declared-OAuth server that is unreachable shows Sign-in required instead of a connection error until the first login (no request is sent without a token). Documented.
  • For a stored token that Google rejects on tools/list (but accepts on initialize), the server shows connected with 0 tools rather than a sign-in CTA — same as before this PR; a tools/list-401 → sign-in signal would close it.
  • mcpproxy's own auth-server discovery still depends on a 401 from its bare preflight; the Gmail login works through mcp-go's handler with a static client_id/client_secret/scopes as the issue reporter observed.

🤖 Generated with Claude Code

Dumbris and others added 4 commits September 12, 2026 21:40
…ethod (#1271)

An upstream that answers initialize/tools/list anonymously but 401s
tools/call (Google's Gmail MCP endpoint) could never be authenticated:
the no-auth strategy "succeeded" on the anonymous handshake, the ladder
stopped there, and the OAuth strategy — with a valid token already in the
store — was never reached. Every tools/call then failed with
"authorization required" while auth status reported the token as valid,
and `mcpproxy auth login` refused with "server connected without OAuth".

- Ladder: a configured `oauth` block (the documented "OAuth required"
  signal) drops the anonymous probe. The headers strategy draws the same
  inference, so it is kept only for a static Authorization credential;
  other static headers now ride on the OAuth transport instead of being
  dropped by it. MCPPROXY_DISABLE_OAUTH keeps the historical chain.
- Manual login: the three login paths continue with the transport's own
  OAuth handler when initialize succeeds but OAuth is declared, instead
  of concluding "no authentication required"; oauth.ShouldUseOAuth no
  longer lets unrelated headers veto a declared oauth block.
- SSE: trySSEOAuthAuth's Start()-error branch (now reachable for declared
  OAuth servers without a token) parks in PendingAuth like the HTTP path
  and clears the in-progress mark before starting a flow, instead of
  dead-ending in "OAuth authorization already in progress".
- forceSSEOAuthFlowWithResult no longer shadows its result.
- tests/oauthserver: `MCPPerMethodAuth` option (and `-per-method-auth`
  flag) reproduces the per-method behaviour; legacy `/sse` endpoint.

Co-Authored-By: Claude Opus 5 <[email protected]>
- Ladder: an oauth block now yields OAuth only — a stale static
  Authorization header could still win the anonymous handshake and pin
  the connection exactly like no-auth did. Static headers ride on the
  OAuth transport where the token store owns Authorization (consistent
  with the GH #1172 projection).
- tryOAuthAuth/trySSEOAuthAuth: oauthErr is now the named return, so the
  ErrOAuthPending and retry-with-stored-token exits reach the
  coordinator's EndFlow as failures instead of telling a concurrent
  waiter the flow succeeded.
- forceSSEOAuthFlowWithResult: the initialize-triggered branch no longer
  shadows the outer result either.

Co-Authored-By: Claude Opus 5 <[email protected]>
- OAuth strategy waiter: returning nil after another client's flow
  completed was read by runAuthStrategies as "connected", leaving a
  client with no transport marked ready (ghost connection). Return an
  OAuth-classified retry error instead. Pre-existing, but with an oauth
  block OAuth is now the only strategy so every same-name overlap hit it.
- Transport: OAuth constructors refuse a brokered per-user credential
  outright and carry cfg.Headers (not effectiveHeaders), so spec 074
  fail-closed holds at the transport too.
- StartManualOAuthQuick: the reconnect watcher owned the 30-minute login
  context and cancelled it after ~2s whenever a completion was already on
  record (the re-login a declared-OAuth server now permits) or after 2
  minutes; the browser callback then found nobody waiting. Completion is
  now detected as a token change, cancel only then or at the deadline.
- ErrOAuthPending detail names the oauth block as the reason the
  anonymous probe was skipped.
- Tests: concurrent same-name clients (ghost-connection invariant),
  brokered+OAuth refusal, manager-level re-login callback; SSE fixture
  shutdown ordering (5s -> 0.1s); short deadline on the PendingAuth test.

Co-Authored-By: Claude Opus 5 <[email protected]>
@cloudflare-workers-and-pages

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/1271-oauth-block-per-method-auth

Available Artifacts

  • archive-darwin-amd64 (29 MB)
  • archive-darwin-arm64 (27 MB)
  • archive-linux-amd64 (17 MB)
  • archive-linux-arm64 (16 MB)
  • archive-windows-amd64 (29 MB)
  • archive-windows-arm64 (26 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (24 MB)
  • installer-dmg-darwin-arm64 (21 MB)
  • smart-mcp-proxymcpproxy-goHY8WDE.dockerbuild (0 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 34714770355 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 70.58824% with 35 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/upstream/core/connection_oauth.go 63.41% 14 Missing and 1 partial ⚠️
tests/oauthserver/mcp.go 56.52% 6 Missing and 4 partials ⚠️
internal/upstream/manager.go 66.66% 4 Missing and 2 partials ⚠️
tests/oauthserver/cmd/server/main.go 0.00% 3 Missing ⚠️
tests/oauthserver/server.go 87.50% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@Dumbris
Dumbris merged commit 9d7e7f6 into main Sep 13, 2026
41 checks passed
@Dumbris
Dumbris deleted the fix/1271-oauth-block-per-method-auth branch September 13, 2026 03:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

OAuth strategy never attempted when an upstream accepts anonymous initialize but requires auth for tools/call

2 participants