diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 62fed0cc8b..80bdf0c732 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -83,7 +83,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService, client, configConfig) affiliateRepository := repository.NewAffiliateRepository(client, db) affiliateService := service.NewAffiliateService(affiliateRepository, settingService, apiKeyAuthCacheInvalidator, billingCacheService) - mcpoAuthRepository := repository.NewMCPOAuthRepository(db) + mcpoAuthRepository := repository.NewMCPOAuthRepository(client, db) mcpoAuthService := service.NewMCPOAuthService(mcpoAuthRepository, userRepository) authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository, mcpoAuthService) userService := service.NewUserService(userRepository, settingRepository, apiKeyAuthCacheInvalidator, billingCache) diff --git a/backend/internal/handler/mcp_oauth_handler.go b/backend/internal/handler/mcp_oauth_handler.go index 6c81b63d7e..ffa27b1fc9 100644 --- a/backend/internal/handler/mcp_oauth_handler.go +++ b/backend/internal/handler/mcp_oauth_handler.go @@ -122,11 +122,6 @@ func (h *MCPOAuthHandler) Register(c *gin.Context) { return } client, err := h.oauth.Register(c.Request.Context(), input) - if errors.Is(err, service.ErrMCPOAuthClientLimit) { - c.Header("Retry-After", "3600") - mcpOAuthErrorResponse(c, http.StatusServiceUnavailable, "temporarily_unavailable", "Too many clients are awaiting authorization; retry later") - return - } if mcpOAuthHandleError(c, err, true) { return } @@ -332,7 +327,7 @@ func mcpOAuthHandleError(c *gin.Context, err error, protocol bool) bool { func mcpOAuthReadJSON(c *gin.Context, out any, browser bool) bool { mediaType, _, _ := mime.ParseMediaType(c.GetHeader("Content-Type")) if mediaType == "application/json" { - // Unauthenticated registrations are persisted, so they get a tighter bound. + // Unauthenticated registrations are embedded in client IDs, so they get a tighter bound. limit := int64(4 << 10) if browser { limit = 16 << 10 diff --git a/backend/internal/handler/mcp_oauth_handler_test.go b/backend/internal/handler/mcp_oauth_handler_test.go index 1fc9675fe0..72399d6909 100644 --- a/backend/internal/handler/mcp_oauth_handler_test.go +++ b/backend/internal/handler/mcp_oauth_handler_test.go @@ -25,23 +25,15 @@ const handlerMCPResource = "https://api.example.com/api/v1/mcp" type handlerMCPRepo struct { service.MCPOAuthRepository - client *service.MCPOAuthClient + clientID string reads, writes int grant *service.MCPOAuthGrant - createErr error } -func (r *handlerMCPRepo) CreateClient(context.Context, *service.MCPOAuthClient, int) error { - r.writes++ - return r.createErr -} - -func (r *handlerMCPRepo) GetClient(_ context.Context, id string) (*service.MCPOAuthClient, error) { +// Resolving a client ID needs its signing key, so key loads count as reads. +func (r *handlerMCPRepo) ClientIDKey(context.Context) ([]byte, error) { r.reads++ - if r.client == nil || r.client.ClientID != id { - return nil, service.ErrMCPOAuthNotFound - } - return r.client, nil + return []byte("handler-test-mcp-client-id-key-0"), nil } func (r *handlerMCPRepo) CreateAuthorization(_ context.Context, grant *service.MCPOAuthGrant, _ *service.MCPOAuthCode, _ int) error { r.writes++ @@ -86,12 +78,16 @@ func newHandlerMCPFixture(t *testing.T) (*MCPOAuthHandler, *handlerMCPRepo, *han t.Helper() cfg := &config.Config{MCP: config.MCPConfig{PublicURL: handlerMCPResource}} cfg.Server.FrontendURL = "https://platform.example.com" - repo := &handlerMCPRepo{client: &service.MCPOAuthClient{ClientID: "client-1", ClientName: "Example assistant", RedirectURIs: []string{"https://client.example.com/callback?workspace=one"}, GrantTypes: []string{"authorization_code", "refresh_token"}}} + repo := &handlerMCPRepo{} users := &handlerMCPUsers{user: &service.User{ID: 7, Role: service.RoleAdmin, Status: service.StatusActive, TotpEnabled: true}} settings := service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyStepUpEnabled: "true"}}, cfg) cache := &handlerMCPCache{} totp := service.NewTotpService(users, nil, cache, settings, nil, nil) - return NewMCPOAuthHandler(service.NewMCPOAuthService(repo, users), totp, service.NewUserService(users, nil, nil, nil), settings, cfg), repo, users, cache + oauth := service.NewMCPOAuthService(repo, users) + client, err := oauth.Register(context.Background(), service.MCPOAuthRegisterInput{ClientName: "Example assistant", RedirectURIs: []string{"https://client.example.com/callback?workspace=one"}}) + require.NoError(t, err) + repo.clientID, repo.reads = client.ClientID, 0 + return NewMCPOAuthHandler(oauth, totp, service.NewUserService(users, nil, nil, nil), settings, cfg), repo, users, cache } func handlerMCPContext(t *testing.T, method, target, body, contentType string) (*gin.Context, *httptest.ResponseRecorder) { t.Helper() @@ -109,9 +105,9 @@ func handlerMCPSubject(c *gin.Context, role string) { c.Set(string(middleware.ContextKeyUserRole), role) c.Set(middleware.ContextKeySessionID, "browser-session-7") } -func handlerMCPAuthorization() service.MCPOAuthAuthorizeInput { +func handlerMCPAuthorization(clientID string) service.MCPOAuthAuthorizeInput { digest := sha256.Sum256([]byte(strings.Repeat("v", 43))) - return service.MCPOAuthAuthorizeInput{ResponseType: "code", ClientID: "client-1", RedirectURI: "https://client.example.com/callback?workspace=one", Scope: "mcp", State: "a+b&c=d", CodeChallenge: base64.RawURLEncoding.EncodeToString(digest[:]), CodeChallengeMethod: "S256", Resource: handlerMCPResource} + return service.MCPOAuthAuthorizeInput{ResponseType: "code", ClientID: clientID, RedirectURI: "https://client.example.com/callback?workspace=one", Scope: "mcp", State: "a+b&c=d", CodeChallenge: base64.RawURLEncoding.EncodeToString(digest[:]), CodeChallengeMethod: "S256", Resource: handlerMCPResource} } func handlerMCPBody(t *testing.T, input any) string { t.Helper() @@ -346,7 +342,7 @@ func TestMCPOAuthHandlerTokenEndpointsRejectConfidentialAuthentication(t *testin func TestMCPOAuthHandlerPreviewFrontendContract(t *testing.T) { h, repo, _, _ := newHandlerMCPFixture(t) - input := handlerMCPAuthorization() + input := handlerMCPAuthorization(repo.clientID) query := url.Values{"response_type": {input.ResponseType}, "client_id": {input.ClientID}, "redirect_uri": {input.RedirectURI}, "scope": {input.Scope}, "state": {input.State}, "code_challenge": {input.CodeChallenge}, "code_challenge_method": {input.CodeChallengeMethod}, "resource": {input.Resource}, "timezone": {"Asia/Shanghai"}} c, rec := handlerMCPContext(t, http.MethodGet, "/user/mcp/authorize?"+query.Encode(), "", "") handlerMCPSubject(c, service.RoleUser) @@ -355,7 +351,7 @@ func TestMCPOAuthHandlerPreviewFrontendContract(t *testing.T) { require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) body := handlerMCPJSON(t, rec) require.Equal(t, float64(0), body["code"]) - require.Equal(t, map[string]any{"client_id": "client-1", "client_name": "Example assistant", "redirect_uri": input.RedirectURI, "resource": handlerMCPResource, "scope": "mcp"}, body["data"]) + require.Equal(t, map[string]any{"client_id": repo.clientID, "client_name": "Example assistant", "redirect_uri": input.RedirectURI, "resource": handlerMCPResource, "scope": "mcp"}, body["data"]) require.Zero(t, repo.writes) query.Add("redirect_uri", "https://attacker.example/callback") c, rec = handlerMCPContext(t, http.MethodGet, "/user/mcp/authorize?"+query.Encode(), "", "") @@ -384,7 +380,7 @@ func TestMCPOAuthHandlerAdminDecisionGatesBeforePersistence(t *testing.T) { h, repo, users, cache := newHandlerMCPFixture(t) users.user.TotpEnabled = tt.totp cache.granted, cache.err = tt.granted, tt.cacheErr - input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(), Approved: true, Scope: service.MCPScopeAdmin} + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin} c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") handlerMCPSubject(c, tt.role) c.Set("auth_method", tt.authMethod) @@ -418,7 +414,7 @@ func TestMCPOAuthHandlerAdminWriteAlwaysRequiresStepUp(t *testing.T) { h.settings = service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyStepUpEnabled: "false"}}, h.cfg) users.user.TotpEnabled = tt.totp cache.granted = tt.granted - input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: tt.readOnly} + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: tt.readOnly} c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") handlerMCPSubject(c, service.RoleAdmin) h.Decide(c) @@ -429,22 +425,24 @@ func TestMCPOAuthHandlerAdminWriteAlwaysRequiresStepUp(t *testing.T) { } } -func TestMCPOAuthHandlerRegistrationCapacityIsTemporary(t *testing.T) { +func TestMCPOAuthHandlerRegistrationPersistsNothing(t *testing.T) { h, repo, _, _ := newHandlerMCPFixture(t) - repo.createErr = service.ErrMCPOAuthClientLimit - c, rec := handlerMCPContext(t, http.MethodPost, "/api/v1/mcp/oauth/register", `{"redirect_uris":["https://client.example.com/cb"]}`, "application/json") + c, rec := handlerMCPContext(t, http.MethodPost, "/api/v1/mcp/oauth/register", `{"client_name":"Example assistant","redirect_uris":["https://client.example.com/cb"]}`, "application/json") h.Register(c) - require.Equal(t, http.StatusServiceUnavailable, rec.Code) - require.Equal(t, "temporarily_unavailable", handlerMCPJSON(t, rec)["error"]) - require.NotEmpty(t, rec.Header().Get("Retry-After")) + require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String()) require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + body := handlerMCPJSON(t, rec) + require.True(t, strings.HasPrefix(body["client_id"].(string), "mcp_client_")) + require.NotEqual(t, repo.clientID, body["client_id"]) + require.Equal(t, []any{"https://client.example.com/cb"}, body["redirect_uris"]) + require.Zero(t, repo.writes) } func TestMCPOAuthHandlerAdminApprovalUsesBrowserSession(t *testing.T) { h, repo, _, cache := newHandlerMCPFixture(t) cache.granted = true readOnly := false - input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: &readOnly} + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: &readOnly} c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") handlerMCPSubject(c, service.RoleAdmin) h.Decide(c) @@ -467,7 +465,7 @@ func TestMCPOAuthHandlerAdminApprovalUsesBrowserSession(t *testing.T) { func TestMCPOAuthHandlerDenialSkipsStepUpAndPersistence(t *testing.T) { h, repo, _, cache := newHandlerMCPFixture(t) cache.err = errors.New("must not be called") - input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(), Approved: false, Scope: service.MCPScopeAdmin} + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: false, Scope: service.MCPScopeAdmin} c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") handlerMCPSubject(c, service.RoleUser) h.Decide(c) diff --git a/backend/internal/managementmcp/server_test.go b/backend/internal/managementmcp/server_test.go index 5dbae89bae..e957d15b45 100644 --- a/backend/internal/managementmcp/server_test.go +++ b/backend/internal/managementmcp/server_test.go @@ -379,7 +379,9 @@ func TestMCPToolResultIsReturnedOnceAndBoundedAfterEncoding(t *testing.T) { content, ok := toolResult["content"].([]any) require.True(t, ok) require.Len(t, content, 1) - require.JSONEq(t, `{"http_status":200,"result":{"data":{"name":"ok"}}}`, rpcObject(t, content[0])["text"].(string)) + text, ok := rpcObject(t, content[0])["text"].(string) + require.True(t, ok) + require.JSONEq(t, `{"http_status":200,"result":{"data":{"name":"ok"}}}`, text) // Under the capture limit as received, but HTML escaping expands it 6x. payload = `{"data":"` + strings.Repeat("<", maxResultBytes/3) + `"}` diff --git a/backend/internal/repository/mcp_oauth.go b/backend/internal/repository/mcp_oauth.go index 30022c5d9a..013a9b0697 100644 --- a/backend/internal/repository/mcp_oauth.go +++ b/backend/internal/repository/mcp_oauth.go @@ -3,112 +3,51 @@ package repository import ( "context" "database/sql" - "encoding/json" "errors" + "sync/atomic" "time" + dbent "github.com/Wei-Shaw/sub2api/ent" "github.com/Wei-Shaw/sub2api/internal/service" - "github.com/lib/pq" ) -type mcpOAuthRepository struct{ db *sql.DB } +const mcpOAuthClientIDKeyName = "mcp_oauth_client_id_key" -func NewMCPOAuthRepository(db *sql.DB) service.MCPOAuthRepository { - return &mcpOAuthRepository{db: db} +type mcpOAuthRepository struct { + client *dbent.Client + db *sql.DB + clientIDKey atomic.Pointer[[]byte] } -func (r *mcpOAuthRepository) CreateClient(ctx context.Context, client *service.MCPOAuthClient, pendingLimit int) error { - redirects, err := json.Marshal(client.RedirectURIs) - if err != nil { - return err - } - grants, err := json.Marshal(client.GrantTypes) - if err != nil { - return err - } - // Registration is unauthenticated, so it performs bounded retention work and - // caps clients awaiting authorization. Active authorizations protect their - // client registration; used refresh hashes remain for the entire grant - // lifetime so replay detection is never shortened by cleanup. - now := time.Unix(client.ClientIDIssuedAt, 0).UTC() - pendingSince := now.Add(-service.MCPOAuthPendingClientLifetime) - tx, err := r.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted}) - if err != nil { - return err - } - defer func() { _ = tx.Rollback() }() - // Serialize registrations so concurrent requests cannot overshoot the cap. - if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtext('mcp_oauth_client_registration'))`); err != nil { - return err - } - if _, err := tx.ExecContext(ctx, `DELETE FROM mcp_oauth_grants WHERE id IN (SELECT id FROM mcp_oauth_grants WHERE expires_at<$1 ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED)`, now.Add(-7*24*time.Hour)); err != nil { - return err - } - rows, err := tx.QueryContext(ctx, `SELECT c.client_id FROM mcp_oauth_clients c WHERE c.created_at<$1 AND NOT EXISTS (SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id) ORDER BY c.created_at LIMIT 100 FOR UPDATE SKIP LOCKED`, pendingSince) - if err != nil { - return err - } - var staleClientIDs []string - for rows.Next() { - var id string - if err := rows.Scan(&id); err != nil { - _ = rows.Close() - return err - } - staleClientIDs = append(staleClientIDs, id) - } - if err := rows.Err(); err != nil { - _ = rows.Close() - return err - } - if err := rows.Close(); err != nil { - return err - } - if len(staleClientIDs) != 0 { - // The second statement gets a fresh READ COMMITTED snapshot after the - // client rows are locked. A concurrent consent that committed just before - // those locks must protect its newly inserted grant from client cleanup. - if _, err := tx.ExecContext(ctx, `DELETE FROM mcp_oauth_clients c WHERE c.client_id=ANY($1) AND NOT EXISTS (SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id)`, pq.Array(staleClientIDs)); err != nil { - return err - } - } - var pending int - if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM mcp_oauth_clients c WHERE c.created_at>=$1 AND NOT EXISTS (SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id)`, pendingSince).Scan(&pending); err != nil { - return err - } - if pending >= pendingLimit { - // Keep the retention work so capacity recovers as registrations expire. - if err := tx.Commit(); err != nil { - return err - } - return service.ErrMCPOAuthClientLimit - } - if _, err := tx.ExecContext(ctx, `INSERT INTO mcp_oauth_clients (client_id,client_name,redirect_uris,grant_types,created_at) VALUES ($1,$2,$3,$4,$5)`, client.ClientID, client.ClientName, string(redirects), string(grants), now); err != nil { - return err - } - return tx.Commit() +func NewMCPOAuthRepository(client *dbent.Client, db *sql.DB) service.MCPOAuthRepository { + return &mcpOAuthRepository{client: client, db: db} } -func (r *mcpOAuthRepository) GetClient(ctx context.Context, id string) (*service.MCPOAuthClient, error) { - client := &service.MCPOAuthClient{TokenEndpointAuthMethod: "none", ResponseTypes: []string{"code"}} - var redirects, grants []byte - var createdAt time.Time - err := r.db.QueryRowContext(ctx, `SELECT client_id,client_name,redirect_uris,grant_types,created_at FROM mcp_oauth_clients WHERE client_id=$1`, id). - Scan(&client.ClientID, &client.ClientName, &redirects, &grants, &createdAt) +// ClientIDKey loads the key that signs stateless client IDs, creating it on +// first use. It is persisted so issued client IDs and grants survive restarts, +// and instances racing to create it converge on the stored value. +func (r *mcpOAuthRepository) ClientIDKey(ctx context.Context) ([]byte, error) { + if key := r.clientIDKey.Load(); key != nil { + return *key, nil + } + value, _, err := getOrCreateGeneratedSecuritySecret(ctx, r.client, mcpOAuthClientIDKeyName, 32) if err != nil { - return nil, mcpOAuthSQLError(err) - } - if err := json.Unmarshal(redirects, &client.RedirectURIs); err != nil { return nil, err } - if err := json.Unmarshal(grants, &client.GrantTypes); err != nil { - return nil, err - } - client.ClientIDIssuedAt = createdAt.Unix() - return client, nil + key := []byte(value) + r.clientIDKey.Store(&key) + return key, nil } func (r *mcpOAuthRepository) CreateAuthorization(ctx context.Context, grant *service.MCPOAuthGrant, code *service.MCPOAuthCode, limit int) error { + // Grants are the only rows that outlive a request, so each new one performs + // bounded retention work. It runs before the owner row is locked, keeping + // cascaded deletes from blocking other updates to that user. Used refresh + // hashes remain for the entire grant lifetime so replay detection is never + // shortened by cleanup. + if _, err := r.db.ExecContext(ctx, `DELETE FROM mcp_oauth_grants WHERE id IN (SELECT id FROM mcp_oauth_grants WHERE expires_at<$1 ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED)`, grant.CreatedAt.Add(-7*24*time.Hour)); err != nil { + return err + } tx, err := r.db.BeginTx(ctx, nil) if err != nil { return err @@ -126,8 +65,8 @@ func (r *mcpOAuthRepository) CreateAuthorization(ctx context.Context, grant *ser if count >= limit { return service.ErrMCPOAuthGrantLimit } - _, err = tx.ExecContext(ctx, `INSERT INTO mcp_oauth_grants (id,client_id,user_id,token_version,resource,scope,read_only,created_at,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, - grant.ID, grant.ClientID, grant.UserID, grant.TokenVersion, grant.Resource, grant.Scope, grant.ReadOnly, grant.CreatedAt, grant.ExpiresAt) + _, err = tx.ExecContext(ctx, `INSERT INTO mcp_oauth_grants (id,client_id,client_name,user_id,token_version,resource,scope,read_only,created_at,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, + grant.ID, grant.ClientID, grant.ClientName, grant.UserID, grant.TokenVersion, grant.Resource, grant.Scope, grant.ReadOnly, grant.CreatedAt, grant.ExpiresAt) if err != nil { return err } @@ -159,7 +98,7 @@ func (r *mcpOAuthRepository) GetCredential(ctx context.Context, hash string) (*s return credential, nil } -const mcpOAuthGrantColumns = `g.id,g.client_id,c.client_name,g.user_id,g.token_version,g.resource,g.scope,g.read_only,g.created_at,g.expires_at,g.last_used_at,g.revoked_at` +const mcpOAuthGrantColumns = `id,client_id,client_name,user_id,token_version,resource,scope,read_only,created_at,expires_at,last_used_at,revoked_at` func scanMCPOAuthGrant(row interface{ Scan(...any) error }) (*service.MCPOAuthGrant, error) { grant := &service.MCPOAuthGrant{} @@ -171,11 +110,11 @@ func scanMCPOAuthGrant(row interface{ Scan(...any) error }) (*service.MCPOAuthGr } func (r *mcpOAuthRepository) GetGrant(ctx context.Context, id string) (*service.MCPOAuthGrant, error) { - return scanMCPOAuthGrant(r.db.QueryRowContext(ctx, `SELECT `+mcpOAuthGrantColumns+` FROM mcp_oauth_grants g JOIN mcp_oauth_clients c ON c.client_id=g.client_id WHERE g.id=$1`, id)) + return scanMCPOAuthGrant(r.db.QueryRowContext(ctx, `SELECT `+mcpOAuthGrantColumns+` FROM mcp_oauth_grants WHERE id=$1`, id)) } func (r *mcpOAuthRepository) ListGrants(ctx context.Context, userID int64) ([]*service.MCPOAuthGrant, error) { - rows, err := r.db.QueryContext(ctx, `SELECT `+mcpOAuthGrantColumns+` FROM mcp_oauth_grants g JOIN mcp_oauth_clients c ON c.client_id=g.client_id WHERE g.user_id=$1 ORDER BY g.created_at DESC`, userID) + rows, err := r.db.QueryContext(ctx, `SELECT `+mcpOAuthGrantColumns+` FROM mcp_oauth_grants WHERE user_id=$1 ORDER BY created_at DESC`, userID) if err != nil { return nil, err } diff --git a/backend/internal/repository/mcp_oauth_integration_test.go b/backend/internal/repository/mcp_oauth_integration_test.go index 6682a08c0b..c58cdb62a5 100644 --- a/backend/internal/repository/mcp_oauth_integration_test.go +++ b/backend/internal/repository/mcp_oauth_integration_test.go @@ -14,7 +14,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/service" - "github.com/lib/pq" "github.com/stretchr/testify/require" ) @@ -33,18 +32,13 @@ type mcpOAuthIntegrationFixture struct { func newMCPOAuthIntegrationFixture(t *testing.T, ctx context.Context) mcpOAuthIntegrationFixture { t.Helper() user := mustCreateUser(t, testEntClient(t), &service.User{}) - repo := NewMCPOAuthRepository(integrationDB) + repo := NewMCPOAuthRepository(integrationEntClient, integrationDB) oauth := service.NewMCPOAuthService(repo, NewUserRepository(integrationEntClient, integrationDB)) - var clientID string t.Cleanup(func() { cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _, err := integrationDB.ExecContext(cleanupCtx, `DELETE FROM users WHERE id=$1`, user.ID) require.NoError(t, err) - if clientID != "" { - _, err = integrationDB.ExecContext(cleanupCtx, `DELETE FROM mcp_oauth_clients WHERE client_id=$1`, clientID) - require.NoError(t, err) - } }) const redirectURI = "https://client.example/callback?channel=desktop" @@ -53,10 +47,7 @@ func newMCPOAuthIntegrationFixture(t *testing.T, ctx context.Context) mcpOAuthIn TokenEndpointAuthMethod: "none", }) require.NoError(t, err) - clientID = client.ClientID - registered, err := repo.GetClient(ctx, clientID) - require.NoError(t, err) - require.Equal(t, client, registered) + clientID := client.ClientID verifier := strings.Repeat("v", 64) challenge := sha256.Sum256([]byte(verifier)) @@ -84,6 +75,8 @@ func newMCPOAuthIntegrationFixture(t *testing.T, ctx context.Context) mcpOAuthIn require.Equal(t, service.MCPScopeUser, grants[0].Scope) require.True(t, grants[0].ReadOnly) require.False(t, grants[0].Invalidated) + require.Equal(t, clientID, grants[0].ClientID) + require.Equal(t, client.ClientName, grants[0].ClientName) return mcpOAuthIntegrationFixture{ oauth: oauth, repo: repo, userID: user.ID, grantID: grants[0].ID, input: service.MCPOAuthTokenInput{ @@ -244,25 +237,37 @@ func TestMCPOAuthIntegrationAccountChangesRevokeGrantsPersistently(t *testing.T) requireMCPIntegrationInvalidGrant(t, err) } -func TestMCPOAuthIntegrationRegistrationStopsAtPendingLimit(t *testing.T) { +func TestMCPOAuthIntegrationClientIDKeyConvergesAcrossInstances(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() - repo := NewMCPOAuthRepository(integrationDB) - var pending int - require.NoError(t, integrationDB.QueryRowContext(ctx, - `SELECT COUNT(*) FROM mcp_oauth_clients c WHERE c.created_at>=$1 AND NOT EXISTS (SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id)`, - time.Now().Add(-service.MCPOAuthPendingClientLifetime)).Scan(&pending)) - ids := []string{"mcp_client_pending_limit_a", "mcp_client_pending_limit_b"} - t.Cleanup(func() { - _, err := integrationDB.ExecContext(context.Background(), `DELETE FROM mcp_oauth_clients WHERE client_id=ANY($1)`, pq.Array(ids)) - require.NoError(t, err) - }) - newClient := func(id string) *service.MCPOAuthClient { - return &service.MCPOAuthClient{ClientID: id, ClientName: "Pending", RedirectURIs: []string{"https://client.example/cb"}, - GrantTypes: []string{"authorization_code"}, ClientIDIssuedAt: time.Now().Unix()} + // Start without a key so the instances race to create it. + _, err := integrationDB.ExecContext(ctx, `DELETE FROM security_secrets WHERE key=$1`, mcpOAuthClientIDKeyName) + require.NoError(t, err) + const instances = 8 + keys := make([][]byte, instances) + errs := make([]error, instances) + start := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < instances; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + keys[i], errs[i] = NewMCPOAuthRepository(integrationEntClient, integrationDB).ClientIDKey(ctx) + }(i) } - require.NoError(t, repo.CreateClient(ctx, newClient(ids[0]), pending+1)) - require.ErrorIs(t, repo.CreateClient(ctx, newClient(ids[1]), pending+1), service.ErrMCPOAuthClientLimit) - _, err := repo.GetClient(ctx, ids[1]) - require.ErrorIs(t, err, service.ErrMCPOAuthNotFound) + close(start) + wg.Wait() + for i := 0; i < instances; i++ { + require.NoError(t, errs[i]) + require.GreaterOrEqual(t, len(keys[i]), 32) + require.Equal(t, keys[0], keys[i]) + } + + // A client registered by one instance is accepted by another. + users := NewUserRepository(integrationEntClient, integrationDB) + client, err := service.NewMCPOAuthService(NewMCPOAuthRepository(integrationEntClient, integrationDB), users).Register(ctx, service.MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) + require.NoError(t, err) + _, err = service.NewMCPOAuthService(NewMCPOAuthRepository(integrationEntClient, integrationDB), users).Token(ctx, service.MCPOAuthTokenInput{GrantType: "authorization_code", ClientID: client.ClientID}, mcpIntegrationResource) + requireMCPIntegrationInvalidGrant(t, err) } diff --git a/backend/internal/repository/mcp_oauth_test.go b/backend/internal/repository/mcp_oauth_test.go index 83fdcdc00c..ace5c3ef27 100644 --- a/backend/internal/repository/mcp_oauth_test.go +++ b/backend/internal/repository/mcp_oauth_test.go @@ -5,46 +5,45 @@ package repository import ( "context" "errors" + "strings" "testing" "time" "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/ent/securitysecret" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" ) -func TestMCPOAuthRepositoryRegistrationPrunesOnlyOldUnreferencedDataInBatches(t *testing.T) { - for _, atLimit := range []bool{false, true} { - t.Run(map[bool]string{false: "create", true: "at pending limit"}[atLimit], func(t *testing.T) { - db, mock, err := sqlmock.New() - require.NoError(t, err) - defer db.Close() - repo := NewMCPOAuthRepository(db) - now := time.Unix(1800000000, 0).UTC() - pendingSince := now.Add(-service.MCPOAuthPendingClientLifetime) - client := &service.MCPOAuthClient{ClientID: "client", ClientName: "Client", RedirectURIs: []string{"https://client.example/cb"}, GrantTypes: []string{"authorization_code", "refresh_token"}, ClientIDIssuedAt: now.Unix()} - pending := 999 - if atLimit { - pending = 1000 - } - mock.ExpectBegin() - mock.ExpectExec(`SELECT pg_advisory_xact_lock\(hashtext\('mcp_oauth_client_registration'\)\)`).WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec(`DELETE FROM mcp_oauth_grants WHERE id IN \(SELECT id FROM mcp_oauth_grants WHERE expires_at<\$1 ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED\)`).WithArgs(now.Add(-7 * 24 * time.Hour)).WillReturnResult(sqlmock.NewResult(0, 2)) - mock.ExpectQuery(`SELECT c.client_id FROM mcp_oauth_clients c WHERE c.created_at<\$1 AND NOT EXISTS \(SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id\) ORDER BY c.created_at LIMIT 100 FOR UPDATE SKIP LOCKED`).WithArgs(pendingSince).WillReturnRows(sqlmock.NewRows([]string{"client_id"}).AddRow("stale-client")) - mock.ExpectExec(`DELETE FROM mcp_oauth_clients c WHERE c.client_id=ANY\(\$1\) AND NOT EXISTS \(SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id\)`).WithArgs(`{"stale-client"}`).WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectQuery(`SELECT COUNT\(\*\) FROM mcp_oauth_clients c WHERE c.created_at>=\$1 AND NOT EXISTS \(SELECT 1 FROM mcp_oauth_grants g WHERE g.client_id=c.client_id\)`).WithArgs(pendingSince).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(pending)) - if atLimit { - // Cleanup still commits so capacity recovers; nothing is inserted. - mock.ExpectCommit() - require.ErrorIs(t, repo.CreateClient(context.Background(), client, 1000), service.ErrMCPOAuthClientLimit) - } else { - mock.ExpectExec(`INSERT INTO mcp_oauth_clients`).WithArgs(client.ClientID, client.ClientName, `["https://client.example/cb"]`, `["authorization_code","refresh_token"]`, now).WillReturnResult(sqlmock.NewResult(0, 1)) - mock.ExpectCommit() - require.NoError(t, repo.CreateClient(context.Background(), client, 1000)) - } - require.NoError(t, mock.ExpectationsWereMet()) - }) - } +func TestMCPOAuthRepositoryClientIDKeyIsPersistedAndCached(t *testing.T) { + ctx := context.Background() + client := newSecuritySecretTestClient(t) + repo := NewMCPOAuthRepository(client, nil) + key, err := repo.ClientIDKey(ctx) + require.NoError(t, err) + require.Len(t, key, 64) + other, err := NewMCPOAuthRepository(client, nil).ClientIDKey(ctx) + require.NoError(t, err) + require.Equal(t, key, other, "instances must share the stored key") + _, err = client.SecuritySecret.Delete().Where(securitysecret.KeyEQ(mcpOAuthClientIDKeyName)).Exec(ctx) + require.NoError(t, err) + cached, err := repo.ClientIDKey(ctx) + require.NoError(t, err) + require.Equal(t, key, cached, "a loaded key is served from memory") +} + +func TestMCPOAuthRepositoryClientIDKeyDoesNotCacheInvalidSecret(t *testing.T) { + ctx := context.Background() + client := newSecuritySecretTestClient(t) + require.NoError(t, client.SecuritySecret.Create().SetKey(mcpOAuthClientIDKeyName).SetValue("short").Exec(ctx)) + repo := NewMCPOAuthRepository(client, nil) + _, err := repo.ClientIDKey(ctx) + require.Error(t, err) + valid := strings.Repeat("c", 64) + require.NoError(t, client.SecuritySecret.Update().Where(securitysecret.KeyEQ(mcpOAuthClientIDKeyName)).SetValue(valid).Exec(ctx)) + key, err := repo.ClientIDKey(ctx) + require.NoError(t, err) + require.Equal(t, []byte(valid), key) } func TestMCPOAuthRepositoryConsumptionCommitsReplayRevocation(t *testing.T) { @@ -53,7 +52,7 @@ func TestMCPOAuthRepositoryConsumptionCommitsReplayRevocation(t *testing.T) { db, mock, err := sqlmock.New() require.NoError(t, err) defer db.Close() - repo := NewMCPOAuthRepository(db) + repo := NewMCPOAuthRepository(nil, db) now := time.Now().UTC() used := now.Add(-time.Minute) mock.ExpectBegin() @@ -87,7 +86,7 @@ func TestMCPOAuthRepositoryConsumptionAndIssuanceAreOneTransaction(t *testing.T) db, mock, err := sqlmock.New() require.NoError(t, err) defer db.Close() - repo := NewMCPOAuthRepository(db) + repo := NewMCPOAuthRepository(nil, db) now := time.Now().UTC() access := &service.MCPOAuthCredential{Hash: "access-digest", GrantID: "grant", Kind: "access", ExpiresAt: now.Add(10 * time.Minute)} refresh := &service.MCPOAuthCredential{Hash: "refresh-digest", GrantID: "grant", Kind: "refresh", ExpiresAt: now.Add(time.Hour)} @@ -131,7 +130,7 @@ func TestMCPOAuthRepositoryRejectsExpiredAndRevokedFamilies(t *testing.T) { for _, revoked := range []bool{false, true} { db, mock, err := sqlmock.New() require.NoError(t, err) - repo := NewMCPOAuthRepository(db) + repo := NewMCPOAuthRepository(nil, db) now := time.Now().UTC() var revokedAt *time.Time expiry := now.Add(-time.Second) @@ -155,14 +154,16 @@ func TestMCPOAuthRepositoryAuthorizationSerializesLimit(t *testing.T) { db, mock, err := sqlmock.New() require.NoError(t, err) defer db.Close() - repo := NewMCPOAuthRepository(db) + repo := NewMCPOAuthRepository(nil, db) now := time.Now().UTC() - grant := &service.MCPOAuthGrant{ID: "grant", ClientID: "client", UserID: 7, TokenVersion: 42, Resource: "https://example.com/mcp", Scope: "user", ReadOnly: true, CreatedAt: now, ExpiresAt: now.Add(time.Hour)} + grant := &service.MCPOAuthGrant{ID: "grant", ClientID: "client", ClientName: "Client", UserID: 7, TokenVersion: 42, Resource: "https://example.com/mcp", Scope: "user", ReadOnly: true, CreatedAt: now, ExpiresAt: now.Add(time.Hour)} code := &service.MCPOAuthCode{Hash: "code-digest", GrantID: grant.ID, ClientID: grant.ClientID, RedirectURI: "https://client.example/cb", Resource: grant.Resource, CodeChallenge: "challenge", ExpiresAt: now.Add(time.Minute)} count := 19 if atLimit { count = 20 } + // Bounded retention runs before the owner row is locked. + mock.ExpectExec(`DELETE FROM mcp_oauth_grants WHERE id IN \(SELECT id FROM mcp_oauth_grants WHERE expires_at<\$1 ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED\)`).WithArgs(now.Add(-7 * 24 * time.Hour)).WillReturnResult(sqlmock.NewResult(0, 2)) mock.ExpectBegin() mock.ExpectQuery(`SELECT id FROM users WHERE id=\$1 AND deleted_at IS NULL FOR UPDATE`).WithArgs(int64(7)).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(7)) mock.ExpectQuery(`SELECT COUNT\(\*\) FROM mcp_oauth_grants WHERE user_id=\$1 AND revoked_at IS NULL AND expires_at>\$2`).WithArgs(int64(7), now).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(count)) @@ -170,7 +171,7 @@ func TestMCPOAuthRepositoryAuthorizationSerializesLimit(t *testing.T) { mock.ExpectRollback() require.ErrorIs(t, repo.CreateAuthorization(context.Background(), grant, code, 20), service.ErrMCPOAuthGrantLimit) } else { - mock.ExpectExec(`INSERT INTO mcp_oauth_grants`).WithArgs(grant.ID, grant.ClientID, grant.UserID, grant.TokenVersion, grant.Resource, grant.Scope, grant.ReadOnly, grant.CreatedAt, grant.ExpiresAt).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`INSERT INTO mcp_oauth_grants`).WithArgs(grant.ID, grant.ClientID, grant.ClientName, grant.UserID, grant.TokenVersion, grant.Resource, grant.Scope, grant.ReadOnly, grant.CreatedAt, grant.ExpiresAt).WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectExec(`INSERT INTO mcp_oauth_codes`).WithArgs(code.Hash, code.GrantID, code.ClientID, code.RedirectURI, code.Resource, code.CodeChallenge, code.ExpiresAt).WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() require.NoError(t, repo.CreateAuthorization(context.Background(), grant, code, 20)) @@ -184,7 +185,7 @@ func TestMCPOAuthRepositoryOwnerAndRevocationBoundaries(t *testing.T) { db, mock, err := sqlmock.New() require.NoError(t, err) defer db.Close() - repo := NewMCPOAuthRepository(db) + repo := NewMCPOAuthRepository(nil, db) now := time.Now().UTC() mock.ExpectExec(`UPDATE mcp_oauth_grants SET revoked_at=COALESCE\(revoked_at,\$3\) WHERE id=\$1 AND user_id=\$2`).WithArgs("grant", int64(8), now).WillReturnResult(sqlmock.NewResult(0, 0)) require.ErrorIs(t, repo.RevokeGrant(context.Background(), 8, "grant", now), service.ErrMCPOAuthNotFound) @@ -197,7 +198,7 @@ func TestMCPOAuthRepositoryRevokeUserGrantsCoversEveryActiveGrant(t *testing.T) db, mock, err := sqlmock.New() require.NoError(t, err) defer db.Close() - repo := NewMCPOAuthRepository(db) + repo := NewMCPOAuthRepository(nil, db) now := time.Now().UTC() mock.ExpectExec(`UPDATE mcp_oauth_grants SET revoked_at=\$2 WHERE user_id=\$1 AND revoked_at IS NULL$`).WithArgs(int64(8), now).WillReturnResult(sqlmock.NewResult(0, 0)) require.NoError(t, repo.RevokeUserGrants(context.Background(), 8, now), "no active grants is not an error") diff --git a/backend/internal/server/routes/mcp_oauth_test.go b/backend/internal/server/routes/mcp_oauth_test.go index 03118a01a8..f677e19c75 100644 --- a/backend/internal/server/routes/mcp_oauth_test.go +++ b/backend/internal/server/routes/mcp_oauth_test.go @@ -29,27 +29,13 @@ import ( // database. SQL locking/rollback behavior is covered by repository unit tests. type mcpOAuthRouteRepo struct { mu sync.Mutex - clients map[string]*service.MCPOAuthClient grants map[string]*service.MCPOAuthGrant codes map[string]*service.MCPOAuthCode credentials map[string]*service.MCPOAuthCredential } -func (r *mcpOAuthRouteRepo) CreateClient(_ context.Context, client *service.MCPOAuthClient, _ int) error { - r.mu.Lock() - defer r.mu.Unlock() - r.clients[client.ClientID] = client - return nil -} - -func (r *mcpOAuthRouteRepo) GetClient(_ context.Context, id string) (*service.MCPOAuthClient, error) { - r.mu.Lock() - defer r.mu.Unlock() - if item := r.clients[id]; item != nil { - copy := *item - return ©, nil - } - return nil, service.ErrMCPOAuthNotFound +func (r *mcpOAuthRouteRepo) ClientIDKey(context.Context) ([]byte, error) { + return []byte("route-test-mcp-client-id-key-000"), nil } func (r *mcpOAuthRouteRepo) CreateAuthorization(_ context.Context, grant *service.MCPOAuthGrant, code *service.MCPOAuthCode, limit int) error { @@ -210,8 +196,8 @@ func (r *mcpOAuthRouteUsers) GetUserAvatar(context.Context, int64) (*service.Use func newMCPRouteOAuthService(role string) (*service.MCPOAuthService, *mcpOAuthRouteRepo, *mcpOAuthRouteUsers) { repo := &mcpOAuthRouteRepo{ - clients: map[string]*service.MCPOAuthClient{}, grants: map[string]*service.MCPOAuthGrant{}, - codes: map[string]*service.MCPOAuthCode{}, credentials: map[string]*service.MCPOAuthCredential{}, + grants: map[string]*service.MCPOAuthGrant{}, codes: map[string]*service.MCPOAuthCode{}, + credentials: map[string]*service.MCPOAuthCredential{}, } users := &mcpOAuthRouteUsers{user: &service.User{ID: 7, Role: role, Status: service.StatusActive, PasswordHash: "test-password", Email: "mcp@example.com"}} return service.NewMCPOAuthService(repo, users), repo, users diff --git a/backend/internal/service/mcp_oauth_service.go b/backend/internal/service/mcp_oauth_service.go index 179d400206..ff2fedefa7 100644 --- a/backend/internal/service/mcp_oauth_service.go +++ b/backend/internal/service/mcp_oauth_service.go @@ -2,11 +2,13 @@ package service import ( "context" + "crypto/hmac" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" + "encoding/json" "errors" "net/url" "strings" @@ -25,12 +27,12 @@ const ( MCPOAuthAccessLifetime = 10 * time.Minute MCPOAuthCodeLifetime = 5 * time.Minute MCPOAuthGrantLifetime = 30 * 24 * time.Hour - // Registration is unauthenticated: clients that never obtain a grant expire - // quickly, and the number awaiting authorization is capped globally. - MCPOAuthPendingClientLifetime = 24 * time.Hour - MCPOAuthPendingClientLimit = 1000 // last_used_at is advisory; writing it once per interval keeps requests read-only. MCPOAuthTouchInterval = time.Minute + + mcpOAuthClientIDPrefix = "mcp_client_" + // Registration bounds keep issued IDs well below this limit. + mcpOAuthClientIDMaxLength = 2048 ) var ( @@ -38,7 +40,6 @@ var ( ErrMCPOAuthNotFound = errors.New("MCP OAuth record not found") ErrMCPOAuthGrantLimit = infraerrors.Conflict("MCP_GRANT_LIMIT", "Revoke an existing MCP authorization before authorizing another client (maximum 20 active authorizations)") ErrMCPOAuthGrantNotFound = infraerrors.NotFound("MCP_GRANT_NOT_FOUND", "MCP authorization not found") - ErrMCPOAuthClientLimit = errors.New("too many MCP OAuth clients are awaiting authorization") ) type MCPOAuthError struct { @@ -157,10 +158,8 @@ type MCPOAuthCredential struct { } type MCPOAuthRepository interface { - // CreateClient returns ErrMCPOAuthClientLimit when the given number of - // recently registered clients without any grant already exists. - CreateClient(context.Context, *MCPOAuthClient, int) error - GetClient(context.Context, string) (*MCPOAuthClient, error) + // ClientIDKey returns the persistent key that signs stateless client IDs. + ClientIDKey(context.Context) ([]byte, error) CreateAuthorization(context.Context, *MCPOAuthGrant, *MCPOAuthCode, int) error GetCode(context.Context, string) (*MCPOAuthCode, error) GetCredential(context.Context, string) (*MCPOAuthCredential, error) @@ -222,19 +221,102 @@ func (s *MCPOAuthService) Register(ctx context.Context, input MCPOAuthRegisterIn if len(input.ResponseTypes) != 0 && (len(input.ResponseTypes) != 1 || input.ResponseTypes[0] != "code") { return nil, mcpOAuthError("invalid_client_metadata", "Only the code response type is supported") } - id, err := mcpOAuthSecret("mcp_client_") + nonce := make([]byte, 16) + if _, err := rand.Read(nonce); err != nil { + return nil, err + } + claims := mcpOAuthClientClaims{Name: input.ClientName, GrantTypes: append([]string(nil), grants...)} + for _, uri := range redirects { + claims.RedirectDigests = append(claims.RedirectDigests, mcpOAuthRedirectDigest(uri)) + } + id, err := s.encodeClientID(ctx, base64.RawURLEncoding.EncodeToString(nonce), &claims) if err != nil { return nil, err } - client := &MCPOAuthClient{ + return &MCPOAuthClient{ ClientID: id, ClientName: input.ClientName, RedirectURIs: redirects, - GrantTypes: append([]string(nil), grants...), ResponseTypes: []string{"code"}, + GrantTypes: claims.GrantTypes, ResponseTypes: []string{"code"}, TokenEndpointAuthMethod: "none", ClientIDIssuedAt: time.Now().UTC().Unix(), + }, nil +} + +// Registration is unauthenticated, so it is never persisted: the client ID is +// the signed metadata itself. Nothing is stored until a user approves a client, +// leaving no storage or shared capacity for anonymous registrations to exhaust. +// Redirect URIs are embedded as digests to keep IDs short enough for URLs. +// +// Format: mcp_client_... +// The random nonce leads, so truncated IDs still tell clients apart. +type mcpOAuthClientClaims struct { + Name string `json:"n"` + RedirectDigests []string `json:"r"` + GrantTypes []string `json:"g"` +} + +func (c *mcpOAuthClientClaims) allowsRedirect(uri string) bool { + return containsMCPString(c.RedirectDigests, mcpOAuthRedirectDigest(uri)) +} + +func mcpOAuthRedirectDigest(uri string) string { + sum := sha256.Sum256([]byte(uri)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func (s *MCPOAuthService) encodeClientID(ctx context.Context, nonce string, claims *mcpOAuthClientClaims) (string, error) { + raw, err := json.Marshal(claims) + if err != nil { + return "", err } - if err := s.repo.CreateClient(ctx, client, MCPOAuthPendingClientLimit); err != nil { + signed := nonce + "." + base64.RawURLEncoding.EncodeToString(raw) + signature, err := s.signClientID(ctx, signed) + if err != nil { + return "", err + } + return mcpOAuthClientIDPrefix + signed + "." + signature, nil +} + +// client verifies a client ID and returns its metadata. IDs that were not +// issued by this server yield ErrMCPOAuthNotFound. +func (s *MCPOAuthService) client(ctx context.Context, id string) (*mcpOAuthClientClaims, error) { + if len(id) > mcpOAuthClientIDMaxLength || !strings.HasPrefix(id, mcpOAuthClientIDPrefix) { + return nil, ErrMCPOAuthNotFound + } + signed := id[len(mcpOAuthClientIDPrefix):] + dot := strings.LastIndexByte(signed, '.') + if dot < 0 { + return nil, ErrMCPOAuthNotFound + } + signed, signature := signed[:dot], signed[dot+1:] + expected, err := s.signClientID(ctx, signed) + if err != nil { return nil, err } - return client, nil + if !hmac.Equal([]byte(signature), []byte(expected)) { + return nil, ErrMCPOAuthNotFound + } + _, payload, ok := strings.Cut(signed, ".") + if !ok { + return nil, ErrMCPOAuthNotFound + } + raw, err := base64.RawURLEncoding.DecodeString(payload) + if err != nil { + return nil, ErrMCPOAuthNotFound + } + var claims mcpOAuthClientClaims + if err := json.Unmarshal(raw, &claims); err != nil { + return nil, ErrMCPOAuthNotFound + } + return &claims, nil +} + +func (s *MCPOAuthService) signClientID(ctx context.Context, payload string) (string, error) { + key, err := s.repo.ClientIDKey(ctx) + if err != nil { + return "", err + } + mac := hmac.New(sha256.New, key) + _, _ = mac.Write([]byte(payload)) + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil } func validMCPClientName(name string) bool { @@ -287,15 +369,15 @@ func validMCPOAuthScope(scope string) bool { return len(fields) == 0 || (len(fields) == 1 && fields[0] == MCPOAuthScope) } -func (s *MCPOAuthService) validateAuthorization(ctx context.Context, userID int64, input MCPOAuthAuthorizeInput, resource string) (*MCPOAuthClient, *User, error) { - client, err := s.repo.GetClient(ctx, input.ClientID) +func (s *MCPOAuthService) validateAuthorization(ctx context.Context, userID int64, input MCPOAuthAuthorizeInput, resource string) (*mcpOAuthClientClaims, *User, error) { + client, err := s.client(ctx, input.ClientID) if errors.Is(err, ErrMCPOAuthNotFound) { return nil, nil, mcpOAuthError("invalid_client", "Unknown client") } if err != nil { return nil, nil, err } - if client == nil || !containsMCPString(client.RedirectURIs, input.RedirectURI) { + if !client.allowsRedirect(input.RedirectURI) { return nil, nil, mcpOAuthError("invalid_request", "redirect_uri must exactly match a registered URI") } if input.ResponseType != "code" { @@ -329,7 +411,7 @@ func (s *MCPOAuthService) Preview(ctx context.Context, userID int64, input MCPOA if err != nil { return nil, err } - return &MCPOAuthConsent{ClientID: client.ClientID, ClientName: client.ClientName, RedirectURI: input.RedirectURI, Resource: resource, Scope: MCPOAuthScope}, nil + return &MCPOAuthConsent{ClientID: input.ClientID, ClientName: client.Name, RedirectURI: input.RedirectURI, Resource: resource, Scope: MCPOAuthScope}, nil } func (s *MCPOAuthService) Decide(ctx context.Context, userID int64, input MCPOAuthConsentInput, resource string) (string, error) { @@ -370,13 +452,13 @@ func (s *MCPOAuthService) Decide(ctx context.Context, userID int64, input MCPOAu return "", err } now := time.Now().UTC() - grant := &MCPOAuthGrant{ID: id, ClientID: client.ClientID, ClientName: client.ClientName, + grant := &MCPOAuthGrant{ID: id, ClientID: input.Authorization.ClientID, ClientName: client.Name, UserID: user.ID, TokenVersion: resolvedTokenVersion(user), Resource: resource, Scope: input.Scope, ReadOnly: true, CreatedAt: now, ExpiresAt: now.Add(MCPOAuthGrantLifetime)} if input.ReadOnly != nil { grant.ReadOnly = *input.ReadOnly } - code := &MCPOAuthCode{Hash: hashMCPOAuthSecret(rawCode), GrantID: grant.ID, ClientID: client.ClientID, + code := &MCPOAuthCode{Hash: hashMCPOAuthSecret(rawCode), GrantID: grant.ID, ClientID: grant.ClientID, RedirectURI: input.Authorization.RedirectURI, Resource: resource, CodeChallenge: input.Authorization.CodeChallenge, ExpiresAt: now.Add(MCPOAuthCodeLifetime)} if err := s.repo.CreateAuthorization(ctx, grant, code, MCPOAuthGrantLimit); err != nil { @@ -388,8 +470,8 @@ func (s *MCPOAuthService) Decide(ctx context.Context, userID int64, input MCPOAu } func (s *MCPOAuthService) Token(ctx context.Context, input MCPOAuthTokenInput, resource string) (*MCPOAuthTokenResponse, error) { - client, err := s.repo.GetClient(ctx, input.ClientID) - if errors.Is(err, ErrMCPOAuthNotFound) || (err == nil && client == nil) { + client, err := s.client(ctx, input.ClientID) + if errors.Is(err, ErrMCPOAuthNotFound) { return nil, mcpOAuthError("invalid_client", "Unknown client") } if err != nil { diff --git a/backend/internal/service/mcp_oauth_service_test.go b/backend/internal/service/mcp_oauth_service_test.go index ec8df8aeb8..8cda7496d4 100644 --- a/backend/internal/service/mcp_oauth_service_test.go +++ b/backend/internal/service/mcp_oauth_service_test.go @@ -20,41 +20,18 @@ import ( type mcpOAuthMemoryRepo struct { mu sync.Mutex - clients map[string]*MCPOAuthClient + clientIDKey []byte grants map[string]*MCPOAuthGrant codes map[string]*MCPOAuthCode credentials map[string]*MCPOAuthCredential touches int } -func (r *mcpOAuthMemoryRepo) CreateClient(_ context.Context, client *MCPOAuthClient, pendingLimit int) error { - r.mu.Lock() - defer r.mu.Unlock() - pending := 0 - for id := range r.clients { - authorized := false - for _, grant := range r.grants { - authorized = authorized || grant.ClientID == id - } - if !authorized { - pending++ - } +func (r *mcpOAuthMemoryRepo) ClientIDKey(context.Context) ([]byte, error) { + if r.clientIDKey == nil { + return []byte("mcp-oauth-service-test-client-id-key"), nil } - if pending >= pendingLimit { - return ErrMCPOAuthClientLimit - } - r.clients[client.ClientID] = client - return nil -} - -func (r *mcpOAuthMemoryRepo) GetClient(_ context.Context, id string) (*MCPOAuthClient, error) { - r.mu.Lock() - defer r.mu.Unlock() - if client := r.clients[id]; client != nil { - copy := *client - return ©, nil - } - return nil, ErrMCPOAuthNotFound + return r.clientIDKey, nil } func (r *mcpOAuthMemoryRepo) CreateAuthorization(_ context.Context, grant *MCPOAuthGrant, code *MCPOAuthCode, limit int) error { @@ -223,7 +200,7 @@ type mcpOAuthFixture struct { func newMCPOAuthFixture(t *testing.T) *mcpOAuthFixture { t.Helper() - r := &mcpOAuthMemoryRepo{clients: map[string]*MCPOAuthClient{}, grants: map[string]*MCPOAuthGrant{}, codes: map[string]*MCPOAuthCode{}, credentials: map[string]*MCPOAuthCredential{}} + r := &mcpOAuthMemoryRepo{grants: map[string]*MCPOAuthGrant{}, codes: map[string]*MCPOAuthCode{}, credentials: map[string]*MCPOAuthCredential{}} u := &mcpOAuthUserRepo{user: &User{ID: 7, Role: RoleUser, Status: StatusActive, Email: "user@example.com", PasswordHash: "original", Concurrency: 3}} s := NewMCPOAuthService(r, u) client, err := s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: "My MCP client", RedirectURIs: []string{"http://127.0.0.1:2345/callback?existing=1", "https://client.example/callback"}}) @@ -544,7 +521,9 @@ func TestMCPOAuthClientRevocationInvalidatesAccessAndRefresh(t *testing.T) { func TestMCPOAuthCodeOnlyClientReceivesNoRefreshToken(t *testing.T) { f := newMCPOAuthFixture(t) - f.r.clients[f.client.ClientID].GrantTypes = []string{"authorization_code"} + client, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: f.client.RedirectURIs, GrantTypes: []string{"authorization_code"}}) + require.NoError(t, err) + f.client, f.authorize.ClientID = client, client.ClientID tokens := f.tokens(t) require.NotEmpty(t, tokens.AccessToken) require.Empty(t, tokens.RefreshToken) @@ -590,17 +569,89 @@ func TestMCPOAuthRegistrationRejectsDisguisedClientNames(t *testing.T) { require.Equal(t, "桌面助手 · Desktop (beta) ✨", client.ClientName) } -func TestMCPOAuthRegistrationStopsAtPendingClientLimit(t *testing.T) { +func TestMCPOAuthRegistrationIsStatelessAndSigned(t *testing.T) { f := newMCPOAuthFixture(t) - f.code(t, "", nil) // An authorized client does not count as pending. - for i := 0; i < MCPOAuthPendingClientLimit; i++ { - f.r.clients[fmt.Sprintf("pending-%d", i)] = &MCPOAuthClient{} + // Anonymous registration persists nothing, so there is no capacity to exhaust. + for i := 0; i < 100; i++ { + _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) + require.NoError(t, err) + } + require.Empty(t, f.r.grants) + require.Empty(t, f.r.codes) + require.Empty(t, f.r.credentials) + twin, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: f.client.ClientName, RedirectURIs: f.client.RedirectURIs}) + require.NoError(t, err) + // The random nonce leads, so even truncated IDs of identical clients differ. + visible := len(mcpOAuthClientIDPrefix) + 22 + require.NotEqual(t, f.client.ClientID[:visible], twin.ClientID[:visible], "identical metadata must still yield distinct clients") + + parts := strings.Split(strings.TrimPrefix(f.client.ClientID, mcpOAuthClientIDPrefix), ".") + require.Len(t, parts, 3) + nonce, payload, signature := parts[0], parts[1], parts[2] + twinNonce, _, _ := strings.Cut(strings.TrimPrefix(twin.ClientID, mcpOAuthClientIDPrefix), ".") + raw, err := base64.RawURLEncoding.DecodeString(payload) + require.NoError(t, err) + renamed := strings.Replace(string(raw), `"n":"My MCP client"`, `"n":"Trusted client"`, 1) + require.NotEqual(t, string(raw), renamed) + foreign, err := NewMCPOAuthService(&mcpOAuthMemoryRepo{clientIDKey: []byte("another-deployment-client-id-key")}, f.u). + Register(context.Background(), MCPOAuthRegisterInput{ClientName: f.client.ClientName, RedirectURIs: f.client.RedirectURIs}) + require.NoError(t, err) + tampered := []byte(f.client.ClientID) + tampered[len(tampered)-1] ^= 1 + for name, id := range map[string]string{ + "forged metadata": mcpOAuthClientIDPrefix + nonce + "." + base64.RawURLEncoding.EncodeToString([]byte(renamed)) + "." + signature, + "swapped nonce": mcpOAuthClientIDPrefix + twinNonce + "." + payload + "." + signature, + "other key": foreign.ClientID, + "bad signature": string(tampered), + "unsigned": mcpOAuthClientIDPrefix + nonce + "." + payload, + "missing prefix": strings.TrimPrefix(f.client.ClientID, mcpOAuthClientIDPrefix), + "oversized": f.client.ClientID + strings.Repeat("A", mcpOAuthClientIDMaxLength), + } { + t.Run(name, func(t *testing.T) { + input := f.authorize + input.ClientID = id + _, err := f.s.Preview(context.Background(), 7, input, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_client") + _, err = f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "authorization_code", ClientID: id}, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_client") + }) } - _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) - require.ErrorIs(t, err, ErrMCPOAuthClientLimit) - require.Len(t, f.r.clients, MCPOAuthPendingClientLimit+1) } +func TestMCPOAuthLargestRegistrationFitsClientIDLimit(t *testing.T) { + f := newMCPOAuthFixture(t) + redirects := make([]string, 10) + for i := range redirects { + redirects[i] = fmt.Sprintf("https://client.example/%d/%s", i, strings.Repeat("p", 2000)) + } + // "<" is JSON-escaped to six bytes, the worst case for an allowed name. + client, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: strings.Repeat("<", 100), RedirectURIs: redirects}) + require.NoError(t, err) + require.LessOrEqual(t, len(client.ClientID), mcpOAuthClientIDMaxLength) + input := f.authorize + input.ClientID, input.RedirectURI = client.ClientID, redirects[9] + preview, err := f.s.Preview(context.Background(), 7, input, mcpTestResource) + require.NoError(t, err) + require.Equal(t, client.ClientName, preview.ClientName) +} + +func TestMCPOAuthClientIDKeyErrorIsNotUnknownClient(t *testing.T) { + f := newMCPOAuthFixture(t) + unavailable := errors.New("database unavailable") + s := NewMCPOAuthService(&mcpOAuthKeyErrorRepo{mcpOAuthMemoryRepo: f.r, err: unavailable}, f.u) + _, err := s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) + require.ErrorIs(t, err, unavailable) + _, err = s.Preview(context.Background(), 7, f.authorize, mcpTestResource) + require.ErrorIs(t, err, unavailable) +} + +type mcpOAuthKeyErrorRepo struct { + *mcpOAuthMemoryRepo + err error +} + +func (r *mcpOAuthKeyErrorRepo) ClientIDKey(context.Context) ([]byte, error) { return nil, r.err } + func TestMCPOAuthAuthenticateThrottlesLastUsedWrites(t *testing.T) { f := newMCPOAuthFixture(t) tokens := f.tokens(t) diff --git a/backend/migrations/249_mcp_oauth.sql b/backend/migrations/249_mcp_oauth.sql index fde8ca68a4..8ba1595a7f 100644 --- a/backend/migrations/249_mcp_oauth.sql +++ b/backend/migrations/249_mcp_oauth.sql @@ -1,17 +1,12 @@ -- OAuth clients use public-client authorization code + S256 PKCE. No client -- secrets, authorization codes, access tokens, or refresh tokens are stored raw. -CREATE TABLE IF NOT EXISTS mcp_oauth_clients ( - client_id VARCHAR(64) PRIMARY KEY, - client_name VARCHAR(100) NOT NULL, - redirect_uris JSONB NOT NULL, - grant_types JSONB NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() -); -CREATE INDEX IF NOT EXISTS idx_mcp_oauth_clients_created ON mcp_oauth_clients(created_at); - +-- Client registration writes nothing: the client ID is signed and carries its +-- own metadata. Rows are created only when a user approves a client, and each +-- grant keeps the client name shown at consent. CREATE TABLE IF NOT EXISTS mcp_oauth_grants ( id VARCHAR(43) PRIMARY KEY, - client_id VARCHAR(64) NOT NULL REFERENCES mcp_oauth_clients(client_id) ON DELETE RESTRICT, + client_id TEXT NOT NULL, + client_name VARCHAR(100) NOT NULL, user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, token_version BIGINT NOT NULL, resource TEXT NOT NULL, @@ -23,13 +18,12 @@ CREATE TABLE IF NOT EXISTS mcp_oauth_grants ( revoked_at TIMESTAMPTZ ); CREATE INDEX IF NOT EXISTS idx_mcp_oauth_grants_user_created ON mcp_oauth_grants(user_id, created_at DESC); -CREATE INDEX IF NOT EXISTS idx_mcp_oauth_grants_client ON mcp_oauth_grants(client_id); CREATE INDEX IF NOT EXISTS idx_mcp_oauth_grants_expiry ON mcp_oauth_grants(expires_at); CREATE TABLE IF NOT EXISTS mcp_oauth_codes ( code_hash VARCHAR(64) PRIMARY KEY, grant_id VARCHAR(43) NOT NULL REFERENCES mcp_oauth_grants(id) ON DELETE CASCADE, - client_id VARCHAR(64) NOT NULL, + client_id TEXT NOT NULL, redirect_uri TEXT NOT NULL, resource TEXT NOT NULL, code_challenge VARCHAR(43) NOT NULL, diff --git a/docs/mcp.md b/docs/mcp.md index 567545c515..c8d7532b0e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -168,4 +168,4 @@ curl 'https://api.example.com/.well-known/oauth-authorization-server' 工具目录位于 `backend/internal/managementmcp/catalog.go`。新增工具应绑定已有管理路由,使用封闭参数 schema,并覆盖权限、资源归属、参数边界及凭证脱敏测试。 -OAuth 存储由 `249_mcp_oauth.sql` 创建。注册时有界清理过期 7 天以上的授权,以及 24 小时前注册且从未获得授权的客户端。24 小时内注册但尚未获得授权的客户端全站最多 1000 个,达到上限后注册返回 503 `temporarily_unavailable`,待旧注册过期后自动恢复。浏览器使用 JWT 保护的 `/api/v1/user/mcp/config` 获取服务端配置的连接地址、`/api/v1/user/mcp/authorize` 预览/决定授权,以及 `/api/v1/user/mcp/grants` 列表、撤销接口。客户端协议端点返回标准 OAuth JSON,浏览器接口沿用平台响应格式。 +OAuth 存储由 `249_mcp_oauth.sql` 创建。动态注册不写数据库:`client_id` 是服务端签名的无状态标识,自带客户端名称、回调 URI 摘要和 grant type,签名密钥首次使用时生成并保存在 `security_secrets`,多实例共享。只有用户同意授权后才写入授权记录,因此匿名注册不会占用存储,也没有可被占满的全站名额。每次新授权时有界清理过期 7 天以上的授权。浏览器使用 JWT 保护的 `/api/v1/user/mcp/config` 获取服务端配置的连接地址、`/api/v1/user/mcp/authorize` 预览/决定授权,以及 `/api/v1/user/mcp/grants` 列表、撤销接口。客户端协议端点返回标准 OAuth JSON,浏览器接口沿用平台响应格式。