Merge upstream main; classify WithBodyReadTimeout failures

Upstream added WithBodyReadTimeout (gateway.request_body_read_timeout_seconds)
and client-gone handling for body reads. Drop this branch's own server-level
idle-timeout wrapper and server.request_body_idle_timeout setting in favor of
it, and keep the classification and diagnostics on top:

- readRequestBodyChunksWithBudget reports the read error before ctx.Err():
  on HTTP/1 a read deadline also cancels the request context, which turned
  every timeout into context.Canceled. Read errors carry bytes read and
  elapsed time in RequestBodyReadError.
- handleRequestBodyReadError and RejectRequestBodyReadError skip the
  client-gone (empty 499) path for read timeouts, so they are reported as
  408 instead of a client cancellation (HTTP/1) or a generic 400 (HTTP/2).
- Every gateway body read site and both body-reading middlewares log
  payload-free diagnostics, including the client-gone path.
This commit is contained in:
cyh committed 2026-11-07 01:52:36 +08:00
commit fdfadb2442
308 files changed
+17946 -1474

No files matched your search

+2
View File
@@ -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
+10 -10
View File
@@ -34,11 +34,11 @@ Please read the following carefully before using this project:
<details open>
<summary>Click to collapse</summary>
<p align="center"><a href="https://wandapi.ai/r/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-en-dark.svg"><img src="assets/partners/banners/wandapi-en.svg" alt="WandAPI" width="100%"></picture></a></p>
<p align="center"><a href="https://wandapi.com/go/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-en-dark.svg"><img src="assets/partners/banners/wandapi-en.svg" alt="WandAPI" width="100%"></picture></a></p>
**[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:
</tr>
<tr>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>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 <a href="https://api.aigocode.dev/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/logos/aigocode-dark.png"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></picture></a></td>
<td>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 <a href="https://api.aigocode.dev/invite/SUB2API">this link</a> to get an extra 10% credits!</td>
</tr>
<tr>
@@ -137,11 +137,6 @@ Please read the following carefully before using this project:
<td>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 — <a href="https://www.swiftproxy.net/?ref=sub2api">start your free test now</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
<td>Thanks to APIMart for sponsoring this project! <a href="https://go.apimart.ai/gh-sub2api">APIMart</a> 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 — <a href="https://go.apimart.ai/gh-sub2api">sign up here</a> to get started.</td>
</tr>
<tr>
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>Thanks to AxisNow for sponsoring this project! <a href="https://www.axisnow.io/">AxisNow</a> 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 — <strong>self-hosted private-deployment CDN</strong> | <strong>subscription-based DDoS-protected CDN</strong> | <strong>autonomous, flexibly composable CDN network</strong>.</td>
@@ -182,6 +177,11 @@ Please read the following carefully before using this project:
<td>Thanks to <a href="https://soleapi.com/r/sub2api">SoleAPI</a> 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 <a href="https://soleapi.com/r/sub2api">referral link</a> to receive free trial credits, and earn ongoing cashback by inviting friends who top up!</td>
</tr>
<tr>
<td width="180"><a href="https://api.muteki.site/register?aff=Sub2"><img src="assets/partners/logos/marucode.jpg" alt="MaruCode" width="150"></a></td>
<td><a href="https://api.muteki.site/register?aff=Sub2">MaruCode</a> — 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).</td>
</tr>
</table>
</details>
+10 -10
View File
@@ -35,11 +35,11 @@
<details open>
<summary>点击折叠</summary>
<p align="center"><a href="https://wandapi.ai/r/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-cn-dark.svg"><img src="assets/partners/banners/wandapi-cn.svg" alt="WandAPI" width="100%"></picture></a></p>
<p align="center"><a href="https://wandapi.com/go/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-cn-dark.svg"><img src="assets/partners/banners/wandapi-cn.svg" alt="WandAPI" width="100%"></picture></a></p>
**[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 @@
</tr>
<tr>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过<a href="https://api.aigocode.dev/invite/SUB2API">此链接</a>注册,首次充值可额外获得 10% 赠送额度!</td>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/logos/aigocode-dark.png"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></picture></a></td>
<td>感谢 AIGoCode 赞助了本项目!订阅制 AI 编程平台,不只按token 算钱。一个账号包月畅用 Claude Code、Codex、Gemini,国内直连、响应快。通过<a href="https://api.aigocode.dev/invite/SUB2API">此链接</a>订阅额外送 10% 额度!</td>
</tr>
<tr>
@@ -140,11 +140,6 @@
<td>Swiftproxy 是面向开发者的高性能代理解决方案,提供稳定可靠的住宅代理和静态住宅代理服务。拥有 9000 万+ 纯净住宅 IP,覆盖全球,支持灵活轮换和精准地理定位,帮助网页抓取、AI 自动化、浏览器自动化、SEO 监控和多账号管理等项目突破访问限制,提升工作流效率。支持 HTTP(S) 和 SOCKS5 协议,兼容 Playwright、Selenium、Puppeteer 等主流自动化工具,动态代理流量用完为止永不过期,支持免费测试 — <a href="https://www.swiftproxy.net/?ref=sub2api">立即开始免费测试</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
<td>感谢 APIMart 赞助了本项目!<a href="https://go.apimart.ai/gh-sub2api">APIMart</a> 是专注于 AI 图片/视频生成的低价 API 平台,GPT-Image-2 低至 $0.006/张,1 美元可生成 160+ 张图片。图片、视频一套异步 API 通吃:提交任务获取 ID,通过轮询或回调获取结果;批量生成上万张图片也不会超时,切换模型无需修改代码。按量付费、无月费,通过<a href="https://go.apimart.ai/gh-sub2api">此注册链接</a>注册即可开始使用。</td>
</tr>
<tr>
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>感谢 AxisNow 赞助了本项目!<a href="https://www.axisnow.io/">AxisNow</a> 保护并加速网站与 API,兼顾中国大陆及全球的访问体验,并通过客户端 SDK,将加速与安全能力延伸至原生/移动 App — <strong>自建私有部署 CDN</strong>|<strong>订阅式高防 CDN</strong>|<strong>自主可控、灵活组合的 CDN 网络</strong>。</td>
@@ -185,6 +180,11 @@
<td>感谢 <a href="https://soleapi.com/r/sub2api">SoleAPI</a> 对本项目的支持!SoleAPI 是面向开发者与企业的 AI 模型网关:一个 API Key 即可调用 Claude、GPT、Gemini 等 30+ 主流模型。原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex、Cursor 及现有 SDK 只需修改 Base URL 即可接入。请求按延迟与上游健康度实时路由,毫秒级自动切换至备用通道,服务可用性达 99.99%,并提供 7×24 小时技术支持。所有调用统一账单结算,每次请求的 token 与费用明细随时可查。通过本项目的<a href="https://soleapi.com/r/sub2api">推荐链接</a>注册即可获得免费试用额度,邀请好友充值还可持续获得返现!</td>
</tr>
<tr>
<td width="180"><a href="https://api.muteki.site/register?aff=Sub2"><img src="assets/partners/logos/marucode.jpg" alt="MaruCode" width="150"></a></td>
<td><a href="https://api.muteki.site/register?aff=Sub2">MaruCode</a> ——偶尔做做慈善的小破站 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)</td>
</tr>
</table>
</details>
+5 -10
View File
@@ -34,11 +34,11 @@
<details open>
<summary>クリックで折りたたむ</summary>
<p align="center"><a href="https://wandapi.ai/r/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-en-dark.svg"><img src="assets/partners/banners/wandapi-en.svg" alt="WandAPI" width="100%"></picture></a></p>
<p align="center"><a href="https://wandapi.com/go/sub2api"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/banners/wandapi-en-dark.svg"><img src="assets/partners/banners/wandapi-en.svg" alt="WandAPI" width="100%"></picture></a></p>
**[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 @@
</tr>
<tr>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
<td>AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:<a href="https://api.aigocode.dev/invite/SUB2API">こちらのリンク</a>から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!</td>
<td width="180"><a href="https://api.aigocode.dev/invite/SUB2API"><picture><source media="(prefers-color-scheme: dark)" srcset="assets/partners/logos/aigocode-dark.png"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></picture></a></td>
<td>AIGoCode のご支援に感謝します!トークン従量課金だけではない、サブスクリプション型の AI コーディングプラットフォームです。1 つのアカウント・月額プランで Claude Code、Codex、Gemini を使い放題。中国本土から直接接続でき、レスポンスも高速です。<a href="https://api.aigocode.dev/invite/SUB2API">こちらのリンク</a>から購読すると、10% の追加クレジットをプレゼント!</td>
</tr>
<tr>
@@ -139,11 +139,6 @@
<td>Swiftproxy は開発者向けの高性能プロキシソリューションで、安定して信頼できるレジデンシャルおよび静的レジデンシャルプロキシサービスを提供します。9,000 万以上のクリーンな住宅 IP を保有し、グローバルカバレッジ、柔軟なローテーション、精密なジオターゲティングにより、Web スクレイピング、AI オートメーション、ブラウザ自動化、SEO モニタリング、マルチアカウント管理などのプロジェクトがアクセス制限を克服し、ワークフロー効率を向上させます。HTTP(S) および SOCKS5 プロトコルに対応し、Playwright、Selenium、Puppeteer などの主要な自動化ツールと統合可能。動的プロキシトラフィックは使い切るまで期限切れなし、無料テストも利用可能 — <a href="https://www.swiftproxy.net/?ref=sub2api">今すぐ無料テストを開始</a>!</td>
</tr>
<tr>
<td width="180"><a href="https://go.apimart.ai/gh-sub2api"><img src="assets/partners/logos/apimart.jpg" alt="APIMart" width="150"></a></td>
<td>APIMart のご支援に感謝します!<a href="https://go.apimart.ai/gh-sub2api">APIMart</a> は AI 画像・動画生成に特化した低価格 API プラットフォームです。GPT-Image-2 は 1 枚 $0.006 から、1 ドルで 160 枚以上の画像を生成できます。画像と動画の両方に対応する非同期 API を 1 つで利用でき、タスクを送信して ID を取得し、ポーリングまたはコールバックで結果を取得できます。数万枚規模のバッチ処理でもタイムアウトせず、モデルを変更してもコードの変更は不要です。月額料金なしの従量課金制で、<a href="https://go.apimart.ai/gh-sub2api">こちらの登録リンク</a>からすぐに利用を開始できます。</td>
</tr>
<tr>
<td width="180"><a href="https://www.axisnow.io/"><img src="assets/partners/logos/axisnow.jpg" alt="AxisNow" width="150"></a></td>
<td>AxisNow のご支援に感謝します!<a href="https://www.axisnow.io/">AxisNow</a> はウェブサイトと API を保護・高速化し、中国本土および世界中で快適なアクセス体験を実現します。クライアント SDK により、ネイティブ/モバイルアプリにも高速化・セキュリティ機能を拡張できます — <strong>自社構築・プライベートデプロイ CDN</strong>|<strong>サブスクリプション型高防御 CDN</strong>|<strong>自律制御で柔軟に組み合わせられる CDN ネットワーク</strong>。</td>
Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

+14
View File
@@ -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()
+15 -1
View File
@@ -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()
+2
View File
@@ -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,
+3 -2
View File
@@ -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
+6 -4
View File
@@ -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=
+41 -17
View File
@@ -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")
}
+16 -11
View File
@@ -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 },
@@ -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)
})
}
}
@@ -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
}
@@ -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
}
@@ -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)}) {
@@ -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) {
@@ -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) {
@@ -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}
}
@@ -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)
}
@@ -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}
}
@@ -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")
}
}
@@ -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
}
@@ -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
}
@@ -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")
}
@@ -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)
}
@@ -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"))
@@ -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) {
@@ -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`)
}
@@ -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)
@@ -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)
}
@@ -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,
})
}
@@ -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))
@@ -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)
@@ -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"`
}
@@ -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]))
@@ -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,
})
}
@@ -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
@@ -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})
}
+10 -2
View File
@@ -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
@@ -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),
@@ -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),
@@ -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"),
@@ -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
}
@@ -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"),
+7 -3
View File
@@ -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.
@@ -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")
})
}
}
+5 -1
View File
@@ -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,
+28 -8
View File
@@ -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 {
@@ -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) {
@@ -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"),
@@ -207,3 +207,30 @@ Read the reference index and report changes. Preserve A &amp; B and &lt;tags&gt;
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)
})
}
}
@@ -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 {
@@ -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))
@@ -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(
@@ -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
@@ -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
@@ -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()
}
}
+11 -2
View File
@@ -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"),
@@ -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])
}
@@ -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"))
}
}
+1 -2
View File
@@ -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 {
@@ -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 {
@@ -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 {
@@ -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")
})
}
}
@@ -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
}
@@ -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 {
@@ -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
})
}
}
}
@@ -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")
}
})
}
}
+19 -1
View File
@@ -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
@@ -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("旧策略不得继承新增权限")
}
}
@@ -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)
}
}
}
}
@@ -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)
}
}
}
@@ -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)) {
@@ -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
@@ -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
@@ -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
@@ -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{
@@ -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] = &copyCall
@@ -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);
@@ -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",
@@ -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,
@@ -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)
}
}
})
}
}
@@ -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
}
+150 -49
View File
@@ -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 {
@@ -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
}
@@ -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()
}
}
@@ -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
@@ -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)
}
@@ -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)
}
}
@@ -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()
}
}
@@ -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()
}
@@ -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)
}
@@ -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)
}
+1 -1
View File
@@ -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)
@@ -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)
@@ -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 必须进入认证投影")
}
@@ -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)
}
Loaded 100 of 308 files, more files were not shown because too many files have changed in this diff. Show more