Skip to content

fix(oauth): keep the loopback callback port stable for static clients - #1069

Merged
Dumbris merged 1 commit into
mainfrom
fix/oauth-static-client-callback-port
Aug 27, 2026
Merged

Dumbris merged 1 commit into
mainfrom
fix/oauth-static-client-callback-port

Conversation

@Dumbris

@Dumbris Dumbris commented Aug 26, 2026

Copy link
Copy Markdown
Member

Related #975

The bug

With a static oauth.client_id configured, mcpproxy allocated a fresh loopback callback port on every login, so the redirect_uri sent to the provider changed each time. GitHub OAuth Apps (and other providers) require the callback URL to match the registered one exactly and reject wildcards, so such an integration could never be made to work — there is no single URL you can register.

Before / after, same isolated instance, same script, two consecutive login cycles with oauth.client_id: test-client:

# origin/main (310386f19)
### login 1
PORT=53568
connected: True
### login 2
PORT=53641          <-- port moved; redirect_uri changed
connected: True

# this branch
### login 1
PORT=53734
connected: True
### login 2
PORT=53734          <-- same port, identical redirect_uri
connected: True

The three parts of the fix

(a) persistDCRCredentials() persists the live callback port.
It previously only preserved an already-stored port (callbackPort := 0 then read the record), and only the DCR-succeeded branches ever wrote one. A static-credential login therefore persisted client_id with port 0. It now resolves the port from the callback server that is actually running for that upstream (resolveCallbackPortForPersistence), falling back to the stored value when no callback server is up, so a refresh-only path never downgrades a known port to 0.

(b) The clearing branches skip static clients.
With a non-empty client_id and port 0, the next login hit the "Legacy DCR credentials found without stored port, clearing for re-registration" branch and wiped the record — after which preferredPort stayed 0 and net.Listen("tcp", "127.0.0.1:0") handed out a new port. A statically configured client is never re-registered, so clearing it is always wrong. Both clearing branches (legacy-no-port and port-changed) now skip when serverConfig.OAuth.ClientID != "". Genuine DCR clients keep the original Spec 022 behavior, guarded by its own test.

(c) oauth.redirect_uri is honored as an explicit operator pin.
The field existed at internal/config/config.go:707, was diffed in DetectConfigChanges, was documented in specs/006-oauth-extra-params/quickstart.md — and was never read: internal/oauth/config.go unconditionally used callbackServer.RedirectURI. Operators believed they had pinned a port and had not. It now pins the preferred callback port, and the configured URI is sent to the provider verbatim (so localhost vs 127.0.0.1 spelling is preserved). New ParsePinnedRedirectURI validates it — http scheme, loopback host, explicit port, /oauth/callback path, no query/fragment — and a malformed value aborts the flow with an actionable error rather than silently falling back to a random port. An unavailable pinned port fails the same way, since any other port produces a redirect the provider will reject.

Pinning verified end to end as well ("redirect_uri": "http://127.0.0.1:18987/oauth/callback"):

### login 1
PORT=18987
connected: True
### login 2
PORT=18987
connected: True

Tests

Written first, watched fail against unmodified production code, then implemented. The regression test drives real production code (oauth.CreateOAuthConfig → markOAuthComplete) against the existing tests/oauthserver provider — no new fake provider.

Red before the fix:

--- FAIL: TestOAuthCallbackPort_StableAcrossLogins_StaticClient
    Error: Not equal: expected: 49679  actual: 49681
    Messages: a statically configured OAuth client must reuse the same loopback
              callback port (issue #975): got 49679 then 49681
    Error: Not equal: expected: 49679  actual: 0
    Messages: the live callback port must be persisted
--- FAIL: TestCreateOAuthConfig_StaticClientCredentialsSurviveMissingPort
    Error: Not equal: expected: "static-client"  actual: ""
    Messages: static OAuth credentials must never be cleared for re-registration
--- FAIL: TestCreateOAuthConfig_MalformedPinnedRedirectURI

Green after:

--- PASS: TestResolveCallbackPortForPersistence_UsesLiveCallbackServer (0.03s)
--- PASS: TestResolveCallbackPortForPersistence_FallsBackToStoredPort (0.03s)
--- PASS: TestOAuthCallbackPort_StableAcrossLogins_StaticClient (0.12s)
--- PASS: TestOAuthCallbackPort_PinnedRedirectURI_StableAcrossLogins (0.18s)

New coverage: internal/upstream/core/oauth_callback_port_test.go, internal/oauth/redirect_uri_pin_test.go (including a ParsePinnedRedirectURI validation table and a guard that legacy DCR credentials are still cleared).

How the local verification was run

Isolated instance only — high port, scratch --data-dir and --config, HEADLESS=1; ~/.mcpproxy/ untouched and scripts/test-api-e2e.sh never invoked. The upstream was tests/oauthserver (go run ./tests/oauthserver/cmd/server -port 18951), configured with a static client_id. Each login cycle: POST /api/v1/servers/oauthtest/login → complete the provider's login form → deliver the callback to the loopback URI. The second login was forced the way a real provider rotation does — restart the provider (new signing keys), then restart the upstream, which lands in Authentication required. No logout between cycles, since a full logout deletes the whole token record (including the port) by design.

The standalone test-provider main.go gained mcpproxy's own /oauth/callback path in the pre-registered client's redirect URIs; without it the provider rejects a real mcpproxy login with invalid_request.

Gates

  • go test -race ./internal/oauth/... ./internal/upstream/... — ok
  • go test ./internal/config/... ./internal/storage/... ./tests/... — ok
  • go build ./... and go build -tags server -o /dev/null ./cmd/mcpproxy — ok
  • golangci-lint run --config .github/.golangci.yml ./internal/oauth/... ./internal/upstream/... ./tests/... — 0 issues

Not touched

The callback-channel / state-dispatch region (handleCallback, the shared CallbackChan, StartCallbackServer's reuse path, waitForOAuthCallbackAsync) is untouched — a separate bug lives there.

A statically configured `oauth.client_id` got a fresh loopback callback
port on every login, so the redirect_uri changed each time. Providers
that require an exact callback URL and reject wildcards — GitHub OAuth
Apps among them — could never be made to work.

Three causes, three fixes:

- `persistDCRCredentials()` only *preserved* an already-stored callback
  port, and only DCR-succeeded flows ever stored one. A static-client
  login therefore persisted port 0. It now persists the port of the live
  callback server for that upstream, falling back to the stored value
  when no callback server is running.

- With client_id set and port 0, the next login took the "legacy DCR
  credentials without stored port" branch and wiped the record. A static
  client is never re-registered, so clearing it is always wrong; both
  clearing branches (legacy and port-changed) now skip static clients.

- `oauth.redirect_uri` was a dead config field: documented, diffed in
  DetectConfigChanges, never read. It is now honored as an explicit
  operator pin — the port is used as the preferred callback port and the
  configured URI is sent to the provider verbatim. It is validated
  (http, loopback host, explicit port, /oauth/callback path); a
  malformed value or an unavailable pinned port fails the login with an
  actionable error instead of silently falling back to a random port.

Related #975
@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 8e0e2e3
Status: ✅  Deploy successful!
Preview URL: https://bf255194.mcpproxy-docs.pages.dev
Branch Preview URL: https://fix-oauth-static-client-call.mcpproxy-docs.pages.dev

View logs

@codecov-commenter

codecov-commenter commented Aug 26, 2026 •

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 72.93233% with 36 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
internal/oauth/config.go 76.57% 22 Missing and 4 partials ⚠️
internal/upstream/core/connection_oauth.go 66.66% 5 Missing and 1 partial ⚠️
tests/oauthserver/cmd/server/main.go 0.00% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@Dumbris Dumbris closed this Aug 27, 2026
@Dumbris Dumbris reopened this Aug 27, 2026
@Dumbris
Dumbris enabled auto-merge (squash) August 27, 2026 05:44
@Dumbris
Dumbris merged commit c619f41 into main Aug 27, 2026
72 of 77 checks passed
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>
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.

2 participants