Repository navigation
Description
Follow-up to #975, specifically #975 (comment)
Summary
The OAuth callback endpoint renders "Authorization Successful" unconditionally — including when the authorization code it just received is discarded because the state does not match the flow that happens to be parked on the callback channel. The user sees success in the browser while mcpproxy stays signed out and the provider never receives a /token request.
Built and reproduced at commit 4d306240e. Verified identical on origin/main as of filing (310386f19): the OAuth sources cited below — connection_oauth.go, internal/oauth/config.go, internal/config/config.go, internal/upstream/manager.go, internal/storage/models.go — are byte-identical between the two commits, and mark3labs/mcp-go is v0.57.0 at both. Every line number below is valid at either commit.
Repro rig
Same isolated rig as #1066:
HEADLESS=1 MCPPROXY_TELEMETRY=false ./mcpproxy serve \
--config ./mcp_config.json --data-dir ./data \
--listen 127.0.0.1:18811 --log-level=debug
Upstream fakegh → http://127.0.0.1:18890/mcp, static oauth.client_id: "Ov23liSTATICCLIENTID", no client_secret. Fake GitHub-shaped provider on 127.0.0.1:18890: PRM + RFC 8414 metadata, code_challenge_methods_supported: ["S256"], no registration_endpoint (DCR impossible, exactly like github.com/login/oauth). Browser simulated with curl, since HEADLESS=1 suppresses the browser open.
Observed
- Browser: the callback page reports success.
GET /api/v1/servers:{'name': 'fakegh', 'connected': False, 'status': 'error', 'tool_count': 0, 'authenticated': False}, health{'level': 'unhealthy', 'admin_state': 'enabled', 'summary': 'Authentication required', 'action': 'login'}.- No token persisted; zero tools discovered.
- The provider receives no
/tokenrequest for that code — it is never redeemed.
Timeline (verbatim from data/logs/main.log)
20:09:57 — manual login (POST /api/v1/servers/fakegh/login) mints state A = acQFHzIy6SIc0w4p0Lf8AD4CwZL2uoP- and parks an async waiter:
L670: 20:09:57.676 | INFO | upstream/manager.go:2361 | 🔐 Starting quick OAuth flow | {"server": "fakegh", "correlation_id": "oauth-fakegh-1787764197676146000"}
L675: 20:09:57.682 | INFO | upstream/manager.go:2361 | 🌐 Authorization URL obtained | {"server": "fakegh", "correlation_id": "oauth-fakegh-1787764197676146000"}
L677: 20:09:57.682 | INFO | runtime/asm_arm64.s:1268 | ⏳ Waiting for OAuth callback in background | {"server": "fakegh", "correlation_id": "oauth-fakegh-1787764197676146000"}
The REST login response carries state A in full:
"auth_url": "http://127.0.0.1:18890/authorize?client_id=Ov23liSTATICCLIENTID&code_challenge=6bifj9S8BZdSPB4CTfsokT67lZ5zUzcQXsujcrtAmJ0&code_challenge_method=S256&redirect_uri=http%3A%2F%2F127.0.0.1%3A54308%2Foauth%2Fcallback&resource=http%3A%2F%2F127.0.0.1%3A18890%2Fmcp%2F&response_type=code&scope=repo+read%3Aorg&state=acQFHzIy6SIc0w4p0Lf8AD4CwZL2uoP-"
20:11:57 — that waiter's hard 120s window expires (internal/upstream/core/connection_oauth.go:2117) and it leaves. The callback server on :54308 stays up.
20:12:56 — a background reconnect (supervisor retry through the connect path) mints state B = cB7PcsY-Dv01x5racJju9GEqDbgX5SVe and parks on the same callback channel. Note the log line says "manual OAuth authorization flow" although no human triggered it — that is handleOAuthAuthorization() reached from the reconnect path, and the wording is itself misleading:
L1086: 20:12:56.606 | INFO | core/connection_oauth.go:501 | 🔐 Starting manual OAuth authorization flow | {"server": "fakegh"}
L1088: 20:12:56.608 | INFO | core/connection_oauth.go:501 | 🔑 Generated PKCE and state parameters | {"server": "fakegh", "state": "cB7PcsY-Dv01x5racJju9GEqDbgX5SVe"}
L1095: 20:12:56.608 | INFO | core/connection_oauth.go:501 | ⏳ Waiting for OAuth authorization callback... | {"server": "fakegh", "timeout": 120, "wait_start": "2026-08-26T20:12:56.608+03:00"}
20:13:04 — the callback carrying state A arrives on :54308. The reconnect's waiter (state B) wins the channel and the code is discarded:
L1115: 20:13:04.281 | DEBUG | core/connection.go:148 | 🚫 Auth strategy failed | {"server": "fakegh", "strategy_index": 2, "strategy": "OAuth", "error": "OAuth authorization during MCP init failed: state mismatch: expected cB7PcsY-Dv01x5racJju9GEqDbgX5SVe, got acQFHzIy6SIc0w4p0Lf8AD4CwZL2uoP-"}
L1120: 20:13:04.281 | ERROR | upstream/manager.go:448 | Connection error | {"component": "managed_client", "server": "fakegh", "error": "failed to connect: OAuth authorization during MCP init failed: state mismatch: expected cB7PcsY-Dv01x5racJju9GEqDbgX5SVe, got acQFHzIy6SIc0w4p0Lf8AD4CwZL2uoP-", "retry_count": 4}
At that exact moment the browser was served:
<html>
<body>
<h1>Authorization Successful</h1>
<p>You can now close this window and return to the application.</p>Provider-side negative evidence — the complete AUTHORIZE/TOKEN log for the session. The :54308 authorize has no matching TOKEN request:
[provider] AUTHORIZE client_id='Ov23liSTATICCLIENTID' redirect_uri='http://127.0.0.1:54108/oauth/callback' -> http://127.0.0.1:54108/oauth/callback?code=CODE-189ab0649a61&state=JpXFE2JnaJhc-326rmXr-HYR_Tbg1gC6
[provider] TOKEN request form= {"client_id": "Ov23liSTATICCLIENTID", "code": "<code:len=17>", "code_verifier": "<code_verifier:len=64>", "grant_type": "authorization_code", "redirect_uri": "http://127.0.0.1:54108/oauth/callback", "resource": "http://127.0.0.1:18890/mcp/"}
[provider] TOKEN issued ACC-66e7c090a2b268d6
[provider] AUTHORIZE client_id='Ov23liSTATICCLIENTID' redirect_uri='http://127.0.0.1:54308/oauth/callback' -> http://127.0.0.1:54308/oauth/callback?code=CODE-0c10dec185a7&state=acQFHzIy6SIc0w4p0Lf8AD4CwZL2uoP-
Root cause
1. One shared, buffer-1 channel per callback server.
internal/oauth/config.go:1027 — callbackChan := make(chan map[string]string, 1), exposed as the single CallbackServer.CallbackChan (:48, :1044). All flows for a given upstream share it; there is no per-flow routing.
2. handleCallback renders success unconditionally.
internal/oauth/config.go:1105-1155. It pushes the params non-blockingly (:1129-1136) and then writes the success page (:1138-1153) with no state check and no dependence on whether the push succeeded:
select {
case c.CallbackChan <- params:
c.logger.Info("✅ OAuth callback parameters sent to channel successfully", ...)
default:
c.logger.Error("❌ OAuth callback channel full, dropping parameters - THIS IS BAD!", ...)
}
// Respond to the user
w.Header().Set("Content-Type", "text/html")
successPage := `... <h1>Authorization Successful</h1> ...`Even on the explicit "THIS IS BAD!" drop path at :1135, the browser is told it worked. The handler has no access to any flow's state, so it cannot tell the truth as currently structured.
3. Server reuse never cancels parked waiters.
internal/oauth/config.go:972 StartCallbackServer returns the existing server for a name (:977-992). It drains at most one stale param map from the channel, but goroutines already blocked on <-CallbackChan from an earlier flow stay parked and remain eligible receivers.
4. Three competing receivers on that one channel.
internal/upstream/core/connection_oauth.go:1248—handleOAuthAuthorization(state check:1256, timeout:1294)internal/upstream/core/connection_oauth.go:1530—handleOAuthAuthorizationWithResult(state check:1536, timeout:1566)internal/upstream/core/connection_oauth.go:2074—waitForOAuthCallbackAsync(state check:2080, timeout:2117)
Go picks one arbitrarily. In the run above the winner was receiver #1 (handleOAuthAuthorization, reached from the reconnect's connect path) while the flow that minted the delivered state had used #3.
How to tell which receiver won, since the error string alone cannot: receivers #1 and #2 return the identical fmt.Errorf("state mismatch: expected %s, got %s", ...) (:1257 and :1537). They are separated only by their entry log line — :931 logs "🔐 Starting manual OAuth authorization flow", :1326 logs the same with the suffix "with result tracking". L1086 above has no suffix, and the failure surfaces through the connection.go:148 auth-strategy frame, which pins it to #1.
5. Every receiver gives up after 120s despite a 30-minute caller context.
All three sites hardcode case <-time.After(120 * time.Second) (:1294, :1566, :2117), while internal/upstream/manager.go:2355 hands the flow context.WithTimeout(context.Background(), 30*time.Minute). The timeline above is exactly this: the manual login's waiter died at 20:11:57, 59 seconds before the reconnect parked and 67 seconds before the callback landed. A GitHub sign-in with 2FA or org approval routinely exceeds two minutes, and after that only background-reconnect waiters remain to catch the callback — which is what makes the state mismatch.
6. In the async path the mismatch is logged and nothing else.
internal/upstream/core/connection_oauth.go:2080-2086 logs "❌ State mismatch in OAuth callback" and returns — no error propagates. (In the two synchronous paths it does propagate, which is why the run above surfaced it in health.detail; but the CLI had already printed ✅ OAuth authentication flow initiated successfully for server: <name> at cmd/mcpproxy/auth_cmd.go:668, and the browser had already said success.) Whichever receiver wins, the user is told the login worked.
Suggested fix
- Dispatch by
state. Register each flow'sstatewith the callback server and route the incoming params to that flow's own channel. Drop the single shared buffer-1 channel. - Render a real failure page for an unknown, expired, or already-consumed
state, and for theerror=case — the browser must not claim success when the code was discarded. Include the correlation id so the log line can be found. - Raise the 120s cap to the caller's context deadline at all three receive sites, so a slow 2FA/org-approval sign-in is not abandoned mid-flight.
- Suppress background-reconnect OAuth flows while a manual login is in flight for the same upstream, so a reconnect cannot mint a competing
stateand steal the callback. - Surface the mismatch to the CLI/UI in the async path instead of only logging it, and fix the "Starting manual OAuth authorization flow" wording at
connection_oauth.go:501, which is emitted on the automatic reconnect path too.
Caveat on attribution to #975
This reproduces a mechanism that yields the reporter's exact symptom. It is not proof that this is the mechanism they hit against real GitHub. A second independent candidate survives: GitHub's authorization_code grant appears to require client_secret even with PKCE, and the reporter's config had client_id only. Live probe with a public client id and no secret against https://github.com/login/oauth/access_token:
grant_type=urn:ietf:params:oauth:grant-type:device_code -> {"error":"authorization_pending", …}
grant_type=authorization_code -> {"error":"incorrect_client_credentials", …}
mcpproxy only sends client_secret when non-empty (mcp-go@v0.57.0/client/transport/oauth.go:1101-1103); oauth.client_secret is wired through at internal/oauth/config.go:905-908. The two causes are separable in the logs — state mismatch: expected … got … (this bug) vs token request failed: incorrect_client_credentials (missing secret). Worth asking the reporter for that line rather than assuming.
Regression test
tests/oauthserver/ already provides a full fake AS (authorize, token, PKCE, discovery, JWKS, mcpproxy_e2e_test.go) and is the right place for this — the Python provider used above duplicated it. Add a case that starts a flow, then starts a competing flow for the same upstream, delivers the callback carrying the first flow's state, and asserts (a) the token is obtained by the flow that minted it and (b) the HTTP callback response is a failure page when the state is unknown.
See also #1066 — the callback-port persistence bug found on the same rig.
Activity
Dumbris commentedon Aug 27, 2026
Fixed by #1068 (merged as af9927b): callbacks are dispatched by
statewith a single-use channel per flow, an unknown or expired state renders an explicit HTTP 400 "Authorization Failed" page instead of a fake success, and the failure is stamped onto the server's status. Not in a release yet — v0.61.0 was cut before it merged.