diff --git a/.gitignore b/.gitignore index 3ee8dfee88..a5ff9a969f 100644 --- a/.gitignore +++ b/.gitignore @@ -133,6 +133,8 @@ deploy/docker-compose.override.yml .gocache/ vite.config.js docs/* +!docs/agent-resource-safety.md +!docs/moego-json-batching.md !docs/admin-api-keys.md !docs/mcp.md !docs/PAYMENT.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/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 80bdf0c732..1356765b79 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -359,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, @@ -426,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, @@ -457,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 0d90a18229..91db5d03b4 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -5,12 +5,13 @@ go 1.27.3 require ( entgo.io/ent v0.14.5 github.com/DATA-DOG/go-sqlmock v1.5.2 + github.com/MoeForge/moego v0.1.0-alpha.1 github.com/alibabacloud-go/captcha-20230305 v1.1.3 github.com/alibabacloud-go/darabonba-openapi/v2 v2.1.13 github.com/alibabacloud-go/tea v1.3.13 github.com/alicebob/miniredis/v2 v2.38.0 github.com/alitto/pond/v2 v2.6.2 - github.com/andybalholm/brotli v1.2.0 + github.com/andybalholm/brotli v1.2.7 github.com/aws/aws-sdk-go-v2 v1.41.5 github.com/aws/aws-sdk-go-v2/config v1.32.10 github.com/aws/aws-sdk-go-v2/credentials v1.19.10 @@ -28,7 +29,7 @@ require ( github.com/hashicorp/go-hclog v1.6.3 github.com/hashicorp/go-plugin v1.8.0 github.com/imroc/req/v3 v3.59.0 - github.com/klauspost/compress v1.18.2 + github.com/klauspost/compress v1.20.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 diff --git a/backend/go.sum b/backend/go.sum index 5f62bf5c24..b6fc3d31dc 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -14,6 +14,8 @@ github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7Oputl github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/MoeForge/moego v0.1.0-alpha.1 h1:d+asBZu+2oKnBj1kzdvdANMStbIKw9BLCpknuWjiR28= +github.com/MoeForge/moego v0.1.0-alpha.1/go.mod h1:SBNiQjCpWC3IEBMKFBOwOyhhQ3jywMrISqCwJTdr4aA= github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/agiledragon/gomonkey v2.0.2+incompatible h1:eXKi9/piiC3cjJD1658mEE2o3NjkJ5vDLgYjCQu0Xlw= @@ -68,8 +70,8 @@ github.com/aliyun/credentials-go v1.3.1/go.mod h1:8jKYhQuDawt8x2+fusqa1Y6mPxemTs github.com/aliyun/credentials-go v1.3.6/go.mod h1:1LxUuX7L5YrZUWzBrRyk0SwSdH4OmPrib8NVePL3fxM= github.com/aliyun/credentials-go v1.4.5 h1:O76WYKgdy1oQYYiJkERjlA2dxGuvLRrzuO2ScrtGWSk= github.com/aliyun/credentials-go v1.4.5/go.mod h1:Jm6d+xIgwJVLVWT561vy67ZRP4lPTQxMbEYRuT2Ti1U= -github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= -github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= +github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY= @@ -297,8 +299,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE= -github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk= -github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4= +github.com/klauspost/compress v1.20.2 h1:v5tiZvm1KGLyg5d5oXdXe3lsSPrbEUiKoXGia//I7Qo= +github.com/klauspost/compress v1.20.2/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 57b13739ad..ac7b9c10df 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -739,17 +739,16 @@ type PricingConfig struct { type ServerConfig struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` - Mode string `mapstructure:"mode"` // debug/release - EnableServerTiming bool `mapstructure:"enable_server_timing"` // Admin UI Server-Timing response header - FrontendURL string `mapstructure:"frontend_url"` // 前端基础 URL,用于生成邮件中的外部链接 - ReadHeaderTimeout int `mapstructure:"read_header_timeout"` // 读取请求头超时(秒) - MaxHeaderBytes int `mapstructure:"max_header_bytes"` // 请求头最大字节数(HTTP/2 映射为 header-list 上限) - IdleTimeout int `mapstructure:"idle_timeout"` // 空闲连接超时(秒) - TrustedProxies []string `mapstructure:"trusted_proxies"` // 可信代理列表(CIDR/IP) - TrustedProxiesConfigured bool `mapstructure:"-" json:"-" yaml:"-"` // 是否显式配置了可信代理列表 - MaxRequestBodySize int64 `mapstructure:"max_request_body_size"` // 全局最大请求体限制 - RequestBodyIdleTimeout int `mapstructure:"request_body_idle_timeout"` // 请求体无数据到达的超时(秒),不限总上传时长;0 关闭 - H2C H2CConfig `mapstructure:"h2c"` // HTTP/2 Cleartext 配置 + Mode string `mapstructure:"mode"` // debug/release + EnableServerTiming bool `mapstructure:"enable_server_timing"` // Admin UI Server-Timing response header + FrontendURL string `mapstructure:"frontend_url"` // 前端基础 URL,用于生成邮件中的外部链接 + ReadHeaderTimeout int `mapstructure:"read_header_timeout"` // 读取请求头超时(秒) + MaxHeaderBytes int `mapstructure:"max_header_bytes"` // 请求头最大字节数(HTTP/2 映射为 header-list 上限) + IdleTimeout int `mapstructure:"idle_timeout"` // 空闲连接超时(秒) + TrustedProxies []string `mapstructure:"trusted_proxies"` // 可信代理列表(CIDR/IP) + TrustedProxiesConfigured bool `mapstructure:"-" json:"-" yaml:"-"` // 是否显式配置了可信代理列表 + MaxRequestBodySize int64 `mapstructure:"max_request_body_size"` // 全局最大请求体限制 + H2C H2CConfig `mapstructure:"h2c"` // HTTP/2 Cleartext 配置 } // H2CConfig HTTP/2 Cleartext 配置 @@ -1039,7 +1038,8 @@ type GatewayConfig struct { ResponseHeaderTimeout int `mapstructure:"response_header_timeout"` // OpenAIResponseHeaderTimeout: OpenAI/Codex 上游等待响应头的超时时间(秒),0表示无超时 // OpenAI/Codex 请求可能在上游排队较久;默认不使用通用响应头超时截断。 - OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"` + OpenAIResponseHeaderTimeout int `mapstructure:"openai_response_header_timeout"` + DisableOpenAITransportErrorCooldown bool `mapstructure:"disable_openai_transport_error_cooldown"` // GrokResponseHeaderTimeout bounds the pre-first-byte wait for xAI/Grok. // A zero value uses the provider-safe default instead of the generic gateway timeout. GrokResponseHeaderTimeout int `mapstructure:"grok_response_header_timeout"` @@ -1050,6 +1050,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"` // 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大 @@ -1144,7 +1150,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"` @@ -2106,7 +2115,6 @@ func setDefaults() { viper.SetDefault("server.max_header_bytes", 64*1024) viper.SetDefault("server.idle_timeout", 120) // 120秒空闲超时 viper.SetDefault("server.max_request_body_size", int64(256*1024*1024)) - viper.SetDefault("server.request_body_idle_timeout", 60) // 60秒内无请求体数据到达则失败 // H2C 默认配置 viper.SetDefault("server.h2c.enabled", false) viper.SetDefault("server.h2c.max_concurrent_streams", uint32(50)) // 50 个并发流 @@ -2481,6 +2489,7 @@ func setDefaults() { // Gateway viper.SetDefault("gateway.response_header_timeout", 600) // 600秒(10分钟)等待上游响应头,LLM高负载时可能排队较久 viper.SetDefault("gateway.openai_response_header_timeout", 0) + viper.SetDefault("gateway.disable_openai_transport_error_cooldown", false) viper.SetDefault("gateway.grok_response_header_timeout", 120) viper.SetDefault("gateway.openai_first_output_timeout_seconds", 0) viper.SetDefault("gateway.openai_high_effort_first_output_timeout_seconds", 0) @@ -2586,6 +2595,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) @@ -2607,6 +2619,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) @@ -2803,9 +2818,6 @@ func (c *Config) Validate() error { if c.Server.MaxRequestBodySize < 0 { return fmt.Errorf("server.max_request_body_size must be non-negative") } - if c.Server.RequestBodyIdleTimeout < 0 || c.Server.RequestBodyIdleTimeout > 3600 { - return fmt.Errorf("server.request_body_idle_timeout must be between 0 and 3600 seconds") - } if c.Server.H2C.Enabled { if c.Server.H2C.MaxConcurrentStreams == 0 { return fmt.Errorf("server.h2c.max_concurrent_streams must be positive") @@ -3413,6 +3425,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") } diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go index dd551ed6c6..bc579aecfd 100644 --- a/backend/internal/config/config_test.go +++ b/backend/internal/config/config_test.go @@ -139,12 +139,17 @@ func TestLoadHTTPIngressSafetyDefaults(t *testing.T) { cfg, err := Load() require.NoError(t, err) require.Equal(t, 10, cfg.Server.ReadHeaderTimeout) - require.Equal(t, 60, cfg.Server.RequestBodyIdleTimeout) require.Equal(t, 64*1024, cfg.Server.MaxHeaderBytes) require.Empty(t, cfg.Server.TrustedProxies) 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) @@ -1635,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 }, @@ -1645,16 +1660,6 @@ func TestValidateConfigErrors(t *testing.T) { mutate: func(c *Config) { c.Server.MaxHeaderBytes = 4096 }, wantErr: "server.max_header_bytes", }, - { - name: "server request body idle timeout negative", - mutate: func(c *Config) { c.Server.RequestBodyIdleTimeout = -1 }, - wantErr: "server.request_body_idle_timeout", - }, - { - name: "server request body idle timeout too large", - mutate: func(c *Config) { c.Server.RequestBodyIdleTimeout = 3601 }, - wantErr: "server.request_body_idle_timeout", - }, { name: "server max request body size", mutate: func(c *Config) { c.Server.MaxRequestBodySize = -1 }, diff --git a/backend/internal/config/openai_transport_error_cooldown_test.go b/backend/internal/config/openai_transport_error_cooldown_test.go new file mode 100644 index 0000000000..a3562ab6eb --- /dev/null +++ b/backend/internal/config/openai_transport_error_cooldown_test.go @@ -0,0 +1,40 @@ +//go:build unit + +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLoadOpenAITransportErrorCooldown(t *testing.T) { + for _, testCase := range []struct { + name string + yaml string + env string + disabled bool + }{ + {name: "default"}, + {name: "env_true", env: "true", disabled: true}, + {name: "env_false", env: "false"}, + {name: "yaml_true", yaml: "true", disabled: true}, + {name: "env_overrides_yaml", yaml: "true", env: "false"}, + } { + t.Run(testCase.name, func(t *testing.T) { + resetViperWithJWTSecret(t) + t.Chdir(t.TempDir()) + t.Setenv("GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN", testCase.env) + if testCase.yaml != "" { + configPath := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(configPath, []byte("gateway:\n disable_openai_transport_error_cooldown: "+testCase.yaml+"\n"), 0600)) + t.Setenv("CONFIG_FILE", configPath) + } + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, testCase.disabled, cfg.Gateway.DisableOpenAITransportErrorCooldown) + }) + } +} 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/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/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/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 01a91ccc7d..6ec51d5430 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -596,6 +599,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, @@ -613,7 +617,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"), @@ -959,6 +963,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, @@ -976,7 +981,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"), @@ -2155,6 +2160,9 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) { // 读取请求体 body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index fad804036d..1db2e0584a 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.chatCompletionsErrorResponse(c, status, "invalid_request_error", message) return @@ -330,6 +333,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, @@ -346,7 +350,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 027a48ad87..79544a48de 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.responsesErrorResponse(c, status, "invalid_request_error", message) return @@ -312,6 +315,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, @@ -328,7 +332,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_systemone.go b/backend/internal/handler/gateway_systemone.go index cd7ea825e2..2cb25a5a32 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -255,9 +258,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, @@ -271,7 +278,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_contents_handler.go b/backend/internal/handler/gemini_cached_contents_handler.go index fc6ead5aa1..e160f8cef9 100644 --- a/backend/internal/handler/gemini_cached_contents_handler.go +++ b/backend/internal/handler/gemini_cached_contents_handler.go @@ -65,7 +65,11 @@ func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - status, message := requestBodyReadFailure(requestLogger(c, "handler.gemini_cached_contents"), c.Request, err) + bodyLog := requestLogger(c, "handler.gemini_cached_contents") + if handleRequestBodyReadError(c, bodyLog, err) { + return nil, false + } + status, message := requestBodyReadFailure(bodyLog, c.Request, err) googleErrorWithType(c, status, "invalid_request_error", "", message) return nil, false } diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go index 1063a45c7b..06e2472f8d 100644 --- a/backend/internal/handler/gemini_v1beta_handler.go +++ b/backend/internal/handler/gemini_v1beta_handler.go @@ -374,6 +374,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if handleRequestBodyReadError(c, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) googleErrorWithType(c, status, "invalid_request_error", "", message) return @@ -827,6 +830,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, @@ -844,7 +848,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..d93e6e6742 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, requestLogger(c, "handler.openai_gateway.grok_voice"), 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 aa7974568c..4a13293a2e 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -754,6 +757,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, @@ -765,7 +769,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/image_task_handler.go b/backend/internal/handler/image_task_handler.go index aef7b661b3..2b01168c54 100644 --- a/backend/internal/handler/image_task_handler.go +++ b/backend/internal/handler/image_task_handler.go @@ -77,7 +77,11 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) { body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { - status, message := requestBodyReadFailure(requestLogger(c, "handler.image_task.create"), c.Request, err) + bodyLog := requestLogger(c, "handler.image_task.create") + if handleRequestBodyReadError(c, bodyLog, err) { + return + } + status, message := requestBodyReadFailure(bodyLog, c.Request, err) imageTaskJSONError(c, status, "invalid_request_error", message) return } @@ -97,7 +101,13 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) { return } - taskCtx, recorder, cancel := newAsyncImageContext(c, body, h.tasks.ExecutionTimeout()) + taskCtx, recorder, cancel, err := newAsyncImageContext(c, body, h.tasks.ExecutionTimeout()) + if err != nil { + if !middleware2.RejectRequestBodyMemoryOverload(c, err) { + imageTaskError(c, service.ErrImageTaskUnavailable) + } + return + } task, err := h.tasks.Create(c.Request.Context(), service.ImageTaskOwner{UserID: apiKey.UserID, APIKeyID: apiKey.ID}) if err != nil { cancel() @@ -255,13 +265,23 @@ func (h *AsyncImageHandler) failTask(taskID string, statusCode int, taskErr json } } -func newAsyncImageContext(c *gin.Context, body []byte, timeoutDuration time.Duration) (*gin.Context, *httptest.ResponseRecorder, context.CancelFunc) { - base := context.WithoutCancel(c.Request.Context()) - executionCtx, cancel := context.WithTimeout(base, timeoutDuration) +func newAsyncImageContext(c *gin.Context, body []byte, timeoutDuration time.Duration) (*gin.Context, *httptest.ResponseRecorder, context.CancelFunc, error) { + // The task keeps body after Submit returns and the ingress reservation is + // released, so it holds the body, and whatever it buffers, on its own one. + retained, releaseBody, err := pkghttputil.DetachRequestBodyMemory(c.Request.Context(), int64(len(body))) + if err != nil { + return nil, nil, nil, err + } + base := context.WithoutCancel(retained) + executionCtx, cancelExecution := context.WithTimeout(base, timeoutDuration) + cancel := func() { + cancelExecution() + releaseBody() + } request := c.Request.Clone(executionCtx) - request.Body = io.NopCloser(bytes.NewReader(body)) + request.Body = pkghttputil.NewPrereadBody(body) request.GetBody = func() (io.ReadCloser, error) { - return io.NopCloser(bytes.NewReader(body)), nil + return pkghttputil.NewPrereadBody(body), nil } request.ContentLength = int64(len(body)) request.URL.Path = strings.TrimSuffix(request.URL.Path, "/async") @@ -271,7 +291,7 @@ func newAsyncImageContext(c *gin.Context, body []byte, timeoutDuration time.Dura recorderCtx, _ := gin.CreateTestContext(recorder) taskCtx.Writer = recorderCtx.Writer taskCtx.Request = request - return taskCtx, recorder, cancel + return taskCtx, recorder, cancel, nil } func asyncImageRequestStreams(contentType string, body []byte) bool { diff --git a/backend/internal/handler/image_task_handler_test.go b/backend/internal/handler/image_task_handler_test.go index 1fbc8d18be..7f360b465f 100644 --- a/backend/internal/handler/image_task_handler_test.go +++ b/backend/internal/handler/image_task_handler_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/gin-gonic/gin" @@ -106,6 +107,150 @@ func TestAsyncImageHandlerSubmitAndPoll(t *testing.T) { require.Contains(t, pollWriter.Body.String(), "https://example.test/image.png") } +// The background task runs after Submit has released the ingress reservation; +// it must still read its body and buffer under the shared budget, then return +// every byte it held. +func TestAsyncImageHandlerTaskUsesOwnBodyReservation(t *testing.T) { + gin.SetMode(gin.TestMode) + const budgetLimit = 1 << 20 + budget := pkghttputil.NewBodyMemoryBudget(budgetLimit) + store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)} + tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute) + requestBody := `{"model":"gpt-image-1","prompt":"cat"}` + submitted := make(chan struct{}) + h := &AsyncImageHandler{tasks: tasks} + h.execute = func(_ string, c *gin.Context) { + <-submitted + body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) + if err != nil || string(body) != requestBody { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{"message": "read body failed"}}) + return + } + if err := pkghttputil.ReserveRequestBodyMemory(c.Request.Context(), 4096); err != nil { + c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{"message": err.Error()}}) + return + } + c.JSON(http.StatusOK, gin.H{"created": 123, "data": []gin.H{{"url": "https://example.test/image.png"}}}) + } + + router := gin.New() + router.Use(middleware2.RequestBodyLimit(1<<20, budget)) + router.Use(func(c *gin.Context) { + groupID := int64(3) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 9, + UserID: 7, + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, AllowImageGeneration: true}, + }) + c.Next() + }) + router.POST("/v1/images/generations/async", h.Submit) + + req := httptest.NewRequest(http.MethodPost, "/v1/images/generations/async", strings.NewReader(requestBody)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, http.StatusAccepted, w.Code) + var accepted struct { + TaskID string `json:"task_id"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &accepted)) + close(submitted) // Submit and its ingress release have completed. + + owner := service.ImageTaskOwner{UserID: 7, APIKeyID: 9} + require.Eventually(t, func() bool { + got, err := tasks.Get(context.Background(), owner, accepted.TaskID) + return err == nil && got.Status != service.ImageTaskStatusProcessing + }, time.Second, 10*time.Millisecond) + got, err := tasks.Get(context.Background(), owner, accepted.TaskID) + require.NoError(t, err) + require.Equal(t, service.ImageTaskStatusCompleted, got.Status, "task error: %s", string(got.Error)) + + require.Eventually(t, func() bool { + ctx, release := pkghttputil.WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + return pkghttputil.ReserveRequestBodyMemory(ctx, budgetLimit) == nil + }, time.Second, 10*time.Millisecond, "task must release its reservation") +} + +// The retained body is charged before a task is created, so exhaustion is +// reported as retryable overload instead of an accepted task that cannot run. +// A body the request already holds moves to the task instead of being charged +// twice. +func TestAsyncImageHandlerSubmitRejectsWhenBodyCannotBeRetained(t *testing.T) { + requestBody := `{"model":"gpt-image-1","prompt":"cat"}` + for _, tt := range []struct { + name string + chargeRequest bool + want int + }{ + {name: "budget held by other requests", want: http.StatusServiceUnavailable}, + {name: "body already charged to the request", chargeRequest: true, want: http.StatusAccepted}, + } { + t.Run(tt.name, func(t *testing.T) { + gin.SetMode(gin.TestMode) + store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)} + tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute) + h := &AsyncImageHandler{tasks: tasks} + ran := make(chan struct{}) + h.execute = func(_ string, c *gin.Context) { + if !tt.chargeRequest { + t.Error("task must not run") + } + close(ran) + } + + budget := pkghttputil.NewBodyMemoryBudget(int64(len(requestBody))) + router := gin.New() + router.Use(func(c *gin.Context) { + groupID := int64(3) + c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{ + ID: 9, + UserID: 7, + GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI, AllowImageGeneration: true}, + }) + ctx, release := pkghttputil.WithRequestBodyMemoryBudget(c.Request.Context(), budget) + defer release() + c.Request = c.Request.WithContext(ctx) + c.Request.Body = pkghttputil.NewPrereadBody([]byte(requestBody)) + if tt.chargeRequest { + require.NoError(t, pkghttputil.ReserveRequestBodyMemory(ctx, int64(len(requestBody)))) + } else { + // Another in-flight request holds all remaining capacity. + other, releaseOther := pkghttputil.WithRequestBodyMemoryBudget(context.Background(), budget) + defer releaseOther() + require.NoError(t, pkghttputil.ReserveRequestBodyMemory(other, int64(len(requestBody)))) + } + c.Next() + }) + router.POST("/v1/images/generations/async", h.Submit) + + req := httptest.NewRequest(http.MethodPost, "/v1/images/generations/async", strings.NewReader(requestBody)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + require.Equal(t, tt.want, w.Code) + if !tt.chargeRequest { + require.Equal(t, "1", w.Header().Get("Retry-After")) + require.Empty(t, store.tasks) + return + } + select { + case <-ran: + case <-time.After(time.Second): + t.Fatal("accepted task did not run") + } + require.Eventually(t, func() bool { + ctx, release := pkghttputil.WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + return pkghttputil.ReserveRequestBodyMemory(ctx, int64(len(requestBody))) == nil + }, time.Second, 10*time.Millisecond, "task must release the body it took over") + }) + } +} + // When object storage is not configured the feature is fully disabled: the // endpoints must return 404 without creating a task or writing to Redis. func TestAsyncImageHandlerDisabledReturns404(t *testing.T) { diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index 3d85812998..8a76f6b23c 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -290,6 +293,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{ @@ -307,7 +311,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_automation_bootstrap_test.go b/backend/internal/handler/openai_automation_bootstrap_test.go index d881315553..0710008f69 100644 --- a/backend/internal/handler/openai_automation_bootstrap_test.go +++ b/backend/internal/handler/openai_automation_bootstrap_test.go @@ -207,3 +207,30 @@ Read the reference index and report changes. Preserve A & B and <tags> require.Equal(t, guarded, unchanged) } } + +// The byte precheck must stay a necessary condition: an escaped type or tool +// name is still a candidate, and a body without either is returned untouched +// without the token scan and decode. +func TestNormalizeCodexBootstrapPrecheck(t *testing.T) { + output := codexAutomationBootstrap("wiki-maintenance", "never", automationBootstrapPrompt) + escaped := []byte(strings.Replace(string(codexAutomationBootstrapBody(t, output, "")), `"automation_update"`, `"\u0061utomation_update"`, 1)) + got, changed := normalizeCodexAutomationBootstrap(escaped) + require.True(t, changed) + require.Equal(t, output, gjson.GetBytes(got, "input.0.content.0.text").String()) + + plain := []byte(`{"model":"gpt-5","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4096) + `"}]},{"type":"function_call_output","call_id":"call_1","output":"ok"}]}`) + for name, normalize := range map[string]func([]byte) ([]byte, bool){ + "automation": normalizeCodexAutomationBootstrap, + "delegation": normalizeCodexDelegationBootstrap, + } { + t.Run(name, func(t *testing.T) { + allocs := testing.AllocsPerRun(10, func() { + got, changed := normalize(plain) + if changed || &got[0] != &plain[0] { + t.Fatal("non-candidate body must be returned unchanged") + } + }) + require.Zero(t, allocs) + }) + } +} diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 9a0d7a4438..ac22b8a553 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -288,6 +291,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, @@ -302,7 +306,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_cyber_allowlist_test.go b/backend/internal/handler/openai_cyber_allowlist_test.go index 22bb674586..2d5276ee06 100644 --- a/backend/internal/handler/openai_cyber_allowlist_test.go +++ b/backend/internal/handler/openai_cyber_allowlist_test.go @@ -49,7 +49,7 @@ func TestCyberAllowlistedUserBypassesExistingBlocksAndContinuesWebSocket(t *test explicitKey := service.CyberSessionExplicitBlockKey(harness.apiKey.ID, c, payload) store, ok := harness.gatewayCache.(service.CyberSessionBlockStore) require.True(t, ok) - require.NoError(t, store.SetCyberSessionBlocked(context.Background(), "", []string{explicitKey}, time.Minute)) + require.NoError(t, store.SetCyberSessionBlocked(context.Background(), service.CyberSessionBlock{APIKeyID: harness.apiKey.ID, Keys: []string{explicitKey}}, time.Minute)) for _, format := range []cyberSessionBlockFormat{cyberBlockFormatResponses, cyberBlockFormatChat, cyberBlockFormatAnthropic} { require.False(t, harness.handler.rejectIfCyberSessionBlocked(c, harness.apiKey, payload, "gpt-5.1", format)) } @@ -63,7 +63,11 @@ func TestCyberAllowlistedUserBypassesExistingBlocksAndContinuesWebSocket(t *test logs := harness.moderationRepo.logSnapshot() return len(logs) == 1 && logs[0].Mode == service.ContentModerationModeCyberLogOnly }, 3*time.Second, 10*time.Millisecond) - matched, err := store.FindCyberSessionBlocked(ctx, service.CyberSessionTranscriptBlockKeys(harness.apiKey.ID, payload)) + transcriptKeys := make([]string, 0, 2) + for _, transcript := range service.CyberSessionTranscriptBlocks(harness.apiKey.ID, payload) { + transcriptKeys = append(transcriptKeys, transcript.Key) + } + matched, err := store.FindCyberSessionBlocked(ctx, transcriptKeys) require.NoError(t, err) require.Empty(t, matched, "the cyber response must not write new transcript blocks") require.NoError(t, harness.clientConn.Write(ctx, coderws.MessageText, payload)) diff --git a/backend/internal/handler/openai_embeddings.go b/backend/internal/handler/openai_embeddings.go index 6d5b618df0..2813578457 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -268,6 +271,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, @@ -282,7 +286,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 edd6e89299..57572c2016 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -132,7 +135,11 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) { func (h *OpenAIGatewayHandler) GrokCountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { - status, message := requestBodyReadFailure(requestLogger(c, "handler.openai_gateway.grok_count_tokens"), c.Request, err) + bodyLog := requestLogger(c, "handler.openai_gateway.grok_count_tokens") + if handleRequestBodyReadError(c, bodyLog, err) { + return + } + status, message := requestBodyReadFailure(bodyLog, c.Request, err) h.anthropicErrorResponse(c, status, "invalid_request_error", message) return } @@ -199,6 +206,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.anthropicErrorResponse(c, status, "invalid_request_error", message) return diff --git a/backend/internal/handler/openai_gateway_cyber_test.go b/backend/internal/handler/openai_gateway_cyber_test.go index 4be214cdc9..ddf4e753e7 100644 --- a/backend/internal/handler/openai_gateway_cyber_test.go +++ b/backend/internal/handler/openai_gateway_cyber_test.go @@ -178,21 +178,24 @@ func TestRejectIfCyberSessionBlocked_FailOpen(t *testing.T) { require.False(t, h2.rejectIfCyberSessionBlocked(c, key, []byte(`{}`), "gpt-5", cyberBlockFormatResponses), "nil gateway service → pass") } -func TestBuildCyberSessionBlockWritePlanCombinesExplicitAndTranscriptKeys(t *testing.T) { +func TestBuildCyberSessionBlockCombinesExplicitAndTranscriptKeys(t *testing.T) { body := []byte(`{"messages":[{"role":"user","content":"setup"},{"role":"assistant","content":"ready"},{"role":"user","content":"trigger"}]}`) c := newTestGinContext() c.Request = httptest.NewRequest("POST", "/openai/v1/responses", strings.NewReader(string(body))) c.Request.RemoteAddr = "203.0.113.44:12345" c.Request.Header.Set("User-Agent", "client/1.2.3") - plan := buildCyberSessionBlockWritePlan(7, c, body) - require.Len(t, plan.keys, 2) - require.NotEmpty(t, plan.scopeKey) + block := buildCyberSessionBlock(7, c, body) + require.Len(t, block.Keys, 2) + require.Equal(t, []int{3, 2}, block.TranscriptLengths) + require.Equal(t, int64(7), block.APIKeyID) + require.NotEmpty(t, block.ScopeKey) c.Request.Header.Set("session_id", "sess-explicit") - plan = buildCyberSessionBlockWritePlan(7, c, body) - require.Len(t, plan.keys, 3) - require.NotEmpty(t, plan.scopeKey) + block = buildCyberSessionBlock(7, c, body) + require.Len(t, block.Keys, 3) + require.Equal(t, []int{3, 2}, block.TranscriptLengths) + require.NotEmpty(t, block.ScopeKey) } // TestRecordCyberPolicyIfMarked_BlockKeyPlumbed verifies the 6th param is diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index d01dfe58e0..cde081e20c 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -19,6 +19,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + 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" "github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel" @@ -270,9 +271,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 +424,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // Read request body body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -652,6 +657,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 重入共用同一门与阈值。 @@ -698,6 +709,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 { @@ -793,6 +811,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { }() return h.gatewayService.Forward(c.Request.Context(), c, account, attemptBody) }() + if h.handleForwardRequestBodyMemoryOverload(c, err, streamStarted) { + return + } var cyberBlockBodyHTTP []byte if service.GetOpsCyberPolicy(c) != nil { cyberBlockBodyHTTP = sessionHashBody @@ -823,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, @@ -838,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, @@ -1184,6 +1206,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg) if err != nil { + if handleRequestBodyReadError(c, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.anthropicErrorResponse(c, status, "invalid_request_error", message) return @@ -1414,6 +1439,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, @@ -1429,7 +1455,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 { @@ -1670,6 +1696,9 @@ func (h *OpenAIGatewayHandler) validateFunctionCallOutputRequest(c *gin.Context, } func normalizeCodexDelegationBootstrap(body []byte) ([]byte, bool) { + if !mayContainCodexCallOutputCandidate(body, "create_thread", "send_message_to_thread") { + return body, false + } // 已有任务通过 send_message_to_thread 唤醒时会携带 previous_response_id; // 完整历史回放还会带有已配对的调用项。delegation 仍是客户端注入的用户输入, // 不属于这些历史调用的结果,因此允许它与可明确配对的历史上下文共存。 @@ -1677,9 +1706,31 @@ func normalizeCodexDelegationBootstrap(body []byte) ([]byte, bool) { } func normalizeCodexAutomationBootstrap(body []byte) ([]byte, bool) { + if !mayContainCodexCallOutputCandidate(body, "automation_update") { + return body, false + } return normalizeCodexCallOutputBootstrap(body, isCodexAutomationCandidate, false) } +// mayContainCodexCallOutputCandidate is a necessary condition for a bootstrap +// candidate, checked before the full uniqueness scan and decode. Its type and +// tool name are JSON strings, which appear literally unless a \u escape spells +// their letters; without either, normalization cannot change the body. +func mayContainCodexCallOutputCandidate(body []byte, toolNames ...string) bool { + if bytes.Contains(body, []byte(`\u`)) { + return true + } + if !bytes.Contains(body, []byte("function_call_output")) { + return false + } + for _, name := range toolNames { + if bytes.Contains(body, []byte(name)) { + return true + } + } + return false +} + func normalizeCodexCallOutputBootstrap(body []byte, isCandidate func(map[string]any) bool, allowHistoricalContext bool) ([]byte, bool) { if !hasUniqueJSONMembers(body) { return body, false @@ -3690,6 +3741,26 @@ func (h *OpenAIGatewayHandler) mapUpstreamError(statusCode int) (int, string, st } } +// handleForwardRequestBodyMemoryOverload ends a request when rewriting exhausts +// local buffering capacity, without retrying or penalizing the upstream account. +func (h *OpenAIGatewayHandler) handleForwardRequestBodyMemoryOverload(c *gin.Context, err error, streamStarted bool) bool { + if !errors.Is(err, pkghttputil.ErrRequestBodyMemoryBudget) { + return false + } + // Stop compact heartbeats before inspecting or writing the response headers. + if service.StopOpenAICompactSSEKeepaliveCommitted(c) { + streamStarted = true + } + streamStarted = streamStarted || c.Writer.Written() + if !c.Writer.Written() { + c.Header("Retry-After", "1") + } + h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "service_unavailable", + "Request body buffering capacity is exhausted; retry later", streamStarted) + c.Abort() + return true +} + // handleStreamingAwareError handles errors that may occur after streaming has started func (h *OpenAIGatewayHandler) handleStreamingAwareError(c *gin.Context, status int, errType, message string, streamStarted bool) { h.handleStreamingAwareErrorWithCode(c, status, errType, "", message, streamStarted, false) @@ -4246,26 +4317,20 @@ func (h *OpenAIGatewayHandler) rejectIfCyberSessionBlocked(c *gin.Context, apiKe return true } -type cyberSessionBlockWritePlan struct { - scopeKey string - keys []string -} - -func buildCyberSessionBlockWritePlan(apiKeyID int64, c *gin.Context, body []byte) cyberSessionBlockWritePlan { - plan := cyberSessionBlockWritePlan{} +func buildCyberSessionBlock(apiKeyID int64, c *gin.Context, body []byte) service.CyberSessionBlock { + block := service.CyberSessionBlock{APIKeyID: apiKeyID} if key := service.CyberSessionExplicitBlockKey(apiKeyID, c, body); key != "" { - plan.keys = append(plan.keys, key) + block.Keys = append(block.Keys, key) } - transcriptKeys := service.CyberSessionTranscriptBlockKeys(apiKeyID, body) - for _, key := range transcriptKeys { - if len(plan.keys) == 0 || key != plan.keys[0] { - plan.keys = append(plan.keys, key) - } + transcriptBlocks := service.CyberSessionTranscriptBlocks(apiKeyID, body) + for _, transcript := range transcriptBlocks { + block.Keys = append(block.Keys, transcript.Key) + block.TranscriptLengths = append(block.TranscriptLengths, transcript.Length) } - if len(transcriptKeys) > 0 { - plan.scopeKey = cyberSessionScopeKey(apiKeyID, c) + if len(transcriptBlocks) > 0 { + block.ScopeKey = cyberSessionScopeKey(apiKeyID, c) } - return plan + return block } func findBlockedCyberSessionKey(ctx context.Context, gatewayService *service.OpenAIGatewayService, apiKeyID int64, c *gin.Context, body []byte) string { @@ -4414,10 +4479,10 @@ func (h *OpenAIGatewayHandler) recordCyberPolicyIfMarked(c *gin.Context, apiKey } cyberLogOnly := h.cyberPolicyLogOnly(c, apiKey) if gwSvc != nil && apiKey != nil && !cyberLogOnly { - plan := buildCyberSessionBlockWritePlan(apiKey.ID, c, cyberBlockBody) - if len(plan.keys) > 0 { + block := buildCyberSessionBlock(apiKey.ID, c, cyberBlockBody) + if len(block.Keys) > 0 { blockCtx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) - gwSvc.MarkCyberSessionBlocked(blockCtx, plan.scopeKey, plan.keys) + gwSvc.MarkCyberSessionBlocked(blockCtx, block) cancel() } } diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index 8e50f3b873..9510fb060b 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, reqLog, err) { + return + } status, message := requestBodyReadFailure(reqLog, c.Request, err) h.errorResponse(c, status, "invalid_request_error", message) return @@ -153,7 +156,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 @@ -186,6 +189,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) @@ -401,6 +409,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, @@ -416,7 +425,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/openai_request_body_memory_test.go b/backend/internal/handler/openai_request_body_memory_test.go new file mode 100644 index 0000000000..d7660844bd --- /dev/null +++ b/backend/internal/handler/openai_request_body_memory_test.go @@ -0,0 +1,59 @@ +package handler + +import ( + "errors" + "fmt" + "net/http" + "strings" + "testing" + + pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIForwardRequestBodyMemoryOverloadReturns503(t *testing.T) { + c, recorder := newGinContextForEndpoint(t, EndpointResponses) + h := &OpenAIGatewayHandler{} + err := fmt.Errorf("materialize rewritten body: %w", pkghttputil.ErrRequestBodyMemoryBudget) + + require.True(t, h.handleForwardRequestBodyMemoryOverload(c, err, false)) + require.True(t, c.IsAborted()) + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Equal(t, "1", recorder.Result().Header.Get("Retry-After")) + require.Equal(t, "service_unavailable", gjson.GetBytes(recorder.Body.Bytes(), "error.type").String()) + require.Contains(t, gjson.GetBytes(recorder.Body.Bytes(), "error.message").String(), "retry later") +} + +func TestOpenAIForwardRequestBodyMemoryOverloadTerminatesCommittedStream(t *testing.T) { + c, recorder := newGinContextForEndpoint(t, EndpointResponses) + c.Header("Content-Type", "text/event-stream") + _, err := c.Writer.Write([]byte(": keepalive\n\n")) + require.NoError(t, err) + c.Writer.Flush() + h := &OpenAIGatewayHandler{} + + // A heartbeat may commit HTTP 200 before the caller updates streamStarted. + require.True(t, h.handleForwardRequestBodyMemoryOverload(c, pkghttputil.ErrRequestBodyMemoryBudget, false)) + require.True(t, c.IsAborted()) + require.Equal(t, http.StatusOK, recorder.Code) + _, errorObject := parseResponsesFailedSSE(t, strings.TrimPrefix(recorder.Body.String(), ": keepalive\n\n")) + require.Contains(t, errorObject["message"], "retry later") + require.NotContains(t, recorder.Body.String(), "response.completed") + streamError, ok := service.GetOpsStreamError(c) + require.True(t, ok) + require.Equal(t, http.StatusServiceUnavailable, streamError.IntendedStatus) +} + +func TestOpenAIForwardRequestBodyMemoryOverloadLeavesOtherErrorsUntouched(t *testing.T) { + for _, err := range []error{nil, errors.New("upstream failed")} { + c, recorder := newGinContextForEndpoint(t, EndpointResponses) + h := &OpenAIGatewayHandler{} + require.False(t, h.handleForwardRequestBodyMemoryOverload(c, err, false)) + require.False(t, c.IsAborted()) + require.False(t, c.Writer.Written()) + require.Empty(t, recorder.Body.String()) + require.Empty(t, recorder.Header().Get("Retry-After")) + } +} 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 82d43d01ce..a52bb0bfb4 100644 --- a/backend/internal/handler/request_body_limit.go +++ b/backend/internal/handler/request_body_limit.go @@ -6,8 +6,26 @@ 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" + "go.uber.org/zap" ) +// handleRequestBodyReadError handles cancellation and temporary capacity errors +// before callers classify malformed or oversized request bodies. +// +// A read deadline on HTTP/1 also cancels the request context, so a body read +// timeout is left to requestBodyReadFailure (408) instead of being reported as +// a client that went away (499). +func handleRequestBodyReadError(c *gin.Context, reqLog *zap.Logger, err error) bool { + if err != nil && !pkghttputil.IsRequestBodyReadTimeout(err) && failoverClientGone(c) { + logRequestBodyReadFailure(reqLog, pkghttputil.DescribeRequestBodyReadFailure(c.Request, err)) + c.Abort() + return true + } + return middleware2.RejectRequestBodyMemoryOverload(c, err) +} + func formatBodyLimit(limit int64) string { const mb = 1024 * 1024 if limit >= mb { diff --git a/backend/internal/handler/request_body_limit_test.go b/backend/internal/handler/request_body_limit_test.go index 12dd7646e8..bbb3d2a070 100644 --- a/backend/internal/handler/request_body_limit_test.go +++ b/backend/internal/handler/request_body_limit_test.go @@ -2,9 +2,12 @@ package handler import ( "bytes" + "context" "io" + "net" "net/http" "net/http/httptest" + "os" "testing" "github.com/Wei-Shaw/sub2api/internal/server/middleware" @@ -36,3 +39,48 @@ 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 + readErr error + handled bool + }{ + {name: "cancelled", cancelled: true, handled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true, handled: true}, + {name: "ordinary_read_error"}, + // An HTTP/1 read deadline also cancels the request context; the + // timeout must reach requestBodyReadFailure (408). + {name: "read_timeout_with_cancelled_context", cancelled: true, readErr: &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}}, + } { + 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() + readErr := tc.readErr + if readErr == nil { + readErr = io.ErrUnexpectedEOF + } + require.Equal(t, tc.handled, handleRequestBodyReadError(c, nil, readErr)) + require.Equal(t, tc.handled, c.IsAborted()) + status := http.StatusOK + if tc.handled && !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/request_body_read_log.go b/backend/internal/handler/request_body_read_log.go index 099c6e7779..0068c79212 100644 --- a/backend/internal/handler/request_body_read_log.go +++ b/backend/internal/handler/request_body_read_log.go @@ -8,19 +8,23 @@ import ( ) // requestBodyReadFailure maps a request body read error to the response status -// and message. Timeouts (408) and client disconnects (499) are no longer -// reported as malformed requests; other read failures keep the stable generic -// 400 message. Failures other than the configured size limit are logged with -// bounded, payload-free diagnostics (kind, declared length, bytes received and -// read duration) so operators can tell a stalled or slow upload from a broken -// client without logging request content. +// and message. Read timeouts (408) are no longer reported as malformed +// requests; other read failures keep the stable generic 400 message. Failures +// other than the configured size limit are logged with bounded, payload-free +// diagnostics (kind, declared length, bytes received and read duration) so +// operators can tell a stalled or slow upload from a broken client without +// logging request content. func requestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) (int, string) { failure := pkghttputil.DescribeRequestBodyReadFailure(req, err) if failure.Kind == pkghttputil.RequestBodyReadErrorMaxBytes { return failure.Status, buildBodyTooLargeMessage(failure.MaxBytesLimit) } + logRequestBodyReadFailure(reqLog, failure) + return failure.Status, failure.Message +} + +func logRequestBodyReadFailure(reqLog *zap.Logger, failure pkghttputil.RequestBodyReadFailure) { if reqLog != nil { reqLog.Warn("read request body failed", failure.LogFields()...) } - return failure.Status, failure.Message } diff --git a/backend/internal/handler/request_body_read_log_test.go b/backend/internal/handler/request_body_read_log_test.go index 1ffacaada4..f9eef560a4 100644 --- a/backend/internal/handler/request_body_read_log_test.go +++ b/backend/internal/handler/request_body_read_log_test.go @@ -51,6 +51,18 @@ func TestRequestBodyReadFailureKeepsBodyLimitMessageWithoutLogging(t *testing.T) require.Empty(t, logs.All()) } +// cancelOnReadErr models net/http on HTTP/1: a failed body read cancels the +// request context before the error reaches the handler. +type cancelOnReadErr struct { + err error + cancel context.CancelFunc +} + +func (r cancelOnReadErr) Read([]byte) (int, error) { + r.cancel() + return 0, r.err +} + // The Anthropic /v1/messages handler reads the full body before it knows the // model or account. A failed read must report why instead of a generic 400. func TestGatewayMessagesClassifiesRequestBodyReadFailures(t *testing.T) { @@ -64,22 +76,27 @@ func TestGatewayMessagesClassifiesRequestBodyReadFailures(t *testing.T) { wantStatus int wantMessage string }{ - {"idle timeout", deadlineErr, false, http.StatusRequestTimeout, "Timed out reading request body"}, - {"client disconnect", io.ErrUnexpectedEOF, true, 499, "Client closed the connection before the request body was received"}, + {"h2 read timeout", deadlineErr, false, http.StatusRequestTimeout, "Timed out reading request body"}, + // net/http cancels the request context when an HTTP/1 read deadline + // fires; this is still a timeout, not a client that went away. + {"http1 read timeout", deadlineErr, true, http.StatusRequestTimeout, "Timed out reading request body"}, + // A client that went away gets no body, matching the failover path. + {"client disconnect", io.ErrUnexpectedEOF, true, 499, ""}, {"truncated body", io.ErrUnexpectedEOF, false, http.StatusBadRequest, "Failed to read request body"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) - body := io.MultiReader(strings.NewReader(`{"model":"claude-sonnet-4-5","messages":[`), iotest.ErrReader(tc.readErr)) - req := httptest.NewRequest(http.MethodPost, "/v1/messages", body) - req.ContentLength = 1 << 20 + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + failing := iotest.ErrReader(tc.readErr) if tc.cancelCtx { - ctx, cancel := context.WithCancel(req.Context()) - cancel() - req = req.WithContext(ctx) + failing = cancelOnReadErr{err: tc.readErr, cancel: cancel} } + body := io.MultiReader(strings.NewReader(`{"model":"claude-sonnet-4-5","messages":[`), failing) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", body).WithContext(ctx) + req.ContentLength = 1 << 20 c.Request = req groupID := int64(1) c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID}) @@ -87,7 +104,11 @@ func TestGatewayMessagesClassifiesRequestBodyReadFailures(t *testing.T) { (&GatewayHandler{}).Messages(c) - require.Equal(t, tc.wantStatus, rec.Code) + require.Equal(t, tc.wantStatus, c.Writer.Status()) + if tc.wantMessage == "" { + require.Empty(t, rec.Body.String()) + return + } var resp struct { Type string `json:"type"` Error struct { 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/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/httputil/body.go b/backend/internal/pkg/httputil/body.go index d51bafeff5..901057c487 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" @@ -20,7 +21,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,13 +66,34 @@ func (p *PrereadBody) Bytes() []byte { // client used to compress the body (zstd, gzip, deflate). // 已由 PrereadBody 回填的请求体直接返回其完整切片(零拷贝),不检查内部 // reader 是否已被消费——见 PrereadBody 的文档说明。 -// 读取失败时返回 *RequestBodyReadError,携带已读字节数与耗时供诊断。 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 @@ -86,9 +109,13 @@ func ReadRequestBodyWithPrealloc(req *http.Request) ([]byte, error) { } startedAt := time.Now() - raw, bytesRead, err := readRequestBodyChunks(req.Body, capHint, req.ContentLength) + raw, err := readRequestBodyChunksWithBudget(req.Context(), req.Body, capHint, req.ContentLength) if err != nil { - return nil, &RequestBodyReadError{Err: err, BytesRead: bytesRead, Elapsed: time.Since(startedAt)} + var readErr *RequestBodyReadError + if errors.As(err, &readErr) { + readErr.Elapsed = time.Since(startedAt) + } + return requestBodyBuffer{}, err } enc := strings.ToLower(strings.TrimSpace(req.Header.Get("Content-Encoding"))) @@ -96,14 +123,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 } @@ -111,8 +139,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. -// The returned count is the number of bytes received, including on error. -func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength int64) ([]byte, int64, 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 @@ -121,16 +154,28 @@ 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 ctxErr := ctx.Err(); ctxErr != nil { + return requestBodyBuffer{}, &RequestBodyReadError{Err: ctxErr, BytesRead: int64(total + n)} + } var read int read, err = reader.Read(chunk[n:]) n += read } + // Report the read error before the context: on HTTP/1 a read deadline + // also cancels the request context, which would hide the timeout. if err != nil && err != io.EOF { - return nil, int64(total + n), err + return requestBodyBuffer{}, &RequestBodyReadError{Err: err, BytesRead: int64(total + n)} + } + if ctxErr := ctx.Err(); ctxErr != nil { + return requestBodyBuffer{}, &RequestBodyReadError{Err: ctxErr, BytesRead: int64(total + n)} } if n > 0 { chunks = append(chunks, chunk[:n]) @@ -138,17 +183,21 @@ func readRequestBodyChunks(reader io.Reader, initialCapacity int, contentLength } if err != nil { if len(chunks) == 0 { - return chunk[:0], 0, nil + return requestBodyBuffer{}, nil } if len(chunks) == 1 { - return chunks[0], int64(total), 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, int64(total), nil + return requestBodyBuffer{data: body, charged: int64(total)}, nil } if capacity < requestBodyReadMaxInitCap { capacity *= 2 @@ -162,73 +211,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 } @@ -241,18 +319,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..3e2c8b55a3 --- /dev/null +++ b/backend/internal/pkg/httputil/body_budget.go @@ -0,0 +1,185 @@ +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), r.release +} + +// WithRequestBodyMemoryScope opens a nested reservation on the request's budget +// for representations that die before the handler returns, such as one upstream +// attempt's rewritten body. Release returns only the scope's bytes and is +// idempotent. Without a request budget in ctx it is a no-op; a scope opened after +// the request released its budget rejects every reservation. +func WithRequestBodyMemoryScope(ctx context.Context) (context.Context, func()) { + parent, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + if parent == nil { + return ctx, func() {} + } + parent.mu.Lock() + closed := parent.closed + parent.mu.Unlock() + r := &bodyMemoryReservation{budget: parent.budget, closed: closed} + return context.WithValue(ctx, bodyMemoryReservationKey{}, r), r.release +} + +// DetachRequestBodyMemory opens a reservation on the request's budget for work +// that keeps request-derived buffers after the handler returns, such as an +// accepted asynchronous task. It takes over up to n bytes the request already +// holds for the retained body and reserves only the remainder, so the body is +// never charged twice; reservations made through the returned ctx accumulate on +// it. The handler's release does not affect it, so the caller owns release and +// must call it when the work ends. Without a request budget in ctx it is a no-op. +func DetachRequestBodyMemory(ctx context.Context, n int64) (context.Context, func(), error) { + parent, _ := ctx.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + if parent == nil { + return ctx, func() {}, nil + } + detached, release := WithRequestBodyMemoryScope(ctx) + r, _ := detached.Value(bodyMemoryReservationKey{}).(*bodyMemoryReservation) + parent.mu.Lock() + moved := int64(0) + if !parent.closed && !r.closed { + moved = min(max(n, 0), parent.bytes) + parent.bytes -= moved + } + parent.mu.Unlock() + r.mu.Lock() + r.bytes += moved + r.mu.Unlock() + if err := reserveRequestBodyMemory(detached, n-moved); err != nil { + // Hand the body back: the handler still owns it until it returns. + r.mu.Lock() + r.bytes -= moved + r.mu.Unlock() + parent.mu.Lock() + if parent.closed { + parent.budget.mu.Lock() + parent.budget.used -= moved + parent.budget.mu.Unlock() + } else { + parent.bytes += moved + } + parent.mu.Unlock() + release() + return ctx, func() {}, err + } + return detached, release, nil +} + +func (r *bodyMemoryReservation) release() { + r.mu.Lock() + defer r.mu.Unlock() + if r.closed { + return + } + r.closed = true + r.budget.mu.Lock() + r.budget.used -= r.bytes + r.budget.mu.Unlock() + r.bytes = 0 +} + +// ReserveRequestBodyMemory reserves n bytes before allocating another buffered +// representation of the request body. The reservation shares the ingress budget +// and is retained until the release function of the handler, or of the innermost +// WithRequestBodyMemoryScope in ctx, runs. Without a budget in +// ctx it is a no-op. Callers must propagate exhaustion instead of allocating +// through an unbudgeted fallback. Unlike ingress reads, it ignores ctx +// cancellation: callers that keep working after a client disconnect own that +// policy. +func ReserveRequestBodyMemory(ctx context.Context, n int64) error { + return reserveBodyMemory(ctx, n) +} + +func reserveRequestBodyMemory(ctx context.Context, n int64) error { + if err := ctx.Err(); err != nil { + return err + } + return reserveBodyMemory(ctx, n) +} + +func reserveBodyMemory(ctx context.Context, n int64) error { + 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 returns up to n bytes previously reserved through ctx, +// for a representation that was never allocated or came out smaller than its +// reservation. It never refunds another request's or scope's bytes. +func ReleaseRequestBodyMemory(ctx context.Context, n int64) { + releaseRequestBodyMemory(ctx, n) +} + +// 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 + } + n = min(n, r.bytes) + 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..b1086ca912 --- /dev/null +++ b/backend/internal/pkg/httputil/body_budget_test.go @@ -0,0 +1,564 @@ +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 TestReserveRequestBodyMemorySharesIngressBudgetAndRelease(t *testing.T) { + budget := NewBodyMemoryBudget(100) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(strings.Repeat("x", 20))).WithContext(ctx) + if _, err := ReadRequestBodyWithPrealloc(req); err != nil { + t.Fatal(err) + } + // The ingress reader reserves the body and one byte for overflow detection. + if err := ReserveRequestBodyMemory(ctx, 79); err != nil { + t.Fatal(err) + } + if err := ReserveRequestBodyMemory(ctx, 1); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("rewrite bypassed the ingress reservation: %v", err) + } + ctx2, release2 := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release2() + if err := ReserveRequestBodyMemory(ctx2, 1); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("parallel request bypassed shared capacity: %v", err) + } + release() + release() + if err := ReserveRequestBodyMemory(ctx2, 100); err != nil { + t.Fatalf("failed reservation or cleanup leaked capacity: %v", err) + } + release2() + if err := ReserveRequestBodyMemory(ctx, 1); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("closed request accepted a new reservation: %v", err) + } + if budget.used != 0 { + t.Fatalf("leaked reservations: %d", budget.used) + } +} + +func TestReserveRequestBodyMemoryWithoutBudgetOrAllocation(t *testing.T) { + if err := ReserveRequestBodyMemory(context.Background(), 1<<30); err != nil { + t.Fatal(err) + } + budget := NewBodyMemoryBudget(1) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + for _, size := range []int64{0, -1} { + if err := ReserveRequestBodyMemory(ctx, size); err != nil { + t.Fatal(err) + } + } + if budget.used != 0 { + t.Fatalf("non-positive allocation consumed budget: %d", budget.used) + } +} + +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) + } +} + +func TestRequestBodyMemoryScopeReleasesOnlyItsBytes(t *testing.T) { + if ctx, release := WithRequestBodyMemoryScope(context.Background()); ctx != context.Background() { + t.Fatal("scope without a request budget must be a no-op") + } else { + release() + } + budget := NewBodyMemoryBudget(100) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + if err := ReserveRequestBodyMemory(ctx, 30); err != nil { + t.Fatal(err) + } + scope, releaseScope := WithRequestBodyMemoryScope(ctx) + if err := ReserveRequestBodyMemory(scope, 50); err != nil { + t.Fatal(err) + } + if err := ReserveRequestBodyMemory(scope, 30); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("scope bypassed shared capacity: %v", err) + } + releaseScope() + releaseScope() // Idempotent cleanup cannot refund the request's own bytes. + if budget.used != 30 { + t.Fatalf("scope release returned %d of the request's bytes", 30-budget.used) + } + if err := ReserveRequestBodyMemory(scope, 1); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("closed scope accepted a new reservation: %v", err) + } + release() + late, releaseLate := WithRequestBodyMemoryScope(ctx) + defer releaseLate() + if err := ReserveRequestBodyMemory(late, 1); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("scope outlived its request: %v", err) + } + if budget.used != 0 { + t.Fatalf("leaked reservations: %d", budget.used) + } +} + +func TestReleaseRequestBodyMemoryCapsAtOwnReservation(t *testing.T) { + budget := NewBodyMemoryBudget(100) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + if err := ReserveRequestBodyMemory(ctx, 40); err != nil { + t.Fatal(err) + } + scope, releaseScope := WithRequestBodyMemoryScope(ctx) + defer releaseScope() + if err := ReserveRequestBodyMemory(scope, 20); err != nil { + t.Fatal(err) + } + ReleaseRequestBodyMemory(scope, 100) + if budget.used != 40 { + t.Fatalf("scope refunded another reservation: used=%d", budget.used) + } + ReleaseRequestBodyMemory(ctx, 10) + ReleaseRequestBodyMemory(ctx, -1) + if budget.used != 30 { + t.Fatalf("partial release: used=%d", budget.used) + } + release() + ReleaseRequestBodyMemory(ctx, 30) + if budget.used != 0 { + t.Fatalf("release after close changed the budget: used=%d", budget.used) + } +} + +func TestDetachRequestBodyMemoryOutlivesHandlerRelease(t *testing.T) { + budget := NewBodyMemoryBudget(100) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + detached, releaseDetached, err := DetachRequestBodyMemory(ctx, 40) + if err != nil { + t.Fatal(err) + } + release() // The handler returns while the detached work still runs. + if budget.used != 40 { + t.Fatalf("detached body must stay reserved: %d", budget.used) + } + if err := ReserveRequestBodyMemory(detached, 30); err != nil { + t.Fatalf("detached work must keep reserving after handler release: %v", err) + } + if err := ReserveRequestBodyMemory(detached, 31); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("detached reservations still share the budget: %v", err) + } + releaseDetached() + releaseDetached() + if budget.used != 0 { + t.Fatalf("leaked reservations: %d", budget.used) + } +} + +func TestDetachRequestBodyMemoryTakesOverTheRequestCharge(t *testing.T) { + budget := NewBodyMemoryBudget(100) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + if err := ReserveRequestBodyMemory(ctx, 70); err != nil { + t.Fatal(err) + } + // The retained body is already charged to the request, so detaching it must + // not need a second copy's worth of capacity. + _, releaseDetached, err := DetachRequestBodyMemory(ctx, 60) + if err != nil { + t.Fatalf("detach charged the body twice: %v", err) + } + if budget.used != 70 { + t.Fatalf("detach changed the shared usage: %d", budget.used) + } + release() + if budget.used != 60 { + t.Fatalf("handler release must leave only the detached body: %d", budget.used) + } + releaseDetached() + if budget.used != 0 { + t.Fatalf("leaked reservations: %d", budget.used) + } + + ctx, release = WithRequestBodyMemoryBudget(context.Background(), budget) + if err := ReserveRequestBodyMemory(ctx, 50); err != nil { + t.Fatal(err) + } + if _, _, err := DetachRequestBodyMemory(ctx, 101); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("want capacity error, got %v", err) + } + if budget.used != 50 { + t.Fatalf("failed detach must return the body to the request: %d", budget.used) + } + release() + if budget.used != 0 { + t.Fatalf("failed detach leaked reservations: %d", budget.used) + } +} + +func TestDetachRequestBodyMemoryRejectsWhenBudgetExhausted(t *testing.T) { + budget := NewBodyMemoryBudget(100) + ctx, release := WithRequestBodyMemoryBudget(context.Background(), budget) + defer release() + if _, _, err := DetachRequestBodyMemory(ctx, 101); !errors.Is(err, ErrRequestBodyMemoryBudget) { + t.Fatalf("want capacity error, got %v", err) + } + if budget.used != 0 { + t.Fatalf("failed detach consumed budget: %d", budget.used) + } + if got, releaseNoop, err := DetachRequestBodyMemory(context.Background(), 101); err != nil || got == nil { + t.Fatalf("without a budget detach is a no-op: %v", err) + } else { + releaseNoop() + } +} diff --git a/backend/internal/pkg/httputil/body_read_error.go b/backend/internal/pkg/httputil/body_read_error.go index 3cfb304b39..5acaa741db 100644 --- a/backend/internal/pkg/httputil/body_read_error.go +++ b/backend/internal/pkg/httputil/body_read_error.go @@ -139,8 +139,7 @@ func classifyRequestBodyReadError(req *http.Request, err error) string { } // Check timeouts first: on HTTP/1 a read deadline also cancels the request // context, which would otherwise look like a client disconnect. - var netErr net.Error - if errors.Is(err, os.ErrDeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) { + if IsRequestBodyReadTimeout(err) { return RequestBodyReadErrorTimeout } if requestBodyClientGone(req, err, lower) { @@ -151,12 +150,20 @@ func classifyRequestBodyReadError(req *http.Request, err error) string { if errors.Is(err, io.ErrUnexpectedEOF) || strings.Contains(lower, "request declared a content-length") { return RequestBodyReadErrorTruncated } + var netErr net.Error if errors.As(err, &netErr) { return RequestBodyReadErrorTransport } return RequestBodyReadErrorIO } +// IsRequestBodyReadTimeout reports whether a body read failed because a read +// deadline expired (for example WithBodyReadTimeout's per-read deadline). +func IsRequestBodyReadTimeout(err error) bool { + var netErr net.Error + return errors.Is(err, os.ErrDeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) +} + func requestBodyClientGone(req *http.Request, err error, lowerErr string) bool { if errors.Is(err, context.Canceled) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) { return true 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/api_key_repo.go b/backend/internal/repository/api_key_repo.go index d2a8a83f10..07c12e43af 100644 --- a/backend/internal/repository/api_key_repo.go +++ b/backend/internal/repository/api_key_repo.go @@ -231,6 +231,8 @@ func (r *apiKeyRepository) GetByKeyForAuth(ctx context.Context, key string) (*se group.FieldProfitControlEnabled, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer, + // OpenAI 选号从 ctx 分组读取隐私门,漏选会放行未设置隐私的账号。 + group.FieldRequirePrivacySet, ) }). Only(ctx) diff --git a/backend/internal/repository/api_key_repo_profit_projection_integration_test.go b/backend/internal/repository/api_key_repo_profit_projection_integration_test.go index 283b103d9b..ff2e398412 100644 --- a/backend/internal/repository/api_key_repo_profit_projection_integration_test.go +++ b/backend/internal/repository/api_key_repo_profit_projection_integration_test.go @@ -28,6 +28,7 @@ func TestGetByKeyForAuthCarriesProfitControlProjection(t *testing.T) { ProfitControlEnabled: true, ProfitMinMargin: 0.2, ProfitSafetyBuffer: 0.05, + RequirePrivacySet: true, }) user := mustCreateUser(t, integrationEntClient, &service.User{ Email: fmt.Sprintf("profit-proj-%d@example.com", suffix), Concurrency: 5, @@ -57,4 +58,6 @@ func TestGetByKeyForAuthCarriesProfitControlProjection(t *testing.T) { require.True(t, got.Group.ProfitControlEnabled, "profit_control_enabled 必须进入认证投影(投影漏列会让门静默失效)") require.InDelta(t, 0.2, got.Group.ProfitMinMargin, 1e-9) require.InDelta(t, 0.05, got.Group.ProfitSafetyBuffer, 1e-9) + // OpenAI 选号从认证分组读取隐私门,漏列会放行未设置隐私的账号。 + require.True(t, got.Group.RequirePrivacySet, "require_privacy_set 必须进入认证投影") } 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/fixtures_integration_test.go b/backend/internal/repository/fixtures_integration_test.go index 98e0085e2f..50e398b3ea 100644 --- a/backend/internal/repository/fixtures_integration_test.go +++ b/backend/internal/repository/fixtures_integration_test.go @@ -96,7 +96,8 @@ func mustCreateGroup(t *testing.T, client *dbent.Client, g *service.Group) *serv SetCodexModelsManifestConfig(g.CodexModelsManifestConfig). SetProfitControlEnabled(g.ProfitControlEnabled). SetProfitMinMargin(g.ProfitMinMargin). - SetProfitSafetyBuffer(g.ProfitSafetyBuffer) + SetProfitSafetyBuffer(g.ProfitSafetyBuffer). + SetRequirePrivacySet(g.RequirePrivacySet) if g.Description != "" { create.SetDescription(g.Description) } diff --git a/backend/internal/repository/gateway_cache.go b/backend/internal/repository/gateway_cache.go index 36935160da..4e5faf6ca2 100644 --- a/backend/internal/repository/gateway_cache.go +++ b/backend/internal/repository/gateway_cache.go @@ -270,15 +270,21 @@ func (c *gatewayCache) GetReasoningContent(ctx context.Context, itemID string) ( } const ( - cyberSessionBlockPrefix = "cyber_session_block:" - cyberSessionScopePrefix = "cyber_session_scope:" - cyberSessionRedisCommandMaxKeys = 128 + cyberSessionBlockPrefix = "cyber_session_block:" + cyberSessionScopePrefix = "cyber_session_scope:" + cyberSessionTranscriptLengthsPrefix = "cyber_session_transcript_lengths:" + cyberSessionRedisCommandMaxKeys = 128 ) +func cyberSessionTranscriptLengthsKey(apiKeyID int64) string { + return cyberSessionTranscriptLengthsPrefix + strconv.FormatInt(apiKeyID, 10) +} + // SetCyberSessionBlocked writes exact blocks in bounded transactions. The -// coarse scope is activated only after all exact blocks have been stored. -func (c *gatewayCache) SetCyberSessionBlocked(ctx context.Context, scopeKey string, keys []string, ttl time.Duration) error { - if len(keys) == 0 { +// transcript length index and the coarse scope are activated only after all +// exact blocks have been stored. +func (c *gatewayCache) SetCyberSessionBlocked(ctx context.Context, block service.CyberSessionBlock, ttl time.Duration) error { + if len(block.Keys) == 0 { return nil } exactKeys := make([]string, 0, cyberSessionRedisCommandMaxKeys) @@ -294,7 +300,7 @@ func (c *gatewayCache) SetCyberSessionBlocked(ctx context.Context, scopeKey stri exactKeys = exactKeys[:0] return err } - for _, key := range keys { + for _, key := range block.Keys { if key != "" { exactKeys = append(exactKeys, key) if len(exactKeys) == cyberSessionRedisCommandMaxKeys { @@ -307,18 +313,53 @@ func (c *gatewayCache) SetCyberSessionBlocked(ctx context.Context, scopeKey stri if err := flush(); err != nil { return err } - if scopeKey != "" { - return c.rdb.Set(ctx, cyberSessionScopePrefix+scopeKey, "1", ttl).Err() + if block.ScopeKey == "" { + return nil } - return nil + pipe := c.rdb.TxPipeline() + if len(block.TranscriptLengths) > 0 { + lengthsKey := cyberSessionTranscriptLengthsKey(block.APIKeyID) + members := make([]any, len(block.TranscriptLengths)) + for i, length := range block.TranscriptLengths { + members[i] = length + } + pipe.SAdd(ctx, lengthsKey, members...) + pipe.Expire(ctx, lengthsKey, ttl) + } + pipe.Set(ctx, cyberSessionScopePrefix+block.ScopeKey, "1", ttl) + _, err := pipe.Exec(ctx) + return err } -func (c *gatewayCache) IsCyberSessionScopeActive(ctx context.Context, scopeKey string) (bool, error) { - n, err := c.rdb.Exists(ctx, cyberSessionScopePrefix+scopeKey).Result() - if err != nil { - return false, err +// cyberSessionTranscriptLengthsScript reads the API key's length index only +// when the source scope is active, keeping inactive sources to one EXISTS. +var cyberSessionTranscriptLengthsScript = redis.NewScript(` + if redis.call('EXISTS', KEYS[1]) == 0 then + return {} + end + return redis.call('SMEMBERS', KEYS[2]) +`) + +func (c *gatewayCache) CyberSessionTranscriptLengths(ctx context.Context, apiKeyID int64, scopeKey string) ([]int, error) { + if scopeKey == "" { + return nil, nil } - return n > 0, nil + members, err := cyberSessionTranscriptLengthsScript.Run(ctx, c.rdb, []string{ + cyberSessionScopePrefix + scopeKey, + cyberSessionTranscriptLengthsKey(apiKeyID), + }).StringSlice() + if err != nil { + return nil, err + } + lengths := make([]int, 0, len(members)) + for _, member := range members { + length, err := strconv.Atoi(member) + if err != nil { + return nil, fmt.Errorf("invalid cyber transcript length %q: %w", member, err) + } + lengths = append(lengths, length) + } + return lengths, nil } // FindCyberSessionBlocked checks bounded batches in caller order and stops at diff --git a/backend/internal/repository/gateway_cache_cyber_test.go b/backend/internal/repository/gateway_cache_cyber_test.go index 03f29e82a1..6194002045 100644 --- a/backend/internal/repository/gateway_cache_cyber_test.go +++ b/backend/internal/repository/gateway_cache_cyber_test.go @@ -49,7 +49,7 @@ func (h *cyberRedisCommandHook) ProcessPipelineHook(next redis.ProcessPipelineHo } } -func TestGatewayCacheCyberBlockWritesScopeAndExactKeysTogether(t *testing.T) { +func TestGatewayCacheCyberBlockWritesScopeLengthsAndExactKeysTogether(t *testing.T) { server := miniredis.RunT(t) client := redis.NewClient(&redis.Options{Addr: server.Addr()}) t.Cleanup(func() { _ = client.Close() }) @@ -57,17 +57,49 @@ func TestGatewayCacheCyberBlockWritesScopeAndExactKeysTogether(t *testing.T) { require.True(t, ok) ctx := context.Background() - require.NoError(t, store.SetCyberSessionBlocked(ctx, "scope-1", []string{"block-1", "block-2"}, time.Minute)) - active, err := store.IsCyberSessionScopeActive(ctx, "scope-1") + lengths, err := store.CyberSessionTranscriptLengths(ctx, 7, "scope-1") require.NoError(t, err) - require.True(t, active) + require.Empty(t, lengths) + + require.NoError(t, store.SetCyberSessionBlocked(ctx, service.CyberSessionBlock{ + APIKeyID: 7, ScopeKey: "scope-1", Keys: []string{"block-1", "block-2"}, TranscriptLengths: []int{3, 2}, + }, time.Minute)) + require.NoError(t, store.SetCyberSessionBlocked(ctx, service.CyberSessionBlock{ + APIKeyID: 7, ScopeKey: "scope-2", Keys: []string{"block-3"}, TranscriptLengths: []int{3, 40}, + }, time.Minute)) + lengths, err = store.CyberSessionTranscriptLengths(ctx, 7, "scope-1") + require.NoError(t, err) + require.ElementsMatch(t, []int{2, 3, 40}, lengths, "lengths are indexed per API key, like the block keys") + lengths, err = store.CyberSessionTranscriptLengths(ctx, 7, "inactive-scope") + require.NoError(t, err) + require.Empty(t, lengths) + lengths, err = store.CyberSessionTranscriptLengths(ctx, 8, "scope-1") + require.NoError(t, err) + require.Empty(t, lengths) + matched, err := store.FindCyberSessionBlocked(ctx, []string{"missing", "block-1", "block-2"}) require.NoError(t, err) require.Equal(t, "block-1", matched) require.Greater(t, server.TTL(cyberSessionScopePrefix+"scope-1"), time.Duration(0)) + require.Greater(t, server.TTL(cyberSessionTranscriptLengthsKey(7)), time.Duration(0)) require.Equal(t, server.TTL(cyberSessionBlockPrefix+"block-1"), server.TTL(cyberSessionBlockPrefix+"block-2")) } +func TestGatewayCacheCyberBlockWithoutScopeSkipsTranscriptIndex(t *testing.T) { + server := miniredis.RunT(t) + client := redis.NewClient(&redis.Options{Addr: server.Addr()}) + t.Cleanup(func() { _ = client.Close() }) + store, ok := NewGatewayCache(client).(service.CyberSessionBlockStore) + require.True(t, ok) + + ctx := context.Background() + require.NoError(t, store.SetCyberSessionBlocked(ctx, service.CyberSessionBlock{APIKeyID: 7, Keys: []string{"explicit"}, TranscriptLengths: []int{3}}, time.Minute)) + require.False(t, server.Exists(cyberSessionTranscriptLengthsKey(7))) + matched, err := store.FindCyberSessionBlocked(ctx, []string{"explicit"}) + require.NoError(t, err) + require.Equal(t, "explicit", matched) +} + func TestGatewayCacheCyberBlockCommandsAreBoundedAndLookupShortCircuits(t *testing.T) { server := miniredis.RunT(t) client := redis.NewClient(&redis.Options{Addr: server.Addr()}) @@ -82,8 +114,9 @@ func TestGatewayCacheCyberBlockCommandsAreBoundedAndLookupShortCircuits(t *testi keys[i] = "block-" + strconv.Itoa(i) } ctx := context.Background() - require.NoError(t, store.SetCyberSessionBlocked(ctx, "large-scope", keys, time.Minute)) - require.Equal(t, []int{cyberSessionRedisCommandMaxKeys, cyberSessionRedisCommandMaxKeys, 44}, hook.setBatchSizes) + require.NoError(t, store.SetCyberSessionBlocked(ctx, service.CyberSessionBlock{APIKeyID: 7, ScopeKey: "large-scope", Keys: keys}, time.Minute)) + // Exact blocks in bounded batches, then the scope activation transaction. + require.Equal(t, []int{cyberSessionRedisCommandMaxKeys, cyberSessionRedisCommandMaxKeys, 44, 1}, hook.setBatchSizes) lookup := make([]string, len(keys)) for i := range lookup { 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/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_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/server/http.go b/backend/internal/server/http.go index b4c1fda3ef..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,8 +122,7 @@ func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server { // IdleTimeout: 空闲连接超时时间,释放不活跃的连接资源 IdleTimeout: time.Duration(cfg.Server.IdleTimeout) * time.Second, // 注意:不设置 WriteTimeout,因为流式响应可能持续十几分钟 - // 不设置 ReadTimeout,因为大请求体可能需要较长时间读取; - // 请求体改由 request_body_idle_timeout 按“无数据到达”的时长约束 + // 请求体使用逐次读取的 idle deadline,不设置覆盖整个大请求上传的 ReadTimeout。 } globalMaxSize := cfg.Server.MaxRequestBodySize @@ -133,7 +133,6 @@ func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server { httpHandler = http.MaxBytesHandler(httpHandler, globalMaxSize) log.Printf("Global max request body size: %d bytes (%.2f MB)", globalMaxSize, float64(globalMaxSize)/(1<<20)) } - httpHandler = requestBodyIdleTimeoutHandler(httpHandler, time.Duration(cfg.Server.RequestBodyIdleTimeout)*time.Second) // 根据配置决定是否启用 H2C if cfg.Server.H2C.Enabled { @@ -161,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 b35ac3d485..ad6e42d6c4 100644 --- a/backend/internal/server/middleware/audit_log.go +++ b/backend/internal/server/middleware/audit_log.go @@ -52,6 +52,7 @@ 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": {}, 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 10d05d9962..d77d22541a 100644 --- a/backend/internal/server/middleware/group_model_allowlist.go +++ b/backend/internal/server/middleware/group_model_allowlist.go @@ -103,8 +103,8 @@ func isResponsesWebSocketRoute(c *gin.Context) bool { } // groupModelAllowlistModelsFromBody 读取请求体并提取客户端模型名,随后把请求体 -// 回填(PrereadBody),保证后续 handler 零拷贝重读。读取失败按共享分类返回 -// 400/408/413/499(返回 false 表示已写出响应并 Abort)。 +// 回填(PrereadBody),保证后续 handler 零拷贝重读。读取失败按现有合成中间件 +// 的方式返回 400/413(返回 false 表示已写出响应并 Abort)。 // // 下游同时存在 gjson(首个、大小写敏感)、encoding/json 绑定(末值、大小写 // 不敏感)与 multipart 表单(首/末字段)三类解析器,这里返回「任一解析器可能 @@ -112,6 +112,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, "middleware.group_model_allowlist", err) { + return nil, false + } AbortWithRequestBodyReadFailure(c, "middleware.group_model_allowlist", err) return nil, false } 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..70666849fb --- /dev/null +++ b/backend/internal/server/middleware/request_body_memory.go @@ -0,0 +1,38 @@ +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. +// A read deadline on HTTP/1 also cancels the request context; timeouts are left +// to AbortWithRequestBodyReadFailure (408). +func RejectRequestBodyReadError(c *gin.Context, component string, err error) bool { + if err != nil && c != nil && c.Request != nil && c.Request.Context().Err() != nil && !pkghttputil.IsRequestBodyReadTimeout(err) { + logRequestBodyReadFailure(c, component, pkghttputil.DescribeRequestBodyReadFailure(c.Request, err)) + 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..67cda868ff --- /dev/null +++ b/backend/internal/server/middleware/request_body_memory_test.go @@ -0,0 +1,109 @@ +package middleware + +import ( + "context" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "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 + readErr error + handled bool + }{ + {name: "cancelled", cancelled: true, handled: true}, + {name: "cancelled_after_commit", cancelled: true, committed: true, handled: true}, + {name: "ordinary_read_error"}, + // An HTTP/1 read deadline also cancels the request context; the + // timeout must reach AbortWithRequestBodyReadFailure (408). + {name: "read_timeout_with_cancelled_context", cancelled: true, readErr: &net.OpError{Op: "read", Net: "tcp", Err: os.ErrDeadlineExceeded}}, + } { + 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() + readErr := tc.readErr + if readErr == nil { + readErr = io.ErrUnexpectedEOF + } + require.Equal(t, tc.handled, RejectRequestBodyReadError(c, "test", readErr)) + require.Equal(t, tc.handled, c.IsAborted()) + status := http.StatusOK + if tc.handled && !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/request_body_read_failure.go b/backend/internal/server/middleware/request_body_read_failure.go index 22b15a8f43..a41430a62f 100644 --- a/backend/internal/server/middleware/request_body_read_failure.go +++ b/backend/internal/server/middleware/request_body_read_failure.go @@ -13,8 +13,12 @@ import ( func AbortWithRequestBodyReadFailure(c *gin.Context, component string, err error) { failure := httputil.DescribeRequestBodyReadFailure(c.Request, err) if failure.Kind != httputil.RequestBodyReadErrorMaxBytes { - fields := append([]zap.Field{zap.String("component", component)}, failure.LogFields()...) - logger.FromContext(c.Request.Context()).Warn("read request body failed", fields...) + logRequestBodyReadFailure(c, component, failure) } c.AbortWithStatusJSON(failure.Status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": failure.Message}}) } + +func logRequestBodyReadFailure(c *gin.Context, component string, failure httputil.RequestBodyReadFailure) { + fields := append([]zap.Field{zap.String("component", component)}, failure.LogFields()...) + logger.FromContext(c.Request.Context()).Warn("read request body failed", fields...) +} diff --git a/backend/internal/server/request_body_idle_timeout.go b/backend/internal/server/request_body_idle_timeout.go deleted file mode 100644 index 967910ec2e..0000000000 --- a/backend/internal/server/request_body_idle_timeout.go +++ /dev/null @@ -1,98 +0,0 @@ -package server - -import ( - "errors" - "io" - "net/http" - "os" - "time" -) - -// requestBodyIdleTimeoutHandler fails a request body read that receives no -// bytes for timeout. Unlike http.Server.ReadTimeout it never bounds the total -// upload time, so large bodies that keep making progress are not cut off, and -// time the handler spends between reads is not counted as client idleness: -// every Read re-arms the deadline before it waits. -// -// HTTP/2 stream deadlines fire even without a pending Read, so they are armed -// only during a Read. HTTP/1 deadlines only affect reads, so they stay armed -// while the body is unfinished: net/http drains up to 256 KiB of an unread -// body itself before writing the response, and that drain must not wait on a -// stalled client forever when a handler rejects a request without reading it. -// After a timeout the expired deadline is kept, so that drain fails at once -// and the connection is closed instead of reused. -func requestBodyIdleTimeoutHandler(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 { - next.ServeHTTP(w, r) - return - } - body := &idleTimeoutBody{ - body: r.Body, - controller: http.NewResponseController(w), - timeout: timeout, - http1: r.ProtoMajor == 1, - } - if body.http1 { - body.arm() - } - // Shallow copy like http.MaxBytesHandler: net/http inspects the - // original *body when writing the response to decide whether the - // connection can be reused. - r2 := *r - r2.Body = body - next.ServeHTTP(w, &r2) - }) -} - -type idleTimeoutBody struct { - body io.ReadCloser - controller *http.ResponseController - timeout time.Duration - http1 bool - // unsupported is set when the ResponseWriter cannot set read deadlines - // (for example httptest.ResponseRecorder); reads are then unbounded. - unsupported bool - timeoutErr error -} - -// arm sets the deadline to now+timeout and reports whether it is supported. -func (b *idleTimeoutBody) arm() bool { - if b.unsupported { - return false - } - if err := b.controller.SetReadDeadline(time.Now().Add(b.timeout)); err != nil { - b.unsupported = true - return false - } - return true -} - -func (b *idleTimeoutBody) Read(p []byte) (int, error) { - if b.timeoutErr != nil { - return 0, b.timeoutErr - } - if len(p) == 0 || !b.arm() { - return b.body.Read(p) - } - n, err := b.body.Read(p) - switch { - case err == nil && b.http1: - b.arm() - case err != nil && errors.Is(err, os.ErrDeadlineExceeded): - b.timeoutErr = err - default: - // The server sets no ReadTimeout, so "no deadline" is the state to - // restore. At EOF net/http has already cleared the HTTP/1 deadline - // for its background read, which must not inherit a new one. - _ = b.controller.SetReadDeadline(time.Time{}) - } - return n, err -} - -func (b *idleTimeoutBody) Close() error { - return b.body.Close() -} diff --git a/backend/internal/server/request_body_idle_timeout_test.go b/backend/internal/server/request_body_idle_timeout_test.go deleted file mode 100644 index 172a43068f..0000000000 --- a/backend/internal/server/request_body_idle_timeout_test.go +++ /dev/null @@ -1,339 +0,0 @@ -//go:build unit - -package server - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "net" - "net/http" - "net/http/httptest" - "strconv" - "strings" - "testing" - "time" - - "github.com/Wei-Shaw/sub2api/internal/handler" - 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" -) - -const testBodyIdleTimeout = 300 * time.Millisecond - -// bodyProbeHandler reads the body through the shared gateway reader. pauseAfter -// bytes into the body it stops reading for pause, and after a successful read it -// waits postReadWait before checking that the request context is still alive. -func bodyProbeHandler(pauseAfter int64, pause, postReadWait time.Duration) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if pause > 0 { - if _, err := io.CopyN(io.Discard, r.Body, pauseAfter); err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - time.Sleep(pause) - } - body, err := pkghttputil.ReadRequestBodyWithPrealloc(r) - if err != nil { - failure := pkghttputil.DescribeRequestBodyReadFailure(r, err) - w.Header().Set("X-Body-Error", failure.Kind) - w.WriteHeader(failure.Status) - return - } - if postReadWait > 0 { - time.Sleep(postReadWait) - if r.Context().Err() != nil { - w.WriteHeader(http.StatusServiceUnavailable) - return - } - } - if pause > 0 { - body = append(make([]byte, pauseAfter), body...) - } - _, _ = io.WriteString(w, strconv.Itoa(len(body))) - }) -} - -func newIdleTimeoutTestServer(t *testing.T, h http.Handler, h2c bool) (*httptest.Server, *http.Client) { - t.Helper() - ts := httptest.NewUnstartedServer(requestBodyIdleTimeoutHandler(h, testBodyIdleTimeout)) - transport := &http.Transport{} - if h2c { - protocols := new(http.Protocols) - protocols.SetHTTP1(true) - protocols.SetUnencryptedHTTP2(true) - ts.Config.Protocols = protocols - clientProtocols := new(http.Protocols) - clientProtocols.SetUnencryptedHTTP2(true) - transport.Protocols = clientProtocols - } - ts.Start() - t.Cleanup(ts.Close) - t.Cleanup(transport.CloseIdleConnections) - return ts, &http.Client{Transport: transport, Timeout: 10 * time.Second} -} - -func forEachProtocol(t *testing.T, fn func(t *testing.T, h2c bool)) { - for _, h2c := range []bool{false, true} { - name := "http1" - if h2c { - name = "h2c" - } - t.Run(name, func(t *testing.T) { fn(t, h2c) }) - } -} - -// writeSlowly sends total bytes in pieces separated by gap, then closes. -func writeSlowly(w *io.PipeWriter, total, pieces int, gap time.Duration) { - piece := bytes.Repeat([]byte("x"), total/pieces) - for i := 0; i < pieces; i++ { - if i > 0 { - time.Sleep(gap) - } - if _, err := w.Write(piece); err != nil { - return - } - } - _ = w.Close() -} - -func TestRequestBodyIdleTimeoutAllowsSlowProgressingUpload(t *testing.T) { - forEachProtocol(t, func(t *testing.T, h2c bool) { - ts, client := newIdleTimeoutTestServer(t, bodyProbeHandler(0, 0, 0), h2c) - const total, pieces = 64 << 10, 8 - pr, pw := io.Pipe() - // 8 pieces 100ms apart: the upload takes ~2.3x the idle timeout in - // total, but no single gap reaches it. - go writeSlowly(pw, total, pieces, testBodyIdleTimeout/3) - req, err := http.NewRequest(http.MethodPost, ts.URL, pr) - require.NoError(t, err) - req.ContentLength = total - - start := time.Now() - resp, err := client.Do(req) - require.NoError(t, err) - defer func() { _ = resp.Body.Close() }() - got, _ := io.ReadAll(resp.Body) - - require.Equal(t, http.StatusOK, resp.StatusCode, resp.Header.Get("X-Body-Error")) - require.Equal(t, strconv.Itoa(total), string(got)) - require.Greater(t, time.Since(start), testBodyIdleTimeout) - if h2c { - require.Equal(t, 2, resp.ProtoMajor) - } - }) -} - -func TestRequestBodyIdleTimeoutFailsStalledUpload(t *testing.T) { - forEachProtocol(t, func(t *testing.T, h2c bool) { - ts, client := newIdleTimeoutTestServer(t, bodyProbeHandler(0, 0, 0), h2c) - pr, pw := io.Pipe() - defer func() { _ = pw.Close() }() - go func() { _, _ = pw.Write([]byte(`{"model":"x","messages":[`)) }() - req, err := http.NewRequest(http.MethodPost, ts.URL, pr) - require.NoError(t, err) - req.ContentLength = 1 << 20 - - start := time.Now() - resp, err := client.Do(req) - require.NoError(t, err) - defer func() { _ = resp.Body.Close() }() - - require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) - require.Equal(t, pkghttputil.RequestBodyReadErrorTimeout, resp.Header.Get("X-Body-Error")) - elapsed := time.Since(start) - require.GreaterOrEqual(t, elapsed, testBodyIdleTimeout) - require.Less(t, elapsed, 5*time.Second) - }) -} - -// With less than 256 KiB of a declared body unread, net/http discards the -// remainder before writing the response. The expired deadline must stay in -// place so the 408 is sent at once instead of waiting on the stalled client. -func TestRequestBodyIdleTimeoutAnswersStalledSmallHTTP1Upload(t *testing.T) { - ts, _ := newIdleTimeoutTestServer(t, bodyProbeHandler(0, 0, 0), false) - conn, err := net.DialTimeout("tcp", ts.Listener.Addr().String(), time.Second) - require.NoError(t, err) - defer func() { _ = conn.Close() }() - _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) - _, err = io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1000\r\n\r\nabc") - require.NoError(t, err) - - start := time.Now() - resp, err := http.ReadResponse(bufio.NewReader(conn), nil) - require.NoError(t, err) - _ = resp.Body.Close() - - require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) - require.Less(t, time.Since(start), 3*testBodyIdleTimeout) - require.True(t, resp.Close) -} - -// net/http drains up to 256 KiB of an unread HTTP/1 body before it writes the -// response. A handler that rejects a request without reading its stalled body, -// or after reading only part of it, must still answer within the idle timeout -// instead of never sending the response. HTTP/2 resets the stream instead. -func TestRequestBodyIdleTimeoutBoundsUnreadBodyDrain(t *testing.T) { - for _, readFirst := range []int{0, 3} { - reject := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if readFirst > 0 { - if _, err := io.ReadFull(r.Body, make([]byte, readFirst)); err != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - } - w.WriteHeader(http.StatusUnauthorized) - }) - t.Run(fmt.Sprintf("read_%d", readFirst), func(t *testing.T) { - forEachProtocol(t, func(t *testing.T, h2c bool) { - ts, client := newIdleTimeoutTestServer(t, reject, h2c) - start := time.Now() - if h2c { - pr, pw := io.Pipe() - defer func() { _ = pw.Close() }() - go func() { _, _ = pw.Write([]byte("abc")) }() - req, err := http.NewRequest(http.MethodPost, ts.URL, pr) - require.NoError(t, err) - req.ContentLength = 1000 - resp, err := client.Do(req) - require.NoError(t, err) - _ = resp.Body.Close() - require.Equal(t, http.StatusUnauthorized, resp.StatusCode) - require.Less(t, time.Since(start), 3*testBodyIdleTimeout) - return - } - conn, err := net.DialTimeout("tcp", ts.Listener.Addr().String(), time.Second) - require.NoError(t, err) - defer func() { _ = conn.Close() }() - _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) - _, err = io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1000\r\n\r\nabc") - require.NoError(t, err) - resp, err := http.ReadResponse(bufio.NewReader(conn), nil) - require.NoError(t, err) - _ = resp.Body.Close() - require.Equal(t, http.StatusUnauthorized, resp.StatusCode) - require.Less(t, time.Since(start), 3*testBodyIdleTimeout) - require.True(t, resp.Close) - }) - }) - } -} - -// A client that disconnects mid-upload is reported as 499, not as a malformed -// request, using the real net/http error and context behavior. -func TestRequestBodyReadClassifiesHTTP1ClientDisconnect(t *testing.T) { - kinds := make(chan string, 1) - ts, _ := newIdleTimeoutTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, err := pkghttputil.ReadRequestBodyWithPrealloc(r) - kinds <- pkghttputil.DescribeRequestBodyReadFailure(r, err).Kind - }), false) - conn, err := net.DialTimeout("tcp", ts.Listener.Addr().String(), time.Second) - require.NoError(t, err) - _, err = io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1000\r\n\r\nabc") - require.NoError(t, err) - time.Sleep(50 * time.Millisecond) - require.NoError(t, conn.Close()) - - select { - case kind := <-kinds: - require.Equal(t, pkghttputil.RequestBodyReadErrorClientDisconnect, kind) - case <-time.After(5 * time.Second): - t.Fatal("handler did not observe the disconnect") - } -} - -// Time the handler spends between reads is not client idleness: the deadline -// is armed only during a Read. The second half arrives while the handler is -// paused but after one idle timeout, so a deadline left armed from the first -// read would fire (an HTTP/2 stream timer runs even without a pending Read). -// A completed body must also leave the request context alive. -func TestRequestBodyIdleTimeoutIgnoresHandlerPauses(t *testing.T) { - forEachProtocol(t, func(t *testing.T, h2c bool) { - const total = 32 << 10 - probe := bodyProbeHandler(total/2, 3*testBodyIdleTimeout, 2*testBodyIdleTimeout) - ts, client := newIdleTimeoutTestServer(t, probe, h2c) - pr, pw := io.Pipe() - go writeSlowly(pw, total, 2, 3*testBodyIdleTimeout/2) - req, err := http.NewRequest(http.MethodPost, ts.URL, pr) - require.NoError(t, err) - req.ContentLength = total - - resp, err := client.Do(req) - require.NoError(t, err) - defer func() { _ = resp.Body.Close() }() - got, _ := io.ReadAll(resp.Body) - - require.Equal(t, http.StatusOK, resp.StatusCode, resp.Header.Get("X-Body-Error")) - require.Equal(t, strconv.Itoa(total), string(got)) - }) -} - -func TestRequestBodyIdleTimeoutFallsBackWithoutDeadlineSupport(t *testing.T) { - h := requestBodyIdleTimeoutHandler(bodyProbeHandler(0, 0, 0), time.Nanosecond) - rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader("hello"))) - require.Equal(t, http.StatusOK, rec.Code) - require.Equal(t, "5", rec.Body.String()) -} - -func TestRequestBodyIdleTimeoutDisabled(t *testing.T) { - next := http.NotFoundHandler() - require.Equal(t, fmt.Sprintf("%p", next), fmt.Sprintf("%p", requestBodyIdleTimeoutHandler(next, 0))) -} - -// End to end over a real HTTP/1 connection: a stalled Anthropic /v1/messages -// upload is answered with 408 after the configured idle timeout, and the -// connection is closed rather than reused. -func TestHTTPServerRequestBodyIdleTimeoutAnthropicMessages(t *testing.T) { - gin.SetMode(gin.TestMode) - r := gin.New() - groupID := int64(1) - r.POST("/v1/messages", func(c *gin.Context) { - c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID}) - c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) - c.Next() - }, (&handler.GatewayHandler{}).Messages) - cfg := ingressTestConfig() - cfg.Server.MaxRequestBodySize = 0 - cfg.Gateway.MaxBodySize = 0 - cfg.Server.RequestBodyIdleTimeout = 1 - addr, stop := serveIngressTestServer(t, ProvideHTTPServer(cfg, r)) - defer stop() - - conn, err := net.DialTimeout("tcp", addr, time.Second) - require.NoError(t, err) - defer func() { _ = conn.Close() }() - _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) - partial := `{"model":"claude-sonnet-4-5","max_tokens":1,"messages":[` - _, err = io.WriteString(conn, "POST /v1/messages HTTP/1.1\r\nHost: test\r\nContent-Type: application/json\r\nContent-Length: 1048576\r\n\r\n"+partial) - require.NoError(t, err) - - start := time.Now() - reader := bufio.NewReader(conn) - resp, err := http.ReadResponse(reader, nil) - require.NoError(t, err) - body, _ := io.ReadAll(resp.Body) - _ = resp.Body.Close() - - require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) - elapsed := time.Since(start) - require.GreaterOrEqual(t, elapsed, 900*time.Millisecond) - require.Less(t, elapsed, 5*time.Second) - var payload struct { - Error struct { - Type string `json:"type"` - Message string `json:"message"` - } `json:"error"` - } - require.NoError(t, json.Unmarshal(body, &payload)) - require.Equal(t, "invalid_request_error", payload.Error.Type) - require.Equal(t, "Timed out reading request body", payload.Error.Message) - require.True(t, resp.Close, "connection with an unread body must not be reused") - _, err = reader.ReadByte() - require.ErrorIs(t, err, io.EOF) -} diff --git a/backend/internal/server/request_body_read_timeout_test.go b/backend/internal/server/request_body_read_timeout_test.go new file mode 100644 index 0000000000..0886aba544 --- /dev/null +++ b/backend/internal/server/request_body_read_timeout_test.go @@ -0,0 +1,163 @@ +//go:build unit + +package server + +import ( + "bufio" + "encoding/json" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/handler" + 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" +) + +const testBodyReadTimeout = 300 * time.Millisecond + +// bodyKindHandler reads the body through the shared gateway reader and reports +// the classified failure kind and status. +func bodyKindHandler(kinds chan<- string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := pkghttputil.ReadRequestBodyWithPrealloc(r) + if err != nil { + failure := pkghttputil.DescribeRequestBodyReadFailure(r, err) + if kinds != nil { + kinds <- failure.Kind + } + w.Header().Set("X-Body-Error", failure.Kind) + w.WriteHeader(failure.Status) + return + } + _, _ = io.WriteString(w, strconv.Itoa(len(body))) + }) +} + +func newBodyReadTimeoutTestServer(t *testing.T, h http.Handler, h2c bool) (*httptest.Server, *http.Client) { + t.Helper() + ts := httptest.NewUnstartedServer(pkghttputil.WithBodyReadTimeout(h, testBodyReadTimeout)) + transport := &http.Transport{} + if h2c { + protocols := new(http.Protocols) + protocols.SetHTTP1(true) + protocols.SetUnencryptedHTTP2(true) + ts.Config.Protocols = protocols + clientProtocols := new(http.Protocols) + clientProtocols.SetUnencryptedHTTP2(true) + transport.Protocols = clientProtocols + } + ts.Start() + t.Cleanup(ts.Close) + t.Cleanup(transport.CloseIdleConnections) + return ts, &http.Client{Transport: transport, Timeout: 10 * time.Second} +} + +// A stalled upload is classified as a read timeout (408) over both protocols. +// On HTTP/1 the deadline also cancels the request context; the timeout must +// still win over the client-disconnect classification. +func TestBodyReadTimeoutClassifiedAsTimeout(t *testing.T) { + for _, h2c := range []bool{false, true} { + name := "http1" + if h2c { + name = "h2c" + } + t.Run(name, func(t *testing.T) { + ts, client := newBodyReadTimeoutTestServer(t, bodyKindHandler(nil), h2c) + pr, pw := io.Pipe() + defer func() { _ = pw.Close() }() + go func() { _, _ = pw.Write([]byte(`{"model":"x","messages":[`)) }() + req, err := http.NewRequest(http.MethodPost, ts.URL, pr) + require.NoError(t, err) + req.ContentLength = 1 << 20 + + start := time.Now() + resp, err := client.Do(req) + require.NoError(t, err) + defer func() { _ = resp.Body.Close() }() + + require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) + require.Equal(t, pkghttputil.RequestBodyReadErrorTimeout, resp.Header.Get("X-Body-Error")) + elapsed := time.Since(start) + require.GreaterOrEqual(t, elapsed, testBodyReadTimeout) + require.Less(t, elapsed, 5*time.Second) + }) + } +} + +// A client that disconnects mid-upload is still classified as a disconnect, +// using the real net/http error and context behavior. +func TestBodyReadClassifiesHTTP1ClientDisconnect(t *testing.T) { + kinds := make(chan string, 1) + ts, _ := newBodyReadTimeoutTestServer(t, bodyKindHandler(kinds), false) + conn, err := net.DialTimeout("tcp", ts.Listener.Addr().String(), time.Second) + require.NoError(t, err) + _, err = io.WriteString(conn, "POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 1000\r\n\r\nabc") + require.NoError(t, err) + time.Sleep(50 * time.Millisecond) + require.NoError(t, conn.Close()) + + select { + case kind := <-kinds: + require.Equal(t, pkghttputil.RequestBodyReadErrorClientDisconnect, kind) + case <-time.After(5 * time.Second): + t.Fatal("handler did not observe the disconnect") + } +} + +// End to end over a real HTTP/1 connection: a stalled Anthropic /v1/messages +// upload is answered with an Anthropic-format 408 after the configured body +// read timeout instead of an empty 499 or a generic 400. +func TestHTTPServerBodyReadTimeoutAnthropicMessages(t *testing.T) { + gin.SetMode(gin.TestMode) + r := gin.New() + groupID := int64(1) + r.POST("/v1/messages", func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 1, UserID: 1, GroupID: &groupID}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 1, Concurrency: 1}) + c.Next() + }, (&handler.GatewayHandler{}).Messages) + cfg := ingressTestConfig() + cfg.Server.MaxRequestBodySize = 0 + cfg.Gateway.MaxBodySize = 0 + cfg.Gateway.RequestBodyReadTimeoutSeconds = 1 + addr, stop := serveIngressTestServer(t, ProvideHTTPServer(cfg, r)) + defer stop() + + conn, err := net.DialTimeout("tcp", addr, time.Second) + require.NoError(t, err) + defer func() { _ = conn.Close() }() + _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) + partial := `{"model":"claude-sonnet-4-5","max_tokens":1,"messages":[` + _, err = io.WriteString(conn, "POST /v1/messages HTTP/1.1\r\nHost: test\r\nContent-Type: application/json\r\nContent-Length: 1048576\r\n\r\n"+partial) + require.NoError(t, err) + + start := time.Now() + reader := bufio.NewReader(conn) + resp, err := http.ReadResponse(reader, nil) + require.NoError(t, err) + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + + require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) + elapsed := time.Since(start) + require.GreaterOrEqual(t, elapsed, 900*time.Millisecond) + require.Less(t, elapsed, 5*time.Second) + var payload struct { + Error struct { + Type string `json:"type"` + Message string `json:"message"` + } `json:"error"` + } + require.NoError(t, json.Unmarshal(body, &payload)) + require.Equal(t, "invalid_request_error", payload.Error.Type) + require.Equal(t, "Timed out reading request body", payload.Error.Message) + require.True(t, resp.Close, "connection with an unread body must not be reused") +} 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 76a055cb21..0e7dbef05a 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -29,8 +29,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() @@ -562,6 +563,9 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver) body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request) if err != nil { + if middleware.RejectRequestBodyReadError(c, "middleware.composite_route", err) { + return + } middleware.AbortWithRequestBodyReadFailure(c, "middleware.composite_route", err) return } 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 6f970eb0f5..45d3c7cb17 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -3060,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)) @@ -3156,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_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_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 e02541ed0d..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() diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index e6b9a73fa8..20018202b7 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -6,7 +6,6 @@ import ( "context" "encoding/json" "fmt" - "io" "net/http" "strings" "sync/atomic" @@ -124,7 +123,7 @@ func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin. clientDisconnect = streamRes.clientDisconnect } else { // 非流式响应:直接透传 - respBody, err := io.ReadAll(resp.Body) + respBody, err := ReadUpstreamResponseBody(resp.Body, s.antigravitySSEConfig(), c, anthropicTooLargeError) if err != nil { return nil, fmt.Errorf("read upstream response: %w", err) } @@ -171,6 +170,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 +178,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 +243,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/api_key_auth_cache.go b/backend/internal/service/api_key_auth_cache.go index bf66fa0c25..716c0a58c5 100644 --- a/backend/internal/service/api_key_auth_cache.go +++ b/backend/internal/service/api_key_auth_cache.go @@ -53,6 +53,9 @@ type APIKeyAuthUserSnapshot struct { // UserGroupRPMOverride 该 API Key 对应的 (user, group) 专属 RPM 覆盖值。 // nil = 无 override(回退到 group/user 级);0 = 不限流;>0 = 专属上限。 UserGroupRPMOverride *int `json:"user_group_rpm_override,omitempty"` + // UserGroupRPMOverrideGroupID 是成功查询 override 的分组(0 = 未查询或查询失败), + // 让 checkRPM 区分"该分组确认无 override"与"需要回源"。 + UserGroupRPMOverrideGroupID int64 `json:"user_group_rpm_override_group_id,omitempty"` } // APIKeyAuthGroupSnapshot 分组快照 @@ -141,6 +144,9 @@ type APIKeyAuthGroupSnapshot struct { ProfitControlEnabled bool `json:"profit_control_enabled"` ProfitMinMargin float64 `json:"profit_min_margin"` ProfitSafetyBuffer float64 `json:"profit_safety_buffer"` + + // RequirePrivacySet 由 OpenAI 选号从 ctx 分组读取,与 GetByKeyForAuth 投影同步。 + RequirePrivacySet bool `json:"require_privacy_set"` } // APIKeyAuthCacheEntry 缓存条目,支持负缓存 diff --git a/backend/internal/service/api_key_auth_cache_impl.go b/backend/internal/service/api_key_auth_cache_impl.go index cb2ade94b8..2bb7204fd9 100644 --- a/backend/internal/service/api_key_auth_cache_impl.go +++ b/backend/internal/service/api_key_auth_cache_impl.go @@ -14,7 +14,7 @@ import ( "github.com/dgraph-io/ristretto" ) -const apiKeyAuthSnapshotVersion = 25 // v25: group image_count_billing switch (per-image billing on image endpoints) +const apiKeyAuthSnapshotVersion = 27 // v27: group require_privacy_set (OpenAI scheduling reads it from ctx) type apiKeyAuthCacheConfig struct { l1Size int @@ -372,10 +372,11 @@ func (s *APIKeyService) snapshotFromAPIKey(ctx context.Context, apiKey *APIKey) // 填充 (user, group) RPM override —— snapshot 构建时查一次 DB,后续请求零 DB 往返。 if apiKey.GroupID != nil && *apiKey.GroupID > 0 && s.userGroupRateRepo != nil { override, err := s.userGroupRateRepo.GetRPMOverrideByUserAndGroup(ctx, apiKey.UserID, *apiKey.GroupID) - if err == nil && override != nil { + if err == nil { snapshot.User.UserGroupRPMOverride = override + snapshot.User.UserGroupRPMOverrideGroupID = *apiKey.GroupID } - // 查询失败或无 override 时留 nil,checkRPM 会回退到 DB 查询 + // 查询失败时不记录分组,checkRPM 会回退到 DB 查询 } if apiKey.Group != nil { snapshot.Group = &APIKeyAuthGroupSnapshot{ @@ -436,6 +437,7 @@ func (s *APIKeyService) snapshotFromAPIKey(ctx context.Context, apiKey *APIKey) ProfitControlEnabled: apiKey.Group.ProfitControlEnabled, ProfitMinMargin: apiKey.Group.ProfitMinMargin, ProfitSafetyBuffer: apiKey.Group.ProfitSafetyBuffer, + RequirePrivacySet: apiKey.Group.RequirePrivacySet, } } return snapshot @@ -461,22 +463,23 @@ func (s *APIKeyService) snapshotToAPIKey(key string, snapshot *APIKeyAuthSnapsho RateLimit1d: snapshot.RateLimit1d, RateLimit7d: snapshot.RateLimit7d, User: &User{ - ID: snapshot.User.ID, - Status: snapshot.User.Status, - Role: snapshot.User.Role, - Balance: snapshot.User.Balance, - Concurrency: snapshot.User.Concurrency, - AllowedGroups: snapshot.User.AllowedGroups, - Email: snapshot.User.Email, - Username: snapshot.User.Username, - BalanceNotifyEnabled: snapshot.User.BalanceNotifyEnabled, - RestrictPublicGroups: snapshot.User.RestrictPublicGroups, - BalanceNotifyThresholdType: snapshot.User.BalanceNotifyThresholdType, - BalanceNotifyThreshold: snapshot.User.BalanceNotifyThreshold, - BalanceNotifyExtraEmails: snapshot.User.BalanceNotifyExtraEmails, - TotalRecharged: snapshot.User.TotalRecharged, - RPMLimit: snapshot.User.RPMLimit, - UserGroupRPMOverride: snapshot.User.UserGroupRPMOverride, + ID: snapshot.User.ID, + Status: snapshot.User.Status, + Role: snapshot.User.Role, + Balance: snapshot.User.Balance, + Concurrency: snapshot.User.Concurrency, + AllowedGroups: snapshot.User.AllowedGroups, + Email: snapshot.User.Email, + Username: snapshot.User.Username, + BalanceNotifyEnabled: snapshot.User.BalanceNotifyEnabled, + RestrictPublicGroups: snapshot.User.RestrictPublicGroups, + BalanceNotifyThresholdType: snapshot.User.BalanceNotifyThresholdType, + BalanceNotifyThreshold: snapshot.User.BalanceNotifyThreshold, + BalanceNotifyExtraEmails: snapshot.User.BalanceNotifyExtraEmails, + TotalRecharged: snapshot.User.TotalRecharged, + RPMLimit: snapshot.User.RPMLimit, + UserGroupRPMOverride: snapshot.User.UserGroupRPMOverride, + UserGroupRPMOverrideGroupID: snapshot.User.UserGroupRPMOverrideGroupID, }, } if snapshot.Group != nil { @@ -539,6 +542,7 @@ func (s *APIKeyService) snapshotToAPIKey(key string, snapshot *APIKeyAuthSnapsho ProfitControlEnabled: snapshot.Group.ProfitControlEnabled, ProfitMinMargin: snapshot.Group.ProfitMinMargin, ProfitSafetyBuffer: snapshot.Group.ProfitSafetyBuffer, + RequirePrivacySet: snapshot.Group.RequirePrivacySet, } } s.compileAPIKeyIPRules(apiKey) 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 d121e2301e..ded56e1e13 100644 --- a/backend/internal/service/auth_service.go +++ b/backend/internal/service/auth_service.go @@ -1202,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 } @@ -1213,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 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..a7637b64e4 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() @@ -241,6 +249,13 @@ type bedrockEventStreamDecoder struct { reader *bufio.Reader } +// AWS EventStream 协议上限(与 AWS SDK 的 eventstream 解码器一致)。帧长度来自 +// 上游,必须在分配前校验,否则单个伪造的 prelude 即可申请约 4 GiB。 +const ( + bedrockEventStreamMaxHeadersLength = 128 << 10 + bedrockEventStreamMaxPayloadLength = 16 << 20 +) + func newBedrockEventStreamDecoder(r io.Reader) *bedrockEventStreamDecoder { return &bedrockEventStreamDecoder{ reader: bufio.NewReaderSize(r, 64*1024), @@ -268,6 +283,12 @@ func (d *bedrockEventStreamDecoder) Decode() ([]byte, error) { if totalLength < 16 { // minimum: 12 prelude + 4 message_crc return nil, fmt.Errorf("invalid eventstream frame: total_length=%d", totalLength) } + if headersLength > bedrockEventStreamMaxHeadersLength || headersLength > totalLength-16 { + return nil, fmt.Errorf("invalid eventstream frame: headers_length=%d total_length=%d", headersLength, totalLength) + } + if totalLength-16-headersLength > bedrockEventStreamMaxPayloadLength { + return nil, fmt.Errorf("invalid eventstream frame: payload too large, total_length=%d", totalLength) + } // 读取 headers + payload + message_crc remaining := int(totalLength) - 12 diff --git a/backend/internal/service/bedrock_stream_test.go b/backend/internal/service/bedrock_stream_test.go index 3d0661379a..d2c63552b9 100644 --- a/backend/internal/service/bedrock_stream_test.go +++ b/backend/internal/service/bedrock_stream_test.go @@ -243,6 +243,45 @@ func TestBedrockEventStreamDecoder(t *testing.T) { }) } +func TestBedrockEventStreamDecoderRejectsUntrustedLengths(t *testing.T) { + // Only the prelude is sent: the decoder must reject the declared lengths + // before allocating or reading the frame body. + prelude := func(totalLen, headersLen uint32) []byte { + var buf bytes.Buffer + _ = binary.Write(&buf, binary.BigEndian, totalLen) + _ = binary.Write(&buf, binary.BigEndian, headersLen) + _ = binary.Write(&buf, binary.BigEndian, crc32.Checksum(buf.Bytes(), crc32.MakeTable(crc32.IEEE))) + return buf.Bytes() + } + for _, tc := range []struct { + name string + totalLen uint32 + headersLen uint32 + }{ + {name: "payload over protocol limit", totalLen: 16 + bedrockEventStreamMaxPayloadLength + 1}, + {name: "maximum total length", totalLen: ^uint32(0)}, + {name: "headers beyond frame", totalLen: 64, headersLen: 49}, + {name: "headers over protocol limit", totalLen: 16 + bedrockEventStreamMaxHeadersLength + 1, headersLen: bedrockEventStreamMaxHeadersLength + 1}, + } { + t.Run(tc.name, func(t *testing.T) { + decoder := newBedrockEventStreamDecoder(bytes.NewReader(prelude(tc.totalLen, tc.headersLen))) + _, err := decoder.Decode() + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid eventstream frame") + }) + } + + t.Run("headers filling the frame are accepted", func(t *testing.T) { + var frame bytes.Buffer + _, _ = frame.Write(prelude(16+4, 4)) + _, _ = frame.Write([]byte{0, 0, 0, 0}) // empty-name, unknown-type header bytes + _ = binary.Write(&frame, binary.BigEndian, crc32.Checksum(frame.Bytes(), crc32.MakeTable(crc32.IEEE))) + decoder := newBedrockEventStreamDecoder(bytes.NewReader(frame.Bytes())) + _, err := decoder.Decode() + assert.Equal(t, io.EOF, err) + }) +} + func TestBuildBedrockURL(t *testing.T) { t.Run("stream URL with colon in model ID", func(t *testing.T) { url := BuildBedrockURL("us-east-1", "us.anthropic.claude-opus-4-5-20251101-v1:0", true) diff --git a/backend/internal/service/billing_cache_service.go b/backend/internal/service/billing_cache_service.go index ea22efe2eb..39435f90bd 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 @@ -938,9 +938,9 @@ func (s *BillingCacheService) checkRPM(ctx context.Context, user *User, group *G // ── 第一层:分组级检查(override 或 group.rpm_limit) ── if group != nil { - // 解析 override:优先从 auth cache snapshot,nil 时回退 DB。 + // 解析 override:优先从 auth cache snapshot;snapshot 未确认该分组时回退 DB。 var override *int - if user.UserGroupRPMOverride != nil { + if user.UserGroupRPMOverride != nil || user.UserGroupRPMOverrideGroupID == group.ID { override = user.UserGroupRPMOverride } else if s.userGroupRateRepo != nil { dbOverride, err := s.userGroupRateRepo.GetRPMOverrideByUserAndGroup(ctx, user.ID, group.ID) diff --git a/backend/internal/service/billing_cache_service_rpm_test.go b/backend/internal/service/billing_cache_service_rpm_test.go index cb71b886cb..fbf5f6e993 100644 --- a/backend/internal/service/billing_cache_service_rpm_test.go +++ b/backend/internal/service/billing_cache_service_rpm_test.go @@ -4,6 +4,7 @@ package service import ( "context" + "encoding/json" "errors" "sync/atomic" "testing" @@ -251,3 +252,55 @@ func TestBillingCacheService_CheckRPM_NilUserIsNoop(t *testing.T) { require.EqualValues(t, 0, atomic.LoadInt32(&cache.userCalls)) require.EqualValues(t, 0, atomic.LoadInt32(&repo.calls)) } + +func TestBillingCacheService_CheckRPM_SnapshotConfirmedNoOverrideSkipsLookup(t *testing.T) { + cache := &userRPMCacheStub{userGroupCounts: []int{5, 6}} + repo := &rpmOverrideRepoStub{err: errors.New("must not be queried")} + svc := newBillingServiceForRPM(t, cache, repo) + + user := &User{ID: 1, UserGroupRPMOverrideGroupID: 10} + group := &Group{ID: 10, RPMLimit: 5} + + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + require.ErrorIs(t, svc.checkRPM(context.Background(), user, group), ErrGroupRPMExceeded) + require.EqualValues(t, 0, atomic.LoadInt32(&repo.calls), "snapshot 已确认无 override 时不应查 DB") +} + +func TestBillingCacheService_CheckRPM_SnapshotForAnotherGroupStillLooksUp(t *testing.T) { + override := 0 + cache := &userRPMCacheStub{} + repo := &rpmOverrideRepoStub{override: &override} + svc := newBillingServiceForRPM(t, cache, repo) + + user := &User{ID: 1, UserGroupRPMOverrideGroupID: 10} + group := &Group{ID: 11, RPMLimit: 5} + + require.NoError(t, svc.checkRPM(context.Background(), user, group)) + require.EqualValues(t, 1, atomic.LoadInt32(&repo.calls), "snapshot 只确认了 key 所属分组") + require.EqualValues(t, 0, atomic.LoadInt32(&cache.userGroupCalls), "DB override=0 应跳过分组计数") +} + +func TestAPIKeyAuthSnapshotRecordsResolvedRPMOverrideGroup(t *testing.T) { + groupID := int64(10) + newKey := func() *APIKey { + return &APIKey{ID: 2, UserID: 1, GroupID: &groupID, Status: StatusActive, + User: &User{ID: 1, Status: StatusActive}} + } + + svc := &APIKeyService{userGroupRateRepo: &rpmOverrideRepoStub{}} + snapshot := svc.snapshotFromAPIKey(context.Background(), newKey()) + require.Nil(t, snapshot.User.UserGroupRPMOverride) + require.Equal(t, groupID, snapshot.User.UserGroupRPMOverrideGroupID) + payload, err := json.Marshal(&APIKeyAuthCacheEntry{Snapshot: snapshot}) + require.NoError(t, err) + var restored APIKeyAuthCacheEntry + require.NoError(t, json.Unmarshal(payload, &restored)) + materialized, used, err := svc.applyAuthCacheEntry("k", &restored) + require.NoError(t, err) + require.True(t, used) + require.Equal(t, groupID, materialized.User.UserGroupRPMOverrideGroupID) + + failing := &APIKeyService{userGroupRateRepo: &rpmOverrideRepoStub{err: errors.New("db down")}} + snapshot = failing.snapshotFromAPIKey(context.Background(), newKey()) + require.Zero(t, snapshot.User.UserGroupRPMOverrideGroupID, "查询失败时必须保留回源") +} 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/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_cache_control_paths_test.go b/backend/internal/service/gateway_cache_control_paths_test.go new file mode 100644 index 0000000000..9ef28b2231 --- /dev/null +++ b/backend/internal/service/gateway_cache_control_paths_test.go @@ -0,0 +1,155 @@ +package service + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type cacheControlPathsSnapshot struct { + invalidThinking []cacheControlPath + messages []string + tools []string + system []string +} + +func snapshotCacheControlPaths(body []byte) cacheControlPathsSnapshot { + invalid, messages, tools, system := collectCacheControlPaths(body) + return cacheControlPathsSnapshot{invalid, messages, tools, system} +} + +func TestCollectCacheControlPaths_BorrowedViewPreservesSelectionAndOwnership(t *testing.T) { + for _, tt := range []struct { + name string + body string + want cacheControlPathsSnapshot + }{ + {name: "empty"}, + { + name: "array order and invalid thinking", + body: `{"system":[{"type":"text","cache_control":{}},{"type":"thinking","cache_control":{}}],"messages":[{"content":[{"type":"text"},{"type":"thinking","cache_control":{}},{"type":"text","cache_control":{}}]},{"content":"plain text"}],"tools":[{"cache_control":{}},{},{"cache_control":{}}]}`, + want: cacheControlPathsSnapshot{ + invalidThinking: []cacheControlPath{ + {path: "system.1.cache_control", log: "[Warning] Removed illegal cache_control from thinking block in system"}, + {path: "messages.0.content.1.cache_control", log: "[Warning] Removed illegal cache_control from thinking block in messages[0].content[1]"}, + }, + messages: []string{"messages.0.content.2.cache_control"}, + tools: []string{"tools.0.cache_control", "tools.2.cache_control"}, + system: []string{"system.0.cache_control"}, + }, + }, + { + name: "first duplicate parent and content keys", + body: `{"system":[{"type":"text","cache_control":null}],"system":[{"type":"thinking","cache_control":{}}],"messages":[{"content":[{"type":"text","cache_control":{}}],"content":[{"type":"thinking","cache_control":{}}]}],"messages":[],"tools":[],"tools":[{"cache_control":{}}]}`, + want: cacheControlPathsSnapshot{ + messages: []string{"messages.0.content.0.cache_control"}, + system: []string{"system.0.cache_control"}, + }, + }, + { + name: "escaped field names", + body: ` {"\u0073ystem":[{"type":"text","cache_control":{}}],"\u006dessages":[{"content":[{"type":"text","cache_control":{}}]}],"\u0074ools":[{"cache_control":{}}]} `, + want: cacheControlPathsSnapshot{ + messages: []string{"messages.0.content.0.cache_control"}, + tools: []string{"tools.0.cache_control"}, + system: []string{"system.0.cache_control"}, + }, + }, + { + name: "garbage prefix retains GetBytes lookup behavior", + body: `junk{"system":[{"type":"text","cache_control":{}}],"messages":[{"content":[{"type":"text","cache_control":{}}]}],"tools":[{"cache_control":{}}]}`, + want: cacheControlPathsSnapshot{ + messages: []string{"messages.0.content.0.cache_control"}, + tools: []string{"tools.0.cache_control"}, + system: []string{"system.0.cache_control"}, + }, + }, + { + name: "nonarray fields and content stay ignored", + body: `{"system":"plain text","messages":[{"content":"plain text"},{"content":null}],"tools":{"cache_control":{}}}`, + }, + } { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + got := snapshotCacheControlPaths(body) + require.Equal(t, tt.body, string(body), "collection must not mutate borrowed input") + // The caller can reuse the source after collection. Returned metadata must + // not retain strings borrowed from the body. + for i := range body { + body[i] = 'x' + } + require.Equal(t, tt.want, got) + }) + } +} + +func TestCollectCacheControlPaths_ConcurrentImmutableInput(t *testing.T) { + body := cacheControlPathsBenchmarkBody(4096) + original := bytes.Clone(body) + want := cacheControlPathsSnapshot{ + messages: []string{"messages.0.content.0.cache_control"}, + tools: []string{"tools.0.cache_control"}, + system: []string{"system.0.cache_control"}, + } + t.Cleanup(func() { require.Equal(t, original, body) }) + for worker := 0; worker < 8; worker++ { + t.Run(fmt.Sprintf("worker_%d", worker), func(t *testing.T) { + t.Parallel() + for i := 0; i < 8; i++ { + require.Equal(t, want, snapshotCacheControlPaths(body)) + } + }) + } +} + +func TestEnforceCacheControlLimit_BorrowedCollectionKeepsDuplicateWireFields(t *testing.T) { + body := `{"opaque":9007199254740993,"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],"system":[{"type":"text","text":"untouched duplicate","cache_control":{"type":"ephemeral","ttl":"5m"}}],"messages":[{"role":"user","content":[{"type":"text","text":"m","cache_control":{"type":"ephemeral","ttl":"1h"}}]}],"unknown":{"decimal":1.2300e+04,"text":"\u4f60\u597d"}}` + want := strings.Replace(body, `"ttl":"5m"`, `"ttl":"1h"`, 1) + out := enforceCacheControlLimit([]byte(body)) + require.Equal(t, want, string(out), "both passes must keep first-key semantics and preserve unrelated bytes") + require.Equal(t, out, enforceCacheControlLimit(out), "a valid TTL order must remain byte-for-byte unchanged") +} + +func cacheControlPathsBenchmarkBody(payloadBytes int) []byte { + return []byte(`{"system":[{"type":"text","text":"s","cache_control":{"type":"ephemeral","ttl":"5m"}}],"messages":[{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", payloadBytes) + `","cache_control":{"type":"ephemeral","ttl":"5m"}}]}],"tools":[{"name":"probe","cache_control":{"type":"ephemeral","ttl":"5m"}}]}`) +} + +var benchmarkCacheControlPathsSnapshotSink cacheControlPathsSnapshot +var benchmarkCacheControlPathsBodySink []byte + +// Fixed breakpoint count, increasing opaque message content: cumulative +// allocation bytes should stay bounded instead of copying messages per scan. +func BenchmarkCacheControlPathsLargeContent(b *testing.B) { + for _, size := range []struct { + name string + bytes int + }{ + {name: "4KiB", bytes: 4 << 10}, + {name: "1MiB", bytes: 1 << 20}, + {name: "8MiB", bytes: 8 << 20}, + } { + body := cacheControlPathsBenchmarkBody(size.bytes) + b.Run(size.name+"/Collect", func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkCacheControlPathsSnapshotSink = snapshotCacheControlPaths(body) + } + }) + b.Run(size.name+"/EnforceUnchanged", func(b *testing.B) { + if got := enforceCacheControlLimit(body); !bytes.Equal(body, got) { + b.Fatal("fixture should not require cache-control changes") + } + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + benchmarkCacheControlPathsBodySink = enforceCacheControlLimit(body) + } + }) + } +} diff --git a/backend/internal/service/gateway_claude_oauth_body.go b/backend/internal/service/gateway_claude_oauth_body.go index 8a3eea4129..355be46b7c 100644 --- a/backend/internal/service/gateway_claude_oauth_body.go +++ b/backend/internal/service/gateway_claude_oauth_body.go @@ -993,7 +993,10 @@ type cacheControlPath struct { } func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath, messagePaths []string, toolPaths []string, systemPaths []string) { - system := gjson.GetBytes(body, "system") + // Borrow only during this synchronous scan. Returned paths/logs own their + // strings; no result may retain the request body after this function returns. + view := openAIWSPayloadStringView(body) + system := gjson.Get(view, "system") if system.IsArray() { sysIndex := 0 system.ForEach(func(_, item gjson.Result) bool { @@ -1013,7 +1016,7 @@ func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath, }) } - messages := gjson.GetBytes(body, "messages") + messages := gjson.Get(view, "messages") if messages.IsArray() { msgIndex := 0 messages.ForEach(func(_, msg gjson.Result) bool { @@ -1041,7 +1044,7 @@ func collectCacheControlPaths(body []byte) (invalidThinking []cacheControlPath, }) } - tools := gjson.GetBytes(body, "tools") + tools := gjson.Get(view, "tools") if tools.IsArray() { toolIndex := 0 tools.ForEach(func(_, tool gjson.Result) bool { 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..f68d87a5ac 100644 --- a/backend/internal/service/gateway_request.go +++ b/backend/internal/service/gateway_request.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "hash/maphash" "math" "regexp" "sort" @@ -60,13 +61,17 @@ type jsonRange struct { } type RequestBodyRef struct { - data []byte + data []byte + parsed *gatewayRequestBodyState } +// NewRequestBodyRef borrows immutable data. Callers must replace the body rather +// than modify its backing storage while any request or attempt still borrows it. func NewRequestBodyRef(data []byte) *RequestBodyRef { return &RequestBodyRef{data: data} } +// Bytes returns a read-only view; use Replace to invalidate parsed state. func (b *RequestBodyRef) Bytes() []byte { if b == nil { return nil @@ -86,6 +91,55 @@ func (b *RequestBodyRef) Replace(data []byte) { return } b.data = data + // Even replacing with the same slice invalidates the snapshot. Callers may + // have reused storage after releasing its previous immutable view. + b.parsed = nil +} + +// gatewayRequestBodySeed keys body fingerprints for this process only. +var gatewayRequestBodySeed = maphash.MakeSeed() + +// gatewayRequestBodyState is an immutable snapshot of a successful parse. It +// owns scalar strings and stores only offsets for large fields, so sharing it +// between attempts cannot retain an old request body or mutable request state. +type gatewayRequestBodyState struct { + model, metadataUserID, outputEffort, speed string + stream, hasSystem, thinkingEnabled bool + maxTokens int + protocol string + systemRange, messagesRange, inputRange jsonRange + fingerprint uint64 +} + +func (p *ParsedRequest) saveBodyState() { + p.Body.parsed = &gatewayRequestBodyState{ + model: p.Model, metadataUserID: p.MetadataUserID, outputEffort: p.OutputEffort, speed: p.Speed, + stream: p.Stream, hasSystem: p.HasSystem, thinkingEnabled: p.ThinkingEnabled, maxTokens: p.MaxTokens, + protocol: p.protocol, systemRange: p.systemRange, messagesRange: p.messagesRange, inputRange: p.inputRange, + fingerprint: maphash.Bytes(gatewayRequestBodySeed, p.Body.Bytes()), + } +} + +func (p *ParsedRequest) restoreBodyState(state *gatewayRequestBodyState) { + p.Model, p.MetadataUserID, p.OutputEffort, p.Speed = state.model, state.metadataUserID, state.outputEffort, state.speed + p.Stream, p.HasSystem, p.ThinkingEnabled, p.MaxTokens = state.stream, state.hasSystem, state.thinkingEnabled, state.maxTokens + p.protocol = state.protocol + p.systemRange, p.messagesRange, p.inputRange = state.systemRange, state.messagesRange, state.inputRange +} + +func (p *ParsedRequest) reusableBodyState(data []byte) *gatewayRequestBodyState { + if p.Body == nil || p.Body.parsed == nil || p.Body.parsed.protocol != p.protocol { + return nil + } + current := p.Body.Bytes() + // Identity alone would trust the immutable borrowing contract. The content + // fingerprint also catches in-place edits of shared storage, which then + // reparse as before; it costs one hash pass instead of a full parse. + if len(data) == 0 || len(data) != len(current) || &data[0] != ¤t[0] || + maphash.Bytes(gatewayRequestBodySeed, data) != p.Body.parsed.fingerprint { + return nil + } + return p.Body.parsed } func missingJSONRange() jsonRange { @@ -180,13 +234,16 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro if parsed == nil || parsed.Body == nil { return fmt.Errorf("empty request body") } + parsed.Body.parsed = nil bodyBytes := parsed.Body.Bytes() if !gjson.ValidBytes(bodyBytes) { 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 +253,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 +277,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") @@ -241,6 +298,7 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro } setGatewayRequestRanges(parsed, protocol, jsonStr) + parsed.saveBodyState() return nil } @@ -418,6 +476,13 @@ func (p *ParsedRequest) CloneForBody(body []byte) (*ParsedRequest, error) { clone := *p clone.Body = NewRequestBodyRef(body) clone.OnUpstreamAccepted = nil + if state := p.reusableBodyState(body); state != nil { + clone.Body.parsed = state + // Restore derived fields just as reparsing would; callers can have + // temporarily overridden exported fields such as Model for routing. + clone.restoreBodyState(state) + return &clone, nil + } if err := refreshGatewayRequestRanges(&clone, clone.protocol); err != nil { return nil, err } @@ -429,6 +494,10 @@ func (p *ParsedRequest) ReplaceBody(data []byte) error { if p == nil { return fmt.Errorf("parse request: empty request") } + if state := p.reusableBodyState(data); state != nil { + p.restoreBodyState(state) + return nil + } if p.Body == nil { p.Body = NewRequestBodyRef(data) } else { @@ -1426,7 +1495,117 @@ func filterThinkingBlocksInternal(body []byte, alwaysThinking bool) []byte { !bytes.Contains(body, []byte(`"thinking" :`)) { return body } + // Signed thinking history and top-level thinking config defeat the substring + // check on most requests; decide without decoding when nothing is dropped. + if needs, decided := thinkingBlocksNeedFiltering(body, alwaysThinking); decided && !needs { + return body + } + return filterThinkingBlocksDecoded(body, alwaysThinking) +} +// thinkingBlocksNeedFiltering reports whether filterThinkingBlocksDecoded would +// drop a block, mirroring its decisions on borrowed gjson views with +// encoding/json's last-wins rule for duplicate keys. The body is borrowed only +// during this call. A non-object root is left to the decoding path +// (decided=false). Invalid JSON needs no separate scan: the decoding path +// returns it unchanged, so either answer yields the same body. +func thinkingBlocksNeedFiltering(body []byte, alwaysThinking bool) (needs, decided bool) { + view := openAIWSPayloadStringView(body) + root := gjson.Parse(view) + if !root.IsObject() { + return false, false + } + var thinking, messages gjson.Result + root.ForEach(func(key, value gjson.Result) bool { + switch key.String() { + case "thinking": + thinking = value + case "messages": + messages = value + } + return true + }) + + thinkingEnabled := alwaysThinking + if thinking.IsObject() { + var thinkType gjson.Result + thinking.ForEach(func(key, value gjson.Result) bool { + if key.String() == "type" { + thinkType = value + } + return true + }) + if thinkType.Type == gjson.String && (thinkType.Str == "enabled" || thinkType.Str == "adaptive") { + thinkingEnabled = true + } + } + if !messages.IsArray() { + return false, true + } + + messages.ForEach(func(_, msg gjson.Result) bool { + if !msg.IsObject() { + return true + } + var role, content gjson.Result + msg.ForEach(func(key, value gjson.Result) bool { + switch key.String() { + case "role": + role = value + case "content": + content = value + } + return true + }) + if !content.IsArray() { + return true + } + isAssistant := role.Type == gjson.String && role.Str == "assistant" + content.ForEach(func(_, block gjson.Result) bool { + if !block.IsObject() { + return true + } + var blockType, data, signature gjson.Result + hasThinking := false + block.ForEach(func(key, value gjson.Result) bool { + switch key.String() { + case "type": + blockType = value + case "data": + data = value + case "signature": + signature = value + case "thinking": + hasThinking = true + } + return true + }) + typ := "" + if blockType.Type == gjson.String { + typ = blockType.Str + } + switch { + case typ == "thinking" || typ == "redacted_thinking": + if thinkingEnabled && isAssistant { + if alwaysThinking && typ == "redacted_thinking" && data.Type == gjson.String && data.Str != "" { + return true + } + if signature.Type == gjson.String && signature.Str != "" && signature.Str != antigravity.DummyThoughtSignature { + return true + } + } + needs = true + case typ == "" && hasThinking: + needs = true + } + return !needs + }) + return !needs + }) + return needs, true +} + +func filterThinkingBlocksDecoded(body []byte, alwaysThinking bool) []byte { var req map[string]any if err := json.Unmarshal(body, &req); err != nil { return body diff --git a/backend/internal/service/gateway_request_reuse_test.go b/backend/internal/service/gateway_request_reuse_test.go new file mode 100644 index 0000000000..c580dca048 --- /dev/null +++ b/backend/internal/service/gateway_request_reuse_test.go @@ -0,0 +1,215 @@ +package service + +import ( + "bytes" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +func TestGatewayRequestBodyReuse_RestoresDerivedStateAndIsolatesAttempts(t *testing.T) { + body := []byte(`{"model":"claude-sonnet-4-5","model":"ignored","stream":true,"metadata":{"user_id":"session"},"system":null,"messages":[{"role":"user","content":"first"}],"messages":[],"thinking":{"type":"enabled"},"output_config":{"effort":"high"},"speed":"fast","max_tokens":123,"unknown":{"number":1.00}}`) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic) + require.NoError(t, err) + want := *parsed.Body.parsed + groupID := int64(17) + parsed.GroupID = &groupID + parsed.SessionContext = &SessionContext{APIKeyID: 9} + callbackCalled := false + parsed.OnUpstreamAccepted = func() { callbackCalled = true } + + // Exported fields are mutable routing inputs, not the authoritative parse. + clearGatewayRequestDerivedState(parsed) + parsed.Model = "temporary-routing-override" + first, err := parsed.CloneForBody(body) + require.NoError(t, err) + require.NotSame(t, parsed.Body, first.Body) + require.Nil(t, first.OnUpstreamAccepted) + require.Same(t, parsed.SessionContext, first.SessionContext) + require.Same(t, parsed.GroupID, first.GroupID) + require.Equal(t, "claude-sonnet-4-5", first.Model) + require.Equal(t, `[{"role":"user","content":"first"}]`, string(first.MessagesRaw())) + require.Equal(t, body, first.Body.Bytes()) + first.saveBodyState() + require.Equal(t, want, *first.Body.parsed) + + require.NoError(t, parsed.ReplaceBody(body)) + parsed.saveBodyState() + require.Equal(t, want, *parsed.Body.parsed) + parsed.OnUpstreamAccepted() + require.True(t, callbackCalled) + second, err := parsed.CloneForBody(body) + require.NoError(t, err) + require.NoError(t, first.ReplaceBody([]byte(`{"model":"other","messages":[{"content":"replacement"}]}`))) + require.Equal(t, "other", first.Model) + require.Equal(t, "claude-sonnet-4-5", parsed.Model) + require.Equal(t, body, parsed.Body.Bytes()) + require.Equal(t, body, second.Body.Bytes()) + require.Equal(t, string(parsed.MessagesRaw()), string(second.MessagesRaw())) +} + +func TestGatewayRequestBodyReuse_InvalidatesReplacedAndUnparsedBodies(t *testing.T) { + for _, mode := range []string{"manual", "replace-ref", "replace-storage", "mutate-in-place", "protocol"} { + t.Run(mode, func(t *testing.T) { + body := []byte(`{"model":"old","system":"system","messages":[1],"contents":[2]}`) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic) + require.NoError(t, err) + switch mode { + case "manual": + parsed = &ParsedRequest{Body: NewRequestBodyRef(body), Model: "unparsed", protocol: domain.PlatformAnthropic} + case "replace-ref": + parsed.Body = NewRequestBodyRef(body) + case "replace-storage": + // Release the previous immutable view before reusing its storage. + parsed.Body.Replace(nil) + copy(body, bytes.Replace(body, []byte(`"old"`), []byte(`"new"`), 1)) + parsed.Body.Replace(body) + case "mutate-in-place": + // Violates the borrowing contract; the fingerprint still forces a reparse. + copy(body, bytes.Replace(body, []byte(`"old"`), []byte(`"new"`), 1)) + case "protocol": + parsed.protocol = domain.PlatformGemini + } + clone, err := parsed.CloneForBody(body) + require.NoError(t, err) + require.NoError(t, parsed.ReplaceBody(body)) + for _, actual := range []*ParsedRequest{parsed, clone} { + if mode == "replace-storage" || mode == "mutate-in-place" { + require.Equal(t, "new", actual.Model) + } else { + require.Equal(t, "old", actual.Model) + } + if mode == "protocol" { + require.Equal(t, "[2]", string(actual.MessagesRaw())) + require.Nil(t, actual.SystemRaw()) + } else { + require.Equal(t, "[1]", string(actual.MessagesRaw())) + } + } + }) + } +} + +func TestGatewayRequestBodyReuse_ExplicitReplaceSameSliceInvalidates(t *testing.T) { + body := []byte(`{"model":"old"}`) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), "") + require.NoError(t, err) + parsed.Body.Replace(body) + require.Nil(t, parsed.Body.parsed) + require.NoError(t, parsed.ReplaceBody(body)) + require.NotNil(t, parsed.Body.parsed) +} + +func TestGatewayRequestBodyReuse_FailedParseCannotBeReused(t *testing.T) { + for _, invalid := range []string{`{"messages":`, `{"model":123}`, `{"stream":"true"}`, `{"model":"claude-sonnet-4[1m]","stream":0}`} { + t.Run(invalid, func(t *testing.T) { + parsed, err := ParseGatewayRequest(NewRequestBodyRef([]byte(`{"model":"valid","system":"old","messages":[1]}`)), domain.PlatformAnthropic) + require.NoError(t, err) + require.Error(t, parsed.ReplaceBody([]byte(invalid))) + require.Nil(t, parsed.Body.parsed) + require.Nil(t, parsed.SystemRaw()) + require.Nil(t, parsed.MessagesRaw()) + _, err = parsed.CloneForBody(parsed.Body.Bytes()) + require.Error(t, err) + require.Error(t, parsed.ReplaceBody(parsed.Body.Bytes())) + require.Nil(t, parsed.Body.parsed) + require.NoError(t, parsed.ReplaceBody([]byte(`{"model":"recovered","messages":[2]}`))) + require.Equal(t, "recovered", parsed.Model) + require.Equal(t, "[2]", string(parsed.MessagesRaw())) + }) + } +} + +func TestGatewayRequestBodyReuse_NormalizedBodyAndProtocolRanges(t *testing.T) { + for _, tt := range []struct{ protocol, body string }{ + {domain.PlatformAnthropic, `{"model":"claude-sonnet-4[1m]","system":"sys","messages":[{"content":"hello"}]}`}, + {domain.PlatformGemini, `{"model":"gemini","systemInstruction":{"parts":[{"text":"sys"}]},"contents":[{"parts":[{"text":"hi"}]}]}`}, + {"responses", `{"model":"gpt-5.4","input":[{"type":"message","content":"hi"}]}`}, + } { + t.Run(tt.protocol, func(t *testing.T) { + original := []byte(tt.body) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(original), tt.protocol) + require.NoError(t, err) + for _, body := range [][]byte{original, parsed.Body.Bytes(), bytes.Clone(parsed.Body.Bytes())} { + clone, err := parsed.CloneForBody(body) + require.NoError(t, err) + require.NoError(t, clone.ReplaceBody(clone.Body.Bytes())) + require.Equal(t, parsed.Model, clone.Model) + require.Equal(t, parsed.Body.Bytes(), clone.Body.Bytes()) + require.Equal(t, parsed.SystemRaw(), clone.SystemRaw()) + require.Equal(t, parsed.MessagesRaw(), clone.MessagesRaw()) + require.Equal(t, parsed.InputRaw(), clone.InputRaw()) + } + }) + } +} + +func TestGatewayRequestBodyReuse_ConcurrentIndependentAttempts(t *testing.T) { + body := []byte(`{"model":"original","messages":[{"content":"hello"}]}`) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic) + require.NoError(t, err) + var wg sync.WaitGroup + for range 16 { + wg.Go(func() { + clone, err := parsed.CloneForBody(body) + if err != nil { + t.Error(err) + return + } + if err := clone.ReplaceBody([]byte(`{"model":"attempt","messages":[]}`)); err != nil { + t.Error(err) + } + }) + } + wg.Wait() + require.Equal(t, "original", parsed.Model) + require.Equal(t, body, parsed.Body.Bytes()) +} + +func BenchmarkGatewayRequestBodyReuse(b *testing.B) { + for _, size := range []struct { + name string + bytes int + }{{"4KiB", 4 << 10}, {"1MiB", 1 << 20}, {"8MiB", 8 << 20}} { + body := buildLargeAnthropicMessagesBody(size.bytes, false) + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), domain.PlatformAnthropic) + if err != nil { + b.Fatal(err) + } + for _, reuse := range []bool{false, true} { + name := "Reparse" + if reuse { + name = "Reuse" + } + b.Run(size.name+"/"+name, func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(body))) + for i := 0; i < b.N; i++ { + if !reuse { + parsed.Body.Replace(body) + } + attempt, err := parsed.CloneForBody(body) + if err != nil { + b.Fatal(err) + } + // Unchanged compatibility and cache-control phases. + for range 2 { + if !reuse { + attempt.Body.Replace(body) + } + if err := attempt.ReplaceBody(body); err != nil { + b.Fatal(err) + } + } + benchmarkIntSink = len(attempt.MessagesRaw()) + } + }) + // Reparse deliberately invalidates the source snapshot. + if err := parsed.ReplaceBody(body); err != nil { + b.Fatal(err) + } + } + } +} 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_service_benchmark_test.go b/backend/internal/service/gateway_service_benchmark_test.go index 42a711db9b..0997253bac 100644 --- a/backend/internal/service/gateway_service_benchmark_test.go +++ b/backend/internal/service/gateway_service_benchmark_test.go @@ -1,6 +1,7 @@ package service import ( + "context" "strconv" "strings" "testing" @@ -136,7 +137,7 @@ func BenchmarkOpenAIResponses_LargeInputRawPatch(b *testing.B) { view := newOpenAIRequestView(body) view.MarkPatchSet("instructions", "You are a helpful coding assistant.") view.MarkPatchSet("reasoning.effort", "none") - patched, err := view.ApplyPatches() + patched, err := view.ApplyPatches(context.Background()) if err != nil { b.Fatalf("应用 OpenAI raw patch 失败: %v", err) } diff --git a/backend/internal/service/gateway_thinking_filter_precheck_test.go b/backend/internal/service/gateway_thinking_filter_precheck_test.go new file mode 100644 index 0000000000..b7cb36c4d9 --- /dev/null +++ b/backend/internal/service/gateway_thinking_filter_precheck_test.go @@ -0,0 +1,123 @@ +package service + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/pkg/antigravity" + "github.com/stretchr/testify/require" +) + +// The precheck may only skip the decoding path when that path would return the +// body unchanged; every case is checked against filterThinkingBlocksDecoded. +func TestThinkingBlocksNeedFilteringMatchesDecodingPath(t *testing.T) { + dummy := antigravity.DummyThoughtSignature + bodies := []string{ + `{"thinking":{"type":"adaptive"},"messages":[{"role":"user","content":"hi"}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"},{"type":"text","text":"a"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":""}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"` + dummy + `"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":7}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"user","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"thinking":{"type":"disabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"redacted_thinking","data":"d"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"redacted_thinking","data":""}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"thinking":"untyped"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":7,"thinking":null}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"text","text":"\"thinking\": quoted"}]}]}`, + // Duplicate keys: encoding/json keeps the last value. + `{"thinking":{"type":"enabled"},"thinking":{"budget_tokens":1},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"thinking":{"type":"disabled","type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"user","role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","signature":"sig","signature":""}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","signature":"sig"}],"content":"plain"}]}`, + `{"thinking":{"type":"enabled"},"messages":[],"messages":[{"role":"assistant","content":[{"type":"thinking","signature":""}]}]}`, + // Escaped keys and values. + `{"thinking":{"\u0074ype":"enabled"},"messages":[{"role":"assistant","content":[{"\u0074ype":"thinking","thinking":"t","signature":"sig"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","\u0073ignature":""}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"\u0061ssistant","content":[{"type":"\u0074hinking","thinking":"t","signature":"\u0073ig"}]}]}`, + `{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"\u0000"}]}]}`, + // Shapes the decoder rejects or ignores. + `{"thinking":{"type":"enabled"},"messages":"none"}`, + `{"thinking":{"type":"enabled"},"messages":[null,1,{"role":"assistant","content":null},{"role":"assistant","content":[null,"x"]}]}`, + `[{"thinking":{}}]`, + `{"thinking":{"type":"enabled"},"messages":[`, + `{"thinking":{"type":"enabled"}} {}`, + } + for _, body := range bodies { + for _, alwaysThinking := range []bool{false, true} { + decoded := filterThinkingBlocksDecoded([]byte(body), alwaysThinking) + changed := !bytes.Equal(decoded, []byte(body)) + needs, decided := thinkingBlocksNeedFiltering([]byte(body), alwaysThinking) + if decided && json.Valid([]byte(body)) { + require.Equal(t, changed, needs, "alwaysThinking=%v body=%s", alwaysThinking, body) + } + require.Equal(t, string(decoded), string(filterThinkingBlocksInternal([]byte(body), alwaysThinking)), "alwaysThinking=%v body=%s", alwaysThinking, body) + } + } +} + +func signedThinkingHistoryBody() []byte { + var b strings.Builder + _, _ = b.WriteString(`{"model":"claude-sonnet-4-5","thinking":{"type":"adaptive"},"messages":[`) + for i := 0; i < 200; i++ { + if i > 0 { + _ = b.WriteByte(',') + } + _, _ = b.WriteString(`{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("q", 2048) + `"}]},`) + _, _ = b.WriteString(`{"role":"assistant","content":[{"type":"thinking","thinking":"reason","signature":"sig-valid"},{"type":"text","text":"answer"}]}`) + } + _, _ = b.WriteString(`]}`) + return []byte(b.String()) +} + +func TestFilterThinkingBlocksSignedHistorySkipsDecode(t *testing.T) { + body := signedThinkingHistoryBody() + allocs := testing.AllocsPerRun(5, func() { + got := filterThinkingBlocksInternal(body, false) + if &got[0] != &body[0] { + t.Fatal("valid signed history must be returned unchanged") + } + }) + require.Less(t, allocs, float64(16), "allocs: %v", allocs) +} + +func FuzzThinkingBlocksNeedFiltering(f *testing.F) { + f.Add([]byte(`{"thinking":{"type":"enabled"},"messages":[{"role":"assistant","content":[{"type":"thinking","thinking":"t","signature":"sig"}]}]}`), false) + f.Add([]byte(`{"thinking":{"type":"adaptive"},"messages":[{"role":"assistant","content":[{"type":"redacted_thinking","data":"d"},{"thinking":1}]}]}`), true) + f.Add([]byte(`{"messages":[{"role":"user","role":"assistant","content":[{"type":"thinking","signature":"","signature":"s"}]}]}`), true) + f.Fuzz(func(t *testing.T, body []byte, alwaysThinking bool) { + original := append([]byte(nil), body...) + decoded := filterThinkingBlocksDecoded(original, alwaysThinking) + needs, decided := thinkingBlocksNeedFiltering(body, alwaysThinking) + if !bytes.Equal(filterThinkingBlocksInternal(body, alwaysThinking), decoded) { + t.Fatalf("filter output differs from decoding path for %q", body) + } + if decided && json.Valid(original) && needs == bytes.Equal(decoded, original) { + t.Fatalf("precheck needs=%v disagrees with decoding path for %q", needs, body) + } + }) +} + +// Decoded is the previous cost of a request whose signed history needs no +// filtering; Precheck is the current path for the same body. +func BenchmarkFilterThinkingBlocksSignedHistory(b *testing.B) { + body := signedThinkingHistoryBody() + b.Run("Decoded", func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(body))) + for i := 0; i < b.N; i++ { + _ = filterThinkingBlocksDecoded(body, false) + } + }) + b.Run("Precheck", func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(body))) + for i := 0; i < b.N; i++ { + _ = filterThinkingBlocksInternal(body, false) + } + }) +} 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_chat_completions_compat_service.go b/backend/internal/service/gemini_chat_completions_compat_service.go index 8e1cd1aa29..0a339d7666 100644 --- a/backend/internal/service/gemini_chat_completions_compat_service.go +++ b/backend/internal/service/gemini_chat_completions_compat_service.go @@ -1,7 +1,6 @@ package service import ( - "bufio" "bytes" "context" "encoding/json" @@ -266,7 +265,7 @@ func (s *GeminiMessagesCompatService) forwardClaudeBodyAsChatCompletions( clientDisconnect = streamRes.clientDisconnect streamFinished = streamRes.finished } else if useUpstreamStream { - collected, usageObj, err := collectGeminiSSE(resp.Body, account.Type == AccountTypeOAuth) + collected, usageObj, err := collectGeminiSSE(s.cfg, resp.Body, account.Type == AccountTypeOAuth) if err != nil { return nil, s.writeChatCompletionsError(c, http.StatusBadGateway, "upstream_error", "Failed to read upstream stream") } @@ -597,11 +596,11 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom nextBlockIndex := 0 openBlockIndex := -1 openBlockType := "" - seenText := "" - seenThought := "" + var seenText geminiTextDelta + var seenThought geminiTextDelta openToolIndex := -1 openToolName := "" - seenToolJSON := "" + var seenToolJSON geminiTextDelta closeOpenBlock := func() bool { if openBlockIndex < 0 { @@ -619,13 +618,13 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom disconnected := emitAnthropicEvent(&apicompat.AnthropicStreamEvent{Type: "content_block_stop"}) openToolIndex = -1 openToolName = "" - seenToolJSON = "" + seenToolJSON.reset() return disconnected } - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadString('\n') + line, err := reader.ReadLineString() if len(line) > 0 { trimmed := strings.TrimRight(line, "\r\n") if strings.HasPrefix(trimmed, "data:") { @@ -654,8 +653,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom for _, part := range extractGeminiParts(geminiResp) { if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) { - delta, newSeen := computeGeminiTextDelta(seenThought, text) - seenThought = newSeen + delta := seenThought.next(text) if delta == "" { continue } @@ -694,8 +692,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom return streamResult(), nil } } - delta, newSeen := computeGeminiTextDelta(seenText, text) - seenText = newSeen + delta := seenText.next(text) if delta == "" { continue } @@ -775,8 +772,7 @@ func (s *GeminiMessagesCompatService) handleChatCompletionsStreamingResponseFrom argsJSONText = string(b) } } - delta, newSeen := computeGeminiTextDelta(seenToolJSON, argsJSONText) - seenToolJSON = newSeen + delta := seenToolJSON.next(argsJSONText) if delta != "" { if emitAnthropicEvent(&apicompat.AnthropicStreamEvent{ Type: "content_block_delta", diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 6f4edef96c..9c1ff6d8ce 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -1,7 +1,6 @@ package service import ( - "bufio" "bytes" "context" "crypto/rand" @@ -1034,7 +1033,7 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex streamFinished = streamRes.finished } else { if useUpstreamStream { - collected, usageObj, err := collectGeminiSSE(resp.Body, true) + collected, usageObj, err := collectGeminiSSE(s.cfg, resp.Body, true) if err != nil { return nil, s.writeClaudeError(c, http.StatusBadGateway, "upstream_error", "Failed to read upstream stream") } @@ -1565,7 +1564,7 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin. } else { if useUpstreamStream { var best geminiResponseSignal - collected, usageObj, stats, err := collectGeminiSSEObserved(resp.Body, isOAuth, func(rawBytes []byte) { + collected, usageObj, stats, err := collectGeminiSSEObserved(s.cfg, resp.Body, isOAuth, func(rawBytes []byte) { if sig, ok := detectGeminiResponseSignal(rawBytes); ok && sig.Kind > best.Kind { best = sig } @@ -2210,16 +2209,16 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re nextBlockIndex := 0 openBlockIndex := -1 openBlockType := "" - seenText := "" - seenThought := "" + var seenText geminiTextDelta + var seenThought geminiTextDelta openToolIndex := -1 openToolID := "" openToolName := "" - seenToolJSON := "" + var seenToolJSON geminiTextDelta - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) for { - line, err := reader.ReadString('\n') + line, err := reader.ReadLineString() if err != nil && !errors.Is(err, io.EOF) { if geminiStreamAbortedWithBillableOutput(c, err, &usage) { logger.LegacyPrintf("service.gemini_messages_compat", "[GeminiAPI] Client disconnected during messages stream, billing collected usage: %v", err) @@ -2270,8 +2269,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re parts := extractGeminiParts(geminiResp) for _, part := range parts { if text, ok := part["text"].(string); ok && isGeminiThoughtPart(part) { - delta, newSeen := computeGeminiTextDelta(seenThought, text) - seenThought = newSeen + delta := seenThought.next(text) if delta == "" { continue } @@ -2282,7 +2280,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re }) openToolIndex = -1 openToolName = "" - seenToolJSON = "" + seenToolJSON.reset() } if openBlockType != "thinking" { if openBlockIndex >= 0 { @@ -2333,11 +2331,10 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re }) openToolIndex = -1 openToolName = "" - seenToolJSON = "" + seenToolJSON.reset() } - delta, newSeen := computeGeminiTextDelta(seenText, text) - seenText = newSeen + delta := seenText.next(text) if delta == "" { continue } @@ -2403,7 +2400,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re }) openToolIndex = -1 openToolName = "" - seenToolJSON = "" + seenToolJSON.reset() } if openToolIndex < 0 { @@ -2439,8 +2436,7 @@ func (s *GeminiMessagesCompatService) handleStreamingResponse(c *gin.Context, re } } - delta, newSeen := computeGeminiTextDelta(seenToolJSON, argsJSONText) - seenToolJSON = newSeen + delta := seenToolJSON.next(argsJSONText) if delta != "" { writeSSE(c.Writer, "content_block_delta", map[string]any{ "type": "content_block_delta", @@ -2566,8 +2562,8 @@ func unwrapIfNeeded(isOAuth bool, raw []byte) []byte { return inner } -func collectGeminiSSE(body io.Reader, isOAuth bool) (map[string]any, *ClaudeUsage, error) { - collected, usage, _, err := collectGeminiSSEObserved(body, isOAuth, nil) +func collectGeminiSSE(cfg *config.Config, body io.Reader, isOAuth bool) (map[string]any, *ClaudeUsage, error) { + collected, usage, _, err := collectGeminiSSEObserved(cfg, body, isOAuth, nil) return collected, usage, err } @@ -2578,8 +2574,8 @@ type geminiSSECollectStats struct { } // collectGeminiSSEObserved 在聚合的同时把每个解包后的事件原文交给 observe(可为 nil)。 -func collectGeminiSSEObserved(body io.Reader, isOAuth bool, observe func(rawBytes []byte)) (map[string]any, *ClaudeUsage, geminiSSECollectStats, error) { - reader := bufio.NewReader(body) +func collectGeminiSSEObserved(cfg *config.Config, body io.Reader, isOAuth bool, observe func(rawBytes []byte)) (map[string]any, *ClaudeUsage, geminiSSECollectStats, error) { + reader := newBoundedSSELineReader(body, cfg) var last map[string]any var lastWithParts map[string]any @@ -2588,7 +2584,7 @@ func collectGeminiSSEObserved(body io.Reader, isOAuth bool, observe func(rawByte stats := geminiSSECollectStats{fallback: &geminiSSEFallbackBody{}} for { - line, err := reader.ReadString('\n') + line, err := reader.ReadLineString() if len(line) > 0 { trimmed := strings.TrimRight(line, "\r\n") if !strings.HasPrefix(trimmed, "data:") { @@ -2909,7 +2905,7 @@ func (s *GeminiMessagesCompatService) handleNativeStreamingResponse(c *gin.Conte return nil, errors.New("streaming not supported") } - reader := bufio.NewReader(resp.Body) + reader := newBoundedSSELineReader(resp.Body, s.cfg) usage := &ClaudeUsage{} observer := upstreamResponseModelObserverFromContext(c) if observer == nil { @@ -2923,7 +2919,7 @@ func (s *GeminiMessagesCompatService) handleNativeStreamingResponse(c *gin.Conte finished := false for { - line, err := reader.ReadString('\n') + line, err := reader.ReadLineString() // 读错误时 line 是未以换行结尾的残行,不透传也不参与用量统计;EOF 时的末行完整有效。 if len(line) > 0 && (err == nil || errors.Is(err, io.EOF)) { trimmed := strings.TrimRight(line, "\r\n") @@ -3427,22 +3423,38 @@ func extractGeminiParts(geminiResp map[string]any) []map[string]any { return nil } -func computeGeminiTextDelta(seen, incoming string) (delta, newSeen string) { +// geminiTextDelta tracks the text already emitted for one stream block. Only the +// storage differs from concatenating strings: appends are amortized, so +// delta-mode streams no longer copy the whole prefix on every chunk. +type geminiTextDelta struct { + seen strings.Builder +} + +// next returns the part of incoming that has not been emitted yet. +func (d *geminiTextDelta) next(incoming string) string { incoming = strings.TrimSuffix(incoming, "\u0000") if incoming == "" { - return "", seen + return "" } + seen := d.seen.String() // Cumulative mode: incoming contains full text so far. if strings.HasPrefix(incoming, seen) { - return strings.TrimPrefix(incoming, seen), incoming + delta := incoming[len(seen):] + _, _ = d.seen.WriteString(delta) + return delta } // Duplicate/rewind: ignore. if strings.HasPrefix(seen, incoming) { - return "", seen + return "" } // Delta mode: treat incoming as incremental chunk. - return incoming, seen + incoming + _, _ = d.seen.WriteString(incoming) + return incoming +} + +func (d *geminiTextDelta) reset() { + d.seen.Reset() } func mapGeminiFinishReasonToClaudeStopReason(finishReason string) string { diff --git a/backend/internal/service/gemini_native_response_signal_test.go b/backend/internal/service/gemini_native_response_signal_test.go index 1005eca1e7..dee07b68cf 100644 --- a/backend/internal/service/gemini_native_response_signal_test.go +++ b/backend/internal/service/gemini_native_response_signal_test.go @@ -501,7 +501,7 @@ func TestGeminiForwardNative_CountTokensBodyLeavesNoMark(t *testing.T) { func TestCollectGeminiSSEObserved_SeesTerminalChunkEvenWhenAggregateDropsIt(t *testing.T) { var observed []string - collected, usage, stats, err := collectGeminiSSEObserved(strings.NewReader(geminiSignalTestProhibitedSSE), false, func(raw []byte) { + collected, usage, stats, err := collectGeminiSSEObserved(nil, strings.NewReader(geminiSignalTestProhibitedSSE), false, func(raw []byte) { observed = append(observed, string(raw)) }) require.NoError(t, err) diff --git a/backend/internal/service/gemini_sse_line_limit_test.go b/backend/internal/service/gemini_sse_line_limit_test.go new file mode 100644 index 0000000000..4a7298e21e --- /dev/null +++ b/backend/internal/service/gemini_sse_line_limit_test.go @@ -0,0 +1,58 @@ +package service + +import ( + "bufio" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Upstreams behind a custom base_url can stream a line that never ends. Every +// Gemini stream reader must stop at the configured line limit instead of +// buffering it, and must not forward a truncated prefix. +func TestGeminiStreamsRejectOversizedUpstreamLines(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := &config.Config{Gateway: config.GatewayConfig{MaxLineSize: 256}} + svc := &GeminiMessagesCompatService{cfg: cfg} + oversized := `data: {"candidates":[{"content":{"parts":[{"text":"` + strings.Repeat("x", 4096) + + run := map[string]func(c *gin.Context, resp *http.Response) error{ + "native": func(c *gin.Context, resp *http.Response) error { + _, err := svc.handleNativeStreamingResponse(c, resp, time.Now(), false, &Account{ID: 1}, "") + return err + }, + "messages": func(c *gin.Context, resp *http.Response) error { + _, err := svc.handleStreamingResponse(c, resp, time.Now(), "gemini-2.5-pro") + return err + }, + "chat_completions": func(c *gin.Context, resp *http.Response) error { + _, err := svc.handleChatCompletionsStreamingResponseFromGemini(c, resp, time.Now(), "gemini-2.5-pro", false, false) + return err + }, + "collector": func(_ *gin.Context, resp *http.Response) error { + _, _, _, err := collectGeminiSSEObserved(cfg, resp.Body, false, nil) + return err + }, + } + for name, fn := range run { + t.Run(name, func(t *testing.T) { + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-pro:streamGenerateContent", nil) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(oversized))} + + err := fn(c, resp) + require.Error(t, err) + require.True(t, errors.Is(err, bufio.ErrTooLong), "got %v", err) + require.NotContains(t, w.Body.String(), "xxxx") + }) + } +} diff --git a/backend/internal/service/gemini_text_delta_test.go b/backend/internal/service/gemini_text_delta_test.go new file mode 100644 index 0000000000..d8a7bcf500 --- /dev/null +++ b/backend/internal/service/gemini_text_delta_test.go @@ -0,0 +1,62 @@ +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// legacyComputeGeminiTextDelta is the previous string-concatenating +// implementation, kept as the oracle for the storage-only change. +func legacyComputeGeminiTextDelta(seen, incoming string) (delta, newSeen string) { + incoming = strings.TrimSuffix(incoming, "\u0000") + if incoming == "" { + return "", seen + } + if strings.HasPrefix(incoming, seen) { + return strings.TrimPrefix(incoming, seen), incoming + } + if strings.HasPrefix(seen, incoming) { + return "", seen + } + return incoming, seen + incoming +} + +func TestGeminiTextDeltaMatchesLegacy(t *testing.T) { + sequences := [][]string{ + {"Hel", "Hello", "Hello, wor", "Hello, world"}, // cumulative + {"Hel", "lo", ", wor", "ld"}, // incremental + {"The", " cat", "The", " sat"}, // delta equal to an emitted prefix + {"abc", "abc", "ab", "abcd", "x"}, // duplicate, rewind, extend, diverge + {"", "\u0000", "a\u0000", "ab", "", "abc\u0000"}, // empty and NUL-terminated chunks + {"{\"a\":", "{\"a\":1", "}", "{\"a\":1}"}, // tool args mixing modes + {"多字节", "多字节文本", "😀", "多字节文本😀继续"}, // non-ASCII + } + for _, seq := range sequences { + var state geminiTextDelta + legacySeen := "" + for i, chunk := range seq { + wantDelta, newSeen := legacyComputeGeminiTextDelta(legacySeen, chunk) + legacySeen = newSeen + require.Equal(t, wantDelta, state.next(chunk), "sequence %q chunk %d", seq, i) + require.Equal(t, legacySeen, state.seen.String(), "sequence %q chunk %d", seq, i) + } + state.reset() + require.Equal(t, "", state.seen.String()) + require.Equal(t, "fresh", state.next("fresh")) + } +} + +func TestGeminiTextDeltaIncrementalAllocationsStayLinear(t *testing.T) { + chunk := strings.Repeat("x", 100) + const chunks = 2000 + allocs := testing.AllocsPerRun(5, func() { + var state geminiTextDelta + for i := 0; i < chunks; i++ { + _ = state.next(chunk) + } + }) + // Concatenation allocates once per chunk; amortized growth needs O(log n). + require.Less(t, allocs, float64(100), "allocs per stream: %v", allocs) +} 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/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 2cbf1211f5..c5912f892d 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -16,6 +16,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "golang.org/x/sync/singleflight" ) @@ -386,6 +387,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 +411,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 +524,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 { @@ -1432,12 +1435,6 @@ func (s *defaultOpenAIAccountScheduler) selectByLoadBalance( accounts = modelFiltered } - // require_privacy_set: 获取分组配置。GetByID 会聚合账号计数,选号不能走它。 - var schedGroup *Group - if req.GroupID != nil && s.service.schedulerSnapshot != nil { - schedGroup, _ = s.service.schedulerSnapshot.GetGroupByIDLite(ctx, *req.GroupID) - } - filterStats := openAISelectionFilterStats{pool: len(accounts)} filtered := make([]*Account, 0, len(accounts)) loadReq := make([]AccountWithConcurrency, 0, len(accounts)) @@ -1464,7 +1461,8 @@ func (s *defaultOpenAIAccountScheduler) selectByLoadBalance( // require_privacy_set is a group-scoped eligibility gate. Do not mutate the // shared account: another group may intentionally allow accounts whose // upstream privacy setting has not been confirmed. - if schedGroup != nil && schedGroup.RequirePrivacySet && !account.IsPrivacySet() { + // Select already resolved the group requirement into req. + if req.RequirePrivacySet && !account.IsPrivacySet() { filterStats.exclude("privacy_not_set") continue } @@ -1823,6 +1821,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 +2154,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 +2176,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 +2192,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{} @@ -2216,7 +2252,14 @@ func (s *OpenAIGatewayService) openAIGroupRequiresPrivacySet(ctx context.Context } func (s *OpenAIGatewayService) loadOpenAIGroupRequiresPrivacySet(ctx context.Context, groupID *int64) bool { - if s == nil || groupID == nil || s.schedulerSnapshot == nil { + if s == nil || groupID == nil { + return false + } + // 直连请求的被调度分组即认证分组,复用 auth 快照;composite 等 ID 不一致时回源。 + if ctxGroup, ok := ctx.Value(ctxkey.Group).(*Group); ok && IsGroupContextValid(ctxGroup) && ctxGroup.ID == *groupID { + return ctxGroup.RequirePrivacySet + } + if s.schedulerSnapshot == nil { return false } // GetByID 会聚合账号计数;隐私开关只在分组行上。 @@ -2272,7 +2315,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 +2366,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 +2414,7 @@ func (s *OpenAIGatewayService) selectAccountWithSchedulerOnce( } } legacySessionHash := sessionHash - if preserveGuardianParentBinding { + if preserveStickyBinding { legacySessionHash = "" } if requiredTransport == OpenAIUpstreamTransportAny || requiredTransport == OpenAIUpstreamTransportHTTPSSE { @@ -2457,7 +2500,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_compact_body_signal.go b/backend/internal/service/openai_compact_body_signal.go index e0ea88b62e..a545f1cfd6 100644 --- a/backend/internal/service/openai_compact_body_signal.go +++ b/backend/internal/service/openai_compact_body_signal.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "net/http" "strings" @@ -28,6 +29,9 @@ func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { if len(body) == 0 { return body, false, nil } + if !compactionTriggerNeedsDecode(body) { + return body, false, nil + } var payload map[string]any if err := decodeOpenAIJSONUseNumber(body, &payload); err != nil { return body, false, err @@ -63,6 +67,18 @@ func NormalizeCompactionTriggerInputOrder(body []byte) ([]byte, bool, error) { return encoded, true, nil } +// compactionTriggerNeedsDecode lets bodies that cannot hold a trigger skip the +// full decode: the type string appears literally unless a \u escape spells it. +// Such a body must still be a valid JSON object, so decode errors keep +// surfacing from the original path. +func compactionTriggerNeedsDecode(body []byte) bool { + if bytes.Contains(body, []byte("compaction_trigger")) || bytes.Contains(body, []byte(`\u`)) { + return true + } + trimmed := bytes.TrimLeft(body, " \t\r\n") + return len(trimmed) == 0 || trimmed[0] != '{' || !gjson.ValidBytes(body) +} + func isOpenAINativeCompactionV2(c *gin.Context) bool { if c == nil { return false diff --git a/backend/internal/service/openai_compact_body_signal_test.go b/backend/internal/service/openai_compact_body_signal_test.go index b0e0e4e24c..ef672ba16b 100644 --- a/backend/internal/service/openai_compact_body_signal_test.go +++ b/backend/internal/service/openai_compact_body_signal_test.go @@ -3,6 +3,7 @@ package service import ( + "strings" "testing" "github.com/gin-gonic/gin" @@ -116,3 +117,25 @@ func TestWebSocketCompatibilityNormalizesTriggerAfterPairedOutputCleanup(t *test require.Equal(t, "message", items[2].Get("type").String()) require.Equal(t, "compaction_trigger", items[3].Get("type").String()) } + +func TestNormalizeCompactionTriggerInputOrder_PrecheckKeepsContract(t *testing.T) { + plain := []byte(`{"model":"gpt-5","input":[{"type":"message","role":"user","content":"` + strings.Repeat("x", 4096) + `"}]}`) + allocs := testing.AllocsPerRun(10, func() { + got, changed, err := NormalizeCompactionTriggerInputOrder(plain) + if err != nil || changed || &got[0] != &plain[0] { + t.Fatal("body without a trigger must be returned unchanged") + } + }) + require.Zero(t, allocs) + + for _, invalid := range []string{`{"input":[`, `[{"type":"message"}]`, `{"input":[]} {}`} { + _, _, err := NormalizeCompactionTriggerInputOrder([]byte(invalid)) + require.Error(t, err, invalid) + } + + escaped := []byte(`{"input":[{"type":"\u0063ompaction_trigger"},{"type":"message","role":"user","content":"hi"}]}`) + normalized, changed, err := NormalizeCompactionTriggerInputOrder(escaped) + require.NoError(t, err) + require.True(t, changed) + require.Equal(t, "compaction_trigger", gjson.GetBytes(normalized, "input.1.type").String()) +} diff --git a/backend/internal/service/openai_cyber_session_block.go b/backend/internal/service/openai_cyber_session_block.go index 44c3ece444..be32b73121 100644 --- a/backend/internal/service/openai_cyber_session_block.go +++ b/backend/internal/service/openai_cyber_session_block.go @@ -16,12 +16,22 @@ import ( // repository 层 gatewayCache 附带实现(类型断言探测接入,不改 GatewayCache // 共享接口);测试 stub 不实现时屏蔽能力自动降级关闭。 type CyberSessionBlockStore interface { - SetCyberSessionBlocked(ctx context.Context, scopeKey string, keys []string, ttl time.Duration) error - IsCyberSessionScopeActive(ctx context.Context, scopeKey string) (bool, error) + SetCyberSessionBlocked(ctx context.Context, block CyberSessionBlock, ttl time.Duration) error + // CyberSessionTranscriptLengths returns the recorded transcript block + // lengths of the API key, or none when the source scope is inactive. + CyberSessionTranscriptLengths(ctx context.Context, apiKeyID int64, scopeKey string) ([]int, error) FindCyberSessionBlocked(ctx context.Context, keys []string) (string, error) } -const cyberSessionTranscriptLookupOverflowBlockKey = "transcript_lookup_limit_exceeded" +// CyberSessionBlock is one cyber hit to persist. Keys are exact block keys; +// TranscriptLengths records the history length of each transcript key among +// them and, like ScopeKey, is only meaningful for transcript matching. +type CyberSessionBlock struct { + APIKeyID int64 + ScopeKey string + Keys []string + TranscriptLengths []int +} // CyberSessionExplicitBlockKey returns an inexpensive exact key when the // client supplies a stable session signal. @@ -29,25 +39,6 @@ func CyberSessionExplicitBlockKey(apiKeyID int64, c *gin.Context, body []byte) s return hashCyberSessionBlockKey(apiKeyID, explicitOpenAISessionID(c, body)) } -// CyberSessionTranscriptBlockKeys returns the exact full-request key followed -// by an optional rewrite-tolerant context key. The latter is emitted only after -// model-generated history has been observed. -func CyberSessionTranscriptBlockKeys(apiKeyID int64, body []byte) []string { - derived := deriveOpenAICyberTranscriptBlockKeys(apiKeyID, body) - if len(derived.lookupKeys) == 0 { - return nil - } - keys := []string{derived.lookupKeys[len(derived.lookupKeys)-1]} - if derived.preLatestUserKey != "" && derived.preLatestUserKey != keys[0] { - keys = append(keys, derived.preLatestUserKey) - } - return keys -} - -func CyberSessionTranscriptLookupKeys(apiKeyID int64, body []byte) []string { - return deriveOpenAICyberTranscriptBlockKeys(apiKeyID, body).lookupKeys -} - // CyberSessionScopeKey is a coarse, non-blocking fingerprint used only to // avoid transcript parsing and MGET for sources that never produced a hit. func CyberSessionScopeKey(apiKeyID int64, clientIP, userAgent string) string { @@ -97,8 +88,8 @@ func (s *OpenAIGatewayService) CyberSessionBlockRuntime(ctx context.Context) (bo // MarkCyberSessionBlocked 把会话写入屏蔽表(写入点:cyber 命中后)。 // 开关关闭、key 为空或存储不可用时静默跳过。 -func (s *OpenAIGatewayService) MarkCyberSessionBlocked(ctx context.Context, scopeKey string, keys []string) { - if s == nil || len(keys) == 0 { +func (s *OpenAIGatewayService) MarkCyberSessionBlocked(ctx context.Context, block CyberSessionBlock) { + if s == nil || len(block.Keys) == 0 { return } enabled, ttl := s.CyberSessionBlockRuntime(ctx) @@ -109,7 +100,7 @@ func (s *OpenAIGatewayService) MarkCyberSessionBlocked(ctx context.Context, scop if store == nil { return } - if err := store.SetCyberSessionBlocked(ctx, scopeKey, keys, ttl); err != nil { + if err := store.SetCyberSessionBlocked(ctx, block, ttl); err != nil { logger.LegacyPrintf("service.openai_gateway", "cyber session block write failed: err=%v", err) } } @@ -135,22 +126,15 @@ func (s *OpenAIGatewayService) FindCyberSessionBlockedForRequest(ctx context.Con return key } } - scopeKey := CyberSessionScopeKey(apiKeyID, clientIP, userAgent) - active, err := store.IsCyberSessionScopeActive(ctx, scopeKey) + lengths, err := store.CyberSessionTranscriptLengths(ctx, apiKeyID, CyberSessionScopeKey(apiKeyID, clientIP, userAgent)) if err != nil { logger.LegacyPrintf("service.openai_gateway", "cyber session scope read failed: err=%v", err) return "" } - if !active { - return "" - } - transcript := deriveOpenAICyberTranscriptBlockKeys(apiKeyID, body) - if transcript.lookupKeysTruncated { - // Once the coarse scope is active, silently dropping old candidates would - // let a blocked client evade prefix matching by appending dummy items. - return cyberSessionTranscriptLookupOverflowBlockKey - } - keys := transcript.lookupKeys + // Blocked prefixes are recomputed only at their recorded lengths, so any + // number of appended items still reaches them and history length alone + // never decides a block. + keys := cyberSessionTranscriptKeysAt(apiKeyID, body, lengths) if len(keys) == 0 { return "" } diff --git a/backend/internal/service/openai_cyber_session_block_test.go b/backend/internal/service/openai_cyber_session_block_test.go index aff46df25d..1260eacbb7 100644 --- a/backend/internal/service/openai_cyber_session_block_test.go +++ b/backend/internal/service/openai_cyber_session_block_test.go @@ -54,81 +54,94 @@ func TestCyberSessionExplicitBlockKey(t *testing.T) { require.Equal(t, k6, CyberSessionExplicitBlockKey(101, c6b, b6b), "conversation_id key must be stable") } -func TestCyberTranscriptBlockKeysRequireModelGeneratedHistory(t *testing.T) { +func TestCyberTranscriptBlocksRequireModelGeneratedHistory(t *testing.T) { first := []byte(`{"instructions":"shared","input":[{"role":"user","content":"fixed environment"},{"role":"user","content":"question one"}]}`) second := []byte(`{"instructions":"shared","input":[{"role":"user","content":"fixed environment"},{"role":"user","content":"question two"}]}`) - firstKeys := CyberSessionTranscriptBlockKeys(77, first) - secondKeys := CyberSessionTranscriptBlockKeys(77, second) - require.Len(t, firstKeys, 1) - require.Len(t, secondKeys, 1) - require.NotEqual(t, firstKeys[0], secondKeys[0]) + firstBlocks := CyberSessionTranscriptBlocks(77, first) + secondBlocks := CyberSessionTranscriptBlocks(77, second) + require.Len(t, firstBlocks, 1) + require.Len(t, secondBlocks, 1) + require.NotEqual(t, firstBlocks[0].Key, secondBlocks[0].Key) hit := []byte(`{"messages":[{"role":"user","content":"setup"},{"role":"assistant","content":"ready"},{"role":"user","content":"trigger"}]}`) continuation := []byte(`{"messages":[{"role":"user","content":"setup"},{"role":"assistant","content":"ready"},{"role":"user","content":"different trigger"},{"role":"assistant","content":"blocked"},{"role":"user","content":"continue"}]}`) - hitKeys := CyberSessionTranscriptBlockKeys(77, hit) - require.Len(t, hitKeys, 2) - require.Contains(t, CyberSessionTranscriptLookupKeys(77, continuation), hitKeys[1]) + hitBlocks := CyberSessionTranscriptBlocks(77, hit) + require.Equal(t, []int{3, 2}, []int{hitBlocks[0].Length, hitBlocks[1].Length}) + require.Equal(t, []string{hitBlocks[1].Key}, cyberSessionTranscriptKeysAt(77, continuation, []int{hitBlocks[1].Length})) + require.NotEqual(t, []string{hitBlocks[0].Key}, cyberSessionTranscriptKeysAt(77, continuation, []int{hitBlocks[0].Length})) } -func TestCyberTranscriptBlockKeysWebSocketResponseCreate(t *testing.T) { +func TestCyberTranscriptBlocksWebSocketResponseCreate(t *testing.T) { body := []byte(`{"type":"response.create","response":{"prompt_cache_key":"ws-session","input":[{"role":"user","content":"setup"},{"role":"assistant","content":"ready"},{"role":"user","content":"trigger"}]}}`) c, _ := newCyberBlockTestCtx(nil, string(body)) require.NotEmpty(t, CyberSessionExplicitBlockKey(88, c, body)) - require.Len(t, CyberSessionTranscriptBlockKeys(88, body), 2) + require.Len(t, CyberSessionTranscriptBlocks(88, body), 2) } -func TestCyberTranscriptLookupKeysAreBoundedAndKeepNewestOrder(t *testing.T) { - messages := make([]map[string]string, maxOpenAICyberTranscriptLookupKeys+44) +func TestCyberTranscriptBlocksStringInputMatchesSingleItemHistory(t *testing.T) { + blocks := CyberSessionTranscriptBlocks(77, []byte(`{"input":"hello"}`)) + require.Equal(t, []CyberSessionTranscriptBlock{{Key: blocks[0].Key, Length: 1}}, blocks) + require.Equal(t, []string{blocks[0].Key}, cyberSessionTranscriptKeysAt(77, []byte(`{"input":["hello","more"]}`), []int{1})) + require.Empty(t, CyberSessionTranscriptBlocks(77, []byte(`{"input":" "}`))) +} + +func TestCyberTranscriptKeysAtRecomputesRecordedLengthsInOrder(t *testing.T) { + messages := make([]map[string]string, 300) for i := range messages { messages[i] = map[string]string{"role": "user", "content": "message-" + strconv.Itoa(i)} } body, err := json.Marshal(map[string]any{"messages": messages}) require.NoError(t, err) + prefixKey := func(length int) string { + prefix, err := json.Marshal(map[string]any{"messages": messages[:length]}) + require.NoError(t, err) + return CyberSessionTranscriptBlocks(77, prefix)[0].Key + } - keys := CyberSessionTranscriptLookupKeys(77, body) - require.Len(t, keys, maxOpenAICyberTranscriptLookupKeys) - - firstRetainedBody, err := json.Marshal(map[string]any{"messages": messages[:45]}) - require.NoError(t, err) - firstRetainedPrefix := CyberSessionTranscriptLookupKeys(77, firstRetainedBody) - require.Equal(t, firstRetainedPrefix[len(firstRetainedPrefix)-1], keys[0]) - - fullKey := CyberSessionTranscriptBlockKeys(77, body)[0] - require.Equal(t, fullKey, keys[len(keys)-1]) + require.Equal(t, []string{prefixKey(1), prefixKey(45), prefixKey(300)}, + cyberSessionTranscriptKeysAt(77, body, []int{300, 45, 1, 45, 301, 0})) + require.Empty(t, cyberSessionTranscriptKeysAt(77, body, nil)) + require.Equal(t, CyberSessionTranscriptBlocks(77, body)[0], CyberSessionTranscriptBlock{Key: prefixKey(300), Length: 300}) } // --- fakes --- type fakeCyberBlockStore struct { - blocked map[string]bool - scopes map[string]bool - findCalls int + blocked map[string]bool + scopes map[string]bool + lengths map[int64][]int + findKeys [][]string } var _ CyberSessionBlockStore = (*fakeCyberBlockStore)(nil) -func (f *fakeCyberBlockStore) SetCyberSessionBlocked(_ context.Context, scopeKey string, keys []string, _ time.Duration) error { +func (f *fakeCyberBlockStore) SetCyberSessionBlocked(_ context.Context, block CyberSessionBlock, _ time.Duration) error { if f.blocked == nil { f.blocked = map[string]bool{} } - for _, key := range keys { + for _, key := range block.Keys { f.blocked[key] = true } - if scopeKey != "" { + if block.ScopeKey != "" { if f.scopes == nil { f.scopes = map[string]bool{} + f.lengths = map[int64][]int{} } - f.scopes[scopeKey] = true + f.scopes[block.ScopeKey] = true + f.lengths[block.APIKeyID] = append(f.lengths[block.APIKeyID], block.TranscriptLengths...) } return nil } -func (f *fakeCyberBlockStore) IsCyberSessionScopeActive(_ context.Context, scopeKey string) (bool, error) { - return f.scopes[scopeKey], nil +func (f *fakeCyberBlockStore) CyberSessionTranscriptLengths(_ context.Context, apiKeyID int64, scopeKey string) ([]int, error) { + if !f.scopes[scopeKey] { + return nil, nil + } + return f.lengths[apiKeyID], nil } func (f *fakeCyberBlockStore) FindCyberSessionBlocked(_ context.Context, keys []string) (string, error) { - f.findCalls++ + f.findKeys = append(f.findKeys, keys) for _, key := range keys { if f.blocked[key] { return key, nil @@ -216,11 +229,11 @@ func (c *comboCacheAndStore) GetReasoningContent(_ context.Context, _ string) (s return "", ErrReasoningContentNotFound } -func (c *comboCacheAndStore) SetCyberSessionBlocked(ctx context.Context, scopeKey string, keys []string, ttl time.Duration) error { - return c.store.SetCyberSessionBlocked(ctx, scopeKey, keys, ttl) +func (c *comboCacheAndStore) SetCyberSessionBlocked(ctx context.Context, block CyberSessionBlock, ttl time.Duration) error { + return c.store.SetCyberSessionBlocked(ctx, block, ttl) } -func (c *comboCacheAndStore) IsCyberSessionScopeActive(ctx context.Context, scopeKey string) (bool, error) { - return c.store.IsCyberSessionScopeActive(ctx, scopeKey) +func (c *comboCacheAndStore) CyberSessionTranscriptLengths(ctx context.Context, apiKeyID int64, scopeKey string) ([]int, error) { + return c.store.CyberSessionTranscriptLengths(ctx, apiKeyID, scopeKey) } func (c *comboCacheAndStore) FindCyberSessionBlocked(ctx context.Context, keys []string) (string, error) { return c.store.FindCyberSessionBlocked(ctx, keys) @@ -233,7 +246,7 @@ func (c *comboCacheAndStore) FindCyberSessionBlocked(ctx context.Context, keys [ func TestFindCyberSessionBlocked_EmptyAndNilService(t *testing.T) { var nilSvc *OpenAIGatewayService require.Empty(t, nilSvc.FindCyberSessionBlockedForRequest(context.Background(), 1, nil, nil, "", "")) - require.NotPanics(t, func() { nilSvc.MarkCyberSessionBlocked(context.Background(), "", []string{"k"}) }) + require.NotPanics(t, func() { nilSvc.MarkCyberSessionBlocked(context.Background(), CyberSessionBlock{Keys: []string{"k"}}) }) svc := &OpenAIGatewayService{} require.Empty(t, svc.FindCyberSessionBlockedForRequest(context.Background(), 1, nil, nil, "", "")) @@ -267,7 +280,7 @@ func TestCyberSessionBlock_RoundTrip(t *testing.T) { explicitKey := CyberSessionExplicitBlockKey(1, c, body) require.Empty(t, svc.FindCyberSessionBlockedForRequest(ctx, 1, c, body, "203.0.113.1", "client/1.0")) - svc.MarkCyberSessionBlocked(ctx, "", []string{explicitKey, testKey}) + svc.MarkCyberSessionBlocked(ctx, CyberSessionBlock{APIKeyID: 1, Keys: []string{explicitKey, testKey}}) require.Equal(t, explicitKey, svc.FindCyberSessionBlockedForRequest(ctx, 1, c, body, "203.0.113.1", "client/1.0")) } @@ -286,16 +299,19 @@ func TestFindCyberSessionBlockedForRequestUsesScopeForTranscript(t *testing.T) { nextCtx, _ := newCyberBlockTestCtx(nil, string(nextBody)) const clientIP = "203.0.113.20" const userAgent = "Codex CLI 1.2.3" - blockKey := CyberSessionTranscriptBlockKeys(9, hitBody)[1] + block := CyberSessionTranscriptBlocks(9, hitBody)[1] // Without an active source scope, transcript candidates are never blocks. require.Empty(t, svc.FindCyberSessionBlockedForRequest(ctx, 9, nextCtx, nextBody, clientIP, userAgent)) scopeKey := CyberSessionScopeKey(9, clientIP, userAgent) - svc.MarkCyberSessionBlocked(ctx, scopeKey, []string{blockKey}) - require.Equal(t, blockKey, svc.FindCyberSessionBlockedForRequest(ctx, 9, nextCtx, nextBody, clientIP, "Codex CLI 1.2.4")) + svc.MarkCyberSessionBlocked(ctx, CyberSessionBlock{APIKeyID: 9, ScopeKey: scopeKey, Keys: []string{block.Key}, TranscriptLengths: []int{block.Length}}) + require.Equal(t, block.Key, svc.FindCyberSessionBlockedForRequest(ctx, 9, nextCtx, nextBody, clientIP, "Codex CLI 1.2.4")) } -func TestFindCyberSessionBlockedForRequestFailsClosedOnScopedTranscriptOverflow(t *testing.T) { +// Issue #8519: once a source scope is active, unrelated sessions with long +// histories must pass, while a blocked transcript padded with any number of +// appended items must still match its recorded prefix. +func TestFindCyberSessionBlockedForRequestMatchesLongHistoriesExactly(t *testing.T) { settingSvc := &SettingService{settingRepo: &fakeSettingRepo{vals: map[string]string{ SettingKeyCyberSessionBlockEnabled: "true", SettingKeyCyberSessionBlockTTLSeconds: "60", @@ -307,20 +323,46 @@ func TestFindCyberSessionBlockedForRequestFailsClosedOnScopedTranscriptOverflow( const clientIP = "203.0.113.20" const userAgent = "Codex CLI 1.2.3" - messages := make([]map[string]string, maxOpenAICyberTranscriptLookupKeys+1) - for i := range messages { - messages[i] = map[string]string{"role": "user", "content": "message-" + strconv.Itoa(i)} + history := func(prefix []map[string]string, padding int, tag string) []byte { + items := append([]map[string]string{}, prefix...) + for i := 0; i < padding; i++ { + role := "user" + if i%2 == 0 { + role = "assistant" + } + items = append(items, map[string]string{"role": role, "content": tag + "-" + strconv.Itoa(i)}) + } + body, err := json.Marshal(map[string]any{"input": items}) + require.NoError(t, err) + return body } - body, err := json.Marshal(map[string]any{"messages": messages}) - require.NoError(t, err) - c, _ := newCyberBlockTestCtx(nil, string(body)) - require.Empty(t, svc.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, body, clientIP, userAgent), - "overflow alone must not bypass the scope gate") - combo.store.scopes = map[string]bool{CyberSessionScopeKey(apiKeyID, clientIP, userAgent): true} + hitPrefix := []map[string]string{{"role": "user", "content": "setup"}, {"role": "assistant", "content": "ready"}, {"role": "user", "content": "trigger"}} + hitBody := history(hitPrefix, 0, "") + hitCtx, _ := newCyberBlockTestCtx(map[string]string{"session_id": "sess-hit"}, string(hitBody)) + block := CyberSessionBlock{ + APIKeyID: apiKeyID, + ScopeKey: CyberSessionScopeKey(apiKeyID, clientIP, userAgent), + Keys: []string{CyberSessionExplicitBlockKey(apiKeyID, hitCtx, hitBody)}, + } + transcripts := CyberSessionTranscriptBlocks(apiKeyID, hitBody) + for _, transcript := range transcripts { + block.Keys = append(block.Keys, transcript.Key) + block.TranscriptLengths = append(block.TranscriptLengths, transcript.Length) + } + svc.MarkCyberSessionBlocked(ctx, block) - require.Equal(t, cyberSessionTranscriptLookupOverflowBlockKey, - svc.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, body, clientIP, userAgent)) - require.Zero(t, combo.store.findCalls, "overflow must not issue an unbounded Redis lookup") + for _, items := range []int{256, 257, 1000} { + unrelated := history(nil, items, "unrelated") + c, _ := newCyberBlockTestCtx(map[string]string{"session_id": "sess-other"}, string(unrelated)) + require.Empty(t, svc.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, unrelated, clientIP, userAgent), "items=%d", items) + } + + padded := history(hitPrefix, 1000, "padding") + c, _ := newCyberBlockTestCtx(nil, string(padded)) + // The shorter rewrite-tolerant prefix is checked first (earliest match). + require.Equal(t, transcripts[1].Key, svc.FindCyberSessionBlockedForRequest(ctx, apiKeyID, c, padded, clientIP, userAgent)) + require.Len(t, combo.store.findKeys[len(combo.store.findKeys)-1], len(block.TranscriptLengths), + "lookup must only recompute the recorded prefix lengths") } func TestCyberSessionScopeKeyNormalizesUserAgentVersion(t *testing.T) { diff --git a/backend/internal/service/openai_cyber_transcript.go b/backend/internal/service/openai_cyber_transcript.go index b286c04769..75ef6cfc6f 100644 --- a/backend/internal/service/openai_cyber_transcript.go +++ b/backend/internal/service/openai_cyber_transcript.go @@ -10,27 +10,80 @@ import ( "github.com/tidwall/gjson" ) -type openAICyberTranscriptBlockKeys struct { - lookupKeys []string - preLatestUserKey string - lookupKeysTruncated bool +// CyberSessionTranscriptBlock is a cumulative history-prefix key together with +// the number of history items it covers. Recording the length lets lookups +// recompute exactly that prefix, so long or padded continuations stay exact. +type CyberSessionTranscriptBlock struct { + Key string + Length int } -// Bound the Redis lookup work for a single request while retaining the most -// recent transcript prefixes, where a continuation is most likely to match. -const maxOpenAICyberTranscriptLookupKeys = 256 - -// deriveOpenAICyberTranscriptBlockKeys returns cumulative semantic-history -// hashes plus the context key immediately before the latest user turn. The -// context key requires model-generated history so shared first-turn templates +// CyberSessionTranscriptBlocks returns the exact full-history block followed +// by an optional rewrite-tolerant block ending before the latest user turn. +// The latter requires model-generated history so shared first-turn templates // cannot block unrelated conversations. -func deriveOpenAICyberTranscriptBlockKeys(apiKeyID int64, body []byte) openAICyberTranscriptBlockKeys { +func CyberSessionTranscriptBlocks(apiKeyID int64, body []byte) []CyberSessionTranscriptBlock { + var full, preLatestUser CyberSessionTranscriptBlock + // This is an entropy heuristic, not provenance proof: authenticated + // server-side history would be required to distinguish fixed few-shot + // assistant items perfectly. + hasModelGeneratedItem := false + walkOpenAICyberTranscript(apiKeyID, body, func(item gjson.Result, length int, prefixKey func() string) bool { + if openAICyberTranscriptItemStartsUserTurn(item) && hasModelGeneratedItem && full.Length > 0 { + preLatestUser = full + } + full = CyberSessionTranscriptBlock{Key: prefixKey(), Length: length} + if openAICyberTranscriptItemIsModelGenerated(item) { + hasModelGeneratedItem = true + } + return true + }) + if full.Length == 0 { + return nil + } + blocks := []CyberSessionTranscriptBlock{full} + if preLatestUser.Length > 0 { + blocks = append(blocks, preLatestUser) + } + return blocks +} + +// cyberSessionTranscriptKeysAt recomputes the transcript prefix keys at the +// recorded block lengths, in ascending length order. Lengths beyond the +// request history cannot match and are skipped. +func cyberSessionTranscriptKeysAt(apiKeyID int64, body []byte, lengths []int) []string { + wanted := make(map[int]struct{}, len(lengths)) + maxLength := 0 + for _, length := range lengths { + if length > 0 { + wanted[length] = struct{}{} + maxLength = max(maxLength, length) + } + } + if len(wanted) == 0 { + return nil + } + keys := make([]string, 0, len(wanted)) + walkOpenAICyberTranscript(apiKeyID, body, func(_ gjson.Result, length int, prefixKey func() string) bool { + if _, ok := wanted[length]; ok { + keys = append(keys, prefixKey()) + } + return length < maxLength + }) + return keys +} + +// walkOpenAICyberTranscript hashes model-visible history cumulatively and calls +// visit after each item with the 1-based prefix length. prefixKey returns the +// key of the prefix ending at that item and is only valid during the call. +// Returning false from visit stops the walk. +func walkOpenAICyberTranscript(apiKeyID int64, body []byte, visit func(item gjson.Result, length int, prefixKey func() string) bool) { if len(body) == 0 { - return openAICyberTranscriptBlockKeys{} + return } root := openAIRequestPayloadView(body) if !root.Exists() || !root.IsObject() { - return openAICyberTranscriptBlockKeys{} + return } h := sha256.New() @@ -53,74 +106,40 @@ func deriveOpenAICyberTranscriptBlockKeys(apiKeyID int64, body []byte) openAICyb _, _ = h.Write([]byte(canonical)) } - appendSequence := func(sequence gjson.Result) openAICyberTranscriptBlockKeys { - if !sequence.Exists() || !sequence.IsArray() { - return openAICyberTranscriptBlockKeys{} + prefixKey := func() string { return hex.EncodeToString(h.Sum(nil)) } + length := 0 + feed := func(_, item gjson.Result) bool { + canonical := item.Raw + switch item.Type { + case gjson.String: + encoded, _ := json.Marshal(item.String()) + canonical = string(encoded) + case gjson.JSON: + canonical = normalizeCompatSeedJSON(json.RawMessage(item.Raw)) } - result := openAICyberTranscriptBlockKeys{ - lookupKeys: make([]string, 0, maxOpenAICyberTranscriptLookupKeys), - } - nextLookupKey := 0 - lookupKeysRotated := false - lastLookupKey := "" - // This is an entropy heuristic, not provenance proof: authenticated - // server-side history would be required to distinguish fixed few-shot - // assistant items perfectly. - hasModelGeneratedItem := false - sequence.ForEach(func(_, item gjson.Result) bool { - canonical := item.Raw - switch item.Type { - case gjson.String: - encoded, _ := json.Marshal(item.String()) - canonical = string(encoded) - case gjson.JSON: - canonical = normalizeCompatSeedJSON(json.RawMessage(item.Raw)) - } - if strings.TrimSpace(canonical) == "" { - return true - } - if openAICyberTranscriptItemStartsUserTurn(item) && hasModelGeneratedItem && lastLookupKey != "" { - result.preLatestUserKey = lastLookupKey - } - _, _ = h.Write([]byte("|item=")) - _, _ = h.Write([]byte(canonical)) - lastLookupKey = hex.EncodeToString(h.Sum(nil)) - if len(result.lookupKeys) < maxOpenAICyberTranscriptLookupKeys { - result.lookupKeys = append(result.lookupKeys, lastLookupKey) - } else { - result.lookupKeys[nextLookupKey] = lastLookupKey - nextLookupKey = (nextLookupKey + 1) % maxOpenAICyberTranscriptLookupKeys - lookupKeysRotated = true - result.lookupKeysTruncated = true - } - if openAICyberTranscriptItemIsModelGenerated(item) { - hasModelGeneratedItem = true - } + if strings.TrimSpace(canonical) == "" { return true - }) - if lookupKeysRotated { - ordered := make([]string, 0, len(result.lookupKeys)) - ordered = append(ordered, result.lookupKeys[nextLookupKey:]...) - ordered = append(ordered, result.lookupKeys[:nextLookupKey]...) - result.lookupKeys = ordered } - return result + _, _ = h.Write([]byte("|item=")) + _, _ = h.Write([]byte(canonical)) + length++ + return visit(item, length, prefixKey) } if messages := root.Get("messages"); messages.Exists() { - return appendSequence(messages) + if messages.IsArray() { + messages.ForEach(feed) + } + return } input := root.Get("input") if input.IsArray() { - return appendSequence(input) + input.ForEach(feed) + return } if input.Type == gjson.String && strings.TrimSpace(input.String()) != "" { - encoded, _ := json.Marshal(input.String()) - _, _ = h.Write([]byte("|item=")) - _, _ = h.Write(encoded) - return openAICyberTranscriptBlockKeys{lookupKeys: []string{hex.EncodeToString(h.Sum(nil))}} + feed(gjson.Result{}, input) } - return openAICyberTranscriptBlockKeys{} } func openAICyberTranscriptItemStartsUserTurn(item gjson.Result) bool { 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..ba7c1beaec 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/openai" "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" @@ -33,6 +34,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 } @@ -290,16 +292,45 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco bodyModified := false clientPromptCacheKey := promptCacheKey var reqBody map[string]any - ensureReqBody := func() (map[string]any, error) { - if requestView.HasPatches() { - patchedBody, patchErr := requestView.ApplyPatches() - if patchErr != nil { - return nil, patchErr - } + // Each patched body supersedes the previous one, so this attempt holds only + // the live output's budget, returned when Forward ends rather than retained + // across failover attempts until the handler returns. + releasePatchedBodyMemory := func() {} + defer func() { releasePatchedBodyMemory() }() + flushPatches := func() error { + if !requestView.HasPatches() { + return nil + } + patchCtx, releasePatch := httputil.WithRequestBodyMemoryScope(ctx) + patchedBody, patchErr := requestView.ApplyPatches(patchCtx) + if patchErr == nil { + releasePatchedBodyMemory() + releasePatchedBodyMemory = releasePatch body = patchedBody requestView = newOpenAIRequestView(body) reqBody = nil bodyModified = false + return nil + } + releasePatch() + if errors.Is(patchErr, httputil.ErrRequestBodyMemoryBudget) { + return patchErr + } + // Raw edits cannot express this patch set. Replay it on the decoded + // body so the map-based fallback still applies every edit. + if reqBody == nil { + decoded, decodeErr := requestView.Decode(c) + if decodeErr != nil { + return decodeErr + } + reqBody = decoded + } + requestView.MovePatchesTo(reqBody) + return nil + } + ensureReqBody := func() (map[string]any, error) { + if err := flushPatches(); err != nil { + return nil, err } if reqBody != nil { return reqBody, nil @@ -705,13 +736,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } if bodyModified { - if requestView.HasPatches() { - if patchedBody, patchErr := requestView.ApplyPatches(); patchErr == nil { - body = patchedBody - requestView = newOpenAIRequestView(body) - reqBody = nil - bodyModified = false - } + if err := flushPatches(); err != nil { + return nil, err } if bodyModified { decoded, decodeErr := ensureReqBody() @@ -1042,6 +1068,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 +1234,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 98f2749455..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 { @@ -376,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 { @@ -443,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 @@ -553,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, @@ -2015,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) @@ -2066,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)) @@ -2378,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) @@ -2445,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) } diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index 38cc743d9d..076ec7b3a7 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -11,9 +11,11 @@ import ( "strings" "unicode/utf8" + "github.com/MoeForge/moego/ojson" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" "github.com/Wei-Shaw/sub2api/internal/util/urlvalidator" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -1170,14 +1172,177 @@ func (v *openAIRequestView) DisablePatches() { v.patches = nil } +// MovePatchesTo replays pending raw patches onto reqBody, decoded from the same +// unpatched body, when they cannot be applied as raw edits. Later edits must go +// to reqBody directly, so patching is disabled afterwards. +func (v *openAIRequestView) MovePatchesTo(reqBody map[string]any) { + if v == nil { + return + } + for _, patch := range v.patches { + if patch.delete { + deleteOpenAIRequestMapPath(reqBody, patch.path) + } else { + setOpenAIRequestMapPath(reqBody, patch.path, patch.value) + } + } + v.DisablePatches() +} + func (v openAIRequestView) HasPatches() bool { return !v.patchesDisabled && len(v.patches) > 0 } -func (v openAIRequestView) ApplyPatches() ([]byte, error) { +func (v openAIRequestView) ApplyPatches(ctx context.Context) ([]byte, error) { if v.patchesDisabled || len(v.patches) == 0 { return nil, errors.New("openai request patches disabled") } + // Every strategy materializes one full output. Reserve the input size before + // editing so an exhausted budget rejects without wasted work, then settle the + // reservation to the exact output length. + reserved := int64(len(v.body)) + if err := httputil.ReserveRequestBodyMemory(ctx, reserved); err != nil { + return nil, err + } + out, err := v.materializePatches() + if err != nil { + httputil.ReleaseRequestBodyMemory(ctx, reserved) + return nil, err + } + if extra := int64(len(out)) - reserved; extra > 0 { + if err := httputil.ReserveRequestBodyMemory(ctx, extra); err != nil { + httputil.ReleaseRequestBodyMemory(ctx, reserved) + return nil, err + } + } else { + httputil.ReleaseRequestBodyMemory(ctx, -extra) + } + return out, nil +} + +func (v openAIRequestView) materializePatches() ([]byte, error) { + // A single edit already needs only one output buffer. Keep sjson's exact + // behavior for it and for inputs outside ojson's compatibility contract. + if len(v.patches) == 1 || !v.canBatchPatches() { + return v.applyPatchesSequential() + } + + // Doc borrows the immutable request body only within this call. Materialize + // once into owned storage; neither Doc nor its borrowed results escape. + doc := ojson.NewDoc(v.body) + for _, patch := range v.patches { + var err error + if patch.delete { + err = doc.Delete(patch.path) + } else { + err = doc.Set(patch.path, patch.value) + } + if err != nil { + // Doc rejects some edits sjson accepts (e.g. a key under an array). + // Only scalar values reach here, so retrying runs no marshaler twice. + return v.applyPatchesSequential() + } + } + return doc.Bytes(), nil +} + +func (v openAIRequestView) canBatchPatches() bool { + // Doc indexes members of containers traversed by edits. Bound that scratch + // metadata independently of body size; a large opaque input is fine, but a + // dense object must not amplify memory before the output reservation. + const maxBatchPatches = 16 + if len(v.patches) > maxBatchPatches { + return false + } + for _, patch := range v.patches { + if !patch.delete { + switch patch.value.(type) { + case nil, bool, string, json.Number, int, int8, int16, int32, int64, + uint, uint8, uint16, uint32, uint64, float32, float64: + default: + // Container/custom values could introduce an unbounded object + // for a later child edit, or run a marshaler twice on fallback. + return false + } + } + if !isOpenAIBatchPatchPath(patch.path) { + return false + } + } + for _, ancestor := range v.patches { + for _, patch := range v.patches { + // An ancestor edit can replace the checked object or expose a second + // duplicate key. Keep those batches on the existing path. + if len(patch.path) > len(ancestor.path) && patch.path[len(ancestor.path)] == '.' && + strings.HasPrefix(patch.path, ancestor.path) { + return false + } + } + } + body := bytes.TrimSpace(v.body) + if len(body) == 0 || body[0] != '{' { + return false + } + // Borrow the body rather than copying it into a string. The scans below do + // not retain results or materialize member maps. + root := ojson.Parse(openAIWSPayloadStringView(body)) + for _, patch := range v.patches { + for i := 0; i < len(patch.path); i++ { + if patch.path[i] != '.' { + continue + } + parent := root.Get(patch.path[:i]) + // sjson edits inside string parents differently. Inspect only the + // original raw input: Doc.Get can copy an already edited container. + if parent.Type == ojson.String || !openAIRequestPatchObjectIsSmall(parent) { + return false + } + } + } + // Reject unsuitable shapes before paying for full validation. Only a valid + // document reaches Doc; both borrowed readers tolerate malformed input. + return openAIRequestPatchObjectIsSmall(root) && ojson.ValidBytes(body) +} + +// isOpenAIBatchPatchPath narrows isSimpleOpenAIRequestPatchPath to what ojson +// and sjson address identically. Production paths are host-owned identifiers; +// queries, array indices, modifiers and non-ASCII keys retain sjson semantics. +func isOpenAIBatchPatchPath(path string) bool { + start := true + depth := 1 + for i := 0; i < len(path); i++ { + c := path[i] + if c == '.' && !start { + depth++ + if depth > 4 { + return false + } + start = true + continue + } + if c != '_' && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && + (start || c < '0' || c > '9') { + return false + } + start = false + } + return !start +} + +func openAIRequestPatchObjectIsSmall(value ojson.Result) bool { + const maxMembers = 64 + if !value.IsObject() { + return true + } + members := 0 + value.ForEach(func(_, _ ojson.Result) bool { + members++ + return members <= maxMembers + }) + return members <= maxMembers +} + +func (v openAIRequestView) applyPatchesSequential() ([]byte, error) { body := v.body for _, patch := range v.patches { var err error @@ -1520,7 +1685,7 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * } } needsOrphanCleanup := account != nil && account.IsOpenAIOAuthLike() && - gjson.GetBytes(normalized, "input").IsArray() + openAIResponsesInputMayNeedOrphanCleanup(normalized) if needsOrphanCleanup || openAIResponsesInputMayNeedTruncation(normalized) { var reqBody map[string]any if err := decodeOpenAIJSONUseNumber(normalized, &reqBody); err != nil { @@ -1691,24 +1856,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 481227c11a..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 @@ -1778,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) } 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_gateway_service_hotpath_test.go b/backend/internal/service/openai_gateway_service_hotpath_test.go index 65ba44f2dd..a703b46a86 100644 --- a/backend/internal/service/openai_gateway_service_hotpath_test.go +++ b/backend/internal/service/openai_gateway_service_hotpath_test.go @@ -68,7 +68,7 @@ func TestOpenAIRequestView_ApplyPatches(t *testing.T) { view.MarkPatchDelete("previous_response_id") view.MarkPatchSet("reasoning.effort", "none") - patched, err := view.ApplyPatches() + patched, err := view.ApplyPatches(context.Background()) require.NoError(t, err) require.JSONEq(t, `{"model":"gpt-5.1","reasoning":{"effort":"none"},"input":[{"type":"message","content":"hi"}]}`, string(patched)) } @@ -78,7 +78,7 @@ func TestOpenAIRequestView_RejectsEscapedPatchPath(t *testing.T) { view.MarkPatchSet(`metadata.user\.id`, "new") require.False(t, view.HasPatches()) - _, err := view.ApplyPatches() + _, err := view.ApplyPatches(context.Background()) require.Error(t, err) } @@ -87,7 +87,7 @@ func TestOpenAIRequestView_ApplyPatchesDisabled(t *testing.T) { view.MarkPatchSet("model", "gpt-5.1") view.DisablePatches() - _, err := view.ApplyPatches() + _, err := view.ApplyPatches(context.Background()) require.Error(t, err) } 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_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_privacy_gate_ctx_test.go b/backend/internal/service/openai_privacy_gate_ctx_test.go new file mode 100644 index 0000000000..0fed48124f --- /dev/null +++ b/backend/internal/service/openai_privacy_gate_ctx_test.go @@ -0,0 +1,80 @@ +package service + +import ( + "context" + "encoding/json" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +type countingPrivacyGroupRepo struct { + GroupRepository + group *Group + calls atomic.Int32 +} + +func (r *countingPrivacyGroupRepo) GetByIDLite(context.Context, int64) (*Group, error) { + r.calls.Add(1) + return r.group, nil +} + +func (r *countingPrivacyGroupRepo) GetByID(ctx context.Context, id int64) (*Group, error) { + return r.GetByIDLite(ctx, id) +} + +// Direct requests schedule on the authenticated group, so the privacy gate +// comes from the auth snapshot in ctx instead of a group-table read per pick. +func TestOpenAIGatewayService_PrivacyGateReadsAuthGroupFromContext(t *testing.T) { + groupID := int64(39101) + for _, advanced := range []string{"false", "true"} { + t.Run(map[string]string{"false": "legacy", "true": "advanced"}[advanced], func(t *testing.T) { + accounts := []Account{ + {ID: 39111, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0, GroupIDs: []int64{groupID}, Credentials: map[string]any{"plan_type": "team"}}, + {ID: 39112, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 5, GroupIDs: []int64{groupID}, Credentials: map[string]any{"plan_type": "team"}, Extra: map[string]any{"privacy_mode": PrivacyModeTrainingOff}}, + } + repo := &guardianAffinityAccountRepo{schedulerGroupAwareOpenAIAccountRepo: schedulerGroupAwareOpenAIAccountRepo{schedulerTestOpenAIAccountRepo{accounts: accounts}}} + // The repository disagrees with ctx; reading it would admit 39111. + groupRepo := &countingPrivacyGroupRepo{group: &Group{ID: groupID, Name: "stale", RequirePrivacySet: false}} + svc := &OpenAIGatewayService{ + accountRepo: repo, + cache: &schedulerTestGatewayCache{}, + cfg: &config.Config{}, + rateLimitService: newOpenAIAdvancedSchedulerRateLimitService(advanced), + concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{acquireResults: map[int64]bool{39111: true, 39112: true}}), + schedulerSnapshot: &SchedulerSnapshotService{accountRepo: repo, groupRepo: groupRepo}, + } + ctx := context.WithValue(context.Background(), ctxkey.Group, &Group{ + ID: groupID, Name: "privacy", Platform: PlatformOpenAI, Status: StatusActive, + Hydrated: true, RequirePrivacySet: true, + }) + + selection, _, err := svc.SelectAccountWithScheduler(ctx, &groupID, "", "", "gpt-5.1", nil, OpenAIUpstreamTransportAny, false) + require.NoError(t, err) + require.NotNil(t, selection) + require.Equal(t, int64(39112), selection.Account.ID) + require.Zero(t, groupRepo.calls.Load(), "privacy gate must not read the group table for the auth group") + if selection.ReleaseFunc != nil { + selection.ReleaseFunc() + } + }) + } +} + +func TestAPIKeyAuthSnapshotRequirePrivacySetRoundtrip(t *testing.T) { + svc := &APIKeyService{} + apiKey := profitAuthTestAPIKey() + apiKey.Group.RequirePrivacySet = true + + payload, err := json.Marshal(&APIKeyAuthCacheEntry{Snapshot: svc.snapshotFromAPIKey(context.Background(), apiKey)}) + require.NoError(t, err) + var restored APIKeyAuthCacheEntry + require.NoError(t, json.Unmarshal(payload, &restored)) + materialized, used, err := svc.applyAuthCacheEntry(apiKey.Key, &restored) + require.NoError(t, err) + require.True(t, used) + require.True(t, materialized.Group.RequirePrivacySet) +} 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_request_patches_benchmark_test.go b/backend/internal/service/openai_request_patches_benchmark_test.go new file mode 100644 index 0000000000..4593eb96a3 --- /dev/null +++ b/backend/internal/service/openai_request_patches_benchmark_test.go @@ -0,0 +1,150 @@ +package service + +import ( + "bytes" + "context" + "strings" + "testing" +) + +var benchmarkOpenAIRequestPatchesSink []byte + +// Compare the same patch list and immutable input, without timing request-view +// construction. BenchmarkOpenAIResponses_LargeInputRawPatch covers that too. +func BenchmarkOpenAIRequestPatches(b *testing.B) { + for _, size := range []struct { + name string + bytes int + }{ + {name: "small", bytes: 256}, + {name: "1MiB", bytes: 1 << 20}, + {name: "8MiB", bytes: 8 << 20}, + } { + body := []byte(`{"model":"old","max_tokens":8192,"input":[{"type":"message","role":"user","content":"` + strings.Repeat("a", size.bytes) + `"}],"reasoning":{"effort":"low"},"previous_response_id":"resp_1","service_tier":"flex"}`) + for _, edits := range []struct { + name string + patches []openAIRequestPatch + }{ + { + name: "1_edit", + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + }, + }, + { + name: "6_edits", + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "reasoning.effort", value: "none"}, + {path: "previous_response_id", delete: true}, + {path: "max_output_tokens", value: 8192}, + {path: "max_tokens", delete: true}, + {path: "service_tier", value: "priority"}, + }, + }, + } { + view := requestViewWithPatches(body, edits.patches) + want, err := applyOpenAIRequestPatchesSequential(body, edits.patches) + if err != nil { + b.Fatal(err) + } + got, err := view.ApplyPatches(context.Background()) + if err != nil || !bytes.Equal(want, got) { + b.Fatalf("patch results differ: %v", err) + } + for _, implementation := range []struct { + name string + apply func() ([]byte, error) + }{ + {name: "SequentialSJSON", apply: func() ([]byte, error) { return applyOpenAIRequestPatchesSequential(body, edits.patches) }}, + {name: "ApplyPatches", apply: func() ([]byte, error) { return view.ApplyPatches(context.Background()) }}, + } { + b.Run(size.name+"/"+edits.name+"/"+implementation.name, func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + patched, err := implementation.apply() + if err != nil { + b.Fatal(err) + } + benchmarkOpenAIRequestPatchesSink = patched + } + }) + } + } + } +} + +// A small byte length can still contain thousands of object members. Keep this +// case beside the large opaque-input benchmarks to expose scratch amplification. +func BenchmarkOpenAIRequestPatches_DenseObjects(b *testing.B) { + for _, fixture := range []struct { + name string + nested bool + }{ + {name: "root"}, + {name: "nested", nested: true}, + } { + body, patches := denseOpenAIRequestPatchFixture(4096, fixture.nested) + view := requestViewWithPatches(body, patches) + if view.canBatchPatches() { + b.Fatal("dense object should retain the sequential implementation") + } + want, err := applyOpenAIRequestPatchesSequential(body, patches) + if err != nil { + b.Fatal(err) + } + got, err := view.ApplyPatches(context.Background()) + if err != nil || !bytes.Equal(want, got) { + b.Fatalf("patch results differ: %v", err) + } + for _, implementation := range []struct { + name string + apply func() ([]byte, error) + }{ + {name: "SequentialSJSON", apply: func() ([]byte, error) { return applyOpenAIRequestPatchesSequential(body, patches) }}, + {name: "ApplyPatches", apply: func() ([]byte, error) { return view.ApplyPatches(context.Background()) }}, + } { + b.Run(fixture.name+"/"+implementation.name, func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + patched, err := implementation.apply() + if err != nil { + b.Fatal(err) + } + benchmarkOpenAIRequestPatchesSink = patched + } + }) + } + } +} + +// Rechecking an edited parent through Doc.Get can materialize its large opaque +// sibling after every edit. The batched path should allocate one final body. +func BenchmarkOpenAIRequestPatches_RepeatedNestedLeaf(b *testing.B) { + body, patches := repeatedNestedOpenAIRequestPatchFixture() + view := requestViewWithPatches(body, patches) + for _, implementation := range []struct { + name string + apply func() ([]byte, error) + }{ + {name: "SequentialSJSON", apply: func() ([]byte, error) { return applyOpenAIRequestPatchesSequential(body, patches) }}, + {name: "ApplyPatches", apply: func() ([]byte, error) { return view.ApplyPatches(context.Background()) }}, + } { + b.Run(implementation.name, func(b *testing.B) { + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + patched, err := implementation.apply() + if err != nil { + b.Fatal(err) + } + benchmarkOpenAIRequestPatchesSink = patched + } + }) + } +} diff --git a/backend/internal/service/openai_request_patches_test.go b/backend/internal/service/openai_request_patches_test.go new file mode 100644 index 0000000000..bd554762bf --- /dev/null +++ b/backend/internal/service/openai_request_patches_test.go @@ -0,0 +1,664 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/httputil" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/sjson" +) + +// Keep the previous sequential implementation as a wire-compatibility oracle. +// JSONEq would miss changes to duplicate keys, number spelling and unknown fields. +func applyOpenAIRequestPatchesSequential(body []byte, patches []openAIRequestPatch) ([]byte, error) { + for _, patch := range patches { + var err error + if patch.delete { + body, err = sjson.DeleteBytes(body, patch.path) + } else { + body, err = sjson.SetBytes(body, patch.path, patch.value) + } + if err != nil { + return nil, err + } + } + return body, nil +} + +func requestViewWithPatches(body []byte, patches []openAIRequestPatch) openAIRequestView { + view := newOpenAIRequestView(body) + for _, patch := range patches { + if patch.delete { + view.MarkPatchDelete(patch.path) + } else { + view.MarkPatchSet(patch.path, patch.value) + } + } + return view +} + +func denseOpenAIRequestPatchFixture(fields int, nested bool) ([]byte, []openAIRequestPatch) { + var body strings.Builder + body.Grow(fields*16 + 64) + prefix := "" + if nested { + _, _ = body.WriteString(`{"model":"old","reasoning":`) + prefix = "reasoning." + } + _ = body.WriteByte('{') + for i := 0; i < fields; i++ { + if i > 0 { + _ = body.WriteByte(',') + } + fmt.Fprintf(&body, `"f%d":0`, i) + } + _ = body.WriteByte('}') + if nested { + _ = body.WriteByte('}') + } + return []byte(body.String()), []openAIRequestPatch{ + {path: fmt.Sprintf("%sf%d", prefix, fields-2), value: 1}, + {path: fmt.Sprintf("%sf%d", prefix, fields-1), value: 2}, + } +} + +func TestOpenAIRequestPatches_BoundIndexedObjectMembers(t *testing.T) { + for _, nested := range []bool{false, true} { + for _, fields := range []int{64, 65, 4096} { + t.Run(fmt.Sprintf("nested_%t_%d_fields", nested, fields), func(t *testing.T) { + body, patches := denseOpenAIRequestPatchFixture(fields, nested) + original := bytes.Clone(body) + view := requestViewWithPatches(body, patches) + require.Equal(t, fields <= 64, view.canBatchPatches(), "dense edited objects must not amplify Doc scratch memory") + want, err := applyOpenAIRequestPatchesSequential(body, patches) + require.NoError(t, err) + got, err := view.ApplyPatches(context.Background()) + require.NoError(t, err) + require.Equal(t, want, got) + require.Equal(t, original, body) + }) + } + } +} + +func TestOpenAIRequestPatches_LargeUntouchedInputStillBatches(t *testing.T) { + dense, _ := denseOpenAIRequestPatchFixture(4096, false) + body := []byte(`{"model":"old","input":[{"content":"` + strings.Repeat("a", 1<<20) + `","opaque":` + string(dense) + `}],"reasoning":{"effort":"low"}}`) + patches := []openAIRequestPatch{{path: "model", value: "mapped"}, {path: "reasoning.effort", value: "none"}} + view := requestViewWithPatches(body, patches) + require.True(t, view.canBatchPatches(), "unvisited input objects must remain opaque regardless of their size or member count") + want, err := applyOpenAIRequestPatchesSequential(body, patches) + require.NoError(t, err) + got, err := view.ApplyPatches(context.Background()) + require.NoError(t, err) + require.Equal(t, want, got) +} + +func TestOpenAIRequestPatches_DeletingParentCannotExposeUncheckedDuplicate(t *testing.T) { + dense, _ := denseOpenAIRequestPatchFixture(4096, false) + body := []byte(`{"model":"old","reasoning":{"effort":"low"},"reasoning":` + string(dense) + `}`) + patches := []openAIRequestPatch{{path: "reasoning", delete: true}, {path: "reasoning.effort", value: "none"}} + view := requestViewWithPatches(body, patches) + require.False(t, view.canBatchPatches(), "deleting the first parent exposes a dense duplicate that the original lookup did not inspect") + want, err := applyOpenAIRequestPatchesSequential(body, patches) + require.NoError(t, err) + got, err := view.ApplyPatches(context.Background()) + require.NoError(t, err) + require.Equal(t, want, got) +} + +func repeatedNestedOpenAIRequestPatchFixture() ([]byte, []openAIRequestPatch) { + body := []byte(`{"model":"old","reasoning":{"effort":"low","opaque":"` + strings.Repeat("a", 1<<20) + `"},"input":[]}`) + return body, []openAIRequestPatch{ + {path: "reasoning.effort", value: "medium"}, + {path: "reasoning.effort", value: "high"}, + {path: "reasoning.effort", value: "none"}, + } +} + +func TestOpenAIRequestPatches_RepeatedNestedLeafKeepsOpaqueSiblingBorrowed(t *testing.T) { + body, patches := repeatedNestedOpenAIRequestPatchFixture() + view := requestViewWithPatches(body, patches) + require.True(t, view.canBatchPatches(), "repeated leaf edits do not replace their parent and must remain eligible") + want, err := applyOpenAIRequestPatchesSequential(body, patches) + require.NoError(t, err) + got, err := view.ApplyPatches(context.Background()) + require.NoError(t, err) + require.Equal(t, want, got) +} + +func TestOpenAIRequestPatches_PreserveSequentialWireBehavior(t *testing.T) { + tests := []struct { + name string + body string + patches []openAIRequestPatch + }{ + { + name: "single edit preserves opaque wire fields", + body: " \n{\"model\":\"old\", \"opaque\": {\"integer\":9007199254740993,\"decimal\":1.2300e+04,\"zero\":-0,\"text\":\"\\u4f60\\u597d\"}, \"input\":[]}\t ", + patches: []openAIRequestPatch{ + {path: "model", value: "new"}, + }, + }, + { + name: "multiple edits preserve opaque wire fields", + body: " \n{\"model\":\"old\", \"opaque\": {\"integer\":9007199254740993,\"decimal\":1.2300e+04,\"zero\":-0,\"text\":\"\\u4f60\\u597d\"}, \"input\":[],\"reasoning\":{\"effort\":\"low\",\"future\":true}}\t ", + patches: []openAIRequestPatch{ + {path: "model", value: "new"}, + {path: "reasoning.effort", value: "none"}, + {path: "instructions", value: "quoted \"text\"\n你好 "}, + }, + }, + { + name: "duplicate top-level and nested keys", + body: `{"model":"first","model":"second","reasoning":{"effort":"low","effort":"high"},"reasoning":{"effort":"max"},"opaque":1,"opaque":2}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "reasoning.effort", value: "none"}, + {path: "model", delete: true}, + {path: "model", value: "final"}, + }, + }, + { + name: "forward token normalization followed by clamp", + body: `{"model":"old","max_tokens":65536,"max_completion_tokens":1000,"prompt_cache_options":{"future":true},"input":[],"previous_response_id":"resp_1","service_tier":"flex"}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "max_output_tokens", value: float64(65536)}, + {path: "max_tokens", delete: true}, + {path: "max_completion_tokens", delete: true}, + {path: "prompt_cache_options", delete: true}, + {path: "max_output_tokens", value: 8192}, + {path: "previous_response_id", delete: true}, + {path: "service_tier", value: "priority"}, + }, + }, + { + name: "replace parent after child then edit new child", + body: `{"model":"gpt-5","reasoning":{"effort":"low","opaque":123},"input":[]}`, + patches: []openAIRequestPatch{ + {path: "reasoning.effort", value: "high"}, + {path: "reasoning", value: map[string]any{"effort": "medium", "future": true}}, + {path: "reasoning.effort", value: "none"}, + }, + }, + { + name: "delete parent and recreate child", + body: `{"model":"gpt-5","reasoning":{"effort":"low","opaque":123},"input":[]}`, + patches: []openAIRequestPatch{ + {path: "reasoning.effort", value: "high"}, + {path: "reasoning", delete: true}, + {path: "reasoning.effort", value: "none"}, + }, + }, + { + name: "create replace delete and recreate same field", + body: `{"model":"gpt-5","input":[]}`, + patches: []openAIRequestPatch{ + {path: "instructions", value: "first"}, + {path: "instructions", value: "second"}, + {path: "instructions", delete: true}, + {path: "instructions", value: "third"}, + }, + }, + { + name: "missing deletes around effective edits", + body: `{"model":"old","reasoning":{"effort":"low"},"input":[]}`, + patches: []openAIRequestPatch{ + {path: "previous_response_id", delete: true}, + {path: "model", value: "mapped"}, + {path: "text.verbosity", delete: true}, + {path: "reasoning.effort", value: "none"}, + {path: "previous_response_id", delete: true}, + }, + }, + { + name: "deleting first middle and last members", + body: `{"previous_response_id":"resp_1", "model":"old", "text":{"verbosity":"high","format":{"type":"text"}}, "max_tokens":100}`, + patches: []openAIRequestPatch{ + {path: "previous_response_id", delete: true}, + {path: "text.verbosity", delete: true}, + {path: "max_tokens", delete: true}, + }, + }, + { + name: "only missing deletes", + body: ` {"model":"old", "input":[]} `, + patches: []openAIRequestPatch{ + {path: "previous_response_id", delete: true}, + {path: "text.verbosity", delete: true}, + }, + }, + { + name: "replace scalar parent with object", + body: `{"model":"gpt-5","reasoning":null,"input":[]}`, + patches: []openAIRequestPatch{ + {path: "reasoning.effort", value: "none"}, + {path: "instructions", value: ""}, + }, + }, + { + name: "scalar types and exact json number", + body: `{"model":"gpt-5","input":[]}`, + patches: []openAIRequestPatch{ + {path: "store", value: false}, + {path: "stream", value: true}, + {path: "max_output_tokens", value: json.Number("9007199254740993")}, + {path: "instructions", value: nil}, + }, + }, + { + name: "existing string parent containing JSON text", + body: `{"model":"old","reasoning":"{\"effort\":\"low\"}","input":[]}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "reasoning.effort", value: "none"}, + }, + }, + { + name: "parent becomes string before child edit", + body: `{"model":"old","reasoning":{"effort":"low"},"input":[]}`, + patches: []openAIRequestPatch{ + {path: "reasoning", value: `{"effort":"high"}`}, + {path: "reasoning.effort", value: "none"}, + }, + }, + { + name: "array parent before child edit", + body: `{"model":"old","reasoning":[{"effort":"low"}],"input":[]}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "reasoning.effort", value: "none"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + want, wantErr := applyOpenAIRequestPatchesSequential(body, tt.patches) + view := requestViewWithPatches(body, tt.patches) + require.True(t, view.HasPatches()) + + got, err := view.ApplyPatches(context.Background()) + if wantErr != nil { + require.EqualError(t, err, wantErr.Error()) + require.Equal(t, want, got) + require.Equal(t, tt.body, string(body)) + return + } + require.NoError(t, err) + require.Equal(t, string(want), string(got)) + require.True(t, json.Valid(got)) + require.Equal(t, tt.body, string(body), "patching must not mutate the source body") + }) + } +} + +func TestOpenAIRequestPatches_PreserveCallerCancellationPolicy(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + for _, edits := range []int{1, 2} { + t.Run(fmt.Sprintf("%d_edits", edits), func(t *testing.T) { + body := []byte(`{"model":"old","input":[]}`) + view := newOpenAIRequestView(body) + for i := 0; i < edits; i++ { + view.MarkPatchSet("model", "mapped") + } + got, err := view.ApplyPatches(ctx) + // Forward owns cancellation/drain policy; editing must not change + // the existing OAuth path's detached upstream-request behavior. + require.NoError(t, err) + require.Equal(t, `{"model":"mapped","input":[]}`, string(got)) + require.Equal(t, `{"model":"old","input":[]}`, string(body)) + }) + } +} + +func TestOpenAIRequestPatches_CompatibilityFallback(t *testing.T) { + for _, tt := range []struct { + name string + body string + patches []openAIRequestPatch + }{ + { + name: "malformed object after a valid prefix", + body: `{"model":"a","input":[`, + patches: []openAIRequestPatch{ + {path: "model", value: "b"}, + {path: "reasoning.effort", value: "none"}, + }, + }, + { + name: "query path", + body: `{"model":"old","input":[{"role":"user","content":"hello"}]}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: `input.#(role=="user").content`, value: "new"}, + }, + }, + { + name: "special path character", + body: `{"model":"old","metadata":{"user*":"old"}}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "metadata.user*", value: "new"}, + }, + }, + { + name: "key under array parent", + body: `{"model":"old","reasoning":[1]}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "reasoning.effort", value: "none"}, + }, + }, + { + name: "invalid UTF-8 path", + body: `{"model":"old","metadata":{}}`, + patches: []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "metadata.\xff", value: "new"}, + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + want, wantErr := applyOpenAIRequestPatchesSequential(body, tt.patches) + view := requestViewWithPatches(body, tt.patches) + require.True(t, view.HasPatches()) + got, gotErr := view.ApplyPatches(context.Background()) + if wantErr != nil { + require.EqualError(t, gotErr, wantErr.Error()) + } else { + require.NoError(t, gotErr) + } + require.Equal(t, want, got) + require.Equal(t, tt.body, string(body)) + }) + } +} + +func TestOpenAIRequestPatches_ReserveOutputUntilRequestRelease(t *testing.T) { + body := []byte(`{"model":"old","reasoning":{"effort":"low"},"input":[]}`) + patches := []openAIRequestPatch{{path: "model", value: "mapped"}, {path: "reasoning.effort", value: "none"}} + want, err := applyOpenAIRequestPatchesSequential(body, patches) + require.NoError(t, err) + limit := int64(len(body) + len(want)) + budget := httputil.NewBodyMemoryBudget(limit) + ctx, release := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + t.Cleanup(release) + require.NoError(t, httputil.ReserveRequestBodyMemory(ctx, int64(len(body)))) + view := requestViewWithPatches(body, patches) + + got, err := view.ApplyPatches(ctx) + require.NoError(t, err, "the exact input plus output budget must suffice") + require.Equal(t, want, got) + probe, releaseProbe := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + t.Cleanup(releaseProbe) + require.ErrorIs(t, httputil.ReserveRequestBodyMemory(probe, 1), httputil.ErrRequestBodyMemoryBudget) + release() + require.NoError(t, httputil.ReserveRequestBodyMemory(probe, limit)) + // A second release must not refund another request's reservation. + release() + require.ErrorIs(t, httputil.ReserveRequestBodyMemory(probe, 1), httputil.ErrRequestBodyMemoryBudget) +} + +func TestOpenAIRequestPatches_RejectUnavailableOutputBudget(t *testing.T) { + body := []byte(`{"model":"old","reasoning":{"effort":"low"},"input":[]}`) + for _, tt := range []struct { + name string + patches []openAIRequestPatch + }{ + {name: "batched", patches: []openAIRequestPatch{{path: "model", value: "mapped"}, {path: "reasoning.effort", value: "none"}}}, + {name: "single", patches: []openAIRequestPatch{{path: "model", value: "mapped"}}}, + {name: "sequential", patches: []openAIRequestPatch{{path: "model", value: "mapped"}, {path: "metadata", value: map[string]any{"k": "v"}}}}, + } { + want, err := applyOpenAIRequestPatchesSequential(body, tt.patches) + require.NoError(t, err) + for _, scenario := range []string{"exhausted", "below input", "closed", "canceled and closed"} { + t.Run(tt.name+"/"+scenario, func(t *testing.T) { + limit := int64(len(want)) + switch scenario { + case "exhausted": + limit-- + case "below input": + // Rejected by the up-front input-size reservation, before editing. + limit = int64(len(body)) - 1 + } + budget := httputil.NewBodyMemoryBudget(limit) + parent, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + ctx, release := httputil.WithRequestBodyMemoryBudget(parent, budget) + t.Cleanup(release) + switch scenario { + case "closed": + release() + case "canceled and closed": + cancel() + release() + } + view := requestViewWithPatches(body, tt.patches) + got, err := view.ApplyPatches(ctx) + require.ErrorIs(t, err, httputil.ErrRequestBodyMemoryBudget) + require.Nil(t, got) + probe, releaseProbe := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + t.Cleanup(releaseProbe) + require.NoError(t, httputil.ReserveRequestBodyMemory(probe, limit), "failed materialization must not consume the shared budget") + }) + } + t.Run(tt.name+"/exact", func(t *testing.T) { + budget := httputil.NewBodyMemoryBudget(int64(len(want))) + ctx, release := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + t.Cleanup(release) + got, err := requestViewWithPatches(body, tt.patches).ApplyPatches(ctx) + require.NoError(t, err) + require.Equal(t, want, got) + probe, releaseProbe := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + t.Cleanup(releaseProbe) + require.ErrorIs(t, httputil.ReserveRequestBodyMemory(probe, 1), httputil.ErrRequestBodyMemoryBudget, "the reservation must settle to the exact output") + }) + } +} + +func TestOpenAIRequestPatches_MovePatchesToDecodedBody(t *testing.T) { + body := []byte(`{"model":"old","reasoning":[1],"previous_response_id":"resp_1"}`) + view := requestViewWithPatches(body, []openAIRequestPatch{ + {path: "model", value: "mapped"}, + {path: "reasoning.effort", value: "none"}, + {path: "previous_response_id", delete: true}, + }) + _, err := view.ApplyPatches(context.Background()) + require.Error(t, err, "raw edits cannot set a key under an array") + decoded, err := view.Decode(nil) + require.NoError(t, err) + view.MovePatchesTo(decoded) + require.False(t, view.HasPatches()) + out, err := json.Marshal(decoded) + require.NoError(t, err) + require.JSONEq(t, `{"model":"mapped","reasoning":{"effort":"none"}}`, string(out)) + require.Equal(t, `{"model":"old","reasoning":[1],"previous_response_id":"resp_1"}`, string(body)) +} + +func TestOpenAIRequestPatches_ForwardReleasesPatchedBodyWhenAttemptEnds(t *testing.T) { + gin.SetMode(gin.TestMode) + body := []byte(`{"model":"gpt-5","stream":false,"reasoning":{"effort":"minimal"},"max_tokens":1024,"input":[{"type":"message","content":"hi"}]}`) + const limit = 1 << 20 + budget := httputil.NewBodyMemoryBudget(limit) + ctx, release := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + t.Cleanup(release) + for attempt := range 3 { + upstream := &httpUpstreamRecorder{ + resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"usage":{"input_tokens":1,"output_tokens":2}}`)), + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream} + account := &Account{ + ID: int64(attempt + 1), + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{"api_key": "sk-test", "base_url": "https://example.com"}, + Extra: map[string]any{"use_responses_api": true}, + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil).WithContext(ctx) + SetOpenAIClientTransport(c, OpenAIClientTransportHTTP) + + _, err := svc.Forward(ctx, c, account, body) + require.NoError(t, err) + require.NotNil(t, upstream.lastReq) + // Failover attempts must not accumulate rewritten bodies until the handler returns. + probe, releaseProbe := httputil.WithRequestBodyMemoryBudget(context.Background(), budget) + require.NoError(t, httputil.ReserveRequestBodyMemory(probe, limit), "attempt %d retained its patched body", attempt) + releaseProbe() + } +} + +func TestOpenAIRequestPatches_ForwardStopsBeforeUpstreamOnOverload(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tt := range []struct { + name string + body string + }{ + { + name: "final raw patch flush", + body: `{"model":"gpt-5","stream":false,"reasoning":{"effort":"minimal"},"max_tokens":1024,"input":[{"type":"message","content":"hi"}]}`, + }, + { + name: "flush before schema decode", + body: `{"model":"client-alias","stream":false,"reasoning":{"effort":"minimal"},"text":{"format":{"type":"json_schema","name":"test","schema":{"type":"object","properties":{}}}},"input":[{"type":"message","content":"hi"}]}`, + }, + } { + t.Run(tt.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{ + resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"usage":{"input_tokens":1,"output_tokens":2}}`)), + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream} + account := &Account{ + ID: 1, + Name: "openai-apikey", + Platform: PlatformOpenAI, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "sk-test", + "base_url": "https://example.com", + "model_mapping": map[string]any{"client-alias": "gpt-5"}, + }, + Extra: map[string]any{"use_responses_api": true}, + } + ctx, release := httputil.WithRequestBodyMemoryBudget(context.Background(), httputil.NewBodyMemoryBudget(1)) + t.Cleanup(release) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil).WithContext(ctx) + SetOpenAIClientTransport(c, OpenAIClientTransportHTTP) + + result, err := svc.Forward(ctx, c, account, []byte(tt.body)) + require.ErrorIs(t, err, httputil.ErrRequestBodyMemoryBudget) + require.Nil(t, result) + require.Nil(t, upstream.lastReq, "overload must not fall back to unbudgeted serialization or forwarding") + }) + } +} + +func TestOpenAIRequestPatches_EffectiveEditsOwnOutput(t *testing.T) { + for _, patches := range [][]openAIRequestPatch{ + {{path: "model", value: "mapped"}}, + {{path: "previous_response_id", delete: true}}, + {{path: "model", value: "mapped"}, {path: "reasoning.effort", value: "none"}, {path: "previous_response_id", delete: true}}, + } { + t.Run(fmt.Sprintf("%d_edits_%s", len(patches), patches[0].path), func(t *testing.T) { + body := []byte(`{"model":"old","reasoning":{"effort":"low"},"previous_response_id":"resp_1","opaque":"` + strings.Repeat("payload", 4096) + `"}`) + view := requestViewWithPatches(body, patches) + got, err := view.ApplyPatches(context.Background()) + require.NoError(t, err) + snapshot := bytes.Clone(got) + + // The borrowed source may be released or reused after ApplyPatches returns. + for i := range body { + body[i] = 'x' + } + require.Equal(t, snapshot, got) + got[0] = '!' + require.Equal(t, bytes.Repeat([]byte{'x'}, len(body)), body) + }) + } +} + +type failingOpenAIRequestPatchValue struct { + err error +} + +func (v failingOpenAIRequestPatchValue) MarshalJSON() ([]byte, error) { + return nil, v.err +} + +func TestOpenAIRequestPatches_PropagateValueErrorWithoutPartialOutput(t *testing.T) { + valueErr := errors.New("request patch encoding failed") + for _, priorEdits := range []int{0, 1, 2} { + t.Run(fmt.Sprintf("after_%d_edits", priorEdits), func(t *testing.T) { + body := []byte(`{"model":"old","instructions":"original","input":[]}`) + original := bytes.Clone(body) + view := newOpenAIRequestView(body) + for i := 0; i < priorEdits; i++ { + view.MarkPatchSet("model", fmt.Sprintf("mapped-%d", i)) + } + view.MarkPatchSet("instructions", failingOpenAIRequestPatchValue{err: valueErr}) + + got, err := view.ApplyPatches(context.Background()) + require.ErrorIs(t, err, valueErr) + require.Nil(t, got) + require.Equal(t, original, body) + }) + } +} + +func TestOpenAIRequestPatches_ConcurrentImmutableInput(t *testing.T) { + body := []byte(`{"model":"old","reasoning":{"effort":"low"},"previous_response_id":"resp_1","opaque":"` + strings.Repeat("payload", 4096) + `"}`) + original := bytes.Clone(body) + t.Cleanup(func() { + require.Equal(t, original, body) + }) + for worker := 0; worker < 8; worker++ { + t.Run(fmt.Sprintf("worker_%d", worker), func(t *testing.T) { + t.Parallel() + patches := []openAIRequestPatch{ + {path: "model", value: fmt.Sprintf("model-%d", worker)}, + {path: "reasoning.effort", value: "none"}, + {path: "previous_response_id", delete: true}, + } + want, err := applyOpenAIRequestPatchesSequential(body, patches) + require.NoError(t, err) + for i := 0; i < 16; i++ { + view := requestViewWithPatches(body, patches) + got, err := view.ApplyPatches(context.Background()) + require.NoError(t, err) + require.Equal(t, want, got) + got[0] = '!' + } + }) + } +} 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_responses_orphan_precheck.go b/backend/internal/service/openai_responses_orphan_precheck.go new file mode 100644 index 0000000000..ec9084988d --- /dev/null +++ b/backend/internal/service/openai_responses_orphan_precheck.go @@ -0,0 +1,133 @@ +package service + +import ( + "bytes" + "encoding/json" + + "github.com/tidwall/gjson" +) + +// openAIResponsesInputMayNeedOrphanCleanup only proves that cleanup is a no-op. +// Possible outputs still use the existing decoder and sanitizer, including its +// named standalone outputs, call/id fallback and item-reference rules. All byte +// spans below borrow the immutable request only for this synchronous call. +func openAIResponsesInputMayNeedOrphanCleanup(body []byte) bool { + // Use Get directly: Parse(...).Get(...) differs from GetBytes on malformed + // prefixes, where the old gate can still find an input and invoke the decoder. + input := gjson.Get(openAIWSPayloadStringView(body), "input") + if !input.IsArray() { + return false + } + if !json.Valid(body) { + // Preserve the existing decoder's malformed/trailing-JSON error path. + return true + } + if body[skipOpenAIWSJSONSpace(body, 0)] != '{' || input.Index <= 0 || input.Index > len(body)-len(input.Raw) { + return true + } + + hasPreviousResponseID := false + inputSeen, previousResponseIDSeen := false, false + if !visitOpenAIResponsesOrphanPrecheckFields(body, func(key, value []byte) bool { + switch string(key) { + case `"input"`: + if inputSeen { + return false + } + inputSeen = true + case `"previous_response_id"`: + if previousResponseIDSeen { + return false + } + previousResponseIDSeen = true + if value[0] == '"' { + if bytes.IndexByte(value, '\\') >= 0 { + return false + } + hasPreviousResponseID = len(bytes.TrimSpace(value[1:len(value)-1])) != 0 + } + } + return true + }) { + // GJSON selects first duplicate keys; encoding/json selects the last. + // Escaped keys and duplicate relevant keys conservatively use the latter. + return true + } + if hasPreviousResponseID { + return false + } + + rawInput := body[input.Index : input.Index+len(input.Raw)] + for i := 1; ; { + i = skipOpenAIWSJSONSpace(rawInput, i) + if rawInput[i] == ']' { + return false + } + start := i + switch rawInput[i] { + case '{', '[', '"': + i = skipOpenAIWSJSONValue(rawInput, i) + default: + // The shared object-value scanner stops at '}', whereas scalar + // array members end at ']'. No scalar item can contain a tool output. + for rawInput[i] != ',' && rawInput[i] != ']' { + i++ + } + } + if rawInput[start] == '{' { + typeSeen := false + if !visitOpenAIResponsesOrphanPrecheckFields(rawInput[start:i], func(key, value []byte) bool { + if string(key) != `"type"` { + return true + } + if typeSeen { + return false + } + typeSeen = true + if value[0] != '"' { + return true + } + if bytes.IndexByte(value, '\\') >= 0 { + return false + } + return !isCodexToolCallOutputItemType(parseRawJSONView(value).Str) + }) { + return true + } + } + i = skipOpenAIWSJSONSpace(rawInput, i) + if rawInput[i] == ',' { + i++ + } + } +} + +// visitOpenAIResponsesOrphanPrecheckFields visits an already-validated object +// without materializing unrelated strings (including large escaped content). +// Escaped keys are deliberately left to the full decoder rather than decoded +// into potentially request-sized temporary strings here. +func visitOpenAIResponsesOrphanPrecheckFields(object []byte, visit func(key, value []byte) bool) bool { + i := skipOpenAIWSJSONSpace(object, 0) + 1 + for { + i = skipOpenAIWSJSONSpace(object, i) + if object[i] == '}' { + return true + } + keyStart := i + keyEnd := scanOpenAIWSJSONString(object, i) + key := object[keyStart:keyEnd] + if bytes.IndexByte(key, '\\') >= 0 { + return false + } + i = skipOpenAIWSJSONSpace(object, keyEnd) + 1 // Valid JSON guarantees ':'. + valueStart := skipOpenAIWSJSONSpace(object, i) + i = skipOpenAIWSJSONValue(object, valueStart) + if !visit(key, bytes.TrimSpace(object[valueStart:i])) { + return false + } + i = skipOpenAIWSJSONSpace(object, i) + if object[i] == ',' { + i++ + } + } +} diff --git a/backend/internal/service/openai_responses_orphan_precheck_benchmark_test.go b/backend/internal/service/openai_responses_orphan_precheck_benchmark_test.go new file mode 100644 index 0000000000..73c1c2c6cf --- /dev/null +++ b/backend/internal/service/openai_responses_orphan_precheck_benchmark_test.go @@ -0,0 +1,49 @@ +package service + +import ( + "fmt" + "strings" + "testing" + + "github.com/tidwall/gjson" +) + +// These measure only the orphan-cleanup stage, not the complete gateway. B/op +// is cumulative allocated memory per operation, not retained heap or RSS. +func BenchmarkOpenAIResponsesOrphanPrecheck(b *testing.B) { + for _, size := range []int{64 << 10, 1 << 20, 4 << 20} { + for _, previous := range []bool{false, true} { + name := fmt.Sprintf("bytes_%d/previous_%t", size, previous) + bodyText := `{"input":[{"type":"message","content":"` + strings.Repeat(`text\n`, size/6) + `"}]` + if previous { + bodyText += `,"previous_response_id":"resp_1"` + } + body := []byte(bodyText + `}`) + b.Run(name+"/before", func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(body))) + for b.Loop() { + if gjson.GetBytes(body, "input").IsArray() { + var request map[string]any + if err := decodeOpenAIJSONUseNumber(body, &request); err != nil { + b.Fatal(err) + } + input, _ := request["input"].([]any) + if sanitizeOpenAIResponsesOrphanToolOutputs(request, input, previous) { + b.Fatal("unexpected cleanup") + } + } + } + }) + b.Run(name+"/after", func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(body))) + for b.Loop() { + if openAIResponsesInputMayNeedOrphanCleanup(body) { + b.Fatal("unexpected cleanup candidate") + } + } + }) + } + } +} diff --git a/backend/internal/service/openai_responses_orphan_precheck_test.go b/backend/internal/service/openai_responses_orphan_precheck_test.go new file mode 100644 index 0000000000..9e41e8ee63 --- /dev/null +++ b/backend/internal/service/openai_responses_orphan_precheck_test.go @@ -0,0 +1,170 @@ +package service + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIResponsesOrphanPrecheck(t *testing.T) { + tests := []struct { + name string + body string + want bool + }{ + {"empty object", `{}`, false}, + {"array root", `[{"input":[]}]`, false}, + {"string root", `"input"`, false}, + {"number root", `1`, false}, + {"null root", `null`, false}, + {"leading whitespace", "\r\n\t {\"input\":[{\"type\":\"message\"}]} ", false}, + {"empty array", `{"input":[]}`, false}, + {"message", `{"input":[{"type":"message","content":"plain text"}]}`, false}, + {"escaped content", `{"input":[{"content":"quoted \"type\":\"function_call_output\"\ntext","type":"message"}]}`, false}, + {"nested output type", `{"input":[{"type":"message","content":[{"type":"function_call_output"}]}]}`, false}, + {"scalar items", `{"input":[null,true,false,1,"escaped\ntext",[],{"type":"message"},null]}`, false}, + {"final scalar whitespace", "{\"input\":[{}, \t 12.5 \r\n ]}", false}, + {"previous response", `{"previous_response_id":" resp_1 ","input":[{"type":"function_call_output","call_id":"missing"}]}`, false}, + {"previous response unicode whitespace", `{"input":[{"type":"function_call_output"}],"previous_response_id":" resp_1 "}`, false}, + {"blank previous response", `{"previous_response_id":"  ","input":[{"type":"function_call_output"}]}`, true}, + {"non string previous response", `{"previous_response_id":123,"input":[{"type":"function_call_output"}]}`, true}, + {"null previous response", `{"previous_response_id":null,"input":[{"type":"function_call_output"}]}`, true}, + {"orphan output", `{"input":[{"type":"function_call_output","call_id":"missing"}]}`, true}, + {"trimmed output type", `{"input":[{"type":" function_call_output "}]}`, true}, + {"named standalone output", `{"input":[{"type":"function_call_output","name":"delegate","output":"task"}]}`, true}, + {"matched id fallback", `{"input":[{"type":"function_call","id":"fc_1"},{"type":"function_call_output","call_id":"fc_1"}]}`, true}, + {"matched reference", `{"input":[{"type":"item_reference","id":"ref_1"},{"type":"custom_tool_call_output","call_id":"ref_1"}]}`, true}, + {"search output", `{"input":[{"type":"tool_search_output"}]}`, true}, + {"mcp output", `{"input":[{"type":"mcp_tool_call_output"}]}`, true}, + {"non string type", `{"input":[{"type":123},{"type":null},{"type":{"type":"function_call_output"}}]}`, false}, + {"escaped input key", `{"inpu\u0074":[{"type":"function_call_output"}]}`, true}, + {"escaped type key", `{"input":[{"ty\u0070e":"function_call_output"}]}`, true}, + {"escaped output type", `{"input":[{"type":"function_call_\u006futput"}]}`, true}, + {"escaped previous key", `{"previous_response_\u0069d":"resp_1","input":[{"type":"function_call_output"}]}`, true}, + {"escaped previous value", `{"previous_response_id":"\u0020","input":[{"type":"function_call_output"}]}`, true}, + {"duplicate type last output", `{"input":[{"type":"message","type":"function_call_output"}]}`, true}, + {"duplicate type last message", `{"input":[{"type":"function_call_output","type":"message"}]}`, true}, + {"duplicate previous last null", `{"previous_response_id":"resp_1","previous_response_id":null,"input":[{"type":"function_call_output"}]}`, true}, + {"duplicate previous last present", `{"previous_response_id":null,"previous_response_id":"resp_1","input":[{"type":"function_call_output"}]}`, true}, + {"duplicate input last output", `{"input":[],"input":[{"type":"function_call_output"}]}`, true}, + {"duplicate input last null", `{"input":[{"type":"function_call_output"}],"input":null}`, true}, + {"first input non array keeps old gate", `{"input":null,"input":[{"type":"function_call_output"}]}`, false}, + {"empty body", ``, false}, + {"malformed without input", `{"model":`, false}, + {"malformed non array input", `{"input":"text",`, false}, + {"trailing non array input", `{"input":null} {}`, false}, + {"garbage prefix array input", `junk{"input":[]}`, true}, + {"garbage prefix non array input", `junk{"input":null}`, false}, + {"truncated", `{"input":[{"type":"message"}]`, true}, + {"trailing object", `{"input":[{"type":"message"}]} {}`, true}, + {"trailing junk", `{"input":[]}x`, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + body := []byte(tt.body) + require.Equal(t, tt.want, openAIResponsesInputMayNeedOrphanCleanup(body)) + require.Equal(t, tt.body, string(body), "precheck must not mutate borrowed input") + }) + } +} + +func TestOpenAIResponsesOrphanPrecheckPreservesSanitizer(t *testing.T) { + for _, body := range []string{ + `{"input":[{"type":"function_call_output","name":"delegate","namespace":"codex_app","output":"task"}]}`, + `{"input":[{"type":"function_call_output","call_id":"fc_1","output":"ok"},{"type":"function_call","call_id":" ","id":"fc_1"}]}`, + `{"input":[{"type":"tool_search_output","call_id":"ref_1"},{"type":"item_reference","id":"ref_1"}]}`, + `{"input":[{"type":"message","type":"function_call_output","call_id":"missing"}]}`, + `{"input":[{"type":"function_call_output","type":"message","content":"keep"}]}`, + `{"previous_response_id":"resp_1","previous_response_id":null,"input":[{"type":"function_call_output"}]}`, + `{"previous_response_id":null,"previous_response_id":"resp_1","input":[{"type":"function_call_output"}]}`, + `{"input":[],"input":[{"type":"function_call_output"}]}`, + `{"input":[{"type":"function_call_output"}],"input":null}`, + `{"inpu\u0074":[{"ty\u0070e":"function_call_\u006futput"}],"vendor":{"count":9007199254740993}}`, + `{"input":[{"type":"message","content":"unchanged"}],"vendor":{"count":9007199254740993}}`, + } { + t.Run(body, func(t *testing.T) { + var expected, actual map[string]any + require.NoError(t, decodeOpenAIJSONUseNumber([]byte(body), &expected)) + require.NoError(t, decodeOpenAIJSONUseNumber([]byte(body), &actual)) + apply := func(request map[string]any) bool { + input, _ := request["input"].([]any) + return sanitizeOpenAIResponsesOrphanToolOutputs(request, input, firstNonEmptyString(request["previous_response_id"]) != "") + } + wantChanged := apply(expected) + gotChanged := false + if openAIResponsesInputMayNeedOrphanCleanup([]byte(body)) { + gotChanged = apply(actual) + } + require.Equal(t, wantChanged, gotChanged) + require.Equal(t, expected, actual) + + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} + normalized, _, err := normalizeOpenAIResponsesWebSocketCompatibilityBody([]byte(body), account, false) + require.NoError(t, err) + var integrated map[string]any + require.NoError(t, decodeOpenAIJSONUseNumber(normalized, &integrated)) + require.Equal(t, expected, integrated) + }) + } +} + +func TestOpenAIResponsesOrphanPrecheckCompatibilityErrors(t *testing.T) { + account := &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth} + for _, body := range []string{ + `{"input":[{"type":"message"}]`, + `{"previous_response_id":"resp_1","input":[]} {}`, + `{"input":[]} trailing`, + } { + t.Run(body, func(t *testing.T) { + require.True(t, openAIResponsesInputMayNeedOrphanCleanup([]byte(body))) + _, _, err := normalizeOpenAIResponsesWebSocketCompatibilityBody([]byte(body), account, false) + require.Error(t, err) + }) + } +} + +func TestOpenAIResponsesOrphanPrecheckLargeEscapedContent(t *testing.T) { + body := []byte(`{"vendor":"` + strings.Repeat(`\n\"`, 1<<16) + `","input":[{"content":"` + strings.Repeat(`\n\"`, 1<<16) + `","type":"message"}]}`) + require.False(t, openAIResponsesInputMayNeedOrphanCleanup(body)) + allocations := testing.AllocsPerRun(5, func() { + if openAIResponsesInputMayNeedOrphanCleanup(body) { + panic("unexpected cleanup candidate") + } + }) + require.Zero(t, allocations, "large borrowed strings must not be unescaped or copied") +} + +func FuzzOpenAIResponsesOrphanPrecheck(f *testing.F) { + for _, seed := range []string{ + `{"input":[{"type":"message","content":"text"}]}`, + `{"input":[null,true,false,1,"text",[],{}]}`, + `{"input":[{"type":"function_call_output"}]}`, + `{"input":[{"type":"message","type":"function_call_output"}]}`, + `{"previous_response_id":"resp_1","previous_response_id":null,"input":[]}`, + `{"input":[{"ty\u0070e":"function_call_output"}]}`, + } { + f.Add(seed) + } + f.Fuzz(func(t *testing.T, raw string) { + body := []byte(raw) + mayNeedCleanup := openAIResponsesInputMayNeedOrphanCleanup(body) + oldEligible := gjson.GetBytes(body, "input").IsArray() + if !oldEligible { + require.False(t, mayNeedCleanup, "must preserve the old non-array gate, including malformed input") + return + } + var request map[string]any + if err := decodeOpenAIJSONUseNumber(body, &request); err != nil { + require.True(t, mayNeedCleanup, "must preserve the old decoder's errors") + return + } + // Preserve the old initial first-key array gate, then compare with the + // authoritative decoder/sanitizer's last-key behavior. + input, _ := request["input"].([]any) + if sanitizeOpenAIResponsesOrphanToolOutputs(request, input, firstNonEmptyString(request["previous_response_id"]) != "") && !mayNeedCleanup { + t.Fatal("precheck missed required cleanup") + } + }) +} 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_upstream_transport_error.go b/backend/internal/service/openai_upstream_transport_error.go index 8c56f000da..7c847b84db 100644 --- a/backend/internal/service/openai_upstream_transport_error.go +++ b/backend/internal/service/openai_upstream_transport_error.go @@ -175,6 +175,9 @@ func (s *OpenAIGatewayService) tempUnscheduleOpenAITransportError(ctx context.Co if s == nil || account == nil { return } + if s.cfg != nil && s.cfg.Gateway.DisableOpenAITransportErrorCooldown { + return + } until := time.Now().Add(openAITransportErrorTempUnschedDuration) reason := "upstream transport error (proxy/network): " + safeErr diff --git a/backend/internal/service/openai_upstream_transport_error_handle_test.go b/backend/internal/service/openai_upstream_transport_error_handle_test.go index 8aaed2eae4..27090f8cdd 100644 --- a/backend/internal/service/openai_upstream_transport_error_handle_test.go +++ b/backend/internal/service/openai_upstream_transport_error_handle_test.go @@ -6,8 +6,10 @@ import ( "context" "errors" "fmt" + "net" "net/http" "net/http/httptest" + "net/url" "testing" "time" @@ -39,6 +41,119 @@ func newOpenAITransportErrTestContext() (*gin.Context, *httptest.ResponseRecorde return c, rec } +func TestHandleOpenAIUpstreamTransportError_DNSCooldownConfig(t *testing.T) { + transportErr := &url.Error{ + Op: "Post", + URL: "https://chatgpt.com/backend-api/codex/responses", + Err: &net.OpError{Op: "dial", Net: "tcp", Err: &net.DNSError{ + Err: "no such host", Name: "chatgpt.com", Server: "127.0.0.11:53", IsNotFound: true, + }}, + } + require.True(t, classifyUpstreamTransportError(transportErr).Persistent) + for _, testCase := range []struct { + name string + cfg *config.Config + disabled bool + }{ + {name: "nil"}, + {name: "zero", cfg: &config.Config{}}, + {name: "enabled", cfg: &config.Config{Gateway: config.GatewayConfig{DisableOpenAITransportErrorCooldown: false}}}, + {name: "disabled", cfg: &config.Config{Gateway: config.GatewayConfig{DisableOpenAITransportErrorCooldown: true}}, disabled: true}, + } { + for _, withRepo := range []bool{false, true} { + for _, passthrough := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/repo=%t/passthrough=%t", testCase.name, withRepo, passthrough), func(t *testing.T) { + repo := &openaiTransportAccountRepoStub{} + svc := &OpenAIGatewayService{cfg: testCase.cfg} + if withRepo { + svc.accountRepo = repo + } + account := &Account{ID: 8541, Name: "shared-egress", Platform: PlatformOpenAI} + c, rec := newOpenAITransportErrTestContext() + before := time.Now() + retErr := svc.handleOpenAIUpstreamTransportError(context.Background(), c, account, transportErr, passthrough) + after := time.Now() + + var failover *UpstreamFailoverError + require.ErrorAs(t, retErr, &failover) + require.Equal(t, http.StatusBadGateway, failover.StatusCode) + require.JSONEq(t, `{"error":{"type":"upstream_error","message":"Upstream request failed"}}`, string(failover.ResponseBody)) + require.False(t, rec.Flushed) + require.False(t, c.Writer.Written()) + require.Empty(t, rec.Body.String()) + rawEvents, exists := c.Get(OpsUpstreamErrorsKey) + require.True(t, exists) + var events []*OpsUpstreamErrorEvent + require.IsType(t, events, rawEvents) + events = rawEvents.([]*OpsUpstreamErrorEvent) + require.Len(t, events, 1) + require.Equal(t, account.ID, events[0].AccountID) + require.Equal(t, account.Name, events[0].AccountName) + require.Equal(t, PlatformOpenAI, events[0].Platform) + require.Equal(t, "request_error", events[0].Kind) + require.Zero(t, events[0].UpstreamStatusCode) + require.Equal(t, passthrough, events[0].Passthrough) + require.Contains(t, events[0].Message, "no such host") + require.Equal(t, 0, c.GetInt(OpsUpstreamStatusCodeKey)) + require.Equal(t, events[0].Message, c.GetString(OpsUpstreamErrorMessageKey)) + + require.Equal(t, !testCase.disabled, svc.isOpenAIAccountRuntimeBlocked(account)) + if testCase.disabled { + _, blocked := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) + require.False(t, blocked) + } else { + blockUntil, exists := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) + require.True(t, exists) + require.WithinRange(t, blockUntil.(time.Time), before.Add(10*time.Minute), after.Add(10*time.Minute)) + } + if withRepo && !testCase.disabled { + require.Len(t, repo.tempUnschedCalls, 1) + call := repo.tempUnschedCalls[0] + require.Equal(t, account.ID, call.accountID) + require.WithinRange(t, call.until, before.Add(10*time.Minute), after.Add(10*time.Minute)) + require.Contains(t, call.reason, "no such host") + } else { + require.Empty(t, repo.tempUnschedCalls) + } + }) + } + } + } +} + +func TestTempUnscheduleOpenAITransportError_DisabledPreservesExistingState(t *testing.T) { + for _, paused := range []bool{false, true} { + t.Run(fmt.Sprintf("paused=%t", paused), func(t *testing.T) { + repo := &openaiTransportAccountRepoStub{} + svc := &OpenAIGatewayService{accountRepo: repo, cfg: &config.Config{}} + account := &Account{ID: 8541, Platform: PlatformOpenAI, Status: StatusActive, Schedulable: !paused} + svc.tempUnscheduleOpenAITransportError(context.Background(), account, "previous failure") + require.Len(t, repo.tempUnschedCalls, 1) + previousCall := repo.tempUnschedCalls[0] + persistedUntil := previousCall.until + account.TempUnschedulableUntil = &persistedUntil + account.TempUnschedulableReason = previousCall.reason + previousAccount := *account + previousBlock, exists := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) + require.True(t, exists) + previousGeneration, _ := svc.openaiAccountRuntimeBlockGeneration.Load(account.ID) + + svc.cfg.Gateway.DisableOpenAITransportErrorCooldown = true + svc.tempUnscheduleOpenAITransportError(context.Background(), account, "new failure") + + require.Equal(t, []tempUnschedCall{previousCall}, repo.tempUnschedCalls) + require.Equal(t, previousAccount, *account) + require.Equal(t, previousCall.until, *account.TempUnschedulableUntil) + currentBlock, exists := svc.openaiAccountRuntimeBlockUntil.Load(account.ID) + require.True(t, exists) + require.Equal(t, previousBlock, currentBlock) + currentGeneration, _ := svc.openaiAccountRuntimeBlockGeneration.Load(account.ID) + require.Equal(t, previousGeneration, currentGeneration) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + type failingOpenAIHTTPUpstream struct { err error calls int 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_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/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..9a54f3212c --- /dev/null +++ b/backend/internal/service/sse_transport_limits.go @@ -0,0 +1,196 @@ +package service + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "sync/atomic" + "unsafe" + + "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 + } +} + +// ReadLineString is ReadLine for callers that keep the line as a string. +// ReadLine returns a fresh allocation that nothing else retains, so the line is +// handed over without a second copy. +func (r *boundedSSELineReader) ReadLineString() (string, error) { + line, err := r.ReadLine() + return unsafe.String(unsafe.SliceData(line), len(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/user.go b/backend/internal/service/user.go index 7f19550fa8..eabe824073 100644 --- a/backend/internal/service/user.go +++ b/backend/internal/service/user.go @@ -63,6 +63,9 @@ type User struct { // nil = 该 API Key 对应的 (user, group) 无 override;非 nil 时 checkRPM 直接使用, // 避免每请求查 DB。字段不持久化到数据库。 UserGroupRPMOverride *int + // UserGroupRPMOverrideGroupID 是 snapshot 已成功查询 override 的分组 ID(0 = 未知)。 + // 等于当前分组且 UserGroupRPMOverride 为 nil 时表示确认无 override,checkRPM 不再查 DB。 + UserGroupRPMOverrideGroupID int64 APIKeys []APIKey Subscriptions []UserSubscription diff --git a/deploy/.env.example b/deploy/.env.example index 0e8ce5304e..d9d1beb337 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -307,6 +307,11 @@ GATEWAY_OPENAI_COMPACT_MODEL=gpt-5.5 SUB2API_IMAGES_MAIN_MODEL=gpt-5.6-luna # OpenAI/Codex 等待上游响应头超时(秒);0 表示不使用本地响应头超时截断。 GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=0 +# Disable only the fixed 10-minute account cooldown for persistent OpenAI DNS/proxy/network failures. +# YAML: gateway.disable_openai_transport_error_cooldown; false preserves the default protection. +# Ops/errors and bounded failover remain; other cooldowns, existing state and admin pauses are unchanged. +# Later requests retry broken shared egress; this is not a DNS/proxy repair or a model speed guarantee. +GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=false # 全局强制 OpenAI Responses 上游使用 HTTP/SSE,不使用 WebSocket。 # 当代理或网络导致上游 WebSocket 反复重连时可设为 true;这不会禁用 HTTP/2。 # 如需回退 HTTP/1.1,请另行设置 GATEWAY_OPENAI_HTTP2_ENABLED=false。 diff --git a/deploy/EDGE_SECURITY.md b/deploy/EDGE_SECURITY.md index 418b974a1a..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 @@ -11,15 +11,54 @@ terminate healthy long generations and streams. - `server.read_header_timeout: 10` bounds slow-header attacks. It does not limit request processing or response streaming. - `server.max_request_body_size: 268435456` is the absolute 256 MiB safety net. -- `server.request_body_idle_timeout: 60` fails a request body read with 408 - when no body bytes arrive for 60 seconds. It does not limit the total upload - time, so large bodies that keep arriving are unaffected; `0` disables it. It - also bounds the drain net/http performs on an unread HTTP/1 body before - sending an early error response. - `gateway.max_body_size: 268435456` remains available to multimodal, Gemini, 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 @@ -27,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 a400bb1be4..557ca32b5f 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -50,11 +50,6 @@ server: # Applies to all requests, especially important for h2c first request memory protection # 适用于所有请求,对 h2c 第一请求的内存保护尤为重要 max_request_body_size: 268435456 - # Fail a request body read when no body bytes arrive for this many seconds (408). - # Does not limit total upload time: large bodies that keep arriving are unaffected. 0 disables. - # 请求体读取空闲超时(秒):持续这么久没有收到任何请求体数据即失败(408)。 - # 不限制总上传时长,持续有数据到达的大请求体不受影响;0 表示关闭。 - request_body_idle_timeout: 60 # HTTP/2 Cleartext (h2c) configuration # HTTP/2 Cleartext (h2c) 配置 h2c: @@ -244,6 +239,12 @@ gateway: # OpenAI/Codex upstream response header timeout (seconds, 0=disabled) # OpenAI/Codex 等待上游响应头超时时间(秒,0=禁用本地响应头超时) openai_response_header_timeout: 0 + # Opt out of the fixed 10-minute account cooldown for persistent OpenAI transport failures (DNS/proxy/network). + # Env: GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=true; default false retains protection. + # Errors/Ops and bounded request failover remain; HTTP 401/403/429, quota/model limits, + # stream timeouts and token-refresh cooldowns are unchanged. Existing cooldowns and admin pauses are not cleared. + # With shared egress still broken, later requests retry it: this does not repair DNS/proxies or guarantee faster models. + disable_openai_transport_error_cooldown: false # Grok text Responses first-byte timeout (seconds, 0=disabled; default 120) # Grok 文本 Responses 首字节超时时间(秒,0=禁用;默认 120) grok_response_header_timeout: 120 @@ -259,6 +260,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 @@ -544,9 +554,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 54953ba2f8..fd13301f69 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -62,6 +62,7 @@ services: - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} + - GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=${GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN:-false} - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false} - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true} - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true} diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index 6ca816a548..ea2827da5a 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -170,6 +170,7 @@ services: - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} + - GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=${GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN:-false} - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false} - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true} - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true} diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index 6711bcbdb4..0c544bd9ca 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -117,6 +117,7 @@ services: - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} + - GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=${GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN:-false} - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false} - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true} - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true} diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index 51e3cb5ded..4d94afb1ab 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -167,6 +167,7 @@ services: - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} + - GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN=${GATEWAY_DISABLE_OPENAI_TRANSPORT_ERROR_COOLDOWN:-false} - GATEWAY_OPENAI_WS_FORCE_HTTP=${GATEWAY_OPENAI_WS_FORCE_HTTP:-false} - GATEWAY_OPENAI_HTTP2_ENABLED=${GATEWAY_OPENAI_HTTP2_ENABLED:-true} - GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1=${GATEWAY_OPENAI_HTTP2_ALLOW_PROXY_FALLBACK_TO_HTTP1:-true} 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/moego-json-batching.md b/docs/moego-json-batching.md new file mode 100644 index 0000000000..9485a167b4 --- /dev/null +++ b/docs/moego-json-batching.md @@ -0,0 +1,150 @@ +# OpenAI 请求的 JSON 批量编辑 + +`openAIRequestView.ApplyPatches` 使用 `github.com/MoeForge/moego/ojson` 的 +`Doc` 合并同一请求上的多次字段修改,最后只生成一次完整结果。依赖固定为 +`v0.1.0-alpha.1`(`d016502783037edc58e422331be2b6775d578c13`)。 + +这项优化不替换其他 gjson/sjson 调用、encoding/json 解码、协议转换或用量提取。 +未知字段、顺序、重复键、数字拼写和未修改文本由字节级差分测试保护。 + +## 适用范围 + +批量路径只接受有效 JSON 对象、2–16 次标量修改、最多四级 ASCII 标识符路径。 +根对象及被修改路径经过的原始父对象最多各 64 个成员。大 input、图片 data URL +或其他未修改内容不因其大小或内部字段数量而被排除。 + +下列情况沿用已有的顺序 sjson 实现:单次编辑,查询/索引/非 ASCII 路径, +异常 JSON,字符串父节点,父子路径交叠,容器或自定义序列化值,以及密集对象。 +这些限制是优化资格判定,不增加请求拒绝规则。 + +限制对象成员数量很重要:Doc 会为经过的容器建立临时成员索引。一个约 40 KB、 +4096 个短字段的对象,在直接使用 Doc 的实验中会累计分配约 720 KB,原 sjson +约 82 KB。现在这种对象回到原实现,不再增加该索引。预检只借用原始输入, +不通过 `Doc.Get` 检查已经修改的父对象,避免其重新物化大型容器。 + +## 所有权和预算 + +- 输入 body 在调用期间不可修改;Doc 和预检结果不会跨调用保存。 +- `ApplyPatches` 的每种策略(批量 Doc、单次编辑、顺序 sjson)都产生一份独立 + 输出,统一计入预算:编辑前先按输入长度预留,预算不足时在任何编辑工作之前拒绝; + 生成后按实际输出长度多退少补,失败则全部退回。批量和非批量请求的拒绝条件相同。 +- Forward 为每次 patch 输出打开 `WithRequestBodyMemoryScope` 子额度。新输出取代 + 旧输出时归还旧额度,Forward 返回时归还最后一份,因此账号切换重试不会在 handler + 返回前累积改写后的 body。ingress 额度仍随 handler 的既有释放函数归还。 +- 该额度覆盖 patch 输出,不是整个进程堆的上限:顺序 sjson 的中间副本、 + decode+marshal 回退以及 Doc 成员索引不单独计入,后者通过上面的资格限制控制。 +- Doc 拒绝某次编辑时改用顺序 sjson;sjson 也无法表达时(例如在数组下设置键), + Forward 把待处理的 patch 重放到解码后的 map 上,走既有 marshal 回退,不会重复 + 执行同一批 patch。 +- 预算耗尽立即返回,不通过另一种序列化方式绕过预算,也不切换账号重试。 + 未提交 HTTP 响应时返回 503 和 `Retry-After: 1`;已有 SSE 心跳时发出 + `response.failed`,保留预期 503 的错误记录。 +- 调用方继续决定取消和上游用量排空策略;编辑函数没有新增提前取消语义。 + +## 兼容性边界 + +上游 alpha 在 Go 1.27.3 下的差分测试存在非法 UTF-8 路径键的输出字节差异: +实际 U+FFFD 和 `\ufffd` 解码后值相同,但字节不同。此类路径不进入本次批量路径。 +所有结构体/自定义值也保留原实现,避免改变自定义序列化的调用次数。 + +## 验证和基准 + +从 `backend` 运行: + +```sh +go test -race ./internal/service -run '^(TestOpenAIRequestPatches_|TestOpenAIRequestView_|TestOpenAIGatewayService_OAuthLegacy_UpstreamRequestIgnoresClientCancel)' -count=1 +go test -race ./internal/pkg/httputil -run 'Test(ReserveRequestBodyMemory|RequestBodyMemoryBudget)' -count=1 +go test -race ./internal/handler -run '^TestOpenAIForwardRequestBodyMemoryOverload' -count=1 +go test -race github.com/MoeForge/moego/ojson -run '^TestDoc' -count=1 +go test ./internal/service -run '^$' -bench '^BenchmarkOpenAIRequestPatches' -benchmem -benchtime=150ms -count=3 -cpu=1 +``` + +`SequentialSJSON` 保留原顺序实现作为基准和字节级 oracle。`ApplyPatches` 包含 +优化资格检查和完整 JSON 验证成本;两个基准均不包括 request view 构造。 +既有 `BenchmarkOpenAIResponses_LargeInputRawPatch` 则包含 view 构造。 + +基准报告的 B/op 是每次调用累计分配字节,不能当作驻留堆或 RSS,也不能直接推断 +整站吞吐、首 token 延迟或上游请求耗时。单次修改应保持相同分配;密集对象回退 +会有额外预检成本。ARM64 的当前 ojson 没有 AMD64 的 AVX2 路径,应单独测量。 + +### 2026-11-03 实测 + +Go 1.27.3,每组 150ms × 3,单 CPU,中位数。Linux 使用支持 AVX2 的 +Xeon Skylake,并固定 CPU;Mac 使用 Apple M2。六次修改包含模型、reasoning、 +删除 previous_response_id、输出上限及 service_tier,输入主体是长文本。 + +| 平台 / 输入 / 修改次数 | 原顺序实现 | 批量实现 | 原累计分配 | 新累计分配 | +|---|---:|---:|---:|---:| +| Linux AMD64 / 1 MiB / 6 | 3.816 ms | 0.756 ms | 6,341,302 B | 1,058,416 B | +| Linux AMD64 / 8 MiB / 6 | 23.162 ms | 5.353 ms | 50,381,747 B | 8,398,448 B | +| Mac ARM64 / 1 MiB / 6 | 2.446 ms | 1.263 ms | 6,341,291 B | 1,058,416 B | +| Mac ARM64 / 8 MiB / 6 | 12.023 ms | 9.290 ms | 50,381,720 B | 8,398,448 B | + +单次修改在两个平台保持相同累计分配。4096 字段的密集根对象回退后,Linux +耗时约 170 μs、累计分配 82,081 B,与原实现相当;密集嵌套对象预检增加约 6% +耗时,分配相同。三个重复嵌套叶节点修改在 Linux 上约快 2.1 倍;Mac 上约慢 8%, +但两个平台累计分配都从 3,171,120 B 降到 1,057,520 B。收益取决于输入与架构。 + +相关服务、handler、预算和上游 Doc 定向 race 测试通过;Linux AMD64 构建、 +`go vet` 通过。当前本机 golangci-lint 2.13.2 的导入器最多支持 export data v4, +无法读取 Go 1.27.3 的 v5,lint 未完成。`go mod tidy -diff` 仅提示清理项目已有的 +旧依赖校验和,本次仅加入 moego 所需校验和,没有混入这些无关清理。 + +## Messages 与 Responses 热点优化(2026-11-04) + +这批优化减少重复工作,保留现有解析器和兼容处理的语义: + +- `collectCacheControlPaths` 在同步扫描内借用 system/messages/tools 的原始视图, + 返回的路径和日志字符串仍拥有独立存储。断点数量限制和 TTL 顺序检查仍分两遍, + 保留重复键删除后露出下一个值的既有行为。 +- OAuth Responses 的 orphan 清理先检查是否可能需要修改。没有工具输出或存在 + 有效 `previous_response_id` 时跳过完整解码;重复相关键、转义键/类型及疑似工具 + 输出继续走原 decoder/sanitizer。预检复用已有字节范围扫描,不展开大段转义文本。 + 原先的首个 input 数组资格判断、末重复键解码和非法/尾随 JSON 错误保持不变。 +- `RequestBodyRef` 保存成功解析的只读快照,包含独立标量字符串、协议和字段偏移, + 不额外引用旧 body。未变化的 `CloneForBody`/`ReplaceBody` 恢复快照;显式 + `RequestBodyRef.Replace` 即使传入同一 slice 也会失效。每次重试仍创建独立 Ref, + 清空上游接受回调。手工构造、解析失败、协议或 body 改变均继续解析。 +- 复用除了要求 slice 起点和长度相同,还要求内容的 `maphash` 指纹与解析时一致。 + 指纹每次复用需要一遍哈希,远低于完整解析;它让违反只读约定的原地修改退回 + 重新解析,而不是恢复过期的模型、流式标记或字段偏移。 + +body 的输入与 `Bytes()` 结果均为只读借用;任何仍被请求或重试持有的底层存储都不应 +原地修改。快照的恢复也会覆盖临时改动过的派生标量,与原先重新解析的效果一致。 +快照增加少量固定元数据,不是新的跨请求缓存,没有后台生命周期或大 body 保留。 + +专用基准: + +```sh +go test ./internal/service -run '^$' -bench '^(BenchmarkCacheControlPathsLargeContent|BenchmarkOpenAIResponsesOrphanPrecheck|BenchmarkGatewayRequestBodyReuse)$' -benchmem -benchtime=150ms -count=3 -cpu=1 +``` + +`GatewayRequestBodyReuse` 从已经完成首次解析的请求开始,对比一次账号尝试的 clone +和两次未变化的刷新。`Reparse` 强制走完整解析,包含新增快照的固定成本,不能当作 +旧提交的精确分配基线;`Reuse` 不代表整个请求已不需要 JSON 解析。 +`OpenAIResponsesOrphanPrecheck` 仅比较 orphan 阶段;cache_control 的旧版基线可以 +通过 Go overlay 使用修改前的 `gateway_claude_oauth_body.go` 测量。 + +实测环境为 Go 1.27.3、Linux AMD64 Xeon Skylake,固定单核、150ms × 3,中位数: + +| 组件 / 合成输入 | 对照耗时 | 优化后耗时 | 对照累计分配 | 优化后累计分配 | +|---|---:|---:|---:|---:| +| cache_control 无需修改 / 1 MiB | 5.854 ms | 5.119 ms | 2,114,374 B | 476 B | +| cache_control 无需修改 / 8 MiB | 45.250 ms | 41.575 ms | 16,794,468 B | 476 B | +| Responses orphan / 4 MiB / 无 previous_response_id | 38.238 ms | 14.168 ms | 28,676,176 B | 10 B | +| Responses orphan / 4 MiB / 有 previous_response_id | 38.070 ms | 8.252 ms | 28,676,204 B | 6 B | +| Messages 三次后续解析 / 8 MiB / 强制解析与复用 | 63.068 ms | 0.000234 ms | 840 B | 240 B | + +cache_control 输入含固定三个断点和变长普通文本,主要收益是消除复制;两遍扫描仍在。 +Responses 输入含大段转义文本,无需修改,优化后各规模均为 0 allocs/op;少量 B/op +包含运行时摊销,不能把它解释为整个网关零分配。Messages 一行不包括首次解析, +也不包括实际执行兼容处理、网络传输或上游推理。这些结果不用于推断整站吞吐。 + +Messages 一行测量于加入内容指纹之前。加入指纹后每次复用需要一遍 `maphash`: +Apple M2 上 8 MiB 复用约 2.1 ms(强制解析约 60 ms),1 MiB 约 0.26 ms, +分配不变(240 B/op)。 + +服务层相关 unit/race 回归、handler 的取消/切换/预算回归、最终边界用例 race 复验、 +`go vet` 和 Linux 基准程序编译均通过。仓库 fuzz 执行 1,393 次通过;将当前源函数 +原样提取到临时模块后的 15 秒 isolated fuzz 执行 34,363 次通过。`golangci-lint` +仍受 Go 1.27.3 export data v5 与当前导入器仅支持 v4 的工具链兼容问题阻断。 diff --git a/frontend/package.json b/frontend/package.json index ef38431a73..e42bcb03f8 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -67,7 +67,7 @@ "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 a6f4b60425..1bf73beac9 100644 --- a/frontend/pnpm-lock.yaml +++ b/frontend/pnpm-lock.yaml @@ -10,7 +10,7 @@ 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: @@ -2566,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: '*' @@ -6563,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 @@ -7305,7 +7305,7 @@ snapshots: flatted@3.3.3: {} - follow-redirects@1.16.1: {} + follow-redirects@1.16.2: {} for-in@1.0.2: {} 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/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 @@