Repository navigation
fix(oauth): dispatch callbacks by state and stop faking success - #1068
Merged
Merged
Conversation
The OAuth callback server had one shared channel per upstream and three competing receivers on it. Whichever receiver the runtime picked won, so a background reconnect could swallow the authorization code minted by the user's manual login and discard it as a state mismatch. The browser was told "Authorization Successful" either way — including on the "channel full, dropping parameters" path — while mcpproxy stayed at "Sign-in required" and the provider never received a /token request. - Dispatch by state: each flow registers the state it minted with the callback server and gets its own single-use channel; handleCallback routes params to that flow. Registration happens before the browser opens and is released on completion or cancel, so a finished state cannot be reused. - Render an explicit "Authorization Failed" page (HTTP 400) for an unknown or expired state, and for a provider error. Success is only ever reported when the params reached a waiting flow. - Reusing a callback server no longer drains params or strands waiters — with per-state dispatch there is no stale-param hazard to drain. - The background callback waiter now follows the caller's deadline (the manager gives manual logins 30 minutes) instead of a hardcoded 120s, which used to abandon any sign-in that needed 2FA or org approval. - Undeliverable callbacks, state mismatches, failed token exchanges and expired sign-in windows are reported through a new OAuth failure hook and land on the server's health/status, so the CLI no longer claims success while the flow is dead. A server that is already Ready is left untouched. - Automatic OAuth flows stand down while a manual sign-in is in flight for the same server (non-blocking flag with an expiry, so the reconnect path cannot deadlock or be suppressed forever). Related #975
Deploying mcpproxy-docs with
|
| Latest commit: |
9bd531b
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://ddcb54b2.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://fix-oauth-callback-state-dis.mcpproxy-docs.pages.dev |
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 33001468559 --repo smart-mcp-proxy/mcpproxy-go
|
This was referenced Aug 27, 2026
github-actions Bot
pushed a commit
that referenced
this pull request
Aug 27, 2026
… and validated (#1070) * fix(oauth): make the redirect_uri pin actually reachable, diagnosable and validated PR #1069 made the per-server `oauth.redirect_uri` field load-bearing for the first time. QA of the merged change found five defects on that newly-live path. - An `::1` pin was accepted, blessed by a test and advertised in the docs, but the callback listener was hard-coded to `net.Listen("tcp", "127.0.0.1:PORT")`. The provider was handed a `[::1]` URL nothing listened on, so the browser redirect was refused and the login hung to the callback timeout. The pin now carries its host: `localhost` and `127.0.0.1` bind IPv4, `::1` binds IPv6. - Every log line in `createOAuthConfigInternal` and in the callback-server manager went to `zap.L()`, which this repo never replaces, so all of it was discarded — including #1069's new "fail loudly" errors, and the docs claim that they appear in the logs. The connection's own logger is threaded in. - A malformed pin was a permanent connect failure reported as "failed to create OAuth config - server may not support OAuth", which never names the culprit. The parse error and the "pinned port unavailable" reason now reach the user-visible error, and the write surfaces (REST config API, MCP `upstream_servers`) reject a bad value up front. The boot path deliberately does not: a value already on disk must not stop the daemon from starting. The Gemini importer no longer copies a callback URL mcpproxy cannot honor. - `StartCallbackServer` returned a cached server without honoring the requested port, so a pinned reconnect after a timed-out flow failed against a free port. It now re-binds — but only when the cached server has no waiter parked on it, preserving the invariant #1068 established. - The pinned path skipped the stored-credential read, so Spec-022 legacy cleanup never ran and a DCR registration issued against a different port was reused forever. The read always runs now; only the port choice short-circuits. Docs: correct the wildcard-callback advice in mcp-go-oauth.md (GitHub OAuth Apps reject `http://127.0.0.1:*`), drop the non-existent `redirect_port` field from the callback-mismatch error page, fix the `:8080` example that collided with mcpproxy's own listener, and resolve the port-allocation contradiction. Follow-up to #1069. Refs #975, #1066. * docs(oauth): correct the GitHub wildcard-matching claim GitHub added per-callback-URL wildcard matching in August 2026, so "rejects wildcards" is no longer accurate. The argument for pinning the port is unchanged and is what GitHub actually documents: wildcard matching covers subdomains and subdirectory paths, while the host and port must still match the registered callback exactly. --------- Co-authored-by: Algis Dumbris <gordon.greatests@gmail.com>
This was referenced Oct 12, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The OAuth callback server kept one shared
chan map[string]string(buffer 1) per upstream, and three separate places received from it (internal/upstream/core/connection_oauth.go: the sync connect flow, the sync manual flow, and the background waiter). Whichever receiver the Go runtime picked won the race.Reproduced shape: a manual login mints state A; ~3 minutes later a background reconnect mints state B and parks its own waiter; the callback arrives with state A; the reconnect's receiver wins and fails with
state mismatch: expected B, got A. The authorization code is discarded, no/tokenrequest is ever made, the server stays inError/Sign-in required, zero tools are discovered — and the browser is told "Authorization Successful" regardless, becausehandleCallbackrendered the success page unconditionally, including on thecallback channel full, dropping parameters - THIS IS BAD!path.Three further contributors:
StartCallbackServerdrained one stale param on reuse and never cancelled parked waiters;waitForOAuthCallbackAsyncgave up after a hardcoded 120s even thoughinternal/upstream/manager.gohands it a 30-minute context (a GitHub sign-in with 2FA or org approval routinely exceeds two minutes); and a state mismatch in the async path was only logged, so the CLI kept its earlier "OAuth authentication flow initiated successfully".Fix
state. Each flow registers the state it minted with the callback server (RegisterState) before the browser opens and gets its own single-use channel;handleCallbackroutes the params to that flow and removes the waiter.UnregisterStateon completion/cancel so a finished flow's state cannot be reused. All three receivers now wait on their own channel.HTTP 400+ "Authorization Failed" and is not delivered to any other flow. A provider error (error=access_denied) also renders a failure page while still reaching the waiting flow. The success page is rendered only when the params were actually delivered.oauthCallbackWaitContext), falling back to 30 minutes only when the caller passed no deadline. The sync paths keep their 120s bound deliberately — they block a caller (connect / a synchronous API call), so extending them would hang the request.TokenStoreManager.SetOAuthFailureCallback/RecordOAuthFailure; the upstream manager wires it toStateManager.SetOAuthError, so an undeliverable callback, state mismatch, failed token exchange or expired sign-in window lands on the server'shealth/last_errorlike any other auth failure. A server that is currentlyReadyis deliberately left alone, so a late or orphaned callback can't knock a working connection intoError.oauth.BeginManualFlow/IsManualFlowActiveis a per-server in-memory flag with an expiry. The automatic OAuth path checks it and stands down while a manual sign-in is in flight; the check is a non-blocking flag read (no lock held across an OAuth call, nothing waits on it), and a missed release expires after 30 minutes rather than suppressing reconnects forever. Manual flows are exempt via the existingmanualOAuthKeycontext marker. This is only noise reduction — dispatch by state is what makes the outcome correct.Also removed: the stale-param drain in
StartCallbackServer(with per-state dispatch there is no stale-param hazard to drain, and draining/stranding a parked waiter was itself part of the bug), plus its two now-obsolete tests, replaced by the dispatch tests.Before / after in the browser — mismatched state
Live against an isolated instance (
mcpproxyon127.0.0.1:18972,tests/oauthserverprovider on18971, scratch--config/--data-dir,HEADLESS=1), with a real login in flight and the callback hit with a state that belongs to no flow:Before (
handleCallbackrendered this for any callback, delivered or dropped):…while the server stayed at
Sign-in requiredand nothing was signed in.After:
and the same event is now on the server's status instead of only in the log:
Decisive test — two concurrent flows on one callback server
TestCallbackDispatch_TwoConcurrentFlows(internal/oauth/callback_dispatch_test.go) parks a manual-login waiter (state A) and a background-reconnect waiter (state B) on the same callback server, drives a real authorization throughtests/oauthserverfor state A, and asserts A receives the code, B receives nothing and stays registered, and A's code is redeemable at/token. Five rounds, alternating which flow registers first.Before — with the pre-fix semantics restored locally (single queue, whichever waiter the runtime picks; success page unconditional):
and, in the same run, the orphaned-callback test:
After:
Tests added
internal/oauth/callback_dispatch_test.go(usestests/oauthserver, no new fake provider):TwoConcurrentFlows,UnknownStateShowsFailurePage,ProviderErrorShowsFailurePage,UnregisteredStateIsRejected,ReuseKeepsWaiters,RecordsFailureForUndeliverableCallback.internal/oauth/manual_flow_test.go: claim/release, expiry, per-server scope, superseded-release safety.internal/upstream/core/oauth_callback_wait_test.go: the wait honours a 30-minute caller deadline, falls back when there is none, an expired window is reported, and the automatic flow stands down for a manual login.internal/upstream/manager_oauth_failure_test.go: a failure lands on the server status, nil/unknown servers are ignored, aReadyserver is left alone.End-to-end verification
Full manual login against
tests/oauthserveron an isolated instance:POST /api/v1/servers/oauthtest/login→ approve at the provider → callback →status: ready, authenticated: true, tools: 2,health: healthy - Connected (2 tools). The core log shows the waiter armed with"deadline": "2026-08-26 22:12:25"for a login started at21:42:25— the 30-minute caller deadline, not the old 120s.Checks
go test -race ./internal/oauth/... ./internal/upstream/...— all greengo build ./...,go build -tags server -o /dev/null ./cmd/mcpproxygolangci-lint run --config .github/.golangci.yml ./internal/oauth/... ./internal/upstream/...— 0 issues(One flake seen once and not reproducible:
TestStartBackgroundMonitoring_IsIdempotentininternal/upstream/managed, a goroutine-count assertion in code this PR does not touch; it passes on the current tree and failed identically nowhere else.)Related #975