From ee71c7f379d56d8b28595beb032883acac8c438d Mon Sep 17 00:00:00 2001 From: haruka <1628615876@qq.com> Date: Wed, 28 Oct 2026 09:30:23 -0400 Subject: [PATCH] fix(backend): harden management MCP per review - Reject JSON-RPC batches and non-object bodies before the SDK; return each tool result once as text and bound the encoded payload (H1). - Enable MCP only when MCP_PUBLIC_URL is set; drop the frontend URL fallback and expose a read-only mcp_enabled public setting (M1). - Expire never-authorized clients after 24h, cap pending registrations globally, aggregate MCP IP limits by IPv6 /64, and limit registration bodies to 4 KiB (M2). - Revoke MCP grants with revoke-all-sessions and always require step-up for administrator write grants (M3). - Rate limit /api/v1/mcp per IP before authentication and write last_used_at at most once per minute (M4). - Persistently revoke grants when an account is disabled or demoted, derive result redaction from SensitiveCredentialKeys, allowlist browser sessions for step-up, audit every MCP read, reject invisible characters in client_name, and document site-root-only deployment (L1-L5, L7). Co-Authored-By: Claude Opus 5.5 --- backend/cmd/server/wire_gen.go | 6 +- backend/internal/config/config.go | 6 +- .../handler/admin/audit_log_handler.go | 8 +- .../handler/admin/setting_handler_update.go | 8 +- backend/internal/handler/dto/settings.go | 1 + backend/internal/handler/mcp_oauth_handler.go | 42 ++++--- .../handler/mcp_oauth_handler_test.go | 67 +++++++++-- backend/internal/handler/setting_handler.go | 1 + backend/internal/managementmcp/auth.go | 2 +- backend/internal/managementmcp/server.go | 57 +++++++--- backend/internal/managementmcp/server_test.go | 83 ++++++++++++++ backend/internal/middleware/rate_limiter.go | 21 +++- .../internal/middleware/rate_limiter_test.go | 40 +++++++ backend/internal/repository/mcp_oauth.go | 42 ++++++- .../repository/mcp_oauth_integration_test.go | 65 +++++++++++ backend/internal/repository/mcp_oauth_test.go | 58 +++++++--- backend/internal/repository/user_repo.go | 12 ++ .../internal/server/middleware/audit_log.go | 6 +- .../server/middleware/audit_log_test.go | 36 ++++++ backend/internal/server/middleware/step_up.go | 28 +++-- .../server/middleware/step_up_test.go | 34 ++++-- backend/internal/server/router.go | 2 +- backend/internal/server/routes/mcp.go | 23 +++- .../internal/server/routes/mcp_oauth_test.go | 35 +++++- .../server/routes/mcp_rate_limit_test.go | 12 +- backend/internal/server/routes/mcp_test.go | 57 ++++++---- backend/internal/service/audit_log.go | 2 + backend/internal/service/auth_service.go | 17 +++ backend/internal/service/mcp_oauth_service.go | 49 ++++++-- .../service/mcp_oauth_service_test.go | 107 +++++++++++++++++- backend/internal/service/setting_public.go | 3 + .../service/setting_service_public_test.go | 25 ++++ backend/internal/service/settings_view.go | 1 + backend/internal/service/wire.go | 4 + deploy/.env.example | 5 +- deploy/config.example.yaml | 8 +- docs/mcp.md | 18 +-- 37 files changed, 833 insertions(+), 158 deletions(-) diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index a59093ed04..62fed0cc8b 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -83,7 +83,9 @@ 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) - authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository) + mcpoAuthRepository := repository.NewMCPOAuthRepository(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) redeemCache := repository.NewRedeemCache(redisClient) redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator, affiliateService) @@ -98,8 +100,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository) authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService, promoService, redeemService, totpService, userAttributeService) userHandler := handler.NewUserHandler(userService, authService, emailService, emailCache, affiliateService, serviceUserPlatformQuotaRepository) - mcpoAuthRepository := repository.NewMCPOAuthRepository(db) - mcpoAuthService := service.NewMCPOAuthService(mcpoAuthRepository, userRepository) mcpoAuthHandler := handler.NewMCPOAuthHandler(mcpoAuthService, totpService, userService, settingService, configConfig) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) usageLogRepository := repository.NewUsageLogRepository(client, db) diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 55b335c304..d270ef9728 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -120,12 +120,16 @@ type SimpleModeConfig struct { } // MCPConfig fixes the public resource URL used by OAuth discovery and tokens. +// Setting it is also the explicit opt-in that enables MCP. type MCPConfig struct { PublicURL string `mapstructure:"public_url"` } +// Enabled reports whether the operator opted in to the management MCP endpoint. +func (c MCPConfig) Enabled() bool { return strings.TrimSpace(c.PublicURL) != "" } + // Validate normalizes the configured resource URL without trusting request headers. -// An empty URL leaves selection of the trusted frontend URL to the MCP handler. +// An empty URL keeps MCP and its OAuth endpoints disabled. func (c *MCPConfig) Validate() error { raw := strings.TrimSpace(c.PublicURL) if raw == "" { diff --git a/backend/internal/handler/admin/audit_log_handler.go b/backend/internal/handler/admin/audit_log_handler.go index a54135c86e..bb5bca8e2e 100644 --- a/backend/internal/handler/admin/audit_log_handler.go +++ b/backend/internal/handler/admin/audit_log_handler.go @@ -110,13 +110,13 @@ type auditLogClearRequest struct { // 安全要求(与需求对齐): // 1. 每次清空都必须现场验证 TOTP 码(不复用 step-up sudo 窗口) // 2. 未启用 TOTP 的管理员不允许清空 -// 3. admin API key(机器凭证)不允许清空 +// 3. 机器凭证(admin API key、MCP OAuth 等非浏览器会话)不允许清空 // 4. 清空完成后同步写入一条留痕记录(操作者、IP、UA、删除行数) func (h *AuditLogHandler) Clear(c *gin.Context) { - if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey { + if reason, machine := middleware.MachineCredentialReason(c); machine { response.ErrorWithDetails(c, http.StatusForbidden, - "Admin API key cannot clear audit logs; a two-factor verified admin session is required", - "STEP_UP_ADMIN_API_KEY_FORBIDDEN", nil) + "Machine credentials cannot clear audit logs; a two-factor verified admin session is required", + reason, nil) return } diff --git a/backend/internal/handler/admin/setting_handler_update.go b/backend/internal/handler/admin/setting_handler_update.go index 0947c43a58..673e08a11b 100644 --- a/backend/internal/handler/admin/setting_handler_update.go +++ b/backend/internal/handler/admin/setting_handler_update.go @@ -396,13 +396,13 @@ type UpdateSettingsRequest struct { // UpdateSettings 更新系统设置 // PUT /api/v1/admin/settings // ensureActorTotpForStepUp 校验当前操作者具备开启 step-up 门控的条件: -// 必须是真人管理员会话(admin API key 无法完成 TOTP step-up,拒绝)且本人已启用 TOTP。 +// 必须是真人管理员会话(admin API key、MCP OAuth 等机器凭证无法完成 TOTP step-up,拒绝)且本人已启用 TOTP。 // 校验失败时写入错误响应并返回 false。 func (h *SettingHandler) ensureActorTotpForStepUp(c *gin.Context) bool { - if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey { + if reason, machine := middleware.MachineCredentialReason(c); machine { response.ErrorWithDetails(c, http.StatusForbidden, - "Admin API key cannot enable step-up verification; use an admin session with TOTP enabled", - "STEP_UP_ADMIN_API_KEY_FORBIDDEN", nil) + "Machine credentials cannot enable step-up verification; use an admin session with TOTP enabled", + reason, nil) return false } subject, ok := middleware.GetAuthSubjectFromContext(c) diff --git a/backend/internal/handler/dto/settings.go b/backend/internal/handler/dto/settings.go index 96dcc82ec6..fb119c1cda 100644 --- a/backend/internal/handler/dto/settings.go +++ b/backend/internal/handler/dto/settings.go @@ -415,6 +415,7 @@ type PublicSettings struct { GitHubOAuthEnabled bool `json:"github_oauth_enabled"` GoogleOAuthEnabled bool `json:"google_oauth_enabled"` BackendModeEnabled bool `json:"backend_mode_enabled"` + MCPEnabled bool `json:"mcp_enabled"` PaymentEnabled bool `json:"payment_enabled"` // PaymentBalanceDisabled mirrors the payment-config BALANCE_PAYMENT_DISABLED switch so the // user shell can derive the site billing mode (recharge & subscription / recharge only / diff --git a/backend/internal/handler/mcp_oauth_handler.go b/backend/internal/handler/mcp_oauth_handler.go index a0b9566546..6c81b63d7e 100644 --- a/backend/internal/handler/mcp_oauth_handler.go +++ b/backend/internal/handler/mcp_oauth_handler.go @@ -33,21 +33,13 @@ func NewMCPOAuthHandler(oauth *service.MCPOAuthService, totp *service.TotpServic func (h *MCPOAuthHandler) Service() *service.MCPOAuthService { return h.oauth } // ResourceURL is anchored to operator configuration, never the request Host or -// forwarded headers. A separate API origin can override the frontend fallback. -func (h *MCPOAuthHandler) ResourceURL(ctx context.Context) (string, error) { - var raw string - if h.cfg != nil { - raw = h.cfg.MCP.PublicURL +// forwarded headers. MCP stays disabled until MCP_PUBLIC_URL is set explicitly, +// so upgrading never exposes client registration or management tools. +func (h *MCPOAuthHandler) ResourceURL(_ context.Context) (string, error) { + if h.cfg == nil || !h.cfg.MCP.Enabled() { + return "", errors.New("MCP is disabled; set MCP_PUBLIC_URL to enable it") } - if strings.TrimSpace(raw) == "" { - frontend := h.frontendURL(ctx) - u, err := url.Parse(frontend) - if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.Contains(frontend, "#") { - return "", errors.New("configure MCP_PUBLIC_URL or the platform frontend URL to enable MCP OAuth") - } - raw = u.Scheme + "://" + u.Host + "/api/v1/mcp" - } - configured := config.MCPConfig{PublicURL: raw} + configured := config.MCPConfig{PublicURL: h.cfg.MCP.PublicURL} if err := configured.Validate(); err != nil || configured.PublicURL == "" { return "", errors.New("MCP public URL is not configured correctly") } @@ -130,6 +122,11 @@ 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 } @@ -229,7 +226,15 @@ func (h *MCPOAuthHandler) Decide(c *gin.Context) { response.Forbidden(c, "Only administrators can authorize admin MCP access") return } - if !middleware.EnforceStepUp(c, h.totp, h.users, h.settings) { + // Administrator write grants outlive browser sessions, so they always + // need a fresh TOTP verification even when the global switch is off. + var verified bool + if input.ReadOnly != nil && !*input.ReadOnly { + verified = middleware.EnforceStepUpAlways(c, h.totp, h.users) + } else { + verified = middleware.EnforceStepUp(c, h.totp, h.users, h.settings) + } + if !verified { return } } @@ -327,7 +332,12 @@ 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" { - c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10) + // Unauthenticated registrations are persisted, so they get a tighter bound. + limit := int64(4 << 10) + if browser { + limit = 16 << 10 + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit) decoder := json.NewDecoder(c.Request.Body) if browser { decoder.DisallowUnknownFields() diff --git a/backend/internal/handler/mcp_oauth_handler_test.go b/backend/internal/handler/mcp_oauth_handler_test.go index c6d6012154..1fc9675fe0 100644 --- a/backend/internal/handler/mcp_oauth_handler_test.go +++ b/backend/internal/handler/mcp_oauth_handler_test.go @@ -28,6 +28,12 @@ type handlerMCPRepo struct { client *service.MCPOAuthClient 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) { @@ -124,23 +130,18 @@ func TestMCPOAuthHandlerResourceURLTrustedConfiguration(t *testing.T) { for _, tt := range []struct{ name, public, frontend, stored, want string }{ {"explicit API origin", handlerMCPResource, "https://platform.example.com", "", handlerMCPResource}, {"normalize explicit", " https://API.EXAMPLE.COM/api/v1/mcp ", "", "", handlerMCPResource}, - {"frontend fallback uses origin", "", "https://platform.example.com/console/", "", "https://platform.example.com/api/v1/mcp"}, - {"stored frontend wins", "", "https://configured.example.com", "https://stored.example.com/ui", "https://stored.example.com/api/v1/mcp"}, {"explicit resource wins", handlerMCPResource, "", "https://stored.example.com", handlerMCPResource}, - {"loopback development", "", "http://127.0.0.1:8080", "", "http://127.0.0.1:8080/api/v1/mcp"}, + {"loopback development", "http://127.0.0.1:8080/api/v1/mcp", "", "", "http://127.0.0.1:8080/api/v1/mcp"}, {"missing configuration", "", "", "", ""}, + // A configured frontend must not implicitly enable MCP after an upgrade. + {"configured frontend stays disabled", "", "https://platform.example.com", "", ""}, + {"stored frontend stays disabled", "", "", "https://stored.example.com", ""}, {"insecure public URL", "http://api.example.com/api/v1/mcp", "", "", ""}, {"wrong resource path", "https://api.example.com/mcp", "", "", ""}, + {"sub-path deployment", "https://example.com/sub2api/api/v1/mcp", "", "", ""}, {"resource userinfo", "https://user:password@api.example.com/api/v1/mcp", "", "", ""}, {"resource query", handlerMCPResource + "?q=1", "", "", ""}, {"resource fragment", handlerMCPResource + "#x", "", "", ""}, - {"relative frontend", "", "/console", "", ""}, - {"frontend credentials", "", "https://user:password@platform.example.com", "", ""}, - {"frontend query", "", "https://platform.example.com?q=1", "", ""}, - {"frontend fragment", "", "https://platform.example.com#fragment", "", ""}, - {"frontend empty query", "", "https://platform.example.com?", "", ""}, - {"frontend empty fragment", "", "https://platform.example.com#", "", ""}, - {"insecure frontend", "", "http://platform.example.com", "", ""}, } { t.Run(tt.name, func(t *testing.T) { cfg := &config.Config{MCP: config.MCPConfig{PublicURL: tt.public}} @@ -268,6 +269,8 @@ func TestMCPOAuthHandlerJSONValidation(t *testing.T) { {"oversized browser", "application/json", `{"authorization":{"state":"` + strings.Repeat("x", 17<<10) + `"}}`, true, false}, {"registration extension metadata", "application/json", `{"client_name":"example","client_uri":"https://client.example.com"}`, false, true}, {"oversized registration", "application/json", `{"client_name":"` + strings.Repeat("x", 17<<10) + `"}`, false, false}, + {"registration above 4 KiB", "application/json", `{"client_name":"x","client_uri":"` + strings.Repeat("x", 4<<10) + `"}`, false, false}, + {"browser body above registration limit", "application/json", `{"authorization":{"state":"` + strings.Repeat("x", 8<<10) + `"}}`, true, true}, {"malformed registration", "application/json", `{`, false, false}, } { t.Run(tt.name, func(t *testing.T) { @@ -375,7 +378,7 @@ func TestMCPOAuthHandlerAdminDecisionGatesBeforePersistence(t *testing.T) { {name: "no recent grant", role: service.RoleAdmin, totp: true, status: 403, marker: "STEP_UP_REQUIRED"}, {name: "step-up unavailable", role: service.RoleAdmin, totp: true, cacheErr: errors.New("cache unavailable"), status: 503, marker: "STEP_UP_UNAVAILABLE"}, {name: "admin API key", role: service.RoleAdmin, authMethod: service.AuditAuthMethodAdminAPIKey, totp: true, granted: true, status: 403, marker: "STEP_UP_ADMIN_API_KEY_FORBIDDEN"}, - {name: "MCP credential", role: service.RoleAdmin, authMethod: "mcp_oauth", totp: true, granted: true, status: 403, marker: "STEP_UP_MCP_OAUTH_FORBIDDEN"}, + {name: "MCP credential", role: service.RoleAdmin, authMethod: service.AuditAuthMethodMCPOAuth, totp: true, granted: true, status: 403, marker: "STEP_UP_MCP_OAUTH_FORBIDDEN"}, } { t.Run(tt.name, func(t *testing.T) { h, repo, users, cache := newHandlerMCPFixture(t) @@ -395,6 +398,48 @@ func TestMCPOAuthHandlerAdminDecisionGatesBeforePersistence(t *testing.T) { } } +func TestMCPOAuthHandlerAdminWriteAlwaysRequiresStepUp(t *testing.T) { + for _, tt := range []struct { + name string + readOnly *bool + totp, granted bool + status, writes int + marker string + }{ + {name: "write without TOTP", readOnly: boolPtr(false), status: 403, marker: "STEP_UP_TOTP_NOT_ENABLED"}, + {name: "write without recent verification", readOnly: boolPtr(false), totp: true, status: 403, marker: "STEP_UP_REQUIRED"}, + {name: "verified write", readOnly: boolPtr(false), totp: true, granted: true, status: 200, writes: 1}, + {name: "read-only follows the switch", readOnly: boolPtr(true), status: 200, writes: 1}, + {name: "default read-only follows the switch", status: 200, writes: 1}, + } { + t.Run(tt.name, func(t *testing.T) { + h, repo, users, cache := newHandlerMCPFixture(t) + // Global step-up is disabled; write grants still need verification. + 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} + c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") + handlerMCPSubject(c, service.RoleAdmin) + h.Decide(c) + require.Equal(t, tt.status, rec.Code, rec.Body.String()) + require.Contains(t, rec.Body.String(), tt.marker) + require.Equal(t, tt.writes, repo.writes) + }) + } +} + +func TestMCPOAuthHandlerRegistrationCapacityIsTemporary(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") + 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, "no-store", rec.Header().Get("Cache-Control")) +} + func TestMCPOAuthHandlerAdminApprovalUsesBrowserSession(t *testing.T) { h, repo, _, cache := newHandlerMCPFixture(t) cache.granted = true diff --git a/backend/internal/handler/setting_handler.go b/backend/internal/handler/setting_handler.go index aa204923f8..1dd3592455 100644 --- a/backend/internal/handler/setting_handler.go +++ b/backend/internal/handler/setting_handler.go @@ -94,6 +94,7 @@ func (h *SettingHandler) GetPublicSettings(c *gin.Context) { GitHubOAuthEnabled: settings.GitHubOAuthEnabled, GoogleOAuthEnabled: settings.GoogleOAuthEnabled, BackendModeEnabled: settings.BackendModeEnabled, + MCPEnabled: settings.MCPEnabled, PaymentEnabled: settings.PaymentEnabled, PaymentBalanceDisabled: settings.PaymentBalanceDisabled, Version: h.version, diff --git a/backend/internal/managementmcp/auth.go b/backend/internal/managementmcp/auth.go index dbe7240a1e..3bd7ad6dc7 100644 --- a/backend/internal/managementmcp/auth.go +++ b/backend/internal/managementmcp/auth.go @@ -13,7 +13,7 @@ import ( "github.com/gin-gonic/gin" ) -const AuthMethod = "mcp_oauth" +const AuthMethod = service.AuditAuthMethodMCPOAuth type TokenAuthenticator interface { Authenticate(context.Context, string) (*service.MCPPrincipal, error) diff --git a/backend/internal/managementmcp/server.go b/backend/internal/managementmcp/server.go index 71984dc92d..395692b0cc 100644 --- a/backend/internal/managementmcp/server.go +++ b/backend/internal/managementmcp/server.go @@ -64,15 +64,20 @@ func NewHandler(dispatcher http.Handler) http.Handler { http.Error(w, "This stateless MCP endpoint only supports POST", http.StatusMethodNotAllowed) return } - if r.Method == http.MethodPost { - // Bound the JSON-RPC envelope before the SDK allocates for it. - body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBytes)) - if err != nil { - http.Error(w, "MCP request body exceeds the limit or cannot be read", http.StatusRequestEntityTooLarge) - return - } - r.Body = io.NopCloser(bytes.NewReader(body)) + // Bound the JSON-RPC envelope before the SDK allocates for it. + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBytes)) + if err != nil { + http.Error(w, "MCP request body exceeds the limit or cannot be read", http.StatusRequestEntityTooLarge) + return } + // Accept exactly one JSON-RPC object per HTTP request. Without this, the + // SDK accepts 2025-03-26 batches and buffers every result in JSON + // response mode, so one request could fan out into thousands of calls. + if trimmed := bytes.TrimLeft(body, " \t\r\n"); len(trimmed) == 0 || trimmed[0] != '{' { + http.Error(w, "MCP requests must contain a single JSON-RPC object; batches are not supported", http.StatusBadRequest) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) transport.ServeHTTP(noStoreResponse{w}, r) }) } @@ -151,13 +156,17 @@ func executeTool(ctx context.Context, dispatcher http.Handler, spec ToolSpec, ar return toolError(fmt.Sprintf("Management API returned HTTP %d without a JSON result", response.status)) } redactResult(result, spec.RevealCreatedKey && response.status >= 200 && response.status < 300, "") - out := map[string]any{"http_status": response.status, "result": result} - encoded, err := json.Marshal(out) + encoded, err := json.Marshal(map[string]any{"http_status": response.status, "result": result}) if err != nil { return toolError("Cannot encode management result") } + // Re-encoding can expand escaped characters, so bound the final payload. + // The result is returned once, as text: tools declare no output schema. + if len(encoded) > maxResultBytes { + return toolError("Result exceeds 2 MiB; narrow the query or reduce page_size") + } return &mcp.CallToolResult{ - Content: []mcp.Content{&mcp.TextContent{Text: string(encoded)}}, StructuredContent: out, + Content: []mcp.Content{&mcp.TextContent{Text: string(encoded)}}, IsError: response.status < 200 || response.status >= 300, } } @@ -184,18 +193,30 @@ func (w noStoreResponse) Flush() { } func (w noStoreResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter } +// redactedResultKeys derives from the authoritative credential table so new +// upstream secret kinds are removed from tool results without a second list. +var redactedResultKeys = func() map[string]struct{} { + keys := map[string]struct{}{} + for _, key := range append([]string{ + "credentials", "password_hash", "session_token", "client_secret", "secret", + "totp_secret", "totp_secret_encrypted", + }, service.SensitiveCredentialKeys...) { + keys[strings.ToLower(key)] = struct{}{} + } + return keys +}() + func redactResult(value any, revealCreatedKey bool, path string) { switch v := value.(type) { case map[string]any: for key, child := range v { childPath := path + "/" + key - switch strings.ToLower(key) { - case "key": - if !revealCreatedKey || childPath != "/data/key" { - delete(v, key) - continue - } - case "credentials", "password", "password_hash", "api_key", "access_token", "refresh_token", "id_token", "session_token", "session_key", "client_secret", "secret", "totp_secret", "totp_secret_encrypted": + lower := strings.ToLower(key) + if lower == "key" && (!revealCreatedKey || childPath != "/data/key") { + delete(v, key) + continue + } + if _, sensitive := redactedResultKeys[lower]; sensitive { delete(v, key) continue } diff --git a/backend/internal/managementmcp/server_test.go b/backend/internal/managementmcp/server_test.go index bfe1723df0..5dbae89bae 100644 --- a/backend/internal/managementmcp/server_test.go +++ b/backend/internal/managementmcp/server_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "strings" @@ -323,3 +324,85 @@ func TestMCPResultLimitAndCancellation(t *testing.T) { t.Fatal("HTTP cancellation did not reach dispatcher") } } + +func TestMCPRejectsJSONRPCBatchesBeforeDispatch(t *testing.T) { + calls := 0 + r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + calls++ + _, _ = w.Write([]byte(`{"data":{}}`)) + })) + call := `{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"user_get_profile","arguments":{}}}` + list := `{"jsonrpc":"2.0","id":%d,"method":"tools/list"}` + batch := "[" + strings.Join([]string{fmt.Sprintf(call, 1), fmt.Sprintf(list, 2), fmt.Sprintf(call, 3)}, ",") + "]" + for _, tc := range []struct{ name, body, version string }{ + // Without a protocol header the SDK assumes 2025-03-26, which allows batches. + {"legacy batch", batch, ""}, + {"current batch", batch, "2025-06-18"}, + {"whitespace batch", " \r\n\t" + batch, ""}, + {"scalar", `"tools/list"`, ""}, + {"empty", " ", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(tc.body)) + req.Header.Set("Authorization", "Bearer admin") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + if tc.version != "" { + req.Header.Set("MCP-Protocol-Version", tc.version) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + require.Equal(t, "no-store", w.Header().Get("Cache-Control")) + }) + } + require.Zero(t, calls) + // A single request without the protocol header is still served. + req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(fmt.Sprintf(call, 1))) + req.Header.Set("Authorization", "Bearer admin") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.Equal(t, 1, calls) +} + +func TestMCPToolResultIsReturnedOnceAndBoundedAfterEncoding(t *testing.T) { + payload := `{"data":{"name":"ok"}}` + r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(payload)) + })) + _, result := rpc(t, r, "reader", "tools/call", map[string]any{"name": "user_get_profile", "arguments": map[string]any{}}) + toolResult := rpcObject(t, result["result"]) + require.NotContains(t, toolResult, "structuredContent", "results must not be duplicated") + 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)) + + // Under the capture limit as received, but HTML escaping expands it 6x. + payload = `{"data":"` + strings.Repeat("<", maxResultBytes/3) + `"}` + _, result = rpc(t, r, "reader", "tools/call", map[string]any{"name": "user_get_profile", "arguments": map[string]any{}}) + toolResult = rpcObject(t, result["result"]) + require.Equal(t, true, toolResult["isError"]) + encoded, _ := json.Marshal(toolResult) + require.Less(t, len(encoded), 1<<10) +} + +func TestMCPRedactsEveryAuthoritativeCredentialKey(t *testing.T) { + data := map[string]any{"name": "visible"} + nested := map[string]any{} + for _, key := range service.SensitiveCredentialKeys { + data[key] = "canary-" + key + nested[strings.ToUpper(key)] = "canary-upper-" + key + } + data["credentials"] = map[string]any{"nested": nested} + data["items"] = []any{nested} + value := map[string]any{"data": data} + redactResult(value, false, "") + encoded, err := json.Marshal(value) + require.NoError(t, err) + require.NotContains(t, string(encoded), "canary") + require.Contains(t, string(encoded), "visible") +} diff --git a/backend/internal/middleware/rate_limiter.go b/backend/internal/middleware/rate_limiter.go index df18a0234e..392236fde9 100644 --- a/backend/internal/middleware/rate_limiter.go +++ b/backend/internal/middleware/rate_limiter.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "net/http" + "net/netip" "strconv" "time" @@ -25,6 +26,8 @@ const ( // RateLimitOptions 限流可选配置 type RateLimitOptions struct { FailureMode RateLimitFailureMode + // IPv6PrefixBits 按网段(如 64)合并 IPv6 客户端计数,避免轮换同一分配内的地址绕过限流;0 表示按单个地址计数。 + IPv6PrefixBits int } var rateLimitScript = redis.NewScript(` @@ -120,6 +123,22 @@ func clientIPForRateLimit(c *gin.Context) string { return c.ClientIP() } +// rateLimitClientKey 把 IPv6 地址归并到指定前缀的网段;IPv4 与无法解析的值保持原样。 +func rateLimitClientKey(ip string, ipv6PrefixBits int) string { + if ipv6PrefixBits <= 0 || ipv6PrefixBits >= 128 { + return ip + } + addr, err := netip.ParseAddr(ip) + if err != nil || !addr.Is6() || addr.Is4In6() { + return ip + } + prefix, err := addr.WithZone("").Prefix(ipv6PrefixBits) + if err != nil { + return ip + } + return prefix.String() +} + // Limit 返回速率限制中间件 // key: 限制类型标识 // limit: 时间窗口内最大请求数 @@ -136,7 +155,7 @@ func (r *RateLimiter) LimitWithOptions(key string, limit int, window time.Durati } return func(c *gin.Context) { - result, err := r.Allow(c.Request.Context(), key+":"+clientIPForRateLimit(c), limit, window) + result, err := r.Allow(c.Request.Context(), key+":"+rateLimitClientKey(clientIPForRateLimit(c), opts.IPv6PrefixBits), limit, window) if err != nil { log.Printf("[RateLimit] redis error: key=%s mode=%s err=%v", r.prefix+key, failureModeLabel(failureMode), err) if failureMode == RateLimitFailClose { diff --git a/backend/internal/middleware/rate_limiter_test.go b/backend/internal/middleware/rate_limiter_test.go index ab1e587851..c76839dbbe 100644 --- a/backend/internal/middleware/rate_limiter_test.go +++ b/backend/internal/middleware/rate_limiter_test.go @@ -224,3 +224,43 @@ func TestRateLimiterSuccessAndLimit(t *testing.T) { router.ServeHTTP(recorder, req) require.Equal(t, http.StatusTooManyRequests, recorder.Code) } + +func TestRateLimitClientKeyAggregatesIPv6Prefix(t *testing.T) { + require.Equal(t, "2001:db8:1:2::/64", rateLimitClientKey("2001:db8:1:2:aaaa:bbbb:cccc:dddd", 64)) + require.Equal(t, "2001:db8:1:2::/64", rateLimitClientKey("2001:db8:1:2::1", 64)) + require.Equal(t, "2001:db8:1:3::/64", rateLimitClientKey("2001:db8:1:3::1", 64)) + require.Equal(t, "2001:db8:1:2::1", rateLimitClientKey("2001:db8:1:2::1", 0), "per-address keys stay the default") + for _, ip := range []string{"203.0.113.9", "::ffff:203.0.113.9", "not-an-ip", ""} { + require.Equal(t, ip, rateLimitClientKey(ip, 64)) + } +} + +func TestRateLimiterIPv6PrefixSharesOneBudget(t *testing.T) { + gin.SetMode(gin.TestMode) + callCounts := make(map[string]int64) + originalRun := rateLimitRun + rateLimitRun = func(ctx context.Context, client *redis.Client, key string, windowMillis int64) (int64, bool, error) { + callCounts[key]++ + return callCounts[key], false, nil + } + t.Cleanup(func() { rateLimitRun = originalRun }) + + limiter := NewRateLimiter(redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})) + router := gin.New() + router.Use(limiter.LimitWithOptions("api", 1, time.Second, RateLimitOptions{IPv6PrefixBits: 64})) + router.GET("/test", func(c *gin.Context) { c.Status(http.StatusOK) }) + for _, tc := range []struct { + addr string + status int + }{ + {"[2001:db8::1]:1234", http.StatusOK}, + {"[2001:db8::2]:1234", http.StatusTooManyRequests}, // same /64, rotated address + {"[2001:db8:0:1::1]:1234", http.StatusOK}, // different /64 + } { + req := httptest.NewRequest(http.MethodGet, "/test", nil) + req.RemoteAddr = tc.addr + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.Equal(t, tc.status, rec.Code, tc.addr) + } +} diff --git a/backend/internal/repository/mcp_oauth.go b/backend/internal/repository/mcp_oauth.go index 9f840b2e70..30022c5d9a 100644 --- a/backend/internal/repository/mcp_oauth.go +++ b/backend/internal/repository/mcp_oauth.go @@ -17,7 +17,7 @@ func NewMCPOAuthRepository(db *sql.DB) service.MCPOAuthRepository { return &mcpOAuthRepository{db: db} } -func (r *mcpOAuthRepository) CreateClient(ctx context.Context, client *service.MCPOAuthClient) error { +func (r *mcpOAuthRepository) CreateClient(ctx context.Context, client *service.MCPOAuthClient, pendingLimit int) error { redirects, err := json.Marshal(client.RedirectURIs) if err != nil { return err @@ -26,19 +26,25 @@ func (r *mcpOAuthRepository) CreateClient(ctx context.Context, client *service.M if err != nil { return err } - // Registration also performs bounded retention work. Active authorizations - // protect their client registration; used refresh hashes remain for the - // entire grant lifetime so replay detection is never shortened by cleanup. + // 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`, now.Add(-90*24*time.Hour)) + 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 } @@ -66,6 +72,17 @@ func (r *mcpOAuthRepository) CreateClient(ctx context.Context, client *service.M 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 } @@ -247,6 +264,21 @@ func (r *mcpOAuthRepository) RevokeGrant(ctx context.Context, userID int64, id s return mcpOAuthResult(r.db.ExecContext(ctx, `UPDATE mcp_oauth_grants SET revoked_at=COALESCE(revoked_at,$3) WHERE id=$1 AND user_id=$2`, id, userID, at)) } +func (r *mcpOAuthRepository) RevokeUserGrants(ctx context.Context, userID int64, at time.Time) error { + return revokeMCPGrants(ctx, r.db, userID, false, at) +} + +// revokeMCPGrants persists revocation instead of relying on per-request user +// checks, so restoring an account or role cannot revive earlier grants. +func revokeMCPGrants(ctx context.Context, exec sqlExecutor, userID int64, adminOnly bool, at time.Time) error { + query := `UPDATE mcp_oauth_grants SET revoked_at=$2 WHERE user_id=$1 AND revoked_at IS NULL` + if adminOnly { + query += ` AND scope='admin'` + } + _, err := exec.ExecContext(ctx, query, userID, at) + return err +} + func mcpOAuthSQLError(err error) error { if errors.Is(err, sql.ErrNoRows) { return service.ErrMCPOAuthNotFound diff --git a/backend/internal/repository/mcp_oauth_integration_test.go b/backend/internal/repository/mcp_oauth_integration_test.go index 8a6bda5d58..6682a08c0b 100644 --- a/backend/internal/repository/mcp_oauth_integration_test.go +++ b/backend/internal/repository/mcp_oauth_integration_test.go @@ -14,6 +14,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/lib/pq" "github.com/stretchr/testify/require" ) @@ -201,3 +202,67 @@ func TestMCPOAuthIntegrationConcurrentCodeExchange(t *testing.T) { }, mcpIntegrationResource) requireMCPIntegrationInvalidGrant(t, err) } + +func TestMCPOAuthIntegrationAccountChangesRevokeGrantsPersistently(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + f := newMCPOAuthIntegrationFixture(t, ctx) + users := NewUserRepository(integrationEntClient, integrationDB) + user, err := users.GetByID(ctx, f.userID) + require.NoError(t, err) + user.Role = service.RoleAdmin + require.NoError(t, users.Update(ctx, user, service.UserUpdateFields{Role: true})) + now := time.Now().UTC() + adminGrant := &service.MCPOAuthGrant{ + ID: "admin-" + strings.Repeat("g", 20), ClientID: f.input.ClientID, UserID: f.userID, TokenVersion: 1, + Resource: mcpIntegrationResource, Scope: service.MCPScopeAdmin, ReadOnly: true, CreatedAt: now, ExpiresAt: now.Add(time.Hour), + } + require.NoError(t, f.repo.CreateAuthorization(ctx, adminGrant, &service.MCPOAuthCode{ + Hash: mcpIntegrationDigest(adminGrant.ID), GrantID: adminGrant.ID, ClientID: f.input.ClientID, RedirectURI: f.input.RedirectURI, + Resource: mcpIntegrationResource, CodeChallenge: strings.Repeat("c", 43), ExpiresAt: now.Add(time.Minute), + }, service.MCPOAuthGrantLimit)) + + requireRevoked := func(id string, revoked bool) { + t.Helper() + grant, err := f.repo.GetGrant(ctx, id) + require.NoError(t, err) + require.Equal(t, revoked, grant.RevokedAt != nil, id) + } + // Demotion revokes administrator grants only; personal access remains. + user.Role = service.RoleUser + require.NoError(t, users.Update(ctx, user, service.UserUpdateFields{Role: true})) + requireRevoked(adminGrant.ID, true) + requireRevoked(f.grantID, false) + + // Disabling revokes everything, and re-enabling must not revive it. + user.Status = service.StatusDisabled + require.NoError(t, users.Update(ctx, user, service.UserUpdateFields{Status: true})) + user.Status = service.StatusActive + require.NoError(t, users.Update(ctx, user, service.UserUpdateFields{Status: true})) + requireRevoked(f.grantID, true) + _, err = f.oauth.Token(ctx, f.input, mcpIntegrationResource) + requireMCPIntegrationInvalidGrant(t, err) +} + +func TestMCPOAuthIntegrationRegistrationStopsAtPendingLimit(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()} + } + 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) +} diff --git a/backend/internal/repository/mcp_oauth_test.go b/backend/internal/repository/mcp_oauth_test.go index 40f227952f..83fdcdc00c 100644 --- a/backend/internal/repository/mcp_oauth_test.go +++ b/backend/internal/repository/mcp_oauth_test.go @@ -14,20 +14,37 @@ import ( ) func TestMCPOAuthRepositoryRegistrationPrunesOnlyOldUnreferencedDataInBatches(t *testing.T) { - db, mock, err := sqlmock.New() - require.NoError(t, err) - defer db.Close() - repo := NewMCPOAuthRepository(db) - now := time.Unix(1800000000, 0).UTC() - client := &service.MCPOAuthClient{ClientID: "client", ClientName: "Client", RedirectURIs: []string{"https://client.example/cb"}, GrantTypes: []string{"authorization_code", "refresh_token"}, ClientIDIssuedAt: now.Unix()} - mock.ExpectBegin() - 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(now.Add(-90 * 24 * time.Hour)).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.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)) - require.NoError(t, mock.ExpectationsWereMet()) + 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 TestMCPOAuthRepositoryConsumptionCommitsReplayRevocation(t *testing.T) { @@ -175,3 +192,16 @@ func TestMCPOAuthRepositoryOwnerAndRevocationBoundaries(t *testing.T) { require.ErrorIs(t, repo.TouchGrant(context.Background(), "grant", now), service.ErrMCPOAuthNotFound) require.NoError(t, mock.ExpectationsWereMet()) } + +func TestMCPOAuthRepositoryRevokeUserGrantsCoversEveryActiveGrant(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewMCPOAuthRepository(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") + mock.ExpectExec(`UPDATE mcp_oauth_grants SET revoked_at=\$2 WHERE user_id=\$1 AND revoked_at IS NULL AND scope='admin'`).WithArgs(int64(8), now).WillReturnResult(sqlmock.NewResult(0, 3)) + require.NoError(t, revokeMCPGrants(context.Background(), db, 8, true, now)) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/repository/user_repo.go b/backend/internal/repository/user_repo.go index a0d7006616..fb9fc18966 100644 --- a/backend/internal/repository/user_repo.go +++ b/backend/internal/repository/user_repo.go @@ -351,6 +351,18 @@ func (r *userRepository) Update(ctx context.Context, userIn *service.User, field return err } } + // 停用或降级时在同一事务内吊销 MCP 授权,恢复账号或角色后旧授权不会复活。 + disabled := fields.Status && updated.Status != existing.Status && updated.Status != service.StatusActive + demoted := fields.Role && updated.Role != existing.Role && updated.Role != service.RoleAdmin + if disabled || demoted { + exec := txAwareSQLExecutor(txCtx, r.sql, r.client) + if exec == nil { + return fmt.Errorf("sql executor is not configured") + } + if err := revokeMCPGrants(txCtx, exec, updated.ID, !disabled, time.Now().UTC()); err != nil { + return err + } + } // 始终以库中的邮箱为准补齐 email 身份:未改邮箱时 updated.Email == oldEmail, // 这里退化为幂等的身份补写,与改邮箱前的行为一致。 if err := replaceEmailAuthIdentityWithClient(txCtx, txClient, updated.ID, oldEmail, updated.Email, "user_repo_update"); err != nil { diff --git a/backend/internal/server/middleware/audit_log.go b/backend/internal/server/middleware/audit_log.go index 968cd80b3a..b35ac3d485 100644 --- a/backend/internal/server/middleware/audit_log.go +++ b/backend/internal/server/middleware/audit_log.go @@ -161,7 +161,7 @@ var auditBodyOmittedRoutes = map[string]struct{}{ } // NewAuditLogMiddleware 创建审计中间件。 -// 记录范围:变更类请求(POST/PUT/PATCH/DELETE)+ 白名单内的敏感 GET 读取。 +// 记录范围:变更类请求(POST/PUT/PATCH/DELETE)+ 白名单内的敏感 GET 读取 + MCP OAuth 的全部读取。 // 挂载位置:admin / user / admin-payment 组挂在各自认证中间件之后(只审计已认证请求, // 未过认证的 401/403 不入库);auth 组(登录/注册/刷新)无前置认证,天然记录失败尝试。 func NewAuditLogMiddleware(auditService *service.AuditLogService) AuditLogMiddleware { @@ -180,6 +180,10 @@ func NewAuditLogMiddleware(auditService *service.AuditLogService) AuditLogMiddle if v, ok := auditSensitiveReads[routeKey]; ok { record = true action = v + } else if c.GetString("auth_method") == service.AuditAuthMethodMCPOAuth { + // Machine credentials can read user data in bulk; every MCP tool + // call is attributable to its grant via audit extra fields. + record = true } } if !record { diff --git a/backend/internal/server/middleware/audit_log_test.go b/backend/internal/server/middleware/audit_log_test.go index 3ff14cd914..3328e4216a 100644 --- a/backend/internal/server/middleware/audit_log_test.go +++ b/backend/internal/server/middleware/audit_log_test.go @@ -188,3 +188,39 @@ func TestOllamaCloudUsageSessionRouteOmitsAuditBody(t *testing.T) { require.Equal(t, "", logs[0].RequestBody) require.NotContains(t, logs[0].RequestBody, "audit-canary") } + +// MCP OAuth 是机器凭证:只读工具同样可以批量读取邮箱等数据,必须全部入审计并带上 grant。 +func TestAuditRecordsEveryMCPOAuthReadWithGrant(t *testing.T) { + gin.SetMode(gin.TestMode) + repository := &auditCaptureRepository{} + auditService := service.NewAuditLogService(repository, nil) + auditService.Start() + + for _, authMethod := range []string{service.AuditAuthMethodMCPOAuth, ""} { + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(ContextKeyUser), AuthSubject{UserID: 77}) + c.Set(string(ContextKeyUserRole), service.RoleAdmin) + if authMethod != "" { + c.Set("auth_method", authMethod) + SetAuditExtra(c, map[string]any{"mcp_grant_id": "grant-1", "mcp_tool": "admin_list_users"}) + } + c.Next() + }) + router.Use(gin.HandlerFunc(NewAuditLogMiddleware(auditService))) + router.GET("/api/v1/admin/users", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"items": []any{}}) }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/admin/users?search=a", nil)) + require.Equal(t, http.StatusOK, recorder.Code) + } + auditService.Stop() + + repository.mu.Lock() + logs := append([]*service.AuditLog(nil), repository.logs...) + repository.mu.Unlock() + require.Len(t, logs, 1, "browser reads stay outside the audit log") + require.Equal(t, service.AuditAuthMethodMCPOAuth, logs[0].AuthMethod) + require.Equal(t, "admin.users.read", logs[0].Action) + require.Equal(t, "grant-1", logs[0].Extra["mcp_grant_id"]) + require.Equal(t, "admin_list_users", logs[0].Extra["mcp_tool"]) +} diff --git a/backend/internal/server/middleware/step_up.go b/backend/internal/server/middleware/step_up.go index 6545aa455c..f6fcba8edc 100644 --- a/backend/internal/server/middleware/step_up.go +++ b/backend/internal/server/middleware/step_up.go @@ -94,6 +94,23 @@ func EnforceStepUpAlways( return enforceStepUp(c, totpService, userService, nil) } +// MachineCredentialReason allowlists interactive browser sessions: the user +// router leaves auth_method empty and the admin router sets "jwt". Every other +// method (admin API keys, MCP OAuth, future credential types) is a machine +// credential and is denied by default; the reason distinguishes known kinds. +func MachineCredentialReason(c *gin.Context) (string, bool) { + switch c.GetString("auth_method") { + case "", service.AuditAuthMethodJWT: + return "", false + case service.AuditAuthMethodAdminAPIKey: + return "STEP_UP_ADMIN_API_KEY_FORBIDDEN", true + case service.AuditAuthMethodMCPOAuth: + return "STEP_UP_MCP_OAUTH_FORBIDDEN", true + default: + return "STEP_UP_MACHINE_CREDENTIAL_FORBIDDEN", true + } +} + func enforceStepUp(c *gin.Context, grantChecker stepUpGrantChecker, userReader stepUpUserReader, settings stepUpSettingReader) bool { // 功能开关关闭时直接放行(含 admin API key),恢复门控引入前的行为。 // settings 为 nil 时保持门控(fail-closed):正常装配不会出现 nil。 @@ -101,14 +118,9 @@ func enforceStepUp(c *gin.Context, grantChecker stepUpGrantChecker, userReader s return true } - if c.GetString("auth_method") == "mcp_oauth" { - AbortWithError(c, 403, "STEP_UP_MCP_OAUTH_FORBIDDEN", - "MCP OAuth credentials cannot perform this operation; use a two-factor verified browser session") - return false - } - if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey { - AbortWithError(c, 403, "STEP_UP_ADMIN_API_KEY_FORBIDDEN", - "Admin API key cannot access this endpoint; a two-factor verified admin session is required") + if reason, machine := MachineCredentialReason(c); machine { + AbortWithError(c, 403, reason, + "Machine credentials cannot access this endpoint; a two-factor verified browser session is required") return false } diff --git a/backend/internal/server/middleware/step_up_test.go b/backend/internal/server/middleware/step_up_test.go index f4d2f37adc..65c3de8888 100644 --- a/backend/internal/server/middleware/step_up_test.go +++ b/backend/internal/server/middleware/step_up_test.go @@ -63,14 +63,32 @@ func TestEnforceStepUpRejectsAdminAPIKey(t *testing.T) { require.Contains(t, rec.Body.String(), "STEP_UP_ADMIN_API_KEY_FORBIDDEN") } -func TestEnforceStepUpRejectsMCPOAuthEvenWithUserGrant(t *testing.T) { - c, rec := newStepUpTestContext(t) - c.Set("auth_method", "mcp_oauth") - c.Set(string(ContextKeyUser), AuthSubject{UserID: 1}) - ok := enforceStepUp(c, stubStepUpGrantChecker{granted: true}, stubStepUpUserReader{user: &service.User{TotpEnabled: true}}, stepUpEnabled) - require.False(t, ok) - require.Equal(t, http.StatusForbidden, rec.Code) - require.Contains(t, rec.Body.String(), "STEP_UP_MCP_OAUTH_FORBIDDEN") +func TestEnforceStepUpRejectsMachineCredentialsEvenWithUserGrant(t *testing.T) { + for method, reason := range map[string]string{ + service.AuditAuthMethodMCPOAuth: "STEP_UP_MCP_OAUTH_FORBIDDEN", + // Unknown credential types are denied by default, not silently allowed. + "future_machine_token": "STEP_UP_MACHINE_CREDENTIAL_FORBIDDEN", + } { + c, rec := newStepUpTestContext(t) + c.Set("auth_method", method) + c.Set(string(ContextKeyUser), AuthSubject{UserID: 1}) + ok := enforceStepUp(c, stubStepUpGrantChecker{granted: true}, stubStepUpUserReader{user: &service.User{TotpEnabled: true}}, stepUpEnabled) + require.False(t, ok, method) + require.Equal(t, http.StatusForbidden, rec.Code, method) + require.Contains(t, rec.Body.String(), reason, method) + } +} + +func TestMachineCredentialReasonAllowlistsBrowserSessions(t *testing.T) { + for method, want := range map[string]bool{ + "": false, service.AuditAuthMethodJWT: false, + service.AuditAuthMethodAdminAPIKey: true, service.AuditAuthMethodMCPOAuth: true, "unknown": true, + } { + c, _ := newStepUpTestContext(t) + c.Set("auth_method", method) + _, machine := MachineCredentialReason(c) + require.Equal(t, want, machine, method) + } } func TestEnforceStepUpRequiresAuthSubject(t *testing.T) { diff --git a/backend/internal/server/router.go b/backend/internal/server/router.go index 99458853a4..8dcc7ab942 100644 --- a/backend/internal/server/router.go +++ b/backend/internal/server/router.go @@ -128,7 +128,7 @@ func registerRoutes( routes.RegisterUserRoutes(v1, h, jwtAuth, auditLog, settingService, panelRateLimiter) routes.RegisterModelPlazaRoutes(v1, h, optionalJWTAuth, settingService, panelRateLimiter) routes.RegisterAdminRoutes(v1, h, adminAuth, auditLog, stepUpAuth, settingService, panelRateLimiter) - routes.RegisterMCPRoutes(v1, h, auditLog, stepUpAuth, settingService, panelRateLimiter, cfg.CORS.AllowedOrigins) + routes.RegisterMCPRoutes(v1, h, auditLog, stepUpAuth, settingService, panelRateLimiter, cfg.CORS.AllowedOrigins, redisClient) routes.RegisterMCPOAuthRoutes(r, v1, h, redisClient) routes.RegisterGatewayRoutes(r, h, apiKeyAuth, apiKeyService, subscriptionService, opsService, settingService, compositeResolver, cfg) routes.RegisterPaymentRoutes(v1, h.Payment, h.PaymentWebhook, h.Admin.Payment, jwtAuth, adminAuth, auditLog, settingService, panelRateLimiter, redisClient) diff --git a/backend/internal/server/routes/mcp.go b/backend/internal/server/routes/mcp.go index 2e7049d915..763f8a55c5 100644 --- a/backend/internal/server/routes/mcp.go +++ b/backend/internal/server/routes/mcp.go @@ -12,11 +12,15 @@ import ( "github.com/redis/go-redis/v9" ) +// MCP limits fail closed and count an IPv6 /64 as one client, so rotating +// addresses within one allocation does not multiply the budget. +var mcpRateLimitOptions = ratelimit.RateLimitOptions{FailureMode: ratelimit.RateLimitFailClose, IPv6PrefixBits: 64} + // RegisterMCPRoutes exposes MCP over HTTP and reuses the normal management // routes in a private router, preserving ownership checks, guards and audit. func RegisterMCPRoutes(v1 *gin.RouterGroup, h *handler.Handlers, audit middleware.AuditLogMiddleware, stepUp middleware.StepUpAuthMiddleware, settings *service.SettingService, - limiter *middleware.PanelRateLimiter, allowedOrigins []string, + limiter *middleware.PanelRateLimiter, allowedOrigins []string, redisClient *redis.Client, ) { inner := gin.New() inner.Use(gin.Recovery()) @@ -24,7 +28,15 @@ func RegisterMCPRoutes(v1 *gin.RouterGroup, h *handler.Handlers, audit middlewar RegisterUserRoutes(api, h, middleware.JWTAuthMiddleware(managementmcp.DispatchAuth(false)), audit, settings, limiter) RegisterAdminRoutes(api, h, middleware.AdminAuthMiddleware(managementmcp.DispatchAuth(true)), audit, stepUp, settings, limiter) transport := managementmcp.NewHandler(inner) - mcp := v1.Group("/mcp", managementmcp.Authenticate(h.MCPOAuth.Service(), allowedOrigins, h.MCPOAuth.ResourceURL), limiter.MCPTransport(), middleware.BackendModeUserGuard(settings)) + var handlers []gin.HandlerFunc + if redisClient != nil { + // Bound token probes per network before authentication reaches the database. + handlers = append(handlers, ratelimit.NewRateLimiter(redisClient).LimitWithOptions("mcp-transport", 600, time.Minute, mcpRateLimitOptions)) + } + handlers = append(handlers, + managementmcp.Authenticate(h.MCPOAuth.Service(), allowedOrigins, h.MCPOAuth.ResourceURL), + limiter.MCPTransport(), middleware.BackendModeUserGuard(settings)) + mcp := v1.Group("/mcp", handlers...) for _, method := range []string{"POST", "GET", "DELETE"} { mcp.Handle(method, "", gin.WrapH(transport)) } @@ -37,9 +49,8 @@ func RegisterMCPOAuthRoutes(r *gin.Engine, v1 *gin.RouterGroup, h *handler.Handl r.GET("/.well-known/oauth-protected-resource", h.MCPOAuth.ResourceMetadata) r.GET("/.well-known/oauth-authorization-server", h.MCPOAuth.AuthorizationMetadata) limit := ratelimit.NewRateLimiter(redisClient) - closed := ratelimit.RateLimitOptions{FailureMode: ratelimit.RateLimitFailClose} oauth := v1.Group("/mcp/oauth") - oauth.POST("/register", limit.LimitWithOptions("mcp-oauth-register", 10, time.Minute, closed), h.MCPOAuth.Register) - oauth.POST("/token", limit.LimitWithOptions("mcp-oauth-token", 60, time.Minute, closed), h.MCPOAuth.Token) - oauth.POST("/revoke", limit.LimitWithOptions("mcp-oauth-revoke", 60, time.Minute, closed), h.MCPOAuth.RevokeToken) + oauth.POST("/register", limit.LimitWithOptions("mcp-oauth-register", 10, time.Minute, mcpRateLimitOptions), h.MCPOAuth.Register) + oauth.POST("/token", limit.LimitWithOptions("mcp-oauth-token", 60, time.Minute, mcpRateLimitOptions), h.MCPOAuth.Token) + oauth.POST("/revoke", limit.LimitWithOptions("mcp-oauth-revoke", 60, time.Minute, mcpRateLimitOptions), h.MCPOAuth.RevokeToken) } diff --git a/backend/internal/server/routes/mcp_oauth_test.go b/backend/internal/server/routes/mcp_oauth_test.go index e651266428..03118a01a8 100644 --- a/backend/internal/server/routes/mcp_oauth_test.go +++ b/backend/internal/server/routes/mcp_oauth_test.go @@ -35,7 +35,7 @@ type mcpOAuthRouteRepo struct { credentials map[string]*service.MCPOAuthCredential } -func (r *mcpOAuthRouteRepo) CreateClient(_ context.Context, client *service.MCPOAuthClient) error { +func (r *mcpOAuthRouteRepo) CreateClient(_ context.Context, client *service.MCPOAuthClient, _ int) error { r.mu.Lock() defer r.mu.Unlock() r.clients[client.ClientID] = client @@ -180,6 +180,17 @@ func (r *mcpOAuthRouteRepo) RevokeGrant(_ context.Context, userID int64, id stri return nil } +func (r *mcpOAuthRouteRepo) RevokeUserGrants(_ context.Context, userID int64, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + for _, item := range r.grants { + if item.UserID == userID && item.RevokedAt == nil { + item.RevokedAt = &now + } + } + return nil +} + type mcpOAuthRouteUsers struct { service.UserRepository user *service.User @@ -193,6 +204,10 @@ func (r *mcpOAuthRouteUsers) GetByID(_ context.Context, id int64) (*service.User return ©, nil } +func (r *mcpOAuthRouteUsers) GetUserAvatar(context.Context, int64) (*service.UserAvatar, error) { + return nil, nil +} + func newMCPRouteOAuthService(role string) (*service.MCPOAuthService, *mcpOAuthRouteRepo, *mcpOAuthRouteUsers) { repo := &mcpOAuthRouteRepo{ clients: map[string]*service.MCPOAuthClient{}, grants: map[string]*service.MCPOAuthGrant{}, @@ -227,6 +242,12 @@ func issueMCPRouteOAuthToken(t *testing.T, oauth *service.MCPOAuthService, resou return tokens.AccessToken } +type mcpOAuthRouteStepUpCache struct{ service.TotpCache } + +func (mcpOAuthRouteStepUpCache) HasStepUpGrant(_ context.Context, _ int64, session string) (bool, error) { + return session == "browser-session", nil +} + type mcpOAuthHTTPFixture struct { server *httptest.Server router *gin.Engine @@ -250,8 +271,11 @@ func newMCPOAuthHTTPFixture(t *testing.T, role string) *mcpOAuthHTTPFixture { cfg.JWT.Secret = "test-jwt-secret-at-least-thirty-two-bytes" settings := service.NewSettingService(&mcpRouteSettingsRepo{values: map[string]string{service.SettingKeyStepUpEnabled: "false"}}, cfg) oauth, repo, users := newMCPRouteOAuthService(role) + // Administrator write grants always pass the real step-up gate. + users.user.TotpEnabled = true + totp := service.NewTotpService(users, nil, mcpOAuthRouteStepUpCache{}, settings, nil, nil) h := mcpRouteHandlers() - h.MCPOAuth = handler.NewMCPOAuthHandler(oauth, nil, nil, settings, cfg) + h.MCPOAuth = handler.NewMCPOAuthHandler(oauth, totp, service.NewUserService(users, nil, nil, nil), settings, cfg) h.APIKey = handler.NewAPIKeyHandler(service.NewAPIKeyService(&mcpRouteAPIKeyRepo{}, nil, nil, nil, nil, nil, nil)) mr := miniredis.RunT(t) rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) @@ -269,7 +293,7 @@ func newMCPOAuthHTTPFixture(t *testing.T, role string) *mcpOAuthHTTPFixture { v1 := router.Group("/api/v1") RegisterUserRoutes(v1, h, browserAuth, middleware.AuditLogMiddleware(mcpRouteNext), settings, nil) RegisterMCPOAuthRoutes(router, v1, h, rdb) - RegisterMCPRoutes(v1, h, middleware.AuditLogMiddleware(mcpRouteNext), middleware.StepUpAuthMiddleware(mcpRouteNext), settings, nil, nil) + RegisterMCPRoutes(v1, h, middleware.AuditLogMiddleware(mcpRouteNext), middleware.StepUpAuthMiddleware(mcpRouteNext), settings, nil, nil, rdb) server.Start() t.Cleanup(server.Close) return &mcpOAuthHTTPFixture{server: server, router: router, resource: cfg.MCP.PublicURL, cfg: cfg, settings: settings, handlers: h, oauth: oauth, repo: repo, users: users} @@ -406,9 +430,8 @@ func TestMCPOAuthHTTPFlowDiscoveryConsentRefreshAndRevocation(t *testing.T) { require.NotContains(t, string(tools.body), "admin_get_dashboard") call := f.rpc(t, tokens.AccessToken, "tools/call", map[string]any{"name": "user_get_api_key", "arguments": map[string]any{"id": 9}}) require.Equal(t, http.StatusOK, call.status, string(call.body)) - var result mcpRouteToolResult - require.NoError(t, json.Unmarshal(call.body, &result)) - require.Equal(t, http.StatusOK, result.Result.StructuredContent.HTTPStatus) + result := decodeMCPRouteToolResult(t, call.body) + require.Equal(t, http.StatusOK, result.Result.Payload.HTTPStatus) require.Contains(t, string(call.body), "owner-key") require.NotContains(t, string(call.body), "must-not-leak") refresh := f.form(t, "/api/v1/mcp/oauth/token", url.Values{"grant_type": {"refresh_token"}, "client_id": {client.ClientID}, "refresh_token": {tokens.RefreshToken}}) diff --git a/backend/internal/server/routes/mcp_rate_limit_test.go b/backend/internal/server/routes/mcp_rate_limit_test.go index 7237087181..c75ac45342 100644 --- a/backend/internal/server/routes/mcp_rate_limit_test.go +++ b/backend/internal/server/routes/mcp_rate_limit_test.go @@ -40,7 +40,7 @@ func newMCPRateLimitEndpoint(t *testing.T, role string, rpm int) (*gin.Engine, s h.APIKey = handler.NewAPIKeyHandler(service.NewAPIKeyService(&mcpRouteAPIKeyRepo{}, nil, nil, nil, nil, nil, nil)) router := gin.New() RegisterMCPRoutes(router.Group("/api/v1"), h, middleware.AuditLogMiddleware(mcpRouteNext), - middleware.StepUpAuthMiddleware(mcpRouteNext), settings, middleware.NewPanelRateLimiter(rdb, settings), nil) + middleware.StepUpAuthMiddleware(mcpRouteNext), settings, middleware.NewPanelRateLimiter(rdb, settings), nil, rdb) return router, token, mr } @@ -74,9 +74,8 @@ func TestMCPToolCallsConsumeGlobalBudgetOnce(t *testing.T) { for i := 0; i < 2; i++ { w := mcpRateLimitRPC(t, endpoint, token, "tools/call", params) require.Equal(t, http.StatusOK, w.Code, w.Body.String()) - var result mcpRouteToolResult - require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) - require.Equal(t, tc.status, result.Result.StructuredContent.HTTPStatus, w.Body.String()) + result := decodeMCPRouteToolResult(t, w.Body.Bytes()) + require.Equal(t, tc.status, result.Result.Payload.HTTPStatus, w.Body.String()) } count, err := mr.Get("rate_limit:panel:global:user:7") require.NoError(t, err) @@ -107,9 +106,8 @@ func TestMCPDispatchRetainsHeavyRateLimit(t *testing.T) { for _, status := range []int{http.StatusBadRequest, http.StatusTooManyRequests} { w := mcpRateLimitRPC(t, endpoint, token, "tools/call", params) require.Equal(t, http.StatusOK, w.Code, w.Body.String()) - var result mcpRouteToolResult - require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result)) - require.Equal(t, status, result.Result.StructuredContent.HTTPStatus, w.Body.String()) + result := decodeMCPRouteToolResult(t, w.Body.Bytes()) + require.Equal(t, status, result.Result.Payload.HTTPStatus, w.Body.String()) } count, err := mr.Get("rate_limit:panel:global:user:7") require.NoError(t, err) diff --git a/backend/internal/server/routes/mcp_test.go b/backend/internal/server/routes/mcp_test.go index d540f31064..f95b08cbe1 100644 --- a/backend/internal/server/routes/mcp_test.go +++ b/backend/internal/server/routes/mcp_test.go @@ -51,7 +51,7 @@ func TestMCPToolCatalogTargetsRegisteredManagementRoutes(t *testing.T) { // duplicate Gin paths or panic while building its permission-filtered servers. mcpRouter := gin.New() require.NotPanics(t, func() { - RegisterMCPRoutes(mcpRouter.Group("/api/v1"), h, middleware.AuditLogMiddleware(mcpRouteNext), middleware.StepUpAuthMiddleware(mcpRouteNext), nil, nil, nil) + RegisterMCPRoutes(mcpRouter.Group("/api/v1"), h, middleware.AuditLogMiddleware(mcpRouteNext), middleware.StepUpAuthMiddleware(mcpRouteNext), nil, nil, nil, nil) }) for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} { w := httptest.NewRecorder() @@ -78,17 +78,39 @@ func newMCPRouteTestEndpoint(h *handler.Handlers, principal *service.MCPPrincipa return outer } +type mcpRouteToolPayload struct { + HTTPStatus int `json:"http_status"` + Result json.RawMessage `json:"result"` +} + type mcpRouteToolResult struct { Result struct { - IsError bool `json:"isError"` - StructuredContent struct { - HTTPStatus int `json:"http_status"` - Result json.RawMessage `json:"result"` - } `json:"structuredContent"` + IsError bool `json:"isError"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + StructuredContent json.RawMessage `json:"structuredContent"` + // Payload is decoded from the single text block that carries the result. + Payload mcpRouteToolPayload `json:"-"` } `json:"result"` Error json.RawMessage `json:"error"` } +// decodeMCPRouteToolResult requires exactly one JSON text block, so results are +// never duplicated into structuredContent. +func decodeMCPRouteToolResult(t *testing.T, raw []byte) mcpRouteToolResult { + t.Helper() + var result mcpRouteToolResult + require.NoError(t, json.Unmarshal(raw, &result), string(raw)) + require.Empty(t, result.Error, string(raw)) + require.Empty(t, result.Result.StructuredContent, string(raw)) + require.Len(t, result.Result.Content, 1, string(raw)) + require.Equal(t, "text", result.Result.Content[0].Type) + require.NoError(t, json.Unmarshal([]byte(result.Result.Content[0].Text), &result.Result.Payload), string(raw)) + return result +} + func callMCPRouteTool(t *testing.T, endpoint http.Handler, name string, args map[string]any) mcpRouteToolResult { t.Helper() body, err := json.Marshal(map[string]any{ @@ -104,10 +126,7 @@ func callMCPRouteTool(t *testing.T, endpoint http.Handler, name string, args map w := httptest.NewRecorder() endpoint.ServeHTTP(w, req) require.Equal(t, http.StatusOK, w.Code, w.Body.String()) - var result mcpRouteToolResult - require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result), w.Body.String()) - require.Empty(t, result.Error, w.Body.String()) - return result + return decodeMCPRouteToolResult(t, w.Body.Bytes()) } type mcpRouteAPIKeyRepo struct{ service.APIKeyRepository } @@ -134,15 +153,15 @@ func TestMCPDispatchRetainsRealAPIKeyOwnershipAndAudit(t *testing.T) { }) result := callMCPRouteTool(t, newMCPRouteTestEndpoint(h, principal, nil, audit), "user_get_api_key", map[string]any{"id": 9}) require.Equal(t, 1, auditCalls) - require.NotContains(t, string(result.Result.StructuredContent.Result), "must-not-leak") + require.NotContains(t, string(result.Result.Payload.Result), "must-not-leak") if userID == 7 { require.False(t, result.Result.IsError) - require.Equal(t, http.StatusOK, result.Result.StructuredContent.HTTPStatus) - require.Contains(t, string(result.Result.StructuredContent.Result), "owner-key") + require.Equal(t, http.StatusOK, result.Result.Payload.HTTPStatus) + require.Contains(t, string(result.Result.Payload.Result), "owner-key") } else { require.True(t, result.Result.IsError) - require.Equal(t, http.StatusNotFound, result.Result.StructuredContent.HTTPStatus) - require.NotContains(t, string(result.Result.StructuredContent.Result), "owner-key") + require.Equal(t, http.StatusNotFound, result.Result.Payload.HTTPStatus) + require.NotContains(t, string(result.Result.Payload.Result), "owner-key") } } } @@ -179,12 +198,12 @@ func TestMCPDispatchRetainsBackendModeAndAdminCompliance(t *testing.T) { user := &service.MCPPrincipal{GrantID: "user", UserID: 7, Role: service.RoleUser, Scope: service.MCPScopeUser, ReadOnly: true} result := callMCPRouteTool(t, newMCPRouteTestEndpoint(h, user, settings, middleware.AuditLogMiddleware(mcpRouteNext)), "user_get_profile", map[string]any{}) require.True(t, result.Result.IsError) - require.Equal(t, http.StatusForbidden, result.Result.StructuredContent.HTTPStatus) - require.Contains(t, string(result.Result.StructuredContent.Result), "Backend mode is active") + require.Equal(t, http.StatusForbidden, result.Result.Payload.HTTPStatus) + require.Contains(t, string(result.Result.Payload.Result), "Backend mode is active") admin := &service.MCPPrincipal{GrantID: "admin", UserID: 8, Role: service.RoleAdmin, Scope: service.MCPScopeAdmin, ReadOnly: true} result = callMCPRouteTool(t, newMCPRouteTestEndpoint(h, admin, settings, middleware.AuditLogMiddleware(mcpRouteNext)), "admin_get_dashboard", map[string]any{}) require.True(t, result.Result.IsError) - require.Equal(t, http.StatusLocked, result.Result.StructuredContent.HTTPStatus) - require.Contains(t, string(result.Result.StructuredContent.Result), "ADMIN_COMPLIANCE_ACK_REQUIRED") + require.Equal(t, http.StatusLocked, result.Result.Payload.HTTPStatus) + require.Contains(t, string(result.Result.Payload.Result), "ADMIN_COMPLIANCE_ACK_REQUIRED") } diff --git a/backend/internal/service/audit_log.go b/backend/internal/service/audit_log.go index 46a59013e0..db2ff3ab6b 100644 --- a/backend/internal/service/audit_log.go +++ b/backend/internal/service/audit_log.go @@ -20,6 +20,8 @@ const ( AuditAuthMethodJWT = "jwt" AuditAuthMethodAdminAPIKey = "admin_api_key" AuditAuthMethodPasskey = "passkey" + // AuditAuthMethodMCPOAuth 标记管理 MCP 的 OAuth 访问令牌(机器凭证)。 + AuditAuthMethodMCPOAuth = "mcp_oauth" // auditRequestBodyMaxBytes 请求体脱敏后入库的最大长度(字节),超出截断。 auditRequestBodyMaxBytes = 16 * 1024 diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index 0774923e6c..d121e2301e 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -86,6 +86,7 @@ type AuthService struct { affiliateService *AffiliateService defaultSubAssigner DefaultSubscriptionAssigner userPlatformQuotaRepo UserPlatformQuotaRepository + mcpGrantRevoker MCPGrantRevoker } type CaptchaProof struct { @@ -95,6 +96,11 @@ type CaptchaProof struct { TencentRandstr string } +// MCPGrantRevoker revokes MCP authorizations, which outlive browser sessions. +type MCPGrantRevoker interface { + RevokeAllGrants(ctx context.Context, userID int64) error +} + type DefaultSubscriptionAssigner interface { AssignOrExtendSubscription(ctx context.Context, input *AssignSubscriptionInput) (*UserSubscription, bool, error) } @@ -154,6 +160,10 @@ func (s *AuthService) SetAliyunCaptchaService(aliyunCaptchaService *AliyunCaptch s.aliyunCaptchaService = aliyunCaptchaService } +func (s *AuthService) SetMCPGrantRevoker(revoker MCPGrantRevoker) { + s.mcpGrantRevoker = revoker +} + // Register 用户注册,返回token和用户 func (s *AuthService) Register(ctx context.Context, email, password string) (string, *User, error) { return s.RegisterWithVerification(ctx, email, password, "", "", "", "") @@ -1907,6 +1917,13 @@ func (s *AuthService) RevokeAllUserTokens(ctx context.Context, userID int64) err if err := s.RevokeAllUserSessions(ctx, userID); err != nil { logger.LegacyPrintf("service.auth", "[Auth] Failed to revoke refresh sessions after token invalidation for user %d: %v", userID, err) } + // A browser JWT can mint a long-lived MCP grant, so revoking every session + // must also revoke those grants. Fail loudly: the caller can retry. + if s.mcpGrantRevoker != nil { + if err := s.mcpGrantRevoker.RevokeAllGrants(ctx, userID); err != nil { + return fmt.Errorf("revoke MCP grants: %w", err) + } + } return nil } diff --git a/backend/internal/service/mcp_oauth_service.go b/backend/internal/service/mcp_oauth_service.go index f74200f744..179d400206 100644 --- a/backend/internal/service/mcp_oauth_service.go +++ b/backend/internal/service/mcp_oauth_service.go @@ -11,6 +11,7 @@ import ( "net/url" "strings" "time" + "unicode" "unicode/utf8" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -24,6 +25,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 ) var ( @@ -31,6 +38,7 @@ 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 { @@ -149,7 +157,9 @@ type MCPOAuthCredential struct { } type MCPOAuthRepository interface { - CreateClient(context.Context, *MCPOAuthClient) error + // 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) CreateAuthorization(context.Context, *MCPOAuthGrant, *MCPOAuthCode, int) error GetCode(context.Context, string) (*MCPOAuthCode, error) @@ -162,6 +172,7 @@ type MCPOAuthRepository interface { TouchGrant(context.Context, string, time.Time) error ListGrants(context.Context, int64) ([]*MCPOAuthGrant, error) RevokeGrant(context.Context, int64, string, time.Time) error + RevokeUserGrants(context.Context, int64, time.Time) error } type MCPOAuthService struct { @@ -178,8 +189,8 @@ func (s *MCPOAuthService) Register(ctx context.Context, input MCPOAuthRegisterIn if input.ClientName == "" { input.ClientName = "MCP client" } - if !utf8.ValidString(input.ClientName) || utf8.RuneCountInString(input.ClientName) > 100 { - return nil, mcpOAuthError("invalid_client_metadata", "client_name must contain at most 100 characters") + if !validMCPClientName(input.ClientName) { + return nil, mcpOAuthError("invalid_client_metadata", "client_name must contain at most 100 printable characters") } if input.TokenEndpointAuthMethod != "" && input.TokenEndpointAuthMethod != "none" { return nil, mcpOAuthError("invalid_client_metadata", "Only public clients using token_endpoint_auth_method=none are supported") @@ -220,12 +231,26 @@ func (s *MCPOAuthService) Register(ctx context.Context, input MCPOAuthRegisterIn GrantTypes: append([]string(nil), grants...), ResponseTypes: []string{"code"}, TokenEndpointAuthMethod: "none", ClientIDIssuedAt: time.Now().UTC().Unix(), } - if err := s.repo.CreateClient(ctx, client); err != nil { + if err := s.repo.CreateClient(ctx, client, MCPOAuthPendingClientLimit); err != nil { return nil, err } return client, nil } +func validMCPClientName(name string) bool { + if !utf8.ValidString(name) || utf8.RuneCountInString(name) > 100 { + return false + } + for _, r := range name { + // Bidi overrides, zero-width and control characters can make the consent + // page show a self-reported name that looks like a different client. + if unicode.In(r, unicode.Cc, unicode.Cf, unicode.Co, unicode.Zl, unicode.Zp) { + return false + } + } + return true +} + func validMCPRedirectURI(raw string) bool { if len(raw) > 2048 || strings.ContainsAny(raw, "*#") { return false @@ -529,11 +554,13 @@ func (s *MCPOAuthService) Authenticate(ctx context.Context, raw string) (*MCPPri if err != nil { return nil, err } - if err := s.repo.TouchGrant(ctx, grant.ID, now); err != nil { - if errors.Is(err, ErrMCPOAuthNotFound) { - return nil, ErrMCPOAuthInvalidToken + if grant.LastUsedAt == nil || !now.Before(grant.LastUsedAt.Add(MCPOAuthTouchInterval)) { + if err := s.repo.TouchGrant(ctx, grant.ID, now); err != nil { + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil, ErrMCPOAuthInvalidToken + } + return nil, err } - return nil, err } return &MCPPrincipal{GrantID: grant.ID, UserID: user.ID, Role: user.Role, Scope: grant.Scope, ReadOnly: grant.ReadOnly, Concurrency: user.Concurrency, Email: user.Email, Resource: grant.Resource}, nil @@ -562,6 +589,12 @@ func (s *MCPOAuthService) RevokeGrant(ctx context.Context, userID int64, id stri return err } +// RevokeAllGrants persistently revokes every MCP authorization of the user, +// including refresh families, e.g. when all browser sessions are revoked. +func (s *MCPOAuthService) RevokeAllGrants(ctx context.Context, userID int64) error { + return s.repo.RevokeUserGrants(ctx, userID, time.Now().UTC()) +} + func (s *MCPOAuthService) RevokeToken(ctx context.Context, clientID, raw string) error { if !validMCPOAuthSecret(raw, "mcp_at_") && !validMCPOAuthSecret(raw, "mcp_rt_") { return nil diff --git a/backend/internal/service/mcp_oauth_service_test.go b/backend/internal/service/mcp_oauth_service_test.go index 1abf3d3c04..ec8df8aeb8 100644 --- a/backend/internal/service/mcp_oauth_service_test.go +++ b/backend/internal/service/mcp_oauth_service_test.go @@ -7,6 +7,8 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" + "errors" + "fmt" "net/url" "strings" "sync" @@ -22,11 +24,25 @@ type mcpOAuthMemoryRepo struct { grants map[string]*MCPOAuthGrant codes map[string]*MCPOAuthCode credentials map[string]*MCPOAuthCredential + touches int } -func (r *mcpOAuthMemoryRepo) CreateClient(_ context.Context, client *MCPOAuthClient) error { +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++ + } + } + if pending >= pendingLimit { + return ErrMCPOAuthClientLimit + } r.clients[client.ClientID] = client return nil } @@ -140,6 +156,7 @@ func (r *mcpOAuthMemoryRepo) TouchGrant(_ context.Context, id string, now time.T return ErrMCPOAuthNotFound } grant.LastUsedAt = &now + r.touches++ return nil } @@ -169,6 +186,17 @@ func (r *mcpOAuthMemoryRepo) RevokeGrant(_ context.Context, userID int64, id str return nil } +func (r *mcpOAuthMemoryRepo) RevokeUserGrants(_ context.Context, userID int64, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + for _, grant := range r.grants { + if grant.UserID == userID && grant.RevokedAt == nil { + grant.RevokedAt = &now + } + } + return nil +} + type mcpOAuthUserRepo struct { UserRepository user *User @@ -550,3 +578,80 @@ func TestMCPOAuthConcurrentCodeExchangeAllowsAtMostOneIssuance(t *testing.T) { require.Equal(t, 1, successes) require.Len(t, f.r.credentials, 2, "only one credential pair may be persisted") } + +func TestMCPOAuthRegistrationRejectsDisguisedClientNames(t *testing.T) { + f := newMCPOAuthFixture(t) + for _, name := range []string{"Claude\u202eedualC", "Clau\u200bde", "Claude\x07", "Claude\u2028Desktop", "Claude\ue000", strings.Repeat("x", 101)} { + _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: name, RedirectURIs: []string{"https://client.example/cb"}}) + requireMCPOAuthError(t, err, "invalid_client_metadata") + } + client, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: " 桌面助手 · Desktop (beta) ✨ ", RedirectURIs: []string{"https://client.example/cb"}}) + require.NoError(t, err) + require.Equal(t, "桌面助手 · Desktop (beta) ✨", client.ClientName) +} + +func TestMCPOAuthRegistrationStopsAtPendingClientLimit(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{} + } + _, 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 TestMCPOAuthAuthenticateThrottlesLastUsedWrites(t *testing.T) { + f := newMCPOAuthFixture(t) + tokens := f.tokens(t) + for i := 0; i < 3; i++ { + _, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.NoError(t, err) + } + require.Equal(t, 1, f.r.touches) + for _, grant := range f.r.grants { + stale := time.Now().Add(-MCPOAuthTouchInterval - time.Second) + grant.LastUsedAt = &stale + } + _, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.NoError(t, err) + require.Equal(t, 2, f.r.touches) +} + +func TestMCPOAuthRevokeAllGrantsEndsEveryFamily(t *testing.T) { + f := newMCPOAuthFixture(t) + first, second := f.tokens(t), f.tokens(t) + require.NoError(t, f.s.RevokeAllGrants(context.Background(), 7)) + for _, tokens := range []*MCPOAuthTokenResponse{first, second} { + _, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) + _, err = f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "refresh_token", ClientID: f.client.ClientID, RefreshToken: tokens.RefreshToken}, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + } + grants, err := f.s.ListGrants(context.Background(), 7) + require.NoError(t, err) + require.Len(t, grants, 2) + for _, grant := range grants { + require.NotNil(t, grant.RevokedAt) + } +} + +type mcpGrantRevokerStub struct { + userIDs []int64 + err error +} + +func (r *mcpGrantRevokerStub) RevokeAllGrants(_ context.Context, userID int64) error { + r.userIDs = append(r.userIDs, userID) + return r.err +} + +func TestRevokeAllUserTokensAlsoRevokesMCPGrants(t *testing.T) { + revoker := &mcpGrantRevokerStub{} + auth := &AuthService{userRepo: &mcpOAuthUserRepo{user: &User{ID: 7, Status: StatusActive}}} + auth.SetMCPGrantRevoker(revoker) + require.NoError(t, auth.RevokeAllUserTokens(context.Background(), 7)) + require.Equal(t, []int64{7}, revoker.userIDs) + revoker.err = errors.New("database unavailable") + require.ErrorIs(t, auth.RevokeAllUserTokens(context.Background(), 7), revoker.err) +} diff --git a/backend/internal/service/setting_public.go b/backend/internal/service/setting_public.go index 9bf3c7d915..35d379b5d6 100644 --- a/backend/internal/service/setting_public.go +++ b/backend/internal/service/setting_public.go @@ -346,6 +346,7 @@ func (s *SettingService) GetPublicSettings(ctx context.Context) (*PublicSettings WeChatOAuthMPEnabled: weChatMPEnabled, WeChatOAuthMobileEnabled: weChatMobileEnabled, BackendModeEnabled: settings[SettingKeyBackendModeEnabled] == "true", + MCPEnabled: s.cfg != nil && s.cfg.MCP.Enabled(), PaymentEnabled: settings[SettingPaymentEnabled] == "true", PaymentBalanceDisabled: settings[SettingBalancePayDisabled] == "true", OIDCOAuthEnabled: oidcEnabled, @@ -609,6 +610,7 @@ type PublicSettingsInjectionPayload struct { GitHubOAuthEnabled bool `json:"github_oauth_enabled"` GoogleOAuthEnabled bool `json:"google_oauth_enabled"` BackendModeEnabled bool `json:"backend_mode_enabled"` + MCPEnabled bool `json:"mcp_enabled"` PaymentEnabled bool `json:"payment_enabled"` PaymentBalanceDisabled bool `json:"payment_balance_disabled"` Version string `json:"version"` @@ -703,6 +705,7 @@ func (s *SettingService) GetPublicSettingsForInjection(ctx context.Context) (any GitHubOAuthEnabled: settings.GitHubOAuthEnabled, GoogleOAuthEnabled: settings.GoogleOAuthEnabled, BackendModeEnabled: settings.BackendModeEnabled, + MCPEnabled: settings.MCPEnabled, PaymentEnabled: settings.PaymentEnabled, PaymentBalanceDisabled: settings.PaymentBalanceDisabled, Version: s.version, diff --git a/backend/internal/service/setting_service_public_test.go b/backend/internal/service/setting_service_public_test.go index d2485639c3..dcda6b73b4 100644 --- a/backend/internal/service/setting_service_public_test.go +++ b/backend/internal/service/setting_service_public_test.go @@ -4,6 +4,8 @@ package service import ( "context" + "encoding/json" + "fmt" "testing" "github.com/Wei-Shaw/sub2api/internal/config" @@ -309,3 +311,26 @@ func TestSettingService_GetPublicSettings_PaymentBalanceDisabledStrictTrue(t *te }) } } + +func TestSettingService_GetPublicSettings_MCPEnabledFollowsExplicitPublicURL(t *testing.T) { + for _, tc := range []struct { + publicURL, frontendURL string + want bool + }{ + {"https://api.example.com/api/v1/mcp", "", true}, + // A frontend URL alone never enables MCP. + {"", "https://platform.example.com", false}, + {" ", "", false}, + } { + cfg := &config.Config{MCP: config.MCPConfig{PublicURL: tc.publicURL}} + cfg.Server.FrontendURL = tc.frontendURL + settings, err := NewSettingService(&settingPublicRepoStub{values: map[string]string{}}, cfg).GetPublicSettings(context.Background()) + require.NoError(t, err) + require.Equal(t, tc.want, settings.MCPEnabled, tc) + payload, err := NewSettingService(&settingPublicRepoStub{values: map[string]string{}}, cfg).GetPublicSettingsForInjection(context.Background()) + require.NoError(t, err) + encoded, err := json.Marshal(payload) + require.NoError(t, err) + require.Contains(t, string(encoded), fmt.Sprintf(`"mcp_enabled":%t`, tc.want)) + } +} diff --git a/backend/internal/service/settings_view.go b/backend/internal/service/settings_view.go index 8535fb6b8b..7d94a5397d 100644 --- a/backend/internal/service/settings_view.go +++ b/backend/internal/service/settings_view.go @@ -375,6 +375,7 @@ type PublicSettings struct { WeChatOAuthMPEnabled bool WeChatOAuthMobileEnabled bool BackendModeEnabled bool + MCPEnabled bool // 由部署配置 MCP_PUBLIC_URL 决定,不可在后台修改 PaymentEnabled bool PaymentBalanceDisabled bool OIDCOAuthEnabled bool diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 5fae3b0536..d24d33a1a4 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -71,6 +71,7 @@ func ProvideAuthService( defaultSubAssigner DefaultSubscriptionAssigner, affiliateService *AffiliateService, userPlatformQuotaRepo UserPlatformQuotaRepository, + mcpOAuthService *MCPOAuthService, ) *AuthService { svc := NewAuthService( entClient, @@ -89,6 +90,9 @@ func ProvideAuthService( ) svc.SetTencentCaptchaService(tencentCaptchaService) svc.SetAliyunCaptchaService(aliyunCaptchaService) + if mcpOAuthService != nil { + svc.SetMCPGrantRevoker(mcpOAuthService) + } return svc } diff --git a/deploy/.env.example b/deploy/.env.example index 4aec7ec545..0e8ce5304e 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -31,8 +31,9 @@ UPDATE_GITHUB_TOKEN= ENABLE_SERVER_TIMING=false # Canonical public MCP endpoint for OAuth discovery, e.g. https://example.com/api/v1/mcp. -# MCP OAuth 固定对外地址;留空使用已配置的前端地址来源,不使用请求中的 Host。 -# HTTPS required except localhost/loopback development; exact /api/v1/mcp path, no trailing slash. +# Leave empty to keep the management MCP and its OAuth endpoints disabled (default). +# MCP OAuth 固定对外地址;留空则关闭 MCP(默认),不会回落到前端地址或请求中的 Host。 +# HTTPS required except localhost/loopback development; exact /api/v1/mcp path at the site root, no trailing slash. MCP_PUBLIC_URL= # Apple container image overrides (ignored by Docker Compose). Pin release tags diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index c7eb2b469e..a4a32027bd 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -126,10 +126,10 @@ cors: mcp: # Canonical public MCP endpoint, e.g. https://example.com/api/v1/mcp. # 固定的 MCP 对外地址,例如 https://example.com/api/v1/mcp。 - # Leave empty to use the trusted frontend URL's origin with /api/v1/mcp. - # 留空时使用已配置的前端地址来源并追加 /api/v1/mcp;不使用请求中的 Host。 - # HTTPS is required except localhost/loopback development; no trailing slash. - # 除 localhost/回环 IP 开发环境外必须使用 HTTPS,路径末尾不加斜杠。 + # Leave empty to keep the management MCP and its OAuth endpoints disabled (default). + # 留空则关闭 MCP 及其 OAuth 接口(默认),不会回落到前端地址或请求中的 Host。 + # HTTPS is required except localhost/loopback development; site-root /api/v1/mcp path, no trailing slash. + # 除 localhost/回环 IP 开发环境外必须使用 HTTPS;路径固定为站点根下的 /api/v1/mcp,末尾不加斜杠。 # Environment / 环境变量: MCP_PUBLIC_URL public_url: "" diff --git a/docs/mcp.md b/docs/mcp.md index 7fe8402312..567545c515 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4,7 +4,7 @@ ## 部署 -配置稳定、可信的公开 MCP 地址,例如: +MCP 默认关闭。只有显式配置稳定、可信的公开 MCP 地址后,才会开放 MCP 资源端点、OAuth 发现及客户端注册接口,侧栏也才会显示 **MCP 接入**。例如: ```sh MCP_PUBLIC_URL=https://api.example.com/api/v1/mcp @@ -17,7 +17,7 @@ mcp: public_url: https://api.example.com/api/v1/mcp ``` -地址必须以 `/api/v1/mcp` 结束,不带尾斜杠、查询参数或片段。生产环境使用 HTTPS;本机开发允许 localhost 或回环 IP 的 HTTP 地址。未显式配置时,可使用平台已配置的前端 URL 的 origin 加 `/api/v1/mcp`;服务不会从请求 Host 或转发头推断 OAuth issuer。没有可信公开地址时,OAuth 接口会返回配置错误。 +地址必须是站点根路径下的 `/api/v1/mcp`,不带尾斜杠、查询参数或片段;OAuth 发现端点同样位于站点根路径,因此不支持挂在子路径(如 `https://example.com/sub2api/`)下部署。生产环境使用 HTTPS;本机开发允许 localhost 或回环 IP 的 HTTP 地址。服务不会从前端 URL、请求 Host 或转发头推断该地址;未配置时 MCP 及其 OAuth 接口均返回 503。清空该配置即可关闭 MCP,已签发的令牌随之无法使用。 同域部署只需上述 MCP 地址。前后端分域时,另外配置平台前端 URL(管理设置或 `SERVER_FRONTEND_URL`),用于定位浏览器授权页。反向代理需转发 `/api/v1/mcp`、`/api/v1/mcp/oauth/*` 及下列 `/.well-known/*` 发现端点,保留 Authorization、Accept 和 MCP 协议请求头。浏览器客户端访问 MCP 资源仍需符合平台的 CORS/Origin 白名单。 @@ -44,7 +44,7 @@ mcp: ## 授权与撤销 -默认授权为**个人范围、只读**。管理员可以在明确同意时选择管理员范围;启用平台敏感操作二次验证时,授予管理员范围同样需要 step-up。 +默认授权为**个人范围、只读**。管理员可以在明确同意时选择管理员范围;启用平台敏感操作二次验证时,授予管理员范围同样需要 step-up。授予**管理员范围的读写**权限时,无论是否启用该开关,都必须已开启 TOTP 并完成一次 step-up 验证。 - **个人范围**:只操作当前用户的数据,即使授权人是管理员也不会开放管理工具。 - **管理员范围**:仅管理员可授予,可使用目录内管理工具及自己的个人工具。 @@ -55,7 +55,7 @@ OAuth scope 为 `mcp`,实际工具权限由浏览器中确认的授权范围 授权码有效期 5 分钟且只能兑换一次。访问令牌有效期最多 10 分钟;授权及刷新令牌最长 30 天,刷新令牌每次使用都会轮换。重复使用授权码或已消费的刷新令牌会撤销该授权。服务端仅保存凭证摘要。 -登录平台后,侧栏 **MCP 接入**(`/settings/mcp`)可查看并撤销已授权应用。每用户最多 20 个有效授权。撤销、密码或登录标识变更、用户停用都会阻止后续调用及刷新;管理员失去角色后,其管理员授权也失效。页面不显示访问或刷新令牌,MCP 工具无法自行授予新授权。 +登录平台后,侧栏 **MCP 接入**(`/settings/mcp`)可查看并撤销已授权应用。每用户最多 20 个有效授权。撤销、密码或登录标识变更、用户停用都会阻止后续调用及刷新;管理员失去角色后,其管理员授权也失效。“撤销全部会话”会同时撤销该用户的全部 MCP 授权。停用用户会持久撤销其全部授权,取消管理员角色会持久撤销其管理员授权,之后重新启用或重新授予角色也不会恢复旧授权。页面不显示访问或刷新令牌,MCP 工具无法自行授予新授权。 ## 工具目录 @@ -78,7 +78,7 @@ OAuth scope 为 `mcp`,实际工具权限由浏览器中确认的授权范围 工具只开放明确列出的字段;不提供任意 HTTP 请求、任意 URL、密码/角色修改、身份绑定、上游凭证管理、备份恢复或支付工具。普通查询和修改结果会去除 API Key、上游令牌等凭证。`user_create_api_key` 的创建结果包含新 API Key,便于配置应用;不要将该结果公开分享。 -现有业务权限、资源归属、平台模式限制、管理合规确认、限流和操作审计继续生效。模型返回的建议不会绕过这些规则。 +现有业务权限、资源归属、平台模式限制、管理合规确认、限流和操作审计继续生效。模型返回的建议不会绕过这些规则。MCP 的每次工具调用(包括只读查询)都会写入操作审计,认证方式为 `mcp_oauth`,并附带 `mcp_grant_id` 和 `mcp_tool`。 ## 参数示例 @@ -149,7 +149,7 @@ OAuth scope 为 `mcp`,实际工具权限由浏览器中确认的授权范围 | `POST /api/v1/mcp/oauth/token` | 授权码兑换与刷新,表单编码 | | `POST /api/v1/mcp/oauth/revoke` | RFC 7009 撤销,表单编码 | -未认证 MCP 请求返回 401,`WWW-Authenticate` 提供 `resource_metadata` 和 `scope="mcp"`。客户端只支持 `token_endpoint_auth_method=none`、`response_type=code`、S256 PKCE,以及授权码/刷新两种 grant type。回调 URI 必须与注册值精确匹配,使用 HTTPS 或本机 HTTP;不支持通配符。当前不提供远程 client metadata URL 自动抓取。 +未认证 MCP 请求返回 401,`WWW-Authenticate` 提供 `resource_metadata` 和 `scope="mcp"`。客户端只支持 `token_endpoint_auth_method=none`、`response_type=code`、S256 PKCE,以及授权码/刷新两种 grant type。回调 URI 必须与注册值精确匹配,使用 HTTPS 或本机 HTTP;不支持通配符。当前不提供远程 client metadata URL 自动抓取。注册请求体不超过 4 KiB;`client_name` 最多 100 个字符,且不得包含控制字符、双向文本控制符或零宽字符等不可见字符。 授权请求和授权码兑换必须携带精确匹配 MCP 地址的 `resource`。刷新可省略 `resource`,此时沿用原授权;传入不同资源会被拒绝。`state` 会原样返回客户端。授权码与客户端、回调、资源和 PKCE 绑定;客户端应安全保管 verifier 和刷新令牌。 @@ -160,12 +160,12 @@ curl 'https://api.example.com/.well-known/oauth-protected-resource/api/v1/mcp' curl 'https://api.example.com/.well-known/oauth-authorization-server' ``` -服务使用官方 Go MCP SDK 的无状态 Streamable HTTP 模式,POST 返回 JSON;GET 事件流和 DELETE 会话操作返回 405。每次 HTTP 请求重新校验授权,响应禁止缓存。业务 API 失败以工具结果 `isError: true` 返回,原 HTTP 状态位于 `structuredContent.http_status`。工具执行限制 30 秒并传递客户端断开取消;写操作超时后应查询状态再决定是否重试。 +服务使用官方 Go MCP SDK 的无状态 Streamable HTTP 模式,POST 返回 JSON;GET 事件流和 DELETE 会话操作返回 405。每个 HTTP 请求只能包含一个 JSON-RPC 对象,JSON-RPC 批量请求(包括未声明 `MCP-Protocol-Version` 的旧版本请求)一律返回 400。每次 HTTP 请求重新校验授权,响应禁止缓存。工具结果以单个文本块返回 JSON `{"http_status": …, "result": …}`,不再重复写入 `structuredContent`;编码后超过 2 MiB 的结果会被拒绝,请缩小查询范围或分页大小。业务 API 失败以工具结果 `isError: true` 返回,原 HTTP 状态位于 `http_status`。工具执行限制 30 秒并传递客户端断开取消;写操作超时后应查询状态再决定是否重试。 -MCP 协议请求使用独立入口限流桶;每个实际工具调用只消耗一次管理面全局额度,聚合统计仍受 Heavy 限流。动态注册、兑换和撤销接口有独立 IP 限流,Redis 不可用时拒绝请求。 +`/api/v1/mcp` 在认证前先按客户端 IP 限流(每分钟 600 次),认证后再使用独立的按用户入口限流桶;每个实际工具调用只消耗一次管理面全局额度,聚合统计仍受 Heavy 限流。授权的最近使用时间每分钟最多写入一次。动态注册、兑换和撤销接口有独立 IP 限流。上述 IP 限流把同一 IPv6 /64 网段视为一个客户端,Redis 不可用时拒绝请求。 ## 开发 工具目录位于 `backend/internal/managementmcp/catalog.go`。新增工具应绑定已有管理路由,使用封闭参数 schema,并覆盖权限、资源归属、参数边界及凭证脱敏测试。 -OAuth 存储由 `249_mcp_oauth.sql` 创建。注册时有界清理过期 7 天以上的授权,以及 90 天前注册且无授权关联的客户端。浏览器使用 JWT 保护的 `/api/v1/user/mcp/config` 获取服务端配置的连接地址、`/api/v1/user/mcp/authorize` 预览/决定授权,以及 `/api/v1/user/mcp/grants` 列表、撤销接口。客户端协议端点返回标准 OAuth JSON,浏览器接口沿用平台响应格式。 +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,浏览器接口沿用平台响应格式。