From 9bd531bf15a1c818880ced7ea9d3ba644b27cc99 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Wed, 26 Aug 2026 21:44:35 +0300 Subject: [PATCH] fix(oauth): dispatch callbacks by state and stop faking success MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- internal/oauth/callback_dispatch_test.go | 353 ++++++++++++++++++ internal/oauth/config.go | 269 ++++++++++--- internal/oauth/config_test.go | 98 +---- internal/oauth/manual_flow.go | 79 ++++ internal/oauth/manual_flow_test.go | 63 ++++ internal/upstream/core/connection_oauth.go | 156 ++++++-- .../upstream/core/oauth_callback_wait_test.go | 122 ++++++ internal/upstream/manager.go | 40 ++ .../upstream/manager_oauth_failure_test.go | 84 +++++ 9 files changed, 1095 insertions(+), 169 deletions(-) create mode 100644 internal/oauth/callback_dispatch_test.go create mode 100644 internal/oauth/manual_flow.go create mode 100644 internal/oauth/manual_flow_test.go create mode 100644 internal/upstream/core/oauth_callback_wait_test.go create mode 100644 internal/upstream/manager_oauth_failure_test.go diff --git a/internal/oauth/callback_dispatch_test.go b/internal/oauth/callback_dispatch_test.go new file mode 100644 index 000000000..f7a4212c2 --- /dev/null +++ b/internal/oauth/callback_dispatch_test.go @@ -0,0 +1,353 @@ +package oauth + +import ( + "crypto/sha256" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/smart-mcp-proxy/mcpproxy-go/tests/oauthserver" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// ============================================================================= +// Issue #975: OAuth callback params must be dispatched to the flow that minted +// the `state`, and a callback nobody is waiting for must NOT render the +// "Authorization Successful" page. +// ============================================================================= + +const ( + testCallbackUser = "testuser" + testCallbackPass = "testpass" +) + +// startTestProvider boots the shared OAuth 2.1 test provider (tests/oauthserver) +// with a public client whose redirect URI is this callback server's. +func startTestProvider(t *testing.T, redirectURI, clientID string) *oauthserver.ServerResult { + t.Helper() + provider := oauthserver.Start(t, oauthserver.Options{ + Clients: []oauthserver.ClientConfig{{ + ClientID: clientID, + RedirectURIs: []string{redirectURI}, + GrantTypes: []string{"authorization_code", "refresh_token"}, + ResponseTypes: []string{"code"}, + Scopes: []string{"read"}, + ClientName: "callback-dispatch-test", + }}, + }) + t.Cleanup(func() { _ = provider.Shutdown() }) + return provider +} + +func pkcePair(verifier string) (codeVerifier, codeChallenge string) { + sum := sha256.Sum256([]byte(verifier)) + return verifier, base64.RawURLEncoding.EncodeToString(sum[:]) +} + +// approveAuthorization drives the provider's login/consent form for the given +// state and follows the redirect all the way into mcpproxy's callback server, +// exactly as a browser would. Returns the final page the user sees. +func approveAuthorization(t *testing.T, provider *oauthserver.ServerResult, clientID, redirectURI, state, codeChallenge string) (status int, body string) { + t.Helper() + + form := url.Values{ + "client_id": {clientID}, + "redirect_uri": {redirectURI}, + "response_type": {"code"}, + "scope": {"read"}, + "state": {state}, + "code_challenge": {codeChallenge}, + "code_challenge_method": {"S256"}, + "username": {testCallbackUser}, + "password": {testCallbackPass}, + "consent": {"on"}, + "action": {"approve"}, + } + + httpClient := &http.Client{Timeout: 10 * time.Second} + resp, err := httpClient.PostForm(provider.AuthorizationEndpoint, form) + require.NoError(t, err, "authorization POST should reach the provider") + defer resp.Body.Close() + + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + return resp.StatusCode, string(raw) +} + +// exchangeCode performs the /token request the way a real flow would, proving +// the delivered code is redeemable (the reported bug was that no /token request +// ever happened). +func exchangeCode(t *testing.T, provider *oauthserver.ServerResult, clientID, redirectURI, code, verifier string) map[string]interface{} { + t.Helper() + + form := url.Values{ + "grant_type": {"authorization_code"}, + "code": {code}, + "redirect_uri": {redirectURI}, + "client_id": {clientID}, + "code_verifier": {verifier}, + } + httpClient := &http.Client{Timeout: 10 * time.Second} + resp, err := httpClient.PostForm(provider.TokenEndpoint, form) + require.NoError(t, err) + defer resp.Body.Close() + + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equal(t, http.StatusOK, resp.StatusCode, "token exchange failed: %s", string(raw)) + + var payload map[string]interface{} + require.NoError(t, json.Unmarshal(raw, &payload)) + return payload +} + +func recvParams(ch <-chan map[string]string, wait time.Duration) (map[string]string, bool) { + select { + case params := <-ch: + return params, true + case <-time.After(wait): + return nil, false + } +} + +// TestCallbackDispatch_TwoConcurrentFlows is the decisive regression test for +// issue #975: a manual login mints state A, a background reconnect later mints +// state B on the SAME callback server, and the provider redirects with state A. +// The code must reach flow A. Before the fix a single shared channel handed the +// params to whichever receiver the runtime picked, and flow B discarded them. +func TestCallbackDispatch_TwoConcurrentFlows(t *testing.T) { + manager := GetGlobalCallbackManager() + serverName := "test-two-concurrent-flows" + + callbackServer, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + clientID := "two-flows-client" + provider := startTestProvider(t, callbackServer.RedirectURI, clientID) + + // Repeat the race several times, alternating which flow registers first. + // Dispatch by state must win every single round; the pre-fix shared channel + // handed the params to whichever receiver the runtime happened to pick. + const rounds = 5 + for round := 0; round < rounds; round++ { + stateA := fmt.Sprintf("state-manual-login-A-%d", round) + stateB := fmt.Sprintf("state-background-reconnect-B-%d", round) + verifierA, challengeA := pkcePair(fmt.Sprintf("verifier-for-manual-login-flow-round-%d-aaaaaaaaaa", round)) + + var chA, chB <-chan map[string]string + if round%2 == 0 { + // Flow A (the user's manual login) parks first, the background + // reconnect joins a moment later. + chA = callbackServer.RegisterState(stateA) + chB = callbackServer.RegisterState(stateB) + } else { + // ...and the other way round. + chB = callbackServer.RegisterState(stateB) + chA = callbackServer.RegisterState(stateA) + } + + status, page := approveAuthorization(t, provider, clientID, callbackServer.RedirectURI, stateA, challengeA) + assert.Equal(t, http.StatusOK, status, "round %d: callback page should be served with 200 on success", round) + assert.Contains(t, page, "Authorization Successful", "round %d: the user completed a real authorization", round) + + paramsA, gotA := recvParams(chA, 3*time.Second) + require.True(t, gotA, "round %d: the flow that minted state A must receive the callback params", round) + assert.Equal(t, stateA, paramsA["state"], "round %d", round) + require.NotEmpty(t, paramsA["code"], "round %d: flow A must receive the authorization code", round) + + _, gotB := recvParams(chB, 200*time.Millisecond) + assert.False(t, gotB, "round %d: the background reconnect (state B) must NOT consume flow A's callback", round) + assert.True(t, callbackServer.HasState(stateB), + "round %d: the background reconnect's waiter must still be registered", round) + + // The code flow A received is redeemable: a /token request actually happens. + token := exchangeCode(t, provider, clientID, callbackServer.RedirectURI, paramsA["code"], verifierA) + assert.NotEmpty(t, token["access_token"], "round %d: flow A's code must exchange for a token", round) + + callbackServer.UnregisterState(stateA) + callbackServer.UnregisterState(stateB) + } + + assert.Len(t, provider.Server.GetIssuedTokens(), rounds, + "the provider must have received one /token request per completed flow") +} + +// TestCallbackDispatch_UnknownStateShowsFailurePage verifies (b): a callback +// whose state nobody registered gets an explicit failure page — never +// "Authorization Successful" — and does not steal a live flow's slot. +func TestCallbackDispatch_UnknownStateShowsFailurePage(t *testing.T) { + manager := GetGlobalCallbackManager() + serverName := "test-unknown-state" + + callbackServer, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + liveState := "state-live-flow" + chLive := callbackServer.RegisterState(liveState) + t.Cleanup(func() { callbackServer.UnregisterState(liveState) }) + + httpClient := &http.Client{Timeout: 5 * time.Second} + resp, err := httpClient.Get(callbackServer.RedirectURI + "?code=orphan-code&state=nobody-is-waiting-for-this") + require.NoError(t, err) + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + page := string(raw) + + assert.NotContains(t, page, "Authorization Successful", + "an orphaned code must never be reported as a successful sign-in") + assert.Contains(t, page, "Authorization Failed", "the browser must show an explicit failure") + assert.Equal(t, http.StatusBadRequest, resp.StatusCode, "unknown state is a client error") + + _, gotLive := recvParams(chLive, 300*time.Millisecond) + assert.False(t, gotLive, "an unknown state must not consume another flow's params") + + // The live flow still works afterwards. + clientID := "unknown-state-client" + provider := startTestProvider(t, callbackServer.RedirectURI, clientID) + _, challenge := pkcePair("verifier-for-the-still-live-flow-bbbbbbbbbbbbbbbb") + status, successPage := approveAuthorization(t, provider, clientID, callbackServer.RedirectURI, liveState, challenge) + assert.Equal(t, http.StatusOK, status) + assert.Contains(t, successPage, "Authorization Successful") + + params, got := recvParams(chLive, 3*time.Second) + require.True(t, got, "the live flow must still receive its own callback") + assert.Equal(t, liveState, params["state"]) +} + +// TestCallbackDispatch_ProviderErrorShowsFailurePage verifies that a provider +// error (access_denied) is reported as a failure in the browser even though a +// flow is waiting for that state, and that the waiting flow still sees it. +func TestCallbackDispatch_ProviderErrorShowsFailurePage(t *testing.T) { + manager := GetGlobalCallbackManager() + serverName := "test-provider-error" + + callbackServer, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + state := "state-denied-flow" + ch := callbackServer.RegisterState(state) + t.Cleanup(func() { callbackServer.UnregisterState(state) }) + + httpClient := &http.Client{Timeout: 5 * time.Second} + resp, err := httpClient.Get(fmt.Sprintf("%s?error=access_denied&error_description=User+denied&state=%s", + callbackServer.RedirectURI, url.QueryEscape(state))) + require.NoError(t, err) + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + page := string(raw) + + assert.NotContains(t, page, "Authorization Successful") + assert.Contains(t, page, "Authorization Failed") + assert.True(t, strings.Contains(page, "access_denied"), "the provider error should be shown to the user") + + params, got := recvParams(ch, 3*time.Second) + require.True(t, got, "the waiting flow must still be told the provider denied the request") + assert.Equal(t, "access_denied", params["error"]) +} + +// TestCallbackDispatch_UnregisteredStateIsRejected verifies that a completed or +// cancelled flow's state cannot be reused: after UnregisterState the callback +// server treats it as unknown. +func TestCallbackDispatch_UnregisteredStateIsRejected(t *testing.T) { + manager := GetGlobalCallbackManager() + serverName := "test-unregistered-state" + + callbackServer, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + state := "state-finished-flow" + callbackServer.RegisterState(state) + callbackServer.UnregisterState(state) + + httpClient := &http.Client{Timeout: 5 * time.Second} + resp, err := httpClient.Get(fmt.Sprintf("%s?code=late-code&state=%s", callbackServer.RedirectURI, url.QueryEscape(state))) + require.NoError(t, err) + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + + assert.Equal(t, http.StatusBadRequest, resp.StatusCode) + assert.Contains(t, string(raw), "Authorization Failed") +} + +// TestCallbackDispatch_ReuseKeepsWaiters replaces the old "drain stale params" +// behaviour: reusing a callback server for a retry must not cancel or drain a +// waiter that is already parked on it (root cause #3 in the report). +func TestCallbackDispatch_ReuseKeepsWaiters(t *testing.T) { + manager := GetGlobalCallbackManager() + serverName := "test-reuse-keeps-waiters" + + first, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + state := "state-parked-before-reuse" + ch := first.RegisterState(state) + t.Cleanup(func() { first.UnregisterState(state) }) + + second, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + assert.Same(t, first, second, "callback server should be reused") + + httpClient := &http.Client{Timeout: 5 * time.Second} + resp, err := httpClient.Get(fmt.Sprintf("%s?code=kept-code&state=%s", second.RedirectURI, url.QueryEscape(state))) + require.NoError(t, err) + defer resp.Body.Close() + _, _ = io.ReadAll(resp.Body) + + params, got := recvParams(ch, 3*time.Second) + require.True(t, got, "a waiter parked before the reuse must still receive its callback") + assert.Equal(t, "kept-code", params["code"]) +} + +// TestCallbackDispatch_RecordsFailureForUndeliverableCallback verifies (d): an +// undeliverable callback is reported through the OAuth failure hook so the +// operator sees it on the server's status instead of only in the log. +func TestCallbackDispatch_RecordsFailureForUndeliverableCallback(t *testing.T) { + manager := GetGlobalCallbackManager() + serverName := "test-failure-hook" + + callbackServer, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + type failure struct { + server string + err error + } + failures := make(chan failure, 4) + tm := GetTokenStoreManager() + tm.SetOAuthFailureCallback(func(server string, err error) { + failures <- failure{server: server, err: err} + }) + t.Cleanup(func() { tm.SetOAuthFailureCallback(nil) }) + + httpClient := &http.Client{Timeout: 5 * time.Second} + resp, err := httpClient.Get(callbackServer.RedirectURI + "?code=orphan&state=unknown-state-xyz") + require.NoError(t, err) + defer resp.Body.Close() + _, _ = io.ReadAll(resp.Body) + + select { + case f := <-failures: + assert.Equal(t, serverName, f.server) + require.Error(t, f.err) + assert.Contains(t, strings.ToLower(f.err.Error()), "state") + case <-time.After(3 * time.Second): + t.Fatal("undeliverable OAuth callback did not surface through the failure hook") + } +} diff --git a/internal/oauth/config.go b/internal/oauth/config.go index 6213e621f..291041abd 100644 --- a/internal/oauth/config.go +++ b/internal/oauth/config.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "html" "io" "net" "net/http" @@ -40,13 +41,22 @@ type CallbackServerManager struct { logger *zap.Logger } -// CallbackServer represents an active OAuth callback server +// CallbackServer represents an active OAuth callback server. +// +// Callback parameters are dispatched by the `state` parameter (issue #975): +// every flow registers the state it minted before opening the browser and gets +// its own single-use channel. A callback whose state nobody registered is +// rejected with an explicit failure page instead of being handed to whichever +// flow happened to be listening. type CallbackServer struct { - Port int - RedirectURI string - Server *http.Server - CallbackChan chan map[string]string - logger *zap.Logger + Port int + RedirectURI string + Server *http.Server + ServerName string + logger *zap.Logger + + waitersMu sync.Mutex + waiters map[string]chan map[string]string } var globalCallbackManager = &CallbackServerManager{ @@ -61,6 +71,7 @@ type TokenStoreManager struct { mu sync.RWMutex logger *zap.Logger oauthCompletionCallback func(serverName string) // Callback when OAuth completes + oauthFailureCallback func(serverName string, err error) // Callback when an unattended OAuth flow fails tokenSavedCallback func(serverName string, expiresAt time.Time) // Callback when token is saved } @@ -181,6 +192,37 @@ func (m *TokenStoreManager) SetOAuthCompletionCallback(callback func(serverName m.oauthCompletionCallback = callback } +// SetOAuthFailureCallback sets a callback invoked when an OAuth flow fails in a +// place that has no caller to return the error to — a callback that could not +// be delivered, a state mismatch, or a background token exchange that failed. +// The upstream manager wires this to the server's connection status so the +// failure is visible to the operator rather than only in the log (issue #975). +// Pass nil to clear it. +func (m *TokenStoreManager) SetOAuthFailureCallback(callback func(serverName string, err error)) { + m.mu.Lock() + defer m.mu.Unlock() + m.oauthFailureCallback = callback +} + +// RecordOAuthFailure reports an OAuth failure that nobody is waiting on. +func (m *TokenStoreManager) RecordOAuthFailure(serverName string, err error) { + if err == nil { + return + } + + m.mu.RLock() + callback := m.oauthFailureCallback + m.mu.RUnlock() + + m.logger.Warn("OAuth failure recorded", + zap.String("server", serverName), + zap.Error(err)) + + if callback != nil { + callback(serverName, err) + } +} + // SetTokenSavedCallback sets a callback function to be called when a token is saved. // Used by RefreshManager to reschedule proactive refresh when tokens are updated. func (m *TokenStoreManager) SetTokenSavedCallback(callback func(serverName string, expiresAt time.Time)) { @@ -975,16 +1017,9 @@ func (m *CallbackServerManager) StartCallbackServer(serverName string, preferred // Check if we already have a server for this name if existing, exists := m.servers[serverName]; exists { - // Drain any stale callback parameters from previous OAuth attempts - // This prevents state mismatch errors when OAuth fails/times out and is retried - select { - case staleParams := <-existing.CallbackChan: - m.logger.Warn("Drained stale OAuth callback params from previous attempt (prevents state mismatch)", - zap.String("server", serverName), - zap.String("stale_state", staleParams["state"])) - default: - // Channel is empty, nothing to drain - } + // No draining here (issue #975): params are dispatched per `state`, so a + // stale callback can no longer be mistaken for this attempt's, and a + // waiter already parked on this server must survive the reuse. m.logger.Debug("Reusing existing callback server", zap.String("server", serverName), zap.Int("port", existing.Port)) @@ -1023,9 +1058,6 @@ func (m *CallbackServerManager) StartCallbackServer(serverName string, preferred port := addr.Port redirectURI := fmt.Sprintf("%s:%d%s", DefaultRedirectURIBase, port, DefaultRedirectPath) - // Create callback channel - callbackChan := make(chan map[string]string, 1) - // Create HTTP server with dedicated mux mux := http.NewServeMux() server := &http.Server{ @@ -1038,11 +1070,12 @@ func (m *CallbackServerManager) StartCallbackServer(serverName string, preferred // Create callback server instance callbackServer := &CallbackServer{ - Port: port, - RedirectURI: redirectURI, - Server: server, - CallbackChan: callbackChan, - logger: m.logger.With(zap.String("server", serverName), zap.Int("port", port)), + Port: port, + RedirectURI: redirectURI, + Server: server, + ServerName: serverName, + logger: m.logger.With(zap.String("server", serverName), zap.Int("port", port)), + waiters: make(map[string]chan map[string]string), } // Set up HTTP handler for OAuth callback @@ -1101,6 +1134,113 @@ func (m *CallbackServerManager) StartCallbackServer(serverName string, preferred return callbackServer, nil } +// RegisterState registers the OAuth `state` a flow just minted and returns the +// channel its callback parameters will be delivered on. Call it BEFORE opening +// the browser so a fast user cannot beat the registration, and pair it with +// UnregisterState so a finished or cancelled flow's state cannot be reused. +// +// Registering the same state twice returns the same channel, which lets the +// flow that mints the state register early and the goroutine that waits for it +// obtain the same channel later without a second buffer. +func (c *CallbackServer) RegisterState(state string) <-chan map[string]string { + c.waitersMu.Lock() + defer c.waitersMu.Unlock() + + if ch, exists := c.waiters[state]; exists { + return ch + } + + ch := make(chan map[string]string, 1) + c.waiters[state] = ch + c.logger.Debug("Registered OAuth callback waiter", zap.String("state", state)) + return ch +} + +// UnregisterState drops the waiter for a state. Safe to call more than once and +// safe to call after delivery (delivery already removes the waiter). +func (c *CallbackServer) UnregisterState(state string) { + c.waitersMu.Lock() + defer c.waitersMu.Unlock() + + if _, exists := c.waiters[state]; exists { + delete(c.waiters, state) + c.logger.Debug("Unregistered OAuth callback waiter", zap.String("state", state)) + } +} + +// HasState reports whether a flow is currently waiting for this state. +func (c *CallbackServer) HasState(state string) bool { + c.waitersMu.Lock() + defer c.waitersMu.Unlock() + _, exists := c.waiters[state] + return exists +} + +// deliver hands the callback params to the flow that registered this state. +// The waiter is single-use: it is removed on delivery so a replayed callback +// cannot be delivered twice. Returns false when no flow is waiting. +func (c *CallbackServer) deliver(state string, params map[string]string) bool { + c.waitersMu.Lock() + ch, exists := c.waiters[state] + if exists { + delete(c.waiters, state) + } + waiterCount := len(c.waiters) + c.waitersMu.Unlock() + + if !exists { + c.logger.Warn("OAuth callback carries a state no flow is waiting for", + zap.String("state", state), + zap.Int("other_waiters", waiterCount)) + return false + } + + select { + case ch <- params: + return true + default: + // Cannot happen: the channel is buffered and single-use. + c.logger.Error("OAuth callback waiter channel unexpectedly full", + zap.String("state", state)) + return false + } +} + +// dropAllWaiters removes every registered waiter. Waiters unblock through their +// own context deadline; the channels are deliberately left unclosed so a parked +// flow never observes a zero-value callback as if it were a real one. +func (c *CallbackServer) dropAllWaiters() int { + c.waitersMu.Lock() + defer c.waitersMu.Unlock() + + dropped := len(c.waiters) + c.waiters = make(map[string]chan map[string]string) + return dropped +} + +// callbackPage renders the page the user's browser lands on. Success is only +// ever reported when the authorization code was actually delivered to the flow +// that asked for it (issue #975). +func callbackPage(title, message string) string { + closeScript := "" + if title == "Authorization Successful" { + closeScript = ` + ` + } + return fmt.Sprintf(` + + +

%s

+

%s

%s + + + `, html.EscapeString(title), html.EscapeString(message), closeScript) +} + // handleCallback handles OAuth callback requests func (c *CallbackServer) handleCallback(w http.ResponseWriter, r *http.Request) { c.logger.Info("🎯 OAuth callback received", @@ -1126,32 +1266,57 @@ func (c *CallbackServer) handleCallback(w http.ResponseWriter, r *http.Request) zap.String("error_description", params["error_description"]), zap.Int("total_params", len(params))) - // Send parameters to the channel (non-blocking) - select { - case c.CallbackChan <- params: - c.logger.Info("✅ OAuth callback parameters sent to channel successfully", - zap.Any("params", params)) - default: - c.logger.Error("❌ OAuth callback channel full, dropping parameters - THIS IS BAD!", - zap.Any("params", params)) + state := params["state"] + + // Route the params to the flow that minted this state. A callback nobody is + // waiting for is NOT delivered to some other flow and NOT reported to the + // user as a success (issue #975). + if !c.deliver(state, params) { + reason := fmt.Errorf("OAuth callback for server %q could not be delivered: state %q is unknown or expired "+ + "(the sign-in may have timed out, or it was started by a different mcpproxy session)", c.ServerName, state) + if state == "" { + reason = fmt.Errorf("OAuth callback for server %q carried no state parameter and was rejected", c.ServerName) + } + c.logger.Error("❌ OAuth callback dropped - no flow is waiting for this state", + zap.String("state", state), + zap.String("error", params["error"])) + + // Surface it to the operator instead of burying it in the log (issue #975). + GetTokenStoreManager().RecordOAuthFailure(c.ServerName, reason) + + c.writePage(w, http.StatusBadRequest, callbackPage( + "Authorization Failed", + fmt.Sprintf("mcpproxy is not waiting for this sign-in (unknown or expired state). "+ + "Nothing was signed in. Start the login again from mcpproxy for '%s'.", c.ServerName))) + return + } + + c.logger.Info("✅ OAuth callback parameters delivered to the waiting flow", + zap.String("state", state)) + + // The provider itself reported a failure: the flow was told, but the user + // must not see a success page. + if providerErr := params["error"]; providerErr != "" { + message := providerErr + if desc := params["error_description"]; desc != "" { + message = providerErr + ": " + desc + } + c.writePage(w, http.StatusBadRequest, callbackPage( + "Authorization Failed", + fmt.Sprintf("The authorization server rejected the request (%s). You can close this window and try again.", message))) + return } - // Respond to the user + c.writePage(w, http.StatusOK, callbackPage( + "Authorization Successful", + "You can now close this window and return to the application.")) +} + +// writePage writes an HTML response for the callback browser window. +func (c *CallbackServer) writePage(w http.ResponseWriter, status int, page string) { w.Header().Set("Content-Type", "text/html") - successPage := ` - - -

Authorization Successful

-

You can now close this window and return to the application.

- - - - ` - if _, err := w.Write([]byte(successPage)); err != nil { + w.WriteHeader(status) + if _, err := w.Write([]byte(page)); err != nil { c.logger.Error("Error writing OAuth callback response", zap.Error(err)) } } @@ -1190,8 +1355,14 @@ func (m *CallbackServerManager) StopCallbackServer(serverName string) error { zap.Error(err)) } - // Close the callback channel - close(server.CallbackChan) + // Drop any registered waiters. They unblock on their own context deadline; + // the channels are left unclosed so a parked flow never mistakes a + // zero-value receive for a real callback. + if dropped := server.dropAllWaiters(); dropped > 0 { + m.logger.Warn("Stopped OAuth callback server while flows were still waiting", + zap.String("server", serverName), + zap.Int("waiters", dropped)) + } // Remove from map delete(m.servers, serverName) diff --git a/internal/oauth/config_test.go b/internal/oauth/config_test.go index 4a358758a..30c109c36 100644 --- a/internal/oauth/config_test.go +++ b/internal/oauth/config_test.go @@ -588,99 +588,11 @@ func TestStartCallbackServerDynamicPort(t *testing.T) { assert.Contains(t, callbackServer.RedirectURI, "http://127.0.0.1:", "Redirect URI should have localhost base") } -// TestStartCallbackServerDrainsStaleParams verifies that when a callback server -// is reused, any stale params from a previous failed OAuth attempt are drained -// from the channel. This prevents state mismatch errors on OAuth retries. -// See: https://github.com/smart-mcp-proxy/mcpproxy-go/pull/281 -func TestStartCallbackServerDrainsStaleParams(t *testing.T) { - manager := GetGlobalCallbackManager() - - serverName := "test-drain-stale-params" - - // Start callback server first time - callbackServer1, err := manager.StartCallbackServer(serverName, 0) - require.NoError(t, err) - t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) - - originalPort := callbackServer1.Port - - // Simulate a failed OAuth attempt by sending stale params to the channel - // This is what happens when OAuth times out after the HTTP callback arrives - staleParams := map[string]string{ - "code": "stale_auth_code", - "state": "stale_state_abc123", - } - select { - case callbackServer1.CallbackChan <- staleParams: - // Stale params buffered in channel - default: - t.Fatal("Failed to send stale params to channel") - } - - // Verify stale params are in the channel - assert.Len(t, callbackServer1.CallbackChan, 1, "Channel should have stale params") - - // Now simulate a retry - call StartCallbackServer again for the same server - // This should reuse the existing server AND drain the stale params - callbackServer2, err := manager.StartCallbackServer(serverName, 0) - require.NoError(t, err) - - // Verify we got the same server (reused) - assert.Equal(t, originalPort, callbackServer2.Port, "Should reuse same callback server") - assert.Same(t, callbackServer1, callbackServer2, "Should return same server instance") - - // Verify channel is now empty (stale params were drained) - select { - case params := <-callbackServer2.CallbackChan: - t.Fatalf("Channel should be empty after draining, but got: %v", params) - default: - // Channel is empty - this is the expected behavior - } -} - -// TestStartCallbackServerDrainsStaleParams_EmptyChannel verifies that draining -// works correctly when the channel is already empty (no stale params). -func TestStartCallbackServerDrainsStaleParams_EmptyChannel(t *testing.T) { - manager := GetGlobalCallbackManager() - - serverName := "test-drain-empty-channel" - - // Start callback server first time - callbackServer1, err := manager.StartCallbackServer(serverName, 0) - require.NoError(t, err) - t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) - - // Don't send any params - channel is empty - - // Call StartCallbackServer again - should work fine with empty channel - callbackServer2, err := manager.StartCallbackServer(serverName, 0) - require.NoError(t, err) - - // Verify we got the same server - assert.Same(t, callbackServer1, callbackServer2, "Should return same server instance") - - // Verify channel is still empty and usable - select { - case <-callbackServer2.CallbackChan: - t.Fatal("Channel should be empty") - default: - // Expected - channel is empty - } - - // Verify we can still send to the channel (it's functional) - newParams := map[string]string{"code": "new_code", "state": "new_state"} - select { - case callbackServer2.CallbackChan <- newParams: - // Success - default: - t.Fatal("Should be able to send to channel") - } - - // Verify we can receive - received := <-callbackServer2.CallbackChan - assert.Equal(t, "new_code", received["code"]) - assert.Equal(t, "new_state", received["state"]) -} +// NOTE: the former TestStartCallbackServerDrainsStaleParams* tests covered the +// single shared callback channel and its stale-param draining. Both are gone: +// callback params are now dispatched per OAuth `state` (issue #975), so a stale +// callback can no longer be mistaken for the current attempt and a waiter parked +// on a reused server must survive. See callback_dispatch_test.go. // ============================================================================= // Tests for Rate Limit Handling in Resource Auto-Detection diff --git a/internal/oauth/manual_flow.go b/internal/oauth/manual_flow.go new file mode 100644 index 000000000..1580c2780 --- /dev/null +++ b/internal/oauth/manual_flow.go @@ -0,0 +1,79 @@ +package oauth + +import ( + "sync" + "time" +) + +// Issue #975: a manual sign-in and a background reconnect used to race each +// other on the same callback server. Dispatching callbacks by `state` fixes the +// correctness half of that (the code always reaches the flow that minted the +// state); this registry fixes the noise half by letting the automatic OAuth +// path stand down while the user is still completing a manual login. +// +// It is deliberately a plain in-memory flag with an expiry, checked and never +// waited on: no lock is held across an OAuth call, so it cannot deadlock the +// reconnect path. A missed release expires on its own rather than suppressing +// reconnects forever. + +// manualFlowWindow is the default lifetime of a manual-flow claim. It matches +// the manager's 30-minute manual OAuth context. +const manualFlowWindow = 30 * time.Minute + +type manualFlowRegistry struct { + mu sync.Mutex + // active maps server name -> claim. Only the newest claim can clear it. + active map[string]*manualFlowClaim +} + +type manualFlowClaim struct { + expiresAt time.Time +} + +var globalManualFlows = &manualFlowRegistry{ + active: make(map[string]*manualFlowClaim), +} + +// BeginManualFlow records that a user-initiated OAuth sign-in is in flight for +// serverName and returns a release function. Pass window <= 0 to use the +// default. The returned release only clears the claim it created, so a +// superseded flow releasing late cannot unsuppress a newer one. +func BeginManualFlow(serverName string, window time.Duration) (release func()) { + if window <= 0 { + window = manualFlowWindow + } + + claim := &manualFlowClaim{expiresAt: time.Now().Add(window)} + + globalManualFlows.mu.Lock() + globalManualFlows.active[serverName] = claim + globalManualFlows.mu.Unlock() + + var once sync.Once + return func() { + once.Do(func() { + globalManualFlows.mu.Lock() + defer globalManualFlows.mu.Unlock() + if current, exists := globalManualFlows.active[serverName]; exists && current == claim { + delete(globalManualFlows.active, serverName) + } + }) + } +} + +// IsManualFlowActive reports whether a user-initiated OAuth sign-in is currently +// in flight for serverName. Expired claims are dropped on read. +func IsManualFlowActive(serverName string) bool { + globalManualFlows.mu.Lock() + defer globalManualFlows.mu.Unlock() + + claim, exists := globalManualFlows.active[serverName] + if !exists { + return false + } + if time.Now().After(claim.expiresAt) { + delete(globalManualFlows.active, serverName) + return false + } + return true +} diff --git a/internal/oauth/manual_flow_test.go b/internal/oauth/manual_flow_test.go new file mode 100644 index 000000000..4e61f3039 --- /dev/null +++ b/internal/oauth/manual_flow_test.go @@ -0,0 +1,63 @@ +package oauth + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +// Issue #975: while the user is completing a manual sign-in, a background +// reconnect must not start a competing OAuth flow for the same server. + +func TestManualFlow_ActiveUntilReleased(t *testing.T) { + server := "manual-flow-release" + + assert.False(t, IsManualFlowActive(server), "no manual flow should be active initially") + + release := BeginManualFlow(server, time.Minute) + assert.True(t, IsManualFlowActive(server), "manual flow must be active after Begin") + + release() + assert.False(t, IsManualFlowActive(server), "manual flow must be cleared after release") + + // Releasing twice is safe. + release() + assert.False(t, IsManualFlowActive(server)) +} + +func TestManualFlow_ExpiresWithoutRelease(t *testing.T) { + server := "manual-flow-expiry" + + release := BeginManualFlow(server, 50*time.Millisecond) + t.Cleanup(release) + assert.True(t, IsManualFlowActive(server)) + + assert.Eventually(t, func() bool { return !IsManualFlowActive(server) }, + 2*time.Second, 10*time.Millisecond, + "a manual flow whose release is missed must expire instead of suppressing reconnects forever") +} + +func TestManualFlow_IsPerServer(t *testing.T) { + release := BeginManualFlow("manual-flow-server-a", time.Minute) + t.Cleanup(release) + + assert.True(t, IsManualFlowActive("manual-flow-server-a")) + assert.False(t, IsManualFlowActive("manual-flow-server-b"), + "a manual sign-in must only suppress reconnects for its own server") +} + +func TestManualFlow_LaterReleaseDoesNotClearNewerFlow(t *testing.T) { + server := "manual-flow-restart" + + firstRelease := BeginManualFlow(server, time.Minute) + secondRelease := BeginManualFlow(server, time.Minute) + + // The user restarted the login; releasing the first (superseded) flow must + // not unsuppress reconnects while the second is still running. + firstRelease() + assert.True(t, IsManualFlowActive(server), "the newer manual flow must stay active") + + secondRelease() + assert.False(t, IsManualFlowActive(server)) +} diff --git a/internal/upstream/core/connection_oauth.go b/internal/upstream/core/connection_oauth.go index a748021b1..2a89d9103 100644 --- a/internal/upstream/core/connection_oauth.go +++ b/internal/upstream/core/connection_oauth.go @@ -912,6 +912,17 @@ func (c *Client) isOAuthError(err error) bool { // handleOAuthAuthorization handles the manual OAuth flow. func (c *Client) handleOAuthAuthorization(ctx context.Context, authErr error, oauthConfig *client.OAuthConfig, extraParams map[string]string) error { + // Stand down while the user is completing a manual sign-in for this server + // (issue #975). A background reconnect that starts its own flow here opens a + // second browser tab and mints a second state; the callback is still routed + // correctly, but the competing flow is pure noise. Checking a flag is + // non-blocking, so the reconnect path cannot deadlock on it. + if !c.isManualOAuthFlow(ctx) && oauth.IsManualFlowActive(c.config.Name) { + c.logger.Info("⏸️ Skipping automatic OAuth flow - a manual sign-in is already in flight", + zap.String("server", c.config.Name)) + return fmt.Errorf("OAuth sign-in already in progress for %s (started manually) - waiting for the user to finish", c.config.Name) + } + // Check if OAuth is already in progress to prevent duplicate flows (CRITICAL FIX for Phase 1) if c.isOAuthInProgress() { c.logger.Warn("⚠️ OAuth authorization already in progress, skipping duplicate attempt", @@ -1010,6 +1021,17 @@ func (c *Client) handleOAuthAuthorization(ctx context.Context, authErr error, oa zap.String("server", c.config.Name), zap.String("state", state)) + // Claim this state on the callback server BEFORE the browser is opened, so + // the callback can only ever be routed to THIS flow (issue #975). Another + // flow on the same server (a manual login, a background reconnect) keeps + // its own registration and cannot swallow our authorization code. + callbackServer, exists := oauth.GetCallbackServer(c.config.Name) + if !exists { + return fmt.Errorf("callback server not found for %s", c.config.Name) + } + callbackCh := callbackServer.RegisterState(state) + defer callbackServer.UnregisterState(state) + // Check if OAuth credentials are available (either from config or persisted DCR) // oauthConfig.ClientID may contain persisted DCR credentials loaded by CreateOAuthConfig() hasStaticCredentials := c.config.OAuth != nil && c.config.OAuth.ClientID != "" @@ -1237,15 +1259,9 @@ func (c *Client) handleOAuthAuthorization(ctx context.Context, authErr error, oa zap.Duration("timeout", 120*time.Second), zap.Time("wait_start", waitStartTime)) - // Get our callback server that was started in OAuth config creation - callbackServer, exists := oauth.GetCallbackServer(c.config.Name) - if !exists { - return fmt.Errorf("callback server not found for %s", c.config.Name) - } - - // Wait for the authorization code with extended timeout for remote/systemd scenarios + // Wait for the authorization code on THIS flow's channel (registered above) select { - case params := <-callbackServer.CallbackChan: + case params := <-callbackCh: waitDuration := time.Since(waitStartTime) c.logger.Info("🎯 OAuth callback received", zap.String("server", c.config.Name), @@ -1323,6 +1339,10 @@ func (c *Client) handleOAuthAuthorizationWithResult(ctx context.Context, authErr c.oauthMu.Unlock() }() + // Suppress background reconnect OAuth flows while this manual sign-in runs + // (issue #975). + defer oauth.BeginManualFlow(c.config.Name, 0)() + c.logger.Info("🔐 Starting manual OAuth authorization flow with result tracking", zap.String("server", c.config.Name), zap.String("correlation_id", result.CorrelationID)) @@ -1377,6 +1397,15 @@ func (c *Client) handleOAuthAuthorizationWithResult(ctx context.Context, authErr return result, fmt.Errorf("failed to generate state: %w", err) } + // Claim this state on the callback server before anything can redirect to + // it, so only this flow can consume its authorization code (issue #975). + callbackServer, exists := oauth.GetCallbackServer(c.config.Name) + if !exists { + return result, fmt.Errorf("callback server not found for %s", c.config.Name) + } + callbackCh := callbackServer.RegisterState(state) + defer callbackServer.UnregisterState(state) + // Check for existing credentials or attempt DCR hasStaticCredentials := c.config.OAuth != nil && c.config.OAuth.ClientID != "" hasPersistedCredentials := oauthConfig.ClientID != "" @@ -1520,14 +1549,9 @@ func (c *Client) handleOAuthAuthorizationWithResult(ctx context.Context, authErr c.lastOAuthTimestamp = time.Now() c.oauthMu.Unlock() - // Wait for the callback - callbackServer, exists := oauth.GetCallbackServer(c.config.Name) - if !exists { - return result, fmt.Errorf("callback server not found for %s", c.config.Name) - } - + // Wait for the callback on THIS flow's channel (registered above) select { - case params := <-callbackServer.CallbackChan: + case params := <-callbackCh: c.logger.Info("🎯 OAuth callback received", zap.String("server", c.config.Name), zap.String("correlation_id", result.CorrelationID)) @@ -1744,6 +1768,17 @@ func (c *Client) StartOAuthFlowQuick(ctx context.Context) (*OAuthStartResult, er // Clear any existing OAuth state c.clearOAuthState() + // Suppress background reconnect OAuth flows for this server until the user + // finishes (or the sign-in window expires) — issue #975. Ownership of the + // release moves to the background waiter once it is started. + releaseManualFlow := oauth.BeginManualFlow(c.config.Name, 0) + waiterOwnsRelease := false + defer func() { + if !waiterOwnsRelease { + releaseManualFlow() + } + }() + // Ensure transport type is determined if c.transportType == "" { c.transportType = transport.DetermineTransportType(c.config) @@ -1810,7 +1845,11 @@ func (c *Client) StartOAuthFlowQuick(ctx context.Context) (*OAuthStartResult, er result.BrowserError = "HEADLESS mode - browser not opened. Please open the auth_url manually." // Start OAuth callback handling in background - go c.waitForOAuthCallbackAsync(ctx, oauthHandler, codeVerifier, state, result.CorrelationID) + waiterOwnsRelease = true + go func() { + defer releaseManualFlow() + c.waitForOAuthCallbackAsync(ctx, oauthHandler, codeVerifier, state, result.CorrelationID) + }() return result, nil } @@ -1830,7 +1869,11 @@ func (c *Client) StartOAuthFlowQuick(ctx context.Context) (*OAuthStartResult, er } // Start OAuth callback handling in background - go c.waitForOAuthCallbackAsync(ctx, oauthHandler, codeVerifier, state, result.CorrelationID) + waiterOwnsRelease = true + go func() { + defer releaseManualFlow() + c.waitForOAuthCallbackAsync(ctx, oauthHandler, codeVerifier, state, result.CorrelationID) + }() return result, nil } @@ -1987,6 +2030,16 @@ func (c *Client) getAuthorizationURLQuick(ctx context.Context, oauthConfig *clie return "", nil, "", "", flowErr } + // Claim the state on the callback server before handing the URL back — the + // caller opens the browser next, and the callback must be routed to this + // flow even if the user authorizes before waitForOAuthCallbackAsync is + // scheduled (issue #975). RegisterState is idempotent, so that goroutine + // obtains this same channel. Registering only on the success path keeps a + // failed flow from leaving a dangling waiter behind. + if callbackServer, exists := oauth.GetCallbackServer(c.config.Name); exists { + callbackServer.RegisterState(state) + } + return authURL, oauthHandler, codeVerifier, state, nil } @@ -2058,30 +2111,44 @@ func (c *Client) waitForOAuthCallbackAsync(ctx context.Context, oauthHandler *up c.oauthMu.Unlock() }() + // The caller owns the deadline (the manager hands this flow a 30-minute + // context). A hardcoded 120s here used to abandon the login while the user + // was still finishing 2FA or waiting for org approval, leaving only + // background waiters behind (issue #975). + ctx, cancel := oauthCallbackWaitContext(ctx) + defer cancel() + + waitDeadline, _ := ctx.Deadline() c.logger.Info("⏳ Waiting for OAuth callback in background", zap.String("server", c.config.Name), - zap.String("correlation_id", correlationID)) + zap.String("correlation_id", correlationID), + zap.Time("deadline", waitDeadline)) // Get or create callback server callbackServer, exists := oauth.GetCallbackServer(c.config.Name) if !exists { - c.logger.Error("❌ Callback server not found", - zap.String("server", c.config.Name)) + c.reportOAuthFailure(fmt.Errorf("OAuth callback server not found for %s - the authorization code cannot be received", c.config.Name)) return } + // The state was registered when the authorization URL was built; this + // returns that same channel (issue #975). + callbackCh := callbackServer.RegisterState(state) + defer callbackServer.UnregisterState(state) + select { - case params := <-callbackServer.CallbackChan: + case params := <-callbackCh: c.logger.Info("🎯 OAuth callback received", zap.String("server", c.config.Name), zap.String("correlation_id", correlationID)) - // Verify state parameter + // Defensive: dispatch is by state, so this cannot normally fire. if params["state"] != state { c.logger.Error("❌ State mismatch in OAuth callback", zap.String("server", c.config.Name), zap.String("expected", state), zap.String("got", params["state"])) + c.reportOAuthFailure(fmt.Errorf("OAuth callback state mismatch for %s - the sign-in was not completed, please try again", c.config.Name)) return } @@ -2093,7 +2160,11 @@ func (c *Client) waitForOAuthCallbackAsync(ctx context.Context, oauthHandler *up zap.String("server", c.config.Name), zap.String("error", params["error"]), zap.String("description", params["error_description"])) + c.reportOAuthFailure(fmt.Errorf("OAuth authorization failed for %s: %s - %s", + c.config.Name, params["error"], params["error_description"])) + return } + c.reportOAuthFailure(fmt.Errorf("OAuth callback for %s carried no authorization code", c.config.Name)) return } @@ -2102,6 +2173,7 @@ func (c *Client) waitForOAuthCallbackAsync(ctx context.Context, oauthHandler *up c.logger.Error("❌ Failed to exchange authorization code", zap.String("server", c.config.Name), zap.Error(err)) + c.reportOAuthFailure(fmt.Errorf("OAuth token exchange failed for %s: %w", c.config.Name, err)) return } @@ -2114,17 +2186,47 @@ func (c *Client) waitForOAuthCallbackAsync(ctx context.Context, oauthHandler *up tokenManager := oauth.GetTokenStoreManager() tokenManager.MarkOAuthCompleted(c.config.Name) - case <-time.After(120 * time.Second): - c.logger.Warn("⏱️ OAuth authorization timeout", - zap.String("server", c.config.Name), - zap.String("correlation_id", correlationID)) - case <-ctx.Done(): + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + c.logger.Warn("⏱️ OAuth authorization timeout", + zap.String("server", c.config.Name), + zap.String("correlation_id", correlationID)) + c.reportOAuthFailure(fmt.Errorf("OAuth authorization for %s was not completed before the sign-in window expired", c.config.Name)) + return + } c.logger.Info("OAuth flow cancelled", zap.String("server", c.config.Name)) } } +// defaultOAuthCallbackWait bounds the background callback wait when the caller +// supplied no deadline of its own. Manual logins come in with the manager's +// 30-minute context; this only covers callers that pass a plain background +// context. +const defaultOAuthCallbackWait = 30 * time.Minute + +// oauthCallbackWaitContext returns a context bounded by the caller's deadline, +// falling back to defaultOAuthCallbackWait when the caller supplied none. The +// wait must follow the caller (the manager gives manual logins 30 minutes) +// rather than a hardcoded constant — a GitHub sign-in with 2FA or an org +// approval routinely takes longer than two minutes (issue #975). +func oauthCallbackWaitContext(ctx context.Context) (context.Context, context.CancelFunc) { + if _, ok := ctx.Deadline(); ok { + return context.WithCancel(ctx) + } + return context.WithTimeout(ctx, defaultOAuthCallbackWait) +} + +// reportOAuthFailure records an OAuth failure that has no caller to return an +// error to (the background callback waiter), so the operator sees it on the +// server's status instead of only in the log (issue #975). +func (c *Client) reportOAuthFailure(err error) { + if err == nil { + return + } + oauth.GetTokenStoreManager().RecordOAuthFailure(c.config.Name, err) +} + // ForceOAuthFlowWithResult forces an OAuth authentication flow and returns the auth URL and browser status. // This is used by Phase 3 (Spec 020) to provide the auth URL to clients even when browser opens successfully. func (c *Client) ForceOAuthFlowWithResult(ctx context.Context) (*OAuthStartResult, error) { diff --git a/internal/upstream/core/oauth_callback_wait_test.go b/internal/upstream/core/oauth_callback_wait_test.go new file mode 100644 index 000000000..438cfa88c --- /dev/null +++ b/internal/upstream/core/oauth_callback_wait_test.go @@ -0,0 +1,122 @@ +package core + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" +) + +// Issue #975: the background callback waiter used to give up after a hardcoded +// 120 seconds even though the manager hands it a 30-minute context, so a +// sign-in that needed 2FA or an org approval found nobody waiting when the +// callback finally arrived. + +func newOAuthWaitTestClient(name string) *Client { + return &Client{ + config: &config.ServerConfig{Name: name, URL: "https://example.test/mcp"}, + logger: zap.NewNop(), + } +} + +func TestOAuthCallbackWaitContext_HonoursCallerDeadline(t *testing.T) { + callerDeadline := time.Now().Add(30 * time.Minute) + parent, cancelParent := context.WithDeadline(context.Background(), callerDeadline) + defer cancelParent() + + ctx, cancel := oauthCallbackWaitContext(parent) + defer cancel() + + deadline, ok := ctx.Deadline() + require.True(t, ok) + assert.WithinDuration(t, callerDeadline, deadline, time.Second, + "the wait must follow the caller's deadline, not a hardcoded 120s") + assert.Greater(t, time.Until(deadline), 2*time.Minute, + "a 30-minute sign-in window must survive past the old 120s cutoff") +} + +func TestOAuthCallbackWaitContext_FallsBackWhenCallerHasNoDeadline(t *testing.T) { + ctx, cancel := oauthCallbackWaitContext(context.Background()) + defer cancel() + + deadline, ok := ctx.Deadline() + require.True(t, ok, "a deadline-less caller must still get a bounded wait") + assert.WithinDuration(t, time.Now().Add(defaultOAuthCallbackWait), deadline, time.Minute) +} + +// TestWaitForOAuthCallbackAsync_ExpiryIsReported verifies (d): when the sign-in +// window closes without a callback, the failure reaches the operator through +// the OAuth failure hook rather than being logged and forgotten. +func TestWaitForOAuthCallbackAsync_ExpiryIsReported(t *testing.T) { + serverName := "wait-expiry-server" + manager := oauth.GetGlobalCallbackManager() + _, err := manager.StartCallbackServer(serverName, 0) + require.NoError(t, err) + t.Cleanup(func() { _ = manager.StopCallbackServer(serverName) }) + + failures := make(chan error, 4) + tm := oauth.GetTokenStoreManager() + tm.SetOAuthFailureCallback(func(server string, failure error) { + if server == serverName { + failures <- failure + } + }) + t.Cleanup(func() { tm.SetOAuthFailureCallback(nil) }) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + + c := newOAuthWaitTestClient(serverName) + + done := make(chan struct{}) + start := time.Now() + go func() { + defer close(done) + c.waitForOAuthCallbackAsync(ctx, nil, "verifier", "state-nobody-answers", "corr-expiry") + }() + + select { + case <-done: + assert.Less(t, time.Since(start), 5*time.Second, + "the waiter must follow the caller's deadline") + case <-time.After(10 * time.Second): + t.Fatal("waitForOAuthCallbackAsync ignored the caller's deadline") + } + + select { + case failure := <-failures: + require.Error(t, failure) + assert.Contains(t, failure.Error(), serverName) + case <-time.After(2 * time.Second): + t.Fatal("an expired sign-in window was not surfaced through the failure hook") + } +} + +// TestHandleOAuthAuthorization_StandsDownForManualFlow verifies (e): a +// background reconnect does not start a competing OAuth flow while the user is +// still completing a manual sign-in. +func TestHandleOAuthAuthorization_StandsDownForManualFlow(t *testing.T) { + serverName := "stand-down-server" + release := oauth.BeginManualFlow(serverName, time.Minute) + defer release() + + c := newOAuthWaitTestClient(serverName) + + err := c.handleOAuthAuthorization(context.Background(), nil, nil, nil) + require.Error(t, err, "the automatic flow must stand down while a manual login is in flight") + assert.Contains(t, err.Error(), "already in progress") + + // A manual flow (marked on the context) is never suppressed by this guard. + release() + release2 := oauth.BeginManualFlow(serverName, time.Minute) + defer release2() + manualCtx := context.WithValue(context.Background(), manualOAuthKey, true) + assert.True(t, c.isManualOAuthFlow(manualCtx), + "a manual flow must be recognised so it is not suppressed by its own claim") +} diff --git a/internal/upstream/manager.go b/internal/upstream/manager.go index dfdad177e..988d329e5 100644 --- a/internal/upstream/manager.go +++ b/internal/upstream/manager.go @@ -224,6 +224,12 @@ func NewManager(logger *zap.Logger, globalConfig *config.Config, boltStorage *st } }) + // Surface OAuth failures that have no caller to return an error to — an + // undeliverable callback, a state mismatch, a background token exchange + // that failed. Without this the CLI kept reporting "OAuth authentication + // flow initiated successfully" while the flow had already died (issue #975). + tokenManager.SetOAuthFailureCallback(manager.recordOAuthFailure) + // Start database event monitor for cross-process OAuth completion notifications if boltStorage != nil { manager.shutdownWg.Add(1) @@ -1789,6 +1795,40 @@ func (m *Manager) ListServers() map[string]*config.ServerConfig { return servers } +// recordOAuthFailure stamps an unattended OAuth failure onto the server's +// connection status so it shows up in `mcpproxy upstream list`, the REST status +// payload and the tray — the same place other auth failures land (issue #975). +// +// A server that is currently Ready is left alone: a late or orphaned callback +// must never knock a working connection into Error. +func (m *Manager) recordOAuthFailure(serverName string, cause error) { + if cause == nil { + return + } + + m.mu.RLock() + client, exists := m.clients[serverName] + m.mu.RUnlock() + if !exists { + m.logger.Warn("OAuth failure reported for unknown server", + zap.String("server", serverName), + zap.Error(cause)) + return + } + + if client.StateManager.IsReady() { + m.logger.Warn("Ignoring OAuth failure for a server that is already connected", + zap.String("server", serverName), + zap.Error(cause)) + return + } + + m.logger.Warn("Recording OAuth failure on server status", + zap.String("server", serverName), + zap.Error(cause)) + client.StateManager.SetOAuthError(cause) +} + // RetryConnection triggers a connection retry for a specific server // This is typically called after OAuth completion to immediately use new tokens func (m *Manager) RetryConnection(serverName string) error { diff --git a/internal/upstream/manager_oauth_failure_test.go b/internal/upstream/manager_oauth_failure_test.go new file mode 100644 index 000000000..c6ccbc5c4 --- /dev/null +++ b/internal/upstream/manager_oauth_failure_test.go @@ -0,0 +1,84 @@ +package upstream + +import ( + "errors" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/managed" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/types" +) + +// Issue #975: an OAuth callback that could not be delivered (unknown/expired +// state) used to produce nothing but a log line, so the CLI kept claiming +// "OAuth authentication flow initiated successfully" while the server sat at +// "Sign-in required" forever. The failure must land on the server's status. + +func newFailureTestManager(t *testing.T, serverName string) (*Manager, *managed.Client) { + t.Helper() + logger := zap.NewNop() + + serverConfig := &config.ServerConfig{ + Name: serverName, + URL: "https://example.test/mcp", + Protocol: "http", + Enabled: true, + Created: time.Now(), + } + + manager := &Manager{ + clients: make(map[string]*managed.Client), + logger: logger, + secretResolver: secret.NewResolver(), + } + + client, err := managed.NewClient(serverName, serverConfig, logger, nil, &config.Config{}, nil, secret.NewResolver()) + require.NoError(t, err) + manager.clients[serverName] = client + + return manager, client +} + +func TestRecordOAuthFailure_SurfacesOnServerStatus(t *testing.T) { + serverName := "oauth-failure-visible" + manager, client := newFailureTestManager(t, serverName) + + cause := errors.New("OAuth callback for \"oauth-failure-visible\" could not be delivered: state is unknown or expired") + manager.recordOAuthFailure(serverName, cause) + + info := client.GetConnectionInfo() + assert.Equal(t, types.StateError, info.State, "the server must not look healthy after a dropped OAuth callback") + require.Error(t, info.LastError) + assert.Contains(t, info.LastError.Error(), "could not be delivered") + assert.True(t, info.IsOAuthError, "the failure must be classified as an OAuth error") +} + +func TestRecordOAuthFailure_IgnoresNilAndUnknownServers(t *testing.T) { + serverName := "oauth-failure-nil" + manager, client := newFailureTestManager(t, serverName) + + manager.recordOAuthFailure(serverName, nil) + manager.recordOAuthFailure("no-such-server", errors.New("boom")) + + info := client.GetConnectionInfo() + assert.NotEqual(t, types.StateError, info.State, "no failure was reported for this server") +} + +func TestRecordOAuthFailure_LeavesReadyServerAlone(t *testing.T) { + serverName := "oauth-failure-ready" + manager, client := newFailureTestManager(t, serverName) + + client.StateManager.TransitionTo(types.StateConnecting) + client.StateManager.TransitionTo(types.StateReady) + + manager.recordOAuthFailure(serverName, errors.New("late orphaned callback")) + + assert.Equal(t, types.StateReady, client.GetConnectionInfo().State, + "a late or orphaned callback must never knock a working connection into Error") +}