Merge main and resolve Codex export model default

This commit is contained in:
danvilig committed 2026-11-05 16:19:22 +00:00
commit 7f07bca99b
359 files changed
+22344 -826

No files matched your search

+1 -1
View File
@@ -54,7 +54,7 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '24'
cache: 'pnpm'
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Install frontend dependencies
+1 -1
View File
@@ -92,7 +92,7 @@ jobs:
version: 9
- uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '24'
cache: pnpm
cache-dependency-path: frontend/pnpm-lock.yaml
- run: pnpm install --frozen-lockfile
+1 -1
View File
@@ -41,7 +41,7 @@ jobs:
- name: Set up Node.js
uses: actions/setup-node@v6
with:
node-version: '20'
node-version: '24'
cache: 'pnpm'
cache-dependency-path: frontend/pnpm-lock.yaml
- name: Install dependencies
+2
View File
@@ -133,7 +133,9 @@ deploy/docker-compose.override.yml
.gocache/
vite.config.js
docs/*
!docs/agent-resource-safety.md
!docs/admin-api-keys.md
!docs/mcp.md
!docs/PAYMENT.md
!docs/PAYMENT_CN.md
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
+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

+1 -1
View File
@@ -1 +1 @@
0.2.18
0.2.19
+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()
+21 -4
View File
@@ -49,10 +49,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
redeemCodeRepository := repository.NewRedeemCodeRepository(client)
redisClient := repository.ProvideRedis(configConfig)
refreshTokenCache := repository.NewRefreshTokenCache(redisClient)
scopedAdminKeyRepository := repository.NewScopedAdminKeyRepository(db)
settingRepository := repository.NewSettingRepository(client)
groupRepository := repository.NewGroupRepository(client, db)
proxyRepository := repository.NewProxyRepository(client, db)
scopedAdminKeyRepository := repository.NewScopedAdminKeyRepository(db)
settingService := service.ProvideSettingService(scopedAdminKeyRepository, settingRepository, groupRepository, proxyRepository, configConfig)
emailCache := repository.NewEmailCache(redisClient)
emailService := service.NewEmailService(settingRepository, emailCache)
@@ -83,7 +83,9 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService, client, configConfig)
affiliateRepository := repository.NewAffiliateRepository(client, db)
affiliateService := service.NewAffiliateService(affiliateRepository, settingService, apiKeyAuthCacheInvalidator, billingCacheService)
authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository)
mcpoAuthRepository := repository.NewMCPOAuthRepository(client, db)
mcpoAuthService := service.NewMCPOAuthService(mcpoAuthRepository, userRepository)
authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository, mcpoAuthService)
userService := service.NewUserService(userRepository, settingRepository, apiKeyAuthCacheInvalidator, billingCache)
redeemCache := repository.NewRedeemCache(redisClient)
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator, affiliateService)
@@ -98,6 +100,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService, promoService, redeemService, totpService, userAttributeService)
userHandler := handler.NewUserHandler(userService, authService, emailService, emailCache, affiliateService, serviceUserPlatformQuotaRepository)
mcpoAuthHandler := handler.NewMCPOAuthHandler(mcpoAuthService, totpService, userService, settingService, configConfig)
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
usageLogRepository := repository.NewUsageLogRepository(client, db)
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
@@ -328,7 +331,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler)
idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig)
openAIQuotaAutoResetService := service.ProvideOpenAIQuotaAutoResetService(accountRepository, openAIQuotaService, rateLimitService, idempotencyCoordinator, auditLogService, settingService, leaderLockCache)
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService)
handlers := handler.ProvideHandlers(authHandler, userHandler, mcpoAuthHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, channelMonitorV2Handler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService, openAIQuotaAutoResetService)
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService)
optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService)
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService)
@@ -356,7 +359,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService, channelMonitorQuotaFetcher)
channelMonitorV2Aggregator := service.ProvideChannelMonitorV2Aggregator(channelMonitorV2Repository, db, settingService)
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, cnProviderBalanceCheckService, openAICodexVersionSyncService, claudeCodeVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, geminiCachedContentService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, balanceNotifyService, digestSessionStore, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, channelMonitorV2Aggregator, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, openCodeGoUsageService, auditLogService, openAIQuotaAutoResetService, promptService, pluginManager)
application := &Application{
Server: httpServer,
PromptAudit: promptService,
@@ -423,6 +426,8 @@ func provideCleanup(
emailQueue *service.EmailQueueService,
billingCache *service.BillingCacheService,
usageRecordWorkerPool *service.UsageRecordWorkerPool,
balanceNotify *service.BalanceNotifyService,
digestSessions *service.DigestSessionStore,
subscriptionService *service.SubscriptionService,
oauth *service.OAuthService,
openaiOAuth *service.OpenAIOAuthService,
@@ -454,6 +459,18 @@ func provideCleanup(
}
parallelSteps := []cleanupStep{
{"DigestSessionStore", func() error {
if digestSessions != nil {
digestSessions.Close()
}
return nil
}},
{"BalanceNotifyService", func() error {
if balanceNotify != nil {
balanceNotify.Stop()
}
return nil
}},
{"PluginManager", func() error {
if pluginManager != nil {
pluginManager.Stop()
+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,
+13 -7
View File
@@ -30,6 +30,7 @@ require (
github.com/imroc/req/v3 v3.59.0
github.com/klauspost/compress v1.18.2
github.com/lib/pq v1.10.9
github.com/modelcontextprotocol/go-sdk v1.4.1
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pquerna/otp v1.5.0
github.com/redis/go-redis/v9 v9.22.0
@@ -51,12 +52,12 @@ require (
github.com/wechatpay-apiv3/wechatpay-go v0.2.21
github.com/zeromicro/go-zero v1.9.4
go.uber.org/zap v1.24.0
golang.org/x/crypto v0.57.0
golang.org/x/crypto v0.58.0
golang.org/x/image v0.41.0
golang.org/x/mod v0.41.0
golang.org/x/net v0.60.0
golang.org/x/sync v0.23.0
golang.org/x/term v0.46.0
golang.org/x/net v0.62.0
golang.org/x/sync v0.24.0
golang.org/x/term v0.47.0
google.golang.org/grpc v1.83.2
google.golang.org/protobuf v1.36.11
gopkg.in/natefinch/lumberjack.v2 v2.2.1
@@ -128,6 +129,7 @@ require (
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/google/jsonschema-go v0.4.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.3 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hashicorp/hcl/v2 v2.18.1 // indirect
@@ -167,6 +169,8 @@ require (
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/smartwalle/ncrypto v1.0.4 // indirect
github.com/smartwalle/ngx v1.1.0 // indirect
@@ -187,6 +191,7 @@ require (
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
github.com/zclconf/go-cty v1.14.4 // indirect
@@ -201,10 +206,11 @@ require (
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.3.0 // indirect
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/time v0.12.0 // indirect
golang.org/x/tools v0.50.0 // indirect
golang.org/x/tools v0.51.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
modernc.org/libc v1.67.6 // indirect
+26 -32
View File
@@ -251,6 +251,8 @@ github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -349,6 +351,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
github.com/modelcontextprotocol/go-sdk v1.4.1 h1:M4x9GyIPj+HoIlHNGpK2hq5o3BFhC+78PkEaldQRphc=
github.com/modelcontextprotocol/go-sdk v1.4.1/go.mod h1:Bo/mS87hPQqHSRkMv4dQq1XCu6zv4INdXnFZabkNU6s=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -405,6 +409,10 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
github.com/shirou/gopsutil/v4 v4.25.6 h1:kLysI2JsKorfaFPcYmcJqbzROzsBWEOAtw6A7dIfqXs=
@@ -498,6 +506,8 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.1.30/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
@@ -562,10 +572,8 @@ golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDf
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.24.0/go.mod h1:Z1PMYSOR5nyMcyAVAIQSKCDwalqy85Aqn1x3Ws4L5DM=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
@@ -580,8 +588,6 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -605,11 +611,11 @@ golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=
golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -620,10 +626,8 @@ golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -655,10 +659,8 @@ golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -671,10 +673,8 @@ golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.21.0/go.mod h1:ooXLefLobQVslOqselCNF4SxFAaoS6KujMbsGzSDmX0=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
@@ -685,10 +685,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE=
golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -703,12 +701,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+89 -1
View File
@@ -7,9 +7,11 @@ import (
"fmt"
"log/slog"
"math"
"net/netip"
"net/textproto"
"net/url"
"os"
"strconv"
"strings"
"sync/atomic"
"time"
@@ -69,6 +71,7 @@ type Config struct {
Server ServerConfig `mapstructure:"server"`
Log LogConfig `mapstructure:"log"`
CORS CORSConfig `mapstructure:"cors"`
MCP MCPConfig `mapstructure:"mcp"`
Security SecurityConfig `mapstructure:"security"`
Billing BillingConfig `mapstructure:"billing"`
Turnstile TurnstileConfig `mapstructure:"turnstile"`
@@ -116,6 +119,54 @@ type SimpleModeConfig struct {
AutoCreateDefaultGroups bool `mapstructure:"auto_create_default_groups" yaml:"auto_create_default_groups"`
}
// MCPConfig fixes the public resource URL used by OAuth discovery and tokens.
// Setting it is also the explicit opt-in that enables MCP.
type MCPConfig struct {
PublicURL string `mapstructure:"public_url"`
}
// Enabled reports whether the operator opted in to the management MCP endpoint.
func (c MCPConfig) Enabled() bool { return strings.TrimSpace(c.PublicURL) != "" }
// Validate normalizes the configured resource URL without trusting request headers.
// An empty URL keeps MCP and its OAuth endpoints disabled.
func (c *MCPConfig) Validate() error {
raw := strings.TrimSpace(c.PublicURL)
if raw == "" {
c.PublicURL = ""
return nil
}
u, err := url.Parse(raw)
if err != nil {
return fmt.Errorf("mcp.public_url invalid: %w", err)
}
if !u.IsAbs() || u.Hostname() == "" || !httpguts.ValidHostHeader(u.Host) || strings.ContainsAny(u.Host, "*%") {
return fmt.Errorf("mcp.public_url must be an absolute URL with a valid host")
}
if u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.Contains(raw, "#") {
return fmt.Errorf("mcp.public_url must not include userinfo, query, or fragment")
}
if u.Path != "/api/v1/mcp" || u.EscapedPath() != "/api/v1/mcp" {
return fmt.Errorf("mcp.public_url must have the exact path /api/v1/mcp without a trailing slash")
}
if port := u.Port(); port != "" {
n, err := strconv.Atoi(port)
if err != nil || n < 1 || n > 65535 {
return fmt.Errorf("mcp.public_url must have a valid port")
}
}
u.Scheme = strings.ToLower(u.Scheme)
u.Host = strings.ToLower(u.Host)
host := u.Hostname()
addr, _ := netip.ParseAddr(host)
localDevelopment := host == "localhost" || addr.IsLoopback()
if u.Scheme != "https" && (u.Scheme != "http" || !localDevelopment) {
return fmt.Errorf("mcp.public_url must use HTTPS (HTTP is allowed only for localhost or loopback IPs)")
}
c.PublicURL = u.String()
return nil
}
// PluginConfig 控制管理员手动上传的本地进程插件。
// 默认不包含插件,也不允许安装未签名插件;TrustedPublishers 用于追加第三方发布者。
type PluginConfig struct {
@@ -998,6 +1049,12 @@ type GatewayConfig struct {
OpenAIHighEffortFirstOutputTimeoutSeconds int `mapstructure:"openai_high_effort_first_output_timeout_seconds"`
// 请求体最大字节数,用于网关请求体大小限制
MaxBodySize int64 `mapstructure:"max_body_size"`
// RequestBodyMemoryBudgetBytes bounds buffered ingress allocations per instance; 0 disables it.
RequestBodyMemoryBudgetBytes int64 `mapstructure:"request_body_memory_budget_bytes"`
// RequestBodyReadTimeoutSeconds bounds each socket read during upload; 0 disables it.
RequestBodyReadTimeoutSeconds int `mapstructure:"request_body_read_timeout_seconds"`
// DownstreamWriteTimeoutSeconds bounds each HTTP write/flush, not the lifetime of a stream.
DownstreamWriteTimeoutSeconds int `mapstructure:"downstream_write_timeout_seconds"`
// TextMaxBodySize limits endpoints that cannot carry inline image/video payloads.
TextMaxBodySize int64 `mapstructure:"text_max_body_size"`
// 非流式上游响应体读取上限(字节),用于防止无界读取导致内存放大
@@ -1092,7 +1149,10 @@ type GatewayConfig struct {
// ImageNonstreamKeepaliveInterval: 图片非流式 JSON keepalive 间隔(秒),0表示禁用
ImageNonstreamKeepaliveInterval int `mapstructure:"image_nonstream_keepalive_interval"`
// MaxLineSize: 上游 SSE 单行最大字节数(0使用默认值)
MaxLineSize int `mapstructure:"max_line_size"`
MaxLineSize int `mapstructure:"max_line_size"`
SSEQueueMaxBytes int64 `mapstructure:"sse_queue_max_bytes"`
SSEEventMaxBytes int64 `mapstructure:"sse_event_max_bytes"`
SSEEventMaxLines int `mapstructure:"sse_event_max_lines"`
// 是否记录上游错误响应体摘要(避免输出请求内容)
LogUpstreamErrorBody bool `mapstructure:"log_upstream_error_body"`
@@ -1109,6 +1169,8 @@ type GatewayConfig struct {
MaxAccountSwitches int `mapstructure:"max_account_switches"`
// Gemini 账户切换最大次数(Gemini 平台单独配置,因 API 限制更严格)
MaxAccountSwitchesGemini int `mapstructure:"max_account_switches_gemini"`
// Gemini 同账号重试次数(429/5xx 等可重试错误在换号前对同一账号的重发次数,不含首次请求)
MaxSameAccountRetriesGemini int `mapstructure:"max_same_account_retries_gemini"`
// Antigravity 429 fallback 限流时间(分钟),解析重置时间失败时使用
AntigravityFallbackCooldownMinutes int `mapstructure:"antigravity_fallback_cooldown_minutes"`
@@ -2082,6 +2144,7 @@ func setDefaults() {
// CORS
viper.SetDefault("cors.allowed_origins", []string{})
viper.SetDefault("cors.allow_credentials", true)
viper.SetDefault("mcp.public_url", "")
// WebAuthn / Passkeys are opt-in because every deployment must explicitly
// declare its relying-party domain and trusted browser origins.
@@ -2434,6 +2497,7 @@ func setDefaults() {
viper.SetDefault("gateway.failover_on_400", false)
viper.SetDefault("gateway.max_account_switches", 10)
viper.SetDefault("gateway.max_account_switches_gemini", 3)
viper.SetDefault("gateway.max_same_account_retries_gemini", 4)
viper.SetDefault("gateway.force_codex_cli", false)
viper.SetDefault("gateway.disable_codex_identity_enforcement", false)
viper.SetDefault("gateway.disable_codex_originator_normalization", false)
@@ -2529,6 +2593,9 @@ func setDefaults() {
viper.SetDefault("gateway.antigravity_fallback_cooldown_minutes", 1)
viper.SetDefault("gateway.antigravity_extra_retries", 10)
viper.SetDefault("gateway.max_body_size", int64(256*1024*1024))
viper.SetDefault("gateway.request_body_memory_budget_bytes", int64(1024*1024*1024))
viper.SetDefault("gateway.request_body_read_timeout_seconds", 120)
viper.SetDefault("gateway.downstream_write_timeout_seconds", 120)
viper.SetDefault("gateway.text_max_body_size", int64(32*1024*1024))
viper.SetDefault("gateway.upstream_response_read_max_bytes", DefaultUpstreamResponseReadMaxBytes)
viper.SetDefault("gateway.models_list_read_max_bytes", DefaultModelsListReadMaxBytes)
@@ -2550,6 +2617,9 @@ func setDefaults() {
viper.SetDefault("gateway.image_stream_keepalive_interval", 10)
viper.SetDefault("gateway.image_nonstream_keepalive_interval", 0)
viper.SetDefault("gateway.max_line_size", 500*1024*1024)
viper.SetDefault("gateway.sse_queue_max_bytes", int64(8*1024*1024))
viper.SetDefault("gateway.sse_event_max_bytes", int64(0))
viper.SetDefault("gateway.sse_event_max_lines", 4096)
viper.SetDefault("gateway.scheduling.sticky_session_max_waiting", 3)
viper.SetDefault("gateway.scheduling.sticky_session_wait_timeout", 120*time.Second)
viper.SetDefault("gateway.scheduling.fallback_wait_timeout", 30*time.Second)
@@ -2856,6 +2926,9 @@ func (c *Config) Validate() error {
return fmt.Errorf("gemini.oauth.client_id and gemini.oauth.client_secret must be both set or both empty")
}
if err := c.MCP.Validate(); err != nil {
return err
}
if strings.TrimSpace(c.Server.FrontendURL) != "" {
if err := ValidateAbsoluteHTTPURL(c.Server.FrontendURL); err != nil {
return fmt.Errorf("server.frontend_url invalid: %w", err)
@@ -3350,6 +3423,18 @@ func (c *Config) Validate() error {
if c.Gateway.MaxBodySize <= 0 {
return fmt.Errorf("gateway.max_body_size must be positive")
}
if c.Gateway.RequestBodyMemoryBudgetBytes < 0 {
return fmt.Errorf("gateway.request_body_memory_budget_bytes must be non-negative")
}
if c.Gateway.RequestBodyReadTimeoutSeconds < 0 || c.Gateway.RequestBodyReadTimeoutSeconds > 3600 {
return fmt.Errorf("gateway.request_body_read_timeout_seconds must be between 0 and 3600")
}
if c.Gateway.DownstreamWriteTimeoutSeconds < 0 || c.Gateway.DownstreamWriteTimeoutSeconds > 3600 {
return fmt.Errorf("gateway.downstream_write_timeout_seconds must be between 0 and 3600")
}
if c.Gateway.SSEQueueMaxBytes < 0 || c.Gateway.SSEEventMaxBytes < 0 || c.Gateway.SSEEventMaxLines < 0 {
return fmt.Errorf("gateway.sse_queue_max_bytes, sse_event_max_bytes and sse_event_max_lines must be non-negative")
}
if c.Gateway.TextMaxBodySize <= 0 || c.Gateway.TextMaxBodySize > c.Gateway.MaxBodySize {
return fmt.Errorf("gateway.text_max_body_size must be positive and no greater than gateway.max_body_size")
}
@@ -3371,6 +3456,9 @@ func (c *Config) Validate() error {
if c.Gateway.GrokResponseHeaderTimeout < 0 || c.Gateway.GrokResponseHeaderTimeout > 1800 {
return fmt.Errorf("gateway.grok_response_header_timeout must be between 0-1800 seconds")
}
if c.Gateway.MaxSameAccountRetriesGemini < 0 || c.Gateway.MaxSameAccountRetriesGemini > 10 {
return fmt.Errorf("gateway.max_same_account_retries_gemini must be between 0-10")
}
if c.Gateway.OpenAIFirstOutputTimeoutSeconds < 0 || c.Gateway.OpenAIFirstOutputTimeoutSeconds > 600 ||
(c.Gateway.OpenAIFirstOutputTimeoutSeconds > 0 && c.Gateway.OpenAIFirstOutputTimeoutSeconds < 30) {
return fmt.Errorf("gateway.openai_first_output_timeout_seconds must be 0 or between 30-600 seconds")
+39
View File
@@ -46,6 +46,19 @@ func TestLoadMinOutputTokensFromEnv(t *testing.T) {
require.Equal(t, 16, cfg.Gateway.MinOutputTokens)
}
func TestLoadGeminiSameAccountRetries(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, 4, cfg.Gateway.MaxSameAccountRetriesGemini)
resetViperWithJWTSecret(t)
t.Setenv("GATEWAY_MAX_SAME_ACCOUNT_RETRIES_GEMINI", "0")
cfg, err = Load()
require.NoError(t, err)
require.Zero(t, cfg.Gateway.MaxSameAccountRetriesGemini)
}
func TestValidateMinOutputTokensMinimum(t *testing.T) {
resetViperWithJWTSecret(t)
cfg, err := Load()
@@ -131,6 +144,12 @@ func TestLoadHTTPIngressSafetyDefaults(t *testing.T) {
require.False(t, cfg.Server.TrustedProxiesConfigured)
require.True(t, cfg.TrustForwardedIPForAPIKeyACL())
require.Equal(t, int64(32*1024*1024), cfg.Gateway.TextMaxBodySize)
require.Equal(t, int64(1<<30), cfg.Gateway.RequestBodyMemoryBudgetBytes)
require.Equal(t, 120, cfg.Gateway.RequestBodyReadTimeoutSeconds)
require.Equal(t, 120, cfg.Gateway.DownstreamWriteTimeoutSeconds)
require.Equal(t, 500<<20, cfg.Gateway.MaxLineSize)
require.Equal(t, int64(8<<20), cfg.Gateway.SSEQueueMaxBytes)
require.Equal(t, 4096, cfg.Gateway.SSEEventMaxLines)
require.True(t, cfg.APIKeyAuth.InvalidAbuse.Enabled)
require.Equal(t, 120, cfg.APIKeyAuth.InvalidAbuse.Threshold)
require.Equal(t, 16384, cfg.APIKeyAuth.InvalidAbuse.Capacity)
@@ -1621,6 +1640,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate func(*Config)
wantErr string
}{
{
name: "negative ingress memory budget",
mutate: func(c *Config) { c.Gateway.RequestBodyMemoryBudgetBytes = -1 },
wantErr: "gateway.request_body_memory_budget_bytes",
},
{
name: "negative upload timeout",
mutate: func(c *Config) { c.Gateway.RequestBodyReadTimeoutSeconds = -1 },
wantErr: "gateway.request_body_read_timeout_seconds",
},
{
name: "server read header timeout",
mutate: func(c *Config) { c.Server.ReadHeaderTimeout = 0 },
@@ -1887,6 +1916,16 @@ func TestValidateConfigErrors(t *testing.T) {
mutate: func(c *Config) { c.Gateway.OpenAIResponseHeaderTimeout = -1 },
wantErr: "gateway.openai_response_header_timeout",
},
{
name: "gateway gemini same account retries negative",
mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = -1 },
wantErr: "gateway.max_same_account_retries_gemini",
},
{
name: "gateway gemini same account retries too large",
mutate: func(c *Config) { c.Gateway.MaxSameAccountRetriesGemini = 11 },
wantErr: "gateway.max_same_account_retries_gemini",
},
{
name: "gateway openai first output timeout below minimum",
mutate: func(c *Config) { c.Gateway.OpenAIFirstOutputTimeoutSeconds = 29 },
@@ -0,0 +1,64 @@
package config
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestMCPConfigValidatePublicURL(t *testing.T) {
for _, tc := range []struct {
name, value, want string
}{
{"unset", "", ""},
{"blank", " ", ""},
{"https", "https://api.example.com/api/v1/mcp", "https://api.example.com/api/v1/mcp"},
{"normalize", " HTTPS://API.Example.COM:8443/api/v1/mcp ", "https://api.example.com:8443/api/v1/mcp"},
{"localhost", "http://localhost:8080/api/v1/mcp", "http://localhost:8080/api/v1/mcp"},
{"loopback IPv4", "http://127.0.0.2:8080/api/v1/mcp", "http://127.0.0.2:8080/api/v1/mcp"},
{"loopback IPv6", "http://[::1]:8080/api/v1/mcp", "http://[::1]:8080/api/v1/mcp"},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := MCPConfig{PublicURL: tc.value}
require.NoError(t, cfg.Validate())
require.Equal(t, tc.want, cfg.PublicURL)
})
}
for _, value := range []string{
"/api/v1/mcp", "//example.com/api/v1/mcp", "https:///api/v1/mcp",
"https://:443/api/v1/mcp", "https://*.example.com/api/v1/mcp",
"http://example.com/api/v1/mcp", "http://localhost.example.com/api/v1/mcp",
"http://10.0.0.1/api/v1/mcp", "http://[::2]/api/v1/mcp",
"ftp://localhost/api/v1/mcp", "https://example.com/api/v1/mcp/",
"https://example.com/mcp", "https://example.com/api/v1/%6dcp",
"https://example.com/api/v1/mcp?", "https://example.com/api/v1/mcp?x=1",
"https://example.com/api/v1/mcp#", "https://example.com/api/v1/mcp#fragment",
"https://user:password@example.com/api/v1/mcp", "https://user@example.com/api/v1/mcp",
"https://example.com:0/api/v1/mcp", "https://example.com:65536/api/v1/mcp",
"https://example.com:invalid/api/v1/mcp", "http://[::1%25eth0]/api/v1/mcp",
} {
t.Run(value, func(t *testing.T) {
cfg := MCPConfig{PublicURL: value}
require.ErrorContains(t, cfg.Validate(), "mcp.public_url")
})
}
}
func TestLoadMCPPublicURLFromEnv(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("MCP_PUBLIC_URL", "HTTPS://MCP.Example.COM/api/v1/mcp")
cfg, err := Load()
require.NoError(t, err)
require.Equal(t, "https://mcp.example.com/api/v1/mcp", cfg.MCP.PublicURL)
cfg.MCP.PublicURL = "http://example.com/api/v1/mcp"
require.ErrorContains(t, cfg.Validate(), "mcp.public_url must use HTTPS")
}
func TestLoadMCPPublicURLDefault(t *testing.T) {
resetViperWithJWTSecret(t)
t.Setenv("MCP_PUBLIC_URL", "")
cfg, err := Load()
require.NoError(t, err)
require.Empty(t, cfg.MCP.PublicURL)
}
@@ -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
}
@@ -110,13 +110,13 @@ type auditLogClearRequest struct {
// 安全要求(与需求对齐):
// 1. 每次清空都必须现场验证 TOTP 码(不复用 step-up sudo 窗口)
// 2. 未启用 TOTP 的管理员不允许清空
// 3. admin API key(机器凭证)不允许清空
// 3. 机器凭证(admin API key、MCP OAuth 等非浏览器会话)不允许清空
// 4. 清空完成后同步写入一条留痕记录(操作者、IP、UA、删除行数)
func (h *AuditLogHandler) Clear(c *gin.Context) {
if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey {
if reason, machine := middleware.MachineCredentialReason(c); machine {
response.ErrorWithDetails(c, http.StatusForbidden,
"Admin API key cannot clear audit logs; a two-factor verified admin session is required",
"STEP_UP_ADMIN_API_KEY_FORBIDDEN", nil)
"Machine credentials cannot clear audit logs; a two-factor verified admin session is required",
reason, nil)
return
}
@@ -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,
})
}
@@ -396,13 +396,13 @@ type UpdateSettingsRequest struct {
// UpdateSettings 更新系统设置
// PUT /api/v1/admin/settings
// ensureActorTotpForStepUp 校验当前操作者具备开启 step-up 门控的条件:
// 必须是真人管理员会话(admin API key 无法完成 TOTP step-up,拒绝)且本人已启用 TOTP。
// 必须是真人管理员会话(admin API key、MCP OAuth 等机器凭证无法完成 TOTP step-up,拒绝)且本人已启用 TOTP。
// 校验失败时写入错误响应并返回 false。
func (h *SettingHandler) ensureActorTotpForStepUp(c *gin.Context) bool {
if c.GetString("auth_method") == service.AuditAuthMethodAdminAPIKey {
if reason, machine := middleware.MachineCredentialReason(c); machine {
response.ErrorWithDetails(c, http.StatusForbidden,
"Admin API key cannot enable step-up verification; use an admin session with TOTP enabled",
"STEP_UP_ADMIN_API_KEY_FORBIDDEN", nil)
"Machine credentials cannot enable step-up verification; use an admin session with TOTP enabled",
reason, nil)
return false
}
subject, ok := middleware.GetAuthSubjectFromContext(c)
@@ -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})
}
+1
View File
@@ -415,6 +415,7 @@ type PublicSettings struct {
GitHubOAuthEnabled bool `json:"github_oauth_enabled"`
GoogleOAuthEnabled bool `json:"google_oauth_enabled"`
BackendModeEnabled bool `json:"backend_mode_enabled"`
MCPEnabled bool `json:"mcp_enabled"`
PaymentEnabled bool `json:"payment_enabled"`
// PaymentBalanceDisabled mirrors the payment-config BALANCE_PAYMENT_DISABLED switch so the
// user shell can derive the site billing mode (recharge & subscription / recharge only /
+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, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -599,6 +602,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
forceCacheBilling := fs.ForceCacheBilling
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -616,7 +620,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
RequestPayloadHash: requestPayloadHash,
ForceCacheBilling: forceCacheBilling,
APIKeyService: h.apiKeyService,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.gateway.messages"),
@@ -962,6 +966,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
forceCacheBilling := fs.ForceCacheBilling
quotaPlatform := service.QuotaPlatform(c.Request.Context(), currentAPIKey)
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -979,7 +984,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
RequestPayloadHash: requestPayloadHash,
ForceCacheBilling: forceCacheBilling,
APIKeyService: h.apiKeyService,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.gateway.messages"),
@@ -2158,6 +2163,9 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) {
// 读取请求体
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -47,6 +47,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
// Read request body
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.chatCompletionsErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -333,6 +336,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -349,7 +353,7 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
RequestPayloadHash: requestPayloadHash,
APIKeyService: h.apiKeyService,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
reqLog.Error("gateway.cc.record_usage_failed",
zap.Int64("account_id", account.ID),
@@ -47,6 +47,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// Read request body
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.responsesErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -315,6 +318,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
stampForwardRequestedReasoningEffort(result, service.RequestedReasoningEffortFromContext(c.Request.Context()))
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -331,7 +335,7 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
RequestPayloadHash: requestPayloadHash,
APIKeyService: h.apiKeyService,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
reqLog.Error("gateway.responses.record_usage_failed",
zap.Int64("account_id", account.ID),
@@ -559,7 +559,7 @@ func TestGatewayModels_GeminiGroupFallsBackToGeminiModels(t *testing.T) {
var got gatewayModelsResponseForTest
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
require.Equal(t, "list", got.Object)
require.Contains(t, modelIDsForTest(got.Data), "gemini-2.5-flash")
require.Contains(t, modelIDsForTest(got.Data), "gemini-3.5-flash")
require.NotContains(t, modelIDsForTest(got.Data), "claude-sonnet-4-6")
}
@@ -56,6 +56,9 @@ func (h *GatewayHandler) SystemOne(c *gin.Context) {
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -258,9 +261,13 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP
sessionID := service.ExtractClientSessionID(c)
requestPayloadHash := service.HashUsageRequestPayload(body)
// An interior pointer into SystemOneForwardResult would also retain its
// response body while usage waits in the queue. Copy only billing metadata.
forwardResult := result.ForwardResult
channelUsageFields := clientRequestedUsageFields(c, mapping, model, result.UpstreamModel)
h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: &result.ForwardResult,
Result: &forwardResult,
APIKey: apiKey,
User: apiKey.User,
Account: account,
@@ -274,7 +281,7 @@ func (h *GatewayHandler) recordSystemOneUsage(c *gin.Context, apiKey *service.AP
RequestPayloadHash: requestPayloadHash,
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
ChannelUsageFields: clientRequestedUsageFields(c, mapping, model, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.gateway.systemone"),
@@ -0,0 +1,120 @@
//go:build unit
package handler
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
const (
boundRetryUpstream429 = `{"error":{"code":429,"message":"Resource exhausted. Please try again later.","status":"RESOURCE_EXHAUSTED"}}`
boundRetryUpstream502 = `{"error":{"code":502,"message":"Upstream service temporarily unavailable","status":"UNAVAILABLE"}}`
)
// boundRetryUpstream 前 failures 次请求返回 failStatus(默认 429),之后返回成功的生成响应。
type boundRetryUpstream struct {
service.HTTPUpstream
mu sync.Mutex
failures int
failStatus int
bodies []string
}
func (u *boundRetryUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
raw, _ := io.ReadAll(req.Body)
u.mu.Lock()
u.bodies = append(u.bodies, string(raw))
n := len(u.bodies)
u.mu.Unlock()
header := http.Header{"Content-Type": []string{"application/json"}}
if n <= u.failures {
if u.failStatus == http.StatusBadGateway {
return &http.Response{StatusCode: http.StatusBadGateway, Header: header, Body: io.NopCloser(strings.NewReader(boundRetryUpstream502))}, nil
}
return &http.Response{StatusCode: http.StatusTooManyRequests, Header: header, Body: io.NopCloser(strings.NewReader(boundRetryUpstream429))}, nil
}
body := `{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],` +
`"usageMetadata":{"promptTokenCount":10,"cachedContentTokenCount":8,"candidatesTokenCount":1,"totalTokenCount":11}}`
return &http.Response{StatusCode: http.StatusOK, Header: header, Body: io.NopCloser(strings.NewReader(body))}, nil
}
func (u *boundRetryUpstream) requestBodies() []string {
u.mu.Lock()
defer u.mu.Unlock()
return append([]string(nil), u.bodies...)
}
// newBoundRetryEnv 构造绑定在池模式上游网关账号 900 上的显式缓存,账号对 retryCodes 同账号重试 2 次。
func newBoundRetryEnv(t *testing.T, upstream *boundRetryUpstream, retryCodes ...int) *cachedBillingEnv {
t.Helper()
env := newCachedBillingEnv(t, 500, 900)
creds := env.accounts[900].Credentials
creds["base_url"] = "https://gw.example.com"
creds[service.GeminiExplicitCacheUpstreamCredentialKey] = true
creds["pool_mode"] = true
creds["pool_mode_retry_count"] = float64(2)
codes := make([]any, 0, len(retryCodes))
for _, code := range retryCodes {
codes = append(codes, float64(code))
}
creds["pool_mode_retry_status_codes"] = codes
env.seed(time.Now().Add(time.Hour))
env.h.geminiCompatService = service.NewGeminiMessagesCompatService(&cachedBillingAccountRepo{accounts: env.accounts},
nil, nil, nil, nil, nil, upstream, nil, &config.Config{})
return env
}
func (e *cachedBillingEnv) generateWithCache() *httptest.ResponseRecorder {
return e.serve(http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent",
`{"cachedContent":"cachedContents/abc","contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
gin.Params{{Key: "modelAction", Value: "/gemini-2.5-pro:generateContent"}}, e.h.GeminiV1BetaModels)
}
func TestGeminiV1BetaModels_BoundCachePoolModeRetriesUpstream429(t *testing.T) {
upstream := &boundRetryUpstream{failures: 1}
env := newBoundRetryEnv(t, upstream, 429)
rec := env.generateWithCache()
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
bodies := upstream.requestBodies()
require.Len(t, bodies, 2, "429 后在持有缓存的账号上重试一次")
for _, body := range bodies {
require.Contains(t, body, `"cachedContents/up1"`, "每次重试都引用上游缓存名")
}
}
func TestGeminiV1BetaModels_BoundCacheRetryExhaustedPassesThroughUpstream429(t *testing.T) {
upstream := &boundRetryUpstream{failures: 10}
env := newBoundRetryEnv(t, upstream, 429)
rec := env.generateWithCache()
require.Len(t, upstream.requestBodies(), 3, "首发 + pool_mode_retry_count 次同账号重试")
require.Equal(t, http.StatusTooManyRequests, rec.Code)
require.JSONEq(t, boundRetryUpstream429, rec.Body.String(), "重试用尽后原样回写上游网关的响应")
}
// 502 在池模式重试状态码内时同样同账号重试;用尽后原样回写,不按空响应临时封禁本账号。
func TestGeminiV1BetaModels_BoundCacheRetryExhaustedOn502KeepsAccountSchedulable(t *testing.T) {
upstream := &boundRetryUpstream{failures: 10, failStatus: http.StatusBadGateway}
env := newBoundRetryEnv(t, upstream, 429, 502)
rec := env.generateWithCache()
require.Len(t, upstream.requestBodies(), 3)
require.Equal(t, http.StatusBadGateway, rec.Code)
require.JSONEq(t, boundRetryUpstream502, rec.Body.String())
}
@@ -65,6 +65,9 @@ func (h *GatewayHandler) geminiCachedContentsPreamble(c *gin.Context, component
func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) {
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
if err != nil {
if handleRequestBodyReadError(c, err) {
return nil, false
}
if maxErr, ok := extractMaxBytesError(err); ok {
googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit))
return nil, false
@@ -102,7 +102,7 @@ func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) {
expectedNative string
}{
{"native", 200, `{"models":[{"name":"models/gemini-native","inputTokenLimit":123}],"nextPageToken":"next"}`, "models/gemini-native"},
{"scope fallback", 403, `{"error":"insufficient authentication scopes"}`, "models/gemini-2.5-pro"},
{"scope fallback", 403, `{"error":"insufficient authentication scopes"}`, "models/gemini-3.5-flash"},
{"upstream error", 429, `{"error":"rate limited"}`, ""},
} {
t.Run(tt.name, func(t *testing.T) {
@@ -134,3 +134,109 @@ func TestGeminiNativeModelsMergesNativeUpstream(t *testing.T) {
})
}
}
type geminiModelsUpstreamCounter struct {
service.HTTPUpstream
calls int
}
func (u *geminiModelsUpstreamCounter) Do(_ *http.Request, _ string, _ int64, _ int) (*http.Response, error) {
u.calls++
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"models":[{"name":"gemini-4-argon-high"}]}`))}, nil
}
type geminiDeclaredModelsFixture struct {
t *testing.T
groupID int64
handler *GatewayHandler
upstream *geminiModelsUpstreamCounter
}
func newGeminiDeclaredModelsFixture(t *testing.T, accounts []service.Account) *geminiDeclaredModelsFixture {
groupID := int64(47)
repo := &geminiAllowlistAccountRepoStub{gatewayModelsAccountRepoStub: gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{groupID: accounts}}}
upstream := &geminiModelsUpstreamCounter{}
return &geminiDeclaredModelsFixture{
t: t,
groupID: groupID,
handler: &GatewayHandler{geminiCompatService: service.NewGeminiMessagesCompatService(repo, nil, nil, nil, nil, nil, upstream, nil, &config.Config{})},
upstream: upstream,
}
}
func (f *geminiDeclaredModelsFixture) context(path, model string, allowlist service.GroupModelAllowlist) (*gin.Context, *httptest.ResponseRecorder) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, path, nil)
if model != "" {
c.Params = gin.Params{{Key: "model", Value: model}}
}
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{GroupID: &f.groupID, Group: &service.Group{ID: f.groupID, Platform: service.PlatformGemini, ModelAllowlist: allowlist}})
return c, rec
}
func (f *geminiDeclaredModelsFixture) list(allowlist service.GroupModelAllowlist) []string {
c, rec := f.context("/v1beta/models", "", allowlist)
f.handler.GeminiV1BetaListModels(c)
require.Equal(f.t, http.StatusOK, rec.Code, rec.Body.String())
var got gemini.ModelsListResponse
require.NoError(f.t, json.Unmarshal(rec.Body.Bytes(), &got))
names := []string{}
for _, model := range got.Models {
names = append(names, model.Name)
}
return names
}
func (f *geminiDeclaredModelsFixture) get(model string) *httptest.ResponseRecorder {
c, rec := f.context("/v1beta/models/"+model, model, service.GroupModelAllowlist{})
f.handler.GeminiV1BetaGetModel(c)
return rec
}
// 分组内 Gemini 账号都声明了 model_mapping 时,列表与详情都按声明的模型应答,不透传选中账号的上游列表。
func TestGeminiNativeModelsUsesDeclaredMappings(t *testing.T) {
f := newGeminiDeclaredModelsFixture(t, []service.Account{
{ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 10, Credentials: map[string]any{"api_key": "a", "model_mapping": map[string]any{"gemini-4-argon": "gemini-4-argon"}}},
{ID: 2, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 11, Credentials: map[string]any{"api_key": "b", "model_mapping": map[string]any{"gemini-2.5-flash": "gemini-2.5-flash", "gemini-3.1-pro-preview": "gemini-3.1-pro-preview", "gemini-3.8-*": "gemini-3.8-flash"}}},
{ID: 3, Platform: service.PlatformAntigravity, Extra: map[string]any{"mixed_scheduling": true}, Credentials: map[string]any{"model_mapping": map[string]any{"gemini-synced-custom": "gemini-3.8-flash-high"}}},
})
names := f.list(service.GroupModelAllowlist{})
require.Subset(t, names, []string{"models/gemini-2.5-flash", "models/gemini-3.1-pro-preview", "models/gemini-3.8-*", "models/gemini-4-argon", "models/gemini-synced-custom"})
require.NotContains(t, names, "models/gemini-4-argon-high")
// 白名单与 /v1/models 同口径:通配符映射键展开为白名单中的具体模型。
require.Equal(t, []string{"models/gemini-2.5-flash", "models/gemini-3.8-flash", "models/gemini-synced-custom"},
f.list(service.GroupModelAllowlist{Enabled: true, Models: []string{"gemini-2.5-flash", "gemini-3.8-flash", "gemini-synced-custom"}}))
for model, status := range map[string]int{
"gemini-4-argon": http.StatusOK,
"gemini-3.8-flash": http.StatusOK,
"gemini-3.1-pro-preview-customtools": http.StatusOK,
"gemini-synced-custom": http.StatusOK,
"gemini-4-argon-high": http.StatusNotFound,
} {
rec := f.get(model)
require.Equal(t, status, rec.Code, model+": "+rec.Body.String())
if status == http.StatusOK {
require.JSONEq(t, `{"name":"models/`+model+`","supportedGenerationMethods":["generateContent","streamGenerateContent"]}`, rec.Body.String())
} else {
require.Contains(t, rec.Body.String(), "models/"+model+" is not found")
}
}
require.Zero(t, f.upstream.calls)
}
// 分组内有 Gemini 账号未配置映射(接受任意模型)时,模型接口仍由选中账号的上游应答。
func TestGeminiNativeModelsUnmappedAccountKeepsUpstream(t *testing.T) {
f := newGeminiDeclaredModelsFixture(t, []service.Account{
{ID: 1, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 10, Credentials: map[string]any{"api_key": "a", "model_mapping": map[string]any{"gemini-4-argon": "gemini-4-argon"}}},
{ID: 2, Platform: service.PlatformGemini, Type: service.AccountTypeAPIKey, Priority: 11, Credentials: map[string]any{"api_key": "b"}},
})
require.Equal(t, []string{"gemini-4-argon-high"}, f.list(service.GroupModelAllowlist{}))
rec := f.get("gemini-2.5-pro")
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, 2, f.upstream.calls)
}
@@ -9,6 +9,7 @@ import (
"errors"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
@@ -76,6 +77,25 @@ func (h *GatewayHandler) GeminiV1BetaListModels(c *gin.Context) {
return
}
// 分组内 Gemini 账号都声明了 model_mapping 时,列表与 /v1/models 同源(含白名单口径),不透传单个账号的上游列表。
if declared, err := h.geminiCompatService.DeclaredModelIDs(c.Request.Context(), apiKey.GroupID); err == nil && len(declared) > 0 {
ids := append([]string{}, declared...)
for _, id := range agModelIDs {
if !slices.Contains(declared, id) {
ids = append(ids, id)
}
}
if apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
ids = apiKey.Group.ModelAllowlist.FilterForListing(ids)
}
declaredModels := make([]gemini.Model, 0, len(ids))
for _, id := range ids {
declaredModels = append(declaredModels, gemini.FallbackModel(id))
}
c.JSON(http.StatusOK, gemini.ModelsListResponse{Models: declaredModels})
return
}
account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID)
if err != nil {
if len(agModels) > 0 {
@@ -259,6 +279,18 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
return
}
// 分组内 Gemini 账号都声明了 model_mapping 时,按列表接口的同一来源判断模型是否存在。
if declared, err := h.geminiCompatService.DeclaredModelIDs(c.Request.Context(), apiKey.GroupID); err == nil && len(declared) > 0 {
if agModelIDs, agErr := h.geminiCompatService.AntigravityGeminiModelIDs(c.Request.Context(), apiKey.GroupID, true); agErr == nil {
if service.DeclaredModelsCover(declared, modelName) || service.DeclaredModelsCover(agModelIDs, modelName) {
c.JSON(http.StatusOK, gemini.FallbackModel(modelName))
return
}
googleError(c, http.StatusNotFound, "models/"+modelName+" is not found")
return
}
}
account, err := h.geminiCompatService.SelectAccountForModelsEndpoints(c.Request.Context(), apiKey.GroupID)
if err != nil {
// 没有 gemini 账户,检查是否有 antigravity 账户可用
@@ -342,6 +374,9 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -798,6 +833,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
// 长上下文阶梯由目录数据驱动,统一在计费路径内生效,入口无需声明。
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
Result: result,
@@ -815,7 +851,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
ForceCacheBilling: forceCacheBilling,
APIKeyService: h.apiKeyService,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.gemini_v1beta.models"),
+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, 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, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -757,6 +760,7 @@ func recordGrokMediaUsage(
payloadForHash = []byte(videoTaskID)
}
}
requestPayloadHash := service.HashUsageRequestPayload(payloadForHash)
h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: result,
@@ -768,7 +772,7 @@ func recordGrokMediaUsage(
UpstreamEndpoint: upstreamEndpoint,
UserAgent: userAgent,
IPAddress: clientIP,
RequestPayloadHash: service.HashUsageRequestPayload(payloadForHash),
RequestPayloadHash: requestPayloadHash,
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
+1
View File
@@ -49,6 +49,7 @@ type AdminHandlers struct {
type Handlers struct {
Auth *AuthHandler
User *UserHandler
MCPOAuth *MCPOAuthHandler
APIKey *APIKeyHandler
Usage *UsageHandler
Redeem *RedeemHandler
@@ -77,6 +77,9 @@ func (h *AsyncImageHandler) Submit(c *gin.Context) {
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
imageTaskJSONError(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -0,0 +1,373 @@
package handler
import (
"context"
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"net/url"
"strings"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/modelcontextprotocol/go-sdk/oauthex"
)
type MCPOAuthHandler struct {
oauth *service.MCPOAuthService
totp *service.TotpService
users *service.UserService
settings *service.SettingService
cfg *config.Config
}
func NewMCPOAuthHandler(oauth *service.MCPOAuthService, totp *service.TotpService, users *service.UserService, settings *service.SettingService, cfg *config.Config) *MCPOAuthHandler {
return &MCPOAuthHandler{oauth: oauth, totp: totp, users: users, settings: settings, cfg: cfg}
}
func (h *MCPOAuthHandler) Service() *service.MCPOAuthService { return h.oauth }
// ResourceURL is anchored to operator configuration, never the request Host or
// forwarded headers. MCP stays disabled until MCP_PUBLIC_URL is set explicitly,
// so upgrading never exposes client registration or management tools.
func (h *MCPOAuthHandler) ResourceURL(_ context.Context) (string, error) {
if h.cfg == nil || !h.cfg.MCP.Enabled() {
return "", errors.New("MCP is disabled; set MCP_PUBLIC_URL to enable it")
}
configured := config.MCPConfig{PublicURL: h.cfg.MCP.PublicURL}
if err := configured.Validate(); err != nil || configured.PublicURL == "" {
return "", errors.New("MCP public URL is not configured correctly")
}
return configured.PublicURL, nil
}
func (h *MCPOAuthHandler) frontendURL(ctx context.Context) string {
if h.settings != nil {
return strings.TrimRight(strings.TrimSpace(h.settings.GetFrontendURL(ctx)), "/")
}
if h.cfg != nil {
return strings.TrimRight(strings.TrimSpace(h.cfg.Server.FrontendURL), "/")
}
return ""
}
func (h *MCPOAuthHandler) ResourceMetadata(c *gin.Context) {
resource, ok := h.resource(c, true)
if !ok {
return
}
u, _ := url.Parse(resource)
issuer := u.Scheme + "://" + u.Host
c.JSON(http.StatusOK, oauthex.ProtectedResourceMetadata{
Resource: resource, AuthorizationServers: []string{issuer},
ScopesSupported: []string{service.MCPOAuthScope}, BearerMethodsSupported: []string{"header"},
ResourceName: "Sub2API management",
})
}
func (h *MCPOAuthHandler) AuthorizationMetadata(c *gin.Context) {
resource, ok := h.resource(c, true)
if !ok {
return
}
u, _ := url.Parse(resource)
issuer := u.Scheme + "://" + u.Host
frontend := h.frontendURL(c.Request.Context())
if frontend == "" {
frontend = issuer
}
// The SPA restores the browser login and obtains explicit user consent.
authorization, err := mcpAuthorizationURL(frontend)
if err != nil {
mcpOAuthErrorResponse(c, http.StatusServiceUnavailable, "server_error", "MCP authorization page is not configured correctly")
return
}
c.JSON(http.StatusOK, gin.H{
"issuer": issuer, "authorization_endpoint": authorization,
"token_endpoint": issuer + "/api/v1/mcp/oauth/token",
"registration_endpoint": issuer + "/api/v1/mcp/oauth/register",
"revocation_endpoint": issuer + "/api/v1/mcp/oauth/revoke",
"response_types_supported": []string{"code"}, "grant_types_supported": []string{"authorization_code", "refresh_token"},
"code_challenge_methods_supported": []string{"S256"}, "token_endpoint_auth_methods_supported": []string{"none"},
"revocation_endpoint_auth_methods_supported": []string{"none"}, "scopes_supported": []string{service.MCPOAuthScope},
})
}
func mcpAuthorizationURL(frontend string) (string, error) {
u, err := url.Parse(frontend)
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.Contains(frontend, "#") {
return "", errors.New("invalid frontend URL")
}
origin := config.MCPConfig{PublicURL: u.Scheme + "://" + u.Host + "/api/v1/mcp"}
if err := origin.Validate(); err != nil {
return "", err
}
u.Path = strings.TrimRight(u.Path, "/") + "/oauth/mcp/authorize"
u.RawPath = ""
return u.String(), nil
}
func (h *MCPOAuthHandler) Register(c *gin.Context) {
mcpOAuthNoStore(c)
if _, ok := h.resource(c, true); !ok {
return
}
var input service.MCPOAuthRegisterInput
if !mcpOAuthReadJSON(c, &input, false) {
return
}
client, err := h.oauth.Register(c.Request.Context(), input)
if mcpOAuthHandleError(c, err, true) {
return
}
c.JSON(http.StatusCreated, client)
}
func (h *MCPOAuthHandler) Token(c *gin.Context) {
mcpOAuthNoStore(c)
resource, ok := h.resource(c, true)
if !ok {
return
}
form, ok := mcpOAuthReadForm(c)
if !ok {
return
}
if c.GetHeader("Authorization") != "" || form.Get("client_secret") != "" {
mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_client", "Only public clients using token_endpoint_auth_method=none are supported")
return
}
input := service.MCPOAuthTokenInput{
GrantType: form.Get("grant_type"), ClientID: form.Get("client_id"), Code: form.Get("code"),
RedirectURI: form.Get("redirect_uri"), CodeVerifier: form.Get("code_verifier"),
RefreshToken: form.Get("refresh_token"), Resource: form.Get("resource"), Scope: form.Get("scope"),
}
result, err := h.oauth.Token(c.Request.Context(), input, resource)
if mcpOAuthHandleError(c, err, true) {
return
}
c.JSON(http.StatusOK, result)
}
func (h *MCPOAuthHandler) RevokeToken(c *gin.Context) {
mcpOAuthNoStore(c)
form, ok := mcpOAuthReadForm(c)
if !ok {
return
}
if c.GetHeader("Authorization") != "" || form.Get("client_secret") != "" {
mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_client", "Only public clients are supported")
return
}
if mcpOAuthHandleError(c, h.oauth.RevokeToken(c.Request.Context(), form.Get("client_id"), form.Get("token")), true) {
return
}
c.Status(http.StatusOK)
}
func (h *MCPOAuthHandler) Preview(c *gin.Context) {
mcpOAuthNoStore(c)
subject, ok := middleware.GetAuthSubjectFromContext(c)
if !ok {
response.Unauthorized(c, "User not authenticated")
return
}
resource, ok := h.resource(c, false)
if !ok {
return
}
query := c.Request.URL.Query()
for _, values := range query {
if len(values) != 1 {
response.BadRequest(c, "Repeated OAuth parameters are not supported")
return
}
}
input := service.MCPOAuthAuthorizeInput{
ResponseType: query.Get("response_type"), ClientID: query.Get("client_id"), RedirectURI: query.Get("redirect_uri"),
Scope: query.Get("scope"), State: query.Get("state"), CodeChallenge: query.Get("code_challenge"),
CodeChallengeMethod: query.Get("code_challenge_method"), Resource: query.Get("resource"),
}
consent, err := h.oauth.Preview(c.Request.Context(), subject.UserID, input, resource)
if mcpOAuthHandleError(c, err, false) {
return
}
response.Success(c, consent)
}
func (h *MCPOAuthHandler) Decide(c *gin.Context) {
mcpOAuthNoStore(c)
subject, ok := middleware.GetAuthSubjectFromContext(c)
if !ok {
response.Unauthorized(c, "User not authenticated")
return
}
resource, ok := h.resource(c, false)
if !ok {
return
}
var input service.MCPOAuthConsentInput
if !mcpOAuthReadJSON(c, &input, true) {
return
}
if input.Approved && input.Scope == service.MCPScopeAdmin {
role, _ := middleware.GetUserRoleFromContext(c)
if role != service.RoleAdmin {
response.Forbidden(c, "Only administrators can authorize admin MCP access")
return
}
// Administrator write grants outlive browser sessions, so they always
// need a fresh TOTP verification even when the global switch is off.
var verified bool
if input.ReadOnly != nil && !*input.ReadOnly {
verified = middleware.EnforceStepUpAlways(c, h.totp, h.users)
} else {
verified = middleware.EnforceStepUp(c, h.totp, h.users, h.settings)
}
if !verified {
return
}
}
redirect, err := h.oauth.Decide(c.Request.Context(), subject.UserID, input, resource)
if mcpOAuthHandleError(c, err, false) {
return
}
middleware.SetAuditAction(c, "user.mcp.authorize")
response.Success(c, gin.H{"redirect_url": redirect})
}
func (h *MCPOAuthHandler) ListGrants(c *gin.Context) {
mcpOAuthNoStore(c)
subject, ok := middleware.GetAuthSubjectFromContext(c)
if !ok {
response.Unauthorized(c, "User not authenticated")
return
}
grants, err := h.oauth.ListGrants(c.Request.Context(), subject.UserID)
if response.ErrorFrom(c, err) {
return
}
response.Success(c, grants)
}
func (h *MCPOAuthHandler) ConnectionConfig(c *gin.Context) {
mcpOAuthNoStore(c)
if _, ok := middleware.GetAuthSubjectFromContext(c); !ok {
response.Unauthorized(c, "User not authenticated")
return
}
resource, ok := h.resource(c, false)
if !ok {
return
}
response.Success(c, gin.H{"resource": resource})
}
func (h *MCPOAuthHandler) RevokeGrant(c *gin.Context) {
mcpOAuthNoStore(c)
subject, ok := middleware.GetAuthSubjectFromContext(c)
if !ok {
response.Unauthorized(c, "User not authenticated")
return
}
if response.ErrorFrom(c, h.oauth.RevokeGrant(c.Request.Context(), subject.UserID, c.Param("id"))) {
return
}
middleware.SetAuditAction(c, "user.mcp.revoke")
response.Success(c, gin.H{"revoked": true})
}
func (h *MCPOAuthHandler) resource(c *gin.Context, protocol bool) (string, bool) {
resource, err := h.ResourceURL(c.Request.Context())
if err != nil {
if protocol {
mcpOAuthErrorResponse(c, http.StatusServiceUnavailable, "server_error", err.Error())
} else {
response.Error(c, http.StatusServiceUnavailable, err.Error())
}
return "", false
}
return resource, true
}
func mcpOAuthNoStore(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.Header("Pragma", "no-cache")
}
func mcpOAuthErrorResponse(c *gin.Context, status int, code, description string) {
mcpOAuthNoStore(c)
c.JSON(status, service.MCPOAuthError{Code: code, Description: description})
}
func mcpOAuthHandleError(c *gin.Context, err error, protocol bool) bool {
if err == nil {
return false
}
var oauthErr *service.MCPOAuthError
if errors.As(err, &oauthErr) {
if protocol {
mcpOAuthErrorResponse(c, http.StatusBadRequest, oauthErr.Code, oauthErr.Description)
} else {
response.BadRequest(c, oauthErr.Description)
}
} else if protocol {
mcpOAuthErrorResponse(c, http.StatusInternalServerError, "server_error", "OAuth request could not be completed")
} else {
response.ErrorFrom(c, err)
}
return true
}
func mcpOAuthReadJSON(c *gin.Context, out any, browser bool) bool {
mediaType, _, _ := mime.ParseMediaType(c.GetHeader("Content-Type"))
if mediaType == "application/json" {
// Unauthenticated registrations are embedded in client IDs, so they get a tighter bound.
limit := int64(4 << 10)
if browser {
limit = 16 << 10
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
decoder := json.NewDecoder(c.Request.Body)
if browser {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(out); err == nil {
var extra any
if errors.Is(decoder.Decode(&extra), io.EOF) {
return true
}
}
}
if browser {
response.BadRequest(c, "Invalid OAuth authorization request")
} else {
mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "A bounded JSON request body is required")
}
return false
}
func mcpOAuthReadForm(c *gin.Context) (url.Values, bool) {
mediaType, _, _ := mime.ParseMediaType(c.GetHeader("Content-Type"))
if mediaType != "application/x-www-form-urlencoded" {
mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "Use application/x-www-form-urlencoded")
return nil, false
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10)
if err := c.Request.ParseForm(); err != nil {
mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "Cannot read OAuth form")
return nil, false
}
for _, values := range c.Request.PostForm {
if len(values) != 1 {
mcpOAuthErrorResponse(c, http.StatusBadRequest, "invalid_request", "Repeated OAuth parameters are not supported")
return nil, false
}
}
return c.Request.PostForm, true
}
@@ -0,0 +1,494 @@
//go:build unit
package handler
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
const handlerMCPResource = "https://api.example.com/api/v1/mcp"
type handlerMCPRepo struct {
service.MCPOAuthRepository
clientID string
reads, writes int
grant *service.MCPOAuthGrant
}
// Resolving a client ID needs its signing key, so key loads count as reads.
func (r *handlerMCPRepo) ClientIDKey(context.Context) ([]byte, error) {
r.reads++
return []byte("handler-test-mcp-client-id-key-0"), nil
}
func (r *handlerMCPRepo) CreateAuthorization(_ context.Context, grant *service.MCPOAuthGrant, _ *service.MCPOAuthCode, _ int) error {
r.writes++
r.grant = grant
return nil
}
type handlerMCPUsers struct {
service.UserRepository
user *service.User
}
func (r *handlerMCPUsers) GetByID(context.Context, int64) (*service.User, error) { return r.user, nil }
func (r *handlerMCPUsers) GetUserAvatar(context.Context, int64) (*service.UserAvatar, error) {
return nil, nil
}
type handlerMCPSettings struct {
service.SettingRepository
values map[string]string
}
func (r *handlerMCPSettings) GetValue(_ context.Context, key string) (string, error) {
return r.values[key], nil
}
type handlerMCPCache struct {
service.TotpCache
granted bool
err error
calls int
userID int64
session string
}
func (r *handlerMCPCache) HasStepUpGrant(_ context.Context, id int64, session string) (bool, error) {
r.calls++
r.userID, r.session = id, session
return r.granted, r.err
}
func newHandlerMCPFixture(t *testing.T) (*MCPOAuthHandler, *handlerMCPRepo, *handlerMCPUsers, *handlerMCPCache) {
t.Helper()
cfg := &config.Config{MCP: config.MCPConfig{PublicURL: handlerMCPResource}}
cfg.Server.FrontendURL = "https://platform.example.com"
repo := &handlerMCPRepo{}
users := &handlerMCPUsers{user: &service.User{ID: 7, Role: service.RoleAdmin, Status: service.StatusActive, TotpEnabled: true}}
settings := service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyStepUpEnabled: "true"}}, cfg)
cache := &handlerMCPCache{}
totp := service.NewTotpService(users, nil, cache, settings, nil, nil)
oauth := service.NewMCPOAuthService(repo, users)
client, err := oauth.Register(context.Background(), service.MCPOAuthRegisterInput{ClientName: "Example assistant", RedirectURIs: []string{"https://client.example.com/callback?workspace=one"}})
require.NoError(t, err)
repo.clientID, repo.reads = client.ClientID, 0
return NewMCPOAuthHandler(oauth, totp, service.NewUserService(users, nil, nil, nil), settings, cfg), repo, users, cache
}
func handlerMCPContext(t *testing.T, method, target, body, contentType string) (*gin.Context, *httptest.ResponseRecorder) {
t.Helper()
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(method, target, strings.NewReader(body))
if contentType != "" {
c.Request.Header.Set("Content-Type", contentType)
}
return c, rec
}
func handlerMCPSubject(c *gin.Context, role string) {
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 7})
c.Set(string(middleware.ContextKeyUserRole), role)
c.Set(middleware.ContextKeySessionID, "browser-session-7")
}
func handlerMCPAuthorization(clientID string) service.MCPOAuthAuthorizeInput {
digest := sha256.Sum256([]byte(strings.Repeat("v", 43)))
return service.MCPOAuthAuthorizeInput{ResponseType: "code", ClientID: clientID, RedirectURI: "https://client.example.com/callback?workspace=one", Scope: "mcp", State: "a+b&c=d", CodeChallenge: base64.RawURLEncoding.EncodeToString(digest[:]), CodeChallengeMethod: "S256", Resource: handlerMCPResource}
}
func handlerMCPBody(t *testing.T, input any) string {
t.Helper()
raw, err := json.Marshal(input)
require.NoError(t, err)
return string(raw)
}
func handlerMCPJSON(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var body map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
return body
}
func TestMCPOAuthHandlerResourceURLTrustedConfiguration(t *testing.T) {
for _, tt := range []struct{ name, public, frontend, stored, want string }{
{"explicit API origin", handlerMCPResource, "https://platform.example.com", "", handlerMCPResource},
{"normalize explicit", " https://API.EXAMPLE.COM/api/v1/mcp ", "", "", handlerMCPResource},
{"explicit resource wins", handlerMCPResource, "", "https://stored.example.com", handlerMCPResource},
{"loopback development", "http://127.0.0.1:8080/api/v1/mcp", "", "", "http://127.0.0.1:8080/api/v1/mcp"},
{"missing configuration", "", "", "", ""},
// A configured frontend must not implicitly enable MCP after an upgrade.
{"configured frontend stays disabled", "", "https://platform.example.com", "", ""},
{"stored frontend stays disabled", "", "", "https://stored.example.com", ""},
{"insecure public URL", "http://api.example.com/api/v1/mcp", "", "", ""},
{"wrong resource path", "https://api.example.com/mcp", "", "", ""},
{"sub-path deployment", "https://example.com/sub2api/api/v1/mcp", "", "", ""},
{"resource userinfo", "https://user:password@api.example.com/api/v1/mcp", "", "", ""},
{"resource query", handlerMCPResource + "?q=1", "", "", ""},
{"resource fragment", handlerMCPResource + "#x", "", "", ""},
} {
t.Run(tt.name, func(t *testing.T) {
cfg := &config.Config{MCP: config.MCPConfig{PublicURL: tt.public}}
cfg.Server.FrontendURL = tt.frontend
var settings *service.SettingService
if tt.stored != "" {
settings = service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyFrontendURL: tt.stored}}, cfg)
}
h := NewMCPOAuthHandler(nil, nil, nil, settings, cfg)
got, err := h.ResourceURL(context.Background())
if tt.want == "" {
require.Error(t, err)
require.Empty(t, got)
} else {
require.NoError(t, err)
require.Equal(t, tt.want, got)
}
})
}
}
func TestMCPOAuthHandlerMetadataRawAndHostIndependent(t *testing.T) {
h, _, _, _ := newHandlerMCPFixture(t)
for _, auth := range []bool{false, true} {
c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/.well-known/oauth-authorization-server", "", "")
c.Request.Header.Set("X-Forwarded-Host", "forwarded-attacker.example")
c.Request.Header.Set("X-Forwarded-Proto", "http")
if auth {
h.AuthorizationMetadata(c)
} else {
h.ResourceMetadata(c)
}
require.Equal(t, http.StatusOK, rec.Code)
body := handlerMCPJSON(t, rec)
require.NotContains(t, body, "data")
require.NotContains(t, body, "code")
require.NotContains(t, rec.Body.String(), "attacker")
require.Equal(t, []any{"mcp"}, body["scopes_supported"])
if auth {
require.Equal(t, "https://api.example.com", body["issuer"])
require.Equal(t, "https://platform.example.com/oauth/mcp/authorize", body["authorization_endpoint"])
require.Equal(t, "https://api.example.com/api/v1/mcp/oauth/token", body["token_endpoint"])
require.Equal(t, "https://api.example.com/api/v1/mcp/oauth/register", body["registration_endpoint"])
require.Equal(t, "https://api.example.com/api/v1/mcp/oauth/revoke", body["revocation_endpoint"])
require.Equal(t, []any{"S256"}, body["code_challenge_methods_supported"])
require.Equal(t, []any{"none"}, body["token_endpoint_auth_methods_supported"])
} else {
require.Equal(t, handlerMCPResource, body["resource"])
require.Equal(t, []any{"https://api.example.com"}, body["authorization_servers"])
require.Equal(t, []any{"header"}, body["bearer_methods_supported"])
}
}
h = NewMCPOAuthHandler(nil, nil, nil, nil, &config.Config{})
for _, serve := range []gin.HandlerFunc{h.ResourceMetadata, h.AuthorizationMetadata} {
c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/metadata", "", "")
serve(c)
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
require.Equal(t, "server_error", handlerMCPJSON(t, rec)["error"])
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
}
}
func TestMCPOAuthHandlerConnectionConfigUsesCanonicalResource(t *testing.T) {
h, repo, _, _ := newHandlerMCPFixture(t)
c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/user/mcp/config", "", "")
c.Request.Header.Set("X-Forwarded-Host", "forwarded-attacker.example")
handlerMCPSubject(c, service.RoleUser)
h.ConnectionConfig(c)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
require.Equal(t, map[string]any{"resource": handlerMCPResource}, handlerMCPJSON(t, rec)["data"])
require.NotContains(t, rec.Body.String(), "attacker")
require.Zero(t, repo.reads)
require.Zero(t, repo.writes)
h = NewMCPOAuthHandler(nil, nil, nil, nil, &config.Config{})
c, rec = handlerMCPContext(t, http.MethodGet, "/user/mcp/config", "", "")
handlerMCPSubject(c, service.RoleUser)
h.ConnectionConfig(c)
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
require.Contains(t, handlerMCPJSON(t, rec), "code")
}
func TestMCPOAuthHandlerAuthorizationMetadataValidatesFrontendURL(t *testing.T) {
for _, tt := range []struct{ frontend, want string }{
{"https://platform.example.com/console/", "https://platform.example.com/console/oauth/mcp/authorize"},
{"http://127.0.0.1:3000/", "http://127.0.0.1:3000/oauth/mcp/authorize"},
{"", "https://api.example.com/oauth/mcp/authorize"},
{"http://platform.example.com", ""}, {"https://user:password@platform.example.com", ""},
{"https://platform.example.com?next=attacker", ""}, {"https://platform.example.com#fragment", ""},
{"https://platform.example.com?", ""}, {"https://platform.example.com#", ""},
} {
t.Run(tt.frontend, func(t *testing.T) {
cfg := &config.Config{MCP: config.MCPConfig{PublicURL: handlerMCPResource}}
cfg.Server.FrontendURL = tt.frontend
h := NewMCPOAuthHandler(nil, nil, nil, nil, cfg)
c, rec := handlerMCPContext(t, http.MethodGet, "https://attacker.example/metadata", "", "")
h.AuthorizationMetadata(c)
if tt.want == "" {
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
require.Equal(t, "server_error", handlerMCPJSON(t, rec)["error"])
} else {
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, tt.want, handlerMCPJSON(t, rec)["authorization_endpoint"])
}
})
}
}
func TestMCPOAuthHandlerJSONValidation(t *testing.T) {
for _, tt := range []struct {
name, contentType, body string
browser, valid bool
}{
{"valid browser", "application/json; charset=utf-8", `{"approved":false,"authorization":{"client_id":"client-1"}}`, true, true},
{"unknown browser field", "application/json", `{"approved":false,"unexpected":true}`, true, false},
{"unknown nested field", "application/json", `{"authorization":{"unexpected":true}}`, true, false},
{"wrong type", "application/json", `{"approved":"true"}`, true, false},
{"two documents", "application/json", `{} {}`, true, false},
{"trailing bytes", "application/json", `{} extra`, true, false},
{"truncated", "application/json", `{"approved":`, true, false},
{"wrong content type", "text/plain", `{}`, true, false},
{"missing content type", "", `{}`, true, false},
{"oversized browser", "application/json", `{"authorization":{"state":"` + strings.Repeat("x", 17<<10) + `"}}`, true, false},
{"registration extension metadata", "application/json", `{"client_name":"example","client_uri":"https://client.example.com"}`, false, true},
{"oversized registration", "application/json", `{"client_name":"` + strings.Repeat("x", 17<<10) + `"}`, false, false},
{"registration above 4 KiB", "application/json", `{"client_name":"x","client_uri":"` + strings.Repeat("x", 4<<10) + `"}`, false, false},
{"browser body above registration limit", "application/json", `{"authorization":{"state":"` + strings.Repeat("x", 8<<10) + `"}}`, true, true},
{"malformed registration", "application/json", `{`, false, false},
} {
t.Run(tt.name, func(t *testing.T) {
c, rec := handlerMCPContext(t, http.MethodPost, "/oauth", tt.body, tt.contentType)
var input any = &service.MCPOAuthRegisterInput{}
if tt.browser {
input = &service.MCPOAuthConsentInput{}
}
require.Equal(t, tt.valid, mcpOAuthReadJSON(c, input, tt.browser))
if !tt.valid {
require.Equal(t, http.StatusBadRequest, rec.Code)
body := handlerMCPJSON(t, rec)
if tt.browser {
require.Contains(t, body, "code")
} else {
require.Equal(t, "invalid_request", body["error"])
require.NotContains(t, body, "data")
}
}
})
}
}
func TestMCPOAuthHandlerFormValidation(t *testing.T) {
for _, tt := range []struct{ name, contentType, body string }{
{"JSON", "application/json", `{}`}, {"missing content type", "", "client_id=client-1"},
{"repeated client", "application/x-www-form-urlencoded", "client_id=one&client_id=two"},
{"repeated code", "application/x-www-form-urlencoded", "code=one&code=two"},
{"invalid escape", "application/x-www-form-urlencoded", "client_id=%zz"},
{"oversized", "application/x-www-form-urlencoded", "code=" + strings.Repeat("x", 17<<10)},
} {
t.Run(tt.name, func(t *testing.T) {
c, rec := handlerMCPContext(t, http.MethodPost, "/oauth/token", tt.body, tt.contentType)
_, ok := mcpOAuthReadForm(c)
require.False(t, ok)
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Equal(t, "invalid_request", handlerMCPJSON(t, rec)["error"])
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
})
}
c, _ := handlerMCPContext(t, http.MethodPost, "/oauth/token?client_id=attacker&code=query-code", "client_id=client-1&code=body-code", "application/x-www-form-urlencoded; charset=utf-8")
values, ok := mcpOAuthReadForm(c)
require.True(t, ok)
require.Equal(t, url.Values{"client_id": {"client-1"}, "code": {"body-code"}}, values)
}
func TestMCPOAuthHandlerTokenEndpointsRejectConfidentialAuthentication(t *testing.T) {
for _, endpoint := range []string{"token", "revoke"} {
for _, auth := range []string{"authorization", "client_secret"} {
t.Run(endpoint+"/"+auth, func(t *testing.T) {
h, repo, _, _ := newHandlerMCPFixture(t)
values := url.Values{"client_id": {"client-1"}}
if auth == "client_secret" {
values.Set("client_secret", "not-supported")
}
c, rec := handlerMCPContext(t, http.MethodPost, "/oauth/"+endpoint, values.Encode(), "application/x-www-form-urlencoded")
if auth == "authorization" {
c.Request.Header.Set("Authorization", "Basic dXNlcjpwYXNz")
}
if endpoint == "token" {
h.Token(c)
} else {
h.RevokeToken(c)
}
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Equal(t, "invalid_client", handlerMCPJSON(t, rec)["error"])
require.Zero(t, repo.reads)
require.Zero(t, repo.writes)
})
}
}
}
func TestMCPOAuthHandlerPreviewFrontendContract(t *testing.T) {
h, repo, _, _ := newHandlerMCPFixture(t)
input := handlerMCPAuthorization(repo.clientID)
query := url.Values{"response_type": {input.ResponseType}, "client_id": {input.ClientID}, "redirect_uri": {input.RedirectURI}, "scope": {input.Scope}, "state": {input.State}, "code_challenge": {input.CodeChallenge}, "code_challenge_method": {input.CodeChallengeMethod}, "resource": {input.Resource}, "timezone": {"Asia/Shanghai"}}
c, rec := handlerMCPContext(t, http.MethodGet, "/user/mcp/authorize?"+query.Encode(), "", "")
handlerMCPSubject(c, service.RoleUser)
h.Preview(c)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
body := handlerMCPJSON(t, rec)
require.Equal(t, float64(0), body["code"])
require.Equal(t, map[string]any{"client_id": repo.clientID, "client_name": "Example assistant", "redirect_uri": input.RedirectURI, "resource": handlerMCPResource, "scope": "mcp"}, body["data"])
require.Zero(t, repo.writes)
query.Add("redirect_uri", "https://attacker.example/callback")
c, rec = handlerMCPContext(t, http.MethodGet, "/user/mcp/authorize?"+query.Encode(), "", "")
handlerMCPSubject(c, service.RoleUser)
h.Preview(c)
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Equal(t, 1, repo.reads, "reject duplicate parameters before service access")
}
func TestMCPOAuthHandlerAdminDecisionGatesBeforePersistence(t *testing.T) {
for _, tt := range []struct {
name, role, authMethod, marker string
totp, granted bool
cacheErr error
status int
}{
{name: "non-admin", role: service.RoleUser, totp: true, granted: true, status: 403, marker: "Only administrators"},
{name: "missing role", totp: true, granted: true, status: 403, marker: "Only administrators"},
{name: "TOTP disabled", role: service.RoleAdmin, status: 403, marker: "STEP_UP_TOTP_NOT_ENABLED"},
{name: "no recent grant", role: service.RoleAdmin, totp: true, status: 403, marker: "STEP_UP_REQUIRED"},
{name: "step-up unavailable", role: service.RoleAdmin, totp: true, cacheErr: errors.New("cache unavailable"), status: 503, marker: "STEP_UP_UNAVAILABLE"},
{name: "admin API key", role: service.RoleAdmin, authMethod: service.AuditAuthMethodAdminAPIKey, totp: true, granted: true, status: 403, marker: "STEP_UP_ADMIN_API_KEY_FORBIDDEN"},
{name: "MCP credential", role: service.RoleAdmin, authMethod: service.AuditAuthMethodMCPOAuth, totp: true, granted: true, status: 403, marker: "STEP_UP_MCP_OAUTH_FORBIDDEN"},
} {
t.Run(tt.name, func(t *testing.T) {
h, repo, users, cache := newHandlerMCPFixture(t)
users.user.TotpEnabled = tt.totp
cache.granted, cache.err = tt.granted, tt.cacheErr
input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin}
c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json")
handlerMCPSubject(c, tt.role)
c.Set("auth_method", tt.authMethod)
h.Decide(c)
require.Equal(t, tt.status, rec.Code)
require.Contains(t, rec.Body.String(), tt.marker)
require.Zero(t, repo.reads)
require.Zero(t, repo.writes)
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
})
}
}
func TestMCPOAuthHandlerAdminWriteAlwaysRequiresStepUp(t *testing.T) {
for _, tt := range []struct {
name string
readOnly *bool
totp, granted bool
status, writes int
marker string
}{
{name: "write without TOTP", readOnly: boolPtr(false), status: 403, marker: "STEP_UP_TOTP_NOT_ENABLED"},
{name: "write without recent verification", readOnly: boolPtr(false), totp: true, status: 403, marker: "STEP_UP_REQUIRED"},
{name: "verified write", readOnly: boolPtr(false), totp: true, granted: true, status: 200, writes: 1},
{name: "read-only follows the switch", readOnly: boolPtr(true), status: 200, writes: 1},
{name: "default read-only follows the switch", status: 200, writes: 1},
} {
t.Run(tt.name, func(t *testing.T) {
h, repo, users, cache := newHandlerMCPFixture(t)
// Global step-up is disabled; write grants still need verification.
h.settings = service.NewSettingService(&handlerMCPSettings{values: map[string]string{service.SettingKeyStepUpEnabled: "false"}}, h.cfg)
users.user.TotpEnabled = tt.totp
cache.granted = tt.granted
input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: tt.readOnly}
c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json")
handlerMCPSubject(c, service.RoleAdmin)
h.Decide(c)
require.Equal(t, tt.status, rec.Code, rec.Body.String())
require.Contains(t, rec.Body.String(), tt.marker)
require.Equal(t, tt.writes, repo.writes)
})
}
}
func TestMCPOAuthHandlerRegistrationPersistsNothing(t *testing.T) {
h, repo, _, _ := newHandlerMCPFixture(t)
c, rec := handlerMCPContext(t, http.MethodPost, "/api/v1/mcp/oauth/register", `{"client_name":"Example assistant","redirect_uris":["https://client.example.com/cb"]}`, "application/json")
h.Register(c)
require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String())
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
body := handlerMCPJSON(t, rec)
require.True(t, strings.HasPrefix(body["client_id"].(string), "mcp_client_"))
require.NotEqual(t, repo.clientID, body["client_id"])
require.Equal(t, []any{"https://client.example.com/cb"}, body["redirect_uris"])
require.Zero(t, repo.writes)
}
func TestMCPOAuthHandlerAdminApprovalUsesBrowserSession(t *testing.T) {
h, repo, _, cache := newHandlerMCPFixture(t)
cache.granted = true
readOnly := false
input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: true, Scope: service.MCPScopeAdmin, ReadOnly: &readOnly}
c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json")
handlerMCPSubject(c, service.RoleAdmin)
h.Decide(c)
require.Equal(t, http.StatusOK, rec.Code)
require.Equal(t, int64(7), cache.userID)
require.Equal(t, "browser-session-7", cache.session)
require.Equal(t, 1, repo.writes)
require.Equal(t, service.MCPScopeAdmin, repo.grant.Scope)
require.False(t, repo.grant.ReadOnly)
result := handlerMCPJSON(t, rec)["data"].(map[string]any)
destination, err := url.Parse(result["redirect_url"].(string))
require.NoError(t, err)
require.Equal(t, "client.example.com", destination.Host)
require.Equal(t, "one", destination.Query().Get("workspace"))
require.Equal(t, input.Authorization.State, destination.Query().Get("state"))
require.NotEmpty(t, destination.Query().Get("code"))
require.Empty(t, rec.Header().Get("Location"), "return a validated URL without an automatic HTTP redirect")
}
func TestMCPOAuthHandlerDenialSkipsStepUpAndPersistence(t *testing.T) {
h, repo, _, cache := newHandlerMCPFixture(t)
cache.err = errors.New("must not be called")
input := service.MCPOAuthConsentInput{Authorization: handlerMCPAuthorization(repo.clientID), Approved: false, Scope: service.MCPScopeAdmin}
c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp/authorize", handlerMCPBody(t, input), "application/json")
handlerMCPSubject(c, service.RoleUser)
h.Decide(c)
require.Equal(t, http.StatusOK, rec.Code)
require.Zero(t, cache.calls)
require.Zero(t, repo.writes)
result := handlerMCPJSON(t, rec)["data"].(map[string]any)
destination, err := url.Parse(result["redirect_url"].(string))
require.NoError(t, err)
require.Equal(t, "client.example.com", destination.Host)
require.Equal(t, "access_denied", destination.Query().Get("error"))
require.Equal(t, input.Authorization.State, destination.Query().Get("state"))
require.Empty(t, destination.Query().Get("code"))
}
func TestMCPOAuthHandlerBrowserEndpointsRequireSession(t *testing.T) {
h, repo, _, _ := newHandlerMCPFixture(t)
for _, serve := range []gin.HandlerFunc{h.ConnectionConfig, h.Preview, h.Decide, h.ListGrants, h.RevokeGrant} {
c, rec := handlerMCPContext(t, http.MethodPost, "/user/mcp", `{}`, "application/json")
serve(c)
require.Equal(t, http.StatusUnauthorized, rec.Code)
require.Equal(t, "no-store", rec.Header().Get("Cache-Control"))
}
require.Zero(t, repo.reads)
require.Zero(t, repo.writes)
}
@@ -52,6 +52,9 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) {
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -293,6 +296,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage(
inboundEndpoint := GetInboundEndpoint(c)
upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
pricingAt := service.OpenAIPricingAtFromContext(c.Request.Context())
h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
@@ -310,7 +314,7 @@ func (h *OpenAIGatewayHandler) recordAlphaSearchUsage(
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: channelMapping.ToUsageFields(requestedModel, result.UpstreamModel),
PricingAt: service.OpenAIPricingAtFromContext(c.Request.Context()),
PricingAt: pricingAt,
}); err != nil {
logger.L().With(
zap.String("component", "handler.openai_gateway.alpha_search"),
@@ -51,6 +51,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -292,6 +295,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel)
h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: res,
@@ -306,7 +310,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel),
ChannelUsageFields: channelUsageFields,
PricingAt: pricingAt,
CyberBlocked: cyberBlocked,
}); err != nil {
@@ -48,6 +48,9 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
body, err := pkghttputil.ReadRequestBodyWithPrealloc(c.Request)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -271,6 +274,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel)
h.submitOpenAIUsageRecordTask(c.Request.Context(), result, func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: result,
@@ -285,7 +289,7 @@ func (h *OpenAIGatewayHandler) Embeddings(c *gin.Context) {
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, result.UpstreamModel),
ChannelUsageFields: channelUsageFields,
PricingAt: pricingAt,
}); err != nil {
logger.L().With(
@@ -42,6 +42,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -135,6 +138,9 @@ func (h *OpenAIGatewayHandler) ResponsesInputTokens(c *gin.Context) {
func (h *OpenAIGatewayHandler) GrokCountTokens(c *gin.Context) {
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -205,6 +211,9 @@ func (h *OpenAIGatewayHandler) CountTokens(c *gin.Context) {
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -270,9 +270,10 @@ func wrapUsageRecordTaskContext(parent context.Context, task service.UsageRecord
if parent != nil {
done = service.InflightReservationFromContext(parent).Acquire()
}
requestContext := usageRecordContext(parent, context.Background())
return func(ctx context.Context) {
defer done()
task(usageRecordContext(parent, ctx))
task(usageRecordContext(requestContext, ctx))
}, done
}
@@ -422,6 +423,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
// Read request body
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -656,6 +660,12 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
// 该判断已排除 Codex 被动 image_gen namespace,避免 CC-only 账号被误过滤(#4476)。
needsResponses := nativeV2 || legacyCompact
requiredCapability := openAIResponsesRequiredCapabilityForRequest(imageIntent, needsResponses, requestPlatform)
imageSizeRouted := imageIntent && requestPlatform == service.PlatformOpenAI
imageSize := ""
if imageSizeRouted {
imageSize = service.OpenAIResponsesImageRequestSize(body)
c.Request = c.Request.WithContext(service.WithOpenAIImageSizeRouting(c.Request.Context(), imageSize))
}
// 分组利润控制:请求级装配定价上下文——pricingAt 固定本请求的
// D 与计费高峰因子,选号、槽位终检与全部 failover 重入共用同一门与阈值。
@@ -702,6 +712,13 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
h.handleStreamingAwareError(c, http.StatusServiceUnavailable, "compact_not_supported", "No available accounts support /responses/compact", streamStarted)
return
}
if imageSizeRouted {
if tier, unsupported := h.gatewayService.OpenAIImageSizeTierUnsupported(c.Request.Context(), apiKey.GroupID, forwardModel, imageSize, requiredCapability, ""); unsupported {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", service.OpenAIImageSizeTierUnsupportedMessage(imageSize, tier), streamStarted)
return
}
}
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, reqModel, reqModel, requestPlatform)
cls = classifySelectionFailureError(err, cls)
if !cls.ModelNotFound {
@@ -827,6 +844,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
channelUsageFields := clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel)
h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: res,
@@ -842,7 +860,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, reqModel, res.UpstreamModel),
ChannelUsageFields: channelUsageFields,
PricingAt: pricingAt,
CyberBlocked: cyberBlocked,
NativeCompactionV2: nativeV2,
@@ -1188,6 +1206,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
body, err := readLenientJSONRequestBodyWithPrealloc(c.Request, h.cfg)
if err != nil {
if handleRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.anthropicErrorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -1421,6 +1442,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
sessionID := service.ExtractClientSessionID(c)
cyberBlocked := service.GetOpsCyberPolicy(c) != nil
channelUsageFields := clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel)
h.submitOpenAIUsageRecordTask(c.Request.Context(), res, func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: res,
@@ -1436,7 +1458,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMappingMsg, reqModel, res.UpstreamModel),
ChannelUsageFields: channelUsageFields,
PricingAt: pricingAt,
CyberBlocked: cyberBlocked,
}); err != nil {
+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, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
return
@@ -156,7 +159,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
defer inflightDone()
sessionHash := h.gatewayService.GenerateExplicitSessionHash(c, body)
requestCtx := service.WithOpenAIImagesEndpoint(service.WithOpenAIImageGenerationIntent(c.Request.Context()))
requestCtx := service.WithOpenAIImageSizeRouting(service.WithOpenAIImagesEndpoint(service.WithOpenAIImageGenerationIntent(c.Request.Context())), parsed.Size)
maxAccountSwitches := h.maxAccountSwitches
switchCount := 0
@@ -189,6 +192,11 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
zap.Int("excluded_account_count", len(failedAccountIDs)),
)
if len(failedAccountIDs) == 0 {
if tier, unsupported := h.gatewayService.OpenAIImageSizeTierUnsupported(c.Request.Context(), apiKey.GroupID, routingModel, parsed.Size, "", parsed.RequiredCapabilityForModel(channelMapping.MappedModel)); unsupported {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
h.handleStreamingAwareError(c, http.StatusBadRequest, "invalid_request_error", service.OpenAIImageSizeTierUnsupportedMessage(parsed.Size, tier), streamStarted)
return
}
cls := classifyNoAccountErrorFromGin(c, h.gatewayService, apiKey, clientRequestModel, routingModel, service.PlatformOpenAI)
if !cls.ModelNotFound {
markOpsRoutingCapacityLimitedIfNoAvailable(c, err)
@@ -404,6 +412,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
upstreamModel = result.UpstreamModel
}
sessionID := service.ExtractClientSessionID(c)
channelUsageFields := clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel)
h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
if err := h.gatewayService.RecordUsage(ctx, &service.OpenAIRecordUsageInput{
Result: result,
@@ -419,7 +428,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) {
APIKeyService: h.apiKeyService,
QuotaPlatform: quotaPlatform,
SessionID: sessionID,
ChannelUsageFields: clientRequestedUsageFields(c, channelMapping, requestModel, upstreamModel),
ChannelUsageFields: channelUsageFields,
}); err != nil {
logger.L().With(
zap.String("component", "handler.openai_gateway.images"),
@@ -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])
}
+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 {
@@ -7,8 +7,20 @@ import (
"github.com/Wei-Shaw/sub2api/internal/config"
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/gin-gonic/gin"
)
// handleRequestBodyReadError handles cancellation and temporary capacity errors
// before callers classify malformed or oversized request bodies.
func handleRequestBodyReadError(c *gin.Context, err error) bool {
if err != nil && failoverClientGone(c) {
c.Abort()
return true
}
return middleware2.RejectRequestBodyMemoryOverload(c, err)
}
func extractMaxBytesError(err error) (*http.MaxBytesError, bool) {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
@@ -2,6 +2,7 @@ package handler
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
@@ -43,3 +44,39 @@ func TestRequestBodyLimitTooLarge(t *testing.T) {
require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code)
require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit))
}
func TestHandleRequestBodyReadErrorCancellation(t *testing.T) {
for _, tc := range []struct {
name string
cancelled bool
committed bool
}{
{name: "cancelled", cancelled: true},
{name: "cancelled_after_commit", cancelled: true, committed: true},
{name: "ordinary_read_error"},
} {
t.Run(tc.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if tc.cancelled {
cancel()
}
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx)
if tc.committed {
_, err := c.Writer.WriteString("already committed")
require.NoError(t, err)
}
bodyBefore := recorder.Body.String()
require.Equal(t, tc.cancelled, handleRequestBodyReadError(c, io.ErrUnexpectedEOF))
require.Equal(t, tc.cancelled, c.IsAborted())
status := http.StatusOK
if tc.cancelled && !tc.committed {
status = statusClientClosedRequest
}
require.Equal(t, status, c.Writer.Status())
require.Equal(t, bodyBefore, recorder.Body.String(), "cancelled clients must not receive an error body")
})
}
}
@@ -94,6 +94,7 @@ func (h *SettingHandler) GetPublicSettings(c *gin.Context) {
GitHubOAuthEnabled: settings.GitHubOAuthEnabled,
GoogleOAuthEnabled: settings.GoogleOAuthEnabled,
BackendModeEnabled: settings.BackendModeEnabled,
MCPEnabled: settings.MCPEnabled,
PaymentEnabled: settings.PaymentEnabled,
PaymentBalanceDisabled: settings.PaymentBalanceDisabled,
Version: h.version,
@@ -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")
}
})
}
}
+3
View File
@@ -183,6 +183,7 @@ func ProvideAdminSettingHandler(settingService *service.SettingService, emailSer
func ProvideHandlers(
authHandler *AuthHandler,
userHandler *UserHandler,
mcpOAuthHandler *MCPOAuthHandler,
apiKeyHandler *APIKeyHandler,
usageHandler *UsageHandler,
redeemHandler *RedeemHandler,
@@ -209,6 +210,7 @@ func ProvideHandlers(
return &Handlers{
Auth: authHandler,
User: userHandler,
MCPOAuth: mcpOAuthHandler,
APIKey: apiKeyHandler,
Usage: usageHandler,
Redeem: redeemHandler,
@@ -236,6 +238,7 @@ var ProviderSet = wire.NewSet(
// Top-level handlers
NewAuthHandler,
NewUserHandler,
NewMCPOAuthHandler,
NewAPIKeyHandler,
NewUsageHandler,
NewRedeemHandler,
+127
View File
@@ -0,0 +1,127 @@
package managementmcp
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
const AuthMethod = service.AuditAuthMethodMCPOAuth
type TokenAuthenticator interface {
Authenticate(context.Context, string) (*service.MCPPrincipal, error)
}
type requestKey struct{}
type dispatchKey struct{}
type authenticatedRequest struct {
principal *service.MCPPrincipal
request *http.Request
}
// Authenticate accepts only resource-bound OAuth access tokens. Browser sessions and
// inference keys never become management credentials through this endpoint.
func Authenticate(tokens TokenAuthenticator, allowedOrigins []string, resourceURL func(context.Context) (string, error)) gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
resource, err := resourceURL(c.Request.Context())
if err != nil {
middleware.AbortWithError(c, http.StatusServiceUnavailable, "MCP_OAUTH_NOT_CONFIGURED", "Configure the public MCP URL to enable OAuth")
return
}
u, err := url.Parse(resource)
if err != nil || u.Host == "" {
middleware.AbortWithError(c, http.StatusServiceUnavailable, "MCP_OAUTH_NOT_CONFIGURED", "MCP public URL is invalid")
return
}
challenge := fmt.Sprintf(`Bearer resource_metadata="%s://%s/.well-known/oauth-protected-resource/api/v1/mcp", scope="mcp"`, u.Scheme, u.Host)
if !originAllowed(c.Request, allowedOrigins) {
middleware.AbortWithError(c, http.StatusForbidden, "MCP_ORIGIN_DENIED", "Origin is not allowed for MCP")
return
}
parts := strings.Fields(c.GetHeader("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
c.Header("WWW-Authenticate", challenge)
middleware.AbortWithError(c, http.StatusUnauthorized, "INVALID_MCP_TOKEN", "An OAuth access token is required")
return
}
principal, err := tokens.Authenticate(c.Request.Context(), parts[1])
if err != nil || principal == nil || principal.Resource != resource {
if err != nil && !errors.Is(err, service.ErrMCPOAuthInvalidToken) {
middleware.AbortWithError(c, http.StatusServiceUnavailable, "MCP_AUTH_UNAVAILABLE", "MCP authentication is temporarily unavailable")
return
}
c.Header("WWW-Authenticate", challenge+`, error="invalid_token"`)
middleware.AbortWithError(c, http.StatusUnauthorized, "INVALID_MCP_TOKEN", "MCP OAuth access token is invalid or expired")
return
}
identity := &authenticatedRequest{principal: principal, request: c.Request}
c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestKey{}, identity))
setSubject(c, principal)
c.Next()
}
}
// DispatchAuth is used exclusively by the private in-process management router.
// No HTTP header can supply this context. Public REST auth remains JWT-only.
func DispatchAuth(admin bool) gin.HandlerFunc {
return func(c *gin.Context) {
identity, _ := c.Request.Context().Value(requestKey{}).(*authenticatedRequest)
spec, ok := c.Request.Context().Value(dispatchKey{}).(ToolSpec)
if identity == nil || !ok || spec.Method != c.Request.Method || spec.Path != c.FullPath() ||
!toolAllowed(identity.principal, spec) || (admin && identity.principal.Scope != service.MCPScopeAdmin) {
middleware.AbortWithError(c, http.StatusForbidden, "MCP_FORBIDDEN", "MCP operation is not allowed")
return
}
setSubject(c, identity.principal)
middleware.SetAuditExtra(c, map[string]any{"mcp_grant_id": identity.principal.GrantID, "mcp_tool": spec.Name})
c.Next()
}
}
func setSubject(c *gin.Context, principal *service.MCPPrincipal) {
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: principal.UserID, Concurrency: principal.Concurrency})
c.Set(string(middleware.ContextKeyUserRole), principal.Role)
c.Set(middleware.ContextKeyAuthEmail, principal.Email)
c.Set("auth_method", AuthMethod)
// Never share a legacy user's step-up grant with a machine credential.
c.Set(middleware.ContextKeySessionID, "mcp:"+principal.GrantID)
}
func toolAllowed(p *service.MCPPrincipal, spec ToolSpec) bool {
return p != nil && p.UserID > 0 &&
(p.Scope == service.MCPScopeUser || p.Scope == service.MCPScopeAdmin) &&
(!spec.Admin || (p.Scope == service.MCPScopeAdmin && p.Role == service.RoleAdmin)) &&
(!p.ReadOnly || spec.ReadOnly)
}
func originAllowed(r *http.Request, origins []string) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true // Native MCP clients do not send an Origin.
}
u, err := url.Parse(origin)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" ||
u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
return false
}
// Same-host browser access also works behind an HTTPS terminating proxy.
if strings.EqualFold(u.Host, r.Host) {
return true
}
for _, allowed := range origins {
// Wildcard CORS does not disable MCP's Origin validation.
if allowed != "*" && origin == strings.TrimSpace(allowed) {
return true
}
}
return false
}
+280
View File
@@ -0,0 +1,280 @@
// Package managementmcp exposes a bounded set of platform management operations.
package managementmcp
import "strings"
// ToolSpec binds one MCP tool to an existing authenticated management route.
// InputSchema permits only named path parameters, query parameters and body fields;
// clients never supply a URL, HTTP method or credentials in tool arguments.
type ToolSpec struct {
Name string
Description string
Method string
Path string
Admin bool
ReadOnly bool
Destructive bool
RevealCreatedKey bool
InputSchema map[string]any
}
// ToolCatalog returns fresh schemas so filtering one connection's tools cannot
// alter another connection's permissions or input validation.
func ToolCatalog() []ToolSpec {
keyList := catalogPage(map[string]any{
"search": catalogText("Search API key names", 100),
"status": catalogEnum("Key status", "active", "inactive", "quota_exhausted", "expired"),
"group_id": catalogID("Group ID"),
})
keyCreate := catalogObject(map[string]any{
"name": catalogNonemptyText("Name for the new API key", 100),
"group_id": catalogID("Accessible group ID; use user_list_groups to find one"),
"quota": catalogNumber("Lifetime spending limit in USD; 0 means unlimited", 0),
"expires_in_days": catalogInteger("Lifetime in days", 1, 36500),
"ip_whitelist": catalogStrings("Allowed IP addresses or CIDR ranges; empty means no allowlist", 100, 128),
"ip_blacklist": catalogStrings("Blocked IP addresses or CIDR ranges", 100, 128),
"rate_limit_5h": catalogNumber("Rolling 5-hour spending limit in USD; 0 means unlimited", 0),
"rate_limit_1d": catalogNumber("Rolling 1-day spending limit in USD; 0 means unlimited", 0),
"rate_limit_7d": catalogNumber("Rolling 7-day spending limit in USD; 0 means unlimited", 0),
}, "name")
keyUpdate := catalogObject(map[string]any{
"name": catalogNonemptyText("New API key name", 100),
"group_id": catalogID("Accessible destination group ID"),
"status": catalogEnum("Enable or disable this key", "active", "inactive"),
"quota": catalogNumber("Lifetime spending limit in USD; 0 means unlimited", 0),
"expires_at": catalogText("Expiry in RFC3339 format; empty string removes expiry", 64),
"ip_whitelist": catalogStrings("Replace allowed IP addresses/CIDRs; empty clears the list", 100, 128),
"ip_blacklist": catalogStrings("Replace blocked IP addresses/CIDRs; empty clears the list", 100, 128),
"rate_limit_5h": catalogNumber("Rolling 5-hour spending limit in USD; 0 means unlimited", 0),
"rate_limit_1d": catalogNumber("Rolling 1-day spending limit in USD; 0 means unlimited", 0),
"rate_limit_7d": catalogNumber("Rolling 7-day spending limit in USD; 0 means unlimited", 0),
})
keyUpdate["minProperties"] = 1
userUpdate := catalogObject(map[string]any{
"username": catalogText("Display name", 100),
"notes": catalogText("Administrator notes", 2000),
"concurrency": catalogInteger("Maximum concurrent requests", 1, 100000),
"rpm_limit": catalogInteger("Requests per minute; 0 means unlimited", 0, 1000000),
"status": catalogEnum("User status; disabling blocks access", "active", "disabled"),
"allowed_groups": catalogIDs("Replace the user's allowed group IDs"),
"restrict_public_groups": catalogBool("Restrict public groups to allowed_groups"),
})
userUpdate["minProperties"] = 1
groupCreateFields := catalogGroupFields()
groupCreateFields["platform"] = catalogNonemptyText("Platform identifier, for example anthropic, openai, gemini or composite", 64)
groupCreate := catalogObject(groupCreateFields, "name", "platform", "rate_multiplier")
groupUpdateFields := catalogGroupFields()
groupUpdateFields["status"] = catalogEnum("Group availability", "active", "inactive")
groupUpdate := catalogObject(groupUpdateFields)
groupUpdate["minProperties"] = 1
accountUpdate := catalogObject(map[string]any{
"name": catalogNonemptyText("Upstream account name", 100),
"notes": catalogText("Administrator notes", 2000),
"concurrency": catalogInteger("Maximum concurrent requests", 1, 100000),
"priority": catalogInteger("Scheduling priority; lower values are preferred", 0, 100000),
"rate_multiplier": catalogNumber("Account cost multiplier; 0 means free", 0),
"status": catalogEnum("Account availability", "active", "inactive", "error"),
"expires_at": catalogInteger("Unix expiry timestamp in seconds; 0 removes expiry", 0, 253402300799),
"auto_pause_on_expired": catalogBool("Stop scheduling after expiry"),
})
accountUpdate["minProperties"] = 1
tools := []ToolSpec{
catalogTool("user_get_profile", "Get your profile, balance and account limits. Always uses the authenticated user.", "GET", "/user/profile", nil, nil),
catalogTool("user_get_platform_quotas", "Get your spending quota and usage windows for each platform.", "GET", "/user/platform-quotas", nil, nil),
catalogTool("user_list_groups", "List the groups available to your API keys, including platform and pricing information.", "GET", "/groups/available", nil, nil),
catalogTool("user_list_channels", "List channels and supported models visible to you. Returns an empty list when channel discovery is disabled.", "GET", "/channels/available", nil, nil),
catalogTool("user_list_api_keys", "List your API key metadata and limits with pagination. Existing key secrets are omitted.", "GET", "/keys", keyList, nil),
catalogTool("user_get_api_key", "Get one of your API keys by ID, including status and limits. The key secret is omitted.", "GET", "/keys/:id", nil, nil),
catalogTool("user_create_api_key", "Create an API key owned by you. Returns the newly created secret once in this tool result; store it securely.", "POST", "/keys", nil, keyCreate),
catalogTool("user_update_api_key", "Update one of your API keys. Only supplied fields change; disabling a key immediately blocks its use. Returns metadata without its secret.", "PUT", "/keys/:id", nil, keyUpdate),
catalogTool("user_delete_api_key", "Permanently delete one of your API keys. Applications using it will lose access. Returns the deletion result.", "DELETE", "/keys/:id", nil, nil),
catalogTool("user_list_usage", "List your request usage, tokens and costs with pagination and optional date, model and key filters.", "GET", "/usage", catalogPage(catalogUsageFields(false)), nil),
catalogTool("user_get_usage_stats", "Get aggregate request counts, token usage and costs for your account; defaults to the last seven days. Dates are inclusive YYYY-MM-DD.", "GET", "/usage/stats", catalogObject(catalogUsageFields(false)), nil),
catalogTool("user_get_dashboard", "Get your dashboard totals, request counts and spending summary.", "GET", "/usage/dashboard/stats", nil, nil),
catalogTool("user_list_subscriptions", "List your subscriptions, associated groups, validity and current usage.", "GET", "/subscriptions", nil, nil),
catalogTool("user_get_subscription_summary", "Get a summary of your active subscription limits and remaining allowance.", "GET", "/subscriptions/summary", nil, nil),
catalogTool("admin_get_dashboard", "Get platform-wide user/account counts, usage, spending and service uptime.", "GET", "/admin/dashboard/stats", nil, nil),
catalogTool("admin_list_users", "List platform users and account limits with pagination. May include contact information and administrator notes.", "GET", "/admin/users", catalogPage(map[string]any{
"search": catalogText("Search email or display name", 100),
"status": catalogEnum("User status", "active", "disabled"),
"role": catalogEnum("User role", "admin", "user"),
"group_name": catalogText("Search allowed group name", 100),
}), nil),
catalogTool("admin_get_user", "Get a platform user's profile, balance and limits by ID. Existing API key secrets are omitted.", "GET", "/admin/users/:id", nil, nil),
catalogTool("admin_update_user", "Update a user's display name, notes, limits, status or group access. Does not change passwords, roles or identity bindings. Returns the updated user.", "PUT", "/admin/users/:id", nil, userUpdate),
catalogTool("admin_update_user_balance", "Set, add to or subtract from a user's balance in USD. This changes real billing credit; verify the user, amount and operation before calling. Returns the updated result.", "POST", "/admin/users/:id/balance", nil, catalogObject(map[string]any{
"balance": map[string]any{"type": "number", "exclusiveMinimum": 0, "description": "Positive amount in USD"},
"operation": catalogEnum("How to apply the amount", "set", "add", "subtract"),
"notes": catalogText("Reason for the balance adjustment", 2000),
}, "balance", "operation", "notes")),
catalogTool("admin_list_groups", "List platform groups, pricing multipliers and status with pagination.", "GET", "/admin/groups", catalogPage(map[string]any{
"search": catalogText("Search group name", 100), "platform": catalogText("Platform identifier", 64),
"status": catalogEnum("Group status", "active", "inactive"), "is_exclusive": catalogBool("Filter exclusive groups"),
}), nil),
catalogTool("admin_get_group", "Get one group's configuration and model allowlist by ID.", "GET", "/admin/groups/:id", nil, nil),
catalogTool("admin_create_group", "Create a platform group with explicit platform and price multiplier. Returns the group; attach upstream accounts in the web console before serving traffic.", "POST", "/admin/groups", nil, groupCreate),
catalogTool("admin_update_group", "Update group name, pricing, spending limits, availability or model allowlist. Changes affect every user of this group. Only supplied fields change.", "PUT", "/admin/groups/:id", nil, groupUpdate),
catalogTool("admin_delete_group", "Delete a platform group. This can disrupt API keys and subscriptions associated with it. Returns the deletion result or a dependency error.", "DELETE", "/admin/groups/:id", nil, nil),
catalogTool("admin_list_accounts", "List upstream account metadata, status and scheduling settings with pagination. Credentials are omitted.", "GET", "/admin/accounts", catalogPage(map[string]any{
"search": catalogText("Search account name", 100), "platform": catalogText("Platform identifier", 64),
"status": catalogEnum("Account status", "active", "inactive", "error", "rate_limited", "temp_unschedulable", "unschedulable"),
"type": catalogEnum("Upstream authentication type", "oauth", "setup-token", "apikey", "upstream", "bedrock", "service_account"),
"group": catalogID("Group ID"), "lite": catalogBool("Request a lightweight account list"),
}), nil),
catalogTool("admin_get_account", "Get one upstream account's metadata and runtime status. Credentials are omitted.", "GET", "/admin/accounts/:id", nil, nil),
catalogTool("admin_update_account", "Update upstream account name, notes, concurrency, priority, cost multiplier, status or expiry. Does not accept credentials or network settings.", "PUT", "/admin/accounts/:id", nil, accountUpdate),
catalogTool("admin_set_account_schedulable", "Enable or disable scheduling for an upstream account. Disabling prevents selection for new requests. Returns updated account metadata.", "POST", "/admin/accounts/:id/schedulable", nil, catalogObject(map[string]any{
"schedulable": catalogBool("Whether the scheduler may select this account"),
}, "schedulable")),
catalogTool("admin_clear_account_error", "Clear an upstream account's error state so it can recover. Investigate and fix the cause first. Returns the recovery result.", "POST", "/admin/accounts/:id/clear-error", nil, nil),
catalogTool("admin_list_usage", "List platform-wide request usage, tokens and costs with pagination. Filter by user, account, group, model or inclusive date range.", "GET", "/admin/usage", catalogPage(catalogUsageFields(true)), nil),
catalogTool("admin_get_usage_stats", "Get platform-wide aggregate usage and costs; defaults to today. Both start_date and end_date should be supplied for a custom range.", "GET", "/admin/usage/stats", catalogObject(catalogUsageFields(true)), nil),
catalogTool("admin_list_subscriptions", "List platform subscriptions and their user/group associations, expiry and quota usage with pagination.", "GET", "/admin/subscriptions", catalogPage(map[string]any{
"user_id": catalogID("User ID"), "group_id": catalogID("Group ID"),
"status": catalogEnum("Subscription status", "active", "expired", "revoked"), "platform": catalogText("Platform identifier", 64),
}), nil),
catalogTool("admin_get_subscription", "Get one platform subscription and its user/group association by ID.", "GET", "/admin/subscriptions/:id", nil, nil),
catalogTool("admin_assign_subscription", "Assign a subscription group to a user for the specified number of days. An existing subscription may be extended; do not retry blindly. Returns the resulting subscription.", "POST", "/admin/subscriptions/assign", nil, catalogObject(map[string]any{
"user_id": catalogID("Recipient user ID"), "group_id": catalogID("Subscription group ID"),
"validity_days": catalogInteger("Validity in days", 1, 36500), "notes": catalogText("Assignment notes", 2000),
}, "user_id", "group_id", "validity_days")),
catalogTool("admin_extend_subscription", "Extend a subscription by the specified positive number of days. Changes billing entitlement; returns the updated subscription.", "POST", "/admin/subscriptions/:id/extend", nil, catalogObject(map[string]any{
"days": catalogInteger("Additional validity in days", 1, 36500),
}, "days")),
catalogTool("admin_revoke_subscription", "Revoke a subscription immediately. The user loses the associated entitlement. Returns the revocation result.", "POST", "/admin/subscriptions/:id/revoke", nil, nil),
catalogTool("admin_get_ops_overview", "Get platform operational health, traffic, latency and error overview for troubleshooting.", "GET", "/admin/ops/dashboard/overview", nil, nil),
}
for i := range tools {
if tools[i].Name == "user_create_api_key" {
tools[i].RevealCreatedKey = true
}
// Creation does not remove or overwrite existing state. Subscription
// assignment is deliberately excluded because it may extend an existing one.
if tools[i].Name == "user_create_api_key" || tools[i].Name == "admin_create_group" {
tools[i].Destructive = false
}
}
return tools
}
func catalogTool(name, description, method, path string, query, body map[string]any) ToolSpec {
properties := map[string]any{}
required := []string{}
if strings.Contains(path, ":id") {
properties["id"] = catalogID("Resource ID")
required = append(required, "id")
}
if query != nil {
properties["query"] = query
}
if body != nil {
properties["body"] = body
required = append(required, "body")
}
// These existing routes require an idempotency key. Keep retries within
// their established coordinator rather than inventing MCP-side settlement.
switch name {
case "user_create_api_key", "admin_update_user_balance", "admin_extend_subscription":
properties["idempotency_key"] = map[string]any{
"type": "string", "minLength": 1, "maxLength": 128, "pattern": "^[!-~]+$",
"description": "Unique operation ID (for example a UUID). Reuse the same value and arguments when retrying this operation; use a new value for a new intended operation.",
}
required = append(required, "idempotency_key")
}
return ToolSpec{
Name: name, Description: description, Method: method, Path: "/api/v1" + path,
Admin: strings.HasPrefix(path, "/admin/"), ReadOnly: method == "GET",
Destructive: method != "GET", InputSchema: catalogObject(properties, required...),
}
}
func catalogObject(properties map[string]any, required ...string) map[string]any {
schema := map[string]any{"type": "object", "properties": properties, "additionalProperties": false}
if len(required) > 0 {
schema["required"] = required
}
return schema
}
func catalogText(description string, maxLength int) map[string]any {
return map[string]any{"type": "string", "description": description, "maxLength": maxLength}
}
func catalogNonemptyText(description string, maxLength int) map[string]any {
schema := catalogText(description, maxLength)
schema["minLength"] = 1
return schema
}
func catalogEnum(description string, values ...string) map[string]any {
return map[string]any{"type": "string", "description": description, "enum": values}
}
func catalogInteger(description string, min, max int64) map[string]any {
return map[string]any{"type": "integer", "description": description, "minimum": min, "maximum": max}
}
func catalogID(description string) map[string]any {
return catalogInteger(description, 1, 9007199254740991)
}
func catalogNumber(description string, min float64) map[string]any {
return map[string]any{"type": "number", "description": description, "minimum": min}
}
func catalogBool(description string) map[string]any {
return map[string]any{"type": "boolean", "description": description}
}
func catalogStrings(description string, maxItems, maxLength int) map[string]any {
return map[string]any{"type": "array", "description": description, "items": catalogNonemptyText("Value", maxLength), "maxItems": maxItems}
}
func catalogIDs(description string) map[string]any {
return map[string]any{"type": "array", "description": description, "items": catalogID("Resource ID"), "maxItems": 100, "uniqueItems": true}
}
func catalogPage(fields map[string]any) map[string]any {
fields["page"] = catalogInteger("Page number, starting at 1", 1, 1000000)
fields["page_size"] = catalogInteger("Results per page; at most 100", 1, 100)
return catalogObject(fields)
}
func catalogUsageFields(admin bool) map[string]any {
fields := map[string]any{
"api_key_id": catalogID("Filter by API key ID"), "group_id": catalogID("Filter by group ID"),
"model": catalogText("Filter by requested model", 200),
"start_date": map[string]any{"type": "string", "description": "Inclusive start date (YYYY-MM-DD)", "pattern": `^\d{4}-\d{2}-\d{2}$`},
"end_date": map[string]any{"type": "string", "description": "Inclusive end date (YYYY-MM-DD)", "pattern": `^\d{4}-\d{2}-\d{2}$`},
"timezone": catalogText("IANA time zone, for example Asia/Shanghai or UTC", 100),
"period": catalogEnum("Stats date range when explicit dates are omitted", "today", "week", "month"),
"stream": catalogBool("Filter streaming or non-streaming requests"),
}
if admin {
fields["user_id"] = catalogID("Filter by user ID")
fields["account_id"] = catalogID("Filter by upstream account ID")
}
return fields
}
func catalogGroupFields() map[string]any {
return map[string]any{
"name": catalogNonemptyText("Group name", 100), "description": catalogText("Group description", 2000),
"rate_multiplier": map[string]any{"type": "number", "exclusiveMinimum": 0, "description": "Positive user billing multiplier; 1 is standard pricing"},
"is_exclusive": catalogBool("Limit access to users explicitly assigned this group"),
"subscription_type": catalogEnum("Group billing mode", "standard", "subscription"),
"daily_limit_usd": catalogNumber("Daily subscription spending limit in USD; -1 means unlimited", -1),
"weekly_limit_usd": catalogNumber("Weekly subscription spending limit in USD; -1 means unlimited", -1),
"monthly_limit_usd": catalogNumber("Monthly subscription spending limit in USD; -1 means unlimited", -1),
"rpm_limit": catalogInteger("Requests per minute; 0 means unlimited", 0, 1000000),
"model_allowlist": catalogObject(map[string]any{
"enabled": catalogBool("Enable the model allowlist; an enabled list must contain at least one model"),
"models": catalogStrings("Allowed upstream model IDs or patterns containing *", 1000, 200),
}, "enabled", "models"),
}
}
@@ -0,0 +1,168 @@
package managementmcp
import (
"encoding/json"
"regexp"
"slices"
"strings"
"testing"
)
func TestToolCatalogRouteAndSchemaBoundaries(t *testing.T) {
names := map[string]bool{}
for _, spec := range ToolCatalog() {
t.Run(spec.Name, func(t *testing.T) {
if names[spec.Name] || !regexp.MustCompile(`^(user|admin)_[a-z0-9_]+$`).MatchString(spec.Name) {
t.Fatalf("duplicate or invalid tool name: %q", spec.Name)
}
names[spec.Name] = true
if spec.Description == "" || !slices.Contains([]string{"GET", "POST", "PUT", "DELETE"}, spec.Method) {
t.Fatal("tool must have a description and supported method")
}
if !strings.HasPrefix(spec.Path, "/api/v1/") || strings.ContainsAny(spec.Path, "?*#") || strings.Contains(spec.Path, "..") {
t.Fatalf("route must be a fixed local API path: %q", spec.Path)
}
if spec.Admin != strings.HasPrefix(spec.Path, "/api/v1/admin/") || spec.Admin != strings.HasPrefix(spec.Name, "admin_") {
t.Fatal("tool role does not match its route")
}
if spec.ReadOnly != (spec.Method == "GET") || (spec.ReadOnly && spec.Destructive) {
t.Fatal("tool mutability metadata does not match its route")
}
checkCatalogSchema(t, spec.InputSchema)
properties, ok := spec.InputSchema["properties"].(map[string]any)
if !ok {
t.Fatal("input schema properties must be an object")
}
required, _ := spec.InputSchema["required"].([]string)
for name := range properties {
if !slices.Contains([]string{"id", "query", "body", "idempotency_key"}, name) {
t.Fatalf("unexpected top-level field %q", name)
}
}
pathParameters := regexp.MustCompile(`:([a-z_]+)`).FindAllStringSubmatch(spec.Path, -1)
for _, match := range pathParameters {
if match[1] != "id" || !slices.Contains(required, match[1]) {
t.Fatalf("path parameter %q must be a required ID", match[1])
}
}
if _, exists := properties["id"]; exists != (len(pathParameters) > 0) {
t.Fatal("ID input and route placeholder disagree")
}
if body, exists := properties["body"]; exists {
bodySchema, ok := body.(map[string]any)
if !ok || spec.ReadOnly || !slices.Contains(required, "body") || bodySchema["type"] != "object" {
t.Fatal("write bodies must be required objects")
}
}
if query, exists := properties["query"].(map[string]any); exists {
queryFields, ok := query["properties"].(map[string]any)
if !ok {
t.Fatal("query schema properties must be an object")
}
if size, exists := queryFields["page_size"].(map[string]any); exists && size["maximum"] != int64(100) {
t.Fatal("list page size must be bounded to 100")
}
if !spec.Admin {
for _, name := range []string{"user_id", "account_id"} {
if _, exists := queryFields[name]; exists {
t.Fatalf("user tool accepts cross-user filter %q", name)
}
}
}
}
if _, err := json.Marshal(spec.InputSchema); err != nil {
t.Fatalf("schema is not JSON: %v", err)
}
})
}
}
func checkCatalogSchema(t *testing.T, schema map[string]any) {
t.Helper()
switch schema["type"] {
case "object":
if schema["additionalProperties"] != false {
t.Fatal("all objects must reject unknown fields")
}
properties, ok := schema["properties"].(map[string]any)
if !ok {
t.Fatal("object lacks explicit properties")
}
for name, field := range properties {
child, ok := field.(map[string]any)
if !ok {
t.Fatalf("field %q lacks a typed schema", name)
}
checkCatalogSchema(t, child)
}
if required, ok := schema["required"].([]string); ok {
for _, name := range required {
if _, exists := properties[name]; !exists {
t.Fatalf("required field %q is not declared", name)
}
}
}
case "array":
child, ok := schema["items"].(map[string]any)
if !ok || schema["maxItems"] == nil {
t.Fatal("arrays must have typed items and size limits")
}
checkCatalogSchema(t, child)
case "integer", "number", "string", "boolean":
default:
t.Fatalf("unsupported or missing schema type: %v", schema["type"])
}
}
func TestToolCatalogDoesNotExposeCredentialOrIdentityManagement(t *testing.T) {
for _, spec := range ToolCatalog() {
if spec.RevealCreatedKey != (spec.Name == "user_create_api_key") {
t.Fatalf("unexpected secret disclosure policy for %s", spec.Name)
}
for _, forbidden := range []string{"admin-api-key", "/auth", "/password", "/totp", "/passkeys", "/payment", "/backup", "/data"} {
if strings.Contains(spec.Path, forbidden) {
t.Fatalf("%s exposes sensitive route %s", spec.Name, spec.Path)
}
}
properties := catalogTestObject(t, spec.InputSchema["properties"])
if body, ok := properties["body"].(map[string]any); ok {
fields := catalogTestObject(t, body["properties"])
for _, forbidden := range []string{"credentials", "extra", "password", "role", "email", "custom_key", "proxy_id", "url"} {
if _, exists := fields[forbidden]; exists {
t.Fatalf("%s accepts sensitive field %s", spec.Name, forbidden)
}
}
}
}
}
func TestToolCatalogSchemasAreIndependent(t *testing.T) {
first := ToolCatalog()
first[0].InputSchema["additionalProperties"] = true
for _, spec := range first {
if spec.Name == "admin_create_group" {
body := catalogTestObject(t, catalogTestObject(t, spec.InputSchema["properties"])["body"])
catalogTestObject(t, body["properties"])["password"] = catalogText("Unexpected", 100)
}
}
for _, spec := range ToolCatalog() {
if spec.InputSchema["additionalProperties"] != false {
t.Fatal("catalog calls share schema state")
}
if spec.Name == "admin_update_group" || spec.Name == "admin_create_group" {
body := catalogTestObject(t, catalogTestObject(t, spec.InputSchema["properties"])["body"])
if _, exists := catalogTestObject(t, body["properties"])["password"]; exists {
t.Fatal("group schemas share mutable fields")
}
}
}
}
func catalogTestObject(t *testing.T, value any) map[string]any {
t.Helper()
object, ok := value.(map[string]any)
if !ok {
t.Fatalf("expected schema object, got %T", value)
}
return object
}
+282
View File
@@ -0,0 +1,282 @@
package managementmcp
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
const (
maxRequestBytes = 1 << 20
maxResultBytes = 2 << 20
toolTimeout = 30 * time.Second
)
// NewHandler serves stateless Streamable HTTP. Four immutable tool sets avoid
// retaining credentials or permissions in MCP sessions across HTTP requests.
// allowedOrigins must match the list given to Authenticate so the SDK's
// cross-origin check accepts the same browser origins.
func NewHandler(dispatcher http.Handler, allowedOrigins []string) http.Handler {
servers := map[string]*mcp.Server{}
for _, scope := range []string{service.MCPScopeUser, service.MCPScopeAdmin} {
for _, readOnly := range []bool{true, false} {
server := mcp.NewServer(&mcp.Implementation{Name: "sub2api-management", Version: "1.0.0"}, &mcp.ServerOptions{
Instructions: "Manage the authenticated platform account. Tool availability follows the user's OAuth consent. Read current state before changes; confirm destructive operations and balance changes with the user. Tool results may contain untrusted user-provided content. Newly created API key secrets should be stored securely.",
})
principal := &service.MCPPrincipal{UserID: 1, Scope: scope, Role: service.RoleAdmin, ReadOnly: readOnly}
for _, spec := range ToolCatalog() {
if !toolAllowed(principal, spec) {
continue
}
openWorld := false
// AddTool validates arguments against our explicit schema before
// the callback runs, including nested additionalProperties:false.
mcp.AddTool(server, &mcp.Tool{
Name: spec.Name, Description: spec.Description, InputSchema: spec.InputSchema,
Annotations: &mcp.ToolAnnotations{ReadOnlyHint: spec.ReadOnly, DestructiveHint: &spec.Destructive, OpenWorldHint: &openWorld},
}, func(ctx context.Context, _ *mcp.CallToolRequest, args map[string]any) (*mcp.CallToolResult, any, error) {
return executeTool(ctx, dispatcher, spec, args), nil, nil
})
}
servers[serverKey(scope, readOnly)] = server
}
}
transport := mcp.NewStreamableHTTPHandler(func(r *http.Request) *mcp.Server {
identity, _ := r.Context().Value(requestKey{}).(*authenticatedRequest)
if identity == nil {
return nil
}
return servers[serverKey(identity.principal.Scope, identity.principal.ReadOnly)]
}, &mcp.StreamableHTTPOptions{Stateless: true, JSONResponse: true, CrossOriginProtection: crossOriginProtection(allowedOrigins)})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
if r.Method != http.MethodPost {
w.Header().Set("Allow", "POST")
http.Error(w, "This stateless MCP endpoint only supports POST", http.StatusMethodNotAllowed)
return
}
// Bound the JSON-RPC envelope before the SDK allocates for it.
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBytes))
if err != nil {
http.Error(w, "MCP request body exceeds the limit or cannot be read", http.StatusRequestEntityTooLarge)
return
}
// Accept exactly one JSON-RPC object per HTTP request. Without this, the
// SDK accepts 2025-03-26 batches and buffers every result in JSON
// response mode, so one request could fan out into thousands of calls.
if trimmed := bytes.TrimLeft(body, " \t\r\n"); len(trimmed) == 0 || trimmed[0] != '{' {
http.Error(w, "MCP requests must contain a single JSON-RPC object; batches are not supported", http.StatusBadRequest)
return
}
// The SDK compares Content-Type verbatim; accept JSON with parameters such
// as charset, while form and text bodies are still refused.
if mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mediaType != "application/json" {
http.Error(w, "Content-Type must be 'application/json'", http.StatusUnsupportedMediaType)
return
}
r.Header.Set("Content-Type", "application/json")
r.Body = io.NopCloser(bytes.NewReader(body))
transport.ServeHTTP(noStoreResponse{w}, r)
})
}
// crossOriginProtection trusts the origins Authenticate accepts. Wildcard CORS
// does not relax MCP origin validation, so "*" is never trusted here either.
func crossOriginProtection(allowedOrigins []string) *http.CrossOriginProtection {
protection := http.NewCrossOriginProtection()
for _, origin := range allowedOrigins {
origin = strings.TrimSpace(origin)
if origin == "" || origin == "*" {
continue
}
// Authenticate matches origins verbatim, so malformed entries never match there either.
_ = protection.AddTrustedOrigin(origin)
}
return protection
}
func serverKey(scope string, readOnly bool) string { return scope + ":" + strconv.FormatBool(readOnly) }
func executeTool(ctx context.Context, dispatcher http.Handler, spec ToolSpec, args map[string]any) *mcp.CallToolResult {
identity, _ := ctx.Value(requestKey{}).(*authenticatedRequest)
if identity == nil || !toolAllowed(identity.principal, spec) {
return toolError("MCP operation is not allowed")
}
// SDK transports may detach the handler context. Explicitly retain HTTP
// disconnect cancellation and bound database work for each invocation.
ctx, cancel := context.WithTimeout(ctx, toolTimeout)
defer cancel()
stop := context.AfterFunc(identity.request.Context(), cancel)
defer stop()
if identity.request.Context().Err() != nil {
return toolError("MCP request was cancelled")
}
path := spec.Path
if strings.Contains(path, ":id") {
id, ok := args["id"].(float64)
if !ok || id < 1 || id > 9007199254740991 || id != float64(int64(id)) {
return toolError("id must be a positive safe integer")
}
path = strings.ReplaceAll(path, ":id", strconv.FormatInt(int64(id), 10))
}
query := url.Values{}
if values, ok := args["query"].(map[string]any); ok {
for key, value := range values {
if number, ok := value.(float64); ok {
// REST filters use ParseInt; %v switches large IDs to exponent notation.
query.Set(key, strconv.FormatFloat(number, 'f', -1, 64))
} else {
query.Set(key, fmt.Sprint(value))
}
}
}
var body []byte
if value, exists := args["body"]; exists {
var err error
body, err = json.Marshal(value)
if err != nil {
return toolError("Cannot encode tool arguments")
}
}
ctx = context.WithValue(ctx, dispatchKey{}, spec)
req := identity.request.Clone(ctx)
req.Method = spec.Method
req.URL = &url.URL{Path: path, RawQuery: query.Encode()}
req.RequestURI = req.URL.RequestURI()
req.Body = io.NopCloser(bytes.NewReader(body))
req.ContentLength = int64(len(body))
// No cookies, browser JWTs, forwarded headers or other credentials enter
// the private router. The outer security IP snapshot remains in context.
req.Header = http.Header{"Content-Type": {"application/json"}, "User-Agent": {identity.request.UserAgent()}}
if key, ok := args["idempotency_key"].(string); ok {
// Scope retries to this credential so another integration cannot replay
// a previous client's cached creation result by guessing its operation ID.
hash := sha256.Sum256([]byte(identity.principal.GrantID + ":" + key))
req.Header.Set("Idempotency-Key", fmt.Sprintf("mcp-%x", hash))
}
response := &boundedResponse{header: make(http.Header)}
dispatcher.ServeHTTP(response, req)
if response.overflow {
return toolError("Result exceeds 2 MiB; narrow the query or reduce page_size")
}
if ctx.Err() != nil {
return toolError("MCP operation was cancelled or timed out; check current state before retrying a write")
}
var result any
decoder := json.NewDecoder(bytes.NewReader(response.body.Bytes()))
decoder.UseNumber()
if decoder.Decode(&result) != nil {
return toolError(fmt.Sprintf("Management API returned HTTP %d without a JSON result", response.status))
}
redactResult(result, spec.RevealCreatedKey && response.status >= 200 && response.status < 300, "")
encoded, err := json.Marshal(map[string]any{"http_status": response.status, "result": result})
if err != nil {
return toolError("Cannot encode management result")
}
// Re-encoding can expand escaped characters, so bound the final payload.
// The result is returned once, as text: tools declare no output schema.
if len(encoded) > maxResultBytes {
return toolError("Result exceeds 2 MiB; narrow the query or reduce page_size")
}
return &mcp.CallToolResult{
Content: []mcp.Content{&mcp.TextContent{Text: string(encoded)}},
IsError: response.status < 200 || response.status >= 300,
}
}
func toolError(message string) *mcp.CallToolResult {
return &mcp.CallToolResult{IsError: true, Content: []mcp.Content{&mcp.TextContent{Text: message}}}
}
// The SDK sets no-cache for transport frames; management results may contain a
// newly created key, so force no-store at the actual response boundary.
type noStoreResponse struct{ http.ResponseWriter }
func (w noStoreResponse) WriteHeader(status int) {
w.Header().Set("Cache-Control", "no-store")
w.ResponseWriter.WriteHeader(status)
}
func (w noStoreResponse) Write(p []byte) (int, error) {
w.Header().Set("Cache-Control", "no-store")
return w.ResponseWriter.Write(p)
}
func (w noStoreResponse) Flush() {
w.Header().Set("Cache-Control", "no-store")
_ = http.NewResponseController(w.ResponseWriter).Flush()
}
func (w noStoreResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter }
// redactedResultKeys derives from the authoritative credential table so new
// upstream secret kinds are removed from tool results without a second list.
var redactedResultKeys = func() map[string]struct{} {
keys := map[string]struct{}{}
for _, key := range append([]string{
"credentials", "password_hash", "session_token", "client_secret", "secret",
"totp_secret", "totp_secret_encrypted",
}, service.SensitiveCredentialKeys...) {
keys[strings.ToLower(key)] = struct{}{}
}
return keys
}()
func redactResult(value any, revealCreatedKey bool, path string) {
switch v := value.(type) {
case map[string]any:
for key, child := range v {
childPath := path + "/" + key
lower := strings.ToLower(key)
if lower == "key" && (!revealCreatedKey || childPath != "/data/key") {
delete(v, key)
continue
}
if _, sensitive := redactedResultKeys[lower]; sensitive {
delete(v, key)
continue
}
redactResult(child, revealCreatedKey, childPath)
}
case []any:
for _, child := range v {
redactResult(child, false, path+"/[]")
}
}
}
// boundedResponse captures only a bounded JSON response from the in-process
// router, never a network hop. Writes beyond the cap are discarded.
type boundedResponse struct {
header http.Header
status int
body bytes.Buffer
overflow bool
}
func (w *boundedResponse) Header() http.Header { return w.header }
func (w *boundedResponse) WriteHeader(status int) {
if w.status == 0 {
w.status = status
}
}
func (w *boundedResponse) Write(p []byte) (int, error) {
if w.status == 0 {
w.status = http.StatusOK
}
if w.body.Len()+len(p) > maxResultBytes {
w.overflow = true
} else if !w.overflow {
_, _ = w.body.Write(p)
}
return len(p), nil
}
@@ -0,0 +1,445 @@
package managementmcp
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type testTokenAuth struct {
mu sync.Mutex
principals map[string]*service.MCPPrincipal
}
func (a *testTokenAuth) Authenticate(_ context.Context, token string) (*service.MCPPrincipal, error) {
a.mu.Lock()
defer a.mu.Unlock()
if p := a.principals[token]; p != nil {
copy := *p
if copy.Resource == "" {
copy.Resource = "https://platform.example/api/v1/mcp"
}
return &copy, nil
}
return nil, service.ErrMCPOAuthInvalidToken
}
func newTestEndpoint(dispatcher http.Handler) (*gin.Engine, *testTokenAuth) {
gin.SetMode(gin.TestMode)
auth := &testTokenAuth{principals: map[string]*service.MCPPrincipal{
"reader": {UserID: 1, GrantID: "one", Role: service.RoleUser, Scope: service.MCPScopeUser, ReadOnly: true},
"writer": {UserID: 1, GrantID: "two", Role: service.RoleUser, Scope: service.MCPScopeUser},
"other": {UserID: 2, GrantID: "three", Role: service.RoleUser, Scope: service.MCPScopeUser},
"admin": {UserID: 3, GrantID: "four", Role: service.RoleAdmin, Scope: service.MCPScopeAdmin},
"admin-reader": {UserID: 3, GrantID: "five", Role: service.RoleAdmin, Scope: service.MCPScopeAdmin, ReadOnly: true},
}}
r := gin.New()
r.Any("/api/v1/mcp", Authenticate(auth, []string{"https://console.example"}, func(context.Context) (string, error) {
return "https://platform.example/api/v1/mcp", nil
}), gin.WrapH(NewHandler(dispatcher, []string{"https://console.example"})))
return r, auth
}
func rpc(t *testing.T, handler http.Handler, token, method string, params any) (int, map[string]any) {
t.Helper()
body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 1, "method": method, "params": params})
require.NoError(t, err)
req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("MCP-Protocol-Version", "2025-06-18")
w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
var result map[string]any
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result), w.Body.String())
require.Equal(t, "no-store", w.Header().Get("Cache-Control"))
return w.Code, result
}
func rpcObject(t *testing.T, value any) map[string]any {
t.Helper()
object, ok := value.(map[string]any)
require.True(t, ok, "expected JSON object, got %T", value)
return object
}
func toolNames(t *testing.T, result map[string]any) []string {
t.Helper()
var names []string
tools, ok := rpcObject(t, result["result"])["tools"].([]any)
require.True(t, ok)
for _, tool := range tools {
name, ok := rpcObject(t, tool)["name"].(string)
require.True(t, ok)
names = append(names, name)
}
return names
}
func TestMCPInitializeAndPermissionFilteredDiscovery(t *testing.T) {
r, _ := newTestEndpoint(http.NotFoundHandler())
status, initialized := rpc(t, r, "reader", "initialize", map[string]any{
"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{"name": "test", "version": "1"},
})
require.Equal(t, 200, status)
require.Equal(t, "sub2api-management", rpcObject(t, rpcObject(t, initialized["result"])["serverInfo"])["name"])
for _, tc := range []struct {
token string
hasAdmin, hasWrite bool
}{
{"reader", false, false}, {"writer", false, true}, {"admin", true, true}, {"admin-reader", true, false},
} {
t.Run(tc.token, func(t *testing.T) {
status, listed := rpc(t, r, tc.token, "tools/list", map[string]any{})
require.Equal(t, 200, status)
names := toolNames(t, listed)
// Verify the permission boundary, not an exact catalogue size.
require.Contains(t, names, "user_get_profile")
if tc.hasAdmin {
require.Contains(t, names, "admin_get_dashboard")
} else {
require.NotContains(t, names, "admin_get_dashboard")
}
if tc.hasWrite {
require.Contains(t, names, "user_create_api_key")
} else {
require.NotContains(t, names, "user_create_api_key")
}
})
}
}
func TestMCPRejectsUnauthorizedToolsAndUnknownArgumentsBeforeDispatch(t *testing.T) {
calls := 0
r, _ := newTestEndpoint(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ }))
for _, tc := range []struct {
token, name string
args any
}{
{"reader", "user_create_api_key", map[string]any{"body": map[string]any{"name": "test"}}},
{"writer", "admin_list_users", map[string]any{}},
{"writer", "user_get_api_key", map[string]any{"id": "../admin/users"}},
{"writer", "user_get_api_key", map[string]any{"id": -1}},
{"writer", "user_list_api_keys", map[string]any{"query": map[string]any{"user_id": 2}}},
{"writer", "user_list_api_keys", map[string]any{"query": map[string]any{"page_size": 101}}},
{"writer", "user_create_api_key", map[string]any{"body": map[string]any{"name": "test", "user_id": 2}}},
{"admin", "admin_update_user", map[string]any{"id": 2, "body": map[string]any{"role": "admin"}}},
{"admin", "admin_update_account", map[string]any{"id": 2, "body": map[string]any{"credentials": map[string]any{"api_key": "x"}}}},
} {
_, result := rpc(t, r, tc.token, "tools/call", map[string]any{"name": tc.name, "arguments": tc.args})
require.Contains(t, result, "error", tc.name)
}
require.Zero(t, calls)
}
func TestMCPDispatchPreservesOwnershipAndRedactsExistingSecrets(t *testing.T) {
inner := gin.New()
inner.GET("/api/v1/keys/:id", DispatchAuth(false), func(c *gin.Context) {
subject, ok := middleware.GetAuthSubjectFromContext(c)
require.True(t, ok)
require.Empty(t, c.GetHeader("Authorization"))
require.Equal(t, AuthMethod, c.GetString("auth_method"))
if subject.UserID != 1 {
c.JSON(403, gin.H{"message": "Key belongs to another user"})
return
}
c.JSON(200, gin.H{"data": gin.H{"id": 7, "name": "key name", "key": "existing-secret", "usage": gin.H{"access_token": "nested-secret"}}})
})
inner.POST("/api/v1/keys", DispatchAuth(false), func(c *gin.Context) {
c.JSON(201, gin.H{"data": gin.H{"id": 8, "key": "new-secret", "group": gin.H{"key": "unrelated-secret"}}})
})
r, auth := newTestEndpoint(inner)
for _, token := range []string{"writer", "other"} {
_, result := rpc(t, r, token, "tools/call", map[string]any{"name": "user_get_api_key", "arguments": map[string]any{"id": 7}})
encoded, _ := json.Marshal(result)
require.NotContains(t, string(encoded), "existing-secret")
require.NotContains(t, string(encoded), "nested-secret")
if token == "other" {
require.Equal(t, true, rpcObject(t, result["result"])["isError"])
} else {
require.Contains(t, string(encoded), "key name")
}
}
_, created := rpc(t, r, "writer", "tools/call", map[string]any{"name": "user_create_api_key", "arguments": map[string]any{"idempotency_key": "create-test-1", "body": map[string]any{"name": "created"}}})
encoded, _ := json.Marshal(created)
require.Contains(t, string(encoded), "new-secret")
require.NotContains(t, string(encoded), "unrelated-secret")
// Tokens are verified on every HTTP request, including after initialization.
auth.mu.Lock()
delete(auth.principals, "writer")
auth.mu.Unlock()
status, _ := rpc(t, r, "writer", "tools/list", map[string]any{})
require.Equal(t, 401, status)
}
func TestMCPDispatchAuthCannotBeForgedOrUsedForAnotherRoute(t *testing.T) {
inner := gin.New()
inner.GET("/api/v1/user/mcp/grants", DispatchAuth(false), func(c *gin.Context) { t.Error("unexpected credential access") })
req := httptest.NewRequest("GET", "/api/v1/user/mcp/grants", nil)
req.Header.Set("Authorization", "Bearer writer")
w := httptest.NewRecorder()
inner.ServeHTTP(w, req)
require.Equal(t, 403, w.Code)
identity := &authenticatedRequest{principal: &service.MCPPrincipal{UserID: 1, Scope: "user"}, request: req}
ctx := context.WithValue(req.Context(), requestKey{}, identity)
ctx = context.WithValue(ctx, dispatchKey{}, ToolSpec{Path: "/api/v1/user/profile", Method: "GET", ReadOnly: true})
w = httptest.NewRecorder()
inner.ServeHTTP(w, req.WithContext(ctx))
require.Equal(t, 403, w.Code)
}
func TestMCPPreservesLargeIntegerQueryFilters(t *testing.T) {
var observed string
r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
observed = r.URL.Query().Get("group_id")
_, _ = w.Write([]byte(`{"data":[]}`))
}))
_, result := rpc(t, r, "writer", "tools/call", map[string]any{"name": "user_list_api_keys", "arguments": map[string]any{"query": map[string]any{"group_id": 12345678}}})
require.NotContains(t, result, "error")
require.Equal(t, "12345678", observed)
}
func TestMCPAccountStatusFiltersMatchManagementAPI(t *testing.T) {
gin.SetMode(gin.TestMode)
var observed []string
inner := gin.New()
inner.GET("/api/v1/admin/accounts", DispatchAuth(true), func(c *gin.Context) {
observed = append(observed, c.Query("status"))
c.JSON(http.StatusOK, gin.H{"data": []any{}})
})
r, _ := newTestEndpoint(inner)
for _, status := range []string{"active", "inactive", "error", "rate_limited", "temp_unschedulable", "unschedulable"} {
t.Run(status, func(t *testing.T) {
before := len(observed)
_, result := rpc(t, r, "admin-reader", "tools/call", map[string]any{
"name": "admin_list_accounts", "arguments": map[string]any{"query": map[string]any{"status": status}},
})
require.NotContains(t, result, "error")
require.Len(t, observed, before+1)
require.Equal(t, status, observed[before])
})
}
t.Run("reject unsupported overloaded filter", func(t *testing.T) {
before := len(observed)
_, result := rpc(t, r, "admin-reader", "tools/call", map[string]any{
"name": "admin_list_accounts", "arguments": map[string]any{"query": map[string]any{"status": "overloaded"}},
})
require.Contains(t, result, "error")
require.Len(t, observed, before, "unsupported status must be rejected before dispatch")
})
}
func TestMCPIdempotencyKeysAreRequiredAndIsolatedPerCredential(t *testing.T) {
var keys []string
r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
keys = append(keys, r.Header.Get("Idempotency-Key"))
_, _ = w.Write([]byte(`{"data":{}}`))
}))
args := map[string]any{"body": map[string]any{"name": "created"}}
_, missing := rpc(t, r, "writer", "tools/call", map[string]any{"name": "user_create_api_key", "arguments": args})
require.Contains(t, missing, "error")
require.Empty(t, keys)
args["idempotency_key"] = "intent-123"
for _, token := range []string{"writer", "writer", "other"} {
_, result := rpc(t, r, token, "tools/call", map[string]any{"name": "user_create_api_key", "arguments": args})
require.NotContains(t, result, "error")
}
require.Len(t, keys, 3)
require.NotEmpty(t, keys[0])
require.Equal(t, keys[0], keys[1])
require.NotEqual(t, keys[0], keys[2])
}
func TestMCPOriginAuthenticationAndRequestLimits(t *testing.T) {
r, _ := newTestEndpoint(http.NotFoundHandler())
for _, tc := range []struct {
origin, token string
size, status int
}{
{"https://attacker.example", "reader", 0, 403}, {"null", "reader", 0, 403},
{"https://console.example", "invalid", 0, 401}, {"", "", 0, 401},
{"https://platform.example", "reader", maxRequestBytes + 1, 413},
} {
req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(strings.Repeat("x", tc.size)))
req.Header.Set("Origin", tc.origin)
if tc.token != "" {
req.Header.Set("Authorization", "Bearer "+tc.token)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, tc.status, w.Code, tc.origin)
}
for _, method := range []string{"GET", "DELETE"} {
req := httptest.NewRequest(method, "http://platform.example/api/v1/mcp", nil)
req.Header.Set("Authorization", "Bearer reader")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 405, w.Code)
}
}
// The SDK's own cross-origin and Content-Type checks must agree with
// Authenticate: allowlisted browser origins and JSON with parameters succeed.
func TestMCPTransportAcceptsAuthenticatedOriginsAndJSONMediaTypes(t *testing.T) {
r, _ := newTestEndpoint(http.NotFoundHandler())
body := `{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}`
for _, tc := range []struct {
name, origin, site, contentType string
status int
}{
{"native", "", "", "application/json", 200},
{"same host", "https://platform.example", "same-origin", "application/json", 200},
{"allowlisted origin", "https://console.example", "cross-site", "application/json", 200},
{"allowlisted origin without fetch metadata", "https://console.example", "", "application/json", 200},
{"unlisted origin", "https://attacker.example", "cross-site", "application/json", 403},
{"json with charset", "", "", "application/json; charset=utf-8", 200},
{"text body", "", "", "text/plain", 415},
{"form body", "", "", "application/x-www-form-urlencoded", 415},
} {
req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer reader")
req.Header.Set("Content-Type", tc.contentType)
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("MCP-Protocol-Version", "2025-06-18")
if tc.origin != "" {
req.Header.Set("Origin", tc.origin)
}
if tc.site != "" {
req.Header.Set("Sec-Fetch-Site", tc.site)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, tc.status, w.Code, "%s: %s", tc.name, w.Body.String())
}
}
func TestMCPResultLimitAndCancellation(t *testing.T) {
r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(strings.Repeat("x", maxResultBytes+1)))
}))
_, result := rpc(t, r, "reader", "tools/call", map[string]any{"name": "user_get_profile", "arguments": map[string]any{}})
require.Equal(t, true, rpcObject(t, result["result"])["isError"])
started, finished := make(chan struct{}), make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
original := httptest.NewRequest("POST", "/api/v1/mcp", nil).WithContext(ctx)
identity := &authenticatedRequest{principal: &service.MCPPrincipal{UserID: 1, Scope: "user"}, request: original}
// Simulate an SDK context detached from the HTTP lifetime.
detached := context.WithValue(context.Background(), requestKey{}, identity)
go func() {
defer close(finished)
executeTool(detached, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
close(started)
<-r.Context().Done()
}), ToolSpec{Path: "/api/v1/user/profile", Method: "GET", ReadOnly: true}, nil)
}()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("dispatcher did not start")
}
cancel()
select {
case <-finished:
case <-time.After(time.Second):
t.Fatal("HTTP cancellation did not reach dispatcher")
}
}
func TestMCPRejectsJSONRPCBatchesBeforeDispatch(t *testing.T) {
calls := 0
r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls++
_, _ = w.Write([]byte(`{"data":{}}`))
}))
call := `{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"user_get_profile","arguments":{}}}`
list := `{"jsonrpc":"2.0","id":%d,"method":"tools/list"}`
batch := "[" + strings.Join([]string{fmt.Sprintf(call, 1), fmt.Sprintf(list, 2), fmt.Sprintf(call, 3)}, ",") + "]"
for _, tc := range []struct{ name, body, version string }{
// Without a protocol header the SDK assumes 2025-03-26, which allows batches.
{"legacy batch", batch, ""},
{"current batch", batch, "2025-06-18"},
{"whitespace batch", " \r\n\t" + batch, ""},
{"scalar", `"tools/list"`, ""},
{"empty", " ", ""},
} {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(tc.body))
req.Header.Set("Authorization", "Bearer admin")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
if tc.version != "" {
req.Header.Set("MCP-Protocol-Version", tc.version)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
require.Equal(t, "no-store", w.Header().Get("Cache-Control"))
})
}
require.Zero(t, calls)
// A single request without the protocol header is still served.
req := httptest.NewRequest("POST", "http://platform.example/api/v1/mcp", strings.NewReader(fmt.Sprintf(call, 1)))
req.Header.Set("Authorization", "Bearer admin")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.Equal(t, 1, calls)
}
func TestMCPToolResultIsReturnedOnceAndBoundedAfterEncoding(t *testing.T) {
payload := `{"data":{"name":"ok"}}`
r, _ := newTestEndpoint(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(payload))
}))
_, result := rpc(t, r, "reader", "tools/call", map[string]any{"name": "user_get_profile", "arguments": map[string]any{}})
toolResult := rpcObject(t, result["result"])
require.NotContains(t, toolResult, "structuredContent", "results must not be duplicated")
content, ok := toolResult["content"].([]any)
require.True(t, ok)
require.Len(t, content, 1)
text, ok := rpcObject(t, content[0])["text"].(string)
require.True(t, ok)
require.JSONEq(t, `{"http_status":200,"result":{"data":{"name":"ok"}}}`, text)
// Under the capture limit as received, but HTML escaping expands it 6x.
payload = `{"data":"` + strings.Repeat("<", maxResultBytes/3) + `"}`
_, result = rpc(t, r, "reader", "tools/call", map[string]any{"name": "user_get_profile", "arguments": map[string]any{}})
toolResult = rpcObject(t, result["result"])
require.Equal(t, true, toolResult["isError"])
encoded, _ := json.Marshal(toolResult)
require.Less(t, len(encoded), 1<<10)
}
func TestMCPRedactsEveryAuthoritativeCredentialKey(t *testing.T) {
data := map[string]any{"name": "visible"}
nested := map[string]any{}
for _, key := range service.SensitiveCredentialKeys {
data[key] = "canary-" + key
nested[strings.ToUpper(key)] = "canary-upper-" + key
}
data["credentials"] = map[string]any{"nested": nested}
data["items"] = []any{nested}
value := map[string]any{"data": data}
redactResult(value, false, "")
encoded, err := json.Marshal(value)
require.NoError(t, err)
require.NotContains(t, string(encoded), "canary")
require.Contains(t, string(encoded), "visible")
}
+20 -1
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net/http"
"net/netip"
"strconv"
"time"
@@ -25,6 +26,8 @@ const (
// RateLimitOptions 限流可选配置
type RateLimitOptions struct {
FailureMode RateLimitFailureMode
// IPv6PrefixBits 按网段(如 64)合并 IPv6 客户端计数,避免轮换同一分配内的地址绕过限流;0 表示按单个地址计数。
IPv6PrefixBits int
}
var rateLimitScript = redis.NewScript(`
@@ -120,6 +123,22 @@ func clientIPForRateLimit(c *gin.Context) string {
return c.ClientIP()
}
// rateLimitClientKey 把 IPv6 地址归并到指定前缀的网段;IPv4 与无法解析的值保持原样。
func rateLimitClientKey(ip string, ipv6PrefixBits int) string {
if ipv6PrefixBits <= 0 || ipv6PrefixBits >= 128 {
return ip
}
addr, err := netip.ParseAddr(ip)
if err != nil || !addr.Is6() || addr.Is4In6() {
return ip
}
prefix, err := addr.WithZone("").Prefix(ipv6PrefixBits)
if err != nil {
return ip
}
return prefix.String()
}
// Limit 返回速率限制中间件
// key: 限制类型标识
// limit: 时间窗口内最大请求数
@@ -136,7 +155,7 @@ func (r *RateLimiter) LimitWithOptions(key string, limit int, window time.Durati
}
return func(c *gin.Context) {
result, err := r.Allow(c.Request.Context(), key+":"+clientIPForRateLimit(c), limit, window)
result, err := r.Allow(c.Request.Context(), key+":"+rateLimitClientKey(clientIPForRateLimit(c), opts.IPv6PrefixBits), limit, window)
if err != nil {
log.Printf("[RateLimit] redis error: key=%s mode=%s err=%v", r.prefix+key, failureModeLabel(failureMode), err)
if failureMode == RateLimitFailClose {
@@ -224,3 +224,43 @@ func TestRateLimiterSuccessAndLimit(t *testing.T) {
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
}
func TestRateLimitClientKeyAggregatesIPv6Prefix(t *testing.T) {
require.Equal(t, "2001:db8:1:2::/64", rateLimitClientKey("2001:db8:1:2:aaaa:bbbb:cccc:dddd", 64))
require.Equal(t, "2001:db8:1:2::/64", rateLimitClientKey("2001:db8:1:2::1", 64))
require.Equal(t, "2001:db8:1:3::/64", rateLimitClientKey("2001:db8:1:3::1", 64))
require.Equal(t, "2001:db8:1:2::1", rateLimitClientKey("2001:db8:1:2::1", 0), "per-address keys stay the default")
for _, ip := range []string{"203.0.113.9", "::ffff:203.0.113.9", "not-an-ip", ""} {
require.Equal(t, ip, rateLimitClientKey(ip, 64))
}
}
func TestRateLimiterIPv6PrefixSharesOneBudget(t *testing.T) {
gin.SetMode(gin.TestMode)
callCounts := make(map[string]int64)
originalRun := rateLimitRun
rateLimitRun = func(ctx context.Context, client *redis.Client, key string, windowMillis int64) (int64, bool, error) {
callCounts[key]++
return callCounts[key], false, nil
}
t.Cleanup(func() { rateLimitRun = originalRun })
limiter := NewRateLimiter(redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}))
router := gin.New()
router.Use(limiter.LimitWithOptions("api", 1, time.Second, RateLimitOptions{IPv6PrefixBits: 64}))
router.GET("/test", func(c *gin.Context) { c.Status(http.StatusOK) })
for _, tc := range []struct {
addr string
status int
}{
{"[2001:db8::1]:1234", http.StatusOK},
{"[2001:db8::2]:1234", http.StatusTooManyRequests}, // same /64, rotated address
{"[2001:db8:0:1::1]:1234", http.StatusOK}, // different /64
} {
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.RemoteAddr = tc.addr
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, tc.status, rec.Code, tc.addr)
}
}
+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)
}
}
})
}
}
Loaded 100 of 359 files, more files were not shown because too many files have changed in this diff. Show more