diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index c9a140f886..d1b420aa94 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -54,7 +54,7 @@ jobs: - name: Setup Node.js uses: actions/setup-node@v6 with: - node-version: '20' + node-version: '24' cache: 'pnpm' cache-dependency-path: frontend/pnpm-lock.yaml - name: Install frontend dependencies diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9cef765b62..9f2ef5dd7d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -92,7 +92,7 @@ jobs: version: 9 - uses: actions/setup-node@v6 with: - node-version: '20' + node-version: '24' cache: pnpm cache-dependency-path: frontend/pnpm-lock.yaml - run: pnpm install --frozen-lockfile diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml index 88da184e5d..703e10354a 100644 --- a/.github/workflows/security-scan.yml +++ b/.github/workflows/security-scan.yml @@ -41,7 +41,7 @@ jobs: - name: Set up Node.js uses: actions/setup-node@v6 with: - node-version: '20' + node-version: '24' cache: 'pnpm' cache-dependency-path: frontend/pnpm-lock.yaml - name: Install dependencies diff --git a/.gitignore b/.gitignore index 93d301f157..1af51f759f 100644 --- a/.gitignore +++ b/.gitignore @@ -133,7 +133,9 @@ deploy/docker-compose.override.yml .gocache/ vite.config.js docs/* +!docs/agent-resource-safety.md !docs/admin-api-keys.md +!docs/mcp.md !docs/PAYMENT.md !docs/PAYMENT_CN.md !docs/ADMIN_PAYMENT_INTEGRATION_API.md diff --git a/README.md b/README.md index 81c9dc3ae4..259c3ddfa8 100644 --- a/README.md +++ b/README.md @@ -34,11 +34,11 @@ Please read the following carefully before using this project:
Click to collapse -

WandAPI

+

WandAPI

-**[WandAPI](https://wandapi.ai/r/sub2api)** — an enterprise-grade, stable AI model API gateway built by a core contributor to this project. One API key gives you access to Claude, GPT, Gemini and other leading models, natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex and your existing SDKs work by simply changing the Base URL. Real-time routing by latency and upstream health with millisecond-level automatic failover keeps requests online, backed by 99.99% service availability. Pay as you go, with per-request token and cost breakdowns. +**[WandAPI](https://wandapi.com/go/sub2api)** — an enterprise-grade, stable AI model API gateway built by a core contributor to this project. One API key gives you access to Claude, GPT, Gemini and other leading models, natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex and your existing SDKs work by simply changing the Base URL. Real-time routing by latency and upstream health with millisecond-level automatic failover keeps requests online, backed by 99.99% service availability. Pay as you go, with per-request token and cost breakdowns. -**Free trial credits**: sign up via [this exclusive link](https://wandapi.ai/r/sub2api) to claim free trial credits. +**Free trial credits**: sign up via [this exclusive link](https://wandapi.com/go/sub2api) to claim free trial credits. --- @@ -65,8 +65,8 @@ Please read the following carefully before using this project: -AIGoCode -Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via this link, you'll receive an extra 10% bonus credit on your first top-up! +AIGoCode +Thanks to AIGoCode for sponsoring this project! A subscription-based AI coding platform, not just pay-per-token. One account, one monthly plan for Claude Code, Codex and Gemini, with direct connection on the mainland and fast responses. Subscribe via this link to get an extra 10% credits! @@ -137,11 +137,6 @@ Please read the following carefully before using this project: Swiftproxy is a high-performance proxy solution built for developers, providing stable and reliable residential and static residential proxy services. With 90M+ clean residential IPs, global coverage, flexible rotation, and precise geo-targeting, it helps projects such as web scraping, AI automation, browser automation, SEO monitoring, and multi-account management overcome access restrictions and improve workflow efficiency. It supports HTTP(S) and SOCKS5 protocols, integrates with popular automation tools like Playwright, Selenium, and Puppeteer, with dynamic proxy traffic that never expires until used and free testing available — start your free test now! - -APIMart -Thanks to APIMart for sponsoring this project! APIMart is a low-cost API platform for AI image and video generation — GPT-Image-2 from $0.006 per image, with 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, and retrieve results via polling or callback. Batch tens of thousands of images without timeouts, and switch models without changing code. Pay as you go with no monthly fee — sign up here to get started. - - AxisNow Thanks to AxisNow for sponsoring this project! AxisNow protects and accelerates websites and APIs, delivering an optimal access experience across mainland China and globally, while extending acceleration and security capabilities to native/mobile apps through client SDKs — self-hosted private-deployment CDN | subscription-based DDoS-protected CDN | autonomous, flexibly composable CDN network. @@ -182,6 +177,11 @@ Please read the following carefully before using this project: Thanks to SoleAPI for supporting this project! SoleAPI is an AI model gateway for developers and enterprises: one API key gives you access to 30+ leading models including Claude, GPT and Gemini. It is natively compatible with the OpenAI and Anthropic protocols, so Claude Code, Codex, Cursor and your existing SDKs work by simply changing the Base URL. Requests are routed in real time by latency and upstream health, with millisecond-level automatic failover to backup channels, 99.99% service availability and 24/7 technical support. Every call lands on a single bill with per-request token and cost breakdowns you can inspect at any time. Sign up through this project's referral link to receive free trial credits, and earn ongoing cashback by inviting friends who top up! + +MaruCode +MaruCode — a small, no-frills API site that does a bit of charity now and then. 🍟 Every Thursday it runs limited-time rate-multiplier events. In operation for over half a year, with a 3K-member main group, focused on stability and welcoming collaboration with universities, enterprises, and more — thank you 🙇. It runs a self-operated account pool with no top-up marketing gimmicks, mainly offering mainstream models such as Codex (GPT 6.2 Astra), Claude Code (Claude Opus 5.5), and GPT Image 2.6, with WebSocket protocol support, clearly published pricing (Codex 0.3x, CC 1.7x), and a transparent exchange rate (1:1). + +
diff --git a/README_CN.md b/README_CN.md index 7199015a71..61b7a4f5da 100644 --- a/README_CN.md +++ b/README_CN.md @@ -35,11 +35,11 @@
点击折叠 -

WandAPI

+

WandAPI

-**[WandAPI](https://wandapi.ai/r/sub2api)** —— 由该项目核心贡献者打造的企业级稳定 AI 大模型 API 网关。一个 API Key 即可调用 Claude、GPT、Gemini 等主流模型,原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex 及现有 SDK 只需修改 Base URL 即可接入。按延迟与上游健康度实时路由,毫秒级自动故障切换,请求不掉线;服务可用性达 99.99%。按量计费,每次请求的 token 与费用明细清晰可查。 +**[WandAPI](https://wandapi.com/go/sub2api)** —— 由该项目核心贡献者打造的企业级稳定 AI 大模型 API 网关。一个 API Key 即可调用 Claude、GPT、Gemini 等主流模型,原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex 及现有 SDK 只需修改 Base URL 即可接入。按延迟与上游健康度实时路由,毫秒级自动故障切换,请求不掉线;服务可用性达 99.99%。按量计费,每次请求的 token 与费用明细清晰可查。 -**免费试用额度**:通过[专属链接](https://wandapi.ai/r/sub2api)注册,即可领取免费试用额度。 +**免费试用额度**:通过[专属链接](https://wandapi.com/go/sub2api)注册,即可领取免费试用额度。 --- @@ -66,8 +66,8 @@ -AIGoCode -感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过此链接注册,首次充值可额外获得 10% 赠送额度! +AIGoCode +感谢 AIGoCode 赞助了本项目!订阅制 AI 编程平台,不只按token 算钱。一个账号包月畅用 Claude Code、Codex、Gemini,国内直连、响应快。通过此链接订阅额外送 10% 额度! @@ -140,11 +140,6 @@ Swiftproxy 是面向开发者的高性能代理解决方案,提供稳定可靠的住宅代理和静态住宅代理服务。拥有 9000 万+ 纯净住宅 IP,覆盖全球,支持灵活轮换和精准地理定位,帮助网页抓取、AI 自动化、浏览器自动化、SEO 监控和多账号管理等项目突破访问限制,提升工作流效率。支持 HTTP(S) 和 SOCKS5 协议,兼容 Playwright、Selenium、Puppeteer 等主流自动化工具,动态代理流量用完为止永不过期,支持免费测试 — 立即开始免费测试! - -APIMart -感谢 APIMart 赞助了本项目!APIMart 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过此注册链接注册即可开始使用。 - - AxisNow 感谢 AxisNow 赞助了本项目!AxisNow 保护并加速网站与 API,兼顾中国大陆及全球的访问体验,并通过客户端 SDK,将加速与安全能力延伸至原生/移动 App — 自建私有部署 CDN|订阅式高防 CDN|自主可控、灵活组合的 CDN 网络。 @@ -185,6 +180,11 @@ 感谢 SoleAPI 对本项目的支持!SoleAPI 是面向开发者与企业的 AI 模型网关:一个 API Key 即可调用 Claude、GPT、Gemini 等 30+ 主流模型。原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex、Cursor 及现有 SDK 只需修改 Base URL 即可接入。请求按延迟与上游健康度实时路由,毫秒级自动切换至备用通道,服务可用性达 99.99%,并提供 7×24 小时技术支持。所有调用统一账单结算,每次请求的 token 与费用明细随时可查。通过本项目的推荐链接注册即可获得免费试用额度,邀请好友充值还可持续获得返现! + +MaruCode +MaruCode ——偶尔做做慈善的小破站 API,站内 🍟每周星期四 会做 限时倍率活动 ,目前已运营半年有余,大群3K人,主打稳定、欢迎高校、企业等合作,感谢🙇,目前已经营半年有余,自营号池,不搞充值营销套路,主要提供 Codex(GPT 6.2 Astra)、Claude Code(Claude Opus 5.5)、GPT Image 2.6 等主流模型,支持 WebSocket 协议,明码标价(Codex 0.3x, CC 1.7x),透明汇率(1:1) + +
diff --git a/README_JA.md b/README_JA.md index a7bb2c47dc..0107d019ff 100644 --- a/README_JA.md +++ b/README_JA.md @@ -34,11 +34,11 @@
クリックで折りたたむ -

WandAPI

+

WandAPI

-**[WandAPI](https://wandapi.ai/r/sub2api)** — 本プロジェクトのコアコントリビューターが手がける、エンタープライズグレードで安定した AI モデル API ゲートウェイ。1 つの API キーで Claude、GPT、Gemini などの主要モデルを利用でき、OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex や既存の SDK も Base URL を変更するだけで接続できます。レイテンシと上流の稼働状況に応じたリアルタイムルーティングとミリ秒単位の自動フェイルオーバーでリクエストを途切れさせず、99.99% のサービス可用性を実現します。従量課金で、リクエストごとの token 数と費用の内訳を確認できます。 +**[WandAPI](https://wandapi.com/go/sub2api)** — 本プロジェクトのコアコントリビューターが手がける、エンタープライズグレードで安定した AI モデル API ゲートウェイ。1 つの API キーで Claude、GPT、Gemini などの主要モデルを利用でき、OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex や既存の SDK も Base URL を変更するだけで接続できます。レイテンシと上流の稼働状況に応じたリアルタイムルーティングとミリ秒単位の自動フェイルオーバーでリクエストを途切れさせず、99.99% のサービス可用性を実現します。従量課金で、リクエストごとの token 数と費用の内訳を確認できます。 -**無料トライアルクレジット**:[専用リンク](https://wandapi.ai/r/sub2api)から登録すると、無料トライアルクレジットを受け取れます。 +**無料トライアルクレジット**:[専用リンク](https://wandapi.com/go/sub2api)から登録すると、無料トライアルクレジットを受け取れます。 --- @@ -65,8 +65,8 @@ -AIGoCode -AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:こちらのリンクから登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント! +AIGoCode +AIGoCode のご支援に感謝します!トークン従量課金だけではない、サブスクリプション型の AI コーディングプラットフォームです。1 つのアカウント・月額プランで Claude Code、Codex、Gemini を使い放題。中国本土から直接接続でき、レスポンスも高速です。こちらのリンクから購読すると、10% の追加クレジットをプレゼント! @@ -139,11 +139,6 @@ Swiftproxy は開発者向けの高性能プロキシソリューションで、安定して信頼できるレジデンシャルおよび静的レジデンシャルプロキシサービスを提供します。9,000 万以上のクリーンな住宅 IP を保有し、グローバルカバレッジ、柔軟なローテーション、精密なジオターゲティングにより、Web スクレイピング、AI オートメーション、ブラウザ自動化、SEO モニタリング、マルチアカウント管理などのプロジェクトがアクセス制限を克服し、ワークフロー効率を向上させます。HTTP(S) および SOCKS5 プロトコルに対応し、Playwright、Selenium、Puppeteer などの主要な自動化ツールと統合可能。動的プロキシトラフィックは使い切るまで期限切れなし、無料テストも利用可能 — 今すぐ無料テストを開始! - -APIMart -APIMart のご支援に感謝します!APIMart は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、こちらの登録リンクからすぐに利用を開始できます。 - - AxisNow AxisNow のご支援に感謝します!AxisNow はウェブサイトと API を保護・高速化し、中国本土および世界中で快適なアクセス体験を実現します。クライアント SDK により、ネイティブ/モバイルアプリにも高速化・セキュリティ機能を拡張できます — 自社構築・プライベートデプロイ CDN|サブスクリプション型高防御 CDN|自律制御で柔軟に組み合わせられる CDN ネットワーク。 diff --git a/assets/partners/logos/aigocode-dark.png b/assets/partners/logos/aigocode-dark.png new file mode 100644 index 0000000000..e3751ea39a Binary files /dev/null and b/assets/partners/logos/aigocode-dark.png differ diff --git a/assets/partners/logos/aigocode.png b/assets/partners/logos/aigocode.png index 6dd5965ac5..caef207431 100644 Binary files a/assets/partners/logos/aigocode.png and b/assets/partners/logos/aigocode.png differ diff --git a/assets/partners/logos/apimart.jpg b/assets/partners/logos/apimart.jpg deleted file mode 100644 index e670cea236..0000000000 Binary files a/assets/partners/logos/apimart.jpg and /dev/null differ diff --git a/assets/partners/logos/marucode.jpg b/assets/partners/logos/marucode.jpg new file mode 100644 index 0000000000..7eb285bc36 Binary files /dev/null and b/assets/partners/logos/marucode.jpg differ diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index 51e8fdc95c..6bf5ecb605 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.2.18 +0.2.19 diff --git a/backend/cmd/server/wire.go b/backend/cmd/server/wire.go index 6834ad78df..05c3334f13 100644 --- a/backend/cmd/server/wire.go +++ b/backend/cmd/server/wire.go @@ -111,6 +111,8 @@ func provideCleanup( emailQueue *service.EmailQueueService, billingCache *service.BillingCacheService, usageRecordWorkerPool *service.UsageRecordWorkerPool, + balanceNotify *service.BalanceNotifyService, + digestSessions *service.DigestSessionStore, subscriptionService *service.SubscriptionService, oauth *service.OAuthService, openaiOAuth *service.OpenAIOAuthService, @@ -143,6 +145,18 @@ func provideCleanup( // 应用层清理步骤可并行执行,基础设施资源(Redis/Ent)最后按顺序关闭。 parallelSteps := []cleanupStep{ + {"DigestSessionStore", func() error { + if digestSessions != nil { + digestSessions.Close() + } + return nil + }}, + {"BalanceNotifyService", func() error { + if balanceNotify != nil { + balanceNotify.Stop() + } + return nil + }}, {"PluginManager", func() error { if pluginManager != nil { pluginManager.Stop() diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 49e42b4c7d..1356765b79 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -49,10 +49,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { redeemCodeRepository := repository.NewRedeemCodeRepository(client) redisClient := repository.ProvideRedis(configConfig) refreshTokenCache := repository.NewRefreshTokenCache(redisClient) + scopedAdminKeyRepository := repository.NewScopedAdminKeyRepository(db) settingRepository := repository.NewSettingRepository(client) groupRepository := repository.NewGroupRepository(client, db) proxyRepository := repository.NewProxyRepository(client, db) - scopedAdminKeyRepository := repository.NewScopedAdminKeyRepository(db) settingService := service.ProvideSettingService(scopedAdminKeyRepository, settingRepository, groupRepository, proxyRepository, configConfig) emailCache := repository.NewEmailCache(redisClient) emailService := service.NewEmailService(settingRepository, emailCache) @@ -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(client, db) + mcpoAuthService := service.NewMCPOAuthService(mcpoAuthRepository, userRepository) + authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository, mcpoAuthService) userService := service.NewUserService(userRepository, settingRepository, apiKeyAuthCacheInvalidator, billingCache) redeemCache := repository.NewRedeemCache(redisClient) redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator, affiliateService) @@ -98,6 +100,7 @@ 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) + mcpoAuthHandler := handler.NewMCPOAuthHandler(mcpoAuthService, totpService, userService, settingService, configConfig) apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService) usageLogRepository := repository.NewUsageLogRepository(client, db) usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator) @@ -328,7 +331,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache) - handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService) + handlers := handler.ProvideHandlers(authHandler, userHandler, mcpoAuthHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService) jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService) optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService) adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService) @@ -356,7 +359,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher) channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService) userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService) - v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) + v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager) application := &Application{ Server: httpServer, PromptAudit: promptService, @@ -423,6 +426,8 @@ func provideCleanup( emailQueue *service.EmailQueueService, billingCache *service.BillingCacheService, usageRecordWorkerPool *service.UsageRecordWorkerPool, + balanceNotify *service.BalanceNotifyService, + digestSessions *service.DigestSessionStore, subscriptionService *service.SubscriptionService, oauth *service.OAuthService, openaiOAuth *service.OpenAIOAuthService, @@ -454,6 +459,18 @@ func provideCleanup( } parallelSteps := []cleanupStep{ + {"DigestSessionStore", func() error { + if digestSessions != nil { + digestSessions.Close() + } + return nil + }}, + {"BalanceNotifyService", func() error { + if balanceNotify != nil { + balanceNotify.Stop() + } + return nil + }}, {"PluginManager", func() error { if pluginManager != nil { pluginManager.Stop() diff --git a/backend/cmd/server/wire_gen_test.go b/backend/cmd/server/wire_gen_test.go index bb56c6735f..b8e601a508 100644 --- a/backend/cmd/server/wire_gen_test.go +++ b/backend/cmd/server/wire_gen_test.go @@ -81,6 +81,8 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) { emailQueueSvc, billingCacheSvc, &service.UsageRecordWorkerPool{}, + service.ProvideBalanceNotifyService(nil, nil, nil, nil), + service.NewDigestSessionStore(), &service.SubscriptionService{}, oauthSvc, openAIOAuthSvc, diff --git a/backend/go.mod b/backend/go.mod index 50865afb0c..0d90a18229 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -30,6 +30,7 @@ require ( github.com/imroc/req/v3 v3.59.0 github.com/klauspost/compress v1.18.2 github.com/lib/pq v1.10.9 + github.com/modelcontextprotocol/go-sdk v1.4.1 github.com/patrickmn/go-cache v2.1.0+incompatible github.com/pquerna/otp v1.5.0 github.com/redis/go-redis/v9 v9.22.0 @@ -51,12 +52,12 @@ require ( github.com/wechatpay-apiv3/wechatpay-go v0.2.21 github.com/zeromicro/go-zero v1.9.4 go.uber.org/zap v1.24.0 - golang.org/x/crypto v0.57.0 + golang.org/x/crypto v0.58.0 golang.org/x/image v0.41.0 golang.org/x/mod v0.41.0 - golang.org/x/net v0.60.0 - golang.org/x/sync v0.23.0 - golang.org/x/term v0.46.0 + golang.org/x/net v0.62.0 + golang.org/x/sync v0.24.0 + golang.org/x/term v0.47.0 google.golang.org/grpc v1.83.2 google.golang.org/protobuf v1.36.11 gopkg.in/natefinch/lumberjack.v2 v2.2.1 @@ -128,6 +129,7 @@ require ( github.com/google/go-cmp v0.7.0 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/google/go-tpm v0.9.8 // indirect + github.com/google/jsonschema-go v0.4.2 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/hcl/v2 v2.18.1 // indirect @@ -167,6 +169,8 @@ require ( github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/segmentio/asm v1.1.3 // indirect + github.com/segmentio/encoding v0.5.4 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/smartwalle/ncrypto v1.0.4 // indirect github.com/smartwalle/ngx v1.1.0 // indirect @@ -187,6 +191,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.11 // indirect github.com/x448/float16 v0.8.4 // indirect + github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect github.com/yusufpapurcu/wmi v1.2.4 // indirect github.com/zclconf/go-cty v1.14.4 // indirect @@ -201,10 +206,11 @@ require ( go.uber.org/multierr v1.9.0 // indirect golang.org/x/arch v0.3.0 // indirect golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/text v0.42.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.12.0 // indirect - golang.org/x/tools v0.50.0 // indirect + golang.org/x/tools v0.51.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect gopkg.in/ini.v1 v1.67.0 // indirect modernc.org/libc v1.67.6 // indirect diff --git a/backend/go.sum b/backend/go.sum index 78270b757e..5f62bf5c24 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -251,6 +251,8 @@ github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc= github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8= +github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -349,6 +351,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/modelcontextprotocol/go-sdk v1.4.1 h1:M4x9GyIPj+HoIlHNGpK2hq5o3BFhC+78PkEaldQRphc= +github.com/modelcontextprotocol/go-sdk v1.4.1/go.mod h1:Bo/mS87hPQqHSRkMv4dQq1XCu6zv4INdXnFZabkNU6s= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -405,6 +409,10 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8= github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I= github.com/shirou/gopsutil/v4 v4.25.6 h1:kLysI2JsKorfaFPcYmcJqbzROzsBWEOAtw6A7dIfqXs= @@ -498,6 +506,8 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= @@ -562,10 +572,8 @@ golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDf golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM= -golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= -golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY= golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70= @@ -580,8 +588,6 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= -golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= -golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -605,11 +611,11 @@ golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= -golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= -golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -620,10 +626,8 @@ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -655,10 +659,8 @@ golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -671,10 +673,8 @@ golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY= golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0= -golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= -golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= @@ -685,10 +685,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= -golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= -golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -703,12 +701,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= -golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= -golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= -golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= -golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 1f488c89af..4b9a59cad0 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -7,9 +7,11 @@ import ( "fmt" "log/slog" "math" + "net/netip" "net/textproto" "net/url" "os" + "strconv" "strings" "sync/atomic" "time" @@ -69,6 +71,7 @@ type Config struct { Server ServerConfig `mapstructure:"server"` Log LogConfig `mapstructure:"log"` CORS CORSConfig `mapstructure:"cors"` + MCP MCPConfig `mapstructure:"mcp"` Security SecurityConfig `mapstructure:"security"` Billing BillingConfig `mapstructure:"billing"` Turnstile TurnstileConfig `mapstructure:"turnstile"` @@ -116,6 +119,54 @@ type SimpleModeConfig struct { AutoCreateDefaultGroups bool `mapstructure:"auto_create_default_groups" yaml:"auto_create_default_groups"` } +// 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 keeps MCP and its OAuth endpoints disabled. +func (c *MCPConfig) Validate() error { + raw := strings.TrimSpace(c.PublicURL) + if raw == "" { + c.PublicURL = "" + return nil + } + u, err := url.Parse(raw) + if err != nil { + return fmt.Errorf("mcp.public_url invalid: %w", err) + } + if !u.IsAbs() || u.Hostname() == "" || !httpguts.ValidHostHeader(u.Host) || strings.ContainsAny(u.Host, "*%") { + return fmt.Errorf("mcp.public_url must be an absolute URL with a valid host") + } + if u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.Contains(raw, "#") { + return fmt.Errorf("mcp.public_url must not include userinfo, query, or fragment") + } + if u.Path != "/api/v1/mcp" || u.EscapedPath() != "/api/v1/mcp" { + return fmt.Errorf("mcp.public_url must have the exact path /api/v1/mcp without a trailing slash") + } + if port := u.Port(); port != "" { + n, err := strconv.Atoi(port) + if err != nil || n < 1 || n > 65535 { + return fmt.Errorf("mcp.public_url must have a valid port") + } + } + u.Scheme = strings.ToLower(u.Scheme) + u.Host = strings.ToLower(u.Host) + host := u.Hostname() + addr, _ := netip.ParseAddr(host) + localDevelopment := host == "localhost" || addr.IsLoopback() + if u.Scheme != "https" && (u.Scheme != "http" || !localDevelopment) { + return fmt.Errorf("mcp.public_url must use HTTPS (HTTP is allowed only for localhost or loopback IPs)") + } + c.PublicURL = u.String() + return nil +} + // PluginConfig 控制管理员手动上传的本地进程插件。 // 默认不包含插件,也不允许安装未签名插件;TrustedPublishers 用于追加第三方发布者。 type PluginConfig struct { @@ -998,6 +1049,12 @@ type GatewayConfig struct { OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"` // 请求体最大字节数,用于网关请求体大小限制 MaxBodySize int64 `mapstructure:"max_body_size"` + // RequestBodyMemoryBudgetBytes bounds buffered ingress allocations per instance; 0 disables it. + RequestBodyMemoryBudgetBytes int64 `mapstructure:"request_body_memory_budget_bytes"` + // RequestBodyReadTimeoutSeconds bounds each socket read during upload; 0 disables it. + RequestBodyReadTimeoutSeconds int `mapstructure:"request_body_read_timeout_seconds"` + // DownstreamWriteTimeoutSeconds bounds each HTTP write/flush, not the lifetime of a stream. + DownstreamWriteTimeoutSeconds int `mapstructure:"downstream_write_timeout_seconds"` // TextMaxBodySize limits endpoints that cannot carry inline image/video payloads. TextMaxBodySize int64 `mapstructure:"text_max_body_size"` // 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大 @@ -1092,7 +1149,10 @@ type GatewayConfig struct { // ImageNonstreamKeepaliveInterval: 图片非流式 JSON keepalive 间隔(秒),0表示禁用 ImageNonstreamKeepaliveInterval int `mapstructure:"image_nonstream_keepalive_interval"` // MaxLineSize: 上游 SSE 单行最大字节数(0使用默认值) - MaxLineSize int `mapstructure:"max_line_size"` + MaxLineSize int `mapstructure:"max_line_size"` + SSEQueueMaxBytes int64 `mapstructure:"sse_queue_max_bytes"` + SSEEventMaxBytes int64 `mapstructure:"sse_event_max_bytes"` + SSEEventMaxLines int `mapstructure:"sse_event_max_lines"` // 是否记录上游错误响应体摘要(避免输出请求内容) LogUpstreamErrorBody bool `mapstructure:"log_upstream_error_body"` @@ -1109,6 +1169,8 @@ type GatewayConfig struct { MaxAccountSwitches int `mapstructure:"max_account_switches"` // Gemini 账户切换最大次数(Gemini 平台单独配置,因 API 限制更严格) MaxAccountSwitchesGemini int `mapstructure:"max_account_switches_gemini"` + // Gemini 同账号重试次数(429/5xx 等可重试错误在换号前对同一账号的重发次数,不含首次请求) + MaxSameAccountRetriesGemini int `mapstructure:"max_same_account_retries_gemini"` // Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用 AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"` @@ -2082,6 +2144,7 @@ func setDefaults() { // CORS viper.SetDefault("cors.allowed_origins", []string{}) viper.SetDefault("cors.allow_credentials", true) + viper.SetDefault("mcp.public_url", "") // WebAuthn / Passkeys are opt-in because every deployment must explicitly // declare its relying-party domain and trusted browser origins. @@ -2434,6 +2497,7 @@ func setDefaults() { viper.SetDefault("gateway.failover_on_400", false) viper.SetDefault("gateway.max_account_switches", 10) viper.SetDefault("gateway.max_account_switches_gemini", 3) + viper.SetDefault("gateway.max_same_account_retries_gemini", 4) viper.SetDefault("gateway.force_codex_cli", false) viper.SetDefault("gateway.disable_codex_identity_enforcement", false) viper.SetDefault("gateway.disable_codex_originator_normalization", false) @@ -2529,6 +2593,9 @@ func setDefaults() { viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1) viper.SetDefault("gateway.antigravity_extra_retries", 10) viper.SetDefault("gateway.max_body_size", int64(256*1024*1024)) + viper.SetDefault("gateway.request_body_memory_budget_bytes", int64(1024*1024*1024)) + viper.SetDefault("gateway.request_body_read_timeout_seconds", 120) + viper.SetDefault("gateway.downstream_write_timeout_seconds", 120) viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024)) viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes) viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes) @@ -2550,6 +2617,9 @@ func setDefaults() { viper.SetDefault("gateway.image_stream_keepalive_interval", 10) viper.SetDefault("gateway.image_nonstream_keepalive_interval", 0) viper.SetDefault("gateway.max_line_size", 500*1024*1024) + viper.SetDefault("gateway.sse_queue_max_bytes", int64(8*1024*1024)) + viper.SetDefault("gateway.sse_event_max_bytes", int64(0)) + viper.SetDefault("gateway.sse_event_max_lines", 4096) viper.SetDefault("gateway.scheduling.sticky_session_max_waiting", 3) viper.SetDefault("gateway.scheduling.sticky_session_wait_timeout", 120*time.Second) viper.SetDefault("gateway.scheduling.fallback_wait_timeout", 30*time.Second) @@ -2856,6 +2926,9 @@ func (c *Config) Validate() error { return fmt.Errorf("gemini.oauth.client_id and gemini.oauth.client_secret must be both set or both empty") } + if err := c.MCP.Validate(); err != nil { + return err + } if strings.TrimSpace(c.Server.FrontendURL) != "" { if err := ValidateAbsoluteHTTPURL(c.Server.FrontendURL); err != nil { return fmt.Errorf("server.frontend_url invalid: %w", err) @@ -3350,6 +3423,18 @@ func (c *Config) Validate() error { if c.Gateway.MaxBodySize <= 0 { return fmt.Errorf("gateway.max_body_size must be positive") } + if c.Gateway.RequestBodyMemoryBudgetBytes < 0 { + return fmt.Errorf("gateway.request_body_memory_budget_bytes must be non-negative") + } + if c.Gateway.RequestBodyReadTimeoutSeconds < 0 || c.Gateway.RequestBodyReadTimeoutSeconds > 3600 { + return fmt.Errorf("gateway.request_body_read_timeout_seconds must be between 0 and 3600") + } + if c.Gateway.DownstreamWriteTimeoutSeconds < 0 || c.Gateway.DownstreamWriteTimeoutSeconds > 3600 { + return fmt.Errorf("gateway.downstream_write_timeout_seconds must be between 0 and 3600") + } + if c.Gateway.SSEQueueMaxBytes < 0 || c.Gateway.SSEEventMaxBytes < 0 || c.Gateway.SSEEventMaxLines < 0 { + return fmt.Errorf("gateway.sse_queue_max_bytes, sse_event_max_bytes and sse_event_max_lines must be non-negative") + } if c.Gateway.TextMaxBodySize <= 0 || c.Gateway.TextMaxBodySize > c.Gateway.MaxBodySize { return fmt.Errorf("gateway.text_max_body_size must be positive and no greater than gateway.max_body_size") } @@ -3371,6 +3456,9 @@ func (c *Config) Validate() error { if c.Gateway.GrokResponseHeaderTimeout < 0 || c.Gateway.GrokResponseHeaderTimeout > 1800 { return fmt.Errorf("gateway.grok_response_header_timeout must be between 0-1800 seconds") } + if c.Gateway.MaxSameAccountRetriesGemini < 0 || c.Gateway.MaxSameAccountRetriesGemini > 10 { + return fmt.Errorf("gateway.max_same_account_retries_gemini must be between 0-10") + } if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 || (c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) { return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds") diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index 434b889955..bc579aecfd 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -46,6 +46,19 @@ func TestLoadMinOutputTokensFromEnv(t *testing.T) { require.Equal(t, 16, cfg.Gateway.MinOutputTokens) } +func TestLoadGeminiSameAccountRetries(t *testing.T) { + resetViperWithJWTSecret(t) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, 4, cfg.Gateway.MaxSameAccountRetriesGemini) + + resetViperWithJWTSecret(t) + t.Setenv("GATEWAY_MAX_SAME_ACCOUNT_RETRIES_GEMINI", "0") + cfg, err = Load() + require.NoError(t, err) + require.Zero(t, cfg.Gateway.MaxSameAccountRetriesGemini) +} + func TestValidateMinOutputTokensMinimum(t *testing.T) { resetViperWithJWTSecret(t) cfg, err := Load() @@ -131,6 +144,12 @@ func TestLoadHTTPIngressSafetyDefaults(t *testing.T) { require.False(t, cfg.Server.TrustedProxiesConfigured) require.True(t, cfg.TrustForwardedIPForAPIKeyACL()) require.Equal(t, int64(32*1024*1024), cfg.Gateway.TextMaxBodySize) + require.Equal(t, int64(1<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes) + require.Equal(t, 120, cfg.Gateway.RequestBodyReadTimeoutSeconds) + require.Equal(t, 120, cfg.Gateway.DownstreamWriteTimeoutSeconds) + require.Equal(t, 500<<20, cfg.Gateway.MaxLineSize) + require.Equal(t, int64(8<<20), cfg.Gateway.SSEQueueMaxBytes) + require.Equal(t, 4096, cfg.Gateway.SSEEventMaxLines) require.True(t, cfg.APIKeyAuth.InvalidAbuse.Enabled) require.Equal(t, 120, cfg.APIKeyAuth.InvalidAbuse.Threshold) require.Equal(t, 16384, cfg.APIKeyAuth.InvalidAbuse.Capacity) @@ -1621,6 +1640,16 @@ func TestValidateConfigErrors(t *testing.T) { mutate func(*Config) wantErr string }{ + { + name: "negative ingress memory budget", + mutate: func(c *Config) { c.Gateway.RequestBodyMemoryBudgetBytes = -1 }, + wantErr: "gateway.request_body_memory_budget_bytes", + }, + { + name: "negative upload timeout", + mutate: func(c *Config) { c.Gateway.RequestBodyReadTimeoutSeconds = -1 }, + wantErr: "gateway.request_body_read_timeout_seconds", + }, { name: "server read header timeout", mutate: func(c *Config) { c.Server.ReadHeaderTimeout = 0 }, @@ -1887,6 +1916,16 @@ func TestValidateConfigErrors(t *testing.T) { mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 }, wantErr: "gateway.openai_response_header_timeout", }, + { + name: "gateway gemini same account retries negative", + mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = -1 }, + wantErr: "gateway.max_same_account_retries_gemini", + }, + { + name: "gateway gemini same account retries too large", + mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = 11 }, + wantErr: "gateway.max_same_account_retries_gemini", + }, { name: "gateway openai first output timeout below minimum", mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 }, diff --git a/backend/internal/config/mcp_config_test.go b/backend/internal/config/mcp_config_test.go new file mode 100644 index 0000000000..93a002be14 --- /dev/null +++ b/backend/internal/config/mcp_config_test.go @@ -0,0 +1,64 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMCPConfigValidatePublicURL(t *testing.T) { + for _, tc := range []struct { + name, value, want string + }{ + {"unset", "", ""}, + {"blank", " ", ""}, + {"https", "https://api.example.com/api/v1/mcp", "https://api.example.com/api/v1/mcp"}, + {"normalize", " HTTPS://API.Example.COM:8443/api/v1/mcp ", "https://api.example.com:8443/api/v1/mcp"}, + {"localhost", "http://localhost:8080/api/v1/mcp", "http://localhost:8080/api/v1/mcp"}, + {"loopback IPv4", "http://127.0.0.2:8080/api/v1/mcp", "http://127.0.0.2:8080/api/v1/mcp"}, + {"loopback IPv6", "http://[::1]:8080/api/v1/mcp", "http://[::1]:8080/api/v1/mcp"}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := MCPConfig{PublicURL: tc.value} + require.NoError(t, cfg.Validate()) + require.Equal(t, tc.want, cfg.PublicURL) + }) + } + for _, value := range []string{ + "/api/v1/mcp", "//example.com/api/v1/mcp", "https:///api/v1/mcp", + "https://:443/api/v1/mcp", "https://*.example.com/api/v1/mcp", + "http://example.com/api/v1/mcp", "http://localhost.example.com/api/v1/mcp", + "http://10.0.0.1/api/v1/mcp", "http://[::2]/api/v1/mcp", + "ftp://localhost/api/v1/mcp", "https://example.com/api/v1/mcp/", + "https://example.com/mcp", "https://example.com/api/v1/%6dcp", + "https://example.com/api/v1/mcp?", "https://example.com/api/v1/mcp?x=1", + "https://example.com/api/v1/mcp#", "https://example.com/api/v1/mcp#fragment", + "https://user:password@example.com/api/v1/mcp", "https://user@example.com/api/v1/mcp", + "https://example.com:0/api/v1/mcp", "https://example.com:65536/api/v1/mcp", + "https://example.com:invalid/api/v1/mcp", "http://[::1%25eth0]/api/v1/mcp", + } { + t.Run(value, func(t *testing.T) { + cfg := MCPConfig{PublicURL: value} + require.ErrorContains(t, cfg.Validate(), "mcp.public_url") + }) + } +} + +func TestLoadMCPPublicURLFromEnv(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv("MCP_PUBLIC_URL", "HTTPS://MCP.Example.COM/api/v1/mcp") + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, "https://mcp.example.com/api/v1/mcp", cfg.MCP.PublicURL) + + cfg.MCP.PublicURL = "http://example.com/api/v1/mcp" + require.ErrorContains(t, cfg.Validate(), "mcp.public_url must use HTTPS") +} + +func TestLoadMCPPublicURLDefault(t *testing.T) { + resetViperWithJWTSecret(t) + t.Setenv("MCP_PUBLIC_URL", "") + cfg, err := Load() + require.NoError(t, err) + require.Empty(t, cfg.MCP.PublicURL) +} diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 352ab5b4d9..225f18f372 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -1734,7 +1734,7 @@ func (h *AccountHandler) GetStats(c *gin.Context) { stats, err := h.accountUsageService.GetAccountUsageStats(c.Request.Context(), accountID, startTime, endTime) if err != nil { - response.ErrorFrom(c, err) + scopedOpenAIError(c, err) return } diff --git a/backend/internal/handler/admin/admin_service_stub_test.go b/backend/internal/handler/admin/admin_service_stub_test.go index c808d1a18c..628fd18133 100644 --- a/backend/internal/handler/admin/admin_service_stub_test.go +++ b/backend/internal/handler/admin/admin_service_stub_test.go @@ -208,6 +208,14 @@ func (s *stubAdminService) BatchUpdateLimits(ctx context.Context, userIDs []int6 return len(userIDs), nil } +func (s *stubAdminService) FindActiveUsersByBlacklistedEmails(ctx context.Context, emails []string) ([]service.User, error) { + return []service.User{}, nil +} + +func (s *stubAdminService) BatchDisableUsers(ctx context.Context, userIDs []int64) (int, error) { + return len(userIDs), nil +} + func (s *stubAdminService) GetUserAPIKeys(ctx context.Context, userID int64, page, pageSize int, sortBy, sortOrder string) ([]service.APIKey, int64, error) { return s.apiKeys, int64(len(s.apiKeys)), nil } 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/custom_admin_key_accounts.go b/backend/internal/handler/admin/custom_admin_key_accounts.go index dc4a2e21a6..c906eafa4e 100644 --- a/backend/internal/handler/admin/custom_admin_key_accounts.go +++ b/backend/internal/handler/admin/custom_admin_key_accounts.go @@ -24,7 +24,7 @@ func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H { groups = append(groups, g) } } - result := gin.H{"id": a.ID, "name": a.Name, "notes": a.Notes, "platform": a.Platform, "type": a.Type, "status": a.Status, "schedulable": a.Schedulable, "concurrency": a.Concurrency, "priority": a.Priority, "group_ids": groups} + result := gin.H{"id": a.ID, "name": a.Name, "notes": a.Notes, "platform": a.Platform, "type": a.Type, "status": a.Status, "schedulable": a.Schedulable, "concurrency": a.Concurrency, "priority": a.Priority, "group_ids": groups, "expires_at": a.ExpiresAt, "rate_limit_reset_at": a.RateLimitResetAt, "overload_until": a.OverloadUntil, "temp_unschedulable_until": a.TempUnschedulableUntil} // 兼容原账户读取结构,仅返回模型映射,凭证及扩展字段继续脱敏。 if p.AllowsAccount("accounts.read", resource) { mapping := map[string]string{} @@ -42,12 +42,43 @@ func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H { } result["credentials"] = gin.H{"model_mapping": mapping} } + if p.AllowsAccount("accounts.identity.read", resource) { + credentials, _ := result["credentials"].(gin.H) + if credentials == nil { + credentials = gin.H{} + } + for _, key := range []string{"email", "plan_type", "subscription_expires_at"} { + if value, ok := a.Credentials[key].(string); ok { + credentials[key] = value + } + } + result["credentials"] = credentials + // 保留两处邮箱供调用方检查一致性,禁止回传其他扩展字段。 + extra := gin.H{} + if value, ok := a.Extra["email"].(string); ok { + extra["email"] = value + } + result["extra"] = extra + result["created_at"] = a.CreatedAt + } + if p.AllowsAccount("accounts.usage.read", resource) { + extra, _ := result["extra"].(gin.H) + if extra == nil { + extra = gin.H{} + } + for _, key := range []string{"codex_usage_updated_at", "codex_7d_used_percent", "codex_7d_reset_at"} { + if value, ok := a.Extra[key]; ok { + extra[key] = value + } + } + result["extra"] = extra + } return result } // ScopedAdminKeyAccounts 在原处理器前完成独立授权和安全输出。 func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) { - principal := adminaccess.FromContext(c.Request.Context()) + principal := adminaccess.RestrictedFromContext(c.Request.Context()) if principal == nil { return } @@ -70,6 +101,9 @@ func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) { h.scopedAdminImportCodexSession(c) return } + if h.scopedAdminStatistics(c) { + return + } api, ok := h.adminService.(service.ScopedAdminAccounts) if !ok { response.Error(c, 503, "受限账户服务不可用") @@ -85,7 +119,17 @@ func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) { if size < 1 || size > 100 { size = 20 } - accounts, total, err := api.ScopedAdminList(ctx, pagination.PaginationParams{Page: page, PageSize: size}, c.Query("platform"), c.Query("type"), c.Query("status"), c.Query("search")) + groupID := int64(0) + // 空分组筛选与省略参数均表示不按分组筛选。 + if raw := c.Query("group"); raw != "" { + var err error + groupID, err = strconv.ParseInt(raw, 10, 64) + if err != nil || groupID < -1 { + response.BadRequest(c, "分组筛选无效") + return + } + } + accounts, total, err := api.ScopedAdminList(ctx, pagination.PaginationParams{Page: page, PageSize: size}, c.Query("platform"), c.Query("type"), c.Query("status"), c.Query("search"), groupID) if err != nil { response.Error(c, 503, "账户查询失败") return @@ -96,10 +140,11 @@ func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) { items = append(items, scopedAdminAccountDTO(&accounts[i], principal.Policy)) } } - response.Success(c, gin.H{"items": items, "total": total, "page": page, "page_size": size}) + response.Paginated(c, items, total, page, size) return } id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + if (path == base+"/:id" || path == base+"/:id/models") && c.Request.Method == "GET" { a, err := h.adminService.GetAccount(ctx, id) if err != nil || a == nil || !principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) { diff --git a/backend/internal/handler/admin/custom_admin_key_accounts_test.go b/backend/internal/handler/admin/custom_admin_key_accounts_test.go index 08be6e6d31..3c58929370 100644 --- a/backend/internal/handler/admin/custom_admin_key_accounts_test.go +++ b/backend/internal/handler/admin/custom_admin_key_accounts_test.go @@ -84,7 +84,7 @@ type scopedBulkAccountService struct { fields map[string]json.RawMessage } -func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) { +func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) { panic("不应读取全站账户") } func (s *scopedBulkAccountService) ScopedAdminWrite(_ context.Context, id int64, _ string, fields map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) { diff --git a/backend/internal/handler/admin/custom_admin_key_commit_test.go b/backend/internal/handler/admin/custom_admin_key_commit_test.go index ded090ed2d..bab7adf84b 100644 --- a/backend/internal/handler/admin/custom_admin_key_commit_test.go +++ b/backend/internal/handler/admin/custom_admin_key_commit_test.go @@ -40,7 +40,7 @@ type scopedCommitAccounts struct { fail bool } -func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) { +func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) { panic("不应查询列表") } func (s *scopedCommitAccounts) ScopedAdminWrite(_ context.Context, id int64, _ string, _ map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) { diff --git a/backend/internal/handler/admin/custom_admin_key_group_models.go b/backend/internal/handler/admin/custom_admin_key_group_models.go index 7b3b5b18ef..7021975520 100644 --- a/backend/internal/handler/admin/custom_admin_key_group_models.go +++ b/backend/internal/handler/admin/custom_admin_key_group_models.go @@ -18,12 +18,12 @@ import ( ) func scopedAdminGroupModelsDTO(g *service.Group) gin.H { - return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "model_allowlist": g.ModelAllowlist} + return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "status": g.Status, "model_allowlist": g.ModelAllowlist} } // ScopedAdminKeyGroupModels 接管分组模型接口,禁止复用可修改费率等字段的完整处理器。 func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) { - p := adminaccess.FromContext(c.Request.Context()) + p := adminaccess.RestrictedFromContext(c.Request.Context()) if p == nil { return } @@ -72,7 +72,8 @@ func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) { if c.Request.Method == http.MethodPut { permission = "groups.models.write" } - allowed := p.Policy.AllowsGroupConfig(permission, g.ID, g.Platform) || (c.Request.Method == http.MethodGet && fullRead) + basicRead := c.Request.Method == http.MethodGet && path == base && p.Policy.AllowsGroupConfig("groups.list.read", g.ID, g.Platform) + allowed := basicRead || p.Policy.AllowsGroupConfig(permission, g.ID, g.Platform) || (c.Request.Method == http.MethodGet && fullRead) if !allowed { response.Error(c, 404, "分组不存在") return @@ -89,7 +90,7 @@ func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) { if fullRead { response.Success(c, dto.GroupFromServiceAdmin(g)) } else { - response.Success(c, scopedAdminGroupModelsDTO(g)) + response.Success(c, scopedAdminGroupReadDTO(g, p.Policy)) } return } @@ -157,7 +158,7 @@ func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) { } out := make([]gin.H, 0, len(groups)) for i := range groups { - out = append(out, scopedAdminGroupModelsDTO(&groups[i])) + out = append(out, scopedAdminGroupReadDTO(&groups[i], adminaccess.FromContext(c.Request.Context()).Policy)) } if all { response.Success(c, out) @@ -165,3 +166,11 @@ func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) { response.Paginated(c, out, total, page, size) } } + +// 基本分组读取不能隐式获得模型配置。 +func scopedAdminGroupReadDTO(g *service.Group, policy adminaccess.Policy) gin.H { + if policy.AllowsGroupConfig("groups.models.read", g.ID, g.Platform) { + return scopedAdminGroupModelsDTO(g) + } + return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "status": g.Status} +} diff --git a/backend/internal/handler/admin/custom_admin_key_idempotency_scope_test.go b/backend/internal/handler/admin/custom_admin_key_idempotency_scope_test.go new file mode 100644 index 0000000000..678f59dc35 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_idempotency_scope_test.go @@ -0,0 +1,30 @@ +//go:build unit + +package admin + +import ( + "context" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "net/http/httptest" + "testing" +) + +func TestAdminFullAccessIdempotencyScopeIsolation(t *testing.T) { + scope := func(p *adminaccess.Principal) string { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest("POST", "/", nil) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9}) + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(context.Background(), p)) + return adminActorScope(c) + } + jwt := scope(nil) + full := scope(&adminaccess.Principal{KeyID: "one", Policy: adminaccess.Policy{FullAccess: true}}) + restricted := scope(&adminaccess.Principal{KeyID: "one", Policy: adminaccess.Policy{}}) + other := scope(&adminaccess.Principal{KeyID: "two", Policy: adminaccess.Policy{FullAccess: true}}) + require.NotEqual(t, jwt, full) + require.NotEqual(t, full, restricted) + require.NotEqual(t, full, other) +} diff --git a/backend/internal/handler/admin/custom_admin_key_openai.go b/backend/internal/handler/admin/custom_admin_key_openai.go new file mode 100644 index 0000000000..8a86d8dd66 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_openai.go @@ -0,0 +1,109 @@ +package admin + +import ( + "strconv" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +func (h *OpenAIOAuthHandler) scopedOpenAIAllowed(c *gin.Context, id int64, action string, parent bool) bool { + if adminaccess.RestrictedFromContext(c.Request.Context()) == nil { + return true + } + _, ok := scopedAuthorizedAccount(c, h.adminService, id, action, parent) + return ok +} + +func (h *OpenAIOAuthHandler) scopedOpenAIHasPermission(c *gin.Context, id int64, action string, parent bool) bool { + p := adminaccess.RestrictedFromContext(c.Request.Context()) + if p == nil { + return true + } + if h.adminService == nil { + return false + } + a, err := h.adminService.GetAccount(c.Request.Context(), id) + if err != nil || a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) { + return false + } + if parent && a.IsShadow() { + if a.ParentAccountID == nil { + return false + } + source, err := h.adminService.GetAccount(c.Request.Context(), *a.ParentAccountID) + return err == nil && source != nil && !source.IsShadow() && p.Policy.AllowsAccount(action, scopedAccountResource(source)) + } + return true +} + +func scopedOpenAIError(c *gin.Context, err error) { + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { + scopedAdminAccountError(c, err) + return + } + response.ErrorFrom(c, err) +} + +func (h *OpenAIOAuthHandler) scopedQuotaDTO(c *gin.Context, id int64, u *service.OpenAIQuotaUsage) *service.OpenAIQuotaUsage { + if u == nil { + return nil + } + safe := *u + p := adminaccess.RestrictedFromContext(c.Request.Context()) + if p == nil { + return &safe + } + identity := h.scopedOpenAIHasPermission(c, id, "accounts.identity.read", true) + if !identity { + safe.UserID = "" + safe.AccountID = "" + safe.Email = "" + safe.PlanType = "" + } + return &safe +} + +func (h *OpenAIOAuthHandler) scopedOpenAIQuota(c *gin.Context, refresh bool) { + id, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || id <= 0 { + response.BadRequest(c, "账户 ID 无效") + return + } + if !h.scopedOpenAIAllowed(c, id, "openai.quota.read", true) { + return + } + if h.quotaService == nil { + response.Error(c, 503, "账户额度服务不可用") + return + } + u, err := h.quotaService.QueryUsage(c.Request.Context(), id) + if err != nil { + scopedOpenAIError(c, err) + return + } + if u == nil { + response.Error(c, 502, "账户额度查询失败") + return + } + safe := h.scopedQuotaDTO(c, id, u) + // 读取只更新展示快照,绝不通知可能消耗重置次数的自动任务。 + if !refresh { + response.Success(c, safe) + return + } + result := openAIQuotaRefreshResponse{OpenAIQuotaUsage: *safe} + result.CreditsCachePersisted = h.quotaService.CacheCreditsSnapshot(c.Request.Context(), id, safe) == nil + result.CachePersisted = h.quotaService.CacheResetCreditsSnapshot(c.Request.Context(), id, safe.RateLimitResetCredits) == nil + response.Success(c, result) +} + +func (h *OpenAIOAuthHandler) scopedReferralDTO(c *gin.Context, e *service.OpenAIReferralEligibility) *service.OpenAIReferralEligibility { + if e == nil || adminaccess.RestrictedFromContext(c.Request.Context()) == nil { + return e + } + // 邀请资格只展示容量和流程字段,不回传上游自由文本及收件人资料。 + return &service.OpenAIReferralEligibility{ShouldShow: e.ShouldShow, RemainingSendCapacity: e.RemainingSendCapacity, RemainingRewardCapacity: e.RemainingRewardCapacity, RequiresExplicitConfirmation: e.RequiresExplicitConfirmation, OfferID: e.OfferID, ProgramID: e.ProgramID, AvailableInvites: e.AvailableInvites, FetchedAt: e.FetchedAt} +} diff --git a/backend/internal/handler/admin/custom_admin_key_permissions_test.go b/backend/internal/handler/admin/custom_admin_key_permissions_test.go new file mode 100644 index 0000000000..b8aadc3218 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_permissions_test.go @@ -0,0 +1,175 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type permissionsProxyService struct { + service.AdminService + proxy *service.Proxy +} + +func (s *permissionsProxyService) GetProxy(context.Context, int64) (*service.Proxy, error) { + return s.proxy, nil +} + +func TestScopedAdminPermissionsRefreshRejectsUnavailableProxyBeforeNetwork(t *testing.T) { + gin.SetMode(gin.TestMode) + expired := time.Now().Add(-time.Hour) + for _, proxy := range []*service.Proxy{nil, {Status: "inactive"}, {Status: "active", ExpiresAt: &expired}} { + h := &OpenAIOAuthHandler{adminService: &permissionsProxyService{proxy: proxy}} + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"openai.tokens.refresh"}}})) + }) + r.POST("/api/v1/admin/openai/refresh-token", h.RefreshToken) + req := httptest.NewRequest("POST", "/api/v1/admin/openai/refresh-token", strings.NewReader(`{"refresh_token":"TEST_SECRET","proxy_id":14}`)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 400, w.Code) + require.NotContains(t, w.Body.String(), "SECRET") + } +} + +type scopedPermissionAccountService struct { + scopedBulkAccountService + listGroupID int64 +} + +func (s *scopedPermissionAccountService) ScopedAdminList(_ context.Context, _ pagination.PaginationParams, _, _, _, _ string, groupID int64) ([]service.Account, int64, error) { + s.listGroupID = groupID + return []service.Account{{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}, 1, nil +} + +func TestScopedAdminPermissionPaginationContract(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name, query string + groupID int64 + invalid bool + }{ + {"无筛选", "page=1&page_size=100", 0, false}, + {"空分组", "group=", 0, false}, + {"补号前全局查重", "platform=openai&type=oauth&status=&group=&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 0, false}, + {"监控分组", "platform=openai&type=oauth&status=&group=2&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 2, false}, + {"查询限流账户", "platform=openai&type=oauth&status=rate_limited&group=2&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 2, false}, + {"未分组", "group=-1", -1, false}, + {"非法负数", "group=-2", 0, true}, + {"非法文本", "group=invalid", 0, true}, + {"空白字符", "group=%20", 0, true}, + {"溢出数值", "group=9999999999999999999999", 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + r := gin.New() + svc := &scopedPermissionAccountService{listGroupID: -99} + h := &AccountHandler{adminService: svc} + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}})) + }) + r.Use(h.ScopedAdminKeyAccounts) + r.GET("/api/v1/admin/accounts", func(c *gin.Context) { t.Fatal("不应调用全权处理器") }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts?"+tc.query, nil)) + if tc.invalid { + require.Equal(t, 400, w.Code, w.Body.String()) + require.Equal(t, int64(-99), svc.listGroupID, "无效筛选不能触达账户查询") + return + } + require.Equal(t, 200, w.Code, "账户查询失败(HTTP %d):%s", w.Code, w.Body.String()) + require.Equal(t, tc.groupID, svc.listGroupID) + var body struct { + Data map[string]any `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body)) + require.Equal(t, float64(1), body.Data["pages"], "标准分页必须包含 pages") + require.Equal(t, float64(1), body.Data["page"]) + }) + } +} + +func (s *scopedPermissionAccountService) GetAccount(context.Context, int64) (*service.Account, error) { + return &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2, 3}, Credentials: map[string]any{"email": "test@example.com", "plan_type": "plus", "access_token": "SECRET"}, Extra: map[string]any{"email": "test@example.com", "codex_usage_updated_at": "2026-10-24T00:00:00Z", "codex_7d_used_percent": 100, "codex_7d_reset_at": "2026-10-30T00:00:00Z", "private": "SECRET"}}, nil +} + +func TestScopedAdminPermissionIdentityAndUsageAreIndependent(t *testing.T) { + for _, permissions := range [][]string{{"accounts.read"}, {"accounts.read", "accounts.identity.read"}, {"accounts.read", "accounts.usage.read"}, {"accounts.read", "accounts.identity.read", "accounts.usage.read"}} { + r := gin.New() + policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: permissions, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}} + h := &AccountHandler{adminService: &scopedPermissionAccountService{}} + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy})) + }) + r.Use(h.ScopedAdminKeyAccounts) + r.GET("/api/v1/admin/accounts/:id", func(c *gin.Context) { t.Fatal("不能调用全权读取") }) + r.GET("/api/v1/admin/accounts/:id/usage", func(c *gin.Context) { t.Fatal("不能绕过额度授权") }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1", nil)) + require.Equal(t, 200, w.Code) + require.NotContains(t, w.Body.String(), "SECRET") + require.Contains(t, w.Body.String(), `"group_ids":[2]`) + a := adminaccess.Account{ID: 1, GroupIDs: []int64{2}, Type: "oauth", Platform: "openai"} + require.Equal(t, policy.AllowsAccount("accounts.identity.read", a), strings.Contains(w.Body.String(), "test@example.com")) + require.Equal(t, policy.AllowsAccount("accounts.usage.read", a), strings.Contains(w.Body.String(), "codex_7d_used_percent")) + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1/usage?source=active&force=true", nil)) + want := 404 + if policy.AllowsAccount("accounts.usage.read", a) { + want = 503 + } // 已授权才会触达尚未接线的额度服务。 + require.Equal(t, want, w.Code) + policy.Rules[0].GroupIDs = []int64{99} + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1/usage", nil)) + require.Equal(t, 404, w.Code) + } +} + +type scopedBasicGroupService struct{ service.AdminService } + +func (*scopedBasicGroupService) GetGroup(context.Context, int64) (*service.Group, error) { + return &service.Group{ID: 1, Name: "基本组", Platform: "openai", Status: "active"}, nil +} +func TestScopedAdminBasicGroupReadDoesNotReturnModels(t *testing.T) { + policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.list.read"}, GroupIDs: []int64{1}, Platforms: []string{"openai"}}}} + h := &GroupHandler{adminService: &scopedBasicGroupService{}} + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy})) + }) + r.Use(h.ScopedAdminKeyGroupModels) + r.GET("/api/v1/admin/groups/:id", func(c *gin.Context) { t.Fatal("不能调用完整处理器") }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/groups/1", nil)) + require.Equal(t, 200, w.Code, w.Body.String()) + require.JSONEq(t, `{"code":0,"message":"success","data":{"id":1,"name":"基本组","platform":"openai","status":"active"}}`, w.Body.String()) +} + +func TestScopedAdminPermissionRefreshRejectsMissingGlobalGrant(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, policy := range []adminaccess.Policy{{}, {Rules: []adminaccess.Rule{{Permissions: []string{"accounts.refresh"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}} { + h := &OpenAIOAuthHandler{} + r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy})) + }) + r.POST("/api/v1/admin/openai/refresh-token", h.RefreshToken) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/admin/openai/refresh-token", strings.NewReader(`{"refresh_token":"SECRET"}`))) + require.Equal(t, 403, w.Code) + require.NotContains(t, w.Body.String(), "SECRET") + } +} diff --git a/backend/internal/handler/admin/custom_admin_key_proxies.go b/backend/internal/handler/admin/custom_admin_key_proxies.go index 970c5b29f7..fd07323720 100644 --- a/backend/internal/handler/admin/custom_admin_key_proxies.go +++ b/backend/internal/handler/admin/custom_admin_key_proxies.go @@ -31,7 +31,7 @@ func scopedProxyDTO(p service.Proxy) scopedProxyOption { // scopedAdminProxyRead 对代理读取限定数量;无分页的 /all 从全池抽样。 func (h *ProxyHandler) scopedAdminProxyRead(c *gin.Context) bool { - principal := adminaccess.FromContext(c.Request.Context()) + principal := adminaccess.RestrictedFromContext(c.Request.Context()) if principal == nil { return false } diff --git a/backend/internal/handler/admin/custom_admin_key_statistics.go b/backend/internal/handler/admin/custom_admin_key_statistics.go new file mode 100644 index 0000000000..ff970c81b6 --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_statistics.go @@ -0,0 +1,233 @@ +package admin + +import ( + "context" + "slices" + "strconv" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +type scopedAccountReader interface { + GetAccount(context.Context, int64) (*service.Account, error) +} + +func scopedAccountResource(a *service.Account) adminaccess.Account { + return adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Platform: a.Platform, Type: a.Type} +} + +// 仅校验实际读取对象;上游凭证来自母账户时,母账户必须同时获授权。 +func scopedAuthorizedAccount(c *gin.Context, reader scopedAccountReader, id int64, action string, parent bool) (*service.Account, bool) { + p := adminaccess.RestrictedFromContext(c.Request.Context()) + if p == nil { + return nil, true + } + if reader == nil || id <= 0 { + response.Error(c, 404, "账户不存在") + return nil, false + } + a, err := reader.GetAccount(c.Request.Context(), id) + if err != nil || a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) { + response.Error(c, 404, "账户不存在") + return nil, false + } + if parent && a.IsShadow() { + if a.ParentAccountID == nil || *a.ParentAccountID == id { + response.Error(c, 404, "账户不存在") + return nil, false + } + source, err := reader.GetAccount(c.Request.Context(), *a.ParentAccountID) + if err != nil || source == nil || source.IsShadow() || !p.Policy.AllowsAccount(action, scopedAccountResource(source)) { + response.Error(c, 404, "账户不存在") + return nil, false + } + } + return a, true +} + +func (h *AccountHandler) scopedAdminStatistics(c *gin.Context) bool { + path := strings.TrimPrefix(c.FullPath(), "/api/v1/admin/accounts") + action := "" + switch { + case c.Request.Method == "GET" && (path == "/:id/today-stats" || path == "/:id/stats"): + action = "accounts.stats.read" + case c.Request.Method == "GET" && path == "/:id/usage": + action = "accounts.usage.read" + case c.Request.Method == "POST" && path == "/today-stats/batch": + action = "accounts.stats.read" + case c.Request.Method == "POST" && path == "/usage/batch": + action = "accounts.usage.read" + default: + return false + } + if strings.HasSuffix(path, "/batch") { + var req BatchUsageRequest + if c.ShouldBindJSON(&req) != nil || len(req.AccountIDs) == 0 || len(req.AccountIDs) > 100 { + response.BadRequest(c, "请明确指定 1 至 100 个账户 ID") + return true + } + ids := make([]int64, 0, len(req.AccountIDs)) + accounts := map[int64]*service.Account{} + for _, id := range req.AccountIDs { + if id <= 0 { + response.BadRequest(c, "账户 ID 无效") + return true + } + if slices.Contains(ids, id) { + continue + } + a, ok := scopedAuthorizedAccount(c, h.adminService, id, action, action == "accounts.usage.read") + if !ok { + return true + } + ids = append(ids, id) + accounts[id] = a + } + if h.accountUsageService == nil { + response.Error(c, 503, "账户额度服务不可用") + return true + } + // 不读取全权批量缓存,避免不同权限共享 ETag 或未裁剪结果。 + if action == "accounts.stats.read" { + stats, err := h.accountUsageService.GetTodayStatsBatch(c.Request.Context(), ids) + if err != nil { + response.Error(c, 502, "账户统计查询失败") + return true + } + response.Success(c, gin.H{"stats": stats}) + return true + } + usage, errs, err := h.accountUsageService.GetUsageBatch(c.Request.Context(), ids, req.Force) + if err != nil { + response.Error(c, 502, "账户额度查询失败") + return true + } + safe := map[int64]any{} + for id, u := range usage { + if a := accounts[id]; a != nil && u != nil { + safe[id] = scopedUsageDTO(u, adminaccess.RestrictedFromContext(c.Request.Context()).Policy, a) + } + } + safeErrors := map[int64]string{} + for id := range errs { + if accounts[id] != nil { + safeErrors[id] = "账户额度查询失败" + } + } + response.Success(c, gin.H{"usage": safe, "errors": safeErrors}) + return true + } + id, _ := strconv.ParseInt(c.Param("id"), 10, 64) + a, ok := scopedAuthorizedAccount(c, h.adminService, id, action, action == "accounts.usage.read") + if !ok { + return true + } + if h.accountUsageService == nil { + response.Error(c, 503, "账户额度服务不可用") + return true + } + switch path { + case "/:id/today-stats": + stats, err := h.accountUsageService.GetTodayStats(c.Request.Context(), id) + if err != nil { + response.Error(c, 502, "账户统计查询失败") + } else { + response.Success(c, stats) + } + case "/:id/stats": + h.GetStats(c) + case "/:id/usage": + var u *service.UsageInfo + var err error + if c.Query("source") == "passive" { + u, err = h.accountUsageService.GetPassiveUsage(c.Request.Context(), id) + } else { + u, err = h.accountUsageService.GetUsage(c.Request.Context(), id, c.Query("force") == "true") + } + if err != nil || u == nil { + response.Error(c, 502, "账户额度查询失败") + } else { + response.Success(c, scopedUsageDTO(u, adminaccess.RestrictedFromContext(c.Request.Context()).Policy, a)) + } + } + return true +} + +func scopedUsageDTO(u *service.UsageInfo, p adminaccess.Policy, a *service.Account) gin.H { + stats := p.AllowsAccount("accounts.stats.read", scopedAccountResource(a)) + window := func(w *service.UsageProgress) *service.UsageProgress { + if w == nil { + return nil + } + safe := *w + if !stats { + safe.WindowStats = nil + } + return &safe + } + out := gin.H{ + "source": u.Source, + "updated_at": u.UpdatedAt, + "five_hour": window(u.FiveHour), + "seven_day": window(u.SevenDay), + "seven_day_sonnet": window(u.SevenDaySonnet), + "seven_day_fable": window(u.SevenDayFable), + "gemini_shared_daily": window(u.GeminiSharedDaily), + "gemini_pro_daily": window(u.GeminiProDaily), + "gemini_flash_daily": window(u.GeminiFlashDaily), + "gemini_shared_minute": window(u.GeminiSharedMinute), + "gemini_pro_minute": window(u.GeminiProMinute), + "gemini_flash_minute": window(u.GeminiFlashMinute), + "thirty_day": window(u.ThirtyDay), + "antigravity_quota": u.AntigravityQuota, + "antigravity_quota_details": u.AntigravityQuotaDetails, + "ai_credits": u.AICredits, + "grok_request_quota": u.GrokRequestQuota, + "grok_token_quota": u.GrokTokenQuota, + "grok_retry_after_seconds": u.GrokRetryAfterSeconds, + "grok_quota_snapshot_state": u.GrokQuotaSnapshotState, + "grok_free_token_limit": u.GrokFreeTokenLimit, + "needs_reauth": u.NeedsReauth, + "needs_verify": u.NeedsVerify, + "is_banned": u.IsBanned, + "is_forbidden": u.IsForbidden, + } + if p.AllowsAccount("accounts.identity.read", scopedAccountResource(a)) { + out["subscription_tier"] = u.SubscriptionTier + out["subscription_tier_raw"] = u.SubscriptionTierRaw + } + + if u.GrokBilling != nil { + billing := *u.GrokBilling + if !p.AllowsAccount("accounts.identity.read", scopedAccountResource(a)) { + billing.Plan = "" + billing.TopUpMethod = "" + billing.IsUnifiedBillingUser = false + } + if !stats { + billing.UsedCents = nil + billing.IncludedUsedCents = nil + billing.MonthlyUsed = nil + billing.OnDemandUsed = nil + } + out["grok_billing"] = &billing + } + if stats { + out["grok_local_usage"] = u.GrokLocalUsage + out["grok_local_usage_24h"] = u.GrokLocalUsage24h + out["grok_local_usage_7d"] = u.GrokLocalUsage7d + out["grok_local_usage_monthly"] = u.GrokLocalUsageMonthly + } + if u.Error != "" { + out["error"] = "上游额度查询失败" + } + switch u.ErrorCode { + case "forbidden", "unauthenticated", "rate_limited", "network_error": + out["error_code"] = u.ErrorCode + } + return out +} diff --git a/backend/internal/handler/admin/custom_admin_key_statistics_test.go b/backend/internal/handler/admin/custom_admin_key_statistics_test.go new file mode 100644 index 0000000000..b41811411e --- /dev/null +++ b/backend/internal/handler/admin/custom_admin_key_statistics_test.go @@ -0,0 +1,239 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "fmt" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type scopedStatisticsAccounts struct { + service.AdminService + accounts map[int64]*service.Account +} + +func (s *scopedStatisticsAccounts) GetAccount(_ context.Context, id int64) (*service.Account, error) { + return s.accounts[id], nil +} +func statisticsPolicy(permission string) adminaccess.Policy { + return adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{permission}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}} +} +func statisticsContext(c *gin.Context, permission string) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: statisticsPolicy(permission)})) +} + +func TestScopedAdminStatisticsRejectBeforeCacheOrService(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, 2: {ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}} + h := &AccountHandler{adminService: svc} + for _, path := range []string{"/api/v1/admin/accounts/1/today-stats", "/api/v1/admin/accounts/1/stats", "/api/v1/admin/accounts/today-stats/batch", "/api/v1/admin/accounts/usage/batch"} { + t.Run(path, func(t *testing.T) { + r := gin.New() + r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.read") }) + r.Use(h.ScopedAdminKeyAccounts) + method := "GET" + if strings.Contains(path, "batch") { + method = "POST" + } + r.Handle(method, strings.Replace(path, "/1/", "/:id/", 1), func(c *gin.Context) { t.Fatal("不得调用原处理器") }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(`{"account_ids":[1,2]}`))) + require.Equal(t, 404, w.Code, w.Body.String()) + }) + } +} + +func TestScopedAdminOpenAIRejectsBeforeUpstream(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}} + stub := &referralHandlerStub{} + h := &OpenAIOAuthHandler{adminService: svc, referralService: stub} + r := gin.New() + r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.read") }) + r.POST("/:id/referrals/invite", h.SendReferralInvite) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("POST", "/1/referrals/invite", strings.NewReader(`{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`))) + require.Equal(t, 404, w.Code, w.Body.String()) + require.Zero(t, stub.sends) +} + +func TestScopedAdminUsageProjectionKeepsPlatformQuotaAndHidesCosts(t *testing.T) { + a := &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}} + u := &service.UsageInfo{FiveHour: &service.UsageProgress{Utilization: 25, WindowStats: &service.WindowStats{Cost: 123}}, SevenDaySonnet: &service.UsageProgress{Utilization: 30}, GeminiProDaily: &service.UsageProgress{Utilization: 40}, AntigravityQuota: map[string]*service.AntigravityModelQuota{"model": {Utilization: 50}}, Error: "TOKEN_SECRET", ValidationURL: "URL_SECRET", ForbiddenReason: "IDENTITY_SECRET"} + out := scopedUsageDTO(u, statisticsPolicy("accounts.usage.read"), a) + require.Nil(t, out["five_hour"].(*service.UsageProgress).WindowStats) + require.NotNil(t, out["seven_day_sonnet"]) + require.NotNil(t, out["gemini_pro_daily"]) + require.NotNil(t, out["antigravity_quota"]) + raw, err := json.Marshal(out) + require.NoError(t, err) + require.NotContains(t, string(raw), "SECRET") + require.NotContains(t, string(raw), "123") + require.NotNil(t, u.FiveHour.WindowStats, "裁剪不能更改共享缓存") +} + +func TestScopedAdminOpenAIQuotaActionsAndIdentity(t *testing.T) { + for _, tc := range []struct { + action, path, method string + allow bool + }{ + {"openai.quota.read", "/1/quota", "GET", true}, {"openai.quota.read", "/1/quota/refresh", "POST", true}, + {"accounts.usage.read", "/1/quota", "GET", false}, {"openai.quota.reset", "/1/quota", "GET", false}, + } { + t.Run(tc.action+tc.path, func(t *testing.T) { + svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}} + stub := &openAIQuotaWorkflowStub{queryResult: &service.OpenAIQuotaUsage{UserID: "IDENTITY_SECRET", Email: "IDENTITY_SECRET", AccountID: "IDENTITY_SECRET", PlanType: "IDENTITY_SECRET", RateLimit: &service.OpenAIRateLimit{PrimaryWindow: &service.OpenAIRateLimitWindow{UsedPercent: 23}}, RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{AvailableCount: 3}}} + h := &OpenAIOAuthHandler{adminService: svc, quotaService: stub} + r := gin.New() + r.Use(func(c *gin.Context) { statisticsContext(c, tc.action) }) + r.GET("/:id/quota", h.QueryQuota) + r.POST("/:id/quota/refresh", h.RefreshQuota) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil)) + if tc.allow { + require.Equal(t, 200, w.Code, w.Body.String()) + require.Equal(t, 1, stub.queryCalls) + require.Contains(t, w.Body.String(), `"available_count":3`) + require.Contains(t, w.Body.String(), `"used_percent":23`) + } else { + require.Equal(t, 404, w.Code) + require.Zero(t, stub.queryCalls) + require.Zero(t, stub.cacheCalls) + } + require.NotContains(t, w.Body.String(), "SECRET") + }) + } +} + +func TestScopedAdminAccountScopeAndShadowSource(t *testing.T) { + parent := int64(2) + for _, tc := range []struct { + name string + a, source *service.Account + rules []adminaccess.Rule + allowed bool + }{ + {"同规则", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, nil, nil, true}, + {"其他组", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}, nil, nil, false}, + {"其他平台", &service.Account{ID: 1, Platform: "anthropic", Type: "oauth", GroupIDs: []int64{1}}, nil, nil, false}, + {"其他类型", &service.Account{ID: 1, Platform: "openai", Type: "apikey", GroupIDs: []int64{1}}, nil, nil, false}, + {"母账户越权", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}, ParentAccountID: &parent}, &service.Account{ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}, nil, false}, + {"不能拼接规则", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, nil, []adminaccess.Rule{{Permissions: []string{"openai.quota.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"apikey"}}, {Permissions: []string{"openai.quota.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: tc.a, 2: tc.source}} + r := gin.New() + r.Use(func(c *gin.Context) { + statisticsContext(c, "openai.quota.read") + if tc.rules != nil { + p := adminaccess.FromContext(c.Request.Context()) + p.Policy.Rules = tc.rules + } + }) + r.GET("/:id/quota", func(c *gin.Context) { + _, ok := scopedAuthorizedAccount(c, svc, 1, "openai.quota.read", true) + if ok { + c.Status(204) + } + }) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/1/quota", nil)) + want := 404 + if tc.allowed { + want = 204 + } + require.Equal(t, want, w.Code, w.Body.String()) + }) + } +} + +func TestScopedAdminMutationResponseRequiresReadPermission(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, read := range []bool{false, true} { + for _, kind := range []string{"reset", "invite"} { + t.Run(fmt.Sprintf("%s/read=%v", kind, read), func(t *testing.T) { + count := 2 + svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}} + quota := &openAIQuotaWorkflowStub{resetResult: &service.OpenAIQuotaResetResult{Code: "success"}, queryResult: &service.OpenAIQuotaUsage{RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{AvailableCount: 3}, Email: "IDENTITY_SECRET"}} + referral := &referralHandlerStub{eligibility: &service.OpenAIReferralEligibility{ShouldShow: true, AvailableInvites: &count}} + h := &OpenAIOAuthHandler{adminService: svc, quotaService: quota, referralService: referral, rateLimitService: &openAIAccountStateRecovererStub{}} + action, readAction, path := "openai.quota.reset", "openai.quota.read", "/1/reset" + if kind == "invite" { + action, readAction, path = "openai.referrals.invite", "openai.referrals.read", "/1/invite" + } + r := gin.New() + r.Use(func(c *gin.Context) { + statisticsContext(c, action) + if read { + p := adminaccess.FromContext(c.Request.Context()) + p.Policy.Rules[0].Permissions = append(p.Policy.Rules[0].Permissions, readAction) + } + }) + r.POST("/:id/reset", h.ResetQuota) + r.POST("/:id/invite", h.SendReferralInvite) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(`{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`))) + require.Equal(t, 200, w.Code, w.Body.String()) + require.NotContains(t, w.Body.String(), "IDENTITY_SECRET") + if kind == "reset" { + require.Equal(t, 1, quota.resetCalls) + if read { + require.Contains(t, w.Body.String(), "available_count") + } else { + require.NotContains(t, w.Body.String(), "available_count") + } + } else { + require.Equal(t, 1, referral.sends) + if read { + require.Contains(t, w.Body.String(), "available_invites") + } else { + require.NotContains(t, w.Body.String(), "available_invites") + } + } + }) + } + } +} + +func TestScopedAdminUsageBillingPreservesQuotaWithoutCost(t *testing.T) { + limit, used, percent := 100.0, 123.0, 25.0 + u := &service.UsageInfo{GrokBilling: &xai.BillingSummary{MonthlyLimit: &limit, MonthlyUsed: &used, UsedCents: &used, UsedPercent: &percent, Plan: "IDENTITY_SECRET"}} + a := &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}} + out := scopedUsageDTO(u, statisticsPolicy("accounts.usage.read"), a) + billing, ok := out["grok_billing"].(*xai.BillingSummary) + require.True(t, ok, "须保留真实上游额度窗口") + require.Equal(t, &limit, billing.MonthlyLimit) + require.Equal(t, &percent, billing.UsedPercent) + require.Nil(t, billing.MonthlyUsed) + require.Nil(t, billing.UsedCents) + require.Empty(t, billing.Plan) + require.NotNil(t, u.GrokBilling.MonthlyUsed, "不能裁剪共享缓存") +} + +func TestScopedAdminBatchAuthorizationPrecedesETag(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, 2: {ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}} + h := &AccountHandler{adminService: svc} + cached := accountTodayStatsBatchCache.Set(buildAccountTodayStatsBatchCacheKey([]int64{1, 2}), gin.H{"stats": "CACHE_SECRET"}) + r := gin.New() + r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.stats.read") }) + r.Use(h.ScopedAdminKeyAccounts) + r.POST("/api/v1/admin/accounts/today-stats/batch", h.GetBatchTodayStats) + request := httptest.NewRequest("POST", "/api/v1/admin/accounts/today-stats/batch", strings.NewReader(`{"account_ids":[1,2]}`)) + request.Header.Set("If-None-Match", cached.ETag) + w := httptest.NewRecorder() + r.ServeHTTP(w, request) + require.Equal(t, 404, w.Code, w.Body.String()) + require.Empty(t, w.Header().Get("ETag")) + require.NotContains(t, w.Body.String(), "CACHE_SECRET") +} diff --git a/backend/internal/handler/admin/custom_admin_key_users.go b/backend/internal/handler/admin/custom_admin_key_users.go index 5a78d7c393..cd10187021 100644 --- a/backend/internal/handler/admin/custom_admin_key_users.go +++ b/backend/internal/handler/admin/custom_admin_key_users.go @@ -12,7 +12,7 @@ import ( // adminUserResponse 对受限密钥使用字段白名单,避免完整管理员 DTO 新增字段时隐式扩大授权。 // 订阅及用量由各自的独立接口提供,用户资料接口不嵌入这些关联数据。 func adminUserResponse(c *gin.Context, user *service.User) any { - principal := adminaccess.FromContext(c.Request.Context()) + principal := adminaccess.RestrictedFromContext(c.Request.Context()) if principal == nil { return dto.UserFromServiceAdmin(user) } diff --git a/backend/internal/handler/admin/custom_admin_key_users_test.go b/backend/internal/handler/admin/custom_admin_key_users_test.go index 497cae2822..42049afb09 100644 --- a/backend/internal/handler/admin/custom_admin_key_users_test.go +++ b/backend/internal/handler/admin/custom_admin_key_users_test.go @@ -43,6 +43,9 @@ func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) { svc := &scopedUserResponseService{} h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil) r := gin.New() + r.Use(func(c *gin.Context) { + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: "full", Policy: adminaccess.Policy{FullAccess: true}})) + }) r.GET("/users", h.List) r.GET("/users/:id", h.GetByID) for _, path := range []string{"/users", "/users?include_subscriptions=true", "/users/7"} { @@ -62,7 +65,7 @@ func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) { } } -func TestScopedAdminUserBalanceResponseRedactsCachedFullAdminResult(t *testing.T) { +func TestScopedAdminUserBalanceReplayRejectsDifferentCredential(t *testing.T) { gin.SetMode(gin.TestMode) previous := service.DefaultIdempotencyCoordinator() t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) }) @@ -91,6 +94,12 @@ func TestScopedAdminUserBalanceResponseRedactsCachedFullAdminResult(t *testing.T } w := httptest.NewRecorder() r.ServeHTTP(w, req) + if scoped != scopedFirst { + require.Equal(t, 409, w.Code, w.Body.String()) + require.NotContains(t, w.Body.String(), "内部备注") + require.NotContains(t, w.Body.String(), "内部密钥") + continue + } require.Equal(t, 200, w.Code, w.Body.String()) if i > 0 { require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed")) diff --git a/backend/internal/handler/admin/custom_admin_keys.go b/backend/internal/handler/admin/custom_admin_keys.go index 8abedc09fb..81ae15af9b 100644 --- a/backend/internal/handler/admin/custom_admin_keys.go +++ b/backend/internal/handler/admin/custom_admin_keys.go @@ -50,6 +50,7 @@ func (h *SettingHandler) CreateScopedAdminKey(c *gin.Context) { response.ErrorFrom(c, e) return } + middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access": item.Policy.FullAccess}) response.Success(c, gin.H{"key": key, "item": item}) } func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) { @@ -66,6 +67,7 @@ func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) { response.ErrorFrom(c, e) return } + middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access_before": item.PreviousFullAccess, "full_access": item.Policy.FullAccess}) response.Success(c, item) } func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) { @@ -77,6 +79,7 @@ func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) { response.ErrorFrom(c, e) return } + middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access": item.Policy.FullAccess}) response.Success(c, gin.H{"key": key, "item": item}) } func (h *SettingHandler) RevokeScopedAdminKey(c *gin.Context) { diff --git a/backend/internal/handler/admin/email_blacklist_handler_test.go b/backend/internal/handler/admin/email_blacklist_handler_test.go new file mode 100644 index 0000000000..e7ad5dac6c --- /dev/null +++ b/backend/internal/handler/admin/email_blacklist_handler_test.go @@ -0,0 +1,179 @@ +package admin + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type emailBlacklistSettingRepoStub struct { + *settingHandlerRepoStub + setCalls int +} + +func (s *emailBlacklistSettingRepoStub) Set(_ context.Context, key, value string) error { + s.setCalls++ + s.values[key] = value + return nil +} + +type emailBlacklistAdminServiceStub struct { + *stubAdminService + findEmails []string + matched []service.User + disableIDs []int64 + disableCalls int +} + +func (s *emailBlacklistAdminServiceStub) FindActiveUsersByBlacklistedEmails(_ context.Context, emails []string) ([]service.User, error) { + s.findEmails = append([]string(nil), emails...) + return s.matched, nil +} + +func (s *emailBlacklistAdminServiceStub) BatchDisableUsers(_ context.Context, userIDs []int64) (int, error) { + s.disableCalls++ + s.disableIDs = append([]int64(nil), userIDs...) + return len(userIDs), nil +} + +func serveEmailBlacklistJSON(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder { + t.Helper() + var reader *bytes.Reader + if raw, ok := body.(string); ok { + reader = bytes.NewReader([]byte(raw)) + } else { + raw, err := json.Marshal(body) + require.NoError(t, err) + reader = bytes.NewReader(raw) + } + recorder := httptest.NewRecorder() + request := httptest.NewRequest(method, path, reader) + request.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, request) + return recorder +} + +func setupEmailBlacklistSettingRouter(repo *emailBlacklistSettingRepoStub) *gin.Engine { + gin.SetMode(gin.TestMode) + svc := service.NewSettingService(repo, &config.Config{}) + handler := NewSettingHandler(svc, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.GET("/api/v1/admin/settings/registration-email-blacklist", handler.GetRegistrationEmailBlacklist) + router.PUT("/api/v1/admin/settings/registration-email-blacklist", handler.UpdateRegistrationEmailBlacklist) + return router +} + +func TestUpdateRegistrationEmailBlacklist_RequiresEmailsField(t *testing.T) { + repo := &emailBlacklistSettingRepoStub{settingHandlerRepoStub: &settingHandlerRepoStub{values: map[string]string{ + service.SettingKeyRegistrationEmailBlacklist: `["keep@gmail.com"]`, + }}} + router := setupEmailBlacklistSettingRouter(repo) + + rec := serveEmailBlacklistJSON(t, router, http.MethodPut, "/api/v1/admin/settings/registration-email-blacklist", `{}`) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Zero(t, repo.setCalls) +} + +func TestUpdateRegistrationEmailBlacklist_ReturnsSavedAndAdded(t *testing.T) { + repo := &emailBlacklistSettingRepoStub{settingHandlerRepoStub: &settingHandlerRepoStub{values: map[string]string{ + service.SettingKeyRegistrationEmailBlacklist: `["keep@gmail.com"]`, + }}} + router := setupEmailBlacklistSettingRouter(repo) + + rec := serveEmailBlacklistJSON(t, router, http.MethodPut, "/api/v1/admin/settings/registration-email-blacklist", + map[string]any{"emails": []string{"keep@gmail.com", "NEW@gmail.com"}}) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + + var resp struct { + Data UpdateRegistrationEmailBlacklistResponse `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + require.Equal(t, []string{"keep@gmail.com", "new@gmail.com"}, resp.Data.Emails) + require.Equal(t, []string{"new@gmail.com"}, resp.Data.Added) + require.Equal(t, service.MaxRegistrationEmailBlacklistSize, resp.Data.Max) + + rec = serveEmailBlacklistJSON(t, router, http.MethodGet, "/api/v1/admin/settings/registration-email-blacklist", `{}`) + require.Equal(t, http.StatusOK, rec.Code) + require.Contains(t, rec.Body.String(), "new@gmail.com") +} + +func TestUpdateRegistrationEmailBlacklist_InvalidEntryRejected(t *testing.T) { + repo := &emailBlacklistSettingRepoStub{settingHandlerRepoStub: &settingHandlerRepoStub{values: map[string]string{}}} + router := setupEmailBlacklistSettingRouter(repo) + + rec := serveEmailBlacklistJSON(t, router, http.MethodPut, "/api/v1/admin/settings/registration-email-blacklist", + map[string]any{"emails": []string{"ok@gmail.com", "broken"}}) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Contains(t, rec.Body.String(), "EMAIL_BLACKLIST_INVALID_ENTRY") + require.Zero(t, repo.setCalls) +} + +func setupEmailBlacklistUserRouter(stub service.AdminService) *gin.Engine { + gin.SetMode(gin.TestMode) + handler := NewUserHandler(stub, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.POST("/api/v1/admin/users/blacklist-matches", handler.FindBlacklistedEmailUsers) + router.POST("/api/v1/admin/users/batch-disable", handler.BatchDisable) + return router +} + +func TestFindBlacklistedEmailUsers_ReturnsMatchedUsers(t *testing.T) { + stub := &emailBlacklistAdminServiceStub{ + stubAdminService: newStubAdminService(), + matched: []service.User{{ID: 3, Email: "a.b@gmail.com", Username: "ab", PasswordHash: "secret"}}, + } + router := setupEmailBlacklistUserRouter(stub) + + rec := serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/blacklist-matches", + map[string]any{"emails": []string{"ab@gmail.com"}}) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, []string{"ab@gmail.com"}, stub.findEmails) + + var resp struct { + Data struct { + Items []map[string]any `json:"items"` + Total int `json:"total"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) + require.Equal(t, 1, resp.Data.Total) + require.Equal(t, map[string]any{"id": float64(3), "email": "a.b@gmail.com", "username": "ab"}, resp.Data.Items[0]) +} + +func TestFindBlacklistedEmailUsers_RejectsOversizedRequest(t *testing.T) { + stub := &emailBlacklistAdminServiceStub{stubAdminService: newStubAdminService()} + router := setupEmailBlacklistUserRouter(stub) + + emails := make([]string, service.MaxRegistrationEmailBlacklistSize+1) + for i := range emails { + emails[i] = "x@gmail.com" + } + rec := serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/blacklist-matches", + map[string]any{"emails": emails}) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Nil(t, stub.findEmails) +} + +func TestBatchDisable_ValidatesAndForwards(t *testing.T) { + stub := &emailBlacklistAdminServiceStub{stubAdminService: newStubAdminService()} + router := setupEmailBlacklistUserRouter(stub) + + rec := serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/batch-disable", + map[string]any{"user_ids": []int64{}}) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Zero(t, stub.disableCalls) + + rec = serveEmailBlacklistJSON(t, router, http.MethodPost, "/api/v1/admin/users/batch-disable", + map[string]any{"user_ids": []int64{4, 5}}) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, []int64{4, 5}, stub.disableIDs) + require.Contains(t, rec.Body.String(), `"affected":2`) +} diff --git a/backend/internal/handler/admin/idempotency_helper.go b/backend/internal/handler/admin/idempotency_helper.go index db104a7d6c..1642b33589 100644 --- a/backend/internal/handler/admin/idempotency_helper.go +++ b/backend/internal/handler/admin/idempotency_helper.go @@ -2,6 +2,10 @@ package admin import ( "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" "strconv" "time" @@ -68,6 +72,11 @@ func executeAdminIdempotentWithTimeout( } func adminActorScope(c *gin.Context) string { + if principal := adminaccess.FromContext(c.Request.Context()); principal != nil { + policy, _ := json.Marshal(principal.Policy) + digest := sha256.Sum256(policy) + return "admin-key:" + principal.KeyID + ":" + hex.EncodeToString(digest[:]) + } actorScope := "admin:0" if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok { actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10) diff --git a/backend/internal/handler/admin/openai_oauth_handler.go b/backend/internal/handler/admin/openai_oauth_handler.go index b96bf426a6..704381ab01 100644 --- a/backend/internal/handler/admin/openai_oauth_handler.go +++ b/backend/internal/handler/admin/openai_oauth_handler.go @@ -9,6 +9,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/handler/dto" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/Wei-Shaw/sub2api/internal/pkg/response" "github.com/Wei-Shaw/sub2api/internal/service" @@ -194,6 +195,11 @@ type OpenAICodexPATCreateRequest struct { // RefreshToken refreshes an OpenAI OAuth token // POST /api/v1/admin/openai/refresh-token func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) { + scoped := adminaccess.RestrictedFromContext(c.Request.Context()) != nil + if scoped && !adminaccess.RouteAllowed(adminaccess.RestrictedFromContext(c.Request.Context()).Policy, c.Request.Method, c.FullPath()) { + response.Error(c, 403, "调用方令牌刷新未授权") + return + } var req OpenAIRefreshTokenRequest if err := c.ShouldBindJSON(&req); err != nil { response.BadRequest(c, "Invalid request: "+err.Error()) @@ -211,6 +217,10 @@ func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) { var proxyURL string if req.ProxyID != nil { proxy, err := h.adminService.GetProxy(c.Request.Context(), *req.ProxyID) + if scoped && (err != nil || proxy == nil || !proxy.IsActive() || proxy.IsExpired(time.Now())) { + response.BadRequest(c, "代理不可用") + return + } if err == nil && proxy != nil { proxyURL = proxy.URL() } @@ -225,6 +235,10 @@ func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) { tokenInfo, err := h.openaiOAuthService.RefreshTokenWithClientID(c.Request.Context(), refreshToken, proxyURL, clientID) if err != nil { + if scoped { + response.Error(c, 502, "调用方令牌刷新失败") + return + } response.ErrorFrom(c, err) return } @@ -477,6 +491,10 @@ func buildOpenAICodexPATAccountName(name string, tokenInfo *service.OpenAITokenI // QueryQuota queries the rate-limit / quota usage for an OpenAI account. // GET /api/v1/admin/openai/accounts/:id/quota func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) { + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { + h.scopedOpenAIQuota(c, false) + return + } accountID, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { response.BadRequest(c, "Invalid account ID") @@ -504,6 +522,10 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) { // state: the audit middleware only records mutating verbs, so a persisting GET // would mutate the database without an audit trail. func (h *OpenAIOAuthHandler) RefreshQuota(c *gin.Context) { + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { + h.scopedOpenAIQuota(c, true) + return + } accountID, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { response.BadRequest(c, "Invalid account ID") @@ -588,13 +610,19 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) { response.BadRequest(c, "Invalid account ID") return } + if !h.scopedOpenAIAllowed(c, accountID, "openai.quota.reset", false) { + return + } if h.quotaService == nil { response.BadRequest(c, "openai quota service is not enabled") return } + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { + c.Request = c.Request.WithContext(service.WithScopedAdminAccountOperation(c.Request.Context(), "openai.quota.reset")) + } result, err := h.quotaService.ResetCredit(c.Request.Context(), accountID) if err != nil { - response.ErrorFrom(c, err) + scopedOpenAIError(c, err) return } if result == nil { @@ -620,5 +648,13 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) { if postResult.Account != nil { resetResponse.Account = dto.AccountFromService(postResult.Account) } + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { + if h.scopedOpenAIHasPermission(c, accountID, "openai.quota.read", true) { + resetResponse.Quota = h.scopedQuotaDTO(c, accountID, resetResponse.Quota) + } else { + resetResponse.Quota = nil + } + resetResponse.Account = nil + } response.Success(c, resetResponse) } diff --git a/backend/internal/handler/admin/openai_referral_handler.go b/backend/internal/handler/admin/openai_referral_handler.go index 42a2226e58..cdb6263743 100644 --- a/backend/internal/handler/admin/openai_referral_handler.go +++ b/backend/internal/handler/admin/openai_referral_handler.go @@ -47,15 +47,19 @@ func (h *OpenAIOAuthHandler) RefreshReferrals(c *gin.Context) { if !ok { return } + if !h.scopedOpenAIAllowed(c, id, "openai.referrals.read", true) { + return + } eligibility, err := h.referralService.QueryReferralEligibility(c.Request.Context(), id) if err != nil { - response.ErrorFrom(c, err) + scopedOpenAIError(c, err) return } if eligibility == nil { response.Error(c, http.StatusBadGateway, "Empty invitation eligibility response") return } + eligibility = h.scopedReferralDTO(c, eligibility) cacheErr := h.referralService.CacheReferralSnapshot(c.Request.Context(), id, eligibility) response.Success(c, openAIReferralRefreshResponse{Eligibility: eligibility, CachePersisted: cacheErr == nil}) } @@ -65,6 +69,9 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) { if !ok { return } + if !h.scopedOpenAIAllowed(c, id, "openai.referrals.invite", false) { + return + } var input service.OpenAIReferralSendRequest if err := c.ShouldBindJSON(&input); err != nil { response.BadRequest(c, "Invalid invitation request") @@ -72,7 +79,7 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) { } result, err := h.referralService.SendReferralInvite(c.Request.Context(), id, input) if err != nil { - response.ErrorFrom(c, err) + scopedOpenAIError(c, err) return } if result == nil || !result.Sent { @@ -81,7 +88,7 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) { } // The email is already sent. Refresh failure must not turn it into a failed // submission and encourage a duplicate send, even if the browser disconnects. - baseCtx := context.WithoutCancel(c.Request.Context()) + baseCtx := service.WithScopedAdminAccountOperation(context.WithoutCancel(c.Request.Context()), "openai.referrals.invite") refreshCtx, cancelRefresh := context.WithTimeout(baseCtx, 8*time.Second) eligibility, refreshErr := h.referralService.QueryReferralEligibility(refreshCtx, id) cancelRefresh() @@ -92,10 +99,15 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) { // invalidating a stale snapshot) a fresh, independent deadline. cacheCtx, cancelCache := context.WithTimeout(baseCtx, 3*time.Second) defer cancelCache() + eligibility = h.scopedReferralDTO(c, eligibility) cacheErr := h.referralService.CacheReferralSnapshot(cacheCtx, id, eligibility) + responseEligibility := eligibility + if !h.scopedOpenAIHasPermission(c, id, "openai.referrals.read", true) { + responseEligibility = nil + } response.Success(c, openAIReferralSendResponse{ OpenAIReferralSendResult: *result, - openAIReferralRefreshResponse: openAIReferralRefreshResponse{Eligibility: eligibility, CachePersisted: cacheErr == nil}, + openAIReferralRefreshResponse: openAIReferralRefreshResponse{Eligibility: responseEligibility, CachePersisted: cacheErr == nil}, RefreshFailed: eligibility == nil, }) } diff --git a/backend/internal/handler/admin/scoped_admin_content_response.go b/backend/internal/handler/admin/scoped_admin_content_response.go index 69e037f8be..e4ff5f3667 100644 --- a/backend/internal/handler/admin/scoped_admin_content_response.go +++ b/backend/internal/handler/admin/scoped_admin_content_response.go @@ -19,7 +19,7 @@ type scopedPromoUsageResponse struct { } func adminPromoUsagesResponse(c *gin.Context, items []dto.PromoCodeUsage) any { - if adminaccess.FromContext(c.Request.Context()) == nil { + if adminaccess.RestrictedFromContext(c.Request.Context()) == nil { return items } out := make([]scopedPromoUsageResponse, 0, len(items)) @@ -36,7 +36,7 @@ type scopedAnnouncementReadResponse struct { } func adminAnnouncementReadResponse(c *gin.Context, items []service.AnnouncementUserReadStatus) any { - if adminaccess.FromContext(c.Request.Context()) == nil { + if adminaccess.RestrictedFromContext(c.Request.Context()) == nil { return items } out := make([]scopedAnnouncementReadResponse, 0, len(items)) diff --git a/backend/internal/handler/admin/scoped_admin_subscription_response.go b/backend/internal/handler/admin/scoped_admin_subscription_response.go index 8c467fbba1..210a35f36e 100644 --- a/backend/internal/handler/admin/scoped_admin_subscription_response.go +++ b/backend/internal/handler/admin/scoped_admin_subscription_response.go @@ -9,14 +9,14 @@ import ( ) func scopedAdminWriteOnly(c *gin.Context, readPermission string) bool { - p := adminaccess.FromContext(c.Request.Context()) + p := adminaccess.RestrictedFromContext(c.Request.Context()) return p != nil && !slices.Contains(p.Policy.GlobalPermissions, readPermission) } // adminSubscriptionResponse 在缓存重放后也应用字段白名单,不嵌入用户、分配人或分组配置。 // 写权限只确认订阅 ID;订阅用量等字段必须另有读取权限。 func adminSubscriptionResponse(c *gin.Context, data any) any { - if adminaccess.FromContext(c.Request.Context()) == nil { + if adminaccess.RestrictedFromContext(c.Request.Context()) == nil { return data } raw, err := json.Marshal(data) diff --git a/backend/internal/handler/admin/scoped_admin_subscription_response_test.go b/backend/internal/handler/admin/scoped_admin_subscription_response_test.go index 0756d674ca..bcdf89bda4 100644 --- a/backend/internal/handler/admin/scoped_admin_subscription_response_test.go +++ b/backend/internal/handler/admin/scoped_admin_subscription_response_test.go @@ -73,7 +73,7 @@ func (r *scopedSubscriptionRepo) ExtendExpiry(context.Context, int64, time.Time) return nil } -func TestScopedAdminSubscriptionExtendReplayRespectsReadPermission(t *testing.T) { +func TestScopedAdminSubscriptionExtendReplayRejectsChangedAuthorization(t *testing.T) { gin.SetMode(gin.TestMode) previous := service.DefaultIdempotencyCoordinator() t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) }) @@ -100,10 +100,12 @@ func TestScopedAdminSubscriptionExtendReplayRespectsReadPermission(t *testing.T) req.Header.Set("X-Test-Mode", mode) w := httptest.NewRecorder() r.ServeHTTP(w, req) - require.Equal(t, 200, w.Code, w.Body.String()) if i > 0 { - require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed")) + require.Equal(t, 409, w.Code, w.Body.String()) + require.NotContains(t, w.Body.String(), "private-user") + continue } + require.Equal(t, 200, w.Code, w.Body.String()) var result struct { Data map[string]json.RawMessage `json:"data"` } diff --git a/backend/internal/handler/admin/scoped_admin_usage_response.go b/backend/internal/handler/admin/scoped_admin_usage_response.go index 902ae310a7..6cc8542f2d 100644 --- a/backend/internal/handler/admin/scoped_admin_usage_response.go +++ b/backend/internal/handler/admin/scoped_admin_usage_response.go @@ -82,7 +82,7 @@ func scopedAdminUsageLogResponse(record *service.UsageLog) gin.H { } func adminUsageLogResponses(c *gin.Context, records []service.UsageLog) any { - if adminaccess.FromContext(c.Request.Context()) != nil { + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { out := make([]gin.H, 0, len(records)) for i := range records { out = append(out, scopedAdminUsageLogResponse(&records[i])) diff --git a/backend/internal/handler/admin/setting_handler_email_blacklist.go b/backend/internal/handler/admin/setting_handler_email_blacklist.go new file mode 100644 index 0000000000..f562531cf9 --- /dev/null +++ b/backend/internal/handler/admin/setting_handler_email_blacklist.go @@ -0,0 +1,65 @@ +package admin + +import ( + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// RegistrationEmailBlacklistResponse 精确邮箱黑名单 +type RegistrationEmailBlacklistResponse struct { + Emails []string `json:"emails"` + Max int `json:"max"` +} + +// UpdateRegistrationEmailBlacklistRequest 整体替换精确邮箱黑名单;emails 必须显式提交, +// 传空数组表示清空。 +type UpdateRegistrationEmailBlacklistRequest struct { + Emails *[]string `json:"emails"` +} + +// UpdateRegistrationEmailBlacklistResponse 保存后的名单,added 为相对旧名单新增的项。 +type UpdateRegistrationEmailBlacklistResponse struct { + Emails []string `json:"emails"` + Added []string `json:"added"` + Max int `json:"max"` +} + +// GetRegistrationEmailBlacklist 获取精确邮箱黑名单 +// GET /api/v1/admin/settings/registration-email-blacklist +func (h *SettingHandler) GetRegistrationEmailBlacklist(c *gin.Context) { + emails, err := h.settingService.GetRegistrationEmailBlacklist(c.Request.Context()) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, RegistrationEmailBlacklistResponse{ + Emails: emails, + Max: service.MaxRegistrationEmailBlacklistSize, + }) +} + +// UpdateRegistrationEmailBlacklist 整体替换精确邮箱黑名单 +// PUT /api/v1/admin/settings/registration-email-blacklist +func (h *SettingHandler) UpdateRegistrationEmailBlacklist(c *gin.Context) { + var req UpdateRegistrationEmailBlacklistRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.BadRequest(c, "Invalid request: "+err.Error()) + return + } + if req.Emails == nil { + response.BadRequest(c, "emails is required") + return + } + saved, added, err := h.settingService.SetRegistrationEmailBlacklist(c.Request.Context(), *req.Emails) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, UpdateRegistrationEmailBlacklistResponse{ + Emails: saved, + Added: added, + Max: service.MaxRegistrationEmailBlacklistSize, + }) +} 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/admin/user_handler.go b/backend/internal/handler/admin/user_handler.go index ceffd27947..7dd286b57c 100644 --- a/backend/internal/handler/admin/user_handler.go +++ b/backend/internal/handler/admin/user_handler.go @@ -151,7 +151,7 @@ func (h *UserHandler) List(c *gin.Context) { includeSubscriptions := parseBoolQueryWithDefault(raw, true) filters.IncludeSubscriptions = &includeSubscriptions } - principal := adminaccess.FromContext(c.Request.Context()) + principal := adminaccess.RestrictedFromContext(c.Request.Context()) if principal != nil { includeSubscriptions := false filters.IncludeSubscriptions = &includeSubscriptions @@ -430,7 +430,7 @@ func (h *UserHandler) UpdateBalance(c *gin.Context) { return dto.UserFromServiceAdmin(user), nil }, func(data any) any { // 成功确认不隐式授予用户资料或余额读取权限;缓存重放也必须经过此边界。 - if adminaccess.FromContext(c.Request.Context()) != nil { + if adminaccess.RestrictedFromContext(c.Request.Context()) != nil { return gin.H{"id": userID} } return data diff --git a/backend/internal/handler/admin/user_handler_email_blacklist.go b/backend/internal/handler/admin/user_handler_email_blacklist.go new file mode 100644 index 0000000000..be59b03d3d --- /dev/null +++ b/backend/internal/handler/admin/user_handler_email_blacklist.go @@ -0,0 +1,77 @@ +package admin + +import ( + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/service" + + "github.com/gin-gonic/gin" +) + +// FindBlacklistedEmailUsersRequest 待核对的黑名单邮箱 +type FindBlacklistedEmailUsersRequest struct { + Emails []string `json:"emails"` +} + +// BlacklistedEmailUser 收件箱身份命中黑名单、仍处于启用状态的普通用户 +type BlacklistedEmailUser struct { + ID int64 `json:"id"` + Email string `json:"email"` + Username string `json:"username"` +} + +// BatchDisableUsersRequest 批量禁用用户 +type BatchDisableUsersRequest struct { + UserIDs []int64 `json:"user_ids" binding:"required"` +} + +// FindBlacklistedEmailUsers 查找邮箱命中给定黑名单项的启用中普通用户 +// POST /api/v1/admin/users/blacklist-matches +func (h *UserHandler) FindBlacklistedEmailUsers(c *gin.Context) { + var req FindBlacklistedEmailUsersRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.BadRequest(c, "Invalid request: "+err.Error()) + return + } + if len(req.Emails) > service.MaxRegistrationEmailBlacklistSize { + response.BadRequest(c, fmt.Sprintf("emails cannot exceed %d", service.MaxRegistrationEmailBlacklistSize)) + return + } + + users, err := h.adminService.FindActiveUsersByBlacklistedEmails(c.Request.Context(), req.Emails) + if err != nil { + response.ErrorFrom(c, err) + return + } + items := make([]BlacklistedEmailUser, 0, len(users)) + for _, user := range users { + items = append(items, BlacklistedEmailUser{ID: user.ID, Email: user.Email, Username: user.Username}) + } + response.Success(c, gin.H{"items": items, "total": len(items)}) +} + +// BatchDisable 批量禁用用户(管理员与已禁用用户跳过) +// POST /api/v1/admin/users/batch-disable +func (h *UserHandler) BatchDisable(c *gin.Context) { + var req BatchDisableUsersRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.BadRequest(c, "Invalid request: "+err.Error()) + return + } + if len(req.UserIDs) == 0 { + response.BadRequest(c, "user_ids is required") + return + } + if len(req.UserIDs) > service.MaxBatchDisableUsers { + response.BadRequest(c, fmt.Sprintf("user_ids cannot exceed %d", service.MaxBatchDisableUsers)) + return + } + + affected, err := h.adminService.BatchDisableUsers(c.Request.Context(), req.UserIDs) + if err != nil { + response.ErrorFrom(c, err) + return + } + response.Success(c, gin.H{"affected": affected}) +} 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/gateway_handler.go b/backend/internal/handler/gateway_handler.go index be7cc0a1b0..58372073dd 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -147,6 +147,9 @@ func (h *GatewayHandler) Messages(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -599,6 +602,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -616,7 +620,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { RequestPayloadHash: requestPayloadHash, ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gateway.messages"), @@ -962,6 +966,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { forceCacheBilling := fs.ForceCacheBilling quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey) sessionID := service.ExtractClientSessionID(c) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -979,7 +984,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { RequestPayloadHash: requestPayloadHash, ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gateway.messages"), @@ -2158,6 +2163,9 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index ab9f931390..55abd416a2 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -47,6 +47,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.chatCompletionsErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -333,6 +336,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -349,7 +353,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { reqLog.Error("gateway.cc.record_usage_failed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 1800e5dda5..233cf07f3b 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -47,6 +47,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.responsesErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -315,6 +318,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context())) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -331,7 +335,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) { RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { reqLog.Error("gateway.responses.record_usage_failed", zap.Int64("account_id", account.ID), diff --git a/backend/internal/handler/gateway_models_test.go b/backend/internal/handler/gateway_models_test.go index 3724973dae..27daa74f8c 100644 --- a/backend/internal/handler/gateway_models_test.go +++ b/backend/internal/handler/gateway_models_test.go @@ -559,7 +559,7 @@ func TestGatewayModels_GeminiGroupFallsBackToGeminiModels(t *testing.T) { var got gatewayModelsResponseForTest require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) require.Equal(t, "list", got.Object) - require.Contains(t, modelIDsForTest(got.Data), "gemini-2.5-flash") + require.Contains(t, modelIDsForTest(got.Data), "gemini-3.5-flash") require.NotContains(t, modelIDsForTest(got.Data), "claude-sonnet-4-6") } diff --git a/backend/internal/handler/gateway_systemone.go b/backend/internal/handler/gateway_systemone.go index f9cc753c79..4f0d650985 100644 --- a/backend/internal/handler/gateway_systemone.go +++ b/backend/internal/handler/gateway_systemone.go @@ -56,6 +56,9 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -258,9 +261,13 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP sessionID := service.ExtractClientSessionID(c) requestPayloadHash := service.HashUsageRequestPayload(body) + // An interior pointer into SystemOneForwardResult would also retain its + // response body while usage waits in the queue. Copy only billing metadata. + forwardResult := result.ForwardResult + channelUsageFields := clientRequestedUsageFields(c, mapping, model, result.UpstreamModel) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ - Result: &result.ForwardResult, + Result: &forwardResult, APIKey: apiKey, User: apiKey.User, Account: account, @@ -274,7 +281,7 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, - ChannelUsageFields: clientRequestedUsageFields(c, mapping, model, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gateway.systemone"), diff --git a/backend/internal/handler/gemini_cached_content_bound_retry_test.go b/backend/internal/handler/gemini_cached_content_bound_retry_test.go new file mode 100644 index 0000000000..6220f12e5c --- /dev/null +++ b/backend/internal/handler/gemini_cached_content_bound_retry_test.go @@ -0,0 +1,120 @@ +//go:build unit + +package handler + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + boundRetryUpstream429 = `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}` + boundRetryUpstream502 = `{"error":{"code":502,"message":"Upstream service temporarily unavailable","status":"UNAVAILABLE"}}` +) + +// boundRetryUpstream 前 failures 次请求返回 failStatus(默认 429),之后返回成功的生成响应。 +type boundRetryUpstream struct { + service.HTTPUpstream + mu sync.Mutex + failures int + failStatus int + bodies []string +} + +func (u *boundRetryUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + raw, _ := io.ReadAll(req.Body) + u.mu.Lock() + u.bodies = append(u.bodies, string(raw)) + n := len(u.bodies) + u.mu.Unlock() + header := http.Header{"Content-Type": []string{"application/json"}} + if n <= u.failures { + if u.failStatus == http.StatusBadGateway { + return &http.Response{StatusCode: http.StatusBadGateway, Header: header, Body: io.NopCloser(strings.NewReader(boundRetryUpstream502))}, nil + } + return &http.Response{StatusCode: http.StatusTooManyRequests, Header: header, Body: io.NopCloser(strings.NewReader(boundRetryUpstream429))}, nil + } + body := `{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],` + + `"usageMetadata":{"promptTokenCount":10,"cachedContentTokenCount":8,"candidatesTokenCount":1,"totalTokenCount":11}}` + return &http.Response{StatusCode: http.StatusOK, Header: header, Body: io.NopCloser(strings.NewReader(body))}, nil +} + +func (u *boundRetryUpstream) requestBodies() []string { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.bodies...) +} + +// newBoundRetryEnv 构造绑定在池模式上游网关账号 900 上的显式缓存,账号对 retryCodes 同账号重试 2 次。 +func newBoundRetryEnv(t *testing.T, upstream *boundRetryUpstream, retryCodes ...int) *cachedBillingEnv { + t.Helper() + env := newCachedBillingEnv(t, 500, 900) + creds := env.accounts[900].Credentials + creds["base_url"] = "https://gw.example.com" + creds[service.GeminiExplicitCacheUpstreamCredentialKey] = true + creds["pool_mode"] = true + creds["pool_mode_retry_count"] = float64(2) + codes := make([]any, 0, len(retryCodes)) + for _, code := range retryCodes { + codes = append(codes, float64(code)) + } + creds["pool_mode_retry_status_codes"] = codes + env.seed(time.Now().Add(time.Hour)) + + env.h.geminiCompatService = service.NewGeminiMessagesCompatService(&cachedBillingAccountRepo{accounts: env.accounts}, + nil, nil, nil, nil, nil, upstream, nil, &config.Config{}) + return env +} + +func (e *cachedBillingEnv) generateWithCache() *httptest.ResponseRecorder { + return e.serve(http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent", + `{"cachedContent":"cachedContents/abc","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`, + gin.Params{{Key: "modelAction", Value: "/gemini-2.5-pro:generateContent"}}, e.h.GeminiV1BetaModels) +} + +func TestGeminiV1BetaModels_BoundCachePoolModeRetriesUpstream429(t *testing.T) { + upstream := &boundRetryUpstream{failures: 1} + env := newBoundRetryEnv(t, upstream, 429) + + rec := env.generateWithCache() + + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + bodies := upstream.requestBodies() + require.Len(t, bodies, 2, "429 后在持有缓存的账号上重试一次") + for _, body := range bodies { + require.Contains(t, body, `"cachedContents/up1"`, "每次重试都引用上游缓存名") + } +} + +func TestGeminiV1BetaModels_BoundCacheRetryExhaustedPassesThroughUpstream429(t *testing.T) { + upstream := &boundRetryUpstream{failures: 10} + env := newBoundRetryEnv(t, upstream, 429) + + rec := env.generateWithCache() + + require.Len(t, upstream.requestBodies(), 3, "首发 + pool_mode_retry_count 次同账号重试") + require.Equal(t, http.StatusTooManyRequests, rec.Code) + require.JSONEq(t, boundRetryUpstream429, rec.Body.String(), "重试用尽后原样回写上游网关的响应") +} + +// 502 在池模式重试状态码内时同样同账号重试;用尽后原样回写,不按空响应临时封禁本账号。 +func TestGeminiV1BetaModels_BoundCacheRetryExhaustedOn502KeepsAccountSchedulable(t *testing.T) { + upstream := &boundRetryUpstream{failures: 10, failStatus: http.StatusBadGateway} + env := newBoundRetryEnv(t, upstream, 429, 502) + + rec := env.generateWithCache() + + require.Len(t, upstream.requestBodies(), 3) + require.Equal(t, http.StatusBadGateway, rec.Code) + require.JSONEq(t, boundRetryUpstream502, rec.Body.String()) +} diff --git a/backend/internal/handler/gemini_cached_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index 2071c16129..ad6cb765dc 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -65,6 +65,9 @@ func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return nil, false + } if maxErr, ok := extractMaxBytesError(err); ok { googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) return nil, false diff --git a/backend/internal/handler/gemini_mixed_models_test.go b/backend/internal/handler/gemini_mixed_models_test.go index 6a0e2c2eb5..3f5ed01401 100644 --- a/backend/internal/handler/gemini_mixed_models_test.go +++ b/backend/internal/handler/gemini_mixed_models_test.go @@ -102,7 +102,7 @@ func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) { expectedNative string }{ {"native", 200, `{"models":[{"name":"models/gemini-native","inputTokenLimit":123}],"nextPageToken":"next"}`, "models/gemini-native"}, - {"scope fallback", 403, `{"error":"insufficient authentication scopes"}`, "models/gemini-2.5-pro"}, + {"scope fallback", 403, `{"error":"insufficient authentication scopes"}`, "models/gemini-3.5-flash"}, {"upstream error", 429, `{"error":"rate limited"}`, ""}, } { t.Run(tt.name, func(t *testing.T) { @@ -134,3 +134,109 @@ func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) { }) } } + +type geminiModelsUpstreamCounter struct { + service.HTTPUpstream + calls int +} + +func (u *geminiModelsUpstreamCounter) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + u.calls++ + return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"models":[{"name":"gemini-4-argon-high"}]}`))}, nil +} + +type geminiDeclaredModelsFixture struct { + t *testing.T + groupID int64 + handler *GatewayHandler + upstream *geminiModelsUpstreamCounter +} + +func newGeminiDeclaredModelsFixture(t *testing.T, accounts []service.Account) *geminiDeclaredModelsFixture { + groupID := int64(47) + repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: accounts}}} + upstream := &geminiModelsUpstreamCounter{} + return &geminiDeclaredModelsFixture{ + t: t, + groupID: groupID, + handler: &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})}, + upstream: upstream, + } +} + +func (f *geminiDeclaredModelsFixture) context(path, model string, allowlist service.GroupModelAllowlist) (*gin.Context, *httptest.ResponseRecorder) { + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodGet, path, nil) + if model != "" { + c.Params = gin.Params{{Key: "model", Value: model}} + } + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{GroupID: &f.groupID, Group: &service.Group{ID: f.groupID, Platform: service.PlatformGemini, ModelAllowlist: allowlist}}) + return c, rec +} + +func (f *geminiDeclaredModelsFixture) list(allowlist service.GroupModelAllowlist) []string { + c, rec := f.context("/v1beta/models", "", allowlist) + f.handler.GeminiV1BetaListModels(c) + require.Equal(f.t, http.StatusOK, rec.Code, rec.Body.String()) + var got gemini.ModelsListResponse + require.NoError(f.t, json.Unmarshal(rec.Body.Bytes(), &got)) + names := []string{} + for _, model := range got.Models { + names = append(names, model.Name) + } + return names +} + +func (f *geminiDeclaredModelsFixture) get(model string) *httptest.ResponseRecorder { + c, rec := f.context("/v1beta/models/"+model, model, service.GroupModelAllowlist{}) + f.handler.GeminiV1BetaGetModel(c) + return rec +} + +// 分组内 Gemini 账号都声明了 model_mapping 时,列表与详情都按声明的模型应答,不透传选中账号的上游列表。 +func TestGeminiNativeModelsUsesDeclaredMappings(t *testing.T) { + f := newGeminiDeclaredModelsFixture(t, []service.Account{ + {ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 10, Credentials: map[string]any{"api_key": "a", "model_mapping": map[string]any{"gemini-4-argon": "gemini-4-argon"}}}, + {ID: 2, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 11, Credentials: map[string]any{"api_key": "b", "model_mapping": map[string]any{"gemini-2.5-flash": "gemini-2.5-flash", "gemini-3.1-pro-preview": "gemini-3.1-pro-preview", "gemini-3.8-*": "gemini-3.8-flash"}}}, + {ID: 3, Platform: service.PlatformAntigravity, Extra: map[string]any{"mixed_scheduling": true}, Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}}}, + }) + + names := f.list(service.GroupModelAllowlist{}) + require.Subset(t, names, []string{"models/gemini-2.5-flash", "models/gemini-3.1-pro-preview", "models/gemini-3.8-*", "models/gemini-4-argon", "models/gemini-synced-custom"}) + require.NotContains(t, names, "models/gemini-4-argon-high") + + // 白名单与 /v1/models 同口径:通配符映射键展开为白名单中的具体模型。 + require.Equal(t, []string{"models/gemini-2.5-flash", "models/gemini-3.8-flash", "models/gemini-synced-custom"}, + f.list(service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-2.5-flash", "gemini-3.8-flash", "gemini-synced-custom"}})) + + for model, status := range map[string]int{ + "gemini-4-argon": http.StatusOK, + "gemini-3.8-flash": http.StatusOK, + "gemini-3.1-pro-preview-customtools": http.StatusOK, + "gemini-synced-custom": http.StatusOK, + "gemini-4-argon-high": http.StatusNotFound, + } { + rec := f.get(model) + require.Equal(t, status, rec.Code, model+": "+rec.Body.String()) + if status == http.StatusOK { + require.JSONEq(t, `{"name":"models/`+model+`","supportedGenerationMethods":["generateContent","streamGenerateContent"]}`, rec.Body.String()) + } else { + require.Contains(t, rec.Body.String(), "models/"+model+" is not found") + } + } + require.Zero(t, f.upstream.calls) +} + +// 分组内有 Gemini 账号未配置映射(接受任意模型)时,模型接口仍由选中账号的上游应答。 +func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) { + f := newGeminiDeclaredModelsFixture(t, []service.Account{ + {ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 10, Credentials: map[string]any{"api_key": "a", "model_mapping": map[string]any{"gemini-4-argon": "gemini-4-argon"}}}, + {ID: 2, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 11, Credentials: map[string]any{"api_key": "b"}}, + }) + + require.Equal(t, []string{"gemini-4-argon-high"}, f.list(service.GroupModelAllowlist{})) + rec := f.get("gemini-2.5-pro") + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, 2, f.upstream.calls) +} diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index c15d212a3b..57c91802fd 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -9,6 +9,7 @@ import ( "errors" "net/http" "regexp" + "slices" "strconv" "strings" @@ -76,6 +77,25 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) { return } + // 分组内 Gemini 账号都声明了 model_mapping 时,列表与 /v1/models 同源(含白名单口径),不透传单个账号的上游列表。 + if declared, err := h.geminiCompatService.DeclaredModelIDs(c.Request.Context(), apiKey.GroupID); err == nil && len(declared) > 0 { + ids := append([]string{}, declared...) + for _, id := range agModelIDs { + if !slices.Contains(declared, id) { + ids = append(ids, id) + } + } + if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() { + ids = apiKey.Group.ModelAllowlist.FilterForListing(ids) + } + declaredModels := make([]gemini.Model, 0, len(ids)) + for _, id := range ids { + declaredModels = append(declaredModels, gemini.FallbackModel(id)) + } + c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: declaredModels}) + return + } + account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID) if err != nil { if len(agModels) > 0 { @@ -259,6 +279,18 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) { return } + // 分组内 Gemini 账号都声明了 model_mapping 时,按列表接口的同一来源判断模型是否存在。 + if declared, err := h.geminiCompatService.DeclaredModelIDs(c.Request.Context(), apiKey.GroupID); err == nil && len(declared) > 0 { + if agModelIDs, agErr := h.geminiCompatService.AntigravityGeminiModelIDs(c.Request.Context(), apiKey.GroupID, true); agErr == nil { + if service.DeclaredModelsCover(declared, modelName) || service.DeclaredModelsCover(agModelIDs, modelName) { + c.JSON(http.StatusOK, gemini.FallbackModel(modelName)) + return + } + googleError(c, http.StatusNotFound, "models/"+modelName+" is not found") + return + } + } + account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID) if err != nil { // 没有 gemini 账户,检查是否有 antigravity 账户可用 @@ -342,6 +374,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit)) return @@ -798,6 +833,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) // 长上下文阶梯由目录数据驱动,统一在计费路径内生效,入口无需声明。 + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{ Result: result, @@ -815,7 +851,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { ForceCacheBilling: forceCacheBilling, APIKeyService: h.apiKeyService, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.gemini_v1beta.models"), diff --git a/backend/internal/handler/grok_audio.go b/backend/internal/handler/grok_audio.go index 7455485d7b..91814fdf4c 100644 --- a/backend/internal/handler/grok_audio.go +++ b/backend/internal/handler/grok_audio.go @@ -4,12 +4,12 @@ import ( "context" "encoding/json" "errors" - "io" "net/http" "strconv" "strings" "time" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/ip" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" @@ -203,6 +203,9 @@ func (h *OpenAIGatewayHandler) GrokVoice(c *gin.Context, endpoint string) { body, err := readGrokVoiceGatewayBody(c) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", err.Error()) return } @@ -344,6 +347,7 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( model = endpoint } + channelUsageFields := clientRequestedUsageFields(c, service.ChannelMappingResult{}, model, result.UpstreamModel) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -359,7 +363,7 @@ func (h *OpenAIGatewayHandler) recordGrokVoiceUsage( APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, service.ChannelMappingResult{}, model, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.openai_gateway.grok_voice"), @@ -383,7 +387,7 @@ func readGrokVoiceGatewayBody(c *gin.Context) ([]byte, error) { } return nil, errors.New("request body is required") } - return io.ReadAll(c.Request.Body) + return pkghttputil.ReadRequestBodyWithPrealloc(c.Request) } // extractGrokTTSInputText pulls the primary spoken text from a TTS JSON body. diff --git a/backend/internal/handler/grok_audio_body_test.go b/backend/internal/handler/grok_audio_body_test.go new file mode 100644 index 0000000000..84621dce9f --- /dev/null +++ b/backend/internal/handler/grok_audio_body_test.go @@ -0,0 +1,53 @@ +package handler + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGrokVoiceRequestBodyMemoryOverload(t *testing.T) { + cfg := &config.Config{RunMode: config.RunModeSimple} + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := &OpenAIGatewayHandler{ + gatewayService: &service.OpenAIGatewayService{}, + billingCacheService: billing, + apiKeyService: &service.APIKeyService{}, + concurrencyHelper: &ConcurrencyHelper{concurrencyService: service.NewConcurrencyService(nil)}, + cfg: cfg, + } + for _, endpoint := range []string{"tts", "stt", "custom-voices"} { + t.Run(endpoint, func(t *testing.T) { + router := gin.New() + router.Use(middleware.RequestBodyLimit(1024, pkghttputil.NewBodyMemoryBudget(1))) + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ + Group: &service.Group{Platform: service.PlatformGrok}, + User: &service.User{ID: 1}, + }) + c.Next() + }) + // A normal Grok group without an allowlist reaches the handler before + // any middleware reads its body. + router.Use(middleware.GroupModelAllowlist()) + router.POST("/v1/"+endpoint, func(c *gin.Context) { h.GrokVoice(c, endpoint) }) + req := httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(`{"input":"hello"}`)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusServiceUnavailable, rec.Code, rec.Body.String()) + require.Equal(t, "1", rec.Header().Get("Retry-After")) + require.Contains(t, rec.Body.String(), "Request body buffering capacity is exhausted") + }) + } +} diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 03dabf7520..db4b4c3f3b 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -90,6 +90,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. if endpoint.RequiresRequestBody() { body, err = pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -757,6 +760,7 @@ func recordGrokMediaUsage( payloadForHash = []byte(videoTaskID) } } + requestPayloadHash := service.HashUsageRequestPayload(payloadForHash) h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -768,7 +772,7 @@ func recordGrokMediaUsage( UpstreamEndpoint: upstreamEndpoint, UserAgent: userAgent, IPAddress: clientIP, - RequestPayloadHash: service.HashUsageRequestPayload(payloadForHash), + RequestPayloadHash: requestPayloadHash, APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, diff --git a/backend/internal/handler/handler.go b/backend/internal/handler/handler.go index f7126904db..6e11effe02 100644 --- a/backend/internal/handler/handler.go +++ b/backend/internal/handler/handler.go @@ -49,6 +49,7 @@ type AdminHandlers struct { type Handlers struct { Auth *AuthHandler User *UserHandler + MCPOAuth *MCPOAuthHandler APIKey *APIKeyHandler Usage *UsageHandler Redeem *RedeemHandler diff --git a/backend/internal/handler/image_task_handler.go b/backend/internal/handler/image_task_handler.go index f9b28668ae..deff4b7a2b 100644 --- a/backend/internal/handler/image_task_handler.go +++ b/backend/internal/handler/image_task_handler.go @@ -77,6 +77,9 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { imageTaskJSONError(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return diff --git a/backend/internal/handler/mcp_oauth_handler.go b/backend/internal/handler/mcp_oauth_handler.go new file mode 100644 index 0000000000..ffa27b1fc9 --- /dev/null +++ b/backend/internal/handler/mcp_oauth_handler.go @@ -0,0 +1,373 @@ +package handler + +import ( + "context" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "net/url" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/response" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/modelcontextprotocol/go-sdk/oauthex" +) + +type MCPOAuthHandler struct { + oauth *service.MCPOAuthService + totp *service.TotpService + users *service.UserService + settings *service.SettingService + cfg *config.Config +} + +func NewMCPOAuthHandler(oauth *service.MCPOAuthService, totp *service.TotpService, users *service.UserService, settings *service.SettingService, cfg *config.Config) *MCPOAuthHandler { + return &MCPOAuthHandler{oauth: oauth, totp: totp, users: users, settings: settings, cfg: cfg} +} + +func (h *MCPOAuthHandler) Service() *service.MCPOAuthService { return h.oauth } + +// ResourceURL is anchored to operator configuration, never the request Host or +// 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") + } + 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") + } + return configured.PublicURL, nil +} + +func (h *MCPOAuthHandler) frontendURL(ctx context.Context) string { + if h.settings != nil { + return strings.TrimRight(strings.TrimSpace(h.settings.GetFrontendURL(ctx)), "/") + } + if h.cfg != nil { + return strings.TrimRight(strings.TrimSpace(h.cfg.Server.FrontendURL), "/") + } + return "" +} + +func (h *MCPOAuthHandler) ResourceMetadata(c *gin.Context) { + resource, ok := h.resource(c, true) + if !ok { + return + } + u, _ := url.Parse(resource) + issuer := u.Scheme + "://" + u.Host + c.JSON(http.StatusOK, oauthex.ProtectedResourceMetadata{ + Resource: resource, AuthorizationServers: []string{issuer}, + ScopesSupported: []string{service.MCPOAuthScope}, BearerMethodsSupported: []string{"header"}, + ResourceName: "Sub2API management", + }) +} + +func (h *MCPOAuthHandler) AuthorizationMetadata(c *gin.Context) { + resource, ok := h.resource(c, true) + if !ok { + return + } + u, _ := url.Parse(resource) + issuer := u.Scheme + "://" + u.Host + frontend := h.frontendURL(c.Request.Context()) + if frontend == "" { + frontend = issuer + } + // The SPA restores the browser login and obtains explicit user consent. + authorization, err := mcpAuthorizationURL(frontend) + if err != nil { + mcpOAuthErrorResponse(c, http.StatusServiceUnavailable, "server_error", "MCP authorization page is not configured correctly") + return + } + c.JSON(http.StatusOK, gin.H{ + "issuer": issuer, "authorization_endpoint": authorization, + "token_endpoint": issuer + "/api/v1/mcp/oauth/token", + "registration_endpoint": issuer + "/api/v1/mcp/oauth/register", + "revocation_endpoint": issuer + "/api/v1/mcp/oauth/revoke", + "response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"}, + "code_challenge_methods_supported": []string{"S256"}, "token_endpoint_auth_methods_supported": []string{"none"}, + "revocation_endpoint_auth_methods_supported": []string{"none"}, "scopes_supported": []string{service.MCPOAuthScope}, + }) +} + +func mcpAuthorizationURL(frontend string) (string, error) { + 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("invalid frontend URL") + } + origin := config.MCPConfig{PublicURL: u.Scheme + "://" + u.Host + "/api/v1/mcp"} + if err := origin.Validate(); err != nil { + return "", err + } + u.Path = strings.TrimRight(u.Path, "/") + "/oauth/mcp/authorize" + u.RawPath = "" + return u.String(), nil +} + +func (h *MCPOAuthHandler) Register(c *gin.Context) { + mcpOAuthNoStore(c) + if _, ok := h.resource(c, true); !ok { + return + } + var input service.MCPOAuthRegisterInput + if !mcpOAuthReadJSON(c, &input, false) { + return + } + client, err := h.oauth.Register(c.Request.Context(), input) + if mcpOAuthHandleError(c, err, true) { + return + } + c.JSON(http.StatusCreated, client) +} + +func (h *MCPOAuthHandler) Token(c *gin.Context) { + mcpOAuthNoStore(c) + resource, ok := h.resource(c, true) + if !ok { + return + } + form, ok := mcpOAuthReadForm(c) + if !ok { + return + } + if c.GetHeader("Authorization") != "" || form.Get("client_secret") != "" { + mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_client", "Only public clients using token_endpoint_auth_method=none are supported") + return + } + input := service.MCPOAuthTokenInput{ + GrantType: form.Get("grant_type"), ClientID: form.Get("client_id"), Code: form.Get("code"), + RedirectURI: form.Get("redirect_uri"), CodeVerifier: form.Get("code_verifier"), + RefreshToken: form.Get("refresh_token"), Resource: form.Get("resource"), Scope: form.Get("scope"), + } + result, err := h.oauth.Token(c.Request.Context(), input, resource) + if mcpOAuthHandleError(c, err, true) { + return + } + c.JSON(http.StatusOK, result) +} + +func (h *MCPOAuthHandler) RevokeToken(c *gin.Context) { + mcpOAuthNoStore(c) + form, ok := mcpOAuthReadForm(c) + if !ok { + return + } + if c.GetHeader("Authorization") != "" || form.Get("client_secret") != "" { + mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_client", "Only public clients are supported") + return + } + if mcpOAuthHandleError(c, h.oauth.RevokeToken(c.Request.Context(), form.Get("client_id"), form.Get("token")), true) { + return + } + c.Status(http.StatusOK) +} + +func (h *MCPOAuthHandler) Preview(c *gin.Context) { + mcpOAuthNoStore(c) + subject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + resource, ok := h.resource(c, false) + if !ok { + return + } + query := c.Request.URL.Query() + for _, values := range query { + if len(values) != 1 { + response.BadRequest(c, "Repeated OAuth parameters are not supported") + return + } + } + input := service.MCPOAuthAuthorizeInput{ + ResponseType: query.Get("response_type"), ClientID: query.Get("client_id"), RedirectURI: query.Get("redirect_uri"), + Scope: query.Get("scope"), State: query.Get("state"), CodeChallenge: query.Get("code_challenge"), + CodeChallengeMethod: query.Get("code_challenge_method"), Resource: query.Get("resource"), + } + consent, err := h.oauth.Preview(c.Request.Context(), subject.UserID, input, resource) + if mcpOAuthHandleError(c, err, false) { + return + } + response.Success(c, consent) +} + +func (h *MCPOAuthHandler) Decide(c *gin.Context) { + mcpOAuthNoStore(c) + subject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + resource, ok := h.resource(c, false) + if !ok { + return + } + var input service.MCPOAuthConsentInput + if !mcpOAuthReadJSON(c, &input, true) { + return + } + if input.Approved && input.Scope == service.MCPScopeAdmin { + role, _ := middleware.GetUserRoleFromContext(c) + if role != service.RoleAdmin { + response.Forbidden(c, "Only administrators can authorize admin MCP access") + return + } + // 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 + } + } + redirect, err := h.oauth.Decide(c.Request.Context(), subject.UserID, input, resource) + if mcpOAuthHandleError(c, err, false) { + return + } + middleware.SetAuditAction(c, "user.mcp.authorize") + response.Success(c, gin.H{"redirect_url": redirect}) +} + +func (h *MCPOAuthHandler) ListGrants(c *gin.Context) { + mcpOAuthNoStore(c) + subject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + grants, err := h.oauth.ListGrants(c.Request.Context(), subject.UserID) + if response.ErrorFrom(c, err) { + return + } + response.Success(c, grants) +} + +func (h *MCPOAuthHandler) ConnectionConfig(c *gin.Context) { + mcpOAuthNoStore(c) + if _, ok := middleware.GetAuthSubjectFromContext(c); !ok { + response.Unauthorized(c, "User not authenticated") + return + } + resource, ok := h.resource(c, false) + if !ok { + return + } + response.Success(c, gin.H{"resource": resource}) +} + +func (h *MCPOAuthHandler) RevokeGrant(c *gin.Context) { + mcpOAuthNoStore(c) + subject, ok := middleware.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + if response.ErrorFrom(c, h.oauth.RevokeGrant(c.Request.Context(), subject.UserID, c.Param("id"))) { + return + } + middleware.SetAuditAction(c, "user.mcp.revoke") + response.Success(c, gin.H{"revoked": true}) +} + +func (h *MCPOAuthHandler) resource(c *gin.Context, protocol bool) (string, bool) { + resource, err := h.ResourceURL(c.Request.Context()) + if err != nil { + if protocol { + mcpOAuthErrorResponse(c, http.StatusServiceUnavailable, "server_error", err.Error()) + } else { + response.Error(c, http.StatusServiceUnavailable, err.Error()) + } + return "", false + } + return resource, true +} + +func mcpOAuthNoStore(c *gin.Context) { + c.Header("Cache-Control", "no-store") + c.Header("Pragma", "no-cache") +} + +func mcpOAuthErrorResponse(c *gin.Context, status int, code, description string) { + mcpOAuthNoStore(c) + c.JSON(status, service.MCPOAuthError{Code: code, Description: description}) +} + +func mcpOAuthHandleError(c *gin.Context, err error, protocol bool) bool { + if err == nil { + return false + } + var oauthErr *service.MCPOAuthError + if errors.As(err, &oauthErr) { + if protocol { + mcpOAuthErrorResponse(c, http.StatusBadRequest, oauthErr.Code, oauthErr.Description) + } else { + response.BadRequest(c, oauthErr.Description) + } + } else if protocol { + mcpOAuthErrorResponse(c, http.StatusInternalServerError, "server_error", "OAuth request could not be completed") + } else { + response.ErrorFrom(c, err) + } + return true +} + +func mcpOAuthReadJSON(c *gin.Context, out any, browser bool) bool { + mediaType, _, _ := mime.ParseMediaType(c.GetHeader("Content-Type")) + if mediaType == "application/json" { + // Unauthenticated registrations are embedded in client IDs, 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() + } + if err := decoder.Decode(out); err == nil { + var extra any + if errors.Is(decoder.Decode(&extra), io.EOF) { + return true + } + } + } + if browser { + response.BadRequest(c, "Invalid OAuth authorization request") + } else { + mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "A bounded JSON request body is required") + } + return false +} + +func mcpOAuthReadForm(c *gin.Context) (url.Values, bool) { + mediaType, _, _ := mime.ParseMediaType(c.GetHeader("Content-Type")) + if mediaType != "application/x-www-form-urlencoded" { + mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "Use application/x-www-form-urlencoded") + return nil, false + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10) + if err := c.Request.ParseForm(); err != nil { + mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "Cannot read OAuth form") + return nil, false + } + for _, values := range c.Request.PostForm { + if len(values) != 1 { + mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "Repeated OAuth parameters are not supported") + return nil, false + } + } + return c.Request.PostForm, true +} diff --git a/backend/internal/handler/mcp_oauth_handler_test.go b/backend/internal/handler/mcp_oauth_handler_test.go new file mode 100644 index 0000000000..72399d6909 --- /dev/null +++ b/backend/internal/handler/mcp_oauth_handler_test.go @@ -0,0 +1,494 @@ +//go:build unit + +package handler + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const handlerMCPResource = "https://api.example.com/api/v1/mcp" + +type handlerMCPRepo struct { + service.MCPOAuthRepository + clientID string + reads, writes int + grant *service.MCPOAuthGrant +} + +// Resolving a client ID needs its signing key, so key loads count as reads. +func (r *handlerMCPRepo) ClientIDKey(context.Context) ([]byte, error) { + r.reads++ + return []byte("handler-test-mcp-client-id-key-0"), nil +} +func (r *handlerMCPRepo) CreateAuthorization(_ context.Context, grant *service.MCPOAuthGrant, _ *service.MCPOAuthCode, _ int) error { + r.writes++ + r.grant = grant + return nil +} + +type handlerMCPUsers struct { + service.UserRepository + user *service.User +} + +func (r *handlerMCPUsers) GetByID(context.Context, int64) (*service.User, error) { return r.user, nil } +func (r *handlerMCPUsers) GetUserAvatar(context.Context, int64) (*service.UserAvatar, error) { + return nil, nil +} + +type handlerMCPSettings struct { + service.SettingRepository + values map[string]string +} + +func (r *handlerMCPSettings) GetValue(_ context.Context, key string) (string, error) { + return r.values[key], nil +} + +type handlerMCPCache struct { + service.TotpCache + granted bool + err error + calls int + userID int64 + session string +} + +func (r *handlerMCPCache) HasStepUpGrant(_ context.Context, id int64, session string) (bool, error) { + r.calls++ + r.userID, r.session = id, session + return r.granted, r.err +} +func newHandlerMCPFixture(t *testing.T) (*MCPOAuthHandler, *handlerMCPRepo, *handlerMCPUsers, *handlerMCPCache) { + t.Helper() + cfg := &config.Config{MCP: config.MCPConfig{PublicURL: handlerMCPResource}} + cfg.Server.FrontendURL = "https://platform.example.com" + repo := &handlerMCPRepo{} + users := &handlerMCPUsers{user: &service.User{ID: 7, Role: service.RoleAdmin, Status: service.StatusActive, TotpEnabled: true}} + settings := service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyStepUpEnabled: "true"}}, cfg) + cache := &handlerMCPCache{} + totp := service.NewTotpService(users, nil, cache, settings, nil, nil) + oauth := service.NewMCPOAuthService(repo, users) + client, err := oauth.Register(context.Background(), service.MCPOAuthRegisterInput{ClientName: "Example assistant", RedirectURIs: []string{"https://client.example.com/callback?workspace=one"}}) + require.NoError(t, err) + repo.clientID, repo.reads = client.ClientID, 0 + return NewMCPOAuthHandler(oauth, totp, service.NewUserService(users, nil, nil, nil), settings, cfg), repo, users, cache +} +func handlerMCPContext(t *testing.T, method, target, body, contentType string) (*gin.Context, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(method, target, strings.NewReader(body)) + if contentType != "" { + c.Request.Header.Set("Content-Type", contentType) + } + return c, rec +} +func handlerMCPSubject(c *gin.Context, role string) { + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 7}) + c.Set(string(middleware.ContextKeyUserRole), role) + c.Set(middleware.ContextKeySessionID, "browser-session-7") +} +func handlerMCPAuthorization(clientID string) service.MCPOAuthAuthorizeInput { + digest := sha256.Sum256([]byte(strings.Repeat("v", 43))) + return service.MCPOAuthAuthorizeInput{ResponseType: "code", ClientID: clientID, RedirectURI: "https://client.example.com/callback?workspace=one", Scope: "mcp", State: "a+b&c=d", CodeChallenge: base64.RawURLEncoding.EncodeToString(digest[:]), CodeChallengeMethod: "S256", Resource: handlerMCPResource} +} +func handlerMCPBody(t *testing.T, input any) string { + t.Helper() + raw, err := json.Marshal(input) + require.NoError(t, err) + return string(raw) +} +func handlerMCPJSON(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + var body map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + return body +} + +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}, + {"explicit resource wins", handlerMCPResource, "", "https://stored.example.com", handlerMCPResource}, + {"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", "", "", ""}, + } { + t.Run(tt.name, func(t *testing.T) { + cfg := &config.Config{MCP: config.MCPConfig{PublicURL: tt.public}} + cfg.Server.FrontendURL = tt.frontend + var settings *service.SettingService + if tt.stored != "" { + settings = service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyFrontendURL: tt.stored}}, cfg) + } + h := NewMCPOAuthHandler(nil, nil, nil, settings, cfg) + got, err := h.ResourceURL(context.Background()) + if tt.want == "" { + require.Error(t, err) + require.Empty(t, got) + } else { + require.NoError(t, err) + require.Equal(t, tt.want, got) + } + }) + } +} + +func TestMCPOAuthHandlerMetadataRawAndHostIndependent(t *testing.T) { + h, _, _, _ := newHandlerMCPFixture(t) + for _, auth := range []bool{false, true} { + c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/.well-known/oauth-authorization-server", "", "") + c.Request.Header.Set("X-Forwarded-Host", "forwarded-attacker.example") + c.Request.Header.Set("X-Forwarded-Proto", "http") + if auth { + h.AuthorizationMetadata(c) + } else { + h.ResourceMetadata(c) + } + require.Equal(t, http.StatusOK, rec.Code) + body := handlerMCPJSON(t, rec) + require.NotContains(t, body, "data") + require.NotContains(t, body, "code") + require.NotContains(t, rec.Body.String(), "attacker") + require.Equal(t, []any{"mcp"}, body["scopes_supported"]) + if auth { + require.Equal(t, "https://api.example.com", body["issuer"]) + require.Equal(t, "https://platform.example.com/oauth/mcp/authorize", body["authorization_endpoint"]) + require.Equal(t, "https://api.example.com/api/v1/mcp/oauth/token", body["token_endpoint"]) + require.Equal(t, "https://api.example.com/api/v1/mcp/oauth/register", body["registration_endpoint"]) + require.Equal(t, "https://api.example.com/api/v1/mcp/oauth/revoke", body["revocation_endpoint"]) + require.Equal(t, []any{"S256"}, body["code_challenge_methods_supported"]) + require.Equal(t, []any{"none"}, body["token_endpoint_auth_methods_supported"]) + } else { + require.Equal(t, handlerMCPResource, body["resource"]) + require.Equal(t, []any{"https://api.example.com"}, body["authorization_servers"]) + require.Equal(t, []any{"header"}, body["bearer_methods_supported"]) + } + } + h = NewMCPOAuthHandler(nil, nil, nil, nil, &config.Config{}) + for _, serve := range []gin.HandlerFunc{h.ResourceMetadata, h.AuthorizationMetadata} { + c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/metadata", "", "") + serve(c) + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Equal(t, "server_error", handlerMCPJSON(t, rec)["error"]) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + } +} + +func TestMCPOAuthHandlerConnectionConfigUsesCanonicalResource(t *testing.T) { + h, repo, _, _ := newHandlerMCPFixture(t) + c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/user/mcp/config", "", "") + c.Request.Header.Set("X-Forwarded-Host", "forwarded-attacker.example") + handlerMCPSubject(c, service.RoleUser) + h.ConnectionConfig(c) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + require.Equal(t, map[string]any{"resource": handlerMCPResource}, handlerMCPJSON(t, rec)["data"]) + require.NotContains(t, rec.Body.String(), "attacker") + require.Zero(t, repo.reads) + require.Zero(t, repo.writes) + + h = NewMCPOAuthHandler(nil, nil, nil, nil, &config.Config{}) + c, rec = handlerMCPContext(t, http.MethodGet, "/user/mcp/config", "", "") + handlerMCPSubject(c, service.RoleUser) + h.ConnectionConfig(c) + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + require.Contains(t, handlerMCPJSON(t, rec), "code") +} + +func TestMCPOAuthHandlerAuthorizationMetadataValidatesFrontendURL(t *testing.T) { + for _, tt := range []struct{ frontend, want string }{ + {"https://platform.example.com/console/", "https://platform.example.com/console/oauth/mcp/authorize"}, + {"http://127.0.0.1:3000/", "http://127.0.0.1:3000/oauth/mcp/authorize"}, + {"", "https://api.example.com/oauth/mcp/authorize"}, + {"http://platform.example.com", ""}, {"https://user:password@platform.example.com", ""}, + {"https://platform.example.com?next=attacker", ""}, {"https://platform.example.com#fragment", ""}, + {"https://platform.example.com?", ""}, {"https://platform.example.com#", ""}, + } { + t.Run(tt.frontend, func(t *testing.T) { + cfg := &config.Config{MCP: config.MCPConfig{PublicURL: handlerMCPResource}} + cfg.Server.FrontendURL = tt.frontend + h := NewMCPOAuthHandler(nil, nil, nil, nil, cfg) + c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/metadata", "", "") + h.AuthorizationMetadata(c) + if tt.want == "" { + require.Equal(t, http.StatusServiceUnavailable, rec.Code) + require.Equal(t, "server_error", handlerMCPJSON(t, rec)["error"]) + } else { + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, tt.want, handlerMCPJSON(t, rec)["authorization_endpoint"]) + } + }) + } +} + +func TestMCPOAuthHandlerJSONValidation(t *testing.T) { + for _, tt := range []struct { + name, contentType, body string + browser, valid bool + }{ + {"valid browser", "application/json; charset=utf-8", `{"approved":false,"authorization":{"client_id":"client-1"}}`, true, true}, + {"unknown browser field", "application/json", `{"approved":false,"unexpected":true}`, true, false}, + {"unknown nested field", "application/json", `{"authorization":{"unexpected":true}}`, true, false}, + {"wrong type", "application/json", `{"approved":"true"}`, true, false}, + {"two documents", "application/json", `{} {}`, true, false}, + {"trailing bytes", "application/json", `{} extra`, true, false}, + {"truncated", "application/json", `{"approved":`, true, false}, + {"wrong content type", "text/plain", `{}`, true, false}, + {"missing content type", "", `{}`, true, false}, + {"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) { + c, rec := handlerMCPContext(t, http.MethodPost, "/oauth", tt.body, tt.contentType) + var input any = &service.MCPOAuthRegisterInput{} + if tt.browser { + input = &service.MCPOAuthConsentInput{} + } + require.Equal(t, tt.valid, mcpOAuthReadJSON(c, input, tt.browser)) + if !tt.valid { + require.Equal(t, http.StatusBadRequest, rec.Code) + body := handlerMCPJSON(t, rec) + if tt.browser { + require.Contains(t, body, "code") + } else { + require.Equal(t, "invalid_request", body["error"]) + require.NotContains(t, body, "data") + } + } + }) + } +} + +func TestMCPOAuthHandlerFormValidation(t *testing.T) { + for _, tt := range []struct{ name, contentType, body string }{ + {"JSON", "application/json", `{}`}, {"missing content type", "", "client_id=client-1"}, + {"repeated client", "application/x-www-form-urlencoded", "client_id=one&client_id=two"}, + {"repeated code", "application/x-www-form-urlencoded", "code=one&code=two"}, + {"invalid escape", "application/x-www-form-urlencoded", "client_id=%zz"}, + {"oversized", "application/x-www-form-urlencoded", "code=" + strings.Repeat("x", 17<<10)}, + } { + t.Run(tt.name, func(t *testing.T) { + c, rec := handlerMCPContext(t, http.MethodPost, "/oauth/token", tt.body, tt.contentType) + _, ok := mcpOAuthReadForm(c) + require.False(t, ok) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, "invalid_request", handlerMCPJSON(t, rec)["error"]) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + }) + } + c, _ := handlerMCPContext(t, http.MethodPost, "/oauth/token?client_id=attacker&code=query-code", "client_id=client-1&code=body-code", "application/x-www-form-urlencoded; charset=utf-8") + values, ok := mcpOAuthReadForm(c) + require.True(t, ok) + require.Equal(t, url.Values{"client_id": {"client-1"}, "code": {"body-code"}}, values) +} + +func TestMCPOAuthHandlerTokenEndpointsRejectConfidentialAuthentication(t *testing.T) { + for _, endpoint := range []string{"token", "revoke"} { + for _, auth := range []string{"authorization", "client_secret"} { + t.Run(endpoint+"/"+auth, func(t *testing.T) { + h, repo, _, _ := newHandlerMCPFixture(t) + values := url.Values{"client_id": {"client-1"}} + if auth == "client_secret" { + values.Set("client_secret", "not-supported") + } + c, rec := handlerMCPContext(t, http.MethodPost, "/oauth/"+endpoint, values.Encode(), "application/x-www-form-urlencoded") + if auth == "authorization" { + c.Request.Header.Set("Authorization", "Basic dXNlcjpwYXNz") + } + if endpoint == "token" { + h.Token(c) + } else { + h.RevokeToken(c) + } + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, "invalid_client", handlerMCPJSON(t, rec)["error"]) + require.Zero(t, repo.reads) + require.Zero(t, repo.writes) + }) + } + } +} + +func TestMCPOAuthHandlerPreviewFrontendContract(t *testing.T) { + h, repo, _, _ := newHandlerMCPFixture(t) + input := handlerMCPAuthorization(repo.clientID) + query := url.Values{"response_type": {input.ResponseType}, "client_id": {input.ClientID}, "redirect_uri": {input.RedirectURI}, "scope": {input.Scope}, "state": {input.State}, "code_challenge": {input.CodeChallenge}, "code_challenge_method": {input.CodeChallengeMethod}, "resource": {input.Resource}, "timezone": {"Asia/Shanghai"}} + c, rec := handlerMCPContext(t, http.MethodGet, "/user/mcp/authorize?"+query.Encode(), "", "") + handlerMCPSubject(c, service.RoleUser) + h.Preview(c) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + body := handlerMCPJSON(t, rec) + require.Equal(t, float64(0), body["code"]) + require.Equal(t, map[string]any{"client_id": repo.clientID, "client_name": "Example assistant", "redirect_uri": input.RedirectURI, "resource": handlerMCPResource, "scope": "mcp"}, body["data"]) + require.Zero(t, repo.writes) + query.Add("redirect_uri", "https://attacker.example/callback") + c, rec = handlerMCPContext(t, http.MethodGet, "/user/mcp/authorize?"+query.Encode(), "", "") + handlerMCPSubject(c, service.RoleUser) + h.Preview(c) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, 1, repo.reads, "reject duplicate parameters before service access") +} + +func TestMCPOAuthHandlerAdminDecisionGatesBeforePersistence(t *testing.T) { + for _, tt := range []struct { + name, role, authMethod, marker string + totp, granted bool + cacheErr error + status int + }{ + {name: "non-admin", role: service.RoleUser, totp: true, granted: true, status: 403, marker: "Only administrators"}, + {name: "missing role", totp: true, granted: true, status: 403, marker: "Only administrators"}, + {name: "TOTP disabled", role: service.RoleAdmin, status: 403, marker: "STEP_UP_TOTP_NOT_ENABLED"}, + {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: 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) + users.user.TotpEnabled = tt.totp + cache.granted, cache.err = tt.granted, tt.cacheErr + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin} + c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") + handlerMCPSubject(c, tt.role) + c.Set("auth_method", tt.authMethod) + h.Decide(c) + require.Equal(t, tt.status, rec.Code) + require.Contains(t, rec.Body.String(), tt.marker) + require.Zero(t, repo.reads) + require.Zero(t, repo.writes) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + }) + } +} + +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(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: tt.readOnly} + c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") + handlerMCPSubject(c, service.RoleAdmin) + h.Decide(c) + 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 TestMCPOAuthHandlerRegistrationPersistsNothing(t *testing.T) { + h, repo, _, _ := newHandlerMCPFixture(t) + c, rec := handlerMCPContext(t, http.MethodPost, "/api/v1/mcp/oauth/register", `{"client_name":"Example assistant","redirect_uris":["https://client.example.com/cb"]}`, "application/json") + h.Register(c) + require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String()) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + body := handlerMCPJSON(t, rec) + require.True(t, strings.HasPrefix(body["client_id"].(string), "mcp_client_")) + require.NotEqual(t, repo.clientID, body["client_id"]) + require.Equal(t, []any{"https://client.example.com/cb"}, body["redirect_uris"]) + require.Zero(t, repo.writes) +} + +func TestMCPOAuthHandlerAdminApprovalUsesBrowserSession(t *testing.T) { + h, repo, _, cache := newHandlerMCPFixture(t) + cache.granted = true + readOnly := false + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: &readOnly} + c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") + handlerMCPSubject(c, service.RoleAdmin) + h.Decide(c) + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, int64(7), cache.userID) + require.Equal(t, "browser-session-7", cache.session) + require.Equal(t, 1, repo.writes) + require.Equal(t, service.MCPScopeAdmin, repo.grant.Scope) + require.False(t, repo.grant.ReadOnly) + result := handlerMCPJSON(t, rec)["data"].(map[string]any) + destination, err := url.Parse(result["redirect_url"].(string)) + require.NoError(t, err) + require.Equal(t, "client.example.com", destination.Host) + require.Equal(t, "one", destination.Query().Get("workspace")) + require.Equal(t, input.Authorization.State, destination.Query().Get("state")) + require.NotEmpty(t, destination.Query().Get("code")) + require.Empty(t, rec.Header().Get("Location"), "return a validated URL without an automatic HTTP redirect") +} + +func TestMCPOAuthHandlerDenialSkipsStepUpAndPersistence(t *testing.T) { + h, repo, _, cache := newHandlerMCPFixture(t) + cache.err = errors.New("must not be called") + input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: false, Scope: service.MCPScopeAdmin} + c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json") + handlerMCPSubject(c, service.RoleUser) + h.Decide(c) + require.Equal(t, http.StatusOK, rec.Code) + require.Zero(t, cache.calls) + require.Zero(t, repo.writes) + result := handlerMCPJSON(t, rec)["data"].(map[string]any) + destination, err := url.Parse(result["redirect_url"].(string)) + require.NoError(t, err) + require.Equal(t, "client.example.com", destination.Host) + require.Equal(t, "access_denied", destination.Query().Get("error")) + require.Equal(t, input.Authorization.State, destination.Query().Get("state")) + require.Empty(t, destination.Query().Get("code")) +} + +func TestMCPOAuthHandlerBrowserEndpointsRequireSession(t *testing.T) { + h, repo, _, _ := newHandlerMCPFixture(t) + for _, serve := range []gin.HandlerFunc{h.ConnectionConfig, h.Preview, h.Decide, h.ListGrants, h.RevokeGrant} { + c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp", `{}`, "application/json") + serve(c) + require.Equal(t, http.StatusUnauthorized, rec.Code) + require.Equal(t, "no-store", rec.Header().Get("Cache-Control")) + } + require.Zero(t, repo.reads) + require.Zero(t, repo.writes) +} diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 3c25b66a08..dd93c44581 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -52,6 +52,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -293,6 +296,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage( inboundEndpoint := GetInboundEndpoint(c) upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform) quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) + pricingAt := service.OpenAIPricingAtFromContext(c.Request.Context()) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ @@ -310,7 +314,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage( QuotaPlatform: quotaPlatform, SessionID: sessionID, ChannelUsageFields: channelMapping.ToUsageFields(requestedModel, result.UpstreamModel), - PricingAt: service.OpenAIPricingAtFromContext(c.Request.Context()), + PricingAt: pricingAt, }); err != nil { logger.L().With( zap.String("component", "handler.openai_gateway.alpha_search"), diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 0a371f12eb..d6bec93e98 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -51,6 +51,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -292,6 +295,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: res, @@ -306,7 +310,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, CyberBlocked: cyberBlocked, }); err != nil { diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index 6c900c482e..dbcd7c9979 100644 --- a/backend/internal/handler/openai_embeddings.go +++ b/backend/internal/handler/openai_embeddings.go @@ -48,6 +48,9 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -271,6 +274,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -285,7 +289,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, }); err != nil { logger.L().With( diff --git a/backend/internal/handler/openai_gateway_count_tokens.go b/backend/internal/handler/openai_gateway_count_tokens.go index 2df4f4f2d0..050a5057bd 100644 --- a/backend/internal/handler/openai_gateway_count_tokens.go +++ b/backend/internal/handler/openai_gateway_count_tokens.go @@ -42,6 +42,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -135,6 +138,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { func (h *OpenAIGatewayHandler) GrokCountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -205,6 +211,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 3518463f4f..4ce98398cd 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -270,9 +270,10 @@ func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecord if parent != nil { done = service.InflightReservationFromContext(parent).Acquire() } + requestContext := usageRecordContext(parent, context.Background()) return func(ctx context.Context) { defer done() - task(usageRecordContext(parent, ctx)) + task(usageRecordContext(requestContext, ctx)) }, done } @@ -422,6 +423,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -656,6 +660,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 该判断已排除 Codex 被动 image_gen namespace,避免 CC-only 账号被误过滤(#4476)。 needsResponses := nativeV2 || legacyCompact requiredCapability := openAIResponsesRequiredCapabilityForRequest(imageIntent, needsResponses, requestPlatform) + imageSizeRouted := imageIntent && requestPlatform == service.PlatformOpenAI + imageSize := "" + if imageSizeRouted { + imageSize = service.OpenAIResponsesImageRequestSize(body) + c.Request = c.Request.WithContext(service.WithOpenAIImageSizeRouting(c.Request.Context(), imageSize)) + } // 分组利润控制:请求级装配定价上下文——pricingAt 固定本请求的 // D 与计费高峰因子,选号、槽位终检与全部 failover 重入共用同一门与阈值。 @@ -702,6 +712,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "compact_not_supported", "No available accounts support /responses/compact", streamStarted) return } + if imageSizeRouted { + if tier, unsupported := h.gatewayService.OpenAIImageSizeTierUnsupported(c.Request.Context(), apiKey.GroupID, forwardModel, imageSize, requiredCapability, ""); unsupported { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", service.OpenAIImageSizeTierUnsupportedMessage(imageSize, tier), streamStarted) + return + } + } cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, requestPlatform) cls = classifySelectionFailureError(err, cls) if !cls.ModelNotFound { @@ -827,6 +844,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil + channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: res, @@ -842,7 +860,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, CyberBlocked: cyberBlocked, NativeCompactionV2: nativeV2, @@ -1188,6 +1206,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -1421,6 +1442,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey) sessionID := service.ExtractClientSessionID(c) cyberBlocked := service.GetOpsCyberPolicy(c) != nil + channelUsageFields := clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel) h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: res, @@ -1436,7 +1458,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel), + ChannelUsageFields: channelUsageFields, PricingAt: pricingAt, CyberBlocked: cyberBlocked, }); err != nil { diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index beda748cff..a8e6413e7b 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -50,6 +50,9 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, err) { + return + } if maxErr, ok := extractMaxBytesError(err); ok { h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit)) return @@ -156,7 +159,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { defer inflightDone() sessionHash := h.gatewayService.GenerateExplicitSessionHash(c, body) - requestCtx := service.WithOpenAIImagesEndpoint(service.WithOpenAIImageGenerationIntent(c.Request.Context())) + requestCtx := service.WithOpenAIImageSizeRouting(service.WithOpenAIImagesEndpoint(service.WithOpenAIImageGenerationIntent(c.Request.Context())), parsed.Size) maxAccountSwitches := h.maxAccountSwitches switchCount := 0 @@ -189,6 +192,11 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { zap.Int("excluded_account_count", len(failedAccountIDs)), ) if len(failedAccountIDs) == 0 { + if tier, unsupported := h.gatewayService.OpenAIImageSizeTierUnsupported(c.Request.Context(), apiKey.GroupID, routingModel, parsed.Size, "", parsed.RequiredCapabilityForModel(channelMapping.MappedModel)); unsupported { + service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration) + h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", service.OpenAIImageSizeTierUnsupportedMessage(parsed.Size, tier), streamStarted) + return + } cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, clientRequestModel, routingModel, service.PlatformOpenAI) if !cls.ModelNotFound { markOpsRoutingCapacityLimitedIfNoAvailable(c, err) @@ -404,6 +412,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { upstreamModel = result.UpstreamModel } sessionID := service.ExtractClientSessionID(c) + channelUsageFields := clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel) h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) { if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{ Result: result, @@ -419,7 +428,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { APIKeyService: h.apiKeyService, QuotaPlatform: quotaPlatform, SessionID: sessionID, - ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel), + ChannelUsageFields: channelUsageFields, }); err != nil { logger.L().With( zap.String("component", "handler.openai_gateway.images"), diff --git a/backend/internal/handler/openai_images_size_routing_test.go b/backend/internal/handler/openai_images_size_routing_test.go new file mode 100644 index 0000000000..45596b4313 --- /dev/null +++ b/backend/internal/handler/openai_images_size_routing_test.go @@ -0,0 +1,164 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type openAIImagesSizeRoutingAccountRepo struct { + openAIImagesFailoverAccountRepo +} + +func (r openAIImagesSizeRoutingAccountRepo) ListModelAvailabilityCandidates(_ context.Context, _ *int64, platforms []string, _ bool) ([]service.Account, error) { + var out []service.Account + for _, platform := range platforms { + out = append(out, r.accountsForPlatform(platform)...) + } + return out, nil +} + +func newOpenAIImagesSizeRoutingTestHandler(t *testing.T, accounts []service.Account, upstream service.HTTPUpstream) *OpenAIGatewayHandler { + t.Helper() + cfg := &config.Config{RunMode: config.RunModeSimple} + gatewayService := service.NewOpenAIGatewayService( + openAIImagesSizeRoutingAccountRepo{openAIImagesFailoverAccountRepo{accounts: accounts}}, + nil, nil, nil, nil, nil, nil, + cfg, + nil, nil, nil, nil, nil, + upstream, + nil, nil, nil, nil, nil, nil, nil, nil, + ) + billingService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingService.Stop) + handler := NewOpenAIGatewayHandler( + gatewayService, + service.NewConcurrencyService(nil), + billingService, + service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), + nil, nil, nil, nil, + cfg, + ) + handler.maxAccountSwitches = 10 + return handler +} + +func serveOpenAIImagesSizeRoutingRequest(handler *OpenAIGatewayHandler, groupID int64, body string) (*httptest.ResponseRecorder, *gin.Context) { + req := httptest.NewRequest(http.MethodPost, "/v1/images/generations", bytes.NewReader([]byte(body))) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = req + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 99, + GroupID: &groupID, + Group: &service.Group{ID: groupID, AllowImageGeneration: true}, + User: &service.User{ID: 100}, + }) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100, Concurrency: 0}) + handler.Images(c) + return rec, c +} + +func newOpenAIImagesSizeRoutingAccount(id int64, tiers ...any) service.Account { + return service.Account{ + ID: id, + Name: fmt.Sprintf("image-size-account-%d", id), + Platform: service.PlatformOpenAI, + Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, + Priority: int(id), + Credentials: map[string]any{"access_token": fmt.Sprintf("token-%d", id)}, + Extra: map[string]any{service.AccountExtraOpenAIImageSizeTiers: tiers}, + } +} + +func TestOpenAIGatewayHandlerImages_SizeTierMissingFromGroupReturns400(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIImagesFailoverHTTPUpstream{} + handler := newOpenAIImagesSizeRoutingTestHandler(t, []service.Account{ + newOpenAIImagesSizeRoutingAccount(1, "1K", "2K"), + }, upstream) + + rec, c := serveOpenAIImagesSizeRoutingRequest(handler, 3140, `{"model":"gpt-image-2","prompt":"draw a cat","size":"3840x2160"}`) + + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, "invalid_request_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) + require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "4K") + require.Empty(t, upstream.calls()) + reason, _ := c.Get(service.OpsClientBusinessLimitedReasonKey) + require.Equal(t, service.OpsClientBusinessLimitedReasonLocalModelConfiguration, reason) +} + +func TestOpenAIGatewayHandlerImages_SizeTierRoutesToAllowedAccounts(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIImagesFailoverHTTPUpstream{} + handler := newOpenAIImagesSizeRoutingTestHandler(t, []service.Account{ + newOpenAIImagesSizeRoutingAccount(1, "1K", "2K"), + newOpenAIImagesSizeRoutingAccount(2, "4K"), + newOpenAIImagesSizeRoutingAccount(3, "4K"), + }, upstream) + + rec, _ := serveOpenAIImagesSizeRoutingRequest(handler, 3141, `{"model":"gpt-image-1","prompt":"draw a cat","size":"2880x2880"}`) + + require.Equal(t, http.StatusBadGateway, rec.Code, "the stub upstream fails every attempt") + require.Equal(t, []int64{2, 3}, upstream.calls(), "4K requests fail over only across 4K accounts") +} + +func serveOpenAIResponsesSizeRoutingRequest(handler *OpenAIGatewayHandler, groupID int64, body string) (*httptest.ResponseRecorder, *gin.Context) { + req := httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader([]byte(body))) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = req + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 99, + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, AllowImageGeneration: true}, + User: &service.User{ID: 100}, + }) + c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 100, Concurrency: 0}) + handler.Responses(c) + return rec, c +} + +func TestOpenAIGatewayHandlerResponses_ImageToolSizeTierMissingFromGroupReturns400(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIImagesFailoverHTTPUpstream{} + handler := newOpenAIImagesSizeRoutingTestHandler(t, []service.Account{ + newOpenAIImagesSizeRoutingAccount(1, "1K", "2K"), + }, upstream) + + rec, _ := serveOpenAIResponsesSizeRoutingRequest(handler, 3142, `{"model":"gpt-5.4","stream":false,"input":"draw a cat","tools":[{"type":"image_generation","size":"3840x2160"}]}`) + + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, "invalid_request_error", gjson.GetBytes(rec.Body.Bytes(), "error.type").String()) + require.Contains(t, gjson.GetBytes(rec.Body.Bytes(), "error.message").String(), "4K") + require.Empty(t, upstream.calls()) +} + +func TestOpenAIGatewayHandlerResponses_TextRequestIgnoresImageSizeTiers(t *testing.T) { + gin.SetMode(gin.TestMode) + upstream := &openAIImagesFailoverHTTPUpstream{} + handler := newOpenAIImagesSizeRoutingTestHandler(t, []service.Account{ + newOpenAIImagesSizeRoutingAccount(1, "4K"), + }, upstream) + + _, _ = serveOpenAIResponsesSizeRoutingRequest(handler, 3143, `{"model":"gpt-5.4","stream":false,"input":"hello","size":"1024x1024"}`) + + require.NotEmpty(t, upstream.calls()) + require.Equal(t, int64(1), upstream.calls()[0]) +} diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 679cf4e8a2..fb52a64a79 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -2343,8 +2343,7 @@ func isOpsLocalBusinessLimitError(code string, msg string) bool { (strings.Contains(msg, "beta feature ") && strings.Contains(msg, " is not allowed")) || (strings.Contains(msg, "openai service_tier=") && strings.Contains(msg, " is not allowed for model")) || strings.Contains(msg, "this account only allows codex official clients") || - strings.Contains(msg, "openai wsv1 is temporarily unsupported") || - strings.Contains(msg, "openai codex passthrough requires a non-empty instructions field") + strings.Contains(msg, "openai wsv1 is temporarily unsupported") } func hasOpsUpstreamErrorContext(c *gin.Context) bool { diff --git a/backend/internal/handler/ops_error_logger_test.go b/backend/internal/handler/ops_error_logger_test.go index 7714f4e349..62f1033cae 100644 --- a/backend/internal/handler/ops_error_logger_test.go +++ b/backend/internal/handler/ops_error_logger_test.go @@ -1324,15 +1324,6 @@ func TestClassifyOpsLocalBusinessLimitErrorsExcludedFromSLA(t *testing.T) { wantErrType: "invalid_request_error", wantPhase: "request", }, - { - name: "openai passthrough instructions policy block", - errType: "forbidden_error", - message: "OpenAI codex passthrough requires a non-empty instructions field", - code: "", - status: http.StatusForbidden, - wantErrType: "forbidden_error", - wantPhase: "request", - }, } for _, tt := range tests { @@ -1561,12 +1552,6 @@ func TestClassifyOpsUpstreamAuthTextStillCountsForSLA(t *testing.T) { code: "400", status: http.StatusBadRequest, }, - { - name: "provider passthrough instructions shaped error", - message: "OpenAI codex passthrough requires a non-empty instructions field", - code: "403", - status: http.StatusForbidden, - }, } for _, tt := range tests { diff --git a/backend/internal/handler/request_body_limit.go b/backend/internal/handler/request_body_limit.go index de24551ba9..4fd1aa13b9 100644 --- a/backend/internal/handler/request_body_limit.go +++ b/backend/internal/handler/request_body_limit.go @@ -7,8 +7,20 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/gin-gonic/gin" ) +// handleRequestBodyReadError handles cancellation and temporary capacity errors +// before callers classify malformed or oversized request bodies. +func handleRequestBodyReadError(c *gin.Context, err error) bool { + if err != nil && failoverClientGone(c) { + c.Abort() + return true + } + return middleware2.RejectRequestBodyMemoryOverload(c, err) +} + func extractMaxBytesError(err error) (*http.MaxBytesError, bool) { var maxErr *http.MaxBytesError if errors.As(err, &maxErr) { diff --git a/backend/internal/handler/request_body_limit_test.go b/backend/internal/handler/request_body_limit_test.go index bd9b817797..826657cd1a 100644 --- a/backend/internal/handler/request_body_limit_test.go +++ b/backend/internal/handler/request_body_limit_test.go @@ -2,6 +2,7 @@ package handler import ( "bytes" + "context" "io" "net/http" "net/http/httptest" @@ -43,3 +44,39 @@ func TestRequestBodyLimitTooLarge(t *testing.T) { require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code) require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit)) } + +func TestHandleRequestBodyReadErrorCancellation(t *testing.T) { + for _, tc := range []struct { + name string + cancelled bool + committed bool + }{ + {name: "cancelled", cancelled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true}, + {name: "ordinary_read_error"}, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if tc.cancelled { + cancel() + } + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + if tc.committed { + _, err := c.Writer.WriteString("already committed") + require.NoError(t, err) + } + bodyBefore := recorder.Body.String() + require.Equal(t, tc.cancelled, handleRequestBodyReadError(c, io.ErrUnexpectedEOF)) + require.Equal(t, tc.cancelled, c.IsAborted()) + status := http.StatusOK + if tc.cancelled && !tc.committed { + status = statusClientClosedRequest + } + require.Equal(t, status, c.Writer.Status()) + require.Equal(t, bodyBefore, recorder.Body.String(), "cancelled clients must not receive an error body") + }) + } +} 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/handler/usage_record_async_boundary_test.go b/backend/internal/handler/usage_record_async_boundary_test.go new file mode 100644 index 0000000000..9cf2ca12de --- /dev/null +++ b/backend/internal/handler/usage_record_async_boundary_test.go @@ -0,0 +1,85 @@ +package handler + +import ( + "go/ast" + "go/parser" + "go/token" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// Gin contexts belong to their request. Enforce the async boundary across all +// usage entry points, including rarely exercised provider and auxiliary routes. +func TestUsageRecordTasksDoNotCaptureGinContext(t *testing.T) { + _, filename, _, ok := runtime.Caller(0) + require.True(t, ok) + paths, err := filepath.Glob(filepath.Join(filepath.Dir(filename), "*.go")) + require.NoError(t, err) + files := token.NewFileSet() + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + file, err := parser.ParseFile(files, path, nil, parser.SkipObjectResolution) + require.NoError(t, err) + for _, declaration := range file.Decls { + function, ok := declaration.(*ast.FuncDecl) + if !ok || function.Body == nil { + continue + } + contexts := make(map[string]bool) + for _, param := range function.Type.Params.List { + pointer, ok := param.Type.(*ast.StarExpr) + if !ok { + continue + } + typeName, ok := pointer.X.(*ast.SelectorExpr) + if !ok || typeName.Sel.Name != "Context" { + continue + } + pkg, ok := typeName.X.(*ast.Ident) + if !ok || pkg.Name != "gin" { + continue + } + for _, name := range param.Names { + contexts[name.Name] = true + } + } + if len(contexts) == 0 { + continue + } + ast.Inspect(function.Body, func(node ast.Node) bool { + call, ok := node.(*ast.CallExpr) + if !ok { + return true + } + method, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + switch method.Sel.Name { + case "submitUsageRecordTask", "submitMandatoryUsageRecordTask", "submitOpenAIUsageRecordTask": + default: + return true + } + for _, arg := range call.Args { + task, ok := arg.(*ast.FuncLit) + if !ok { + continue + } + ast.Inspect(task.Body, func(node ast.Node) bool { + if name, ok := node.(*ast.Ident); ok && contexts[name.Name] { + t.Errorf("%s: usage task captures gin.Context %q; snapshot required fields before submitting", files.Position(name.Pos()), name.Name) + } + return true + }) + } + return true + }) + } + } +} diff --git a/backend/internal/handler/usage_record_context_reuse_test.go b/backend/internal/handler/usage_record_context_reuse_test.go new file mode 100644 index 0000000000..779fff2c6b --- /dev/null +++ b/backend/internal/handler/usage_record_context_reuse_test.go @@ -0,0 +1,105 @@ +//go:build unit + +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Exercise the actual forwarding handlers with their usage worker blocked. The +// same Gin context then handles another request before the queued charge runs. +// HandleContext makes that reuse deterministic, including under -race (where +// sync.Pool is allowed to randomly discard entries). +func TestGatewayUsageKeepsModelAfterGinContextReuse(t *testing.T) { + for _, endpoint := range []string{"chat/completions", "responses"} { + t.Run(endpoint, func(t *testing.T) { + cfg := &config.Config{} + groupID := int64(9300) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ + ID: 9301, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "test-key"}, + AccountGroups: []service.AccountGroup{{AccountID: 9301, GroupID: groupID}}, + } + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{account}}, nil, nil, nil, nil) + usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)} + billingRepo := &compatStreamUsageBillingRepo{} + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + upstream := &compatStreamUsageUpstream{response: &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(compatStreamUsagePartialStream + compatStreamUsageCompletion)), + Header: http.Header{"X-Request-Id": []string{"usage-context-reuse"}}, + }} + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, usageRepo, billingRepo, nil, nil, nil, nil, cfg, + snapshot, nil, service.NewBillingService(cfg, nil), nil, nil, nil, upstream, + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + pool := newUsageRecordTestPool(t) + blocked, release := make(chan struct{}), make(chan struct{}) + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(unblock) + pool.Submit(func(context.Context) { close(blocked); <-release }) + <-blocked + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + usageRecordWorkerPool: pool, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + apiKey := &service.APIKey{ID: 9302, UserID: 9303, GroupID: &groupID, Group: group, User: &service.User{ID: 9303, Balance: 100}} + var first *gin.Context + router := gin.New() + router.POST("/v1/"+endpoint, func(c *gin.Context) { + first = c + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.RequestedPublicModel, "public-model-A")) + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9303}) + if endpoint == "chat/completions" { + h.ChatCompletions(c) + } else { + h.Responses(c) + } + }) + router.GET("/next", func(c *gin.Context) { + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.RequestedPublicModel, "public-model-B")) + }) + body := `{"model":"claude-sonnet-4.5","stream":true,"input":"hello"}` + if endpoint == "chat/completions" { + body = `{"model":"claude-sonnet-4.5","stream":true,"messages":[{"role":"user","content":"hello"}]}` + } + req := httptest.NewRequest(http.MethodPost, "/v1/"+endpoint, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, uint64(1), pool.Stats().WaitingTasks) + + first.Request = httptest.NewRequest(http.MethodGet, "/next", nil) + router.HandleContext(first) + unblock() + select { + case usage := <-usageRepo.created: + require.Equal(t, "public-model-A", usage.RequestedModel) + case <-time.After(2 * time.Second): + t.Fatal("queued request usage was not recorded") + } + }) + } +} diff --git a/backend/internal/handler/wire.go b/backend/internal/handler/wire.go index bdd47f4265..86b21a01f9 100644 --- a/backend/internal/handler/wire.go +++ b/backend/internal/handler/wire.go @@ -183,6 +183,7 @@ func ProvideAdminSettingHandler(settingService *service.SettingService, emailSer func ProvideHandlers( authHandler *AuthHandler, userHandler *UserHandler, + mcpOAuthHandler *MCPOAuthHandler, apiKeyHandler *APIKeyHandler, usageHandler *UsageHandler, redeemHandler *RedeemHandler, @@ -209,6 +210,7 @@ func ProvideHandlers( return &Handlers{ Auth: authHandler, User: userHandler, + MCPOAuth: mcpOAuthHandler, APIKey: apiKeyHandler, Usage: usageHandler, Redeem: redeemHandler, @@ -236,6 +238,7 @@ var ProviderSet = wire.NewSet( // Top-level handlers NewAuthHandler, NewUserHandler, + NewMCPOAuthHandler, NewAPIKeyHandler, NewUsageHandler, NewRedeemHandler, diff --git a/backend/internal/managementmcp/auth.go b/backend/internal/managementmcp/auth.go new file mode 100644 index 0000000000..3bd7ad6dc7 --- /dev/null +++ b/backend/internal/managementmcp/auth.go @@ -0,0 +1,127 @@ +package managementmcp + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" +) + +const AuthMethod = service.AuditAuthMethodMCPOAuth + +type TokenAuthenticator interface { + Authenticate(context.Context, string) (*service.MCPPrincipal, error) +} + +type requestKey struct{} +type dispatchKey struct{} + +type authenticatedRequest struct { + principal *service.MCPPrincipal + request *http.Request +} + +// Authenticate accepts only resource-bound OAuth access tokens. Browser sessions and +// inference keys never become management credentials through this endpoint. +func Authenticate(tokens TokenAuthenticator, allowedOrigins []string, resourceURL func(context.Context) (string, error)) gin.HandlerFunc { + return func(c *gin.Context) { + c.Header("Cache-Control", "no-store") + resource, err := resourceURL(c.Request.Context()) + if err != nil { + middleware.AbortWithError(c, http.StatusServiceUnavailable, "MCP_OAUTH_NOT_CONFIGURED", "Configure the public MCP URL to enable OAuth") + return + } + u, err := url.Parse(resource) + if err != nil || u.Host == "" { + middleware.AbortWithError(c, http.StatusServiceUnavailable, "MCP_OAUTH_NOT_CONFIGURED", "MCP public URL is invalid") + return + } + challenge := fmt.Sprintf(`Bearer resource_metadata="%s://%s/.well-known/oauth-protected-resource/api/v1/mcp", scope="mcp"`, u.Scheme, u.Host) + if !originAllowed(c.Request, allowedOrigins) { + middleware.AbortWithError(c, http.StatusForbidden, "MCP_ORIGIN_DENIED", "Origin is not allowed for MCP") + return + } + parts := strings.Fields(c.GetHeader("Authorization")) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + c.Header("WWW-Authenticate", challenge) + middleware.AbortWithError(c, http.StatusUnauthorized, "INVALID_MCP_TOKEN", "An OAuth access token is required") + return + } + principal, err := tokens.Authenticate(c.Request.Context(), parts[1]) + if err != nil || principal == nil || principal.Resource != resource { + if err != nil && !errors.Is(err, service.ErrMCPOAuthInvalidToken) { + middleware.AbortWithError(c, http.StatusServiceUnavailable, "MCP_AUTH_UNAVAILABLE", "MCP authentication is temporarily unavailable") + return + } + c.Header("WWW-Authenticate", challenge+`, error="invalid_token"`) + middleware.AbortWithError(c, http.StatusUnauthorized, "INVALID_MCP_TOKEN", "MCP OAuth access token is invalid or expired") + return + } + identity := &authenticatedRequest{principal: principal, request: c.Request} + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestKey{}, identity)) + setSubject(c, principal) + c.Next() + } +} + +// DispatchAuth is used exclusively by the private in-process management router. +// No HTTP header can supply this context. Public REST auth remains JWT-only. +func DispatchAuth(admin bool) gin.HandlerFunc { + return func(c *gin.Context) { + identity, _ := c.Request.Context().Value(requestKey{}).(*authenticatedRequest) + spec, ok := c.Request.Context().Value(dispatchKey{}).(ToolSpec) + if identity == nil || !ok || spec.Method != c.Request.Method || spec.Path != c.FullPath() || + !toolAllowed(identity.principal, spec) || (admin && identity.principal.Scope != service.MCPScopeAdmin) { + middleware.AbortWithError(c, http.StatusForbidden, "MCP_FORBIDDEN", "MCP operation is not allowed") + return + } + setSubject(c, identity.principal) + middleware.SetAuditExtra(c, map[string]any{"mcp_grant_id": identity.principal.GrantID, "mcp_tool": spec.Name}) + c.Next() + } +} + +func setSubject(c *gin.Context, principal *service.MCPPrincipal) { + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: principal.UserID, Concurrency: principal.Concurrency}) + c.Set(string(middleware.ContextKeyUserRole), principal.Role) + c.Set(middleware.ContextKeyAuthEmail, principal.Email) + c.Set("auth_method", AuthMethod) + // Never share a legacy user's step-up grant with a machine credential. + c.Set(middleware.ContextKeySessionID, "mcp:"+principal.GrantID) +} + +func toolAllowed(p *service.MCPPrincipal, spec ToolSpec) bool { + return p != nil && p.UserID > 0 && + (p.Scope == service.MCPScopeUser || p.Scope == service.MCPScopeAdmin) && + (!spec.Admin || (p.Scope == service.MCPScopeAdmin && p.Role == service.RoleAdmin)) && + (!p.ReadOnly || spec.ReadOnly) +} + +func originAllowed(r *http.Request, origins []string) bool { + origin := r.Header.Get("Origin") + if origin == "" { + return true // Native MCP clients do not send an Origin. + } + u, err := url.Parse(origin) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || + u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return false + } + // Same-host browser access also works behind an HTTPS terminating proxy. + if strings.EqualFold(u.Host, r.Host) { + return true + } + for _, allowed := range origins { + // Wildcard CORS does not disable MCP's Origin validation. + if allowed != "*" && origin == strings.TrimSpace(allowed) { + return true + } + } + return false +} diff --git a/backend/internal/managementmcp/catalog.go b/backend/internal/managementmcp/catalog.go new file mode 100644 index 0000000000..bd623e59e3 --- /dev/null +++ b/backend/internal/managementmcp/catalog.go @@ -0,0 +1,280 @@ +// Package managementmcp exposes a bounded set of platform management operations. +package managementmcp + +import "strings" + +// ToolSpec binds one MCP tool to an existing authenticated management route. +// InputSchema permits only named path parameters, query parameters and body fields; +// clients never supply a URL, HTTP method or credentials in tool arguments. +type ToolSpec struct { + Name string + Description string + Method string + Path string + Admin bool + ReadOnly bool + Destructive bool + RevealCreatedKey bool + InputSchema map[string]any +} + +// ToolCatalog returns fresh schemas so filtering one connection's tools cannot +// alter another connection's permissions or input validation. +func ToolCatalog() []ToolSpec { + keyList := catalogPage(map[string]any{ + "search": catalogText("Search API key names", 100), + "status": catalogEnum("Key status", "active", "inactive", "quota_exhausted", "expired"), + "group_id": catalogID("Group ID"), + }) + keyCreate := catalogObject(map[string]any{ + "name": catalogNonemptyText("Name for the new API key", 100), + "group_id": catalogID("Accessible group ID; use user_list_groups to find one"), + "quota": catalogNumber("Lifetime spending limit in USD; 0 means unlimited", 0), + "expires_in_days": catalogInteger("Lifetime in days", 1, 36500), + "ip_whitelist": catalogStrings("Allowed IP addresses or CIDR ranges; empty means no allowlist", 100, 128), + "ip_blacklist": catalogStrings("Blocked IP addresses or CIDR ranges", 100, 128), + "rate_limit_5h": catalogNumber("Rolling 5-hour spending limit in USD; 0 means unlimited", 0), + "rate_limit_1d": catalogNumber("Rolling 1-day spending limit in USD; 0 means unlimited", 0), + "rate_limit_7d": catalogNumber("Rolling 7-day spending limit in USD; 0 means unlimited", 0), + }, "name") + keyUpdate := catalogObject(map[string]any{ + "name": catalogNonemptyText("New API key name", 100), + "group_id": catalogID("Accessible destination group ID"), + "status": catalogEnum("Enable or disable this key", "active", "inactive"), + "quota": catalogNumber("Lifetime spending limit in USD; 0 means unlimited", 0), + "expires_at": catalogText("Expiry in RFC3339 format; empty string removes expiry", 64), + "ip_whitelist": catalogStrings("Replace allowed IP addresses/CIDRs; empty clears the list", 100, 128), + "ip_blacklist": catalogStrings("Replace blocked IP addresses/CIDRs; empty clears the list", 100, 128), + "rate_limit_5h": catalogNumber("Rolling 5-hour spending limit in USD; 0 means unlimited", 0), + "rate_limit_1d": catalogNumber("Rolling 1-day spending limit in USD; 0 means unlimited", 0), + "rate_limit_7d": catalogNumber("Rolling 7-day spending limit in USD; 0 means unlimited", 0), + }) + keyUpdate["minProperties"] = 1 + + userUpdate := catalogObject(map[string]any{ + "username": catalogText("Display name", 100), + "notes": catalogText("Administrator notes", 2000), + "concurrency": catalogInteger("Maximum concurrent requests", 1, 100000), + "rpm_limit": catalogInteger("Requests per minute; 0 means unlimited", 0, 1000000), + "status": catalogEnum("User status; disabling blocks access", "active", "disabled"), + "allowed_groups": catalogIDs("Replace the user's allowed group IDs"), + "restrict_public_groups": catalogBool("Restrict public groups to allowed_groups"), + }) + userUpdate["minProperties"] = 1 + + groupCreateFields := catalogGroupFields() + groupCreateFields["platform"] = catalogNonemptyText("Platform identifier, for example anthropic, openai, gemini or composite", 64) + groupCreate := catalogObject(groupCreateFields, "name", "platform", "rate_multiplier") + groupUpdateFields := catalogGroupFields() + groupUpdateFields["status"] = catalogEnum("Group availability", "active", "inactive") + groupUpdate := catalogObject(groupUpdateFields) + groupUpdate["minProperties"] = 1 + + accountUpdate := catalogObject(map[string]any{ + "name": catalogNonemptyText("Upstream account name", 100), + "notes": catalogText("Administrator notes", 2000), + "concurrency": catalogInteger("Maximum concurrent requests", 1, 100000), + "priority": catalogInteger("Scheduling priority; lower values are preferred", 0, 100000), + "rate_multiplier": catalogNumber("Account cost multiplier; 0 means free", 0), + "status": catalogEnum("Account availability", "active", "inactive", "error"), + "expires_at": catalogInteger("Unix expiry timestamp in seconds; 0 removes expiry", 0, 253402300799), + "auto_pause_on_expired": catalogBool("Stop scheduling after expiry"), + }) + accountUpdate["minProperties"] = 1 + + tools := []ToolSpec{ + catalogTool("user_get_profile", "Get your profile, balance and account limits. Always uses the authenticated user.", "GET", "/user/profile", nil, nil), + catalogTool("user_get_platform_quotas", "Get your spending quota and usage windows for each platform.", "GET", "/user/platform-quotas", nil, nil), + catalogTool("user_list_groups", "List the groups available to your API keys, including platform and pricing information.", "GET", "/groups/available", nil, nil), + catalogTool("user_list_channels", "List channels and supported models visible to you. Returns an empty list when channel discovery is disabled.", "GET", "/channels/available", nil, nil), + catalogTool("user_list_api_keys", "List your API key metadata and limits with pagination. Existing key secrets are omitted.", "GET", "/keys", keyList, nil), + catalogTool("user_get_api_key", "Get one of your API keys by ID, including status and limits. The key secret is omitted.", "GET", "/keys/:id", nil, nil), + catalogTool("user_create_api_key", "Create an API key owned by you. Returns the newly created secret once in this tool result; store it securely.", "POST", "/keys", nil, keyCreate), + catalogTool("user_update_api_key", "Update one of your API keys. Only supplied fields change; disabling a key immediately blocks its use. Returns metadata without its secret.", "PUT", "/keys/:id", nil, keyUpdate), + catalogTool("user_delete_api_key", "Permanently delete one of your API keys. Applications using it will lose access. Returns the deletion result.", "DELETE", "/keys/:id", nil, nil), + catalogTool("user_list_usage", "List your request usage, tokens and costs with pagination and optional date, model and key filters.", "GET", "/usage", catalogPage(catalogUsageFields(false)), nil), + catalogTool("user_get_usage_stats", "Get aggregate request counts, token usage and costs for your account; defaults to the last seven days. Dates are inclusive YYYY-MM-DD.", "GET", "/usage/stats", catalogObject(catalogUsageFields(false)), nil), + catalogTool("user_get_dashboard", "Get your dashboard totals, request counts and spending summary.", "GET", "/usage/dashboard/stats", nil, nil), + catalogTool("user_list_subscriptions", "List your subscriptions, associated groups, validity and current usage.", "GET", "/subscriptions", nil, nil), + catalogTool("user_get_subscription_summary", "Get a summary of your active subscription limits and remaining allowance.", "GET", "/subscriptions/summary", nil, nil), + + catalogTool("admin_get_dashboard", "Get platform-wide user/account counts, usage, spending and service uptime.", "GET", "/admin/dashboard/stats", nil, nil), + catalogTool("admin_list_users", "List platform users and account limits with pagination. May include contact information and administrator notes.", "GET", "/admin/users", catalogPage(map[string]any{ + "search": catalogText("Search email or display name", 100), + "status": catalogEnum("User status", "active", "disabled"), + "role": catalogEnum("User role", "admin", "user"), + "group_name": catalogText("Search allowed group name", 100), + }), nil), + catalogTool("admin_get_user", "Get a platform user's profile, balance and limits by ID. Existing API key secrets are omitted.", "GET", "/admin/users/:id", nil, nil), + catalogTool("admin_update_user", "Update a user's display name, notes, limits, status or group access. Does not change passwords, roles or identity bindings. Returns the updated user.", "PUT", "/admin/users/:id", nil, userUpdate), + catalogTool("admin_update_user_balance", "Set, add to or subtract from a user's balance in USD. This changes real billing credit; verify the user, amount and operation before calling. Returns the updated result.", "POST", "/admin/users/:id/balance", nil, catalogObject(map[string]any{ + "balance": map[string]any{"type": "number", "exclusiveMinimum": 0, "description": "Positive amount in USD"}, + "operation": catalogEnum("How to apply the amount", "set", "add", "subtract"), + "notes": catalogText("Reason for the balance adjustment", 2000), + }, "balance", "operation", "notes")), + catalogTool("admin_list_groups", "List platform groups, pricing multipliers and status with pagination.", "GET", "/admin/groups", catalogPage(map[string]any{ + "search": catalogText("Search group name", 100), "platform": catalogText("Platform identifier", 64), + "status": catalogEnum("Group status", "active", "inactive"), "is_exclusive": catalogBool("Filter exclusive groups"), + }), nil), + catalogTool("admin_get_group", "Get one group's configuration and model allowlist by ID.", "GET", "/admin/groups/:id", nil, nil), + catalogTool("admin_create_group", "Create a platform group with explicit platform and price multiplier. Returns the group; attach upstream accounts in the web console before serving traffic.", "POST", "/admin/groups", nil, groupCreate), + catalogTool("admin_update_group", "Update group name, pricing, spending limits, availability or model allowlist. Changes affect every user of this group. Only supplied fields change.", "PUT", "/admin/groups/:id", nil, groupUpdate), + catalogTool("admin_delete_group", "Delete a platform group. This can disrupt API keys and subscriptions associated with it. Returns the deletion result or a dependency error.", "DELETE", "/admin/groups/:id", nil, nil), + catalogTool("admin_list_accounts", "List upstream account metadata, status and scheduling settings with pagination. Credentials are omitted.", "GET", "/admin/accounts", catalogPage(map[string]any{ + "search": catalogText("Search account name", 100), "platform": catalogText("Platform identifier", 64), + "status": catalogEnum("Account status", "active", "inactive", "error", "rate_limited", "temp_unschedulable", "unschedulable"), + "type": catalogEnum("Upstream authentication type", "oauth", "setup-token", "apikey", "upstream", "bedrock", "service_account"), + "group": catalogID("Group ID"), "lite": catalogBool("Request a lightweight account list"), + }), nil), + catalogTool("admin_get_account", "Get one upstream account's metadata and runtime status. Credentials are omitted.", "GET", "/admin/accounts/:id", nil, nil), + catalogTool("admin_update_account", "Update upstream account name, notes, concurrency, priority, cost multiplier, status or expiry. Does not accept credentials or network settings.", "PUT", "/admin/accounts/:id", nil, accountUpdate), + catalogTool("admin_set_account_schedulable", "Enable or disable scheduling for an upstream account. Disabling prevents selection for new requests. Returns updated account metadata.", "POST", "/admin/accounts/:id/schedulable", nil, catalogObject(map[string]any{ + "schedulable": catalogBool("Whether the scheduler may select this account"), + }, "schedulable")), + catalogTool("admin_clear_account_error", "Clear an upstream account's error state so it can recover. Investigate and fix the cause first. Returns the recovery result.", "POST", "/admin/accounts/:id/clear-error", nil, nil), + catalogTool("admin_list_usage", "List platform-wide request usage, tokens and costs with pagination. Filter by user, account, group, model or inclusive date range.", "GET", "/admin/usage", catalogPage(catalogUsageFields(true)), nil), + catalogTool("admin_get_usage_stats", "Get platform-wide aggregate usage and costs; defaults to today. Both start_date and end_date should be supplied for a custom range.", "GET", "/admin/usage/stats", catalogObject(catalogUsageFields(true)), nil), + catalogTool("admin_list_subscriptions", "List platform subscriptions and their user/group associations, expiry and quota usage with pagination.", "GET", "/admin/subscriptions", catalogPage(map[string]any{ + "user_id": catalogID("User ID"), "group_id": catalogID("Group ID"), + "status": catalogEnum("Subscription status", "active", "expired", "revoked"), "platform": catalogText("Platform identifier", 64), + }), nil), + catalogTool("admin_get_subscription", "Get one platform subscription and its user/group association by ID.", "GET", "/admin/subscriptions/:id", nil, nil), + catalogTool("admin_assign_subscription", "Assign a subscription group to a user for the specified number of days. An existing subscription may be extended; do not retry blindly. Returns the resulting subscription.", "POST", "/admin/subscriptions/assign", nil, catalogObject(map[string]any{ + "user_id": catalogID("Recipient user ID"), "group_id": catalogID("Subscription group ID"), + "validity_days": catalogInteger("Validity in days", 1, 36500), "notes": catalogText("Assignment notes", 2000), + }, "user_id", "group_id", "validity_days")), + catalogTool("admin_extend_subscription", "Extend a subscription by the specified positive number of days. Changes billing entitlement; returns the updated subscription.", "POST", "/admin/subscriptions/:id/extend", nil, catalogObject(map[string]any{ + "days": catalogInteger("Additional validity in days", 1, 36500), + }, "days")), + catalogTool("admin_revoke_subscription", "Revoke a subscription immediately. The user loses the associated entitlement. Returns the revocation result.", "POST", "/admin/subscriptions/:id/revoke", nil, nil), + catalogTool("admin_get_ops_overview", "Get platform operational health, traffic, latency and error overview for troubleshooting.", "GET", "/admin/ops/dashboard/overview", nil, nil), + } + for i := range tools { + if tools[i].Name == "user_create_api_key" { + tools[i].RevealCreatedKey = true + } + // Creation does not remove or overwrite existing state. Subscription + // assignment is deliberately excluded because it may extend an existing one. + if tools[i].Name == "user_create_api_key" || tools[i].Name == "admin_create_group" { + tools[i].Destructive = false + } + } + return tools +} + +func catalogTool(name, description, method, path string, query, body map[string]any) ToolSpec { + properties := map[string]any{} + required := []string{} + if strings.Contains(path, ":id") { + properties["id"] = catalogID("Resource ID") + required = append(required, "id") + } + if query != nil { + properties["query"] = query + } + if body != nil { + properties["body"] = body + required = append(required, "body") + } + // These existing routes require an idempotency key. Keep retries within + // their established coordinator rather than inventing MCP-side settlement. + switch name { + case "user_create_api_key", "admin_update_user_balance", "admin_extend_subscription": + properties["idempotency_key"] = map[string]any{ + "type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[!-~]+$", + "description": "Unique operation ID (for example a UUID). Reuse the same value and arguments when retrying this operation; use a new value for a new intended operation.", + } + required = append(required, "idempotency_key") + } + return ToolSpec{ + Name: name, Description: description, Method: method, Path: "/api/v1" + path, + Admin: strings.HasPrefix(path, "/admin/"), ReadOnly: method == "GET", + Destructive: method != "GET", InputSchema: catalogObject(properties, required...), + } +} + +func catalogObject(properties map[string]any, required ...string) map[string]any { + schema := map[string]any{"type": "object", "properties": properties, "additionalProperties": false} + if len(required) > 0 { + schema["required"] = required + } + return schema +} + +func catalogText(description string, maxLength int) map[string]any { + return map[string]any{"type": "string", "description": description, "maxLength": maxLength} +} + +func catalogNonemptyText(description string, maxLength int) map[string]any { + schema := catalogText(description, maxLength) + schema["minLength"] = 1 + return schema +} + +func catalogEnum(description string, values ...string) map[string]any { + return map[string]any{"type": "string", "description": description, "enum": values} +} + +func catalogInteger(description string, min, max int64) map[string]any { + return map[string]any{"type": "integer", "description": description, "minimum": min, "maximum": max} +} + +func catalogID(description string) map[string]any { + return catalogInteger(description, 1, 9007199254740991) +} + +func catalogNumber(description string, min float64) map[string]any { + return map[string]any{"type": "number", "description": description, "minimum": min} +} + +func catalogBool(description string) map[string]any { + return map[string]any{"type": "boolean", "description": description} +} + +func catalogStrings(description string, maxItems, maxLength int) map[string]any { + return map[string]any{"type": "array", "description": description, "items": catalogNonemptyText("Value", maxLength), "maxItems": maxItems} +} + +func catalogIDs(description string) map[string]any { + return map[string]any{"type": "array", "description": description, "items": catalogID("Resource ID"), "maxItems": 100, "uniqueItems": true} +} + +func catalogPage(fields map[string]any) map[string]any { + fields["page"] = catalogInteger("Page number, starting at 1", 1, 1000000) + fields["page_size"] = catalogInteger("Results per page; at most 100", 1, 100) + return catalogObject(fields) +} + +func catalogUsageFields(admin bool) map[string]any { + fields := map[string]any{ + "api_key_id": catalogID("Filter by API key ID"), "group_id": catalogID("Filter by group ID"), + "model": catalogText("Filter by requested model", 200), + "start_date": map[string]any{"type": "string", "description": "Inclusive start date (YYYY-MM-DD)", "pattern": `^\d{4}-\d{2}-\d{2}$`}, + "end_date": map[string]any{"type": "string", "description": "Inclusive end date (YYYY-MM-DD)", "pattern": `^\d{4}-\d{2}-\d{2}$`}, + "timezone": catalogText("IANA time zone, for example Asia/Shanghai or UTC", 100), + "period": catalogEnum("Stats date range when explicit dates are omitted", "today", "week", "month"), + "stream": catalogBool("Filter streaming or non-streaming requests"), + } + if admin { + fields["user_id"] = catalogID("Filter by user ID") + fields["account_id"] = catalogID("Filter by upstream account ID") + } + return fields +} + +func catalogGroupFields() map[string]any { + return map[string]any{ + "name": catalogNonemptyText("Group name", 100), "description": catalogText("Group description", 2000), + "rate_multiplier": map[string]any{"type": "number", "exclusiveMinimum": 0, "description": "Positive user billing multiplier; 1 is standard pricing"}, + "is_exclusive": catalogBool("Limit access to users explicitly assigned this group"), + "subscription_type": catalogEnum("Group billing mode", "standard", "subscription"), + "daily_limit_usd": catalogNumber("Daily subscription spending limit in USD; -1 means unlimited", -1), + "weekly_limit_usd": catalogNumber("Weekly subscription spending limit in USD; -1 means unlimited", -1), + "monthly_limit_usd": catalogNumber("Monthly subscription spending limit in USD; -1 means unlimited", -1), + "rpm_limit": catalogInteger("Requests per minute; 0 means unlimited", 0, 1000000), + "model_allowlist": catalogObject(map[string]any{ + "enabled": catalogBool("Enable the model allowlist; an enabled list must contain at least one model"), + "models": catalogStrings("Allowed upstream model IDs or patterns containing *", 1000, 200), + }, "enabled", "models"), + } +} diff --git a/backend/internal/managementmcp/catalog_test.go b/backend/internal/managementmcp/catalog_test.go new file mode 100644 index 0000000000..010166e901 --- /dev/null +++ b/backend/internal/managementmcp/catalog_test.go @@ -0,0 +1,168 @@ +package managementmcp + +import ( + "encoding/json" + "regexp" + "slices" + "strings" + "testing" +) + +func TestToolCatalogRouteAndSchemaBoundaries(t *testing.T) { + names := map[string]bool{} + for _, spec := range ToolCatalog() { + t.Run(spec.Name, func(t *testing.T) { + if names[spec.Name] || !regexp.MustCompile(`^(user|admin)_[a-z0-9_]+$`).MatchString(spec.Name) { + t.Fatalf("duplicate or invalid tool name: %q", spec.Name) + } + names[spec.Name] = true + if spec.Description == "" || !slices.Contains([]string{"GET", "POST", "PUT", "DELETE"}, spec.Method) { + t.Fatal("tool must have a description and supported method") + } + if !strings.HasPrefix(spec.Path, "/api/v1/") || strings.ContainsAny(spec.Path, "?*#") || strings.Contains(spec.Path, "..") { + t.Fatalf("route must be a fixed local API path: %q", spec.Path) + } + if spec.Admin != strings.HasPrefix(spec.Path, "/api/v1/admin/") || spec.Admin != strings.HasPrefix(spec.Name, "admin_") { + t.Fatal("tool role does not match its route") + } + if spec.ReadOnly != (spec.Method == "GET") || (spec.ReadOnly && spec.Destructive) { + t.Fatal("tool mutability metadata does not match its route") + } + checkCatalogSchema(t, spec.InputSchema) + properties, ok := spec.InputSchema["properties"].(map[string]any) + if !ok { + t.Fatal("input schema properties must be an object") + } + required, _ := spec.InputSchema["required"].([]string) + for name := range properties { + if !slices.Contains([]string{"id", "query", "body", "idempotency_key"}, name) { + t.Fatalf("unexpected top-level field %q", name) + } + } + pathParameters := regexp.MustCompile(`:([a-z_]+)`).FindAllStringSubmatch(spec.Path, -1) + for _, match := range pathParameters { + if match[1] != "id" || !slices.Contains(required, match[1]) { + t.Fatalf("path parameter %q must be a required ID", match[1]) + } + } + if _, exists := properties["id"]; exists != (len(pathParameters) > 0) { + t.Fatal("ID input and route placeholder disagree") + } + if body, exists := properties["body"]; exists { + bodySchema, ok := body.(map[string]any) + if !ok || spec.ReadOnly || !slices.Contains(required, "body") || bodySchema["type"] != "object" { + t.Fatal("write bodies must be required objects") + } + } + if query, exists := properties["query"].(map[string]any); exists { + queryFields, ok := query["properties"].(map[string]any) + if !ok { + t.Fatal("query schema properties must be an object") + } + if size, exists := queryFields["page_size"].(map[string]any); exists && size["maximum"] != int64(100) { + t.Fatal("list page size must be bounded to 100") + } + if !spec.Admin { + for _, name := range []string{"user_id", "account_id"} { + if _, exists := queryFields[name]; exists { + t.Fatalf("user tool accepts cross-user filter %q", name) + } + } + } + } + if _, err := json.Marshal(spec.InputSchema); err != nil { + t.Fatalf("schema is not JSON: %v", err) + } + }) + } +} + +func checkCatalogSchema(t *testing.T, schema map[string]any) { + t.Helper() + switch schema["type"] { + case "object": + if schema["additionalProperties"] != false { + t.Fatal("all objects must reject unknown fields") + } + properties, ok := schema["properties"].(map[string]any) + if !ok { + t.Fatal("object lacks explicit properties") + } + for name, field := range properties { + child, ok := field.(map[string]any) + if !ok { + t.Fatalf("field %q lacks a typed schema", name) + } + checkCatalogSchema(t, child) + } + if required, ok := schema["required"].([]string); ok { + for _, name := range required { + if _, exists := properties[name]; !exists { + t.Fatalf("required field %q is not declared", name) + } + } + } + case "array": + child, ok := schema["items"].(map[string]any) + if !ok || schema["maxItems"] == nil { + t.Fatal("arrays must have typed items and size limits") + } + checkCatalogSchema(t, child) + case "integer", "number", "string", "boolean": + default: + t.Fatalf("unsupported or missing schema type: %v", schema["type"]) + } +} + +func TestToolCatalogDoesNotExposeCredentialOrIdentityManagement(t *testing.T) { + for _, spec := range ToolCatalog() { + if spec.RevealCreatedKey != (spec.Name == "user_create_api_key") { + t.Fatalf("unexpected secret disclosure policy for %s", spec.Name) + } + for _, forbidden := range []string{"admin-api-key", "/auth", "/password", "/totp", "/passkeys", "/payment", "/backup", "/data"} { + if strings.Contains(spec.Path, forbidden) { + t.Fatalf("%s exposes sensitive route %s", spec.Name, spec.Path) + } + } + properties := catalogTestObject(t, spec.InputSchema["properties"]) + if body, ok := properties["body"].(map[string]any); ok { + fields := catalogTestObject(t, body["properties"]) + for _, forbidden := range []string{"credentials", "extra", "password", "role", "email", "custom_key", "proxy_id", "url"} { + if _, exists := fields[forbidden]; exists { + t.Fatalf("%s accepts sensitive field %s", spec.Name, forbidden) + } + } + } + } +} + +func TestToolCatalogSchemasAreIndependent(t *testing.T) { + first := ToolCatalog() + first[0].InputSchema["additionalProperties"] = true + for _, spec := range first { + if spec.Name == "admin_create_group" { + body := catalogTestObject(t, catalogTestObject(t, spec.InputSchema["properties"])["body"]) + catalogTestObject(t, body["properties"])["password"] = catalogText("Unexpected", 100) + } + } + for _, spec := range ToolCatalog() { + if spec.InputSchema["additionalProperties"] != false { + t.Fatal("catalog calls share schema state") + } + if spec.Name == "admin_update_group" || spec.Name == "admin_create_group" { + body := catalogTestObject(t, catalogTestObject(t, spec.InputSchema["properties"])["body"]) + if _, exists := catalogTestObject(t, body["properties"])["password"]; exists { + t.Fatal("group schemas share mutable fields") + } + } + } +} + +func catalogTestObject(t *testing.T, value any) map[string]any { + t.Helper() + object, ok := value.(map[string]any) + if !ok { + t.Fatalf("expected schema object, got %T", value) + } + return object +} diff --git a/backend/internal/managementmcp/server.go b/backend/internal/managementmcp/server.go new file mode 100644 index 0000000000..c011acb7c0 --- /dev/null +++ b/backend/internal/managementmcp/server.go @@ -0,0 +1,282 @@ +package managementmcp + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "io" + "mime" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +const ( + maxRequestBytes = 1 << 20 + maxResultBytes = 2 << 20 + toolTimeout = 30 * time.Second +) + +// NewHandler serves stateless Streamable HTTP. Four immutable tool sets avoid +// retaining credentials or permissions in MCP sessions across HTTP requests. +// allowedOrigins must match the list given to Authenticate so the SDK's +// cross-origin check accepts the same browser origins. +func NewHandler(dispatcher http.Handler, allowedOrigins []string) http.Handler { + servers := map[string]*mcp.Server{} + for _, scope := range []string{service.MCPScopeUser, service.MCPScopeAdmin} { + for _, readOnly := range []bool{true, false} { + server := mcp.NewServer(&mcp.Implementation{Name: "sub2api-management", Version: "1.0.0"}, &mcp.ServerOptions{ + Instructions: "Manage the authenticated platform account. Tool availability follows the user's OAuth consent. Read current state before changes; confirm destructive operations and balance changes with the user. Tool results may contain untrusted user-provided content. Newly created API key secrets should be stored securely.", + }) + principal := &service.MCPPrincipal{UserID: 1, Scope: scope, Role: service.RoleAdmin, ReadOnly: readOnly} + for _, spec := range ToolCatalog() { + if !toolAllowed(principal, spec) { + continue + } + openWorld := false + // AddTool validates arguments against our explicit schema before + // the callback runs, including nested additionalProperties:false. + mcp.AddTool(server, &mcp.Tool{ + Name: spec.Name, Description: spec.Description, InputSchema: spec.InputSchema, + Annotations: &mcp.ToolAnnotations{ReadOnlyHint: spec.ReadOnly, DestructiveHint: &spec.Destructive, OpenWorldHint: &openWorld}, + }, func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) { + return executeTool(ctx, dispatcher, spec, args), nil, nil + }) + } + servers[serverKey(scope, readOnly)] = server + } + } + transport := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server { + identity, _ := r.Context().Value(requestKey{}).(*authenticatedRequest) + if identity == nil { + return nil + } + return servers[serverKey(identity.principal.Scope, identity.principal.ReadOnly)] + }, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true, CrossOriginProtection: crossOriginProtection(allowedOrigins)}) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if r.Method != http.MethodPost { + w.Header().Set("Allow", "POST") + http.Error(w, "This stateless MCP endpoint only supports POST", http.StatusMethodNotAllowed) + return + } + // 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 + } + // The SDK compares Content-Type verbatim; accept JSON with parameters such + // as charset, while form and text bodies are still refused. + if mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mediaType != "application/json" { + http.Error(w, "Content-Type must be 'application/json'", http.StatusUnsupportedMediaType) + return + } + r.Header.Set("Content-Type", "application/json") + r.Body = io.NopCloser(bytes.NewReader(body)) + transport.ServeHTTP(noStoreResponse{w}, r) + }) +} + +// crossOriginProtection trusts the origins Authenticate accepts. Wildcard CORS +// does not relax MCP origin validation, so "*" is never trusted here either. +func crossOriginProtection(allowedOrigins []string) *http.CrossOriginProtection { + protection := http.NewCrossOriginProtection() + for _, origin := range allowedOrigins { + origin = strings.TrimSpace(origin) + if origin == "" || origin == "*" { + continue + } + // Authenticate matches origins verbatim, so malformed entries never match there either. + _ = protection.AddTrustedOrigin(origin) + } + return protection +} + +func serverKey(scope string, readOnly bool) string { return scope + ":" + strconv.FormatBool(readOnly) } + +func executeTool(ctx context.Context, dispatcher http.Handler, spec ToolSpec, args map[string]any) *mcp.CallToolResult { + identity, _ := ctx.Value(requestKey{}).(*authenticatedRequest) + if identity == nil || !toolAllowed(identity.principal, spec) { + return toolError("MCP operation is not allowed") + } + // SDK transports may detach the handler context. Explicitly retain HTTP + // disconnect cancellation and bound database work for each invocation. + ctx, cancel := context.WithTimeout(ctx, toolTimeout) + defer cancel() + stop := context.AfterFunc(identity.request.Context(), cancel) + defer stop() + if identity.request.Context().Err() != nil { + return toolError("MCP request was cancelled") + } + path := spec.Path + if strings.Contains(path, ":id") { + id, ok := args["id"].(float64) + if !ok || id < 1 || id > 9007199254740991 || id != float64(int64(id)) { + return toolError("id must be a positive safe integer") + } + path = strings.ReplaceAll(path, ":id", strconv.FormatInt(int64(id), 10)) + } + query := url.Values{} + if values, ok := args["query"].(map[string]any); ok { + for key, value := range values { + if number, ok := value.(float64); ok { + // REST filters use ParseInt; %v switches large IDs to exponent notation. + query.Set(key, strconv.FormatFloat(number, 'f', -1, 64)) + } else { + query.Set(key, fmt.Sprint(value)) + } + } + } + var body []byte + if value, exists := args["body"]; exists { + var err error + body, err = json.Marshal(value) + if err != nil { + return toolError("Cannot encode tool arguments") + } + } + ctx = context.WithValue(ctx, dispatchKey{}, spec) + req := identity.request.Clone(ctx) + req.Method = spec.Method + req.URL = &url.URL{Path: path, RawQuery: query.Encode()} + req.RequestURI = req.URL.RequestURI() + req.Body = io.NopCloser(bytes.NewReader(body)) + req.ContentLength = int64(len(body)) + // No cookies, browser JWTs, forwarded headers or other credentials enter + // the private router. The outer security IP snapshot remains in context. + req.Header = http.Header{"Content-Type": {"application/json"}, "User-Agent": {identity.request.UserAgent()}} + if key, ok := args["idempotency_key"].(string); ok { + // Scope retries to this credential so another integration cannot replay + // a previous client's cached creation result by guessing its operation ID. + hash := sha256.Sum256([]byte(identity.principal.GrantID + ":" + key)) + req.Header.Set("Idempotency-Key", fmt.Sprintf("mcp-%x", hash)) + } + response := &boundedResponse{header: make(http.Header)} + dispatcher.ServeHTTP(response, req) + if response.overflow { + return toolError("Result exceeds 2 MiB; narrow the query or reduce page_size") + } + if ctx.Err() != nil { + return toolError("MCP operation was cancelled or timed out; check current state before retrying a write") + } + var result any + decoder := json.NewDecoder(bytes.NewReader(response.body.Bytes())) + decoder.UseNumber() + if decoder.Decode(&result) != nil { + 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, "") + 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)}}, + IsError: response.status < 200 || response.status >= 300, + } +} + +func toolError(message string) *mcp.CallToolResult { + return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: message}}} +} + +// The SDK sets no-cache for transport frames; management results may contain a +// newly created key, so force no-store at the actual response boundary. +type noStoreResponse struct{ http.ResponseWriter } + +func (w noStoreResponse) WriteHeader(status int) { + w.Header().Set("Cache-Control", "no-store") + w.ResponseWriter.WriteHeader(status) +} +func (w noStoreResponse) Write(p []byte) (int, error) { + w.Header().Set("Cache-Control", "no-store") + return w.ResponseWriter.Write(p) +} +func (w noStoreResponse) Flush() { + w.Header().Set("Cache-Control", "no-store") + _ = http.NewResponseController(w.ResponseWriter).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 + lower := strings.ToLower(key) + if lower == "key" && (!revealCreatedKey || childPath != "/data/key") { + delete(v, key) + continue + } + if _, sensitive := redactedResultKeys[lower]; sensitive { + delete(v, key) + continue + } + redactResult(child, revealCreatedKey, childPath) + } + case []any: + for _, child := range v { + redactResult(child, false, path+"/[]") + } + } +} + +// boundedResponse captures only a bounded JSON response from the in-process +// router, never a network hop. Writes beyond the cap are discarded. +type boundedResponse struct { + header http.Header + status int + body bytes.Buffer + overflow bool +} + +func (w *boundedResponse) Header() http.Header { return w.header } +func (w *boundedResponse) WriteHeader(status int) { + if w.status == 0 { + w.status = status + } +} +func (w *boundedResponse) Write(p []byte) (int, error) { + if w.status == 0 { + w.status = http.StatusOK + } + if w.body.Len()+len(p) > maxResultBytes { + w.overflow = true + } else if !w.overflow { + _, _ = w.body.Write(p) + } + return len(p), nil +} diff --git a/backend/internal/managementmcp/server_test.go b/backend/internal/managementmcp/server_test.go new file mode 100644 index 0000000000..8767f31143 --- /dev/null +++ b/backend/internal/managementmcp/server_test.go @@ -0,0 +1,445 @@ +package managementmcp + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type testTokenAuth struct { + mu sync.Mutex + principals map[string]*service.MCPPrincipal +} + +func (a *testTokenAuth) Authenticate(_ context.Context, token string) (*service.MCPPrincipal, error) { + a.mu.Lock() + defer a.mu.Unlock() + if p := a.principals[token]; p != nil { + copy := *p + if copy.Resource == "" { + copy.Resource = "https://platform.example/api/v1/mcp" + } + return ©, nil + } + return nil, service.ErrMCPOAuthInvalidToken +} + +func newTestEndpoint(dispatcher http.Handler) (*gin.Engine, *testTokenAuth) { + gin.SetMode(gin.TestMode) + auth := &testTokenAuth{principals: map[string]*service.MCPPrincipal{ + "reader": {UserID: 1, GrantID: "one", Role: service.RoleUser, Scope: service.MCPScopeUser, ReadOnly: true}, + "writer": {UserID: 1, GrantID: "two", Role: service.RoleUser, Scope: service.MCPScopeUser}, + "other": {UserID: 2, GrantID: "three", Role: service.RoleUser, Scope: service.MCPScopeUser}, + "admin": {UserID: 3, GrantID: "four", Role: service.RoleAdmin, Scope: service.MCPScopeAdmin}, + "admin-reader": {UserID: 3, GrantID: "five", Role: service.RoleAdmin, Scope: service.MCPScopeAdmin, ReadOnly: true}, + }} + r := gin.New() + r.Any("/api/v1/mcp", Authenticate(auth, []string{"https://console.example"}, func(context.Context) (string, error) { + return "https://platform.example/api/v1/mcp", nil + }), gin.WrapH(NewHandler(dispatcher, []string{"https://console.example"}))) + return r, auth +} + +func rpc(t *testing.T, handler http.Handler, token, method string, params any) (int, map[string]any) { + t.Helper() + body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) + require.NoError(t, err) + req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("MCP-Protocol-Version", "2025-06-18") + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + var result map[string]any + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result), w.Body.String()) + require.Equal(t, "no-store", w.Header().Get("Cache-Control")) + return w.Code, result +} + +func rpcObject(t *testing.T, value any) map[string]any { + t.Helper() + object, ok := value.(map[string]any) + require.True(t, ok, "expected JSON object, got %T", value) + return object +} + +func toolNames(t *testing.T, result map[string]any) []string { + t.Helper() + var names []string + tools, ok := rpcObject(t, result["result"])["tools"].([]any) + require.True(t, ok) + for _, tool := range tools { + name, ok := rpcObject(t, tool)["name"].(string) + require.True(t, ok) + names = append(names, name) + } + return names +} + +func TestMCPInitializeAndPermissionFilteredDiscovery(t *testing.T) { + r, _ := newTestEndpoint(http.NotFoundHandler()) + status, initialized := rpc(t, r, "reader", "initialize", map[string]any{ + "protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "test", "version": "1"}, + }) + require.Equal(t, 200, status) + require.Equal(t, "sub2api-management", rpcObject(t, rpcObject(t, initialized["result"])["serverInfo"])["name"]) + for _, tc := range []struct { + token string + hasAdmin, hasWrite bool + }{ + {"reader", false, false}, {"writer", false, true}, {"admin", true, true}, {"admin-reader", true, false}, + } { + t.Run(tc.token, func(t *testing.T) { + status, listed := rpc(t, r, tc.token, "tools/list", map[string]any{}) + require.Equal(t, 200, status) + names := toolNames(t, listed) + // Verify the permission boundary, not an exact catalogue size. + require.Contains(t, names, "user_get_profile") + if tc.hasAdmin { + require.Contains(t, names, "admin_get_dashboard") + } else { + require.NotContains(t, names, "admin_get_dashboard") + } + if tc.hasWrite { + require.Contains(t, names, "user_create_api_key") + } else { + require.NotContains(t, names, "user_create_api_key") + } + }) + } +} + +func TestMCPRejectsUnauthorizedToolsAndUnknownArgumentsBeforeDispatch(t *testing.T) { + calls := 0 + r, _ := newTestEndpoint(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ })) + for _, tc := range []struct { + token, name string + args any + }{ + {"reader", "user_create_api_key", map[string]any{"body": map[string]any{"name": "test"}}}, + {"writer", "admin_list_users", map[string]any{}}, + {"writer", "user_get_api_key", map[string]any{"id": "../admin/users"}}, + {"writer", "user_get_api_key", map[string]any{"id": -1}}, + {"writer", "user_list_api_keys", map[string]any{"query": map[string]any{"user_id": 2}}}, + {"writer", "user_list_api_keys", map[string]any{"query": map[string]any{"page_size": 101}}}, + {"writer", "user_create_api_key", map[string]any{"body": map[string]any{"name": "test", "user_id": 2}}}, + {"admin", "admin_update_user", map[string]any{"id": 2, "body": map[string]any{"role": "admin"}}}, + {"admin", "admin_update_account", map[string]any{"id": 2, "body": map[string]any{"credentials": map[string]any{"api_key": "x"}}}}, + } { + _, result := rpc(t, r, tc.token, "tools/call", map[string]any{"name": tc.name, "arguments": tc.args}) + require.Contains(t, result, "error", tc.name) + } + require.Zero(t, calls) +} + +func TestMCPDispatchPreservesOwnershipAndRedactsExistingSecrets(t *testing.T) { + inner := gin.New() + inner.GET("/api/v1/keys/:id", DispatchAuth(false), func(c *gin.Context) { + subject, ok := middleware.GetAuthSubjectFromContext(c) + require.True(t, ok) + require.Empty(t, c.GetHeader("Authorization")) + require.Equal(t, AuthMethod, c.GetString("auth_method")) + if subject.UserID != 1 { + c.JSON(403, gin.H{"message": "Key belongs to another user"}) + return + } + c.JSON(200, gin.H{"data": gin.H{"id": 7, "name": "key name", "key": "existing-secret", "usage": gin.H{"access_token": "nested-secret"}}}) + }) + inner.POST("/api/v1/keys", DispatchAuth(false), func(c *gin.Context) { + c.JSON(201, gin.H{"data": gin.H{"id": 8, "key": "new-secret", "group": gin.H{"key": "unrelated-secret"}}}) + }) + r, auth := newTestEndpoint(inner) + for _, token := range []string{"writer", "other"} { + _, result := rpc(t, r, token, "tools/call", map[string]any{"name": "user_get_api_key", "arguments": map[string]any{"id": 7}}) + encoded, _ := json.Marshal(result) + require.NotContains(t, string(encoded), "existing-secret") + require.NotContains(t, string(encoded), "nested-secret") + if token == "other" { + require.Equal(t, true, rpcObject(t, result["result"])["isError"]) + } else { + require.Contains(t, string(encoded), "key name") + } + } + _, created := rpc(t, r, "writer", "tools/call", map[string]any{"name": "user_create_api_key", "arguments": map[string]any{"idempotency_key": "create-test-1", "body": map[string]any{"name": "created"}}}) + encoded, _ := json.Marshal(created) + require.Contains(t, string(encoded), "new-secret") + require.NotContains(t, string(encoded), "unrelated-secret") + // Tokens are verified on every HTTP request, including after initialization. + auth.mu.Lock() + delete(auth.principals, "writer") + auth.mu.Unlock() + status, _ := rpc(t, r, "writer", "tools/list", map[string]any{}) + require.Equal(t, 401, status) +} + +func TestMCPDispatchAuthCannotBeForgedOrUsedForAnotherRoute(t *testing.T) { + inner := gin.New() + inner.GET("/api/v1/user/mcp/grants", DispatchAuth(false), func(c *gin.Context) { t.Error("unexpected credential access") }) + req := httptest.NewRequest("GET", "/api/v1/user/mcp/grants", nil) + req.Header.Set("Authorization", "Bearer writer") + w := httptest.NewRecorder() + inner.ServeHTTP(w, req) + require.Equal(t, 403, w.Code) + identity := &authenticatedRequest{principal: &service.MCPPrincipal{UserID: 1, Scope: "user"}, request: req} + ctx := context.WithValue(req.Context(), requestKey{}, identity) + ctx = context.WithValue(ctx, dispatchKey{}, ToolSpec{Path: "/api/v1/user/profile", Method: "GET", ReadOnly: true}) + w = httptest.NewRecorder() + inner.ServeHTTP(w, req.WithContext(ctx)) + require.Equal(t, 403, w.Code) +} + +func TestMCPPreservesLargeIntegerQueryFilters(t *testing.T) { + var observed string + r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + observed = r.URL.Query().Get("group_id") + _, _ = w.Write([]byte(`{"data":[]}`)) + })) + _, result := rpc(t, r, "writer", "tools/call", map[string]any{"name": "user_list_api_keys", "arguments": map[string]any{"query": map[string]any{"group_id": 12345678}}}) + require.NotContains(t, result, "error") + require.Equal(t, "12345678", observed) +} + +func TestMCPAccountStatusFiltersMatchManagementAPI(t *testing.T) { + gin.SetMode(gin.TestMode) + var observed []string + inner := gin.New() + inner.GET("/api/v1/admin/accounts", DispatchAuth(true), func(c *gin.Context) { + observed = append(observed, c.Query("status")) + c.JSON(http.StatusOK, gin.H{"data": []any{}}) + }) + r, _ := newTestEndpoint(inner) + for _, status := range []string{"active", "inactive", "error", "rate_limited", "temp_unschedulable", "unschedulable"} { + t.Run(status, func(t *testing.T) { + before := len(observed) + _, result := rpc(t, r, "admin-reader", "tools/call", map[string]any{ + "name": "admin_list_accounts", "arguments": map[string]any{"query": map[string]any{"status": status}}, + }) + require.NotContains(t, result, "error") + require.Len(t, observed, before+1) + require.Equal(t, status, observed[before]) + }) + } + t.Run("reject unsupported overloaded filter", func(t *testing.T) { + before := len(observed) + _, result := rpc(t, r, "admin-reader", "tools/call", map[string]any{ + "name": "admin_list_accounts", "arguments": map[string]any{"query": map[string]any{"status": "overloaded"}}, + }) + require.Contains(t, result, "error") + require.Len(t, observed, before, "unsupported status must be rejected before dispatch") + }) +} + +func TestMCPIdempotencyKeysAreRequiredAndIsolatedPerCredential(t *testing.T) { + var keys []string + r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + keys = append(keys, r.Header.Get("Idempotency-Key")) + _, _ = w.Write([]byte(`{"data":{}}`)) + })) + args := map[string]any{"body": map[string]any{"name": "created"}} + _, missing := rpc(t, r, "writer", "tools/call", map[string]any{"name": "user_create_api_key", "arguments": args}) + require.Contains(t, missing, "error") + require.Empty(t, keys) + args["idempotency_key"] = "intent-123" + for _, token := range []string{"writer", "writer", "other"} { + _, result := rpc(t, r, token, "tools/call", map[string]any{"name": "user_create_api_key", "arguments": args}) + require.NotContains(t, result, "error") + } + require.Len(t, keys, 3) + require.NotEmpty(t, keys[0]) + require.Equal(t, keys[0], keys[1]) + require.NotEqual(t, keys[0], keys[2]) +} + +func TestMCPOriginAuthenticationAndRequestLimits(t *testing.T) { + r, _ := newTestEndpoint(http.NotFoundHandler()) + for _, tc := range []struct { + origin, token string + size, status int + }{ + {"https://attacker.example", "reader", 0, 403}, {"null", "reader", 0, 403}, + {"https://console.example", "invalid", 0, 401}, {"", "", 0, 401}, + {"https://platform.example", "reader", maxRequestBytes + 1, 413}, + } { + req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(strings.Repeat("x", tc.size))) + req.Header.Set("Origin", tc.origin) + if tc.token != "" { + req.Header.Set("Authorization", "Bearer "+tc.token) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, tc.status, w.Code, tc.origin) + } + for _, method := range []string{"GET", "DELETE"} { + req := httptest.NewRequest(method, "http://platform.example/api/v1/mcp", nil) + req.Header.Set("Authorization", "Bearer reader") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 405, w.Code) + } +} + +// The SDK's own cross-origin and Content-Type checks must agree with +// Authenticate: allowlisted browser origins and JSON with parameters succeed. +func TestMCPTransportAcceptsAuthenticatedOriginsAndJSONMediaTypes(t *testing.T) { + r, _ := newTestEndpoint(http.NotFoundHandler()) + body := `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}` + for _, tc := range []struct { + name, origin, site, contentType string + status int + }{ + {"native", "", "", "application/json", 200}, + {"same host", "https://platform.example", "same-origin", "application/json", 200}, + {"allowlisted origin", "https://console.example", "cross-site", "application/json", 200}, + {"allowlisted origin without fetch metadata", "https://console.example", "", "application/json", 200}, + {"unlisted origin", "https://attacker.example", "cross-site", "application/json", 403}, + {"json with charset", "", "", "application/json; charset=utf-8", 200}, + {"text body", "", "", "text/plain", 415}, + {"form body", "", "", "application/x-www-form-urlencoded", 415}, + } { + req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer reader") + req.Header.Set("Content-Type", tc.contentType) + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("MCP-Protocol-Version", "2025-06-18") + if tc.origin != "" { + req.Header.Set("Origin", tc.origin) + } + if tc.site != "" { + req.Header.Set("Sec-Fetch-Site", tc.site) + } + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, tc.status, w.Code, "%s: %s", tc.name, w.Body.String()) + } +} + +func TestMCPResultLimitAndCancellation(t *testing.T) { + r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(strings.Repeat("x", maxResultBytes+1))) + })) + _, result := rpc(t, r, "reader", "tools/call", map[string]any{"name": "user_get_profile", "arguments": map[string]any{}}) + require.Equal(t, true, rpcObject(t, result["result"])["isError"]) + + started, finished := make(chan struct{}), make(chan struct{}) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + original := httptest.NewRequest("POST", "/api/v1/mcp", nil).WithContext(ctx) + identity := &authenticatedRequest{principal: &service.MCPPrincipal{UserID: 1, Scope: "user"}, request: original} + // Simulate an SDK context detached from the HTTP lifetime. + detached := context.WithValue(context.Background(), requestKey{}, identity) + go func() { + defer close(finished) + executeTool(detached, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + }), ToolSpec{Path: "/api/v1/user/profile", Method: "GET", ReadOnly: true}, nil) + }() + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("dispatcher did not start") + } + cancel() + select { + case <-finished: + case <-time.After(time.Second): + 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) + text, ok := rpcObject(t, content[0])["text"].(string) + require.True(t, ok) + require.JSONEq(t, `{"http_status":200,"result":{"data":{"name":"ok"}}}`, text) + + // Under the capture limit as received, but HTML escaping expands it 6x. + payload = `{"data":"` + strings.Repeat("<", maxResultBytes/3) + `"}` + _, 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/pkg/adminaccess/catalog.go b/backend/internal/pkg/adminaccess/catalog.go index d8dbe44b55..75f9d0cc99 100644 --- a/backend/internal/pkg/adminaccess/catalog.go +++ b/backend/internal/pkg/adminaccess/catalog.go @@ -1,6 +1,9 @@ package adminaccess -import "slices" +import ( + "slices" + "strings" +) type Permission struct { ID string `json:"id"` @@ -17,6 +20,18 @@ type permissionDefinition struct { // 接口按方法和 Gin 完整路径精确登记;新增接口不会继承同目录权限。 // 全站权限与账户规则独立,选中分组绝不会隐式授予全站操作。 var definitions = []permissionDefinition{ + {Permission{"accounts.identity.read", "读取账户邮箱、套餐及创建时间(不含令牌)", "账户", "account"}, []string{"GET /accounts/:id"}}, + {Permission{"accounts.usage.read", "读取及主动刷新授权账户额度与快照", "账户", "account"}, []string{"GET /accounts/:id/usage", "POST /accounts/usage/batch"}}, + {Permission{"accounts.stats.read", "读取账户用量与费用统计", "账户", "account"}, []string{"GET /accounts/:id/today-stats", "POST /accounts/today-stats/batch", "GET /accounts/:id/stats"}}, + {Permission{"openai.quota.read", "查询 OpenAI 上游额度与重置次数", "OpenAI", "account"}, []string{"GET /openai/accounts/:id/quota", "POST /openai/accounts/:id/quota/refresh"}}, + {Permission{"openai.quota.reset", "消耗 OpenAI 重置次数恢复额度", "OpenAI", "account"}, []string{"POST /openai/accounts/:id/reset-quota"}}, + {Permission{"openai.referrals.read", "查询 OpenAI 邀请资格与次数", "OpenAI", "account"}, []string{"POST /openai/accounts/:id/referrals/refresh"}}, + {Permission{"openai.referrals.invite", "发送 OpenAI 邀请邮件", "OpenAI", "account"}, []string{"POST /openai/accounts/:id/referrals/invite"}}, + {Permission{"accounts.options.write", "写入 OpenAI OAuth 身份与连接选项", "账户", "account"}, []string{"POST /accounts"}}, + {Permission{"accounts.rate.write", "设置账户计费倍率", "账户", "account"}, []string{"POST /accounts", "PUT /accounts/:id"}}, + {Permission{"groups.list.read", "读取所选分组基本信息(名称、平台、状态)", "分组", "group"}, []string{"GET /groups", "GET /groups/all", "GET /groups/:id"}}, + {Permission{"groups.capacity.read", "读取所选分组容量(整个分组,不按账户类型过滤)", "分组", "group"}, []string{"GET /groups/capacity-summary"}}, + {Permission{"openai.tokens.refresh", "刷新调用方提供的 OpenAI 令牌(返回令牌,可使用所选代理)", "OAuth", "global"}, []string{"POST /openai/refresh-token"}}, {Permission{"accounts.read", "查看账户(脱敏)", "账户", "account"}, []string{"GET /accounts", "GET /accounts/:id", "GET /accounts/:id/models"}}, {Permission{"accounts.create", "创建账户", "账户", "account"}, []string{"POST /accounts", "POST /accounts/import/codex-session"}}, {Permission{"accounts.update", "编辑名称与备注", "账户", "account"}, []string{"PUT /accounts/:id"}}, @@ -77,6 +92,9 @@ func PermissionCatalog() []Permission { // RouteAllowed 只检查动作准入;账户资源及字段必须再由专用处理器检查。 func RouteAllowed(policy Policy, method, path string) bool { + if policy.FullAccess { + return strings.HasPrefix(path, "/api/v1/admin/") && !strings.HasPrefix(path, "/api/v1/admin/settings/admin-api-key") + } target := method + " " + path for _, definition := range definitions { matched := false diff --git a/backend/internal/pkg/adminaccess/catalog_permissions_test.go b/backend/internal/pkg/adminaccess/catalog_permissions_test.go new file mode 100644 index 0000000000..ce167a577d --- /dev/null +++ b/backend/internal/pkg/adminaccess/catalog_permissions_test.go @@ -0,0 +1,20 @@ +package adminaccess + +import "testing" + +func TestScopedPermissionCatalogRequiresExplicitGrant(t *testing.T) { + for _, id := range []string{"accounts.identity.read", "accounts.usage.read", "accounts.options.write", "accounts.rate.write", "groups.list.read", "groups.capacity.read", "openai.tokens.refresh"} { + found := false + for _, entry := range PermissionCatalog() { + if entry.ID == id { + found = true + } + } + if !found { + t.Errorf("权限未登记: %s", id) + } + } + if RouteAllowed(Policy{}, "POST", "/api/v1/admin/openai/refresh-token") { + t.Fatal("旧策略不得继承新增权限") + } +} diff --git a/backend/internal/pkg/adminaccess/catalog_statistics_test.go b/backend/internal/pkg/adminaccess/catalog_statistics_test.go new file mode 100644 index 0000000000..42f24770b9 --- /dev/null +++ b/backend/internal/pkg/adminaccess/catalog_statistics_test.go @@ -0,0 +1,31 @@ +package adminaccess + +import "testing" + +func TestStatisticsAndOpenAIPermissions(t *testing.T) { + for action, routes := range map[string][]string{ + "accounts.stats.read": {"GET /accounts/:id/today-stats", "POST /accounts/today-stats/batch", "GET /accounts/:id/stats"}, + "accounts.usage.read": {"POST /accounts/usage/batch"}, + "openai.quota.read": {"GET /openai/accounts/:id/quota", "POST /openai/accounts/:id/quota/refresh"}, + "openai.quota.reset": {"POST /openai/accounts/:id/reset-quota"}, + "openai.referrals.read": {"POST /openai/accounts/:id/referrals/refresh"}, + "openai.referrals.invite": {"POST /openai/accounts/:id/referrals/invite"}, + } { + p := Policy{Rules: []Rule{{Permissions: []string{action}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}} + if err := ValidatePolicy(p); err != nil { + t.Errorf("%s: %v", action, err) + } + for _, route := range routes { + var method, path string + for i, c := range route { + if c == ' ' { + method, path = route[:i], route[i+1:] + break + } + } + if !RouteAllowed(p, method, "/api/v1/admin"+path) { + t.Errorf("%s 无法进入 %s", action, route) + } + } + } +} diff --git a/backend/internal/pkg/adminaccess/full_access_test.go b/backend/internal/pkg/adminaccess/full_access_test.go new file mode 100644 index 0000000000..28ac97467a --- /dev/null +++ b/backend/internal/pkg/adminaccess/full_access_test.go @@ -0,0 +1,32 @@ +//go:build unit + +package adminaccess + +import ( + "encoding/json" + "testing" +) + +func TestAdminFullAccessRouteBoundary(t *testing.T) { + var policy Policy + if err := json.Unmarshal([]byte(`{"full_access":true}`), &policy); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + path string + allowed bool + }{ + {"/api/v1/admin/future-operation", true}, + {"/api/v1/admin/accounts/:id", true}, + {"/api/v1/admin/settings/admin-api-keys", false}, + {"/api/v1/admin/settings/admin-api-keys/:id/rotate", false}, + {"/api/v1/admin/settings/admin-api-key/regenerate", false}, + {"/api/v1/user/profile", false}, + {"/v1/messages", false}, + {"", false}, + } { + if got := RouteAllowed(policy, "POST", tc.path); got != tc.allowed { + t.Errorf("%s: got %v want %v", tc.path, got, tc.allowed) + } + } +} diff --git a/backend/internal/pkg/adminaccess/policy.go b/backend/internal/pkg/adminaccess/policy.go index 2eaf07b5ed..b4232f67db 100644 --- a/backend/internal/pkg/adminaccess/policy.go +++ b/backend/internal/pkg/adminaccess/policy.go @@ -18,6 +18,7 @@ type Rule struct { } type Policy struct { + FullAccess bool `json:"full_access,omitempty"` Rules []Rule `json:"rules"` GlobalPermissions []string `json:"global_permissions"` } @@ -47,6 +48,16 @@ func FromContext(ctx context.Context) *Principal { return principal } +// RestrictedFromContext 只返回需要资源限制和响应裁剪的密钥。 +// 全权密钥仍保留原 Principal,供审计、限流和幂等隔离使用。 +func RestrictedFromContext(ctx context.Context) *Principal { + principal := FromContext(ctx) + if principal != nil && !principal.Policy.FullAccess { + return principal + } + return nil +} + // Matches 保持分组、类型和平台在同一规则中匹配,不拆开合并授权条件。 func (r Rule) Matches(a Account) bool { if !slices.Contains(r.AccountTypes, a.Type) || (len(r.Platforms) > 0 && !slices.Contains(r.Platforms, a.Platform)) { diff --git a/backend/internal/pkg/antigravity/attribution_test.go b/backend/internal/pkg/antigravity/attribution_test.go index 79cc3c7ab3..1eee227383 100644 --- a/backend/internal/pkg/antigravity/attribution_test.go +++ b/backend/internal/pkg/antigravity/attribution_test.go @@ -27,6 +27,22 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { {"different field", "x-anthropic-billing-header-extra: keep", "x-anthropic-billing-header-extra: keep"}, {"quoted within instructions", "Explain this metadata: " + attribution, "Explain this metadata: " + attribution}, {"later line", "Example:\n" + attribution, "Example:\n" + attribution}, + {"Codex GPT 5", "You are Codex, based on GPT-5. Keep GPT-5 model ids.", "You are an AI agent. Keep GPT-5 model ids."}, + {"Codex GPT 5.6", "You are Codex, a coding agent based on GPT-5.6.\nKeep indentation.", "You are an AI agent.\nKeep indentation."}, + {"Codex GPT 6", "You are Codex, based on GPT-6.", "You are an AI agent."}, + {"Codex GPT 6 agent", "You are Codex, an agent based on GPT-6. Rest.", "You are an AI agent. Rest."}, + {"CLI comma", "You are GPT-5.6 running in the Codex CLI, a terminal-based coding assistant.", "You are an AI agent, a terminal-based coding assistant."}, + {"Codex model suffix", "You are Codex, based on GPT-5.6-Codex. Rest.", "You are an AI agent. Rest."}, + {"CLI GPT 5.6", "You are GPT-5.6 running in the Codex CLI. Rest.", "You are an AI agent. Rest."}, + {"CLI GPT 6", " \nYou are GPT-6 running in the Codex CLI\nRest.", "You are an AI agent.\nRest."}, + {"Claude CLI", "You are Claude Code, Anthropic's official CLI for Claude. Rest.", "You are an AI agent. Rest."}, + {"Claude SDK", "You are a Claude agent, built on Anthropic's Claude Agent SDK. Rest.", "You are an AI agent. Rest."}, + {"attribution before GPT", attribution + "\r\nYou are Codex, based on GPT-6. Rest.", "You are an AI agent. Rest."}, + {"quoted GPT", `"You are Codex, based on GPT-6."`, `"You are Codex, based on GPT-6."`}, + {"later GPT", "Example:\nYou are GPT-6 running in the Codex CLI.", "Example:\nYou are GPT-6 running in the Codex CLI."}, + {"vendor mentions", "Use OpenAI GPT-5.6 and Anthropic Claude; preserve gpt-6.", "Use OpenAI GPT-5.6 and Anthropic Claude; preserve gpt-6."}, + {"not identity", "You are Codex, do not claim to be based on GPT-6.", "You are Codex, do not claim to be based on GPT-6."}, + {"model token boundary", "You are Codex, based on GPT-6example.", "You are Codex, based on GPT-6example."}, } for _, tt := range tests { for _, arrayForm := range []bool{false, true} { @@ -39,12 +55,13 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { t.Run(name, func(t *testing.T) { systemJSON, err := json.Marshal(system) require.NoError(t, err) - userJSON, err := json.Marshal(attribution) + userText := strings.TrimSpace(tt.text) + userJSON, err := json.Marshal(userText) require.NoError(t, err) input := &ClaudeRequest{ Model: "gemini-3.8-flash-high", System: systemJSON, Messages: []ClaudeMessage{{Role: "user", Content: userJSON}}, - Tools: []ClaudeTool{{Name: "example", Description: attribution, + Tools: []ClaudeTool{{Name: "example", Description: tt.text, InputSchema: map[string]any{"type": "object", "properties": map[string]any{"query": map[string]any{"type": "string"}}}}}, } before, err := json.Marshal(input) @@ -68,8 +85,8 @@ func TestTransformClaudeToGemini_AttributionSystemText(t *testing.T) { } require.Equal(t, want, texts) // The same literal text in user content and tool descriptions is not metadata. - require.Equal(t, attribution, got.Request.Contents[0].Parts[0].Text) - require.Equal(t, attribution, got.Request.Tools[0].FunctionDeclarations[0].Description) + require.Equal(t, userText, got.Request.Contents[0].Parts[0].Text) + require.Equal(t, tt.text, got.Request.Tools[0].FunctionDeclarations[0].Description) after, err := json.Marshal(input) require.NoError(t, err) require.JSONEq(t, string(before), string(after), "do not mutate the incoming request") @@ -124,7 +141,7 @@ func TestNeutralizeClaudeIdentity(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.want, neutralizeClaudeIdentity(tt.text)) + require.Equal(t, tt.want, NeutralizeSystemIdentity(tt.text)) }) } } @@ -135,7 +152,7 @@ func TestAttributionAndIdentityTogether(t *testing.T) { attribution := "x-anthropic-billing-header: cc_version=2.1.278.0a9; cc_entrypoint=claude-vscode;" identity := "You are a Claude agent, built on Anthropic's Claude Agent SDK." require.Equal(t, "", stripClaudeAttribution(attribution)) - require.Equal(t, "You are an AI agent.", neutralizeClaudeIdentity(identity)) + require.Equal(t, "You are an AI agent.", NeutralizeSystemIdentity(identity)) } // End-to-end through the transformer: the attribution block and the identity diff --git a/backend/internal/pkg/antigravity/request_transformer.go b/backend/internal/pkg/antigravity/request_transformer.go index a13748926e..ea6717ccd9 100644 --- a/backend/internal/pkg/antigravity/request_transformer.go +++ b/backend/internal/pkg/antigravity/request_transformer.go @@ -294,27 +294,28 @@ func filterOpenCodePrompt(text string) string { return "" } -// stripClaudeAttribution removes the leading Claude Code attribution metadata line -// from Antigravity system text. This is prompt metadata, not an HTTP header; it -// can trigger RESOURCE_EXHAUSTED on the Google upstream. Keep this scoped to the -// Antigravity transformer: native Anthropic OAuth may require the attribution. -// claudeIdentityOpeners 是部分 Anthropic 客户端放在系统块开头的 Claude Agent SDK 身份语句。 -// 仅移除 x-anthropic-billing-header 行还不够:如果系统文本仍以这些语句开头, -// Google 上游仍会返回 429 RESOURCE_EXHAUSTED。 -// // The patterns are anchored at the start of a system block on purpose, so user -// instructions that merely mention Claude or Anthropic are left untouched. -var claudeIdentityOpeners = []*regexp.Regexp{ +// instructions that merely mention Claude, GPT or their vendors are left untouched. +var systemIdentityOpeners = []*regexp.Regexp{ regexp.MustCompile(`(?i)^[ \t\r\n]*You are a Claude agent, built on Anthropic'?s Claude Agent SDK\.?`), regexp.MustCompile(`(?i)^[ \t\r\n]*You are Claude Code, Anthropic'?s official CLI for Claude\.?`), + regexp.MustCompile(`(?i)^[ \t\r\n]*You are Codex,? (?:a coding agent |an agent )?based on GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)*\.?`), + regexp.MustCompile(`(?i)^[ \t\r\n]*You are GPT-[0-9]+(?:\.[0-9]+)*(?:-[a-z0-9]+)* running in the Codex CLI\.?`), } -// neutralizeClaudeIdentity rewrites a leading vendor identity sentence into a -// vendor-neutral one. It keeps the rest of the block, including any user -// instructions that follow. -func neutralizeClaudeIdentity(text string) string { - for _, re := range claudeIdentityOpeners { +// NeutralizeSystemIdentity removes leading client attribution and rewrites a +// leading vendor identity sentence, preserving the rest of the system block. +// Only Antigravity forwarding should use this; native Anthropic may require attribution. +func NeutralizeSystemIdentity(text string) string { + text = stripClaudeAttribution(text) + for _, re := range systemIdentityOpeners { if loc := re.FindStringIndex(text); loc != nil { + if strings.HasPrefix(text[loc[1]:], ",") { + return "You are an AI agent" + text[loc[1]:] + } + if loc[1] < len(text) && !strings.ContainsAny(text[loc[1]:loc[1]+1], " \t\r\n") { + continue + } return "You are an AI agent." + text[loc[1]:] } } @@ -349,7 +350,7 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans // 尝试解析为字符串 var sysStr string if err := json.Unmarshal(system, &sysStr); err == nil { - sysStr = neutralizeClaudeIdentity(stripClaudeAttribution(sysStr)) + sysStr = NeutralizeSystemIdentity(sysStr) if strings.TrimSpace(sysStr) != "" { if strings.Contains(sysStr, "You are Antigravity") { userHasAntigravityIdentity = true @@ -365,7 +366,7 @@ func buildSystemInstruction(system json.RawMessage, modelName string, opts Trans var sysBlocks []SystemBlock if err := json.Unmarshal(system, &sysBlocks); err == nil { for _, block := range sysBlocks { - block.Text = neutralizeClaudeIdentity(stripClaudeAttribution(block.Text)) + block.Text = NeutralizeSystemIdentity(block.Text) if block.Type == "text" && strings.TrimSpace(block.Text) != "" { if strings.Contains(block.Text, "You are Antigravity") { userHasAntigravityIdentity = true diff --git a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go index 2e7c85d3c9..e29bcdeaf9 100644 --- a/backend/internal/pkg/apicompat/anthropic_to_responses_response.go +++ b/backend/internal/pkg/apicompat/anthropic_to_responses_response.go @@ -198,6 +198,10 @@ type AnthropicEventToResponsesState struct { CurrentSummary string // reasoning CurrentThinking AnthropicContentBlock PreserveThinkingSignatures bool + textAccumBuffer *strings.Builder + currentArgsBuffer *strings.Builder + currentSummaryBuffer *strings.Builder + currentSignatureBuffer *strings.Builder // PendingToolInput holds tool arguments that arrived complete on // content_block_start instead of as input_json_delta. It is only consumed at @@ -332,6 +336,8 @@ func anthToResHandleContentBlockStart(evt *AnthropicStreamEvent, state *Anthropi state.CurrentItemType = "reasoning" state.CurrentThinking = *evt.ContentBlock state.CurrentSummary = evt.ContentBlock.Thinking + state.currentSummaryBuffer = nil + state.currentSignatureBuffer = nil state.ContentIndex = 0 events = append(events, makeResponsesEvent(state, "response.output_item.added", &ResponsesStreamEvent{ @@ -380,6 +386,7 @@ func anthToResHandleContentBlockStart(evt *AnthropicStreamEvent, state *Anthropi Part: &ResponsesContentPart{Type: "output_text", Text: ""}, })) state.TextAccum = "" + state.textAccumBuffer = nil case "tool_use": // Close previous item if any @@ -421,7 +428,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi if evt.Delta.Text == "" { return nil } - state.TextAccum += evt.Delta.Text + state.TextAccum = appendStreamString(&state.textAccumBuffer, state.TextAccum, evt.Delta.Text) return []ResponsesStreamEvent{makeResponsesEvent(state, "response.output_text.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, ContentIndex: state.ContentIndex, @@ -433,7 +440,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi if evt.Delta.Thinking == "" { return nil } - state.CurrentSummary += evt.Delta.Thinking + state.CurrentSummary = appendStreamString(&state.currentSummaryBuffer, state.CurrentSummary, evt.Delta.Thinking) return []ResponsesStreamEvent{makeResponsesEvent(state, "response.reasoning_summary_text.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, SummaryIndex: 0, @@ -448,7 +455,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi // A real delta supersedes whatever content_block_start carried; keeping // both would splice two complete JSON documents together. state.PendingToolInput = "" - state.CurrentArgs += evt.Delta.PartialJSON + state.CurrentArgs = appendStreamString(&state.currentArgsBuffer, state.CurrentArgs, evt.Delta.PartialJSON) return []ResponsesStreamEvent{makeResponsesEvent(state, "response.function_call_arguments.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, Delta: evt.Delta.PartialJSON, @@ -460,7 +467,7 @@ func anthToResHandleContentBlockDelta(evt *AnthropicStreamEvent, state *Anthropi case "signature_delta": // Keep signatures in the opaque bridge envelope, never in visible text. if state.PreserveThinkingSignatures { - state.CurrentThinking.Signature += evt.Delta.Signature + state.CurrentThinking.Signature = appendStreamString(&state.currentSignatureBuffer, state.CurrentThinking.Signature, evt.Delta.Signature) } return nil } @@ -489,6 +496,7 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic // the done event below still repeats exactly what the deltas streamed. if state.CurrentArgs == "" && state.PendingToolInput != "" { state.CurrentArgs = state.PendingToolInput + state.currentArgsBuffer = nil events = append(events, makeResponsesEvent(state, "response.function_call_arguments.delta", &ResponsesStreamEvent{ OutputIndex: state.OutputIndex, Delta: state.PendingToolInput, @@ -521,6 +529,7 @@ func anthToResHandleContentBlockStop(evt *AnthropicStreamEvent, state *Anthropic // item itself stays open since more blocks may follow. text := state.TextAccum state.TextAccum = "" + state.textAccumBuffer = nil contentIndex := state.ContentIndex state.CurrentContent = append(state.CurrentContent, ResponsesContentPart{Type: "output_text", Text: text}) // 关掉一个 part 就推进 content_index:上面那句注释说的「item 保持打开, @@ -648,10 +657,14 @@ func closeCurrentResponsesItem(state *AnthropicEventToResponsesState) []Response state.CurrentName = "" state.CurrentContent = nil state.CurrentArgs = "" + state.currentArgsBuffer = nil state.PendingToolInput = "" state.CurrentSummary = "" + state.currentSummaryBuffer = nil state.CurrentThinking = AnthropicContentBlock{} + state.currentSignatureBuffer = nil state.TextAccum = "" + state.textAccumBuffer = nil state.OutputIndex++ state.ContentIndex = 0 diff --git a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go index 20a590c1c6..29b5bbbe17 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_anthropic_bridge.go @@ -577,7 +577,7 @@ type ChatCompletionsToAnthropicStreamState struct { toolAnnounced map[int]bool toolName map[int]string pendingToolCallID map[int]string - pendingToolArgs map[int]string + pendingToolArgs map[int]*strings.Builder // Reasoning (DeepSeek-style): reasoning_content streamed before content. // No separate reasoning block index — it uses ContentBlockIndex like the @@ -606,7 +606,7 @@ func NewChatCompletionsToAnthropicStreamState(model string) *ChatCompletionsToAn toolAnnounced: make(map[int]bool), toolName: make(map[int]string), pendingToolCallID: make(map[int]string), - pendingToolArgs: make(map[int]string), + pendingToolArgs: make(map[int]*strings.Builder), } } @@ -841,7 +841,12 @@ func handleCCAnthropicToolCall(state *ChatCompletionsToAnthropicStreamState, too }, }) } else { - state.pendingToolArgs[idx] += toolCall.Function.Arguments + buffer := state.pendingToolArgs[idx] + if buffer == nil { + buffer = &strings.Builder{} + state.pendingToolArgs[idx] = buffer + } + _, _ = buffer.WriteString(toolCall.Function.Arguments) } } @@ -872,7 +877,8 @@ func announceCCAnthropicToolBlock(state *ChatCompletionsToAnthropicStreamState, Input: json.RawMessage("{}"), }, }} - if pending := state.pendingToolArgs[idx]; pending != "" { + if buffer := state.pendingToolArgs[idx]; buffer != nil && buffer.Len() > 0 { + pending := buffer.String() delete(state.pendingToolArgs, idx) state.CurrentToolHadDelta = true events = append(events, AnthropicStreamEvent{ diff --git a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go index ff3234b277..ac7472e778 100644 --- a/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go +++ b/backend/internal/pkg/apicompat/chatcompletions_responses_bridge.go @@ -584,7 +584,7 @@ func buildChatMessagesFromItems(messages []ChatMessage, rawItems []json.RawMessa // input_text 是信封(消息类型、任务名、发送者),正文放在 encrypted_content 片段里 // (自定义 provider 下为明文)。chat 上游没有对应条目,按原顺序拼成一条 user 消息, // 否则子智能体收不到任务却仍返回 200。 - text := agentMessageText(item["content"]) + text := AgentMessageText(item["content"]) if text == "" { pendingReasoning = "" continue @@ -653,8 +653,9 @@ func buildChatMessagesFromItems(messages []ChatMessage, rawItems []json.RawMessa return messages, mediaByCallID, nil } -// agentMessageText 按原顺序拼接 agent_message 里 input_text 与 encrypted_content 片段的文本。 -func agentMessageText(raw json.RawMessage) string { +// AgentMessageText concatenates agent_message text and plaintext encrypted_content +// parts in their original order without attempting to decrypt their contents. +func AgentMessageText(raw json.RawMessage) string { raw = bytesTrimSpace(raw) if len(raw) == 0 || string(raw) == "null" { return "" @@ -1593,9 +1594,10 @@ type ChatCompletionsToResponsesStreamState struct { Reasoning strings.Builder // Tool-call lifecycle, keyed by the upstream tool_call index. - ToolCalls map[int]*ChatToolCall - ToolItemIDs map[int]string - ToolOutputIndex map[int]int + ToolCalls map[int]*ChatToolCall + ToolItemIDs map[int]string + ToolOutputIndex map[int]int + toolArgumentBuffers map[int]*strings.Builder // CustomTools 是客户端请求中 custom/freeform 工具的名字集合(见 // CustomToolNames)。命中的调用按 custom_tool_call 生命周期下发,codex 才能 @@ -1755,7 +1757,7 @@ func ChatCompletionsChunkToResponsesEvents( // emitted delta and the stored value stay in sync. Some upstreams // (e.g. GLM/Zhipu) pack id+name+arguments into the first tool_call // chunk; without this reset the first chunk's arguments would be - // counted twice (once from this copy, once from the += below), + // counted twice (once from this copy, once from the append below), // producing a doubled, invalid JSON like {"a":1}{"a":1}. copyCall.Function.Arguments = "" state.ToolCalls[idx] = ©Call @@ -1772,7 +1774,7 @@ func ChatCompletionsChunkToResponsesEvents( } events = append(events, announceChatToolItem(state, idx, stored, false)...) if toolCall.Function.Arguments != "" { - stored.Function.Arguments += toolCall.Function.Arguments + stored.Function.Arguments = appendIndexedStreamString(&state.toolArgumentBuffers, idx, stored.Function.Arguments, toolCall.Function.Arguments) // 未宣告(名字未到)时仅累积,宣告时统一补发;custom 调用的 // arguments 是包裹 input 的 JSON 片段,无法增量还原为自由文本 // 输入,缓冲整份 arguments 收尾时一次性下发(见 closeChatToolItems); diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 424affde73..976d01de8b 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -182,12 +182,14 @@ type ResponsesEventToAnthropicState struct { MessageStartSent bool MessageStopSent bool - ContentBlockIndex int - ContentBlockOpen bool - CurrentBlockType string // "text" | "thinking" | "tool_use" - CurrentToolName string - CurrentToolArgs string - CurrentToolHadDelta bool + ContentBlockIndex int + ContentBlockOpen bool + CurrentBlockType string // "text" | "thinking" | "tool_use" + CurrentToolName string + CurrentToolArgs string + CurrentToolHadDelta bool + currentToolArgsBuffer *strings.Builder + currentToolArgsValidation *streamStringBytes // PendingThinkingSignature is filled from reasoning.encrypted_content and // emitted as signature_delta before the thinking block is closed. PendingThinkingSignature string @@ -361,6 +363,8 @@ func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE state.CurrentBlockType = "tool_use" state.CurrentToolName = evt.Item.Name state.CurrentToolArgs = "" + state.currentToolArgsBuffer = nil + state.currentToolArgsValidation = nil state.CurrentToolHadDelta = false state.HasToolCall = true @@ -501,8 +505,9 @@ func resToAnthHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve } if state.CurrentBlockType == "tool_use" && state.CurrentToolName == "Read" { - state.CurrentToolArgs += evt.Delta - if state.CurrentToolHadDelta || !json.Valid([]byte(state.CurrentToolArgs)) { + previousArgs := state.CurrentToolArgs + state.CurrentToolArgs = appendStreamString(&state.currentToolArgsBuffer, state.CurrentToolArgs, evt.Delta) + if state.CurrentToolHadDelta || !json.Valid(appendStreamStringBytes(&state.currentToolArgsValidation, previousArgs, state.CurrentToolArgs, evt.Delta)) { return nil } @@ -805,6 +810,8 @@ func closeCurrentBlock(state *ResponsesEventToAnthropicState) []AnthropicStreamE state.ContentBlockIndex++ state.CurrentToolName = "" state.CurrentToolArgs = "" + state.currentToolArgsBuffer = nil + state.currentToolArgsValidation = nil state.CurrentToolHadDelta = false events = append(events, AnthropicStreamEvent{ Type: "content_block_stop", diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index 2b8f2b8117..0c9afd8ead 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -132,6 +132,7 @@ type ResponsesEventToChatState struct { NextToolCallIndex int // next sequential tool_call index to assign OutputIndexToToolIndex map[int]int // Responses output_index → Chat tool_calls index OutputIndexToArguments map[int]string + argumentBuffers map[int]*strings.Builder IncludeUsage bool Usage *ChatUsage } @@ -296,7 +297,7 @@ func resToChatHandleFuncArgsDelta(evt *ResponsesStreamEvent, state *ResponsesEve if !ok { return nil } - state.OutputIndexToArguments[evt.OutputIndex] += evt.Delta + state.OutputIndexToArguments[evt.OutputIndex] = appendIndexedStreamString(&state.argumentBuffers, evt.OutputIndex, state.OutputIndexToArguments[evt.OutputIndex], evt.Delta) return []ChatCompletionsChunk{makeChatDeltaChunk(state, ChatDelta{ ToolCalls: []ChatToolCall{{ @@ -325,6 +326,7 @@ func resToChatHandleFuncArgsDone(evt *ResponsesStreamEvent, state *ResponsesEven remainder := completed[len(current):] state.OutputIndexToArguments[evt.OutputIndex] = completed + delete(state.argumentBuffers, evt.OutputIndex) return []ChatCompletionsChunk{makeChatDeltaChunk(state, ChatDelta{ ToolCalls: []ChatToolCall{{ Index: &idx, diff --git a/backend/internal/pkg/apicompat/stream_accumulation_memory_test.go b/backend/internal/pkg/apicompat/stream_accumulation_memory_test.go new file mode 100644 index 0000000000..f6a8ea2e53 --- /dev/null +++ b/backend/internal/pkg/apicompat/stream_accumulation_memory_test.go @@ -0,0 +1,356 @@ +package apicompat + +import ( + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type streamAccumulationFieldCase struct { + name string + blockType string + field func(*AnthropicEventToResponsesState) *string + delta func(string) *AnthropicDelta +} + +func streamAccumulationFieldCases() []streamAccumulationFieldCase { + return []streamAccumulationFieldCase{ + {"text", "text", func(s *AnthropicEventToResponsesState) *string { return &s.TextAccum }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "text_delta", Text: v} }}, + {"thinking", "thinking", func(s *AnthropicEventToResponsesState) *string { return &s.CurrentSummary }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "thinking_delta", Thinking: v} }}, + {"arguments", "tool_use", func(s *AnthropicEventToResponsesState) *string { return &s.CurrentArgs }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "input_json_delta", PartialJSON: v} }}, + {"signature", "thinking", func(s *AnthropicEventToResponsesState) *string { return &s.CurrentThinking.Signature }, func(v string) *AnthropicDelta { return &AnthropicDelta{Type: "signature_delta", Signature: v} }}, + } +} + +func TestStreamAccumulationAnthropicPublicStringsAndReset(t *testing.T) { + for _, tc := range streamAccumulationFieldCases() { + t.Run(tc.name, func(t *testing.T) { + state := NewAnthropicEventToResponsesState() + state.PreserveThinkingSignatures = true + block := &AnthropicContentBlock{Type: tc.blockType, ID: "call_seed", Name: "tool"} + if tc.name == "thinking" { + block.Thinking = "seed-" + } + if tc.name == "signature" { + block.Signature = "seed-" + } + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_start", ContentBlock: block}, state) + if tc.name == "thinking" || tc.name == "signature" { + require.Equal(t, "seed-", *tc.field(state), "content block seeds remain visible") + } else { + *tc.field(state) = "seed-" + } + appendDelta := func(value string) { + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_delta", Delta: tc.delta(value)}, state) + } + + appendDelta("one") + require.Equal(t, "seed-one", *tc.field(state)) + firstSnapshot := *tc.field(state) + appendDelta("-two") + require.Equal(t, "seed-one-two", *tc.field(state)) + require.Equal(t, "seed-one", firstSnapshot, "later deltas must not mutate borrowed strings") + secondSnapshot := *tc.field(state) + + // An external assignment with the same length must replace the old + // accumulator, not be mistaken for a synchronized public field. + replacement := strings.Repeat("r", len(secondSnapshot)) + *tc.field(state) = replacement + appendDelta("!") + require.Equal(t, replacement+"!", *tc.field(state)) + require.Equal(t, "seed-one-two", secondSnapshot) + + *tc.field(state) = "" + appendDelta("after-reset") + require.Equal(t, "after-reset", *tc.field(state)) + closedSnapshot := *tc.field(state) + closedEvents := AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_stop"}, state) + require.Empty(t, *tc.field(state)) + + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_start", ContentBlock: &AnthropicContentBlock{Type: tc.blockType, ID: "call_next", Name: "tool"}}, state) + appendDelta(strings.Repeat("next", 128)) + require.Equal(t, strings.Repeat("next", 128), *tc.field(state), "a new block must not reuse the previous prefix") + require.Equal(t, "after-reset", closedSnapshot) + require.Equal(t, "seed-one", firstSnapshot) + if tc.name == "text" { + require.Len(t, closedEvents, 2) + require.Equal(t, "after-reset", closedEvents[0].Text) + require.Equal(t, "after-reset", closedEvents[1].Part.Text) + } + }) + } +} + +func TestStreamAccumulationAnthropicCopiedStateBranches(t *testing.T) { + for _, tc := range streamAccumulationFieldCases() { + t.Run(tc.name, func(t *testing.T) { + original := NewAnthropicEventToResponsesState() + original.PreserveThinkingSignatures = true + appendDelta := func(state *AnthropicEventToResponsesState, value string) { + AnthropicEventToResponsesEvents(&AnthropicStreamEvent{Type: "content_block_delta", Delta: tc.delta(value)}, state) + } + appendDelta(original, "base") + baseSnapshot := *tc.field(original) + copied := *original + + // Sequential copies historically had independent string values. + // This does not promise concurrent mutation of shared state is safe. + appendDelta(original, "/left") + appendDelta(&copied, "/right") + require.Equal(t, "base/left", *tc.field(original)) + require.Equal(t, "base/right", *tc.field(&copied)) + appendDelta(original, "/again") + require.Equal(t, "base/left/again", *tc.field(original)) + require.Equal(t, "base/right", *tc.field(&copied)) + require.Equal(t, "base", baseSnapshot) + }) + } +} + +func TestStreamAccumulationResponsesChatToolIsolation(t *testing.T) { + state := NewResponsesEventToChatState() + for _, idx := range []int{2, 7} { + ResponsesEventToChatChunks(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: idx, Item: &ResponsesOutput{Type: "function_call", CallID: fmt.Sprintf("call_%d", idx), Name: "tool"}}, state) + } + appendDelta := func(idx int, delta, want string) { + t.Helper() + ResponsesEventToChatChunks(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: idx, Delta: delta}, state) + require.Equal(t, want, state.OutputIndexToArguments[idx]) + } + state.OutputIndexToArguments[2] = `{"a":` + appendDelta(2, "1", `{"a":1`) + firstSnapshot := state.OutputIndexToArguments[2] + appendDelta(7, `{"b":`, `{"b":`) + appendDelta(2, "}", `{"a":1}`) + appendDelta(7, "2}", `{"b":2}`) + require.Equal(t, `{"a":1`, firstSnapshot) + require.Equal(t, `{"a":1}`, state.OutputIndexToArguments[2]) + + ResponsesEventToChatChunks(&ResponsesStreamEvent{Type: "response.function_call_arguments.done", OutputIndex: 2, Arguments: `{"a":1} `}, state) + require.Equal(t, `{"a":1} `, state.OutputIndexToArguments[2]) + appendDelta(2, "\n", "{\"a\":1} \n") + state.OutputIndexToArguments[2] = "external" + appendDelta(2, "!", "external!") + delete(state.OutputIndexToArguments, 2) + appendDelta(2, "fresh", "fresh") + require.Equal(t, `{"b":2}`, state.OutputIndexToArguments[7]) +} + +func streamAccumulationChatToolChunk(idx int, name, arguments string) *ChatCompletionsChunk { + return &ChatCompletionsChunk{Choices: []ChatChunkChoice{{Delta: ChatDelta{ToolCalls: []ChatToolCall{{Index: &idx, ID: fmt.Sprintf("call_%d", idx), Type: "function", Function: ChatFunctionCall{Name: name, Arguments: arguments}}}}}}} +} + +func TestStreamAccumulationChatResponsesToolIsolation(t *testing.T) { + state := NewChatCompletionsToResponsesStreamState("model") + appendDelta := func(idx int, name, delta, want string) { + t.Helper() + ChatCompletionsChunkToResponsesEvents(streamAccumulationChatToolChunk(idx, name, delta), state) + require.Equal(t, want, state.ToolCalls[idx].Function.Arguments) + } + appendDelta(0, "first", `{"a":`, `{"a":`) + firstSnapshot := state.ToolCalls[0].Function.Arguments + appendDelta(1, "second", `{"b":`, `{"b":`) + appendDelta(0, "", "1}", `{"a":1}`) + appendDelta(1, "", "2}", `{"b":2}`) + require.Equal(t, `{"a":`, firstSnapshot) + require.Equal(t, `{"a":1}`, state.ToolCalls[0].Function.Arguments) + + state.ToolCalls[0].Function.Arguments = `{"c":3` + appendDelta(0, "", "}", `{"c":3}`) + state.ToolCalls[0].Function.Arguments = "" + appendDelta(0, "", "{}", "{}") + oldCall := state.ToolCalls[0] + delete(state.ToolCalls, 0) + appendDelta(0, "replacement", `{"new":`, `{"new":`) + appendDelta(0, "", "4}", `{"new":4}`) + require.Equal(t, "{}", oldCall.Function.Arguments, "replacing an indexed call must leave the old call immutable") + require.Equal(t, `{"b":2}`, state.ToolCalls[1].Function.Arguments) + require.NoError(t, state.ValidateToolCallArguments()) +} + +func TestStreamAccumulationReadRawArgumentsAndReset(t *testing.T) { + state := NewResponsesEventToAnthropicState() + startTool := func(idx int) { + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: idx, Item: &ResponsesOutput{Type: "function_call", CallID: fmt.Sprintf("call_%d", idx), Name: "Read"}}, state) + } + startTool(0) + state.CurrentToolArgs = `{"file_path":"` + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: "/tmp/one"}, state) + require.Equal(t, `{"file_path":"/tmp/one`, state.CurrentToolArgs) + require.NotNil(t, state.currentToolArgsValidation) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + firstSnapshot := state.CurrentToolArgs + firstValidationSnapshot := state.currentToolArgsValidation.data + // Same-length caller replacement must also be respected by this special + // path, whose externally visible raw JSON differs from sanitized output. + state.CurrentToolArgs = `{"file_path":"/tmp/two` + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: `","pages":""}`}, state) + require.Len(t, events, 1) + require.JSONEq(t, `{"file_path":"/tmp/two"}`, events[0].Delta.PartialJSON) + require.Equal(t, `{"file_path":"/tmp/two","pages":""}`, state.CurrentToolArgs) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + require.Equal(t, firstSnapshot, string(firstValidationSnapshot), "external replacement must not overwrite a borrowed validation prefix") + rawSnapshot := state.CurrentToolArgs + require.Equal(t, `{"file_path":"/tmp/one`, firstSnapshot) + + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.done", OutputIndex: 0}, state) + require.Empty(t, state.CurrentToolArgs) + require.Nil(t, state.currentToolArgsValidation) + startTool(1) + require.Nil(t, state.currentToolArgsValidation) + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 1, Delta: `{"file_path":"/tmp/new"}`}, state) + require.Equal(t, `{"file_path":"/tmp/new"}`, state.CurrentToolArgs) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + require.Equal(t, `{"file_path":"/tmp/two","pages":""}`, rawSnapshot) + require.JSONEq(t, `{"file_path":"/tmp/two"}`, events[0].Delta.PartialJSON) +} + +func TestStreamAccumulationReadValidationCopiedStateBranches(t *testing.T) { + original := NewResponsesEventToAnthropicState() + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 0, Item: &ResponsesOutput{Type: "function_call", CallID: "call_read", Name: "Read"}}, original) + appendDelta := func(state *ResponsesEventToAnthropicState, value string) { + t.Helper() + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: value}, state) + require.Empty(t, events, "unfinished strings must not pass the complete-JSON gate") + require.NotNil(t, state.currentToolArgsValidation) + require.Equal(t, state.CurrentToolArgs, string(state.currentToolArgsValidation.data)) + require.Equal(t, state.CurrentToolArgs, state.currentToolArgsValidation.snapshot) + } + original.CurrentToolArgs = `{"file_path":"` + appendDelta(original, "base") + baseSnapshot := original.CurrentToolArgs + baseValidationSnapshot := original.currentToolArgsValidation.data + copied := *original + + appendDelta(original, "/left") + leftValidationSnapshot := original.currentToolArgsValidation.data + appendDelta(&copied, "/right") + require.Equal(t, `{"file_path":"base/left`, original.CurrentToolArgs) + require.Equal(t, original.CurrentToolArgs, string(original.currentToolArgsValidation.data)) + require.Equal(t, `{"file_path":"base/right`, copied.CurrentToolArgs) + appendDelta(original, "/again") + require.Equal(t, `{"file_path":"base/left/again`, original.CurrentToolArgs) + require.Equal(t, `{"file_path":"base/right`, string(copied.currentToolArgsValidation.data)) + require.Equal(t, baseSnapshot, string(baseValidationSnapshot)) + require.Equal(t, `{"file_path":"base/left`, string(leftValidationSnapshot)) + + beforeReset := original.currentToolArgsValidation.data + original.CurrentToolArgs = "" + appendDelta(original, `{"file_path":"reset`) + require.Equal(t, `{"file_path":"reset`, original.CurrentToolArgs) + require.Equal(t, `{"file_path":"base/left/again`, string(beforeReset)) + require.Equal(t, `{"file_path":"base/right`, string(copied.currentToolArgsValidation.data)) +} + +func TestStreamAccumulationReadValidationStopsAfterComplete(t *testing.T) { + state := NewResponsesEventToAnthropicState() + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 0, Item: &ResponsesOutput{Type: "function_call", CallID: "call_read", Name: "Read"}}, state) + const raw = `{"file_path":"/tmp/file","pages":""}` + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: raw}, state) + require.Len(t, events, 1) + require.True(t, state.CurrentToolHadDelta) + validation := state.currentToolArgsValidation + require.NotNil(t, validation) + require.Equal(t, raw, string(validation.data)) + validationCapacity := cap(validation.data) + + for _, trailing := range []string{" ", strings.Repeat("x", 1024)} { + previous := state.CurrentToolArgs + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: trailing}, state) + require.Empty(t, events, "a completed Read tool must not emit another sanitized delta") + require.Equal(t, previous+trailing, state.CurrentToolArgs, "the existing public string still accumulates late deltas") + require.Same(t, validation, state.currentToolArgsValidation) + require.Equal(t, raw, string(validation.data)) + require.Equal(t, raw, validation.snapshot) + require.Equal(t, validationCapacity, cap(validation.data)) + } + require.JSONEq(t, `{"file_path":"/tmp/file"}`, events[0].Delta.PartialJSON) + ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{Type: "response.function_call_arguments.done", OutputIndex: 0}, state) + require.Nil(t, state.currentToolArgsValidation) + require.Empty(t, state.CurrentToolArgs) +} + +func TestStreamAccumulationDeferredAnthropicTools(t *testing.T) { + state := NewChatCompletionsToAnthropicStreamState("model") + var events []AnthropicStreamEvent + feed := func(idx int, name, args string) { + events = append(events, ChatCompletionsChunkToAnthropicEvents(streamAccumulationChatToolChunk(idx, name, args), state)...) + } + feed(0, "", `{"a":`) + feed(1, "", `{"b":`) + feed(0, "", "1") + feed(1, "", "2") + feed(0, "first", "}") + feed(1, "second", "}") + events = append(events, FinalizeChatCompletionsAnthropicStream(state)...) + blocks := assembleToolUseBlocks(events) + require.Len(t, blocks, 2) + require.Equal(t, "first", blocks[0].Name) + require.Equal(t, `{"a":1}`, blocks[0].Input) + require.Equal(t, "second", blocks[1].Name) + require.Equal(t, `{"b":2}`, blocks[1].Input) + require.Empty(t, FinalizeChatCompletionsAnthropicStream(state)) +} + +var streamAccumulationBenchmarkSink string + +// ReportAllocs measures cumulative allocation traffic, not retained heap/RSS. +// A fixed 64-byte delta makes total-size scaling expose repeated prefix copies. +func BenchmarkStreamAccumulationAnthropic64ByteDeltas(b *testing.B) { + for _, tc := range streamAccumulationFieldCases() { + for _, size := range []int{32 << 10, 128 << 10, 512 << 10} { + b.Run(fmt.Sprintf("%s/%dKiB", tc.name, size>>10), func(b *testing.B) { + payload := strings.Repeat("x", 64) + event := &AnthropicStreamEvent{Type: "content_block_delta", Delta: tc.delta(payload)} + b.ReportAllocs() + b.SetBytes(int64(size)) + b.ResetTimer() + for i := 0; i < b.N; i++ { + state := NewAnthropicEventToResponsesState() + state.PreserveThinkingSignatures = true + for received := 0; received < size; received += len(payload) { + AnthropicEventToResponsesEvents(event, state) + } + streamAccumulationBenchmarkSink = *tc.field(state) + if len(streamAccumulationBenchmarkSink) != size { + b.Fatalf("accumulated %d bytes, want %d", len(streamAccumulationBenchmarkSink), size) + } + } + }) + } + } +} + +// Read's existing complete-JSON gate inspects the accumulated arguments on +// every delta. Keep the file_path string unfinished to measure that independent +// cost without changing when the converter emits sanitized tool input. +func BenchmarkStreamAccumulationRead64ByteDeltas(b *testing.B) { + for _, size := range []int{32 << 10, 128 << 10, 512 << 10} { + b.Run(fmt.Sprintf("%dKiB", size>>10), func(b *testing.B) { + const prefix = `{"file_path":"` + firstEvent := &ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: prefix + strings.Repeat("x", 64-len(prefix))} + nextEvent := &ResponsesStreamEvent{Type: "response.function_call_arguments.delta", OutputIndex: 0, Delta: strings.Repeat("x", 64)} + b.ReportAllocs() + b.SetBytes(int64(size)) + b.ResetTimer() + for i := 0; i < b.N; i++ { + state := NewResponsesEventToAnthropicState() + state.MessageStartSent = true + state.ContentBlockOpen = true + state.CurrentBlockType = "tool_use" + state.CurrentToolName = "Read" + state.OutputIndexToBlockIdx[0] = 0 + ResponsesEventToAnthropicEvents(firstEvent, state) + for received := 64; received < size; received += 64 { + ResponsesEventToAnthropicEvents(nextEvent, state) + } + streamAccumulationBenchmarkSink = state.CurrentToolArgs + if len(streamAccumulationBenchmarkSink) != size || state.CurrentToolHadDelta { + b.Fatalf("unfinished Read arguments: bytes=%d, emitted=%v", len(streamAccumulationBenchmarkSink), state.CurrentToolHadDelta) + } + } + }) + } +} diff --git a/backend/internal/pkg/apicompat/stream_string_buffer.go b/backend/internal/pkg/apicompat/stream_string_buffer.go new file mode 100644 index 0000000000..fa16797846 --- /dev/null +++ b/backend/internal/pkg/apicompat/stream_string_buffer.go @@ -0,0 +1,48 @@ +package apicompat + +import "strings" + +// appendStreamString changes only how an existing cumulative string is stored. +// Callers still publish its complete value after each delta. A caller-provided +// seed or replacement stays authoritative, including an explicit empty string. +// Builders are never copied or pooled: previously published String snapshots +// remain immutable when the next block starts or an external value replaces it. +func appendStreamString(buffer **strings.Builder, current, delta string) string { + if delta == "" { + return current + } + if *buffer == nil || (*buffer).String() != current { + *buffer = &strings.Builder{} + _, _ = (*buffer).WriteString(current) + } + _, _ = (*buffer).WriteString(delta) + return (*buffer).String() +} + +func appendIndexedStreamString(buffers *map[int]*strings.Builder, index int, current, delta string) string { + if *buffers == nil { + *buffers = make(map[int]*strings.Builder) + } + buffer := (*buffers)[index] + value := appendStreamString(&buffer, current, delta) + (*buffers)[index] = buffer + return value +} + +// streamStringBytes keeps matching bytes for APIs that require []byte without +// copying the growing public string on every call. The shared snapshot also +// detects sequentially diverging state copies: a mismatch creates a new buffer +// instead of overwriting another state's accumulated prefix. +type streamStringBytes struct { + data []byte + snapshot string +} + +func appendStreamStringBytes(buffer **streamStringBytes, previous, current, delta string) []byte { + if *buffer == nil || (*buffer).snapshot != previous { + *buffer = &streamStringBytes{data: append([]byte(nil), previous...)} + } + (*buffer).data = append((*buffer).data, delta...) + (*buffer).snapshot = current + return (*buffer).data +} diff --git a/backend/internal/pkg/gemini/models.go b/backend/internal/pkg/gemini/models.go index 1d38fc9909..7e4066c004 100644 --- a/backend/internal/pkg/gemini/models.go +++ b/backend/internal/pkg/gemini/models.go @@ -18,16 +18,22 @@ type ModelsListResponse struct { func DefaultModels() []Model { methods := []string{"generateContent", "streamGenerateContent"} return []Model{ - {Name: "models/gemini-2.0-flash", SupportedGenerationMethods: methods}, - {Name: "models/gemini-2.5-flash", SupportedGenerationMethods: methods}, - {Name: "models/gemini-2.5-flash-image", SupportedGenerationMethods: methods}, - {Name: "models/gemini-2.5-pro", SupportedGenerationMethods: methods}, - {Name: "models/gemini-3.5-flash", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.1-flash-image-preview", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.1-flash-lite-image", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3-pro-image", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3-pro-image-preview", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3-flash", SupportedGenerationMethods: methods}, {Name: "models/gemini-3-flash-preview", SupportedGenerationMethods: methods}, - {Name: "models/gemini-3-pro-preview", SupportedGenerationMethods: methods}, {Name: "models/gemini-3.1-pro-preview", SupportedGenerationMethods: methods}, {Name: "models/gemini-3.1-pro-preview-customtools", SupportedGenerationMethods: methods}, - {Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.1-flash-lite", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.1-flash-lite-preview", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.5-flash", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.5-flash-lite", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.6-flash", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.7-flash", SupportedGenerationMethods: methods}, + {Name: "models/gemini-3.8-flash", SupportedGenerationMethods: methods}, {Name: "models/gemini-4-argon", SupportedGenerationMethods: methods}, } } diff --git a/backend/internal/pkg/gemini/models_test.go b/backend/internal/pkg/gemini/models_test.go index 1d20c0e62d..a85ecb20e5 100644 --- a/backend/internal/pkg/gemini/models_test.go +++ b/backend/internal/pkg/gemini/models_test.go @@ -12,7 +12,7 @@ func TestDefaultModels_ContainsFallbackCatalogModels(t *testing.T) { } required := []string{ - "models/gemini-2.5-flash-image", + "models/gemini-3-pro-image", "models/gemini-3.1-pro-preview-customtools", "models/gemini-3.1-flash-image", } diff --git a/backend/internal/pkg/geminicli/models.go b/backend/internal/pkg/geminicli/models.go index 4e2fa55bb1..6fe3a5f368 100644 --- a/backend/internal/pkg/geminicli/models.go +++ b/backend/internal/pkg/geminicli/models.go @@ -11,15 +11,22 @@ type Model struct { // DefaultModels is the curated Gemini model list used by the admin UI "test account" flow. var DefaultModels = []Model{ - {ID: "gemini-2.0-flash", Type: "model", DisplayName: "Gemini 2.0 Flash", CreatedAt: ""}, - {ID: "gemini-2.5-flash", Type: "model", DisplayName: "Gemini 2.5 Flash", CreatedAt: ""}, - {ID: "gemini-2.5-flash-image", Type: "model", DisplayName: "Gemini 2.5 Flash Image", CreatedAt: ""}, - {ID: "gemini-2.5-pro", Type: "model", DisplayName: "Gemini 2.5 Pro", CreatedAt: ""}, - {ID: "gemini-3.5-flash", Type: "model", DisplayName: "Gemini 3.5 Flash", CreatedAt: ""}, - {ID: "gemini-3-flash-preview", Type: "model", DisplayName: "Gemini 3 Flash Preview", CreatedAt: ""}, - {ID: "gemini-3-pro-preview", Type: "model", DisplayName: "Gemini 3 Pro Preview", CreatedAt: ""}, - {ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""}, {ID: "gemini-3.1-flash-image", Type: "model", DisplayName: "Gemini 3.1 Flash Image", CreatedAt: ""}, + {ID: "gemini-3.1-flash-image-preview", Type: "model", DisplayName: "Gemini 3.1 Flash Image Preview", CreatedAt: ""}, + {ID: "gemini-3.1-flash-lite-image", Type: "model", DisplayName: "Gemini 3.1 Flash Lite Image", CreatedAt: ""}, + {ID: "gemini-3-pro-image", Type: "model", DisplayName: "Gemini 3 Pro Image", CreatedAt: ""}, + {ID: "gemini-3-pro-image-preview", Type: "model", DisplayName: "Gemini 3 Pro Image Preview", CreatedAt: ""}, + {ID: "gemini-3-flash", Type: "model", DisplayName: "Gemini 3 Flash", CreatedAt: ""}, + {ID: "gemini-3-flash-preview", Type: "model", DisplayName: "Gemini 3 Flash Preview", CreatedAt: ""}, + {ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""}, + {ID: "gemini-3.1-pro-preview-customtools", Type: "model", DisplayName: "Gemini 3.1 Pro Preview Custom Tools", CreatedAt: ""}, + {ID: "gemini-3.1-flash-lite", Type: "model", DisplayName: "Gemini 3.1 Flash Lite", CreatedAt: ""}, + {ID: "gemini-3.1-flash-lite-preview", Type: "model", DisplayName: "Gemini 3.1 Flash Lite Preview", CreatedAt: ""}, + {ID: "gemini-3.5-flash", Type: "model", DisplayName: "Gemini 3.5 Flash", CreatedAt: ""}, + {ID: "gemini-3.5-flash-lite", Type: "model", DisplayName: "Gemini 3.5 Flash Lite", CreatedAt: ""}, + {ID: "gemini-3.6-flash", Type: "model", DisplayName: "Gemini 3.6 Flash", CreatedAt: ""}, + {ID: "gemini-3.7-flash", Type: "model", DisplayName: "Gemini 3.7 Flash", CreatedAt: ""}, + {ID: "gemini-3.8-flash", Type: "model", DisplayName: "Gemini 3.8 Flash", CreatedAt: ""}, {ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""}, } @@ -43,4 +50,4 @@ func GoogleOneModelMapping() map[string]string { } // DefaultTestModel is the default model to preselect in test flows. -const DefaultTestModel = "gemini-2.0-flash" +const DefaultTestModel = "gemini-3.5-flash" diff --git a/backend/internal/pkg/geminicli/models_test.go b/backend/internal/pkg/geminicli/models_test.go index e0cb57941f..7ef2647fa5 100644 --- a/backend/internal/pkg/geminicli/models_test.go +++ b/backend/internal/pkg/geminicli/models_test.go @@ -11,8 +11,9 @@ func TestDefaultModels_ContainsImageModels(t *testing.T) { } required := []string{ - "gemini-2.5-flash-image", "gemini-3.1-flash-image", + "gemini-3-pro-image", + DefaultTestModel, } for _, id := range required { diff --git a/backend/internal/pkg/httputil/body.go b/backend/internal/pkg/httputil/body.go index 3a6fab4b78..2923520dde 100644 --- a/backend/internal/pkg/httputil/body.go +++ b/backend/internal/pkg/httputil/body.go @@ -4,6 +4,7 @@ import ( "bytes" "compress/gzip" "compress/zlib" + "context" "errors" "fmt" "io" @@ -19,7 +20,8 @@ const ( jsonUTF8BOMLen = 3 // maxDecompressedBodySize limits the decompressed request body to 64 MB // to prevent decompression bomb attacks. - maxDecompressedBodySize = 64 << 20 + maxDecompressedBodySize = 64 << 20 + maxRequestZstdWindowSize = 8 << 20 ) // PrereadBody 回填已读取完成的请求体:作为 io.ReadCloser 可被再次顺序消费 @@ -64,11 +66,33 @@ func (p *PrereadBody) Bytes() []byte { // 已由 PrereadBody 回填的请求体直接返回其完整切片(零拷贝),不检查内部 // reader 是否已被消费——见 PrereadBody 的文档说明。 func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { + body, err := readRequestBodyWithBudget(req) + return body.data, err +} + +// requestBodyBuffer carries only allocations owned by the current helper. +// Borrowed input (notably PrereadBody) has no charge to release: its original +// owner may still retain it even if normalization creates a replacement. +type requestBodyBuffer struct { + data []byte + charged int64 +} + +func (b *requestBodyBuffer) release(ctx context.Context) { + charged := b.charged + *b = requestBodyBuffer{} + releaseRequestBodyMemory(ctx, charged) +} + +func readRequestBodyWithBudget(req *http.Request) (requestBodyBuffer, error) { if req == nil || req.Body == nil { - return nil, nil + return requestBodyBuffer{}, nil + } + if err := req.Context().Err(); err != nil { + return requestBodyBuffer{}, err } if preread, ok := req.Body.(*PrereadBody); ok { - return preread.Bytes(), nil + return requestBodyBuffer{data: preread.Bytes()}, nil } capHint := requestBodyReadInitCap @@ -83,9 +107,9 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { } } - raw, err := readRequestBodyChunks(req.Body, capHint, req.ContentLength) + raw, err := readRequestBodyChunksWithBudget(req.Context(), req.Body, capHint, req.ContentLength) if err != nil { - return nil, err + return requestBodyBuffer{}, err } enc := strings.ToLower(strings.TrimSpace(req.Header.Get("Content-Encoding"))) @@ -93,14 +117,15 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { return raw, nil } - decoded, err := decompressRequestBody(enc, raw) + defer raw.release(req.Context()) + decoded, err := decompressRequestBodyWithBudget(req.Context(), enc, raw.data) if err != nil { - return nil, fmt.Errorf("decode Content-Encoding %q: %w", enc, err) + return requestBodyBuffer{}, fmt.Errorf("decode Content-Encoding %q: %w", enc, err) } req.Header.Del("Content-Encoding") req.Header.Del("Content-Length") - req.ContentLength = int64(len(decoded)) + req.ContentLength = int64(len(decoded.data)) return decoded, nil } @@ -108,7 +133,13 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { // Read bounded chunks as bytes arrive, then assemble the exact-size result. // This avoids doubling large buffers or eagerly allocating an untrusted // Content-Length before the corresponding bytes have arrived. -func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength int64) ([]byte, error) { +func readRequestBodyChunksWithBudget(ctx context.Context, reader io.Reader, initialCapacity int, contentLength int64) (result requestBodyBuffer, err error) { + var reserved int64 + defer func() { + // Chunks and the EOF probe are temporary once the final buffer is + // assembled. On failure there is no result, so refund all allocations. + releaseRequestBodyMemory(ctx, reserved-result.charged) + }() capacity := initialCapacity var chunks [][]byte total := 0 @@ -117,16 +148,26 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength if remaining := contentLength - int64(total); remaining >= 0 && remaining < int64(chunkCapacity) { chunkCapacity = int(remaining) + 1 } + if err := reserveRequestBodyMemory(ctx, int64(chunkCapacity)); err != nil { + return requestBodyBuffer{}, err + } + reserved += int64(chunkCapacity) chunk := make([]byte, chunkCapacity) n := 0 var err error for n < len(chunk) && err == nil { + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } var read int read, err = reader.Read(chunk[n:]) n += read } + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } if err != nil && err != io.EOF { - return nil, err + return requestBodyBuffer{}, err } if n > 0 { chunks = append(chunks, chunk[:n]) @@ -134,17 +175,21 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength } if err != nil { if len(chunks) == 0 { - return chunk[:0], nil + return requestBodyBuffer{}, nil } if len(chunks) == 1 { - return chunks[0], nil + return requestBodyBuffer{data: chunks[0], charged: int64(cap(chunks[0]))}, nil } + if err := reserveRequestBodyMemory(ctx, int64(total)); err != nil { + return requestBodyBuffer{}, err + } + reserved += int64(total) body := make([]byte, total) offset := 0 for _, part := range chunks { offset += copy(body[offset:], part) } - return body, nil + return requestBodyBuffer{data: body, charged: int64(total)}, nil } if capacity < requestBodyReadMaxInitCap { capacity *= 2 @@ -158,73 +203,102 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength // ReadLenientJSONRequestBodyWithPrealloc reads a request body and normalizes // JSON string control bytes before strict validation. func ReadLenientJSONRequestBodyWithPrealloc(req *http.Request, maxNormalizedBytes int64) ([]byte, error) { - body, err := ReadRequestBodyWithPrealloc(req) + if req == nil { + return nil, nil + } + body, err := readRequestBodyWithBudget(req) if err != nil { return nil, err } - return NormalizeLenientJSONRequestBody(body, maxNormalizedBytes) + normalized, err := normalizeLenientJSONRequestBody(req.Context(), body.data, maxNormalizedBytes) + if err != nil || normalized.charged > 0 { + body.release(req.Context()) + } + return normalized.data, err } func decompressRequestBody(encoding string, raw []byte) ([]byte, error) { + body, err := decompressRequestBodyWithBudget(context.Background(), encoding, raw) + return body.data, err +} + +func decompressRequestBodyWithBudget(ctx context.Context, encoding string, raw []byte) (requestBodyBuffer, error) { + var reader io.Reader switch encoding { case "zstd": - dec, err := zstd.NewReader(bytes.NewReader(raw)) + if err := reserveRequestBodyMemory(ctx, maxRequestZstdWindowSize); err != nil { + return requestBodyBuffer{}, err + } + defer releaseRequestBodyMemory(ctx, maxRequestZstdWindowSize) + dec, err := zstd.NewReader(bytes.NewReader(raw), + zstd.WithDecoderConcurrency(1), + zstd.WithDecoderMaxWindow(maxRequestZstdWindowSize), + zstd.WithDecoderMaxMemory(maxDecompressedBodySize)) if err != nil { - return nil, err + return requestBodyBuffer{}, err } defer dec.Close() - return io.ReadAll(io.LimitReader(dec, maxDecompressedBodySize)) + reader = dec case "gzip", "x-gzip": gr, err := gzip.NewReader(bytes.NewReader(raw)) if err != nil { - return nil, err + return requestBodyBuffer{}, err } defer func() { _ = gr.Close() }() - return io.ReadAll(io.LimitReader(gr, maxDecompressedBodySize)) + reader = gr case "deflate": zr, err := zlib.NewReader(bytes.NewReader(raw)) if err != nil { - return nil, err + return requestBodyBuffer{}, err } defer func() { _ = zr.Close() }() - return io.ReadAll(io.LimitReader(zr, maxDecompressedBodySize)) + reader = zr default: - return nil, errors.New("unsupported Content-Encoding") + return requestBodyBuffer{}, errors.New("unsupported Content-Encoding") } + decoded, err := readRequestBodyChunksWithBudget(ctx, io.LimitReader(reader, maxDecompressedBodySize+1), requestBodyReadInitCap, -1) + if err != nil { + return requestBodyBuffer{}, err + } + if len(decoded.data) > maxDecompressedBodySize { + decoded.release(ctx) + return requestBodyBuffer{}, &http.MaxBytesError{Limit: maxDecompressedBodySize} + } + return decoded, nil } // NormalizeLenientJSONRequestBody escapes raw control bytes that broken // OpenAI-compatible clients sometimes place inside JSON strings. func NormalizeLenientJSONRequestBody(body []byte, maxNormalizedBytes int64) ([]byte, error) { + normalized, err := normalizeLenientJSONRequestBody(context.Background(), body, maxNormalizedBytes) + return normalized.data, err +} + +func normalizeLenientJSONRequestBody(ctx context.Context, body []byte, maxNormalizedBytes int64) (requestBodyBuffer, error) { + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } if maxNormalizedBytes <= 0 { maxNormalizedBytes = maxDecompressedBodySize } body = trimUTF8BOM(body) if len(body) == 0 { - return body, nil + return requestBodyBuffer{data: body}, nil } if int64(len(body)) > maxNormalizedBytes { - return nil, &http.MaxBytesError{Limit: maxNormalizedBytes} + return requestBodyBuffer{}, &http.MaxBytesError{Limit: maxNormalizedBytes} } - var out []byte + normalizedSize := int64(len(body)) inString := false escaped := false - for i, b := range body { + for _, b := range body { if inString && isJSONControlByte(b) { - if out == nil { - capHint := len(body) + 6 - if int64(capHint) > maxNormalizedBytes { - capHint = int(maxNormalizedBytes) - } - out = make([]byte, 0, capHint) - out = append(out, body[:i]...) + if maxNormalizedBytes-normalizedSize < 5 { + return requestBodyBuffer{}, &http.MaxBytesError{Limit: maxNormalizedBytes} } - if int64(len(out)+6) > maxNormalizedBytes { - return nil, &http.MaxBytesError{Limit: maxNormalizedBytes} - } - out = appendJSONUnicodeEscape(out, b) + normalizedSize += 5 escaped = false continue } @@ -237,18 +311,41 @@ func NormalizeLenientJSONRequestBody(body []byte, maxNormalizedBytes int64) ([]b case b == '"': inString = !inString } - - if out != nil { - if int64(len(out)+1) > maxNormalizedBytes { - return nil, &http.MaxBytesError{Limit: maxNormalizedBytes} - } - out = append(out, b) + } + if err := ctx.Err(); err != nil { + return requestBodyBuffer{}, err + } + if normalizedSize == int64(len(body)) { + return requestBodyBuffer{data: body}, nil + } + if err := reserveRequestBodyMemory(ctx, normalizedSize); err != nil { + return requestBodyBuffer{}, err + } + // Allocate once after counting expansion, so escaped control bytes cannot + // bypass the ingress budget through append's geometric capacity growth. + out := make([]byte, 0, int(normalizedSize)) + inString, escaped = false, false + for _, b := range body { + if inString && isJSONControlByte(b) { + out = appendJSONUnicodeEscape(out, b) + escaped = false + continue } + switch { + case escaped: + escaped = false + case inString && b == '\\': + escaped = true + case b == '"': + inString = !inString + } + out = append(out, b) } - if out != nil { - return out, nil + if err := ctx.Err(); err != nil { + releaseRequestBodyMemory(ctx, normalizedSize) + return requestBodyBuffer{}, err } - return body, nil + return requestBodyBuffer{data: out, charged: normalizedSize}, nil } func trimUTF8BOM(body []byte) []byte { diff --git a/backend/internal/pkg/httputil/body_budget.go b/backend/internal/pkg/httputil/body_budget.go new file mode 100644 index 0000000000..9c6dc9fbea --- /dev/null +++ b/backend/internal/pkg/httputil/body_budget.go @@ -0,0 +1,98 @@ +package httputil + +import ( + "context" + "errors" + "sync" +) + +// ErrRequestBodyMemoryBudget means this instance cannot buffer another request +// body yet. It is transient overload, not a malformed or oversized request. +var ErrRequestBodyMemoryBudget = errors.New("request body memory budget exhausted") + +// BodyMemoryBudget bounds buffered ingress allocations across requests. It +// counts chunks, their contiguous copy, decoded output and the decoder window; +// it is not a bound on the application's total heap or protocol conversion. +type BodyMemoryBudget struct { + mu sync.Mutex + limit int64 + used int64 +} + +func NewBodyMemoryBudget(limit int64) *BodyMemoryBudget { + return &BodyMemoryBudget{limit: limit} +} + +type bodyMemoryReservation struct { + mu sync.Mutex + budget *BodyMemoryBudget + bytes int64 + closed bool +} + +type bodyMemoryReservationKey struct{} + +// WithRequestBodyMemoryBudget retains final body reservations until the HTTP +// handler returns, including while a buffered request waits for a user slot. +// Read/decode/normalize helpers release temporary allocations when no longer +// owned. No goroutines or wait queue are created on exhaustion. +func WithRequestBodyMemoryBudget(ctx context.Context, budget *BodyMemoryBudget) (context.Context, func()) { + if budget == nil || budget.limit <= 0 || ctx.Value(bodyMemoryReservationKey{}) != nil { + return ctx, func() {} + } + r := &bodyMemoryReservation{budget: budget} + return context.WithValue(ctx, bodyMemoryReservationKey{}, r), func() { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return + } + r.closed = true + budget.mu.Lock() + budget.used -= r.bytes + budget.mu.Unlock() + r.bytes = 0 + } +} + +func reserveRequestBodyMemory(ctx context.Context, n int64) error { + if err := ctx.Err(); err != nil { + return err + } + r, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + if r == nil || n <= 0 { + return nil + } + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return ErrRequestBodyMemoryBudget + } + r.budget.mu.Lock() + defer r.budget.mu.Unlock() + if n > r.budget.limit-r.budget.used { + return ErrRequestBodyMemoryBudget + } + r.budget.used += n + r.bytes += n + return nil +} + +// releaseRequestBodyMemory refunds storage that a helper no longer owns. Each +// allocation must be released once, or left for the handler's final cleanup. +// Cleanup may race with a cancelled read, so a closed reservation is a no-op. +func releaseRequestBodyMemory(ctx context.Context, n int64) { + r, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + if r == nil || n <= 0 { + return + } + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return + } + r.budget.mu.Lock() + r.budget.used -= n + r.budget.mu.Unlock() + r.bytes -= n +} diff --git a/backend/internal/pkg/httputil/body_budget_test.go b/backend/internal/pkg/httputil/body_budget_test.go new file mode 100644 index 0000000000..3f2f06c7f7 --- /dev/null +++ b/backend/internal/pkg/httputil/body_budget_test.go @@ -0,0 +1,367 @@ +package httputil + +import ( + "bytes" + "compress/gzip" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/klauspost/compress/zstd" +) + +func TestRequestBodyMemoryBudgetSharedUntilRelease(t *testing.T) { + budget := NewBodyMemoryBudget(1024) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + req := httptest.NewRequest("POST", "/", bytes.NewReader(bytes.Repeat([]byte{'x'}, 700))).WithContext(ctx) + got, err := ReadRequestBodyWithPrealloc(req) + if err != nil || len(got) != 700 { + t.Fatalf("read: %d %v", len(got), err) + } + ctx2, release2 := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release2() + req2 := httptest.NewRequest("POST", "/", bytes.NewReader(bytes.Repeat([]byte{'x'}, 700))).WithContext(ctx2) + if _, err := ReadRequestBodyWithPrealloc(req2); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("want capacity error, got %v", err) + } + release() + release() // Idempotent cleanup cannot refund another request's allocation. + if _, err := ReadRequestBodyWithPrealloc(req2); err != nil { + t.Fatal(err) + } +} + +func TestRequestBodyMemoryBudgetUnknownLengthAndConcurrency(t *testing.T) { + budget := NewBodyMemoryBudget(4096) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + req := httptest.NewRequest("POST", "/", io.NopCloser(bytes.NewReader(bytes.Repeat([]byte{'x'}, 8192)))).WithContext(ctx) + req.ContentLength = -1 + if _, err := ReadRequestBodyWithPrealloc(req); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("unknown length bypassed budget: %v", err) + } + release() + var wg sync.WaitGroup + for range 20 { + wg.Go(func() { + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + _ = reserveRequestBodyMemory(ctx, 1024) + }) + } + wg.Wait() + if budget.used != 0 { + t.Fatalf("leaked reservations: %d", budget.used) + } +} + +func TestDecompressRequestBodyRejectsExcessiveZstdWindow(t *testing.T) { + for _, exponent := range []byte{20, 24, 29} { + raw := []byte{0x28, 0xb5, 0x2f, 0xfd, 0, (exponent - 10) << 3, 9, 0, 0, 'x'} + decoded, err := decompressRequestBody("zstd", raw) + if exponent == 20 { + if err != nil || string(decoded) != "x" { + t.Fatalf("small window: %q %v", decoded, err) + } + } else if err == nil { + t.Fatalf("accepted window 2^%d", exponent) + } + } +} + +func TestDecompressRequestBodyRejectsOversizeInsteadOfTruncating(t *testing.T) { + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + chunk := bytes.Repeat([]byte{' '}, 1<<20) + for range maxDecompressedBodySize / len(chunk) { + _, _ = encoder.Write(chunk) + } + _, _ = encoder.Write([]byte{'x'}) + if err := encoder.Close(); err != nil { + t.Fatal(err) + } + budget := NewBodyMemoryBudget(256 << 20) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + req := newRequestWithBody(t, compressed.Bytes(), "gzip").WithContext(ctx) + decoded, err := ReadRequestBodyWithPrealloc(req) + var maxErr *http.MaxBytesError + if decoded != nil || !errors.As(err, &maxErr) || maxErr.Limit != maxDecompressedBodySize { + t.Fatalf("silently truncated: len=%d err=%v", len(decoded), err) + } + if used := requestBodyBudgetUsed(budget); used != 0 { + t.Fatalf("oversize decoded body retained %d bytes", used) + } +} + +func TestDecodedRequestBodySharesMemoryBudget(t *testing.T) { + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + _, _ = encoder.Write(bytes.Repeat([]byte{'x'}, 4096)) + _ = encoder.Close() + ctx, release := WithRequestBodyMemoryBudget(context.Background(), NewBodyMemoryBudget(2048)) + defer release() + req := httptest.NewRequest("POST", "/", bytes.NewReader(compressed.Bytes())).WithContext(ctx) + req.Header.Set("Content-Encoding", "gzip") + if _, err := ReadRequestBodyWithPrealloc(req); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("decode bypassed budget: %v", err) + } +} + +func TestNormalizedRequestBodySharesMemoryBudget(t *testing.T) { + body := []byte(`{"input":"` + strings.Repeat("\x00", 100) + `"}`) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), NewBodyMemoryBudget(600)) + defer release() + req := httptest.NewRequest("POST", "/", bytes.NewReader(body)).WithContext(ctx) + if _, err := ReadLenientJSONRequestBodyWithPrealloc(req, 4096); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("normalization bypassed budget: %v", err) + } +} + +func requestBodyBudgetUsed(budget *BodyMemoryBudget) int64 { + budget.mu.Lock() + defer budget.mu.Unlock() + return budget.used +} + +func TestRequestBodyMemoryBudgetRetainsOnlyFinalAllocation(t *testing.T) { + for _, encoding := range []string{"identity", "gzip", "zstd"} { + for _, normalize := range []bool{false, true} { + name := encoding + if normalize { + name += "/normalized" + } + t.Run(name, func(t *testing.T) { + text := strings.Repeat("x", requestBodyReadMaxInitCap+64) + if normalize { + text += "\x00" + } + payload := []byte(`{"input":"` + text + `"}`) + raw := payload + switch encoding { + case "gzip": + var compressed bytes.Buffer + encoder := gzip.NewWriter(&compressed) + if _, err := encoder.Write(payload); err != nil { + t.Fatal(err) + } + if err := encoder.Close(); err != nil { + t.Fatal(err) + } + raw = compressed.Bytes() + case "zstd": + encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + raw = encoder.EncodeAll(payload, nil) + if err := encoder.Close(); err != nil { + t.Fatal(err) + } + } + budget := NewBodyMemoryBudget(32 << 20) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + req := newRequestWithBody(t, raw, encoding).WithContext(ctx) + // Unknown length exercises chunk growth and its extra EOF probe. + req.ContentLength = -1 + got, err := ReadLenientJSONRequestBodyWithPrealloc(req, 4<<20) + if err != nil { + t.Fatal(err) + } + want := bytes.ReplaceAll(payload, []byte{0}, []byte(`\u0000`)) + if !bytes.Equal(got, want) { + t.Fatal("body contents changed") + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(got)) { + t.Fatalf("retained %d bytes, final allocation is %d", used, cap(got)) + } + release() + if used := requestBodyBudgetUsed(budget); used != 0 { + t.Fatalf("handler cleanup retained %d bytes", used) + } + }) + } + } +} + +func TestRequestBodyMemoryBudgetReusesTransientCapacityWhileHandlersWait(t *testing.T) { + const bodySize = requestBodyReadMaxInitCap + 512 + // Enough for two retained bodies plus the third body before concatenation. + // A third simultaneous final copy must still be rejected. + budget := NewBodyMemoryBudget(3*bodySize + 1) + payload := bytes.Repeat([]byte{'x'}, bodySize) + readDone := make(chan error, 2) + finish := make(chan struct{}) + var handlers sync.WaitGroup + defer func() { + close(finish) + handlers.Wait() + if used := requestBodyBudgetUsed(budget); used != 0 { + t.Errorf("completed handlers retained %d bytes", used) + } + }() + handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + ctx, release := WithRequestBodyMemoryBudget(req.Context(), budget) + defer release() + body, err := ReadRequestBodyWithPrealloc(req.WithContext(ctx)) + if err != nil { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + readDone <- nil + <-finish + // Keep the final body live for the entire waiting handler. + _, _ = w.Write(body[:1]) + }) + for range 2 { + handlers.Go(func() { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))) + if recorder.Code != http.StatusOK { + readDone <- errors.New("temporary allocations blocked a second held request") + } + }) + select { + case err := <-readDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("request did not finish reading") + } + } + if used := requestBodyBudgetUsed(budget); used != 2*bodySize { + t.Fatalf("waiting handlers retain %d bytes, want %d", used, 2*bodySize) + } + thirdDone := make(chan *httptest.ResponseRecorder, 1) + handlers.Go(func() { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(payload))) + thirdDone <- recorder + }) + select { + case recorder := <-thirdDone: + if recorder.Code != http.StatusServiceUnavailable { + t.Fatalf("third request escaped the transient peak budget: %d", recorder.Code) + } + case <-readDone: + t.Fatal("third request escaped the transient peak budget") + case <-time.After(5 * time.Second): + t.Fatal("third request did not reject overload") + } + if used := requestBodyBudgetUsed(budget); used != 2*bodySize { + t.Fatalf("failed request retained temporary storage: %d", used) + } +} + +type requestBodyBudgetReaderFunc func([]byte) (int, error) + +func (read requestBodyBudgetReaderFunc) Read(p []byte) (int, error) { return read(p) } + +func TestRequestBodyMemoryBudgetRefundsFailedOwnedBuffers(t *testing.T) { + for _, name := range []string{"unknown_length_overload", "concat_overload", "normalization_overload", "normalization_size", "invalid_gzip", "invalid_zstd", "read_error", "cancellation"} { + t.Run(name, func(t *testing.T) { + budget := NewBodyMemoryBudget(16 << 20) + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx, release := WithRequestBodyMemoryBudget(parent, budget) + defer release() + // A previous returned/borrowed allocation must survive this failure. + if err := reserveRequestBodyMemory(ctx, 100); err != nil { + t.Fatal(err) + } + payload := []byte(`{"input":"` + strings.Repeat("x", 100) + `"}`) + maxNormalized := int64(4 << 20) + encoding := "" + var wantErr error + switch name { + case "unknown_length_overload": + budget.limit = 4096 + payload = bytes.Repeat([]byte{'x'}, 8192) + wantErr = ErrRequestBodyMemoryBudget + case "concat_overload": + budget.limit = 20000 + payload = bytes.Repeat([]byte{'x'}, 8192) + wantErr = ErrRequestBodyMemoryBudget + case "normalization_overload": + budget.limit = 600 + payload = []byte(`{"input":"` + strings.Repeat("\x00", 100) + `"}`) + wantErr = ErrRequestBodyMemoryBudget + case "normalization_size": + maxNormalized = 64 + case "invalid_gzip": + encoding = "gzip" + case "invalid_zstd": + encoding = "zstd" + case "read_error": + wantErr = io.ErrUnexpectedEOF + case "cancellation": + wantErr = context.Canceled + } + req := newRequestWithBody(t, payload, encoding).WithContext(ctx) + req.ContentLength = -1 + if name == "normalization_overload" { + req.ContentLength = int64(len(payload)) + } + if name == "read_error" { + req.Body = io.NopCloser(io.MultiReader(bytes.NewReader(payload), requestBodyBudgetReaderFunc(func([]byte) (int, error) { + return 0, io.ErrUnexpectedEOF + }))) + } + if name == "cancellation" { + reader := bytes.NewReader(payload) + req.Body = io.NopCloser(requestBodyBudgetReaderFunc(func(p []byte) (int, error) { + n, err := reader.Read(p) + cancel() + return n, err + })) + } + got, err := ReadLenientJSONRequestBodyWithPrealloc(req, maxNormalized) + if got != nil || err == nil || wantErr != nil && !errors.Is(err, wantErr) { + t.Fatalf("expected failed read (%v), got len=%d err=%v", wantErr, len(got), err) + } + if used := requestBodyBudgetUsed(budget); used != 100 { + t.Fatalf("failed read retained temporary storage or refunded another owner: %d", used) + } + }) + } +} + +func TestRequestBodyMemoryBudgetPreservesBorrowedPrereadAllocation(t *testing.T) { + budget := NewBodyMemoryBudget(4096) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + payload := []byte(`{"input":"hello` + "\x00" + `"}`) + req := newRequestWithBody(t, payload, "").WithContext(ctx) + original, err := ReadRequestBodyWithPrealloc(req) + if err != nil { + t.Fatal(err) + } + req.Body = NewPrereadBody(original) + if _, err := ReadLenientJSONRequestBodyWithPrealloc(req, 1); err == nil { + t.Fatal("oversize preread body was accepted") + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(original)) { + t.Fatalf("failed normalization refunded borrowed storage: %d", used) + } + normalized, err := ReadLenientJSONRequestBodyWithPrealloc(req, 4096) + if err != nil { + t.Fatal(err) + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(original)+cap(normalized)) { + t.Fatalf("original and normalized bodies remain live but only %d bytes are charged", used) + } + again, err := ReadRequestBodyWithPrealloc(req) + if err != nil || !bytes.Equal(again, payload) || &again[0] != &original[0] { + t.Fatal("normalization changed the borrowed preread body") + } + if used := requestBodyBudgetUsed(budget); used != int64(cap(original)+cap(normalized)) { + t.Fatalf("preread fast path changed the budget: %d", used) + } +} diff --git a/backend/internal/pkg/httputil/read_timeout.go b/backend/internal/pkg/httputil/read_timeout.go new file mode 100644 index 0000000000..9c74c450a0 --- /dev/null +++ b/backend/internal/pkg/httputil/read_timeout.go @@ -0,0 +1,156 @@ +package httputil + +import ( + "bufio" + "errors" + "io" + "net" + "net/http" + "sync/atomic" + "time" +) + +// WithBodyReadTimeout bounds each socket read while receiving a body. It does +// not set a whole-request deadline or limit the duration of an SSE response. +func WithBodyReadTimeout(next http.Handler, timeout time.Duration) http.Handler { + if timeout <= 0 { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Body != nil && r.Body != http.NoBody { + body := &bodyReadTimeout{ReadCloser: r.Body, controller: http.NewResponseController(w), timeout: timeout} + r.Body = body + if r.ProtoMajor == 1 { + writer := &bodyDrainTimeoutWriter{ResponseWriter: w, body: body} + defer func() { + if !writer.hijacked.Load() { + // net/http closes its original body after ServeHTTP returns, + // bypassing our Read and Close methods. + body.startDrain() + } + }() + next.ServeHTTP(writer, r) + return + } + } + next.ServeHTTP(w, r) + }) +} + +type bodyReadTimeout struct { + io.ReadCloser + controller *http.ResponseController + timeout time.Duration + finished atomic.Bool + failed atomic.Bool +} + +func (r *bodyReadTimeout) Read(p []byte) (int, error) { + err := r.controller.SetReadDeadline(time.Now().Add(r.timeout)) + if err != nil && !errors.Is(err, http.ErrNotSupported) { + return 0, err + } + n, readErr := r.ReadCloser.Read(p) + if errors.Is(readErr, io.EOF) { + r.finished.Store(true) + } else if readErr != nil { + r.failed.Store(true) + } + if readErr == nil || errors.Is(readErr, io.EOF) { + _ = r.controller.SetReadDeadline(time.Time{}) + } + // Keep a failed read's deadline: net/http may drain an unread HTTP/1 body + // after the handler returns. Clearing a timeout here could block that drain. + return n, readErr +} + +func (r *bodyReadTimeout) Close() error { + armed := r.startDrain() + err := r.ReadCloser.Close() + if err == nil { + r.finished.Store(true) + } else { + r.failed.Store(true) + } + r.finishDrain(armed) + return err +} + +func (r *bodyReadTimeout) startDrain() bool { + if r.finished.Load() || r.failed.Load() { + return false + } + return r.controller.SetReadDeadline(time.Now().Add(r.timeout)) == nil +} + +func (r *bodyReadTimeout) finishDrain(armed bool) { + if armed && !r.failed.Load() { + _ = r.controller.SetReadDeadline(time.Time{}) + } +} + +// HTTP/1 can drain an unread request body during its first response write or +// flush as well as after the handler returns. These reads use net/http's original +// body, so guard the response operations too. HTTP/2 has no such implicit drain. +type bodyDrainTimeoutWriter struct { + http.ResponseWriter + body *bodyReadTimeout + hijacked atomic.Bool + fullDuplex atomic.Bool +} + +func (w *bodyDrainTimeoutWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func (w *bodyDrainTimeoutWriter) startDrain() bool { + return !w.fullDuplex.Load() && w.body.startDrain() +} + +func (w *bodyDrainTimeoutWriter) Write(p []byte) (int, error) { + armed := w.startDrain() + defer w.body.finishDrain(armed) + return w.ResponseWriter.Write(p) +} + +func (w *bodyDrainTimeoutWriter) WriteString(s string) (int, error) { + armed := w.startDrain() + defer w.body.finishDrain(armed) + return io.WriteString(w.ResponseWriter, s) +} + +func (w *bodyDrainTimeoutWriter) WriteHeader(status int) { + armed := w.startDrain() + defer w.body.finishDrain(armed) + w.ResponseWriter.WriteHeader(status) +} + +func (w *bodyDrainTimeoutWriter) FlushError() error { + armed := w.startDrain() + defer w.body.finishDrain(armed) + return http.NewResponseController(w.ResponseWriter).Flush() +} + +func (w *bodyDrainTimeoutWriter) Flush() { _ = w.FlushError() } + +func (w *bodyDrainTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack() + if err == nil { + w.hijacked.Store(true) + _ = conn.SetReadDeadline(time.Time{}) + } + return conn, rw, err +} + +func (w *bodyDrainTimeoutWriter) EnableFullDuplex() error { + if err := http.NewResponseController(w.ResponseWriter).EnableFullDuplex(); err != nil { + return err + } + w.fullDuplex.Store(true) + return nil +} + +func (w *bodyDrainTimeoutWriter) CloseNotify() <-chan bool { + if notifier, ok := w.ResponseWriter.(http.CloseNotifier); ok { //nolint:staticcheck // Gin's ResponseWriter still requires legacy CloseNotify forwarding. + return notifier.CloseNotify() + } + return make(chan bool) +} diff --git a/backend/internal/pkg/httputil/read_timeout_test.go b/backend/internal/pkg/httputil/read_timeout_test.go new file mode 100644 index 0000000000..6d10bc9e6f --- /dev/null +++ b/backend/internal/pkg/httputil/read_timeout_test.go @@ -0,0 +1,261 @@ +package httputil + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestBodyReadTimeoutReleasesStalledUpload(t *testing.T) { + readDone := make(chan error, 1) + srv := httptest.NewServer(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, err := io.ReadAll(r.Body) + readDone <- err + }), 100*time.Millisecond)) + defer srv.Close() + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + if _, err := io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1024\r\n\r\nx"); err != nil { + t.Fatal(err) + } + select { + case err := <-readDone: + var timeout net.Error + if !errors.As(err, &timeout) || !timeout.Timeout() { + t.Fatalf("want upload timeout, got %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("stalled upload retained handler") + } +} + +func TestBodyReadTimeoutClosesStalledHTTP1Connection(t *testing.T) { + closed := make(chan struct{}, 1) + handlerDone := make(chan struct{}) + srv := httptest.NewUnstartedServer(WithWriteTimeout(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if _, err := io.ReadAll(r.Body); err != nil { + w.WriteHeader(http.StatusBadRequest) + } + close(handlerDone) + }), 100*time.Millisecond), 100*time.Millisecond)) + srv.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateClosed { + select { + case closed <- struct{}{}: + default: + } + } + } + srv.Start() + defer srv.Close() + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + // Keep the remainder small enough for net/http's automatic post-handler + // drain. Clearing the failed read's deadline would strand that drain even + // though the application handler itself has already returned. + if _, err := io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1024\r\n\r\nx"); err != nil { + t.Fatal(err) + } + select { + case <-handlerDone: + case <-time.After(2 * time.Second): + t.Fatal("stalled upload retained handler") + } + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("timed-out upload retained the connection while net/http drained the unread body") + } +} + +func TestBodyReadTimeoutClosesRejectedHTTP1Upload(t *testing.T) { + for _, partialRead := range []bool{false, true} { + for _, response := range []string{"buffered", "flush", "large_write", "close_body"} { + name := response + "/unread" + if partialRead { + name = response + "/partial_read" + } + t.Run(name, func(t *testing.T) { + handlerDone := make(chan error, 1) + closed := make(chan struct{}, 1) + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if partialRead { + if _, err := io.ReadFull(r.Body, make([]byte, 1)); err != nil { + handlerDone <- err + return + } + } + ctx, release := WithRequestBodyMemoryBudget(r.Context(), NewBodyMemoryBudget(1)) + defer release() + _, err := ReadRequestBodyWithPrealloc(r.WithContext(ctx)) + if !errors.Is(err, ErrRequestBodyMemoryBudget) { + handlerDone <- errors.New("request did not exhaust its body budget") + return + } + w.WriteHeader(http.StatusServiceUnavailable) + switch response { + case "flush": + _ = http.NewResponseController(w).Flush() + case "large_write": + _, _ = w.Write([]byte(strings.Repeat("x", 8192))) + case "close_body": + _ = r.Body.Close() + default: + _, _ = io.WriteString(w, "busy") + } + handlerDone <- nil + }) + srv := httptest.NewUnstartedServer(WithWriteTimeout(WithBodyReadTimeout(handler, 50*time.Millisecond), 100*time.Millisecond)) + srv.Config.ConnState = func(_ net.Conn, state http.ConnState) { + if state == http.StateClosed { + select { + case closed <- struct{}{}: + default: + } + } + } + srv.Start() + defer srv.Close() + conn, err := net.Dial("tcp", srv.Listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer func() { _ = conn.Close() }() + if _, err := io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1024\r\n\r\nx"); err != nil { + t.Fatal(err) + } + select { + case err := <-handlerDone: + if err != nil { + t.Fatal(err) + } + case <-time.After(2 * time.Second): + t.Fatal("rejection blocked while writing the response or closing the body") + } + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("rejected upload retained its HTTP/1 connection") + } + }) + } + } +} + +func TestBodyReadTimeoutDoesNotLimitHTTP1ResponseLifetime(t *testing.T) { + for _, readAll := range []bool{false, true} { + name := "implicit_drain" + if readAll { + name = "complete_body" + } + t.Run(name, func(t *testing.T) { + handlerErr := make(chan error, 1) + srv := httptest.NewServer(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var err error + if readAll { + _, err = io.Copy(io.Discard, r.Body) + } else { + _, err = io.ReadFull(r.Body, make([]byte, 1)) + } + if err != nil { + handlerErr <- err + return + } + _, _ = io.WriteString(w, "first\n") + if err = http.NewResponseController(w).Flush(); err != nil { + handlerErr <- err + return + } + // The first flush implicitly consumes any unread body. Its read + // deadline must not cancel the response during upstream thinking. + timer := time.NewTimer(300 * time.Millisecond) + defer timer.Stop() + select { + case <-r.Context().Done(): + handlerErr <- r.Context().Err() + return + case <-timer.C: + } + _, err = io.WriteString(w, "last\n") + handlerErr <- err + }), 100*time.Millisecond)) + defer srv.Close() + client := srv.Client() + client.Timeout = 3 * time.Second + resp, err := client.Post(srv.URL, "application/json", strings.NewReader(`{"input":"hello"}`)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + if err != nil || string(body) != "first\nlast\n" { + t.Fatalf("response was truncated: %q, %v", body, err) + } + if err := <-handlerErr; err != nil { + t.Fatalf("response lifetime was limited by the upload deadline: %v", err) + } + }) + } +} + +func TestBodyReadTimeoutHTTP2DoesNotCancelOtherStreams(t *testing.T) { + readDone := make(chan error, 1) + srv := httptest.NewUnstartedServer(WithBodyReadTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/slow" { + _, err := io.ReadAll(r.Body) + readDone <- err + return + } + w.WriteHeader(http.StatusNoContent) + }), 100*time.Millisecond)) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + reader, writer := io.Pipe() + defer func() { _ = writer.Close() }() + slow, _ := http.NewRequestWithContext(ctx, http.MethodPost, srv.URL+"/slow", reader) + clientDone := make(chan struct{}) + go func() { + defer close(clientDone) + resp, err := srv.Client().Do(slow) + if err == nil { + _ = resp.Body.Close() + } + }() + defer func() { + cancel() + _ = writer.Close() + <-clientDone + }() + select { + case err := <-readDone: + if err == nil { + t.Fatal("stalled HTTP/2 upload accepted") + } + case <-ctx.Done(): + t.Fatal("stalled HTTP/2 upload retained handler") + } + fast, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/fast", nil) + resp, err := srv.Client().Do(fast) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + if resp.ProtoMajor != 2 || resp.StatusCode != http.StatusNoContent { + t.Fatalf("other stream failed: %s %s", resp.Proto, resp.Status) + } +} diff --git a/backend/internal/pkg/httputil/upstream_drain.go b/backend/internal/pkg/httputil/upstream_drain.go new file mode 100644 index 0000000000..9aee08bfb2 --- /dev/null +++ b/backend/internal/pkg/httputil/upstream_drain.go @@ -0,0 +1,73 @@ +package httputil + +import ( + "context" + "sync" + "time" +) + +const DefaultUpstreamDrainTimeout = 180 * time.Second + +type upstreamDrainKey struct{} +type upstreamDrainPolicy struct { + client context.Context + timeout time.Duration +} + +// DetachUpstreamContext keeps billing reads alive after the client leaves. It +// records the original cancellation signal without starting a timer or changing +// existing construction-time release semantics. The transport owns the actual +// attempt lifetime and installs the bounded drain when sending the request. +func DetachUpstreamContext(ctx context.Context, timeout ...time.Duration) context.Context { + if ctx == nil { + ctx = context.Background() + } + policy := upstreamDrainPolicy{client: ctx} + if previous, ok := ctx.Value(upstreamDrainKey{}).(upstreamDrainPolicy); ok { + policy = previous + } + if len(timeout) > 0 && timeout[0] > 0 { + policy.timeout = timeout[0] + } + return context.WithValue(context.WithoutCancel(ctx), upstreamDrainKey{}, policy) +} + +// NewUpstreamAttemptContext starts a total drain budget when the original client +// context is cancelled. Incoming bytes do not extend this budget. Until then the +// request may stream for arbitrarily long, and late usage remains readable +// throughout the drain window. release must run on error or response-body close. +func NewUpstreamAttemptContext(parent context.Context, defaultTimeout time.Duration) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(parent) + policy, ok := parent.Value(upstreamDrainKey{}).(upstreamDrainPolicy) + if !ok || policy.client.Done() == nil { + return ctx, cancel + } + timeout := policy.timeout + if timeout <= 0 { + timeout = defaultTimeout + } + if timeout <= 0 { + timeout = DefaultUpstreamDrainTimeout + } + var mu sync.Mutex + var timer *time.Timer + closed := false + startDrain := func() { + mu.Lock() + defer mu.Unlock() + if !closed { + timer = time.AfterFunc(timeout, cancel) + } + } + stop := context.AfterFunc(policy.client, startDrain) + return ctx, func() { + stop() + mu.Lock() + closed = true + if timer != nil { + timer.Stop() + } + mu.Unlock() + cancel() + } +} diff --git a/backend/internal/pkg/httputil/upstream_drain_test.go b/backend/internal/pkg/httputil/upstream_drain_test.go new file mode 100644 index 0000000000..b6e6f8f9cf --- /dev/null +++ b/backend/internal/pkg/httputil/upstream_drain_test.go @@ -0,0 +1,54 @@ +package httputil + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestUpstreamDrainStartsOnlyAfterClientCancellation(t *testing.T) { + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + upstream, release := NewUpstreamAttemptContext(DetachUpstreamContext(client), 30*time.Millisecond) + defer release() + time.Sleep(60 * time.Millisecond) + require.NoError(t, upstream.Err()) + cancelClient() + select { + case <-upstream.Done(): + t.Fatal("cancelled before late usage drain window") + case <-time.After(10 * time.Millisecond): + } + select { + case <-upstream.Done(): + require.ErrorIs(t, upstream.Err(), context.Canceled) + case <-time.After(time.Second): + t.Fatal("drain exceeded total budget") + } +} + +func TestUpstreamDrainOverrideAndNestedDetachKeepOriginalSignal(t *testing.T) { + client, cancelClient := context.WithCancel(context.Background()) + parent := DetachUpstreamContext(DetachUpstreamContext(client, 20*time.Millisecond)) + upstream, release := NewUpstreamAttemptContext(parent, time.Second) + defer release() + cancelClient() + select { + case <-upstream.Done(): + case <-time.After(200 * time.Millisecond): + t.Fatal("nested detach lost original cancellation or override") + } +} + +func TestUpstreamDrainReleaseDoesNotCancelCaller(t *testing.T) { + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + upstream, release := NewUpstreamAttemptContext(DetachUpstreamContext(client), time.Second) + release() + release() + require.ErrorIs(t, upstream.Err(), context.Canceled) + require.NoError(t, client.Err()) + cancelClient() +} diff --git a/backend/internal/pkg/httputil/write_timeout.go b/backend/internal/pkg/httputil/write_timeout.go new file mode 100644 index 0000000000..3fbdc664f5 --- /dev/null +++ b/backend/internal/pkg/httputil/write_timeout.go @@ -0,0 +1,116 @@ +package httputil + +import ( + "bufio" + "context" + "errors" + "io" + "net" + "net/http" + "time" +) + +// WithWriteTimeout bounds individual writes and flushes. Clearing the deadline +// after each operation permits arbitrarily long upstream thinking intervals. +// Wrapping below Gin also covers all its ResponseWriter decorators and keeps +// HTTP/2 deadlines scoped to the individual stream. +func WithWriteTimeout(next http.Handler, timeout time.Duration) http.Handler { + if timeout <= 0 { + return next + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + writer := &writeTimeoutWriter{ResponseWriter: w, timeout: timeout, cancel: cancel} + next.ServeHTTP(writer, r.WithContext(ctx)) + }) +} + +type writeTimeoutWriter struct { + http.ResponseWriter + timeout time.Duration + cancel context.CancelFunc + err error +} + +func (w *writeTimeoutWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func (w *writeTimeoutWriter) start() error { + if w.err != nil { + return w.err + } + err := http.NewResponseController(w.ResponseWriter).SetWriteDeadline(time.Now().Add(w.timeout)) + if err != nil && !errors.Is(err, http.ErrNotSupported) { + w.fail(err) + } + return w.err +} + +func (w *writeTimeoutWriter) finish() { + _ = http.NewResponseController(w.ResponseWriter).SetWriteDeadline(time.Time{}) +} + +func (w *writeTimeoutWriter) fail(err error) { + if err != nil { + w.err = err + w.cancel() + } +} + +func (w *writeTimeoutWriter) Write(p []byte) (int, error) { + if err := w.start(); err != nil { + return 0, err + } + defer w.finish() + n, err := w.ResponseWriter.Write(p) + w.fail(err) + return n, err +} + +func (w *writeTimeoutWriter) WriteString(s string) (int, error) { + if err := w.start(); err != nil { + return 0, err + } + defer w.finish() + n, err := io.WriteString(w.ResponseWriter, s) + w.fail(err) + return n, err +} + +func (w *writeTimeoutWriter) WriteHeader(status int) { + if w.start() != nil { + return + } + defer w.finish() + w.ResponseWriter.WriteHeader(status) +} + +func (w *writeTimeoutWriter) FlushError() error { + if err := w.start(); err != nil { + return err + } + defer w.finish() + err := http.NewResponseController(w.ResponseWriter).Flush() + w.fail(err) + return err +} + +func (w *writeTimeoutWriter) Flush() { _ = w.FlushError() } + +func (w *writeTimeoutWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return http.NewResponseController(w.ResponseWriter).Hijack() +} + +func (w *writeTimeoutWriter) Push(target string, opts *http.PushOptions) error { + if pusher, ok := w.ResponseWriter.(http.Pusher); ok { + return pusher.Push(target, opts) + } + return http.ErrNotSupported +} + +func (w *writeTimeoutWriter) CloseNotify() <-chan bool { + if notifier, ok := w.ResponseWriter.(http.CloseNotifier); ok { //nolint:staticcheck // Gin still exposes CloseNotify; preserve legacy writer compatibility. + return notifier.CloseNotify() + } + return make(chan bool) +} diff --git a/backend/internal/pkg/httputil/write_timeout_test.go b/backend/internal/pkg/httputil/write_timeout_test.go new file mode 100644 index 0000000000..e5d026ebaa --- /dev/null +++ b/backend/internal/pkg/httputil/write_timeout_test.go @@ -0,0 +1,145 @@ +package httputil + +import ( + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestWriteTimeoutReleasesSlowHTTP1Client(t *testing.T) { + type result struct { + err error + cancelled bool + } + finished := make(chan result, 1) + srv := httptest.NewServer(WithWriteTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + payload := make([]byte, 64<<10) + for i := 0; i < 1024; i++ { + if _, err := w.Write(payload); err != nil { + finished <- result{err, r.Context().Err() != nil} + return + } + } + finished <- result{} + }), 40*time.Millisecond)) + defer srv.Close() + conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://")) + require.NoError(t, err) + defer func() { _ = conn.Close() }() + if tcp, ok := conn.(*net.TCPConn); ok { + require.NoError(t, tcp.SetReadBuffer(1024)) + } + _, err = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: example\r\n\r\n") + require.NoError(t, err) + select { + case got := <-finished: + require.Error(t, got.err) + require.True(t, got.cancelled) + case <-time.After(3 * time.Second): + t.Fatal("slow HTTP/1 client blocked the handler past its write timeout") + } +} + +func TestWriteTimeoutOnlyCancelsSlowHTTP2Stream(t *testing.T) { + finished := make(chan error, 1) + srv := httptest.NewUnstartedServer(WithWriteTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/fast" { + _, _ = io.WriteString(w, "ok") + return + } + w.Header().Set("Content-Type", "text/event-stream") + _ = http.NewResponseController(w).Flush() + payload := make([]byte, 64<<10) + for i := 0; i < 1024; i++ { + if _, err := w.Write(payload); err != nil { + if r.Context().Err() == nil { + finished <- errors.New("write failed without cancelling request") + } else { + finished <- err + } + return + } + } + finished <- nil + }), 40*time.Millisecond)) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + client := srv.Client() + client.Timeout = 3 * time.Second + resp, err := client.Get(srv.URL + "/slow") + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + require.Equal(t, 2, resp.ProtoMajor) + select { + case err := <-finished: + require.Error(t, err) + case <-time.After(3 * time.Second): + t.Fatal("HTTP/2 flow-control stall did not time out") + } + fast, err := client.Get(srv.URL + "/fast") + require.NoError(t, err) + defer func() { _ = fast.Body.Close() }() + body, err := io.ReadAll(fast.Body) + require.NoError(t, err) + require.Equal(t, "ok", string(body)) +} + +func TestWriteTimeoutClearsDeadlineDuringUpstreamThinkTime(t *testing.T) { + srv := httptest.NewServer(WithWriteTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.WriteString(w, "first") + _ = http.NewResponseController(w).Flush() + time.Sleep(80 * time.Millisecond) + _, _ = io.WriteString(w, "second") + _ = http.NewResponseController(w).Flush() + }), 20*time.Millisecond)) + defer srv.Close() + resp, err := srv.Client().Get(srv.URL) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.Equal(t, "firstsecond", string(body)) +} + +type deadlineFlushWriter struct { + header http.Header + deadline time.Time +} + +func (w *deadlineFlushWriter) Header() http.Header { return w.header } +func (w *deadlineFlushWriter) Write(p []byte) (int, error) { return len(p), nil } +func (w *deadlineFlushWriter) WriteHeader(int) {} +func (w *deadlineFlushWriter) SetWriteDeadline(deadline time.Time) error { + w.deadline = deadline + return nil +} +func (w *deadlineFlushWriter) FlushError() error { + if w.deadline.IsZero() { + return errors.New("flush has no deadline") + } + <-time.After(time.Until(w.deadline)) + return os.ErrDeadlineExceeded +} + +func TestWriteTimeoutFlushCancelsContextAndRemembersFailure(t *testing.T) { + underlying := &deadlineFlushWriter{header: make(http.Header)} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + w := &writeTimeoutWriter{ResponseWriter: underlying, timeout: 10 * time.Millisecond, cancel: cancel} + err := w.FlushError() + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + require.ErrorIs(t, ctx.Err(), context.Canceled) + require.True(t, underlying.deadline.IsZero()) + _, err = w.Write([]byte("must not retry after failed flush")) + require.ErrorIs(t, err, os.ErrDeadlineExceeded) +} diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index bd9b1b0419..733ff9034b 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1969,7 +1969,7 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro if scoped := r.accountTransactionScope(ctx); scoped != r { return scoped.BindGroups(ctx, accountID, groupIDs) } - if adminaccess.FromContext(ctx) != nil { + if adminaccess.RestrictedFromContext(ctx) != nil { return r.scopedAdminBindGroups(ctx, accountID, groupIDs) } existingGroupIDs, err := r.loadAccountGroupIDs(ctx, accountID) diff --git a/backend/internal/repository/custom_admin_key_group_capacity.go b/backend/internal/repository/custom_admin_key_group_capacity.go new file mode 100644 index 0000000000..d9962e1134 --- /dev/null +++ b/backend/internal/repository/custom_admin_key_group_capacity.go @@ -0,0 +1,37 @@ +package repository + +import ( + "context" + + "github.com/Wei-Shaw/sub2api/ent/group" + "github.com/Wei-Shaw/sub2api/ent/predicate" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// ListScopedAdminCapacityGroupIDs 先在数据库内限定分组,再查询账户与实时容量。 +func (r *groupRepository) ListScopedAdminCapacityGroupIDs(ctx context.Context) ([]int64, error) { + p := adminaccess.FromContext(ctx) + if p == nil { + return nil, infraerrors.Forbidden("SCOPED_GROUP_CAPACITY_FORBIDDEN", "缺少受限身份") + } + alternatives := []predicate.Group{} + for _, rule := range p.Policy.RulesFor("groups.capacity.read") { + terms := []predicate.Group{group.IDGT(0)} + if !rule.AllGroups { + if len(rule.GroupIDs) == 0 { + continue + } + terms = append(terms, group.IDIn(rule.GroupIDs...)) + } + if len(rule.Platforms) > 0 { + terms = append(terms, group.PlatformIn(rule.Platforms...)) + } + alternatives = append(alternatives, group.And(terms...)) + } + if len(alternatives) == 0 { + return []int64{}, nil + } + return r.client.Group.Query().Where(group.DeletedAtIsNil(), group.StatusEQ(service.StatusActive), group.Or(alternatives...)).Order(group.ByID()).IDs(ctx) +} diff --git a/backend/internal/repository/custom_admin_key_group_models.go b/backend/internal/repository/custom_admin_key_group_models.go index f7d219f987..a12dae8521 100644 --- a/backend/internal/repository/custom_admin_key_group_models.go +++ b/backend/internal/repository/custom_admin_key_group_models.go @@ -25,7 +25,7 @@ func (r *groupRepository) ScopedAdminUpdateGroupModels(ctx context.Context, id i defer func() { _ = tx.Rollback() }() txctx := dbent.NewTxContext(ctx, tx) row, err := tx.Client().Group.Query().Where(group.IDEQ(id), group.DeletedAtIsNil()). - Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldModelAllowlist).ForUpdate().Only(txctx) + Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldStatus, group.FieldModelAllowlist).ForUpdate().Only(txctx) if err != nil { return nil, translatePersistenceError(err, service.ErrGroupNotFound, nil) } @@ -42,7 +42,7 @@ func (r *groupRepository) ScopedAdminUpdateGroupModels(ctx context.Context, id i if err = tx.Commit(); err != nil { return nil, err } - return &service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, ModelAllowlist: cfg}, nil + return &service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, Status: row.Status, ModelAllowlist: cfg}, nil } // ScopedAdminListGroupModels 在数据库内过滤范围,分页和总数均只包含已授权分组。 @@ -52,7 +52,8 @@ func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params return nil, 0, infraerrors.Forbidden("SCOPED_GROUP_MODELS_FORBIDDEN", "缺少受限身份") } alternatives := []predicate.Group{} - for _, rule := range p.Policy.RulesFor("groups.models.read") { + rules := append(p.Policy.RulesFor("groups.models.read"), p.Policy.RulesFor("groups.list.read")...) + for _, rule := range rules { terms := []predicate.Group{group.IDGT(0)} if !rule.AllGroups { if len(rule.GroupIDs) == 0 { @@ -82,7 +83,7 @@ func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params if err != nil { return nil, 0, err } - q.Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldModelAllowlist).Order(group.ByID()) + q.Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldStatus).Order(group.ByID()) if !all { q.Offset(params.Offset()).Limit(params.Limit()) } @@ -91,8 +92,24 @@ func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params return nil, 0, err } result := make([]service.Group, 0, len(rows)) + modelIDs := make([]int64, 0, len(rows)) + modelIndexes := make(map[int64]int) for _, row := range rows { - result = append(result, service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, ModelAllowlist: service.GroupModelAllowlistFromDomain(row.ModelAllowlist)}) + result = append(result, service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, Status: row.Status}) + if p.Policy.AllowsGroupConfig("groups.models.read", row.ID, row.Platform) { + modelIDs = append(modelIDs, row.ID) + modelIndexes[row.ID] = len(result) - 1 + } + } + // 仅为独立模型读取权限允许的行加载配置,基本列表不读取模型或费率。 + if len(modelIDs) > 0 { + models, err := r.client.Group.Query().Where(group.IDIn(modelIDs...), group.DeletedAtIsNil()).Select(group.FieldID, group.FieldModelAllowlist).All(ctx) + if err != nil { + return nil, 0, err + } + for _, model := range models { + result[modelIndexes[model.ID]].ModelAllowlist = service.GroupModelAllowlistFromDomain(model.ModelAllowlist) + } } return result, int64(total), nil } diff --git a/backend/internal/repository/custom_admin_key_permissions_test.go b/backend/internal/repository/custom_admin_key_permissions_test.go new file mode 100644 index 0000000000..75a6110dce --- /dev/null +++ b/backend/internal/repository/custom_admin_key_permissions_test.go @@ -0,0 +1,230 @@ +//go:build unit + +package repository + +import ( + "context" + "database/sql" + "fmt" + "github.com/Wei-Shaw/sub2api/internal/service" + "os" + "strings" + "testing" + "time" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/stretchr/testify/require" +) + +func scopedPermissionsTestDB(t *testing.T, options ...dbent.Option) (*dbent.Client, *sql.DB) { + t.Helper() + dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN") + if dsn == "" { + t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN") + } + base, err := sql.Open("postgres", dsn) + require.NoError(t, err) + schema := fmt.Sprintf("permissions_test_%d", time.Now().UnixNano()) + _, err = base.Exec(`CREATE SCHEMA ` + schema) + require.NoError(t, err) + db, err := sql.Open("postgres", dsn+" search_path="+schema) + require.NoError(t, err) + client := dbent.NewClient(append([]dbent.Option{dbent.Driver(entsql.OpenDB(dialect.Postgres, db))}, options...)...) + t.Cleanup(func() { _ = client.Close(); _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`); _ = base.Close() }) + _, err = db.Exec(`CREATE TABLE groups(id BIGINT PRIMARY KEY, name TEXT DEFAULT '分组', platform TEXT DEFAULT 'openai', status TEXT DEFAULT 'active', model_allowlist JSONB DEFAULT '{}', deleted_at TIMESTAMPTZ); + CREATE TABLE accounts(id BIGINT PRIMARY KEY, name TEXT DEFAULT '账户', notes TEXT, platform TEXT DEFAULT 'openai', type TEXT DEFAULT 'oauth', status TEXT DEFAULT 'active', schedulable BOOLEAN DEFAULT true, concurrency INT DEFAULT 1, priority INT DEFAULT 1, credentials JSONB DEFAULT '{}', extra JSONB DEFAULT '{}', expires_at TIMESTAMPTZ, rate_limit_reset_at TIMESTAMPTZ, overload_until TIMESTAMPTZ, temp_unschedulable_until TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW(), deleted_at TIMESTAMPTZ); + CREATE TABLE account_groups(account_id BIGINT, group_id BIGINT, priority INT DEFAULT 50, created_at TIMESTAMPTZ DEFAULT NOW()); + INSERT INTO groups(id,platform,status) VALUES (1,'openai','active'),(2,'openai','active'),(3,'anthropic','active'),(4,'openai','inactive'); + INSERT INTO accounts(id,credentials,extra) VALUES (1,'{"email":"test@example.com","access_token":"SECRET"}','{}'),(2,'{}','{"email":"test@example.com"}'),(3,'{"email":"test@example.com"}','{}'); + INSERT INTO account_groups(account_id,group_id) VALUES (1,1),(1,9),(2,2),(3,3);`) + require.NoError(t, err) + return client, db +} + +func TestScopedAdminPermissionsPostgresFilters(t *testing.T) { + client, db := scopedPermissionsTestDB(t) + policy := adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"accounts.read", "groups.list.read", "groups.capacity.read"}, GroupIDs: []int64{1, 2, 3, 4}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + {Permissions: []string{"accounts.identity.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + {Permissions: []string{"groups.capacity.read"}, GroupIDs: []int64{2}, Platforms: []string{"anthropic"}}, + }} + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: policy}) + groups := newGroupRepositoryWithSQL(client, db) + ids, err := groups.ListScopedAdminCapacityGroupIDs(ctx) + require.NoError(t, err) + require.Equal(t, []int64{1, 2}, ids, "平台和分组不能跨规则拼接,停用组不能参与容量统计") + rows, total, err := groups.ScopedAdminListGroupModels(ctx, pagination.PaginationParams{Page: 1, PageSize: 1}, false, "openai", "active", "") + require.NoError(t, err) + require.EqualValues(t, 2, total) + require.Len(t, rows, 1) + require.Equal(t, "active", rows[0].Status) + accounts := newAccountRepositoryWithSQL(client, db, nil) + for _, tc := range []struct { + group int64 + search string + ids []int64 + }{ + {2, "", []int64{2}}, {1, "TEST@example.com", []int64{1}}, {2, "test@example.com", []int64{}}, {0, "test@example.com", []int64{1}}, {9, "", []int64{}}, + } { + rows, total, err := accounts.ScopedAdminList(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, "openai", "oauth", "", tc.search, tc.group) + require.NoError(t, err) + require.EqualValues(t, len(tc.ids), total) + ids := []int64{} + for _, row := range rows { + ids = append(ids, row.ID) + require.NotContains(t, row.Credentials, "access_token") + if row.ID == 1 { + require.Equal(t, "test@example.com", row.Credentials["email"]) + require.False(t, row.CreatedAt.IsZero()) + } else { + require.NotContains(t, row.Credentials, "email") + } + } + + require.Equal(t, tc.ids, ids) + } + _, err = groups.ListScopedAdminCapacityGroupIDs(context.Background()) + require.Error(t, err) +} + +func TestScopedAdminPermissionsWeeklySnapshotPostgres(t *testing.T) { + client, db := scopedPermissionsTestDB(t) + _, err := db.Exec(`UPDATE accounts SET credentials = '{"email":"test@example.com","access_token":"SECRET"}', extra = '{"email":"test@example.com","codex_usage_updated_at":"2026-10-25T00:00:00Z","codex_7d_used_percent":90,"codex_7d_reset_at":"2026-10-30T00:00:00Z","private":"SECRET"}'`) + require.NoError(t, err) + repo := newAccountRepositoryWithSQL(client, db, nil) + for _, tc := range []struct { + name string + usage adminaccess.Rule + identity bool + want bool + }{ + {name: "无额度权限"}, + {name: "仅身份权限", identity: true}, + {name: "仅额度权限", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, want: true}, + {name: "身份和额度权限", identity: true, usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, want: true}, + {name: "额度分组不匹配", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{99}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}, + {name: "额度类型不匹配", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"apikey"}, Platforms: []string{"openai"}}}, + {name: "额度平台不匹配", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"anthropic"}}}, + } { + t.Run(tc.name, func(t *testing.T) { + read := adminaccess.Rule{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1, 2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}} + if tc.identity { + read.Permissions = append(read.Permissions, "accounts.identity.read") + } + policy := adminaccess.Policy{Rules: []adminaccess.Rule{read}} + if len(tc.usage.Permissions) > 0 { + policy.Rules = append(policy.Rules, tc.usage) + } + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: policy}) + rows, total, err := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, "openai", "oauth", "", "", 0) + require.NoError(t, err) + require.EqualValues(t, 2, total) + require.Len(t, rows, 2) + for _, row := range rows { + want := map[string]any{} + if tc.identity { + want["email"] = "test@example.com" + require.Equal(t, "test@example.com", row.Credentials["email"]) + } + if tc.want && row.ID == 1 { + want["codex_usage_updated_at"] = "2026-10-25T00:00:00Z" + want["codex_7d_used_percent"] = float64(90) + want["codex_7d_reset_at"] = "2026-10-30T00:00:00Z" + } + if len(want) == 0 { + require.Empty(t, row.Extra) + } else { + require.Equal(t, want, row.Extra, "列表必须保留已授权的周额度快照,必须按行应用额度权限") + } + require.NotContains(t, row.Credentials, "access_token") + } + }) + } +} + +func TestScopedAdminPermissionBasicGroupRepositoryRedactsModels(t *testing.T) { + client, db := scopedPermissionsTestDB(t) + _, err := db.Exec(`UPDATE groups SET model_allowlist='{"enabled":true,"models":["private-model"]}'`) + require.NoError(t, err) + repo := newGroupRepositoryWithSQL(client, db) + p := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"groups.list.read"}, GroupIDs: []int64{1, 2}, Platforms: []string{"openai"}}, + {Permissions: []string{"groups.models.read"}, GroupIDs: []int64{2}, Platforms: []string{"openai"}}, + }}} + rows, total, err := repo.ScopedAdminListGroupModels(adminaccess.WithPrincipal(context.Background(), p), pagination.DefaultPagination(), false, "", "", "") + require.NoError(t, err) + require.EqualValues(t, 2, total) + require.Len(t, rows, 2) + require.Empty(t, rows[0].ModelAllowlist.Models, "基本分组权限不能加载模型配置") + require.Equal(t, []string{"private-model"}, rows[1].ModelAllowlist.Models) +} + +func TestScopedAdminGroupModelsUpdatePreservesStatusPostgres(t *testing.T) { + client, db := scopedPermissionsTestDB(t) + _, err := db.Exec(`ALTER TABLE groups ADD COLUMN updated_at TIMESTAMPTZ; + CREATE TABLE scheduler_outbox(id BIGSERIAL PRIMARY KEY,event_type TEXT,account_id BIGINT,group_id BIGINT,payload JSONB,dedup_key TEXT); + CREATE UNIQUE INDEX outbox_dedup ON scheduler_outbox(dedup_key) WHERE dedup_key IS NOT NULL;`) + require.NoError(t, err) + repo := newGroupRepositoryWithSQL(client, db) + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.write"}, GroupIDs: []int64{1}, Platforms: []string{"openai"}}}}}) + cfg := service.GroupModelAllowlist{Enabled: true, Models: []string{"model"}} + for _, status := range []string{"active", "inactive"} { + t.Run(status, func(t *testing.T) { + _, err := db.Exec(`UPDATE groups SET status=$1 WHERE id=1`, status) + require.NoError(t, err) + updated, err := repo.ScopedAdminUpdateGroupModels(ctx, 1, cfg) + require.NoError(t, err) + require.Equal(t, status, updated.Status) + var stored string + require.NoError(t, db.QueryRow(`SELECT status FROM groups WHERE id=1`).Scan(&stored)) + require.Equal(t, status, stored) + }) + } +} + +func TestScopedAdminIdentityProjectionBatchesAuthorizedPagePostgres(t *testing.T) { + identityQueries := []string{} + client, db := scopedPermissionsTestDB(t, dbent.Debug(), dbent.Log(func(args ...any) { + query := fmt.Sprint(args...) + if strings.Contains(query, "subscription_expires_at") { + identityQueries = append(identityQueries, query) + } + })) + _, err := db.Exec(`INSERT INTO accounts(id,credentials,extra) SELECT i,'{"email":"batch@example.com","access_token":"SECRET","model_mapping":{"alias":"target"}}'::jsonb,'{"email":"batch@example.com","codex_7d_used_percent":90,"private":"SECRET"}'::jsonb FROM generate_series(100,199) i; + INSERT INTO account_groups(account_id,group_id) SELECT i,CASE WHEN i%2=0 THEN 1 ELSE 2 END FROM generate_series(100,199) i;`) + require.NoError(t, err) + policy := adminaccess.Policy{Rules: []adminaccess.Rule{ + {Permissions: []string{"accounts.read"}, GroupIDs: []int64{1, 2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + {Permissions: []string{"accounts.identity.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + {Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, + }} + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: policy}) + repo := newAccountRepositoryWithSQL(client, db, nil) + rows, total, err := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, "openai", "oauth", "", "", 0) + require.NoError(t, err) + require.EqualValues(t, 102, total) + require.Len(t, rows, 100) + for _, row := range rows { + resource := adminaccess.Account{ID: row.ID, Type: row.Type, Platform: row.Platform, GroupIDs: row.GroupIDs} + if policy.AllowsAccount("accounts.identity.read", resource) { + require.Contains(t, row.Credentials, "email") + require.False(t, row.CreatedAt.IsZero()) + } else { + require.NotContains(t, row.Credentials, "email") + require.NotContains(t, row.Extra, "email") + require.True(t, row.CreatedAt.IsZero()) + } + if row.ID >= 100 { + require.Equal(t, map[string]string{"alias": "target"}, row.Credentials["model_mapping"]) + require.Equal(t, policy.AllowsAccount("accounts.usage.read", resource), row.Extra["codex_7d_used_percent"] != nil) + } + require.NotContains(t, row.Credentials, "access_token") + require.NotContains(t, row.Extra, "private") + } + require.Equal(t, 1, len(identityQueries), "同一分页的身份信息必须单次批量读取") + require.Contains(t, identityQueries[0], `"accounts"."id" IN (`) +} diff --git a/backend/internal/repository/custom_admin_key_scope.go b/backend/internal/repository/custom_admin_key_scope.go index 79e9fd19fe..46e20dfd0c 100644 --- a/backend/internal/repository/custom_admin_key_scope.go +++ b/backend/internal/repository/custom_admin_key_scope.go @@ -6,6 +6,7 @@ import ( "fmt" "slices" "strings" + "time" entsql "entgo.io/ent/dialect/sql" dbent "github.com/Wei-Shaw/sub2api/ent" @@ -17,35 +18,62 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" ) -func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string) ([]service.Account, int64, error) { +func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string, groupID int64) ([]service.Account, int64, error) { principal := adminaccess.FromContext(ctx) if principal == nil { return nil, 0, fmt.Errorf("缺少受限身份") } - alternatives := scopedAdminAccountPredicates(principal.Policy, "accounts.read") + readPolicy := principal.Policy + if groupID > 0 { + readPolicy.Rules = nil + for _, rule := range principal.Policy.RulesFor("accounts.read") { + if rule.AllGroups || slices.Contains(rule.GroupIDs, groupID) { + readPolicy.Rules = append(readPolicy.Rules, rule) + } + } + } + alternatives := scopedAdminAccountPredicates(readPolicy, "accounts.read") if len(alternatives) == 0 { return []service.Account{}, 0, nil } - q := r.accountListFilteredQuery(platform, kind, status, search, 0, "").Where(dbaccount.Or(alternatives...)) + q := r.accountListFilteredQuery(platform, kind, status, "", groupID, "").Where(dbaccount.Or(alternatives...)) + if search != "" { + matches := []dbpredicate.Account{dbaccount.NameContainsFold(search)} + identityScope := scopedAdminAccountPredicates(principal.Policy, "accounts.identity.read") + if len(identityScope) > 0 { + email := dbpredicate.Account(func(s *entsql.Selector) { + s.Where(entsql.P(func(b *entsql.Builder) { + b.WriteString("(lower(" + s.C(dbaccount.FieldCredentials) + "->>'email') = ").Arg(strings.ToLower(search)) + b.WriteString(" OR lower(" + s.C(dbaccount.FieldExtra) + "->>'email') = ").Arg(strings.ToLower(search)).WriteString(")") + })) + }) + matches = append(matches, dbaccount.And(dbaccount.Or(identityScope...), email)) + } + q.Where(dbaccount.Or(matches...)) + } total, err := q.Clone().Count(ctx) if err != nil { return nil, 0, err } // SQL 只投影模型映射子字段,不加载 Token、API Key、接入地址或其他凭证。 var rows []struct { - ID int64 - Name string - Notes *string - Platform string - Type string - Status string - Schedulable bool - Concurrency int - Priority int - ModelMapping json.RawMessage `json:"model_mapping"` + ID int64 + Name string + Notes *string + Platform string + Type string + Status string + Schedulable bool + Concurrency int + Priority int + ExpiresAt *time.Time `json:"expires_at"` + RateLimitResetAt *time.Time `json:"rate_limit_reset_at"` + OverloadUntil *time.Time `json:"overload_until"` + TempUnschedulableUntil *time.Time `json:"temp_unschedulable_until"` + ModelMapping json.RawMessage `json:"model_mapping"` } err = q.Offset(p.Offset()).Limit(p.Limit()).Order(dbaccount.ByID()). - Select(dbaccount.FieldID, dbaccount.FieldName, dbaccount.FieldNotes, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldStatus, dbaccount.FieldSchedulable, dbaccount.FieldConcurrency, dbaccount.FieldPriority). + Select(dbaccount.FieldID, dbaccount.FieldName, dbaccount.FieldNotes, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldStatus, dbaccount.FieldSchedulable, dbaccount.FieldConcurrency, dbaccount.FieldPriority, dbaccount.FieldExpiresAt, dbaccount.FieldRateLimitResetAt, dbaccount.FieldOverloadUntil, dbaccount.FieldTempUnschedulableUntil). Aggregate(func(s *entsql.Selector) string { return s.C(dbaccount.FieldCredentials) + "->'model_mapping' AS model_mapping" }).Scan(ctx, &rows) @@ -71,7 +99,75 @@ func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.Pa if len(mapping) > 0 { credentials = map[string]any{"model_mapping": mapping} } - accounts = append(accounts, service.Account{ID: row.ID, Name: row.Name, Notes: row.Notes, Platform: row.Platform, Type: row.Type, Status: row.Status, Schedulable: row.Schedulable, Concurrency: row.Concurrency, Priority: row.Priority, GroupIDs: groups, Credentials: credentials}) + a := service.Account{ID: row.ID, Name: row.Name, Notes: row.Notes, Platform: row.Platform, Type: row.Type, Status: row.Status, Schedulable: row.Schedulable, Concurrency: row.Concurrency, Priority: row.Priority, GroupIDs: groups, Credentials: credentials, ExpiresAt: row.ExpiresAt, RateLimitResetAt: row.RateLimitResetAt, OverloadUntil: row.OverloadUntil, TempUnschedulableUntil: row.TempUnschedulableUntil} + accounts = append(accounts, a) + } + // 身份字段只为本页逐行鉴权通过的账户批量投影,不加载完整凭证或 extra。 + identityIDs := make([]int64, 0, len(accounts)) + identityAccounts := make(map[int64]*service.Account) + for i := range accounts { + a := &accounts[i] + if principal.Policy.AllowsAccount("accounts.identity.read", adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Type: a.Type, Platform: a.Platform}) { + identityIDs = append(identityIDs, a.ID) + identityAccounts[a.ID] = a + } + } + if len(identityIDs) > 0 { + var identities []struct { + ID int64 `json:"id"` + CreatedAt time.Time `json:"created_at"` + Credentials json.RawMessage `json:"credentials"` + Extra json.RawMessage `json:"extra"` + } + err := r.client.Account.Query().Where(dbaccount.IDIn(identityIDs...)).Select(dbaccount.FieldID, dbaccount.FieldCreatedAt). + Aggregate(func(s *entsql.Selector) string { + return "jsonb_build_object('email', " + s.C(dbaccount.FieldCredentials) + "->'email', 'plan_type', " + s.C(dbaccount.FieldCredentials) + "->'plan_type', 'subscription_expires_at', " + s.C(dbaccount.FieldCredentials) + "->'subscription_expires_at') AS credentials" + }, func(s *entsql.Selector) string { + return "jsonb_build_object('email', " + s.C(dbaccount.FieldExtra) + "->'email') AS extra" + }).Scan(ctx, &identities) + if err != nil { + return nil, 0, err + } + for _, identity := range identities { + a := identityAccounts[identity.ID] + if err := json.Unmarshal(identity.Credentials, &a.Credentials); err != nil { + return nil, 0, err + } + if err := json.Unmarshal(identity.Extra, &a.Extra); err != nil { + return nil, 0, err + } + a.CreatedAt = identity.CreatedAt + } + } + // 仅为本页已获额度权限的账户批量加载三个周额度快照字段。 + usageIDs := make([]int64, 0, len(accounts)) + usageAccounts := make(map[int64]*service.Account) + for i := range accounts { + a := &accounts[i] + if principal.Policy.AllowsAccount("accounts.usage.read", adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Type: a.Type, Platform: a.Platform}) { + usageIDs = append(usageIDs, a.ID) + usageAccounts[a.ID] = a + } + } + if len(usageIDs) > 0 { + var snapshots []struct { + ID int64 `json:"id"` + Extra json.RawMessage `json:"extra"` + } + err := r.client.Account.Query().Where(dbaccount.IDIn(usageIDs...)).Select(dbaccount.FieldID). + Aggregate(func(s *entsql.Selector) string { + extra := s.C(dbaccount.FieldExtra) + return "jsonb_strip_nulls(jsonb_build_object('codex_usage_updated_at', " + extra + "->'codex_usage_updated_at', 'codex_7d_used_percent', " + extra + "->'codex_7d_used_percent', 'codex_7d_reset_at', " + extra + "->'codex_7d_reset_at')) AS extra" + }).Scan(ctx, &snapshots) + if err != nil { + return nil, 0, err + } + for _, snapshot := range snapshots { + // 合并到已有 extra,保留独立身份权限允许读取的邮箱。 + if err := json.Unmarshal(snapshot.Extra, &usageAccounts[snapshot.ID].Extra); err != nil { + return nil, 0, err + } + } } return accounts, int64(total), nil } diff --git a/backend/internal/repository/custom_admin_key_scope_test.go b/backend/internal/repository/custom_admin_key_scope_test.go index 06c192c9a0..979faceae5 100644 --- a/backend/internal/repository/custom_admin_key_scope_test.go +++ b/backend/internal/repository/custom_admin_key_scope_test.go @@ -63,7 +63,7 @@ func TestScopedAdminAccountListScopesCountAndPageInSQL(t *testing.T) { {Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}, {Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"apikey"}}, }}} - _, total, err := repo.ScopedAdminList(adminaccess.WithPrincipal(context.Background(), principal), pagination.PaginationParams{Page: 1, PageSize: 20}, "", "", "", "") + _, total, err := repo.ScopedAdminList(adminaccess.WithPrincipal(context.Background(), principal), pagination.PaginationParams{Page: 1, PageSize: 20}, "", "", "", "", 0) if err != nil { t.Fatal(err) } @@ -97,7 +97,7 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) { _, err = db.Exec(`CREATE TABLE accounts ( id BIGINT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', notes TEXT, platform TEXT NOT NULL, type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active', schedulable BOOLEAN NOT NULL DEFAULT true, - concurrency INT NOT NULL DEFAULT 1, priority INT NOT NULL DEFAULT 1, credentials JSONB DEFAULT '{}', deleted_at TIMESTAMPTZ + concurrency INT NOT NULL DEFAULT 1, priority INT NOT NULL DEFAULT 1, credentials JSONB DEFAULT '{}', expires_at TIMESTAMPTZ, rate_limit_reset_at TIMESTAMPTZ, overload_until TIMESTAMPTZ, temp_unschedulable_until TIMESTAMPTZ, deleted_at TIMESTAMPTZ ); CREATE TABLE account_groups(account_id BIGINT, group_id BIGINT, priority INT DEFAULT 50, created_at TIMESTAMPTZ DEFAULT NOW()); INSERT INTO accounts(id,platform,type) VALUES @@ -114,7 +114,7 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) { }}} ctx := adminaccess.WithPrincipal(context.Background(), principal) for page, wantID := range []int64{1, 4} { - rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: page + 1, PageSize: 1}, "", "", "", "") + rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: page + 1, PageSize: 1}, "", "", "", "", 0) require.NoError(t, listErr) require.EqualValues(t, 2, total) require.Len(t, rows, 1) @@ -129,7 +129,7 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) { for _, credentials := range []string{`{}`, `{"model_mapping":null}`, `{"model_mapping":{}}`, `{"model_mapping":[]}`, `{"model_mapping":"invalid"}`, `{"model_mapping":{"bad":{"token":"SECRET"},"number":1},"access_token":"SECRET"}`} { _, err = db.Exec(`UPDATE accounts SET credentials=$1::jsonb WHERE id=4`, credentials) require.NoError(t, err) - rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 2, PageSize: 1}, "", "", "", "") + rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 2, PageSize: 1}, "", "", "", "", 0) require.NoError(t, listErr) require.EqualValues(t, 2, total) require.Len(t, rows, 1) @@ -137,12 +137,12 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) { require.Empty(t, rows[0].Credentials) } principal.Policy.Rules = []adminaccess.Rule{{Permissions: []string{"accounts.read"}, AllGroups: true, AccountTypes: []string{"oauth"}}} - rows, total, err := repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "") + rows, total, err := repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "", 0) require.NoError(t, err) require.EqualValues(t, 3, total, "全部分组不包含无分组账户") require.Len(t, rows, 3) principal.Policy.Rules[0].IncludeUngrouped = true - _, total, err = repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "") + _, total, err = repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "", 0) require.NoError(t, err) require.EqualValues(t, 4, total) } diff --git a/backend/internal/repository/custom_admin_keys.go b/backend/internal/repository/custom_admin_keys.go index 18d459ed5b..ffc864b9e4 100644 --- a/backend/internal/repository/custom_admin_keys.go +++ b/backend/internal/repository/custom_admin_keys.go @@ -88,7 +88,19 @@ func (r *scopedAdminKeyRepository) UpdateScopedAdminKey(ctx context.Context, k * if e != nil { return e } - return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET name=$2,description=$3,enabled=$4,expires_at=$5,allowed_ips=$6,policy=$7,updated_at=$8 WHERE id=$1 AND revoked_at IS NULL`, k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, string(ips), string(policy), k.UpdatedAt)) + // 只允许更新刚读取的版本,避免并发收权后旧请求恢复全权模式。 + result, err := r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET name=$2,description=$3,enabled=$4,expires_at=$5,allowed_ips=$6,policy=$7,updated_at=$8 WHERE id=$1 AND revoked_at IS NULL AND updated_at=$9`, k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, string(ips), string(policy), k.UpdatedAt, k.ExpectedUpdatedAt) + if err != nil { + return err + } + affected, err := result.RowsAffected() + if err != nil { + return err + } + if affected == 0 { + return service.ErrScopedAdminKeyConflict + } + return nil } func (r *scopedAdminKeyRepository) TouchScopedAdminKey(ctx context.Context, id, expectedHash string, expectedUpdatedAt time.Time, ip string, now time.Time) error { return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET last_used_at=$5,last_used_ip=$4 WHERE id=$1 AND key_hash=$2 AND updated_at=$3 AND revoked_at IS NULL AND enabled=true AND (expires_at IS NULL OR expires_at>$5)`, id, expectedHash, expectedUpdatedAt, ip, now)) diff --git a/backend/internal/repository/custom_admin_keys_postgres_test.go b/backend/internal/repository/custom_admin_keys_postgres_test.go index 5fe0f3d7af..02fc3b0e87 100644 --- a/backend/internal/repository/custom_admin_keys_postgres_test.go +++ b/backend/internal/repository/custom_admin_keys_postgres_test.go @@ -144,3 +144,23 @@ func TestScopedAdminKeyPostgresMigrationAndLifecycle(t *testing.T) { _, _, err = settings.RotateScopedAdminKey(ctx, item.ID) require.ErrorIs(t, err, service.ErrScopedAdminKeyNotFound) } + +func TestAdminFullAccessPostgresStaleEditCannotRestorePrivileges(t *testing.T) { + db := scopedAdminKeyTestDB(t) + repo := NewScopedAdminKeyRepository(db) + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + ctx := context.Background() + key, item, err := settings.CreateScopedAdminKey(ctx, service.ScopedAdminKeyInput{Name: "兼容", Enabled: true, ConfirmFullAccess: true, Policy: adminaccess.Policy{FullAccess: true}}, 9) + require.NoError(t, err) + stale, err := repo.GetScopedAdminKey(ctx, item.ID) + require.NoError(t, err) + stale.ExpectedUpdatedAt = stale.UpdatedAt + _, err = settings.UpdateScopedAdminKey(ctx, item.ID, service.ScopedAdminKeyInput{Name: "收权", Enabled: true}) + require.NoError(t, err) + stale.UpdatedAt = time.Now().UTC() + require.ErrorIs(t, repo.UpdateScopedAdminKey(ctx, stale), service.ErrScopedAdminKeyConflict) + current, err := settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1") + require.NoError(t, err) + require.False(t, current.Policy.FullAccess) +} diff --git a/backend/internal/repository/custom_admin_keys_test.go b/backend/internal/repository/custom_admin_keys_test.go index 1d7684035f..c9bdcb84fc 100644 --- a/backend/internal/repository/custom_admin_keys_test.go +++ b/backend/internal/repository/custom_admin_keys_test.go @@ -44,7 +44,7 @@ func TestScopedAdminKeyRepositoryEditDoesNotRestoreOldHash(t *testing.T) { defer db.Close() repo := NewScopedAdminKeyRepository(db) k := &service.ScopedAdminKey{ID: "id", Hash: "旧摘要", ScopedAdminKeyInput: service.ScopedAdminKeyInput{Name: "更新", AllowedIPs: []string{}}, UpdatedAt: time.Now().UTC()} - mock.ExpectExec(`UPDATE scoped_admin_api_keys SET name=\$2,description=\$3,enabled=\$4,expires_at=\$5,allowed_ips=\$6,policy=\$7,updated_at=\$8 WHERE id=\$1 AND revoked_at IS NULL`).WithArgs(k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, "[]", sqlmock.AnyArg(), k.UpdatedAt).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`UPDATE scoped_admin_api_keys SET name=\$2,description=\$3,enabled=\$4,expires_at=\$5,allowed_ips=\$6,policy=\$7,updated_at=\$8 WHERE id=\$1 AND revoked_at IS NULL`).WithArgs(k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, "[]", sqlmock.AnyArg(), k.UpdatedAt, k.ExpectedUpdatedAt).WillReturnResult(sqlmock.NewResult(0, 1)) require.NoError(t, repo.UpdateScopedAdminKey(context.Background(), k)) require.NoError(t, mock.ExpectationsWereMet()) } diff --git a/backend/internal/repository/http_upstream.go b/backend/internal/repository/http_upstream.go index ff19b03d83..e830b43380 100644 --- a/backend/internal/repository/http_upstream.go +++ b/backend/internal/repository/http_upstream.go @@ -27,6 +27,7 @@ import ( "golang.org/x/net/http2" "github.com/Wei-Shaw/sub2api/internal/config" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/proxyurl" "github.com/Wei-Shaw/sub2api/internal/pkg/proxyutil" "github.com/Wei-Shaw/sub2api/internal/pkg/servertiming" @@ -219,7 +220,7 @@ func (s *httpUpstreamService) Do(req *http.Request, proxyURL string, accountID i // 执行请求 client := s.httpClientForUpstreamRequest(entry.client, req) client = httpClientWithGrokAccessDeniedFallback(client) - resp, err := doUpstreamRequest(client, req) + resp, err := doUpstreamRequest(client, req, s.upstreamDrainTimeout()) if err != nil { s.recordOpenAIHTTP2Failure(profile, entry.protocolMode, entry.proxyKey, err) // 请求失败,立即减少计数 @@ -280,7 +281,7 @@ func (s *httpUpstreamService) DoWithTLS(req *http.Request, proxyURL string, acco client := s.httpClientForUpstreamRequest(entry.client, req) client = httpClientWithGrokAccessDeniedFallback(client) - resp, err := doUpstreamRequest(client, req) + resp, err := doUpstreamRequest(client, req, s.upstreamDrainTimeout()) if err != nil { atomic.AddInt64(&entry.inFlight, -1) atomic.StoreInt64(&entry.lastUsed, time.Now().UnixNano()) @@ -296,10 +297,21 @@ func (s *httpUpstreamService) DoWithTLS(req *http.Request, proxyURL string, acco return resp, nil } +func (s *httpUpstreamService) upstreamDrainTimeout() time.Duration { + if s.cfg != nil && s.cfg.Gateway.StreamDataIntervalTimeout > 0 { + return time.Duration(s.cfg.Gateway.StreamDataIntervalTimeout) * time.Second + } + return pkghttputil.DefaultUpstreamDrainTimeout +} + // doUpstreamRequest owns cancellation for one attempt, without cancelling the // caller's context (which may be detached for billing or reused for retries). -func doUpstreamRequest(client *http.Client, req *http.Request) (*http.Response, error) { - ctx, cancel := context.WithCancel(req.Context()) +func doUpstreamRequest(client *http.Client, req *http.Request, drainTimeouts ...time.Duration) (*http.Response, error) { + var drainTimeout time.Duration + if len(drainTimeouts) > 0 { + drainTimeout = drainTimeouts[0] + } + ctx, cancel := pkghttputil.NewUpstreamAttemptContext(req.Context(), drainTimeout) resp, err := servertiming.Do(client, req.WithContext(ctx)) if err != nil { cancel() diff --git a/backend/internal/repository/http_upstream_drain_test.go b/backend/internal/repository/http_upstream_drain_test.go new file mode 100644 index 0000000000..1d3fbf548b --- /dev/null +++ b/backend/internal/repository/http_upstream_drain_test.go @@ -0,0 +1,67 @@ +package repository + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/stretchr/testify/require" +) + +func TestHTTPUpstreamDrainContinuousPingsCannotExtendBudget(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _ = http.NewResponseController(w).Flush() + ticker := time.NewTicker(5 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-r.Context().Done(): + return + case <-ticker.C: + _, _ = io.WriteString(w, ": ping\n\n") + _ = http.NewResponseController(w).Flush() + } + } + })) + defer srv.Close() + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + req, err := http.NewRequestWithContext(pkghttputil.DetachUpstreamContext(client), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + resp, err := doUpstreamRequest(srv.Client(), req, 40*time.Millisecond) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + cancelClient() + started := time.Now() + body, err := io.ReadAll(resp.Body) + require.Error(t, err) + require.Contains(t, string(body), ": ping") + require.Less(t, time.Since(started), time.Second) +} + +func TestHTTPUpstreamDrainPreservesLateTerminalUsage(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + _ = http.NewResponseController(w).Flush() + time.Sleep(20 * time.Millisecond) + _, _ = io.WriteString(w, "data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":7}}\n\ndata: {\"type\":\"message_stop\"}\n\n") + })) + defer srv.Close() + client, cancelClient := context.WithCancel(context.Background()) + defer cancelClient() + req, err := http.NewRequestWithContext(pkghttputil.DetachUpstreamContext(client), http.MethodGet, srv.URL, nil) + require.NoError(t, err) + resp, err := doUpstreamRequest(srv.Client(), req, 200*time.Millisecond) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + cancelClient() + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.True(t, strings.Contains(string(body), "output_tokens\":7") && strings.Contains(string(body), "message_stop")) +} diff --git a/backend/internal/repository/mcp_oauth.go b/backend/internal/repository/mcp_oauth.go new file mode 100644 index 0000000000..013a9b0697 --- /dev/null +++ b/backend/internal/repository/mcp_oauth.go @@ -0,0 +1,240 @@ +package repository + +import ( + "context" + "database/sql" + "errors" + "sync/atomic" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +const mcpOAuthClientIDKeyName = "mcp_oauth_client_id_key" + +type mcpOAuthRepository struct { + client *dbent.Client + db *sql.DB + clientIDKey atomic.Pointer[[]byte] +} + +func NewMCPOAuthRepository(client *dbent.Client, db *sql.DB) service.MCPOAuthRepository { + return &mcpOAuthRepository{client: client, db: db} +} + +// ClientIDKey loads the key that signs stateless client IDs, creating it on +// first use. It is persisted so issued client IDs and grants survive restarts, +// and instances racing to create it converge on the stored value. +func (r *mcpOAuthRepository) ClientIDKey(ctx context.Context) ([]byte, error) { + if key := r.clientIDKey.Load(); key != nil { + return *key, nil + } + value, _, err := getOrCreateGeneratedSecuritySecret(ctx, r.client, mcpOAuthClientIDKeyName, 32) + if err != nil { + return nil, err + } + key := []byte(value) + r.clientIDKey.Store(&key) + return key, nil +} + +func (r *mcpOAuthRepository) CreateAuthorization(ctx context.Context, grant *service.MCPOAuthGrant, code *service.MCPOAuthCode, limit int) error { + // Grants are the only rows that outlive a request, so each new one performs + // bounded retention work. It runs before the owner row is locked, keeping + // cascaded deletes from blocking other updates to that user. Used refresh + // hashes remain for the entire grant lifetime so replay detection is never + // shortened by cleanup. + if _, err := r.db.ExecContext(ctx, `DELETE FROM mcp_oauth_grants WHERE id IN (SELECT id FROM mcp_oauth_grants WHERE expires_at<$1 ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED)`, grant.CreatedAt.Add(-7*24*time.Hour)); err != nil { + return err + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + // Serialize the per-user limit with other authorizations for this owner. + var ownerID int64 + if err := tx.QueryRowContext(ctx, `SELECT id FROM users WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, grant.UserID).Scan(&ownerID); err != nil { + return mcpOAuthSQLError(err) + } + var count int + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM mcp_oauth_grants WHERE user_id=$1 AND revoked_at IS NULL AND expires_at>$2`, grant.UserID, grant.CreatedAt).Scan(&count); err != nil { + return err + } + if count >= limit { + return service.ErrMCPOAuthGrantLimit + } + _, err = tx.ExecContext(ctx, `INSERT INTO mcp_oauth_grants (id,client_id,client_name,user_id,token_version,resource,scope,read_only,created_at,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, + grant.ID, grant.ClientID, grant.ClientName, grant.UserID, grant.TokenVersion, grant.Resource, grant.Scope, grant.ReadOnly, grant.CreatedAt, grant.ExpiresAt) + if err != nil { + return err + } + _, err = tx.ExecContext(ctx, `INSERT INTO mcp_oauth_codes (code_hash,grant_id,client_id,redirect_uri,resource,code_challenge,expires_at) VALUES ($1,$2,$3,$4,$5,$6,$7)`, + code.Hash, code.GrantID, code.ClientID, code.RedirectURI, code.Resource, code.CodeChallenge, code.ExpiresAt) + if err != nil { + return err + } + return tx.Commit() +} + +func (r *mcpOAuthRepository) GetCode(ctx context.Context, hash string) (*service.MCPOAuthCode, error) { + code := &service.MCPOAuthCode{} + err := r.db.QueryRowContext(ctx, `SELECT code_hash,grant_id,client_id,redirect_uri,resource,code_challenge,expires_at,consumed_at FROM mcp_oauth_codes WHERE code_hash=$1`, hash). + Scan(&code.Hash, &code.GrantID, &code.ClientID, &code.RedirectURI, &code.Resource, &code.CodeChallenge, &code.ExpiresAt, &code.ConsumedAt) + if err != nil { + return nil, mcpOAuthSQLError(err) + } + return code, nil +} + +func (r *mcpOAuthRepository) GetCredential(ctx context.Context, hash string) (*service.MCPOAuthCredential, error) { + credential := &service.MCPOAuthCredential{} + err := r.db.QueryRowContext(ctx, `SELECT key_hash,grant_id,kind,expires_at,used_at FROM mcp_oauth_credentials WHERE key_hash=$1`, hash). + Scan(&credential.Hash, &credential.GrantID, &credential.Kind, &credential.ExpiresAt, &credential.UsedAt) + if err != nil { + return nil, mcpOAuthSQLError(err) + } + return credential, nil +} + +const mcpOAuthGrantColumns = `id,client_id,client_name,user_id,token_version,resource,scope,read_only,created_at,expires_at,last_used_at,revoked_at` + +func scanMCPOAuthGrant(row interface{ Scan(...any) error }) (*service.MCPOAuthGrant, error) { + grant := &service.MCPOAuthGrant{} + err := row.Scan(&grant.ID, &grant.ClientID, &grant.ClientName, &grant.UserID, &grant.TokenVersion, &grant.Resource, &grant.Scope, &grant.ReadOnly, &grant.CreatedAt, &grant.ExpiresAt, &grant.LastUsedAt, &grant.RevokedAt) + if err != nil { + return nil, mcpOAuthSQLError(err) + } + return grant, nil +} + +func (r *mcpOAuthRepository) GetGrant(ctx context.Context, id string) (*service.MCPOAuthGrant, error) { + return scanMCPOAuthGrant(r.db.QueryRowContext(ctx, `SELECT `+mcpOAuthGrantColumns+` FROM mcp_oauth_grants WHERE id=$1`, id)) +} + +func (r *mcpOAuthRepository) ListGrants(ctx context.Context, userID int64) ([]*service.MCPOAuthGrant, error) { + rows, err := r.db.QueryContext(ctx, `SELECT `+mcpOAuthGrantColumns+` FROM mcp_oauth_grants WHERE user_id=$1 ORDER BY created_at DESC`, userID) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + grants := []*service.MCPOAuthGrant{} + for rows.Next() { + grant, err := scanMCPOAuthGrant(rows) + if err != nil { + return nil, err + } + grants = append(grants, grant) + } + return grants, rows.Err() +} + +func (r *mcpOAuthRepository) ExchangeCode(ctx context.Context, hash, grantID string, at time.Time, access, refresh *service.MCPOAuthCredential) error { + return r.consumeAndIssue(ctx, hash, grantID, at, access, refresh, false) +} + +func (r *mcpOAuthRepository) RotateRefresh(ctx context.Context, hash, grantID string, at time.Time, access, refresh *service.MCPOAuthCredential) error { + return r.consumeAndIssue(ctx, hash, grantID, at, access, refresh, true) +} + +func (r *mcpOAuthRepository) consumeAndIssue(ctx context.Context, hash, grantID string, at time.Time, access, refresh *service.MCPOAuthCredential, rotating bool) error { + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + // Always lock the grant first: rotation, code exchange, and revocation + // serialize on the same family without code/refresh lock-order inversion. + var revokedAt *time.Time + var grantExpiry time.Time + if err := tx.QueryRowContext(ctx, `SELECT revoked_at,expires_at FROM mcp_oauth_grants WHERE id=$1 FOR UPDATE`, grantID).Scan(&revokedAt, &grantExpiry); err != nil { + return mcpOAuthSQLError(err) + } + if revokedAt != nil || !at.Before(grantExpiry) { + return service.ErrMCPOAuthNotFound + } + var expiresAt time.Time + var usedAt *time.Time + query := `SELECT expires_at,consumed_at FROM mcp_oauth_codes WHERE code_hash=$1 AND grant_id=$2 FOR UPDATE` + if rotating { + query = `SELECT expires_at,used_at FROM mcp_oauth_credentials WHERE key_hash=$1 AND grant_id=$2 AND kind='refresh' FOR UPDATE` + } + if err := tx.QueryRowContext(ctx, query, hash, grantID).Scan(&expiresAt, &usedAt); err != nil { + return mcpOAuthSQLError(err) + } + if usedAt != nil { + // Do not return before committing: rolling back here would leave all + // newer credentials usable after a detected replay. + if _, err := tx.ExecContext(ctx, `UPDATE mcp_oauth_grants SET revoked_at=$2 WHERE id=$1`, grantID, at); err != nil { + return err + } + if err := tx.Commit(); err != nil { + return err + } + return service.ErrMCPOAuthNotFound + } + if !at.Before(expiresAt) { + return service.ErrMCPOAuthNotFound + } + query = `UPDATE mcp_oauth_codes SET consumed_at=$2 WHERE code_hash=$1` + if rotating { + query = `UPDATE mcp_oauth_credentials SET used_at=$2 WHERE key_hash=$1` + } + if _, err := tx.ExecContext(ctx, query, hash, at); err != nil { + return err + } + for _, credential := range []*service.MCPOAuthCredential{access, refresh} { + if credential == nil { + continue + } + if _, err := tx.ExecContext(ctx, `INSERT INTO mcp_oauth_credentials (key_hash,grant_id,kind,expires_at) VALUES ($1,$2,$3,$4)`, credential.Hash, grantID, credential.Kind, credential.ExpiresAt); err != nil { + return err + } + } + return tx.Commit() +} + +func (r *mcpOAuthRepository) TouchGrant(ctx context.Context, id string, at time.Time) error { + return mcpOAuthResult(r.db.ExecContext(ctx, `UPDATE mcp_oauth_grants SET last_used_at=$2 WHERE id=$1 AND revoked_at IS NULL AND expires_at>$2`, id, at)) +} + +func (r *mcpOAuthRepository) RevokeGrant(ctx context.Context, userID int64, id string, at time.Time) error { + 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 + } + return err +} + +func mcpOAuthResult(result sql.Result, err error) error { + if err != nil { + return err + } + n, err := result.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return service.ErrMCPOAuthNotFound + } + return nil +} diff --git a/backend/internal/repository/mcp_oauth_integration_test.go b/backend/internal/repository/mcp_oauth_integration_test.go new file mode 100644 index 0000000000..c58cdb62a5 --- /dev/null +++ b/backend/internal/repository/mcp_oauth_integration_test.go @@ -0,0 +1,273 @@ +//go:build integration + +package repository + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +const mcpIntegrationResource = "https://platform.example/api/v1/mcp" + +type mcpOAuthIntegrationFixture struct { + oauth *service.MCPOAuthService + repo service.MCPOAuthRepository + input service.MCPOAuthTokenInput + userID int64 + grantID string +} + +// Use committed rows and the production repositories: OAuth owns its database +// transactions, so wrapping this fixture in testTx would hide lock behavior. +func newMCPOAuthIntegrationFixture(t *testing.T, ctx context.Context) mcpOAuthIntegrationFixture { + t.Helper() + user := mustCreateUser(t, testEntClient(t), &service.User{}) + repo := NewMCPOAuthRepository(integrationEntClient, integrationDB) + oauth := service.NewMCPOAuthService(repo, NewUserRepository(integrationEntClient, integrationDB)) + t.Cleanup(func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := integrationDB.ExecContext(cleanupCtx, `DELETE FROM users WHERE id=$1`, user.ID) + require.NoError(t, err) + }) + + const redirectURI = "https://client.example/callback?channel=desktop" + client, err := oauth.Register(ctx, service.MCPOAuthRegisterInput{ + ClientName: "Integration MCP client", RedirectURIs: []string{redirectURI}, + TokenEndpointAuthMethod: "none", + }) + require.NoError(t, err) + clientID := client.ClientID + + verifier := strings.Repeat("v", 64) + challenge := sha256.Sum256([]byte(verifier)) + authorization := service.MCPOAuthAuthorizeInput{ + ResponseType: "code", ClientID: clientID, RedirectURI: redirectURI, + Scope: "mcp", State: "integration-state", Resource: mcpIntegrationResource, + CodeChallenge: base64.RawURLEncoding.EncodeToString(challenge[:]), CodeChallengeMethod: "S256", + } + preview, err := oauth.Preview(ctx, user.ID, authorization, mcpIntegrationResource) + require.NoError(t, err) + require.Equal(t, client.ClientName, preview.ClientName) + require.Equal(t, redirectURI, preview.RedirectURI) + redirect, err := oauth.Decide(ctx, user.ID, service.MCPOAuthConsentInput{ + Authorization: authorization, Approved: true, + }, mcpIntegrationResource) + require.NoError(t, err) + callback, err := url.Parse(redirect) + require.NoError(t, err) + require.Equal(t, "desktop", callback.Query().Get("channel")) + require.Equal(t, authorization.State, callback.Query().Get("state")) + require.NotEmpty(t, callback.Query().Get("code")) + grants, err := oauth.ListGrants(ctx, user.ID) + require.NoError(t, err) + require.Len(t, grants, 1) + require.Equal(t, service.MCPScopeUser, grants[0].Scope) + require.True(t, grants[0].ReadOnly) + require.False(t, grants[0].Invalidated) + require.Equal(t, clientID, grants[0].ClientID) + require.Equal(t, client.ClientName, grants[0].ClientName) + return mcpOAuthIntegrationFixture{ + oauth: oauth, repo: repo, userID: user.ID, grantID: grants[0].ID, + input: service.MCPOAuthTokenInput{ + GrantType: "authorization_code", ClientID: clientID, RedirectURI: redirectURI, + Code: callback.Query().Get("code"), CodeVerifier: verifier, Resource: mcpIntegrationResource, + }, + } +} + +func mcpIntegrationDigest(raw string) string { + sum := sha256.Sum256([]byte(raw)) + return hex.EncodeToString(sum[:]) +} + +func requireMCPIntegrationInvalidGrant(t *testing.T, err error) { + t.Helper() + var oauthErr *service.MCPOAuthError + require.ErrorAs(t, err, &oauthErr) + require.Equal(t, "invalid_grant", oauthErr.Code) +} + +func TestMCPOAuthIntegrationAuthorizationAndRefreshReplay(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + f := newMCPOAuthIntegrationFixture(t, ctx) + // TestMain applies the real SQL migrations before this end-to-end flow. + issued, err := f.oauth.Token(ctx, f.input, mcpIntegrationResource) + require.NoError(t, err) + require.NotEmpty(t, issued.RefreshToken) + principal, err := f.oauth.Authenticate(ctx, issued.AccessToken) + require.NoError(t, err) + require.Equal(t, f.userID, principal.UserID) + require.Equal(t, f.grantID, principal.GrantID) + code, err := f.repo.GetCode(ctx, mcpIntegrationDigest(f.input.Code)) + require.NoError(t, err) + require.NotNil(t, code.ConsumedAt) + refresh, err := f.repo.GetCredential(ctx, mcpIntegrationDigest(issued.RefreshToken)) + require.NoError(t, err) + require.Nil(t, refresh.UsedAt) + + // SDK clients omit resource on refresh; it must inherit the original binding. + refreshInput := service.MCPOAuthTokenInput{ + GrantType: "refresh_token", ClientID: f.input.ClientID, RefreshToken: issued.RefreshToken, + } + rotated, err := f.oauth.Token(ctx, refreshInput, mcpIntegrationResource) + require.NoError(t, err) + require.NotEqual(t, issued.RefreshToken, rotated.RefreshToken) + principal, err = f.oauth.Authenticate(ctx, rotated.AccessToken) + require.NoError(t, err) + require.Equal(t, mcpIntegrationResource, principal.Resource) + refresh, err = f.repo.GetCredential(ctx, mcpIntegrationDigest(issued.RefreshToken)) + require.NoError(t, err) + require.NotNil(t, refresh.UsedAt, "old refresh digest must remain for replay detection") + + _, err = f.oauth.Token(ctx, refreshInput, mcpIntegrationResource) + requireMCPIntegrationInvalidGrant(t, err) + grant, err := f.repo.GetGrant(ctx, f.grantID) + require.NoError(t, err) + require.NotNil(t, grant.RevokedAt, "replay revocation must commit despite invalid_grant") + for _, raw := range []string{issued.AccessToken, rotated.AccessToken} { + _, err = f.oauth.Authenticate(ctx, raw) + require.ErrorIs(t, err, service.ErrMCPOAuthInvalidToken) + } + refreshInput.RefreshToken = rotated.RefreshToken + _, err = f.oauth.Token(ctx, refreshInput, mcpIntegrationResource) + requireMCPIntegrationInvalidGrant(t, err) +} + +func TestMCPOAuthIntegrationConcurrentCodeExchange(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + f := newMCPOAuthIntegrationFixture(t, ctx) + const attempts = 8 + type exchangeResult struct { + tokens *service.MCPOAuthTokenResponse + err error + } + start := make(chan struct{}) + results := make(chan exchangeResult, attempts) + var workers sync.WaitGroup + for range attempts { + workers.Add(1) + go func() { + defer workers.Done() + <-start + tokens, err := f.oauth.Token(ctx, f.input, mcpIntegrationResource) + results <- exchangeResult{tokens: tokens, err: err} + }() + } + close(start) + workers.Wait() + close(results) + var issued *service.MCPOAuthTokenResponse + successes := 0 + for result := range results { + if result.err != nil { + requireMCPIntegrationInvalidGrant(t, result.err) + continue + } + successes++ + issued = result.tokens + } + require.Equal(t, 1, successes, "one authorization code must issue only one credential pair") + require.NotNil(t, issued) + var credentialCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, + `SELECT COUNT(*) FROM mcp_oauth_credentials WHERE grant_id=$1`, f.grantID).Scan(&credentialCount)) + require.Equal(t, 2, credentialCount, "losing transactions must not persist extra access or refresh tokens") + grant, err := f.repo.GetGrant(ctx, f.grantID) + require.NoError(t, err) + require.NotNil(t, grant.RevokedAt, "the concurrent code replay must revoke the winning issuance") + _, err = f.oauth.Authenticate(ctx, issued.AccessToken) + require.ErrorIs(t, err, service.ErrMCPOAuthInvalidToken) + _, err = f.oauth.Token(ctx, service.MCPOAuthTokenInput{ + GrantType: "refresh_token", ClientID: f.input.ClientID, RefreshToken: issued.RefreshToken, + }, 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 TestMCPOAuthIntegrationClientIDKeyConvergesAcrossInstances(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + // Start without a key so the instances race to create it. + _, err := integrationDB.ExecContext(ctx, `DELETE FROM security_secrets WHERE key=$1`, mcpOAuthClientIDKeyName) + require.NoError(t, err) + const instances = 8 + keys := make([][]byte, instances) + errs := make([]error, instances) + start := make(chan struct{}) + var wg sync.WaitGroup + for i := 0; i < instances; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + <-start + keys[i], errs[i] = NewMCPOAuthRepository(integrationEntClient, integrationDB).ClientIDKey(ctx) + }(i) + } + close(start) + wg.Wait() + for i := 0; i < instances; i++ { + require.NoError(t, errs[i]) + require.GreaterOrEqual(t, len(keys[i]), 32) + require.Equal(t, keys[0], keys[i]) + } + + // A client registered by one instance is accepted by another. + users := NewUserRepository(integrationEntClient, integrationDB) + client, err := service.NewMCPOAuthService(NewMCPOAuthRepository(integrationEntClient, integrationDB), users).Register(ctx, service.MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) + require.NoError(t, err) + _, err = service.NewMCPOAuthService(NewMCPOAuthRepository(integrationEntClient, integrationDB), users).Token(ctx, service.MCPOAuthTokenInput{GrantType: "authorization_code", ClientID: client.ClientID}, mcpIntegrationResource) + requireMCPIntegrationInvalidGrant(t, err) +} diff --git a/backend/internal/repository/mcp_oauth_test.go b/backend/internal/repository/mcp_oauth_test.go new file mode 100644 index 0000000000..ace5c3ef27 --- /dev/null +++ b/backend/internal/repository/mcp_oauth_test.go @@ -0,0 +1,208 @@ +//go:build unit + +package repository + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/ent/securitysecret" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestMCPOAuthRepositoryClientIDKeyIsPersistedAndCached(t *testing.T) { + ctx := context.Background() + client := newSecuritySecretTestClient(t) + repo := NewMCPOAuthRepository(client, nil) + key, err := repo.ClientIDKey(ctx) + require.NoError(t, err) + require.Len(t, key, 64) + other, err := NewMCPOAuthRepository(client, nil).ClientIDKey(ctx) + require.NoError(t, err) + require.Equal(t, key, other, "instances must share the stored key") + _, err = client.SecuritySecret.Delete().Where(securitysecret.KeyEQ(mcpOAuthClientIDKeyName)).Exec(ctx) + require.NoError(t, err) + cached, err := repo.ClientIDKey(ctx) + require.NoError(t, err) + require.Equal(t, key, cached, "a loaded key is served from memory") +} + +func TestMCPOAuthRepositoryClientIDKeyDoesNotCacheInvalidSecret(t *testing.T) { + ctx := context.Background() + client := newSecuritySecretTestClient(t) + require.NoError(t, client.SecuritySecret.Create().SetKey(mcpOAuthClientIDKeyName).SetValue("short").Exec(ctx)) + repo := NewMCPOAuthRepository(client, nil) + _, err := repo.ClientIDKey(ctx) + require.Error(t, err) + valid := strings.Repeat("c", 64) + require.NoError(t, client.SecuritySecret.Update().Where(securitysecret.KeyEQ(mcpOAuthClientIDKeyName)).SetValue(valid).Exec(ctx)) + key, err := repo.ClientIDKey(ctx) + require.NoError(t, err) + require.Equal(t, []byte(valid), key) +} + +func TestMCPOAuthRepositoryConsumptionCommitsReplayRevocation(t *testing.T) { + for _, rotating := range []bool{false, true} { + t.Run(map[bool]string{false: "code", true: "refresh"}[rotating], func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewMCPOAuthRepository(nil, db) + now := time.Now().UTC() + used := now.Add(-time.Minute) + mock.ExpectBegin() + mock.ExpectQuery(`SELECT revoked_at,expires_at FROM mcp_oauth_grants WHERE id=\$1 FOR UPDATE`).WithArgs("grant"). + WillReturnRows(sqlmock.NewRows([]string{"revoked_at", "expires_at"}).AddRow(nil, now.Add(time.Hour))) + if rotating { + mock.ExpectQuery(`SELECT expires_at,used_at FROM mcp_oauth_credentials WHERE key_hash=\$1 AND grant_id=\$2 AND kind='refresh' FOR UPDATE`).WithArgs("old-hash", "grant"). + WillReturnRows(sqlmock.NewRows([]string{"expires_at", "used_at"}).AddRow(now.Add(time.Hour), used)) + } else { + mock.ExpectQuery(`SELECT expires_at,consumed_at FROM mcp_oauth_codes WHERE code_hash=\$1 AND grant_id=\$2 FOR UPDATE`).WithArgs("old-hash", "grant"). + WillReturnRows(sqlmock.NewRows([]string{"expires_at", "consumed_at"}).AddRow(now.Add(time.Hour), used)) + } + mock.ExpectExec(`UPDATE mcp_oauth_grants SET revoked_at=\$2 WHERE id=\$1`).WithArgs("grant", now).WillReturnResult(sqlmock.NewResult(0, 1)) + // The security change MUST commit despite returning an error to OAuth. + mock.ExpectCommit() + if rotating { + err = repo.RotateRefresh(context.Background(), "old-hash", "grant", now, nil, nil) + } else { + err = repo.ExchangeCode(context.Background(), "old-hash", "grant", now, nil, nil) + } + require.ErrorIs(t, err, service.ErrMCPOAuthNotFound) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} + +func TestMCPOAuthRepositoryConsumptionAndIssuanceAreOneTransaction(t *testing.T) { + for _, rotating := range []bool{false, true} { + for _, failInsert := range []bool{false, true} { + t.Run(map[bool]string{false: "code", true: "refresh"}[rotating]+map[bool]string{false: "/commit", true: "/rollback"}[failInsert], func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewMCPOAuthRepository(nil, db) + now := time.Now().UTC() + access := &service.MCPOAuthCredential{Hash: "access-digest", GrantID: "grant", Kind: "access", ExpiresAt: now.Add(10 * time.Minute)} + refresh := &service.MCPOAuthCredential{Hash: "refresh-digest", GrantID: "grant", Kind: "refresh", ExpiresAt: now.Add(time.Hour)} + mock.ExpectBegin() + mock.ExpectQuery(`SELECT revoked_at,expires_at FROM mcp_oauth_grants WHERE id=\$1 FOR UPDATE`).WithArgs("grant"). + WillReturnRows(sqlmock.NewRows([]string{"revoked_at", "expires_at"}).AddRow(nil, now.Add(time.Hour))) + if rotating { + mock.ExpectQuery(`SELECT expires_at,used_at FROM mcp_oauth_credentials`).WithArgs("old-hash", "grant").WillReturnRows(sqlmock.NewRows([]string{"expires_at", "used_at"}).AddRow(now.Add(time.Hour), nil)) + mock.ExpectExec(`UPDATE mcp_oauth_credentials SET used_at=\$2 WHERE key_hash=\$1`).WithArgs("old-hash", now).WillReturnResult(sqlmock.NewResult(0, 1)) + } else { + mock.ExpectQuery(`SELECT expires_at,consumed_at FROM mcp_oauth_codes`).WithArgs("old-hash", "grant").WillReturnRows(sqlmock.NewRows([]string{"expires_at", "consumed_at"}).AddRow(now.Add(time.Hour), nil)) + mock.ExpectExec(`UPDATE mcp_oauth_codes SET consumed_at=\$2 WHERE code_hash=\$1`).WithArgs("old-hash", now).WillReturnResult(sqlmock.NewResult(0, 1)) + } + mock.ExpectExec(`INSERT INTO mcp_oauth_credentials`).WithArgs(access.Hash, "grant", "access", access.ExpiresAt).WillReturnResult(sqlmock.NewResult(0, 1)) + insert := mock.ExpectExec(`INSERT INTO mcp_oauth_credentials`).WithArgs(refresh.Hash, "grant", "refresh", refresh.ExpiresAt) + injected := errors.New("database unavailable") + if failInsert { + insert.WillReturnError(injected) + mock.ExpectRollback() + } else { + insert.WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + } + if rotating { + err = repo.RotateRefresh(context.Background(), "old-hash", "grant", now, access, refresh) + } else { + err = repo.ExchangeCode(context.Background(), "old-hash", "grant", now, access, refresh) + } + if failInsert { + require.ErrorIs(t, err, injected) + } else { + require.NoError(t, err) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } + } +} + +func TestMCPOAuthRepositoryRejectsExpiredAndRevokedFamilies(t *testing.T) { + for _, revoked := range []bool{false, true} { + db, mock, err := sqlmock.New() + require.NoError(t, err) + repo := NewMCPOAuthRepository(nil, db) + now := time.Now().UTC() + var revokedAt *time.Time + expiry := now.Add(-time.Second) + if revoked { + revokedAt, expiry = &now, now.Add(time.Hour) + } + mock.ExpectBegin() + mock.ExpectQuery(`SELECT revoked_at,expires_at FROM mcp_oauth_grants WHERE id=\$1 FOR UPDATE`).WithArgs("grant").WillReturnRows(sqlmock.NewRows([]string{"revoked_at", "expires_at"}).AddRow(revokedAt, expiry)) + mock.ExpectRollback() + err = repo.RotateRefresh(context.Background(), "old-hash", "grant", now, nil, nil) + require.ErrorIs(t, err, service.ErrMCPOAuthNotFound) + require.NoError(t, mock.ExpectationsWereMet()) + mock.ExpectClose() + require.NoError(t, db.Close()) + } +} + +func TestMCPOAuthRepositoryAuthorizationSerializesLimit(t *testing.T) { + for _, atLimit := range []bool{false, true} { + t.Run(map[bool]string{false: "create", true: "at limit"}[atLimit], func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewMCPOAuthRepository(nil, db) + now := time.Now().UTC() + grant := &service.MCPOAuthGrant{ID: "grant", ClientID: "client", ClientName: "Client", UserID: 7, TokenVersion: 42, Resource: "https://example.com/mcp", Scope: "user", ReadOnly: true, CreatedAt: now, ExpiresAt: now.Add(time.Hour)} + code := &service.MCPOAuthCode{Hash: "code-digest", GrantID: grant.ID, ClientID: grant.ClientID, RedirectURI: "https://client.example/cb", Resource: grant.Resource, CodeChallenge: "challenge", ExpiresAt: now.Add(time.Minute)} + count := 19 + if atLimit { + count = 20 + } + // Bounded retention runs before the owner row is locked. + mock.ExpectExec(`DELETE FROM mcp_oauth_grants WHERE id IN \(SELECT id FROM mcp_oauth_grants WHERE expires_at<\$1 ORDER BY expires_at LIMIT 100 FOR UPDATE SKIP LOCKED\)`).WithArgs(now.Add(-7 * 24 * time.Hour)).WillReturnResult(sqlmock.NewResult(0, 2)) + mock.ExpectBegin() + mock.ExpectQuery(`SELECT id FROM users WHERE id=\$1 AND deleted_at IS NULL FOR UPDATE`).WithArgs(int64(7)).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(7)) + mock.ExpectQuery(`SELECT COUNT\(\*\) FROM mcp_oauth_grants WHERE user_id=\$1 AND revoked_at IS NULL AND expires_at>\$2`).WithArgs(int64(7), now).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(count)) + if atLimit { + mock.ExpectRollback() + require.ErrorIs(t, repo.CreateAuthorization(context.Background(), grant, code, 20), service.ErrMCPOAuthGrantLimit) + } else { + mock.ExpectExec(`INSERT INTO mcp_oauth_grants`).WithArgs(grant.ID, grant.ClientID, grant.ClientName, grant.UserID, grant.TokenVersion, grant.Resource, grant.Scope, grant.ReadOnly, grant.CreatedAt, grant.ExpiresAt).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectExec(`INSERT INTO mcp_oauth_codes`).WithArgs(code.Hash, code.GrantID, code.ClientID, code.RedirectURI, code.Resource, code.CodeChallenge, code.ExpiresAt).WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectCommit() + require.NoError(t, repo.CreateAuthorization(context.Background(), grant, code, 20)) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} + +func TestMCPOAuthRepositoryOwnerAndRevocationBoundaries(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + repo := NewMCPOAuthRepository(nil, db) + now := time.Now().UTC() + mock.ExpectExec(`UPDATE mcp_oauth_grants SET revoked_at=COALESCE\(revoked_at,\$3\) WHERE id=\$1 AND user_id=\$2`).WithArgs("grant", int64(8), now).WillReturnResult(sqlmock.NewResult(0, 0)) + require.ErrorIs(t, repo.RevokeGrant(context.Background(), 8, "grant", now), service.ErrMCPOAuthNotFound) + mock.ExpectExec(`UPDATE mcp_oauth_grants SET last_used_at=\$2 WHERE id=\$1 AND revoked_at IS NULL AND expires_at>\$2`).WithArgs("grant", now).WillReturnResult(sqlmock.NewResult(0, 0)) + 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(nil, db) + now := time.Now().UTC() + mock.ExpectExec(`UPDATE mcp_oauth_grants SET revoked_at=\$2 WHERE user_id=\$1 AND revoked_at IS NULL$`).WithArgs(int64(8), now).WillReturnResult(sqlmock.NewResult(0, 0)) + require.NoError(t, repo.RevokeUserGrants(context.Background(), 8, now), "no active grants is not an error") + 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/scheduler_cache.go b/backend/internal/repository/scheduler_cache.go index 2aa73c61ea..f8a283d09f 100644 --- a/backend/internal/repository/scheduler_cache.go +++ b/backend/internal/repository/scheduler_cache.go @@ -1317,6 +1317,8 @@ func filterSchedulerExtra(extra map[string]any) map[string]any { // 走网关报 no available accounts"。 "openai_passthrough", "openai_oauth_passthrough", + // 生图尺寸档位在候选过滤阶段按本投影判定,裁掉后受限账号会接到不允许的档位。 + service.AccountExtraOpenAIImageSizeTiers, "codex_fingerprint_mode", "codex_fingerprint_seed", "codex_5h_used_percent", diff --git a/backend/internal/repository/scheduler_cache_unit_test.go b/backend/internal/repository/scheduler_cache_unit_test.go index 2b8dd78657..0a81d5a3c2 100644 --- a/backend/internal/repository/scheduler_cache_unit_test.go +++ b/backend/internal/repository/scheduler_cache_unit_test.go @@ -567,6 +567,23 @@ func TestBuildSchedulerMetadataAccount_KeepsQuotaStateForCachedAccounts(t *testi } } +func TestBuildSchedulerMetadataAccount_KeepsOpenAIImageSizeTiers(t *testing.T) { + account := service.Account{ + ID: 91, + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Extra: map[string]any{ + service.AccountExtraOpenAIImageSizeTiers: []any{"4K"}, + "unused_large_field": "drop-me", + }, + } + + got := buildSchedulerMetadataAccount(account) + + require.Equal(t, []string{"4K"}, got.OpenAIImageSizeTiers()) + require.Nil(t, got.Extra["unused_large_field"]) +} + func TestBuildSchedulerMetadataAccount_KeepsModelRateLimits(t *testing.T) { account := service.Account{ ID: 90, 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/repository/user_repo_email_blacklist.go b/backend/internal/repository/user_repo_email_blacklist.go new file mode 100644 index 0000000000..29709e8739 --- /dev/null +++ b/backend/internal/repository/user_repo_email_blacklist.go @@ -0,0 +1,137 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "slices" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/lib/pq" +) + +var _ service.UserEmailBlacklistRepository = (*userRepository)(nil) + +// listActiveUsersByEmailAliasProbeKeysSQL 把每个用户邮箱折成与 service.EmailAliasProbeKey +// 相同的形态(小写、去首尾空白与域名根点、本地部分去 "+后缀"、本地与域名都去点)后与探针键做 +// 哈希连接;去点会在 Gmail 系之外过度匹配,由 service 层按收件箱身份复核。 +const listActiveUsersByEmailAliasProbeKeysSQL = ` +WITH probes AS ( + SELECT DISTINCT unnest($1::text[]) AS probe +), candidates AS ( + SELECT id, email, username, + split_part(RTRIM(LOWER(TRIM(email)), '.'), '@', 1) AS local_part, + split_part(RTRIM(LOWER(TRIM(email)), '.'), '@', 2) AS domain_part + FROM users + WHERE deleted_at IS NULL AND status = $2 AND role <> $3 +) +SELECT c.id, c.email, c.username +FROM candidates c +JOIN probes p ON p.probe = + REPLACE( + CASE WHEN strpos(c.local_part, '+') > 1 THEN split_part(c.local_part, '+', 1) ELSE c.local_part END, + '.', '' + ) || '@' || REPLACE(c.domain_part, '.', '') +ORDER BY c.id` + +// ListActiveUsersByEmailAliasProbeKeys 见 service.UserEmailBlacklistRepository。 +func (r *userRepository) ListActiveUsersByEmailAliasProbeKeys(ctx context.Context, keys []string) ([]service.User, error) { + if len(keys) == 0 { + return []service.User{}, nil + } + if r.sql == nil { + return nil, fmt.Errorf("sql executor is not configured") + } + rows, err := r.sql.QueryContext(ctx, listActiveUsersByEmailAliasProbeKeysSQL, pq.Array(keys), service.StatusActive, service.RoleAdmin) + if err != nil { + return nil, fmt.Errorf("list users by email alias probes: %w", err) + } + defer func() { _ = rows.Close() }() + + users := make([]service.User, 0) + for rows.Next() { + var user service.User + if err := rows.Scan(&user.ID, &user.Email, &user.Username); err != nil { + return nil, fmt.Errorf("scan user by email alias probe: %w", err) + } + user.Status = service.StatusActive + users = append(users, user) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate users by email alias probes: %w", err) + } + return users, nil +} + +// BatchDisableUsers 见 service.UserEmailBlacklistRepository。 +// +// 与 userRepository.Update 停用单个用户的口径一致:停用与吊销 MCP 授权在同一事务内分两条语句 +// 执行,恢复账号后旧授权不会复活。吊销语句在停用语句拿到用户行锁之后才取快照,能看到持有该行锁 +// 并发新建、随后提交的授权。 +func (r *userRepository) BatchDisableUsers(ctx context.Context, userIDs []int64) ([]int64, error) { + if len(userIDs) == 0 { + return []int64{}, nil + } + if r.client == nil { + return nil, fmt.Errorf("ent client is not configured") + } + tx, err := r.client.Tx(ctx) + if err != nil && !errors.Is(err, dbent.ErrTxStarted) { + return nil, err + } + txCtx := ctx + if err == nil { + defer func() { _ = tx.Rollback() }() + txCtx = dbent.NewTxContext(ctx, tx) + } + exec := txAwareSQLExecutor(txCtx, r.sql, r.client) + if exec == nil { + return nil, fmt.Errorf("sql executor is not configured") + } + + disabled, err := batchDisableUserRows(txCtx, exec, userIDs) + if err != nil { + return nil, err + } + if len(disabled) > 0 { + if _, err := exec.ExecContext(txCtx, + `UPDATE mcp_oauth_grants SET revoked_at = $2 WHERE user_id = ANY($1) AND revoked_at IS NULL`, + pq.Array(disabled), time.Now().UTC(), + ); err != nil { + return nil, fmt.Errorf("revoke mcp grants of disabled users: %w", err) + } + } + if tx != nil { + if err := tx.Commit(); err != nil { + return nil, err + } + } + return disabled, nil +} + +func batchDisableUserRows(ctx context.Context, exec sqlQueryExecutor, userIDs []int64) ([]int64, error) { + rows, err := exec.QueryContext(ctx, ` +UPDATE users SET status = $1, updated_at = NOW() +WHERE id = ANY($2) AND deleted_at IS NULL AND role <> $3 AND status <> $1 +RETURNING id`, service.StatusDisabled, pq.Array(userIDs), service.RoleAdmin) + if err != nil { + return nil, fmt.Errorf("batch disable users: %w", err) + } + defer func() { _ = rows.Close() }() + + disabled := make([]int64, 0, len(userIDs)) + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, fmt.Errorf("scan disabled user id: %w", err) + } + disabled = append(disabled, id) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("iterate disabled user ids: %w", err) + } + slices.Sort(disabled) + return disabled, nil +} diff --git a/backend/internal/repository/user_repo_email_blacklist_integration_test.go b/backend/internal/repository/user_repo_email_blacklist_integration_test.go new file mode 100644 index 0000000000..a29831d7b8 --- /dev/null +++ b/backend/internal/repository/user_repo_email_blacklist_integration_test.go @@ -0,0 +1,163 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func emailBlacklistProbeKeys(emails ...string) []string { + keys := make([]string, 0, 2*len(emails)) + for _, email := range emails { + for _, probe := range service.EmailAliasDedupProbes(email) { + keys = append(keys, service.EmailAliasProbeKey(probe)) + } + } + return keys +} + +func (s *UserRepoSuite) TestListActiveUsersByEmailAliasProbeKeys_MatchesInboxVariants() { + dotted := s.mustCreateUser(&service.User{Email: "bl.target@gmail.com"}) + plusGooglemail := s.mustCreateUser(&service.User{Email: "bltarget+promo@googlemail.com"}) + upperRootDot := s.mustCreateUser(&service.User{Email: "BL.Tar.Get@Gmail.com."}) + nonGmailDotted := s.mustCreateUser(&service.User{Email: "bl.target@company.example"}) + s.mustCreateUser(&service.User{Email: "bltarget2@gmail.com"}) + s.mustCreateUser(&service.User{Email: "b.l.target@gmail.com", Status: service.StatusDisabled}) + s.mustCreateUser(&service.User{Email: "bltarget@gmail.com", Role: service.RoleAdmin}) + deleted := s.mustCreateUser(&service.User{Email: "bltar.get+x@gmail.com"}) + s.Require().NoError(s.repo.Delete(s.ctx, deleted.ID)) + + users, err := s.repo.ListActiveUsersByEmailAliasProbeKeys(s.ctx, + emailBlacklistProbeKeys("bltarget@googlemail.com", "bltarget@company.example")) + s.Require().NoError(err) + + ids := make([]int64, 0, len(users)) + for _, user := range users { + s.Require().Equal(service.StatusActive, user.Status) + ids = append(ids, user.ID) + } + // 仓储层按去点形态过度匹配非 Gmail 域名(bl.target@company.example),由 service 层复核。 + s.Require().ElementsMatch([]int64{dotted.ID, plusGooglemail.ID, upperRootDot.ID, nonGmailDotted.ID}, ids) +} + +func (s *UserRepoSuite) TestListActiveUsersByEmailAliasProbeKeys_EmptyKeys() { + s.mustCreateUser(&service.User{Email: "bl-empty@gmail.com"}) + + users, err := s.repo.ListActiveUsersByEmailAliasProbeKeys(s.ctx, nil) + s.Require().NoError(err) + s.Require().Empty(users) +} + +func (s *UserRepoSuite) TestBatchDisableUsers_SkipsAdminDisabledAndDeleted() { + active := s.mustCreateUser(&service.User{Email: "bl-disable-active@example.com"}) + admin := s.mustCreateUser(&service.User{Email: "bl-disable-admin@example.com", Role: service.RoleAdmin}) + already := s.mustCreateUser(&service.User{Email: "bl-disable-already@example.com", Status: service.StatusDisabled}) + deleted := s.mustCreateUser(&service.User{Email: "bl-disable-deleted@example.com"}) + s.Require().NoError(s.repo.Delete(s.ctx, deleted.ID)) + + disabled, err := s.repo.BatchDisableUsers(s.ctx, []int64{active.ID, admin.ID, already.ID, deleted.ID, 99999999}) + s.Require().NoError(err) + s.Require().Equal([]int64{active.ID}, disabled) + + got, err := s.repo.GetByID(s.ctx, active.ID) + s.Require().NoError(err) + s.Require().Equal(service.StatusDisabled, got.Status) + + gotAdmin, err := s.repo.GetByID(s.ctx, admin.ID) + s.Require().NoError(err) + s.Require().Equal(service.StatusActive, gotAdmin.Status) +} + +// 批量禁用与单个禁用一样持久吊销 MCP 授权:恢复账号后旧授权与令牌不会复活,被跳过的用户授权不受影响。 +func TestBatchDisableUsers_RevokesMCPGrantsPersistently(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + target := newMCPOAuthIntegrationFixture(t, ctx) + skippedAdmin := newMCPOAuthIntegrationFixture(t, ctx) + issued, err := target.oauth.Token(ctx, target.input, mcpIntegrationResource) + require.NoError(t, err) + + users := NewUserRepository(integrationEntClient, integrationDB) + admin, err := users.GetByID(ctx, skippedAdmin.userID) + require.NoError(t, err) + admin.Role = service.RoleAdmin + require.NoError(t, users.Update(ctx, admin, service.UserUpdateFields{Role: true})) + + blacklistRepo, ok := users.(service.UserEmailBlacklistRepository) + require.True(t, ok) + disabled, err := blacklistRepo.BatchDisableUsers(ctx, []int64{target.userID, skippedAdmin.userID}) + require.NoError(t, err) + require.Equal(t, []int64{target.userID}, disabled) + + requireRevoked := func(f mcpOAuthIntegrationFixture, revoked bool) { + t.Helper() + grant, err := f.repo.GetGrant(ctx, f.grantID) + require.NoError(t, err) + require.Equal(t, revoked, grant.RevokedAt != nil, f.grantID) + } + requireRevoked(target, true) + requireRevoked(skippedAdmin, false) + + user, err := users.GetByID(ctx, target.userID) + require.NoError(t, err) + user.Status = service.StatusActive + require.NoError(t, users.Update(ctx, user, service.UserUpdateFields{Status: true})) + requireRevoked(target, true) + _, err = target.oauth.Authenticate(ctx, issued.AccessToken) + require.ErrorIs(t, err, service.ErrMCPOAuthInvalidToken) +} + +// 授权创建持有用户行锁时发起批量禁用:禁用等锁释放后执行,并吊销对方刚提交的授权。 +func TestBatchDisableUsers_RevokesGrantCommittedWhileWaitingForUserLock(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + f := newMCPOAuthIntegrationFixture(t, ctx) + + // 与 mcpOAuthRepository.CreateAuthorization 相同的加锁顺序:先锁用户行,再插入授权。 + lockTx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = lockTx.Rollback() }() + _, err = lockTx.ExecContext(ctx, `SELECT id FROM users WHERE id=$1 FOR UPDATE`, f.userID) + require.NoError(t, err) + now := time.Now().UTC() + const racingGrantID = "bl-race-grant-0000000000000000" + _, err = lockTx.ExecContext(ctx, ` +INSERT INTO mcp_oauth_grants (id, client_id, client_name, user_id, token_version, resource, scope, read_only, created_at, expires_at) +VALUES ($1, $2, 'racing client', $3, 1, $4, 'user', TRUE, $5, $6)`, + racingGrantID, f.input.ClientID, f.userID, mcpIntegrationResource, now, now.Add(time.Hour)) + require.NoError(t, err) + + users := NewUserRepository(integrationEntClient, integrationDB).(service.UserEmailBlacklistRepository) + type batchResult struct { + disabled []int64 + err error + } + done := make(chan batchResult, 1) + go func() { + disabled, err := users.BatchDisableUsers(ctx, []int64{f.userID}) + done <- batchResult{disabled: disabled, err: err} + }() + + require.Eventually(t, func() bool { + var waiting int + err := integrationDB.QueryRowContext(ctx, ` +SELECT COUNT(*) FROM pg_stat_activity +WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE '%UPDATE users SET status%'`).Scan(&waiting) + return err == nil && waiting > 0 + }, 10*time.Second, 10*time.Millisecond, "batch disable should wait for the user row lock") + require.NoError(t, lockTx.Commit()) + + result := <-done + require.NoError(t, result.err) + require.Equal(t, []int64{f.userID}, result.disabled) + for _, id := range []string{f.grantID, racingGrantID} { + grant, err := f.repo.GetGrant(ctx, id) + require.NoError(t, err) + require.NotNil(t, grant.RevokedAt, id) + } +} diff --git a/backend/internal/repository/wire.go b/backend/internal/repository/wire.go index f176e56eea..786392193f 100644 --- a/backend/internal/repository/wire.go +++ b/backend/internal/repository/wire.go @@ -66,6 +66,7 @@ func ProvideSchedulerCache(rdb *redis.Client, cfg *config.Config) service.Schedu // ProviderSet is the Wire provider set for all repositories var ProviderSet = wire.NewSet( NewUserRepository, + NewMCPOAuthRepository, NewAPIKeyRepository, NewGroupRepository, NewAdminGroupRepository, diff --git a/backend/internal/server/http.go b/backend/internal/server/http.go index f999b343b2..68db383d1d 100644 --- a/backend/internal/server/http.go +++ b/backend/internal/server/http.go @@ -10,6 +10,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/handler" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/websearch" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" @@ -121,7 +122,7 @@ func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server { // IdleTimeout: 空闲连接超时时间,释放不活跃的连接资源 IdleTimeout: time.Duration(cfg.Server.IdleTimeout) * time.Second, // 注意:不设置 WriteTimeout,因为流式响应可能持续十几分钟 - // 不设置 ReadTimeout,因为大请求体可能需要较长时间读取 + // 请求体使用逐次读取的 idle deadline,不设置覆盖整个大请求上传的 ReadTimeout。 } globalMaxSize := cfg.Server.MaxRequestBodySize @@ -159,7 +160,8 @@ func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server { } } - server.Handler = httpHandler + httpHandler = pkghttputil.WithBodyReadTimeout(httpHandler, time.Duration(cfg.Gateway.RequestBodyReadTimeoutSeconds)*time.Second) + server.Handler = pkghttputil.WithWriteTimeout(httpHandler, time.Duration(cfg.Gateway.DownstreamWriteTimeoutSeconds)*time.Second) return server } diff --git a/backend/internal/server/middleware/admin_auth.go b/backend/internal/server/middleware/admin_auth.go index fd0f270534..61899cb981 100644 --- a/backend/internal/server/middleware/admin_auth.go +++ b/backend/internal/server/middleware/admin_auth.go @@ -268,7 +268,7 @@ func recordAdminKeyRequest(c *gin.Context, audit *service.AuditLogService, item } entry := &service.AuditLog{CreatedAt: time.Now().UTC(), AuthMethod: service.AuditAuthMethodAdminAPIKey, Action: "admin.api_key.request", Method: c.Request.Method, Path: c.Request.URL.Path, StatusCode: c.Writer.Status(), ClientIP: SecurityClientIP(c), UserAgent: c.Request.UserAgent()} if item != nil { - entry.Extra = map[string]any{"admin_key_id": item.ID, "admin_key_name": item.Name} + entry.Extra = map[string]any{"admin_key_id": item.ID, "admin_key_name": item.Name, "full_access": item.Policy.FullAccess} uid := item.CreatedBy entry.ActorUserID = &uid } diff --git a/backend/internal/server/middleware/audit_log.go b/backend/internal/server/middleware/audit_log.go index 30f399eea3..ad6e42d6c4 100644 --- a/backend/internal/server/middleware/audit_log.go +++ b/backend/internal/server/middleware/audit_log.go @@ -52,6 +52,8 @@ func SkipAudit(c *gin.Context) { // scalar, non-secret operation summaries. Request bodies and arbitrary maps // are never accepted through this channel. var auditExtraAllowedKeys = map[string]struct{}{ + "admin_key_id": {}, "full_access": {}, "full_access_before": {}, + "mcp_grant_id": {}, "mcp_tool": {}, "result": {}, "error_code": {}, "enabled": {}, "blocking_enabled": {}, "config_version": {}, "endpoint_count": {}, "scanner_count": {}, "all_groups": {}, "group_count": {}, "guard_endpoint_id": {}, @@ -160,7 +162,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 { @@ -179,6 +181,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/cors.go b/backend/internal/server/middleware/cors.go index fcf6d332bc..cf63a29c91 100644 --- a/backend/internal/server/middleware/cors.go +++ b/backend/internal/server/middleware/cors.go @@ -53,6 +53,7 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { allowHeaders := []string{ "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", "X-User-UI-Request", + "MCP-Protocol-Version", "MCP-Session-Id", } // OpenAI Node SDK 会发送 x-stainless-* 请求头,需在 CORS 中显式放行。 openAIProperties := []string{ @@ -65,6 +66,28 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { allowHeadersValue := strings.Join(allowHeaders, ", ") return func(c *gin.Context) { + // OAuth discovery and public-client protocol endpoints use no browser + // session credentials. Keep this exception exact so consent and account + // management APIs retain the configured origin policy. + if method := publicMCPOAuthMethod(c.Request.URL.EscapedPath()); method != "" && + (c.Request.Method == method || c.Request.Method == http.MethodOptions) { + if requested := c.GetHeader("Access-Control-Request-Method"); c.Request.Method == http.MethodOptions && requested != "" && requested != method { + c.AbortWithStatus(http.StatusForbidden) + return + } + c.Header("Access-Control-Allow-Origin", "*") + c.Writer.Header().Del("Access-Control-Allow-Credentials") + c.Header("Access-Control-Allow-Headers", "Content-Type") + c.Header("Access-Control-Allow-Methods", method+", OPTIONS") + c.Header("Access-Control-Expose-Headers", "WWW-Authenticate") + c.Header("Access-Control-Max-Age", "86400") + if c.Request.Method == http.MethodOptions { + c.AbortWithStatus(http.StatusNoContent) + return + } + c.Next() + return + } origin := strings.TrimSpace(c.GetHeader("Origin")) originAllowed := allowAll if origin != "" && !allowAll { @@ -83,7 +106,7 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { } c.Writer.Header().Set("Access-Control-Allow-Headers", allowHeadersValue) c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH") - c.Writer.Header().Set("Access-Control-Expose-Headers", "ETag, Server-Timing") + c.Writer.Header().Set("Access-Control-Expose-Headers", "ETag, Server-Timing, WWW-Authenticate") c.Writer.Header().Set("Access-Control-Max-Age", "86400") } // 处理预检请求 @@ -100,6 +123,17 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { } } +func publicMCPOAuthMethod(path string) string { + switch path { + case "/.well-known/oauth-protected-resource/api/v1/mcp", "/.well-known/oauth-protected-resource", "/.well-known/oauth-authorization-server": + return http.MethodGet + case "/api/v1/mcp/oauth/register", "/api/v1/mcp/oauth/token", "/api/v1/mcp/oauth/revoke": + return http.MethodPost + default: + return "" + } +} + func normalizeOrigins(values []string) []string { if len(values) == 0 { return nil diff --git a/backend/internal/server/middleware/cors_test.go b/backend/internal/server/middleware/cors_test.go index 8828389860..d6eb8c612d 100644 --- a/backend/internal/server/middleware/cors_test.go +++ b/backend/internal/server/middleware/cors_test.go @@ -108,6 +108,7 @@ func TestCORS_AllowedOrigin_HasAllowHeaders(t *testing.T) { assert.NotEmpty(t, w.Header().Get("Access-Control-Allow-Methods"), "允许的 origin 应收到 Allow-Methods") assert.Contains(t, w.Header().Get("Access-Control-Expose-Headers"), "Server-Timing") + assert.Contains(t, w.Header().Get("Access-Control-Expose-Headers"), "WWW-Authenticate") assert.Equal(t, "86400", w.Header().Get("Access-Control-Max-Age"), "允许的 origin 应收到 Max-Age=86400") assert.Equal(t, "https://allowed.example.com", w.Header().Get("Access-Control-Allow-Origin"), @@ -116,6 +117,102 @@ func TestCORS_AllowedOrigin_HasAllowHeaders(t *testing.T) { } } +func TestCORSPublicMCPOAuthEndpoints(t *testing.T) { + endpoints := []struct{ path, method string }{ + {"/.well-known/oauth-protected-resource/api/v1/mcp", http.MethodGet}, + {"/.well-known/oauth-protected-resource", http.MethodGet}, + {"/.well-known/oauth-authorization-server", http.MethodGet}, + {"/api/v1/mcp/oauth/register", http.MethodPost}, + {"/api/v1/mcp/oauth/token", http.MethodPost}, + {"/api/v1/mcp/oauth/revoke", http.MethodPost}, + } + for _, allowedOrigins := range [][]string{nil, {"https://console.example.com"}, {"*"}} { + middleware := CORS(config.CORSConfig{AllowedOrigins: allowedOrigins, AllowCredentials: true}) + for _, endpoint := range endpoints { + for _, origin := range []string{"https://client.example.com", "https://console.example.com"} { + for _, method := range []string{endpoint.method, http.MethodOptions} { + t.Run(endpoint.path+"/"+method+"/"+origin, func(t *testing.T) { + w := httptest.NewRecorder() + // Public OAuth responses must never inherit credentialed CORS. + w.Header().Set("Access-Control-Allow-Credentials", "true") + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(method, endpoint.path, nil) + c.Request.Header.Set("Origin", origin) + if method == http.MethodOptions { + c.Request.Header.Set("Access-Control-Request-Method", endpoint.method) + c.Request.Header.Set("Access-Control-Request-Headers", "content-type") + } + + middleware(c) + + assert.Equal(t, "*", w.Header().Get("Access-Control-Allow-Origin")) + assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials")) + assert.Equal(t, "Content-Type", w.Header().Get("Access-Control-Allow-Headers")) + assert.Equal(t, endpoint.method+", OPTIONS", w.Header().Get("Access-Control-Allow-Methods")) + if method == http.MethodOptions { + assert.Equal(t, http.StatusNoContent, w.Code) + assert.True(t, c.IsAborted()) + } else { + assert.False(t, c.IsAborted()) + } + }) + } + } + } + } +} + +func TestCORSPublicMCPOAuthExceptionDoesNotCoverOtherPaths(t *testing.T) { + for _, path := range []string{ + "/api/v1/mcp", "/api/v1/mcp/oauth/authorize", "/api/v1/mcp/oauth/consent", + "/api/v1/user/mcp/grants", "/api/v1/user/profile", "/settings/mcp", + "/api/v1/mcp/oauth/token/", "/api/v1/mcp/oauth/token-extra", "/api/v1/mcp/oauth/%74oken", + "/.well-known/oauth-protected-resource/other", "/.well-known/oauth-authorization-server/", + } { + t.Run(path, func(t *testing.T) { + middleware := CORS(config.CORSConfig{AllowedOrigins: []string{"https://console.example.com"}, AllowCredentials: true}) + for _, origin := range []string{"https://client.example.com", "https://console.example.com"} { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodOptions, path, nil) + c.Request.Header.Set("Origin", origin) + c.Request.Header.Set("Access-Control-Request-Method", http.MethodPost) + + middleware(c) + + if origin == "https://console.example.com" { + assert.Equal(t, http.StatusNoContent, w.Code) + assert.Equal(t, origin, w.Header().Get("Access-Control-Allow-Origin")) + assert.Equal(t, "true", w.Header().Get("Access-Control-Allow-Credentials")) + } else { + assert.Equal(t, http.StatusForbidden, w.Code) + assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin")) + assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials")) + } + } + }) + } +} + +func TestCORSPublicMCPOAuthPreflightRejectsUnsupportedMethods(t *testing.T) { + for _, tc := range []struct{ path, method string }{ + {"/.well-known/oauth-protected-resource/api/v1/mcp", http.MethodPost}, + {"/api/v1/mcp/oauth/token", http.MethodDelete}, + } { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodOptions, tc.path, nil) + c.Request.Header.Set("Origin", "https://client.example.com") + c.Request.Header.Set("Access-Control-Request-Method", tc.method) + + CORS(config.CORSConfig{AllowCredentials: true})(c) + + assert.Equal(t, http.StatusForbidden, w.Code) + assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin")) + assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials")) + } +} + func TestCORS_PreflightDisallowedOrigin_ReturnsForbidden(t *testing.T) { cfg := config.CORSConfig{ AllowedOrigins: []string{"https://allowed.example.com"}, diff --git a/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go b/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go index 305b7b34de..453ba5e0a3 100644 --- a/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go +++ b/backend/internal/server/middleware/custom_admin_key_rate_limit_test.go @@ -168,3 +168,21 @@ func TestScopedAdminKeyPanelRateLimitPreservesUnrestrictedAdminWrites(t *testing }) } } + +func TestAdminFullAccessRetainsPerKeyRateLimit(t *testing.T) { + allower := &fakePanelAllower{} + limiter := &PanelRateLimiter{limiter: allower, settingService: newPanelRateLimitTestService(t, `{"enabled":true,"user_rpm":1,"heavy_rpm":1,"exempt_admin":true}`)} + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(string(ContextKeyUser), AuthSubject{UserID: 9}) + c.Set(string(ContextKeyUserRole), service.RoleAdmin) + c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: "full", Policy: adminaccess.Policy{FullAccess: true}})) + }, limiter.Global()) + r.GET("/full", func(c *gin.Context) { c.Status(204) }) + for _, want := range []int{204, 429} { + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/full", nil)) + require.Equal(t, want, w.Code) + } + require.Equal(t, int64(2), allower.counts["panel:global:admin-key:full"]) +} diff --git a/backend/internal/server/middleware/custom_admin_keys_test.go b/backend/internal/server/middleware/custom_admin_keys_test.go index 23d40240c8..f9f2d02003 100644 --- a/backend/internal/server/middleware/custom_admin_keys_test.go +++ b/backend/internal/server/middleware/custom_admin_keys_test.go @@ -115,3 +115,36 @@ func TestScopedAdminKeyMissingDependenciesFailClosed(t *testing.T) { require.NotPanics(t, func() { r.ServeHTTP(w, req) }) require.Equal(t, 401, w.Code) } + +func TestAdminFullAccessKeepsIdentityAndJWTBoundary(t *testing.T) { + repo := &adminAuthKeyRepo{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(repo) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "兼容", Enabled: true, ConfirmFullAccess: true, Policy: adminaccess.Policy{FullAccess: true}}, 9) + require.NoError(t, err) + users := service.NewUserService(&stubUserRepo{getByID: func(context.Context, int64) (*service.User, error) { + return &service.User{ID: 9, Role: service.RoleAdmin, Status: service.StatusActive}, nil + }}, nil, nil, nil) + r := gin.New() + r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, users, settings, nil))) + r.GET("/api/v1/admin/future", func(c *gin.Context) { + require.NotNil(t, adminaccess.FromContext(c.Request.Context())) + require.Nil(t, adminaccess.RestrictedFromContext(c.Request.Context())) + require.Equal(t, service.AuditAuthMethodAdminAPIKey, c.GetString("auth_method")) + c.Status(204) + }) + r.POST("/api/v1/admin/settings/admin-api-keys", func(c *gin.Context) { t.Fatal("全权key不能管理密钥") }) + r.GET("/api/v1/admin/interactive", func(c *gin.Context) { + require.False(t, enforceStepUp(c, nil, nil, nil)) + }) + for _, tc := range []struct { + method, path string + status int + }{{"GET", "/api/v1/admin/future", 204}, {"POST", "/api/v1/admin/settings/admin-api-keys", 403}, {"GET", "/api/v1/admin/interactive", 403}} { + w := httptest.NewRecorder() + req := httptest.NewRequest(tc.method, tc.path, nil) + req.Header.Set("x-api-key", key) + r.ServeHTTP(w, req) + require.Equal(t, tc.status, w.Code, w.Body.String()) + } +} diff --git a/backend/internal/server/middleware/group_model_allowlist.go b/backend/internal/server/middleware/group_model_allowlist.go index 3f5e61e585..3c8c5d0628 100644 --- a/backend/internal/server/middleware/group_model_allowlist.go +++ b/backend/internal/server/middleware/group_model_allowlist.go @@ -113,6 +113,9 @@ func isResponsesWebSocketRoute(c *gin.Context) bool { func groupModelAllowlistModelsFromBody(c *gin.Context) ([]string, bool) { body, err := httputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if RejectRequestBodyReadError(c, err) { + return nil, false + } status := http.StatusBadRequest message := "Failed to read request body" var maxErr *http.MaxBytesError diff --git a/backend/internal/server/middleware/panel_rate_limit.go b/backend/internal/server/middleware/panel_rate_limit.go index b9f2453d0f..8f0eac5efa 100644 --- a/backend/internal/server/middleware/panel_rate_limit.go +++ b/backend/internal/server/middleware/panel_rate_limit.go @@ -54,6 +54,12 @@ func (p *PanelRateLimiter) Global() gin.HandlerFunc { return p.userScoped("global", func(s service.PanelRateLimitSettings) int { return s.UserRPM }) } +// MCPTransport bounds protocol requests, including discovery, separately from +// the global budget charged by each dispatched management operation. +func (p *PanelRateLimiter) MCPTransport() gin.HandlerFunc { + return p.userScoped("mcp", func(s service.PanelRateLimitSettings) int { return s.UserRPM }) +} + // Heavy 重查询接口的按用户限流(严格档,覆盖 usage/dashboard 等聚合统计端点)。 // 与 Global 叠加计数:一次重查询同时消耗两档额度。 func (p *PanelRateLimiter) Heavy() gin.HandlerFunc { diff --git a/backend/internal/server/middleware/request_body_limit.go b/backend/internal/server/middleware/request_body_limit.go index fce13eea9b..14d3eaa662 100644 --- a/backend/internal/server/middleware/request_body_limit.go +++ b/backend/internal/server/middleware/request_body_limit.go @@ -1,14 +1,20 @@ package middleware import ( + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "net/http" "github.com/gin-gonic/gin" ) // RequestBodyLimit 使用 MaxBytesReader 限制请求体大小。 -func RequestBodyLimit(maxBytes int64) gin.HandlerFunc { +func RequestBodyLimit(maxBytes int64, budgets ...*pkghttputil.BodyMemoryBudget) gin.HandlerFunc { return func(c *gin.Context) { + if len(budgets) > 0 { + ctx, release := pkghttputil.WithRequestBodyMemoryBudget(c.Request.Context(), budgets[0]) + defer release() + c.Request = c.Request.WithContext(ctx) + } c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes) c.Next() } diff --git a/backend/internal/server/middleware/request_body_memory.go b/backend/internal/server/middleware/request_body_memory.go new file mode 100644 index 0000000000..d66034f996 --- /dev/null +++ b/backend/internal/server/middleware/request_body_memory.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "errors" + "net/http" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/gin-gonic/gin" +) + +// RejectRequestBodyReadError handles early ingress termination before the route +// handler runs. Cancelled clients have no response body and an uncommitted +// response is marked 499, matching the gateway handler's cancellation path. +func RejectRequestBodyReadError(c *gin.Context, err error) bool { + if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil { + if !c.Writer.Written() { + c.Status(499) + } + c.Abort() + return true + } + return RejectRequestBodyMemoryOverload(c, err) +} + +// RejectRequestBodyMemoryOverload keeps temporary capacity errors distinct +// from invalid JSON and the per-request 413 size limit. +func RejectRequestBodyMemoryOverload(c *gin.Context, err error) bool { + if !errors.Is(err, pkghttputil.ErrRequestBodyMemoryBudget) { + return false + } + c.Header("Retry-After", "1") + groupModelAllowlistErrorWriter(c)(c, http.StatusServiceUnavailable, "Request body buffering capacity is exhausted; retry later") + c.Abort() + return true +} diff --git a/backend/internal/server/middleware/request_body_memory_test.go b/backend/internal/server/middleware/request_body_memory_test.go new file mode 100644 index 0000000000..30cff09a4e --- /dev/null +++ b/backend/internal/server/middleware/request_body_memory_test.go @@ -0,0 +1,98 @@ +package middleware + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestRequestBodyMemoryRejectsOverloadAndReleasesAfterHandler(t *testing.T) { + router := gin.New() + held := make(chan struct{}) + release := make(chan struct{}) + router.POST("/v1/responses", RequestBodyLimit(2048, pkghttputil.NewBodyMemoryBudget(1024)), func(c *gin.Context) { + _, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) + if RejectRequestBodyMemoryOverload(c, err) { + return + } + if err != nil { + c.AbortWithStatus(http.StatusBadRequest) + return + } + if c.Query("hold") == "1" { + close(held) + <-release + } + c.Status(http.StatusNoContent) + }) + request := func(path string) *httptest.ResponseRecorder { + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(strings.Repeat("x", 700)))) + return w + } + firstDone := make(chan *httptest.ResponseRecorder, 1) + go func() { firstDone <- request("/v1/responses?hold=1") }() + releaseHeld := sync.OnceFunc(func() { close(release) }) + defer releaseHeld() + select { + case <-held: + case <-time.After(5 * time.Second): + t.Fatal("first request did not reach handler") + } + w := request("/v1/responses") + require.Equal(t, http.StatusServiceUnavailable, w.Code) + require.Equal(t, "1", w.Header().Get("Retry-After")) + releaseHeld() + select { + case first := <-firstDone: + require.Equal(t, http.StatusNoContent, first.Code) + case <-time.After(5 * time.Second): + t.Fatal("held request did not finish") + } + require.Equal(t, http.StatusNoContent, request("/v1/responses").Code) +} + +func TestRejectRequestBodyReadErrorCancellation(t *testing.T) { + for _, tc := range []struct { + name string + cancelled bool + committed bool + }{ + {name: "cancelled", cancelled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true}, + {name: "ordinary_read_error"}, + } { + t.Run(tc.name, func(t *testing.T) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + if tc.cancelled { + cancel() + } + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + if tc.committed { + _, err := c.Writer.WriteString("already committed") + require.NoError(t, err) + } + bodyBefore := recorder.Body.String() + require.Equal(t, tc.cancelled, RejectRequestBodyReadError(c, io.ErrUnexpectedEOF)) + require.Equal(t, tc.cancelled, c.IsAborted()) + status := http.StatusOK + if tc.cancelled && !tc.committed { + status = 499 + } + require.Equal(t, status, c.Writer.Status()) + require.Equal(t, bodyBefore, recorder.Body.String()) + }) + } +} diff --git a/backend/internal/server/middleware/step_up.go b/backend/internal/server/middleware/step_up.go index 31a320e3fd..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,9 +118,9 @@ func enforceStepUp(c *gin.Context, grantChecker stepUpGrantChecker, userReader s return true } - 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 d817d4659a..65c3de8888 100644 --- a/backend/internal/server/middleware/step_up_test.go +++ b/backend/internal/server/middleware/step_up_test.go @@ -63,6 +63,34 @@ func TestEnforceStepUpRejectsAdminAPIKey(t *testing.T) { require.Contains(t, rec.Body.String(), "STEP_UP_ADMIN_API_KEY_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) { c, rec := newStepUpTestContext(t) diff --git a/backend/internal/server/router.go b/backend/internal/server/router.go index c0dde5c426..8dcc7ab942 100644 --- a/backend/internal/server/router.go +++ b/backend/internal/server/router.go @@ -128,6 +128,8 @@ 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, 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/admin.go b/backend/internal/server/routes/admin.go index fbeac5fe11..51efcd36ab 100644 --- a/backend/internal/server/routes/admin.go +++ b/backend/internal/server/routes/admin.go @@ -316,6 +316,8 @@ func registerUserManagementRoutes(admin *gin.RouterGroup, h *handler.Handlers) { users.GET("/:id/rpm-status", h.Admin.User.GetUserRPMStatus) users.POST("/batch-concurrency", h.Admin.User.BatchUpdateConcurrency) users.POST("/batch-limits", h.Admin.User.BatchUpdateLimits) + users.POST("/batch-disable", h.Admin.User.BatchDisable) + users.POST("/blacklist-matches", h.Admin.User.FindBlacklistedEmailUsers) users.GET("/:id/platform-quotas", h.Admin.User.GetUserPlatformQuotas) users.PUT("/:id/platform-quotas", h.Admin.User.UpdateUserPlatformQuotas) users.POST("/:id/platform-quotas/reset", h.Admin.User.ResetUserPlatformQuotaWindow) @@ -593,6 +595,9 @@ func registerSettingsRoutes(admin *gin.RouterGroup, h *handler.Handlers, stepUpA // OpenAI OAuth image-tool unavailable cooldown configuration adminSettings.GET("/openai-images-oauth-unavailable-cooldown", h.Admin.Setting.GetOpenAIImagesOAuthUnavailableCooldownSettings) adminSettings.PUT("/openai-images-oauth-unavailable-cooldown", h.Admin.Setting.UpdateOpenAIImagesOAuthUnavailableCooldownSettings) + // 注册邮箱精确黑名单 + adminSettings.GET("/registration-email-blacklist", h.Admin.Setting.GetRegistrationEmailBlacklist) + adminSettings.PUT("/registration-email-blacklist", h.Admin.Setting.UpdateRegistrationEmailBlacklist) // 面板 API 限流配置 adminSettings.GET("/panel-rate-limit", h.Admin.Setting.GetPanelRateLimitSettings) adminSettings.PUT("/panel-rate-limit", h.Admin.Setting.UpdatePanelRateLimitSettings) diff --git a/backend/internal/server/routes/custom_admin_key_access_test.go b/backend/internal/server/routes/custom_admin_key_access_test.go index 32794e1b88..8563d42747 100644 --- a/backend/internal/server/routes/custom_admin_key_access_test.go +++ b/backend/internal/server/routes/custom_admin_key_access_test.go @@ -76,7 +76,7 @@ func (*scopedRouteAccounts) GetAccount(_ context.Context, id int64) (*service.Ac } return a, nil } -func (s *scopedRouteAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) { +func (s *scopedRouteAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) { s.t.Fatal("本测试中列表必须在权限准入阶段被拒绝") return nil, 0, nil } diff --git a/backend/internal/server/routes/custom_admin_key_full_access_test.go b/backend/internal/server/routes/custom_admin_key_full_access_test.go new file mode 100644 index 0000000000..ca2cbb606d --- /dev/null +++ b/backend/internal/server/routes/custom_admin_key_full_access_test.go @@ -0,0 +1,96 @@ +//go:build unit + +package routes + +import ( + "context" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type fullAccessRouteService struct{ scopedRouteAccounts } + +func (*fullAccessRouteService) GetProxy(context.Context, int64) (*service.Proxy, error) { + return &service.Proxy{ID: 9, Username: "proxy-user", Password: "proxy-secret", Status: "active"}, nil +} +func (*fullAccessRouteService) GetGroup(context.Context, int64) (*service.Group, error) { + return &service.Group{ID: 9, Name: "完整分组", Platform: "openai", RateMultiplier: 12.5}, nil +} + +func TestAdminFullAccessRegisteredRoutesPreserveFullHandlers(t *testing.T) { + gin.SetMode(gin.TestMode) + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "完整管理", Enabled: true, ConfirmFullAccess: true, Policy: adminaccess.Policy{FullAccess: true}}, 9) + require.NoError(t, err) + svc := &fullAccessRouteService{scopedRouteAccounts{t: t}} + account := adminhandler.NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, service.NewUserService(&scopedRouteUsers{}, nil, nil, nil), settings, nil) + r := gin.New() + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: account, Group: adminhandler.NewGroupHandler(svc, nil, nil), Proxy: adminhandler.NewProxyHandler(svc)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.AbortWithStatus(403) }), nil, nil) + for _, tc := range []struct{ path, contains string }{ + {"/accounts/3", `"group_ids":[2]`}, + {"/groups/9", `"rate_multiplier":12.5`}, + {"/proxies/9", `"password":"proxy-secret"`}, + } { + req := httptest.NewRequest("GET", "/api/v1/admin"+tc.path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 200, w.Code, tc.path+": "+w.Body.String()) + require.Contains(t, w.Body.String(), tc.contains) + } + // 密钥全权模式仍不跨越真人会话边界。 + for _, path := range []string{"/api/v1/admin/settings/admin-api-keys", "/api/v1/admin/accounts/data"} { + req := httptest.NewRequest("GET", path, nil) + req.Header.Set("x-api-key", key) + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, 403, w.Code) + } +} + +func TestAdminFullAccessCreationRequiresHTTPConfirmation(t *testing.T) { + for _, tc := range []struct { + body string + status int + }{ + {`{"name":"兼容","enabled":true,"policy":{"full_access":true}}`, 400}, + {`{"name":"兼容","enabled":true,"policy":{"full_access":true},"confirm_full_access":"true"}`, 400}, + {`{"name":"兼容","enabled":true,"policy":{"full_access":true},"confirm_full_access":true}`, 200}, + } { + keys := &scopedRouteKeys{} + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(keys) + r := gin.New() + auth := middleware.AdminAuthMiddleware(func(c *gin.Context) { + c.Set("auth_method", service.AuditAuthMethodJWT) + c.Set(string(middleware.ContextKeyUserRole), service.RoleAdmin) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9}) + c.Next() + }) + RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Setting: adminhandler.NewSettingHandler(settings, nil, nil, nil, nil, nil, nil)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + req := httptest.NewRequest("POST", "/api/v1/admin/settings/admin-api-keys", strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + require.Equal(t, tc.status, w.Code, w.Body.String()) + if tc.status == 400 { + require.Nil(t, keys.item) + } else { + require.True(t, keys.item.Policy.FullAccess) + require.False(t, keys.item.ConfirmFullAccess) + require.NotContains(t, w.Body.String(), "confirm_full_access") + } + } +} diff --git a/backend/internal/server/routes/custom_admin_key_statistics_test.go b/backend/internal/server/routes/custom_admin_key_statistics_test.go new file mode 100644 index 0000000000..057631296b --- /dev/null +++ b/backend/internal/server/routes/custom_admin_key_statistics_test.go @@ -0,0 +1,200 @@ +//go:build unit + +package routes + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler" + adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/imroc/req/v3" + "github.com/stretchr/testify/require" +) + +type scopedRouteStatisticsAccounts struct{ scopedRouteAccounts } + +func (s *scopedRouteStatisticsAccounts) GetAccount(ctx context.Context, id int64) (*service.Account, error) { + a, err := s.scopedRouteAccounts.GetAccount(ctx, id) + a.Credentials["access_token"] = "PRIVATE_TOKEN" + a.Credentials["chatgpt_account_id"] = "PRIVATE_ACCOUNT" + a.Credentials["plan_type"] = "plus" + return a, err +} +func (*scopedRouteStatisticsAccounts) GetGroup(_ context.Context, id int64) (*service.Group, error) { + return &service.Group{ID: id, Name: "组", Platform: "openai", Status: service.StatusActive}, nil +} +func (*scopedRouteStatisticsAccounts) ScopedAdminListGroupModels(context.Context, pagination.PaginationParams, bool, string, string, string) ([]service.Group, int64, error) { + return []service.Group{{ID: 1, Name: "组", Platform: "openai", Status: service.StatusActive}}, 1, nil +} + +type scopedRouteStatisticsRepo struct { + service.AccountRepository + admin *scopedRouteStatisticsAccounts +} + +func (s *scopedRouteStatisticsRepo) GetByID(ctx context.Context, id int64) (*service.Account, error) { + return s.admin.GetAccount(ctx, id) +} +func (s *scopedRouteStatisticsRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) { + out := []*service.Account{} + for _, id := range ids { + a, err := s.GetByID(ctx, id) + if err != nil { + return nil, err + } + out = append(out, a) + } + return out, nil +} +func (*scopedRouteStatisticsRepo) UpdateExtra(context.Context, int64, map[string]any) error { + return nil +} +func (*scopedRouteStatisticsRepo) ListSchedulableCapacityByGroupIDs(context.Context, []int64) ([]service.GroupAccountCapacityRow, error) { + return nil, nil +} + +type scopedRouteStatisticsLogs struct { + service.UsageLogRepository + reads atomic.Int64 +} + +func (s *scopedRouteStatisticsLogs) GetAccountTodayStats(context.Context, int64) (*usagestats.AccountStats, error) { + s.reads.Add(1) + return &usagestats.AccountStats{Requests: 7, Cost: 12}, nil +} +func (s *scopedRouteStatisticsLogs) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) { + s.reads.Add(1) + return &usagestats.AccountStats{Requests: 7, Cost: 12}, nil +} +func (s *scopedRouteStatisticsLogs) GetAccountUsageStats(context.Context, int64, time.Time, time.Time) (*usagestats.AccountUsageStatsResponse, error) { + s.reads.Add(1) + return &usagestats.AccountUsageStatsResponse{}, nil +} + +type scopedRouteCapacityGroups struct{ service.GroupRepository } + +func (*scopedRouteCapacityGroups) ListScopedAdminCapacityGroupIDs(context.Context) ([]int64, error) { + return []int64{1}, nil +} + +type scopedRouteReferrals struct{ queries, sends atomic.Int64 } + +func (s *scopedRouteReferrals) QueryEligibility(context.Context, service.OpenAIReferralCall) (*service.OpenAIReferralEligibility, error) { + s.queries.Add(1) + count := 2 + confirm := true + return &service.OpenAIReferralEligibility{ShouldShow: true, RemainingSendCapacity: &count, RequiresExplicitConfirmation: &confirm}, nil +} +func (s *scopedRouteReferrals) SendInvite(context.Context, service.OpenAIReferralCall, string) error { + s.sends.Add(1) + return nil +} + +func TestScopedAdminRegisteredStatisticsAndOpenAIRoutes(t *testing.T) { + gin.SetMode(gin.TestMode) + cases := []struct { + permission, method, path, body string + want int + }{ + {"accounts.stats.read", "GET", "/accounts/1/today-stats", "", 200}, + {"accounts.stats.read", "GET", "/accounts/1/stats", "", 200}, + {"accounts.stats.read", "POST", "/accounts/today-stats/batch", `{"account_ids":[1,1]}`, 200}, + {"accounts.usage.read", "GET", "/accounts/1/usage", "", 200}, + {"accounts.usage.read", "POST", "/accounts/usage/batch", `{"account_ids":[1,1]}`, 200}, + {"openai.quota.read", "GET", "/openai/accounts/1/quota", "", 200}, + {"openai.quota.read", "POST", "/openai/accounts/1/quota/refresh", "", 200}, + {"openai.quota.reset", "POST", "/openai/accounts/1/reset-quota", "", 200}, + {"openai.referrals.read", "POST", "/openai/accounts/1/referrals/refresh", "", 200}, + {"openai.referrals.invite", "POST", "/openai/accounts/1/referrals/invite", `{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`, 200}, + {"groups.list.read", "GET", "/groups", "", 200}, + {"groups.capacity.read", "GET", "/groups/capacity-summary", "", 200}, + {"openai.tokens.refresh", "POST", "/openai/refresh-token", `{}`, 400}, + } + for _, tc := range cases { + for _, allowed := range []bool{false, true} { + t.Run(tc.permission+tc.path+map[bool]string{false: "/默认拒绝", true: "/显式授权"}[allowed], func(t *testing.T) { + policy := adminaccess.Policy{Rules: []adminaccess.Rule{{GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}} + if allowed { + if tc.permission == "openai.tokens.refresh" { + policy.GlobalPermissions = []string{tc.permission} + } else { + policy.Rules[0].Permissions = []string{tc.permission} + } + } + settings := service.NewSettingService(nil, nil) + settings.SetScopedAdminKeyRepository(&scopedRouteKeys{}) + key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "统计路由", Enabled: true, Policy: policy}, 9) + require.NoError(t, err) + users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil) + auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil) + admin := &scopedRouteStatisticsAccounts{scopedRouteAccounts: scopedRouteAccounts{t: t}} + repo := &scopedRouteStatisticsRepo{admin: admin} + logs := &scopedRouteStatisticsLogs{} + referrals := &scopedRouteReferrals{} + var calls atomic.Int64 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls.Add(1) + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/consume") { + _, _ = w.Write([]byte(`{"code":"success","windows_reset":1}`)) + } else if strings.HasSuffix(r.URL.Path, "/credits") { + _, _ = w.Write([]byte(`{"available_count":0,"credits":[]}`)) + } else { + _, _ = w.Write([]byte(`{"email":"PRIVATE_EMAIL","account_id":"PRIVATE_ACCOUNT","rate_limit":{"allowed":true,"primary_window":{"used_percent":25}},"rate_limit_reset_credits":{"available_count":0},"credits":{"has_credits":true,"balance":"50"}}`)) + } + })) + defer srv.Close() + target, _ := url.Parse(srv.URL) + factory := func(string) (*req.Client, error) { + return req.C().WrapRoundTripFunc(func(rt req.RoundTripper) req.RoundTripFunc { + return func(r *req.Request) (*req.Response, error) { + r.URL.Scheme = target.Scheme + r.URL.Host = target.Host + return rt.RoundTrip(r) + } + }), nil + } + quota := service.NewOpenAIQuotaService(repo, nil, service.NewOpenAITokenProvider(repo, nil, nil), factory, referrals) + usage := service.NewAccountUsageService(repo, logs, nil, nil, nil, nil, nil, quota, service.NewUsageCache(), nil, nil) + accounts := adminhandler.NewAccountHandler(admin, nil, nil, nil, nil, nil, nil, usage, nil, nil, nil, nil, nil, nil) + openai := adminhandler.NewOpenAIOAuthHandler(nil, admin, quota, nil) + groups := adminhandler.NewGroupHandler(admin, nil, service.NewGroupCapacityService(repo, &scopedRouteCapacityGroups{}, nil, nil, nil)) + router := gin.New() + RegisterAdminRoutes(router.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: accounts, OpenAIOAuth: openai, Group: groups}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil) + request := httptest.NewRequest(tc.method, "/api/v1/admin"+tc.path, strings.NewReader(tc.body)) + request.Header.Set("x-api-key", key) + request.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + want := 403 + if allowed { + want = tc.want + } + require.Equal(t, want, recorder.Code, recorder.Body.String()) + require.NotContains(t, recorder.Body.String(), "PRIVATE_") + if !allowed { + require.Zero(t, calls.Load()) + require.Zero(t, logs.reads.Load()) + require.Zero(t, referrals.queries.Load()) + require.Zero(t, referrals.sends.Load()) + } + if tc.permission != "openai.referrals.invite" { + require.Zero(t, referrals.sends.Load()) + } + }) + } + } +} diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 3f09ebf405..3c1036921d 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -30,8 +30,9 @@ func RegisterGatewayRoutes( compositeResolver *service.CompositeRouteResolver, cfg *config.Config, ) { - bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize) - textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize) + bodyMemoryBudget := pkghttputil.NewBodyMemoryBudget(cfg.Gateway.RequestBodyMemoryBudgetBytes) + bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize, bodyMemoryBudget) + textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize, bodyMemoryBudget) clientRequestID := middleware.ClientRequestID() opsErrorLogger := handler.OpsErrorLoggerMiddleware(opsService) endpointNorm := handler.InboundEndpointMiddleware() @@ -563,6 +564,9 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if middleware.RejectRequestBodyReadError(c, err) { + return + } status := http.StatusBadRequest message := "Failed to read request body" var maxErr *http.MaxBytesError diff --git a/backend/internal/server/routes/mcp.go b/backend/internal/server/routes/mcp.go new file mode 100644 index 0000000000..535b9eec1c --- /dev/null +++ b/backend/internal/server/routes/mcp.go @@ -0,0 +1,56 @@ +package routes + +import ( + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/managementmcp" + ratelimit "github.com/Wei-Shaw/sub2api/internal/middleware" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "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, redisClient *redis.Client, +) { + inner := gin.New() + inner.Use(gin.Recovery()) + api := inner.Group("/api/v1") + 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, allowedOrigins) + 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)) + } +} + +// RegisterMCPOAuthRoutes exposes OAuth discovery and public-client protocol +// endpoints. Browser consent and grant management live in the JWT user router. +func RegisterMCPOAuthRoutes(r *gin.Engine, v1 *gin.RouterGroup, h *handler.Handlers, redisClient *redis.Client) { + r.GET("/.well-known/oauth-protected-resource/api/v1/mcp", h.MCPOAuth.ResourceMetadata) + r.GET("/.well-known/oauth-protected-resource", h.MCPOAuth.ResourceMetadata) + r.GET("/.well-known/oauth-authorization-server", h.MCPOAuth.AuthorizationMetadata) + limit := ratelimit.NewRateLimiter(redisClient) + oauth := v1.Group("/mcp/oauth") + 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_sdk_test.go b/backend/internal/server/routes/mcp_oauth_sdk_test.go new file mode 100644 index 0000000000..6649cdc089 --- /dev/null +++ b/backend/internal/server/routes/mcp_oauth_sdk_test.go @@ -0,0 +1,120 @@ +//go:build mcp_go_client_oauth + +package routes + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/url" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/modelcontextprotocol/go-sdk/auth" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/modelcontextprotocol/go-sdk/oauthex" + "github.com/stretchr/testify/require" +) + +// The SDK drives discovery, dynamic registration, PKCE generation, code +// exchange, transport authentication, and refresh. Only the browser UI is +// simulated through the same preview/consent REST API used by the SPA. +func TestMCPOAuthOfficialGoSDKInteroperability(t *testing.T) { + f := newMCPOAuthHTTPFixture(t, service.RoleUser) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var browserApprovals atomic.Int32 + oauth, err := auth.NewAuthorizationCodeHandler(&auth.AuthorizationCodeHandlerConfig{ + DynamicClientRegistrationConfig: &auth.DynamicClientRegistrationConfig{ + Metadata: &oauthex.ClientRegistrationMetadata{ + ClientName: "Official Go SDK", RedirectURIs: []string{"http://127.0.0.1:37777/callback"}, + TokenEndpointAuthMethod: "none", GrantTypes: []string{"authorization_code", "refresh_token"}, ResponseTypes: []string{"code"}, + }, + }, + AuthorizationCodeFetcher: func(_ context.Context, args *auth.AuthorizationArgs) (*auth.AuthorizationResult, error) { + authorizationURL, err := url.Parse(args.URL) + if err != nil { + return nil, err + } + if authorizationURL.Scheme+"://"+authorizationURL.Host+authorizationURL.Path != f.server.URL+"/oauth/mcp/authorize" { + return nil, fmt.Errorf("unexpected authorization endpoint") + } + q := authorizationURL.Query() + if q.Get("resource") != f.resource || q.Get("code_challenge_method") != "S256" || q.Get("code_challenge") == "" { + return nil, fmt.Errorf("SDK authorization did not bind resource and S256 PKCE") + } + preview := f.request(t, http.MethodGet, "/api/v1/user/mcp/authorize?"+q.Encode(), "browser-session", "", nil, false) + if preview.status != http.StatusOK { + return nil, fmt.Errorf("authorization preview returned %d: %s", preview.status, preview.body) + } + input := service.MCPOAuthConsentInput{Approved: true, Scope: service.MCPScopeUser, + Authorization: service.MCPOAuthAuthorizeInput{ + ResponseType: q.Get("response_type"), ClientID: q.Get("client_id"), RedirectURI: q.Get("redirect_uri"), + Scope: q.Get("scope"), State: q.Get("state"), Resource: q.Get("resource"), + CodeChallenge: q.Get("code_challenge"), CodeChallengeMethod: q.Get("code_challenge_method"), + }, + } + decided := f.json(t, http.MethodPost, "/api/v1/user/mcp/authorize", "browser-session", input) + if decided.status != http.StatusOK { + return nil, fmt.Errorf("authorization consent returned %d: %s", decided.status, decided.body) + } + var result struct { + Data struct { + RedirectURL string `json:"redirect_url"` + } `json:"data"` + } + if err := json.Unmarshal(decided.body, &result); err != nil { + return nil, err + } + redirect, err := url.Parse(result.Data.RedirectURL) + if err != nil { + return nil, err + } + browserApprovals.Add(1) + return &auth.AuthorizationResult{Code: redirect.Query().Get("code"), State: redirect.Query().Get("state")}, nil + }, + }) + require.NoError(t, err) + client := mcp.NewClient(&mcp.Implementation{Name: "oauth-interop-test", Version: "1.0"}, nil) + session, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: f.resource, HTTPClient: f.server.Client(), OAuthHandler: oauth}, nil) + require.NoError(t, err) + t.Cleanup(func() { _ = session.Close() }) + require.Equal(t, int32(1), browserApprovals.Load()) + listed, err := session.ListTools(ctx, nil) + require.NoError(t, err) + names := make([]string, 0, len(listed.Tools)) + for _, tool := range listed.Tools { + names = append(names, tool.Name) + } + require.Contains(t, names, "user_get_api_key") + require.NotContains(t, names, "user_create_api_key") + require.NotContains(t, names, "admin_get_dashboard") + called, err := session.CallTool(ctx, &mcp.CallToolParams{Name: "user_get_api_key", Arguments: map[string]any{"id": 9}}) + require.NoError(t, err) + require.False(t, called.IsError) + encoded, err := json.Marshal(called) + require.NoError(t, err) + require.Contains(t, string(encoded), "owner-key") + require.NotContains(t, string(encoded), "must-not-leak") + source, err := oauth.TokenSource(ctx) + require.NoError(t, err) + initial, err := source.Token() + require.NoError(t, err) + oldAccess, oldRefresh := initial.AccessToken, initial.RefreshToken + require.NotEmpty(t, oldRefresh) + // oauth2 caches the returned token pointer. Expire that cache entry to drive + // the SDK's real refresh request without sleeping for the access lifetime. + initial.Expiry = time.Now().Add(-time.Minute) + _, err = session.ListTools(ctx, nil) + require.NoError(t, err) + rotated, err := source.Token() + require.NoError(t, err) + require.NotEqual(t, oldAccess, rotated.AccessToken) + require.NotEqual(t, oldRefresh, rotated.RefreshToken) + require.Equal(t, int32(1), browserApprovals.Load(), "refresh must not require another browser authorization") + _, err = f.oauth.Authenticate(ctx, oldAccess) + require.NoError(t, err, "ordinary refresh preserves in-flight access tokens") +} diff --git a/backend/internal/server/routes/mcp_oauth_test.go b/backend/internal/server/routes/mcp_oauth_test.go new file mode 100644 index 0000000000..f677e19c75 --- /dev/null +++ b/backend/internal/server/routes/mcp_oauth_test.go @@ -0,0 +1,500 @@ +package routes + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +// This repository exercises real OAuth services and HTTP handlers without a +// database. SQL locking/rollback behavior is covered by repository unit tests. +type mcpOAuthRouteRepo struct { + mu sync.Mutex + grants map[string]*service.MCPOAuthGrant + codes map[string]*service.MCPOAuthCode + credentials map[string]*service.MCPOAuthCredential +} + +func (r *mcpOAuthRouteRepo) ClientIDKey(context.Context) ([]byte, error) { + return []byte("route-test-mcp-client-id-key-000"), nil +} + +func (r *mcpOAuthRouteRepo) CreateAuthorization(_ context.Context, grant *service.MCPOAuthGrant, code *service.MCPOAuthCode, limit int) error { + r.mu.Lock() + defer r.mu.Unlock() + count := 0 + for _, item := range r.grants { + if item.UserID == grant.UserID && item.RevokedAt == nil && item.ExpiresAt.After(grant.CreatedAt) { + count++ + } + } + if count >= limit { + return service.ErrMCPOAuthGrantLimit + } + r.grants[grant.ID], r.codes[code.Hash] = grant, code + return nil +} + +func (r *mcpOAuthRouteRepo) GetCode(_ context.Context, hash string) (*service.MCPOAuthCode, error) { + r.mu.Lock() + defer r.mu.Unlock() + if item := r.codes[hash]; item != nil { + copy := *item + return ©, nil + } + return nil, service.ErrMCPOAuthNotFound +} + +func (r *mcpOAuthRouteRepo) GetCredential(_ context.Context, hash string) (*service.MCPOAuthCredential, error) { + r.mu.Lock() + defer r.mu.Unlock() + if item := r.credentials[hash]; item != nil { + copy := *item + return ©, nil + } + return nil, service.ErrMCPOAuthNotFound +} + +func (r *mcpOAuthRouteRepo) GetGrant(_ context.Context, id string) (*service.MCPOAuthGrant, error) { + r.mu.Lock() + defer r.mu.Unlock() + if item := r.grants[id]; item != nil { + copy := *item + return ©, nil + } + return nil, service.ErrMCPOAuthNotFound +} + +func (r *mcpOAuthRouteRepo) consume(hash, id string, now time.Time, access, refresh *service.MCPOAuthCredential, rotating bool) error { + r.mu.Lock() + defer r.mu.Unlock() + grant := r.grants[id] + if grant == nil || grant.RevokedAt != nil || !now.Before(grant.ExpiresAt) { + return service.ErrMCPOAuthNotFound + } + var expiresAt time.Time + var usedAt **time.Time + if rotating { + item := r.credentials[hash] + if item == nil || item.GrantID != id || item.Kind != "refresh" { + return service.ErrMCPOAuthNotFound + } + expiresAt, usedAt = item.ExpiresAt, &item.UsedAt + } else { + item := r.codes[hash] + if item == nil || item.GrantID != id { + return service.ErrMCPOAuthNotFound + } + expiresAt, usedAt = item.ExpiresAt, &item.ConsumedAt + } + if *usedAt != nil { + grant.RevokedAt = &now + return service.ErrMCPOAuthNotFound + } + if !now.Before(expiresAt) { + return service.ErrMCPOAuthNotFound + } + *usedAt = &now + r.credentials[access.Hash] = access + if refresh != nil { + r.credentials[refresh.Hash] = refresh + } + return nil +} + +func (r *mcpOAuthRouteRepo) ExchangeCode(_ context.Context, hash, id string, now time.Time, access, refresh *service.MCPOAuthCredential) error { + return r.consume(hash, id, now, access, refresh, false) +} + +func (r *mcpOAuthRouteRepo) RotateRefresh(_ context.Context, hash, id string, now time.Time, access, refresh *service.MCPOAuthCredential) error { + return r.consume(hash, id, now, access, refresh, true) +} + +func (r *mcpOAuthRouteRepo) TouchGrant(_ context.Context, id string, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + item := r.grants[id] + if item == nil || item.RevokedAt != nil || !now.Before(item.ExpiresAt) { + return service.ErrMCPOAuthNotFound + } + item.LastUsedAt = &now + return nil +} + +func (r *mcpOAuthRouteRepo) ListGrants(_ context.Context, userID int64) ([]*service.MCPOAuthGrant, error) { + r.mu.Lock() + defer r.mu.Unlock() + items := []*service.MCPOAuthGrant{} + for _, item := range r.grants { + if item.UserID == userID { + copy := *item + items = append(items, ©) + } + } + return items, nil +} + +func (r *mcpOAuthRouteRepo) RevokeGrant(_ context.Context, userID int64, id string, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + item := r.grants[id] + if item == nil || item.UserID != userID { + return service.ErrMCPOAuthNotFound + } + if item.RevokedAt == nil { + item.RevokedAt = &now + } + 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 +} + +func (r *mcpOAuthRouteUsers) GetByID(_ context.Context, id int64) (*service.User, error) { + if r.user == nil || r.user.ID != id { + return nil, service.ErrUserNotFound + } + copy := *r.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{ + grants: map[string]*service.MCPOAuthGrant{}, codes: map[string]*service.MCPOAuthCode{}, + credentials: map[string]*service.MCPOAuthCredential{}, + } + users := &mcpOAuthRouteUsers{user: &service.User{ID: 7, Role: role, Status: service.StatusActive, PasswordHash: "test-password", Email: "mcp@example.com"}} + return service.NewMCPOAuthService(repo, users), repo, users +} + +const mcpOAuthRouteVerifier = "a-valid-43-character-pkce-verifier-for-testing-only" + +func mcpOAuthRouteAuthorization(clientID, resource string) service.MCPOAuthAuthorizeInput { + sum := sha256.Sum256([]byte(mcpOAuthRouteVerifier)) + return service.MCPOAuthAuthorizeInput{ + ResponseType: "code", ClientID: clientID, RedirectURI: "http://127.0.0.1:37777/callback", + Scope: "mcp", State: "opaque-state-with&symbols", CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]), + CodeChallengeMethod: "S256", Resource: resource, + } +} + +func issueMCPRouteOAuthToken(t *testing.T, oauth *service.MCPOAuthService, resource, scope string, readOnly bool) string { + t.Helper() + client, err := oauth.Register(context.Background(), service.MCPOAuthRegisterInput{RedirectURIs: []string{"http://127.0.0.1:37777/callback"}}) + require.NoError(t, err) + authorization := mcpOAuthRouteAuthorization(client.ClientID, resource) + redirect, err := oauth.Decide(context.Background(), 7, service.MCPOAuthConsentInput{Authorization: authorization, Approved: true, Scope: scope, ReadOnly: &readOnly}, resource) + require.NoError(t, err) + u, err := url.Parse(redirect) + require.NoError(t, err) + tokens, err := oauth.Token(context.Background(), service.MCPOAuthTokenInput{GrantType: "authorization_code", ClientID: client.ClientID, Code: u.Query().Get("code"), RedirectURI: authorization.RedirectURI, CodeVerifier: mcpOAuthRouteVerifier, Resource: resource}, resource) + require.NoError(t, err) + 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 + resource string + cfg *config.Config + settings *service.SettingService + handlers *handler.Handlers + oauth *service.MCPOAuthService + repo *mcpOAuthRouteRepo + users *mcpOAuthRouteUsers +} + +func newMCPOAuthHTTPFixture(t *testing.T, role string) *mcpOAuthHTTPFixture { + t.Helper() + gin.SetMode(gin.TestMode) + router := gin.New() + server := httptest.NewUnstartedServer(router) + base := "http://" + server.Listener.Addr().String() + cfg := &config.Config{MCP: config.MCPConfig{PublicURL: base + "/api/v1/mcp"}} + cfg.Server.FrontendURL = base + 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, 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()}) + t.Cleanup(func() { _ = rdb.Close() }) + browserAuth := middleware.JWTAuthMiddleware(func(c *gin.Context) { + if c.GetHeader("Authorization") != "Bearer browser-session" { + middleware.AbortWithError(c, http.StatusUnauthorized, "UNAUTHORIZED", "Browser login required") + return + } + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 7}) + c.Set(string(middleware.ContextKeyUserRole), role) + c.Set(middleware.ContextKeySessionID, "browser-session") + c.Next() + }) + 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, 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} +} + +type mcpOAuthHTTPResult struct { + status int + header http.Header + body []byte +} + +func (f *mcpOAuthHTTPFixture) request(t *testing.T, method, path, auth, contentType string, body []byte, spoofHost bool) mcpOAuthHTTPResult { + t.Helper() + req, err := http.NewRequest(method, f.server.URL+path, bytes.NewReader(body)) + require.NoError(t, err) + if auth != "" { + req.Header.Set("Authorization", "Bearer "+auth) + } + if contentType != "" { + req.Header.Set("Content-Type", contentType) + } + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("MCP-Protocol-Version", "2025-06-18") + if spoofHost { + req.Host = "attacker.example" + req.Header.Set("X-Forwarded-Host", "attacker.example") + req.Header.Set("X-Forwarded-Proto", "https") + } + res, err := f.server.Client().Do(req) + require.NoError(t, err) + defer func() { _ = res.Body.Close() }() + raw, err := io.ReadAll(res.Body) + require.NoError(t, err) + return mcpOAuthHTTPResult{status: res.StatusCode, header: res.Header.Clone(), body: raw} +} + +func (f *mcpOAuthHTTPFixture) json(t *testing.T, method, path, auth string, body any) mcpOAuthHTTPResult { + t.Helper() + raw, err := json.Marshal(body) + require.NoError(t, err) + return f.request(t, method, path, auth, "application/json", raw, false) +} + +func (f *mcpOAuthHTTPFixture) form(t *testing.T, path string, body url.Values) mcpOAuthHTTPResult { + t.Helper() + return f.request(t, http.MethodPost, path, "", "application/x-www-form-urlencoded", []byte(body.Encode()), false) +} + +func (f *mcpOAuthHTTPFixture) rpc(t *testing.T, access, method string, params any) mcpOAuthHTTPResult { + t.Helper() + return f.json(t, http.MethodPost, "/api/v1/mcp", access, map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) +} + +func (f *mcpOAuthHTTPFixture) authorize(t *testing.T, scope string, readOnly bool) (service.MCPOAuthClient, service.MCPOAuthTokenResponse) { + t.Helper() + registration := f.json(t, http.MethodPost, "/api/v1/mcp/oauth/register", "", map[string]any{ + "client_name": "Integration client", "redirect_uris": []string{"http://127.0.0.1:37777/callback"}, + "token_endpoint_auth_method": "none", "grant_types": []string{"authorization_code", "refresh_token"}, "response_types": []string{"code"}, + }) + require.Equal(t, http.StatusCreated, registration.status, string(registration.body)) + var client service.MCPOAuthClient + require.NoError(t, json.Unmarshal(registration.body, &client)) + authorization := mcpOAuthRouteAuthorization(client.ClientID, f.resource) + query := url.Values{"response_type": {authorization.ResponseType}, "client_id": {authorization.ClientID}, "redirect_uri": {authorization.RedirectURI}, "scope": {authorization.Scope}, "state": {authorization.State}, "code_challenge": {authorization.CodeChallenge}, "code_challenge_method": {authorization.CodeChallengeMethod}, "resource": {authorization.Resource}} + before, err := f.oauth.ListGrants(context.Background(), 7) + require.NoError(t, err) + preview := f.request(t, http.MethodGet, "/api/v1/user/mcp/authorize?"+query.Encode(), "browser-session", "", nil, false) + require.Equal(t, http.StatusOK, preview.status, string(preview.body)) + require.Contains(t, string(preview.body), "Integration client") + afterPreview, err := f.oauth.ListGrants(context.Background(), 7) + require.NoError(t, err) + require.Len(t, afterPreview, len(before), "preview must not create an authorization") + decided := f.json(t, http.MethodPost, "/api/v1/user/mcp/authorize", "browser-session", service.MCPOAuthConsentInput{Authorization: authorization, Approved: true, Scope: scope, ReadOnly: &readOnly}) + require.Equal(t, http.StatusOK, decided.status, string(decided.body)) + var consent struct { + Data struct { + RedirectURL string `json:"redirect_url"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(decided.body, &consent)) + redirect, err := url.Parse(consent.Data.RedirectURL) + require.NoError(t, err) + require.Equal(t, authorization.State, redirect.Query().Get("state")) + require.Equal(t, "127.0.0.1:37777", redirect.Host) + after, err := f.oauth.ListGrants(context.Background(), 7) + require.NoError(t, err) + require.Len(t, after, len(before)+1) + token := f.form(t, "/api/v1/mcp/oauth/token", url.Values{"grant_type": {"authorization_code"}, "client_id": {client.ClientID}, "code": {redirect.Query().Get("code")}, "redirect_uri": {authorization.RedirectURI}, "code_verifier": {mcpOAuthRouteVerifier}, "resource": {f.resource}}) + require.Equal(t, http.StatusOK, token.status, string(token.body)) + require.Equal(t, "no-store", token.header.Get("Cache-Control")) + var tokens service.MCPOAuthTokenResponse + require.NoError(t, json.Unmarshal(token.body, &tokens)) + require.NotEmpty(t, tokens.AccessToken) + require.NotEmpty(t, tokens.RefreshToken) + return client, tokens +} + +func TestMCPOAuthHTTPFlowDiscoveryConsentRefreshAndRevocation(t *testing.T) { + f := newMCPOAuthHTTPFixture(t, service.RoleUser) + for _, path := range []string{"/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/api/v1/mcp"} { + metadata := f.request(t, http.MethodGet, path, "", "", nil, true) + require.Equal(t, http.StatusOK, metadata.status, string(metadata.body)) + var value struct { + Resource string `json:"resource"` + AuthorizationServers []string `json:"authorization_servers"` + } + require.NoError(t, json.Unmarshal(metadata.body, &value)) + require.Equal(t, f.resource, value.Resource) + require.Equal(t, []string{f.server.URL}, value.AuthorizationServers) + require.NotContains(t, string(metadata.body), "attacker.example") + } + authorizationMetadata := f.request(t, http.MethodGet, "/.well-known/oauth-authorization-server", "", "", nil, true) + require.Equal(t, http.StatusOK, authorizationMetadata.status, string(authorizationMetadata.body)) + var endpoints map[string]any + require.NoError(t, json.Unmarshal(authorizationMetadata.body, &endpoints)) + require.Equal(t, f.server.URL, endpoints["issuer"]) + require.Equal(t, f.server.URL+"/oauth/mcp/authorize", endpoints["authorization_endpoint"]) + require.Equal(t, f.server.URL+"/api/v1/mcp/oauth/token", endpoints["token_endpoint"]) + unauthorized := f.request(t, http.MethodPost, "/api/v1/mcp", "", "application/json", []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`), true) + require.Equal(t, http.StatusUnauthorized, unauthorized.status) + require.Contains(t, unauthorized.header.Get("WWW-Authenticate"), f.server.URL+"/.well-known/oauth-protected-resource/api/v1/mcp") + require.NotContains(t, unauthorized.header.Get("WWW-Authenticate"), "attacker.example") + client, tokens := f.authorize(t, service.MCPScopeUser, true) + initialized := f.rpc(t, tokens.AccessToken, "initialize", map[string]any{ + "protocolVersion": "2025-06-18", "capabilities": map[string]any{}, + "clientInfo": map[string]any{"name": "oauth-integration", "version": "1.0"}, + }) + require.Equal(t, http.StatusOK, initialized.status, string(initialized.body)) + require.Contains(t, string(initialized.body), "protocolVersion") + tools := f.rpc(t, tokens.AccessToken, "tools/list", map[string]any{}) + require.Equal(t, http.StatusOK, tools.status, string(tools.body)) + require.Contains(t, string(tools.body), "user_get_api_key") + require.NotContains(t, string(tools.body), "user_create_api_key") + 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)) + 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}}) + require.Equal(t, http.StatusOK, refresh.status, string(refresh.body)) + var rotated service.MCPOAuthTokenResponse + require.NoError(t, json.Unmarshal(refresh.body, &rotated)) + require.NotEqual(t, tokens.AccessToken, rotated.AccessToken) + require.Equal(t, http.StatusOK, f.rpc(t, rotated.AccessToken, "tools/list", map[string]any{}).status) + revoked := f.form(t, "/api/v1/mcp/oauth/revoke", url.Values{"client_id": {client.ClientID}, "token": {rotated.RefreshToken}}) + require.Equal(t, http.StatusOK, revoked.status, string(revoked.body)) + require.Equal(t, http.StatusUnauthorized, f.rpc(t, rotated.AccessToken, "tools/list", map[string]any{}).status) + require.Equal(t, http.StatusUnauthorized, f.rpc(t, tokens.AccessToken, "tools/list", map[string]any{}).status) +} + +func TestMCPOAuthHTTPPermissionAndCredentialBoundaries(t *testing.T) { + f := newMCPOAuthHTTPFixture(t, service.RoleAdmin) + _, user := f.authorize(t, service.MCPScopeUser, true) + userTools := f.rpc(t, user.AccessToken, "tools/list", map[string]any{}) + require.NotContains(t, string(userTools.body), "admin_get_dashboard") + _, admin := f.authorize(t, service.MCPScopeAdmin, false) + adminTools := f.rpc(t, admin.AccessToken, "tools/list", map[string]any{}) + require.Equal(t, http.StatusOK, adminTools.status, string(adminTools.body)) + require.Contains(t, string(adminTools.body), "admin_get_dashboard") + require.Contains(t, string(adminTools.body), "user_create_api_key") + for _, tool := range []string{"admin_get_dashboard", "user_delete_api_key"} { + blocked := f.rpc(t, user.AccessToken, "tools/call", map[string]any{"name": tool, "arguments": map[string]any{"id": 9}}) + var result mcpRouteToolResult + require.NoError(t, json.Unmarshal(blocked.body, &result)) + require.NotEmpty(t, result.Error, string(blocked.body)) + } + for _, credential := range []string{"browser-session", "sk-inference-key", "mcp_legacy_personal_token", admin.RefreshToken} { + require.Equal(t, http.StatusUnauthorized, f.rpc(t, credential, "tools/list", map[string]any{}).status, credential) + } + // Use the real production JWT middleware to prove MCP access credentials + // cannot become browser REST credentials, even for an administrator owner. + rest := gin.New() + auth := service.NewAuthService(nil, nil, nil, nil, f.cfg, f.settings, nil, nil, nil, nil, nil, nil, nil) + jwtAuth := middleware.NewJWTAuthMiddleware(auth, nil, f.settings, nil) + RegisterUserRoutes(rest.Group("/api/v1"), f.handlers, jwtAuth, middleware.AuditLogMiddleware(mcpRouteNext), f.settings, nil) + req := httptest.NewRequest(http.MethodGet, "/api/v1/user/mcp/grants", nil) + req.Header.Set("Authorization", "Bearer "+admin.AccessToken) + w := httptest.NewRecorder() + rest.ServeHTTP(w, req) + require.Equal(t, http.StatusUnauthorized, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "INVALID_TOKEN") +} + +func TestMCPOAuthHTTPConsentRequiresBrowserAndExplicitApproval(t *testing.T) { + f := newMCPOAuthHTTPFixture(t, service.RoleUser) + client, err := f.oauth.Register(context.Background(), service.MCPOAuthRegisterInput{RedirectURIs: []string{"http://127.0.0.1:37777/callback"}}) + require.NoError(t, err) + input := service.MCPOAuthConsentInput{Authorization: mcpOAuthRouteAuthorization(client.ClientID, f.resource), Approved: true, Scope: service.MCPScopeAdmin} + unauthenticated := f.json(t, http.MethodPost, "/api/v1/user/mcp/authorize", "", input) + require.Equal(t, http.StatusUnauthorized, unauthenticated.status) + escalated := f.json(t, http.MethodPost, "/api/v1/user/mcp/authorize", "browser-session", input) + require.Equal(t, http.StatusForbidden, escalated.status, string(escalated.body)) + input.Approved = false + denied := f.json(t, http.MethodPost, "/api/v1/user/mcp/authorize", "browser-session", input) + require.Equal(t, http.StatusOK, denied.status, string(denied.body)) + require.Contains(t, string(denied.body), "access_denied") + grants, err := f.oauth.ListGrants(context.Background(), 7) + require.NoError(t, err) + require.Empty(t, grants) + legacy := f.request(t, http.MethodPost, "/api/v1/user/mcp-tokens", "browser-session", "application/json", []byte(`{"name":"legacy"}`), false) + require.Equal(t, http.StatusNotFound, legacy.status) +} + +func TestMCPOAuthHTTPRejectsAmbiguousTokenForms(t *testing.T) { + f := newMCPOAuthHTTPFixture(t, service.RoleUser) + for _, form := range []string{ + "grant_type=authorization_code&client_id=first&client_id=second", + "grant_type=authorization_code&resource=a&resource=b", + "grant_type=authorization_code&client_secret=not-supported", + } { + result := f.request(t, http.MethodPost, "/api/v1/mcp/oauth/token", "", "application/x-www-form-urlencoded", []byte(form), false) + require.Equal(t, http.StatusBadRequest, result.status, string(result.body)) + require.Equal(t, "no-store", result.header.Get("Cache-Control")) + require.True(t, strings.Contains(string(result.body), "invalid_request") || strings.Contains(string(result.body), "invalid_client")) + } +} diff --git a/backend/internal/server/routes/mcp_rate_limit_test.go b/backend/internal/server/routes/mcp_rate_limit_test.go new file mode 100644 index 0000000000..c75ac45342 --- /dev/null +++ b/backend/internal/server/routes/mcp_rate_limit_test.go @@ -0,0 +1,115 @@ +package routes + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/alicebob/miniredis/v2" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +func newMCPRateLimitEndpoint(t *testing.T, role string, rpm int) (*gin.Engine, string, *miniredis.Miniredis) { + t.Helper() + gin.SetMode(gin.TestMode) + mr := miniredis.RunT(t) + rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()}) + t.Cleanup(func() { _ = rdb.Close() }) + settingsJSON, err := json.Marshal(service.PanelRateLimitSettings{Enabled: true, UserRPM: rpm, HeavyRPM: 1}) + require.NoError(t, err) + cfg := &config.Config{MCP: config.MCPConfig{PublicURL: "https://mcp.example/api/v1/mcp"}} + settings := service.NewSettingService(&mcpRouteSettingsRepo{values: map[string]string{ + service.SettingKeyPanelRateLimitSettings: string(settingsJSON), + }}, cfg) + oauth, _, _ := newMCPRouteOAuthService(role) + scope := service.MCPScopeUser + if role == service.RoleAdmin { + scope = service.MCPScopeAdmin + } + token := issueMCPRouteOAuthToken(t, oauth, cfg.MCP.PublicURL, scope, true) + h := mcpRouteHandlers() + h.MCPOAuth = handler.NewMCPOAuthHandler(oauth, nil, nil, settings, cfg) + 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, rdb) + return router, token, mr +} + +func mcpRateLimitRPC(t *testing.T, endpoint http.Handler, token, method string, params any) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/api/v1/mcp", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+token) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("MCP-Protocol-Version", "2025-06-18") + w := httptest.NewRecorder() + endpoint.ServeHTTP(w, req) + return w +} + +func TestMCPToolCallsConsumeGlobalBudgetOnce(t *testing.T) { + for _, tc := range []struct { + role, tool string + args map[string]any + status int + }{ + {service.RoleUser, "user_get_api_key", map[string]any{"id": 9}, http.StatusOK}, + // The compliance response proves the request passed the admin limiter. + {service.RoleAdmin, "admin_get_dashboard", map[string]any{}, http.StatusLocked}, + } { + t.Run(tc.role, func(t *testing.T) { + endpoint, token, mr := newMCPRateLimitEndpoint(t, tc.role, 2) + params := map[string]any{"name": tc.tool, "arguments": tc.args} + for i := 0; i < 2; i++ { + w := mcpRateLimitRPC(t, endpoint, token, "tools/call", params) + require.Equal(t, http.StatusOK, w.Code, 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) + require.Equal(t, "2", count) + w := mcpRateLimitRPC(t, endpoint, token, "tools/call", params) + require.Equal(t, http.StatusTooManyRequests, w.Code, w.Body.String()) + }) + } +} + +func TestMCPDiscoveryHasItsOwnBoundedBudget(t *testing.T) { + endpoint, token, mr := newMCPRateLimitEndpoint(t, service.RoleUser, 2) + for i := 0; i < 2; i++ { + w := mcpRateLimitRPC(t, endpoint, token, "tools/list", map[string]any{}) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + } + require.False(t, mr.Exists("rate_limit:panel:global:user:7"), "discovery must not spend the shared REST budget") + w := mcpRateLimitRPC(t, endpoint, token, "tools/list", map[string]any{}) + require.Equal(t, http.StatusTooManyRequests, w.Code, w.Body.String()) +} + +func TestMCPDispatchRetainsHeavyRateLimit(t *testing.T) { + endpoint, token, mr := newMCPRateLimitEndpoint(t, service.RoleUser, 10) + params := map[string]any{"name": "user_get_usage_stats", "arguments": map[string]any{ + // A malformed date reaches the real handler without needing a usage DB. + "query": map[string]any{"start_date": "2026-99-99"}, + }} + 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()) + 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) + require.Equal(t, "2", count) +} diff --git a/backend/internal/server/routes/mcp_test.go b/backend/internal/server/routes/mcp_test.go new file mode 100644 index 0000000000..e1a1e583e6 --- /dev/null +++ b/backend/internal/server/routes/mcp_test.go @@ -0,0 +1,209 @@ +package routes + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/handler" + "github.com/Wei-Shaw/sub2api/internal/managementmcp" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func mcpRouteHandlers() *handler.Handlers { + // Nil method receivers are sufficient for route registration. Individual + // behavior tests populate only the handlers whose dependencies they exercise. + return &handler.Handlers{ + Admin: &handler.AdminHandlers{}, + MCPOAuth: handler.NewMCPOAuthHandler(nil, nil, nil, nil, &config.Config{MCP: config.MCPConfig{PublicURL: "https://platform.example/api/v1/mcp"}}), + } +} + +func mcpRouteNext(c *gin.Context) { c.Next() } + +func TestMCPToolCatalogTargetsRegisteredManagementRoutes(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + v1 := router.Group("/api/v1") + h := mcpRouteHandlers() + require.NotPanics(t, func() { + RegisterUserRoutes(v1, h, middleware.JWTAuthMiddleware(mcpRouteNext), middleware.AuditLogMiddleware(mcpRouteNext), nil, nil) + RegisterAdminRoutes(v1, h, middleware.AdminAuthMiddleware(mcpRouteNext), middleware.AuditLogMiddleware(mcpRouteNext), middleware.StepUpAuthMiddleware(mcpRouteNext), nil, nil) + }) + registered := map[string]bool{} + for _, route := range router.Routes() { + registered[route.Method+" "+route.Path] = true + } + catalog := managementmcp.ToolCatalog() + require.NotEmpty(t, catalog) + for _, tool := range catalog { + require.True(t, registered[tool.Method+" "+tool.Path], "%s targets missing route %s %s", tool.Name, tool.Method, tool.Path) + } + + // Exercise the real factory as well: transport setup must not introduce + // 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, nil) + }) + for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} { + w := httptest.NewRecorder() + mcpRouter.ServeHTTP(w, httptest.NewRequest(method, "/api/v1/mcp", nil)) + require.Equal(t, http.StatusUnauthorized, w.Code, method) + } +} + +type mcpRouteTokenAuth struct{ principal *service.MCPPrincipal } + +func (a mcpRouteTokenAuth) Authenticate(context.Context, string) (*service.MCPPrincipal, error) { + copy := *a.principal + copy.Resource = "https://platform.example/api/v1/mcp" + return ©, nil +} + +func newMCPRouteTestEndpoint(h *handler.Handlers, principal *service.MCPPrincipal, settings *service.SettingService, audit middleware.AuditLogMiddleware) *gin.Engine { + inner := gin.New() + v1 := inner.Group("/api/v1") + RegisterUserRoutes(v1, h, middleware.JWTAuthMiddleware(managementmcp.DispatchAuth(false)), audit, settings, nil) + RegisterAdminRoutes(v1, h, middleware.AdminAuthMiddleware(managementmcp.DispatchAuth(true)), audit, middleware.StepUpAuthMiddleware(mcpRouteNext), settings, nil) + outer := gin.New() + outer.POST("/api/v1/mcp", managementmcp.Authenticate(mcpRouteTokenAuth{principal: principal}, nil, h.MCPOAuth.ResourceURL), gin.WrapH(managementmcp.NewHandler(inner, nil))) + return outer +} + +type mcpRouteToolPayload struct { + HTTPStatus int `json:"http_status"` + Result json.RawMessage `json:"result"` +} + +type mcpRouteToolResult struct { + Result struct { + 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{ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": map[string]any{"name": name, "arguments": args}, + }) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/api/v1/mcp", bytes.NewReader(body)) + req.Header.Set("Authorization", "Bearer test-token") + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("MCP-Protocol-Version", "2025-06-18") + w := httptest.NewRecorder() + endpoint.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + return decodeMCPRouteToolResult(t, w.Body.Bytes()) +} + +type mcpRouteAPIKeyRepo struct{ service.APIKeyRepository } + +func (r *mcpRouteAPIKeyRepo) GetByID(context.Context, int64) (*service.APIKey, error) { + return &service.APIKey{ID: 9, UserID: 7, Name: "owner-key", Key: "must-not-leak", Status: service.StatusActive}, nil +} + +func TestMCPDispatchRetainsRealAPIKeyOwnershipAndAudit(t *testing.T) { + gin.SetMode(gin.TestMode) + h := mcpRouteHandlers() + h.APIKey = handler.NewAPIKeyHandler(service.NewAPIKeyService(&mcpRouteAPIKeyRepo{}, nil, nil, nil, nil, nil, nil)) + for _, userID := range []int64{7, 8} { + principal := &service.MCPPrincipal{GrantID: "test", UserID: userID, Role: service.RoleUser, Scope: service.MCPScopeUser, ReadOnly: true} + auditCalls := 0 + audit := middleware.AuditLogMiddleware(func(c *gin.Context) { + subject, ok := middleware.GetAuthSubjectFromContext(c) + require.True(t, ok) + require.Equal(t, userID, subject.UserID) + require.Equal(t, "/api/v1/keys/:id", c.FullPath()) + require.Equal(t, managementmcp.AuthMethod, c.GetString("auth_method")) + auditCalls++ + c.Next() + }) + 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.Payload.Result), "must-not-leak") + if userID == 7 { + require.False(t, result.Result.IsError) + 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.Payload.HTTPStatus) + require.NotContains(t, string(result.Result.Payload.Result), "owner-key") + } + } +} + +type mcpRouteSettingsRepo struct { + service.SettingRepository + values map[string]string +} + +func (r *mcpRouteSettingsRepo) GetValue(_ context.Context, key string) (string, error) { + if value, ok := r.values[key]; ok { + return value, nil + } + return "", service.ErrSettingNotFound +} + +func (r *mcpRouteSettingsRepo) SetMultiple(_ context.Context, values map[string]string) error { + for key, value := range values { + r.values[key] = value + } + return nil +} + +func TestMCPDispatchRetainsBackendModeAndAdminCompliance(t *testing.T) { + gin.SetMode(gin.TestMode) + settings := service.NewSettingService(&mcpRouteSettingsRepo{values: map[string]string{}}, &config.Config{}) + // UpdateSettings also updates the global backend-mode cache. Reset it on + // cleanup so this integration test cannot affect unrelated route tests. + require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{BackendModeEnabled: true})) + t.Cleanup(func() { + require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{BackendModeEnabled: false})) + }) + h := mcpRouteHandlers() + 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.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.Payload.HTTPStatus) + require.Contains(t, string(result.Result.Payload.Result), "ADMIN_COMPLIANCE_ACK_REQUIRED") +} diff --git a/backend/internal/server/routes/user.go b/backend/internal/server/routes/user.go index 65ecaa037d..6b995c1a72 100644 --- a/backend/internal/server/routes/user.go +++ b/backend/internal/server/routes/user.go @@ -29,6 +29,13 @@ func RegisterUserRoutes( user := authenticated.Group("/user") { user.GET("/profile", h.User.GetProfile) + if h.MCPOAuth != nil { + user.GET("/mcp/config", h.MCPOAuth.ConnectionConfig) + user.GET("/mcp/grants", h.MCPOAuth.ListGrants) + user.DELETE("/mcp/grants/:id", h.MCPOAuth.RevokeGrant) + user.GET("/mcp/authorize", h.MCPOAuth.Preview) + user.POST("/mcp/authorize", h.MCPOAuth.Decide) + } user.PUT("/password", h.User.ChangePassword) user.PUT("", h.User.UpdateProfile) user.GET("/aff", h.User.GetAffiliate) diff --git a/backend/internal/service/account_quota_service_account_test.go b/backend/internal/service/account_quota_service_account_test.go index 6358f32024..a45f23c5d5 100644 --- a/backend/internal/service/account_quota_service_account_test.go +++ b/backend/internal/service/account_quota_service_account_test.go @@ -178,7 +178,7 @@ func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { settings := &settingGetValueCounter{} - notifyAccountQuota(&postUsageBillingParams{ + notifyAccountQuota(context.Background(), &postUsageBillingParams{ Cost: &CostBreakdown{TotalCost: 2}, Account: tt.account, AccountRateMultiplier: 1, @@ -193,7 +193,7 @@ func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) { // 账号已删除时计数被跳过、无递增后状态,不应回退到快照做阈值判定。 func TestNotifyAccountQuotaSkipsWhenQuotaIncrementSkipped(t *testing.T) { settings := &settingGetValueCounter{} - notifyAccountQuota(&postUsageBillingParams{ + notifyAccountQuota(context.Background(), &postUsageBillingParams{ Cost: &CostBreakdown{TotalCost: 2}, Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, AccountRateMultiplier: 1, diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 210033179a..45d3c7cb17 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -2382,6 +2382,14 @@ func (s *AccountTestService) reconcileOpenAI429State(ctx context.Context, accoun } } +// geminiDefaultTestModel 返回 Gemini 连接测试未指定模型时使用的模型;Google One 账号只能使用其保守模型集。 +func geminiDefaultTestModel(account *Account) string { + if account.IsGeminiGoogleOne() { + return geminicli.GoogleOneModels[0].ID + } + return geminicli.DefaultTestModel +} + // testGeminiAccountConnection tests a Gemini account's connection func (s *AccountTestService) testGeminiAccountConnection(c *gin.Context, account *Account, modelID string, prompt string) error { ctx := c.Request.Context() @@ -2389,7 +2397,7 @@ func (s *AccountTestService) testGeminiAccountConnection(c *gin.Context, account // Determine the model to use testModelID := modelID if testModelID == "" { - testModelID = geminicli.DefaultTestModel + testModelID = geminiDefaultTestModel(account) } // For static upstream credentials with model mapping, map the model @@ -3052,6 +3060,9 @@ func (s *AccountTestService) testOpenAIImageAPIKey(c *gin.Context, ctx context.C "n": 1, "response_format": "b64_json", } + if size := account.OpenAIImageTestSize(); size != "" { + payload["size"] = size + } payloadBytes, _ := json.Marshal(payload) req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes)) @@ -3148,7 +3159,9 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co Endpoint: openAIImagesGenerationsEndpoint, Model: strings.TrimSpace(modelID), Prompt: prompt, + Size: account.OpenAIImageTestSize(), } + parsed.ExplicitSize = parsed.Size != "" applyOpenAIImagesDefaults(parsed) upstreamModel := account.GetMappedModel(parsed.Model) diff --git a/backend/internal/service/account_test_service_gemini_test.go b/backend/internal/service/account_test_service_gemini_test.go index f38264a215..16492c4cf7 100644 --- a/backend/internal/service/account_test_service_gemini_test.go +++ b/backend/internal/service/account_test_service_gemini_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/Wei-Shaw/sub2api/internal/pkg/geminicli" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" ) @@ -57,3 +58,14 @@ func TestProcessGeminiStream_EmitsImageEvent(t *testing.T) { require.Contains(t, body, "\"image_url\":\"data:image/png;base64,QUJD\"") require.Contains(t, body, "\"mime_type\":\"image/png\"") } + +func TestGeminiDefaultTestModel(t *testing.T) { + t.Parallel() + + googleOne := &Account{Platform: PlatformGemini, Type: AccountTypeOAuth, Credentials: map[string]any{"oauth_type": "google_one"}} + require.Equal(t, geminicli.GoogleOneModels[0].ID, geminiDefaultTestModel(googleOne)) + require.Contains(t, googleOne.GetModelMapping(), geminiDefaultTestModel(googleOne)) + + apiKey := &Account{Platform: PlatformGemini, Type: AccountTypeAPIKey} + require.Equal(t, geminicli.DefaultTestModel, geminiDefaultTestModel(apiKey)) +} diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 746cb324a2..1516e0822c 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -13,6 +13,7 @@ import ( "sync" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" httppool "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient" openaipkg "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" @@ -346,6 +347,9 @@ func batchUsageErrorMessage(err error) string { } func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *Account, forceProbe bool) (*UsageInfo, error) { + if err := scopedAccountAccess(ctx, s.accountRepo, account, "accounts.usage.read", true); err != nil { + return nil, err + } if account == nil { return nil, fmt.Errorf("account is required") } @@ -512,6 +516,16 @@ func (s *AccountUsageService) GetUsageForAccount(ctx context.Context, account *A // Anthropic OAuth/SetupToken 统一走 passive 链路,其他账号复用现有主动查询逻辑。 // 单个账号失败不会中断整批请求,错误会按账号返回。 func (s *AccountUsageService) GetUsageBatch(ctx context.Context, accountIDs []int64, force bool) (map[int64]*UsageInfo, map[int64]string, error) { + if adminaccess.RestrictedFromContext(ctx) != nil { + if len(accountIDs) > 100 { + return nil, nil, fmt.Errorf("账户数量超过限制") + } + for _, id := range accountIDs { + if id <= 0 { + return nil, nil, fmt.Errorf("账户 ID 无效") + } + } + } uniqueIDs := make([]int64, 0, len(accountIDs)) seen := make(map[int64]struct{}, len(accountIDs)) for _, accountID := range accountIDs { @@ -544,6 +558,13 @@ func (s *AccountUsageService) GetUsageBatch(ctx context.Context, accountIDs []in accountsByID[account.ID] = account } + if adminaccess.RestrictedFromContext(ctx) != nil { + for _, id := range uniqueIDs { + if err := scopedAccountAccess(ctx, s.accountRepo, accountsByID[id], "accounts.usage.read", true); err != nil { + return nil, nil, err + } + } + } var mu sync.Mutex g, gctx := errgroup.WithContext(ctx) g.SetLimit(6) @@ -595,6 +616,9 @@ func (s *AccountUsageService) GetPassiveUsage(ctx context.Context, accountID int } func (s *AccountUsageService) getPassiveUsageForAccount(ctx context.Context, account *Account) (*UsageInfo, error) { + if err := scopedAccountAccess(ctx, s.accountRepo, account, "accounts.usage.read", false); err != nil { + return nil, err + } if !supportsAnthropicPassiveUsage(account) { return nil, fmt.Errorf("passive usage only supported for Anthropic OAuth/SetupToken accounts") } @@ -717,17 +741,32 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou applyExtraToUsage(usage, account.Extra, now) if (force || shouldRefreshOpenAICodexSnapshot(account, usage, now)) && s.shouldProbeOpenAICodexSnapshot(account.ID, now, force) { - if account.IsShadow() { + if adminaccess.RestrictedFromContext(ctx) != nil { + // 受限额度读取只调用额度 API,不生成 /responses 合成请求或消费重置次数。 + if s.openAIQuotaService != nil { + if quotaUsage, err := s.openAIQuotaService.QueryUsage(WithScopedAdminAccountOperation(ctx, "accounts.usage.read"), account.ID); err == nil { + updates := buildOpenAIAutoResetUsageUpdates(quotaUsage, now) + if account.IsShadow() { + updates = buildCodexSparkWindowExtraUpdates(quotaUsage, now) + } + if len(updates) > 0 { + mergeAccountExtra(account, updates) + s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates) + applyExtraToUsage(usage, account.Extra, now) + } + } + } + } else if account.IsShadow() { // Spark shadow accounts fetch usage from /wham/usage (bengalfox channel) // via the shared OpenAIQuotaService, which resolves credentials from the // parent account. The result is written to the shadow row's own codex_* // Extra keys and immediately reflected in the returned UsageInfo. if s.openAIQuotaService != nil { - if quotaUsage, err := s.openAIQuotaService.QueryUsage(ctx, account.ID); err == nil { + if quotaUsage, err := s.openAIQuotaService.QueryUsage(WithScopedAdminAccountOperation(ctx, "accounts.usage.read"), account.ID); err == nil { if updates := buildCodexSparkWindowExtraUpdates(quotaUsage, now); len(updates) > 0 { mergeAccountExtra(account, updates) - s.persistOpenAICodexProbeSnapshot(account.ID, updates) - if account.ParentAccountID != nil { + s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates) + if account.ParentAccountID != nil && adminaccess.RestrictedFromContext(ctx) == nil { notifyOpenAIAutoReset(*account.ParentAccountID) } if usage.UpdatedAt == nil { @@ -905,13 +944,17 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco return nil, err } if len(updates) > 0 { - s.persistOpenAICodexProbeSnapshot(account.ID, updates) + s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates) return updates, nil } return nil, nil } func (s *AccountUsageService) persistOpenAICodexProbeSnapshot(accountID int64, updates map[string]any) { + s.persistOpenAICodexProbeSnapshotContext(context.Background(), accountID, updates) +} + +func (s *AccountUsageService) persistOpenAICodexProbeSnapshotContext(ctx context.Context, accountID int64, updates map[string]any) { if s == nil || s.accountRepo == nil || accountID <= 0 { return } @@ -920,9 +963,12 @@ func (s *AccountUsageService) persistOpenAICodexProbeSnapshot(accountID int64, u } go func() { - updateCtx, updateCancel := context.WithTimeout(context.Background(), 5*time.Second) + updateCtx, updateCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer updateCancel() - if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil { + if err := scopedAccountIDAccess(updateCtx, s.accountRepo, accountID, "accounts.usage.read", true); err != nil { + return + } + if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil && adminaccess.RestrictedFromContext(ctx) == nil { notifyOpenAIAutoReset(accountID) } }() @@ -1063,7 +1109,7 @@ func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account * } // 使用独立 context,避免调用方 cancel 导致所有共享 flight 的请求失败 - fetchCtx, fetchCancel := context.WithTimeout(context.Background(), 30*time.Second) + fetchCtx, fetchCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) defer fetchCancel() proxyURL := s.antigravityQuotaFetcher.GetProxyURL(fetchCtx, account) @@ -1392,6 +1438,9 @@ func (s *AccountUsageService) addWindowStats(ctx context.Context, account *Accou // GetTodayStats 获取账号今日统计 func (s *AccountUsageService) GetTodayStats(ctx context.Context, accountID int64) (*WindowStats, error) { + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "accounts.stats.read", false); err != nil { + return nil, err + } stats, err := s.usageLogRepo.GetAccountTodayStats(ctx, accountID) if err != nil { return nil, fmt.Errorf("get today stats failed: %w", err) @@ -1408,6 +1457,16 @@ func (s *AccountUsageService) GetTodayStats(ctx context.Context, accountID int64 // GetTodayStatsBatch 批量获取账号今日统计,优先走批量 SQL,失败时回退单账号查询。 func (s *AccountUsageService) GetTodayStatsBatch(ctx context.Context, accountIDs []int64) (map[int64]*WindowStats, error) { + if adminaccess.RestrictedFromContext(ctx) != nil { + if len(accountIDs) > 100 { + return nil, fmt.Errorf("账户数量超过限制") + } + for _, id := range accountIDs { + if err := scopedAccountIDAccess(ctx, s.accountRepo, id, "accounts.stats.read", false); err != nil { + return nil, err + } + } + } uniqueIDs := make([]int64, 0, len(accountIDs)) seen := make(map[int64]struct{}, len(accountIDs)) for _, accountID := range accountIDs { @@ -1550,6 +1609,9 @@ func codexWindowStatsStart(progress *UsageProgress, fallbackWindow time.Duration } func (s *AccountUsageService) GetAccountUsageStats(ctx context.Context, accountID int64, startTime, endTime time.Time) (*usagestats.AccountUsageStatsResponse, error) { + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "accounts.stats.read", false); err != nil { + return nil, err + } stats, err := s.usageLogRepo.GetAccountUsageStats(ctx, accountID, startTime, endTime) if err != nil { return nil, fmt.Errorf("get account usage stats failed: %w", err) @@ -1606,6 +1668,10 @@ func parseTime(s string) (time.Time, error) { } func (s *AccountUsageService) tryClearRecoverableAccountError(ctx context.Context, account *Account) { + // 额度读取不能隐式恢复账户状态或调度。 + if adminaccess.RestrictedFromContext(ctx) != nil { + return + } if account == nil || account.Status != StatusError { return } diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 89ae03f075..ade1b59c55 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -22,6 +22,10 @@ type AdminService interface { UpdateUserBalance(ctx context.Context, userID int64, balance float64, operation string, notes string) (*User, error) BatchUpdateConcurrency(ctx context.Context, userIDs []int64, value int, mode string) (int, error) BatchUpdateLimits(ctx context.Context, userIDs []int64, concurrency, rpmLimit *int) (int, error) + // FindActiveUsersByBlacklistedEmails 按收件箱身份查找命中给定邮箱的未禁用普通用户。 + FindActiveUsersByBlacklistedEmails(ctx context.Context, emails []string) ([]User, error) + // BatchDisableUsers 批量禁用普通用户,返回实际禁用的人数。 + BatchDisableUsers(ctx context.Context, userIDs []int64) (int, error) GetUserAPIKeys(ctx context.Context, userID int64, page, pageSize int, sortBy, sortOrder string) ([]APIKey, int64, error) GetUserUsageStats(ctx context.Context, userID int64, period string) (any, error) GetUserRPMStatus(ctx context.Context, userID int64) (*UserRPMStatus, error) diff --git a/backend/internal/service/admin_service_role_test.go b/backend/internal/service/admin_service_role_test.go index 956b7fae17..86fe8eee46 100644 --- a/backend/internal/service/admin_service_role_test.go +++ b/backend/internal/service/admin_service_role_test.go @@ -4,8 +4,10 @@ package service import ( "context" + "net/http" "testing" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" "github.com/stretchr/testify/require" ) @@ -141,3 +143,18 @@ func TestAdminService_UpdateUser_PromoteDoesNotCountAdmins(t *testing.T) { require.Equal(t, RoleAdmin, updated.Role) require.Equal(t, 0, repo.listCalls, "升级路径不应触发管理员计数") } + +func TestAdminService_UpdateUser_AdminGuardsAreClientErrors(t *testing.T) { + base := &userRepoStub{user: &User{ID: 42, Email: "a@example.com", Role: RoleAdmin}} + repo := &roleGuardUserRepoStub{rpmUserRepoStub: &rpmUserRepoStub{userRepoStub: base}, adminTotal: 1} + svc := &adminServiceImpl{userRepo: repo, redeemCodeRepo: &redeemRepoStub{}} + + _, err := svc.UpdateUser(context.Background(), 42, &UpdateUserInput{Status: StatusDisabled}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "ADMIN_DISABLE_FORBIDDEN", infraerrors.Reason(err)) + + _, err = svc.UpdateUser(context.Background(), 42, &UpdateUserInput{Role: RoleUser}) + require.Equal(t, http.StatusBadRequest, infraerrors.Code(err)) + require.Equal(t, "LAST_ADMIN_DEMOTE_FORBIDDEN", infraerrors.Reason(err)) + require.Nil(t, repo.lastUpdated) +} diff --git a/backend/internal/service/admin_user.go b/backend/internal/service/admin_user.go index 12f71f96a2..653a5d62dd 100644 --- a/backend/internal/service/admin_user.go +++ b/backend/internal/service/admin_user.go @@ -172,7 +172,7 @@ func (s *adminServiceImpl) ensureNotLastAdmin(ctx context.Context) error { return fmt.Errorf("count admin users: %w", err) } if result == nil || result.Total <= 1 { - return errors.New("cannot demote the last admin user") + return infraerrors.BadRequest("LAST_ADMIN_DEMOTE_FORBIDDEN", "cannot demote the last admin user") } return nil } @@ -211,7 +211,7 @@ func (s *adminServiceImpl) UpdateUser(ctx context.Context, id int64, input *Upda // Protect admin users: cannot disable admin accounts if user.Role == "admin" && input.Status == "disabled" { - return nil, errors.New("cannot disable admin user") + return nil, infraerrors.BadRequest("ADMIN_DISABLE_FORBIDDEN", "cannot disable admin user; change the role to user first") } oldConcurrency := user.Concurrency @@ -363,7 +363,7 @@ func (s *adminServiceImpl) DeleteUser(ctx context.Context, id int64) error { return err } if user.Role == "admin" { - return errors.New("cannot delete admin user") + return infraerrors.BadRequest("ADMIN_DELETE_FORBIDDEN", "cannot delete admin user; change the role to user first") } apiKeys, err := s.listUserAPIKeysForDeletion(ctx, id) diff --git a/backend/internal/service/admin_user_email_blacklist.go b/backend/internal/service/admin_user_email_blacklist.go new file mode 100644 index 0000000000..84583b6db7 --- /dev/null +++ b/backend/internal/service/admin_user_email_blacklist.go @@ -0,0 +1,111 @@ +package service + +import ( + "context" + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" +) + +// MaxBatchDisableUsers 是单次批量禁用的用户数上限。 +const MaxBatchDisableUsers = MaxRegistrationEmailBlacklistSize + +// UserEmailBlacklistRepository 是精确邮箱黑名单关联已注册用户所需的仓储能力。 +type UserEmailBlacklistRepository interface { + // ListActiveUsersByEmailAliasProbeKeys 返回未删除、状态为 active、非管理员且邮箱折叠后 + // 命中任一 EmailAliasProbeKey 的用户。结果会过度匹配,调用方需按收件箱身份复核。 + ListActiveUsersByEmailAliasProbeKeys(ctx context.Context, keys []string) ([]User, error) + // BatchDisableUsers 把未删除、非管理员且尚未禁用的用户置为 disabled,并在同一事务内吊销这些用户的 + // 全部 MCP 授权,返回实际变更的用户 ID。 + BatchDisableUsers(ctx context.Context, userIDs []int64) ([]int64, error) +} + +// EmailAliasProbeKey 把探针拼成仓储层比对用的 "本地部分@域名" 键(两侧均已去点)。 +func EmailAliasProbeKey(probe EmailAliasProbe) string { + return probe.Local + "@" + probe.Domain +} + +// FindActiveUsersByBlacklistedEmails 返回收件箱身份命中给定邮箱的未禁用普通用户; +// 格式不合法的邮箱忽略。 +func (s *adminServiceImpl) FindActiveUsersByBlacklistedEmails(ctx context.Context, emails []string) ([]User, error) { + repo, ok := s.userRepo.(UserEmailBlacklistRepository) + if !ok { + return nil, ErrServiceUnavailable + } + + normalized := make([]string, 0, len(emails)) + for _, raw := range emails { + if email, valid := NormalizeRegistrationEmailBlacklistEntry(raw); valid { + normalized = append(normalized, email) + } + } + identities := RegistrationEmailBlacklistIdentities(normalized) + if len(identities) == 0 { + return []User{}, nil + } + + keySet := make(map[string]struct{}, 2*len(normalized)) + keys := make([]string, 0, 2*len(normalized)) + for _, email := range normalized { + for _, probe := range EmailAliasDedupProbes(email) { + key := EmailAliasProbeKey(probe) + if _, dup := keySet[key]; dup { + continue + } + keySet[key] = struct{}{} + keys = append(keys, key) + } + } + + candidates, err := repo.ListActiveUsersByEmailAliasProbeKeys(ctx, keys) + if err != nil { + return nil, err + } + matched := make([]User, 0, len(candidates)) + for _, candidate := range candidates { + if _, hit := identities[NormalizeEmailForAliasDedup(candidate.Email)]; hit { + matched = append(matched, candidate) + } + } + return matched, nil +} + +// BatchDisableUsers 批量禁用普通用户(管理员与已禁用用户跳过),返回实际禁用的人数。 +func (s *adminServiceImpl) BatchDisableUsers(ctx context.Context, userIDs []int64) (int, error) { + cleaned := make([]int64, 0, len(userIDs)) + seen := make(map[int64]struct{}, len(userIDs)) + for _, userID := range userIDs { + if userID <= 0 { + continue + } + if _, dup := seen[userID]; dup { + continue + } + seen[userID] = struct{}{} + cleaned = append(cleaned, userID) + } + if len(cleaned) == 0 { + return 0, nil + } + if len(cleaned) > MaxBatchDisableUsers { + return 0, fmt.Errorf("user_ids cannot exceed %d", MaxBatchDisableUsers) + } + + repo, ok := s.userRepo.(UserEmailBlacklistRepository) + if !ok { + return 0, ErrServiceUnavailable + } + disabled, err := repo.BatchDisableUsers(ctx, cleaned) + if err != nil { + return 0, err + } + if s.authCacheInvalidator != nil { + // 状态已落库,缓存失效不随请求取消中断,否则未清到的用户在缓存 TTL 内仍能用 API Key。 + invalidateCtx := context.WithoutCancel(ctx) + for _, userID := range disabled { + s.authCacheInvalidator.InvalidateAuthCacheByUserID(invalidateCtx, userID) + } + } + logger.LegacyPrintf("service.admin", "audit: batch disable users requested=%d disabled=%d", len(cleaned), len(disabled)) + return len(disabled), nil +} diff --git a/backend/internal/service/admin_user_email_blacklist_test.go b/backend/internal/service/admin_user_email_blacklist_test.go new file mode 100644 index 0000000000..e200bd7960 --- /dev/null +++ b/backend/internal/service/admin_user_email_blacklist_test.go @@ -0,0 +1,125 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/require" +) + +type emailBlacklistUserRepoStub struct { + *userRepoStub + probeKeys []string + candidates []User + listErr error + disableIDs []int64 + disabled []int64 + disableErr error + listCalls int + disableCall int +} + +func (s *emailBlacklistUserRepoStub) ListActiveUsersByEmailAliasProbeKeys(_ context.Context, keys []string) ([]User, error) { + s.listCalls++ + s.probeKeys = append([]string(nil), keys...) + return s.candidates, s.listErr +} + +func (s *emailBlacklistUserRepoStub) BatchDisableUsers(_ context.Context, userIDs []int64) ([]int64, error) { + s.disableCall++ + s.disableIDs = append([]int64(nil), userIDs...) + return s.disabled, s.disableErr +} + +func TestAdminService_FindActiveUsersByBlacklistedEmails_FiltersProbeOvermatch(t *testing.T) { + repo := &emailBlacklistUserRepoStub{ + userRepoStub: &userRepoStub{}, + candidates: []User{ + {ID: 1, Email: "a.b@gmail.com"}, + {ID: 2, Email: "ab+x@googlemail.com"}, + {ID: 3, Email: "first.last@company.example"}, + {ID: 4, Email: "firstlast@company.example"}, + }, + } + svc := &adminServiceImpl{userRepo: repo} + + users, err := svc.FindActiveUsersByBlacklistedEmails(context.Background(), []string{ + "AB@googlemail.com", "firstlast@company.example", "not-an-email", "ab@gmail.com", + }) + require.NoError(t, err) + ids := make([]int64, 0, len(users)) + for _, user := range users { + ids = append(ids, user.ID) + } + require.Equal(t, []int64{1, 2, 4}, ids) + require.ElementsMatch(t, []string{"ab@gmailcom", "ab@googlemailcom", "firstlast@companyexample"}, repo.probeKeys) +} + +func TestAdminService_FindActiveUsersByBlacklistedEmails_NoValidEmailSkipsQuery(t *testing.T) { + repo := &emailBlacklistUserRepoStub{userRepoStub: &userRepoStub{}} + svc := &adminServiceImpl{userRepo: repo} + + users, err := svc.FindActiveUsersByBlacklistedEmails(context.Background(), []string{"", "bad"}) + require.NoError(t, err) + require.Empty(t, users) + require.Zero(t, repo.listCalls) +} + +func TestAdminService_FindActiveUsersByBlacklistedEmails_RequiresRepositoryCapability(t *testing.T) { + svc := &adminServiceImpl{userRepo: &userRepoStub{}} + _, err := svc.FindActiveUsersByBlacklistedEmails(context.Background(), []string{"a@gmail.com"}) + require.ErrorIs(t, err, ErrServiceUnavailable) +} + +func TestAdminService_BatchDisableUsers_InvalidatesOnlyDisabledUsers(t *testing.T) { + repo := &emailBlacklistUserRepoStub{userRepoStub: &userRepoStub{}, disabled: []int64{7}} + invalidator := &authCacheInvalidatorStub{} + svc := &adminServiceImpl{userRepo: repo, authCacheInvalidator: invalidator} + + affected, err := svc.BatchDisableUsers(context.Background(), []int64{7, 0, 7, 9, -3}) + require.NoError(t, err) + require.Equal(t, 1, affected) + require.Equal(t, []int64{7, 9}, repo.disableIDs) + require.Equal(t, []int64{7}, invalidator.userIDs) +} + +func TestAdminService_BatchDisableUsers_EmptyAndErrors(t *testing.T) { + repo := &emailBlacklistUserRepoStub{userRepoStub: &userRepoStub{}} + svc := &adminServiceImpl{userRepo: repo} + + affected, err := svc.BatchDisableUsers(context.Background(), []int64{0, -1}) + require.NoError(t, err) + require.Zero(t, affected) + require.Zero(t, repo.disableCall) + + repo.disableErr = errors.New("db down") + _, err = svc.BatchDisableUsers(context.Background(), []int64{5}) + require.Error(t, err) +} + +type ctxRecordingAuthCacheInvalidator struct { + authCacheInvalidatorStub + ctxErrs []error +} + +func (s *ctxRecordingAuthCacheInvalidator) InvalidateAuthCacheByUserID(ctx context.Context, userID int64) { + s.ctxErrs = append(s.ctxErrs, ctx.Err()) + s.authCacheInvalidatorStub.InvalidateAuthCacheByUserID(ctx, userID) +} + +func TestAdminService_BatchDisableUsers_InvalidatesCacheAfterRequestCanceled(t *testing.T) { + repo := &emailBlacklistUserRepoStub{userRepoStub: &userRepoStub{}, disabled: []int64{4, 5}} + invalidator := &ctxRecordingAuthCacheInvalidator{} + svc := &adminServiceImpl{userRepo: repo, authCacheInvalidator: invalidator} + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + affected, err := svc.BatchDisableUsers(ctx, []int64{4, 5}) + require.NoError(t, err) + require.Equal(t, 2, affected) + require.Equal(t, []int64{4, 5}, invalidator.userIDs) + require.Equal(t, []error{nil, nil}, invalidator.ctxErrs) +} diff --git a/backend/internal/service/antigravity_gateway_compat.go b/backend/internal/service/antigravity_gateway_compat.go index f4e041adc0..fcc782a8fb 100644 --- a/backend/internal/service/antigravity_gateway_compat.go +++ b/backend/internal/service/antigravity_gateway_compat.go @@ -13,6 +13,8 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) type antigravityCompatProtocol uint8 @@ -75,7 +77,7 @@ func (s *AntigravityGatewayService) ForwardAsChatCompletions( if err != nil { return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } - claudeRequest, err := apicompat.ResponsesToAnthropicRequest(responsesRequest) + claudeRequest, err := convertAntigravityCompatResponsesToAnthropic(responsesRequest) if err != nil { return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } @@ -118,7 +120,7 @@ func (s *AntigravityGatewayService) ForwardAsResponses( return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", "model is required") } - claudeRequest, err := apicompat.ResponsesToAnthropicRequest(&request) + claudeRequest, err := convertAntigravityCompatResponsesToAnthropic(&request) if err != nil { return nil, s.writeAntigravityCompatError(c, http.StatusBadRequest, "invalid_request_error", err.Error()) } @@ -151,6 +153,48 @@ func (s *AntigravityGatewayService) validateAntigravityCompatAccount(c *gin.Cont ) } +func convertAntigravityCompatResponsesToAnthropic(request *apicompat.ResponsesRequest) (*apicompat.AnthropicRequest, error) { + request.Instructions = antigravity.NeutralizeSystemIdentity(request.Instructions) + neutralizeText := func(path string, text gjson.Result) error { + if text.Type != gjson.String { + return nil + } + neutral := antigravity.NeutralizeSystemIdentity(text.String()) + if neutral == text.String() { + return nil + } + var err error + request.Input, err = sjson.SetBytes(request.Input, path, neutral) + return err + } + for itemIndex, item := range gjson.ParseBytes(request.Input).Array() { + role := item.Get("role").String() + if role != "system" && role != "developer" { + continue + } + content := item.Get("content") + path := fmt.Sprintf("%d.content", itemIndex) + if content.Type == gjson.String { + if err := neutralizeText(path, content); err != nil { + return nil, err + } + continue + } + if !content.IsArray() { + continue + } + for partIndex, part := range content.Array() { + switch part.Get("type").String() { + case "text", "input_text", "output_text": + if err := neutralizeText(fmt.Sprintf("%s.%d.text", path, partIndex), part.Get("text")); err != nil { + return nil, err + } + } + } + } + return apicompat.ResponsesToAnthropicRequest(request) +} + func preserveChatCompletionTokenLimit(request *apicompat.ChatCompletionsRequest, claudeRequest *apicompat.AnthropicRequest) { if request == nil || claudeRequest == nil { return diff --git a/backend/internal/service/antigravity_gateway_compat_stream.go b/backend/internal/service/antigravity_gateway_compat_stream.go index 140792451d..4dea4c453c 100644 --- a/backend/internal/service/antigravity_gateway_compat_stream.go +++ b/backend/internal/service/antigravity_gateway_compat_stream.go @@ -304,7 +304,7 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn } session := newAntigravityCompatStreamSession(originalModel, startTime, adapter, writer) session.preContentKeepaliveInterval = interval - events, stopScanner, maxLineSize := s.startAntigravityCompatScanner(resp.Body) + events, stopScanner, maxLineSize, queueBudget := s.startAntigravityCompatScanner(resp.Body) defer stopScanner() timeout := s.antigravityCompatStreamTimeout() @@ -340,6 +340,9 @@ func (s *AntigravityGatewayService) handleAntigravityCompatStreamWithKeepaliveIn for { select { case event, open := <-events: + if open { + queueBudget.release(len(event.line)) + } if !session.hasMeaningfulData() && !writer.Disconnected() && !time.Now().Before(preContentDeadline) { return preContentTimeout() } @@ -397,7 +400,7 @@ func handleAntigravityCompatEmptyStream(c *gin.Context, session *antigravityComp func (s *AntigravityGatewayService) startAntigravityCompatScanner( body io.Reader, -) (<-chan antigravityCompatScanEvent, func(), int) { +) (<-chan antigravityCompatScanEvent, func(), int, *sseQueueBudget) { maxLineSize := defaultMaxLineSize if s.settingService != nil && s.settingService.cfg != nil && s.settingService.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.settingService.cfg.Gateway.MaxLineSize @@ -405,17 +408,23 @@ func (s *AntigravityGatewayService) startAntigravityCompatScanner( scanner := bufio.NewScanner(body) scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.antigravitySSEConfig(), maxLineSize, nil)) + queueBudget := newSSEQueueBudget(s.antigravitySSEConfig()) events := make(chan antigravityCompatScanEvent, 16) done := make(chan struct{}) go func() { defer putSSEScannerBuf64K(scanBuf) defer close(events) send := func(event antigravityCompatScanEvent) bool { + if !queueBudget.acquire(len(event.line), done) { + return false + } select { case events <- event: return true case <-done: + queueBudget.release(len(event.line)) return false } } @@ -428,7 +437,7 @@ func (s *AntigravityGatewayService) startAntigravityCompatScanner( send(antigravityCompatScanEvent{err: err}) } }() - return events, func() { close(done) }, maxLineSize + return events, func() { close(done) }, maxLineSize, queueBudget } func (s *AntigravityGatewayService) antigravityCompatStreamTimeout() time.Duration { diff --git a/backend/internal/service/antigravity_gateway_compat_test.go b/backend/internal/service/antigravity_gateway_compat_test.go index 825997e4f3..bccbe2472f 100644 --- a/backend/internal/service/antigravity_gateway_compat_test.go +++ b/backend/internal/service/antigravity_gateway_compat_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "net/http/httptest" @@ -131,6 +132,234 @@ func antigravityCompatSuccessResponse() *http.Response { } } +func TestAntigravitySystemIdentityAcrossProtocols(t *testing.T) { + gin.SetMode(gin.TestMode) + const task = "\nKeep GPT-5.6, gpt-6 and Claude model ids unchanged." + for _, identity := range []string{"You are Codex, based on GPT-5.6.", "You are Codex, an agent based on GPT-6.", "You are GPT-6 running in the Codex CLI.", "You are Claude Code, Anthropic's official CLI for Claude."} { + for _, model := range []string{"gemini-3.1-pro-high", "claude-sonnet-4-6"} { + for _, protocol := range []string{"responses", "chat", "messages"} { + for _, arraySystem := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/%s/array=%t", identity, model, protocol, arraySystem), func(t *testing.T) { + text := "x-anthropic-billing-header: cc_version=example;\n" + identity + task + var system any = text + if arraySystem { + system = []map[string]any{{"type": "text", "text": text}} + } + request := map[string]any{"model": model, "max_tokens": 128} + switch protocol { + case "responses": + request["input"] = identity + request["instructions"] = text + if arraySystem { + delete(request, "instructions") + request["input"] = []map[string]any{ + {"type": "message", "role": "developer", "content": []map[string]string{{"type": "input_text", "text": text}}}, + {"type": "message", "role": "user", "content": identity}, + } + } + case "chat": + request["messages"] = []map[string]any{{"role": "system", "content": system}, {"role": "user", "content": identity}} + case "messages": + request["system"] = system + request["messages"] = []map[string]any{{"role": "user", "content": identity}} + } + body, err := json.Marshal(request) + require.NoError(t, err) + var forwarded []byte + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{antigravityCompatSuccessResponse()}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + forwarded, err = io.ReadAll(req.Body) + require.NoError(t, err) + }, + } + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + c, _ := newAntigravityCompatContext(http.MethodPost, "/v1/"+protocol, body) + switch protocol { + case "responses": + _, err = svc.ForwardAsResponses(context.Background(), c, account, body, nil) + case "chat": + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, nil) + case "messages": + _, err = svc.Forward(context.Background(), c, account, body, false) + } + require.NoError(t, err) + systemText := gjson.GetBytes(forwarded, "request.systemInstruction.parts").Raw + require.Contains(t, systemText, "You are an AI agent.") + require.Contains(t, systemText, "Keep GPT-5.6, gpt-6 and Claude model ids unchanged.") + require.NotContains(t, systemText, identity) + require.NotContains(t, systemText, "x-anthropic-billing-header:") + require.Equal(t, identity, gjson.GetBytes(forwarded, "request.contents.0.parts.0.text").String()) + require.Equal(t, model, gjson.GetBytes(forwarded, "model").String()) + }) + } + } + } + } +} + +func TestAntigravitySystemIdentityMultipleBlocksForward(test *testing.T) { + gin.SetMode(gin.TestMode) + const model = "gemini-3.1-pro-high" + const stale = "You are Codex, based on GPT-6." + const otherStale = "You are Claude Code, Anthropic's official CLI for Claude." + const benign = "Keep GPT-5.6, gpt-6 and Claude model ids unchanged." + const quoted = `"You are Codex, based on GPT-6."` + const embedded = "Example identity:\nYou are Codex, based on GPT-6." + const userText = stale + "\n" + otherStale + for _, scenario := range []struct { + name string + blocks []string + }{ + {"benign_then_stale", []string{benign, stale}}, + {"native_then_stale", []string{"You are Antigravity, a helpful assistant.", stale}}, + {"multiple_stale", []string{stale, otherStale}}, + } { + for _, protocol := range []string{"responses", "chat", "messages"} { + for _, separateMessages := range []bool{false, true} { + if protocol == "messages" && separateMessages { + continue + } + test.Run(fmt.Sprintf("%s/%s/separate=%t", scenario.name, protocol, separateMessages), func(test *testing.T) { + texts := append(append([]string{}, scenario.blocks...), quoted, embedded, benign) + blocks := make([]map[string]any, 0, len(texts)) + for _, text := range texts { + blocks = append(blocks, map[string]any{"type": "text", "text": text}) + } + request := map[string]any{"model": model, "max_tokens": 128} + tool := map[string]any{"name": "example", "description": userText, "parameters": map[string]any{"type": "object"}} + switch protocol { + case "responses", "chat": + if protocol == "responses" { + for _, block := range blocks { + block["type"] = "input_text" + } + tool["type"] = "function" + request["tools"] = []any{tool} + } else { + request["tools"] = []any{map[string]any{"type": "function", "function": tool}} + } + messages := []map[string]any{{"role": "system", "content": blocks}} + if separateMessages { + messages = nil + for index, text := range texts { + role := "system" + if index%2 == 1 { + role = "developer" + } + if protocol == "responses" && index == 0 { + request["instructions"] = text + continue + } + messages = append(messages, map[string]any{"role": role, "content": text}) + } + } + messages = append(messages, map[string]any{"role": "user", "content": userText}) + if protocol == "responses" { + request["input"] = messages + } else { + request["messages"] = messages + } + case "messages": + request["system"] = blocks + request["messages"] = []map[string]any{{"role": "user", "content": userText}} + request["tools"] = []any{map[string]any{"name": "example", "description": userText, "input_schema": map[string]any{"type": "object"}}} + } + body, err := json.Marshal(request) + require.NoError(test, err) + var forwarded []byte + upstream := &queuedHTTPUpstreamStub{ + responses: []*http.Response{antigravityCompatSuccessResponse()}, + onCall: func(req *http.Request, _ *queuedHTTPUpstreamStub) { + forwarded, err = io.ReadAll(req.Body) + require.NoError(test, err) + }, + } + svc := newAntigravityCompatService(config.GatewayConfig{MaxLineSize: defaultMaxLineSize}, upstream) + account := newAntigravityCompatAccount(AccountTypeOAuth) + requestContext, _ := newAntigravityCompatContext(http.MethodPost, "/v1/"+protocol, body) + switch protocol { + case "responses": + _, err = svc.ForwardAsResponses(context.Background(), requestContext, account, body, nil) + case "chat": + _, err = svc.ForwardAsChatCompletions(context.Background(), requestContext, account, body, nil) + case "messages": + _, err = svc.Forward(context.Background(), requestContext, account, body, false) + } + require.NoError(test, err) + parts := gjson.GetBytes(forwarded, "request.systemInstruction.parts").Array() + var systemTexts []string + for _, part := range parts { + systemTexts = append(systemTexts, part.Get("text").String()) + } + require.NotEmpty(test, systemTexts) + wantTexts := append([]string{}, texts...) + for index, text := range wantTexts { + if text == stale || text == otherStale { + wantTexts[index] = "You are an AI agent." + } + } + if scenario.name != "native_then_stale" { + require.Contains(test, systemTexts[0], "You are Antigravity") + systemTexts = systemTexts[1:] + if protocol == "messages" { + require.GreaterOrEqual(test, len(systemTexts), 2) + require.Contains(test, systemTexts[0], "Below are your system instructions.") + require.Equal(test, "\n--- [SYSTEM_PROMPT_END] ---", systemTexts[len(systemTexts)-1]) + systemTexts = systemTexts[1 : len(systemTexts)-1] + } + } + separator := "\n\n" + if protocol == "messages" { + separator = "\n" + } + require.Equal(test, strings.Join(wantTexts, separator), strings.Join(systemTexts, "\n")) + require.Equal(test, userText, gjson.GetBytes(forwarded, "request.contents.0.parts.0.text").String()) + require.Equal(test, userText, gjson.GetBytes(forwarded, "request.tools.0.functionDeclarations.0.description").String()) + require.Equal(test, model, gjson.GetBytes(forwarded, "model").String()) + }) + } + } + } +} + +func TestInjectAntigravityGeminiSystemIdentity(t *testing.T) { + const identity = "You are Codex, based on GPT-6." + const mention = "Example: You are GPT-5.6 running in the Codex CLI." + for _, existingIdentity := range []bool{false, true} { + t.Run(fmt.Sprintf("existing identity=%t", existingIdentity), func(t *testing.T) { + parts := []map[string]any{ + {"text": "x-anthropic-billing-header: cc_version=example;"}, + {"text": identity, "custom": "preserved"}, + {"text": mention}, + {"text": `"You are Codex, based on GPT-6."`}, + } + if existingIdentity { + parts = append([]map[string]any{{"text": "You are Antigravity."}}, parts...) + } + body, err := json.Marshal(map[string]any{ + "systemInstruction": map[string]any{"parts": parts}, + "contents": []map[string]any{{"role": "user", "parts": []map[string]string{{"text": identity}}}}, + "tools": []map[string]any{{"functionDeclarations": []map[string]string{{"name": "example", "description": identity}}}}, + }) + require.NoError(t, err) + got, err := injectIdentityPatchToGeminiRequest(body) + require.NoError(t, err) + require.Equal(t, "You are an AI agent.", gjson.GetBytes(got, "systemInstruction.parts.2.text").String()) + require.Equal(t, "preserved", gjson.GetBytes(got, "systemInstruction.parts.2.custom").String()) + require.Equal(t, mention, gjson.GetBytes(got, "systemInstruction.parts.3.text").String()) + require.Equal(t, `"You are Codex, based on GPT-6."`, gjson.GetBytes(got, "systemInstruction.parts.4.text").String()) + for _, field := range []string{"contents", "tools"} { + require.JSONEq(t, gjson.GetBytes(body, field).Raw, gjson.GetBytes(got, field).Raw) + } + again, err := injectIdentityPatchToGeminiRequest(got) + require.NoError(t, err) + require.Equal(t, string(got), string(again)) + }) + } +} + func TestAntigravityCompatOAuthUsesNativeTokenAndRoute(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/antigravity_gateway_service.go b/backend/internal/service/antigravity_gateway_service.go index 66a0f02cdb..d2a4d81b1e 100644 --- a/backend/internal/service/antigravity_gateway_service.go +++ b/backend/internal/service/antigravity_gateway_service.go @@ -641,21 +641,33 @@ func injectIdentityPatchToGeminiRequest(body []byte) ([]byte, error) { return nil, fmt.Errorf("解析 Gemini 请求失败: %w", err) } + identityFound := false + systemChanged := false // 检查现有 systemInstruction 是否已包含身份提示词 if sysInst, ok := request["systemInstruction"].(map[string]any); ok { if parts, ok := sysInst["parts"].([]any); ok { for _, part := range parts { if partMap, ok := part.(map[string]any); ok { if text, ok := partMap["text"].(string); ok { - if strings.Contains(text, "You are Antigravity") { - // 已包含身份提示词,直接返回原始请求 - return body, nil + neutral := antigravity.NeutralizeSystemIdentity(text) + if neutral != text { + partMap["text"] = neutral + systemChanged = true + } + if strings.Contains(neutral, "You are Antigravity") { + identityFound = true } } } } } } + if identityFound { + if systemChanged { + return json.Marshal(request) + } + return body, nil + } // 获取默认身份提示词 identityPatch := antigravity.GetDefaultIdentityPatch() diff --git a/backend/internal/service/antigravity_gateway_streaming.go b/backend/internal/service/antigravity_gateway_streaming.go index 75b0bd5a75..2b5be77706 100644 --- a/backend/internal/service/antigravity_gateway_streaming.go +++ b/backend/internal/service/antigravity_gateway_streaming.go @@ -142,6 +142,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) usage := &ClaudeUsage{} var firstTokenMs *int @@ -152,11 +153,16 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -229,6 +235,9 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { return &antigravityStreamResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: cw.Disconnected()}, nil } @@ -345,6 +354,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) usage := &ClaudeUsage{} var firstTokenMs *int @@ -360,11 +370,16 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -404,6 +419,9 @@ func (s *AntigravityGatewayService) handleGeminiStreamToNonStreaming(c *gin.Cont for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 流结束,返回收集的响应 goto returnResponse @@ -756,6 +774,7 @@ func (s *AntigravityGatewayService) collectClaudeStreamResponse(c *gin.Context, } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) var firstTokenMs *int var last map[string]any @@ -771,11 +790,16 @@ func (s *AntigravityGatewayService) collectClaudeStreamResponse(c *gin.Context, // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -815,6 +839,9 @@ func (s *AntigravityGatewayService) collectClaudeStreamResponse(c *gin.Context, for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 流结束,转换并返回响应 goto returnResponse @@ -980,6 +1007,7 @@ func (s *AntigravityGatewayService) handleClaudeStreamingResponse(c *gin.Context } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) // 辅助函数:转换 antigravity.ClaudeUsage 到 service.ClaudeUsage convertUsage := func(agUsage *antigravity.ClaudeUsage) *ClaudeUsage { @@ -1001,11 +1029,16 @@ func (s *AntigravityGatewayService) handleClaudeStreamingResponse(c *gin.Context // 独立 goroutine 读取上游,避免读取阻塞影响超时处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1078,6 +1111,9 @@ func (s *AntigravityGatewayService) handleClaudeStreamingResponse(c *gin.Context for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 上游完成,发送结束事件 finalEvents, agUsage := processor.Finish() @@ -1165,7 +1201,7 @@ func (s *AntigravityGatewayService) extractImageInputSize(body []byte) string { } // isImageGenerationModel 判断模型是否为图片生成模型 -// 支持的模型:gemini-3.1-flash-image, gemini-3-pro-image, gemini-2.5-flash-image 等 +// 支持的模型:gemini-3.1-flash-image, gemini-3.1-flash-lite-image, gemini-3-pro-image, gemini-2.5-flash-image 等 func isImageGenerationModel(model string) bool { modelLower := strings.ToLower(model) // 移除 models/ 前缀 @@ -1175,6 +1211,8 @@ func isImageGenerationModel(model string) bool { return modelLower == "gemini-3.1-flash-image" || modelLower == "gemini-3.1-flash-image-preview" || strings.HasPrefix(modelLower, "gemini-3.1-flash-image-") || + modelLower == "gemini-3.1-flash-lite-image" || + strings.HasPrefix(modelLower, "gemini-3.1-flash-lite-image-") || modelLower == "gemini-3-pro-image" || modelLower == "gemini-3-pro-image-preview" || strings.HasPrefix(modelLower, "gemini-3-pro-image-") || diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index e6b9a73fa8..22925c74ff 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -171,6 +171,7 @@ func (s *AntigravityGatewayService) streamUpstreamResponse(c *gin.Context, resp maxLineSize = s.settingService.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.settingService.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -178,11 +179,16 @@ func (s *AntigravityGatewayService) streamUpstreamResponse(c *gin.Context, resp } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.settingService.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -238,6 +244,9 @@ func (s *AntigravityGatewayService) streamUpstreamResponse(c *gin.Context, resp for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { return &antigravityStreamResult{usage: usage, firstTokenMs: firstTokenMs, clientDisconnect: cw.Disconnected()} } diff --git a/backend/internal/service/antigravity_image_test.go b/backend/internal/service/antigravity_image_test.go index 76269dd3c3..11029785b3 100644 --- a/backend/internal/service/antigravity_image_test.go +++ b/backend/internal/service/antigravity_image_test.go @@ -21,6 +21,13 @@ func TestIsImageGenerationModel_GeminiFlashImage(t *testing.T) { require.True(t, isImageGenerationModel("gemini-2.5-flash-image-preview")) } +// TestIsImageGenerationModel_GeminiFlashLiteImage 测试 gemini-3.1-flash-lite-image 识别 +func TestIsImageGenerationModel_GeminiFlashLiteImage(t *testing.T) { + require.True(t, isImageGenerationModel("gemini-3.1-flash-lite-image")) + require.True(t, isImageGenerationModel("models/gemini-3.1-flash-lite-image")) + require.False(t, isImageGenerationModel("gemini-3.1-flash-lite")) +} + // TestIsImageGenerationModel_RegularModel 测试普通模型不被识别为图片模型 func TestIsImageGenerationModel_RegularModel(t *testing.T) { require.False(t, isImageGenerationModel("claude-3-opus")) 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_email_oauth_auto.go b/backend/internal/service/auth_email_oauth_auto.go index 655c39b362..0b0e5b3ad6 100644 --- a/backend/internal/service/auth_email_oauth_auto.go +++ b/backend/internal/service/auth_email_oauth_auto.go @@ -85,7 +85,8 @@ func (s *AuthService) loginOrRegisterVerifiedEmailOAuth( if isReservedEmail(email) { return nil, nil, ErrEmailReserved } - if err := s.validateRegistrationEmailPolicy(ctx, email); err != nil { + // 精确黑名单只拦新建账号(见 createEmailOAuthUser),已有账号能否登录由账号状态决定。 + if err := s.validateRegistrationEmailSuffixPolicy(ctx, email); err != nil { return nil, nil, err } @@ -158,6 +159,9 @@ func (s *AuthService) createEmailOAuthUser(ctx context.Context, email, username, if s.settingService == nil || !s.settingService.IsRegistrationEnabled(ctx) { return nil, ErrRegDisabled } + if s.settingService.IsRegistrationEmailBlacklisted(ctx, email) { + return nil, ErrEmailBlocked + } invitationRedeemCode, err := s.validateOAuthRegistrationInvitation(ctx, invitationCode) if err != nil { if errors.Is(err, ErrInvitationCodeRequired) { diff --git a/backend/internal/service/auth_email_oauth_blacklist_test.go b/backend/internal/service/auth_email_oauth_blacklist_test.go new file mode 100644 index 0000000000..07aac51394 --- /dev/null +++ b/backend/internal/service/auth_email_oauth_blacklist_test.go @@ -0,0 +1,60 @@ +//go:build unit + +package service_test + +import ( + "context" + "testing" + + dbuser "github.com/Wei-Shaw/sub2api/ent/user" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestLoginOrRegisterVerifiedEmailOAuth_BlacklistedExistingUserCanStillSignIn(t *testing.T) { + svc, repo, _ := newAuthServiceForEmailBindWithRefreshCache(t, map[string]string{ + service.SettingKeyRegistrationEnabled: "true", + service.SettingKeyRegistrationEmailBlacklist: `["kept.user@gmail.com"]`, + }, nil, nil, newEmailBindRefreshTokenCacheStub()) + ctx := context.Background() + + existing := &service.User{ + Email: "kept.user@gmail.com", + PasswordHash: "hash", + Role: service.RoleUser, + Status: service.StatusActive, + Concurrency: 1, + } + require.NoError(t, repo.Create(ctx, existing)) + + tokens, user, err := svc.LoginOrRegisterVerifiedEmailOAuth(ctx, service.EmailOAuthIdentityInput{ + ProviderType: "github", + ProviderSubject: "gh-kept-user", + Email: "kept.user@gmail.com", + EmailVerified: true, + Username: "kept", + }) + require.NoError(t, err) + require.NotNil(t, tokens) + require.Equal(t, existing.ID, user.ID) +} + +func TestLoginOrRegisterVerifiedEmailOAuth_BlacklistedNewEmailRejected(t *testing.T) { + svc, _, client := newAuthServiceForEmailBindWithRefreshCache(t, map[string]string{ + service.SettingKeyRegistrationEnabled: "true", + service.SettingKeyRegistrationEmailBlacklist: `["blocked.user@gmail.com"]`, + }, nil, nil, newEmailBindRefreshTokenCacheStub()) + ctx := context.Background() + + _, _, err := svc.LoginOrRegisterVerifiedEmailOAuth(ctx, service.EmailOAuthIdentityInput{ + ProviderType: "google", + ProviderSubject: "google-blocked-user", + Email: "blockeduser+x@googlemail.com", + EmailVerified: true, + }) + require.ErrorIs(t, err, service.ErrEmailBlocked) + + count, err := client.User.Query().Where(dbuser.EmailEQ("blockeduser+x@googlemail.com")).Count(ctx) + require.NoError(t, err) + require.Zero(t, count) +} diff --git a/backend/internal/service/auth_registration_email_blacklist_test.go b/backend/internal/service/auth_registration_email_blacklist_test.go new file mode 100644 index 0000000000..6cde4cb51d --- /dev/null +++ b/backend/internal/service/auth_registration_email_blacklist_test.go @@ -0,0 +1,62 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestAuthService_Register_BlacklistedEmailAliasRejected(t *testing.T) { + repo := &userRepoStub{nextID: 9} + svc := newAuthService(repo, map[string]string{ + SettingKeyRegistrationEnabled: "true", + SettingKeyRegistrationEmailBlacklist: `["spam.user@gmail.com"]`, + }, nil, nil) + + _, _, err := svc.Register(context.Background(), "SpamUser+1@googlemail.com", "password") + require.ErrorIs(t, err, ErrEmailBlocked) + require.Equal(t, "EMAIL_BLOCKED", infraerrors.FromError(err).Reason) + require.Empty(t, repo.created) +} + +func TestAuthService_Register_BlacklistOverridesSuffixWhitelist(t *testing.T) { + repo := &userRepoStub{nextID: 9} + svc := newAuthService(repo, map[string]string{ + SettingKeyRegistrationEnabled: "true", + SettingKeyRegistrationEmailSuffixWhitelist: `["@gmail.com"]`, + SettingKeyRegistrationEmailBlacklist: `["blocked@gmail.com"]`, + }, nil, nil) + + _, _, err := svc.Register(context.Background(), "blocked@gmail.com", "password") + require.ErrorIs(t, err, ErrEmailBlocked) + require.Empty(t, repo.created) + + _, user, err := svc.Register(context.Background(), "allowed@gmail.com", "password") + require.NoError(t, err) + require.Equal(t, "allowed@gmail.com", user.Email) +} + +func TestAuthService_SendVerifyCode_BlacklistedEmailRejected(t *testing.T) { + svc := newAuthService(&userRepoStub{}, map[string]string{ + SettingKeyRegistrationEnabled: "true", + SettingKeyEmailVerifyEnabled: "true", + SettingKeyRegistrationEmailBlacklist: `["blocked@example.com"]`, + }, nil, nil) + + require.ErrorIs(t, svc.SendVerifyCode(context.Background(), "blocked+x@example.com"), ErrEmailBlocked) + _, err := svc.SendVerifyCodeAsync(context.Background(), "blocked@example.com") + require.ErrorIs(t, err, ErrEmailBlocked) +} + +func TestAuthService_ValidateRegistrationEmailPolicy_BlacklistedEmailRejected(t *testing.T) { + svc := newAuthService(&userRepoStub{}, map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["bind.target@gmail.com"]`, + }, nil, nil) + + require.ErrorIs(t, svc.validateRegistrationEmailPolicy(context.Background(), "bindtarget@gmail.com"), ErrEmailBlocked) + require.NoError(t, svc.validateRegistrationEmailPolicy(context.Background(), "someone@gmail.com")) +} diff --git a/backend/internal/service/auth_service.go b/backend/internal/service/auth_service.go index 0774923e6c..ded56e1e13 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, "", "", "", "") @@ -1192,7 +1202,19 @@ func inferLegacySignupSource(email string) string { } } +// validateRegistrationEmailPolicy 校验邮箱能否用于新建账号或绑定为账号邮箱:精确黑名单与域名白名单。 func (s *AuthService) validateRegistrationEmailPolicy(ctx context.Context, email string) error { + if s.settingService == nil { + return nil + } + if s.settingService.IsRegistrationEmailBlacklisted(ctx, email) { + return ErrEmailBlocked + } + return s.validateRegistrationEmailSuffixPolicy(ctx, email) +} + +// validateRegistrationEmailSuffixPolicy 只校验域名白名单。 +func (s *AuthService) validateRegistrationEmailSuffixPolicy(ctx context.Context, email string) error { if s.settingService == nil { return nil } @@ -1203,13 +1225,16 @@ func (s *AuthService) validateRegistrationEmailPolicy(ctx context.Context, email return nil } -// validateRegistrationEmailQuota 保留白名单为空时的全放行行为;配置白名单后, -// 非白名单域名默认直接拒绝(严格白名单模式);仅当域名限量注册开关开启时, +// validateRegistrationEmailQuota 精确黑名单命中直接拒绝;保留白名单为空时的全放行行为; +// 配置白名单后,非白名单域名默认直接拒绝(严格白名单模式);仅当域名限量注册开关开启时, // 非白名单域名每个最多允许一个账户。 func (s *AuthService) validateRegistrationEmailQuota(ctx context.Context, email string) error { if s.settingService == nil { return nil } + if s.settingService.IsRegistrationEmailBlacklisted(ctx, email) { + return ErrEmailBlocked + } whitelist := s.settingService.GetRegistrationEmailSuffixWhitelist(ctx) if !IsRegistrationEmailSuffixLimited(email, whitelist) { return nil @@ -1907,6 +1932,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/balance_notify_check_test.go b/backend/internal/service/balance_notify_check_test.go index 7bb4cf9e7f..9035737fe6 100644 --- a/backend/internal/service/balance_notify_check_test.go +++ b/backend/internal/service/balance_notify_check_test.go @@ -240,8 +240,8 @@ func TestCheckQuotaDimCrossings_NoDimensions(t *testing.T) { s, _ := newBalanceNotifyServiceForTest() account := &Account{ID: 1, Name: "test", Platform: PlatformAnthropic} // Empty dims → no crossing, no panic. - s.checkQuotaDimCrossings(account, nil, 10, []string{"admin@example.com"}, "TestSite") - s.checkQuotaDimCrossings(account, []quotaDim{}, 10, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, nil, 10, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, []quotaDim{}, 10, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_DisabledDimension(t *testing.T) { @@ -258,7 +258,7 @@ func TestCheckQuotaDimCrossings_DisabledDimension(t *testing.T) { }, } // Disabled dimension should be skipped even if crossing would occur. - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_ZeroThresholdSkipped(t *testing.T) { @@ -275,7 +275,7 @@ func TestCheckQuotaDimCrossings_ZeroThresholdSkipped(t *testing.T) { }, } // Zero threshold → skipped. - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_NoCrossing_BothBelowThreshold(t *testing.T) { @@ -293,7 +293,7 @@ func TestCheckQuotaDimCrossings_NoCrossing_BothBelowThreshold(t *testing.T) { limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_NoCrossing_BothAboveThreshold(t *testing.T) { @@ -311,7 +311,7 @@ func TestCheckQuotaDimCrossings_NoCrossing_BothAboveThreshold(t *testing.T) { limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_NegativeResolvedThreshold_Skipped(t *testing.T) { @@ -329,7 +329,7 @@ func TestCheckQuotaDimCrossings_NegativeResolvedThreshold_Skipped(t *testing.T) limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_PercentageThreshold_NoCrossing(t *testing.T) { @@ -347,7 +347,7 @@ func TestCheckQuotaDimCrossings_PercentageThreshold_NoCrossing(t *testing.T) { limit: 1000, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_ZeroLimit_Skipped(t *testing.T) { @@ -364,7 +364,7 @@ func TestCheckQuotaDimCrossings_ZeroLimit_Skipped(t *testing.T) { limit: 0, }, } - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } func TestCheckQuotaDimCrossings_MultipleDims_MixedResults(t *testing.T) { @@ -400,5 +400,5 @@ func TestCheckQuotaDimCrossings_MultipleDims_MixedResults(t *testing.T) { }, } // None should trigger. No panic expected. - s.checkQuotaDimCrossings(account, dims, 50, []string{"admin@example.com"}, "TestSite") + s.checkQuotaDimCrossings(context.Background(), account, dims, 50, []string{"admin@example.com"}, "TestSite") } diff --git a/backend/internal/service/balance_notify_service.go b/backend/internal/service/balance_notify_service.go index 268032750a..b7c43f84b9 100644 --- a/backend/internal/service/balance_notify_service.go +++ b/backend/internal/service/balance_notify_service.go @@ -43,14 +43,16 @@ type BalanceNotifyService struct { settingRepo SettingRepository accountRepo AccountQuotaReader notificationEmailService *NotificationEmailService + usageNotifications *usageNotificationWorker } // NewBalanceNotifyService creates a new BalanceNotifyService. func NewBalanceNotifyService(emailService *EmailService, settingRepo SettingRepository, accountRepo AccountQuotaReader) *BalanceNotifyService { return &BalanceNotifyService{ - emailService: emailService, - settingRepo: settingRepo, - accountRepo: accountRepo, + emailService: emailService, + settingRepo: settingRepo, + accountRepo: accountRepo, + usageNotifications: newUsageNotificationWorker(), } } @@ -118,20 +120,13 @@ func crossedDownward(oldV, newV, threshold float64) bool { return oldV >= threshold && newV < threshold } -// dispatchBalanceLowEmail collects recipients and sends the alert in a goroutine. +// dispatchBalanceLowEmail sends within the bounded notification task. func (s *BalanceNotifyService) dispatchBalanceLowEmail(ctx context.Context, user *User, newBalance, threshold float64, rechargeURL string) { siteName := s.getSiteName(ctx) recipients := s.collectBalanceNotifyRecipients(user) slog.Info("CheckBalanceAfterDeduction: sending notification", "user_id", user.ID, "recipients", recipients, "new_balance", newBalance, "threshold", threshold) - go func() { - defer func() { - if r := recover(); r != nil { - slog.Error("panic in balance notification", "recover", r) - } - }() - s.sendBalanceLowEmails(recipients, user.ID, user.Username, user.Email, newBalance, threshold, siteName, rechargeURL) - }() + s.sendBalanceLowEmails(ctx, recipients, user.ID, user.Username, user.Email, newBalance, threshold, siteName, rechargeURL) } // quotaDim describes one quota dimension for notification checking. @@ -201,7 +196,7 @@ func (s *BalanceNotifyService) CheckAccountQuotaAfterIncrement(ctx context.Conte dims = buildQuotaDims(freshAccount) account = freshAccount // use fresh data for alert metadata } - s.checkQuotaDimCrossings(account, dims, cost, adminEmails, siteName) + s.checkQuotaDimCrossings(ctx, account, dims, cost, adminEmails, siteName) } // fetchFreshAccount loads the latest account from DB; falls back to the snapshot on error. @@ -220,7 +215,7 @@ func (s *BalanceNotifyService) fetchFreshAccount(ctx context.Context, snapshot * // checkQuotaDimCrossings iterates pre-built quota dimensions and sends alerts for threshold crossings. // Pre-increment value is reconstructed as currentUsed - cost to detect the crossing moment. -func (s *BalanceNotifyService) checkQuotaDimCrossings(account *Account, dims []quotaDim, cost float64, adminEmails []string, siteName string) { +func (s *BalanceNotifyService) checkQuotaDimCrossings(ctx context.Context, account *Account, dims []quotaDim, cost float64, adminEmails []string, siteName string) { for _, dim := range dims { if !dim.enabled || dim.threshold <= 0 { continue @@ -232,23 +227,11 @@ func (s *BalanceNotifyService) checkQuotaDimCrossings(account *Account, dims []q newUsed := dim.currentUsed oldUsed := dim.currentUsed - cost if oldUsed < effectiveThreshold && newUsed >= effectiveThreshold { - s.asyncSendQuotaAlert(adminEmails, account.ID, account.Name, account.Platform, dim, newUsed, effectiveThreshold, siteName) + s.sendQuotaAlertEmails(ctx, adminEmails, account.ID, account.Name, account.Platform, dim, newUsed, siteName) } } } -// asyncSendQuotaAlert sends quota alert email in a goroutine with panic recovery. -func (s *BalanceNotifyService) asyncSendQuotaAlert(adminEmails []string, accountID int64, accountName, platform string, dim quotaDim, newUsed, effectiveThreshold float64, siteName string) { - go func() { - defer func() { - if r := recover(); r != nil { - slog.Error("panic in quota notification", "recover", r) - } - }() - s.sendQuotaAlertEmails(adminEmails, accountID, accountName, platform, dim, newUsed, siteName) - }() -} - // getBalanceNotifyConfig reads global balance notification settings. func (s *BalanceNotifyService) getBalanceNotifyConfig(ctx context.Context) (enabled bool, threshold float64, rechargeURL string) { keys := []string{SettingKeyBalanceLowNotifyEnabled, SettingKeyBalanceLowNotifyThreshold, SettingKeyBalanceLowNotifyRechargeURL} @@ -329,13 +312,16 @@ func (s *BalanceNotifyService) collectBalanceNotifyRecipients(user *User) []stri } // sendEmails sends an email to all recipients with shared timeout and error logging. -func (s *BalanceNotifyService) sendEmails(recipients []string, subject, body string, logAttrs ...any) { +func (s *BalanceNotifyService) sendEmails(parent context.Context, recipients []string, subject, body string, logAttrs ...any) { if len(recipients) == 0 { slog.Warn("sendEmails: no recipients", "subject", subject) return } for _, to := range recipients { - ctx, cancel := context.WithTimeout(context.Background(), emailSendTimeout) + if parent.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(parent, emailSendTimeout) if err := s.emailService.SendEmail(ctx, to, subject, body); err != nil { attrs := append([]any{"to", to, "error", err}, logAttrs...) slog.Error("failed to send notification", attrs...) @@ -347,7 +333,7 @@ func (s *BalanceNotifyService) sendEmails(recipients []string, subject, body str } // sendBalanceLowEmails sends balance low notification to all recipients. -func (s *BalanceNotifyService) sendBalanceLowEmails(recipients []string, userID int64, userName, userEmail string, balance, threshold float64, siteName, rechargeURL string) { +func (s *BalanceNotifyService) sendBalanceLowEmails(parent context.Context, recipients []string, userID int64, userName, userEmail string, balance, threshold float64, siteName, rechargeURL string) { displayName := userName if displayName == "" { displayName = userEmail @@ -355,7 +341,10 @@ func (s *BalanceNotifyService) sendBalanceLowEmails(recipients []string, userID if s.notificationEmailService != nil { fallbackRecipients := make([]string, 0, len(recipients)) for _, to := range recipients { - ctx, cancel := context.WithTimeout(context.Background(), emailSendTimeout) + if parent.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(parent, emailSendTimeout) err := s.notificationEmailService.Send(ctx, NotificationEmailSendInput{ Event: NotificationEmailEventBalanceLow, RecipientEmail: to, @@ -387,11 +376,11 @@ func (s *BalanceNotifyService) sendBalanceLowEmails(recipients []string, userID } subject := fmt.Sprintf("[%s] 余额不足提醒 / Balance Low Alert", sanitizeEmailHeader(siteName)) body := s.buildBalanceLowEmailBody(html.EscapeString(displayName), balance, threshold, html.EscapeString(siteName), rechargeURL) - s.sendEmails(recipients, subject, body, "user_email", userEmail, "balance", balance) + s.sendEmails(parent, recipients, subject, body, "user_email", userEmail, "balance", balance) } // sendQuotaAlertEmails sends quota alert notification to admin emails. -func (s *BalanceNotifyService) sendQuotaAlertEmails(adminEmails []string, accountID int64, accountName, platform string, dim quotaDim, used float64, siteName string) { +func (s *BalanceNotifyService) sendQuotaAlertEmails(parent context.Context, adminEmails []string, accountID int64, accountName, platform string, dim quotaDim, used float64, siteName string) { dimLabel := quotaDimLabels[dim.name] if dimLabel == "" { dimLabel = dim.name @@ -410,7 +399,10 @@ func (s *BalanceNotifyService) sendQuotaAlertEmails(adminEmails []string, accoun if s.notificationEmailService != nil { fallbackRecipients := make([]string, 0, len(adminEmails)) for _, to := range adminEmails { - ctx, cancel := context.WithTimeout(context.Background(), emailSendTimeout) + if parent.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(parent, emailSendTimeout) err := s.notificationEmailService.Send(ctx, NotificationEmailSendInput{ Event: NotificationEmailEventAccountQuotaAlert, RecipientEmail: to, @@ -447,7 +439,7 @@ func (s *BalanceNotifyService) sendQuotaAlertEmails(adminEmails []string, accoun subject := fmt.Sprintf("[%s] 账号限额告警 / Account Quota Alert - %s", sanitizeEmailHeader(siteName), sanitizeEmailHeader(accountName)) body := s.buildQuotaAlertEmailBody(accountID, html.EscapeString(accountName), html.EscapeString(platform), html.EscapeString(dimLabel), used, dim.limit, remaining, thresholdDisplay, html.EscapeString(siteName)) - s.sendEmails(adminEmails, subject, body, "account", accountName, "dimension", dim.name) + s.sendEmails(parent, adminEmails, subject, body, "account", accountName, "dimension", dim.name) } // sanitizeEmailHeader removes CR/LF characters to prevent SMTP header injection. diff --git a/backend/internal/service/bedrock_stream.go b/backend/internal/service/bedrock_stream.go index 9ce6b87e24..3656628c22 100644 --- a/backend/internal/service/bedrock_stream.go +++ b/backend/internal/service/bedrock_stream.go @@ -60,11 +60,16 @@ func (s *GatewayService) handleBedrockStreamingResponse( } events := make(chan decodeEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev decodeEvent) bool { + if !queueBudget.acquire(len(ev.payload), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.payload)) return false } } @@ -107,6 +112,9 @@ func (s *GatewayService) handleBedrockStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.payload)) + } if !ok { if !clientDisconnected { flusher.Flush() diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go index ea22efe2eb..b4734f1e17 100644 --- a/backend/internal/service/billing_cache_service.go +++ b/backend/internal/service/billing_cache_service.go @@ -714,7 +714,7 @@ func (s *BillingCacheService) QueueUpdateAPIKeyRateLimitUsage(apiKeyID int64, co // 把 TOCTOU 超支窗口限制在并发 in-flight 请求数量内(而非随时间无限累积)。 // 写延迟通常 < 1ms(本地 Redis),换取 quota 视图实时性的取舍合理。 // -// Redis 写失败用 ALERT 级 log;DB 持久化由 caller 单独 goroutine 兜底(gateway_service.go)。 +// Redis 写失败用 ALERT 级 log;DB 持久化由计费 worker 内同步执行或批量 flusher 处理。 func (s *BillingCacheService) IncrementUserPlatformQuotaUsage(userID int64, platform string, cost float64) { if s.cache == nil { return diff --git a/backend/internal/service/billing_notification_worker.go b/backend/internal/service/billing_notification_worker.go new file mode 100644 index 0000000000..c82eca212e --- /dev/null +++ b/backend/internal/service/billing_notification_worker.go @@ -0,0 +1,103 @@ +package service + +import ( + "context" + "log/slog" + "sync" + "sync/atomic" + "time" + + "github.com/alitto/pond/v2" +) + +const ( + usageNotificationWorkers = 4 + usageNotificationQueueSize = 128 + usageNotificationTimeout = 30 * time.Second +) + +// Notification work is best effort and must not create an unbounded queue or +// compete with committed-charge persistence for usage workers. A task includes +// both settings reads and email delivery, including all quota dimensions. +type usageNotificationWorker struct { + pool pond.Pool + ctx context.Context + cancel context.CancelFunc + stopOnce sync.Once + dropped atomic.Uint64 + lastDropLog atomic.Int64 +} + +func newUsageNotificationWorker() *usageNotificationWorker { + ctx, cancel := context.WithCancel(context.Background()) + return &usageNotificationWorker{ + pool: pond.NewPool(usageNotificationWorkers, pond.WithQueueSize(usageNotificationQueueSize)), + ctx: ctx, + cancel: cancel, + } +} + +func (w *usageNotificationWorker) submit(task func(context.Context)) bool { + if w == nil || task == nil { + return false + } + _, accepted := w.pool.TrySubmit(func() { + if w.ctx.Err() != nil { + return + } + ctx, cancel := context.WithTimeout(w.ctx, usageNotificationTimeout) + defer cancel() + defer func() { + if recovered := recover(); recovered != nil { + slog.Error("panic in usage notification", "recover", recovered) + } + }() + task(ctx) + }) + if !accepted { + count := w.dropped.Add(1) + now := time.Now().UnixNano() + last := w.lastDropLog.Load() + if now-last >= int64(5*time.Second) && w.lastDropLog.CompareAndSwap(last, now) { + slog.Warn("usage notification queue unavailable; notification skipped", "dropped_total", count) + } + } + return accepted +} + +func (w *usageNotificationWorker) stop() { + if w == nil { + return + } + w.stopOnce.Do(func() { + // Cancel settings reads and discard queued notifications during shutdown. + // Active SMTP calls also have their own dial and I/O deadlines. + w.cancel() + w.pool.StopAndWait() + }) +} + +func (s *BalanceNotifyService) submitUsageNotifications(p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { + if s == nil || s.usageNotifications == nil || p == nil || p.Cost == nil { + return + } + balanceEnabled := !p.IsSubscriptionBill && p.Cost.ActualCost > 0 && s.canNotifyBalance(p.User) + quotaEnabled := p.Cost.TotalCost > 0 && p.Account != nil && p.Account.SupportsAccountQuota() && p.Account.HasAnyQuotaLimit() + if !balanceEnabled && !quotaEnabled { + return + } + s.usageNotifications.submit(func(ctx context.Context) { + notifyBalanceLow(ctx, p, deps, result) + if ctx.Err() == nil { + notifyAccountQuota(ctx, p, deps, result) + } + }) +} + +// Stop cancels notification work and waits for the bounded workers to exit. +// Billing persistence belongs to usage tasks and is never dropped here. +func (s *BalanceNotifyService) Stop() { + if s != nil { + s.usageNotifications.stop() + } +} diff --git a/backend/internal/service/billing_notification_worker_test.go b/backend/internal/service/billing_notification_worker_test.go new file mode 100644 index 0000000000..cc0c6b7f9c --- /dev/null +++ b/backend/internal/service/billing_notification_worker_test.go @@ -0,0 +1,76 @@ +package service + +import ( + "context" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestUsageNotificationsBoundWorkAndCancelOnStop(t *testing.T) { + w := newUsageNotificationWorker() + t.Cleanup(w.stop) + started := make(chan context.Context, usageNotificationWorkers) + var running, queuedRan atomic.Int64 + for range usageNotificationWorkers { + require.True(t, w.submit(func(ctx context.Context) { + running.Add(1) + defer running.Add(-1) + started <- ctx + <-ctx.Done() + })) + } + for range usageNotificationWorkers { + select { + case ctx := <-started: + deadline, ok := ctx.Deadline() + require.True(t, ok) + require.InDelta(t, usageNotificationTimeout.Seconds(), time.Until(deadline).Seconds(), 2) + case <-time.After(2 * time.Second): + t.Fatal("notification worker did not start") + } + } + for range usageNotificationQueueSize { + require.True(t, w.submit(func(context.Context) { queuedRan.Add(1) })) + } + require.False(t, w.submit(func(context.Context) { queuedRan.Add(1) })) + require.Equal(t, int64(usageNotificationWorkers), running.Load()) + require.Equal(t, uint64(1), w.dropped.Load()) + + w.stop() + w.stop() + require.Zero(t, running.Load()) + require.Zero(t, queuedRan.Load(), "shutdown must not start queued settings reads or email deliveries") + require.False(t, w.submit(func(context.Context) { t.Error("stopped worker accepted work") })) +} + +type notificationCancellationSettings struct { + SettingRepository + started chan context.Context +} + +func (s *notificationCancellationSettings) GetMultiple(ctx context.Context, _ []string) (map[string]string, error) { + s.started <- ctx + <-ctx.Done() + return nil, ctx.Err() +} + +func TestBalanceNotifyStopCancelsSettingsReads(t *testing.T) { + settings := ¬ificationCancellationSettings{started: make(chan context.Context, 1)} + s := NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil) + t.Cleanup(s.Stop) + s.submitUsageNotifications(&postUsageBillingParams{ + Cost: &CostBreakdown{ActualCost: 1}, + User: &User{ID: 1, BalanceNotifyEnabled: true}, + }, &billingDeps{balanceNotifyService: s}, nil) + select { + case ctx := <-settings.started: + _, ok := ctx.Deadline() + require.True(t, ok) + case <-time.After(2 * time.Second): + t.Fatal("notification settings read did not start") + } + s.Stop() +} diff --git a/backend/internal/service/channel_service.go b/backend/internal/service/channel_service.go index 85d6409301..1473f3edfd 100644 --- a/backend/internal/service/channel_service.go +++ b/backend/internal/service/channel_service.go @@ -973,7 +973,7 @@ func (s *ChannelService) applyUpdateInput(ctx context.Context, channel *Channel, channel.BillingModelSource = input.BillingModelSource } if input.FeaturesConfig != nil { - channel.FeaturesConfig = input.FeaturesConfig + channel.FeaturesConfig = mergeWebSearchEmulationDimensions(channel.FeaturesConfig, input.FeaturesConfig) } if input.ApplyPricingToAccountStats != nil { channel.ApplyPricingToAccountStats = *input.ApplyPricingToAccountStats @@ -986,6 +986,65 @@ func (s *ChannelService) applyUpdateInput(ctx context.Context, channel *Channel, // checkGroupConflicts 检查待关联的分组是否已属于其他渠道。 // channelID 为当前渠道 ID(Create 时传 0)。 +// mergeWebSearchEmulationDimensions keeps the per-platform dimensions of +// features_config.web_search_emulation across channel updates. +// +// Why: the key is a map keyed by platform ("anthropic", "openai", ...), but +// UpdateChannel replaces features_config as a whole block. A client that only +// knows about a subset of platforms (the admin UI used to submit the anthropic +// dimension only) therefore erased every other platform's setting on each save — +// silently disabling web search emulation for openai/command_code/... channels. +// +// Rules: +// - key present in the request: request dimensions win, missing dimensions are +// inherited from the current value; +// - key absent from the request: the whole key is inherited, so clients that do +// not know the feature cannot wipe it; +// - explicit empty object {} or null: treated as "clear" and replaces the value. +// +// Other features_config keys keep the historical whole-block replacement +// semantics. No generic deep merge is performed: nested objects are replaced as +// a unit so deleting a dimension stays expressible. +func mergeWebSearchEmulationDimensions(existing, incoming map[string]any) map[string]any { + if incoming == nil { + return nil + } + current, _ := existing[featureKeyWebSearchEmulation].(map[string]any) + rawIncoming, present := incoming[featureKeyWebSearchEmulation] + incomingDims, incomingIsMap := rawIncoming.(map[string]any) + + if !present && len(current) > 0 { + return withWebSearchEmulationKey(incoming, current) + } + if !incomingIsMap || len(current) == 0 || len(incomingDims) == 0 { + return incoming + } + + merged := make(map[string]any, len(incomingDims)+len(current)) + for platform, value := range current { + merged[platform] = value + } + for platform, value := range incomingDims { + merged[platform] = value + } + return withWebSearchEmulationKey(incoming, merged) +} + +// withWebSearchEmulationKey returns a copy of incoming whose +// web_search_emulation key points at a copy of value. +func withWebSearchEmulationKey(incoming, value map[string]any) map[string]any { + out := make(map[string]any, len(incoming)+1) + for key, item := range incoming { + out[key] = item + } + copied := make(map[string]any, len(value)) + for platform, item := range value { + copied[platform] = item + } + out[featureKeyWebSearchEmulation] = copied + return out +} + func (s *ChannelService) checkGroupConflicts(ctx context.Context, channelID int64, groupIDs []int64) error { if len(groupIDs) == 0 { return nil diff --git a/backend/internal/service/channel_websearch_merge_test.go b/backend/internal/service/channel_websearch_merge_test.go new file mode 100644 index 0000000000..e37d750624 --- /dev/null +++ b/backend/internal/service/channel_websearch_merge_test.go @@ -0,0 +1,130 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMergeWebSearchEmulationDimensions_MissingDimensionsInherited(t *testing.T) { + existing := map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"openai": true, "command_code": true}, + } + incoming := map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"anthropic": false}, + } + merged := mergeWebSearchEmulationDimensions(existing, incoming) + + dims, ok := merged[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok) + require.Equal(t, false, dims["anthropic"]) + require.Equal(t, true, dims["openai"]) + require.Equal(t, true, dims["command_code"]) +} + +func TestMergeWebSearchEmulationDimensions_RequestValueWins(t *testing.T) { + existing := map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"openai": true}, + } + incoming := map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"openai": false}, + } + merged := mergeWebSearchEmulationDimensions(existing, incoming) + + dims, ok := merged[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok) + require.Equal(t, false, dims["openai"]) +} + +func TestMergeWebSearchEmulationDimensions_KeyAbsentInheritsWholeKey(t *testing.T) { + existing := map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"openai": true}, + "bedrock_cc_compat": map[string]any{"anthropic": true}, + } + incoming := map[string]any{"other": 2} + merged := mergeWebSearchEmulationDimensions(existing, incoming) + + dims, ok := merged[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok, "clients that do not send the key must not erase it") + require.Equal(t, true, dims["openai"]) + require.Equal(t, 2, merged["other"]) + + // The inherited value must be a copy: mutating the result must not modify + // the previous configuration. + dims["openai"] = false + existingDims, ok := existing[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok) + require.Equal(t, true, existingDims["openai"]) +} + +func TestMergeWebSearchEmulationDimensions_KeyAbsentWithoutExistingIsNoop(t *testing.T) { + merged := mergeWebSearchEmulationDimensions(map[string]any{}, map[string]any{"other": 3}) + _, ok := merged[featureKeyWebSearchEmulation] + require.False(t, ok) + require.Equal(t, 3, merged["other"]) +} + +func TestMergeWebSearchEmulationDimensions_EmptyObjectMeansClear(t *testing.T) { + existing := map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"openai": true}, + } + merged := mergeWebSearchEmulationDimensions(existing, map[string]any{ + featureKeyWebSearchEmulation: map[string]any{}, + }) + dims, ok := merged[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok) + require.Empty(t, dims, "an explicit empty object must clear the value") +} + +func TestMergeWebSearchEmulationDimensions_NilIncoming(t *testing.T) { + require.Nil(t, mergeWebSearchEmulationDimensions(map[string]any{featureKeyWebSearchEmulation: map[string]any{"openai": true}}, nil)) +} + +// Wiring-level: the merge must be applied by applyUpdateInput. +func TestChannelService_ApplyUpdateInputMergesWebSearchEmulationDimensions(t *testing.T) { + svc := &ChannelService{} + channel := &Channel{ + FeaturesConfig: map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"anthropic": false, "openai": true, "command_code": true}, + }, + } + + require.NoError(t, svc.applyUpdateInput(context.Background(), channel, &UpdateChannelInput{ + FeaturesConfig: map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"anthropic": false}, + }, + })) + + dims, ok := channel.FeaturesConfig[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok) + require.Equal(t, false, dims["anthropic"]) + require.Equal(t, true, dims["openai"]) + require.Equal(t, true, dims["command_code"]) +} + +func TestChannelService_ApplyUpdateInputInheritsWebSearchEmulationWhenKeyAbsent(t *testing.T) { + svc := &ChannelService{} + channel := &Channel{ + FeaturesConfig: map[string]any{ + featureKeyWebSearchEmulation: map[string]any{"openai": true, "command_code": true}, + "bedrock_cc_compat": map[string]any{"anthropic": true}, + }, + } + + require.NoError(t, svc.applyUpdateInput(context.Background(), channel, &UpdateChannelInput{ + FeaturesConfig: map[string]any{ + "bedrock_cc_compat": map[string]any{"anthropic": false}, + }, + })) + + dims, ok := channel.FeaturesConfig[featureKeyWebSearchEmulation].(map[string]any) + require.True(t, ok) + require.Equal(t, true, dims["openai"]) + require.Equal(t, true, dims["command_code"]) + + // Other keys keep the historical whole-block replacement semantics. + bedrock, ok := channel.FeaturesConfig["bedrock_cc_compat"].(map[string]any) + require.True(t, ok) + require.Equal(t, false, bedrock["anthropic"]) +} diff --git a/backend/internal/service/custom_admin_key_accounts.go b/backend/internal/service/custom_admin_key_accounts.go index 91d5131f9c..5806cf5b51 100644 --- a/backend/internal/service/custom_admin_key_accounts.go +++ b/backend/internal/service/custom_admin_key_accounts.go @@ -18,7 +18,7 @@ import ( // ScopedAdminAccounts 只提供受限管理密钥需要的窄接口。 type ScopedAdminAccounts interface { - ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]Account, int64, error) + ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]Account, int64, error) ScopedAdminWrite(context.Context, int64, string, map[string]json.RawMessage, func(context.Context, *Account) (*Account, error)) (*Account, error) } @@ -45,6 +45,21 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo permission = "accounts.schedule" case "proxy_id", "proxy_mode", "random_proxy": permission = "accounts.network" + case "rate_multiplier": + var rate float64 + if string(raw) == "null" || json.Unmarshal(raw, &rate) != nil || rate < 0 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_RATE", "账户倍率无效") + } + permission = "accounts.rate.write" + case "extra": + if !create { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_FIELD", "仅创建支持身份与连接选项") + } + if err := validateScopedOpenAIOptions(raw); err != nil { + return nil, err + } + permissions = append(permissions, "accounts.options.write") + continue case "group_ids": permission = "accounts.groups" case "platform", "type": @@ -58,6 +73,23 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "凭证格式无效") } for name, value := range credentials { + if name == "expires_at" { + var expires int64 + if string(value) == "null" || json.Unmarshal(value, &expires) != nil || expires < 0 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "凭证到期时间无效") + } + permissions = append(permissions, "accounts.credentials") + continue + } + if slices.Contains([]string{"email", "chatgpt_account_id", "chatgpt_user_id", "organization_id", "plan_type", "subscription_expires_at", "client_id"}, name) { + var text string + if json.Unmarshal(value, &text) != nil || len(text) > 4096 { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "身份字段格式无效") + } + permissions = append(permissions, "accounts.credentials") + continue + } + // 白名单与映射共用 model_mapping,只授予模型配置写入权限。 if name == "model_mapping" { var mapping map[string]json.RawMessage @@ -90,7 +122,7 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo default: return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_FIELD", "请求包含不开放的账户字段") } - if !create || permission == "accounts.schedule" || permission == "accounts.network" { + if !create || permission == "accounts.schedule" || permission == "accounts.network" || permission == "accounts.rate.write" { permissions = append(permissions, permission) } else if key == "status" || key == "schedulable" { return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建不支持状态字段") @@ -99,14 +131,14 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo return permissions, nil } -func (s *adminServiceImpl) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string) ([]Account, int64, error) { +func (s *adminServiceImpl) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string, groupID int64) ([]Account, int64, error) { repo, ok := s.accountRepo.(interface { - ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]Account, int64, error) + ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]Account, int64, error) }) if !ok { return nil, 0, fmt.Errorf("受限账户查询不可用") } - return repo.ScopedAdminList(ctx, p, platform, kind, status, search) + return repo.ScopedAdminList(ctx, p, platform, kind, status, search, groupID) } func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, action string, fields map[string]json.RawMessage, run func(context.Context, *Account) (*Account, error)) (*Account, error) { @@ -123,20 +155,22 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio } if id == 0 { var input struct { - ProxyID *int64 `json:"proxy_id"` - ProxyMode string `json:"proxy_mode"` - RandomProxy bool `json:"random_proxy"` - Name string `json:"name"` - Notes *string `json:"notes"` - Platform string `json:"platform"` - Type string `json:"type"` - Credentials map[string]any `json:"credentials"` - GroupIDs []int64 `json:"group_ids"` - Concurrency int `json:"concurrency"` - Priority int `json:"priority"` - LoadFactor *int `json:"load_factor"` - ExpiresAt *int64 `json:"expires_at"` - AutoPause *bool `json:"auto_pause_on_expired"` + ProxyID *int64 `json:"proxy_id"` + ProxyMode string `json:"proxy_mode"` + RandomProxy bool `json:"random_proxy"` + Name string `json:"name"` + Notes *string `json:"notes"` + Extra map[string]any `json:"extra"` + Platform string `json:"platform"` + Type string `json:"type"` + Credentials map[string]any `json:"credentials"` + RateMultiplier *float64 `json:"rate_multiplier"` + GroupIDs []int64 `json:"group_ids"` + Concurrency int `json:"concurrency"` + Priority int `json:"priority"` + LoadFactor *int `json:"load_factor"` + ExpiresAt *int64 `json:"expires_at"` + AutoPause *bool `json:"auto_pause_on_expired"` } body, _ := json.Marshal(fields) if err = json.Unmarshal(body, &input); err != nil { @@ -151,6 +185,11 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio if !slices.Contains(domain.ConcretePlatformIDs(), input.Platform) || input.Concurrency < 0 || input.Priority < 0 { return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建参数无效") } + if input.Extra != nil && (input.Platform != PlatformOpenAI || input.Type != AccountTypeOAuth) { + return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_OPTIONS", "这些选项仅适用于 OpenAI OAuth") + } + // 隐私结果只能由服务端确认;空字符串同样会让 Ensure 跳过,必须删除键。 + delete(input.Extra, "privacy_mode") resource := adminaccess.Account{Type: input.Type, Platform: input.Platform, GroupIDs: input.GroupIDs} if input.Type == "" || input.Platform == "" || !principal.Policy.AllowsAccount("accounts.create", resource) { return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "创建范围未授权") @@ -170,7 +209,7 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio if e != nil { return nil, e } - return s.scopedAdminCreateTransaction(ctx, &CreateAccountInput{ProxyID: input.ProxyID, ProxyMode: proxyMode, Name: input.Name, Notes: input.Notes, Platform: input.Platform, Type: input.Type, Credentials: input.Credentials, GroupIDs: input.GroupIDs, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause, SkipDefaultGroupBind: true}) + return s.scopedAdminCreateTransaction(ctx, &CreateAccountInput{ProxyID: input.ProxyID, ProxyMode: proxyMode, Name: input.Name, Notes: input.Notes, Platform: input.Platform, Type: input.Type, Credentials: input.Credentials, Extra: input.Extra, RateMultiplier: input.RateMultiplier, GroupIDs: input.GroupIDs, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause, SkipDefaultGroupBind: true}) } result, err := s.scopedAdminTransaction(ctx, id, action == "accounts.delete", func(txctx context.Context) (*Account, error) { a, e := s.accountRepo.GetByID(txctx, id) @@ -221,20 +260,21 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio return s.ClearAccountError(txctx, id) } var input struct { - ProxyID *int64 `json:"proxy_id"` - ProxyMode string `json:"proxy_mode"` - RandomProxy bool `json:"random_proxy"` - Name string `json:"name"` - Notes *string `json:"notes"` - Credentials map[string]any `json:"credentials"` - Concurrency *int `json:"concurrency"` - Priority *int `json:"priority"` - LoadFactor *int `json:"load_factor"` - Status string `json:"status"` - GroupIDs *[]int64 `json:"group_ids"` - ExpiresAt *int64 `json:"expires_at"` - AutoPause *bool `json:"auto_pause_on_expired"` - Schedulable *bool `json:"schedulable"` + ProxyID *int64 `json:"proxy_id"` + ProxyMode string `json:"proxy_mode"` + RandomProxy bool `json:"random_proxy"` + Name string `json:"name"` + Notes *string `json:"notes"` + Credentials map[string]any `json:"credentials"` + RateMultiplier *float64 `json:"rate_multiplier"` + Concurrency *int `json:"concurrency"` + Priority *int `json:"priority"` + LoadFactor *int `json:"load_factor"` + Status string `json:"status"` + GroupIDs *[]int64 `json:"group_ids"` + ExpiresAt *int64 `json:"expires_at"` + AutoPause *bool `json:"auto_pause_on_expired"` + Schedulable *bool `json:"schedulable"` } body, _ := json.Marshal(fields) if e = json.Unmarshal(body, &input); e != nil { @@ -264,7 +304,7 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio maps.Copy(merged, input.Credentials) input.Credentials = merged } - updated, e := s.UpdateAccount(txctx, id, &UpdateAccountInput{ProxyID: input.ProxyID, Name: input.Name, Notes: input.Notes, Credentials: input.Credentials, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, Status: input.Status, GroupIDs: input.GroupIDs, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause}) + updated, e := s.UpdateAccount(txctx, id, &UpdateAccountInput{ProxyID: input.ProxyID, Name: input.Name, Notes: input.Notes, Credentials: input.Credentials, RateMultiplier: input.RateMultiplier, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, Status: input.Status, GroupIDs: input.GroupIDs, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause}) if e != nil { return nil, e } diff --git a/backend/internal/service/custom_admin_key_full_access_test.go b/backend/internal/service/custom_admin_key_full_access_test.go new file mode 100644 index 0000000000..2dc30041af --- /dev/null +++ b/backend/internal/service/custom_admin_key_full_access_test.go @@ -0,0 +1,88 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func fullAccessInput(t *testing.T, confirm bool) ScopedAdminKeyInput { + t.Helper() + var input ScopedAdminKeyInput + data := `{"name":"兼容工具","enabled":true,"policy":{"full_access":true},"confirm_full_access":false}` + if confirm { + data = `{"name":"兼容工具","enabled":true,"policy":{"full_access":true},"confirm_full_access":true}` + } + require.NoError(t, json.Unmarshal([]byte(data), &input)) + return input +} + +func TestAdminFullAccessRequiresExplicitConfirmation(t *testing.T) { + s := &SettingService{scopedAdminKeyRepo: &scopedKeyMemoryRepo{}} + ctx := context.Background() + _, _, err := s.CreateScopedAdminKey(ctx, fullAccessInput(t, false), 9) + require.Error(t, err, "新建全权密钥必须显式确认") + _, item, err := s.CreateScopedAdminKey(ctx, ScopedAdminKeyInput{Name: "受限", Enabled: true}, 9) + require.NoError(t, err) + _, err = s.UpdateScopedAdminKey(ctx, item.ID, fullAccessInput(t, false)) + require.Error(t, err, "受限密钥升级必须显式确认") +} + +func TestAdminFullAccessConfirmationIsNotPersisted(t *testing.T) { + repo := &scopedKeyMemoryRepo{} + s := &SettingService{scopedAdminKeyRepo: repo} + ctx := context.Background() + key, item, err := s.CreateScopedAdminKey(ctx, fullAccessInput(t, true), 9) + require.NoError(t, err) + raw, err := json.Marshal(item) + require.NoError(t, err) + require.Contains(t, string(raw), `"full_access":true`) + require.NotContains(t, string(raw), `"confirm_full_access":true`) + _, err = s.UpdateScopedAdminKey(ctx, item.ID, fullAccessInput(t, false)) + require.NoError(t, err, "不扩权的编辑不需要再次确认") + restricted := ScopedAdminKeyInput{Name: "关闭兼容", Enabled: true} + _, err = s.UpdateScopedAdminKey(ctx, item.ID, restricted) + require.NoError(t, err) + _, err = s.UpdateScopedAdminKey(ctx, item.ID, fullAccessInput(t, false)) + require.Error(t, err, "再次开启仍需确认") + authenticated, err := s.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1") + require.NoError(t, err) + raw, err = json.Marshal(authenticated.Policy) + require.NoError(t, err) + require.NotContains(t, string(raw), `"full_access":true`) +} + +func TestAdminFullAccessLifecycleRestrictions(t *testing.T) { + repo := &scopedKeyMemoryRepo{} + s := &SettingService{scopedAdminKeyRepo: repo} + ctx := context.Background() + in := fullAccessInput(t, true) + in.AllowedIPs = []string{"192.0.2.0/24"} + key, item, err := s.CreateScopedAdminKey(ctx, in, 9) + require.NoError(t, err) + _, err = s.AuthenticateScopedAdminKey(ctx, key, "198.51.100.1") + require.Error(t, err) + next, _, err := s.RotateScopedAdminKey(ctx, item.ID) + require.NoError(t, err) + _, err = s.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1") + require.Error(t, err) + _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1") + require.NoError(t, err) + repo.item.Enabled = false + _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1") + require.Error(t, err) + repo.item.Enabled = true + past := time.Now().Add(-time.Hour) + repo.item.ExpiresAt = &past + _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1") + require.Error(t, err) + repo.item.ExpiresAt = nil + require.NoError(t, s.RevokeScopedAdminKey(ctx, item.ID)) + _, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1") + require.Error(t, err) +} diff --git a/backend/internal/service/custom_admin_key_openai_options.go b/backend/internal/service/custom_admin_key_openai_options.go new file mode 100644 index 0000000000..f23cfd5504 --- /dev/null +++ b/backend/internal/service/custom_admin_key_openai_options.go @@ -0,0 +1,40 @@ +package service + +import ( + "encoding/json" + "slices" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// 只接受对接客户端实际需要的字段,不能写入额度快照、任意 extra 或影子关系。 +func validateScopedOpenAIOptions(raw json.RawMessage) error { + var fields map[string]json.RawMessage + invalid := infraerrors.BadRequest("SCOPED_ACCOUNT_OPTIONS", "身份与连接选项格式无效或包含不支持的字段") + if json.Unmarshal(raw, &fields) != nil || len(fields) == 0 { + return invalid + } + for key, value := range fields { + var text string + var flag bool + switch key { + case "email", "privacy_mode": + // privacy_mode 仅兼容旧客户端入参,创建前会移除,服务端仍独立核验。 + if string(value) == "null" || json.Unmarshal(value, &text) != nil || len(text) > 512 { + return invalid + } + case "openai_oauth_responses_websockets_v2_mode": + if json.Unmarshal(value, &text) != nil || !slices.Contains([]string{"off", "shared", "dedicated", "ctx_pool", "passthrough", "http_bridge"}, text) { + return invalid + } + + case "openai_oauth_responses_websockets_v2_enabled", "openai_long_context_billing_enabled": + if string(value) == "null" || json.Unmarshal(value, &flag) != nil { + return invalid + } + default: + return invalid + } + } + return nil +} diff --git a/backend/internal/service/custom_admin_key_permissions_test.go b/backend/internal/service/custom_admin_key_permissions_test.go new file mode 100644 index 0000000000..4eaf87e6a1 --- /dev/null +++ b/backend/internal/service/custom_admin_key_permissions_test.go @@ -0,0 +1,158 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +func TestScopedAdminPermissionFieldClassification(t *testing.T) { + for _, tc := range []struct { + body string + want []string + }{ + {`{"extra":{"email":"test@example.com","openai_oauth_responses_websockets_v2_enabled":false,"openai_oauth_responses_websockets_v2_mode":"off","openai_long_context_billing_enabled":false}}`, []string{"accounts.options.write"}}, + {`{"rate_multiplier":0.5}`, []string{"accounts.rate.write"}}, + {`{"credentials":{"expires_at":2000000000,"email":"test@example.com","plan_type":"plus"}}`, []string{"accounts.credentials", "accounts.credentials", "accounts.credentials"}}, + } { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(tc.body), &fields)) + got, err := scopedAccountFieldPermissions(fields, true) + require.NoError(t, err) + require.ElementsMatch(t, tc.want, got) + } +} + +func TestScopedAdminPermissionRejectsUnlistedOptions(t *testing.T) { + for _, body := range []string{`{"extra":{"codex_7d_used_percent":100}}`, `{"extra":{"openai_timezone_mode":"fixed"}}`, `{"extra":{"secret":"x"}}`, `{"extra":{"openai_long_context_billing_enabled":null}}`, `{"extra":{"openai_oauth_responses_websockets_v2_mode":null}}`, `{"rate_multiplier":-1}`, `{"rate_multiplier":null}`} { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(body), &fields)) + _, err := scopedAccountFieldPermissions(fields, true) + require.Error(t, err, body) + } +} + +type scopedPermissionsCapacityGroups struct{ groupCapacityGroupRepoStub } + +func (*scopedPermissionsCapacityGroups) ListScopedAdminCapacityGroupIDs(context.Context) ([]int64, error) { + return []int64{2}, nil +} +func TestScopedAdminPermissionCapacityScopesBeforeAggregation(t *testing.T) { + groups := &scopedPermissionsCapacityGroups{groupCapacityGroupRepoStub{groupIDs: []int64{1, 2, 3}}} + accounts := &groupCapacityAccountRepoStub{} + svc := NewGroupCapacityService(accounts, groups, nil, nil, nil) + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{}) + result, err := svc.GetAllGroupCapacity(ctx) + require.NoError(t, err) + require.Equal(t, []int64{2}, accounts.requested) + require.Equal(t, []GroupCapacitySummary{{GroupID: 2}}, result) + require.Zero(t, groups.listCalls) + svc.groupRepo = &groupCapacityGroupRepoStub{} + _, err = svc.GetAllGroupCapacity(ctx) + require.Error(t, err) +} + +type scopedPermissionCreationRepo struct{ AccountRepository } + +func (*scopedPermissionCreationRepo) Create(_ context.Context, a *Account) error { + a.ID = 1 + return nil +} +func TestScopedAdminPermissionCreateAuthorizesEveryField(t *testing.T) { + permissions := []string{"accounts.create", "accounts.credentials", "accounts.options.write", "accounts.rate.write", "accounts.schedule"} + for _, missing := range append([]string{""}, permissions...) { + t.Run(missing, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + if missing == "" { + mock.ExpectBegin() + mock.ExpectCommit() + } + svc := &adminServiceImpl{accountRepo: &scopedPermissionCreationRepo{}, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + granted := []string{} + for _, permission := range permissions { + if permission != missing { + granted = append(granted, permission) + } + } + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: granted, IncludeUngrouped: true, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}}) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"name":"授权创建","platform":"openai","type":"oauth","group_ids":[],"credentials":{"access_token":"test","refresh_token":"test","expires_at":2000000000,"email":"test@example.com","plan_type":"plus"},"extra":{"email":"test@example.com","openai_oauth_responses_websockets_v2_enabled":false,"openai_oauth_responses_websockets_v2_mode":"off","openai_long_context_billing_enabled":false},"rate_multiplier":0.5,"concurrency":20,"priority":1,"expires_at":null,"auto_pause_on_expired":true}`), &fields)) + a, err := svc.ScopedAdminWrite(ctx, 0, "", fields, nil) + if missing != "" { + require.Equal(t, 403, infraerrors.Code(err)) + } else { + require.NoError(t, err) + require.Equal(t, 0.5, *a.RateMultiplier) + require.Equal(t, "test@example.com", a.Credentials["email"]) + require.Equal(t, "test@example.com", a.Extra["email"]) + require.NotContains(t, a.Extra, "privacy_mode") + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} + +type scopedPrivacyCreationRepo struct { + scopedPermissionCreationRepo + capturedExtra map[string]any + capturedSkip bool + capturedPrivacySet bool +} + +func (r *scopedPrivacyCreationRepo) Create(ctx context.Context, a *Account) error { + r.capturedExtra = map[string]any{} + for key, value := range a.Extra { + r.capturedExtra[key] = value + } + r.capturedSkip = shouldSkipOpenAIPrivacyEnsure(a.Extra) + r.capturedPrivacySet = a.IsPrivacySet() + return r.scopedPermissionCreationRepo.Create(ctx, a) +} +func TestScopedAdminPrivacyCompatibilityIgnoresCallerStateBeforeCreate(t *testing.T) { + for _, mode := range []string{"training_off", "training_disabled", "training_set_failed", "unknown", ""} { + t.Run(mode, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer db.Close() + mock.ExpectBegin() + mock.ExpectCommit() + repo := &scopedPrivacyCreationRepo{} + svc := &adminServiceImpl{accountRepo: repo, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))} + ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.options.write"}, IncludeUngrouped: true, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}}) + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"name":"兼容隐私入参","platform":"openai","type":"oauth","group_ids":[],"credentials":{"access_token":"test"}}`), &fields)) + fields["extra"], err = json.Marshal(map[string]any{"privacy_mode": mode, "email": "test@example.com"}) + require.NoError(t, err) + account, err := svc.ScopedAdminWrite(ctx, 0, "", fields, nil) + require.NoError(t, err) + require.Equal(t, "test@example.com", repo.capturedExtra["email"]) + require.NotContains(t, repo.capturedExtra, "privacy_mode", "持久化前必须删除隐私状态键,空字符串同样不能残留") + require.False(t, repo.capturedSkip, "调用方隐私值不能阻止服务端 Ensure") + require.False(t, repo.capturedPrivacySet) + require.NotContains(t, account.Extra, "privacy_mode") + require.False(t, account.IsPrivacySet()) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} +func TestScopedAdminPrivacyCompatibilityRejectsInvalidTypes(t *testing.T) { + for _, value := range []string{`null`, `true`, `1`, `[]`, `{}`, `"` + strings.Repeat("x", 513) + `"`} { + var fields map[string]json.RawMessage + require.NoError(t, json.Unmarshal([]byte(`{"extra":{"privacy_mode":`+value+`}}`), &fields)) + _, err := scopedAccountFieldPermissions(fields, true) + require.Equal(t, 400, infraerrors.Code(err), value) + } +} diff --git a/backend/internal/service/custom_admin_key_statistics.go b/backend/internal/service/custom_admin_key_statistics.go new file mode 100644 index 0000000000..baf17ba87d --- /dev/null +++ b/backend/internal/service/custom_admin_key_statistics.go @@ -0,0 +1,56 @@ +package service + +import ( + "context" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +type scopedAccountOperationKey struct{} + +// WithScopedAdminAccountOperation 仅供已完成动作验权的处理器传递同一操作的后续查询。 +// 例如重置后的额度刷新仍属于重置操作,不要求额外授予读取权限。 +func WithScopedAdminAccountOperation(ctx context.Context, action string) context.Context { + return context.WithValue(ctx, scopedAccountOperationKey{}, action) +} +func scopedAccountOperation(ctx context.Context, fallback string) string { + if action, ok := ctx.Value(scopedAccountOperationKey{}).(string); ok && action != "" { + return action + } + return fallback +} + +func scopedAccountAccess(ctx context.Context, repo AccountRepository, a *Account, action string, parent bool) error { + p := adminaccess.RestrictedFromContext(ctx) + if p == nil { + return nil + } + denied := func() error { return infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") } + if a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) { + return denied() + } + if parent && a.IsShadow() { + if repo == nil || a.ParentAccountID == nil || *a.ParentAccountID == a.ID { + return denied() + } + source, err := repo.GetByID(ctx, *a.ParentAccountID) + if err != nil || source == nil || source.IsShadow() || !p.Policy.AllowsAccount(action, scopedAccountResource(source)) { + return denied() + } + } + return nil +} +func scopedAccountIDAccess(ctx context.Context, repo AccountRepository, id int64, action string, parent bool) error { + if adminaccess.RestrictedFromContext(ctx) == nil { + return nil + } + if repo == nil { + return infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + a, err := repo.GetByID(ctx, id) + if err != nil { + return infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } + return scopedAccountAccess(ctx, repo, a, action, parent) +} diff --git a/backend/internal/service/custom_admin_key_statistics_test.go b/backend/internal/service/custom_admin_key_statistics_test.go new file mode 100644 index 0000000000..803734faa7 --- /dev/null +++ b/backend/internal/service/custom_admin_key_statistics_test.go @@ -0,0 +1,295 @@ +//go:build unit + +package service + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "testing/synctest" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + httppool "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/stretchr/testify/require" +) + +func scopedStatisticsServiceContext(action string) context.Context { + return adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{action}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}}) +} +func TestScopedAdminUsageServiceRechecksScopeBeforeSnapshot(t *testing.T) { + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}, Extra: map[string]any{"codex_5h_used_percent": 25.0}} + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}} + svc := &AccountUsageService{accountRepo: repo} + u, err := svc.getUsageForAccount(scopedStatisticsServiceContext("accounts.usage.read"), a, false) + require.Nil(t, u) + require.Equal(t, 404, infraerrors.Code(err)) +} +func TestScopedAdminReferralServiceChecksScopeBeforeResolvingParent(t *testing.T) { + parentID := int64(2) + shadow := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, ParentAccountID: &parentID} + parent := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}} + svc := &OpenAIQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: shadow, 2: parent}}} + a, err := svc.referralAccount(scopedStatisticsServiceContext("openai.referrals.read"), 1, false) + require.Nil(t, a) + require.Equal(t, 404, infraerrors.Code(err)) +} + +func TestScopedAdminQuotaCacheWriteRechecksScope(t *testing.T) { + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}} + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}} + svc := &OpenAIQuotaService{accountRepo: repo} + err := svc.CacheCreditsSnapshot(scopedStatisticsServiceContext("openai.quota.read"), 1, &OpenAIQuotaUsage{}) + require.Equal(t, 404, infraerrors.Code(err)) + require.Zero(t, repo.extraUpdateCalls) +} + +type scopedUsageRecoveryRepo struct { + stubQuotaAccountRepo + clears int +} + +func (r *scopedUsageRecoveryRepo) ClearError(context.Context, int64) error { r.clears++; return nil } + +func TestScopedAdminUsageReadDoesNotRecoverAccount(t *testing.T) { + for _, platform := range []string{PlatformGemini, PlatformAnthropic} { + t.Run(platform, func(t *testing.T) { + a := &Account{ID: 1, Platform: platform, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Status: StatusError, ErrorMessage: "unauthenticated", Credentials: map[string]any{"access_token": "token", "scope": "user:profile"}} + repo := &scopedUsageRecoveryRepo{stubQuotaAccountRepo: stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}} + cache := NewUsageCache() + cache.apiCache.Store(int64(1), &apiUsageCache{response: &ClaudeUsageResponse{}, timestamp: time.Now()}) + svc := &AccountUsageService{accountRepo: repo, usageLogRepo: &usageBatchLogRepoStub{}, cache: cache} + ctx := scopedStatisticsServiceContext("accounts.usage.read") + adminaccess.FromContext(ctx).Policy.Rules[0].Platforms = []string{platform} + _, err := svc.getUsageForAccount(ctx, a, false) + require.NoError(t, err) + require.Zero(t, repo.clears) + require.Equal(t, StatusError, a.Status) + }) + } +} + +type scopedStatisticsBatchRepo struct{ stubQuotaAccountRepo } + +func (r *scopedStatisticsBatchRepo) GetByIDs(ctx context.Context, ids []int64) ([]*Account, error) { + out := []*Account{} + for _, id := range ids { + a, err := r.GetByID(ctx, id) + if err != nil { + continue + } + out = append(out, a) + } + return out, nil +} + +type scopedStatisticsLogRepo struct { + usageBatchLogRepoStub + reads int +} + +func (r *scopedStatisticsLogRepo) GetAccountTodayStats(context.Context, int64) (*usagestats.AccountStats, error) { + r.reads++ + return &usagestats.AccountStats{Cost: 23}, nil +} +func (r *scopedStatisticsLogRepo) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) { + r.reads++ + return &usagestats.AccountStats{Cost: 23}, nil +} + +func TestScopedAdminBatchRejectsWholeRequestBeforeData(t *testing.T) { + for _, action := range []string{"accounts.usage.read", "accounts.stats.read"} { + for _, id := range []int64{2, 3} { + t.Run(fmt.Sprintf("%s/id=%d", action, id), func(t *testing.T) { + repo := &scopedStatisticsBatchRepo{stubQuotaAccountRepo: stubQuotaAccountRepo{accounts: map[int64]*Account{1: {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}}, 2: {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}}}}} + logs := &scopedStatisticsLogRepo{} + svc := &AccountUsageService{accountRepo: repo, usageLogRepo: logs, cache: NewUsageCache()} + ctx := scopedStatisticsServiceContext(action) + var err error + if action == "accounts.usage.read" { + _, _, err = svc.GetUsageBatch(ctx, []int64{1, id}, true) + } else { + _, err = svc.GetTodayStatsBatch(ctx, []int64{1, id}) + } + require.Equal(t, 404, infraerrors.Code(err)) + require.Zero(t, logs.reads) + require.Zero(t, repo.extraUpdateCalls) + }) + } + } +} + +func TestScopedAdminSnapshotWriteDoesNotNotifyAutomaticReset(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}} + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}} + svc := &AccountUsageService{accountRepo: repo} + notifier := NewOpenAIQuotaAutoResetService(nil, nil, nil, nil, nil, nil, nil) + openAIAutoResetNotifierRegistry.Lock() + previous := openAIAutoResetNotifierRegistry.service + openAIAutoResetNotifierRegistry.service = notifier + openAIAutoResetNotifierRegistry.Unlock() + defer func() { + openAIAutoResetNotifierRegistry.Lock() + openAIAutoResetNotifierRegistry.service = previous + openAIAutoResetNotifierRegistry.Unlock() + notifier.cancel() + }() + svc.persistOpenAICodexProbeSnapshotContext(scopedStatisticsServiceContext("accounts.usage.read"), 1, map[string]any{"codex_5h_used_percent": 25.0}) + synctest.Wait() + require.Equal(t, 1, repo.extraUpdateCalls) + require.Empty(t, notifier.queue) + }) +} + +func TestScopedAdminQuotaHeaderReloadRechecksScope(t *testing.T) { + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}} + svc := &OpenAIQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}} + headers, _, err := svc.buildCodexQuotaHeaders(scopedStatisticsServiceContext("openai.quota.read"), 1, "token", "upstream-id", false) + require.Nil(t, headers) + require.Equal(t, 404, infraerrors.Code(err)) +} + +func TestScopedAdminGrokQuotaReloadRechecksScope(t *testing.T) { + a := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth, GroupIDs: []int64{2}} + svc := &GrokQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}} + ctx := scopedStatisticsServiceContext("accounts.usage.read") + adminaccess.FromContext(ctx).Policy.Rules[0].Platforms = []string{PlatformGrok} + account, err := svc.loadGrokOAuthAccount(ctx, 1) + require.Nil(t, account) + require.Equal(t, 404, infraerrors.Code(err)) +} + +func TestScopedAdminGrokBillingChecksScopeBeforeJoiningFlight(t *testing.T) { + a := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth, GroupIDs: []int64{2}} + svc := &GrokQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}} + ctx := scopedStatisticsServiceContext("accounts.usage.read") + adminaccess.FromContext(ctx).Policy.Rules[0].Platforms = []string{PlatformGrok} + result, err := svc.ProbeBilling(ctx, 1) + require.Nil(t, result) + require.Equal(t, 404, infraerrors.Code(err)) +} +func TestScopedAdminGrokSharedFlightPreservesPrincipal(t *testing.T) { + svc := &GrokQuotaService{} + ctx := scopedStatisticsServiceContext("accounts.usage.read") + _, err := svc.runProbeFlight(ctx, "context", func(shared context.Context) (*GrokQuotaProbeResult, error) { + if adminaccess.FromContext(ctx) != adminaccess.FromContext(shared) { + return nil, fmt.Errorf("共享任务丢失授权身份") + } + return &GrokQuotaProbeResult{}, nil + }) + require.NoError(t, err) +} + +type scopedQuotaParentDisappears struct { + AccountRepository + shadow, parent *Account + parentReads int +} + +func (r *scopedQuotaParentDisappears) GetByID(_ context.Context, id int64) (*Account, error) { + if id == r.shadow.ID { + return r.shadow, nil + } + r.parentReads++ + if r.parentReads == 1 { + return r.parent, nil + } + return nil, fmt.Errorf("母账户读取失败") +} +func TestScopedAdminQuotaHeaderParentResolveFailureFailsClosed(t *testing.T) { + parentID := int64(2) + repo := &scopedQuotaParentDisappears{shadow: &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, ParentAccountID: &parentID}, parent: &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}}} + svc := &OpenAIQuotaService{accountRepo: repo} + headers, _, err := svc.buildCodexQuotaHeaders(scopedStatisticsServiceContext("openai.quota.read"), 1, "old-token", "old-account-id", false) + require.Nil(t, headers) + require.Equal(t, 404, infraerrors.Code(err)) +} + +type scopedUsageRoundTripper func(*http.Request) (*http.Response, error) + +func (f scopedUsageRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestScopedAdminOpenAIUsageRefreshNeverGeneratesModelRequests(t *testing.T) { + for _, tc := range []struct { + name string + restricted, shadow, full bool + wantModel int + wantUsage float64 + }{ + {"受限普通账户", true, false, false, 0, 37}, {"受限影子账户", true, true, false, 0, 67}, + {"JWT普通账户", false, false, false, 1, 98}, {"全权密钥普通账户", false, false, true, 1, 98}, + } { + t.Run(tc.name, func(t *testing.T) { + parentID := int64(2) + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Credentials: map[string]any{"access_token": "test-token", "chatgpt_account_id": "test-account"}} + parent := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Credentials: a.Credentials} + if tc.shadow { + a.ParentAccountID = &parentID + a.QuotaDimension = QuotaDimensionSpark + } + updates := make(chan map[string]any, 1) + repo := &sparkShadowUsageTestRepo{accounts: map[int64]*Account{1: a, 2: parent}, updateExtraCh: updates} + var quotaCalls, nonReadCalls int + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + nonReadCalls++ + } + if strings.HasSuffix(r.URL.Path, "/usage") { + quotaCalls++ + } + w.Header().Set("Content-Type", "application/json") + if !strings.HasSuffix(r.URL.Path, "/usage") { + _, _ = w.Write([]byte(`[]`)) + return + } + _, _ = w.Write([]byte(`{"rate_limit":{"primary_window":{"used_percent":37,"limit_window_seconds":18000,"reset_after_seconds":3600}},"additional_rate_limits":[{"metered_feature":"codex_bengalfox","rate_limit":{"primary_window":{"used_percent":67,"limit_window_seconds":18000,"reset_after_seconds":3600}}}],"rate_limit_reset_credits":{"available_count":0}}`)) + })) + defer upstream.Close() + quota := NewOpenAIQuotaService(repo, nil, NewOpenAITokenProvider(repo, nil, nil), newQuotaRedirectingFactory(upstream), nil) + client, err := httppool.GetClient(httppool.Options{Timeout: 15 * time.Second, ResponseHeaderTimeout: 10 * time.Second}) + require.NoError(t, err) + previous := client.Transport + defer func() { client.Transport = previous }() + modelCalls := 0 + client.Transport = scopedUsageRoundTripper(func(r *http.Request) (*http.Response, error) { + modelCalls++ + headers := make(http.Header) + headers.Set("x-codex-primary-used-percent", "98") + headers.Set("x-codex-primary-window-minutes", "300") + headers.Set("x-codex-primary-reset-after-seconds", "3600") + return &http.Response{StatusCode: 200, Header: headers, Body: io.NopCloser(strings.NewReader(""))}, nil + }) + svc := &AccountUsageService{accountRepo: repo, openAIQuotaService: quota, cache: NewUsageCache()} + ctx := context.Background() + if tc.restricted { + ctx = scopedStatisticsServiceContext("accounts.usage.read") + } + if tc.full { + ctx = adminaccess.WithPrincipal(ctx, &adminaccess.Principal{Policy: adminaccess.Policy{FullAccess: true}}) + } + usage, err := svc.GetUsageForAccount(ctx, a, true) + require.NoError(t, err) + require.Equal(t, tc.wantModel, modelCalls, "读取额度不能合成模型消费请求") + if tc.restricted { + require.Equal(t, 1, quotaCalls) + require.Zero(t, nonReadCalls) + } else { + require.Zero(t, quotaCalls) + } + require.NotNil(t, usage.FiveHour) + require.Equal(t, tc.wantUsage, usage.FiveHour.Utilization) + select { + case <-updates: + case <-time.After(time.Second): + t.Fatal("展示快照未写入") + } + }) + } +} diff --git a/backend/internal/service/custom_admin_keys.go b/backend/internal/service/custom_admin_keys.go index f11c31711b..dd63a16af8 100644 --- a/backend/internal/service/custom_admin_keys.go +++ b/backend/internal/service/custom_admin_keys.go @@ -20,24 +20,27 @@ var ErrScopedAdminKeyConflict = infraerrors.Conflict("ADMIN_KEY_CONFLICT", "密 var ErrScopedAdminKeyNotFound = infraerrors.NotFound("ADMIN_KEY_NOT_FOUND", "Admin key not found") type ScopedAdminKeyInput struct { - Name string `json:"name"` - Description string `json:"description"` - Enabled bool `json:"enabled"` - ExpiresAt *time.Time `json:"expires_at"` - AllowedIPs []string `json:"allowed_ips"` - Policy adminaccess.Policy `json:"policy"` + ConfirmFullAccess bool `json:"confirm_full_access,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Enabled bool `json:"enabled"` + ExpiresAt *time.Time `json:"expires_at"` + AllowedIPs []string `json:"allowed_ips"` + Policy adminaccess.Policy `json:"policy"` } type ScopedAdminKey struct { ScopedAdminKeyInput - ID string `json:"id"` - KeyPrefix string `json:"key_prefix"` - Hash string `json:"-"` - CreatedBy int64 `json:"created_by"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - LastUsedAt *time.Time `json:"last_used_at"` - LastUsedIP string `json:"last_used_ip"` - RevokedAt *time.Time `json:"revoked_at"` + PreviousFullAccess bool `json:"-"` + ExpectedUpdatedAt time.Time `json:"-"` + ID string `json:"id"` + KeyPrefix string `json:"key_prefix"` + Hash string `json:"-"` + CreatedBy int64 `json:"created_by"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` + LastUsedAt *time.Time `json:"last_used_at"` + LastUsedIP string `json:"last_used_ip"` + RevokedAt *time.Time `json:"revoked_at"` } type ScopedAdminKeyRepository interface { ListScopedAdminKeys(context.Context) ([]*ScopedAdminKey, error) @@ -126,6 +129,10 @@ func (s *SettingService) ListScopedAdminKeys(ctx context.Context) ([]*ScopedAdmi return r.ListScopedAdminKeys(ctx) } func (s *SettingService) CreateScopedAdminKey(ctx context.Context, in ScopedAdminKeyInput, creator int64) (string, *ScopedAdminKey, error) { + if in.Policy.FullAccess && !in.ConfirmFullAccess { + return "", nil, infraerrors.BadRequest("ADMIN_KEY_FULL_ACCESS_CONFIRMATION_REQUIRED", "开启全权访问需要显式确认") + } + in.ConfirmFullAccess = false if e := validateScopedAdminKeyInput(&in); e != nil { return "", nil, e } @@ -161,9 +168,15 @@ func (s *SettingService) UpdateScopedAdminKey(ctx context.Context, id string, in if item.RevokedAt != nil { return nil, ErrScopedAdminKeyNotFound } + if in.Policy.FullAccess && !item.Policy.FullAccess && !in.ConfirmFullAccess { + return nil, infraerrors.BadRequest("ADMIN_KEY_FULL_ACCESS_CONFIRMATION_REQUIRED", "开启全权访问需要显式确认") + } + in.ConfirmFullAccess = false if e := validateScopedAdminKeyInputForUpdate(&in, item.ExpiresAt); e != nil { return nil, e } + item.PreviousFullAccess = item.Policy.FullAccess + item.ExpectedUpdatedAt = item.UpdatedAt item.ScopedAdminKeyInput = in item.UpdatedAt = time.Now().UTC() if e = r.UpdateScopedAdminKey(ctx, item); e != nil { diff --git a/backend/internal/service/digest_session_store.go b/backend/internal/service/digest_session_store.go index 3ac0893689..30a1c7f626 100644 --- a/backend/internal/service/digest_session_store.go +++ b/backend/internal/service/digest_session_store.go @@ -4,8 +4,6 @@ import ( "strconv" "strings" "time" - - gocache "github.com/patrickmn/go-cache" ) // digestSessionTTL 摘要会话默认 TTL @@ -15,52 +13,61 @@ const digestSessionTTL = 5 * time.Minute type sessionEntry struct { uuid string accountID int64 + expiresAt time.Time } -// DigestSessionStore 内存摘要会话存储(flat cache 实现) +func (e *sessionEntry) sessionExpiresAt() time.Time { return e.expiresAt } +func (e *sessionEntry) sessionCost() int { return len(e.uuid) } +func (e *sessionEntry) cloneSessionValue() sessionMemoryValue { + cloned := *e + cloned.uuid = strings.Clone(e.uuid) + return &cloned +} + +// DigestSessionStore 内存摘要会话存储(有界 TTL 缓存,增量摘要索引) // key: "{groupID}:{prefixHash}|{digestChain}" → *sessionEntry type DigestSessionStore struct { - cache *gocache.Cache + cache sessionMemoryCache + ttl time.Duration } // NewDigestSessionStore 创建内存摘要会话存储 func NewDigestSessionStore() *DigestSessionStore { return &DigestSessionStore{ - cache: gocache.New(digestSessionTTL, time.Minute), + ttl: digestSessionTTL, } } +func (s *DigestSessionStore) Close() { s.cache.Close() } + // Save 保存摘要会话。oldDigestChain 为 Find 返回的 matchedChain,用于删旧 key。 func (s *DigestSessionStore) Save(groupID int64, prefixHash, digestChain, uuid string, accountID int64, oldDigestChain string) { if digestChain == "" { return } ns := buildNS(groupID, prefixHash) - s.cache.Set(ns+digestChain, &sessionEntry{uuid: uuid, accountID: accountID}, gocache.DefaultExpiration) + ttl := s.ttl + if ttl <= 0 { + ttl = digestSessionTTL + } + s.cache.Store(ns+digestChain, &sessionEntry{uuid: uuid, accountID: accountID, expiresAt: time.Now().Add(ttl)}) if oldDigestChain != "" && oldDigestChain != digestChain { s.cache.Delete(ns + oldDigestChain) } } -// Find 查找摘要会话,从完整 chain 逐段截断,返回最长匹配及对应 matchedChain。 +// Find 查找摘要会话,在消息边界上返回最长匹配及对应 matchedChain。 func (s *DigestSessionStore) Find(groupID int64, prefixHash, digestChain string) (uuid string, accountID int64, matchedChain string, found bool) { if digestChain == "" { return "", 0, "", false } ns := buildNS(groupID, prefixHash) - chain := digestChain - for { - if val, ok := s.cache.Get(ns + chain); ok { - if e, ok := val.(*sessionEntry); ok { - return e.uuid, e.accountID, chain, true - } + if val, chain, ok := s.cache.longestDigestPrefix(ns, digestChain); ok { + if e, ok := val.(*sessionEntry); ok { + return e.uuid, e.accountID, chain, true } - i := strings.LastIndex(chain, "-") - if i < 0 { - return "", 0, "", false - } - chain = chain[:i] } + return "", 0, "", false } // buildNS 构建 namespace 前缀 diff --git a/backend/internal/service/digest_session_store_test.go b/backend/internal/service/digest_session_store_test.go index e505bf30be..f1d5b96a4c 100644 --- a/backend/internal/service/digest_session_store_test.go +++ b/backend/internal/service/digest_session_store_test.go @@ -8,13 +8,13 @@ import ( "testing" "time" - gocache "github.com/patrickmn/go-cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDigestSessionStore_SaveAndFind(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "s:a1-u:b2-m:c3", "uuid-1", 100, "") @@ -26,6 +26,7 @@ func TestDigestSessionStore_SaveAndFind(t *testing.T) { func TestDigestSessionStore_PrefixMatch(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 保存短链 store.Save(1, "prefix", "u:a-m:b", "uuid-short", 10, "") @@ -40,6 +41,7 @@ func TestDigestSessionStore_PrefixMatch(t *testing.T) { func TestDigestSessionStore_LongestPrefixMatch(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a", "uuid-1", 1, "") store.Save(1, "prefix", "u:a-m:b", "uuid-2", 2, "") @@ -60,6 +62,7 @@ func TestDigestSessionStore_LongestPrefixMatch(t *testing.T) { func TestDigestSessionStore_SaveDeletesOldChain(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 第一轮:保存 "u:a-m:b" store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -80,6 +83,7 @@ func TestDigestSessionStore_SaveDeletesOldChain(t *testing.T) { func TestDigestSessionStore_DifferentSessionsNoInterference(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 相同系统提示词,不同用户提示词 store.Save(1, "prefix", "s:sys-u:user1", "uuid-1", 100, "") @@ -98,6 +102,7 @@ func TestDigestSessionStore_DifferentSessionsNoInterference(t *testing.T) { func TestDigestSessionStore_NoMatch(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -108,6 +113,7 @@ func TestDigestSessionStore_NoMatch(t *testing.T) { func TestDigestSessionStore_DifferentPrefixHash(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix1", "u:a-m:b", "uuid-1", 100, "") @@ -118,6 +124,7 @@ func TestDigestSessionStore_DifferentPrefixHash(t *testing.T) { func TestDigestSessionStore_DifferentGroupID(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -128,6 +135,7 @@ func TestDigestSessionStore_DifferentGroupID(t *testing.T) { func TestDigestSessionStore_EmptyDigestChain(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 空链不应保存 store.Save(1, "prefix", "", "uuid-1", 100, "") @@ -137,8 +145,10 @@ func TestDigestSessionStore_EmptyDigestChain(t *testing.T) { func TestDigestSessionStore_TTLExpiration(t *testing.T) { store := &DigestSessionStore{ - cache: gocache.New(100*time.Millisecond, 50*time.Millisecond), + cache: sessionMemoryCache{sweep: 50 * time.Millisecond}, + ttl: 100 * time.Millisecond, } + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") @@ -156,6 +166,7 @@ func TestDigestSessionStore_TTLExpiration(t *testing.T) { func TestDigestSessionStore_ConcurrentSafety(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) var wg sync.WaitGroup const goroutines = 50 @@ -179,6 +190,7 @@ func TestDigestSessionStore_ConcurrentSafety(t *testing.T) { func TestDigestSessionStore_MultipleSessions(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) sessions := []struct { chain string @@ -211,6 +223,7 @@ func TestDigestSessionStore_MultipleSessions(t *testing.T) { func TestDigestSessionStore_Performance1000Sessions(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 插入 1000 个会话 for i := 0; i < 1000; i++ { @@ -233,6 +246,7 @@ func TestDigestSessionStore_Performance1000Sessions(t *testing.T) { func TestDigestSessionStore_FindReturnsMatchedChain(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) store.Save(1, "prefix", "u:a-m:b-u:c", "uuid-1", 100, "") @@ -249,6 +263,7 @@ func TestDigestSessionStore_FindReturnsMatchedChain(t *testing.T) { func TestDigestSessionStore_CacheItemCountStable(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 模拟 100 个独立会话,每个进行 10 轮对话 // 正确传递 oldDigestChain 时,每个会话始终只保留 1 个 key @@ -278,8 +293,10 @@ func TestDigestSessionStore_CacheItemCountStable(t *testing.T) { func TestDigestSessionStore_TTLPreventsUnboundedGrowth(t *testing.T) { // 使用极短 TTL 验证大量写入后 cache 能被清理 store := &DigestSessionStore{ - cache: gocache.New(100*time.Millisecond, 50*time.Millisecond), + cache: sessionMemoryCache{sweep: 50 * time.Millisecond}, + ttl: 100 * time.Millisecond, } + t.Cleanup(store.Close) // 插入 500 个不同的 key(无 oldDigestChain,模拟最坏场景:全是新会话首轮) for i := 0; i < 500; i++ { @@ -297,6 +314,7 @@ func TestDigestSessionStore_TTLPreventsUnboundedGrowth(t *testing.T) { func TestDigestSessionStore_SaveSameChainNoDelete(t *testing.T) { store := NewDigestSessionStore() + t.Cleanup(store.Close) // 保存 chain store.Save(1, "prefix", "u:a-m:b", "uuid-1", 100, "") diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index ad9e63d3c7..c1068de281 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -223,6 +223,7 @@ const ( // 白名单非空时,是否放行非白名单域名按主域名限量注册(每域名 1 个账户)。 // 默认 false:非白名单域名直接拒绝(白名单严格模式)。 SettingKeyRegistrationEmailDomainQuotaEnabled = "registration_email_domain_quota_enabled" + SettingKeyRegistrationEmailBlacklist = "registration_email_blacklist" // 注册邮箱精确黑名单(JSON 数组,按收件箱身份匹配;不进 SystemSettings,由专用接口读写) SettingKeyPromoCodeEnabled = "promo_code_enabled" // 是否启用优惠码功能 SettingKeyPasswordResetEnabled = "password_reset_enabled" // 是否启用忘记密码功能(需要先开启邮件验证) SettingKeyFrontendURL = "frontend_url" // 前端基础URL,用于生成邮件中的重置密码链接 diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 889e2faa36..faca0a12c7 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -422,6 +422,7 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -429,11 +430,16 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -499,6 +505,9 @@ func (s *GatewayService) handleStreamingResponseAnthropicAPIKeyPassthrough( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if !clientDisconnected { // 兜底补刷,确保最后一个未以空行结尾的事件也能及时送达客户端。 diff --git a/backend/internal/service/gateway_forward_as_chat_completions.go b/backend/internal/service/gateway_forward_as_chat_completions.go index 24a281d612..f2e3f0027e 100644 --- a/backend/internal/service/gateway_forward_as_chat_completions.go +++ b/backend/internal/service/gateway_forward_as_chat_completions.go @@ -243,9 +243,11 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage + streamStatus := &anthropicCompatStream{body: resp.Body} for scanner.Scan() { line := scanner.Text() @@ -268,6 +270,11 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + // message_start carries the initial response structure and cache usage if event.Type == "message_start" && event.Message != nil { finalResp = event.Message @@ -310,6 +317,17 @@ func (s *GatewayService) handleCCBufferedFromAnthropic( } } + streamStatus.readErr = scanner.Err() + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeGatewayCCError(c, http.StatusBadGateway, "server_error", failure.message) + return &ForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeGatewayCCError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") diff --git a/backend/internal/service/gateway_forward_as_responses.go b/backend/internal/service/gateway_forward_as_responses.go index f7f4897d5a..802d090457 100644 --- a/backend/internal/service/gateway_forward_as_responses.go +++ b/backend/internal/service/gateway_forward_as_responses.go @@ -392,10 +392,12 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) // Accumulate the final Anthropic response from streaming events var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage + streamStatus := &anthropicCompatStream{body: resp.Body} for scanner.Scan() { line := scanner.Text() @@ -424,6 +426,11 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + // message_start carries the initial response structure if event.Type == "message_start" && event.Message != nil { finalResp = event.Message @@ -470,6 +477,17 @@ func (s *GatewayService) handleResponsesBufferedStreamingResponse( } } + streamStatus.readErr = scanner.Err() + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message) + return &ForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: usage, + Model: originalModel, UpstreamModel: mappedModel, ReasoningEffort: reasoningEffort, + Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeResponsesError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") diff --git a/backend/internal/service/gateway_forward_compat_stream.go b/backend/internal/service/gateway_forward_compat_stream.go index 7be3e85c35..0f9c43d1ca 100644 --- a/backend/internal/service/gateway_forward_compat_stream.go +++ b/backend/internal/service/gateway_forward_compat_stream.go @@ -65,8 +65,9 @@ func newAnthropicCompatStream(cfg *config.Config, c *gin.Context, resp *http.Res maxLineSize = cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(cfg, maxLineSize, nil)) stream := &anthropicCompatStream{ - pump: newAnthropicNativeLinePump(scanner, anthropicNativeStreamInterval(cfg)), + pump: newAnthropicNativeLinePump(scanner, anthropicNativeStreamInterval(cfg), cfg), body: resp.Body, maxLineSize: maxLineSize, logPrefix: logPrefix, diff --git a/backend/internal/service/gateway_request.go b/backend/internal/service/gateway_request.go index b77fac3187..0e52e00ecb 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -186,7 +186,9 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro return DescribeInvalidJSON(bodyBytes) } - // 只在当前函数内零拷贝读取 JSON 字段;ReplaceBody 后必须重新进入本函数刷新派生状态。 + // Zero-copy JSON reads stay local to parsing. Persisted scalar strings must + // own their storage: an unescaped gjson string otherwise retains the complete + // request buffer when copied into queued billing work. Raw ranges stay zero-copy. jsonStr := *(*string)(unsafe.Pointer(&bodyBytes)) clearGatewayRequestDerivedState(parsed) parsed.protocol = protocol @@ -196,7 +198,7 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro if modelResult.Type != gjson.String { return fmt.Errorf("invalid model field type") } - parsed.Model = modelResult.String() + parsed.Model = strings.Clone(modelResult.String()) if protocol == domain.PlatformAnthropic { normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model) if normalizedModel != parsed.Model { @@ -220,15 +222,15 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro parsed.Stream = streamResult.Bool() } - parsed.MetadataUserID = gjson.Get(jsonStr, "metadata.user_id").String() + parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String()) thinkingType := gjson.Get(jsonStr, "thinking.type").String() parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" || (protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model)) - parsed.OutputEffort = strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()) + parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String())) if protocol == domain.PlatformAnthropic { - parsed.Speed = strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())) + parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String()))) } maxTokensResult := gjson.Get(jsonStr, "max_tokens") diff --git a/backend/internal/service/gateway_request_scalar_memory_test.go b/backend/internal/service/gateway_request_scalar_memory_test.go new file mode 100644 index 0000000000..b0aeada1a4 --- /dev/null +++ b/backend/internal/service/gateway_request_scalar_memory_test.go @@ -0,0 +1,52 @@ +package service + +import ( + "fmt" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +func TestParsedRequestScalarsDoNotAliasRequestBody(t *testing.T) { + for _, replace := range []bool{false, true} { + for _, suffix := range []string{"", "[1m]"} { + t.Run(fmt.Sprintf("replace=%t/suffix=%s", replace, suffix), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":"claude-sonnet-4%s","metadata":{"user_id":"session-123"},"output_config":{"effort":" high "},"speed":"fast","system":"instructions","messages":[{"role":"user","content":"%s"}]}`, suffix, strings.Repeat("x", 64<<10))) + var parsed *ParsedRequest + var err error + if replace { + parsed, err = ParseGatewayRequest(NewRequestBodyRef([]byte(`{}`)), domain.PlatformAnthropic) + require.NoError(t, err) + err = parsed.ReplaceBody(body) + } else { + parsed, err = ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic) + } + require.NoError(t, err) + + // Large payload sections must still refer directly to the current + // body; only persistent scalar strings should get their own storage. + currentBody := parsed.Body.Bytes() + require.True(t, &parsed.SystemRaw()[0] == ¤tBody[parsed.systemRange.start]) + require.True(t, &parsed.MessagesRaw()[0] == ¤tBody[parsed.messagesRange.start]) + model, userID, effort, speed := parsed.Model, parsed.MetadataUserID, parsed.OutputEffort, parsed.Speed + parsed.Body.Replace(nil) + + // Reusing the source storage must not change metadata retained by + // queued billing work. Also overwrite the pre-normalization body: + // stripping [1m] must not leave Model pointing into that old buffer. + for i := range body { + body[i] = '!' + } + for i := range currentBody { + currentBody[i] = '!' + } + require.Equal(t, "claude-sonnet-4", model) + require.Equal(t, "session-123", userID) + require.Equal(t, "high", effort) + require.Equal(t, "fast", speed) + }) + } + } +} diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index fb9368b6c0..85b415e5cf 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -745,6 +745,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -753,11 +754,16 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http // 独立 goroutine 读取上游,避免读取阻塞导致超时/keepalive无法处理 events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1022,6 +1028,9 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // 上游完成,返回结果 if !sawTerminalEvent { @@ -1081,6 +1090,7 @@ func (s *GatewayService) handleStreamingResponse(ctx context.Context, resp *http } outputBlocks, data, usagePatch, err := processSSEEvent(pendingEventLines) + clear(pendingEventLines) pendingEventLines = pendingEventLines[:0] if err != nil { if clientDisconnected { diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 0ece86cd3b..10e0992c9c 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -9,6 +9,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" ) @@ -425,44 +426,44 @@ func finalizePostUsageBilling(ctx context.Context, p *postUsageBillingParams, de deps.deferredService.ScheduleLastUsedUpdate(p.Account.ID) - // Platform quota 累加:仅在 standard(余额)模式生效;订阅模式豁免;仅对有 limit 的用户写 - // Redis 同步写 + DB 异步持久化(flag=false 降级)或 flusher 异步刷(flag=true): - // - HasUserPlatformQuotaLimit 守卫:无 limit 的公司跳过,避免无效写入 + 浪费 Redis 容量 - // - Redis 同步:确保下次 preflight 立即看到最新 usage,把 TOCTOU 超支窗口 - // 限制在并发 in-flight 请求数量内(旧实现的异步入队会让超支无限累积直到 worker 处理) - // - DB 异步(flusher_enabled=false):在独立 goroutine 中走 detached context,失败用 ALERT log 触发 oncall 对账 - // - flusher_enabled=true:不直写 DB,由 flusher 异步批量刷(markDirty 已在 IncrementUserPlatformQuotaUsage 内部完成) + // Redis is updated before returning so subsequent preflight checks observe the + // charge. Without the batch flusher, persist inline with the usage task (in a + // worker or its synchronous overflow caller), without spawning detached work. + // Synchronous overflow remains backpressure, not a global DB concurrency cap. if !p.IsSubscriptionBill && p.Platform != "" && p.Cost.ActualCost > 0 && p.User != nil && deps.userPlatformQuotaRepo != nil && deps.billingCacheService != nil { if deps.billingCacheService.HasUserPlatformQuotaLimit(ctx, p.User.ID, p.Platform) { deps.billingCacheService.IncrementUserPlatformQuotaUsage(p.User.ID, p.Platform, p.Cost.ActualCost) if deps.cfg == nil || !deps.cfg.Database.UserPlatformQuotaFlusherEnabled { - // 降级路径:flusher 未启用时保留原有异步直写 DB - dbCtx, dbCancel := detachUpstreamContext(ctx) - userID, platform, cost := p.User.ID, p.Platform, p.Cost.ActualCost - go func() { - defer func() { - if r := recover(); r != nil { - logger.LegacyPrintf("service.gateway", "ALERT: panic in user platform quota incr goroutine user=%d platform=%s: %v", userID, platform, r) - } - }() - defer dbCancel() - if err := deps.userPlatformQuotaRepo.IncrementUsageWithReset(dbCtx, userID, platform, cost, time.Now().UTC()); err != nil { - // 失败计数器:暴露给 GatewayUserPlatformQuotaIncrStats(),由 ops 面板做斜率告警。 - userPlatformQuotaDBIncrErrorTotal.Add(1) - // ALERT 级别:DB 持久化失败意味着 Redis cache 失效后该笔 cost 永久丢失, - // 用户配额视图与实际消费会偏差,oncall 需要据此对账或人工补录。 - logger.LegacyPrintf("service.gateway", "ALERT: incr user platform quota DB failed user=%d platform=%s cost=%f: %v", userID, platform, cost, err) - } - }() + persistPostUsagePlatformQuota(ctx, deps.userPlatformQuotaRepo, p.User.ID, p.Platform, p.Cost.ActualCost) } - // flusher_enabled=true:不直写 DB,flusher 异步批量刷 } } - // Notification checks run async — all parameters are already captured, - // no dependency on the request context or upstream connection. - go notifyBalanceLow(p, deps, result) - go notifyAccountQuota(p, deps, result) + if deps.balanceNotifyService != nil { + deps.balanceNotifyService.submitUsageNotifications(p, deps, result) + } +} + +// A committed charge must still attempt quota persistence if the request/worker +// context expired. Bound that independent attempt, and keep failures observable; +// this path has no durable retry queue. +func persistPostUsagePlatformQuota(ctx context.Context, repo UserPlatformQuotaRepository, userID int64, platform string, cost float64) { + base := context.Background() + if ctx != nil { + base = context.WithoutCancel(ctx) + } + dbCtx, cancel := context.WithTimeout(base, 5*time.Second) + defer cancel() + defer func() { + if r := recover(); r != nil { + userPlatformQuotaDBIncrErrorTotal.Add(1) + logger.LegacyPrintf("service.gateway", "ALERT: panic persisting user platform quota user=%d platform=%s: %v", userID, platform, r) + } + }() + if err := repo.IncrementUsageWithReset(dbCtx, userID, platform, cost, time.Now().UTC()); err != nil { + userPlatformQuotaDBIncrErrorTotal.Add(1) + logger.LegacyPrintf("service.gateway", "ALERT: incr user platform quota DB failed user=%d platform=%s cost=%f: %v", userID, platform, cost, err) + } } func syncBalanceCacheAfterDeduction(ctx context.Context, p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { @@ -496,7 +497,7 @@ func syncBalanceCacheAfterDeduction(ctx context.Context, p *postUsageBillingPara // notifyBalanceLow sends balance low notification after deduction. // When result.NewBalance is available (from DB transaction RETURNING), it is used directly // to reconstruct oldBalance, avoiding stale Redis reads and concurrent-deduction races. -func notifyBalanceLow(p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { +func notifyBalanceLow(ctx context.Context, p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { defer func() { if r := recover(); r != nil { slog.Error("panic in notifyBalanceLow", "recover", r) @@ -521,7 +522,7 @@ func notifyBalanceLow(p *postUsageBillingParams, deps *billingDeps, result *Usag "threshold", p.User.BalanceNotifyThreshold, "result_has_new_balance", result != nil && result.NewBalance != nil, ) - deps.balanceNotifyService.CheckBalanceAfterDeduction(context.Background(), p.User, oldBalance, p.Cost.ActualCost) + deps.balanceNotifyService.CheckBalanceAfterDeduction(ctx, p.User, oldBalance, p.Cost.ActualCost) } // resolveOldBalance returns the pre-deduction balance. @@ -537,7 +538,7 @@ func resolveOldBalance(p *postUsageBillingParams, result *UsageBillingApplyResul // notifyAccountQuota sends account quota threshold notification after increment. // When result.QuotaState is available (from DB transaction RETURNING), it is passed directly // to avoid a separate DB read that may see stale or concurrently-modified data. -func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { +func notifyAccountQuota(ctx context.Context, p *postUsageBillingParams, deps *billingDeps, result *UsageBillingApplyResult) { defer func() { if r := recover(); r != nil { slog.Error("panic in notifyAccountQuota", "recover", r) @@ -567,7 +568,7 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us "account_cost", accountCost, "has_quota_state", quotaState != nil, ) - deps.balanceNotifyService.CheckAccountQuotaAfterIncrement(context.Background(), p.Account, accountCost, quotaState) + deps.balanceNotifyService.CheckAccountQuotaAfterIncrement(ctx, p.Account, accountCost, quotaState) } func detachedBillingContext(ctx context.Context) (context.Context, context.CancelFunc) { @@ -585,14 +586,14 @@ func detachStreamUpstreamContext(ctx context.Context, stream bool) (context.Cont if !stream { return ctx, func() {} } - return context.WithoutCancel(ctx), func() {} + return pkghttputil.DetachUpstreamContext(ctx), func() {} } -func detachUpstreamContext(ctx context.Context) (context.Context, context.CancelFunc) { +func detachUpstreamContext(ctx context.Context, drainTimeout ...time.Duration) (context.Context, context.CancelFunc) { if ctx == nil { return context.Background(), func() {} } - return context.WithoutCancel(ctx), func() {} + return pkghttputil.DetachUpstreamContext(ctx, drainTimeout...), func() {} } // billingDeps 扣费逻辑依赖的服务(由各 gateway service 提供) diff --git a/backend/internal/service/gateway_usage_quota_worker_test.go b/backend/internal/service/gateway_usage_quota_worker_test.go new file mode 100644 index 0000000000..11515a0d14 --- /dev/null +++ b/backend/internal/service/gateway_usage_quota_worker_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type blockingUsageQuotaRepo struct { + UserPlatformQuotaRepository + entered chan context.Context + release chan struct{} +} + +func (r *blockingUsageQuotaRepo) IncrementUsageWithReset(ctx context.Context, _ int64, _ string, _ float64, _ time.Time) error { + r.entered <- ctx + select { + case <-r.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func TestPostUsageQuotaPersistenceStaysInUsageWorker(t *testing.T) { + repo := &blockingUsageQuotaRepo{entered: make(chan context.Context, 1), release: make(chan struct{})} + pool := NewUsageRecordWorkerPoolWithOptions(UsageRecordWorkerPoolOptions{ + WorkerCount: 1, QueueSize: 8, TaskTimeout: time.Second, OverflowPolicy: "sync", + }) + t.Cleanup(pool.Stop) + t.Cleanup(func() { close(repo.release) }) + pool.Submit(func(ctx context.Context) { + finalizePostUsageBilling(ctx, &postUsageBillingParams{ + Cost: &CostBreakdown{ActualCost: 1}, User: &User{ID: 1}, Account: &Account{ID: 2}, Platform: PlatformOpenAI, + }, &billingDeps{ + userPlatformQuotaRepo: repo, + billingCacheService: &BillingCacheService{cfg: &config.Config{}}, + deferredService: &DeferredService{}, + }, nil) + }) + select { + case ctx := <-repo.entered: + deadline, ok := ctx.Deadline() + require.True(t, ok) + require.InDelta(t, 5, time.Until(deadline).Seconds(), 1) + case <-time.After(2 * time.Second): + t.Fatal("quota persistence did not start") + } + next := make(chan struct{}) + pool.Submit(func(context.Context) { close(next) }) + select { + case <-next: + t.Fatal("quota persistence escaped the usage worker and released its concurrency slot") + case <-time.After(20 * time.Millisecond): + } +} + +type failedUsageQuotaRepo struct { + UserPlatformQuotaRepository + ctx context.Context + errAtCall error +} + +func (r *failedUsageQuotaRepo) IncrementUsageWithReset(ctx context.Context, _ int64, _ string, _ float64, _ time.Time) error { + r.ctx = ctx + r.errAtCall = ctx.Err() + return errors.New("database unavailable") +} + +func TestPostUsageQuotaPersistenceHasIndependentDeadlineAndReportsFailure(t *testing.T) { + parent, cancel := context.WithCancel(context.Background()) + cancel() + repo := &failedUsageQuotaRepo{} + before := userPlatformQuotaDBIncrErrorTotal.Load() + persistPostUsagePlatformQuota(parent, repo, 1, PlatformOpenAI, 1) + require.NotNil(t, repo.ctx) + require.NoError(t, repo.errAtCall, "committed charge must attempt persistence after parent cancellation") + deadline, ok := repo.ctx.Deadline() + require.True(t, ok) + require.InDelta(t, 5, time.Until(deadline).Seconds(), 1) + require.Equal(t, before+1, userPlatformQuotaDBIncrErrorTotal.Load()) +} diff --git a/backend/internal/service/gemini_cached_content.go b/backend/internal/service/gemini_cached_content.go index bc1a3353dc..95264148d0 100644 --- a/backend/internal/service/gemini_cached_content.go +++ b/backend/internal/service/gemini_cached_content.go @@ -277,7 +277,7 @@ func geminiCachedContentBoundFromContext(ctx context.Context) bool { } // isGeminiBoundCacheUpstreamPassthrough 判断绑定缓存的请求在上游网关账号上收到的错误是否只反映 -// 上游持有缓存的那个账号的状态(429 / 5xx),不应据此限流或重试本账号。 +// 上游持有缓存的那个账号的状态(429 / 5xx),不应据此限流或封禁本账号。 func isGeminiBoundCacheUpstreamPassthrough(ctx context.Context, account *Account, statusCode int) bool { if statusCode != http.StatusTooManyRequests && statusCode < http.StatusInternalServerError { return false diff --git a/backend/internal/service/gemini_cached_content_hardening_test.go b/backend/internal/service/gemini_cached_content_hardening_test.go index f93b9424a0..965df5b48b 100644 --- a/backend/internal/service/gemini_cached_content_hardening_test.go +++ b/backend/internal/service/gemini_cached_content_hardening_test.go @@ -295,6 +295,55 @@ func TestGeminiForwardNative_BoundCacheUpstreamGatewayErrorsSkipAccountPenalty(t } } +func TestGeminiForwardNative_BoundCacheUpstreamGatewayErrorsRetryablePerPoolModeCodes(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tt := range []struct { + status int + retryable bool + }{ + {status: http.StatusTooManyRequests, retryable: true}, + {status: http.StatusServiceUnavailable, retryable: false}, + } { + t.Run(http.StatusText(tt.status), func(t *testing.T) { + body := fmt.Sprintf(`{"error":{"code":%d,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`, tt.status) + svc, httpStub, _ := newGeminiCachedContentTestService(tt.status, body) + repo := &geminiBoundCacheRateLimitRepo{} + svc.accountRepo = repo + svc.rateLimitService = NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + account := &Account{ID: 712, Platform: PlatformGemini, Type: AccountTypeAPIKey, Credentials: map[string]any{ + "api_key": "k", "base_url": "https://gw.example.com", "explicit_cache_upstream": true, + "pool_mode": true, "pool_mode_retry_count": float64(2), "pool_mode_retry_status_codes": []any{float64(429)}, + }} + c, _ := newGeminiNativeTestContext(t) + + _, err := svc.ForwardNative(WithGeminiCachedContentBound(context.Background()), c, account, + "gemini-3.8-flash", "generateContent", false, []byte(geminiCachedContentRequestBody)) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr)) + require.True(t, failoverErr.BoundUpstreamPassthrough, "重试用尽后仍由 handler 原样回写") + require.Equal(t, tt.retryable, failoverErr.RetryableOnSameAccount, "按池模式重试状态码决定同账号重试") + require.Equal(t, tt.retryable, failoverErr.RequestScopedTransient, "重试用尽不临时封禁本账号") + require.Equal(t, 1, httpStub.calls, "同账号重试由 handler 执行") + require.Zero(t, repo.rateLimitedCalls) + require.Zero(t, repo.tempCalls) + require.Zero(t, repo.setErrCalls) + + raw, ok := c.Get(OpsUpstreamErrorsKey) + if !tt.retryable { + require.False(t, ok, "不可重试时不登记上游事件,由耗尽处理写 ops") + return + } + require.True(t, ok) + events, ok := raw.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 1, "每次尝试登记一个上游事件,重试成功时 ops 记为恢复") + require.Equal(t, tt.status, events[0].UpstreamStatusCode) + require.Equal(t, "retry", events[0].Kind, "同账号重试不计入换号次数") + }) + } +} + type fixedChargeCacheStub struct { billingCacheWorkerStub balance float64 diff --git a/backend/internal/service/gemini_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index 0f5417e8a4..8e1cd1aa29 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -127,7 +127,8 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( var resp *http.Response // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 var checkedPolicy *ErrorPolicyResult - for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + maxAttempts := s.geminiMaxAttemptsPerAccount() + for attempt := 1; attempt <= maxAttempts; attempt++ { upstreamReq, idHeader, err := buildReq(ctx) if err != nil { if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { @@ -166,7 +167,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( if resp.StatusCode == http.StatusTooManyRequests { s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } - if attempt < geminiMaxRetries { + if attempt < maxAttempts { upstreamReqID := resp.Header.Get(requestIDHeader) if upstreamReqID == "" { upstreamReqID = resp.Header.Get("x-goog-request-id") @@ -184,7 +185,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( Kind: "retry", Message: upstreamMsg, }) - logger.LegacyPrintf("service.gemini_chat_completions", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries) + logger.LegacyPrintf("service.gemini_chat_completions", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, maxAttempts) sleepGeminiBackoff(attempt) continue } diff --git a/backend/internal/service/gemini_error_policy_single_check_test.go b/backend/internal/service/gemini_error_policy_single_check_test.go index 0ba4344c53..3ab842a534 100644 --- a/backend/internal/service/gemini_error_policy_single_check_test.go +++ b/backend/internal/service/gemini_error_policy_single_check_test.go @@ -182,6 +182,7 @@ func TestGeminiForward_UncheckedFinalResponseIsCheckedAfterLoop(t *testing.T) { geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: `{"error":{"code":503,"message":"backend busy","status":"UNAVAILABLE"}}`}, geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: `{"error":{"code":400,"message":"quota project misconfigured","status":"FAILED_PRECONDITION"}}`}, ) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = 1 account := geminiAPIKeyAccountWithTempRule(map[string]any{ "error_code": float64(400), "keywords": []any{"misconfigured"}, diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 40fd16baf8..6f4edef96c 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -35,9 +35,10 @@ import ( const geminiStickySessionTTL = time.Hour const ( - geminiMaxRetries = 5 - geminiRetryBaseDelay = 1 * time.Second - geminiRetryMaxDelay = 16 * time.Second + // 未注入配置时的同账号重试次数,与 gateway.max_same_account_retries_gemini 默认值一致 + geminiDefaultSameAccountRetries = 4 + geminiRetryBaseDelay = 1 * time.Second + geminiRetryMaxDelay = 16 * time.Second ) const ( @@ -717,7 +718,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 var checkedPolicy *ErrorPolicyResult signatureRetryStage := 0 - for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + maxAttempts := s.geminiMaxAttemptsPerAccount() + // 签名降级重发不占用同号重试次数:每进入一个降级阶段,循环上限随之顺延一次。 + for attempt := 1; attempt <= maxAttempts+signatureRetryStage; attempt++ { checkedPolicy = nil upstreamReq, idHeader, err := buildReq(ctx) if err != nil { @@ -798,7 +801,6 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: detected signature-related 400, retrying with downgraded Claude blocks (%s)", account.ID, stageName) // 降级只改写历史块,思考参数沿用客户端原始请求。 geminiReq = applyGeminiCompatThinkingConfig(retryGeminiReq, originalClaudeBody, mappedModel, includeThoughts) - // Consume one retry budget attempt and continue with the updated request payload. sleepGeminiBackoff(1) continue } @@ -837,7 +839,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex // Apply account-scoped 429 handling early so concurrent requests avoid a rate-limited account. s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } - if attempt < geminiMaxRetries { + retryAttempt := attempt - signatureRetryStage + if retryAttempt < maxAttempts { upstreamReqID := resp.Header.Get(requestIDHeader) if upstreamReqID == "" { upstreamReqID = resp.Header.Get("x-goog-request-id") @@ -865,8 +868,8 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex Detail: upstreamDetail, }) - logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries) - sleepGeminiBackoff(attempt) + logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, retryAttempt, maxAttempts) + sleepGeminiBackoff(retryAttempt) continue } // Final attempt: surface the upstream error body (mapped below) instead of a generic retry error. @@ -1269,7 +1272,8 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. var resp *http.Response // checkedPolicy 是循环内对当前 resp 的错误策略检查结果,未检查时为 nil。 var checkedPolicy *ErrorPolicyResult - for attempt := 1; attempt <= geminiMaxRetries; attempt++ { + maxAttempts := s.geminiMaxAttemptsPerAccount() + for attempt := 1; attempt <= maxAttempts; attempt++ { checkedPolicy = nil upstreamReq, idHeader, err := buildReq(ctx) if err != nil { @@ -1340,7 +1344,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. if resp.StatusCode == 429 { s.handleGeminiUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) } - if attempt < geminiMaxRetries { + if attempt < maxAttempts { upstreamReqID := resp.Header.Get(requestIDHeader) if upstreamReqID == "" { upstreamReqID = resp.Header.Get("x-goog-request-id") @@ -1368,7 +1372,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. Detail: upstreamDetail, }) - logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, geminiMaxRetries) + logger.LegacyPrintf("service.gemini_messages_compat", "Gemini account %d: upstream status %d, retry %d/%d", account.ID, resp.StatusCode, attempt, maxAttempts) sleepGeminiBackoff(attempt) continue } @@ -1414,9 +1418,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. if isGeminiCachedContentNotFound(resp.StatusCode, respBody) { return nil, s.writeGeminiCachedContentNotFound(c, account, resp, respBody, requestID, isOAuth) } - // 上游网关的限流 / 不可用只针对其持有缓存的账号:不改本账号状态,交由绑定请求的耗尽处理透传。 + // 上游网关的限流 / 不可用只针对其持有缓存的账号:不改本账号状态,按池模式配置同账号重试,用尽后透传。 if isGeminiBoundCacheUpstreamPassthrough(ctx, account, resp.StatusCode) { - return nil, &UpstreamFailoverError{StatusCode: resp.StatusCode, ResponseBody: respBody, BoundUpstreamPassthrough: true} + return nil, s.boundCacheUpstreamPassthroughError(c, account, resp.StatusCode, respBody, requestID) } // Best-effort fallback for OAuth tokens missing AI Studio scopes when calling countTokens. // This avoids Gemini SDKs failing hard during preflight token counting. @@ -1671,6 +1675,14 @@ func (s *GeminiMessagesCompatService) cachedContentPassthroughInLoop(ctx context return isGeminiCachedContentNotFound(resp.StatusCode, body), rebuilt } +// geminiMaxAttemptsPerAccount 返回可重试上游错误在单个账号上的最大请求次数(首次请求 + 同账号重试)。 +func (s *GeminiMessagesCompatService) geminiMaxAttemptsPerAccount() int { + if s == nil || s.cfg == nil { + return geminiDefaultSameAccountRetries + 1 + } + return s.cfg.Gateway.MaxSameAccountRetriesGemini + 1 +} + func (s *GeminiMessagesCompatService) shouldRetryGeminiUpstreamError(account *Account, statusCode int) bool { switch statusCode { case 429, 500, 502, 503, 504, 529: @@ -1729,6 +1741,36 @@ func (s *GeminiMessagesCompatService) skippedErrorPolicyFailoverError(c *gin.Con } } +// boundCacheUpstreamPassthroughError 构造绑定显式缓存的请求在上游网关账号上收到 429 / 5xx 时的 failover 错误。 +// 缓存只存在于该账号,handler 不换号;池模式账号对 pool_mode_retry_status_codes 内的状态码按 pool_mode_retry_count +// 同账号重试,用尽或不可重试时原样回写上游响应。故障在上游网关持有缓存的账号上,与本账号健康无关, +// 因此可重试的错误标为请求级瞬时故障:重试用尽也不临时封禁本账号。可重试时每次尝试登记一条 retry 事件, +// 重试成功的请求在 ops 记为恢复。 +func (s *GeminiMessagesCompatService) boundCacheUpstreamPassthroughError(c *gin.Context, account *Account, statusCode int, respBody []byte, upstreamRequestID string) *UpstreamFailoverError { + retryable := account.IsPoolMode() && account.IsPoolModeRetryableStatus(statusCode) + if retryable { + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + ProxyID: opsUpstreamProxyID(account), + ProxyName: opsUpstreamProxyName(account), + Platform: account.Platform, + AccountID: account.ID, + AccountName: account.Name, + UpstreamStatusCode: statusCode, + UpstreamRequestID: upstreamRequestID, + Kind: "retry", + Message: sanitizeUpstreamErrorMessage(strings.TrimSpace(extractUpstreamErrorMessage(respBody))), + Detail: s.upstreamErrorDetail(respBody), + }) + } + return &UpstreamFailoverError{ + StatusCode: statusCode, + ResponseBody: respBody, + BoundUpstreamPassthrough: true, + RetryableOnSameAccount: retryable, + RequestScopedTransient: retryable, + } +} + // geminiCustomCodeSkippedClientMessage 自定义错误码未命中时对客户端隐藏上游细节的固定文案, // 与 OpenAI 网关路径同场景的文案一致。 const geminiCustomCodeSkippedClientMessage = "Upstream gateway error" diff --git a/backend/internal/service/gemini_models_endpoints.go b/backend/internal/service/gemini_models_endpoints.go index 02f3b985a1..34a86444d1 100644 --- a/backend/internal/service/gemini_models_endpoints.go +++ b/backend/internal/service/gemini_models_endpoints.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "slices" + "sort" "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/gemini" @@ -23,6 +24,47 @@ import ( // errGeminiModelsUpstreamStatus 在 Vertex 分页读取遇到非 2xx 时中止分页,原始响应由调用方另行保存。 var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non-2xx status") +// DeclaredModelIDs 在分组内每个可调度 Gemini 账号都有生效的 model_mapping(含 Google One 的默认映射)时, +// 返回这些映射键的并集(去重排序,通配符键原样保留)。有账号未配置映射时该账号接受任意模型,返回空, +// 模型接口由选中账号的上游应答。 +func (s *GeminiMessagesCompatService) DeclaredModelIDs(ctx context.Context, groupID *int64) ([]string, error) { + accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true) + if err != nil { + return nil, fmt.Errorf("query accounts failed: %w", err) + } + seen := make(map[string]struct{}) + for i := range accounts { + if accounts[i].Platform != PlatformGemini { + continue + } + mapping := accounts[i].GetModelMapping() + if len(mapping) == 0 { + return nil, nil + } + for model := range mapping { + seen[model] = struct{}{} + } + } + models := make([]string, 0, len(seen)) + for model := range seen { + models = append(models, model) + } + sort.Strings(models) + return models, nil +} + +// DeclaredModelsCover 判断声明的模型中是否有条目覆盖 model:键末尾的 * 按前缀匹配, +// 模型别名按请求路径查映射时的规则归一后再比较。 +func DeclaredModelsCover(declared []string, model string) bool { + normalized := normalizeRequestedModelForLookup(PlatformGemini, model) + for _, pattern := range declared { + if matchWildcard(pattern, model) || matchWildcard(pattern, normalized) { + return true + } + } + return false +} + // SelectAccountForModelsEndpoints 为模型列表与模型详情接口选择账号。 // // 优先级: @@ -35,7 +77,7 @@ var errGeminiModelsUpstreamStatus = errors.New("upstream model list returned non // 7. Vertex API Key 账号(列表接口不接受 API Key,只能返回内置列表) // // Vertex 账号排在所有 AI Studio 兼容账号之后,混合分组始终由 AI Studio 兼容账号应答。 -// 同级账号按 priority、最近使用时间挑选。 +// 同级账号按 priority、最近使用时间挑选。DeclaredModelIDs 非空时模型接口按声明的模型应答,不经过选号。 func (s *GeminiMessagesCompatService) SelectAccountForModelsEndpoints(ctx context.Context, groupID *int64) (*Account, error) { accounts, err := s.listSchedulableAccountsOnce(ctx, groupID, PlatformGemini, true) if err != nil { diff --git a/backend/internal/service/gemini_same_account_retries_test.go b/backend/internal/service/gemini_same_account_retries_test.go new file mode 100644 index 0000000000..56c63de789 --- /dev/null +++ b/backend/internal/service/gemini_same_account_retries_test.go @@ -0,0 +1,92 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + geminiRetryTest503Body = `{"error":{"code":503,"message":"The model is overloaded.","status":"UNAVAILABLE"}}` + geminiRetryTestSignatureBody = `{"error":{"code":400,"message":"Function call is missing a thought_signature in functionCall parts.","status":"INVALID_ARGUMENT"}}` + geminiRetryTestOKBody = `{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":1,"totalTokenCount":4}}` +) + +func geminiSameAccountRetryTestAccount() *Account { + return &Account{ + ID: 840, + Platform: PlatformGemini, + Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "test-key"}, + } +} + +func TestGeminiForward_SameAccountRetriesFollowConfig(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, retries := range []int{0, 1} { + for _, fw := range geminiSingleCheckForwarders { + t.Run(fmt.Sprintf("%s/retries=%d", fw.name, retries), func(t *testing.T) { + svc, upstream, _ := newGeminiSingleCheckService(geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body}) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = retries + + err, _ := fw.forward(t, svc, geminiSameAccountRetryTestAccount()) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "同号重试耗尽应换号,got %T: %v", err, err) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.StatusCode) + require.Equal(t, retries+1, upstream.calls) + }) + } + } +} + +func TestGeminiClaudeCompat_SignatureDowngradeDoesNotConsumeSameAccountRetries(t *testing.T) { + gin.SetMode(gin.TestMode) + forward := func(svc *GeminiMessagesCompatService) (*ForwardResult, error) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(`{"model":"gemini-2.5-flash","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + return svc.Forward(context.Background(), c, geminiSameAccountRetryTestAccount(), body) + } + + t.Run("both downgrade stages run without same-account retries", func(t *testing.T) { + svc, upstream, _ := newGeminiSingleCheckService( + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusOK, body: geminiRetryTestOKBody}, + ) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = 0 + + result, err := forward(svc) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 3, upstream.calls) + }) + + t.Run("same-account retries are counted apart from downgrades", func(t *testing.T) { + svc, upstream, _ := newGeminiSingleCheckService( + geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusBadRequest, body: geminiRetryTestSignatureBody}, + geminiSequenceUpstreamResponse{status: http.StatusServiceUnavailable, body: geminiRetryTest503Body}, + ) + svc.cfg.Gateway.MaxSameAccountRetriesGemini = 1 + + _, err := forward(svc) + + var failoverErr *UpstreamFailoverError + require.True(t, errors.As(err, &failoverErr), "同号重试耗尽应换号,got %T: %v", err, err) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.StatusCode) + require.Equal(t, 4, upstream.calls) + }) +} diff --git a/backend/internal/service/gemini_vertex_api_key_forward_test.go b/backend/internal/service/gemini_vertex_api_key_forward_test.go index 5c1d5f1b20..1b57bbb1fc 100644 --- a/backend/internal/service/gemini_vertex_api_key_forward_test.go +++ b/backend/internal/service/gemini_vertex_api_key_forward_test.go @@ -144,7 +144,7 @@ func TestGeminiForwardNative_VertexSharedCapacity429RetriesSameAccountWithoutCoo repo := &geminiBoundCacheRateLimitRepo{} svc := &GeminiMessagesCompatService{ httpUpstream: upstream, - cfg: &config.Config{}, + cfg: &config.Config{Gateway: config.GatewayConfig{MaxSameAccountRetriesGemini: 1}}, accountRepo: repo, rateLimitService: NewRateLimitService(repo, nil, &config.Config{}, nil, nil), } diff --git a/backend/internal/service/grok_quota_service.go b/backend/internal/service/grok_quota_service.go index 391ba8c6ab..410bdd4f41 100644 --- a/backend/internal/service/grok_quota_service.go +++ b/backend/internal/service/grok_quota_service.go @@ -244,6 +244,12 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr // ProbeBilling only calls the xAI billing endpoints. Account usage refreshes // use this method so opening the account list never consumes model quota. func (s *GrokQuotaService) ProbeBilling(ctx context.Context, accountID int64) (*GrokQuotaProbeResult, error) { + // 每个调用者在加入共享查询前独立验权,不能继承任务发起者的范围。 + if s != nil { + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "accounts.usage.read", false); err != nil { + return nil, err + } + } return s.runProbeFlight(ctx, "billing:"+strconv.FormatInt(accountID, 10), func(sharedCtx context.Context) (*GrokQuotaProbeResult, error) { return s.probeBilling(sharedCtx, accountID) }) @@ -353,7 +359,7 @@ func (s *GrokQuotaService) runProbeFlight( return nil, infraerrors.New(http.StatusInternalServerError, "GROK_QUOTA_NOT_CONFIGURED", "grok quota service is not configured") } resultCh := s.probeFlight.DoChan(key, func() (any, error) { - sharedCtx, cancel := context.WithTimeout(context.Background(), grokQuotaUpstreamTimeout+5*time.Second) + sharedCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grokQuotaUpstreamTimeout+5*time.Second) defer cancel() return probe(sharedCtx) }) @@ -544,6 +550,9 @@ func (s *GrokQuotaService) loadGrokOAuthAccount(ctx context.Context, accountID i if account == nil { return nil, infraerrors.New(http.StatusNotFound, "GROK_QUOTA_ACCOUNT_NOT_FOUND", "account not found") } + if err := scopedAccountAccess(ctx, s.accountRepo, account, "accounts.usage.read", false); err != nil { + return nil, err + } if account.Platform != PlatformGrok { return nil, infraerrors.New(http.StatusBadRequest, "GROK_QUOTA_INVALID_PLATFORM", "account is not a Grok account") } diff --git a/backend/internal/service/grok_sse_transport_config_test.go b/backend/internal/service/grok_sse_transport_config_test.go new file mode 100644 index 0000000000..461b920d25 --- /dev/null +++ b/backend/internal/service/grok_sse_transport_config_test.go @@ -0,0 +1,70 @@ +package service + +import ( + "io" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/stretchr/testify/require" +) + +func TestGrokSSEPrefiltersRespectConfiguredEventLimits(t *testing.T) { + filters := []struct { + name string + wrap func(io.ReadCloser, *config.Config) io.ReadCloser + }{ + {"billing_ping", func(source io.ReadCloser, cfg *config.Config) io.ReadCloser { + return newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformGrok}, cfg.Gateway.MaxLineSize, cfg) + }}, + {"client_tools", func(source io.ReadCloser, cfg *config.Config) io.ReadCloser { + return newGrokResponsesClientToolStreamBody(source, apicompat.ResponsesClientToolMapping{}, cfg.Gateway.MaxLineSize, cfg) + }}, + } + for _, filter := range filters { + t.Run(filter.name, func(t *testing.T) { + for _, tc := range []struct { + name string + gateway config.GatewayConfig + wire string + limited bool + }{ + { + name: "byte_limit", + gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxBytes: 64}, + wire: strings.Repeat(": "+strings.Repeat("x", 30)+"\n", 3) + "\n", + limited: true, + }, + { + name: "line_limit", + gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxLines: 2}, + wire: strings.Repeat(": keepalive\n", 3) + "\n", + limited: true, + }, + { + name: "event_larger_than_individual_line_limit", + gateway: config.GatewayConfig{MaxLineSize: 128, SSEEventMaxBytes: 1024}, + wire: strings.Repeat(": "+strings.Repeat("x", 30)+"\n", 8) + "\n", + }, + { + name: "line_limit_above_default", + gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxLines: defaultSSEEventMaxLines + 1}, + wire: strings.Repeat(": keepalive\n", defaultSSEEventMaxLines+1) + "\n", + }, + } { + t.Run(tc.name, func(t *testing.T) { + body := filter.wrap(io.NopCloser(strings.NewReader(tc.wire)), &config.Config{Gateway: tc.gateway}) + defer func() { require.NoError(t, body.Close()) }() + output, err := io.ReadAll(body) + if tc.limited { + require.ErrorIs(t, err, errSSETransportLimit) + return + } + require.NoError(t, err) + require.Equal(t, tc.wire, string(output)) + }) + } + }) + } +} diff --git a/backend/internal/service/group_capacity_service.go b/backend/internal/service/group_capacity_service.go index b77b35773b..b242976287 100644 --- a/backend/internal/service/group_capacity_service.go +++ b/backend/internal/service/group_capacity_service.go @@ -2,6 +2,8 @@ package service import ( "context" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "time" ) @@ -77,6 +79,15 @@ func (s *GroupCapacityService) GetAllGroupCapacity(ctx context.Context) ([]Group } func (s *GroupCapacityService) listActiveGroupIDs(ctx context.Context) ([]int64, error) { + if adminaccess.RestrictedFromContext(ctx) != nil { + if repo, ok := s.groupRepo.(interface { + ListScopedAdminCapacityGroupIDs(context.Context) ([]int64, error) + }); ok { + return repo.ListScopedAdminCapacityGroupIDs(ctx) + } + return nil, infraerrors.ServiceUnavailable("SCOPED_GROUP_CAPACITY_UNAVAILABLE", "受限分组容量服务不可用") + } + if lister, ok := s.groupRepo.(groupCapacityActiveGroupIDLister); ok { return lister.ListActiveIDs(ctx) } diff --git a/backend/internal/service/mcp_oauth_service.go b/backend/internal/service/mcp_oauth_service.go new file mode 100644 index 0000000000..ff2fedefa7 --- /dev/null +++ b/backend/internal/service/mcp_oauth_service.go @@ -0,0 +1,724 @@ +package service + +import ( + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "net/url" + "strings" + "time" + "unicode" + "unicode/utf8" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +const ( + MCPScopeUser = "user" + MCPScopeAdmin = "admin" + MCPOAuthScope = "mcp" + MCPOAuthGrantLimit = 20 + MCPOAuthAccessLifetime = 10 * time.Minute + MCPOAuthCodeLifetime = 5 * time.Minute + MCPOAuthGrantLifetime = 30 * 24 * time.Hour + // last_used_at is advisory; writing it once per interval keeps requests read-only. + MCPOAuthTouchInterval = time.Minute + + mcpOAuthClientIDPrefix = "mcp_client_" + // Registration bounds keep issued IDs well below this limit. + mcpOAuthClientIDMaxLength = 2048 +) + +var ( + ErrMCPOAuthInvalidToken = infraerrors.Unauthorized("INVALID_MCP_TOKEN", "MCP access token is invalid or expired") + 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") +) + +type MCPOAuthError struct { + Code string `json:"error"` + Description string `json:"error_description"` +} + +func (e *MCPOAuthError) Error() string { return e.Code + ": " + e.Description } + +func mcpOAuthError(code, description string) error { + return &MCPOAuthError{Code: code, Description: description} +} + +type MCPOAuthRegisterInput struct { + ClientName string `json:"client_name"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + RedirectURIs []string `json:"redirect_uris"` + GrantTypes []string `json:"grant_types"` + ResponseTypes []string `json:"response_types"` +} + +type MCPOAuthClient struct { + ClientID string `json:"client_id"` + ClientName string `json:"client_name"` + TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"` + RedirectURIs []string `json:"redirect_uris"` + GrantTypes []string `json:"grant_types"` + ResponseTypes []string `json:"response_types"` + ClientIDIssuedAt int64 `json:"client_id_issued_at"` +} + +type MCPOAuthAuthorizeInput struct { + ResponseType string `json:"response_type"` + ClientID string `json:"client_id"` + RedirectURI string `json:"redirect_uri"` + Scope string `json:"scope"` + State string `json:"state"` + CodeChallenge string `json:"code_challenge"` + CodeChallengeMethod string `json:"code_challenge_method"` + Resource string `json:"resource"` +} + +type MCPOAuthConsentInput struct { + Authorization MCPOAuthAuthorizeInput `json:"authorization"` + Approved bool `json:"approved"` + Scope string `json:"scope"` + ReadOnly *bool `json:"read_only"` +} + +type MCPOAuthConsent struct { + ClientID string `json:"client_id"` + ClientName string `json:"client_name"` + RedirectURI string `json:"redirect_uri"` + Resource string `json:"resource"` + Scope string `json:"scope"` +} + +type MCPOAuthGrant struct { + ID string `json:"id"` + ClientID string `json:"client_id"` + ClientName string `json:"client_name"` + Scope string `json:"scope"` + ReadOnly bool `json:"read_only"` + CreatedAt time.Time `json:"created_at"` + ExpiresAt time.Time `json:"expires_at"` + LastUsedAt *time.Time `json:"last_used_at"` + RevokedAt *time.Time `json:"revoked_at"` + Invalidated bool `json:"invalidated"` + UserID int64 `json:"-"` + TokenVersion int64 `json:"-"` + Resource string `json:"-"` +} + +type MCPPrincipal struct { + GrantID string + UserID int64 + Role string + Scope string + ReadOnly bool + Concurrency int + Email string + Resource string +} + +type MCPOAuthTokenInput struct { + GrantType string `json:"grant_type"` + ClientID string `json:"client_id"` + Code string `json:"code"` + RedirectURI string `json:"redirect_uri"` + CodeVerifier string `json:"code_verifier"` + RefreshToken string `json:"refresh_token"` + Resource string `json:"resource"` + Scope string `json:"scope"` +} + +type MCPOAuthTokenResponse struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + Scope string `json:"scope"` +} + +// Authorization codes and credentials contain digests only; bearer secrets are +// returned directly to the client and never reach persistence. +type MCPOAuthCode struct { + Hash, GrantID, ClientID, RedirectURI, Resource, CodeChallenge string + ExpiresAt time.Time + ConsumedAt *time.Time +} + +type MCPOAuthCredential struct { + Hash, GrantID, Kind string + ExpiresAt time.Time + UsedAt *time.Time +} + +type MCPOAuthRepository interface { + // ClientIDKey returns the persistent key that signs stateless client IDs. + ClientIDKey(context.Context) ([]byte, error) + CreateAuthorization(context.Context, *MCPOAuthGrant, *MCPOAuthCode, int) error + GetCode(context.Context, string) (*MCPOAuthCode, error) + GetCredential(context.Context, string) (*MCPOAuthCredential, error) + GetGrant(context.Context, string) (*MCPOAuthGrant, error) + // ExchangeCode and RotateRefresh atomically consume and issue credentials. + // Replays revoke the entire grant and COMMIT that revocation before erroring. + ExchangeCode(context.Context, string, string, time.Time, *MCPOAuthCredential, *MCPOAuthCredential) error + RotateRefresh(context.Context, string, string, time.Time, *MCPOAuthCredential, *MCPOAuthCredential) error + 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 { + repo MCPOAuthRepository + users UserRepository +} + +func NewMCPOAuthService(repo MCPOAuthRepository, users UserRepository) *MCPOAuthService { + return &MCPOAuthService{repo: repo, users: users} +} + +func (s *MCPOAuthService) Register(ctx context.Context, input MCPOAuthRegisterInput) (*MCPOAuthClient, error) { + input.ClientName = strings.TrimSpace(input.ClientName) + if input.ClientName == "" { + input.ClientName = "MCP client" + } + 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") + } + if len(input.RedirectURIs) < 1 || len(input.RedirectURIs) > 10 { + return nil, mcpOAuthError("invalid_redirect_uri", "Register between 1 and 10 redirect URIs") + } + redirects := make([]string, 0, len(input.RedirectURIs)) + for _, uri := range input.RedirectURIs { + if !validMCPRedirectURI(uri) { + return nil, mcpOAuthError("invalid_redirect_uri", "Redirect URIs must use HTTPS or HTTP loopback, without fragments, credentials, or wildcards") + } + if !containsMCPString(redirects, uri) { + redirects = append(redirects, uri) + } + } + grants := input.GrantTypes + if len(grants) == 0 { + grants = []string{"authorization_code", "refresh_token"} + } + if len(grants) > 2 || !containsMCPString(grants, "authorization_code") { + return nil, mcpOAuthError("invalid_client_metadata", "authorization_code is required") + } + for _, grant := range grants { + if grant != "authorization_code" && grant != "refresh_token" { + return nil, mcpOAuthError("invalid_client_metadata", "Unsupported grant type") + } + } + if len(input.ResponseTypes) != 0 && (len(input.ResponseTypes) != 1 || input.ResponseTypes[0] != "code") { + return nil, mcpOAuthError("invalid_client_metadata", "Only the code response type is supported") + } + nonce := make([]byte, 16) + if _, err := rand.Read(nonce); err != nil { + return nil, err + } + claims := mcpOAuthClientClaims{Name: input.ClientName, GrantTypes: append([]string(nil), grants...)} + for _, uri := range redirects { + claims.RedirectDigests = append(claims.RedirectDigests, mcpOAuthRedirectDigest(uri)) + } + id, err := s.encodeClientID(ctx, base64.RawURLEncoding.EncodeToString(nonce), &claims) + if err != nil { + return nil, err + } + return &MCPOAuthClient{ + ClientID: id, ClientName: input.ClientName, RedirectURIs: redirects, + GrantTypes: claims.GrantTypes, ResponseTypes: []string{"code"}, + TokenEndpointAuthMethod: "none", ClientIDIssuedAt: time.Now().UTC().Unix(), + }, nil +} + +// Registration is unauthenticated, so it is never persisted: the client ID is +// the signed metadata itself. Nothing is stored until a user approves a client, +// leaving no storage or shared capacity for anonymous registrations to exhaust. +// Redirect URIs are embedded as digests to keep IDs short enough for URLs. +// +// Format: mcp_client_... +// The random nonce leads, so truncated IDs still tell clients apart. +type mcpOAuthClientClaims struct { + Name string `json:"n"` + RedirectDigests []string `json:"r"` + GrantTypes []string `json:"g"` +} + +func (c *mcpOAuthClientClaims) allowsRedirect(uri string) bool { + return containsMCPString(c.RedirectDigests, mcpOAuthRedirectDigest(uri)) +} + +func mcpOAuthRedirectDigest(uri string) string { + sum := sha256.Sum256([]byte(uri)) + return base64.RawURLEncoding.EncodeToString(sum[:]) +} + +func (s *MCPOAuthService) encodeClientID(ctx context.Context, nonce string, claims *mcpOAuthClientClaims) (string, error) { + raw, err := json.Marshal(claims) + if err != nil { + return "", err + } + signed := nonce + "." + base64.RawURLEncoding.EncodeToString(raw) + signature, err := s.signClientID(ctx, signed) + if err != nil { + return "", err + } + return mcpOAuthClientIDPrefix + signed + "." + signature, nil +} + +// client verifies a client ID and returns its metadata. IDs that were not +// issued by this server yield ErrMCPOAuthNotFound. +func (s *MCPOAuthService) client(ctx context.Context, id string) (*mcpOAuthClientClaims, error) { + if len(id) > mcpOAuthClientIDMaxLength || !strings.HasPrefix(id, mcpOAuthClientIDPrefix) { + return nil, ErrMCPOAuthNotFound + } + signed := id[len(mcpOAuthClientIDPrefix):] + dot := strings.LastIndexByte(signed, '.') + if dot < 0 { + return nil, ErrMCPOAuthNotFound + } + signed, signature := signed[:dot], signed[dot+1:] + expected, err := s.signClientID(ctx, signed) + if err != nil { + return nil, err + } + if !hmac.Equal([]byte(signature), []byte(expected)) { + return nil, ErrMCPOAuthNotFound + } + _, payload, ok := strings.Cut(signed, ".") + if !ok { + return nil, ErrMCPOAuthNotFound + } + raw, err := base64.RawURLEncoding.DecodeString(payload) + if err != nil { + return nil, ErrMCPOAuthNotFound + } + var claims mcpOAuthClientClaims + if err := json.Unmarshal(raw, &claims); err != nil { + return nil, ErrMCPOAuthNotFound + } + return &claims, nil +} + +func (s *MCPOAuthService) signClientID(ctx context.Context, payload string) (string, error) { + key, err := s.repo.ClientIDKey(ctx) + if err != nil { + return "", err + } + mac := hmac.New(sha256.New, key) + _, _ = mac.Write([]byte(payload)) + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil +} + +func validMCPClientName(name string) bool { + 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 + } + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" || u.User != nil || u.Opaque != "" || u.Fragment != "" { + return false + } + if u.Scheme == "https" { + return true + } + if u.Scheme != "http" { + return false + } + switch strings.ToLower(u.Hostname()) { + case "localhost", "127.0.0.1", "::1": + return true + default: + return false + } +} + +func containsMCPString(values []string, want string) bool { + for _, value := range values { + if value == want { + return true + } + } + return false +} + +func validMCPOAuthScope(scope string) bool { + fields := strings.Fields(scope) + return len(fields) == 0 || (len(fields) == 1 && fields[0] == MCPOAuthScope) +} + +func (s *MCPOAuthService) validateAuthorization(ctx context.Context, userID int64, input MCPOAuthAuthorizeInput, resource string) (*mcpOAuthClientClaims, *User, error) { + client, err := s.client(ctx, input.ClientID) + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil, nil, mcpOAuthError("invalid_client", "Unknown client") + } + if err != nil { + return nil, nil, err + } + if !client.allowsRedirect(input.RedirectURI) { + return nil, nil, mcpOAuthError("invalid_request", "redirect_uri must exactly match a registered URI") + } + if input.ResponseType != "code" { + return nil, nil, mcpOAuthError("unsupported_response_type", "Only response_type=code is supported") + } + if !validMCPOAuthScope(input.Scope) { + return nil, nil, mcpOAuthError("invalid_scope", "Only the mcp OAuth scope is supported") + } + if resource == "" || input.Resource != resource { + return nil, nil, mcpOAuthError("invalid_target", "resource must identify this MCP endpoint") + } + challenge, decodeErr := base64.RawURLEncoding.DecodeString(input.CodeChallenge) + if input.CodeChallengeMethod != "S256" || decodeErr != nil || len(challenge) != sha256.Size || base64.RawURLEncoding.EncodeToString(challenge) != input.CodeChallenge { + return nil, nil, mcpOAuthError("invalid_request", "A valid S256 PKCE code challenge is required") + } + if len(input.State) > 2048 { + return nil, nil, mcpOAuthError("invalid_request", "state is too long") + } + user, err := s.users.GetByID(ctx, userID) + if errors.Is(err, ErrUserNotFound) || (err == nil && (user == nil || !user.IsActive() || user.DeletedAt != nil)) { + return nil, nil, mcpOAuthError("access_denied", "User account is not active") + } + if err != nil { + return nil, nil, err + } + return client, user, nil +} + +func (s *MCPOAuthService) Preview(ctx context.Context, userID int64, input MCPOAuthAuthorizeInput, resource string) (*MCPOAuthConsent, error) { + client, _, err := s.validateAuthorization(ctx, userID, input, resource) + if err != nil { + return nil, err + } + return &MCPOAuthConsent{ClientID: input.ClientID, ClientName: client.Name, RedirectURI: input.RedirectURI, Resource: resource, Scope: MCPOAuthScope}, nil +} + +func (s *MCPOAuthService) Decide(ctx context.Context, userID int64, input MCPOAuthConsentInput, resource string) (string, error) { + client, user, err := s.validateAuthorization(ctx, userID, input.Authorization, resource) + if err != nil { + return "", err + } + redirect, _ := url.Parse(input.Authorization.RedirectURI) + query := redirect.Query() + // Registered URI queries are retained; OAuth response fields are authoritative. + query.Del("code") + query.Del("error") + query.Del("error_description") + query.Del("state") + if input.Authorization.State != "" { + query.Set("state", input.Authorization.State) + } + if !input.Approved { + query.Set("error", "access_denied") + redirect.RawQuery = query.Encode() + return redirect.String(), nil + } + if input.Scope == "" { + input.Scope = MCPScopeUser + } + if input.Scope != MCPScopeUser && input.Scope != MCPScopeAdmin { + return "", mcpOAuthError("invalid_scope", "Management permission must be user or admin") + } + if input.Scope == MCPScopeAdmin && !user.IsAdmin() { + return "", mcpOAuthError("access_denied", "Only administrators can authorize admin access") + } + id, err := mcpOAuthSecret("") + if err != nil { + return "", err + } + rawCode, err := mcpOAuthSecret("mcp_code_") + if err != nil { + return "", err + } + now := time.Now().UTC() + grant := &MCPOAuthGrant{ID: id, ClientID: input.Authorization.ClientID, ClientName: client.Name, + UserID: user.ID, TokenVersion: resolvedTokenVersion(user), Resource: resource, + Scope: input.Scope, ReadOnly: true, CreatedAt: now, ExpiresAt: now.Add(MCPOAuthGrantLifetime)} + if input.ReadOnly != nil { + grant.ReadOnly = *input.ReadOnly + } + code := &MCPOAuthCode{Hash: hashMCPOAuthSecret(rawCode), GrantID: grant.ID, ClientID: grant.ClientID, + RedirectURI: input.Authorization.RedirectURI, Resource: resource, CodeChallenge: input.Authorization.CodeChallenge, + ExpiresAt: now.Add(MCPOAuthCodeLifetime)} + if err := s.repo.CreateAuthorization(ctx, grant, code, MCPOAuthGrantLimit); err != nil { + return "", err + } + query.Set("code", rawCode) + redirect.RawQuery = query.Encode() + return redirect.String(), nil +} + +func (s *MCPOAuthService) Token(ctx context.Context, input MCPOAuthTokenInput, resource string) (*MCPOAuthTokenResponse, error) { + client, err := s.client(ctx, input.ClientID) + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil, mcpOAuthError("invalid_client", "Unknown client") + } + if err != nil { + return nil, err + } + if !validMCPOAuthScope(input.Scope) { + return nil, mcpOAuthError("invalid_scope", "Only the mcp OAuth scope is supported") + } + if input.GrantType != "authorization_code" && input.GrantType != "refresh_token" { + return nil, mcpOAuthError("unsupported_grant_type", "Unsupported grant type") + } + if !containsMCPString(client.GrantTypes, input.GrantType) { + return nil, mcpOAuthError("unauthorized_client", "Client is not registered for this grant type") + } + var grantID, credentialHash string + if input.GrantType == "authorization_code" { + if !validMCPOAuthSecret(input.Code, "mcp_code_") || !validMCPCodeVerifier(input.CodeVerifier) { + return nil, mcpOAuthError("invalid_grant", "Invalid authorization code or verifier") + } + credentialHash = hashMCPOAuthSecret(input.Code) + code, err := s.repo.GetCode(ctx, credentialHash) + if errors.Is(err, ErrMCPOAuthNotFound) || (err == nil && code == nil) { + return nil, mcpOAuthError("invalid_grant", "Invalid authorization code") + } + if err != nil { + return nil, err + } + sum := sha256.Sum256([]byte(input.CodeVerifier)) + challenge := base64.RawURLEncoding.EncodeToString(sum[:]) + if code.ClientID != input.ClientID || code.RedirectURI != input.RedirectURI || resource == "" || input.Resource != resource || code.Resource != resource || subtle.ConstantTimeCompare([]byte(challenge), []byte(code.CodeChallenge)) != 1 { + return nil, mcpOAuthError("invalid_grant", "Authorization code binding or PKCE verification failed") + } + grantID = code.GrantID + } else { + if !validMCPOAuthSecret(input.RefreshToken, "mcp_rt_") { + return nil, mcpOAuthError("invalid_grant", "Invalid refresh token") + } + credentialHash = hashMCPOAuthSecret(input.RefreshToken) + credential, err := s.repo.GetCredential(ctx, credentialHash) + if errors.Is(err, ErrMCPOAuthNotFound) || (err == nil && (credential == nil || credential.Kind != "refresh")) { + return nil, mcpOAuthError("invalid_grant", "Invalid refresh token") + } + if err != nil { + return nil, err + } + grantID = credential.GrantID + } + grant, err := s.repo.GetGrant(ctx, grantID) + if errors.Is(err, ErrMCPOAuthNotFound) || (err == nil && grant == nil) { + return nil, mcpOAuthError("invalid_grant", "Authorization is no longer valid") + } + if err != nil { + return nil, err + } + if grant.ClientID != input.ClientID || resource == "" || grant.Resource != resource || (input.Resource != "" && input.Resource != grant.Resource) { + return nil, mcpOAuthError("invalid_grant", "Token is not bound to this client and resource") + } + if _, err := s.validateGrant(ctx, grant); err != nil { + if errors.Is(err, ErrMCPOAuthInvalidToken) { + return nil, mcpOAuthError("invalid_grant", "Authorization is no longer valid") + } + return nil, err + } + now := time.Now().UTC() + result, access, refresh, err := newMCPOAuthTokens(grant, now, containsMCPString(client.GrantTypes, "refresh_token")) + if err != nil { + return nil, err + } + if input.GrantType == "authorization_code" { + err = s.repo.ExchangeCode(ctx, credentialHash, grant.ID, now, access, refresh) + } else { + err = s.repo.RotateRefresh(ctx, credentialHash, grant.ID, now, access, refresh) + } + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil, mcpOAuthError("invalid_grant", "Code or refresh token was expired, revoked, or already used") + } + if err != nil { + return nil, err + } + return result, nil +} + +func newMCPOAuthTokens(grant *MCPOAuthGrant, now time.Time, includeRefresh bool) (*MCPOAuthTokenResponse, *MCPOAuthCredential, *MCPOAuthCredential, error) { + access, err := mcpOAuthSecret("mcp_at_") + if err != nil { + return nil, nil, nil, err + } + expiresAt := now.Add(MCPOAuthAccessLifetime) + if grant.ExpiresAt.Before(expiresAt) { + expiresAt = grant.ExpiresAt + } + result := &MCPOAuthTokenResponse{AccessToken: access, TokenType: "Bearer", ExpiresIn: int64(expiresAt.Sub(now) / time.Second), Scope: MCPOAuthScope} + accessRecord := &MCPOAuthCredential{Hash: hashMCPOAuthSecret(access), GrantID: grant.ID, Kind: "access", ExpiresAt: expiresAt} + var refreshRecord *MCPOAuthCredential + if includeRefresh { + refresh, err := mcpOAuthSecret("mcp_rt_") + if err != nil { + return nil, nil, nil, err + } + result.RefreshToken = refresh + refreshRecord = &MCPOAuthCredential{Hash: hashMCPOAuthSecret(refresh), GrantID: grant.ID, Kind: "refresh", ExpiresAt: grant.ExpiresAt} + } + return result, accessRecord, refreshRecord, nil +} + +func validMCPCodeVerifier(value string) bool { + if len(value) < 43 || len(value) > 128 { + return false + } + for _, ch := range value { + if (ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') && (ch < '0' || ch > '9') && ch != '-' && ch != '.' && ch != '_' && ch != '~' { + return false + } + } + return true +} + +func (s *MCPOAuthService) validateGrant(ctx context.Context, grant *MCPOAuthGrant) (*User, error) { + if grant == nil || grant.RevokedAt != nil || !time.Now().Before(grant.ExpiresAt) || (grant.Scope != MCPScopeUser && grant.Scope != MCPScopeAdmin) { + return nil, ErrMCPOAuthInvalidToken + } + user, err := s.users.GetByID(ctx, grant.UserID) + if errors.Is(err, ErrUserNotFound) { + return nil, ErrMCPOAuthInvalidToken + } + if err != nil { + return nil, err + } + if mcpGrantInvalidated(grant, user) { + return nil, ErrMCPOAuthInvalidToken + } + return user, nil +} + +func mcpGrantInvalidated(grant *MCPOAuthGrant, user *User) bool { + return user == nil || !user.IsActive() || user.DeletedAt != nil || grant.TokenVersion != resolvedTokenVersion(user) || (grant.Scope == MCPScopeAdmin && !user.IsAdmin()) +} + +func (s *MCPOAuthService) Authenticate(ctx context.Context, raw string) (*MCPPrincipal, error) { + if !validMCPOAuthSecret(raw, "mcp_at_") { + return nil, ErrMCPOAuthInvalidToken + } + credential, err := s.repo.GetCredential(ctx, hashMCPOAuthSecret(raw)) + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil, ErrMCPOAuthInvalidToken + } + if err != nil { + return nil, err + } + now := time.Now().UTC() + if credential == nil || credential.Kind != "access" || !now.Before(credential.ExpiresAt) { + return nil, ErrMCPOAuthInvalidToken + } + grant, err := s.repo.GetGrant(ctx, credential.GrantID) + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil, ErrMCPOAuthInvalidToken + } + if err != nil { + return nil, err + } + user, err := s.validateGrant(ctx, grant) + if err != nil { + return nil, err + } + 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 &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 +} + +func (s *MCPOAuthService) ListGrants(ctx context.Context, userID int64) ([]*MCPOAuthGrant, error) { + user, err := s.users.GetByID(ctx, userID) + if err != nil { + return nil, err + } + grants, err := s.repo.ListGrants(ctx, userID) + if err != nil { + return nil, err + } + for _, grant := range grants { + grant.Invalidated = mcpGrantInvalidated(grant, user) + } + return grants, nil +} + +func (s *MCPOAuthService) RevokeGrant(ctx context.Context, userID int64, id string) error { + err := s.repo.RevokeGrant(ctx, userID, id, time.Now().UTC()) + if errors.Is(err, ErrMCPOAuthNotFound) { + return ErrMCPOAuthGrantNotFound + } + 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 + } + credential, err := s.repo.GetCredential(ctx, hashMCPOAuthSecret(raw)) + if errors.Is(err, ErrMCPOAuthNotFound) || (err == nil && credential == nil) { + return nil + } + if err != nil { + return err + } + grant, err := s.repo.GetGrant(ctx, credential.GrantID) + if errors.Is(err, ErrMCPOAuthNotFound) || (err == nil && (grant == nil || grant.ClientID != clientID)) { + return nil + } + if err != nil { + return err + } + err = s.repo.RevokeGrant(ctx, grant.UserID, grant.ID, time.Now().UTC()) + if errors.Is(err, ErrMCPOAuthNotFound) { + return nil + } + return err +} + +func mcpOAuthSecret(prefix string) (string, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", err + } + return prefix + base64.RawURLEncoding.EncodeToString(raw), nil +} + +func validMCPOAuthSecret(raw, prefix string) bool { + if len(raw) != len(prefix)+43 || !strings.HasPrefix(raw, prefix) { + return false + } + decoded, err := base64.RawURLEncoding.DecodeString(raw[len(prefix):]) + return err == nil && len(decoded) == 32 && base64.RawURLEncoding.EncodeToString(decoded) == raw[len(prefix):] +} + +func hashMCPOAuthSecret(raw string) string { + sum := sha256.Sum256([]byte(raw)) + return hex.EncodeToString(sum[:]) +} diff --git a/backend/internal/service/mcp_oauth_service_test.go b/backend/internal/service/mcp_oauth_service_test.go new file mode 100644 index 0000000000..8cda7496d4 --- /dev/null +++ b/backend/internal/service/mcp_oauth_service_test.go @@ -0,0 +1,708 @@ +//go:build unit + +package service + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type mcpOAuthMemoryRepo struct { + mu sync.Mutex + clientIDKey []byte + grants map[string]*MCPOAuthGrant + codes map[string]*MCPOAuthCode + credentials map[string]*MCPOAuthCredential + touches int +} + +func (r *mcpOAuthMemoryRepo) ClientIDKey(context.Context) ([]byte, error) { + if r.clientIDKey == nil { + return []byte("mcp-oauth-service-test-client-id-key"), nil + } + return r.clientIDKey, nil +} + +func (r *mcpOAuthMemoryRepo) CreateAuthorization(_ context.Context, grant *MCPOAuthGrant, code *MCPOAuthCode, limit int) error { + r.mu.Lock() + defer r.mu.Unlock() + count := 0 + for _, existing := range r.grants { + if existing.UserID == grant.UserID && existing.RevokedAt == nil && existing.ExpiresAt.After(grant.CreatedAt) { + count++ + } + } + if count >= limit { + return ErrMCPOAuthGrantLimit + } + r.grants[grant.ID], r.codes[code.Hash] = grant, code + return nil +} + +func (r *mcpOAuthMemoryRepo) GetCode(_ context.Context, hash string) (*MCPOAuthCode, error) { + r.mu.Lock() + defer r.mu.Unlock() + if code := r.codes[hash]; code != nil { + copy := *code + return ©, nil + } + return nil, ErrMCPOAuthNotFound +} + +func (r *mcpOAuthMemoryRepo) GetCredential(_ context.Context, hash string) (*MCPOAuthCredential, error) { + r.mu.Lock() + defer r.mu.Unlock() + if credential := r.credentials[hash]; credential != nil { + copy := *credential + return ©, nil + } + return nil, ErrMCPOAuthNotFound +} + +func (r *mcpOAuthMemoryRepo) GetGrant(_ context.Context, id string) (*MCPOAuthGrant, error) { + r.mu.Lock() + defer r.mu.Unlock() + if grant := r.grants[id]; grant != nil { + copy := *grant + return ©, nil + } + return nil, ErrMCPOAuthNotFound +} + +func (r *mcpOAuthMemoryRepo) consume(hash, grantID string, now time.Time, access, refresh *MCPOAuthCredential, rotating bool) error { + r.mu.Lock() + defer r.mu.Unlock() + grant := r.grants[grantID] + if grant == nil || grant.RevokedAt != nil || !now.Before(grant.ExpiresAt) { + return ErrMCPOAuthNotFound + } + var expiry time.Time + var used **time.Time + if rotating { + old := r.credentials[hash] + if old == nil || old.GrantID != grantID || old.Kind != "refresh" { + return ErrMCPOAuthNotFound + } + expiry, used = old.ExpiresAt, &old.UsedAt + } else { + code := r.codes[hash] + if code == nil || code.GrantID != grantID { + return ErrMCPOAuthNotFound + } + expiry, used = code.ExpiresAt, &code.ConsumedAt + } + if *used != nil { + grant.RevokedAt = &now + return ErrMCPOAuthNotFound + } + if !now.Before(expiry) { + return ErrMCPOAuthNotFound + } + *used = &now + r.credentials[access.Hash] = access + if refresh != nil { + r.credentials[refresh.Hash] = refresh + } + return nil +} + +func (r *mcpOAuthMemoryRepo) ExchangeCode(_ context.Context, hash, grantID string, now time.Time, access, refresh *MCPOAuthCredential) error { + return r.consume(hash, grantID, now, access, refresh, false) +} + +func (r *mcpOAuthMemoryRepo) RotateRefresh(_ context.Context, hash, grantID string, now time.Time, access, refresh *MCPOAuthCredential) error { + return r.consume(hash, grantID, now, access, refresh, true) +} + +func (r *mcpOAuthMemoryRepo) TouchGrant(_ context.Context, id string, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + grant := r.grants[id] + if grant == nil || grant.RevokedAt != nil || !now.Before(grant.ExpiresAt) { + return ErrMCPOAuthNotFound + } + grant.LastUsedAt = &now + r.touches++ + return nil +} + +func (r *mcpOAuthMemoryRepo) ListGrants(_ context.Context, userID int64) ([]*MCPOAuthGrant, error) { + r.mu.Lock() + defer r.mu.Unlock() + grants := []*MCPOAuthGrant{} + for _, grant := range r.grants { + if grant.UserID == userID { + copy := *grant + grants = append(grants, ©) + } + } + return grants, nil +} + +func (r *mcpOAuthMemoryRepo) RevokeGrant(_ context.Context, userID int64, id string, now time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + grant := r.grants[id] + if grant == nil || grant.UserID != userID { + return ErrMCPOAuthNotFound + } + if grant.RevokedAt == nil { + grant.RevokedAt = &now + } + 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 +} + +func (r *mcpOAuthUserRepo) GetByID(_ context.Context, id int64) (*User, error) { + if r.user == nil || r.user.ID != id { + return nil, ErrUserNotFound + } + copy := *r.user + return ©, nil +} + +const mcpTestResource = "https://platform.example/api/v1/mcp" + +type mcpOAuthFixture struct { + s *MCPOAuthService + r *mcpOAuthMemoryRepo + u *mcpOAuthUserRepo + client *MCPOAuthClient + authorize MCPOAuthAuthorizeInput + verifier string +} + +func newMCPOAuthFixture(t *testing.T) *mcpOAuthFixture { + t.Helper() + r := &mcpOAuthMemoryRepo{grants: map[string]*MCPOAuthGrant{}, codes: map[string]*MCPOAuthCode{}, credentials: map[string]*MCPOAuthCredential{}} + u := &mcpOAuthUserRepo{user: &User{ID: 7, Role: RoleUser, Status: StatusActive, Email: "user@example.com", PasswordHash: "original", Concurrency: 3}} + s := NewMCPOAuthService(r, u) + client, err := s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: "My MCP client", RedirectURIs: []string{"http://127.0.0.1:2345/callback?existing=1", "https://client.example/callback"}}) + require.NoError(t, err) + verifier := strings.Repeat("a", 43) + sum := sha256.Sum256([]byte(verifier)) + return &mcpOAuthFixture{s: s, r: r, u: u, client: client, verifier: verifier, + authorize: MCPOAuthAuthorizeInput{ResponseType: "code", ClientID: client.ClientID, RedirectURI: client.RedirectURIs[0], Scope: "mcp", State: "opaque&state", CodeChallenge: base64.RawURLEncoding.EncodeToString(sum[:]), CodeChallengeMethod: "S256", Resource: mcpTestResource}} +} + +func (f *mcpOAuthFixture) code(t *testing.T, scope string, readOnly *bool) MCPOAuthTokenInput { + t.Helper() + redirect, err := f.s.Decide(context.Background(), 7, MCPOAuthConsentInput{Authorization: f.authorize, Approved: true, Scope: scope, ReadOnly: readOnly}, mcpTestResource) + require.NoError(t, err) + u, err := url.Parse(redirect) + require.NoError(t, err) + require.Equal(t, "opaque&state", u.Query().Get("state")) + require.Equal(t, "1", u.Query().Get("existing")) + return MCPOAuthTokenInput{GrantType: "authorization_code", ClientID: f.client.ClientID, Code: u.Query().Get("code"), RedirectURI: f.authorize.RedirectURI, CodeVerifier: f.verifier, Resource: mcpTestResource} +} + +func (f *mcpOAuthFixture) tokens(t *testing.T) *MCPOAuthTokenResponse { + t.Helper() + tokens, err := f.s.Token(context.Background(), f.code(t, "", nil), mcpTestResource) + require.NoError(t, err) + return tokens +} + +func requireMCPOAuthError(t *testing.T, err error, code string) { + t.Helper() + var oauthErr *MCPOAuthError + require.ErrorAs(t, err, &oauthErr) + require.Equal(t, code, oauthErr.Code) +} + +func TestMCPOAuthRegistrationValidatesRedirectsAndPublicClientMetadata(t *testing.T) { + f := newMCPOAuthFixture(t) + require.Equal(t, "none", f.client.TokenEndpointAuthMethod) + require.Equal(t, []string{"authorization_code", "refresh_token"}, f.client.GrantTypes) + for _, uri := range []string{"https://client.example/callback", "http://localhost:3000/cb", "http://[::1]:3000/cb", "http://127.0.0.1/cb"} { + _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{uri}}) + require.NoError(t, err, uri) + } + for _, uri := range []string{"http://client.example/cb", "https://client.example/cb#fragment", "https://user:password@client.example/cb", "https://*.example/cb", "file:///callback", "https:///callback", "http://127.0.0.1.evil.example/cb", "https://client.example/cb#"} { + _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{uri}}) + requireMCPOAuthError(t, err, "invalid_redirect_uri") + } + _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}, TokenEndpointAuthMethod: "client_secret_post"}) + requireMCPOAuthError(t, err, "invalid_client_metadata") +} + +func TestMCPOAuthAuthorizationRequiresPKCEResourceAndRegisteredRedirect(t *testing.T) { + f := newMCPOAuthFixture(t) + preview, err := f.s.Preview(context.Background(), 7, f.authorize, mcpTestResource) + require.NoError(t, err) + require.Equal(t, MCPOAuthScope, preview.Scope) + for _, tc := range []struct { + name, code string + mutate func(*MCPOAuthAuthorizeInput) + }{ + {"redirect", "invalid_request", func(a *MCPOAuthAuthorizeInput) { a.RedirectURI += "x" }}, + {"client", "invalid_client", func(a *MCPOAuthAuthorizeInput) { a.ClientID = "unknown" }}, + {"response", "unsupported_response_type", func(a *MCPOAuthAuthorizeInput) { a.ResponseType = "token" }}, + {"scope", "invalid_scope", func(a *MCPOAuthAuthorizeInput) { a.Scope = "mcp admin" }}, + {"resource", "invalid_target", func(a *MCPOAuthAuthorizeInput) { a.Resource = "https://other.example/mcp" }}, + {"missing resource", "invalid_target", func(a *MCPOAuthAuthorizeInput) { a.Resource = "" }}, + {"plain PKCE", "invalid_request", func(a *MCPOAuthAuthorizeInput) { a.CodeChallengeMethod = "plain" }}, + {"missing PKCE", "invalid_request", func(a *MCPOAuthAuthorizeInput) { a.CodeChallenge = "" }}, + } { + t.Run(tc.name, func(t *testing.T) { + input := f.authorize + tc.mutate(&input) + _, err := f.s.Preview(context.Background(), 7, input, mcpTestResource) + requireMCPOAuthError(t, err, tc.code) + }) + } + redirect, err := f.s.Decide(context.Background(), 7, MCPOAuthConsentInput{Authorization: f.authorize}, mcpTestResource) + require.NoError(t, err) + u, err := url.Parse(redirect) + require.NoError(t, err) + require.Equal(t, "access_denied", u.Query().Get("error")) + require.Equal(t, f.authorize.State, u.Query().Get("state")) + require.Empty(t, f.r.grants) +} + +func TestMCPOAuthCodeBindingFailuresDoNotConsumeCode(t *testing.T) { + for _, name := range []string{"client", "redirect", "resource", "missing resource", "verifier"} { + t.Run(name, func(t *testing.T) { + f := newMCPOAuthFixture(t) + valid := f.code(t, "", nil) + invalid := valid + switch name { + case "client": + client, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: f.client.RedirectURIs}) + require.NoError(t, err) + invalid.ClientID = client.ClientID + case "redirect": + invalid.RedirectURI = f.client.RedirectURIs[1] + case "resource": + invalid.Resource = "https://other.example/mcp" + case "missing resource": + invalid.Resource = "" + case "verifier": + invalid.CodeVerifier = strings.Repeat("b", 43) + } + _, err := f.s.Token(context.Background(), invalid, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + _, err = f.s.Token(context.Background(), valid, mcpTestResource) + require.NoError(t, err) + }) + } +} + +func TestMCPOAuthCodeReplayRevokesEntireGrant(t *testing.T) { + f := newMCPOAuthFixture(t) + input := f.code(t, "", nil) + tokens, err := f.s.Token(context.Background(), input, mcpTestResource) + require.NoError(t, err) + principal, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.NoError(t, err) + require.Equal(t, MCPScopeUser, principal.Scope) + require.True(t, principal.ReadOnly) + require.Equal(t, mcpTestResource, principal.Resource) + require.Equal(t, int64(600), tokens.ExpiresIn) + _, err = f.s.Token(context.Background(), input, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + _, 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") +} + +func TestMCPOAuthRefreshRotationInheritsResourceAndDetectsReplay(t *testing.T) { + f := newMCPOAuthFixture(t) + first := f.tokens(t) + input := MCPOAuthTokenInput{GrantType: "refresh_token", ClientID: f.client.ClientID, RefreshToken: first.RefreshToken} + second, err := f.s.Token(context.Background(), input, mcpTestResource) + require.NoError(t, err) + require.NotEqual(t, first.AccessToken, second.AccessToken) + require.NotEqual(t, first.RefreshToken, second.RefreshToken) + _, err = f.s.Authenticate(context.Background(), first.AccessToken) + require.NoError(t, err, "ordinary refresh must preserve in-flight access credentials") + _, err = f.s.Authenticate(context.Background(), second.AccessToken) + require.NoError(t, err) + require.Equal(t, f.r.credentials[hashMCPOAuthSecret(first.RefreshToken)].ExpiresAt, f.r.credentials[hashMCPOAuthSecret(second.RefreshToken)].ExpiresAt) + _, err = f.s.Token(context.Background(), input, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + _, err = f.s.Authenticate(context.Background(), second.AccessToken) + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) + input.RefreshToken = second.RefreshToken + _, err = f.s.Token(context.Background(), input, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") +} + +func TestMCPOAuthRefreshRejectsOtherClientResourceAndScope(t *testing.T) { + f := newMCPOAuthFixture(t) + tokens := f.tokens(t) + other, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: f.client.RedirectURIs}) + require.NoError(t, err) + for _, tc := range []struct{ client, resource, scope, code string }{ + {other.ClientID, "", "", "invalid_grant"}, + {f.client.ClientID, "https://other.example/mcp", "", "invalid_grant"}, + {f.client.ClientID, "", "admin", "invalid_scope"}, + } { + _, err := f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "refresh_token", ClientID: tc.client, RefreshToken: tokens.RefreshToken, Resource: tc.resource, Scope: tc.scope}, mcpTestResource) + requireMCPOAuthError(t, err, tc.code) + } + _, err = f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "refresh_token", ClientID: f.client.ClientID, RefreshToken: tokens.RefreshToken, Resource: mcpTestResource}, mcpTestResource) + require.NoError(t, err) +} + +func TestMCPOAuthRechecksLiveOwnerOnExchangeRefreshAndAccess(t *testing.T) { + for _, operation := range []string{"exchange", "refresh", "access"} { + for _, change := range []string{"password", "email", "disabled", "deleted", "missing", "demoted"} { + t.Run(operation+"/"+change, func(t *testing.T) { + f := newMCPOAuthFixture(t) + f.u.user.Role = RoleAdmin + code := f.code(t, MCPScopeAdmin, nil) + var tokens *MCPOAuthTokenResponse + if operation != "exchange" { + var err error + tokens, err = f.s.Token(context.Background(), code, mcpTestResource) + require.NoError(t, err) + } + switch change { + case "password": + f.u.user.PasswordHash = "changed" + case "email": + f.u.user.Email = "new@example.com" + case "disabled": + f.u.user.Status = StatusDisabled + case "deleted": + now := time.Now() + f.u.user.DeletedAt = &now + case "missing": + f.u.user = nil + case "demoted": + f.u.user.Role = RoleUser + } + switch operation { + case "exchange": + _, err := f.s.Token(context.Background(), code, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + case "refresh": + _, err := f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "refresh_token", ClientID: f.client.ClientID, RefreshToken: tokens.RefreshToken}, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + case "access": + _, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) + } + }) + } + } +} + +func TestMCPOAuthExpiryAndCredentialTypeBoundaries(t *testing.T) { + t.Run("code", func(t *testing.T) { + f := newMCPOAuthFixture(t) + input := f.code(t, "", nil) + f.r.codes[hashMCPOAuthSecret(input.Code)].ExpiresAt = time.Now().Add(-time.Second) + _, err := f.s.Token(context.Background(), input, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + }) + for _, kind := range []string{"access", "refresh", "grant"} { + t.Run(kind, func(t *testing.T) { + f := newMCPOAuthFixture(t) + tokens := f.tokens(t) + principal, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.NoError(t, err) + past := time.Now().Add(-time.Second) + switch kind { + case "access": + f.r.credentials[hashMCPOAuthSecret(tokens.AccessToken)].ExpiresAt = past + case "refresh": + f.r.credentials[hashMCPOAuthSecret(tokens.RefreshToken)].ExpiresAt = past + case "grant": + f.r.grants[principal.GrantID].ExpiresAt = past + } + if kind != "refresh" { + _, err = f.s.Authenticate(context.Background(), tokens.AccessToken) + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) + } + if kind != "access" { + _, err = f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "refresh_token", ClientID: f.client.ClientID, RefreshToken: tokens.RefreshToken}, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_grant") + } + }) + } + f := newMCPOAuthFixture(t) + tokens := f.tokens(t) + _, err := f.s.Authenticate(context.Background(), tokens.RefreshToken) + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) + _, err = f.s.Authenticate(context.Background(), "mcp_legacy_personal_token") + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) +} + +func TestMCPOAuthConsentPermissionsRevocationAndNoSecretPersistence(t *testing.T) { + f := newMCPOAuthFixture(t) + _, err := f.s.Decide(context.Background(), 7, MCPOAuthConsentInput{Authorization: f.authorize, Approved: true, Scope: MCPScopeAdmin}, mcpTestResource) + requireMCPOAuthError(t, err, "access_denied") + f.u.user.Role = RoleAdmin + readOnly := false + input := f.code(t, MCPScopeAdmin, &readOnly) + tokens, err := f.s.Token(context.Background(), input, mcpTestResource) + require.NoError(t, err) + principal, err := f.s.Authenticate(context.Background(), tokens.AccessToken) + require.NoError(t, err) + require.Equal(t, MCPScopeAdmin, principal.Scope) + require.False(t, principal.ReadOnly) + grants, err := f.s.ListGrants(context.Background(), 7) + require.NoError(t, err) + require.Len(t, grants, 1) + require.NotNil(t, grants[0].LastUsedAt) + encoded, err := json.Marshal(grants) + require.NoError(t, err) + for _, secret := range []string{input.Code, tokens.AccessToken, tokens.RefreshToken, "token_version", "user_id", "resource"} { + require.NotContains(t, string(encoded), secret) + } + require.NotContains(t, f.r.credentials, tokens.AccessToken) + require.NotContains(t, f.r.credentials, tokens.RefreshToken) + require.NotContains(t, f.r.codes, input.Code) + require.ErrorIs(t, f.s.RevokeGrant(context.Background(), 8, principal.GrantID), ErrMCPOAuthGrantNotFound) + require.NoError(t, f.s.RevokeToken(context.Background(), "other-client", tokens.RefreshToken)) + _, err = f.s.Authenticate(context.Background(), tokens.AccessToken) + require.NoError(t, err) + require.NoError(t, f.s.RevokeGrant(context.Background(), 7, principal.GrantID)) + require.NoError(t, f.s.RevokeGrant(context.Background(), 7, principal.GrantID)) + _, err = f.s.Authenticate(context.Background(), tokens.AccessToken) + require.ErrorIs(t, err, ErrMCPOAuthInvalidToken) +} + +func TestMCPOAuthListReportsInvalidatedAndGrantLimit(t *testing.T) { + f := newMCPOAuthFixture(t) + for i := 0; i < MCPOAuthGrantLimit; i++ { + f.code(t, "", nil) + } + _, err := f.s.Decide(context.Background(), 7, MCPOAuthConsentInput{Authorization: f.authorize, Approved: true}, mcpTestResource) + require.ErrorIs(t, err, ErrMCPOAuthGrantLimit) + f.u.user.PasswordHash = "changed" + grants, err := f.s.ListGrants(context.Background(), 7) + require.NoError(t, err) + for _, grant := range grants { + require.True(t, grant.Invalidated) + } +} + +func TestMCPOAuthClientRevocationInvalidatesAccessAndRefresh(t *testing.T) { + f := newMCPOAuthFixture(t) + tokens := f.tokens(t) + require.NoError(t, f.s.RevokeToken(context.Background(), f.client.ClientID, tokens.RefreshToken)) + _, 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") + require.NoError(t, f.s.RevokeToken(context.Background(), f.client.ClientID, tokens.RefreshToken)) + require.NoError(t, f.s.RevokeToken(context.Background(), f.client.ClientID, "unknown")) +} + +func TestMCPOAuthCodeOnlyClientReceivesNoRefreshToken(t *testing.T) { + f := newMCPOAuthFixture(t) + client, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: f.client.RedirectURIs, GrantTypes: []string{"authorization_code"}}) + require.NoError(t, err) + f.client, f.authorize.ClientID = client, client.ClientID + tokens := f.tokens(t) + require.NotEmpty(t, tokens.AccessToken) + require.Empty(t, tokens.RefreshToken) + encoded, err := json.Marshal(tokens) + require.NoError(t, err) + require.NotContains(t, string(encoded), "refresh_token") + require.Len(t, f.r.credentials, 1) +} + +func TestMCPOAuthConcurrentCodeExchangeAllowsAtMostOneIssuance(t *testing.T) { + f := newMCPOAuthFixture(t) + input := f.code(t, "", nil) + start := make(chan struct{}) + results := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { + <-start + _, err := f.s.Token(context.Background(), input, mcpTestResource) + results <- err + }() + } + close(start) + successes := 0 + for i := 0; i < 2; i++ { + if err := <-results; err == nil { + successes++ + } else { + requireMCPOAuthError(t, err, "invalid_grant") + } + } + 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 TestMCPOAuthRegistrationIsStatelessAndSigned(t *testing.T) { + f := newMCPOAuthFixture(t) + // Anonymous registration persists nothing, so there is no capacity to exhaust. + for i := 0; i < 100; i++ { + _, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) + require.NoError(t, err) + } + require.Empty(t, f.r.grants) + require.Empty(t, f.r.codes) + require.Empty(t, f.r.credentials) + twin, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: f.client.ClientName, RedirectURIs: f.client.RedirectURIs}) + require.NoError(t, err) + // The random nonce leads, so even truncated IDs of identical clients differ. + visible := len(mcpOAuthClientIDPrefix) + 22 + require.NotEqual(t, f.client.ClientID[:visible], twin.ClientID[:visible], "identical metadata must still yield distinct clients") + + parts := strings.Split(strings.TrimPrefix(f.client.ClientID, mcpOAuthClientIDPrefix), ".") + require.Len(t, parts, 3) + nonce, payload, signature := parts[0], parts[1], parts[2] + twinNonce, _, _ := strings.Cut(strings.TrimPrefix(twin.ClientID, mcpOAuthClientIDPrefix), ".") + raw, err := base64.RawURLEncoding.DecodeString(payload) + require.NoError(t, err) + renamed := strings.Replace(string(raw), `"n":"My MCP client"`, `"n":"Trusted client"`, 1) + require.NotEqual(t, string(raw), renamed) + foreign, err := NewMCPOAuthService(&mcpOAuthMemoryRepo{clientIDKey: []byte("another-deployment-client-id-key")}, f.u). + Register(context.Background(), MCPOAuthRegisterInput{ClientName: f.client.ClientName, RedirectURIs: f.client.RedirectURIs}) + require.NoError(t, err) + tampered := []byte(f.client.ClientID) + tampered[len(tampered)-1] ^= 1 + for name, id := range map[string]string{ + "forged metadata": mcpOAuthClientIDPrefix + nonce + "." + base64.RawURLEncoding.EncodeToString([]byte(renamed)) + "." + signature, + "swapped nonce": mcpOAuthClientIDPrefix + twinNonce + "." + payload + "." + signature, + "other key": foreign.ClientID, + "bad signature": string(tampered), + "unsigned": mcpOAuthClientIDPrefix + nonce + "." + payload, + "missing prefix": strings.TrimPrefix(f.client.ClientID, mcpOAuthClientIDPrefix), + "oversized": f.client.ClientID + strings.Repeat("A", mcpOAuthClientIDMaxLength), + } { + t.Run(name, func(t *testing.T) { + input := f.authorize + input.ClientID = id + _, err := f.s.Preview(context.Background(), 7, input, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_client") + _, err = f.s.Token(context.Background(), MCPOAuthTokenInput{GrantType: "authorization_code", ClientID: id}, mcpTestResource) + requireMCPOAuthError(t, err, "invalid_client") + }) + } +} + +func TestMCPOAuthLargestRegistrationFitsClientIDLimit(t *testing.T) { + f := newMCPOAuthFixture(t) + redirects := make([]string, 10) + for i := range redirects { + redirects[i] = fmt.Sprintf("https://client.example/%d/%s", i, strings.Repeat("p", 2000)) + } + // "<" is JSON-escaped to six bytes, the worst case for an allowed name. + client, err := f.s.Register(context.Background(), MCPOAuthRegisterInput{ClientName: strings.Repeat("<", 100), RedirectURIs: redirects}) + require.NoError(t, err) + require.LessOrEqual(t, len(client.ClientID), mcpOAuthClientIDMaxLength) + input := f.authorize + input.ClientID, input.RedirectURI = client.ClientID, redirects[9] + preview, err := f.s.Preview(context.Background(), 7, input, mcpTestResource) + require.NoError(t, err) + require.Equal(t, client.ClientName, preview.ClientName) +} + +func TestMCPOAuthClientIDKeyErrorIsNotUnknownClient(t *testing.T) { + f := newMCPOAuthFixture(t) + unavailable := errors.New("database unavailable") + s := NewMCPOAuthService(&mcpOAuthKeyErrorRepo{mcpOAuthMemoryRepo: f.r, err: unavailable}, f.u) + _, err := s.Register(context.Background(), MCPOAuthRegisterInput{RedirectURIs: []string{"https://client.example/cb"}}) + require.ErrorIs(t, err, unavailable) + _, err = s.Preview(context.Background(), 7, f.authorize, mcpTestResource) + require.ErrorIs(t, err, unavailable) +} + +type mcpOAuthKeyErrorRepo struct { + *mcpOAuthMemoryRepo + err error +} + +func (r *mcpOAuthKeyErrorRepo) ClientIDKey(context.Context) ([]byte, error) { return nil, r.err } + +func TestMCPOAuthAuthenticateThrottlesLastUsedWrites(t *testing.T) { + f := newMCPOAuthFixture(t) + tokens := f.tokens(t) + 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/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 2cbf1211f5..3f2a2c9935 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -386,6 +386,7 @@ func (s *defaultOpenAIAccountScheduler) Select( if s != nil && s.service != nil && s.service.openAIGroupRequiresPrivacySet(ctx, req.GroupID) { req.RequirePrivacySet = true } + ctx = withOpenAIImageSizeStickyAccount(withOpenAIImageSizeStickyAccount(ctx, req.StickyAccountID), req.StickyPreviousAccountID) start := time.Now() // 命名返回值保证 defer 写入的耗时同时返回给调用方。 defer func() { @@ -409,7 +410,7 @@ func (s *defaultOpenAIAccountScheduler) Select( return nil, decision, err } if selection != nil && selection.Account != nil { - compatible, _ := s.isAccountRequestCompatibleReason(ctx, selection.Account, req) + compatible, _ := s.isAccountRequestCompatibleReason(withOpenAIImageSizeStickyAccount(ctx, selection.Account.ID), selection.Account, req) hasGroupMetadata := len(selection.Account.GroupIDs) > 0 || len(selection.Account.AccountGroups) > 0 groupCompatible := !hasGroupMetadata || openAIStickyAccountMatchesGroup(selection.Account, req.GroupID) if hasGroupMetadata && s.service != nil { @@ -522,6 +523,7 @@ func (s *defaultOpenAIAccountScheduler) selectBySessionHash( return nil, false, nil } } + ctx = withOpenAIImageSizeStickyAccount(ctx, accountID) account, err := s.service.getSchedulableAccount(ctx, accountID) if err != nil || account == nil { @@ -1823,6 +1825,9 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con if !accountSupportsOpenAICapabilities(account, req.RequiredCapability, req.RequiredImageCapability) { return false, "capability_mismatch" } + if vetoed, reason := openAIImageSizeVetoReason(ctx, account); vetoed { + return false, reason + } // 分组利润控制:不合格账号在候选过滤与抢槽后终检阶段即被排除, // 排序/评分/粘性/熔断只在合格账号之间工作;named reason 进入 filter stats。 if vetoed, reason := openAIProfitControlVetoReason(ctx, account); vetoed { @@ -2153,7 +2158,7 @@ func (s *OpenAIGatewayService) SelectAccountWithSchedulerForImages( return selection, decision, err } -// selectAccountWithScheduler wraps selectAccountWithSchedulerOnce with a +// selectAccountWithScheduler wraps selectAccountWithSchedulerBySize with a // fail-open second pass for the proxy stream circuit (#5056): when the only // reason no account is available is that every candidate sits behind a // quarantined proxy, the quarantine must degrade to a preference instead of @@ -2175,7 +2180,7 @@ func (s *OpenAIGatewayService) selectAccountWithScheduler( previousResponseCanMove bool, useUpstreamTokenCost bool, ) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { - selection, decision, err := s.selectAccountWithSchedulerOnce(ctx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost) + selection, decision, err := s.selectAccountWithSchedulerBySize(ctx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost) if err == nil || openAIProxyStreamQuarantineBypassed(ctx) { return selection, decision, err } @@ -2191,7 +2196,42 @@ func (s *OpenAIGatewayService) selectAccountWithScheduler( return selection, decision, err } s.logOpenAIProxyStreamQuarantineFailOpen(requestedModel, blocked) - return s.selectAccountWithSchedulerOnce(withOpenAIProxyStreamQuarantineBypass(ctx), groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost) + return s.selectAccountWithSchedulerBySize(withOpenAIProxyStreamQuarantineBypass(ctx), groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost) +} + +// selectAccountWithSchedulerBySize runs selectAccountWithSchedulerOnce once per +// image size pass recorded by WithOpenAIImageSizeRouting, or once when the +// request carries no image size. A spillover pass that acquires a slot hands +// the session binding to bindOpenAIImageSizeSpilloverAccount together with the +// binding read before the first pass. +func (s *OpenAIGatewayService) selectAccountWithSchedulerBySize( + ctx context.Context, + groupID *int64, + previousResponseID string, + sessionHash string, + requestedModel string, + excludedIDs map[int64]struct{}, + requiredTransport OpenAIUpstreamTransport, + requiredCapability OpenAIEndpointCapability, + requiredImageCapability OpenAIImagesCapability, + requireCompact bool, + platform string, + previousResponseCanMove bool, + useUpstreamTokenCost bool, +) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + var initialStickyAccountID int64 + if strings.TrimSpace(sessionHash) != "" && openAIImageSizeRoutingUsesPreference(ctx) { + if accountID, err := s.getStickySessionAccountID(ctx, groupID, sessionHash); err == nil { + initialStickyAccountID = accountID + } + } + return selectOpenAIAccountByImageSizePasses(ctx, func(passCtx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + selection, decision, err := s.selectAccountWithSchedulerOnce(passCtx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, requiredImageCapability, requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost) + if err == nil && selection != nil && selection.Acquired && openAIImageSizeSpilloverPass(passCtx) { + s.bindOpenAIImageSizeSpilloverAccount(passCtx, groupID, sessionHash, initialStickyAccountID, selection) + } + return selection, decision, err + }) } type openAIGroupPrivacyRequirementContextKey struct{} @@ -2272,7 +2312,7 @@ func (s *OpenAIGatewayService) selectLegacyAccountByPreviousResponse( } account := selection.Account scheduler := &defaultOpenAIAccountScheduler{service: s, stats: newOpenAIAccountRuntimeStats()} - compatible, _ := scheduler.isAccountRequestCompatibleReason(ctx, account, OpenAIAccountScheduleRequest{ + compatible, _ := scheduler.isAccountRequestCompatibleReason(withOpenAIImageSizeStickyAccount(ctx, account.ID), account, OpenAIAccountScheduleRequest{ GroupID: groupID, Platform: platform, RequestedModel: requestedModel, @@ -2323,7 +2363,7 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce( } platform = NormalizeOpenAICompatiblePlatform(platform) decision := OpenAIAccountScheduleDecision{} - preserveGuardianParentBinding := preserveOpenAIGuardianParentBinding(ctx, sessionHash) + preserveStickyBinding := preserveOpenAIGuardianParentBinding(ctx, sessionHash) || openAIImageSizeSpilloverPass(ctx) guardianParentAccountID := int64(0) if strings.TrimSpace(previousResponseID) == "" { guardianParentAccountID = s.resolveOpenAIGuardianParentAccountID(ctx, groupID) @@ -2371,7 +2411,7 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce( } } legacySessionHash := sessionHash - if preserveGuardianParentBinding { + if preserveStickyBinding { legacySessionHash = "" } if requiredTransport == OpenAIUpstreamTransportAny || requiredTransport == OpenAIUpstreamTransportHTTPSSE { @@ -2457,7 +2497,7 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce( StickyPreviousAccountID: stickyPreviousAccountID, StickyWeighted: stickyWeighted, SubscriptionPriority: subscriptionPriority, - PreserveStickyBinding: preserveGuardianParentBinding, + PreserveStickyBinding: preserveStickyBinding, RequirePrivacySet: s.openAIGroupRequiresPrivacySet(ctx, groupID), PreviousResponseID: previousResponseID, PreviousResponseCanMove: previousResponseCanMove, diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 4f810cc6bd..22e5d613f2 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -1893,9 +1893,13 @@ func (s *OpenAIGatewayService) fetchCachedOpenAIModels(ctx context.Context, requ func (s *OpenAIGatewayService) refreshCachedOpenAIModels(cacheKey string, request openAIModelsRequest, fetch func(ctx context.Context, ifNoneMatch string) (*OpenAIModelsResponse, error)) <-chan singleflight.Result { return s.openAIModelsCache.refresh.DoChan(cacheKey, func() (any, error) { + cached, state := s.openAIModelsCache.get(cacheKey, time.Now()) + // 调用方读缓存之后、进入 singleflight 之前,上一轮刷新可能已写入新鲜结果:直接复用,不重复请求上游。 + if state == openAIModelsCacheFresh { + return cached, nil + } ctx, cancel := context.WithTimeout(context.Background(), codexModelsManifestRequestTimeout) defer cancel() - cached, _ := s.openAIModelsCache.get(cacheKey, time.Now()) ifNoneMatch := "" if cached != nil { ifNoneMatch = cached.upstreamETag diff --git a/backend/internal/service/openai_first_output_timeout_test.go b/backend/internal/service/openai_first_output_timeout_test.go index fc4b5076ca..ebab68c019 100644 --- a/backend/internal/service/openai_first_output_timeout_test.go +++ b/backend/internal/service/openai_first_output_timeout_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net/http" "net/http/httptest" @@ -481,10 +482,12 @@ func TestOpenAINativeFirstOutputStageOverflowFailsOverWithoutAttemptBytes(t *tes }} svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} const lineSize = 1024*1024 - 256 - prefix := `data: {"type":"response.output_text.delta","delta":"` - suffix := `"}` + // Complete metadata events stay staged until visible output arrives. Each + // event fits the transport cap; their cumulative size exceeds the stage cap. + prefix := `data: {"type":"response.in_progress","response":{"id":"resp_staged","padding":"` + suffix := `"}}` line := prefix + strings.Repeat("x", lineSize-len(prefix)-len(suffix)) + suffix - body := strings.Repeat(line+"\n", 9) + body := strings.Repeat(line+"\n\n", 9) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) @@ -509,6 +512,45 @@ func TestOpenAINativeFirstOutputStageOverflowFailsOverWithoutAttemptBytes(t *tes require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) } +func TestOpenAINativeFirstOutputEventLimitFailsOverWithoutAttemptBytes(t *testing.T) { + for _, explicitLimit := range []int64{0, 1024} { + t.Run(fmt.Sprintf("event_limit_%d", explicitLimit), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{ + OpenAIFirstOutputTimeoutSeconds: 30, + MaxLineSize: 2048, + SSEEventMaxBytes: explicitLimit, + }} + svc := &OpenAIGatewayService{cfg: cfg, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + line := `data: {"type":"response.output_text.delta","delta":"` + strings.Repeat("x", 700) + `"}` + // No blank line: several individually legal lines form one oversized + // event, which must fail before the independent 8 MiB stage limit. + body := strings.Repeat(line+"\n", 4) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{ + "X-Request-Id": []string{"request-event-overflow"}, + "X-Ratelimit-Remaining-Requests": []string{"1"}, + }, + Body: io.NopCloser(strings.NewReader(body)), + } + + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "model", "model") + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) + require.True(t, failoverErr.SafeToFailoverAfterWrite) + require.Contains(t, string(failoverErr.ResponseBody), "event exceeds first-output transport limit") + require.Empty(t, rec.Body.String()) + require.Empty(t, rec.Header().Values("X-Request-Id")) + require.Empty(t, rec.Header().Values("X-Ratelimit-Remaining-Requests")) + }) + } +} + func TestOpenAINativeFirstOutputScannerRejectsOversizedLineWithoutLeak(t *testing.T) { cfg := &config.Config{Gateway: config.GatewayConfig{ OpenAIFirstOutputTimeoutSeconds: 30, diff --git a/backend/internal/service/openai_gateway_anthropic_native_pump.go b/backend/internal/service/openai_gateway_anthropic_native_pump.go index 3b679bc4e8..a5f12fb1be 100644 --- a/backend/internal/service/openai_gateway_anthropic_native_pump.go +++ b/backend/internal/service/openai_gateway_anthropic_native_pump.go @@ -41,18 +41,24 @@ type anthropicNativeLineEvent struct { // anthropicNativeLinePump 以独立 goroutine 泵送 scanner 的行,并对逐行到达 // 间隔施加 interval 上限(<=0 表示禁用,可经 enableInterval 启用)。 type anthropicNativeLinePump struct { - events chan anthropicNativeLineEvent - done chan struct{} - timer *time.Timer - interval time.Duration + events chan anthropicNativeLineEvent + done chan struct{} + timer *time.Timer + interval time.Duration + queueBudget *sseQueueBudget } // newAnthropicNativeLinePump 启动泵 goroutine;调用方 defer pump.stop()。 -func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration) *anthropicNativeLinePump { +func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration, configs ...*config.Config) *anthropicNativeLinePump { + var cfg *config.Config + if len(configs) > 0 { + cfg = configs[0] + } p := &anthropicNativeLinePump{ - events: make(chan anthropicNativeLineEvent, 16), - done: make(chan struct{}), - interval: interval, + events: make(chan anthropicNativeLineEvent, 16), + done: make(chan struct{}), + interval: interval, + queueBudget: newSSEQueueBudget(cfg), } if interval > 0 { p.timer = time.NewTimer(interval) @@ -60,9 +66,13 @@ func newAnthropicNativeLinePump(scanner *bufio.Scanner, interval time.Duration) go func() { defer close(p.events) for scanner.Scan() { + if !p.queueBudget.acquire(len(scanner.Bytes()), p.done) { + return + } select { case p.events <- anthropicNativeLineEvent{line: scanner.Text()}: case <-p.done: + p.queueBudget.release(len(scanner.Bytes())) return } } @@ -110,6 +120,9 @@ func (p *anthropicNativeLinePump) deliver(ev anthropicNativeLineEvent, ok bool) if !ok { return "", io.EOF } + if p.queueBudget != nil { + p.queueBudget.release(len(ev.line)) + } p.resetTimer() return ev.line, ev.err } diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 4d65374a45..b7eadf7b4b 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -39,6 +39,7 @@ func (s *OpenAIGatewayService) newUpstreamSSEScanner(r io.Reader) *bufio.Scanner maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) return scanner } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 6c727da0cc..ed8433d97f 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -1211,11 +1211,16 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( done := make(chan struct{}) var lastReadAt int64 atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1248,6 +1253,9 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if frame, ok := parser.Finish(); ok { if strings.TrimSpace(frame.Data) == "[DONE]" { diff --git a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go index f6333661f5..5c2d86b87d 100644 --- a/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go +++ b/backend/internal/service/openai_gateway_chat_completions_anthropic_native.go @@ -164,13 +164,15 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage // 读间隔上限:上游挂住 SSE 时中止组装(缓冲路径尚未提交响应头,可回 502)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -198,6 +200,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } // SSE 规范允许 `event:xxx`(冒号后无空格):Kimi 等 Anthropic 兼容上游 @@ -212,6 +215,7 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -224,6 +228,11 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + if event.Type == "message_start" && event.Message != nil { finalResp = event.Message mergeAnthropicUsage(&usage, event.Message.Usage) @@ -254,6 +263,16 @@ func (s *OpenAIGatewayService) handleCCBufferedFromNativeAnthropic( } } + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeChatCompletionsError(c, http.StatusBadGateway, "server_error", failure.message) + return &OpenAIForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: claudeUsageToOpenAIUsage(&usage), + Model: originalModel, BillingModel: billingModel, UpstreamModel: upstreamModel, + UpstreamEndpoint: "/v1/messages", ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeChatCompletionsError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") @@ -335,6 +354,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) resultWithUsage := func() *OpenAIForwardResult { return &OpenAIForwardResult{ @@ -357,7 +377,8 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( // WithoutCancel 且 http.Client 无整体 Timeout,无此界限则客户端断开后 // scanner.Scan() 永久阻塞(见 anthropic native pump 文件注释)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -443,6 +464,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } if _, ok := extractOpenAISSEEventLine(line); !ok { @@ -456,6 +478,7 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( } // EOF / 读错误:事件行后流终止,进入 finalize。 logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -468,6 +491,11 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + // Forward received usage regardless of the client stream_options. // The intermediate Responses converter synthesizes usage even when absent. ccState.IncludeUsage = ccState.IncludeUsage || anthropicChatStreamHasUsage(&event, payload) @@ -477,7 +505,19 @@ func (s *OpenAIGatewayService) handleCCStreamingFromNativeAnthropic( } } - // Finalize both state machines(客户端已断开时仍执行,保证 usage 汇总完整)。 + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + if !clientDisconnected { + writeAnthropicCompatCCStreamFailure(c, failure) + } + return resultWithUsage(), failure.err + } + + if clientDisconnected { + return resultWithUsage(), nil + } + + // Finalize only after the upstream has supplied a terminal event. finalResEvents := apicompat.FinalizeAnthropicResponsesStream(anthState) for _, resEvt := range finalResEvents { ccChunks := apicompat.ResponsesEventToChatChunks(&resEvt, ccState) diff --git a/backend/internal/service/openai_gateway_cn_fixes_test.go b/backend/internal/service/openai_gateway_cn_fixes_test.go index 1ab002af89..dbbed21ef4 100644 --- a/backend/internal/service/openai_gateway_cn_fixes_test.go +++ b/backend/internal/service/openai_gateway_cn_fixes_test.go @@ -12,7 +12,6 @@ package service import ( "context" "encoding/json" - "errors" "io" "net/http" "net/http/httptest" @@ -270,6 +269,7 @@ func TestHandle403_OtherCNProviderWithKimiConcurrencyMessageUsesNormalPolicy(t * require.True(t, shouldDisable) require.Equal(t, 1, repo.setErrorCalls, "non-Kimi CN provider must retain the normal permanent-error policy") require.Equal(t, 0, repo.tempCalls) + require.Zero(t, repo.rateLimitedCalls) require.Empty(t, counter.counts, "normal CN 403 policy must consume the counter result") require.Equal(t, []string{"auth_error"}, blocker.reasons, "the Kimi-specific runtime block must not apply") } @@ -290,16 +290,16 @@ func TestHandle403_CNProviderConcurrencyLimitAlwaysUsesTemporaryCooldown(t *test require.True(t, shouldDisable, "the request must still fail over to another account") require.Equal(t, 0, repo.setErrorCalls) - require.Equal(t, 1, repo.tempCalls) - require.Contains(t, repo.lastTempReason, cnConcurrencyLimitReasonPrefix) + require.Equal(t, 0, repo.tempCalls) + require.Equal(t, 1, repo.rateLimitedCalls) require.Equal(t, []int64{openAI403DisableThreshold}, counter.counts, "transient concurrency 403 must bypass the permanent-error counter") require.Len(t, blocker.accounts, 1) - require.Equal(t, cnConcurrencyLimitReasonPrefix, blocker.reasons[0]) + require.Equal(t, "429_fallback", blocker.reasons[0]) require.True(t, blocker.until[0].After(time.Now())) } func TestHandle403_KimiConcurrencyLimitRepositoryFailureKeepsRuntimeBlock(t *testing.T) { - repo := &rateLimitAccountRepoStub{tempErr: errors.New("repository unavailable")} + repo := &kimiConcurrencyRateLimitFailureRepo{} counter := &openAI403CounterCacheStub{counts: []int64{openAI403DisableThreshold}} blocker := &runtimeBlockRecorder{} service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) @@ -313,12 +313,13 @@ func TestHandle403_KimiConcurrencyLimitRepositoryFailureKeepsRuntimeBlock(t *tes ) require.True(t, shouldDisable, "the current request must fail over even when persistence fails") - require.Equal(t, 1, repo.tempCalls, "the temporary cooldown should still be persisted when possible") + require.Equal(t, 1, repo.rateLimitedCalls, "the rate limit cooldown should still be persisted when possible") + require.Zero(t, repo.tempCalls) require.Equal(t, 0, repo.setErrorCalls, "persistence failure must not fall back to permanent account error") require.Equal(t, []int64{openAI403DisableThreshold}, counter.counts, "persistence failure must not enter the permanent-error counter path") require.Len(t, blocker.accounts, 1, "the in-memory runtime block must survive repository failure") require.Same(t, account, blocker.accounts[0]) - require.Equal(t, cnConcurrencyLimitReasonPrefix, blocker.reasons[0]) + require.Equal(t, "429_fallback", blocker.reasons[0]) require.True(t, blocker.until[0].After(time.Now())) } @@ -337,4 +338,5 @@ func TestHandle403_CNProviderNearMatchRetainsNormalPermanentErrorPolicy(t *testi require.True(t, shouldDisable) require.Equal(t, 1, repo.setErrorCalls, "non-exact 403 must retain existing permission/auth protection") require.Equal(t, 0, repo.tempCalls) + require.Zero(t, repo.rateLimitedCalls) } diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 27aafd997d..b8bee593b1 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -33,6 +33,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco clearOpenAIResponsesClientToolMapping(c) clearOpenAIResponsesNamespaceNames(c) setCodexToolNameReverse(c, nil) + rememberOpenAIResponsesClientInstructions(c, body) if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil { return nil, err } @@ -1042,6 +1043,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamCtx, releaseUpstreamCtx, startTime.Add(firstOutputTimeout), ) } + syncOpenAIResponsesInstructionsEcho(c, body) upstreamReq, err := s.buildUpstreamRequest(upstreamCtx, c, account, body, token, reqStream, promptCacheKey, isCodexCLI) if headerGuard == nil { releaseUpstreamCtx() @@ -1207,7 +1209,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.cfg.Gateway.MaxLineSize } - resp.Body = newResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) + resp.Body = newResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize, s.cfg) } serviceTier := extractOpenAIServiceTierFromBody(body) diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index aea1e3c964..ad40eac7db 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -218,9 +218,9 @@ func (s *OpenAIGatewayService) forwardGrokResponses( if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.cfg.Gateway.MaxLineSize } - resp.Body = newGrokResponsesBillingPingFilterBody(resp.Body, account, maxLineSize) + resp.Body = newGrokResponsesBillingPingFilterBody(resp.Body, account, maxLineSize, s.cfg) if hasGrokResponsesClientToolMapping(clientToolMapping) { - resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize) + resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize, s.cfg) } streamResult, err := s.handleStreamingResponse(ctx, resp, c, account, startTime, originalModel, upstreamModel) if err != nil { diff --git a/backend/internal/service/openai_gateway_grok_model_input.go b/backend/internal/service/openai_gateway_grok_model_input.go index dc1b522a9c..809e3c5fad 100644 --- a/backend/internal/service/openai_gateway_grok_model_input.go +++ b/backend/internal/service/openai_gateway_grok_model_input.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/tidwall/gjson" "github.com/tidwall/sjson" ) @@ -69,6 +70,18 @@ func sanitizeGrokResponsesModelInput(body []byte) ([]byte, error) { pendingOutputImages = pendingOutputImages[:0] switch itemType { + case "agent_message": + content, err := json.Marshal(item["content"]) + if err != nil { + return nil, fmt.Errorf("serialize Grok agent message content: %w", err) + } + text := apicompat.AgentMessageText(content) + if text == "" { + continue + } + role = "user" + item = map[string]any{"type": "message", "role": role, "content": text} + itemType = "message" case "text", "input_text", "output_text": text := strings.TrimSpace(grokStringValue(item["text"])) if text == "" { diff --git a/backend/internal/service/openai_gateway_grok_model_input_test.go b/backend/internal/service/openai_gateway_grok_model_input_test.go index 4533bc646c..4190a40e33 100644 --- a/backend/internal/service/openai_gateway_grok_model_input_test.go +++ b/backend/internal/service/openai_gateway_grok_model_input_test.go @@ -1,6 +1,7 @@ package service import ( + "encoding/json" "net/http" "strconv" "testing" @@ -9,6 +10,61 @@ import ( "github.com/tidwall/gjson" ) +func TestSanitizeGrokResponsesModelInputAgentMessage(t *testing.T) { + tests := []struct { + name string + content string + text string + }{ + {"text only", `[{"type":"input_text","text":"What is 19 plus 23?"}]`, "What is 19 plus 23?"}, + {"envelope and plaintext payload", `[{"type":"input_text","text":"Message Type: NEW_TASK\nPayload:\n"},{"type":"encrypted_content","encrypted_content":"Review the code"},{"type":"text","text":"\nthen report"},{"type":"encrypted_content","encrypted_content":" back. "}]`, "Message Type: NEW_TASK\nPayload:\nReview the code\nthen report back. "}, + {"string content", `" task\n"`, " task\n"}, + {"opaque content is not decrypted", `[{"type":"encrypted_content","encrypted_content":"gAAAAABopaque=="}]`, "gAAAAABopaque=="}, + {"empty content", `[]`, ""}, + {"null content", `null`, ""}, + {"unsupported content", `[{"type":"input_image","image_url":"https://example.com/image.png"},{"type":"output_text","text":"ignored"}]`, ""}, + {"malformed content", `{"text":"ignored"}`, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body := []byte(`{"input":[{"type":"agent_message","id":"amsg_1","author":"/root","recipient":"/root/child","role":"assistant","content":` + tt.content + `}]}`) + patched, err := sanitizeGrokResponsesModelInput(body) + require.NoError(t, err) + if tt.text == "" { + require.Empty(t, gjson.GetBytes(patched, "input").Array()) + return + } + expected, err := json.Marshal([]map[string]any{{"type": "message", "role": "user", "content": tt.text}}) + require.NoError(t, err) + require.JSONEq(t, string(expected), gjson.GetBytes(patched, "input").Raw) + }) + } +} + +func TestSanitizeGrokResponsesModelInputAgentMessageMixedHistory(t *testing.T) { + body := []byte(`{"input":[ + {"type":"message","role":"user","content":"start"}, + {"type":"agent_message","author":"/root","recipient":"/root/child","content":[{"type":"input_text","text":"Payload:\n"},{"type":"encrypted_content","encrypted_content":"task"}]}, + {"type":"message","role":"assistant","content":"working"}, + {"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}, + {"type":"function_call_output","call_id":"call_1","output":"found"}, + {"type":"agent_message","content":[]}, + {"type":"agent_message","author":"/root/child","recipient":"/root","content":[{"type":"input_text","text":"result"}]}, + {"type":"message","role":"user","content":"continue"} + ]}`) + patched, err := sanitizeGrokResponsesModelInput(body) + require.NoError(t, err) + require.JSONEq(t, `[ + {"type":"message","role":"user","content":"start"}, + {"type":"message","role":"user","content":"Payload:\ntask"}, + {"type":"message","role":"assistant","content":"working"}, + {"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"}, + {"type":"function_call_output","call_id":"call_1","output":"found"}, + {"type":"message","role":"user","content":"result"}, + {"type":"message","role":"user","content":"continue"} + ]`, gjson.GetBytes(patched, "input").Raw) +} + func TestSanitizeGrokResponsesModelInputNormalizesReplayHistory(t *testing.T) { body := []byte(`{ "input":[ diff --git a/backend/internal/service/openai_gateway_grok_sse_filter.go b/backend/internal/service/openai_gateway_grok_sse_filter.go index 78159144d5..109ca50473 100644 --- a/backend/internal/service/openai_gateway_grok_sse_filter.go +++ b/backend/internal/service/openai_gateway_grok_sse_filter.go @@ -8,6 +8,8 @@ import ( "io" "strings" "sync" + + "github.com/Wei-Shaw/sub2api/internal/config" ) // OpenAI Responses SSE event types are a closed enum for strict clients @@ -46,13 +48,13 @@ func (b *grokResponsesBillingPingFilterBody) closeSource() error { return b.closeErr } -func newGrokResponsesBillingPingFilterBody(source io.ReadCloser, account *Account, maxLineSize int) io.ReadCloser { +func newGrokResponsesBillingPingFilterBody(source io.ReadCloser, account *Account, maxLineSize int, cfg *config.Config) io.ReadCloser { if account == nil || account.Platform != PlatformGrok { return source } reader, writer := io.Pipe() body := &grokResponsesBillingPingFilterBody{PipeReader: reader, source: source} - go filterGrokResponsesBillingPings(source, writer, body.closeSource, maxLineSize) + go filterGrokResponsesBillingPings(source, writer, body.closeSource, maxLineSize, cfg) return body } @@ -61,6 +63,7 @@ func filterGrokResponsesBillingPings( destination *io.PipeWriter, closeSource func() error, maxLineSize int, + cfg *config.Config, ) { defer func() { _ = closeSource() }() if maxLineSize <= 0 { @@ -75,7 +78,7 @@ func filterGrokResponsesBillingPings( initialBufferSize = maxLineSize } scanner.Buffer(scanBuf[:0:initialBufferSize], maxLineSize) - scanner.Split(scanSSELinesPreservingEndings) + scanner.Split(newBoundedSSESplit(cfg, maxLineSize, scanSSELinesPreservingEndings)) // Only frames opened by an `event: ping` line are buffered (pingFrame); // every other frame streams through line by line without copying. diff --git a/backend/internal/service/openai_gateway_grok_sse_filter_test.go b/backend/internal/service/openai_gateway_grok_sse_filter_test.go index 1dce65e95a..236f799541 100644 --- a/backend/internal/service/openai_gateway_grok_sse_filter_test.go +++ b/backend/internal/service/openai_gateway_grok_sse_filter_test.go @@ -22,6 +22,7 @@ func filterGrokPingTestInput(t *testing.T, input string) string { io.NopCloser(strings.NewReader(input)), &Account{Platform: PlatformGrok}, defaultMaxLineSize, + nil, ) output, err := io.ReadAll(body) require.NoError(t, err) @@ -157,7 +158,7 @@ func TestGrokResponsesBillingPingFilterConvertsPartialPingFrameAtEOF(t *testing. func TestGrokResponsesBillingPingFilterDoesNotFilterNonGrokAccounts(t *testing.T) { input := "event: ping\ndata: {\"type\":\"ping\",\"cost\":\"0\"}\n\n" source := io.NopCloser(strings.NewReader(input)) - body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformOpenAI}, defaultMaxLineSize) + body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformOpenAI}, defaultMaxLineSize, nil) output, err := io.ReadAll(body) require.NoError(t, err) @@ -180,7 +181,7 @@ func TestGrokResponsesBillingPingFilterPreservesUsageAndTerminalEvent(t *testing StatusCode: http.StatusOK, Header: http.Header{}, Body: newGrokResponsesBillingPingFilterBody( - io.NopCloser(strings.NewReader(input)), account, defaultMaxLineSize, + io.NopCloser(strings.NewReader(input)), account, defaultMaxLineSize, nil, ), } recorder := httptest.NewRecorder() @@ -215,7 +216,7 @@ func (r *grokPingFilterTestReadCloser) Close() error { func TestGrokResponsesBillingPingFilterCloseCancelsSourceOnce(t *testing.T) { upstreamReader, upstreamWriter := io.Pipe() source := &grokPingFilterTestReadCloser{reader: upstreamReader} - body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformGrok}, defaultMaxLineSize) + body := newGrokResponsesBillingPingFilterBody(source, &Account{Platform: PlatformGrok}, defaultMaxLineSize, nil) require.NoError(t, body.Close()) require.Eventually(t, func() bool { return source.closeCount.Load() == 1 }, time.Second, time.Millisecond) @@ -226,7 +227,7 @@ func TestGrokResponsesBillingPingFilterCloseCancelsSourceOnce(t *testing.T) { func TestGrokResponsesBillingPingFilterFlushesCompletedFrames(t *testing.T) { upstreamReader, upstreamWriter := io.Pipe() - body := newGrokResponsesBillingPingFilterBody(upstreamReader, &Account{Platform: PlatformGrok}, defaultMaxLineSize) + body := newGrokResponsesBillingPingFilterBody(upstreamReader, &Account{Platform: PlatformGrok}, defaultMaxLineSize, nil) t.Cleanup(func() { require.NoError(t, body.Close()) }) go func() { @@ -255,6 +256,7 @@ func TestGrokResponsesBillingPingFilterReportsOversizedLine(t *testing.T) { io.NopCloser(strings.NewReader("data: 123456789\n\n")), &Account{Platform: PlatformGrok}, 8, + nil, ) _, err := io.ReadAll(body) require.ErrorContains(t, err, "filter Grok Responses billing ping") diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index cdd24b400c..f8aef113d7 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -2041,6 +2041,71 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test require.NotNil(t, repo.updates[52][grokQuotaSnapshotExtraKey]) } +func TestForwardGrokResponsesAgentMessage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, stream := range []bool{false, true} { + for _, payload := range []struct { + name string + content string + text string + }{ + {"text", `[{"type":"input_text","text":"What is 19 plus 23?"}]`, "What is 19 plus 23?"}, + {"plaintext payload", `[{"type":"input_text","text":"Payload:\n"},{"type":"encrypted_content","encrypted_content":"What is 19 plus 23?"}]`, "Payload:\nWhat is 19 plus 23?"}, + } { + t.Run(fmt.Sprintf("stream=%t/%s", stream, payload.name), func(t *testing.T) { + body := []byte(fmt.Sprintf(`{"model":"grok-4.7","stream":%t,"input":[ + {"type":"message","role":"user","content":"history"}, + {"type":"agent_message","id":"amsg_repro","author":"/root","recipient":"/root/child","content":%s}, + {"type":"message","role":"assistant","content":"ready"} + ]}`, stream, payload.content)) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + account := &Account{ + ID: 53, Platform: PlatformGrok, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "xai-test-key", "base_url": "https://api.x.ai/v1"}, + } + response := `{"id":"resp_agent","object":"response","model":"grok-4.7","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"42"}]}],"usage":{"input_tokens":5,"output_tokens":1}}` + upstreamBody := response + contentType := "application/json" + if stream { + contentType = "text/event-stream" + upstreamBody = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"42\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + response + "}\n\n" + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{contentType}}, + Body: io.NopCloser(strings.NewReader(upstreamBody)), + }} + svc := &OpenAIGatewayService{httpUpstream: upstream} + result, err := svc.forwardGrokResponses(context.Background(), c, account, body, "grok-4.7", stream, time.Now()) + require.NoError(t, err) + require.Equal(t, "https://api.x.ai/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, stream, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + expected, err := json.Marshal([]map[string]any{ + {"type": "message", "role": "user", "content": "history"}, + {"type": "message", "role": "user", "content": payload.text}, + {"type": "message", "role": "assistant", "content": "ready"}, + }) + require.NoError(t, err) + require.JSONEq(t, string(expected), gjson.GetBytes(upstream.lastBody, "input").Raw) + require.Equal(t, stream, result.Stream) + require.Equal(t, "resp_agent", result.ResponseID) + require.Equal(t, 5, result.Usage.InputTokens) + require.Equal(t, 1, result.Usage.OutputTokens) + require.Equal(t, http.StatusOK, recorder.Code) + require.Contains(t, recorder.Header().Get("Content-Type"), contentType) + if stream { + require.Contains(t, recorder.Body.String(), `"delta":"42"`) + require.Contains(t, recorder.Body.String(), `"type":"response.completed"`) + } else { + require.Equal(t, "42", gjson.GetBytes(recorder.Body.Bytes(), "output.0.content.0.text").String()) + } + }) + } + } +} + func TestForwardGrokResponsesAPIKeyUsesXAIResponses(t *testing.T) { gin.SetMode(gin.TestMode) diff --git a/backend/internal/service/openai_gateway_grok_tool_protocol.go b/backend/internal/service/openai_gateway_grok_tool_protocol.go index 9f876a1a6e..f62db8960d 100644 --- a/backend/internal/service/openai_gateway_grok_tool_protocol.go +++ b/backend/internal/service/openai_gateway_grok_tool_protocol.go @@ -8,6 +8,7 @@ import ( "io" "strings" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -122,10 +123,11 @@ func newResponsesClientToolStreamBody( source io.ReadCloser, mapping apicompat.ResponsesClientToolMapping, maxLineSize int, + cfg *config.Config, ) io.ReadCloser { reader, writer := io.Pipe() body := &responsesClientToolStreamBody{PipeReader: reader, source: source} - go transformResponsesClientToolStream(source, writer, mapping, maxLineSize) + go transformResponsesClientToolStream(source, writer, mapping, maxLineSize, cfg) return body } @@ -133,8 +135,9 @@ func newGrokResponsesClientToolStreamBody( source io.ReadCloser, mapping apicompat.ResponsesClientToolMapping, maxLineSize int, + cfg *config.Config, ) io.ReadCloser { - return newResponsesClientToolStreamBody(source, mapping, maxLineSize) + return newResponsesClientToolStreamBody(source, mapping, maxLineSize, cfg) } func transformResponsesClientToolStream( @@ -142,6 +145,7 @@ func transformResponsesClientToolStream( destination *io.PipeWriter, mapping apicompat.ResponsesClientToolMapping, maxLineSize int, + cfg *config.Config, ) { defer func() { _ = source.Close() }() if maxLineSize <= 0 { @@ -152,6 +156,7 @@ func transformResponsesClientToolStream( scanBuf := getSSEScannerBuf64K() defer putSSEScannerBuf64K(scanBuf) scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(cfg, maxLineSize, nil)) documents := newOpenAISSEJSONDocumentScanner(scanner) restorer := apicompat.NewResponsesClientToolStreamRestorer(mapping) buffered := bufio.NewWriterSize(destination, 4*1024) diff --git a/backend/internal/service/openai_gateway_grok_tool_protocol_test.go b/backend/internal/service/openai_gateway_grok_tool_protocol_test.go index dd2cd5bb66..32dc6c3856 100644 --- a/backend/internal/service/openai_gateway_grok_tool_protocol_test.go +++ b/backend/internal/service/openai_gateway_grok_tool_protocol_test.go @@ -429,7 +429,7 @@ func TestGrokResponsesClientToolStreamBodyFlushesFrameBeforeEOF(t *testing.T) { sourceReader, sourceWriter := io.Pipe() body := newGrokResponsesClientToolStreamBody(sourceReader, apicompat.ResponsesClientToolMapping{ CustomTools: map[string]bool{"apply_patch": true}, - }, defaultMaxLineSize) + }, defaultMaxLineSize, nil) defer func() { _ = body.Close() }() defer func() { _ = sourceWriter.Close() }() diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index dfe326e847..39a8ecedc8 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -880,12 +880,17 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) go func() { defer close(events) for scanner.Scan() { + if !queueBudget.acquire(len(scanner.Bytes()), done) { + return + } select { case events <- scanEvent{line: scanner.Text()}: case <-done: + queueBudget.release(len(scanner.Bytes())) return } } @@ -902,6 +907,9 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) @@ -1300,11 +1308,16 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( done := make(chan struct{}) var lastReadAt int64 atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1337,6 +1350,9 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { // Upstream closed if frame, ok := parser.Finish(); ok { diff --git a/backend/internal/service/openai_gateway_messages_anthropic_native.go b/backend/internal/service/openai_gateway_messages_anthropic_native.go index 12a3344068..3156aa8546 100644 --- a/backend/internal/service/openai_gateway_messages_anthropic_native.go +++ b/backend/internal/service/openai_gateway_messages_anthropic_native.go @@ -347,6 +347,7 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) type scanEvent struct { line string @@ -354,11 +355,16 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( } events := make(chan scanEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -424,6 +430,9 @@ func (s *OpenAIGatewayService) handleNativeAnthropicStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if !clientDisconnected { flusher.Flush() diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 90039f0522..af55cc0900 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -151,18 +151,6 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( } if account != nil && account.UsesOpenAICodexProtocol() { - if rejectReason := detectOpenAIPassthroughInstructionsRejectReason(reqModel, body); rejectReason != "" { - rejectMsg := "OpenAI codex passthrough requires a non-empty instructions field" - MarkOpsClientBusinessLimited(c, OpsClientBusinessLimitedReasonLocalPolicyDenied) - logOpenAIPassthroughInstructionsRejected(ctx, c, account, reqModel, rejectReason, body) - c.JSON(http.StatusForbidden, gin.H{ - "error": gin.H{ - "type": "forbidden_error", - "message": rejectMsg, - }, - }) - return nil, fmt.Errorf("openai passthrough rejected before upstream: %s", rejectReason) - } if isOpenAICodexModel(reqModel) && !gjson.GetBytes(body, "instructions").Exists() { nextBody, setErr := sjson.SetBytes(body, "instructions", defaultCodexSynthInstructions(reqModel)) if setErr != nil { @@ -178,7 +166,12 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if normalized { body = normalizedBody } - reqStream = gjson.GetBytes(body, "stream").Bool() + // 上游 ChatGPT internal API 要求 stream=true,但下游响应形态必须遵循 + // 客户端原始的 stream 标志:stream=false 时由非流式分支把上游 SSE + // 聚合为单个 JSON(#7978)。compact 请求始终为非流式。 + if isOpenAIResponsesCompactPath(c) { + reqStream = false + } accountScopedBody, accountScoped, scopeErr := applyCodexAccountIdentityClientMetadataRaw(body, codexAccountIdentitySource(c, account), getAPIKeyIDFromContext(c)) if scopeErr != nil { @@ -371,6 +364,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( } SetOpsUpstreamModel(c, actualModel) upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + syncOpenAIResponsesInstructionsEcho(c, body) upstreamReq, buildErr := s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) releaseUpstreamCtx() if buildErr != nil { @@ -438,7 +432,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( if s.cfg != nil && s.cfg.Gateway.MaxLineSize > 0 { maxLineSize = s.cfg.Gateway.MaxLineSize } - resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize) + resp.Body = newGrokResponsesClientToolStreamBody(resp.Body, mapping, maxLineSize, s.cfg) } // x-codex-turn-state 溯源:下游回传由 writeOpenAIPassthroughResponseHeaders @@ -548,37 +542,6 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( return forwardResult, nil } -func logOpenAIPassthroughInstructionsRejected( - ctx context.Context, - c *gin.Context, - account *Account, - reqModel string, - rejectReason string, - body []byte, -) { - if ctx == nil { - ctx = context.Background() - } - accountID := int64(0) - accountName := "" - accountType := "" - if account != nil { - accountID = account.ID - accountName = strings.TrimSpace(account.Name) - accountType = strings.TrimSpace(string(account.Type)) - } - fields := []zap.Field{ - zap.String("component", "service.openai_gateway"), - zap.Int64("account_id", accountID), - zap.String("account_name", accountName), - zap.String("account_type", accountType), - zap.String("request_model", strings.TrimSpace(reqModel)), - zap.String("reject_reason", strings.TrimSpace(rejectReason)), - } - fields = appendCodexCLIOnlyRejectedRequestFields(fields, c, body) - logger.FromContext(ctx).With(fields...).Warn("OpenAI passthrough 本地拦截:Codex 请求缺少有效 instructions") -} - func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( ctx context.Context, c *gin.Context, @@ -2010,6 +1973,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( } scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) defer putSSEScannerBuf64K(scanBuf) documentScanner := newOpenAISSEJSONDocumentScanner(scanner) @@ -2061,6 +2025,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthrough( return resultWithUsage(), fmt.Errorf("restore OpenAI passthrough namespace response: %w", restoreErr) } restoredData = restoreCodexToolNamesFromSSEContext(c, restoredData, rawEventType) + restoredData = restoreOpenAIResponsesInstructionsEchoInEvent(c, restoredData) if !bytes.Equal(restoredData, dataBytes) { dataBytes = restoredData trimmedData = strings.TrimSpace(string(restoredData)) @@ -2338,7 +2303,10 @@ func (s *OpenAIGatewayService) handleNonStreamingResponsePassthrough( // Some upstreams (e.g. other sub2api instances) may return SSE even when // stream=false was requested. Without this conversion the client would // receive raw SSE text or a terminal event with empty output. - if isEventStreamResponse(resp.Header) { + // The ChatGPT OAuth upstream may omit Content-Type while still sending SSE, + // so OAuth accounts also fall back to the body framing (same rule as + // handleNonStreamingResponse). + if isEventStreamResponse(resp.Header) || (account != nil && account.Type == AccountTypeOAuth && bodyHasSSEFraming(body)) { return s.handlePassthroughSSEToJSON(resp, c, account, body, originalModel, mappedModel) } @@ -2370,6 +2338,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponsePassthrough( return nil, fmt.Errorf("restore OpenAI passthrough namespace response: %w", err) } body = restoreCodexToolNamesFromContext(c, body) + body = restoreOpenAIResponsesInstructionsEchoInResponse(c, body) body, err = restoreOpenAIResponsesClientToolPayload(c, body) if err != nil { return nil, fmt.Errorf("restore OpenAI Responses client tools: %w", err) @@ -2407,6 +2376,9 @@ func (s *OpenAIGatewayService) handlePassthroughSSEToJSON(resp *http.Response, c return nil, s.writeOpenAINonStreamingProtocolError(resp, c, msg) } finalResponse, ok := extractCodexFinalResponse(bodyText) + if !ok && terminalOK { + finalResponse, ok = extractOpenAINonCompletedTerminalResponse(terminalType, terminalPayload) + } usage := s.parseSSEUsageFromBody(bodyText) if ok { @@ -2434,11 +2406,12 @@ func (s *OpenAIGatewayService) handlePassthroughSSEToJSON(resp *http.Response, c return nil, fmt.Errorf("restore OpenAI passthrough namespace response: %w", restoreErr) } restoredBody = restoreCodexToolNamesFromContext(c, restoredBody) - body = restoredBody + body = restoreOpenAIResponsesInstructionsEchoInResponse(c, restoredBody) } else { if originalModel != "" && mappedModel != "" && originalModel != mappedModel { bodyText = s.replaceModelInSSEBody(bodyText, mappedModel, originalModel) } + bodyText = restoreOpenAIResponsesInstructionsEchoInSSEBody(c, bodyText) body = []byte(bodyText) } @@ -2453,6 +2426,9 @@ func (s *OpenAIGatewayService) handlePassthroughSSEToJSON(resp *http.Response, c } } if !writeOpenAICompactSSEBridge(c, resp.StatusCode, body) { + // 上游的 Content-Type(text/event-stream)已复制到响应头,而 c.Data + // 不会覆盖已存在的 Content-Type,这里需显式设置为聚合后的类型。 + c.Writer.Header().Set("Content-Type", contentType) c.Data(resp.StatusCode, contentType, body) } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 38cc743d9d..36125142a5 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1691,24 +1691,6 @@ func normalizeOpenAIPassthroughOAuthBody(body []byte, compact bool) ([]byte, boo return normalized, changed, nil } -func detectOpenAIPassthroughInstructionsRejectReason(reqModel string, body []byte) string { - if !isOpenAICodexModel(reqModel) { - return "" - } - - instructions := gjson.GetBytes(body, "instructions") - if !instructions.Exists() { - return "" - } - if instructions.Type != gjson.String { - return "instructions_not_string" - } - if strings.TrimSpace(instructions.String()) == "" { - return "instructions_empty" - } - return "" -} - func isOpenAICodexModel(model string) bool { return strings.Contains(strings.ToLower(strings.TrimSpace(model)), "codex") } diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 0707d85a39..a2b0fae6a2 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -165,8 +165,9 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. scanner := bufio.NewScanner(resp.Body) scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) if stageFirstOutput { - scanner.Split(openAIFirstOutputDynamicScanLines(&firstOutputScanGuard)) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, openAIFirstOutputDynamicScanLines(&firstOutputScanGuard))) } documentScanner := newOpenAISSEJSONDocumentScanner(scanner) @@ -428,6 +429,15 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. failoverErr.SafeToFailoverAfterWrite = true return resultWithUsage(), failoverErr, true } + if errors.Is(scanErr, errSSETransportLimit) && stageFirstOutput && !firstOutputProgressObserved { + logger.LegacyPrintf("service.openai_gateway", "SSE event exceeded transport limit before first output: account=%d error=%v", account.ID, scanErr) + failoverErr := s.newOpenAIStreamFailoverError( + c, account, false, upstreamRequestID, nil, + "OpenAI SSE event exceeds first-output transport limit: "+scanErr.Error(), + ) + failoverErr.SafeToFailoverAfterWrite = true + return resultWithUsage(), failoverErr, true + } if errors.Is(scanErr, bufio.ErrTooLong) && stageFirstOutput && !firstOutputProgressObserved { logger.LegacyPrintf("service.openai_gateway", "SSE line too long before first output: account=%d max_size=%d error=%v", account.ID, maxLineSize, scanErr) failoverErr := s.newOpenAIStreamFailoverError( @@ -653,6 +663,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. return } restoredData = restoreCodexToolNamesFromSSEContext(c, restoredData, eventType) + restoredData = restoreOpenAIResponsesInstructionsEchoInEvent(c, restoredData) if !bytes.Equal(restoredData, dataBytes) { dataBytes = restoredData data = string(restoredData) @@ -842,13 +853,18 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. // the timeout-disabled path preserves the legacy depth of 16. events := make(chan scanEvent, openAIFirstOutputEventQueueSize(guardFirstOutput)) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev scanEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } if firstOutputScanGuard.Load() { ev.processed = make(chan struct{}) } select { case events <- ev: case <-done: + queueBudget.release(len(ev.line)) return false } if ev.processed == nil { @@ -886,6 +902,9 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if stageFirstOutput && eventInProgress { // EOF dispatches the final SSE event even without a trailing blank @@ -1674,6 +1693,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponse(ctx context.Context, r return nil, fmt.Errorf("restore OpenAI namespace response: %w", err) } body = restoreCodexToolNamesFromContext(c, body) + body = restoreOpenAIResponsesInstructionsEchoInResponse(c, body) body = ensureOpenAIResponseObjectCreatedAt(body) responseheaders.WriteFilteredHeaders(c.Writer.Header(), resp.Header, s.responseHeaderFilter) // Codex 协议要求 /responses/compact JSON 响应携带 x-codex-turn-state @@ -1739,6 +1759,9 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte return nil, s.writeOpenAINonStreamingProtocolError(resp, c, msg) } finalResponse, ok := extractCodexFinalResponse(bodyText) + if !ok && terminalOK { + finalResponse, ok = extractOpenAINonCompletedTerminalResponse(terminalType, terminalPayload) + } usage := s.parseSSEUsageFromBody(bodyText) if ok { @@ -1775,11 +1798,13 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte return nil, fmt.Errorf("restore OpenAI namespace response: %w", restoreErr) } restoredBody = restoreCodexToolNamesFromContext(c, restoredBody) + restoredBody = restoreOpenAIResponsesInstructionsEchoInResponse(c, restoredBody) body = ensureOpenAIResponseObjectCreatedAt(restoredBody) } else { if originalModel != mappedModel { bodyText = s.replaceModelInSSEBody(bodyText, mappedModel, originalModel) } + bodyText = restoreOpenAIResponsesInstructionsEchoInSSEBody(c, bodyText) body = []byte(bodyText) } @@ -1795,6 +1820,9 @@ func (s *OpenAIGatewayService) handleSSEToJSON(resp *http.Response, c *gin.Conte } } if !writeOpenAICompactSSEBridge(c, resp.StatusCode, body) { + // 上游的 Content-Type(text/event-stream)已复制到响应头,而 c.Data + // 不会覆盖已存在的 Content-Type,这里需显式设置为聚合后的类型。 + c.Writer.Header().Set("Content-Type", contentType) c.Data(resp.StatusCode, contentType, body) } @@ -1981,6 +2009,21 @@ func (s *OpenAIGatewayService) writeOpenAINonStreamingProtocolError(resp *http.R return fmt.Errorf("non-streaming openai protocol error: %s", message) } +// extractOpenAINonCompletedTerminalResponse 在没有 response.completed/done 时, +// 从 response.incomplete / response.cancelled 终止事件中取出 response 对象, +// 使非流式客户端拿到带 status/incomplete_details 的单个 JSON,而不是原始 SSE。 +func extractOpenAINonCompletedTerminalResponse(terminalType string, payload []byte) ([]byte, bool) { + switch terminalType { + case "response.incomplete", "response.cancelled", "response.canceled": + default: + return nil, false + } + if response := gjson.GetBytes(payload, "response"); response.Exists() && response.IsObject() { + return []byte(response.Raw), true + } + return nil, false +} + func extractCodexFinalResponse(body string) ([]byte, bool) { var finalResponse []byte forEachOpenAISSEFrame(body, func(eventType string, data []byte) { diff --git a/backend/internal/service/openai_gateway_responses_anthropic_native.go b/backend/internal/service/openai_gateway_responses_anthropic_native.go index ec4fada790..d4ed554a71 100644 --- a/backend/internal/service/openai_gateway_responses_anthropic_native.go +++ b/backend/internal/service/openai_gateway_responses_anthropic_native.go @@ -166,13 +166,15 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) var finalResp *apicompat.AnthropicResponse var usage ClaudeUsage // 读间隔上限:上游挂住 SSE 时中止组装(缓冲路径尚未提交响应头,可回 502)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -200,6 +202,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } // SSE 规范允许 `event:xxx`(冒号后无空格):Kimi 等上游返回紧凑格式。 @@ -213,6 +216,7 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -225,6 +229,11 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + if event.Type == "message_start" && event.Message != nil { finalResp = event.Message mergeAnthropicUsage(&usage, event.Message.Usage) @@ -257,6 +266,16 @@ func (s *OpenAIGatewayService) handleResponsesBufferedFromNativeAnthropic( } } + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + writeResponsesError(c, http.StatusBadGateway, "server_error", failure.message) + return &OpenAIForwardResult{ + RequestID: requestID, UpstreamHeaders: resp.Header, Usage: claudeUsageToOpenAIUsage(&usage), + Model: originalModel, BillingModel: billingModel, UpstreamModel: upstreamModel, + UpstreamEndpoint: "/v1/messages", ReasoningEffort: reasoningEffort, Duration: time.Since(startTime), + }, failure.err + } + if finalResp == nil { writeResponsesError(c, http.StatusBadGateway, "server_error", "Upstream stream ended without a response") return nil, fmt.Errorf("upstream stream ended without response") @@ -346,6 +365,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( maxLineSize = s.cfg.Gateway.MaxLineSize } scanner.Buffer(make([]byte, 0, 64*1024), maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) resultWithUsage := func() *OpenAIForwardResult { return &OpenAIForwardResult{ @@ -368,7 +388,8 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( // WithoutCancel 且 http.Client 无整体 Timeout,无此界限则 scanner.Scan() // 永久阻塞(见 anthropic native pump 文件注释)。 streamInterval := anthropicNativeStreamInterval(s.cfg) - pump := newAnthropicNativeLinePump(scanner, streamInterval) + pump := newAnthropicNativeLinePump(scanner, streamInterval, s.cfg) + streamStatus := &anthropicCompatStream{body: resp.Body} defer pump.stop() logReadErr := func(err error) { @@ -391,7 +412,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( // 与 CC 姊妹路径(handleCCStreamingFromNativeAnthropic.writeChunk)同语义: // 客户端断开后不再写出,但继续排水上游至流自然结束——Anthropic 的最终 // output_tokens 只在末尾 message_delta 携带,提前退出会把整段生成记成 ~1 - // token,payg 上游照常计费而平台漏记。状态机照常推进以保证 finalize 一致。 + // token,payg 上游照常计费而平台漏记。断连后只采集 usage,避免继续累积转换输出。 processAnthropicEvent := func(event *apicompat.AnthropicStreamEvent) { if firstChunk { firstChunk = false @@ -412,10 +433,10 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( syncAnthropicResponsesUsage(state, usage) normalizeAnthropicEventUsageForResponses(event, usage) - events := apicompat.AnthropicEventToResponsesEvents(event, state) if clientDisconnected { return } + events := apicompat.AnthropicEventToResponsesEvents(event, state) for _, evt := range events { payload, err := json.Marshal(evt) if err != nil { @@ -446,6 +467,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } if _, ok := extractOpenAISSEEventLine(line); !ok { @@ -458,6 +480,7 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( return onIdle() } logReadErr(rerr) + streamStatus.readErr = rerr break } payload, ok := extractOpenAISSEDataLine(dataLine) @@ -470,11 +493,28 @@ func (s *OpenAIGatewayService) handleResponsesStreamingFromNativeAnthropic( continue } + streamStatus.observe(&event, payload) + if streamStatus.upstreamErrType != "" { + break + } + processAnthropicEvent(&event) } - // Finalize state machine(客户端已断开时仍推进,保证 usage 汇总完整;仅在 - // 客户端仍连接时写出)。终态帧与逐事件路径一致过工具名反转与客户端工具还原, + if failure := streamStatus.failure(); failure != nil { + _ = resp.Body.Close() + if !clientDisconnected { + writeAnthropicCompatResponsesStreamFailure(c, state, clientToolRestorer, failure) + } + return resultWithUsage(), failure.err + } + + if clientDisconnected { + return resultWithUsage(), nil + } + + // Finalize only after the upstream has supplied a terminal event. + // 终态帧与逐事件路径一致过工具名反转与客户端工具还原, // 避免流截断时终态帧携带改写后的工具名。 if finalEvents := apicompat.FinalizeAnthropicResponsesStream(state); len(finalEvents) > 0 && !clientDisconnected { wrote := false diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go index af0b73d9d8..90728a3f96 100644 --- a/backend/internal/service/openai_gateway_scheduling.go +++ b/backend/internal/service/openai_gateway_scheduling.go @@ -453,6 +453,9 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con if requireCompact && openAICompactSupportTier(account) == 0 { return "compact_unsupported" } + if vetoed, reason := openAIImageSizeVetoReason(ctx, account); vetoed { + return reason + } return "" } @@ -970,6 +973,7 @@ func (s *OpenAIGatewayService) tryStickySessionHit(ctx context.Context, groupID if _, excluded := excludedIDs[accountID]; excluded { return nil } + ctx = withOpenAIImageSizeStickyAccount(ctx, accountID) account, err := s.getSchedulableAccount(ctx, accountID) if err != nil { @@ -1153,6 +1157,7 @@ func (s *OpenAIGatewayService) selectAccountWithLoadAwareness(ctx context.Contex stickyAccountID = accountID } } + ctx = withOpenAIImageSizeStickyAccount(ctx, stickyAccountID) if s.concurrencyService == nil || !cfg.LoadBatchEnabled { account, stickyHit, err := s.selectAccountForModelWithExclusionsStickyHit(ctx, groupID, platform, sessionHash, requestedModel, excludedIDs, requireCompact, stickyAccountID, requiredCapability, preferLowUpstreamRate) if err != nil { diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 1084c824a2..e929ce22b0 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -504,8 +504,8 @@ type OpenAIGatewayService struct { responseHeaderFilter *responseheaders.CompiledHeaderFilter codexSnapshotThrottle *accountWriteThrottle openAIModelsCache openAIModelsCache - openaiCompatSessionResponses sync.Map - openaiCompatAnthropicDigestSessions sync.Map + openaiCompatSessionResponses sessionMemoryCache + openaiCompatAnthropicDigestSessions sessionMemoryCache // openaiCodexTurnStateOrigins: 下游会话 seed → openAICodexTurnStateOrigin, // 记录最近一次向该会话下发 x-codex-turn-state 的铸造账号,供出站守卫 // 剥离跨账号回带(openai_codex_turn_state.go)。 @@ -704,10 +704,15 @@ func (s *OpenAIGatewayService) billingDeps() *billingDeps { } } -// CloseOpenAIWSPool 关闭 OpenAI WebSocket 连接池的后台 worker 和空闲连接。 +// CloseOpenAIWSPool 关闭 OpenAI WebSocket 连接池、后台 worker 和会话缓存清理 timer。 // 应在应用优雅关闭时调用。 func (s *OpenAIGatewayService) CloseOpenAIWSPool() { - if s != nil && s.openaiWSPool != nil { + if s == nil { + return + } + s.openaiCompatSessionResponses.Close() + s.openaiCompatAnthropicDigestSessions.Close() + if s.openaiWSPool != nil { s.openaiWSPool.Close() } } diff --git a/backend/internal/service/openai_image_size_routing.go b/backend/internal/service/openai_image_size_routing.go new file mode 100644 index 0000000000..7b73a8c6ce --- /dev/null +++ b/backend/internal/service/openai_image_size_routing.go @@ -0,0 +1,343 @@ +package service + +import ( + "context" + "errors" + "fmt" + "slices" + "strings" + "sync/atomic" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" +) + +// AccountExtraOpenAIImageSizeTiers 是账号允许承接的生图尺寸档位列表,档位口径与 +// ClassifyImageBillingTier 一致(1K/2K/4K)。缺省、空列表或三档齐全表示不限。 +const AccountExtraOpenAIImageSizeTiers = "openai_image_size_tiers" + +const openAIImageSizeTierUnsupportedReason = "image_size_tier_unsupported" + +var openAIImageSizeTierOrder = []string{ImageBillingSize1K, ImageBillingSize2K, ImageBillingSize4K} + +// openAIImageSizeTestSizes 是测试连接按账号最低允许档位发送的尺寸,各档取该档内的常用尺寸。 +var openAIImageSizeTestSizes = map[string]string{ + ImageBillingSize1K: "1024x1024", + ImageBillingSize2K: "1536x1024", + ImageBillingSize4K: "3840x2160", +} + +// OpenAIImageSizeTiers 按 1K、2K、4K 顺序返回账号限定的尺寸档位;不限时返回 nil。 +func (a *Account) OpenAIImageSizeTiers() []string { + if a == nil || a.Extra == nil { + return nil + } + var values []string + switch raw := a.Extra[AccountExtraOpenAIImageSizeTiers].(type) { + case []any: + for _, item := range raw { + if value, ok := item.(string); ok { + values = append(values, value) + } + } + case []string: + values = raw + } + tiers := make([]string, 0, len(openAIImageSizeTierOrder)) + for _, tier := range openAIImageSizeTierOrder { + for _, value := range values { + if strings.EqualFold(strings.TrimSpace(value), tier) { + tiers = append(tiers, tier) + break + } + } + } + if len(tiers) == 0 || len(tiers) == len(openAIImageSizeTierOrder) { + return nil + } + return tiers +} + +// SupportsOpenAIImageSizeTier 报告账号是否允许承接该尺寸档位。 +func (a *Account) SupportsOpenAIImageSizeTier(tier string) bool { + tiers := a.OpenAIImageSizeTiers() + return tiers == nil || slices.Contains(tiers, tier) +} + +// OpenAIImageTestSize 返回测试连接应发送的尺寸:不限档位时为空(沿用上游默认), +// 否则取账号最低允许档位的代表尺寸。 +func (a *Account) OpenAIImageTestSize() string { + tiers := a.OpenAIImageSizeTiers() + if len(tiers) == 0 { + return "" + } + return openAIImageSizeTestSizes[tiers[0]] +} + +type openAIImageSizeRoutingCtxKey struct{} + +type openAIImageSizePassCtxKey struct{} + +// WithOpenAIImageSizeRouting 记录生图请求的尺寸参数,OpenAI 选号据此按账号尺寸档位分流。 +func WithOpenAIImageSizeRouting(ctx context.Context, size string) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, openAIImageSizeRoutingCtxKey{}, strings.TrimSpace(size)) +} + +func openAIImageSizeRoutingFromContext(ctx context.Context) (string, bool) { + if ctx == nil { + return "", false + } + size, ok := ctx.Value(openAIImageSizeRoutingCtxKey{}).(string) + return size, ok +} + +type openAIImageSizeStickyAccountsCtxKey struct{} + +// withOpenAIImageSizeStickyAccount 在未指定尺寸的选号轮次中标记请求已粘在 accountID 上 +// (会话粘性、previous_response_id),档位偏好不约束这些账号;其他请求原样返回 ctx。 +func withOpenAIImageSizeStickyAccount(ctx context.Context, accountID int64) context.Context { + if ctx == nil || accountID <= 0 { + return ctx + } + if pass, _ := ctx.Value(openAIImageSizePassCtxKey{}).(*openAIImageSizePass); pass == nil || pass.tier != "" { + return ctx + } + prev, _ := ctx.Value(openAIImageSizeStickyAccountsCtxKey{}).([]int64) + if slices.Contains(prev, accountID) { + return ctx + } + ids := make([]int64, len(prev), len(prev)+1) + copy(ids, prev) + return context.WithValue(ctx, openAIImageSizeStickyAccountsCtxKey{}, append(ids, accountID)) +} + +func isOpenAIImageSizeStickyAccount(ctx context.Context, account *Account) bool { + if ctx == nil || account == nil { + return false + } + ids, _ := ctx.Value(openAIImageSizeStickyAccountsCtxKey{}).([]int64) + return slices.Contains(ids, account.ID) +} + +// openAIImageSizePass 是一轮选号的尺寸档位约束。 +type openAIImageSizePass struct { + // tier 非空时只放行允许该档位的账号(请求尺寸可识别)。 + tier string + // rank 在 tier 为空时生效:只放行档位偏好层级等于 rank 的账号, + // 请求已粘在其上的账号(会话粘性、previous_response_id)不受约束。 + rank int + // queuedIDs 是较早轮次只能排队的账号,本轮不再选它们。 + queuedIDs map[int64]struct{} + // nextRank 是本轮排除过的后续层级中最小的一级;为 openAIImageSizePreferenceRanks 时后续各轮没有候选。 + nextRank atomic.Int32 +} + +func (p *openAIImageSizePass) noteLaterRank(rank int) { + for { + current := p.nextRank.Load() + if int32(rank) >= current || p.nextRank.CompareAndSwap(current, int32(rank)) { + return + } + } +} + +// openAIImageSizePreferenceRanks 是未指定尺寸请求的选号层级数,见 openAIImageSizePreferenceRank。 +const openAIImageSizePreferenceRanks = 4 + +// openAIImageSizePreferenceRank 返回账号在未指定尺寸请求中的偏好层级: +// 不限档位为 0,允许 4K 为 1,允许 2K(不含 4K)为 2,仅 1K 为 3。 +func openAIImageSizePreferenceRank(tiers []string) int { + switch { + case tiers == nil: + return 0 + case slices.Contains(tiers, ImageBillingSize4K): + return 1 + case slices.Contains(tiers, ImageBillingSize2K): + return 2 + default: + return 3 + } +} + +// openAIImageSizeVetoReason 判定账号是否被当前选号轮次的尺寸档位约束排除。 +func openAIImageSizeVetoReason(ctx context.Context, account *Account) (bool, string) { + if ctx == nil || account == nil { + return false, "" + } + pass, _ := ctx.Value(openAIImageSizePassCtxKey{}).(*openAIImageSizePass) + if pass == nil { + return false, "" + } + tiers := account.OpenAIImageSizeTiers() + if pass.tier != "" { + if tiers == nil || slices.Contains(tiers, pass.tier) { + return false, "" + } + return true, openAIImageSizeTierUnsupportedReason + } + if _, queued := pass.queuedIDs[account.ID]; queued { + return true, openAIImageSizeTierUnsupportedReason + } + if isOpenAIImageSizeStickyAccount(ctx, account) { + return false, "" + } + rank := openAIImageSizePreferenceRank(tiers) + if rank == pass.rank { + return false, "" + } + if rank > pass.rank { + pass.noteLaterRank(rank) + } + return true, openAIImageSizeTierUnsupportedReason +} + +// openAIImageSizeRoutingUsesPreference 报告 ctx 记录的生图尺寸是否按偏好层级逐层选号(未传、auto 或无法识别的尺寸)。 +func openAIImageSizeRoutingUsesPreference(ctx context.Context) bool { + size, ok := openAIImageSizeRoutingFromContext(ctx) + if !ok { + return false + } + _, explicit := ClassifyImageBillingTier(size) + return !explicit +} + +// openAIImageSizeSpilloverPass 报告本轮是否在较早轮次只拿到排队结果之后进行。这些轮次选号时不写会话粘性绑定, +// 抢到槽位后由 bindOpenAIImageSizeSpilloverAccount 处理绑定。 +func openAIImageSizeSpilloverPass(ctx context.Context) bool { + if ctx == nil { + return false + } + pass, _ := ctx.Value(openAIImageSizePassCtxKey{}).(*openAIImageSizePass) + return pass != nil && len(pass.queuedIDs) > 0 +} + +// bindOpenAIImageSizeSpilloverAccount 处理溢出轮次抢到槽位的选号结果的会话粘性绑定:会话仍绑定在首轮选号前的 +// 账号 initialAccountID 上时保留该绑定,溢出选中的账号只服务本次请求;首轮选号前没有绑定,或绑定已在选号过程中 +// 被清除、改写时,绑定选中的账号。选号结果带利润门时由 handler 在终检通过后绑定,会话保留守护父账号绑定时不改写, +// 这两种情况这里都不绑定。 +func (s *OpenAIGatewayService) bindOpenAIImageSizeSpilloverAccount(ctx context.Context, groupID *int64, sessionHash string, initialAccountID int64, selection *AccountSelectionResult) { + if strings.TrimSpace(sessionHash) == "" || selection == nil || selection.Account == nil || selection.Account.ID <= 0 { + return + } + if selection.ProfitGateActive() || preserveOpenAIGuardianParentBinding(ctx, sessionHash) { + return + } + if initialAccountID > 0 { + if current, err := s.getStickySessionAccountID(ctx, groupID, sessionHash); err == nil && current == initialAccountID { + return + } + } + _ = s.BindStickySession(ctx, groupID, sessionHash, selection.Account.ID) +} + +type openAIAccountSelectFunc func(ctx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) + +// selectOpenAIAccountByImageSizePasses 按尺寸档位约束选号,ctx 未记录生图尺寸时直接选号。 +// 可识别档位的请求只选一轮,只放行允许该档位的账号。未传、auto 或无法识别的尺寸按偏好层级逐层选号: +// 先选不限档位的账号,再依次降级到允许 4K、2K、1K 的账号,跳过本轮未见到账号的层级。 +// 较早轮次抢到槽位的结果优先;某轮只能排队时把该账号留作后备并继续尝试后续层级, +// 都抢不到槽位时返回最早的排队结果。返回的 LatencyMs 是各轮合计耗时。 +func selectOpenAIAccountByImageSizePasses(ctx context.Context, selectFn openAIAccountSelectFunc) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + size, ok := openAIImageSizeRoutingFromContext(ctx) + if !ok { + return selectFn(ctx) + } + if tier, explicit := ClassifyImageBillingTier(size); explicit { + return selectFn(context.WithValue(ctx, openAIImageSizePassCtxKey{}, &openAIImageSizePass{tier: tier})) + } + start := time.Now() + var ( + waiting *AccountSelectionResult + waitingDecision OpenAIAccountScheduleDecision + lastDecision OpenAIAccountScheduleDecision + lastErr error + ) + queuedIDs := make(map[int64]struct{}) + finish := func(selection *AccountSelectionResult, decision OpenAIAccountScheduleDecision, err error) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + decision.LatencyMs = time.Since(start).Milliseconds() + return selection, decision, err + } + for rank := 0; rank < openAIImageSizePreferenceRanks; { + pass := &openAIImageSizePass{rank: rank, queuedIDs: queuedIDs} + pass.nextRank.Store(openAIImageSizePreferenceRanks) + selection, decision, err := selectFn(context.WithValue(ctx, openAIImageSizePassCtxKey{}, pass)) + switch { + case err == nil && selection != nil && selection.Account != nil: + if selection.Acquired || selection.WaitPlan == nil { + return finish(selection, decision, nil) + } + if waiting == nil { + waiting, waitingDecision = selection, decision + } + queuedIDs[selection.Account.ID] = struct{}{} + case err != nil && !errors.Is(err, ErrNoAvailableAccounts) && !errors.Is(err, ErrNoAvailableCompactAccounts): + if waiting != nil { + return finish(waiting, waitingDecision, nil) + } + return finish(selection, decision, err) + default: + lastDecision, lastErr = decision, err + } + rank = int(pass.nextRank.Load()) + } + if waiting != nil { + return finish(waiting, waitingDecision, nil) + } + return finish(nil, lastDecision, lastErr) +} + +// OpenAIImageSizeTierUnsupported 报告分组内持久可调度、支持该模型且具备所需端点与生图能力的 +// OpenAI 账号是否都不允许 size 所属档位,并返回该档位。查询绕过调度快照、忽略限流冷却等临时状态; +// 尺寸无法识别、分组内没有满足模型与能力的账号或查询失败时返回 false。 +func (s *OpenAIGatewayService) OpenAIImageSizeTierUnsupported( + ctx context.Context, + groupID *int64, + requestedModel string, + size string, + requiredCapability OpenAIEndpointCapability, + requiredImageCapability OpenAIImagesCapability, +) (string, bool) { + tier, ok := ClassifyImageBillingTier(size) + if !ok || s == nil || s.accountRepo == nil { + return "", false + } + requestedModel = strings.TrimSpace(requestedModel) + queryGroupID := groupID + includeGrouped := false + if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple { + queryGroupID = nil + includeGrouped = true + } + accounts, err := s.accountRepo.ListModelAvailabilityCandidates(ctx, queryGroupID, []string{PlatformOpenAI}, includeGrouped) + if err != nil { + return "", false + } + hasModelSupport := false + for i := range accounts { + if requestedModel != "" && !accounts[i].IsModelSupported(requestedModel) { + continue + } + if !accountSupportsOpenAICapabilities(&accounts[i], requiredCapability, requiredImageCapability) { + continue + } + hasModelSupport = true + if accounts[i].SupportsOpenAIImageSizeTier(tier) { + return "", false + } + } + return tier, hasModelSupport +} + +// OpenAIImageSizeTierUnsupportedMessage 是分组缺少某尺寸档位账号时返回给客户端的错误信息。 +func OpenAIImageSizeTierUnsupportedMessage(size string, tier string) string { + return fmt.Sprintf("Image size %q (%s tier) is not supported by any account in this group", strings.TrimSpace(size), tier) +} + +// OpenAIResponsesImageRequestSize 返回 Responses 请求生图工具声明的尺寸,工具未声明时取顶层 size。 +func OpenAIResponsesImageRequestSize(body []byte) string { + cfg, _ := resolveOpenAIResponsesImageBillingConfigDetailedFromBody(body, "") + return cfg.InputSize +} diff --git a/backend/internal/service/openai_image_size_routing_test.go b/backend/internal/service/openai_image_size_routing_test.go new file mode 100644 index 0000000000..aef39c1429 --- /dev/null +++ b/backend/internal/service/openai_image_size_routing_test.go @@ -0,0 +1,589 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestAccountOpenAIImageSizeTiers(t *testing.T) { + cases := []struct { + name string + extra map[string]any + want []string + }{ + {name: "missing", extra: nil, want: nil}, + {name: "empty", extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{}}, want: nil}, + {name: "all tiers", extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{"4K", "1K", "2K"}}, want: nil}, + {name: "unknown only", extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{"8K", 4}}, want: nil}, + {name: "not a list", extra: map[string]any{AccountExtraOpenAIImageSizeTiers: "4K"}, want: nil}, + {name: "ordered and case-insensitive", extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{" 2k", "1K", "2K"}}, want: []string{"1K", "2K"}}, + {name: "string slice", extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []string{"4K"}}, want: []string{"4K"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Extra: tc.extra} + require.Equal(t, tc.want, account.OpenAIImageSizeTiers()) + }) + } + + lowOnly := &Account{Extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{"1K", "2K"}}} + require.True(t, lowOnly.SupportsOpenAIImageSizeTier("2K")) + require.False(t, lowOnly.SupportsOpenAIImageSizeTier("4K")) + require.True(t, (&Account{}).SupportsOpenAIImageSizeTier("4K")) +} + +func TestAccountOpenAIImageTestSize(t *testing.T) { + require.Empty(t, (&Account{}).OpenAIImageTestSize()) + require.Equal(t, "1024x1024", (&Account{Extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{"2K", "1K"}}}).OpenAIImageTestSize()) + require.Equal(t, "1536x1024", (&Account{Extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{"2K", "4K"}}}).OpenAIImageTestSize()) + require.Equal(t, "3840x2160", (&Account{Extra: map[string]any{AccountExtraOpenAIImageSizeTiers: []any{"4K"}}}).OpenAIImageTestSize()) +} + +func TestOpenAIResponsesImageRequestSize(t *testing.T) { + require.Equal(t, "3840x2160", OpenAIResponsesImageRequestSize([]byte(`{"model":"gpt-5.4","tools":[{"type":"web_search"},{"type":"image_generation","size":"3840x2160"}]}`))) + require.Equal(t, "1024x1024", OpenAIResponsesImageRequestSize([]byte(`{"model":"gpt-5.4","size":"1024x1024","tools":[{"type":"image_generation"}]}`))) + require.Empty(t, OpenAIResponsesImageRequestSize([]byte(`{"model":"gpt-5.4","tools":[{"type":"image_generation"}]}`))) +} + +func newOpenAIImageSizeTestAccount(id int64, priority int, tiers ...string) Account { + extra := map[string]any{} + if len(tiers) > 0 { + values := make([]any, 0, len(tiers)) + for _, tier := range tiers { + values = append(values, tier) + } + extra[AccountExtraOpenAIImageSizeTiers] = values + } + return Account{ + ID: id, + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Priority: priority, + Extra: extra, + } +} + +type openAIImageSizeSchedulerMode struct { + name string + advanced bool + loadBatch bool +} + +var openAIImageSizeSchedulerModes = []openAIImageSizeSchedulerMode{ + {name: "advanced", advanced: true, loadBatch: true}, + {name: "legacy_load_batch", loadBatch: true}, + {name: "legacy_sequential"}, +} + +func newOpenAIImageSizeSchedulerTestService(mode openAIImageSizeSchedulerMode, accounts []Account, cache *schedulerTestGatewayCache, concurrency schedulerTestConcurrencyCache) *OpenAIGatewayService { + cfg := &config.Config{} + cfg.Gateway.Scheduling.LoadBatchEnabled = mode.loadBatch + cfg.Gateway.Scheduling.StickySessionMaxWaiting = 3 + cfg.Gateway.Scheduling.FallbackMaxWaiting = 3 + if cache == nil { + cache = &schedulerTestGatewayCache{} + } + svc := &OpenAIGatewayService{ + accountRepo: schedulerTestOpenAIAccountRepo{accounts: accounts}, + cache: cache, + cfg: cfg, + concurrencyService: NewConcurrencyService(concurrency), + } + if mode.advanced { + svc.rateLimitService = newOpenAIAdvancedSchedulerRateLimitService("true") + } else { + svc.rateLimitService = newOpenAIAdvancedSchedulerRateLimitService("false") + } + return svc +} + +func selectOpenAIImageSizeTestAccount(t *testing.T, svc *OpenAIGatewayService, groupID int64, sessionHash string, size string) (*AccountSelectionResult, error) { + t.Helper() + ctx := WithOpenAIImageSizeRouting(context.Background(), size) + selection, _, err := svc.SelectAccountWithSchedulerForImages(ctx, &groupID, sessionHash, "gpt-image-2", nil, OpenAIImagesCapabilityNative) + return selection, err +} + +func TestSelectAccountWithSchedulerForImages_ExplicitSizeFiltersByTier(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93001) + accounts := []Account{ + newOpenAIImageSizeTestAccount(81001, 0, "1K", "2K"), + newOpenAIImageSizeTestAccount(81002, 5, "4K"), + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, nil, schedulerTestConcurrencyCache{}) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, "", "3840x2160") + require.NoError(t, err) + require.Equal(t, int64(81002), selection.Account.ID) + + selection, err = selectOpenAIImageSizeTestAccount(t, svc, groupID, "", "1536x1024") + require.NoError(t, err) + require.Equal(t, int64(81001), selection.Account.ID) + + selection, err = selectOpenAIImageSizeTestAccount(t, svc, groupID, "", "4K") + require.NoError(t, err) + require.Equal(t, int64(81002), selection.Account.ID) + }) + } +} + +func TestSelectAccountWithSchedulerForImages_ExplicitSizeWithoutTierAccountFails(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93002) + accounts := []Account{ + newOpenAIImageSizeTestAccount(81011, 0, "1K", "2K"), + newOpenAIImageSizeTestAccount(81012, 0, "2K"), + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, nil, schedulerTestConcurrencyCache{}) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, "", "2880x2880") + require.Error(t, err) + require.True(t, errors.Is(err, ErrNoAvailableAccounts)) + require.Nil(t, selection) + }) + } +} + +func TestSelectAccountWithSchedulerForImages_UnspecifiedSizePreferenceOrder(t *testing.T) { + cases := []struct { + name string + accounts []Account + want int64 + }{ + { + name: "unrestricted first", + accounts: []Account{ + newOpenAIImageSizeTestAccount(81021, 0, "4K"), + newOpenAIImageSizeTestAccount(81022, 0, "1K", "2K"), + newOpenAIImageSizeTestAccount(81023, 9), + }, + want: 81023, + }, + { + name: "then 4K", + accounts: []Account{ + newOpenAIImageSizeTestAccount(81031, 0, "1K", "2K"), + newOpenAIImageSizeTestAccount(81032, 9, "2K", "4K"), + }, + want: 81032, + }, + { + name: "then 2K", + accounts: []Account{ + newOpenAIImageSizeTestAccount(81041, 0, "1K"), + newOpenAIImageSizeTestAccount(81042, 9, "2K"), + }, + want: 81042, + }, + { + name: "then 1K", + accounts: []Account{ + newOpenAIImageSizeTestAccount(81051, 0, "1K"), + }, + want: 81051, + }, + } + for _, mode := range openAIImageSizeSchedulerModes { + for _, tc := range cases { + t.Run(mode.name+"/"+tc.name, func(t *testing.T) { + svc := newOpenAIImageSizeSchedulerTestService(mode, tc.accounts, nil, schedulerTestConcurrencyCache{}) + for _, size := range []string{"", "auto", "3:2"} { + selection, err := selectOpenAIImageSizeTestAccount(t, svc, 93003, "", size) + require.NoError(t, err, size) + require.Equal(t, tc.want, selection.Account.ID, size) + } + }) + } + } +} + +func TestSelectAccountWithSchedulerForImages_UnspecifiedSizeSkipsBusyPreferredAccount(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + accounts := []Account{ + newOpenAIImageSizeTestAccount(81061, 0), + newOpenAIImageSizeTestAccount(81062, 9, "4K"), + } + concurrency := schedulerTestConcurrencyCache{acquireResults: map[int64]bool{81061: false}} + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, nil, concurrency) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, 93004, "", "") + require.NoError(t, err) + require.Equal(t, int64(81062), selection.Account.ID) + require.True(t, selection.Acquired) + }) + } +} + +func TestSelectAccountWithSchedulerForImages_UnspecifiedSizeSkipsBusyPreferredAccountWithSession(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93009) + accounts := []Account{ + newOpenAIImageSizeTestAccount(81111, 0), + newOpenAIImageSizeTestAccount(81112, 9, "4K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{} + concurrency := schedulerTestConcurrencyCache{acquireResults: map[int64]bool{81111: false}} + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, "image-size-busy-session", "") + require.NoError(t, err) + require.Equal(t, int64(81112), selection.Account.ID) + require.True(t, selection.Acquired) + }) + } +} + +func TestSelectAccountWithSchedulerForImages_SpilloverToRestrictedAccountKeepsStickyBinding(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93011) + sessionHash := "image-size-spillover" + accounts := []Account{ + newOpenAIImageSizeTestAccount(81131, 0), + newOpenAIImageSizeTestAccount(81132, 9, "4K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:" + sessionHash: 81131}} + concurrency := schedulerTestConcurrencyCache{ + acquireResults: map[int64]bool{81131: false}, + waitCounts: map[int64]int{81131: 3}, + loadMap: map[int64]*AccountLoadInfo{81131: {AccountID: 81131, LoadRate: 100, WaitingCount: 3}}, + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "") + require.NoError(t, err) + require.NotNil(t, selection.Account) + require.Equal(t, int64(81131), cache.sessionBindings["openai:"+sessionHash], "a spillover pick must not rebind the session") + if mode.loadBatch { + require.Equal(t, int64(81132), selection.Account.ID) + require.True(t, selection.Acquired) + } + }) + } +} + +func TestSelectAccountWithSchedulerForImages_SpilloverWithoutBindingBindsServedAccount(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93012) + sessionHash := "image-size-spillover-unbound" + accounts := []Account{ + newOpenAIImageSizeTestAccount(81141, 0), + newOpenAIImageSizeTestAccount(81142, 9, "4K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{} + concurrency := schedulerTestConcurrencyCache{ + acquireResults: map[int64]bool{81141: false}, + waitCounts: map[int64]int{81141: 3}, + loadMap: map[int64]*AccountLoadInfo{81141: {AccountID: 81141, LoadRate: 100, WaitingCount: 3}}, + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "") + require.NoError(t, err) + require.Equal(t, int64(81142), selection.Account.ID) + require.Equal(t, int64(81142), cache.sessionBindings["openai:"+sessionHash]) + }) + } +} + +func TestSelectAccountWithSchedulerForImages_SpilloverReplacesClearedStaleBinding(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93014) + sessionHash := "image-size-spillover-stale" + accounts := []Account{ + newOpenAIImageSizeTestAccount(81161, 0), + newOpenAIImageSizeTestAccount(81162, 9, "4K"), + newOpenAIImageSizeTestAccount(81163, 0), + } + accounts[2].Schedulable = false + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:" + sessionHash: 81163}} + concurrency := schedulerTestConcurrencyCache{ + acquireResults: map[int64]bool{81161: false}, + waitCounts: map[int64]int{81161: 3}, + loadMap: map[int64]*AccountLoadInfo{81161: {AccountID: 81161, LoadRate: 100, WaitingCount: 3}}, + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "") + require.NoError(t, err) + require.Equal(t, int64(81162), selection.Account.ID) + require.True(t, selection.Acquired) + require.Equal(t, int64(81162), cache.sessionBindings["openai:"+sessionHash], "a binding that is no longer usable is replaced by the served account") + }) + } +} + +func TestSelectAccountWithSchedulerForImages_AllPassesQueuedKeepBindingOnReturnedAccount(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93015) + sessionHash := "image-size-all-queued" + accounts := []Account{ + newOpenAIImageSizeTestAccount(81171, 0), + newOpenAIImageSizeTestAccount(81172, 9, "4K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{} + concurrency := schedulerTestConcurrencyCache{ + acquireResults: map[int64]bool{81171: false, 81172: false}, + waitCounts: map[int64]int{81171: 3, 81172: 3}, + loadMap: map[int64]*AccountLoadInfo{ + 81171: {AccountID: 81171, LoadRate: 100, WaitingCount: 3}, + 81172: {AccountID: 81172, LoadRate: 100, WaitingCount: 3}, + }, + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "") + require.NoError(t, err) + require.Equal(t, int64(81171), selection.Account.ID) + require.NotNil(t, selection.WaitPlan) + bound, ok := cache.sessionBindings["openai:"+sessionHash] + if mode.loadBatch { + require.False(t, ok, "a queued selection does not bind the session") + } else { + require.Equal(t, int64(81171), bound, "eager sequential binding stays on the returned queued account") + } + }) + } +} + +func TestSelectAccountWithSchedulerForImages_UnspecifiedSizePrefersHealthyProxyOverQuarantinedUnrestricted(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + quarantinedProxy := int64(71) + healthyProxy := int64(72) + unrestricted := newOpenAIImageSizeTestAccount(81121, 0) + unrestricted.ProxyID = &quarantinedProxy + highOnly := newOpenAIImageSizeTestAccount(81122, 9, "4K") + highOnly.ProxyID = &healthyProxy + svc := newOpenAIImageSizeSchedulerTestService(mode, []Account{unrestricted, highOnly}, nil, schedulerTestConcurrencyCache{}) + svc.openaiProxyStreamCircuit = newOpenAIProxyStreamCircuit(openAIProxyStreamCircuitSettings{ + failureThreshold: 1, + failureWindow: time.Minute, + quarantineTTL: 10 * time.Minute, + maxEntries: 16, + }) + svc.openaiProxyStreamCircuit.recordFailure(quarantinedProxy, time.Now()) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, 93010, "", "") + require.NoError(t, err) + require.Equal(t, int64(81122), selection.Account.ID, "a restricted account on a healthy proxy beats the quarantine fail-open") + + svc.accountRepo = schedulerTestOpenAIAccountRepo{accounts: []Account{unrestricted}} + selection, err = selectOpenAIImageSizeTestAccount(t, svc, 93010, "", "") + require.NoError(t, err) + require.Equal(t, int64(81121), selection.Account.ID, "fail-open still serves when nothing else can") + }) + } +} + +func TestSelectAccountWithSchedulerForImages_StickyAccountUnderSizeRouting(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93005) + sessionHash := "image-size-sticky" + accounts := []Account{ + newOpenAIImageSizeTestAccount(81071, 0), + newOpenAIImageSizeTestAccount(81072, 9, "1K", "2K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{ + "openai:" + sessionHash: 81072, + }} + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, schedulerTestConcurrencyCache{}) + + selection, err := selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "") + require.NoError(t, err) + require.Equal(t, int64(81072), selection.Account.ID, "unspecified size keeps the sticky account") + + cache.sessionBindings["openai:"+sessionHash] = 81072 + selection, err = selectOpenAIImageSizeTestAccount(t, svc, groupID, sessionHash, "3840x2160") + require.NoError(t, err) + require.Equal(t, int64(81071), selection.Account.ID, "explicit 4K leaves a 1K/2K-only sticky account") + }) + } +} + +func TestSelectAccountWithSchedulerForImages_BusyStickyAccountMatchesUnroutedSelection(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93013) + sessionHash := "image-size-busy-sticky" + selectWith := func(ctx context.Context) (int64, bool) { + accounts := []Account{ + newOpenAIImageSizeTestAccount(81151, 0), + newOpenAIImageSizeTestAccount(81152, 9, "4K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + cache := &schedulerTestGatewayCache{sessionBindings: map[string]int64{"openai:" + sessionHash: 81151}} + concurrency := schedulerTestConcurrencyCache{ + acquireResults: map[int64]bool{81151: false}, + loadMap: map[int64]*AccountLoadInfo{81151: {AccountID: 81151, LoadRate: 100}}, + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, cache, concurrency) + selection, _, err := svc.SelectAccountWithSchedulerForImages(ctx, &groupID, sessionHash, "gpt-image-2", nil, OpenAIImagesCapabilityNative) + require.NoError(t, err) + require.NotNil(t, selection.Account) + return selection.Account.ID, selection.Acquired + } + routedID, routedAcquired := selectWith(WithOpenAIImageSizeRouting(context.Background(), "")) + unroutedID, unroutedAcquired := selectWith(context.Background()) + require.Equal(t, unroutedID, routedID, "a busy sticky account is waited on or escaped exactly as without size routing") + require.Equal(t, unroutedAcquired, routedAcquired) + }) + } +} + +func TestSelectAccountWithScheduler_PreviousResponseAccountUnderSizeRouting(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93008) + accounts := []Account{ + newOpenAIImageSizeTestAccount(81101, 0), + newOpenAIImageSizeTestAccount(81102, 9, "1K", "2K"), + } + for i := range accounts { + accounts[i].GroupIDs = []int64{groupID} + } + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, nil, schedulerTestConcurrencyCache{}) + require.NoError(t, svc.getOpenAIWSStateStore().BindResponseAccount(context.Background(), groupID, "resp_image_size", 81102, time.Hour)) + + selectWithSize := func(size string) int64 { + ctx := WithOpenAIImageSizeRouting(context.Background(), size) + selection, _, err := svc.SelectAccountWithScheduler(ctx, &groupID, "resp_image_size", "", "gpt-5.4", nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + if selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + return selection.Account.ID + } + require.Equal(t, int64(81102), selectWithSize(""), "unspecified size keeps the previous_response account") + require.Equal(t, int64(81101), selectWithSize("3840x2160"), "explicit 4K leaves a 1K/2K-only previous_response account") + }) + } +} + +func TestSelectAccountWithScheduler_TextRequestIgnoresImageSizeTiers(t *testing.T) { + for _, mode := range openAIImageSizeSchedulerModes { + t.Run(mode.name, func(t *testing.T) { + groupID := int64(93006) + accounts := []Account{newOpenAIImageSizeTestAccount(81081, 0, "4K")} + svc := newOpenAIImageSizeSchedulerTestService(mode, accounts, nil, schedulerTestConcurrencyCache{}) + + selection, _, err := svc.SelectAccountWithScheduler(context.Background(), &groupID, "", "", "gpt-5.4", nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.Equal(t, int64(81081), selection.Account.ID) + }) + } +} + +func TestSelectOpenAIAccountByImageSizePasses_StopsWhenNoAccountVetoed(t *testing.T) { + restricted := newOpenAIImageSizeTestAccount(1, 0, "4K") + unrestricted := newOpenAIImageSizeTestAccount(2, 0) + + calls := 0 + _, _, err := selectOpenAIAccountByImageSizePasses(WithOpenAIImageSizeRouting(context.Background(), ""), func(ctx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + calls++ + vetoed, _ := openAIImageSizeVetoReason(ctx, &unrestricted) + require.False(t, vetoed) + return nil, OpenAIAccountScheduleDecision{}, ErrNoAvailableAccounts + }) + require.ErrorIs(t, err, ErrNoAvailableAccounts) + require.Equal(t, 1, calls) + + calls = 0 + _, _, err = selectOpenAIAccountByImageSizePasses(WithOpenAIImageSizeRouting(context.Background(), ""), func(ctx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + calls++ + _, _ = openAIImageSizeVetoReason(ctx, &restricted) + return nil, OpenAIAccountScheduleDecision{}, ErrNoAvailableAccounts + }) + require.ErrorIs(t, err, ErrNoAvailableAccounts) + require.Equal(t, 2, calls, "the 4K pass admits the 4K-only account, so the 2K and 1K passes are skipped") +} + +func TestSelectOpenAIAccountByImageSizePasses_ReturnsEarliestWaitPlan(t *testing.T) { + restricted := newOpenAIImageSizeTestAccount(1, 0, "1K") + calls := 0 + selection, _, err := selectOpenAIAccountByImageSizePasses(WithOpenAIImageSizeRouting(context.Background(), "auto"), func(ctx context.Context) (*AccountSelectionResult, OpenAIAccountScheduleDecision, error) { + calls++ + _, _ = openAIImageSizeVetoReason(ctx, &restricted) + if calls == 1 { + return &AccountSelectionResult{Account: &Account{ID: 10}, WaitPlan: &AccountWaitPlan{AccountID: 10}}, OpenAIAccountScheduleDecision{}, nil + } + if calls == 2 { + return &AccountSelectionResult{Account: &Account{ID: 11}, WaitPlan: &AccountWaitPlan{AccountID: 11}}, OpenAIAccountScheduleDecision{}, nil + } + return nil, OpenAIAccountScheduleDecision{}, ErrNoAvailableAccounts + }) + require.NoError(t, err) + require.Equal(t, int64(10), selection.Account.ID) + require.Equal(t, 2, calls, "the unrestricted pass jumps straight to the 1K-only rank") +} + +func TestOpenAIImageSizeTierUnsupported(t *testing.T) { + groupID := int64(93007) + lowOnly := newOpenAIImageSizeTestAccount(81091, 0, "1K", "2K") + highOnly := newOpenAIImageSizeTestAccount(81092, 0, "4K") + textOnly := newOpenAIImageSizeTestAccount(81093, 0) + textOnly.Credentials = map[string]any{"model_mapping": map[string]any{"gpt-5.4": "gpt-5.4"}} + + svc := &OpenAIGatewayService{accountRepo: schedulerTestOpenAIAccountRepo{accounts: []Account{lowOnly, textOnly}}} + tier, unsupported := svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-image-2", "3840x2160", "", OpenAIImagesCapabilityNative) + require.True(t, unsupported) + require.Equal(t, "4K", tier) + + _, unsupported = svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-image-2", "1024x1024", "", OpenAIImagesCapabilityNative) + require.False(t, unsupported) + _, unsupported = svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-image-2", "auto", "", OpenAIImagesCapabilityNative) + require.False(t, unsupported) + + svc.accountRepo = schedulerTestOpenAIAccountRepo{accounts: []Account{lowOnly, highOnly}} + _, unsupported = svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-image-2", "3840x2160", "", OpenAIImagesCapabilityNative) + require.False(t, unsupported) + + svc.accountRepo = schedulerTestOpenAIAccountRepo{accounts: []Account{textOnly}} + _, unsupported = svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-image-2", "3840x2160", "", OpenAIImagesCapabilityNative) + require.False(t, unsupported, "no account serves the model: leave classification to model_not_found") + + chatOnly := newOpenAIImageSizeTestAccount(81094, 0) + chatOnly.Extra["openai_responses_supported"] = false + svc.accountRepo = schedulerTestOpenAIAccountRepo{accounts: []Account{chatOnly, lowOnly}} + _, unsupported = svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-5.4", "3840x2160", OpenAIEndpointCapabilityResponses, "") + require.True(t, unsupported, "an unrestricted account without the Responses capability cannot serve the request") + _, unsupported = svc.OpenAIImageSizeTierUnsupported(context.Background(), &groupID, "gpt-5.4", "3840x2160", OpenAIEndpointCapabilityChatCompletions, "") + require.False(t, unsupported) +} diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index 12042b0e58..bd5b85aa0d 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -1,13 +1,13 @@ package service import ( - "bufio" "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" + "errors" "fmt" "io" "mime" @@ -660,7 +660,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( // 就把已经在出图的上游调用打断成 context canceled,网关记 502、不扣费,而上游那边 // 图已经生成并计费。同一端点的 OAuth 分支 forwardOpenAIImagesOAuth 以及 Grok 媒体 // 路径本来就无条件脱钩,这里对齐;上游侧仍由 ResponseHeaderTimeout 兜底。 - upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx, s.openAIImageDrainTimeout()) defer releaseUpstreamCtx() token, _, err := s.GetAccessToken(upstreamCtx, account) @@ -1018,6 +1018,30 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( seenSSEData := false fallbackTooLarge := false var sseData openAISSEDataAccumulator + // Keep raw passthrough frames until their delimiter so a rejected event is + // never completed downstream by the gateway's own error frame. These strings + // share storage with sseData and are bounded by the same SSE event limits. + var pendingRawLines []string + discardRawEvent := func() { + clear(pendingRawLines) + pendingRawLines = pendingRawLines[:0] + } + flushRawEvent := func() { + defer discardRawEvent() + if clientDisconnected || len(pendingRawLines) == 0 { + return + } + for _, line := range pendingRawLines { + if _, writeErr := io.WriteString(c.Writer, line); writeErr != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Images stream client disconnected, continue draining upstream for billing") + return + } + } + flusher.Flush() + lastDownstreamWriteAt = time.Now() + } + defer discardRawEvent() var streamErr error finish := func() error { if direct == nil { @@ -1096,6 +1120,7 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( } flushSSEEvent := func() { + flushRawEvent() sseData.Flush(processSSEData) } @@ -1107,17 +1132,14 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( ms := int(time.Since(startTime).Milliseconds()) firstTokenMs = &ms } + rawLine := string(line) + trimmedLine := strings.TrimRight(rawLine, "\r\n") if !clientDisconnected && direct == nil { - if _, writeErr := c.Writer.Write(line); writeErr != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "[OpenAI] Images stream client disconnected, continue draining upstream for billing") - } else { - flusher.Flush() - lastDownstreamWriteAt = time.Now() + pendingRawLines = append(pendingRawLines, rawLine) + if trimmedLine == "" { + flushRawEvent() } } - - trimmedLine := strings.TrimRight(string(line), "\r\n") if _, ok := extractOpenAISSEDataLine(trimmedLine); ok || strings.TrimSpace(trimmedLine) == "" { sseData.AddLine(trimmedLine, processSSEData) return @@ -1151,9 +1173,15 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( streamInterval := s.openAIImageStreamDataInterval() keepaliveInterval := s.openAIImageStreamKeepaliveInterval() if streamInterval <= 0 && keepaliveInterval <= 0 { - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() + if errors.Is(err, errSSETransportLimit) { + discardRawEvent() + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, err + } processLine(line) if err == io.EOF { break @@ -1174,11 +1202,16 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( } events := make(chan readEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev readEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1186,9 +1219,9 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) go func() { defer close(events) - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() if len(line) > 0 { atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) } @@ -1229,12 +1262,21 @@ func (s *OpenAIGatewayService) handleOpenAIImagesStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { flushSSEEvent() finalizeFallbackBody() return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, finish() } if ev.err != nil { + if errors.Is(ev.err, errSSETransportLimit) { + discardRawEvent() + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, ev.err + } flushSSEEvent() return usage, imageCounter.Count(), imageCounter.Sizes(), firstTokenMs, ev.err } @@ -1805,3 +1847,13 @@ func dedupeStrings(values []string) []string { } return out } + +// Image generation may continue long enough to incur upstream costs after the +// client disconnects. Keep its bounded billing drain aligned with image idle +// configuration, while preserving a safety limit if idle checks are disabled. +func (s *OpenAIGatewayService) openAIImageDrainTimeout() time.Duration { + if timeout := s.openAIImageStreamDataInterval(); timeout > 0 { + return timeout + } + return 900 * time.Second +} diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 36995437fd..63db0668ac 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -1,7 +1,6 @@ package service import ( - "bufio" "bytes" "context" "encoding/base64" @@ -1169,6 +1168,17 @@ func (s *OpenAIGatewayService) tryWriteOpenAIImagesStreamEvent( return true } +func (s *OpenAIGatewayService) tryWriteOpenAIImagesStreamLimitError(c *gin.Context, flusher http.Flusher, clientDisconnected *bool, lastWriteAt *time.Time) { + if c.Request != nil && c.Request.Context().Err() != nil { + return + } + payload := buildOpenAIImagesStreamErrorBodyFromUpstream(&OpenAIImagesUpstreamError{ + Code: "response_too_large", + Message: "upstream image stream exceeded transport limits", + }) + s.tryWriteOpenAIImagesStreamEvent(c, flusher, clientDisconnected, lastWriteAt, "error", payload) +} + func (s *OpenAIGatewayService) parseOpenAIImagesSSEUsageBytes(data []byte, usage *OpenAIUsage) { s.parseSSEUsageBytes(data, usage) if usage == nil || !gjson.ValidBytes(data) || gjson.GetBytes(data, "type").String() != "response.completed" { @@ -1629,9 +1639,14 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( streamInterval := s.openAIImageStreamDataInterval() keepaliveInterval := s.openAIImageStreamKeepaliveInterval() if streamInterval <= 0 && keepaliveInterval <= 0 { - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() + if errors.Is(err, errSSETransportLimit) { + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCount, imageOutputSizes, firstTokenMs, err + } done, processErr := processLine(line) if processErr != nil { return usage, imageCount, imageOutputSizes, firstTokenMs, processErr @@ -1671,11 +1686,16 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( } events := make(chan readEvent, 16) done := make(chan struct{}) + queueBudget := newSSEQueueBudget(s.cfg) sendEvent := func(ev readEvent) bool { + if !queueBudget.acquire(len(ev.line), done) { + return false + } select { case events <- ev: return true case <-done: + queueBudget.release(len(ev.line)) return false } } @@ -1683,9 +1703,9 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) go func() { defer close(events) - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadBytes('\n') + line, err := reader.ReadLine() if len(line) > 0 { atomic.StoreInt64(&lastReadAt, time.Now().UnixNano()) } @@ -1726,6 +1746,9 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( for { select { case ev, ok := <-events: + if ok { + queueBudget.release(len(ev.line)) + } if !ok { if done, processErr := flushData(); processErr != nil { return usage, imageCount, imageOutputSizes, firstTokenMs, processErr @@ -1738,6 +1761,11 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthStreamingResponse( return usage, imageCount, imageOutputSizes, firstTokenMs, nil } if ev.err != nil { + if errors.Is(ev.err, errSSETransportLimit) { + s.tryWriteOpenAIImagesStreamLimitError(c, flusher, &clientDisconnected, &lastDownstreamWriteAt) + _ = resp.Body.Close() + return usage, imageCount, imageOutputSizes, firstTokenMs, ev.err + } if done, processErr := flushData(); processErr != nil { return usage, imageCount, imageOutputSizes, firstTokenMs, processErr } else if done { @@ -1819,7 +1847,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( len(parsed.Uploads), uploadParts, ) - upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx, s.openAIImageDrainTimeout()) defer releaseUpstreamCtx() token, _, err := s.GetAccessToken(upstreamCtx, account) diff --git a/backend/internal/service/openai_images_stream_limit_error_test.go b/backend/internal/service/openai_images_stream_limit_error_test.go new file mode 100644 index 0000000000..a563227faf --- /dev/null +++ b/backend/internal/service/openai_images_stream_limit_error_test.go @@ -0,0 +1,243 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type imageLimitTestBody struct { + *strings.Reader + closed atomic.Bool +} + +func (b *imageLimitTestBody) Close() error { + b.closed.Store(true) + return nil +} + +type imageLimitDisconnectedWriter struct { + gin.ResponseWriter + attempts int +} + +func (w *imageLimitDisconnectedWriter) Write([]byte) (int, error) { + w.attempts++ + return 0, io.ErrClosedPipe +} + +func (w *imageLimitDisconnectedWriter) WriteString(string) (int, error) { + w.attempts++ + return 0, io.ErrClosedPipe +} + +func TestImageStreamTransportLimitEmitsErrorAndPreservesUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, route := range []string{"direct", "responses", "passthrough"} { + for _, async := range []bool{false, true} { + for _, limit := range []string{"line", "event_bytes", "event_lines"} { + t.Run(fmt.Sprintf("%s/async_%t/%s", route, async, limit), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1024, SSEEventMaxBytes: 4096, SSEQueueMaxBytes: 128}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + wire := "data: {\"type\":\"image_generation.partial_image\",\"b64_json\":\"AA==\",\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}\n\n" + pendingTerminal := "data: {\"type\":\"image_generation.completed\",\"b64_json\":\"AA==\",\"usage\":{\"input_tokens\":999}}\n" + if route == "responses" { + wire = "data: {\"type\":\"response.in_progress\",\"response\":{\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}}\n\n" + + "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"image_generation_call\",\"id\":\"image-pending\",\"result\":\"AA==\"}}\n\n" + pendingTerminal = "data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":999},\"output\":[{\"type\":\"image_generation_call\",\"result\":\"AA==\"}]}}\n" + } + wire += pendingTerminal + switch limit { + case "line": + cfg.Gateway.MaxLineSize = 256 + wire += ":" + strings.Repeat("x", 512) + case "event_bytes": + cfg.Gateway.SSEEventMaxBytes = 256 + wire += ":" + strings.Repeat("x", 150) + "\n:" + strings.Repeat("x", 150) + case "event_lines": + cfg.Gateway.SSEEventMaxLines = 2 + wire += ":first\n:second\n" + } + wire += "\n\ndata: [DONE]\n\n" + body := &imageLimitTestBody{Reader: strings.NewReader(wire)} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + svc := &OpenAIGatewayService{cfg: cfg} + var usage OpenAIUsage + var count int + var err error + if route == "responses" { + usage, count, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + var direct *OpenAIImagesRequest + if route == "direct" { + direct = &OpenAIImagesRequest{Model: "gpt-image-2", ResponseFormat: "b64_json"} + } + usage, count, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), direct) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.True(t, body.closed.Load(), "transport-limit failures must release the upstream body") + wantUsage := OpenAIUsage{InputTokens: 11, OutputTokens: 7} + if route == "direct" { + wantUsage.ImageOutputTokens = 7 + } + require.Equal(t, wantUsage, usage) + require.Zero(t, count, "pending image output must not be finalized on a failed stream") + require.NotContains(t, rec.Body.String(), ".completed") + require.NotContains(t, rec.Body.String(), "[DONE]") + requireImageTransportLimitError(t, rec.Body.String()) + }) + } + } + } +} + +func TestImageStreamPassthroughPreservesRawFrames(t *testing.T) { + completed := `{"type":"image_generation.completed","b64_json":"AA==","usage":{"input_tokens":11,"output_tokens":7},"unknown":{"keep":true}}` + for _, async := range []bool{false, true} { + for _, wire := range []string{ + ": heartbeat\r\nevent: image_generation.completed\r\nid: opaque\r\ndata: " + completed + "\r\n\r\n: final comment", + "event: image_generation.completed\ndata: " + completed, + } { + t.Run(fmt.Sprintf("async_%t/bytes_%d", async, len(wire)), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1024}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + body := &imageLimitTestBody{Reader: strings.NewReader(wire)} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + svc := &OpenAIGatewayService{cfg: cfg} + usage, count, _, _, err := svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), nil) + require.NoError(t, err) + require.Equal(t, wire, rec.Body.String(), "passthrough must retain CRLF, comments, unknown fields and unterminated EOF bytes") + require.Equal(t, OpenAIUsage{InputTokens: 11, OutputTokens: 7}, usage) + require.Equal(t, 1, count) + }) + } + } +} + +func TestImageStreamTransportLimitSkipsDisconnectedClient(t *testing.T) { + for _, oauth := range []bool{false, true} { + for _, async := range []bool{false, true} { + t.Run(fmt.Sprintf("oauth_%t/async_%t", oauth, async), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 32}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil).WithContext(ctx) + body := &imageLimitTestBody{Reader: strings.NewReader(":" + strings.Repeat("x", 64))} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + svc := &OpenAIGatewayService{cfg: cfg} + var err error + if oauth { + _, _, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + _, _, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), nil) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.True(t, body.closed.Load()) + require.Empty(t, rec.Body.String()) + }) + } + } +} + +func TestImageStreamTransportLimitDoesNotRetryFailedClientWriter(t *testing.T) { + for _, route := range []string{"direct", "responses", "passthrough"} { + for _, async := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/async_%t", route, async), func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 512}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + wire := "data: {\"type\":\"image_generation.partial_image\",\"b64_json\":\"AA==\",\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}\n\n" + if route == "responses" { + wire = "data: {\"type\":\"response.image_generation_call.partial_image\",\"partial_image_b64\":\"AA==\",\"usage\":{\"input_tokens\":11,\"output_tokens\":7}}\n\n" + } + wire += ":" + strings.Repeat("x", 1024) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + writer := &imageLimitDisconnectedWriter{ResponseWriter: c.Writer} + c.Writer = writer + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + body := &imageLimitTestBody{Reader: strings.NewReader(wire)} + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: body} + svc := &OpenAIGatewayService{cfg: cfg} + var usage OpenAIUsage + var err error + if route == "responses" { + usage, _, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + var direct *OpenAIImagesRequest + if route == "direct" { + direct = &OpenAIImagesRequest{Model: "gpt-image-2"} + } + usage, _, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), direct) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.True(t, body.closed.Load()) + require.Equal(t, 11, usage.InputTokens) + require.Equal(t, 7, usage.OutputTokens) + require.Equal(t, 1, writer.attempts, "do not write a transport-limit error after the client writer has failed") + }) + } + } +} + +func requireImageTransportLimitError(t *testing.T, wire string) { + t.Helper() + errorEvents := 0 + for _, frame := range strings.Split(strings.ReplaceAll(wire, "\r\n", "\n"), "\n\n") { + var eventName string + var data []string + for _, line := range strings.Split(frame, "\n") { + if value, ok := strings.CutPrefix(line, "event:"); ok { + eventName = strings.TrimSpace(value) + } + if value, ok := strings.CutPrefix(line, "data:"); ok { + data = append(data, strings.TrimPrefix(value, " ")) + } + } + if eventName != "error" { + continue + } + errorEvents++ + var payload struct { + Type string `json:"type"` + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + require.NoError(t, json.Unmarshal([]byte(strings.Join(data, "\n")), &payload), "the error must be a standalone, parseable SSE event") + require.Equal(t, "error", payload.Type) + require.Equal(t, "upstream_error", payload.Error.Type) + require.Equal(t, "response_too_large", payload.Error.Code) + require.NotEmpty(t, payload.Error.Message) + } + require.Equal(t, 1, errorEvents) +} diff --git a/backend/internal/service/openai_messages_continuation.go b/backend/internal/service/openai_messages_continuation.go index 65bafbd544..601922c226 100644 --- a/backend/internal/service/openai_messages_continuation.go +++ b/backend/internal/service/openai_messages_continuation.go @@ -20,6 +20,16 @@ type openAICompatSessionResponseBinding struct { ExpiresAt time.Time } +func (b openAICompatSessionResponseBinding) sessionExpiresAt() time.Time { return b.ExpiresAt } +func (b openAICompatSessionResponseBinding) sessionCost() int { + return len(b.ResponseID) + len(b.TurnState) +} +func (b openAICompatSessionResponseBinding) cloneSessionValue() sessionMemoryValue { + b.ResponseID = strings.Clone(b.ResponseID) + b.TurnState = strings.Clone(b.TurnState) + return b +} + func openAICompatContinuationEnabled(account *Account, model string) bool { if account == nil || account.Type != AccountTypeAPIKey { return false diff --git a/backend/internal/service/openai_messages_digest_session.go b/backend/internal/service/openai_messages_digest_session.go index 44a49d1e39..b00697c43e 100644 --- a/backend/internal/service/openai_messages_digest_session.go +++ b/backend/internal/service/openai_messages_digest_session.go @@ -14,6 +14,13 @@ type openAICompatAnthropicDigestBinding struct { ExpiresAt time.Time } +func (b openAICompatAnthropicDigestBinding) sessionExpiresAt() time.Time { return b.ExpiresAt } +func (b openAICompatAnthropicDigestBinding) sessionCost() int { return len(b.PromptCacheKey) } +func (b openAICompatAnthropicDigestBinding) cloneSessionValue() sessionMemoryValue { + b.PromptCacheKey = strings.Clone(b.PromptCacheKey) + return b +} + func buildOpenAICompatAnthropicDigestChain(req *apicompat.AnthropicRequest) string { if req == nil { return "" @@ -52,24 +59,12 @@ func (s *OpenAIGatewayService) findOpenAICompatAnthropicDigestPromptCacheKey(acc if ns == "" { return "", "" } - chain := digestChain - for { - if raw, ok := s.openaiCompatAnthropicDigestSessions.Load(ns + chain); ok { - if binding, ok := raw.(openAICompatAnthropicDigestBinding); ok { - if binding.ExpiresAt.IsZero() || time.Now().Before(binding.ExpiresAt) { - if key := strings.TrimSpace(binding.PromptCacheKey); key != "" { - return key, chain - } - } - } - s.openaiCompatAnthropicDigestSessions.Delete(ns + chain) + if raw, chain, ok := s.openaiCompatAnthropicDigestSessions.longestDigestPrefix(ns, digestChain); ok { + if binding, ok := raw.(openAICompatAnthropicDigestBinding); ok { + return binding.PromptCacheKey, chain } - i := strings.LastIndex(chain, "-") - if i < 0 { - return "", "" - } - chain = chain[:i] } + return "", "" } func (s *OpenAIGatewayService) bindOpenAICompatAnthropicDigestPromptCacheKey(account *Account, cAPIKeyID int64, digestChain, promptCacheKey, oldDigestChain string) { diff --git a/backend/internal/service/openai_oauth_passthrough_non_stream_test.go b/backend/internal/service/openai_oauth_passthrough_non_stream_test.go new file mode 100644 index 0000000000..25e334abcb --- /dev/null +++ b/backend/internal/service/openai_oauth_passthrough_non_stream_test.go @@ -0,0 +1,162 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Regression tests for #7978: /v1/responses with stream=false must return a +// single JSON Responses object even though the ChatGPT OAuth upstream is +// always called with stream=true and answers with SSE. + +const openAINonStreamRegressionSSE = "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_7978","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.completed\n" + + `data: {"type":"response.completed","response":{"id":"resp_7978","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}` + "\n\n" + +func runOpenAIOAuthNonStreamRegression(t *testing.T, passthrough bool, requestBody string, upstreamSSE ...string) (*httptest.ResponseRecorder, *httpUpstreamRecorder, *OpenAIForwardResult) { + t.Helper() + sseBody := openAINonStreamRegressionSSE + if len(upstreamSSE) > 0 { + sseBody = upstreamSSE[0] + } + header := http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_7978"}} + return runOpenAIOAuthNonStreamRegressionWithHeader(t, passthrough, requestBody, header, sseBody) +} + +func runOpenAIOAuthNonStreamRegressionWithHeader(t *testing.T, passthrough bool, requestBody string, upstreamHeader http.Header, sseBody string) (*httptest.ResponseRecorder, *httpUpstreamRecorder, *OpenAIForwardResult) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("Accept", "application/json") + + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: upstreamHeader, + Body: io.NopCloser(strings.NewReader(sseBody)), + }} + cfg := &config.Config{} + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + account := &Account{ + ID: 7978, + Name: "acc", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + Extra: map[string]any{"openai_passthrough": passthrough}, + Status: StatusActive, + Schedulable: true, + RateMultiplier: f64p(1), + } + + result, err := svc.Forward(context.Background(), c, account, []byte(requestBody)) + require.NoError(t, err) + require.NotNil(t, result) + return rec, upstream, result +} + +func requireSingleJSONResponsesObject(t *testing.T, rec *httptest.ResponseRecorder) { + t.Helper() + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json"), "Content-Type=%q", rec.Header().Get("Content-Type")) + var obj map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &obj), "body=%s", rec.Body.String()) + require.Equal(t, "resp_7978", obj["id"]) + require.Equal(t, "completed", obj["status"]) + require.Equal(t, "OK", gjson.GetBytes(rec.Body.Bytes(), "output.0.content.0.text").String()) +} + +func TestOpenAIGatewayService_OAuthPassthrough_StreamFalseReturnsJSON(t *testing.T) { + rec, upstream, result := runOpenAIOAuthNonStreamRegression(t, true, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":false}`) + + // Upstream still requires stream=true. + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.False(t, result.Stream) + requireSingleJSONResponsesObject(t, rec) +} + +func TestOpenAIGatewayService_OAuthPassthrough_StreamTrueStillStreams(t *testing.T) { + rec, upstream, result := runOpenAIOAuthNonStreamRegression(t, true, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":true}`) + + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.True(t, result.Stream) + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "text/event-stream"), "Content-Type=%q", rec.Header().Get("Content-Type")) + require.Contains(t, rec.Body.String(), "event: response.completed") +} + +func TestOpenAIGatewayService_OAuthLegacy_StreamFalseReturnsJSONContentType(t *testing.T) { + rec, upstream, result := runOpenAIOAuthNonStreamRegression(t, false, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":false}`) + + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.False(t, result.Stream) + requireSingleJSONResponsesObject(t, rec) +} + +const openAINonStreamIncompleteSSE = "event: response.created\n" + + `data: {"type":"response.created","response":{"id":"resp_7978","status":"in_progress","output":[]}}` + "\n\n" + + "event: response.output_text.delta\n" + + `data: {"type":"response.output_text.delta","delta":"Hel"}` + "\n\n" + + "event: response.incomplete\n" + + `data: {"type":"response.incomplete","response":{"id":"resp_7978","object":"response","status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hel"}]}],"usage":{"input_tokens":5,"output_tokens":16,"total_tokens":21}}}` + "\n\n" + +func TestOpenAIGatewayService_OAuthStreamFalseIncompleteReturnsJSON(t *testing.T) { + for _, passthrough := range []bool{true, false} { + rec, _, result := runOpenAIOAuthNonStreamRegression(t, passthrough, + `{"model":"gpt-5.4","instructions":"x","input":"hi","max_output_tokens":16,"stream":false}`, + openAINonStreamIncompleteSSE) + + require.False(t, result.Stream) + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json"), "passthrough=%v Content-Type=%q", passthrough, rec.Header().Get("Content-Type")) + var obj map[string]any + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &obj), "passthrough=%v body=%s", passthrough, rec.Body.String()) + require.Equal(t, "resp_7978", obj["id"]) + require.Equal(t, "incomplete", obj["status"]) + require.Equal(t, "max_output_tokens", gjson.GetBytes(rec.Body.Bytes(), "incomplete_details.reason").String()) + require.Equal(t, "Hel", gjson.GetBytes(rec.Body.Bytes(), "output.0.content.0.text").String()) + require.Equal(t, 5, result.Usage.InputTokens) + require.Equal(t, 16, result.Usage.OutputTokens) + } +} + +func TestOpenAIGatewayService_OAuthStreamFalseCancelledReturnsJSON(t *testing.T) { + cancelledSSE := "event: response.cancelled\n" + + `data: {"type":"response.cancelled","response":{"id":"resp_7978","object":"response","status":"cancelled","output":[],"usage":{"input_tokens":5,"output_tokens":0,"total_tokens":5}}}` + "\n\n" + for _, passthrough := range []bool{true, false} { + rec, _, _ := runOpenAIOAuthNonStreamRegression(t, passthrough, + `{"model":"gpt-5.4","instructions":"x","input":"hi","stream":false}`, cancelledSSE) + + require.True(t, strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json"), "passthrough=%v Content-Type=%q", passthrough, rec.Header().Get("Content-Type")) + require.Equal(t, "cancelled", gjson.GetBytes(rec.Body.Bytes(), "status").String(), "passthrough=%v body=%s", passthrough, rec.Body.String()) + } +} + +// The ChatGPT OAuth upstream can answer with SSE but no Content-Type header; +// the body framing alone must route the response through SSE-to-JSON. +func TestOpenAIGatewayService_OAuthStreamFalseWithoutUpstreamContentTypeReturnsJSON(t *testing.T) { + for _, passthrough := range []bool{true, false} { + header := http.Header{"x-request-id": []string{"rid_7978"}} + rec, upstream, result := runOpenAIOAuthNonStreamRegressionWithHeader(t, passthrough, + `{"model":"gpt-5.4","instructions":"x","input":"Reply with exactly OK.","stream":false}`, + header, openAINonStreamRegressionSSE) + + require.True(t, gjson.GetBytes(upstream.lastBody, "stream").Bool(), "passthrough=%v", passthrough) + require.False(t, result.Stream, "passthrough=%v", passthrough) + requireSingleJSONResponsesObject(t, rec) + } +} diff --git a/backend/internal/service/openai_passthrough_normalization_test.go b/backend/internal/service/openai_passthrough_normalization_test.go index f2071443ad..d419b58a60 100644 --- a/backend/internal/service/openai_passthrough_normalization_test.go +++ b/backend/internal/service/openai_passthrough_normalization_test.go @@ -358,20 +358,3 @@ func TestNormalizeOpenAIPassthroughOAuthBody_ArrayInputUnchanged(t *testing.T) { require.Len(t, input.Array(), 1) require.Equal(t, "message", input.Array()[0].Get("type").String()) } - -func TestDetectOpenAIPassthroughInstructionsRejectReason(t *testing.T) { - for _, tt := range []struct { - name string - body string - want string - }{ - {name: "missing is optional", body: `{"model":"gpt-5.1-codex"}`, want: ""}, - {name: "non string remains rejected", body: `{"instructions":{"text":"invalid"}}`, want: "instructions_not_string"}, - {name: "empty remains rejected", body: `{"instructions":" "}`, want: "instructions_empty"}, - {name: "non empty remains accepted", body: `{"instructions":"client guidance"}`, want: ""}, - } { - t.Run(tt.name, func(t *testing.T) { - require.Equal(t, tt.want, detectOpenAIPassthroughInstructionsRejectReason("gpt-5.1-codex", []byte(tt.body))) - }) - } -} diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 7f24c1d153..5fd986a18c 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -11,6 +11,7 @@ import ( "sync" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" "github.com/imroc/req/v3" ) @@ -252,6 +253,9 @@ func (s *OpenAIQuotaService) CacheResetCreditsSnapshot(ctx context.Context, acco // of reset-credit expiration details. A successful read with absent credits // replaces the previous balance with unknown, never with a fabricated zero. func (s *OpenAIQuotaService) CacheCreditsSnapshot(ctx context.Context, accountID int64, usage *OpenAIQuotaUsage) error { + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, scopedAccountOperation(ctx, "openai.quota.read"), true); err != nil { + return err + } if usage == nil { return infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_EMPTY_USAGE", "openai quota query returned an empty result") } @@ -265,6 +269,9 @@ func (s *OpenAIQuotaService) CacheCreditsSnapshot(ctx context.Context, accountID // CachePostResetSnapshot persists the credits and usage windows observed after a reset. func (s *OpenAIQuotaService) CachePostResetSnapshot(ctx context.Context, accountID int64, usage *OpenAIQuotaUsage) error { + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, scopedAccountOperation(ctx, "openai.quota.reset"), true); err != nil { + return err + } if usage == nil { return s.cacheResetCreditsSnapshot(ctx, accountID, nil, nil) } @@ -282,6 +289,9 @@ func (s *OpenAIQuotaService) CachePostResetSnapshot(ctx context.Context, account } func (s *OpenAIQuotaService) cacheResetCreditsSnapshot(ctx context.Context, accountID int64, credits *OpenAIRateLimitResetCredits, updates map[string]any) error { + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, scopedAccountOperation(ctx, "openai.quota.read"), true); err != nil { + return err + } if credits == nil || (credits.AvailableCount > 0 && len(credits.Credits) == 0) { return infraerrors.New( http.StatusBadGateway, @@ -358,6 +368,10 @@ func (s *OpenAIQuotaService) ResetCreditTargeted(ctx context.Context, accountID } func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, creditID, redeemRequestID string, targeted bool) (*OpenAIQuotaResetResult, error) { + ctx = WithScopedAdminAccountOperation(ctx, "openai.quota.reset") + if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "openai.quota.reset", false); err != nil { + return nil, err + } // Shadow guard: resetting credits via a shadow account would silently // operate on the parent's quota; that is surprising and unwanted. Callers // must reset the parent account directly. @@ -453,6 +467,9 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID if account == nil { return "", "", "", false, infraerrors.New(http.StatusNotFound, "OPENAI_QUOTA_ACCOUNT_NOT_FOUND", "account not found") } + if err := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), true); err != nil { + return "", "", "", false, err + } if account.Platform != PlatformOpenAI { return "", "", "", false, infraerrors.New(http.StatusBadRequest, "OPENAI_QUOTA_INVALID_PLATFORM", "account is not an OpenAI account") } @@ -469,6 +486,9 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return "", "", "", false, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_SHADOW_RESOLVE_FAILED", "failed to resolve shadow account: %v", rerr) } account = resolved + if err := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), false); err != nil { + return "", "", "", false, err + } } chatGPTAccountID = strings.TrimSpace(account.GetCredential("chatgpt_account_id")) @@ -521,12 +541,18 @@ func (s *OpenAIQuotaService) recoverAgentIdentityTask(ctx context.Context, accou if err != nil || account == nil { return fmt.Errorf("account is unavailable") } + if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), true); scopeErr != nil { + return scopeErr + } if account.IsShadow() { account, err = resolveCredentialAccount(ctx, s.accountRepo, account) if err != nil || account == nil { return fmt.Errorf("credential account is unavailable") } } + if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), false); scopeErr != nil { + return scopeErr + } if !account.IsOpenAIAgentIdentity() { return nil } @@ -553,10 +579,19 @@ func (s *OpenAIQuotaService) isAgentIdentityAccount(ctx context.Context, account func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, accountID int64, accessToken, chatGPTAccountID string, fedRAMP bool) (map[string]string, string, error) { headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP) if s == nil || s.accountRepo == nil { + if adminaccess.RestrictedFromContext(ctx) != nil { + return nil, "", infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } return headers, "", nil } account, err := s.accountRepo.GetByID(ctx, accountID) + if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), true); scopeErr != nil { + return nil, "", scopeErr + } if err != nil || account == nil { + if adminaccess.RestrictedFromContext(ctx) != nil { + return nil, "", infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") + } if strings.TrimSpace(accessToken) == "" { return nil, "", fmt.Errorf("agent identity account credentials are unavailable") } @@ -565,6 +600,11 @@ func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, account if account.IsShadow() { if resolved, resolveErr := resolveCredentialAccount(ctx, s.accountRepo, account); resolveErr == nil && resolved != nil { account = resolved + if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), false); scopeErr != nil { + return nil, "", scopeErr + } + } else if adminaccess.RestrictedFromContext(ctx) != nil { + return nil, "", infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") } else if strings.TrimSpace(accessToken) == "" { return nil, "", fmt.Errorf("agent identity shadow credentials are unavailable") } diff --git a/backend/internal/service/openai_referral_service.go b/backend/internal/service/openai_referral_service.go index 37cc843687..3eacc7b8b3 100644 --- a/backend/internal/service/openai_referral_service.go +++ b/backend/internal/service/openai_referral_service.go @@ -68,6 +68,13 @@ func (s *OpenAIQuotaService) referralAccount(ctx context.Context, id int64, send if a == nil { return nil, ErrAccountNotFound } + action := scopedAccountOperation(ctx, "openai.referrals.read") + if sending { + action = "openai.referrals.invite" + } + if err := scopedAccountAccess(ctx, s.accountRepo, a, action, !sending); err != nil { + return nil, err + } if a.Platform != PlatformOpenAI || a.Type != AccountTypeOAuth { return nil, infraerrors.New(http.StatusBadRequest, "OPENAI_REFERRAL_INVALID_ACCOUNT", "referrals require an OpenAI OAuth account") } @@ -75,7 +82,14 @@ func (s *OpenAIQuotaService) referralAccount(ctx context.Context, id int64, send if sending { return nil, infraerrors.New(http.StatusConflict, "OPENAI_REFERRAL_SHADOW_ACCOUNT", "send invitations from the parent account") } - return resolveCredentialAccount(ctx, s.accountRepo, a) + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, a) + if err != nil { + return nil, err + } + if err := scopedAccountAccess(ctx, s.accountRepo, resolved, action, false); err != nil { + return nil, err + } + return resolved, nil } return a, nil } @@ -108,6 +122,7 @@ func (s *OpenAIQuotaService) referralCall(ctx context.Context, id int64, program } func (s *OpenAIQuotaService) QueryReferralEligibility(ctx context.Context, id int64) (*OpenAIReferralEligibility, error) { + ctx = WithScopedAdminAccountOperation(ctx, scopedAccountOperation(ctx, "openai.referrals.read")) account, err := s.referralAccount(ctx, id, false) if err != nil { return nil, err @@ -130,6 +145,9 @@ func (s *OpenAIQuotaService) QueryReferralEligibility(ctx context.Context, id in } func (s *OpenAIQuotaService) CacheReferralSnapshot(ctx context.Context, id int64, eligibility *OpenAIReferralEligibility) error { + if err := scopedAccountIDAccess(ctx, s.accountRepo, id, scopedAccountOperation(ctx, "openai.referrals.read"), true); err != nil { + return err + } return s.accountRepo.UpdateExtra(ctx, id, map[string]any{openAIReferralSnapshotKey: eligibility}) } @@ -145,6 +163,7 @@ type OpenAIReferralSendResult struct { } func (s *OpenAIQuotaService) SendReferralInvite(ctx context.Context, id int64, input OpenAIReferralSendRequest) (*OpenAIReferralSendResult, error) { + ctx = WithScopedAdminAccountOperation(ctx, "openai.referrals.invite") email := strings.TrimSpace(input.Email) address, err := mail.ParseAddress(email) if err != nil || address.Address != email || len(email) > 254 || strings.ContainsAny(email, "\r\n") { diff --git a/backend/internal/service/openai_responses_instructions_echo.go b/backend/internal/service/openai_responses_instructions_echo.go new file mode 100644 index 0000000000..72e45397b1 --- /dev/null +++ b/backend/internal/service/openai_responses_instructions_echo.go @@ -0,0 +1,161 @@ +package service + +import ( + "bytes" + "encoding/json" + "strings" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Responses 的 response 对象回显上游实际收到的 instructions。网关补写、追加或 +// 搬运 instructions 后,回显按客户端请求里的原始取值还原;客户端未传时还原为 null。 + +const ( + openAIResponsesClientInstructionsKey = "openai_responses_client_instructions" + openAIResponsesInstructionsEchoRestoreKey = "openai_responses_instructions_echo_restore" +) + +var openAIResponsesInstructionsFieldMarker = []byte(`"instructions"`) + +type openAIResponsesClientInstructions struct { + // raw 是客户端 instructions 压缩成单行后的 JSON;未传时为空串。 + // 单行保证还原值写回 SSE data 行时不会拆帧。 + raw string +} + +// rememberOpenAIResponsesClientInstructions 记录本次转发尝试的客户端原始 +// instructions,并清空还原值,使未登记上游请求体的转发分支不做还原。 +func rememberOpenAIResponsesClientInstructions(c *gin.Context, body []byte) { + if c == nil { + return + } + raw := "" + if value := gjson.GetBytes(body, "instructions"); value.Exists() { + raw = compactOpenAIResponsesInstructionsRaw(value.Raw) + } + c.Set(openAIResponsesClientInstructionsKey, openAIResponsesClientInstructions{raw: raw}) + c.Set(openAIResponsesInstructionsEchoRestoreKey, "") +} + +// syncOpenAIResponsesInstructionsEcho 比较即将发往上游的 instructions 与客户端 +// 原始取值,不一致时登记回显还原值。 +func syncOpenAIResponsesInstructionsEcho(c *gin.Context, upstreamBody []byte) { + if c == nil { + return + } + stored, ok := c.Get(openAIResponsesClientInstructionsKey) + if !ok { + return + } + client, ok := stored.(openAIResponsesClientInstructions) + if !ok { + return + } + upstreamRaw := "" + if value := gjson.GetBytes(upstreamBody, "instructions"); value.Exists() { + upstreamRaw = value.Raw + } + restore := "" + if !openAIResponsesInstructionsRawEqual(client.raw, upstreamRaw) { + restore = client.raw + if restore == "" { + restore = "null" + } + } + c.Set(openAIResponsesInstructionsEchoRestoreKey, restore) +} + +// compactOpenAIResponsesInstructionsRaw 去掉 JSON 值里的格式空白;无法解析时 +// 返回 null。 +func compactOpenAIResponsesInstructionsRaw(raw string) string { + var buf bytes.Buffer + if err := json.Compact(&buf, []byte(raw)); err != nil { + return "null" + } + return buf.String() +} + +func openAIResponsesInstructionsRawEqual(left, right string) bool { + if left == right { + return true + } + if left == "" || right == "" { + return false + } + l := gjson.Parse(left) + r := gjson.Parse(right) + if l.Type != r.Type { + return false + } + if l.Type == gjson.String { + return l.Str == r.Str + } + return compactOpenAIResponsesInstructionsRaw(l.Raw) == compactOpenAIResponsesInstructionsRaw(r.Raw) +} + +func openAIResponsesInstructionsEchoRestoreValue(c *gin.Context) string { + if c == nil { + return "" + } + stored, ok := c.Get(openAIResponsesInstructionsEchoRestoreKey) + if !ok { + return "" + } + restore, _ := stored.(string) + return restore +} + +func restoreOpenAIResponsesInstructionsAtPath(data []byte, path, restore string) []byte { + if restore == "" || !bytes.Contains(data, openAIResponsesInstructionsFieldMarker) { + return data + } + if !gjson.GetBytes(data, path).Exists() { + return data + } + restored, err := sjson.SetRawBytes(data, path, []byte(restore)) + if err != nil { + return data + } + return restored +} + +// restoreOpenAIResponsesInstructionsEchoInEvent 还原单个 SSE 事件里 +// response.instructions 的回显。 +func restoreOpenAIResponsesInstructionsEchoInEvent(c *gin.Context, data []byte) []byte { + return restoreOpenAIResponsesInstructionsAtPath(data, "response.instructions", openAIResponsesInstructionsEchoRestoreValue(c)) +} + +// restoreOpenAIResponsesInstructionsEchoInResponse 还原非流式 response 对象里 +// instructions 的回显。 +func restoreOpenAIResponsesInstructionsEchoInResponse(c *gin.Context, body []byte) []byte { + return restoreOpenAIResponsesInstructionsAtPath(body, "instructions", openAIResponsesInstructionsEchoRestoreValue(c)) +} + +// restoreOpenAIResponsesInstructionsEchoInSSEBody 逐个 data 行还原整段 SSE 文本里的回显。 +func restoreOpenAIResponsesInstructionsEchoInSSEBody(c *gin.Context, body string) string { + restore := openAIResponsesInstructionsEchoRestoreValue(c) + if restore == "" || !strings.Contains(body, `"instructions"`) { + return body + } + lines := strings.Split(body, "\n") + changed := false + for i, line := range lines { + data, ok := extractOpenAISSEDataLine(line) + if !ok { + continue + } + restored := restoreOpenAIResponsesInstructionsAtPath([]byte(data), "response.instructions", restore) + if string(restored) == data { + continue + } + lines[i] = "data: " + string(restored) + changed = true + } + if !changed { + return body + } + return strings.Join(lines, "\n") +} diff --git a/backend/internal/service/openai_responses_instructions_echo_test.go b/backend/internal/service/openai_responses_instructions_echo_test.go new file mode 100644 index 0000000000..9f3300aece --- /dev/null +++ b/backend/internal/service/openai_responses_instructions_echo_test.go @@ -0,0 +1,227 @@ +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const instructionsEchoMarker = "UPSTREAM-ECHOED-INSTRUCTIONS" + +func instructionsEchoUpstreamSSE(echo string) string { + return strings.Join([]string{ + `data: {"type":"response.created","response":{"id":"resp_echo","status":"in_progress","instructions":` + echo + `}}`, + "", + `data: {"type":"response.output_text.delta","delta":"OK"}`, + "", + `data: {"type":"response.completed","response":{"id":"resp_echo","status":"completed","instructions":` + echo + `,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":11,"output_tokens":5,"total_tokens":16}}}`, + "", + "data: [DONE]", + "", + }, "\n") +} + +func instructionsEchoUpstream(echo string) *httpUpstreamRecorder { + return &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}, "x-request-id": []string{"rid_echo"}}, + Body: io.NopCloser(strings.NewReader(instructionsEchoUpstreamSSE(echo))), + }} +} + +func instructionsEchoOAuthAccount(passthrough bool) *Account { + account := &Account{ + ID: 501, Name: "oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + Status: StatusActive, Schedulable: true, RateMultiplier: f64p(1), + } + if passthrough { + account.Extra = map[string]any{"openai_passthrough": true} + } + return account +} + +func instructionsEchoForward(t *testing.T, account *Account, upstream *httpUpstreamRecorder, body string) (*OpenAIForwardResult, *httptest.ResponseRecorder, error) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil)) + c.Request.Header.Set("User-Agent", "OpenAI/Python 2.8.0") + SetOpenAIClientTransport(c, OpenAIClientTransportHTTP) + svc := &OpenAIGatewayService{cfg: &config.Config{}, httpUpstream: upstream} + result, err := svc.Forward(context.Background(), c, account, []byte(body)) + return result, rec, err +} + +func sseResponseInstructions(t *testing.T, body, eventType string) gjson.Result { + t.Helper() + for _, line := range strings.Split(body, "\n") { + data, ok := extractOpenAISSEDataLine(line) + if !ok || gjson.Get(data, "type").String() != eventType { + continue + } + return gjson.Get(data, "response.instructions") + } + t.Fatalf("event %s not found in body: %s", eventType, body) + return gjson.Result{} +} + +func TestOpenAIResponsesInstructionsEchoRestoreHelpers(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tt := range []struct { + name string + clientBody string + upstream string + wantRestore string + }{ + {name: "missing then injected restores null", clientBody: `{"model":"m"}`, upstream: `{"instructions":"injected"}`, wantRestore: "null"}, + {name: "blank then injected restores blank", clientBody: `{"instructions":" "}`, upstream: `{"instructions":"injected"}`, wantRestore: `" "`}, + {name: "client text appended restores client text", clientBody: `{"instructions":"mine"}`, upstream: `{"instructions":"mine\n\nbridge"}`, wantRestore: `"mine"`}, + {name: "unchanged text keeps upstream echo", clientBody: `{"instructions":"mine"}`, upstream: `{"instructions":"mine"}`, wantRestore: ""}, + {name: "escaped spelling of same text keeps upstream echo", clientBody: `{"instructions":"a\/b"}`, upstream: `{"instructions":"a/b"}`, wantRestore: ""}, + {name: "reformatted object keeps upstream echo", clientBody: "{\"instructions\": {\n \"k\": [1, 2]\n}}", upstream: `{"instructions":{"k":[1,2]}}`, wantRestore: ""}, + {name: "multi-line object then injected restores single line", clientBody: "{\"instructions\": [\n {\"role\": \"developer\", \"content\": \"x\"}\n]}", upstream: `{"instructions":"injected"}`, wantRestore: `[{"role":"developer","content":"x"}]`}, + {name: "missing on both sides keeps upstream echo", clientBody: `{"model":"m"}`, upstream: `{"model":"m"}`, wantRestore: ""}, + } { + t.Run(tt.name, func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + rememberOpenAIResponsesClientInstructions(c, []byte(tt.clientBody)) + syncOpenAIResponsesInstructionsEcho(c, []byte(tt.upstream)) + require.Equal(t, tt.wantRestore, openAIResponsesInstructionsEchoRestoreValue(c)) + }) + } + + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + event := []byte(`{"type":"response.created","response":{"id":"r","instructions":"injected"}}`) + delta := []byte(`{"type":"response.output_text.delta","delta":"the word \"instructions\" in text"}`) + require.Equal(t, event, restoreOpenAIResponsesInstructionsEchoInEvent(c, event), "unregistered context must not rewrite") + + rememberOpenAIResponsesClientInstructions(c, []byte(`{"model":"m"}`)) + syncOpenAIResponsesInstructionsEcho(c, []byte(`{"instructions":"injected"}`)) + require.JSONEq(t, `{"type":"response.created","response":{"id":"r","instructions":null}}`, string(restoreOpenAIResponsesInstructionsEchoInEvent(c, event))) + require.Equal(t, delta, restoreOpenAIResponsesInstructionsEchoInEvent(c, delta)) + require.JSONEq(t, `{"id":"r","instructions":null}`, string(restoreOpenAIResponsesInstructionsEchoInResponse(c, []byte(`{"id":"r","instructions":"injected"}`)))) + sseBody := "event: response.created\ndata: " + string(event) + "\n\ndata: " + string(delta) + "\n" + restoredSSE := restoreOpenAIResponsesInstructionsEchoInSSEBody(c, sseBody) + require.NotContains(t, restoredSSE, `"instructions":"injected"`) + require.Contains(t, restoredSSE, `"instructions":null`) + require.Contains(t, restoredSSE, string(delta)) + + rememberOpenAIResponsesClientInstructions(c, []byte(`{"model":"m"}`)) + require.Equal(t, event, restoreOpenAIResponsesInstructionsEchoInEvent(c, event), "a new attempt clears the previous restore value") +} + +func TestOpenAIGatewayService_OAuthPassthrough_CodexBlankInstructionsForwardedAsIs(t *testing.T) { + for _, raw := range []string{`""`, `" "`, `{"text":"x"}`} { + t.Run(raw, func(t *testing.T) { + upstream := instructionsEchoUpstream(raw) + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(true), upstream, + `{"model":"gpt-5.3-codex","stream":true,"instructions":`+raw+`,"input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, http.StatusOK, rec.Code) + require.JSONEq(t, raw, gjson.GetBytes(upstream.lastBody, "instructions").Raw) + require.JSONEq(t, raw, sseResponseInstructions(t, rec.Body.String(), "response.completed").Raw) + }) + } +} + +func TestOpenAIGatewayService_OAuthPassthrough_MissingInstructionsForwardedWithoutField(t *testing.T) { + upstream := instructionsEchoUpstream("null") + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(true), upstream, + `{"model":"gpt-6.1-sol","stream":true,"input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.False(t, gjson.GetBytes(upstream.lastBody, "instructions").Exists()) + require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.created").Type) + require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.completed").Type) +} + +func TestOpenAIGatewayService_OAuthPassthrough_InjectedCodexInstructionsEchoRestored(t *testing.T) { + upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`) + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(true), upstream, + `{"model":"gpt-5.3-codex","stream":true,"input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "instructions").String()) + require.NotContains(t, rec.Body.String(), instructionsEchoMarker) + require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.created").Type) + require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.completed").Type) + + nonStreamUpstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`) + result, rec, err = instructionsEchoForward(t, instructionsEchoOAuthAccount(true), nonStreamUpstream, + `{"model":"gpt-5.3-codex","stream":false,"input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.NotContains(t, rec.Body.String(), instructionsEchoMarker) + instructions := gjson.Get(rec.Body.String(), "instructions") + require.True(t, instructions.Exists()) + require.Equal(t, gjson.Null, instructions.Type) +} + +func TestOpenAIGatewayService_OAuthResponses_MultiLineInstructionsEchoKeepsSSEFraming(t *testing.T) { + upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`) + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream, + "{\"model\":\"gpt-6.1-sol\",\"stream\":true,\"instructions\": [\n {\"role\": \"developer\", \"content\": \"x\"}\n],\"input\":[{\"type\":\"message\",\"role\":\"user\",\"content\":\"Hi\"}]}") + require.NoError(t, err) + require.NotNil(t, result) + require.NotContains(t, rec.Body.String(), instructionsEchoMarker) + for _, line := range strings.Split(rec.Body.String(), "\n") { + if strings.TrimSpace(line) == "" || strings.HasPrefix(line, "event:") || strings.HasPrefix(line, ":") { + continue + } + data, ok := extractOpenAISSEDataLine(line) + require.True(t, ok, "unexpected non-data line %q", line) + if data == "[DONE]" { + continue + } + require.True(t, gjson.Valid(data), "data line must stay a complete JSON document: %q", data) + } + require.JSONEq(t, `[{"role":"developer","content":"x"}]`, sseResponseInstructions(t, rec.Body.String(), "response.completed").Raw) +} + +func TestOpenAIGatewayService_OAuthResponses_InjectedInstructionsEchoRestored(t *testing.T) { + t.Run("stream", func(t *testing.T) { + upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`) + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream, + `{"model":"gpt-6.1-sol","stream":true,"input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "instructions").String()) + require.NotContains(t, rec.Body.String(), instructionsEchoMarker) + require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.created").Type) + require.Equal(t, gjson.Null, sseResponseInstructions(t, rec.Body.String(), "response.completed").Type) + }) + + t.Run("non-stream", func(t *testing.T) { + upstream := instructionsEchoUpstream(`"` + instructionsEchoMarker + `"`) + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream, + `{"model":"gpt-6.1-sol","stream":false,"input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.NotContains(t, rec.Body.String(), instructionsEchoMarker) + instructions := gjson.Get(rec.Body.String(), "instructions") + require.True(t, instructions.Exists()) + require.Equal(t, gjson.Null, instructions.Type) + }) + + t.Run("client instructions kept", func(t *testing.T) { + upstream := instructionsEchoUpstream(`"client rule"`) + result, rec, err := instructionsEchoForward(t, instructionsEchoOAuthAccount(false), upstream, + `{"model":"gpt-6.1-sol","stream":true,"instructions":"client rule","input":[{"type":"message","role":"user","content":"Hi"}]}`) + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, "client rule", gjson.GetBytes(upstream.lastBody, "instructions").String()) + require.Equal(t, "client rule", sseResponseInstructions(t, rec.Body.String(), "response.completed").String()) + }) +} diff --git a/backend/internal/service/openai_sse_data.go b/backend/internal/service/openai_sse_data.go index 3fdb70f8f4..7b14ece1ac 100644 --- a/backend/internal/service/openai_sse_data.go +++ b/backend/internal/service/openai_sse_data.go @@ -29,6 +29,7 @@ func (a *openAISSEDataAccumulator) Flush(fn func([]byte)) { return } emitOpenAISSEDataPayloads(a.lines, fn) + clear(a.lines) a.lines = a.lines[:0] } diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 066c769c20..fa7c62e04a 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -704,11 +704,12 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( maxLineSize = s.cfg.Gateway.MaxLineSize } if hasResponsesClientToolMapping(clientToolMapping) { - resp.Body = newResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize) + resp.Body = newResponsesClientToolStreamBody(resp.Body, clientToolMapping, maxLineSize, s.cfg) } scanner := bufio.NewScanner(resp.Body) scanBuf := getSSEScannerBuf64K() scanner.Buffer(scanBuf[:0], maxLineSize) + scanner.Split(newBoundedSSESplit(s.cfg, maxLineSize, nil)) defer putSSEScannerBuf64K(scanBuf) pendingSSEEventType := "" diff --git a/backend/internal/service/ratelimit_cn_concurrency_403_test.go b/backend/internal/service/ratelimit_cn_concurrency_403_test.go new file mode 100644 index 0000000000..8edb2e5970 --- /dev/null +++ b/backend/internal/service/ratelimit_cn_concurrency_403_test.go @@ -0,0 +1,167 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type kimiConcurrencyRateLimitFailureRepo struct { + rateLimitAccountRepoStub +} + +func (repo *kimiConcurrencyRateLimitFailureRepo) SetRateLimited(ctx context.Context, accountID int64, resetAt time.Time) error { + _ = repo.rateLimitAccountRepoStub.SetRateLimited(ctx, accountID, resetAt) + return errors.New("repository unavailable") +} + +func TestHandleUpstreamError_KimiConcurrency403CooldownSettings(t *testing.T) { + for _, testCase := range []struct { + name string + settings *RateLimit429CooldownSettings + seconds int + }{ + {name: "no setting service", seconds: 5}, + {name: "default settings", settings: &RateLimit429CooldownSettings{}, seconds: 5}, + {name: "custom seconds", settings: &RateLimit429CooldownSettings{Enabled: true, CooldownSeconds: 17}, seconds: 17}, + {name: "disabled", settings: &RateLimit429CooldownSettings{Enabled: false, CooldownSeconds: 17}}, + } { + t.Run(testCase.name, func(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + counter := &openAI403CounterCacheStub{counts: []int64{openAI403DisableThreshold}} + blocker := &runtimeBlockRecorder{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + service.SetOpenAI403CounterCache(counter) + service.SetAccountRuntimeBlocker(blocker) + if testCase.settings != nil { + settingRepo := newMockSettingRepo() + if testCase.settings.CooldownSeconds > 0 { + data, err := json.Marshal(testCase.settings) + require.NoError(t, err) + settingRepo.data[SettingKeyRateLimit429CooldownSettings] = string(data) + } + service.SetSettingService(NewSettingService(settingRepo, &config.Config{})) + } + account := newCNQuotaExhaustedTestAccount(2 * time.Hour) + for attempt := 0; attempt < 5; attempt++ { + before := time.Now() + require.True(t, runKimi403(service, account, `{"error":{"message":"`+kimiConcurrentRequestLimitMessage+`"}}`), "must switch accounts even with cooldown disabled") + after := time.Now() + if testCase.seconds > 0 { + cooldown := time.Duration(testCase.seconds) * time.Second + require.Equal(t, attempt+1, repo.rateLimitedCalls) + require.Equal(t, account.ID, repo.lastRateLimitedID) + require.False(t, repo.lastRateLimitedAt.Before(before.Add(cooldown))) + require.False(t, repo.lastRateLimitedAt.After(after.Add(cooldown))) + require.Len(t, blocker.accounts, attempt+1) + require.Same(t, account, blocker.accounts[attempt]) + require.Equal(t, repo.lastRateLimitedAt, blocker.until[attempt]) + require.Equal(t, "429_fallback", blocker.reasons[attempt]) + } else { + require.Zero(t, repo.rateLimitedCalls) + require.Empty(t, blocker.accounts) + } + require.Zero(t, repo.tempCalls) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, []int64{openAI403DisableThreshold}, counter.counts) + } + }) + } +} + +func TestHandleUpstreamError_KimiQuota403IgnoresDisabledConcurrencyCooldown(t *testing.T) { + for _, resetIn := range []time.Duration{0, 2 * time.Hour} { + t.Run(resetIn.String(), func(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + blocker := &runtimeBlockRecorder{} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + service.SetAccountRuntimeBlocker(blocker) + settingRepo := newMockSettingRepo() + settingRepo.data[SettingKeyRateLimit429CooldownSettings] = `{"enabled":false,"cooldown_seconds":17}` + service.SetSettingService(NewSettingService(settingRepo, &config.Config{})) + account := newCNQuotaExhaustedTestAccount(resetIn) + require.True(t, runKimi403(service, account, kimiWeeklyQuotaExhaustedBody)) + require.Zero(t, repo.setErrorCalls) + require.Len(t, blocker.accounts, 1) + require.Equal(t, cnQuotaExhaustedReasonPrefix, blocker.reasons[0]) + if resetIn > 0 { + require.Equal(t, 1, repo.rateLimitedCalls) + require.Zero(t, repo.tempCalls) + require.WithinDuration(t, time.Now().Add(resetIn), repo.lastRateLimitedAt, time.Second) + } else { + require.Zero(t, repo.rateLimitedCalls) + require.Equal(t, 1, repo.tempCalls) + require.WithinDuration(t, time.Now().Add(10*time.Minute), blocker.until[0], time.Second) + } + }) + } +} + +func TestHandleUpstreamError_KimiConcurrency403ExplicitRulesTakePriority(t *testing.T) { + for _, testCase := range []struct { + name string + credentials map[string]any + wantSwitch bool + wantTemp int + wantLimited int + }{ + { + name: "custom error codes exclude 403", + credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(429)}, + }, + }, + { + name: "custom error codes include 403", + credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(403)}, + }, + wantSwitch: true, wantLimited: 1, + }, + { + name: "explicit temporary unschedulable rule", + credentials: map[string]any{ + "temp_unschedulable_enabled": true, + "temp_unschedulable_rules": []any{map[string]any{ + "error_code": float64(403), "keywords": []any{"concurrent request limit"}, + "duration_minutes": float64(23), + }}, + }, + wantSwitch: true, wantTemp: 1, + }, + } { + t.Run(testCase.name, func(t *testing.T) { + repo := &rateLimitAccountRepoStub{} + blocker := &runtimeBlockRecorder{} + counter := &openAI403CounterCacheStub{counts: []int64{openAI403DisableThreshold}} + service := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + service.SetAccountRuntimeBlocker(blocker) + service.SetOpenAI403CounterCache(counter) + account := newCNQuotaExhaustedTestAccount(0) + account.Credentials = testCase.credentials + before := time.Now() + require.Equal(t, testCase.wantSwitch, runKimi403(service, account, + `{"error":{"message":"`+kimiConcurrentRequestLimitMessage+`"}}`)) + require.Equal(t, testCase.wantTemp, repo.tempCalls) + require.Equal(t, testCase.wantLimited, repo.rateLimitedCalls) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, []int64{openAI403DisableThreshold}, counter.counts) + if testCase.wantTemp > 0 { + require.Len(t, blocker.accounts, 1) + require.NotEqual(t, "429_fallback", blocker.reasons[0]) + require.WithinDuration(t, before.Add(23*time.Minute), blocker.until[0], time.Second) + } else if !testCase.wantSwitch { + require.Empty(t, blocker.accounts) + } + }) + } +} diff --git a/backend/internal/service/ratelimit_cn_providers.go b/backend/internal/service/ratelimit_cn_providers.go index 8ffa3e774d..9fa194de69 100644 --- a/backend/internal/service/ratelimit_cn_providers.go +++ b/backend/internal/service/ratelimit_cn_providers.go @@ -93,10 +93,7 @@ func (s *RateLimitService) handleCNProviderConcurrencyLimit403( ctx context.Context, account *Account, ) { - until := time.Now().Add(time.Duration(openAI403CooldownMinutesDefault) * time.Minute) - s.setCNProviderTempUnschedulable(ctx, account, until, - cnConcurrencyLimitReasonPrefix, cnConcurrencyLimitReasonPrefix+": "+kimiConcurrentRequestLimitMessage, - "cn_provider_concurrency_limited") + s.apply429FallbackRateLimit(ctx, account, cnConcurrencyLimitReasonPrefix) } // cnBalanceLowReason 构造余额不足临时停调的 reason(带稳定前缀)。 diff --git a/backend/internal/service/ratelimit_service_cn_quota_403_test.go b/backend/internal/service/ratelimit_service_cn_quota_403_test.go index 44062eb8a2..f353def530 100644 --- a/backend/internal/service/ratelimit_service_cn_quota_403_test.go +++ b/backend/internal/service/ratelimit_service_cn_quota_403_test.go @@ -103,9 +103,9 @@ func TestHandleUpstreamError_KimiConcurrencyLimit403StillUsesConcurrencyPath(t * require.True(t, shouldDisable) require.Equal(t, 0, repo.setErrorCalls) - require.Equal(t, 0, repo.rateLimitedCalls, "concurrency-limit message must keep its dedicated path") - require.Equal(t, 1, repo.tempCalls) - require.Contains(t, repo.lastTempReason, cnConcurrencyLimitReasonPrefix) + require.Equal(t, 1, repo.rateLimitedCalls, "concurrency-limit message must keep its dedicated path") + require.Equal(t, 0, repo.tempCalls) + require.WithinDuration(t, time.Now().Add(5*time.Second), repo.lastRateLimitedAt, time.Second) } func TestHandleUpstreamError_KimiGeneric403StillEscalates(t *testing.T) { diff --git a/backend/internal/service/registration_email_blacklist.go b/backend/internal/service/registration_email_blacklist.go new file mode 100644 index 0000000000..e96f7e9d92 --- /dev/null +++ b/backend/internal/service/registration_email_blacklist.go @@ -0,0 +1,268 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strconv" + "strings" + "time" + "unicode" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" +) + +// 注册邮箱精确黑名单。 +// +// 名单项是完整邮箱地址,匹配按收件箱身份(NormalizeEmailForAliasDedup)进行: +// 拉黑 a.b@gmail.com 同时拦截 ab@googlemail.com、a.b+x@gmail.com 等投递到同一收件箱的 +// 变体;Gmail 系之外点号仍有意义,只折叠 "+后缀"。名单原样保存管理员录入的地址, +// 身份归一只发生在匹配时。 + +// MaxRegistrationEmailBlacklistSize 是精确黑名单的条数上限。 +const MaxRegistrationEmailBlacklistSize = 20000 + +const ( + registrationEmailBlacklistLocalMaxLen = 64 + registrationEmailBlacklistMaxLen = 254 + registrationEmailBlacklistErrorSample = 10 +) + +var ErrEmailBlocked = infraerrors.BadRequest("EMAIL_BLOCKED", "this email address is not allowed") + +// NormalizeRegistrationEmailBlacklistEntry 把一条录入归一为小写、去首尾空白、去域名根点的 +// 邮箱地址;格式不合法时返回 false。 +func NormalizeRegistrationEmailBlacklistEntry(raw string) (string, bool) { + local, domain, ok := splitEmailForPolicy(raw) + if !ok { + return "", false + } + if len(local) > registrationEmailBlacklistLocalMaxLen || !isValidRegistrationEmailDomain(domain) { + return "", false + } + for _, r := range local { + if unicode.IsSpace(r) || unicode.IsControl(r) { + return "", false + } + } + email := local + "@" + domain + if len(email) > registrationEmailBlacklistMaxLen { + return "", false + } + return email, true +} + +// NormalizeRegistrationEmailBlacklist 校验并归一管理员提交的名单:按归一后的地址去重并保持 +// 原有顺序;任一项格式不合法或超过条数上限都整体拒绝。 +func NormalizeRegistrationEmailBlacklist(raw []string) ([]string, error) { + out := make([]string, 0, len(raw)) + seen := make(map[string]struct{}, len(raw)) + var invalid []string + for _, item := range raw { + if strings.TrimSpace(item) == "" { + continue + } + email, ok := NormalizeRegistrationEmailBlacklistEntry(item) + if !ok { + invalid = append(invalid, strings.TrimSpace(item)) + continue + } + if _, dup := seen[email]; dup { + continue + } + seen[email] = struct{}{} + out = append(out, email) + } + if len(invalid) > 0 { + sample := invalid + if len(sample) > registrationEmailBlacklistErrorSample { + sample = sample[:registrationEmailBlacklistErrorSample] + } + return nil, infraerrors.BadRequest( + "EMAIL_BLACKLIST_INVALID_ENTRY", + fmt.Sprintf("invalid email address (%d): %s", len(invalid), strings.Join(sample, ", ")), + ).WithMetadata(map[string]string{ + "invalid_count": strconv.Itoa(len(invalid)), + "invalid_entries": strings.Join(sample, ","), + }) + } + if len(out) > MaxRegistrationEmailBlacklistSize { + return nil, infraerrors.BadRequest( + "EMAIL_BLACKLIST_TOO_LARGE", + fmt.Sprintf("email blacklist cannot exceed %d entries", MaxRegistrationEmailBlacklistSize), + ).WithMetadata(map[string]string{ + "max": strconv.Itoa(MaxRegistrationEmailBlacklistSize), + }) + } + return out, nil +} + +// ParseRegistrationEmailBlacklist 解析已持久化的 JSON 名单;非法项被跳过,不影响其余项生效。 +func ParseRegistrationEmailBlacklist(raw string) []string { + raw = strings.TrimSpace(raw) + if raw == "" { + return []string{} + } + var items []string + if err := json.Unmarshal([]byte(raw), &items); err != nil { + return []string{} + } + out := make([]string, 0, len(items)) + seen := make(map[string]struct{}, len(items)) + for _, item := range items { + email, ok := NormalizeRegistrationEmailBlacklistEntry(item) + if !ok { + continue + } + if _, dup := seen[email]; dup { + continue + } + seen[email] = struct{}{} + out = append(out, email) + } + return out +} + +// RegistrationEmailBlacklistIdentities 返回名单项对应的收件箱身份集合。 +func RegistrationEmailBlacklistIdentities(emails []string) map[string]struct{} { + identities := make(map[string]struct{}, len(emails)) + for _, email := range emails { + if identity := NormalizeEmailForAliasDedup(email); identity != "" { + identities[identity] = struct{}{} + } + } + return identities +} + +const ( + registrationEmailBlacklistCacheTTL = 60 * time.Second + registrationEmailBlacklistErrorTTL = 5 * time.Second + registrationEmailBlacklistDBTimeout = 5 * time.Second +) + +// registrationEmailBlacklistIndex 是精确黑名单的进程内缓存条目:只保留收件箱身份集合, +// 不保留原始 JSON。 +type registrationEmailBlacklistIndex struct { + identities map[string]struct{} + expiresAt int64 // unix nano +} + +func (idx *registrationEmailBlacklistIndex) contains(email string) bool { + if idx == nil || len(idx.identities) == 0 { + return false + } + if _, _, ok := splitEmailForPolicy(email); !ok { + return false + } + _, hit := idx.identities[NormalizeEmailForAliasDedup(email)] + return hit +} + +func (s *SettingService) storeRegistrationEmailBlacklistIndex(identities map[string]struct{}, ttl time.Duration) *registrationEmailBlacklistIndex { + idx := ®istrationEmailBlacklistIndex{ + identities: identities, + expiresAt: time.Now().Add(ttl).UnixNano(), + } + s.registrationEmailBlacklistCache.Store(idx) + return idx +} + +// registrationEmailBlacklistIndexCached 返回精确黑名单索引(进程内缓存,60s TTL)。 +// 公开的注册与发码接口每次请求都会调用,名单最多两万项,不能每次都从 DB 读出整份 JSON。 +// DB 读取失败时沿用最近一次已知名单(没有则视为空名单),并以短 TTL 快速重试。 +func (s *SettingService) registrationEmailBlacklistIndexCached(ctx context.Context) *registrationEmailBlacklistIndex { + if cached, ok := s.registrationEmailBlacklistCache.Load().(*registrationEmailBlacklistIndex); ok && cached != nil { + if time.Now().UnixNano() < cached.expiresAt { + return cached + } + } + result, _, _ := s.registrationEmailBlacklistSF.Do("registration_email_blacklist", func() (any, error) { + s.registrationEmailBlacklistMu.Lock() + defer s.registrationEmailBlacklistMu.Unlock() + prior, _ := s.registrationEmailBlacklistCache.Load().(*registrationEmailBlacklistIndex) + if prior != nil && time.Now().UnixNano() < prior.expiresAt { + return prior, nil + } + // 独立 context:断开请求取消链,避免客户端断连污染缓存 + dbCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), registrationEmailBlacklistDBTimeout) + defer cancel() + + raw, err := s.settingRepo.GetValue(dbCtx, SettingKeyRegistrationEmailBlacklist) + switch { + case err == nil: + return s.storeRegistrationEmailBlacklistIndex( + RegistrationEmailBlacklistIdentities(ParseRegistrationEmailBlacklist(raw)), + registrationEmailBlacklistCacheTTL, + ), nil + case errors.Is(err, ErrSettingNotFound): + return s.storeRegistrationEmailBlacklistIndex(map[string]struct{}{}, registrationEmailBlacklistCacheTTL), nil + default: + slog.Warn("failed to get registration email blacklist", "error", err) + fallback := map[string]struct{}{} + if prior != nil { + fallback = prior.identities + } + return s.storeRegistrationEmailBlacklistIndex(fallback, registrationEmailBlacklistErrorTTL), nil + } + }) + idx, _ := result.(*registrationEmailBlacklistIndex) + return idx +} + +// GetRegistrationEmailBlacklist 返回已保存的精确邮箱黑名单。 +func (s *SettingService) GetRegistrationEmailBlacklist(ctx context.Context) ([]string, error) { + raw, err := s.settingRepo.GetValue(ctx, SettingKeyRegistrationEmailBlacklist) + if err != nil { + if errors.Is(err, ErrSettingNotFound) { + return []string{}, nil + } + return nil, fmt.Errorf("get registration email blacklist: %w", err) + } + return ParseRegistrationEmailBlacklist(raw), nil +} + +// SetRegistrationEmailBlacklist 整体替换精确邮箱黑名单,返回保存后的名单与相对旧名单新增的项。 +func (s *SettingService) SetRegistrationEmailBlacklist(ctx context.Context, emails []string) (saved []string, added []string, err error) { + normalized, err := NormalizeRegistrationEmailBlacklist(emails) + if err != nil { + return nil, nil, err + } + previous, err := s.GetRegistrationEmailBlacklist(ctx) + if err != nil { + return nil, nil, err + } + previousSet := make(map[string]struct{}, len(previous)) + for _, email := range previous { + previousSet[email] = struct{}{} + } + added = make([]string, 0) + for _, email := range normalized { + if _, existed := previousSet[email]; !existed { + added = append(added, email) + } + } + + data, err := json.Marshal(normalized) + if err != nil { + return nil, nil, fmt.Errorf("marshal registration email blacklist: %w", err) + } + if err := s.settingRepo.Set(ctx, SettingKeyRegistrationEmailBlacklist, string(data)); err != nil { + return nil, nil, fmt.Errorf("save registration email blacklist: %w", err) + } + identities := RegistrationEmailBlacklistIdentities(normalized) + s.registrationEmailBlacklistMu.Lock() + s.storeRegistrationEmailBlacklistIndex(identities, registrationEmailBlacklistCacheTTL) + s.registrationEmailBlacklistMu.Unlock() + return normalized, added, nil +} + +// IsRegistrationEmailBlacklisted 判断邮箱(含同一收件箱的别名变体)是否在精确黑名单中。 +// 名单在本实例保存后立即生效,其它实例最迟在缓存 TTL 后生效;从未读到名单时不拦截。 +func (s *SettingService) IsRegistrationEmailBlacklisted(ctx context.Context, email string) bool { + if s == nil || s.settingRepo == nil { + return false + } + return s.registrationEmailBlacklistIndexCached(ctx).contains(email) +} diff --git a/backend/internal/service/registration_email_blacklist_test.go b/backend/internal/service/registration_email_blacklist_test.go new file mode 100644 index 0000000000..98316711d7 --- /dev/null +++ b/backend/internal/service/registration_email_blacklist_test.go @@ -0,0 +1,311 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/stretchr/testify/require" +) + +type writableSettingRepoStub struct { + *settingRepoStub + setCalls int + setErr error +} + +func newWritableSettingRepoStub(values map[string]string) *writableSettingRepoStub { + if values == nil { + values = map[string]string{} + } + return &writableSettingRepoStub{settingRepoStub: &settingRepoStub{values: values}} +} + +func (s *writableSettingRepoStub) Set(_ context.Context, key, value string) error { + s.mu.Lock() + defer s.mu.Unlock() + s.setCalls++ + if s.setErr != nil { + return s.setErr + } + s.values[key] = value + return nil +} + +func TestNormalizeRegistrationEmailBlacklistEntry(t *testing.T) { + cases := []struct { + raw string + want string + ok bool + }{ + {raw: " Alice@Gmail.COM ", want: "alice@gmail.com", ok: true}, + {raw: "a.b+tag@googlemail.com", want: "a.b+tag@googlemail.com", ok: true}, + {raw: "user@example.com.", want: "user@example.com", ok: true}, + {raw: "", ok: false}, + {raw: "@gmail.com", ok: false}, + {raw: "user@", ok: false}, + {raw: "user", ok: false}, + {raw: "a@b@gmail.com", ok: false}, + {raw: "user@localhost", ok: false}, + {raw: "us er@gmail.com", ok: false}, + {raw: "user@bad_domain.com", ok: false}, + {raw: fmt.Sprintf("%065d@gmail.com", 0), ok: false}, + } + for _, tc := range cases { + got, ok := NormalizeRegistrationEmailBlacklistEntry(tc.raw) + require.Equal(t, tc.ok, ok, tc.raw) + require.Equal(t, tc.want, got, tc.raw) + } +} + +func TestNormalizeRegistrationEmailBlacklist_DedupesAndKeepsOrder(t *testing.T) { + got, err := NormalizeRegistrationEmailBlacklist([]string{ + "B@gmail.com", " ", "a@googlemail.com", "b@gmail.com", "A@googlemail.com", + }) + require.NoError(t, err) + require.Equal(t, []string{"b@gmail.com", "a@googlemail.com"}, got) +} + +func TestNormalizeRegistrationEmailBlacklist_RejectsInvalidEntries(t *testing.T) { + _, err := NormalizeRegistrationEmailBlacklist([]string{"ok@gmail.com", "bad", "also bad@gmail.com"}) + require.Error(t, err) + appErr := infraerrors.FromError(err) + require.Equal(t, "EMAIL_BLACKLIST_INVALID_ENTRY", appErr.Reason) + require.Equal(t, "2", appErr.Metadata["invalid_count"]) + require.Contains(t, appErr.Message, "bad") +} + +func TestNormalizeRegistrationEmailBlacklist_RejectsOversizedList(t *testing.T) { + emails := make([]string, MaxRegistrationEmailBlacklistSize+1) + for i := range emails { + emails[i] = fmt.Sprintf("u%d@example.com", i) + } + _, err := NormalizeRegistrationEmailBlacklist(emails) + require.Error(t, err) + require.Equal(t, "EMAIL_BLACKLIST_TOO_LARGE", infraerrors.FromError(err).Reason) + + got, err := NormalizeRegistrationEmailBlacklist(emails[:MaxRegistrationEmailBlacklistSize]) + require.NoError(t, err) + require.Len(t, got, MaxRegistrationEmailBlacklistSize) +} + +func TestParseRegistrationEmailBlacklist_SkipsInvalidAndMalformed(t *testing.T) { + require.Equal(t, []string{}, ParseRegistrationEmailBlacklist("")) + require.Equal(t, []string{}, ParseRegistrationEmailBlacklist("not json")) + require.Equal(t, + []string{"a@gmail.com", "b@example.com"}, + ParseRegistrationEmailBlacklist(`["A@gmail.com","bad","b@example.com","a@gmail.com"]`), + ) +} + +func TestSettingService_IsRegistrationEmailBlacklisted_MatchesInboxIdentity(t *testing.T) { + repo := &settingRepoStub{values: map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["john.doe@gmail.com","sales@company.example"]`, + }} + svc := NewSettingService(repo, &config.Config{}) + ctx := context.Background() + + for _, email := range []string{ + "john.doe@gmail.com", + "JohnDoe@gmail.com", + "j.o.h.n.d.o.e+spam@googlemail.com", + "johndoe@gmail.com.", + "sales@company.example", + "sales+x@company.example", + } { + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, email), email) + } + for _, email := range []string{ + "john.doe2@gmail.com", + "s.ales@company.example", + "sales@other.example", + "not-an-email", + "", + } { + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, email), email) + } +} + +func expireRegistrationEmailBlacklistCache(svc *SettingService) { + if cached, ok := svc.registrationEmailBlacklistCache.Load().(*registrationEmailBlacklistIndex); ok && cached != nil { + svc.registrationEmailBlacklistCache.Store(®istrationEmailBlacklistIndex{identities: cached.identities}) + } +} + +func TestSettingService_IsRegistrationEmailBlacklisted_CachesUntilTTL(t *testing.T) { + repo := &settingRepoStub{values: map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["first@gmail.com"]`, + }} + svc := NewSettingService(repo, &config.Config{}) + ctx := context.Background() + + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "first@gmail.com")) + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, "other@gmail.com")) + require.Equal(t, 1, repo.getValueCalls) + + repo.mu.Lock() + repo.values[SettingKeyRegistrationEmailBlacklist] = `["second@gmail.com"]` + repo.mu.Unlock() + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "first@gmail.com"), "cached list is served within TTL") + require.Equal(t, 1, repo.getValueCalls) + + expireRegistrationEmailBlacklistCache(svc) + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, "first@gmail.com")) + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "second@gmail.com")) + require.Equal(t, 2, repo.getValueCalls) +} + +func TestSettingService_IsRegistrationEmailBlacklisted_CachesMissingSetting(t *testing.T) { + repo := &settingRepoStub{values: map[string]string{}} + svc := NewSettingService(repo, &config.Config{}) + ctx := context.Background() + + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, "anyone@gmail.com")) + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, "anyone@gmail.com")) + require.Equal(t, 1, repo.getValueCalls) +} + +func TestSettingService_IsRegistrationEmailBlacklisted_ReadFailureDoesNotBlock(t *testing.T) { + svc := NewSettingService(&settingRepoStub{err: errors.New("db down")}, &config.Config{}) + require.False(t, svc.IsRegistrationEmailBlacklisted(context.Background(), "anyone@gmail.com")) +} + +func TestSettingService_IsRegistrationEmailBlacklisted_ReadFailureKeepsLastKnownList(t *testing.T) { + repo := &settingRepoStub{values: map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["blocked@gmail.com"]`, + }} + svc := NewSettingService(repo, &config.Config{}) + ctx := context.Background() + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "blocked@gmail.com")) + + repo.mu.Lock() + repo.err = errors.New("db down") + repo.mu.Unlock() + expireRegistrationEmailBlacklistCache(svc) + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "blocked@gmail.com")) + + cached, ok := svc.registrationEmailBlacklistCache.Load().(*registrationEmailBlacklistIndex) + require.True(t, ok) + require.LessOrEqual(t, cached.expiresAt, time.Now().Add(registrationEmailBlacklistErrorTTL).UnixNano()) +} + +// blockingBlacklistRepoStub 让下一次读取名单停在返回旧值之前,用来构造刷新与保存交错的时序。 +type blockingBlacklistRepoStub struct { + *writableSettingRepoStub + blockNext bool + entered chan struct{} + release chan struct{} + saved chan struct{} +} + +func (s *blockingBlacklistRepoStub) GetValue(ctx context.Context, key string) (string, error) { + value, err := s.writableSettingRepoStub.GetValue(ctx, key) + s.mu.Lock() + block := s.blockNext + s.blockNext = false + s.mu.Unlock() + if block { + close(s.entered) + <-s.release + } + return value, err +} + +func (s *blockingBlacklistRepoStub) Set(ctx context.Context, key, value string) error { + err := s.writableSettingRepoStub.Set(ctx, key, value) + close(s.saved) + return err +} + +func TestSettingService_SetRegistrationEmailBlacklist_NotOverwrittenByInFlightRefresh(t *testing.T) { + repo := &blockingBlacklistRepoStub{ + writableSettingRepoStub: newWritableSettingRepoStub(map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["old@gmail.com"]`, + }), + entered: make(chan struct{}), + release: make(chan struct{}), + saved: make(chan struct{}), + } + svc := NewSettingService(repo, &config.Config{}) + ctx := context.Background() + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "old@gmail.com")) + expireRegistrationEmailBlacklistCache(svc) + + repo.mu.Lock() + repo.blockNext = true + repo.mu.Unlock() + refreshDone := make(chan struct{}) + go func() { + defer close(refreshDone) + svc.IsRegistrationEmailBlacklisted(ctx, "old@gmail.com") + }() + <-repo.entered + + saveDone := make(chan error, 1) + go func() { + _, _, err := svc.SetRegistrationEmailBlacklist(ctx, []string{"new@gmail.com"}) + saveDone <- err + }() + <-repo.saved + close(repo.release) + <-refreshDone + require.NoError(t, <-saveDone) + + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "new@gmail.com")) + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, "old@gmail.com")) +} + +func TestSettingService_SetRegistrationEmailBlacklist_ReportsAddedAndPersists(t *testing.T) { + repo := newWritableSettingRepoStub(map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["old@gmail.com","keep@gmail.com"]`, + }) + svc := NewSettingService(repo, &config.Config{}) + ctx := context.Background() + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "old@gmail.com")) + + saved, added, err := svc.SetRegistrationEmailBlacklist(ctx, []string{"Keep@gmail.com", "new@gmail.com", "new@gmail.com"}) + require.NoError(t, err) + require.Equal(t, []string{"keep@gmail.com", "new@gmail.com"}, saved) + require.Equal(t, []string{"new@gmail.com"}, added) + + var stored []string + require.NoError(t, json.Unmarshal([]byte(repo.values[SettingKeyRegistrationEmailBlacklist]), &stored)) + require.Equal(t, saved, stored) + require.True(t, svc.IsRegistrationEmailBlacklisted(ctx, "n.e.w@googlemail.com")) + require.False(t, svc.IsRegistrationEmailBlacklisted(ctx, "old@gmail.com")) + + saved, added, err = svc.SetRegistrationEmailBlacklist(ctx, []string{}) + require.NoError(t, err) + require.Empty(t, saved) + require.Empty(t, added) + require.Equal(t, "[]", repo.values[SettingKeyRegistrationEmailBlacklist]) +} + +func TestSettingService_SetRegistrationEmailBlacklist_InvalidEntryDoesNotWrite(t *testing.T) { + repo := newWritableSettingRepoStub(map[string]string{ + SettingKeyRegistrationEmailBlacklist: `["old@gmail.com"]`, + }) + svc := NewSettingService(repo, &config.Config{}) + + _, _, err := svc.SetRegistrationEmailBlacklist(context.Background(), []string{"ok@gmail.com", "broken"}) + require.Error(t, err) + require.Zero(t, repo.setCalls) + require.Equal(t, `["old@gmail.com"]`, repo.values[SettingKeyRegistrationEmailBlacklist]) +} + +func TestSettingService_SetRegistrationEmailBlacklist_ReadFailureDoesNotWrite(t *testing.T) { + repo := newWritableSettingRepoStub(nil) + repo.err = errors.New("db down") + svc := NewSettingService(repo, &config.Config{}) + + _, _, err := svc.SetRegistrationEmailBlacklist(context.Background(), []string{"ok@gmail.com"}) + require.Error(t, err) + require.Zero(t, repo.setCalls) +} diff --git a/backend/internal/service/session_memory_cache.go b/backend/internal/service/session_memory_cache.go new file mode 100644 index 0000000000..857a72e6d3 --- /dev/null +++ b/backend/internal/service/session_memory_cache.go @@ -0,0 +1,244 @@ +package service + +import ( + "container/list" + "hash/maphash" + "strings" + "sync" + "time" +) + +const ( + sessionMemoryCacheMaxEntries = 16_384 + sessionMemoryCacheMaxBytes = 32 << 20 + sessionMemoryCacheSweep = time.Minute + // Includes the map/list/index entries and interface/string headers. The + // entry cap separately bounds bookkeeping even for very small values. + sessionMemoryCacheEntryCost = 512 +) + +type sessionMemoryValue interface { + sessionExpiresAt() time.Time + sessionCost() int + cloneSessionValue() sessionMemoryValue +} + +type sessionMemoryEntry struct { + key string + hash uint64 + value sessionMemoryValue + expiresAt time.Time + cost int +} + +// sessionMemoryCache keeps the original string keys and bounds both their +// count and retained bytes. Cleanup stops when a sweep finds the cache empty; +// there is no goroutine waiting for the lifetime of a service or test instance. +// The zero value is ready for use. +type sessionMemoryCache struct { + mu sync.Mutex + entries map[string]*list.Element + prefixes map[uint64][]*list.Element + lru list.List + seed maphash.Seed + bytes int + maxEntries int + maxBytes int + sweep time.Duration + timer *time.Timer + closed bool +} + +func (c *sessionMemoryCache) initLocked() { + if c.entries != nil { + return + } + c.entries = make(map[string]*list.Element) + c.prefixes = make(map[uint64][]*list.Element) + c.seed = maphash.MakeSeed() + if c.maxEntries <= 0 { + c.maxEntries = sessionMemoryCacheMaxEntries + } + if c.maxBytes <= 0 { + c.maxBytes = sessionMemoryCacheMaxBytes + } + if c.sweep <= 0 { + c.sweep = sessionMemoryCacheSweep + } +} + +func (c *sessionMemoryCache) Store(key string, value sessionMemoryValue) { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + c.initLocked() + if current := c.entries[key]; current != nil { + c.removeLocked(current) + } + cost := sessionMemoryCacheEntryCost + len(key) + value.sessionCost() + expiresAt := value.sessionExpiresAt() + if cost > c.maxBytes || !expiresAt.After(time.Now()) { + return + } + for len(c.entries) >= c.maxEntries || c.bytes+cost > c.maxBytes { + c.removeLocked(c.lru.Back()) + } + // Never let a short slice of a request or response pin its backing body. + key = strings.Clone(key) + entry := &sessionMemoryEntry{ + key: key, hash: maphash.String(c.seed, key), value: value.cloneSessionValue(), + expiresAt: expiresAt, cost: cost, + } + element := c.lru.PushFront(entry) + c.entries[key] = element + c.prefixes[entry.hash] = append(c.prefixes[entry.hash], element) + c.bytes += cost + if c.timer == nil { + c.timer = time.AfterFunc(c.sweep, c.sweepExpired) + } +} + +func (c *sessionMemoryCache) Load(key string) (sessionMemoryValue, bool) { + c.mu.Lock() + defer c.mu.Unlock() + element := c.entries[key] + if element == nil { + return nil, false + } + entry, _ := element.Value.(*sessionMemoryEntry) + if !entry.expiresAt.After(time.Now()) { + c.removeLocked(element) + return nil, false + } + c.lru.MoveToFront(element) + return entry.value, true +} + +func (c *sessionMemoryCache) Delete(key string) { + c.mu.Lock() + defer c.mu.Unlock() + if element := c.entries[key]; element != nil { + c.removeLocked(element) + } +} + +func (c *sessionMemoryCache) removeLocked(element *list.Element) { + entry, _ := element.Value.(*sessionMemoryEntry) + delete(c.entries, entry.key) + indexed := c.prefixes[entry.hash] + for i, candidate := range indexed { + if candidate == element { + indexed[i] = indexed[len(indexed)-1] + indexed[len(indexed)-1] = nil + indexed = indexed[:len(indexed)-1] + break + } + } + if len(indexed) == 0 { + delete(c.prefixes, entry.hash) + } else { + c.prefixes[entry.hash] = indexed + } + c.bytes -= entry.cost + c.lru.Remove(element) +} + +func (c *sessionMemoryCache) sweepExpired() { + c.mu.Lock() + defer c.mu.Unlock() + c.timer = nil + if c.closed { + return + } + now := time.Now() + for element := c.lru.Back(); element != nil; { + previous := element.Prev() + entry, _ := element.Value.(*sessionMemoryEntry) + if !entry.expiresAt.After(now) { + c.removeLocked(element) + } + element = previous + } + if len(c.entries) > 0 { + c.timer = time.AfterFunc(c.sweep, c.sweepExpired) + } +} + +func (c *sessionMemoryCache) Close() { + c.mu.Lock() + defer c.mu.Unlock() + c.closed = true + if c.timer != nil { + c.timer.Stop() + c.timer = nil + } + c.entries = nil + c.prefixes = nil + c.lru.Init() + c.bytes = 0 +} + +func (c *sessionMemoryCache) ItemCount() int { + c.mu.Lock() + defer c.mu.Unlock() + return len(c.entries) +} + +// longestDigestPrefix uses incrementally hashed prefixes to avoid allocating +// and hashing ns+chain[:end] for every message. Keys remain unchanged, and a +// hash hit is checked against the full original key, including its namespace. +// Hashing and temporary storage are O(len(chain)); map lookups are O(messages). +func (c *sessionMemoryCache) longestDigestPrefix(ns, chain string) (sessionMemoryValue, string, bool) { + c.mu.Lock() + if len(c.entries) == 0 { + c.mu.Unlock() + return nil, "", false + } + seed := c.seed + c.mu.Unlock() + + type prefix struct { + hash uint64 + end int + } + prefixes := make([]prefix, 0, strings.Count(chain, "-")+1) + var hash maphash.Hash + hash.SetSeed(seed) + _, _ = hash.WriteString(ns) + start := 0 + for i := 0; i < len(chain); i++ { + if chain[i] != '-' { + continue + } + _, _ = hash.WriteString(chain[start:i]) + prefixes = append(prefixes, prefix{hash: hash.Sum64(), end: i}) + // Include the separator only in subsequent, longer prefixes. + _, _ = hash.WriteString("-") + start = i + 1 + } + _, _ = hash.WriteString(chain[start:]) + prefixes = append(prefixes, prefix{hash: hash.Sum64(), end: len(chain)}) + + c.mu.Lock() + defer c.mu.Unlock() + now := time.Now() + for i := len(prefixes) - 1; i >= 0; i-- { + candidate := prefixes[i] + for _, element := range c.prefixes[candidate.hash] { + entry, _ := element.Value.(*sessionMemoryEntry) + if !entry.expiresAt.After(now) { + // The active timer reclaims this entry. Avoid editing the + // collision bucket while it is being iterated. + continue + } + if len(entry.key) != len(ns)+candidate.end || !strings.HasPrefix(entry.key, ns) || entry.key[len(ns):] != chain[:candidate.end] { + continue + } + c.lru.MoveToFront(element) + return entry.value, chain[:candidate.end], true + } + } + return nil, "", false +} diff --git a/backend/internal/service/session_memory_cache_test.go b/backend/internal/service/session_memory_cache_test.go new file mode 100644 index 0000000000..e33bfadfe5 --- /dev/null +++ b/backend/internal/service/session_memory_cache_test.go @@ -0,0 +1,223 @@ +package service + +import ( + "context" + "fmt" + "math/rand" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestSessionMemoryCacheExpiresWithoutReads(t *testing.T) { + cache := &sessionMemoryCache{sweep: 5 * time.Millisecond} + t.Cleanup(cache.Close) + for i := 0; i < 100; i++ { + cache.Store(fmt.Sprintf("session-%d", i), &sessionEntry{uuid: "session", expiresAt: time.Now().Add(30 * time.Millisecond)}) + } + require.Equal(t, 100, cache.ItemCount()) + // ItemCount only observes the map; it does not trigger lazy expiration. + require.Eventually(t, func() bool { return cache.ItemCount() == 0 }, time.Second, 5*time.Millisecond) + cache.mu.Lock() + defer cache.mu.Unlock() + require.Zero(t, cache.bytes) + require.Empty(t, cache.prefixes) + require.Nil(t, cache.timer, "the last expiry must stop scheduling cleanup") +} + +func TestOpenAICompatSessionCachesExpireWithoutRevisit(t *testing.T) { + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.StickyResponseIDTTLSeconds = 1 + s := &OpenAIGatewayService{cfg: cfg} + s.openaiCompatAnthropicDigestSessions.sweep = 5 * time.Millisecond + s.openaiCompatSessionResponses.sweep = 5 * time.Millisecond + t.Cleanup(s.CloseOpenAIWSPool) + account := &Account{ID: 1} + for i := 0; i < 100; i++ { + key := fmt.Sprintf("session-%d", i) + s.bindOpenAICompatAnthropicDigestPromptCacheKey(account, 1, "u:"+key, key, "") + s.bindOpenAICompatSessionResponseID(context.Background(), nil, account, key, "resp-test") + } + require.Equal(t, 100, s.openaiCompatAnthropicDigestSessions.ItemCount()) + require.Equal(t, 100, s.openaiCompatSessionResponses.ItemCount()) + require.Eventually(t, func() bool { + return s.openaiCompatAnthropicDigestSessions.ItemCount() == 0 && s.openaiCompatSessionResponses.ItemCount() == 0 + }, 2*time.Second, 10*time.Millisecond) +} + +func TestSessionMemoryCacheBoundsAndLRU(t *testing.T) { + cache := &sessionMemoryCache{maxEntries: 2, maxBytes: 2048} + t.Cleanup(cache.Close) + value := &sessionEntry{uuid: "value", expiresAt: time.Now().Add(time.Hour)} + cache.Store("first", value) + cache.Store("second", value) + _, ok := cache.Load("first") + require.True(t, ok) + cache.Store("third", value) + _, ok = cache.Load("second") + require.False(t, ok) + require.Equal(t, 2, cache.ItemCount()) + _, _, ok = cache.longestDigestPrefix("", "second-u:next") + require.False(t, ok, "eviction must also remove the prefix index") + + // An individually oversized key or value must never enter the cache. + cache.Store(strings.Repeat("x", 2048), value) + cache.Store("large-value", &sessionEntry{uuid: strings.Repeat("x", 2048), expiresAt: value.expiresAt}) + require.Equal(t, 2, cache.ItemCount()) + cache.Store("third", &sessionEntry{uuid: strings.Repeat("x", 1400), expiresAt: value.expiresAt}) + require.Equal(t, 1, cache.ItemCount(), "byte pressure must evict independently of the entry cap") + _, ok = cache.Load("third") + require.True(t, ok) + cache.mu.Lock() + require.LessOrEqual(t, cache.bytes, cache.maxBytes) + cache.mu.Unlock() +} + +func TestSessionMemoryCacheLongestPrefixKeepsRawKeySemantics(t *testing.T) { + cache := &sessionMemoryCache{} + t.Cleanup(cache.Close) + deadline := time.Now().Add(time.Hour) + // Use the historical raw namespace+chain format, without a rewritten key. + for _, chain := range []string{"u:a", "u:ab", "u:a-a:b", "u:a-a:b-u:c"} { + cache.Store("account|key|"+chain, &sessionEntry{uuid: chain, expiresAt: deadline}) + } + cache.Store("other|key|u:a-a:b-u:c-a:d", &sessionEntry{uuid: "wrong tenant", expiresAt: deadline}) + for _, tc := range []struct{ query, matched string }{ + {"u:a", "u:a"}, + {"u:ab-u:next", "u:ab"}, + {"u:abc-u:next", ""}, + {"u:a-a:b-u:c-a:d", "u:a-a:b-u:c"}, + {"u:a-a:b-u:changed", "u:a-a:b"}, + } { + value, matched, found := cache.longestDigestPrefix("account|key|", tc.query) + require.Equal(t, tc.matched != "", found, tc.query) + require.Equal(t, tc.matched, matched, tc.query) + if found { + entry, ok := value.(*sessionEntry) + require.True(t, ok) + require.Equal(t, matched, entry.uuid) + } + } + cache.Delete("account|key|u:a-a:b-u:c") + _, matched, found := cache.longestDigestPrefix("account|key|", "u:a-a:b-u:c-a:d") + require.True(t, found) + require.Equal(t, "u:a-a:b", matched) +} + +func TestSessionMemoryCacheExpiredLongestPrefixFallsBack(t *testing.T) { + cache := &sessionMemoryCache{} + t.Cleanup(cache.Close) + cache.Store("ns|u:a", &sessionEntry{uuid: "short", expiresAt: time.Now().Add(time.Hour)}) + cache.Store("ns|u:a-a:b", &sessionEntry{uuid: "long", expiresAt: time.Now().Add(time.Hour)}) + cache.mu.Lock() + entry, ok := cache.entries["ns|u:a-a:b"].Value.(*sessionMemoryEntry) + if ok { + entry.expiresAt = time.Now().Add(-time.Second) + } + cache.mu.Unlock() + require.True(t, ok) + value, matched, found := cache.longestDigestPrefix("ns|", "u:a-a:b-u:c") + require.True(t, found) + require.Equal(t, "u:a", matched) + session, ok := value.(*sessionEntry) + require.True(t, ok) + require.Equal(t, "short", session.uuid) +} + +func TestSessionMemoryCacheDigestIndexMatchesLegacyLookup(t *testing.T) { + cache := &sessionMemoryCache{} + t.Cleanup(cache.Close) + rng := rand.New(rand.NewSource(42)) + legacy := make(map[string]bool) + for i := 0; i < 500; i++ { + ns := fmt.Sprintf("%d|", rng.Intn(3)) + var parts []string + for j := 0; j <= rng.Intn(12); j++ { + parts = append(parts, fmt.Sprintf("u:%d", rng.Intn(4))) + } + chain := strings.Join(parts, "-") + cache.Store(ns+chain, &sessionEntry{uuid: chain, expiresAt: time.Now().Add(time.Hour)}) + legacy[ns+chain] = true + query := chain + "-a:next-u:later" + if rng.Intn(3) == 0 { + cache.Delete(ns + chain) + delete(legacy, ns+chain) + } + want := query + for !legacy[ns+want] { + end := strings.LastIndexByte(want, '-') + if end < 0 { + want = "" + break + } + want = want[:end] + } + _, got, found := cache.longestDigestPrefix(ns, query) + require.Equal(t, want != "", found) + require.Equal(t, want, got) + } +} + +func TestSessionMemoryCacheConcurrentClose(t *testing.T) { + cache := &sessionMemoryCache{maxEntries: 32, maxBytes: 8192, sweep: time.Millisecond} + var wg sync.WaitGroup + started := make(chan struct{}, 8) + for g := 0; g < 8; g++ { + wg.Add(1) + go func(id int) { + defer wg.Done() + for i := 0; i < 100; i++ { + key := fmt.Sprintf("ns|u:%d-a:%d", id, i) + cache.Store(key, &sessionEntry{uuid: key, expiresAt: time.Now().Add(2 * time.Millisecond)}) + if i == 0 { + started <- struct{}{} + } + cache.Load(key) + cache.longestDigestPrefix("ns|", key[3:]+"-u:next") + cache.Delete(key) + } + }(g) + } + for g := 0; g < 8; g++ { + <-started + } + cache.Close() + wg.Wait() + cache.Close() + require.Zero(t, cache.ItemCount()) + cache.mu.Lock() + defer cache.mu.Unlock() + require.Nil(t, cache.timer) + require.Zero(t, cache.bytes) +} + +func BenchmarkDigestSessionLookupMiss(b *testing.B) { + for _, n := range []int{100, 1000, 5000} { + chain := strings.TrimSuffix(strings.Repeat("u:0123456789abc-", n), "-") + b.Run(fmt.Sprintf("OpenAICompat/messages_%d", n), func(b *testing.B) { + s := &OpenAIGatewayService{} + b.Cleanup(s.CloseOpenAIWSPool) + account := &Account{ID: 1} + s.bindOpenAICompatAnthropicDigestPromptCacheKey(account, 1, "u:unrelated", "cache-key", "") + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.findOpenAICompatAnthropicDigestPromptCacheKey(account, 1, chain) + } + }) + b.Run(fmt.Sprintf("SharedStore/messages_%d", n), func(b *testing.B) { + s := NewDigestSessionStore() + b.Cleanup(s.Close) + s.Save(1, "prefix", "u:unrelated", "uuid", 1, "") + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + s.Find(1, "prefix", chain) + } + }) + } +} 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.go b/backend/internal/service/setting_service.go index c8c0ad1e9d..082d999468 100644 --- a/backend/internal/service/setting_service.go +++ b/backend/internal/service/setting_service.go @@ -145,6 +145,14 @@ type SettingService struct { panelRateLimitCache atomic.Value panelRateLimitSF singleflight.Group + // registrationEmailBlacklistCache 精确邮箱黑名单进程内缓存(*registrationEmailBlacklistIndex,60s TTL)。 + // 公开的注册与发码接口每次请求都会读取,禁止在热路径上直接访问 DB。 + // registrationEmailBlacklistMu 串行化刷新时的「读 DB + 写缓存」与保存后的写缓存, + // 避免进行中的刷新用旧名单覆盖刚保存的名单。 + registrationEmailBlacklistMu sync.Mutex + registrationEmailBlacklistCache atomic.Value + registrationEmailBlacklistSF singleflight.Group + // openAIQuotaAutoPauseSettingsCache holds the most recently observed quota auto-pause // settings. GetOpenAIQuotaAutoPauseSettings reads this atomic.Value on the request hot // path without ever blocking on the DB; when the cached entry expires, a background 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/sse_large_image_compat_test.go b/backend/internal/service/sse_large_image_compat_test.go new file mode 100644 index 0000000000..78c86b6610 --- /dev/null +++ b/backend/internal/service/sse_large_image_compat_test.go @@ -0,0 +1,45 @@ +package service + +import ( + "bytes" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type largeImageBase64Reader struct{} + +func (largeImageBase64Reader) Read(p []byte) (int, error) { + for i := range p { + p[i] = 'A' + } + return len(p), nil +} + +func TestDefaultSSELimitPreservesImageFrameAbove40MiB(t *testing.T) { + // High-resolution image frames can carry more than 40 MiB of base64 data. + // Generate the input lazily so this test retains only the reader's result. + const imageBytes = 41 << 20 + const prefix = "data: {\"b64_json\":\"" + const suffix = "\"}\r\n" + wire := io.MultiReader( + strings.NewReader(prefix), + io.LimitReader(largeImageBase64Reader{}, imageBytes), + strings.NewReader(suffix+"\r\ndata: [DONE]"), + ) + reader := newBoundedSSELineReader(wire, nil) + line, err := reader.ReadLine() + require.NoError(t, err) + require.Len(t, line, len(prefix)+imageBytes+len(suffix)) + require.True(t, bytes.HasPrefix(line, []byte(prefix))) + require.True(t, bytes.HasSuffix(line, []byte(suffix))) + require.Equal(t, imageBytes, bytes.Count(line, []byte{'A'})) + line, err = reader.ReadLine() + require.NoError(t, err) + require.Equal(t, "\r\n", string(line)) + line, err = reader.ReadLine() + require.ErrorIs(t, err, io.EOF) + require.Equal(t, "data: [DONE]", string(line)) +} diff --git a/backend/internal/service/sse_transport_limits.go b/backend/internal/service/sse_transport_limits.go new file mode 100644 index 0000000000..f9c5352342 --- /dev/null +++ b/backend/internal/service/sse_transport_limits.go @@ -0,0 +1,187 @@ +package service + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "sync/atomic" + + "github.com/Wei-Shaw/sub2api/internal/config" +) + +const ( + defaultSSEQueueMaxBytes = 8 << 20 + defaultSSEEventMaxLines = 4096 +) + +// sseQueueBudget bounds queued payload bytes, in addition to the channel's +// event count. A single line larger than the budget reserves the whole budget: +// legitimate image frames still pass, but cannot fill all 16 queue slots. The +// consumer's current line and the producer's next line/scanner buffer are not +// queue storage and remain subject to the line/event limits. +// +// There is one producer and one consumer. Release on dequeue, not on shutdown, +// so cancellation never depends on draining an abandoned queue. +type sseQueueBudget struct { + limit int64 + used atomic.Int64 + available chan struct{} +} + +func newSSEQueueBudget(cfg *config.Config) *sseQueueBudget { + limit := int64(defaultSSEQueueMaxBytes) + if cfg != nil && cfg.Gateway.SSEQueueMaxBytes > 0 { + limit = cfg.Gateway.SSEQueueMaxBytes + } + return &sseQueueBudget{limit: limit, available: make(chan struct{}, 1)} +} + +func (b *sseQueueBudget) weight(size int) int64 { + return min(int64(size), b.limit) +} + +func (b *sseQueueBudget) acquire(size int, done <-chan struct{}) bool { + weight := b.weight(size) + for { + select { + case <-done: + return false + default: + } + used := b.used.Load() + if weight <= b.limit-used && b.used.CompareAndSwap(used, used+weight) { + return true + } + select { + case <-done: + return false + case <-b.available: + } + } +} + +func (b *sseQueueBudget) release(size int) { + if size == 0 { + return + } + b.used.Add(-b.weight(size)) + select { + case b.available <- struct{}{}: + default: + } +} + +var errSSETransportLimit = errors.New("upstream SSE transport limit exceeded") + +type sseEventLimits struct { + maxBytes int64 + maxLines int + bytes int64 + lines int +} + +func newSSEEventLimits(cfg *config.Config, maxLineSize int) *sseEventLimits { + if maxLineSize <= 0 { + maxLineSize = defaultMaxLineSize + } + limits := &sseEventLimits{maxBytes: int64(maxLineSize), maxLines: defaultSSEEventMaxLines} + if cfg != nil { + if cfg.Gateway.SSEEventMaxBytes > 0 { + limits.maxBytes = cfg.Gateway.SSEEventMaxBytes + } + if cfg.Gateway.SSEEventMaxLines > 0 { + limits.maxLines = cfg.Gateway.SSEEventMaxLines + } + } + return limits +} + +func (l *sseEventLimits) observe(line []byte, wireBytes int) error { + if len(bytes.TrimRight(line, "\r\n")) == 0 { + l.bytes, l.lines = 0, 0 + return nil + } + if int64(wireBytes) > l.maxBytes-l.bytes || l.lines >= l.maxLines { + return l.exceeded() + } + l.bytes += int64(wireBytes) + l.lines++ + return nil +} + +func (l *sseEventLimits) exceeded() error { + // Preserve the existing upstream response_too_large error paths. This is + // an SSE framing limit, independent of JSON/protocol translation. + return fmt.Errorf("%w: %w: SSE event exceeds %d bytes or %d lines", errSSETransportLimit, bufio.ErrTooLong, l.maxBytes, l.maxLines) +} + +// newBoundedSSESplit limits complete events as well as incomplete lines. Without +// this, an upstream can bypass a single-line cap by never sending a blank line. +// next may preserve line endings or enforce the OpenAI pre-output guard. +func newBoundedSSESplit(cfg *config.Config, maxLineSize int, next bufio.SplitFunc) bufio.SplitFunc { + if next == nil { + next = bufio.ScanLines + } + limits := newSSEEventLimits(cfg, maxLineSize) + return func(data []byte, atEOF bool) (int, []byte, error) { + advance, token, err := next(data, atEOF) + if err != nil { + return advance, token, err + } + if token != nil { + if err := limits.observe(token, advance); err != nil { + return 0, nil, err + } + } else if int64(len(data)) > limits.maxBytes-limits.bytes { + return 0, nil, limits.exceeded() + } + return advance, token, nil + } +} + +// boundedSSELineReader preserves the original bytes (including CRLF and the +// final unterminated line) used by image passthrough. ReadSlice bounds individual +// allocations; oversized/incomplete lines are rejected without forwarding a +// truncated prefix as a successful SSE event. +type boundedSSELineReader struct { + reader *bufio.Reader + maxLineSize int + limits *sseEventLimits +} + +func newBoundedSSELineReader(reader io.Reader, cfg *config.Config) *boundedSSELineReader { + maxLineSize := defaultMaxLineSize + if cfg != nil && cfg.Gateway.MaxLineSize > 0 { + maxLineSize = cfg.Gateway.MaxLineSize + } + return &boundedSSELineReader{reader: bufio.NewReader(reader), maxLineSize: maxLineSize, limits: newSSEEventLimits(cfg, maxLineSize)} +} + +func (r *boundedSSELineReader) ReadLine() ([]byte, error) { + var line []byte + for { + part, err := r.reader.ReadSlice('\n') + if len(part) > r.maxLineSize-len(line) || (len(bytes.TrimRight(part, "\r\n")) != 0 || len(line) != 0) && int64(len(line)+len(part)) > r.limits.maxBytes-r.limits.bytes { + return nil, r.limits.exceeded() + } + line = append(line, part...) + if err == bufio.ErrBufferFull { + continue + } + if len(line) > 0 { + if limitErr := r.limits.observe(line, len(line)); limitErr != nil { + return nil, limitErr + } + } + return line, err + } +} + +func (s *AntigravityGatewayService) antigravitySSEConfig() *config.Config { + if s == nil || s.settingService == nil { + return nil + } + return s.settingService.cfg +} diff --git a/backend/internal/service/sse_transport_limits_test.go b/backend/internal/service/sse_transport_limits_test.go new file mode 100644 index 0000000000..5be85a3d05 --- /dev/null +++ b/backend/internal/service/sse_transport_limits_test.go @@ -0,0 +1,313 @@ +package service + +import ( + "bufio" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestSSEQueueBudgetBackpressureAndCancellation(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{SSEQueueMaxBytes: 64}} + budget := newSSEQueueBudget(cfg) + done := make(chan struct{}) + require.True(t, budget.acquire(48, done)) + acquired := make(chan bool, 1) + go func() { acquired <- budget.acquire(32, done) }() + select { + case <-acquired: + t.Fatal("queue accepted more bytes than its budget") + case <-time.After(20 * time.Millisecond): + } + budget.release(48) + require.True(t, <-acquired) + budget.release(32) + + // Large image frames may occupy the budget alone, without reducing the + // configured per-line limit to the (much smaller) queue budget. + require.True(t, budget.acquire(1024, done)) + require.Equal(t, int64(64), budget.used.Load()) + go func() { acquired <- budget.acquire(1, done) }() + select { + case <-acquired: + t.Fatal("queued another payload alongside an oversized frame") + case <-time.After(20 * time.Millisecond): + } + close(done) + select { + case ok := <-acquired: + require.False(t, ok) + case <-time.After(time.Second): + t.Fatal("cancellation did not release queue producer") + } + budget.release(1024) + require.Zero(t, budget.used.Load()) + require.False(t, budget.acquire(1, done)) +} + +func TestBoundedSSESplitRejectsUndelimitedEvents(t *testing.T) { + for _, tc := range []struct { + name string + gateway config.GatewayConfig + wire string + }{ + {"lines", config.GatewayConfig{SSEEventMaxLines: 4}, strings.Repeat(": keepalive\n", 5)}, + {"bytes", config.GatewayConfig{SSEEventMaxBytes: 20}, strings.Repeat("data: abcd\n", 3)}, + {"incomplete_line", config.GatewayConfig{SSEEventMaxBytes: 20}, "data: " + strings.Repeat("a", 32)}, + } { + t.Run(tc.name, func(t *testing.T) { + scanner := bufio.NewScanner(strings.NewReader(tc.wire)) + scanner.Split(newBoundedSSESplit(&config.Config{Gateway: tc.gateway}, 1<<20, nil)) + for scanner.Scan() { + } + require.ErrorIs(t, scanner.Err(), errSSETransportLimit) + require.ErrorIs(t, scanner.Err(), bufio.ErrTooLong) + }) + } +} + +func TestBoundedSSESplitResetsAtEventBoundaryAndPreservesEOF(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{SSEEventMaxBytes: 11, SSEEventMaxLines: 1}} + scanner := bufio.NewScanner(strings.NewReader("data: abcd\n\ndata: last")) + scanner.Split(newBoundedSSESplit(cfg, 1<<20, nil)) + var lines []string + for scanner.Scan() { + lines = append(lines, scanner.Text()) + } + require.NoError(t, scanner.Err()) + require.Equal(t, []string{"data: abcd", "", "data: last"}, lines) +} + +func TestBoundedSSELineReaderPreservesLargeImageFrame(t *testing.T) { + payload := "data: {\"b64_json\":\"" + strings.Repeat("A", 128<<10) + "\"}\r\n" + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 256 << 10, SSEQueueMaxBytes: 1024}} + reader := newBoundedSSELineReader(strings.NewReader(payload+"\r\n"+"data: [DONE]"), cfg) + line, err := reader.ReadLine() + require.NoError(t, err) + require.Equal(t, payload, string(line)) + line, err = reader.ReadLine() + require.NoError(t, err) + require.Equal(t, "\r\n", string(line)) + line, err = reader.ReadLine() + require.ErrorIs(t, err, io.EOF) + require.Equal(t, "data: [DONE]", string(line)) +} + +func TestBoundedSSELineReaderRejectsOversizeWithoutTruncatedPrefix(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 4096, SSEEventMaxBytes: 8192}} + reader := newBoundedSSELineReader(strings.NewReader("data: "+strings.Repeat("A", 64<<10)), cfg) + line, err := reader.ReadLine() + require.Nil(t, line) + require.ErrorIs(t, err, errSSETransportLimit) +} + +func TestGatewayStreamingUndelimitedEventFailsWithoutSuccessfulTerminal(t *testing.T) { + gin.SetMode(gin.TestMode) + svc := newStreamingResponseTestGatewayService() + svc.cfg.Gateway.SSEEventMaxLines = 4 + svc.cfg.Gateway.SSEQueueMaxBytes = 128 + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + wire := "data: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":3}}}\n\n" + strings.Repeat(": malformed event\n", 5) + "\ndata: {\"type\":\"message_stop\"}\n\n" + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(wire))} + defer func() { _ = resp.Body.Close() }() + result, err := svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1}, time.Now(), "model", "model", false) + require.ErrorIs(t, err, errSSETransportLimit) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.InputTokens) + require.Contains(t, rec.Body.String(), "response_too_large") + require.NotContains(t, rec.Body.String(), "message_stop") +} + +func TestAnthropicNativePumpLargeLineBudgetAndStop(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{SSEQueueMaxBytes: 64}} + scanner := bufio.NewScanner(strings.NewReader(strings.Repeat(strings.Repeat("x", 1024)+"\n", 32))) + pump := newAnthropicNativeLinePump(scanner, time.Second, cfg) + line, err := pump.next() + require.NoError(t, err) + require.Len(t, line, 1024) + pump.stop() + // The producer must stop even if another oversized payload already occupies + // the entire queue budget. Draining here observes channel closure only. + deadline := time.After(time.Second) + for { + select { + case _, ok := <-pump.events: + if !ok { + return + } + case <-deadline: + t.Fatal("line pump remained blocked after stop") + } + } +} + +func TestSSETransportDefaultsAndFirstOutputGuardCompose(t *testing.T) { + require.Equal(t, int64(defaultSSEQueueMaxBytes), newSSEQueueBudget(&config.Config{}).limit) + limits := newSSEEventLimits(&config.Config{}, 1234) + require.Equal(t, int64(1234), limits.maxBytes) + require.Equal(t, defaultSSEEventMaxLines, limits.maxLines) + innerErr := errors.New("pre-output guard") + scanner := bufio.NewScanner(strings.NewReader("data: test\n")) + scanner.Split(newBoundedSSESplit(nil, 1024, func([]byte, bool) (int, []byte, error) { return 0, nil, innerErr })) + require.False(t, scanner.Scan()) + require.ErrorIs(t, scanner.Err(), innerErr) +} + +func TestSSEConfiguredLargeFrameLimitRemainsAvailable(t *testing.T) { + defaults := newBoundedSSELineReader(strings.NewReader(""), nil) + require.Equal(t, 500<<20, defaults.maxLineSize) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 64 << 20}} + configured := newBoundedSSELineReader(strings.NewReader(""), cfg) + require.Equal(t, 64<<20, configured.maxLineSize) + require.Equal(t, int64(64<<20), configured.limits.maxBytes) +} + +type sseTransportFailureReader struct{ err error } + +func (r sseTransportFailureReader) Read([]byte) (int, error) { return 0, r.err } + +func TestAnthropicCompatTransportFailureNeverFinalizesSuccess(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1 << 20, SSEEventMaxLines: 4, SSEQueueMaxBytes: 128}} + gateway := &GatewayService{cfg: cfg} + openai := &OpenAIGatewayService{cfg: cfg} + mapping := apicompat.ResponsesClientToolMapping{} + calls := []struct { + name string + stream bool + call func(*http.Response, *gin.Context) (int, error) + }{ + {"gateway_cc_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := gateway.handleCCBufferedFromAnthropic(resp, c, "m", "m", nil, time.Now()) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"gateway_responses_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := gateway.handleResponsesBufferedStreamingResponse(resp, c, "m", "m", nil, time.Now(), mapping) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_cc_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleCCBufferedFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now()) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_responses_buffered", false, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleResponsesBufferedFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now(), mapping) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_cc_stream", true, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleCCStreamingFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now()) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + {"native_responses_stream", true, func(resp *http.Response, c *gin.Context) (int, error) { + r, e := openai.handleResponsesStreamingFromNativeAnthropic(resp, c, "m", "m", "m", nil, time.Now(), mapping) + if r == nil { + return 0, e + } + return r.Usage.InputTokens, e + }}, + } + prefix := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_test\",\"model\":\"m\",\"usage\":{\"input_tokens\":3}}}\n\n" + for _, call := range calls { + for _, failure := range []string{"event_limit", "cancel", "truncated"} { + t.Run(call.name+"/"+failure, func(t *testing.T) { + var tail io.Reader + switch failure { + case "event_limit": + tail = strings.NewReader(strings.Repeat(": missing delimiter\n", 5)) + case "cancel": + tail = sseTransportFailureReader{context.Canceled} + default: + tail = strings.NewReader("") + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(io.MultiReader(strings.NewReader(prefix), tail))} + defer func() { _ = resp.Body.Close() }() + usage, err := call.call(resp, c) + require.Error(t, err) + if failure == "event_limit" { + require.ErrorIs(t, err, errSSETransportLimit) + } + if failure == "cancel" { + require.ErrorIs(t, err, context.Canceled) + } + require.Equal(t, 3, usage) + if !call.stream { + require.Equal(t, http.StatusBadGateway, rec.Code) + } + require.NotContains(t, rec.Body.String(), "response.completed") + require.NotContains(t, rec.Body.String(), "data: [DONE]") + }) + } + } +} + +func TestImageStreamLimitDoesNotFinalizePendingTerminal(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, async := range []bool{false, true} { + for _, oauth := range []bool{false, true} { + name := "direct" + if oauth { + name = "responses" + } + if async { + name += "_async" + } else { + name += "_sync" + } + t.Run(name, func(t *testing.T) { + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 1024, SSEQueueMaxBytes: 128}} + if async { + cfg.Gateway.ImageStreamDataIntervalTimeout = 1 + } + svc := &OpenAIGatewayService{cfg: cfg} + wire := "data: {\"type\":\"image_generation.completed\",\"b64_json\":\"AA==\"}\n" + if oauth { + wire = "data: {\"type\":\"response.completed\",\"response\":{\"output\":[{\"type\":\"image_generation_call\",\"result\":\"AA==\"}]}}\n" + } + wire += ":" + strings.Repeat("x", 2048) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(wire))} + defer func() { _ = resp.Body.Close() }() + var err error + if oauth { + _, _, _, _, err = svc.handleOpenAIImagesOAuthStreamingResponse(resp, c, time.Now(), "b64_json", "image_generation", "gpt-image-2") + } else { + _, _, _, _, err = svc.handleOpenAIImagesStreamingResponse(resp, c, time.Now(), &OpenAIImagesRequest{Model: "gpt-image-2", ResponseFormat: "b64_json"}) + } + require.ErrorIs(t, err, errSSETransportLimit) + require.NotContains(t, rec.Body.String(), "image_generation.completed") + require.NotContains(t, rec.Body.String(), "response.completed") + }) + } + } +} diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 472046b047..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 } @@ -861,6 +865,7 @@ var ProviderSet = wire.NewSet( ProvideAuthService, NewPasskeyService, NewUserService, + NewMCPOAuthService, ProvideAPIKeyService, ProvideAPIKeyAuthCacheInvalidator, ProvideAuthCacheInvalidationWorker, diff --git a/backend/internal/web/embed_on.go b/backend/internal/web/embed_on.go index d16b1c4d80..03e5e5f50e 100644 --- a/backend/internal/web/embed_on.go +++ b/backend/internal/web/embed_on.go @@ -355,6 +355,9 @@ func tryServeOverrideFile(c *gin.Context, overrideDir, cleanPath string) bool { func shouldBypassEmbeddedFrontend(path string) bool { trimmed := strings.TrimSpace(path) return strings.HasPrefix(trimmed, "/api/") || + trimmed == "/.well-known/oauth-protected-resource" || + trimmed == "/.well-known/oauth-protected-resource/api/v1/mcp" || + trimmed == "/.well-known/oauth-authorization-server" || strings.HasPrefix(trimmed, "/v1/") || strings.HasPrefix(trimmed, "/v1beta/") || strings.HasPrefix(trimmed, "/backend-api/") || diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go index 965ee6cb0e..75dac764fb 100644 --- a/backend/internal/web/embed_test.go +++ b/backend/internal/web/embed_test.go @@ -528,6 +528,9 @@ func TestFrontendServer_Middleware(t *testing.T) { "/antigravity/test", "/setup/init", "/health", + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/api/v1/mcp", + "/.well-known/oauth-authorization-server", "/responses", "/responses/compact", "/chat/completions", @@ -827,6 +830,9 @@ func TestServeEmbeddedFrontend(t *testing.T) { "/antigravity/test", "/setup/init", "/health", + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/api/v1/mcp", + "/.well-known/oauth-authorization-server", "/responses", "/responses/compact", "/chat/completions", diff --git a/backend/migrations/249_mcp_oauth.sql b/backend/migrations/249_mcp_oauth.sql new file mode 100644 index 0000000000..8ba1595a7f --- /dev/null +++ b/backend/migrations/249_mcp_oauth.sql @@ -0,0 +1,44 @@ +-- OAuth clients use public-client authorization code + S256 PKCE. No client +-- secrets, authorization codes, access tokens, or refresh tokens are stored raw. +-- Client registration writes nothing: the client ID is signed and carries its +-- own metadata. Rows are created only when a user approves a client, and each +-- grant keeps the client name shown at consent. +CREATE TABLE IF NOT EXISTS mcp_oauth_grants ( + id VARCHAR(43) PRIMARY KEY, + client_id TEXT NOT NULL, + client_name VARCHAR(100) NOT NULL, + user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + token_version BIGINT NOT NULL, + resource TEXT NOT NULL, + scope VARCHAR(16) NOT NULL CHECK (scope IN ('user', 'admin')), + read_only BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + last_used_at TIMESTAMPTZ, + revoked_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_mcp_oauth_grants_user_created ON mcp_oauth_grants(user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_mcp_oauth_grants_expiry ON mcp_oauth_grants(expires_at); + +CREATE TABLE IF NOT EXISTS mcp_oauth_codes ( + code_hash VARCHAR(64) PRIMARY KEY, + grant_id VARCHAR(43) NOT NULL REFERENCES mcp_oauth_grants(id) ON DELETE CASCADE, + client_id TEXT NOT NULL, + redirect_uri TEXT NOT NULL, + resource TEXT NOT NULL, + code_challenge VARCHAR(43) NOT NULL, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_mcp_oauth_codes_grant ON mcp_oauth_codes(grant_id); + +-- Consumed refresh digests remain until the grant is pruned, allowing a replay +-- to revoke the entire family, including access tokens issued after rotation. +CREATE TABLE IF NOT EXISTS mcp_oauth_credentials ( + key_hash VARCHAR(64) PRIMARY KEY, + grant_id VARCHAR(43) NOT NULL REFERENCES mcp_oauth_grants(id) ON DELETE CASCADE, + kind VARCHAR(8) NOT NULL CHECK (kind IN ('access', 'refresh')), + expires_at TIMESTAMPTZ NOT NULL, + used_at TIMESTAMPTZ +); +CREATE INDEX IF NOT EXISTS idx_mcp_oauth_credentials_grant ON mcp_oauth_credentials(grant_id); diff --git a/deploy/.env.example b/deploy/.env.example index fa10e83e79..0e8ce5304e 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -30,6 +30,12 @@ UPDATE_GITHUB_TOKEN= # Return Server-Timing for authenticated requests made by the Admin web UI ENABLE_SERVER_TIMING=false +# Canonical public MCP endpoint for OAuth discovery, e.g. https://example.com/api/v1/mcp. +# 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 # or digests for repeatable operator-managed deployments. APPLE_CONTAINER_SUB2API_IMAGE=weishaw/sub2api:latest diff --git a/deploy/EDGE_SECURITY.md b/deploy/EDGE_SECURITY.md index 5e9ab10fb8..0d4581ecaa 100644 --- a/deploy/EDGE_SECURITY.md +++ b/deploy/EDGE_SECURITY.md @@ -1,8 +1,8 @@ # Edge and HTTP Ingress Security -Sub2API supports long-lived SSE and WebSocket requests. Protect the request -ingress without imposing a response `WriteTimeout`: a write deadline would -terminate healthy long generations and streams. +Sub2API supports long-lived SSE and WebSocket requests. Protect request ingress +and individual socket operations without imposing a fixed timeout on the entire +response. Healthy generations can remain open while an upstream is thinking. ## Application defaults @@ -15,6 +15,50 @@ terminate healthy long generations and streams. image, video, and batch-image endpoints. - `gateway.text_max_body_size: 33554432` limits the known pure-text `/embeddings` and `/alpha/search` endpoints to 32 MiB. +- `gateway.request_body_memory_budget_bytes: 1073741824` shares a 1 GiB + buffering budget across gateway routes and aliases. Chunk allocations, the + contiguous body copy, decompressed output, JSON normalization, and a Zstd + decoder reservation are charged before allocation. Each phase releases the + intermediate allocations it no longer references: chunks after assembly, + compressed input and decoder workspace after decoding, and owned input after + normalization. The final body allocation stays charged until the handler + returns, including throughout a long SSE response. A preread buffer that may + still be referenced by middleware stays charged alongside a normalized copy. + Exhaustion returns 503 with `Retry-After`; a single-request + size violation remains 413. Set this budget to fit the instance's memory, + leaving headroom for connections, conversion state, caches and GC. This is + conservative ingress accounting, not a hard bound on total heap or RSS. +- Compressed request output is capped at 64 MiB, with overflow rejected rather + than truncated. Zstd additionally has an 8 MiB window cap and one decoder + worker per request. +- `gateway.request_body_read_timeout_seconds: 120` bounds a stalled body read; + `gateway.downstream_write_timeout_seconds: 120` bounds each write/flush. + Successful operations clear their deadline, so upstream thinking does not + consume a whole-response time budget. Zero disables the corresponding limit. +- `gateway.max_line_size: 524288000` preserves the 500 MiB SSE line default + required by large base64 4K images, image-generation output and multi-image + responses. Upgrading does not silently lower this compatibility limit. + `sse_event_max_bytes: 0` inherits that cap for each complete event and + `sse_event_max_lines: 4096` also bounds streams of short lines without a blank + delimiter. `sse_queue_max_bytes: 8388608` bounds queued payload bytes; a line + larger than 8 MiB can occupy the queue alone, up to the line/event cap. + The consumer's current line and producer's scanner/read buffer are additional + bounded storage. The 8 MiB queue budget does not reduce the maximum size of + one image frame. Lower line/event limits only when the supported models and + output sizes fit them. Explicit event byte/line settings also apply to Grok + billing-ping and client-tool prefilters. +- Detached HTTP upstream attempts may continue collecting late billing usage + after client cancellation, but only for a finite drain window. The window + follows the stream data interval timeout (180 seconds by default). OpenAI + image API-key/OAuth forwarding uses the image timeout (900 seconds by + default); Grok media retains the general drain timeout. Incoming pings do not + restart the window. + This replaces the previously unlimited post-disconnect drain: when the + window expires, the attempt is cancelled and only usage observed before + cancellation is available for settlement. Final usage arriving later may be + lost even if the provider continues generating and charging. Disabling the + stream idle timeout does not disable this drain safety limit (180 seconds; + OpenAI image API-key/OAuth forwarding retains a 900-second fallback). - H2C defaults to 50 concurrent streams per connection, a 2 MiB connection upload window, and a 512 KiB stream upload window. - Invalid credential abuse is limited in process by trusted client IP (IPv6 @@ -22,10 +66,56 @@ terminate healthy long generations and streams. per-instance safety net; multi-instance enforcement still belongs at the load balancer, CDN, or WAF. -Do not add a single application-wide request semaphore: an SSE request may -legitimately occupy it for many minutes. Apply connection and unauthenticated -request controls at the edge; authenticated user/API-key concurrency remains -the application's responsibility. +Do not replace these controls with a single application-wide request semaphore: +an SSE request may legitimately occupy it for many minutes. Apply connection +and unauthenticated request controls at the edge; authenticated user/API-key +concurrency and buffered request bytes remain the application's responsibility. + +Compatibility session caches (digest sessions, Responses continuation bindings +and Anthropic digest bindings) each have fixed limits of 16,384 entries and +32 MiB of accounted storage, including 512 bytes of bookkeeping per entry. +These limits are not currently configurable. The least recently used entry is +evicted when either limit is reached, even if its TTL has not expired; a TTL is +therefore not a guarantee that a continuation binding remains available. Active +expiry scans run at most once a minute while the cache is nonempty, and shutdown +stops cleanup. Monitor 503 body-budget rejections, response-too-large errors, +allocation rate, retained heap after GC, goroutine counts, usage-worker queues +and database connection waits when tuning capacity. Notification queues may +skip best-effort messages on overload or shutdown and log a dropped count; +committed-charge persistence is not dropped by that notification policy. +When the platform-quota flusher is disabled, its quota mirror update now runs +inside the usage task with a separate five-second database deadline. Failures +remain counted and logged for reconciliation; this path has no durable automatic +retry. The main charge is committed idempotently before this mirror update. +With the default `gateway.usage_record.overflow_policy: sync`, a full usage +queue executes the task in the submitting handler. Database latency can +therefore delay usage submission and handler completion by up to the separate +five-second quota persistence attempt, in addition to the other usage work. +The configured worker count is not a hard global limit on database concurrency. + +## Sizing the request-body budget + +Size `request_body_memory_budget_bytes` for the final body allocations retained +by all active requests, plus peak workspace for requests currently being read, +decoded or normalized. Streaming duration increases the number of retained +bodies even after their upload has finished. The budget is not just the number +of simultaneous uploads, and releasing an allocation's charge does not force Go +to reclaim that unreachable memory immediately. + +For example, 200 long-lived streams retaining 4 MiB each account for about +800 MiB before new uploads and decoding. Another 32 concurrent Zstd decoders +can reserve 256 MiB of window space alone, exceeding the default 1 GiB budget +before their input/output buffers are counted. Increase the budget for such a +workload only with sufficient instance memory, or reduce concurrency/request +sizes. Leave separate memory headroom for SSE frames (which may be larger than +the queue budget), conversion state, caches, connections and GC. Setting the +budget to `0` disables ingress memory admission rather than limiting RSS. + +Legacy Read tool-call completion still validates the growing JSON argument +prefix. Incremental storage removes repeated prefix allocations, but validation +CPU can remain quadratic for large arguments delivered in many small deltas. +Measure this separately from allocation savings; cumulative bytes allocated in +benchmarks are not retained heap or RSS. ## Trusted client IPs diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index d4ccebd235..fe63434873 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -120,6 +120,19 @@ cors: # 允许携带凭证(cookies/授权头)。不能与 "*" 通配符同时使用。 allow_credentials: true +# ============================================================================= +# MCP OAuth Configuration / MCP OAuth 配置 +# ============================================================================= +mcp: + # Canonical public MCP endpoint, e.g. https://example.com/api/v1/mcp. + # 固定的 MCP 对外地址,例如 https://example.com/api/v1/mcp。 + # 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: "" + # ============================================================================= # Security Configuration # 安全配置 @@ -241,6 +254,15 @@ gateway: # Max request body size in bytes (default: 256MB) # 请求体最大字节数(默认 256MB) max_body_size: 268435456 + # Per-instance ingress allocation budget. Unreferenced intermediates are released after each phase. + # Final bodies (and still-referenced preread buffers) remain charged until the handler returns. + # Include all concurrent long-lived requests and upload/decode workspace; see EDGE_SECURITY.md. + # 实例级请求体分配预算;超出返回 503 + Retry-After,0 禁用。按容器内存预留业务/GC空间。 + request_body_memory_budget_bytes: 1073741824 + # Individual socket read/write idle deadlines, not the entire SSE lifetime; 0 disables. + # 上传单次读取、下游单次写入/flush 超时(秒),不会限制正常长流的总时长;0 禁用。 + request_body_read_timeout_seconds: 120 + downstream_write_timeout_seconds: 120 # Pure-text endpoint body limit (embeddings and alpha/search), default 32 MiB. # 纯文本端点请求体上限(embeddings、alpha/search),默认 32 MiB。 text_max_body_size: 33554432 @@ -526,9 +548,16 @@ gateway: # Max image requests waiting in this process when overflow_mode=wait, 0=unlimited # wait 模式当前进程允许排队等待的图片请求数,0=不限制 max_waiting_requests: 100 - # SSE max line size in bytes (default: 40MB) - # SSE 单行最大字节数(默认 40MB) - max_line_size: 41943040 + # SSE max line size in bytes (default: 500 MiB, including large inline 4K images) + # SSE 单行最大字节数(默认 500 MiB,兼容含大尺寸 4K 图片的响应) + max_line_size: 524288000 + # Queue byte budget. One larger line may be transferred alone, bounded by max_line_size. + # 队列按字节限流;超过预算的单行只能独占传递,仍受 max_line_size 硬上限约束。 + sse_queue_max_bytes: 8388608 + # Accumulated event byte limit (0 inherits max_line_size) and nonempty line limit. + # 事件累计字节上限(0 继承单行上限)与行数上限;持续短行也不能无界积累。 + sse_event_max_bytes: 0 + sse_event_max_lines: 4096 # Log upstream error response body summary (safe/truncated; does not log request content) # 记录上游错误响应体摘要(安全/截断;不记录请求内容) log_upstream_error_body: true diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml index 45789f48ab..54953ba2f8 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -29,6 +29,7 @@ services: - SERVER_PORT=8080 - SERVER_MODE=debug - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false} + - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index 32bc439f4d..6ca816a548 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -54,6 +54,7 @@ services: - SERVER_PORT=8080 - SERVER_MODE=${SERVER_MODE:-release} - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false} + - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index fe9619df15..6711bcbdb4 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -40,6 +40,7 @@ services: - SERVER_PORT=8080 - SERVER_MODE=${SERVER_MODE:-release} - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false} + - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 84c98643ea..51e3cb5ded 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -50,6 +50,7 @@ services: - SERVER_PORT=8080 - SERVER_MODE=${SERVER_MODE:-release} - ENABLE_SERVER_TIMING=${ENABLE_SERVER_TIMING:-false} + - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-} - RUN_MODE=${RUN_MODE:-standard} - SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS=${SIMPLE_MODE_AUTO_CREATE_DEFAULT_GROUPS:-} - SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED=${SIMPLE_MODE_KEY_RATE_LIMIT_ENABLED:-false} diff --git a/docs/admin-api-keys.md b/docs/admin-api-keys.md index c24627f9b6..e275adcc3f 100644 --- a/docs/admin-api-keys.md +++ b/docs/admin-api-keys.md @@ -1,6 +1,6 @@ -# 受限管理员 API 密钥 +# 管理员 API 密钥 -受限管理员密钥用于自动化管理指定资源。它与调用模型使用的用户 API Key 不同,也不等同于管理员登录会话。通过请求头 `x-api-key` 使用;只有权限目录明确登记的接口和操作才会开放,新增接口不会自动继承权限。 +受限管理员密钥用于自动化管理指定资源。它与调用模型使用的用户 API Key 不同,也不等同于管理员登录会话。通过请求头 `x-api-key` 使用。默认采用受限模式:只有权限目录明确登记的接口和操作才会开放,新增接口不会自动继承权限。确需旧版完整管理能力时,可显式开启下述全权兼容模式。 ## 创建与配置 @@ -12,7 +12,43 @@ 创建、更新、停用/启用、轮换、撤销和删除记录均沿用系统二次验证流程;是否弹出验证由系统的 step-up 配置和当前授权状态决定。密钥生命周期接口只接受管理员 JWT 会话,受限密钥不能管理自身或创建其他管理员密钥。 -已有旧版全权密钥时,页面显示兼容折叠区,可轮换或删除。页面不再提供新建旧版全权密钥的入口;应将自动化任务迁移到受限密钥。 +已有旧版全权密钥时,页面显示兼容折叠区,可轮换或删除。页面不再提供新建旧版单一密钥的入口;新密钥可选择受限模式或需确认的全权兼容模式。 + +## 全权兼容模式 + +每枚密钥可单独开启「全权访问(兼容旧版管理员 Key)」,默认关闭。开启前弹窗说明影响,必须输入确认文字;取消不会改变授权。关闭后恢复原资源规则,启用全权期间这些规则只保留配置、不参与限制。 + +- 全权模式使用原管理处理器及完整响应,可访问全部管理资源和未来新增的管理接口,包括敏感数据、账户及财务配置。它不是普通权限目录的「全选」。 +- `policy.full_access` 控制模式。创建全权密钥或从受限切换到全权时,请求必须显式携带 `confirm_full_access: true`;服务端检查确认,确认值不保存为授权。 +- 密钥管理接口始终只接受管理员 JWT 会话。系统启用 step-up 时,要求二次验证的接口继续拒绝机器密钥;全权模式不会绕过这些要求,也不替代模型调用使用的用户 API Key。 +- 有效期、来源 IP、启停、轮换、永久撤销、按 Key 限流及审计继续生效。审计包含全权状态,模式修改记录变更前后状态。 +- 并发编辑可能返回 `ADMIN_KEY_CONFLICT`,应重新读取当前配置后编辑,不要盲目覆盖。相同幂等键跨密钥或授权策略重用会冲突,不能重放其他权限下的结果或重复执行财务操作。 + +## 自动化查询与操作权限 + +以下账户权限均放在资源规则中,按同一规则的分组、账户类型和平台校验;分组权限只按分组和平台校验。升级不会给已有密钥自动增加这些权限。 + +| 权限 | 用途 | +| --- | --- | +| `accounts.identity.read` | 账户邮箱、套餐、订阅到期及创建时间;列表/详情仍需 `accounts.read` | +| `accounts.usage.read` | 单个及批量账户额度查询、主动刷新,以及列表/详情中的周额度快照 | +| `accounts.stats.read` | 单个/批量今日统计与历史统计,包含请求数、Token 和费用 | +| `accounts.options.write` | 创建 OpenAI OAuth 账户时写入已列明的身份和连接选项 | +| `accounts.rate.write` | 创建/修改账户计费倍率 | +| `groups.list.read` | 所选分组的 ID、名称、平台与状态,不含费率或模型配置 | +| `groups.capacity.read` | 所选启用分组的容量;统计整个分组,不按账户类型裁剪 | +| `openai.quota.read` | OpenAI 额度、点数及重置次数查询和展示快照刷新 | +| `openai.quota.reset` | 执行 OpenAI 上游额度重置,可能消耗可用次数 | +| `openai.referrals.read` | 查询邀请资格与名额并刷新展示快照 | +| `openai.referrals.invite` | 实际发送邀请;不由邀请查询权限附带授予 | + +`openai.tokens.refresh` 是独立的**全站权限**:仅刷新调用方提交的 OpenAI 令牌并返回新令牌,不读取服务器已有账户凭证。指定代理必须存在、启用且未过期;无效代理不会静默回退为直连。它与 `accounts.refresh`(刷新已保存的授权账户凭证)不同。 + +账户列表接受 `group` 筛选,省略或 `group=` 表示不指定分组,`-1` 表示未分组;筛选不会扩大授权范围。分页返回 `items/total/page/page_size/pages`。周额度是当前快照(`codex_usage_updated_at`、`codex_7d_used_percent`、`codex_7d_reset_at`),不是历史事件记录;缺失不伪装为零用量。 + +批量查询一次接受 1 至 100 个账户 ID,先验证所有账户范围,再读取统计、缓存或访问上游。混入未授权账户时整批拒绝。受限 OpenAI 额度刷新只调用额度查询接口,不发送模型探测请求。只读额度权限不授权消耗重置次数、发送邀请或恢复账户状态及调度。影子账户借用母账户凭证时,母账户也必须有对应操作权限。重置或发送邀请后的响应仍分别检查额度或邀请读取权限,身份信息另行验权;响应不会返回完整凭证、任意 `extra` 或原始上游错误。 + +`accounts.options.write` 仅开放创建 OpenAI OAuth 账户时的 `extra.email`、`openai_oauth_responses_websockets_v2_mode`、`openai_oauth_responses_websockets_v2_enabled` 和 `openai_long_context_billing_enabled`,不能任意写入 `extra`、额度快照、影子关系或声明隐私设置成功。为兼容已有客户端,字符串 `privacy_mode` 入参会被移除,隐私状态仍由服务端原流程确认。创建倍率独立需要 `accounts.rate.write`,写入凭证及身份元数据仍遵循对应凭证权限。 ## 账户规则如何匹配 diff --git a/docs/agent-resource-safety.md b/docs/agent-resource-safety.md new file mode 100644 index 0000000000..23e4526f58 --- /dev/null +++ b/docs/agent-resource-safety.md @@ -0,0 +1,15 @@ +# Agent rules for concurrency and resource safety + +These rules apply when changing request ingestion, HTTP/SSE transport, protocol conversion, asynchronous usage/billing work, notifications, or in-memory caches. They supplement the repository protocol translation and billing rules. + +- Never capture `*gin.Context`, a response writer, or a pooled/mutable request object in work that can outlive the handler. Compute immutable billing, routing, model, and logging snapshots before enqueueing. `c.Copy()` is not a substitute for explicit ownership of referenced data. +- Request buffering must use the shared ingress memory budget before allocating, including unknown-length uploads, decompression, normalization, and contiguous copies. Per-user concurrency acquired after reading a body does not protect ingress. Distinguish temporary capacity exhaustion (503 with retry guidance) from a per-request size violation (413); never turn either into a successful or truncated request. +- Bound decompressor window/memory and internal concurrency as well as decoded output. Read one byte beyond an output limit to detect overflow. Do not assume `io.LimitReader` outside a decoder bounds its internal allocations. +- Bound streaming data at the line, accumulated event, and queued-byte levels. A channel capacity limits item count, not memory. Document any single-item exception and its hard size cap. A sequence of short lines, comments, or heartbeats must not bypass event bounds or cancellation/drain budgets. +- Use per-operation upload/read and downstream write/flush deadlines for long-lived HTTP streams. Do not impose a short deadline on the entire healthy stream. After client cancellation, any upstream drain for late billing usage must have a finite budget and release its body, timers, goroutines, and concurrency slots. Resource limits and truncated streams must never manufacture a successful terminal event. +- No unbounded per-request background goroutines or queues for persistence, notifications, or retries. Reuse a bounded executor, define overload behavior, give I/O an explicit deadline, and integrate shutdown. `context.WithoutCancel` alone is not an I/O timeout. Financial work must not be silently dropped; notification work may be best effort with observable drops. +- In-memory caches need active expiry and explicit entry/byte bounds. A timestamp checked only on lookup does not reclaim abandoned keys. Avoid one timer/goroutine per key and unbounded scans or network I/O under shared locks; tie background cleanup to service shutdown. +- Keep work proportional to input/output size. Avoid growing-string concatenation per delta, repeated whole-prefix copies/hashes, and repeated full JSON decoding on hot paths. Preserve protocol compatibility through RelayKit under the rules above; performance work does not authorize a local translator or changing billing semantics. +- For an already-active legacy converter, storage-only maintenance must preserve the same mappings, emitted events, state transitions, signatures, usage and public snapshots. Retain all compatibility regressions and verify size-scaling allocations. This does not authorize new translation behavior, restored fallbacks, or expanded legacy coverage; those changes still require RelayKit first. +- Treat zero-copy strings/slices, pooled buffers, and cached objects as immutable while borrowed. Do not return storage to a pool, mutate it, or retain a small slice of a large buffer across asynchronous boundaries without an explicit ownership/copy policy. +- For changes to these boundaries, add focused regression coverage for overload, cancellation, expiry, and shutdown as applicable; run affected tests with `-race`. Use representative size-scaling benchmarks for algorithm changes and report cumulative allocations separately from retained heap/RSS. Keep configuration defaults, validation, and deployment examples consistent, and regenerate Wire after lifecycle/DI changes. diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000000..c8d7532b0e --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,171 @@ +# 平台管理 MCP(OAuth) + +平台内置远程 MCP 服务,通过 **Streamable HTTP + OAuth 授权码 / S256 PKCE** 接入。客户端只需配置 MCP 地址;连接时打开浏览器登录平台,再明确同意个人或管理员范围、只读或读写权限。无需创建、复制或保存静态令牌。 + +## 部署 + +MCP 默认关闭。只有显式配置稳定、可信的公开 MCP 地址后,才会开放 MCP 资源端点、OAuth 发现及客户端注册接口,侧栏也才会显示 **MCP 接入**。例如: + +```sh +MCP_PUBLIC_URL=https://api.example.com/api/v1/mcp +``` + +也可以在配置文件中设置: + +```yaml +mcp: + public_url: https://api.example.com/api/v1/mcp +``` + +地址必须是站点根路径下的 `/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 白名单。 + +## 连接 + +1. 在支持远程 MCP OAuth 的客户端中添加 `https://api.example.com/api/v1/mcp`。 +2. 客户端发现授权服务器,注册公共客户端,并自动生成 PKCE 参数。 +3. 浏览器打开平台登录与授权页面。检查应用名称和返回地址,选择授权范围及权限,再点击同意。 +4. 客户端自动交换授权码并刷新访问令牌。 + +适用于使用 `mcpServers` 和 `url` 配置的客户端: + +```json +{ + "mcpServers": { + "sub2api": { + "url": "https://api.example.com/api/v1/mcp" + } + } +} +``` + +不同客户端的配置结构可能不同;传输使用 Streamable HTTP,认证使用 OAuth。平台不接受模型调用 API Key、浏览器 JWT、管理员 API Key 或静态 MCP 令牌作为 MCP 凭证。 + +## 授权与撤销 + +默认授权为**个人范围、只读**。管理员可以在明确同意时选择管理员范围;启用平台敏感操作二次验证时,授予管理员范围同样需要 step-up。授予**管理员范围的读写**权限时,无论是否启用该开关,都必须已开启 TOTP 并完成一次 step-up 验证。 + +- **个人范围**:只操作当前用户的数据,即使授权人是管理员也不会开放管理工具。 +- **管理员范围**:仅管理员可授予,可使用目录内管理工具及自己的个人工具。 +- **只读**:不列出写工具,直接调用写工具同样会被拒绝。 +- **读写**:开放对应范围内的修改工具,包括删除 API Key、调整余额、停用账户和撤销订阅等操作。 + +OAuth scope 为 `mcp`,实际工具权限由浏览器中确认的授权范围与读写选项决定。刷新不会扩大权限,改变权限需要重新授权。客户端应用名来自注册请求,并不代表平台验证了该应用;授权页面同时显示其回调地址。 + +授权码有效期 5 分钟且只能兑换一次。访问令牌有效期最多 10 分钟;授权及刷新令牌最长 30 天,刷新令牌每次使用都会轮换。重复使用授权码或已消费的刷新令牌会撤销该授权。服务端仅保存凭证摘要。 + +登录平台后,侧栏 **MCP 接入**(`/settings/mcp`)可查看并撤销已授权应用。每用户最多 20 个有效授权。撤销、密码或登录标识变更、用户停用都会阻止后续调用及刷新;管理员失去角色后,其管理员授权也失效。“撤销全部会话”会同时撤销该用户的全部 MCP 授权。停用用户会持久撤销其全部授权,取消管理员角色会持久撤销其管理员授权,之后重新启用或重新授予角色也不会恢复旧授权。页面不显示访问或刷新令牌,MCP 工具无法自行授予新授权。 + +## 工具目录 + +客户端通过 `tools/list` 获取当前 OAuth 授权可用的工具及完整参数说明。 + +| 范围 | 工具 | 用途 | +| --- | --- | --- | +| 个人 | `user_get_profile`、`user_get_platform_quotas` | 查看个人资料、余额、限额和平台额度 | +| 个人 | `user_list_groups`、`user_list_channels` | 查看可用分组、渠道及模型 | +| 个人 | `user_list_api_keys`、`user_get_api_key` | 查询自己的 API Key 元数据和限额 | +| 个人 | `user_create_api_key`、`user_update_api_key`、`user_delete_api_key` | 创建、修改、停用或删除自己的 API Key | +| 个人 | `user_list_usage`、`user_get_usage_stats`、`user_get_dashboard` | 查询请求明细、用量统计和仪表盘 | +| 个人 | `user_list_subscriptions`、`user_get_subscription_summary` | 查看自己的订阅和剩余额度 | +| 管理员 | `admin_get_dashboard`、`admin_get_ops_overview` | 平台经营统计和运维概览 | +| 管理员 | `admin_list_users`、`admin_get_user`、`admin_update_user`、`admin_update_user_balance` | 查询用户,调整状态、限额、分组权限和余额 | +| 管理员 | `admin_list_groups`、`admin_get_group`、`admin_create_group`、`admin_update_group`、`admin_delete_group` | 管理分组基础配置、价格倍率、额度和模型白名单 | +| 管理员 | `admin_list_accounts`、`admin_get_account`、`admin_update_account`、`admin_set_account_schedulable`、`admin_clear_account_error` | 管理上游账户的状态、调度、并发、优先级和有效期 | +| 管理员 | `admin_list_usage`、`admin_get_usage_stats` | 查询全站请求明细和用量统计 | +| 管理员 | `admin_list_subscriptions`、`admin_get_subscription`、`admin_assign_subscription`、`admin_extend_subscription`、`admin_revoke_subscription` | 查询、分配、延长和撤销订阅 | + +工具只开放明确列出的字段;不提供任意 HTTP 请求、任意 URL、密码/角色修改、身份绑定、上游凭证管理、备份恢复或支付工具。普通查询和修改结果会去除 API Key、上游令牌等凭证。`user_create_api_key` 的创建结果包含新 API Key,便于配置应用;不要将该结果公开分享。 + +现有业务权限、资源归属、平台模式限制、管理合规确认、限流和操作审计继续生效。模型返回的建议不会绕过这些规则。MCP 的每次工具调用(包括只读查询)都会写入操作审计,认证方式为 `mcp_oauth`,并附带 `mcp_grant_id` 和 `mcp_tool`。 + +## 参数示例 + +工具参数使用 `id`、`query`、`body` 三种字段。路径中的资源 ID 放在顶层 `id`,查询条件放在 `query`,修改字段放在 `body`。未提供的更新字段保持原值;未知字段会被拒绝。分页从 1 开始,每页最多 100 条。 + +创建 API Key、调整用户余额和延长订阅还要求顶层 `idempotency_key`,可使用 UUID。同一次操作重试时保持该值和参数一致;新的操作使用新值。平台沿用已有幂等机制,避免超时重试造成重复创建或重复扣加款。 + +查询自己的用量: + +```json +{ + "name": "user_list_usage", + "arguments": { + "query": { + "page": 1, + "page_size": 20, + "start_date": "2026-10-01", + "end_date": "2026-10-28", + "timezone": "Asia/Shanghai" + } + } +} +``` + +日期格式为 `YYYY-MM-DD`,起止日期均包含在统计范围内;时区使用 IANA 名称。管理员自定义统计范围请同时提供起止日期。 + +创建一个有额度和有效期的个人 API Key: + +```json +{ + "name": "user_create_api_key", + "arguments": { + "idempotency_key": "create-development-key-20261028-1", + "body": { + "name": "development", + "group_id": 12, + "quota": 10, + "expires_in_days": 7 + } + } +} +``` + +先使用 `user_list_groups` 确认可用分组 ID。上述操作要求个人或管理员范围的读写授权。 + +暂停一个上游账户的调度: + +```json +{ + "name": "admin_set_account_schedulable", + "arguments": { + "id": 42, + "body": { "schedulable": false } + } +} +``` + +余额调整和订阅分配会改变实际计费权益。发送前确认目标和金额/天数;客户端超时后先查询结果,避免盲目重复调用。 + +## 协议与发现 + +| 端点 | 用途 | +| --- | --- | +| `GET /.well-known/oauth-protected-resource/api/v1/mcp` | RFC 9728 资源元数据;根路径 `/.well-known/oauth-protected-resource` 也可发现 | +| `GET /.well-known/oauth-authorization-server` | RFC 8414 授权服务器元数据 | +| `POST /api/v1/mcp/oauth/register` | RFC 7591 公共客户端动态注册,返回 HTTP 201 | +| `/oauth/mcp/authorize` | 前端登录与明确同意页面 | +| `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 自动抓取。注册请求体不超过 4 KiB;`client_name` 最多 100 个字符,且不得包含控制字符、双向文本控制符或零宽字符等不可见字符。 + +授权请求和授权码兑换必须携带精确匹配 MCP 地址的 `resource`。刷新可省略 `resource`,此时沿用原授权;传入不同资源会被拒绝。`state` 会原样返回客户端。授权码与客户端、回调、资源和 PKCE 绑定;客户端应安全保管 verifier 和刷新令牌。 + +查看发现信息: + +```sh +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 请求只能包含一个 JSON-RPC 对象,JSON-RPC 批量请求(包括未声明 `MCP-Protocol-Version` 的旧版本请求)一律返回 400。每次 HTTP 请求重新校验授权,响应禁止缓存。工具结果以单个文本块返回 JSON `{"http_status": …, "result": …}`,不再重复写入 `structuredContent`;编码后超过 2 MiB 的结果会被拒绝,请缩小查询范围或分页大小。业务 API 失败以工具结果 `isError: true` 返回,原 HTTP 状态位于 `http_status`。工具执行限制 30 秒并传递客户端断开取消;写操作超时后应查询状态再决定是否重试。 + +`/api/v1/mcp` 在认证前先按客户端 IP 限流(每分钟 600 次),认证后再使用独立的按用户入口限流桶;每个实际工具调用只消耗一次管理面全局额度,聚合统计仍受 Heavy 限流。授权的最近使用时间每分钟最多写入一次。动态注册、兑换和撤销接口有独立 IP 限流。上述 IP 限流把同一 IPv6 /64 网段视为一个客户端,Redis 不可用时拒绝请求。 + +## 开发 + +工具目录位于 `backend/internal/managementmcp/catalog.go`。新增工具应绑定已有管理路由,使用封闭参数 schema,并覆盖权限、资源归属、参数边界及凭证脱敏测试。 + +OAuth 存储由 `249_mcp_oauth.sql` 创建。动态注册不写数据库:`client_id` 是服务端签名的无状态标识,自带客户端名称、回调 URI 摘要和 grant type,签名密钥首次使用时生成并保存在 `security_secrets`,多实例共享。只有用户同意授权后才写入授权记录,因此匿名注册不会占用存储,也没有可被占满的全站名额。每次新授权时有界清理过期 7 天以上的授权。浏览器使用 JWT 保护的 `/api/v1/user/mcp/config` 获取服务端配置的连接地址、`/api/v1/user/mcp/authorize` 预览/决定授权,以及 `/api/v1/user/mcp/grants` 列表、撤销接口。客户端协议端点返回标准 OAuth JSON,浏览器接口沿用平台响应格式。 diff --git a/frontend/package.json b/frontend/package.json index fa12747fa7..e42bcb03f8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -32,12 +32,12 @@ "vue": "^3.5.43", "vue-chartjs": "^5.3.0", "vue-draggable-plus": "^0.6.1", - "vue-i18n": "^9.14.5", + "vue-i18n": "^11.4.16", "vue-router": "^4.2.5", "xlsx": "^0.18.5" }, "devDependencies": { - "@intlify/message-compiler": "9.14.5", + "@intlify/message-compiler": "11.4.16", "@types/dompurify": "^3.0.5", "@types/file-saver": "^2.0.7", "@types/mdx": "^2.0.13", @@ -67,7 +67,8 @@ "postcss@<8.5.18": ">=8.5.18", "dompurify@<3.4.17": ">=3.4.17", "source-map-js@<1.2.2": ">=1.2.2", - "follow-redirects@<1.16.1": ">=1.16.1" + "follow-redirects@<1.16.2": ">=1.16.2", + "decode-uri-component@<0.5.1": ">=0.5.1" } } } diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml index d2714896a9..1bf73beac9 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -10,7 +10,8 @@ overrides: postcss@<8.5.18: '>=8.5.18' dompurify@<3.4.17: '>=3.4.17' source-map-js@<1.2.2: '>=1.2.2' - follow-redirects@<1.16.1: '>=1.16.1' + follow-redirects@<1.16.2: '>=1.16.2' + decode-uri-component@<0.5.1: '>=0.5.1' importers: @@ -65,8 +66,8 @@ importers: specifier: ^0.6.1 version: 0.6.1(@types/sortablejs@1.15.9) vue-i18n: - specifier: ^9.14.5 - version: 9.14.5(vue@3.5.43(typescript@5.6.3)) + specifier: ^11.4.16 + version: 11.4.16(vue@3.5.43(typescript@5.6.3)) vue-router: specifier: ^4.2.5 version: 4.6.4(vue@3.5.43(typescript@5.6.3)) @@ -75,8 +76,8 @@ importers: version: 0.18.5 devDependencies: '@intlify/message-compiler': - specifier: 9.14.5 - version: 9.14.5 + specifier: 11.4.16 + version: 11.4.16 '@types/dompurify': specifier: ^3.0.5 version: 3.2.0 @@ -626,17 +627,21 @@ packages: '@iconify/utils@3.1.0': resolution: {integrity: sha512-Zlzem1ZXhI1iHeeERabLNzBHdOa4VhQbqAcOQaMKuTuyZCpwKbC2R4Dd0Zo3g9EAc+Y4fiarO8HIHRAth7+skw==} - '@intlify/core-base@9.14.5': - resolution: {integrity: sha512-5ah5FqZG4pOoHjkvs8mjtv+gPKYU0zCISaYNjBNNqYiaITxW8ZtVih3GS/oTOqN8d9/mDLyrjD46GBApNxmlsA==} - engines: {node: '>= 16'} + '@intlify/core-base@11.4.16': + resolution: {integrity: sha512-xB8nMdMRLNx7b0zPvrHy0+N9uq9Vfi1aUxHqWgn2e2/TbjCKy8HfoFpnUXXxVP8I0p1ccd6LFSC3XsFjZ3vweA==} + engines: {node: '>= 22'} - '@intlify/message-compiler@9.14.5': - resolution: {integrity: sha512-IHzgEu61/YIpQV5Pc3aRWScDcnFKWvQA9kigcINcCBXN8mbW+vk9SK+lDxA6STzKQsVJxUPg9ACC52pKKo3SVQ==} - engines: {node: '>= 16'} + '@intlify/devtools-types@11.4.16': + resolution: {integrity: sha512-Bl7arICsKgwcSEQuZJun3swenN4jwSpg35lCpijFznYbW9GvkfH4wLxcI5+gz7d/EHqu66UT9CZDIdnQdgMAGg==} + engines: {node: '>= 22'} - '@intlify/shared@9.14.5': - resolution: {integrity: sha512-9gB+E53BYuAEMhbCAxVgG38EZrk59sxBtv3jSizNL2hEWlgjBjAw1AwpLHtNaeda12pe6W20OGEa0TwuMSRbyQ==} - engines: {node: '>= 16'} + '@intlify/message-compiler@11.4.16': + resolution: {integrity: sha512-p4lDWmBAsi3ja+PuEfPRavYyvqkYn/Upxz7UpnyI9LgIIy8XawcGIDzN+k99Z+99etO3HmDXGeTxnJIJGgSZ+g==} + engines: {node: '>= 22'} + + '@intlify/shared@11.4.16': + resolution: {integrity: sha512-xehmkbEgbbNh/V+d8r3hFup0ViaN29YTJSAfRr28C54rxjyZEO0RNQKqW7VVajj16gLdglotNjiq+sIVNtHGzw==} + engines: {node: '>= 22'} '@isaacs/cliui@8.0.2': resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} @@ -2285,8 +2290,8 @@ packages: decode-named-character-reference@1.3.0: resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==} - decode-uri-component@0.4.1: - resolution: {integrity: sha512-+8VxcR21HhTy8nOt6jf20w0c9CADrw1O8d+VZ/YzzCt4bJ3uBjw+D1q2osAB8RnpwwaeYBxy0HyKQxD5JBMuuQ==} + decode-uri-component@0.5.1: + resolution: {integrity: sha512-vWHQkXgg2cE3BB4rR0c+PYw9BCQzLoNIRMI7AunIkZst74tw/vpPp7VLoYtsR/cy1f55g3XDWUslfeCZjiZJyA==} engines: {node: '>=14.16'} deep-eql@5.0.2: @@ -2561,8 +2566,8 @@ packages: flatted@3.3.3: resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} - follow-redirects@1.16.1: - resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -4411,10 +4416,9 @@ packages: peerDependencies: eslint: '>=6.0.0' - vue-i18n@9.14.5: - resolution: {integrity: sha512-0jQ9Em3ymWngyiIkj0+c/k7WgaPO+TNzjKSNq9BvBQaKJECqn9cd9fL4tkDhB5G1QBskGl9YxxbDAhgbFtpe2g==} - engines: {node: '>= 16'} - deprecated: v9 and v10 no longer supported. please migrate to v11. about maintenance status, see https://vue-i18n.intlify.dev/guide/maintenance.html + vue-i18n@11.4.16: + resolution: {integrity: sha512-Kv9tp6iTmaAeOwop7hkAo28N1IBsbSVpnxyE26b6gqc4Q2E9Ke3ZHHA3oqqwS6/cYLT1henZU4etTaLQxrK98Q==} + engines: {node: '>= 22'} peerDependencies: vue: ^3.0.0 @@ -5032,17 +5036,23 @@ snapshots: '@iconify/types': 2.0.0 mlly: 1.8.2 - '@intlify/core-base@9.14.5': + '@intlify/core-base@11.4.16': dependencies: - '@intlify/message-compiler': 9.14.5 - '@intlify/shared': 9.14.5 + '@intlify/devtools-types': 11.4.16 + '@intlify/message-compiler': 11.4.16 + '@intlify/shared': 11.4.16 - '@intlify/message-compiler@9.14.5': + '@intlify/devtools-types@11.4.16': dependencies: - '@intlify/shared': 9.14.5 + '@intlify/core-base': 11.4.16 + '@intlify/shared': 11.4.16 + + '@intlify/message-compiler@11.4.16': + dependencies: + '@intlify/shared': 11.4.16 source-map-js: 1.2.2 - '@intlify/shared@9.14.5': {} + '@intlify/shared@11.4.16': {} '@isaacs/cliui@8.0.2': dependencies: @@ -6553,7 +6563,7 @@ snapshots: axios@1.20.0: dependencies: - follow-redirects: 1.16.1 + follow-redirects: 1.16.2 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -6969,7 +6979,7 @@ snapshots: dependencies: character-entities: 2.0.2 - decode-uri-component@0.4.1: {} + decode-uri-component@0.5.1: {} deep-eql@5.0.2: {} @@ -7295,7 +7305,7 @@ snapshots: flatted@3.3.3: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2: {} for-in@1.0.2: {} @@ -8705,7 +8715,7 @@ snapshots: query-string@9.3.1: dependencies: - decode-uri-component: 0.4.1 + decode-uri-component: 0.5.1 filter-obj: 5.1.0 split-on-first: 3.0.0 @@ -9609,10 +9619,11 @@ snapshots: transitivePeerDependencies: - supports-color - vue-i18n@9.14.5(vue@3.5.43(typescript@5.6.3)): + vue-i18n@11.4.16(vue@3.5.43(typescript@5.6.3)): dependencies: - '@intlify/core-base': 9.14.5 - '@intlify/shared': 9.14.5 + '@intlify/core-base': 11.4.16 + '@intlify/devtools-types': 11.4.16 + '@intlify/shared': 11.4.16 '@vue/devtools-api': 6.6.4 vue: 3.5.43(typescript@5.6.3) diff --git a/frontend/src/api/__tests__/admin.emailBlacklist.spec.ts b/frontend/src/api/__tests__/admin.emailBlacklist.spec.ts new file mode 100644 index 0000000000..1d9c44f736 --- /dev/null +++ b/frontend/src/api/__tests__/admin.emailBlacklist.spec.ts @@ -0,0 +1,50 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { get, post, put } = vi.hoisted(() => ({ + get: vi.fn(), + post: vi.fn(), + put: vi.fn() +})) + +vi.mock('@/api/client', () => ({ + apiClient: { get, post, put } +})) + +import { + getRegistrationEmailBlacklist, + updateRegistrationEmailBlacklist +} from '@/api/admin/settings' +import { batchDisable, findBlacklistedEmailUsers } from '@/api/admin/users' + +describe('admin email blacklist api', () => { + beforeEach(() => { + get.mockReset() + post.mockReset() + put.mockReset() + }) + + it('reads and replaces the exact email blacklist', async () => { + get.mockResolvedValue({ data: { emails: ['a@gmail.com'], max: 20000 } }) + put.mockResolvedValue({ data: { emails: [], added: [], max: 20000 } }) + + await expect(getRegistrationEmailBlacklist()).resolves.toEqual({ emails: ['a@gmail.com'], max: 20000 }) + expect(get).toHaveBeenCalledWith('/admin/settings/registration-email-blacklist') + + await expect(updateRegistrationEmailBlacklist([])).resolves.toEqual({ emails: [], added: [], max: 20000 }) + expect(put).toHaveBeenCalledWith('/admin/settings/registration-email-blacklist', { emails: [] }) + }) + + it('finds blacklisted users and disables them in batch', async () => { + post.mockResolvedValueOnce({ data: { items: [{ id: 3, email: 'a.b@gmail.com', username: '' }], total: 1 } }) + post.mockResolvedValueOnce({ data: { affected: 1 } }) + + await expect(findBlacklistedEmailUsers(['ab@gmail.com'])).resolves.toEqual({ + items: [{ id: 3, email: 'a.b@gmail.com', username: '' }], + total: 1 + }) + expect(post).toHaveBeenNthCalledWith(1, '/admin/users/blacklist-matches', { emails: ['ab@gmail.com'] }) + + await expect(batchDisable([3])).resolves.toEqual({ affected: 1 }) + expect(post).toHaveBeenNthCalledWith(2, '/admin/users/batch-disable', { user_ids: [3] }) + }) +}) diff --git a/frontend/src/api/__tests__/client.spec.ts b/frontend/src/api/__tests__/client.spec.ts index debcb6a67e..de22f555d8 100644 --- a/frontend/src/api/__tests__/client.spec.ts +++ b/frontend/src/api/__tests__/client.spec.ts @@ -260,6 +260,25 @@ describe('API Client', () => { ) }) + it.each([ + ['17', 17], + ['Wed, 21 Oct 2026 07:28:00 GMT', undefined], + [undefined, undefined], + ])('429 结构化错误携带 Retry-After 秒数(%s)', async (retryAfter, expected) => { + apiClient.defaults.adapter = vi.fn().mockRejectedValueOnce({ + response: { + status: 429, + data: { code: 'RATE_LIMITED', message: 'Too many requests' }, + headers: retryAfter === undefined ? {} : { 'retry-after': retryAfter }, + }, + config: { url: '/usage', headers: {} }, + }) + + const error = await apiClient.get('/usage').catch((err) => err) + expect(error).toMatchObject({ status: 429, code: 'RATE_LIMITED', message: 'Too many requests' }) + expect(error.retry_after_seconds).toBe(expected) + }) + it('部署与运营合规未确认时广播事件且保留登录态', async () => { localStorage.setItem('auth_token', 'admin-token') const listener = vi.fn() diff --git a/frontend/src/api/admin/adminAccessKeys.ts b/frontend/src/api/admin/adminAccessKeys.ts index 3580a5f30f..2aa070a582 100644 --- a/frontend/src/api/admin/adminAccessKeys.ts +++ b/frontend/src/api/admin/adminAccessKeys.ts @@ -8,9 +8,10 @@ export interface AccessRule { account_types: string[] platforms: string[] } -export interface AccessPolicy { rules: AccessRule[]; global_permissions: string[] } +export interface AccessPolicy { full_access?: boolean; rules: AccessRule[]; global_permissions: string[] } export interface Permission { id: string; label: string; category: string; scope: 'account' | 'group' | 'global' } export interface AdminKeyInput { + confirm_full_access?: boolean name: string description: string enabled: boolean diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index c760d45f18..184cc9170e 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -1359,6 +1359,35 @@ export interface PanelRateLimitSettings { public_ip_rpm: number; } +/** Exact registration email blacklist (matched by inbox identity). */ +export interface RegistrationEmailBlacklist { + emails: string[]; + max: number; +} + +export interface UpdateRegistrationEmailBlacklistResponse extends RegistrationEmailBlacklist { + /** Entries not present in the previously saved list. */ + added: string[]; +} + +export async function getRegistrationEmailBlacklist(): Promise { + const { data } = await apiClient.get( + "/admin/settings/registration-email-blacklist", + ); + return data; +} + +/** Replace the whole exact email blacklist; an empty array clears it. */ +export async function updateRegistrationEmailBlacklist( + emails: string[], +): Promise { + const { data } = await apiClient.put( + "/admin/settings/registration-email-blacklist", + { emails }, + ); + return data; +} + export async function getPanelRateLimitSettings(): Promise { const { data } = await apiClient.get( "/admin/settings/panel-rate-limit", @@ -1603,6 +1632,8 @@ export const settingsAPI = { updateOverloadCooldownSettings, getRateLimit429CooldownSettings, updateRateLimit429CooldownSettings, + getRegistrationEmailBlacklist, + updateRegistrationEmailBlacklist, getPanelRateLimitSettings, updatePanelRateLimitSettings, getStreamTimeoutSettings, diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts index d943508e79..b14ec34397 100644 --- a/frontend/src/api/admin/users.ts +++ b/frontend/src/api/admin/users.ts @@ -207,6 +207,32 @@ export async function batchUpdateLimits( return data } +/** Active non-admin user whose inbox identity matches a blacklisted email. */ +export interface BlacklistedEmailUser { + id: number + email: string + username: string +} + +/** Find active non-admin users whose email (or an alias of it) is in the given list. */ +export async function findBlacklistedEmailUsers( + emails: string[] +): Promise<{ items: BlacklistedEmailUser[]; total: number }> { + const { data } = await apiClient.post<{ items: BlacklistedEmailUser[]; total: number }>( + '/admin/users/blacklist-matches', + { emails } + ) + return data +} + +/** Disable multiple users; admins and already-disabled users are skipped. */ +export async function batchDisable(userIds: number[]): Promise<{ affected: number }> { + const { data } = await apiClient.post<{ affected: number }>('/admin/users/batch-disable', { + user_ids: userIds + }) + return data +} + /** * Toggle user status * @param id - User ID @@ -413,6 +439,8 @@ export const usersAPI = { updateBalance, updateConcurrency, batchUpdateLimits, + findBlacklistedEmailUsers, + batchDisable, toggleStatus, getUserApiKeys, getUserUsageStats, diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts index 064f8f83ee..c7072003fa 100644 --- a/frontend/src/api/client.ts +++ b/frontend/src/api/client.ts @@ -78,6 +78,13 @@ apiClient.interceptors.request.use( // ==================== Response Interceptor ==================== +// Retry-After 只接受整数秒;跨域部署未暴露该头或为 HTTP-date 形式时返回 undefined。 +const parseRetryAfterSeconds = (headers: unknown): number | undefined => { + const raw = (headers as Record | undefined)?.['retry-after'] + if (typeof raw !== 'string' || !/^\d+$/.test(raw.trim())) return undefined + return Number(raw.trim()) +} + apiClient.interceptors.response.use( (response: AxiosResponse) => { // Unwrap standard API response format { code, message, data } @@ -262,6 +269,7 @@ apiClient.interceptors.response.use( error: apiData.error, message: apiData.message || apiData.detail || error.message, metadata: apiData.metadata, + retry_after_seconds: parseRetryAfterSeconds(error.response.headers), }) } diff --git a/frontend/src/api/mcp.ts b/frontend/src/api/mcp.ts new file mode 100644 index 0000000000..7693d0c35b --- /dev/null +++ b/frontend/src/api/mcp.ts @@ -0,0 +1,64 @@ +import { apiClient } from './client' + +export type MCPAccessScope = 'user' | 'admin' + +export interface MCPGrant { + id: string + client_id: string + client_name: string + scope: MCPAccessScope + read_only: boolean + created_at: string + expires_at: string + last_used_at: string | null + revoked_at: string | null + invalidated: boolean +} + +export interface MCPAuthorization { + response_type: string + client_id: string + redirect_uri: string + scope?: string + state?: string + code_challenge: string + code_challenge_method: string + resource: string +} + +export interface MCPConsent { + client_id: string + client_name: string + redirect_uri: string + resource: string + scope: 'mcp' +} + +export interface MCPAuthorizationDecision { + authorization: MCPAuthorization + approved: boolean + scope: MCPAccessScope + read_only: boolean +} + +export const mcpAPI = { + async getConnectionConfig(): Promise<{ resource: string }> { + const { data } = await apiClient.get<{ resource: string }>('/user/mcp/config') + return data + }, + async listGrants(): Promise { + const { data } = await apiClient.get('/user/mcp/grants') + return data + }, + async revokeGrant(id: string): Promise { + await apiClient.delete(`/user/mcp/grants/${encodeURIComponent(id)}`) + }, + async previewAuthorization(authorization: MCPAuthorization): Promise { + const { data } = await apiClient.get('/user/mcp/authorize', { params: authorization }) + return data + }, + async authorize(input: MCPAuthorizationDecision): Promise<{ redirect_url: string }> { + const { data } = await apiClient.post<{ redirect_url: string }>('/user/mcp/authorize', input) + return data + } +} diff --git a/frontend/src/components/account/BulkEditAccountModal.vue b/frontend/src/components/account/BulkEditAccountModal.vue index 7acd3ac79b..6b839b1a00 100644 --- a/frontend/src/components/account/BulkEditAccountModal.vue +++ b/frontend/src/components/account/BulkEditAccountModal.vue @@ -193,6 +193,43 @@

+ +
+
+ + +
+
+ +
+
+
@@ -1508,6 +1545,13 @@ import { type HeaderOverrideRow } from '@/components/account/credentialsBuilder' import GrokBaseUrlPresets from '@/components/account/GrokBaseUrlPresets.vue' +import OpenAIImageSizeTiersField from '@/components/account/OpenAIImageSizeTiersField.vue' +import { + OPENAI_IMAGE_SIZE_TIERS, + OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY, + openAIImageSizeTiersPayload, + type OpenAIImageSizeTier +} from '@/components/account/openaiImageSizeTiers' import { OPENAI_WS_MODE_CTX_POOL, OPENAI_WS_MODE_OFF, @@ -1661,6 +1705,7 @@ const enableGroups = ref(false) const enableOpenAIPassthrough = ref(false) const enableOpenAIFlattenNamespaces = ref(false) const enableOpenAILongContextBilling = ref(false) +const enableOpenAIImageSizeTiers = ref(false) const enableOpenAIEndpointCapabilities = ref(false) const enableOpenAIResponsesMode = ref(false) const enableOpenAIWSMode = ref(false) @@ -1697,6 +1742,7 @@ const openaiPassthroughEnabled = ref(false) // Codex namespace 工具摊平兼容开关(仅 OAuth),缺省关闭即原样保留 const openaiFlattenNamespacesEnabled = ref(false) const openAILongContextBillingEnabled = ref(false) +const openAIImageSizeTiers = ref([...OPENAI_IMAGE_SIZE_TIERS]) const openAIEndpointCapabilities = ref([ 'chat_completions', 'embeddings' @@ -1996,6 +2042,11 @@ const buildUpdatePayload = (): Record | null => { extra.openai_long_context_billing_enabled = openAILongContextBillingEnabled.value } + if (enableOpenAIImageSizeTiers.value && allOpenAIPassthroughCapable.value) { + // extra 按 JSONB 合并写入,不限档位用空列表覆盖旧值。 + ensureExtra()[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY] = openAIImageSizeTiersPayload(openAIImageSizeTiers.value) ?? [] + } + if (applyOpenAIEndpointCapabilities) { credentials.openai_capabilities = openAIEndpointCapabilities.value.length === 2 && !openAIEndpointCapabilities.value.includes('seedance') @@ -2206,6 +2257,7 @@ const handleSubmit = async () => { enableOpenAIPassthrough.value || enableOpenAIFlattenNamespaces.value || (enableOpenAILongContextBilling.value && allOpenAIPassthroughCapable.value) || + (enableOpenAIImageSizeTiers.value && allOpenAIPassthroughCapable.value) || (enableOpenAIEndpointCapabilities.value && allOpenAIAPIKey.value) || (enableOpenAIResponsesMode.value && allOpenAIAPIKey.value) || enableModelRestriction.value || @@ -2368,6 +2420,7 @@ watch( enableOpenAIPassthrough.value = false enableOpenAIFlattenNamespaces.value = false enableOpenAILongContextBilling.value = false + enableOpenAIImageSizeTiers.value = false enableOpenAIEndpointCapabilities.value = false enableOpenAIResponsesMode.value = false enableOpenAIWSMode.value = false @@ -2386,6 +2439,7 @@ watch( openaiPassthroughEnabled.value = false openaiFlattenNamespacesEnabled.value = false openAILongContextBillingEnabled.value = false + openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS] openAIEndpointCapabilities.value = ['chat_completions', 'embeddings'] openAIResponsesMode.value = 'auto' modelRestrictionMode.value = 'whitelist' diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index cb013a4dd3..aa27e6e841 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -3662,6 +3662,14 @@
+ +
+ +
+
@@ -4154,6 +4162,12 @@ import ConfirmDialog from '@/components/common/ConfirmDialog.vue' import Select from '@/components/common/Select.vue' import HelpTooltip from '@/components/common/HelpTooltip.vue' import UpstreamRequestIdHeaderField from '@/components/account/UpstreamRequestIdHeaderField.vue' +import OpenAIImageSizeTiersField from '@/components/account/OpenAIImageSizeTiersField.vue' +import { + OPENAI_IMAGE_SIZE_TIERS, + applyOpenAIImageSizeTiersToExtra, + type OpenAIImageSizeTier +} from '@/components/account/openaiImageSizeTiers' import PlatformIcon from '@/components/common/PlatformIcon.vue' import Icon from '@/components/icons/Icon.vue' import ProxySelector from '@/components/common/ProxySelector.vue' @@ -4709,6 +4723,7 @@ const openAICompactMode = ref('auto') const openAIResponsesMode = ref('auto') // Images 非流式响应缺 b64_json 时由网关下载 url 回填(仅 OpenAI API Key)。 const openAIImagesUrlToB64JsonEnabled = ref(false) +const openAIImageSizeTiers = ref([...OPENAI_IMAGE_SIZE_TIERS]) const openAIEndpointCapabilities = ref(['chat_completions', 'embeddings']) const openaiOAuthResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF) const openaiAPIKeyResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF) @@ -5227,6 +5242,7 @@ watch( headerOverrideEnabled.value = false headerOverrideRows.value = [] openAIImagesUrlToB64JsonEnabled.value = false + openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS] grokOAuthCustomBaseUrlEnabled.value = false grokOAuthBaseUrl.value = '' // Reset OAuth states @@ -5663,6 +5679,7 @@ const resetForm = () => { headerOverrideEnabled.value = false headerOverrideRows.value = [] openAIImagesUrlToB64JsonEnabled.value = false + openAIImageSizeTiers.value = [...OPENAI_IMAGE_SIZE_TIERS] grokOAuthCustomBaseUrlEnabled.value = false grokOAuthBaseUrl.value = '' interceptWarmupRequests.value = false @@ -5807,6 +5824,7 @@ const buildOpenAIExtra = (base?: Record): Record 0 ? extra : undefined } diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 9ca560b519..8182d4d7b4 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2243,6 +2243,14 @@
+ +
+ +
+
('auto') const openAIResponsesMode = ref('auto') // Images 非流式响应缺 b64_json 时由网关下载 url 回填(仅 OpenAI API Key)。 const openAIImagesUrlToB64JsonEnabled = ref(false) +const openAIImageSizeTiers = ref([...OPENAI_IMAGE_SIZE_TIERS]) const openAIEndpointCapabilities = ref(['chat_completions', 'embeddings']) const openaiOAuthResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF) const openaiAPIKeyResponsesWebSocketV2Mode = ref(OPENAI_WS_MODE_OFF) @@ -4630,6 +4646,7 @@ const syncFormFromAccount = (newAccount: Account | null) => { allowOverages.value = extra?.allow_overages === true upstreamRequestIdHeader.value = readUpstreamRequestIdHeader(extra) openAIImagesUrlToB64JsonEnabled.value = extra?.images_url_to_b64_json === true + openAIImageSizeTiers.value = readOpenAIImageSizeTiers(extra) autoPause5hThreshold.value = typeof extra?.auto_pause_5h_threshold === 'number' ? extra.auto_pause_5h_threshold * 100 : null autoPause7dThreshold.value = typeof extra?.auto_pause_7d_threshold === 'number' ? extra.auto_pause_7d_threshold * 100 : null autoPause5hDisabled.value = extra?.auto_pause_5h_disabled === true @@ -6242,6 +6259,7 @@ const handleSubmit = async () => { newExtra.web_search_emulation = webSearchEmulationMode.value } } + applyOpenAIImageSizeTiersToExtra(newExtra, openAIImageSizeTiers.value) if (autoPause5hThreshold.value != null && autoPause5hThreshold.value > 0) { newExtra.auto_pause_5h_threshold = autoPause5hThreshold.value / 100 } else { diff --git a/frontend/src/components/account/OpenAIImageSizeTiersField.vue b/frontend/src/components/account/OpenAIImageSizeTiersField.vue new file mode 100644 index 0000000000..bfc8008496 --- /dev/null +++ b/frontend/src/components/account/OpenAIImageSizeTiersField.vue @@ -0,0 +1,52 @@ + + + diff --git a/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts b/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts index daae21b9f9..dd23419db2 100644 --- a/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/BulkEditAccountModal.spec.ts @@ -492,6 +492,42 @@ describe('BulkEditAccountModal', () => { }) }) + it('生图尺寸档位独立启用,全选时提交空列表表示不限', async () => { + const restricted = mountModal({ + selectedPlatforms: ['openai'], + selectedTypes: ['oauth', 'apikey'] + }) + await restricted.get('#bulk-edit-openai-image-size-tiers-enabled').setValue(true) + await restricted.get('[data-testid="bulk-edit-openai-image-size-tier-4K"]').setValue(false) + await restricted.get('#bulk-edit-account-form').trigger('submit.prevent') + await flushPromises() + + expect(adminAPI.accounts.bulkUpdate).toHaveBeenLastCalledWith([1, 2], { + extra: { openai_image_size_tiers: ['1K', '2K'] } + }) + restricted.unmount() + + vi.mocked(adminAPI.accounts.bulkUpdate).mockClear() + const unrestricted = mountModal({ + selectedPlatforms: ['openai'], + selectedTypes: ['apikey'] + }) + await unrestricted.get('#bulk-edit-openai-image-size-tiers-enabled').setValue(true) + await unrestricted.get('#bulk-edit-account-form').trigger('submit.prevent') + await flushPromises() + + expect(adminAPI.accounts.bulkUpdate).toHaveBeenCalledWith([1, 2], { + extra: { openai_image_size_tiers: [] } + }) + unrestricted.unmount() + + const mixed = mountModal({ + selectedPlatforms: ['openai', 'anthropic'], + selectedTypes: ['apikey'] + }) + expect(mixed.find('#bulk-edit-openai-image-size-tiers-enabled').exists()).toBe(false) + }) + it('端点能力默认值提交 null,表示恢复两个默认端点', async () => { const wrapper = mountModal({ selectedPlatforms: ['openai'], diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index 84cfa81123..302c78829c 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -338,6 +338,25 @@ describe('CreateAccountModal OpenAI long-context billing', () => { expect(createAccountMock.mock.calls[0]?.[0]?.extra?.images_url_to_b64_json).toBe(true) }) + it('omits image size tiers by default and sends restricted tiers when set', async () => { + await submitApiKeyAccount('openai') + expect(createAccountMock.mock.calls[0]?.[0]?.extra).not.toHaveProperty('openai_image_size_tiers') + + createAccountMock.mockClear() + const wrapper = mountModal() + await selectButtonByText(wrapper, 'OpenAI') + await selectButtonByText(wrapper, 'API Key') + await wrapper.get('form#create-account-form input[type="text"]').setValue('openai account') + await wrapper.get('form#create-account-form input[type="password"]').setValue('test-api-key') + await wrapper.get('[data-testid="openai-image-size-tier-1K"]').setValue(false) + await wrapper.get('[data-testid="openai-image-size-tier-2K"]').setValue(false) + await wrapper.get('form#create-account-form').trigger('submit.prevent') + await flushPromises() + + expect(createAccountMock).toHaveBeenCalledTimes(1) + expect(createAccountMock.mock.calls[0]?.[0]?.extra?.openai_image_size_tiers).toEqual(['4K']) + }) + it('persists upstream model metadata after creating an account from preview', async () => { const wrapper = mountModal() await selectButtonByText(wrapper, 'OpenAI') diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 9e786042f2..3e65714d5e 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -1040,6 +1040,41 @@ describe('EditAccountModal', () => { expect(updateAccountMock.mock.calls[0]?.[1]?.extra).not.toHaveProperty('images_url_to_b64_json') }) + it('writes restricted image size tiers into extra', async () => { + const account = buildAccount() + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset() + checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false }) + updateAccountMock.mockResolvedValue(account) + + const wrapper = mountModal(account) + await wrapper.get('[data-testid="openai-image-size-tier-1K"]').setValue(false) + await wrapper.get('[data-testid="openai-image-size-tier-2K"]').setValue(false) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.extra?.openai_image_size_tiers).toEqual(['4K']) + }) + + it('removes image size tiers from extra when every tier is selected again', async () => { + const account = buildAccount() + account.extra = { openai_image_size_tiers: ['1K', '2K'] } + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset() + checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false }) + updateAccountMock.mockResolvedValue(account) + + const wrapper = mountModal(account) + const tier4K = wrapper.get('[data-testid="openai-image-size-tier-4K"]') + expect((tier4K.element as HTMLInputElement).checked).toBe(false) + await tier4K.setValue(true) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + expect(updateAccountMock.mock.calls[0]?.[1]?.extra).toBeDefined() + expect(updateAccountMock.mock.calls[0]?.[1]?.extra).not.toHaveProperty('openai_image_size_tiers') + }) + it('hides the Codex namespace flatten toggle for non-OAuth OpenAI accounts', async () => { const account = buildAccount() const wrapper = mountModal(account) diff --git a/frontend/src/components/account/__tests__/OpenAIImageSizeTiersField.spec.ts b/frontend/src/components/account/__tests__/OpenAIImageSizeTiersField.spec.ts new file mode 100644 index 0000000000..f01cb67af7 --- /dev/null +++ b/frontend/src/components/account/__tests__/OpenAIImageSizeTiersField.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import OpenAIImageSizeTiersField from '../OpenAIImageSizeTiersField.vue' +import { + applyOpenAIImageSizeTiersToExtra, + openAIImageSizeTiersPayload, + readOpenAIImageSizeTiers +} from '../openaiImageSizeTiers' + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ t: (key: string) => key }) + } +}) + +describe('openaiImageSizeTiers helpers', () => { + it('reads unrestricted extra as all tiers', () => { + expect(readOpenAIImageSizeTiers(undefined)).toEqual(['1K', '2K', '4K']) + expect(readOpenAIImageSizeTiers({ openai_image_size_tiers: [] })).toEqual(['1K', '2K', '4K']) + expect(readOpenAIImageSizeTiers({ openai_image_size_tiers: ['8K'] })).toEqual(['1K', '2K', '4K']) + }) + + it('reads restricted tiers in canonical order', () => { + expect(readOpenAIImageSizeTiers({ openai_image_size_tiers: ['4k', ' 1K'] })).toEqual(['1K', '4K']) + }) + + it('omits the key when every tier is allowed', () => { + expect(openAIImageSizeTiersPayload(['4K', '1K', '2K'])).toBeNull() + expect(openAIImageSizeTiersPayload(['2K', '1K'])).toEqual(['1K', '2K']) + + const extra: Record = { openai_image_size_tiers: ['4K'] } + applyOpenAIImageSizeTiersToExtra(extra, ['1K', '2K', '4K']) + expect(extra).not.toHaveProperty('openai_image_size_tiers') + applyOpenAIImageSizeTiersToExtra(extra, ['4K']) + expect(extra.openai_image_size_tiers).toEqual(['4K']) + }) +}) + +describe('OpenAIImageSizeTiersField', () => { + it('toggles tiers and keeps at least one selected', async () => { + const wrapper = mount(OpenAIImageSizeTiersField, { + props: { + modelValue: ['1K', '2K', '4K'], + 'onUpdate:modelValue': (value: string[]) => wrapper.setProps({ modelValue: value as never }) + } + }) + + await wrapper.get('[data-testid="openai-image-size-tier-4K"]').setValue(false) + expect(wrapper.props('modelValue')).toEqual(['1K', '2K']) + await wrapper.get('[data-testid="openai-image-size-tier-1K"]').setValue(false) + expect(wrapper.props('modelValue')).toEqual(['2K']) + + const last = wrapper.get('[data-testid="openai-image-size-tier-2K"]') + await last.setValue(false) + expect((last.element as HTMLInputElement).checked).toBe(true) + expect(wrapper.props('modelValue')).toEqual(['2K']) + + await wrapper.get('[data-testid="openai-image-size-tier-4K"]').setValue(true) + expect(wrapper.props('modelValue')).toEqual(['2K', '4K']) + }) +}) diff --git a/frontend/src/components/account/openaiImageSizeTiers.ts b/frontend/src/components/account/openaiImageSizeTiers.ts new file mode 100644 index 0000000000..6cd003c57a --- /dev/null +++ b/frontend/src/components/account/openaiImageSizeTiers.ts @@ -0,0 +1,37 @@ +export const OPENAI_IMAGE_SIZE_TIERS = ['1K', '2K', '4K'] as const + +export type OpenAIImageSizeTier = (typeof OPENAI_IMAGE_SIZE_TIERS)[number] + +export const OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY = 'openai_image_size_tiers' + +// 返回账号允许的档位(按 1K/2K/4K 排序);未配置、空列表或无有效档位视为三档全允许。 +export function readOpenAIImageSizeTiers(extra: unknown): OpenAIImageSizeTier[] { + const raw = (extra as Record | null | undefined)?.[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY] + const values = Array.isArray(raw) + ? raw.filter((item): item is string => typeof item === 'string').map(item => item.trim().toUpperCase()) + : [] + const tiers = OPENAI_IMAGE_SIZE_TIERS.filter(tier => values.includes(tier)) + return tiers.length > 0 ? tiers : [...OPENAI_IMAGE_SIZE_TIERS] +} + +export function normalizeOpenAIImageSizeTiers(tiers: readonly string[]): OpenAIImageSizeTier[] { + return OPENAI_IMAGE_SIZE_TIERS.filter(tier => tiers.includes(tier)) +} + +// 三档全选即不限:返回 null,表示 extra 中不写该键(批量编辑以空列表清除)。 +export function openAIImageSizeTiersPayload(tiers: readonly string[]): OpenAIImageSizeTier[] | null { + const normalized = normalizeOpenAIImageSizeTiers(tiers) + if (normalized.length === 0 || normalized.length === OPENAI_IMAGE_SIZE_TIERS.length) { + return null + } + return normalized +} + +export function applyOpenAIImageSizeTiersToExtra(extra: Record, tiers: readonly string[]): void { + const payload = openAIImageSizeTiersPayload(tiers) + if (payload) { + extra[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY] = payload + } else { + delete extra[OPENAI_IMAGE_SIZE_TIERS_EXTRA_KEY] + } +} diff --git a/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue b/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue index bc256fc479..799ce6bfc0 100644 --- a/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue +++ b/frontend/src/components/admin/settings/AdminAccessKeysSettings.vue @@ -21,6 +21,7 @@

{{ item.description || t('adminAccessKeys.noDescription') }} · {{ t('adminAccessKeys.expires', { value: item.expires_at || t('adminAccessKeys.never') }) }}

{{ t('adminAccessKeys.lastUsed', { value: item.last_used_at || t('adminAccessKeys.neverUsed') }) }} {{ item.last_used_ip }}

+

{{ t('adminAccessKeys.fullAccessLabel') }}

{{ t('adminAccessKeys.summary', { globals: item.policy.global_permissions.length, rules: item.policy.rules.length }) }}

{{ t('adminAccessKeys.ruleLine', { index: index + 1, summary: ruleSummary(rule) }) }}

@@ -41,6 +42,12 @@