diff --git a/internal/agent/tools/mcp_oauth.go b/internal/agent/tools/mcp_oauth.go index 554ed83e..3ec61954 100644 --- a/internal/agent/tools/mcp_oauth.go +++ b/internal/agent/tools/mcp_oauth.go @@ -110,7 +110,14 @@ func getOrCreateMCPClientWithOAuthRetry( } defer cancel() - _ = mcpManager.CloseClient(service.ID) + // The callback that completed the authorization may have been handled by + // another replica, so this one recycles its own connections: this user's, + // and any built with a replaced OAuth client registration. Other users' + // in-flight calls continue. + tenantID, _ := types.TenantIDFromContext(retryCtx) + _ = mcpManager.CloseClientsAfterAuthorization( + retryCtx, tenantID, service.ID, types.MCPOAuthPrincipalFromContext(retryCtx), + ) return mcpManager.GetOrCreateClient(retryCtx, service) } diff --git a/internal/agent/tools/mcp_oauth_test.go b/internal/agent/tools/mcp_oauth_test.go new file mode 100644 index 00000000..cc0d8819 --- /dev/null +++ b/internal/agent/tools/mcp_oauth_test.go @@ -0,0 +1,142 @@ +package tools + +import ( + "context" + "fmt" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/agent/approval" + "github.com/Tencent/WeKnora/internal/event" + "github.com/Tencent/WeKnora/internal/mcp" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/Tencent/WeKnora/internal/utils" + sdkserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/require" +) + +const oauthRetryTestTenant = uint64(7) + +type oauthRetryTestRepo struct { + interfaces.MCPOAuthRepository + mu sync.Mutex + clients map[string]*types.MCPOAuthClient + tokens map[string]*types.MCPOAuthToken +} + +func (r *oauthRetryTestRepo) GetClient( + _ context.Context, tenantID uint64, serviceID string, +) (*types.MCPOAuthClient, error) { + r.mu.Lock() + defer r.mu.Unlock() + return r.clients[fmt.Sprintf("%d|%s", tenantID, serviceID)], nil +} + +func (r *oauthRetryTestRepo) registerClient(serviceID, clientID string) { + r.mu.Lock() + defer r.mu.Unlock() + r.clients[fmt.Sprintf("%d|%s", oauthRetryTestTenant, serviceID)] = &types.MCPOAuthClient{ + TenantID: oauthRetryTestTenant, ServiceID: serviceID, ClientID: clientID, + } +} + +func (r *oauthRetryTestRepo) GetTokenForPrincipal( + _ context.Context, tenantID uint64, principal types.Principal, serviceID string, +) (*types.MCPOAuthToken, error) { + r.mu.Lock() + defer r.mu.Unlock() + return r.tokens[fmt.Sprintf("%d|%s|%s", tenantID, principal.StorageID(), serviceID)], nil +} + +func (r *oauthRetryTestRepo) saveToken(principal types.Principal, serviceID string) { + r.mu.Lock() + defer r.mu.Unlock() + r.tokens[fmt.Sprintf("%d|%s|%s", oauthRetryTestTenant, principal.StorageID(), serviceID)] = &types.MCPOAuthToken{ + TenantID: oauthRetryTestTenant, + PrincipalType: principal.Type, + PrincipalID: principal.ID, + ServiceID: serviceID, + AccessToken: "access-" + principal.ID, + TokenType: "Bearer", + ExpiresAt: time.Now().Add(time.Hour), + } +} + +// oauthRetryTestGate completes the in-conversation authorization as soon as +// the agent asks for it, running authorized in place of the user. +type oauthRetryTestGate struct { + approval.MCPApproval + authorized func() +} + +func (g oauthRetryTestGate) RequestOAuthAndWait( + context.Context, approval.OAuthPendingRequest, +) (approval.Decision, error) { + g.authorized() + return approval.Decision{Approved: true}, nil +} + +func ctxForOAuthRetryTest(principal types.Principal) context.Context { + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, oauthRetryTestTenant) + return types.WithPrincipal(ctx, principal) +} + +// After the user authorizes mid-conversation, the waiting replica recycles the +// user's connection and connections built with a replaced client registration, +// and leaves other users' connections, and their in-flight calls, alone. +func TestOAuthRetryRecyclesOnlyOutdatedConnections(t *testing.T) { + for _, tc := range []struct { + name string + reregister bool + otherUserSurvives bool + }{ + {name: "client registration unchanged", otherUserSurvives: true}, + {name: "client registration replaced elsewhere", reregister: true}, + } { + t.Run(tc.name, func(t *testing.T) { + utils.SetSSRFWhitelistFromRaw("127.0.0.1") + t.Cleanup(utils.ResetSSRFWhitelistForTest) + server := httptest.NewServer(sdkserver.NewStreamableHTTPServer( + sdkserver.NewMCPServer("test", "1"), sdkserver.WithStateLess(true), + )) + t.Cleanup(server.Close) + service := &types.MCPService{ + ID: "svc-1", + Enabled: true, + TransportType: types.MCPTransportHTTPStreamable, + URL: &server.URL, + AuthConfig: &types.MCPAuthConfig{AuthType: types.MCPAuthOAuth}, + } + repo := &oauthRetryTestRepo{ + clients: map[string]*types.MCPOAuthClient{}, + tokens: map[string]*types.MCPOAuthToken{}, + } + repo.registerClient(service.ID, "client-1") + manager := mcp.NewMCPManager(repo) + t.Cleanup(manager.Shutdown) + + bob := types.Principal{Type: types.PrincipalWebUser, ID: "bob"} + repo.saveToken(bob, service.ID) + bobConn, err := manager.GetOrCreateClient(ctxForOAuthRetryTest(bob), service) + require.NoError(t, err) + + alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"} + ctx := ctxForOAuthRetryTest(alice) + gate := oauthRetryTestGate{authorized: func() { + repo.saveToken(alice, service.ID) + if tc.reregister { + repo.registerClient(service.ID, "client-2") + } + }} + sess := &MCPOAuthSession{EventBus: event.NewEventBus(), ApprovalCtx: ctx, ExecTimeout: 5 * time.Second} + + aliceConn, err := getOrCreateMCPClientWithOAuthRetry(ctx, manager, service, gate, sess, "tool", "call-1") + require.NoError(t, err) + require.True(t, aliceConn.IsConnected()) + require.Equal(t, tc.otherUserSurvives, bobConn.IsConnected()) + }) + } +} diff --git a/internal/handler/mcp_oauth.go b/internal/handler/mcp_oauth.go index fe92e928..49526a7e 100644 --- a/internal/handler/mcp_oauth.go +++ b/internal/handler/mcp_oauth.go @@ -1,9 +1,11 @@ package handler import ( + "context" stderrors "errors" "net/http" "strings" + "time" "github.com/Tencent/WeKnora/internal/agent/approval" "github.com/Tencent/WeKnora/internal/errors" @@ -15,6 +17,10 @@ import ( "github.com/gin-gonic/gin" ) +// oauthConnectionCleanupTimeout bounds reading the OAuth client registration +// when the callback recycles cached connections. +const oauthConnectionCleanupTimeout = 5 * time.Second + // MCPOAuthHandler exposes the per-user MCP OAuth2 authorization-code flow: // kicking off authorization (discovery + dynamic client registration + PKCE), // receiving the provider redirect, reporting authorization status, and @@ -151,7 +157,8 @@ func (h *MCPOAuthHandler) Callback(c *gin.Context) { return } - frontendRedirect, serviceID, err := h.oauth.CompleteAuthorization(ctx, state, code) + result, err := h.oauth.CompleteAuthorization(ctx, state, code) + frontendRedirect := result.FrontendRedirect if frontendRedirect == "" { frontendRedirect = fallbackRedirect } @@ -160,11 +167,16 @@ func (h *MCPOAuthHandler) Callback(c *gin.Context) { c.Redirect(http.StatusFound, frontendRedirect+"#mcp_oauth_error="+urlQueryEscape("authorization_failed")) return } - // The old transport may have been created with an OAuth client registration - // that was invalidated together with the refresh token. Recreate it against - // the freshly persisted token/client on next use. - if h.mcpManager != nil && serviceID != "" { - _ = h.mcpManager.CloseClient(serviceID) + // Recycle the authorizing user's connection and any connection built with + // a replaced OAuth client registration. Other users' connections, and the + // tool calls in flight on them, are left alone. The browser may leave as + // soon as it is redirected, which must not cut this short. + if h.mcpManager != nil { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), oauthConnectionCleanupTimeout) + _ = h.mcpManager.CloseClientsAfterAuthorization( + cleanupCtx, result.TenantID, result.ServiceID, result.Principal, + ) + cancel() } c.Redirect(http.StatusFound, frontendRedirect+"#mcp_oauth_result=success") } @@ -219,7 +231,7 @@ func (h *MCPOAuthHandler) Status(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"success": true, "data": status}) } -// Revoke removes the current user's stored token and recycles connections. +// Revoke removes the current user's stored token and recycles their connection. // // Revoke godoc // @Summary 撤销 MCP OAuth 授权 @@ -244,8 +256,11 @@ func (h *MCPOAuthHandler) Revoke(c *gin.Context) { c.Error(errors.NewInternalServerError("failed to revoke authorization: " + err.Error())) return } - // Recycle any cached connections so a subsequent call re-authorizes. - _ = h.mcpManager.CloseClient(serviceID) + // Recycle this user's cached connection so a subsequent call re-authorizes. + // Other users' connections do not use the revoked token and stay open. + if h.mcpManager != nil { + _ = h.mcpManager.CloseClientForPrincipal(serviceID, principal) + } c.Status(http.StatusNoContent) } diff --git a/internal/handler/mcp_oauth_test.go b/internal/handler/mcp_oauth_test.go new file mode 100644 index 00000000..83a67f9b --- /dev/null +++ b/internal/handler/mcp_oauth_test.go @@ -0,0 +1,256 @@ +package handler + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/mcp" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + secutils "github.com/Tencent/WeKnora/internal/utils" + "github.com/gin-gonic/gin" + sdkserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/require" +) + +const mcpOAuthTestTenant = uint64(7) + +type mcpOAuthTestRepo struct { + interfaces.MCPOAuthRepository + mu sync.Mutex + clients map[string]*types.MCPOAuthClient + tokens map[string]*types.MCPOAuthToken +} + +func mcpOAuthTestTokenKey(tenantID uint64, principal types.Principal, serviceID string) string { + return fmt.Sprintf("%d|%s|%s", tenantID, principal.StorageID(), serviceID) +} + +func (r *mcpOAuthTestRepo) GetClient( + _ context.Context, tenantID uint64, serviceID string, +) (*types.MCPOAuthClient, error) { + r.mu.Lock() + defer r.mu.Unlock() + return r.clients[fmt.Sprintf("%d|%s", tenantID, serviceID)], nil +} + +func (r *mcpOAuthTestRepo) SaveClient(_ context.Context, client *types.MCPOAuthClient) error { + r.mu.Lock() + defer r.mu.Unlock() + r.clients[fmt.Sprintf("%d|%s", client.TenantID, client.ServiceID)] = client + return nil +} + +func (r *mcpOAuthTestRepo) GetTokenForPrincipal( + _ context.Context, tenantID uint64, principal types.Principal, serviceID string, +) (*types.MCPOAuthToken, error) { + r.mu.Lock() + defer r.mu.Unlock() + return r.tokens[mcpOAuthTestTokenKey(tenantID, principal, serviceID)], nil +} + +func (r *mcpOAuthTestRepo) SaveTokenForPrincipal(_ context.Context, token *types.MCPOAuthToken) error { + r.mu.Lock() + defer r.mu.Unlock() + principal := types.Principal{Type: token.PrincipalType, ID: token.PrincipalID} + r.tokens[mcpOAuthTestTokenKey(token.TenantID, principal, token.ServiceID)] = token + return nil +} + +func (r *mcpOAuthTestRepo) DeleteTokenForPrincipal( + _ context.Context, tenantID uint64, principal types.Principal, serviceID string, +) error { + r.mu.Lock() + defer r.mu.Unlock() + delete(r.tokens, mcpOAuthTestTokenKey(tenantID, principal, serviceID)) + return nil +} + +type mcpOAuthTestServiceRepo struct { + interfaces.MCPServiceRepository + service *types.MCPService +} + +func (r mcpOAuthTestServiceRepo) GetByID(_ context.Context, _ uint64, id string) (*types.MCPService, error) { + if r.service.ID == id { + return r.service, nil + } + return nil, nil +} + +// mcpOAuthTestEnv is an OAuth MCP service whose authorization server and MCP +// server run in process, with a handler wired to a real connection manager. +type mcpOAuthTestEnv struct { + service *types.MCPService + repo *mcpOAuthTestRepo + oauth *mcp.OAuthManager + manager *mcp.MCPManager + handler *MCPOAuthHandler +} + +func newMCPOAuthTestEnv(t *testing.T) *mcpOAuthTestEnv { + t.Helper() + t.Setenv("SSRF_WHITELIST", "127.0.0.1") + secutils.ResetSSRFWhitelistForTest() + t.Cleanup(secutils.ResetSSRFWhitelistForTest) + + mux := http.NewServeMux() + var serverURL string + mux.HandleFunc("/.well-known/oauth-authorization-server", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": serverURL, + "authorization_endpoint": serverURL + "/authorize", + "token_endpoint": serverURL + "/token", + }) + }) + mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "access_token": "access-new", + "token_type": "Bearer", + "expires_in": 3600, + }) + }) + mux.Handle("/mcp", sdkserver.NewStreamableHTTPServer( + sdkserver.NewMCPServer("test", "1"), sdkserver.WithStateLess(true), + )) + server := httptest.NewServer(mux) + t.Cleanup(server.Close) + serverURL = server.URL + + serviceURL := server.URL + "/mcp" + service := &types.MCPService{ + ID: "svc-1", + TenantID: mcpOAuthTestTenant, + Enabled: true, + TransportType: types.MCPTransportHTTPStreamable, + URL: &serviceURL, + AuthConfig: &types.MCPAuthConfig{ + AuthType: types.MCPAuthOAuth, + AuthServerMetadataURL: server.URL + "/.well-known/oauth-authorization-server", + }, + } + repo := &mcpOAuthTestRepo{ + clients: map[string]*types.MCPOAuthClient{}, + tokens: map[string]*types.MCPOAuthToken{}, + } + oauth := mcp.NewOAuthManager(repo, mcpOAuthTestServiceRepo{service: service}, nil) + manager := mcp.NewMCPManager(repo) + t.Cleanup(manager.Shutdown) + return &mcpOAuthTestEnv{ + service: service, + repo: repo, + oauth: oauth, + manager: manager, + handler: NewMCPOAuthHandler(oauth, manager, nil, nil), + } +} + +func (e *mcpOAuthTestEnv) registerClient(t *testing.T, clientID string) { + t.Helper() + require.NoError(t, e.repo.SaveClient(context.Background(), &types.MCPOAuthClient{ + TenantID: mcpOAuthTestTenant, ServiceID: e.service.ID, ClientID: clientID, + })) +} + +// connect authorizes principal and opens its cached connection. +func (e *mcpOAuthTestEnv) connect(t *testing.T, principal types.Principal) mcp.MCPClient { + t.Helper() + require.NoError(t, e.repo.SaveTokenForPrincipal(context.Background(), &types.MCPOAuthToken{ + TenantID: mcpOAuthTestTenant, + PrincipalType: principal.Type, + PrincipalID: principal.ID, + ServiceID: e.service.ID, + AccessToken: "access-" + principal.ID, + TokenType: "Bearer", + ExpiresAt: time.Now().Add(time.Hour), + })) + ctx := context.WithValue(context.Background(), types.TenantIDContextKey, mcpOAuthTestTenant) + ctx, cancel := context.WithTimeout(types.WithPrincipal(ctx, principal), 5*time.Second) + defer cancel() + client, err := e.manager.GetOrCreateClient(ctx, e.service) + require.NoError(t, err) + return client +} + +// authorize runs one authorization attempt of principal through the callback. +func (e *mcpOAuthTestEnv) authorize(t *testing.T, principal types.Principal) { + t.Helper() + _, state, err := e.oauth.StartAuthorization( + context.Background(), e.service, mcpOAuthTestTenant, principal, "http://localhost/callback", "/settings", + ) + require.NoError(t, err) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + query := url.Values{"state": {state}, "code": {"code"}} + c.Request = httptest.NewRequest(http.MethodGet, "/mcp-services/oauth/callback?"+query.Encode(), nil) + e.handler.Callback(c) + require.Equal(t, http.StatusFound, w.Code) + require.Equal(t, "/settings#mcp_oauth_result=success", w.Header().Get("Location")) +} + +func TestMCPOAuthCallbackRecyclesOnlyTheAuthorizingUsersConnection(t *testing.T) { + env := newMCPOAuthTestEnv(t) + env.registerClient(t, "client-1") + alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"} + bob := types.Principal{Type: types.PrincipalWebUser, ID: "bob"} + aliceConn, bobConn := env.connect(t, alice), env.connect(t, bob) + + env.authorize(t, alice) + + require.False(t, aliceConn.IsConnected()) + require.True(t, bobConn.IsConnected(), "another user's connection and its in-flight calls are left alone") +} + +// The client registration is shared by every user of the service. Once it has +// been replaced, for example by another replica re-registering after the old +// client was rejected, connections still holding the old client ID are +// recycled by the next authorization as well. +func TestMCPOAuthCallbackRecyclesConnectionsOfAReplacedRegistration(t *testing.T) { + env := newMCPOAuthTestEnv(t) + env.registerClient(t, "client-1") + alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"} + bob := types.Principal{Type: types.PrincipalWebUser, ID: "bob"} + aliceConn, bobConn := env.connect(t, alice), env.connect(t, bob) + env.registerClient(t, "client-2") + carol := types.Principal{Type: types.PrincipalWebUser, ID: "carol"} + carolConn := env.connect(t, carol) + + env.authorize(t, alice) + + require.False(t, aliceConn.IsConnected()) + require.False(t, bobConn.IsConnected(), "built with the replaced client registration") + require.True(t, carolConn.IsConnected(), "built with the current client registration") +} + +func TestMCPOAuthRevokeRecyclesOnlyTheRevokingUsersConnection(t *testing.T) { + env := newMCPOAuthTestEnv(t) + env.registerClient(t, "client-1") + alice := types.Principal{Type: types.PrincipalWebUser, ID: "alice"} + bob := types.Principal{Type: types.PrincipalWebUser, ID: "bob"} + aliceConn, bobConn := env.connect(t, alice), env.connect(t, bob) + + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + req := httptest.NewRequest(http.MethodDelete, "/mcp-services/svc-1/oauth/token", nil) + c.Request = req.WithContext(types.WithPrincipal(req.Context(), alice)) + c.Params = gin.Params{{Key: "id", Value: env.service.ID}} + c.Set(types.TenantIDContextKey.String(), mcpOAuthTestTenant) + env.handler.Revoke(c) + c.Writer.WriteHeaderNow() + + require.Equal(t, http.StatusNoContent, w.Code) + token, err := env.repo.GetTokenForPrincipal(context.Background(), mcpOAuthTestTenant, alice, env.service.ID) + require.NoError(t, err) + require.Nil(t, token) + require.False(t, aliceConn.IsConnected()) + require.True(t, bobConn.IsConnected()) +} diff --git a/internal/mcp/client.go b/internal/mcp/client.go index 25724cef..08c461f2 100644 --- a/internal/mcp/client.go +++ b/internal/mcp/client.go @@ -894,6 +894,15 @@ func (c *mcpGoClient) IsConnected() bool { return c.connected.Load() } +// oauthClientRegistration reports the tenant and OAuth client ID the +// connection was built with; ok is false for a connection without OAuth. +func (c *mcpGoClient) oauthClientRegistration() (tenantID uint64, clientID string, ok bool) { + if c.oauth == nil { + return 0, "", false + } + return c.oauth.tenantID, c.oauth.clientID, true +} + // GetServiceID returns the service ID func (c *mcpGoClient) GetServiceID() string { return c.service.ID diff --git a/internal/mcp/manager.go b/internal/mcp/manager.go index 74c2955b..79519cad 100644 --- a/internal/mcp/manager.go +++ b/internal/mcp/manager.go @@ -75,11 +75,17 @@ func NewMCPManager(oauthRepo interfaces.MCPOAuthRepository) *MCPManager { // services share a single connection per service ID. func cacheKey(service *types.MCPService, principal types.Principal) string { if service.AuthConfig.IsOAuth() { - return service.ID + "\x00" + principal.Normalize().StorageID() + return principalCacheKey(service.ID, principal) } return service.ID } +// principalCacheKey is the cache key of one principal's connection to an +// OAuth service. +func principalCacheKey(serviceID string, principal types.Principal) string { + return serviceID + "\x00" + principal.StorageID() +} + // GetOrCreateClient gets an existing client or creates a new one // Caches and reuses existing connections for SSE/HTTP Streamable // Note: Stdio transport is disabled for security reasons @@ -265,6 +271,139 @@ func (m *MCPManager) CloseClient(serviceID string) error { return nil } +// CloseClientForPrincipal closes the connection one principal holds to an +// OAuth service and retires that principal's connection attempt if one is +// still in flight. Connections of other principals stay open, so the requests +// they have in flight are not canceled. A service without OAuth shares one +// connection that carries no per-user credential; it is left alone. +func (m *MCPManager) CloseClientForPrincipal(serviceID string, principal types.Principal) error { + if serviceID == "" || !principal.Valid() { + return nil + } + detached := make(map[string]MCPClient) + m.clientsMu.Lock() + m.detachLocked(principalCacheKey(serviceID, principal), detached) + m.clientsMu.Unlock() + m.disconnectDetached(serviceID, detached) + return nil +} + +// CloseClientsAfterAuthorization recycles the cached connections that a +// completed OAuth authorization of principal leaves outdated: +// +// - The principal's own connection. The server may have tied its MCP +// session, and the tools it advertised, to the account that authorized +// it, and the new authorization may be for another account. An SSE event +// stream also keeps the credentials it was opened with. +// - Connections of the service in the same tenant that were built with an +// OAuth client ID other than the registration stored now. The registration +// is shared by every principal of the service and may have been replaced, +// in this process or in another replica. A connection still holding the +// old client ID can fail its next token refresh with invalid_client, and +// handling that failure deletes the stored registration, which by then is +// the replacement. +// +// Other connections stay open: each one reads its principal's token from the +// store on every request, and closing a connection cancels the requests it has +// in flight. Only connections cached by this process are examined, and +// connection attempts of other principals that are still in flight are not. +// If the stored registration cannot be read, every connection of the service +// is closed, unless ctx has ended, in which case only the principal's own +// connection is: a caller that went away must not cancel other principals' +// requests. +func (m *MCPManager) CloseClientsAfterAuthorization( + ctx context.Context, tenantID uint64, serviceID string, principal types.Principal, +) error { + if serviceID == "" { + return nil + } + if m.oauthRepo == nil { + // Without the repository no OAuth connection can be built, so there is + // no registration to compare against. + return m.CloseClientForPrincipal(serviceID, principal) + } + registration, err := m.oauthRepo.GetClient(ctx, tenantID, serviceID) + if err != nil && ctx.Err() != nil { + logger.GetLogger(ctx).Warnf( + "Failed to read MCP OAuth client registration service=%s, closing only principal=%s: %v", + serviceID, principal.StorageID(), err, + ) + return m.CloseClientForPrincipal(serviceID, principal) + } + if err != nil { + logger.GetLogger(ctx).Warnf( + "Failed to read MCP OAuth client registration service=%s, closing all its connections: %v", serviceID, err, + ) + return m.CloseClient(serviceID) + } + currentClientID := "" + if registration != nil { + currentClientID = registration.ClientID + } + + detached := make(map[string]MCPClient) + m.clientsMu.Lock() + if principal.Valid() { + m.detachLocked(principalCacheKey(serviceID, principal), detached) + } + for key, client := range m.clients { + if !strings.HasPrefix(key, serviceID+"\x00") { + continue + } + connTenantID, clientID, ok := oauthClientRegistrationOf(client) + if ok && connTenantID == tenantID && clientID != currentClientID { + m.detachLocked(key, detached) + } + } + m.clientsMu.Unlock() + m.disconnectDetached(serviceID, detached) + return nil +} + +// oauthClientRegistrationOf reports the tenant and OAuth client ID a cached +// connection was built with; ok is false for a connection without OAuth. +func oauthClientRegistrationOf(client MCPClient) (tenantID uint64, clientID string, ok bool) { + if managed, owned := client.(*managedMCPClient); owned { + client = managed.MCPClient + } + registered, ok := client.(interface { + oauthClientRegistration() (uint64, string, bool) + }) + if !ok { + return 0, "", false + } + return registered.oauthClientRegistration() +} + +// detachLocked removes key's connection and in-flight connection attempt from +// the manager, cancelling the attempt and adding the connection to detached. +// The caller holds clientsMu and disconnects the detached connections once it +// has released the lock, since closing a transport may wait on the server. +func (m *MCPManager) detachLocked(key string, detached map[string]MCPClient) { + if pending, ok := m.connecting[key]; ok { + pending.cancel() + delete(m.connecting, key) + } + if client, ok := m.clients[key]; ok { + detached[key] = client + delete(m.clients, key) + } +} + +// disconnectDetached disconnects connections of serviceID that detachLocked +// removed from the manager. +func (m *MCPManager) disconnectDetached(serviceID string, detached map[string]MCPClient) { + for key, client := range detached { + principal := strings.TrimPrefix(key, serviceID+"\x00") + if err := client.Disconnect(); err != nil { + logger.GetLogger(m.ctx).Errorf( + "Failed to disconnect MCP client service=%s principal=%s: %v", serviceID, principal, err, + ) + } + logger.GetLogger(m.ctx).Infof("MCP client closed: service=%s principal=%s", serviceID, principal) + } +} + // InvalidateToolSchemas drops the header-schema caches of every cached // connection for a service after listedBy completed a newer directory read. // Connections stay open; their next modern CallTool reloads the directory. diff --git a/internal/mcp/manager_close_principal_test.go b/internal/mcp/manager_close_principal_test.go new file mode 100644 index 00000000..919b4908 --- /dev/null +++ b/internal/mcp/manager_close_principal_test.go @@ -0,0 +1,385 @@ +package mcp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/utils" + sdkmcp "github.com/mark3labs/mcp-go/mcp" + sdkserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/require" +) + +func oauthTestService(id string) *types.MCPService { + return &types.MCPService{ + ID: id, + Enabled: true, + TransportType: types.MCPTransportHTTPStreamable, + AuthConfig: &types.MCPAuthConfig{AuthType: types.MCPAuthOAuth}, + } +} + +func webUser(id string) types.Principal { + return types.Principal{Type: types.PrincipalWebUser, ID: id} +} + +// newPendingConnection registers an in-flight connection attempt under key and +// returns the context its cancel func retires. +func newPendingConnection(m *MCPManager, key string) context.Context { + ctx, cancel := context.WithCancel(context.Background()) + m.connecting[key] = &pendingMCPConnection{done: make(chan struct{}), cancel: cancel} + return ctx +} + +// registeredClient is a cached OAuth connection built with a given client +// registration. +type registeredClient struct { + *disconnectClient + tenantID uint64 + clientID string +} + +func newRegisteredClient(tenantID uint64, clientID string) registeredClient { + return registeredClient{disconnectClient: &disconnectClient{}, tenantID: tenantID, clientID: clientID} +} + +func (c registeredClient) oauthClientRegistration() (uint64, string, bool) { + return c.tenantID, c.clientID, true +} + +// failingClientRepo cannot read the OAuth client registration. +type failingClientRepo struct { + *fakeOAuthRepo +} + +func (failingClientRepo) GetClient(ctx context.Context, _ uint64, _ string) (*types.MCPOAuthClient, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + return nil, errors.New("database unavailable") +} + +func TestCloseClientForPrincipalClosesOnlyThatPrincipal(t *testing.T) { + m := NewMCPManager(nil) + defer m.cancel() + service := oauthTestService("svc-1") + other := oauthTestService("svc-2") + alice, bob := webUser("alice"), webUser("bob") + + aliceConn := &disconnectClient{} + bobConn := &disconnectClient{} + aliceOther := &disconnectClient{} + m.clients[cacheKey(service, alice)] = aliceConn + m.clients[cacheKey(service, bob)] = bobConn + m.clients[cacheKey(other, alice)] = aliceOther + aliceConnecting := newPendingConnection(m, cacheKey(service, alice)) + bobConnecting := newPendingConnection(m, cacheKey(service, bob)) + + // Surrounding whitespace must not change which connection is addressed. + require.NoError(t, m.CloseClientForPrincipal(service.ID, types.Principal{Type: " web_user ", ID: "alice "})) + + require.True(t, aliceConn.disconnected.Load()) + require.NotContains(t, m.clients, cacheKey(service, alice), "the closed connection is detached") + require.ErrorIs(t, aliceConnecting.Err(), context.Canceled) + require.NotContains(t, m.connecting, cacheKey(service, alice), "the principal's attempt is retired") + + require.False(t, bobConn.disconnected.Load(), "another principal's connection stays open") + require.Same(t, MCPClient(bobConn), m.clients[cacheKey(service, bob)]) + require.NoError(t, bobConnecting.Err(), "another principal's connection attempt keeps running") + require.Contains(t, m.connecting, cacheKey(service, bob)) + require.False(t, aliceOther.disconnected.Load(), "the principal's connections to other services stay open") +} + +// A service without OAuth has a single connection keyed by the service ID that +// every caller shares; closing one principal's connection must not touch it. +func TestCloseClientForPrincipalLeavesSharedConnectionOpen(t *testing.T) { + m := NewMCPManager(nil) + defer m.cancel() + service := &types.MCPService{ID: "plain", Enabled: true, TransportType: types.MCPTransportHTTPStreamable} + alice := webUser("alice") + require.Equal(t, service.ID, cacheKey(service, alice)) + + shared := &disconnectClient{} + m.clients[service.ID] = shared + connecting := newPendingConnection(m, service.ID) + + require.NoError(t, m.CloseClientForPrincipal(service.ID, alice)) + require.False(t, shared.disconnected.Load()) + require.Contains(t, m.clients, service.ID) + require.NoError(t, connecting.Err()) + + require.NoError(t, m.CloseClientForPrincipal(service.ID, types.Principal{})) + require.False(t, shared.disconnected.Load(), "an empty principal addresses no connection") + require.Contains(t, m.connecting, service.ID) +} + +// After an authorization, the authorizing principal's connection and the +// connections built with a client registration that has since been replaced +// are closed. Connections built with the current registration, and those of +// another tenant, whose registration was not read, stay open. +func TestCloseClientsAfterAuthorizationClosesStaleRegistrations(t *testing.T) { + const tenantID = uint64(7) + service := oauthTestService("svc-1") + alice, bob, carol := webUser("alice"), webUser("bob"), webUser("carol") + repo := newFakeOAuthRepo() + require.NoError(t, repo.SaveClient(context.Background(), &types.MCPOAuthClient{ + TenantID: tenantID, ServiceID: service.ID, ClientID: "client-new", + })) + m := NewMCPManager(repo) + defer m.cancel() + + aliceConn := newRegisteredClient(tenantID, "client-new") + bobConn := newRegisteredClient(tenantID, "client-new") + carolConn := newRegisteredClient(tenantID, "client-old") + otherTenantConn := newRegisteredClient(8, "client-old") + m.clients[cacheKey(service, alice)] = aliceConn + m.clients[cacheKey(service, bob)] = &managedMCPClient{MCPClient: bobConn, cancel: func() {}} + m.clients[cacheKey(service, carol)] = &managedMCPClient{MCPClient: carolConn, cancel: func() {}} + m.clients[cacheKey(service, webUser("dave"))] = otherTenantConn + bobConnecting := newPendingConnection(m, cacheKey(service, bob)) + + require.NoError(t, m.CloseClientsAfterAuthorization(context.Background(), tenantID, service.ID, alice)) + + require.True(t, aliceConn.disconnected.Load(), "the authorizing principal's connection is closed") + require.True(t, carolConn.disconnected.Load(), "a connection with the replaced client ID is closed") + require.False(t, bobConn.disconnected.Load(), "a connection with the current client ID stays open") + require.NoError(t, bobConnecting.Err()) + require.False(t, otherTenantConn.disconnected.Load(), "another tenant's connection stays open") + require.Len(t, m.clients, 2) +} + +// Without the stored registration no connection can be judged current, so the +// whole service is closed, unless the read failed because the caller's +// context ended: closing everything then would cancel other principals' +// requests just because one caller went away. +func TestCloseClientsAfterAuthorizationWhenTheRegistrationIsUnreadable(t *testing.T) { + service := oauthTestService("svc-1") + alice, bob := webUser("alice"), webUser("bob") + setup := func(t *testing.T) (*MCPManager, registeredClient, registeredClient) { + m := NewMCPManager(failingClientRepo{newFakeOAuthRepo()}) + t.Cleanup(m.cancel) + aliceConn, bobConn := newRegisteredClient(7, "client-1"), newRegisteredClient(7, "client-1") + m.clients[cacheKey(service, alice)] = aliceConn + m.clients[cacheKey(service, bob)] = bobConn + return m, aliceConn, bobConn + } + + t.Run("read error closes the service", func(t *testing.T) { + m, aliceConn, bobConn := setup(t) + require.NoError(t, m.CloseClientsAfterAuthorization(context.Background(), 7, service.ID, alice)) + require.True(t, aliceConn.disconnected.Load()) + require.True(t, bobConn.disconnected.Load()) + }) + + t.Run("ended context closes only the principal", func(t *testing.T) { + m, aliceConn, bobConn := setup(t) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + require.NoError(t, m.CloseClientsAfterAuthorization(ctx, 7, service.ID, alice)) + require.True(t, aliceConn.disconnected.Load()) + require.False(t, bobConn.disconnected.Load()) + }) +} + +// liveOAuthService is an OAuth MCP service backed by an in-process MCP server +// that records the bearer token of every tool call. +type liveOAuthService struct { + service *types.MCPService + repo *fakeOAuthRepo + manager *MCPManager + callStarted chan struct{} + release chan struct{} + + mu sync.Mutex + callAuths []string +} + +const liveTenantID = uint64(7) + +func newLiveOAuthService(t *testing.T) *liveOAuthService { + t.Helper() + utils.SetSSRFWhitelistFromRaw("127.0.0.1") + t.Cleanup(utils.ResetSSRFWhitelistForTest) + + live := &liveOAuthService{ + repo: newFakeOAuthRepo(), + callStarted: make(chan struct{}), + release: make(chan struct{}), + } + var startOnce sync.Once + server := sdkserver.NewMCPServer("test", "1") + slow := func(ctx context.Context, _ sdkmcp.CallToolRequest) (*sdkmcp.CallToolResult, error) { + startOnce.Do(func() { close(live.callStarted) }) + select { + case <-live.release: + return sdkmcp.NewToolResultText("done"), nil + case <-ctx.Done(): + return nil, ctx.Err() + } + } + echo := func(context.Context, sdkmcp.CallToolRequest) (*sdkmcp.CallToolResult, error) { + return sdkmcp.NewToolResultText("echo"), nil + } + server.AddTool(sdkmcp.NewTool("slow"), slow) + server.AddTool(sdkmcp.NewTool("echo"), echo) + transport := sdkserver.NewStreamableHTTPServer(server, sdkserver.WithStateLess(true)) + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(body)) + var request struct { + Method string `json:"method"` + } + if json.Unmarshal(body, &request) == nil && request.Method == string(sdkmcp.MethodToolsCall) { + live.mu.Lock() + live.callAuths = append(live.callAuths, r.Header.Get("Authorization")) + live.mu.Unlock() + } + transport.ServeHTTP(w, r) + })) + t.Cleanup(httpServer.Close) + + live.service = oauthTestService("svc-1") + live.service.URL = &httpServer.URL + live.manager = NewMCPManager(live.repo) + t.Cleanup(live.manager.Shutdown) + return live +} + +func (l *liveOAuthService) saveToken(t *testing.T, principal types.Principal, accessToken string) { + t.Helper() + require.NoError(t, l.repo.SaveTokenForPrincipal(context.Background(), &types.MCPOAuthToken{ + TenantID: liveTenantID, + PrincipalType: principal.Type, + PrincipalID: principal.ID, + ServiceID: l.service.ID, + AccessToken: accessToken, + TokenType: "Bearer", + ExpiresAt: time.Now().Add(time.Hour), + })) +} + +func (l *liveOAuthService) connect(ctx context.Context, t *testing.T) MCPClient { + t.Helper() + ctx = context.WithValue(ctx, types.TenantIDContextKey, liveTenantID) + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + client, err := l.manager.GetOrCreateClient(ctx, l.service) + require.NoError(t, err) + return client +} + +func (l *liveOAuthService) connectAs(t *testing.T, principal types.Principal) MCPClient { + t.Helper() + return l.connect(types.WithPrincipal(context.Background(), principal), t) +} + +func (l *liveOAuthService) lastCallAuth() string { + l.mu.Lock() + defer l.mu.Unlock() + if len(l.callAuths) == 0 { + return "" + } + return l.callAuths[len(l.callAuths)-1] +} + +// Closing a connection cancels the requests it has in flight. Recycling the +// connection of a user whose token changed must not cancel a tool call another +// user is running against the same OAuth service. +func TestCloseClientForPrincipalKeepsOtherPrincipalsCallsRunning(t *testing.T) { + live := newLiveOAuthService(t) + alice, bob := webUser("alice"), webUser("bob") + live.saveToken(t, alice, "access-alice") + live.saveToken(t, bob, "access-bob") + aliceConn, bobConn := live.connectAs(t, alice), live.connectAs(t, bob) + require.NotSame(t, aliceConn, bobConn) + + callDone := make(chan error, 1) + go func() { + _, err := bobConn.CallTool(context.Background(), "slow", nil) + callDone <- err + }() + select { + case <-live.callStarted: + case <-time.After(5 * time.Second): + t.Fatal("tool call never reached the server") + } + + require.NoError(t, live.manager.CloseClientForPrincipal(live.service.ID, alice)) + require.False(t, aliceConn.IsConnected()) + require.True(t, bobConn.IsConnected()) + + close(live.release) + select { + case err := <-callDone: + require.NoError(t, err, "the other principal's in-flight call must complete") + case <-time.After(5 * time.Second): + t.Fatal("tool call did not finish") + } + require.NotSame(t, aliceConn, live.connectAs(t, alice), "the closed principal reconnects on next use") + require.Same(t, bobConn, live.connectAs(t, bob)) +} + +// Leaving other principals' connections open after a token change relies on +// connections reading the token from the store on every request rather than +// keeping the one they were opened with. +func TestCachedOAuthConnectionSendsTheCurrentToken(t *testing.T) { + live := newLiveOAuthService(t) + bob := webUser("bob") + live.saveToken(t, bob, "access-bob") + bobConn := live.connectAs(t, bob) + + _, err := bobConn.CallTool(context.Background(), "echo", nil) + require.NoError(t, err) + require.Equal(t, "Bearer access-bob", live.lastCallAuth()) + + live.saveToken(t, bob, "access-bob-rotated") + require.Same(t, bobConn, live.connectAs(t, bob)) + _, err = bobConn.CallTool(context.Background(), "echo", nil) + require.NoError(t, err) + require.Equal(t, "Bearer access-bob-rotated", live.lastCallAuth()) +} + +// An embed chat connects with a per-visitor principal derived from the +// session principal and the visitor ID. Callers that close a principal's +// connection resolve the principal from the same context and must address +// the connection the manager cached. +func TestCloseClientForPrincipalAddressesEmbedVisitorConnections(t *testing.T) { + live := newLiveOAuthService(t) + session := types.Principal{Type: types.PrincipalEmbedSession, ID: "7:channel-1:session-1"} + ctx := types.WithEmbedVisitorID(types.WithPrincipal(context.Background(), session), "visitor-1") + visitor := types.MCPOAuthPrincipalFromContext(ctx) + require.Equal(t, types.PrincipalEmbedVisitor, visitor.Type) + live.saveToken(t, visitor, "access-visitor") + conn := live.connect(ctx, t) + + require.NoError(t, live.manager.CloseClientForPrincipal(live.service.ID, session)) + require.True(t, conn.IsConnected(), "the session principal does not own the visitor's connection") + + require.NoError(t, live.manager.CloseClientForPrincipal(live.service.ID, visitor)) + require.False(t, conn.IsConnected()) +} + +// A real connection reports the client registration it was built with, which +// is what decides whether an authorization leaves it stale. +func TestOAuthConnectionReportsItsClientRegistration(t *testing.T) { + live := newLiveOAuthService(t) + require.NoError(t, live.repo.SaveClient(context.Background(), &types.MCPOAuthClient{ + TenantID: liveTenantID, ServiceID: live.service.ID, ClientID: "client-1", + })) + bob := webUser("bob") + live.saveToken(t, bob, "access-bob") + + tenantID, clientID, ok := oauthClientRegistrationOf(live.connectAs(t, bob)) + require.True(t, ok) + require.Equal(t, liveTenantID, tenantID) + require.Equal(t, "client-1", clientID) +} diff --git a/internal/mcp/oauth_lifecycle.go b/internal/mcp/oauth_lifecycle.go index ec7ed05f..06ddd71e 100644 --- a/internal/mcp/oauth_lifecycle.go +++ b/internal/mcp/oauth_lifecycle.go @@ -65,6 +65,7 @@ type oauthRuntime struct { tenantID uint64 principal types.Principal serviceID string + clientID string handler *transport.OAuthHandler leaseDuration time.Duration } @@ -87,6 +88,7 @@ func newOAuthRuntime( tenantID: tenantID, principal: principal.Normalize(), serviceID: serviceID, + clientID: cfg.ClientID, handler: h, leaseDuration: leaseDuration, } diff --git a/internal/mcp/oauth_manager.go b/internal/mcp/oauth_manager.go index 11aa7480..fc3cd42c 100644 --- a/internal/mcp/oauth_manager.go +++ b/internal/mcp/oauth_manager.go @@ -183,61 +183,78 @@ func (m *OAuthManager) StartAuthorizationForService( return authURL, err } +// OAuthAuthorizationResult describes the authorization attempt a provider +// callback belonged to. +type OAuthAuthorizationResult struct { + // FrontendRedirect is where the browser is sent next. It is set even when + // the callback fails, as soon as the attempt's state has been read. + FrontendRedirect string + // TenantID and ServiceID identify the service the attempt authorized. + TenantID uint64 + ServiceID string + // Principal is the identity the token was issued for. + Principal types.Principal +} + // CompleteAuthorization handles the provider callback: it validates state, // exchanges the code for tokens (PKCE), and persists the per-user token. -// Returns the frontend redirect URL and service ID recorded at -// StartAuthorization time so the caller can recycle any cached transport that -// still carries the previous OAuth client registration. +// The result identifies the authorized service and principal so the caller can +// recycle the cached connections the new authorization leaves outdated. func (m *OAuthManager) CompleteAuthorization( ctx context.Context, state, code string, -) (frontendRedirect, serviceID string, err error) { +) (OAuthAuthorizationResult, error) { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), oauthCallbackTimeout) defer cancel() st, err := m.states.Take(ctx, state) if err != nil { - return "", "", err + return OAuthAuthorizationResult{}, err } - frontendRedirect, err = validateFrontendRedirect(st.FrontendRedirect) + frontendRedirect, err := validateFrontendRedirect(st.FrontendRedirect) if err != nil { - return "/", "", err + return OAuthAuthorizationResult{FrontendRedirect: "/"}, err + } + result := OAuthAuthorizationResult{ + FrontendRedirect: frontendRedirect, + TenantID: st.TenantID, + ServiceID: st.ServiceID, } - serviceID = st.ServiceID principal := st.Principal.Normalize() if !principal.Valid() && st.UserID != "" { principal = types.Principal{Type: types.PrincipalWebUser, ID: st.UserID}.Normalize() } if !principal.Valid() { - return frontendRedirect, serviceID, fmt.Errorf("principal context is missing from OAuth state") + return result, fmt.Errorf("principal context is missing from OAuth state") } + result.Principal = principal service, err := m.serviceRepo.GetByID(ctx, st.TenantID, st.ServiceID) if err != nil { - return frontendRedirect, serviceID, fmt.Errorf("failed to load MCP service: %w", err) + return result, fmt.Errorf("failed to load MCP service: %w", err) } if service == nil { - return frontendRedirect, serviceID, fmt.Errorf("MCP service not found") + return result, fmt.Errorf("MCP service not found") } h, err := m.newHandler(ctx, service, st.TenantID, principal, st.RedirectURI) if err != nil { - return frontendRedirect, serviceID, err + return result, err } // Re-prime the expected state so the library's CSRF check passes after // reconstructing the handler in this separate request. h.SetExpectedState(state) if err := h.ProcessAuthorizationResponse(ctx, code, state, st.CodeVerifier); err != nil { - return frontendRedirect, serviceID, fmt.Errorf("token exchange failed: %w", err) + return result, fmt.Errorf("token exchange failed: %w", err) } if err := m.states.CompleteAttempt(ctx, state); err != nil { - return frontendRedirect, serviceID, fmt.Errorf("failed to record authorization completion: %w", err) + return result, fmt.Errorf("failed to record authorization completion: %w", err) } // ProcessAuthorizationResponse persists the token via the TokenStore. logger.GetLogger(ctx).Infof( "MCP OAuth authorized: service=%s principal=%s", st.ServiceID, principal.StorageID(), ) - return frontendRedirect, serviceID, nil + return result, nil } // IsAuthorizationAttemptComplete reports whether this exact authorization diff --git a/internal/mcp/oauth_manager_test.go b/internal/mcp/oauth_manager_test.go index 963e8fc6..8e55dd2f 100644 --- a/internal/mcp/oauth_manager_test.go +++ b/internal/mcp/oauth_manager_test.go @@ -95,7 +95,7 @@ func TestOAuthManagerKeepsTheRegisteredClientSecret(t *testing.T) { require.Equal(t, "registered-client", stored.ClientID) require.Equal(t, "registered-secret", stored.ClientSecret) - _, _, err = manager.CompleteAuthorization(ctx, state, "code") + _, err = manager.CompleteAuthorization(ctx, state, "code") require.NoError(t, err) require.Equal(t, "registered-secret", tokenRequestSecret)