Skip to content

OAuth callback port is not persisted for a static client_id, so it changes on every login #1066

Closed

Description

@Dumbris

Follow-up to #975, specifically #975 (comment)

Summary

With a configured static oauth.client_id (no DCR), the loopback callback port is re-allocated on every login. GitHub OAuth Apps require an exact, literal callback URL and do not accept wildcards or a wildcard port, so a GitHub OAuth App can never be configured to work with mcpproxy.

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

Isolated core instance, no shared ~/.mcpproxy state:

HEADLESS=1 MCPPROXY_TELEMETRY=false ./mcpproxy serve \
  --config ./mcp_config.json --data-dir ./data \
  --listen 127.0.0.1:18811 --log-level=debug

Upstream under test — static client_id, no client_secret:

{
  "name": "fakegh",
  "url": "http://127.0.0.1:18890/mcp",
  "protocol": "http",
  "enabled": true,
  "oauth": { "client_id": "Ov23liSTATICCLIENTID" }
}

Fake GitHub-shaped provider on 127.0.0.1:18890: serves PRM (/.well-known/oauth-protected-resource) + RFC 8414 AS metadata with code_challenge_methods_supported: ["S256"] and deliberately no registration_endpoint, so DCR is impossible — exactly like github.com/login/oauth (confirmed live: https://github.com/.well-known/oauth-authorization-server/login/oauth advertises S256 and no registration_endpoint). POST /mcp returns 401 + WWW-Authenticate: ...resource_metadata=... without a bearer, and real MCP streamable-HTTP with one. Browser was simulated with curl, since HEADLESS=1 suppresses the browser open.

Baseline first: with the callback delivered promptly, the static-client_id login fully succeeds — {'name': 'fakegh', 'connected': True, 'status': 'ready', 'tool_count': 1, 'authenticated': True}. The static path is not broken per se; the bug is that its port cannot be pinned.

Observed

Two login cycles on the same daemon (auth login → auth logout → auth login) allocate different ports. Authorize URLs as emitted by mcpproxy (code_challenge in the first is masked by mcpproxy's own log redaction):

login #1:
http://127.0.0.1:18890/authorize?client_id=Ov23liSTATICCLIENTID&code_challenge=VZo***00&code_challenge_method=S256&redirect_uri=http%3A%2F%2F127.0.0.1%3A54108%2Foauth%2Fcallback&resource=http%3A%2F%2F127.0.0.1%3A18890%2Fmcp%2F&response_type=code&scope=repo+read%3Aorg&state=JpXFE2JnaJhc-326rmXr-HYR_Tbg1gC6

login #2:
http://127.0.0.1:18890/authorize?client_id=Ov23liSTATICCLIENTID&code_challenge=TMm37weBJmLWxtB4BcxKf_Armb4XxX4NMa_QK7P4BTo&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=Q4dDmK-aISOcNAlng6zFNSu4Zc6H-fmJ

Decoded:

redirect_uri = http://127.0.0.1:54108/oauth/callback   (login #1)
redirect_uri = http://127.0.0.1:54308/oauth/callback   (login #2)

Provider side confirms login #1 was a real, completed exchange on 54108 (secret values elided by the provider's own logging, lengths only):

[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

The persisted BBolt record after that fully successful login carries the client_id but no callback_port key — CallbackPort is 0 and the field is omitempty (internal/storage/models.go:417). Read via strings -a data/config.db | grep -o '{"server_name":"fakegh_[^}]*}':

{"server_name":"fakegh_43c4351737672179","display_name":"fakegh","access_token":"ACC-66e7c090a2b268d6","refresh_token":"REF-ab84239ebb15","token_type":"Bearer","expires_at":"2026-08-26T21:08:04.165294+03:00","scopes":["repo","read:org"],"created":"2026-08-26T20:08:04.165295+03:00","updated":"2026-08-26T20:08:04.21713+03:00","client_id":"Ov23liSTATICCLIENTID"}

On the next login that zero port takes the legacy-clearing branch and the whole credential record is wiped, so the cycle repeats forever.

Root cause chain

  1. The static-credentials path never persists the port.
    internal/upstream/core/connection_oauth.go:1015 computes hasStaticCredentials; the branch at :1021-1026 only logs "Skipping Dynamic Client Registration (static credentials provided)" and returns. UpdateOAuthClientCredentials(serverKey, clientID, clientSecret, callbackPort) is called only inside the DCR-succeeded branches:

    • :1068-1085 (in connectWithOAuth-side flow), call at :1075
    • :1417-1426 (handleOAuthAuthorizationWithResult), call at :1423
    • :1924-1931 (StartOAuthFlowQuick-side flow), call at :1930

    All three read the live port via oauth.GetCallbackServer(...).Port. The static branch reaches none of them.

  2. persistDCRCredentials() only preserves an already-stored port.
    internal/upstream/core/connection_oauth.go:1648 runs for every completed flow (called from markOAuthComplete(), :1607), but at :1669-1672:

    // Preserve existing callbackPort from the record (set during the DCR flow)
    callbackPort := 0
    if record, err := c.storage.GetOAuthToken(serverKey); err == nil {
        callbackPort = record.CallbackPort
    }

    For a static-credential login there is no prior record with a port, so it persists client_id with callback_port = 0.

  3. Port 0 + non-empty client_id wipes the record on the next login.
    internal/oauth/config.go:753-775: when storedPort == 0 && storedClientID != "" it takes the branch at :764, logs "⚠️ Legacy DCR credentials found without stored port, clearing for re-registration" (:767) and calls ClearOAuthClientCredentials. preferredPort stays 0, so StartCallbackServer (:785) falls through to net.Listen("tcp", "127.0.0.1:0") (internal/oauth/config.go:1015) and a fresh random port is allocated.

    This branch is wrong for static credentials by definition: a client_id that came from mcp_config.json can never be "re-registered".

Dead config surface: oauth.redirect_uri

The natural fix already has a config field — and it is never read.

  • OAuthConfig.RedirectURI is declared at internal/config/config.go:707 (json:"redirect_uri").

  • It is diffed in DetectConfigChanges at internal/config/config.go:2616, merged in internal/config/merge.go:559-560, whitelisted in internal/config/oauth_validation.go:12, and stored as a server-identity attribute in internal/storage/server_identity.go:153,216.

  • But the OAuth flow never reads it. internal/oauth/config.go reads only serverConfig.OAuth.ExtraParams (:352, :629), .Scopes (:664), and .ClientID/.ClientSecret (:905-908). The redirect URI is set unconditionally at internal/oauth/config.go:948:

    RedirectURI: callbackServer.RedirectURI, // Exact redirect URI with allocated port
  • specs/006-oauth-extra-params/quickstart.md:333 documents "redirect_uri": "http://127.0.0.1:9000/oauth/callback" and :341 states "Custom redirect_uri disables this feature" (dynamic port allocation). Neither is true today, so users believe they have pinned a port and have not.

The workaround in #975 cannot work

The advice in #975 — set the OAuth App callback URL to http://127.0.0.1:*/oauth/callback, any port — does not work: GitHub OAuth Apps reject wildcard callback URLs and require the registered URL to match the request exactly (a port is part of that match). That inability to pin the port is this bug.

Suggested fix

  1. persistDCRCredentials() takes the live callback port (oauth.GetCallbackServer(c.config.Name).Port) instead of only preserving a stored one, so the first static-credential login records the port it actually used. Equivalently: hoist port persistence out of the DCR-succeeded branches so every completed flow records its port.
  2. Skip the legacy-clearing branch at internal/oauth/config.go:764-775 when serverConfig.OAuth != nil && serverConfig.OAuth.ClientID != "" — static credentials must never be cleared "for re-registration".
  3. Honor oauth.redirect_uri as an explicit pin: parse its port, pass it as preferredPort, fail loudly if the port is unavailable rather than silently falling back to a random one, and use the configured URI verbatim at internal/oauth/config.go:948. Update specs/006-oauth-extra-params/quickstart.md and the OAuth docs once it is real.

Regression test

tests/oauthserver/ already provides a full fake AS (DCR, PKCE, discovery, JWKS, device flow, plus mcpproxy_e2e_test.go) and is the right home for this — the throwaway Python provider used in this repro duplicated it. The fix should add a no-registration_endpoint + static-client_id variant there and assert the callback port is identical across two consecutive logins.

See also #1067 — a second, independent OAuth bug found on the same rig.

Activity

  1. added
    kind/bug
    area/oauth
    priority/high
    on Aug 26, 2026
  2. Dumbris commented on Aug 27, 2026

    @Dumbris
    MemberAuthor

    Fixed by #1069 (merged as c619f41). Follow-up #1070 closes several holes QA found in the redirect_uri pin that #1069 introduced: an [::1] pin bound IPv4 and silently timed out, the new fail-loudly errors reached no log, and a malformed value was an undiagnosable permanent connect failure. Neither is in a release yet — v0.61.0 was cut before both merged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/oauthkind/bugpriority/high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions