From 8e0e2e35c149a6c55f7a4ba3f64032aa22fa3023 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 26 Aug 2026 21:47:02 +0300 Subject: [PATCH] fix(oauth): keep the loopback callback port stable for static clients MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/configuration.md | 30 ++- internal/oauth/config.go | 161 ++++++++++++-- internal/oauth/redirect_uri_pin_test.go | 206 ++++++++++++++++++ internal/upstream/core/connection_oauth.go | 36 ++- .../upstream/core/oauth_callback_port_test.go | 190 ++++++++++++++++ tests/oauthserver/cmd/server/main.go | 9 +- 6 files changed, 608 insertions(+), 24 deletions(-) create mode 100644 internal/oauth/redirect_uri_pin_test.go create mode 100644 internal/upstream/core/oauth_callback_port_test.go diff --git a/docs/configuration.md b/docs/configuration.md index 8160c1e5e..855960dc2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -540,10 +540,38 @@ explicitly to one of `http`, `sse`, or `streamable-http`. |-------|------|----------|-------------| | `client_id` | string | No | OAuth client ID (uses Dynamic Client Registration if empty) | | `client_secret` | string | No | OAuth client secret (can reference secure storage) | -| `redirect_uri` | string | No | OAuth redirect URI (auto-generated if not provided) | +| `redirect_uri` | string | No | Pins the loopback callback URL (auto-allocated if not provided) | | `scopes` | array | No | OAuth scopes to request | | `pkce_enabled` | boolean | No | PKCE is always enabled for security; this flag is currently ignored | +#### Pinning the callback port with `redirect_uri` + +By default mcpproxy allocates a fresh loopback port for the OAuth callback on +every login. Some providers — notably GitHub OAuth Apps — require the callback +URL to match the registered one **exactly** and reject wildcards, so the port +must not move. + +Set `redirect_uri` to pin it. mcpproxy then binds that exact port and sends that +exact string to the provider as `redirect_uri`: + +```json +{ + "oauth": { + "client_id": "Iv1.abc123", + "redirect_uri": "http://127.0.0.1:54108/oauth/callback" + } +} +``` + +The value must be an RFC 8252 loopback redirect: `http` scheme, a loopback host +(`127.0.0.1`, `localhost` or `::1`), an explicit port, and the +`/oauth/callback` path. A malformed value, or a pinned port that is already in +use, fails the login with an explicit error in the logs rather than silently +falling back to a random port. Register the same URL with the provider. + +When `redirect_uri` is not set, mcpproxy persists the port used by the first +successful login and reuses it for subsequent logins. + See [OAuth Documentation](mcp-go-oauth.md) for complete details. --- diff --git a/internal/oauth/config.go b/internal/oauth/config.go index 6213e621f..21488e217 100644 --- a/internal/oauth/config.go +++ b/internal/oauth/config.go @@ -33,6 +33,62 @@ const ( resourceDetectRequestTimeout = 5 * time.Second // Timeout for preflight requests ) +// ParsePinnedRedirectURI validates an operator-pinned OAuth redirect URI (the +// per-server `oauth.redirect_uri` config field) and returns the loopback port it +// pins. +// +// Providers such as GitHub OAuth Apps require the callback URL to match the +// registered one exactly and reject wildcards, so operators need a way to nail +// the loopback port down instead of letting mcpproxy allocate a fresh one per +// login. The URI must therefore be an RFC 8252 loopback redirect with an +// explicit port and mcpproxy's callback path, e.g. +// +// http://127.0.0.1:54108/oauth/callback +// +// Anything else is rejected with an actionable error rather than silently +// downgraded to dynamic allocation. +func ParsePinnedRedirectURI(rawURI string) (int, error) { + trimmed := strings.TrimSpace(rawURI) + if trimmed == "" { + return 0, fmt.Errorf("oauth.redirect_uri is empty") + } + + parsed, err := url.Parse(trimmed) + if err != nil { + return 0, fmt.Errorf("oauth.redirect_uri %q is not a valid URL: %w", trimmed, err) + } + + if parsed.Scheme != "http" { + return 0, fmt.Errorf("oauth.redirect_uri %q must use the http scheme for a loopback redirect (RFC 8252), got %q", trimmed, parsed.Scheme) + } + + switch parsed.Hostname() { + case "127.0.0.1", "localhost", "::1": + default: + return 0, fmt.Errorf("oauth.redirect_uri %q must use a loopback host (127.0.0.1, localhost or ::1), got %q", trimmed, parsed.Hostname()) + } + + if parsed.Path != DefaultRedirectPath { + return 0, fmt.Errorf("oauth.redirect_uri %q must use the callback path %q, got %q", trimmed, DefaultRedirectPath, parsed.Path) + } + + if parsed.RawQuery != "" || parsed.Fragment != "" { + return 0, fmt.Errorf("oauth.redirect_uri %q must not contain a query string or fragment", trimmed) + } + + portStr := parsed.Port() + if portStr == "" { + return 0, fmt.Errorf("oauth.redirect_uri %q must include an explicit port to pin (e.g. %s:54108%s)", trimmed, DefaultRedirectURIBase, DefaultRedirectPath) + } + + port, err := strconv.Atoi(portStr) + if err != nil || port < 1 || port > 65535 { + return 0, fmt.Errorf("oauth.redirect_uri %q has an invalid port %q (expected 1-65535)", trimmed, portStr) + } + + return port, nil +} + // CallbackServerManager manages OAuth callback servers for dynamic port allocation type CallbackServerManager struct { servers map[string]*CallbackServer @@ -750,18 +806,60 @@ func createOAuthConfigInternal(serverConfig *config.ServerConfig, storage *stora zap.String("hint", "Set oauth.scopes in server config or ensure PRM/AS metadata advertises scopes_supported")) } + // A static client_id in the server config is an operator-supplied credential. + // It is never obtained from — nor refreshable by — Dynamic Client Registration, + // so the DCR "clear and re-register" recovery paths below must never wipe it. + hasStaticClientID := serverConfig.OAuth != nil && serverConfig.OAuth.ClientID != "" + + // An explicit `oauth.redirect_uri` pins the loopback callback port. Providers + // such as GitHub OAuth Apps match the callback URL exactly and reject + // wildcards, so an operator must be able to nail the port down (issue #975). + var pinnedRedirectURI string + var pinnedPort int + if serverConfig.OAuth != nil && strings.TrimSpace(serverConfig.OAuth.RedirectURI) != "" { + port, err := ParsePinnedRedirectURI(serverConfig.OAuth.RedirectURI) + if err != nil { + // Fail loudly: silently falling back to a random port would leave the + // operator believing they pinned the callback URL when they had not. + logger.Error("❌ Invalid oauth.redirect_uri in server config - refusing to fall back to a random callback port", + zap.String("server", serverConfig.Name), + zap.String("redirect_uri", serverConfig.OAuth.RedirectURI), + zap.Error(err), + zap.String("expected_format", "http://127.0.0.1:"+DefaultRedirectPath)) + return nil + } + pinnedRedirectURI = strings.TrimSpace(serverConfig.OAuth.RedirectURI) + pinnedPort = port + } + // Check for stored callback port from previous DCR (Spec 022: OAuth Redirect URI Port Persistence) var preferredPort int var serverKey string if storage != nil { serverKey = GenerateServerKey(serverConfig.Name, serverConfig.URL) + } + + switch { + case pinnedPort > 0: + preferredPort = pinnedPort + logger.Info("📌 Using operator-pinned OAuth callback port from oauth.redirect_uri", + zap.String("server", serverConfig.Name), + zap.String("redirect_uri", pinnedRedirectURI), + zap.Int("preferred_port", preferredPort)) + case storage != nil: storedClientID, _, storedPort, err := storage.GetOAuthClientCredentials(serverKey) - if err == nil && storedPort > 0 { + switch { + case err == nil && storedPort > 0: preferredPort = storedPort - logger.Info("🔄 Found stored callback port from previous DCR", + logger.Info("🔄 Found stored callback port from previous OAuth login", zap.String("server", serverConfig.Name), zap.Int("preferred_port", preferredPort)) - } else if err == nil && storedClientID != "" && storedPort == 0 { + case err == nil && storedClientID != "" && storedPort == 0 && hasStaticClientID: + // Static credentials are configured by hand; there is nothing to + // re-register, so keep the record and let this login persist its port. + logger.Debug("Static OAuth client has no stored callback port yet; keeping credentials", + zap.String("server", serverConfig.Name)) + case err == nil && storedClientID != "" && storedPort == 0: // Spec 022: Legacy DCR credentials exist but port is unknown // Clear them to force fresh registration with port tracking logger.Warn("⚠️ Legacy DCR credentials found without stored port, clearing for re-registration", @@ -793,27 +891,60 @@ func createOAuthConfigInternal(serverConfig *config.ServerConfig, storage *stora // Spec 022: Detect port conflict and clear DCR credentials if port changed // This forces fresh DCR with the new port if preferredPort > 0 && callbackServer.Port != preferredPort { - logger.Warn("⚠️ Callback port changed, clearing DCR credentials for re-registration", - zap.String("server", serverConfig.Name), - zap.Int("stored_port", preferredPort), - zap.Int("new_port", callbackServer.Port)) - if storage != nil { - if err := storage.ClearOAuthClientCredentials(serverKey); err != nil { - logger.Warn("Failed to clear DCR credentials after port change", + switch { + case pinnedPort > 0: + // The operator pinned this port; any other port produces a + // redirect_uri the provider will reject. Abort instead of pretending. + logger.Error("❌ Pinned OAuth callback port is unavailable - cannot honor oauth.redirect_uri", + zap.String("server", serverConfig.Name), + zap.String("redirect_uri", pinnedRedirectURI), + zap.Int("pinned_port", pinnedPort), + zap.Int("bound_port", callbackServer.Port), + zap.String("hint", "free the pinned port, or change oauth.redirect_uri (and the provider's callback URL) to a free one")) + if stopErr := globalCallbackManager.StopCallbackServer(serverConfig.Name); stopErr != nil { + logger.Warn("Failed to stop callback server bound to the wrong port", zap.String("server", serverConfig.Name), - zap.Error(err)) + zap.Error(stopErr)) + } + return nil + case hasStaticClientID: + // Static credentials are not re-registerable, so clearing them would + // only destroy the operator's configuration for no benefit. + logger.Warn("⚠️ Callback port changed for a statically configured OAuth client; keeping credentials", + zap.String("server", serverConfig.Name), + zap.Int("stored_port", preferredPort), + zap.Int("new_port", callbackServer.Port), + zap.String("hint", "pin the port with oauth.redirect_uri if the provider requires an exact callback URL")) + default: + logger.Warn("⚠️ Callback port changed, clearing DCR credentials for re-registration", + zap.String("server", serverConfig.Name), + zap.Int("stored_port", preferredPort), + zap.Int("new_port", callbackServer.Port)) + if storage != nil { + if err := storage.ClearOAuthClientCredentials(serverKey); err != nil { + logger.Warn("Failed to clear DCR credentials after port change", + zap.String("server", serverConfig.Name), + zap.Error(err)) + } } } } + // The pinned URI is sent to the provider verbatim so the string matches the + // one registered there (host spelling included: localhost vs 127.0.0.1). + redirectURI := callbackServer.RedirectURI + if pinnedRedirectURI != "" { + redirectURI = pinnedRedirectURI + } + logger.Info("Using exact redirect URI from allocated callback server", zap.String("server", serverConfig.Name), - zap.String("redirect_uri", callbackServer.RedirectURI), + zap.String("redirect_uri", redirectURI), zap.Int("port", callbackServer.Port)) logger.Info("OAuth callback server started successfully", zap.String("server", serverConfig.Name), - zap.String("redirect_uri", callbackServer.RedirectURI), + zap.String("redirect_uri", redirectURI), zap.Int("port", callbackServer.Port)) // Try to find a working metadata URL by validating multiple URL patterns @@ -945,7 +1076,7 @@ func createOAuthConfigInternal(serverConfig *config.ServerConfig, storage *stora oauthConfig := &client.OAuthConfig{ ClientID: clientID, ClientSecret: clientSecret, - RedirectURI: callbackServer.RedirectURI, // Exact redirect URI with allocated port + RedirectURI: redirectURI, // Exact redirect URI: operator-pinned, or the allocated port Scopes: scopes, TokenStore: tokenStore, // Shared token store for this server PKCEEnabled: true, // Always enable PKCE for security @@ -957,7 +1088,7 @@ func createOAuthConfigInternal(serverConfig *config.ServerConfig, storage *stora zap.String("server", serverConfig.Name), zap.Strings("scopes", scopes), zap.Bool("pkce_enabled", true), - zap.String("redirect_uri", callbackServer.RedirectURI), + zap.String("redirect_uri", redirectURI), zap.String("auth_server_metadata_url", authServerMetadataURL), zap.String("registration_mode", registrationMode), zap.String("discovery_mode", "explicit metadata URL"), // Using explicit metadata URL to avoid discovery timeouts diff --git a/internal/oauth/redirect_uri_pin_test.go b/internal/oauth/redirect_uri_pin_test.go new file mode 100644 index 000000000..4518c066e --- /dev/null +++ b/internal/oauth/redirect_uri_pin_test.go @@ -0,0 +1,206 @@ +package oauth + +import ( + "fmt" + "net" + "net/http" + "net/http/httptest" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// newUnreachableUpstream returns an httptest server that answers 404 to every +// request. OAuth metadata discovery degrades gracefully against it, which keeps +// these tests hermetic and fast while still exercising the real +// createOAuthConfigInternal() code path. +func newUnreachableUpstream(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNotFound) + })) + t.Cleanup(srv.Close) + return srv +} + +// reserveLoopbackPort picks a currently-free loopback port and releases it, so a +// pinned redirect_uri in the test can name a port the callback server can bind. +func reserveLoopbackPort(t *testing.T) int { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + port := ln.Addr().(*net.TCPAddr).Port + require.NoError(t, ln.Close()) + return port +} + +func stopCallbackServer(t *testing.T, serverName string) { + t.Helper() + t.Cleanup(func() { + if mgr := GetGlobalCallbackManager(); mgr != nil { + _ = mgr.StopCallbackServer(serverName) + } + }) +} + +func TestParsePinnedRedirectURI(t *testing.T) { + tests := []struct { + name string + uri string + wantPort int + wantErr string + }{ + {name: "loopback ipv4", uri: "http://127.0.0.1:54108/oauth/callback", wantPort: 54108}, + {name: "localhost", uri: "http://localhost:8123/oauth/callback", wantPort: 8123}, + {name: "ipv6 loopback", uri: "http://[::1]:8123/oauth/callback", wantPort: 8123}, + {name: "surrounding whitespace tolerated", uri: " http://127.0.0.1:54108/oauth/callback ", wantPort: 54108}, + {name: "empty", uri: "", wantErr: "empty"}, + {name: "not a url", uri: "://nope", wantErr: "not a valid URL"}, + {name: "https scheme", uri: "https://127.0.0.1:54108/oauth/callback", wantErr: "http scheme"}, + {name: "non-loopback host", uri: "http://example.com:54108/oauth/callback", wantErr: "loopback host"}, + {name: "wrong path", uri: "http://127.0.0.1:54108/callback", wantErr: "callback path"}, + {name: "no port", uri: "http://127.0.0.1/oauth/callback", wantErr: "explicit port"}, + {name: "port zero", uri: "http://127.0.0.1:0/oauth/callback", wantErr: "invalid port"}, + {name: "query string", uri: "http://127.0.0.1:54108/oauth/callback?x=1", wantErr: "query string or fragment"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + port, err := ParsePinnedRedirectURI(tt.uri) + if tt.wantErr != "" { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantPort, port) + }) + } +} + +// TestCreateOAuthConfig_HonorsPinnedRedirectURI verifies part (c) of the fix: +// a configured oauth.redirect_uri pins the loopback callback port AND is sent to +// the provider verbatim (GitHub OAuth Apps match the callback URL exactly). +func TestCreateOAuthConfig_HonorsPinnedRedirectURI(t *testing.T) { + upstream := newUnreachableUpstream(t) + store := setupTestStorage(t) + + port := reserveLoopbackPort(t) + pinned := fmt.Sprintf("http://127.0.0.1:%d/oauth/callback", port) + + serverName := "pinned-redirect-server" + stopCallbackServer(t, serverName) + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: upstream.URL + "/mcp", + OAuth: &config.OAuthConfig{ + ClientID: "static-client", + RedirectURI: pinned, + }, + } + + oauthConfig := CreateOAuthConfig(serverConfig, store) + require.NotNil(t, oauthConfig, "pinned redirect_uri should produce a usable OAuth config") + + assert.Equal(t, pinned, oauthConfig.RedirectURI, + "the configured redirect_uri must be sent to the provider verbatim") + + callbackServer, ok := GetCallbackServer(serverName) + require.True(t, ok, "callback server should be running") + assert.Equal(t, port, callbackServer.Port, + "callback server must listen on the pinned port") +} + +// TestCreateOAuthConfig_MalformedPinnedRedirectURI verifies that a malformed +// oauth.redirect_uri fails loudly instead of silently falling back to a random +// port (which the operator would never discover until the provider rejects it). +func TestCreateOAuthConfig_MalformedPinnedRedirectURI(t *testing.T) { + upstream := newUnreachableUpstream(t) + store := setupTestStorage(t) + + serverName := "malformed-redirect-server" + stopCallbackServer(t, serverName) + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: upstream.URL + "/mcp", + OAuth: &config.OAuthConfig{ + ClientID: "static-client", + RedirectURI: "https://example.com/oauth/callback", + }, + } + + oauthConfig := CreateOAuthConfig(serverConfig, store) + assert.Nil(t, oauthConfig, "malformed redirect_uri must abort OAuth config creation") + + _, ok := GetCallbackServer(serverName) + assert.False(t, ok, "no callback server should be started for a malformed pin") +} + +// TestCreateOAuthConfig_StaticClientCredentialsSurviveMissingPort verifies part +// (b) of the fix: a statically configured client is never "re-registered", so +// the legacy-DCR clearing branch must not wipe its stored record. +func TestCreateOAuthConfig_StaticClientCredentialsSurviveMissingPort(t *testing.T) { + upstream := newUnreachableUpstream(t) + store := setupTestStorage(t) + + serverName := "static-client-server" + stopCallbackServer(t, serverName) + + serverURL := upstream.URL + "/mcp" + serverKey := GenerateServerKey(serverName, serverURL) + + // Simulate the state left behind by a login that persisted the static + // client_id but no callback port. + require.NoError(t, store.UpdateOAuthClientCredentials(serverKey, "static-client", "static-secret", 0)) + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: serverURL, + OAuth: &config.OAuthConfig{ + ClientID: "static-client", + ClientSecret: "static-secret", + }, + } + + oauthConfig := CreateOAuthConfig(serverConfig, store) + require.NotNil(t, oauthConfig) + + storedClientID, storedSecret, _, err := store.GetOAuthClientCredentials(serverKey) + require.NoError(t, err) + assert.Equal(t, "static-client", storedClientID, + "static OAuth credentials must never be cleared for re-registration") + assert.Equal(t, "static-secret", storedSecret) +} + +// TestCreateOAuthConfig_LegacyDCRCredentialsStillCleared guards the original +// Spec 022 behavior for genuine DCR clients (no static client_id in config). +func TestCreateOAuthConfig_LegacyDCRCredentialsStillCleared(t *testing.T) { + upstream := newUnreachableUpstream(t) + store := setupTestStorage(t) + + serverName := "legacy-dcr-server" + stopCallbackServer(t, serverName) + + serverURL := upstream.URL + "/mcp" + serverKey := GenerateServerKey(serverName, serverURL) + + require.NoError(t, store.UpdateOAuthClientCredentials(serverKey, "dcr-client", "dcr-secret", 0)) + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: serverURL, + } + + oauthConfig := CreateOAuthConfig(serverConfig, store) + require.NotNil(t, oauthConfig) + + storedClientID, _, _, err := store.GetOAuthClientCredentials(serverKey) + require.NoError(t, err) + assert.Empty(t, storedClientID, + "legacy DCR credentials without a stored port should still be cleared") +} diff --git a/internal/upstream/core/connection_oauth.go b/internal/upstream/core/connection_oauth.go index a748021b1..f610090bf 100644 --- a/internal/upstream/core/connection_oauth.go +++ b/internal/upstream/core/connection_oauth.go @@ -14,6 +14,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/contracts" "github.com/smart-mcp-proxy/mcpproxy-go/internal/diagnostics" "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" "github.com/smart-mcp-proxy/mcpproxy-go/internal/transport" "github.com/mark3labs/mcp-go/client" @@ -1666,11 +1667,11 @@ func (c *Client) persistDCRCredentials() { serverKey := oauth.GenerateServerKey(c.config.Name, c.config.URL) - // 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 - } + // Persist the port this login actually used. Only DCR-succeeded flows used + // to record a port, so a static-client login persisted port 0 and the next + // login allocated a fresh loopback port — breaking providers that require an + // exact, unchanging callback URL (issue #975). + callbackPort := resolveCallbackPortForPersistence(c.config.Name, serverKey, c.storage) if err := c.storage.UpdateOAuthClientCredentials(serverKey, clientID, clientSecret, callbackPort); err != nil { c.logger.Error("Failed to persist DCR credentials", @@ -1682,7 +1683,30 @@ func (c *Client) persistDCRCredentials() { c.logger.Info("DCR credentials persisted for proactive token refresh", zap.String("server", c.config.Name), zap.String("client_id_prefix", clientID[:min(8, len(clientID))]+"..."), - zap.Bool("has_client_secret", clientSecret != "")) + zap.Bool("has_client_secret", clientSecret != ""), + zap.Int("callback_port", callbackPort)) +} + +// resolveCallbackPortForPersistence returns the loopback callback port to store +// alongside the OAuth client credentials for serverName. +// +// The live callback server wins: it is the port the redirect_uri of the login +// that just completed actually pointed at, so persisting it lets the next login +// bind the same port and reuse the identical redirect_uri. Only when no callback +// server is running do we fall back to whatever was stored previously, so a +// refresh-only code path never downgrades a known port to 0. +func resolveCallbackPortForPersistence(serverName, serverKey string, store *storage.BoltDB) int { + if callbackServer, exists := oauth.GetCallbackServer(serverName); exists && callbackServer.Port > 0 { + return callbackServer.Port + } + + if store == nil { + return 0 + } + if record, err := store.GetOAuthToken(serverKey); err == nil && record != nil { + return record.CallbackPort + } + return 0 } // wasOAuthRecentlyCompleted checks if OAuth was completed recently to prevent retry loops diff --git a/internal/upstream/core/oauth_callback_port_test.go b/internal/upstream/core/oauth_callback_port_test.go new file mode 100644 index 000000000..e018bad3d --- /dev/null +++ b/internal/upstream/core/oauth_callback_port_test.go @@ -0,0 +1,190 @@ +package core + +import ( + "fmt" + "net" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" + "github.com/smart-mcp-proxy/mcpproxy-go/tests/oauthserver" + + mcpclient "github.com/mark3labs/mcp-go/client" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" +) + +func newCallbackPortTestStorage(t *testing.T) *storage.BoltDB { + t.Helper() + db, err := storage.NewBoltDB(t.TempDir(), zap.NewNop().Sugar()) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + return db +} + +func stopCallbackServerAfterTest(t *testing.T, serverName string) { + t.Helper() + t.Cleanup(func() { + if mgr := oauth.GetGlobalCallbackManager(); mgr != nil { + _ = mgr.StopCallbackServer(serverName) + } + }) +} + +// TestResolveCallbackPortForPersistence_UsesLiveCallbackServer covers part (a) +// of the fix: the port we persist must be the one the callback server is +// actually listening on, not merely whatever happened to be stored already. +func TestResolveCallbackPortForPersistence_UsesLiveCallbackServer(t *testing.T) { + db := newCallbackPortTestStorage(t) + serverName := "live-callback-port" + serverKey := oauth.GenerateServerKey(serverName, "https://example.test/mcp") + + // A record exists with no port — the pre-fix code would keep persisting 0. + require.NoError(t, db.UpdateOAuthClientCredentials(serverKey, "static-client", "", 0)) + + stopCallbackServerAfterTest(t, serverName) + callbackServer, err := oauth.GetGlobalCallbackManager().StartCallbackServer(serverName, 0) + require.NoError(t, err) + require.Positive(t, callbackServer.Port) + + got := resolveCallbackPortForPersistence(serverName, serverKey, db) + assert.Equal(t, callbackServer.Port, got, + "the live callback server port must win over the stored value") +} + +// TestResolveCallbackPortForPersistence_FallsBackToStoredPort verifies we do not +// regress the original behavior when no callback server is running. +func TestResolveCallbackPortForPersistence_FallsBackToStoredPort(t *testing.T) { + db := newCallbackPortTestStorage(t) + serverName := "no-live-callback-port" + serverKey := oauth.GenerateServerKey(serverName, "https://example.test/mcp") + + require.NoError(t, db.UpdateOAuthClientCredentials(serverKey, "static-client", "", 43117)) + + got := resolveCallbackPortForPersistence(serverName, serverKey, db) + assert.Equal(t, 43117, got) +} + +// loginCycle runs one complete OAuth login for serverConfig against a real test +// OAuth provider using production code only: +// +// oauth.CreateOAuthConfig() -> allocates/binds the loopback callback server +// client.markOAuthComplete() -> persists credentials, then frees the port +// +// It returns the loopback port the callback server bound for this login and the +// redirect_uri that would have been sent to the provider. +func loginCycle(t *testing.T, serverConfig *config.ServerConfig, db *storage.BoltDB) (port int, redirectURI string) { + t.Helper() + + oauthConfig := oauth.CreateOAuthConfig(serverConfig, db) + require.NotNil(t, oauthConfig, "OAuth config creation must succeed") + + callbackServer, ok := oauth.GetCallbackServer(serverConfig.Name) + require.True(t, ok, "callback server must be running during the flow") + port = callbackServer.Port + redirectURI = oauthConfig.RedirectURI + + mcpClient, err := mcpclient.NewOAuthStreamableHttpClient(serverConfig.URL, *oauthConfig) + require.NoError(t, err) + + c := &Client{ + config: serverConfig, + storage: db, + logger: zap.NewNop(), + client: mcpClient, + } + + // This is what the real connection does when the browser callback lands: + // persist the credentials, then shut the callback server down. + c.markOAuthComplete() + + return port, redirectURI +} + +// TestOAuthCallbackPort_StableAcrossLogins_StaticClient is the regression test +// for issue #975. With a static oauth.client_id, the loopback callback port used +// to change on every login, so providers that require an exact callback URL +// (GitHub OAuth Apps reject wildcards) could never be made to work. +func TestOAuthCallbackPort_StableAcrossLogins_StaticClient(t *testing.T) { + provider := oauthserver.Start(t, oauthserver.Options{ + Clients: []oauthserver.ClientConfig{{ + ClientID: "static-client", + ClientName: "Static Client", + RedirectURIs: []string{"http://127.0.0.1/oauth/callback"}, + }}, + }) + t.Cleanup(func() { _ = provider.Shutdown() }) + + db := newCallbackPortTestStorage(t) + serverName := "static-client-port-stability" + stopCallbackServerAfterTest(t, serverName) + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: provider.MCPURL, + Protocol: "http", + OAuth: &config.OAuthConfig{ + ClientID: "static-client", + }, + } + + firstPort, firstURI := loginCycle(t, serverConfig, db) + secondPort, secondURI := loginCycle(t, serverConfig, db) + + assert.Equal(t, firstPort, secondPort, + "a statically configured OAuth client must reuse the same loopback callback port (issue #975): got %d then %d", + firstPort, secondPort) + assert.Equal(t, firstURI, secondURI, + "the redirect_uri sent to the provider must be identical across logins") + + // And the record must survive: the static client is never re-registered. + serverKey := oauth.GenerateServerKey(serverName, serverConfig.URL) + storedClientID, _, storedPort, err := db.GetOAuthClientCredentials(serverKey) + require.NoError(t, err) + assert.Equal(t, "static-client", storedClientID) + assert.Equal(t, firstPort, storedPort, "the live callback port must be persisted") +} + +// TestOAuthCallbackPort_PinnedRedirectURI_StableAcrossLogins covers part (c): +// an operator who pins oauth.redirect_uri gets exactly that port and URI, on +// every login, with no reliance on stored state at all. +func TestOAuthCallbackPort_PinnedRedirectURI_StableAcrossLogins(t *testing.T) { + provider := oauthserver.Start(t, oauthserver.Options{ + Clients: []oauthserver.ClientConfig{{ + ClientID: "pinned-client", + ClientName: "Pinned Client", + RedirectURIs: []string{"http://127.0.0.1/oauth/callback"}, + }}, + }) + t.Cleanup(func() { _ = provider.Shutdown() }) + + ln, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + pinnedPort := ln.Addr().(*net.TCPAddr).Port + require.NoError(t, ln.Close()) + pinnedURI := fmt.Sprintf("http://127.0.0.1:%d/oauth/callback", pinnedPort) + + db := newCallbackPortTestStorage(t) + serverName := "pinned-client-port-stability" + stopCallbackServerAfterTest(t, serverName) + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: provider.MCPURL, + Protocol: "http", + OAuth: &config.OAuthConfig{ + ClientID: "pinned-client", + RedirectURI: pinnedURI, + }, + } + + firstPort, firstURI := loginCycle(t, serverConfig, db) + secondPort, secondURI := loginCycle(t, serverConfig, db) + + assert.Equal(t, pinnedPort, firstPort) + assert.Equal(t, pinnedPort, secondPort) + assert.Equal(t, pinnedURI, firstURI) + assert.Equal(t, pinnedURI, secondURI) +} diff --git a/tests/oauthserver/cmd/server/main.go b/tests/oauthserver/cmd/server/main.go index 7a9d1feb1..fa9ed82b0 100644 --- a/tests/oauthserver/cmd/server/main.go +++ b/tests/oauthserver/cmd/server/main.go @@ -126,12 +126,17 @@ func main() { // Pre-register test-client for Playwright tests Clients: []oauthserver.ClientConfig{ { - ClientID: "test-client", - ClientName: "Test Client", + ClientID: "test-client", + ClientName: "Test Client", RedirectURIs: []string{ "http://127.0.0.1/callback", "http://localhost/callback", "http://127.0.0.1:9000/callback", // Allow callback on same port as OAuth server + // mcpproxy's own loopback callback path (internal/oauth + // DefaultRedirectPath) — needed to drive a real login + // against this server. + "http://127.0.0.1/oauth/callback", + "http://localhost/oauth/callback", }, }, },