mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
Merge remote-tracking branch 'upstream/main' into HEAD
This commit is contained in:
commit
9e8913876f
335 files changed
+30111
-728
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -133,6 +133,8 @@ deploy/docker-compose.override.yml
|
||||
.gocache/
|
||||
vite.config.js
|
||||
docs/*
|
||||
!docs/admin-api-keys.md
|
||||
!docs/mcp.md
|
||||
!docs/PAYMENT.md
|
||||
!docs/PAYMENT_CN.md
|
||||
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
|
||||
|
||||
@@ -31,6 +31,17 @@ Please read the following carefully before using this project:
|
||||
|
||||
> [Want to appear here?](mailto:support@sub2api.org)
|
||||
|
||||
<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>
|
||||
|
||||
**[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.
|
||||
|
||||
**Free trial credits**: sign up via [this exclusive link](https://wandapi.ai/r/sub2api) to claim free trial credits.
|
||||
|
||||
---
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
@@ -161,8 +172,20 @@ Please read the following carefully before using this project:
|
||||
<td>🔑 Buying AI accounts at top prices | Gemini · Claude · GPT | Main and alt accounts all welcome, any channel wanted | Pay-per-usage supported | Seeking first-hand resources from major providers, I'll bring the KEY.<br>WeChat: Liuyou-zawd | Telegram: <a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
|
||||
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> provides affordable global proxy solutions for web scraping, AI agents, automation, and data collection. With residential proxies starting at $0.35/GB across 190+ countries and regions, NiuProxy offers flexible plans and HTTP(S)/SOCKS5 support.<br>🎁 Use code PAY2 for 10% OFF your recharge!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
|
||||
<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>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## Overview
|
||||
|
||||
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
|
||||
|
||||
@@ -32,6 +32,17 @@
|
||||
|
||||
> [想出现在这里?](mailto:support@sub2api.org)
|
||||
|
||||
<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>
|
||||
|
||||
**[WandAPI](https://wandapi.ai/r/sub2api)** —— 由该项目核心贡献者打造的企业级稳定 AI 大模型 API 网关。一个 API Key 即可调用 Claude、GPT、Gemini 等主流模型,原生兼容 OpenAI 与 Anthropic 协议,Claude Code、Codex 及现有 SDK 只需修改 Base URL 即可接入。按延迟与上游健康度实时路由,毫秒级自动故障切换,请求不掉线;服务可用性达 99.99%。按量计费,每次请求的 token 与费用明细清晰可查。
|
||||
|
||||
**免费试用额度**:通过[专属链接](https://wandapi.ai/r/sub2api)注册,即可领取免费试用额度。
|
||||
|
||||
---
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
@@ -164,8 +175,20 @@
|
||||
<td>🔑 高价收 AI 账号|Gemini · Claude · GPT|大小号通收,各种渠道都要|支持按量跑付|寻一手大厂资源,我上 KEY 。<br>微信:Liuyou-zawd|TG:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
|
||||
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> 为网页抓取、AI 智能体、自动化和数据采集提供高性价比的全球代理解决方案。住宅代理低至 $0.35/GB,覆盖 190+ 个国家和地区,套餐灵活,支持 HTTP(S)/SOCKS5 协议。<br>🎁 使用优惠码 PAY2 充值立享 9 折优惠!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
|
||||
<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>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## 项目概述
|
||||
|
||||
Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的 API 配额。用户通过平台生成的 API Key 调用上游 AI 服务,平台负责鉴权、计费、负载均衡和请求转发。
|
||||
|
||||
@@ -31,6 +31,17 @@
|
||||
|
||||
> [こちらに掲載しませんか?](mailto:support@sub2api.org)
|
||||
|
||||
<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>
|
||||
|
||||
**[WandAPI](https://wandapi.ai/r/sub2api)** — 本プロジェクトのコアコントリビューターが手がける、エンタープライズグレードで安定した AI モデル API ゲートウェイ。1 つの API キーで Claude、GPT、Gemini などの主要モデルを利用でき、OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex や既存の SDK も Base URL を変更するだけで接続できます。レイテンシと上流の稼働状況に応じたリアルタイムルーティングとミリ秒単位の自動フェイルオーバーでリクエストを途切れさせず、99.99% のサービス可用性を実現します。従量課金で、リクエストごとの token 数と費用の内訳を確認できます。
|
||||
|
||||
**無料トライアルクレジット**:[専用リンク](https://wandapi.ai/r/sub2api)から登録すると、無料トライアルクレジットを受け取れます。
|
||||
|
||||
---
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
@@ -163,8 +174,20 @@
|
||||
<td>🔑 AI アカウント高価買取|Gemini · Claude · GPT|メイン・サブアカウントすべて買取、チャネル問わず歓迎|従量制での支払いに対応|大手の一次リソースを求めています、KEY は私が用意します。<br>WeChat:Liuyou-zawd|Telegram:<a href="https://t.me/AACC8888888">AACC8888888</a></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api"><img src="assets/partners/logos/NiuProxy.jpg" alt="NiuProxy" width="150"></a></td>
|
||||
<td><a href="https://niuproxy.com/?utm_source=sub2api&utm_medium=sub2api&ref=sub2api">NiuProxy</a> は、Web スクレイピング、AI エージェント、自動化、データ収集向けに、手頃な価格のグローバルプロキシソリューションを提供します。住宅プロキシは $0.35/GB から、190 以上の国と地域をカバーし、柔軟なプランと HTTP(S)/SOCKS5 に対応しています。<br>🎁 コード PAY2 でチャージが 10% オフ!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://soleapi.com/r/sub2api"><img src="assets/partners/logos/soleapi.png" alt="SoleAPI" width="150"></a></td>
|
||||
<td><a href="https://soleapi.com/r/sub2api">SoleAPI</a> 様、本プロジェクトへのご支援ありがとうございます!SoleAPI は開発者と企業向けの AI モデルゲートウェイです。1 つの API キーで Claude、GPT、Gemini をはじめとする 30 以上の主要モデルを利用できます。OpenAI と Anthropic のプロトコルにネイティブ対応しているため、Claude Code、Codex、Cursor や既存の SDK も Base URL を変更するだけで動作します。リクエストはレイテンシと上流の稼働状況に応じてリアルタイムにルーティングされ、ミリ秒単位でバックアップチャネルへ自動フェイルオーバーします。サービス可用性は 99.99%、24 時間 365 日の技術サポートも提供しています。すべての呼び出しは 1 つの請求書にまとめられ、リクエストごとの token 数と費用の内訳をいつでも確認できます。本プロジェクトの<a href="https://soleapi.com/r/sub2api">紹介リンク</a>から登録すると無料トライアルクレジットを受け取れ、友人を招待してチャージしてもらうと継続的にキャッシュバックを獲得できます!</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
</details>
|
||||
|
||||
## 概要
|
||||
|
||||
Sub2API は、AI 製品のサブスクリプションから API クォータを配分・管理するために設計された AI API ゲートウェイプラットフォームです。ユーザーはプラットフォームが生成した API キーを通じて上流の AI サービスにアクセスでき、プラットフォームは認証、課金、負荷分散、リクエスト転送を処理します。
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
|
||||
<defs>
|
||||
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
|
||||
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#000000" stop-opacity=".45"/><stop offset="1" stop-color="#000000" stop-opacity="0"/></radialGradient>
|
||||
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
|
||||
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#frame)">
|
||||
<rect width="1760" height="220" fill="#0A2540"/>
|
||||
<g clip-path="url(#slant)">
|
||||
<rect x="900" width="860" height="220" fill="url(#band)"/>
|
||||
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
|
||||
</g>
|
||||
<g transform="translate(72 36) scale(0.7)">
|
||||
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
|
||||
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
|
||||
<g stroke="#FFFFFF"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
|
||||
<g stroke="#8C86FF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
|
||||
</g>
|
||||
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#8C86FF"/>
|
||||
</g>
|
||||
<path d="M73.7 107.1V113.1H116.3V107.1ZM138.1 103.8V132H143.8V103.8ZM140.9 88.9C136.2 96.7 127.8 102.3 119.1 105.6C120.6 107.2 122.2 109.3 123.1 111C129.8 107.9 136.2 103.5 141.2 97.7C148.4 105.2 154.1 108.6 159.1 111.1C160 109.2 161.7 107.1 163.2 105.8C157.9 103.8 151.6 100.4 144.5 93.4L145.9 91.2ZM174.3 128H181.2L183.6 119.3H194.5L196.9 128H204.1L193.2 93.9H185.2ZM185 114 186 110.2C187 106.7 188 102.8 188.9 99.1H189.1C190.1 102.7 191 106.7 192.1 110.2L193.1 114ZM208.1 128H214.9V115.9H219.5C226.8 115.9 232.6 112.4 232.6 104.6C232.6 96.6 226.8 93.9 219.3 93.9H208.1ZM214.9 110.5V99.3H218.8C223.5 99.3 226 100.7 226 104.6C226 108.5 223.7 110.5 219 110.5ZM238.8 128H245.6V93.9H238.8ZM264.4 128H271.2V118.4L275.7 112.7L284.5 128H292L279.7 107.3L290.1 93.9H282.6L271.4 108.7H271.2V93.9H264.4ZM306.6 128.6C309.8 128.6 313.1 127.5 315.6 125.8L313.3 121.7C311.4 122.8 309.6 123.4 307.6 123.4C303.7 123.4 300.9 121.2 300.4 117.1H316.3C316.4 116.4 316.6 115.2 316.6 113.9C316.6 106.7 312.9 101.6 305.8 101.6C299.7 101.6 293.8 106.8 293.8 115.1C293.8 123.6 299.4 128.6 306.6 128.6ZM300.3 112.5C300.8 108.8 303.2 106.8 305.9 106.8C309.3 106.8 310.8 109 310.8 112.5ZM324.4 138.3C330.2 138.3 332.9 134.9 335.2 128.8L344.3 102.2H337.8L334.3 114.2C333.6 116.6 333 119.1 332.5 121.5H332.2C331.5 119 330.8 116.5 330.1 114.2L326 102.2H319.2L329.2 127.5L328.7 129.1C328 131.3 326.5 133 323.9 133C323.3 133 322.6 132.8 322.1 132.6L320.9 137.8C321.9 138.1 322.9 138.3 324.4 138.3ZM353.8 134.3C359.5 132.6 362.9 128.4 362.9 123.2C362.9 119.3 361.2 116.9 357.9 116.9C355.5 116.9 353.4 118.4 353.4 121C353.4 123.6 355.5 125.1 357.8 125.1L358.3 125.1C358 127.5 355.9 129.5 352.4 130.6ZM399 88.9V95.4H393.1V120.1H397.1V117.8H399V132H404V117.8H410.3V95.4H404V88.9ZM406 108.6V113.2H403.6V108.6ZM406 104.3H403.6V100.1H406ZM397.1 108.6H399.5V113.2H397.1ZM397.1 104.3V100.1H399.5V104.3ZM413 109.1C413.4 108.7 415 108.5 416.6 108.4C415 112.9 412.3 116.7 408.7 119.3C409.9 119.9 411.9 121.3 412.8 122.2C416.5 119 419.9 114.1 421.7 108.4H423.6C421.3 117.2 417.1 124.4 410.7 128.7C411.9 129.4 414.1 130.9 414.9 131.7C421.3 126.6 426 118.6 428.6 108.4H429.6C428.9 120.3 428 124.9 427 126.1C426.5 126.7 426.2 126.8 425.5 126.8C424.7 126.8 423.4 126.8 421.9 126.6C422.7 128 423.3 130.3 423.3 131.8C425.3 131.9 427.1 131.8 428.3 131.6C429.7 131.4 430.8 130.9 431.8 129.5C433.4 127.5 434.3 121.5 435.2 105.6C435.3 104.9 435.3 103.2 435.3 103.2H421.6C425.4 100.5 429.4 97.1 433.1 93.5L429.2 90.5L427.8 91H411.4V96.1H422.4C419.5 98.7 416.5 100.8 415.4 101.6C413.7 102.7 412 103.8 410.7 104C411.4 105.3 412.6 107.9 413 109.1ZM440.2 92C442.4 94.7 445.1 98.3 446.3 100.6L450.8 97.5C449.5 95.2 446.6 91.8 444.4 89.3ZM449.2 104.2H438.7V109.3H444V121.8C441.9 122.8 439.6 124.5 437.5 127L441.5 132.6C443.1 129.7 445 126.5 446.3 126.5C447.4 126.5 449 128 451.1 129.2C454.6 131.2 458.5 131.7 464.6 131.7C469.5 131.7 477.2 131.4 480.5 131.2C480.6 129.6 481.5 126.7 482.2 125.1C477.4 125.8 469.8 126.3 464.8 126.3C459.5 126.3 455.1 126 452 124C450.9 123.4 450 122.8 449.2 122.3ZM454.2 110.2C454.6 109.6 456.6 109.4 458.6 109.4H465V113.5H451.5V118.7H465V125.2H470.7V118.7H480.5V113.5H470.7V109.4H478.5V104.3H470.7V99.8H465V104.3H459.6C460.7 102.4 461.7 100.4 462.7 98.2H480V93.5H464.7L465.8 90.4L460 88.9C459.6 90.4 459.1 92 458.6 93.5H451.9V98.2H456.8C456.1 100 455.4 101.4 454.9 102.1C454 103.7 453.3 104.7 452.3 105C453 106.4 453.9 109 454.2 110.2ZM505 88.5C500.4 95.7 491.9 101.6 483.7 105.1C485 106.4 486.6 108.3 487.4 109.7C488.9 109 490.4 108.2 491.8 107.3V110.4H503V115.8H492.5V120.5H503V126.1H486.4V131H525.7V126.1H508.8V120.5H519.8V115.8H508.8V110.4H520.2V107.5C521.6 108.3 523.1 109.1 524.6 109.9C525.3 108.3 526.9 106.4 528.3 105.2C521 102 514.5 97.9 509 92L509.9 90.8ZM494.6 105.6C498.7 102.8 502.6 99.6 505.9 96C509.4 99.8 513.1 102.9 517.1 105.6ZM546.4 105.4C548.1 107.9 549.9 111.4 550.6 113.6L555.1 111.5C554.4 109.3 552.4 106 550.6 103.5ZM529.9 122.5 531 127.8 544.7 123.4 547.3 127.3C550.2 124.7 553.5 121.6 556.7 118.4V126C556.7 126.7 556.5 126.9 555.7 126.9C555 126.9 552.9 126.9 550.6 126.8C551.4 128.3 552.3 130.7 552.5 132.1C556 132.1 558.3 132 559.9 131C561.5 130.2 562.1 128.7 562.1 125.9V118.7C564.2 122.5 567 125.7 570.8 128.6C571.4 127.1 572.9 125.3 574.2 124.4C570.2 121.7 567.5 118.7 565.5 114.7C567.8 112.3 570.7 108.9 573.1 105.7L568.3 103.3C567.2 105.4 565.4 107.9 563.7 110.1C563 108.1 562.5 106 562.1 103.6V101.4H573.4V96.4H569.4L572 93.8C570.9 92.4 568.4 90.5 566.5 89.2L563.5 92C565.1 93.2 567.1 95 568.3 96.4H562.1V88.9H556.7V96.4H546.1V101.4H556.7V112.5C552.9 115.7 548.8 118.9 545.8 121.1L545.2 118.1L540.6 119.5V109.9H544.6V104.8H540.6V96.7H545.2V91.6H530.6V96.7H535.4V104.8H530.8V109.9H535.4V121C533.3 121.6 531.4 122.2 529.9 122.5ZM585.2 128H592.1L594.5 119.3H605.5L607.9 128H615L604.1 93.9H596.1ZM595.9 114 597 110.2C598 106.7 598.9 102.8 599.8 99.1H600C601 102.7 602 106.7 603 110.2L604 114ZM619 128H625.8V93.9H619ZM660.3 88.9C660.3 92.7 660.3 97 659.9 101.3H643V107H659C657.1 115 652.7 122.6 642.2 12Line truncated
|
||||
<rect x="72" y="148" width="266.0" height="44" rx="22" fill="#635BFF"/>
|
||||
<path d="M95.9 161.8C97.2 162.4 99 163.4 99.8 164.1L101.3 162C100.4 161.4 98.6 160.5 97.3 159.9ZM94.7 167.6C96 168.3 97.8 169.2 98.7 169.9L100.1 167.8C99.1 167.2 97.3 166.3 96.1 165.7ZM95.3 177.5 97.4 179.2C98.7 177.2 100 174.8 101.1 172.6L99.3 170.9C98 173.3 96.4 175.9 95.3 177.5ZM105.5 160.3C106.1 161.4 106.6 162.7 106.9 163.6H101.3V166H106.4V169.7H102.2V172.1H106.4V176.4H100.7V178.8H114.4V176.4H109V172.1H113.1V169.7H109V166H113.8V163.6H107.4L109.4 162.8C109.2 161.9 108.4 160.6 107.8 159.6ZM126.2 161V167.9H124.6V161H117.9V167.9H115.7V170.3H117.9C117.7 172.9 117.2 175.7 115.6 177.8C116.1 178.1 117.1 179.1 117.4 179.6C119.4 177.1 120 173.4 120.2 170.3H122.2V176.7C122.2 177 122.1 177.1 121.8 177.1C121.5 177.1 120.6 177.1 119.8 177.1C120.1 177.6 120.5 178.7 120.6 179.3C122 179.3 123 179.2 123.7 178.8C124.1 178.6 124.3 178.3 124.5 177.9C125 178.3 125.8 179.1 126.1 179.5C127.8 177.1 128.4 173.4 128.6 170.3H130.8V176.6C130.8 176.9 130.7 177 130.4 177C130.1 177 129.2 177 128.4 177C128.7 177.6 129.1 178.7 129.2 179.3C130.6 179.3 131.6 179.3 132.4 178.9C133.1 178.5 133.3 177.8 133.3 176.6V170.3H135.3V167.9H133.3V161ZM120.3 163.3H122.2V167.9H120.3ZM124.6 170.3H126.2C126 172.6 125.7 175.1 124.6 177.1V176.7ZM128.6 167.9V163.3H130.8V167.9ZM140.1 166.2C140.9 167 141.8 168.1 142.3 168.8L143.9 167.6C143.4 167 142.4 166 141.6 165.3ZM146.9 164.7V174.6H149.2V166.5H153.4V174.5H155.7V164.7H151.8L152.5 162.9H156.2V160.7H146.5V162.9H150.2C150 163.5 149.8 164.1 149.6 164.7ZM150.3 167.2C150.2 174 150.1 176.4 145.4 177.8C145.8 178.2 146.4 179 146.6 179.5C149 178.8 150.4 177.7 151.2 176C152.5 177.1 154 178.5 154.8 179.4L156.4 177.9C155.6 177 153.8 175.5 152.5 174.5L151.5 175.5C152.2 173.5 152.3 170.9 152.3 167.2ZM141.4 159.6C140.4 162.1 138.6 164.9 136.4 166.6C136.9 167 137.7 167.8 138.1 168.2C139.6 167 140.9 165.3 141.9 163.5C143.2 164.9 144.6 166.4 145.3 167.5L146.8 165.8C146 164.6 144.4 162.9 143 161.6C143.2 161.1 143.4 160.7 143.5 160.2ZM138.1 168.9V171.1H143C142.4 172.2 141.8 173.4 141.1 174.4L139.9 173.3L138.2 174.5C139.7 176 141.6 178 142.4 179.2L144.3 177.8C143.9 177.2 143.3 176.6 142.7 175.9C143.8 174.2 145.2 171.9 146 169.8L144.4 168.8L144 168.9ZM174.2 164.2C173.9 166.6 173.3 168.8 172.4 170.7C171.6 168.8 171.1 166.6 170.7 164.2ZM167.7 161.9V164.2H168.4C169 167.7 169.8 170.8 171.1 173.4C170 175.2 168.6 176.6 167 177.5C167.5 178 168.2 178.8 168.6 179.4C170.1 178.4 171.3 177.2 172.4 175.7C173.4 177.1 174.5 178.3 175.9 179.2C176.3 178.6 177 177.7 177.6 177.3C176 176.4 174.8 175.1 173.8 173.5C175.4 170.5 176.4 166.8 176.9 162.2L175.3 161.8L174.9 161.9ZM157.7 174.4 158.2 176.8 163.9 175.8V179.3H166.3V175.4L168.1 175.1L168 173L166.3 173.2V162.7H167.6V160.5H157.9V162.7H159.1V174.2ZM161.5 162.7H163.9V164.9H161.5ZM161.5 167H163.9V169.3H161.5ZM161.5 171.5H163.9V173.6L161.5 173.9ZM184.4 159.6C183.3 161.7 181.3 164.1 178.4 166C179 166.4 179.8 167.3 180.2 167.9L180.9 167.4V172.1H186.2C185.2 174.2 183.1 176 178.8 177.1C179.3 177.6 180 178.6 180.2 179.2C185.5 177.7 187.8 175.2 189 172.1H189.3V176C189.3 178.3 189.9 179 192.4 179C193 179 194.8 179 195.3 179C197.4 179 198.1 178.1 198.3 175C197.6 174.9 196.6 174.5 196 174.1C196 176.4 195.8 176.7 195.1 176.7C194.6 176.7 193.2 176.7 192.8 176.7C192 176.7 191.9 176.7 191.9 176V172.1H196.6V164.9H190.9C191.7 164 192.4 162.9 192.9 162.1L191.1 160.9L190.7 161H186.5L187.1 160.1ZM183.6 164.9C184.1 164.3 184.6 163.7 185.1 163.1H189.3C188.9 163.7 188.4 164.4 187.9 164.9ZM183.4 167.1H187.3C187.2 168.1 187.1 169 186.9 169.9H183.4ZM189.9 167.1H193.9V169.9H189.6C189.7 169 189.8 168.1 189.9 167.1ZM208.6 173C207.8 175.3 206.3 176.6 199.6 177.2C200.1 177.7 200.5 178.8 200.7 179.3C208.1 178.4 210.2 176.4 211.1 173ZM209.9 176.7C212.5 177.4 216.1 178.6 217.9 179.4L219.3 177.5C217.4 176.7 213.7 175.7 211.2 175.1ZM206.1 165C206.1 165.4 206 165.7 205.9 165.9H203.6L203.8 165ZM208.3 165H210.7V165.9H208.3C208.3 165.7 208.3 165.4 208.3 165ZM201.8 163.4C201.6 164.8 201.3 166.5 201.1 167.6H204.8C203.9 168.3 202.4 168.9 199.9 169.3C200.4 169.8 201 170.7 201.2 171.2C201.7 171.1 202.2 171.1 202.6 170.9V176H205V172.3H213.9V175.8H216.5V170.2H204.7C206.3 169.5 207.2 168.6 207.7 167.6H210.7V169.8H213.1V167.6H216.3C216.3 167.9 216.2 168.1 216.2 168.2C216.1 168.3 215.9 168.3 215.7 168.3C215.5 168.3 215.1 168.3 214.6 168.2C214.8 168.7 215 169.4 215 169.8C215.8 169.9 216.6 169.9 217 169.8C217.4 169.8 217.9 169.6 218.2 169.3C218.6 168.9 218.7 168.1 218.8 166.6C218.8 166.4 218.8 165.9 218.8 165.9H213.1V165H217.5V160.7H213.1V159.7H210.7V160.7H208.4V159.7H206.1V160.7H201.2V162.4H206.1V163.4L202.7 163.4ZM208.4 162.4H210.7V163.4H208.4ZM213.1 162.4H215.2V163.4H213.1ZM222 161.5C223.2 162.5 224.6 163.9 225.3 164.8L227 163.1C226.3 162.2 224.8 160.8 223.7 159.9ZM228 168.5V170.8H229.7V175.3L228.4 175.7L228.4 175.7C228.2 175.2 227.9 174.2 227.8 173.5L225.9 174.7V166.1H221V168.6H223.5V174.9C223.5 175.8 222.9 176.5 222.4 176.8C222.8 177.3 223.4 178.4 223.5 179C223.9 178.6 224.6 178.2 227.7 176.1L228.3 178.2C230.1 177.6 232.3 177 234.5 176.4L234.Line truncated
|
||||
<path d="M315.0 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M367.6 177.5H371.1L372.3 172.4C372.6 171.3 372.8 170.2 373 168.9H373.1C373.3 170.2 373.5 171.3 373.8 172.4L375 177.5H378.6L381.5 165.7H378.7L377.4 171.5C377.2 172.7 377 173.8 376.8 175H376.7C376.5 173.8 376.2 172.7 376 171.5L374.5 165.7H371.8L370.3 171.5C370 172.7 369.8 173.8 369.6 175H369.5C369.3 173.8 369.1 172.7 369 171.5L367.7 165.7H364.6ZM386.7 177.8C388 177.8 389.2 177.1 390.2 176.2H390.3L390.5 177.5H393V170.6C393 167.2 391.5 165.4 388.5 165.4C386.7 165.4 385 166.2 383.6 167L384.7 169.1C385.8 168.4 386.9 167.9 388 167.9C389.4 167.9 389.9 168.8 390 170C385.2 170.5 383.2 171.8 383.2 174.3C383.2 176.3 384.6 177.8 386.7 177.8ZM387.7 175.4C386.8 175.4 386.1 175 386.1 174.1C386.1 173 387.1 172.2 390 171.9V174.2C389.2 175 388.6 175.4 387.7 175.4ZM396.2 177.5H399.3V169.4C400.1 168.6 400.8 168.1 401.7 168.1C402.9 168.1 403.4 168.7 403.4 170.5V177.5H406.5V170.2C406.5 167.2 405.4 165.4 402.8 165.4C401.2 165.4 400 166.3 399 167.3H398.9L398.7 165.7H396.2ZM413.8 177.8C415 177.8 416.2 177.1 417 176.3H417.1L417.4 177.5H419.9V160.7H416.8V164.9L416.9 166.7C416.1 165.9 415.2 165.4 413.9 165.4C411.4 165.4 409 167.8 409 171.6C409 175.5 410.9 177.8 413.8 177.8ZM414.6 175.3C413 175.3 412.2 174 412.2 171.6C412.2 169.2 413.3 168 414.6 168C415.3 168 416.1 168.2 416.8 168.9V174C416.1 174.9 415.4 175.3 414.6 175.3ZM426.1 177.8C427.4 177.8 428.6 177.1 429.6 176.2H429.7L429.9 177.5H432.4V170.6C432.4 167.2 430.9 165.4 427.9 165.4C426.1 165.4 424.4 166.2 423 167L424.1 169.1C425.2 168.4 426.3 167.9 427.4 167.9C428.8 167.9 429.3 168.8 429.4 170C424.6 170.5 422.6 171.8 422.6 174.3C422.6 176.3 424 177.8 426.1 177.8ZM427.1 175.4C426.2 175.4 425.5 175 425.5 174.1C425.5 173 426.5 172.2 429.4 171.9V174.2C428.6 175 428 175.4 427.1 175.4ZM435.6 182H438.7V178.4L438.6 176.5C439.5 177.3 440.5 177.8 441.5 177.8C444.1 177.8 446.5 175.5 446.5 171.4C446.5 167.8 444.7 165.4 441.9 165.4C440.6 165.4 439.4 166.1 438.4 167H438.3L438.1 165.7H435.6ZM440.8 175.3C440.2 175.3 439.4 175 438.7 174.4V169.2C439.5 168.4 440.2 168 441 168C442.6 168 443.3 169.2 443.3 171.5C443.3 174 442.2 175.3 440.8 175.3ZM449.1 177.5H452.2V165.7H449.1ZM450.7 163.8C451.7 163.8 452.5 163.2 452.5 162.1C452.5 161.1 451.7 160.5 450.7 160.5C449.6 160.5 448.9 161.1 448.9 162.1C448.9 163.2 449.6 163.8 450.7 163.8ZM457.3 177.8C458.4 177.8 459.2 176.9 459.2 175.8C459.2 174.6 458.4 173.8 457.3 173.8C456.1 173.8 455.3 174.6 455.3 175.8C455.3 176.9 456.1 177.8 457.3 177.8ZM465.2 177.8C466.6 177.8 467.7 177.1 468.7 176.2H468.9L469.1 177.5H471.6V170.6C471.6 167.2 470.1 165.4 467.1 165.4C465.2 165.4 463.5 166.2 462.2 167L463.3 169.1C464.4 168.4 465.4 167.9 466.5 167.9C467.9 167.9 468.5 168.8 468.5 170C463.8 170.5 461.7 171.8 461.7 174.3C461.7 176.3 463.1 177.8 465.2 177.8ZM466.2 175.4C465.3 175.4 464.7 175 464.7 174.1C464.7 173 465.6 172.2 468.5 171.9V174.2C467.8 175 467.1 175.4 466.2 175.4ZM474.7 177.5H477.8V165.7H474.7ZM476.3 163.8C477.3 163.8 478.1 163.2 478.1 162.1C478.1 161.1 477.3 160.5 476.3 160.5C475.2 160.5 474.5 161.1 474.5 162.1C474.5 163.2 475.2 163.8 476.3 163.8Z" fill="#8C86FF"/>
|
||||
<path d="M488.5 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#8C86FF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
|
||||
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
|
||||
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
|
||||
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
|
||||
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
|
||||
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
|
||||
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#FFFFFF"></path></g>
|
||||
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
|
||||
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
|
||||
<path d="M1644.6 120.5V128H1646.6L1644.9 128.6C1645.5 129.4 1646.1 130.1 1646.8 130.7C1645.8 131.1 1644.4 131.4 1642.7 131.7C1643.2 132.2 1643.8 133.1 1644 133.6C1646.1 133.2 1647.7 132.6 1648.9 131.9C1651.5 133.1 1654.8 133.3 1658.8 133.4C1658.9 132.7 1659.3 131.8 1659.7 131.3C1656 131.3 1653 131.2 1650.7 130.5C1651.4 129.7 1651.8 128.9 1652 128H1657.8V120.5H1652.3V119.5H1658.9V117.5H1643.1V119.5H1650V120.5ZM1646.7 125H1650V125.6L1650 126.2H1646.7ZM1652.3 126.2 1652.3 125.6V125H1655.7V126.2ZM1646.7 122.2H1650V123.4H1646.7ZM1652.3 122.2H1655.7V123.4H1652.3ZM1649.7 128C1649.5 128.5 1649.1 129 1648.6 129.5C1648 129.1 1647.4 128.6 1646.9 128ZM1667.9 116.6C1666.6 118.1 1664.5 119.6 1661.6 120.7C1662.1 121 1662.7 121.7 1663 122.2C1664.5 121.6 1665.8 120.9 1666.9 120.1H1671.4C1670.6 120.9 1669.6 121.6 1668.4 122.2C1667.9 121.7 1667.2 121.2 1666.6 120.8L1665 121.8C1665.5 122.2 1666 122.6 1666.5 123.1C1664.8 123.7 1663 124.2 1661.1 124.4C1661.5 124.9 1661.9 125.8 1662.1 126.3C1667.3 125.3 1672.5 123.1 1674.8 118.9L1673.4 118.1L1673 118.2H1669.2C1669.5 117.9 1669.9 117.5 1670.2 117.2ZM1670.8 123.1C1669.5 124.9 1667 126.6 1663.3 127.8C1663.7 128.2 1664.3 129 1664.6 129.5C1666.6 128.7 1668.4 127.8 1669.8 126.8H1673.9C1673.1 127.8 1672.1 128.6 1670.9 129.2C1670.3 128.7 1669.7 128.2 1669.1 127.8L1667.3 128.8C1667.8 129.2 1668.4 129.7 1668.9 130.1C1666.6 130.9 1663.9 131.4 1661 131.6C1661.3 132.1 1661.7 133.1 1661.8 133.7C1668.7 133 1674.7 131.1 1677.2 125.6L1675.7 124.7L1675.3 124.9H1672.1C1672.5 124.5 1672.9 124 1673.2 123.6Z" fill="#fff"/>
|
||||
</g>
|
||||
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#1F3A5C" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,57 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
|
||||
<defs>
|
||||
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
|
||||
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#32325D" stop-opacity=".30"/><stop offset="1" stop-color="#32325D" stop-opacity="0"/></radialGradient>
|
||||
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
|
||||
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#frame)">
|
||||
<rect width="1760" height="220" fill="#FFFFFF"/>
|
||||
<g clip-path="url(#slant)">
|
||||
<rect x="900" width="860" height="220" fill="url(#band)"/>
|
||||
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
|
||||
</g>
|
||||
<g transform="translate(72 36) scale(0.7)">
|
||||
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
|
||||
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
|
||||
<g stroke="#0A2540"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
|
||||
<g stroke="#635BFF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
|
||||
</g>
|
||||
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#635BFF"/>
|
||||
</g>
|
||||
<path d="M73.7 107.1V113.1H116.3V107.1ZM138.1 103.8V132H143.8V103.8ZM140.9 88.9C136.2 96.7 127.8 102.3 119.1 105.6C120.6 107.2 122.2 109.3 123.1 111C129.8 107.9 136.2 103.5 141.2 97.7C148.4 105.2 154.1 108.6 159.1 111.1C160 109.2 161.7 107.1 163.2 105.8C157.9 103.8 151.6 100.4 144.5 93.4L145.9 91.2ZM174.3 128H181.2L183.6 119.3H194.5L196.9 128H204.1L193.2 93.9H185.2ZM185 114 186 110.2C187 106.7 188 102.8 188.9 99.1H189.1C190.1 102.7 191 106.7 192.1 110.2L193.1 114ZM208.1 128H214.9V115.9H219.5C226.8 115.9 232.6 112.4 232.6 104.6C232.6 96.6 226.8 93.9 219.3 93.9H208.1ZM214.9 110.5V99.3H218.8C223.5 99.3 226 100.7 226 104.6C226 108.5 223.7 110.5 219 110.5ZM238.8 128H245.6V93.9H238.8ZM264.4 128H271.2V118.4L275.7 112.7L284.5 128H292L279.7 107.3L290.1 93.9H282.6L271.4 108.7H271.2V93.9H264.4ZM306.6 128.6C309.8 128.6 313.1 127.5 315.6 125.8L313.3 121.7C311.4 122.8 309.6 123.4 307.6 123.4C303.7 123.4 300.9 121.2 300.4 117.1H316.3C316.4 116.4 316.6 115.2 316.6 113.9C316.6 106.7 312.9 101.6 305.8 101.6C299.7 101.6 293.8 106.8 293.8 115.1C293.8 123.6 299.4 128.6 306.6 128.6ZM300.3 112.5C300.8 108.8 303.2 106.8 305.9 106.8C309.3 106.8 310.8 109 310.8 112.5ZM324.4 138.3C330.2 138.3 332.9 134.9 335.2 128.8L344.3 102.2H337.8L334.3 114.2C333.6 116.6 333 119.1 332.5 121.5H332.2C331.5 119 330.8 116.5 330.1 114.2L326 102.2H319.2L329.2 127.5L328.7 129.1C328 131.3 326.5 133 323.9 133C323.3 133 322.6 132.8 322.1 132.6L320.9 137.8C321.9 138.1 322.9 138.3 324.4 138.3ZM353.8 134.3C359.5 132.6 362.9 128.4 362.9 123.2C362.9 119.3 361.2 116.9 357.9 116.9C355.5 116.9 353.4 118.4 353.4 121C353.4 123.6 355.5 125.1 357.8 125.1L358.3 125.1C358 127.5 355.9 129.5 352.4 130.6ZM399 88.9V95.4H393.1V120.1H397.1V117.8H399V132H404V117.8H410.3V95.4H404V88.9ZM406 108.6V113.2H403.6V108.6ZM406 104.3H403.6V100.1H406ZM397.1 108.6H399.5V113.2H397.1ZM397.1 104.3V100.1H399.5V104.3ZM413 109.1C413.4 108.7 415 108.5 416.6 108.4C415 112.9 412.3 116.7 408.7 119.3C409.9 119.9 411.9 121.3 412.8 122.2C416.5 119 419.9 114.1 421.7 108.4H423.6C421.3 117.2 417.1 124.4 410.7 128.7C411.9 129.4 414.1 130.9 414.9 131.7C421.3 126.6 426 118.6 428.6 108.4H429.6C428.9 120.3 428 124.9 427 126.1C426.5 126.7 426.2 126.8 425.5 126.8C424.7 126.8 423.4 126.8 421.9 126.6C422.7 128 423.3 130.3 423.3 131.8C425.3 131.9 427.1 131.8 428.3 131.6C429.7 131.4 430.8 130.9 431.8 129.5C433.4 127.5 434.3 121.5 435.2 105.6C435.3 104.9 435.3 103.2 435.3 103.2H421.6C425.4 100.5 429.4 97.1 433.1 93.5L429.2 90.5L427.8 91H411.4V96.1H422.4C419.5 98.7 416.5 100.8 415.4 101.6C413.7 102.7 412 103.8 410.7 104C411.4 105.3 412.6 107.9 413 109.1ZM440.2 92C442.4 94.7 445.1 98.3 446.3 100.6L450.8 97.5C449.5 95.2 446.6 91.8 444.4 89.3ZM449.2 104.2H438.7V109.3H444V121.8C441.9 122.8 439.6 124.5 437.5 127L441.5 132.6C443.1 129.7 445 126.5 446.3 126.5C447.4 126.5 449 128 451.1 129.2C454.6 131.2 458.5 131.7 464.6 131.7C469.5 131.7 477.2 131.4 480.5 131.2C480.6 129.6 481.5 126.7 482.2 125.1C477.4 125.8 469.8 126.3 464.8 126.3C459.5 126.3 455.1 126 452 124C450.9 123.4 450 122.8 449.2 122.3ZM454.2 110.2C454.6 109.6 456.6 109.4 458.6 109.4H465V113.5H451.5V118.7H465V125.2H470.7V118.7H480.5V113.5H470.7V109.4H478.5V104.3H470.7V99.8H465V104.3H459.6C460.7 102.4 461.7 100.4 462.7 98.2H480V93.5H464.7L465.8 90.4L460 88.9C459.6 90.4 459.1 92 458.6 93.5H451.9V98.2H456.8C456.1 100 455.4 101.4 454.9 102.1C454 103.7 453.3 104.7 452.3 105C453 106.4 453.9 109 454.2 110.2ZM505 88.5C500.4 95.7 491.9 101.6 483.7 105.1C485 106.4 486.6 108.3 487.4 109.7C488.9 109 490.4 108.2 491.8 107.3V110.4H503V115.8H492.5V120.5H503V126.1H486.4V131H525.7V126.1H508.8V120.5H519.8V115.8H508.8V110.4H520.2V107.5C521.6 108.3 523.1 109.1 524.6 109.9C525.3 108.3 526.9 106.4 528.3 105.2C521 102 514.5 97.9 509 92L509.9 90.8ZM494.6 105.6C498.7 102.8 502.6 99.6 505.9 96C509.4 99.8 513.1 102.9 517.1 105.6ZM546.4 105.4C548.1 107.9 549.9 111.4 550.6 113.6L555.1 111.5C554.4 109.3 552.4 106 550.6 103.5ZM529.9 122.5 531 127.8 544.7 123.4 547.3 127.3C550.2 124.7 553.5 121.6 556.7 118.4V126C556.7 126.7 556.5 126.9 555.7 126.9C555 126.9 552.9 126.9 550.6 126.8C551.4 128.3 552.3 130.7 552.5 132.1C556 132.1 558.3 132 559.9 131C561.5 130.2 562.1 128.7 562.1 125.9V118.7C564.2 122.5 567 125.7 570.8 128.6C571.4 127.1 572.9 125.3 574.2 124.4C570.2 121.7 567.5 118.7 565.5 114.7C567.8 112.3 570.7 108.9 573.1 105.7L568.3 103.3C567.2 105.4 565.4 107.9 563.7 110.1C563 108.1 562.5 106 562.1 103.6V101.4H573.4V96.4H569.4L572 93.8C570.9 92.4 568.4 90.5 566.5 89.2L563.5 92C565.1 93.2 567.1 95 568.3 96.4H562.1V88.9H556.7V96.4H546.1V101.4H556.7V112.5C552.9 115.7 548.8 118.9 545.8 121.1L545.2 118.1L540.6 119.5V109.9H544.6V104.8H540.6V96.7H545.2V91.6H530.6V96.7H535.4V104.8H530.8V109.9H535.4V121C533.3 121.6 531.4 122.2 529.9 122.5ZM585.2 128H592.1L594.5 119.3H605.5L607.9 128H615L604.1 93.9H596.1ZM595.9 114 597 110.2C598 106.7 598.9 102.8 599.8 99.1H600C601 102.7 602 106.7 603 110.2L604 114ZM619 128H625.8V93.9H619ZM660.3 88.9C660.3 92.7 660.3 97 659.9 101.3H643V107H659C657.1 115 652.7 122.6 642.2 12Line truncated
|
||||
<rect x="72" y="148" width="266.0" height="44" rx="22" fill="#635BFF"/>
|
||||
<path d="M95.9 161.8C97.2 162.4 99 163.4 99.8 164.1L101.3 162C100.4 161.4 98.6 160.5 97.3 159.9ZM94.7 167.6C96 168.3 97.8 169.2 98.7 169.9L100.1 167.8C99.1 167.2 97.3 166.3 96.1 165.7ZM95.3 177.5 97.4 179.2C98.7 177.2 100 174.8 101.1 172.6L99.3 170.9C98 173.3 96.4 175.9 95.3 177.5ZM105.5 160.3C106.1 161.4 106.6 162.7 106.9 163.6H101.3V166H106.4V169.7H102.2V172.1H106.4V176.4H100.7V178.8H114.4V176.4H109V172.1H113.1V169.7H109V166H113.8V163.6H107.4L109.4 162.8C109.2 161.9 108.4 160.6 107.8 159.6ZM126.2 161V167.9H124.6V161H117.9V167.9H115.7V170.3H117.9C117.7 172.9 117.2 175.7 115.6 177.8C116.1 178.1 117.1 179.1 117.4 179.6C119.4 177.1 120 173.4 120.2 170.3H122.2V176.7C122.2 177 122.1 177.1 121.8 177.1C121.5 177.1 120.6 177.1 119.8 177.1C120.1 177.6 120.5 178.7 120.6 179.3C122 179.3 123 179.2 123.7 178.8C124.1 178.6 124.3 178.3 124.5 177.9C125 178.3 125.8 179.1 126.1 179.5C127.8 177.1 128.4 173.4 128.6 170.3H130.8V176.6C130.8 176.9 130.7 177 130.4 177C130.1 177 129.2 177 128.4 177C128.7 177.6 129.1 178.7 129.2 179.3C130.6 179.3 131.6 179.3 132.4 178.9C133.1 178.5 133.3 177.8 133.3 176.6V170.3H135.3V167.9H133.3V161ZM120.3 163.3H122.2V167.9H120.3ZM124.6 170.3H126.2C126 172.6 125.7 175.1 124.6 177.1V176.7ZM128.6 167.9V163.3H130.8V167.9ZM140.1 166.2C140.9 167 141.8 168.1 142.3 168.8L143.9 167.6C143.4 167 142.4 166 141.6 165.3ZM146.9 164.7V174.6H149.2V166.5H153.4V174.5H155.7V164.7H151.8L152.5 162.9H156.2V160.7H146.5V162.9H150.2C150 163.5 149.8 164.1 149.6 164.7ZM150.3 167.2C150.2 174 150.1 176.4 145.4 177.8C145.8 178.2 146.4 179 146.6 179.5C149 178.8 150.4 177.7 151.2 176C152.5 177.1 154 178.5 154.8 179.4L156.4 177.9C155.6 177 153.8 175.5 152.5 174.5L151.5 175.5C152.2 173.5 152.3 170.9 152.3 167.2ZM141.4 159.6C140.4 162.1 138.6 164.9 136.4 166.6C136.9 167 137.7 167.8 138.1 168.2C139.6 167 140.9 165.3 141.9 163.5C143.2 164.9 144.6 166.4 145.3 167.5L146.8 165.8C146 164.6 144.4 162.9 143 161.6C143.2 161.1 143.4 160.7 143.5 160.2ZM138.1 168.9V171.1H143C142.4 172.2 141.8 173.4 141.1 174.4L139.9 173.3L138.2 174.5C139.7 176 141.6 178 142.4 179.2L144.3 177.8C143.9 177.2 143.3 176.6 142.7 175.9C143.8 174.2 145.2 171.9 146 169.8L144.4 168.8L144 168.9ZM174.2 164.2C173.9 166.6 173.3 168.8 172.4 170.7C171.6 168.8 171.1 166.6 170.7 164.2ZM167.7 161.9V164.2H168.4C169 167.7 169.8 170.8 171.1 173.4C170 175.2 168.6 176.6 167 177.5C167.5 178 168.2 178.8 168.6 179.4C170.1 178.4 171.3 177.2 172.4 175.7C173.4 177.1 174.5 178.3 175.9 179.2C176.3 178.6 177 177.7 177.6 177.3C176 176.4 174.8 175.1 173.8 173.5C175.4 170.5 176.4 166.8 176.9 162.2L175.3 161.8L174.9 161.9ZM157.7 174.4 158.2 176.8 163.9 175.8V179.3H166.3V175.4L168.1 175.1L168 173L166.3 173.2V162.7H167.6V160.5H157.9V162.7H159.1V174.2ZM161.5 162.7H163.9V164.9H161.5ZM161.5 167H163.9V169.3H161.5ZM161.5 171.5H163.9V173.6L161.5 173.9ZM184.4 159.6C183.3 161.7 181.3 164.1 178.4 166C179 166.4 179.8 167.3 180.2 167.9L180.9 167.4V172.1H186.2C185.2 174.2 183.1 176 178.8 177.1C179.3 177.6 180 178.6 180.2 179.2C185.5 177.7 187.8 175.2 189 172.1H189.3V176C189.3 178.3 189.9 179 192.4 179C193 179 194.8 179 195.3 179C197.4 179 198.1 178.1 198.3 175C197.6 174.9 196.6 174.5 196 174.1C196 176.4 195.8 176.7 195.1 176.7C194.6 176.7 193.2 176.7 192.8 176.7C192 176.7 191.9 176.7 191.9 176V172.1H196.6V164.9H190.9C191.7 164 192.4 162.9 192.9 162.1L191.1 160.9L190.7 161H186.5L187.1 160.1ZM183.6 164.9C184.1 164.3 184.6 163.7 185.1 163.1H189.3C188.9 163.7 188.4 164.4 187.9 164.9ZM183.4 167.1H187.3C187.2 168.1 187.1 169 186.9 169.9H183.4ZM189.9 167.1H193.9V169.9H189.6C189.7 169 189.8 168.1 189.9 167.1ZM208.6 173C207.8 175.3 206.3 176.6 199.6 177.2C200.1 177.7 200.5 178.8 200.7 179.3C208.1 178.4 210.2 176.4 211.1 173ZM209.9 176.7C212.5 177.4 216.1 178.6 217.9 179.4L219.3 177.5C217.4 176.7 213.7 175.7 211.2 175.1ZM206.1 165C206.1 165.4 206 165.7 205.9 165.9H203.6L203.8 165ZM208.3 165H210.7V165.9H208.3C208.3 165.7 208.3 165.4 208.3 165ZM201.8 163.4C201.6 164.8 201.3 166.5 201.1 167.6H204.8C203.9 168.3 202.4 168.9 199.9 169.3C200.4 169.8 201 170.7 201.2 171.2C201.7 171.1 202.2 171.1 202.6 170.9V176H205V172.3H213.9V175.8H216.5V170.2H204.7C206.3 169.5 207.2 168.6 207.7 167.6H210.7V169.8H213.1V167.6H216.3C216.3 167.9 216.2 168.1 216.2 168.2C216.1 168.3 215.9 168.3 215.7 168.3C215.5 168.3 215.1 168.3 214.6 168.2C214.8 168.7 215 169.4 215 169.8C215.8 169.9 216.6 169.9 217 169.8C217.4 169.8 217.9 169.6 218.2 169.3C218.6 168.9 218.7 168.1 218.8 166.6C218.8 166.4 218.8 165.9 218.8 165.9H213.1V165H217.5V160.7H213.1V159.7H210.7V160.7H208.4V159.7H206.1V160.7H201.2V162.4H206.1V163.4L202.7 163.4ZM208.4 162.4H210.7V163.4H208.4ZM213.1 162.4H215.2V163.4H213.1ZM222 161.5C223.2 162.5 224.6 163.9 225.3 164.8L227 163.1C226.3 162.2 224.8 160.8 223.7 159.9ZM228 168.5V170.8H229.7V175.3L228.4 175.7L228.4 175.7C228.2 175.2 227.9 174.2 227.8 173.5L225.9 174.7V166.1H221V168.6H223.5V174.9C223.5 175.8 222.9 176.5 222.4 176.8C222.8 177.3 223.4 178.4 223.5 179C223.9 178.6 224.6 178.2 227.7 176.1L228.3 178.2C230.1 177.6 232.3 177 234.5 176.4L234.Line truncated
|
||||
<path d="M315.0 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M367.6 177.5H371.1L372.3 172.4C372.6 171.3 372.8 170.2 373 168.9H373.1C373.3 170.2 373.5 171.3 373.8 172.4L375 177.5H378.6L381.5 165.7H378.7L377.4 171.5C377.2 172.7 377 173.8 376.8 175H376.7C376.5 173.8 376.2 172.7 376 171.5L374.5 165.7H371.8L370.3 171.5C370 172.7 369.8 173.8 369.6 175H369.5C369.3 173.8 369.1 172.7 369 171.5L367.7 165.7H364.6ZM386.7 177.8C388 177.8 389.2 177.1 390.2 176.2H390.3L390.5 177.5H393V170.6C393 167.2 391.5 165.4 388.5 165.4C386.7 165.4 385 166.2 383.6 167L384.7 169.1C385.8 168.4 386.9 167.9 388 167.9C389.4 167.9 389.9 168.8 390 170C385.2 170.5 383.2 171.8 383.2 174.3C383.2 176.3 384.6 177.8 386.7 177.8ZM387.7 175.4C386.8 175.4 386.1 175 386.1 174.1C386.1 173 387.1 172.2 390 171.9V174.2C389.2 175 388.6 175.4 387.7 175.4ZM396.2 177.5H399.3V169.4C400.1 168.6 400.8 168.1 401.7 168.1C402.9 168.1 403.4 168.7 403.4 170.5V177.5H406.5V170.2C406.5 167.2 405.4 165.4 402.8 165.4C401.2 165.4 400 166.3 399 167.3H398.9L398.7 165.7H396.2ZM413.8 177.8C415 177.8 416.2 177.1 417 176.3H417.1L417.4 177.5H419.9V160.7H416.8V164.9L416.9 166.7C416.1 165.9 415.2 165.4 413.9 165.4C411.4 165.4 409 167.8 409 171.6C409 175.5 410.9 177.8 413.8 177.8ZM414.6 175.3C413 175.3 412.2 174 412.2 171.6C412.2 169.2 413.3 168 414.6 168C415.3 168 416.1 168.2 416.8 168.9V174C416.1 174.9 415.4 175.3 414.6 175.3ZM426.1 177.8C427.4 177.8 428.6 177.1 429.6 176.2H429.7L429.9 177.5H432.4V170.6C432.4 167.2 430.9 165.4 427.9 165.4C426.1 165.4 424.4 166.2 423 167L424.1 169.1C425.2 168.4 426.3 167.9 427.4 167.9C428.8 167.9 429.3 168.8 429.4 170C424.6 170.5 422.6 171.8 422.6 174.3C422.6 176.3 424 177.8 426.1 177.8ZM427.1 175.4C426.2 175.4 425.5 175 425.5 174.1C425.5 173 426.5 172.2 429.4 171.9V174.2C428.6 175 428 175.4 427.1 175.4ZM435.6 182H438.7V178.4L438.6 176.5C439.5 177.3 440.5 177.8 441.5 177.8C444.1 177.8 446.5 175.5 446.5 171.4C446.5 167.8 444.7 165.4 441.9 165.4C440.6 165.4 439.4 166.1 438.4 167H438.3L438.1 165.7H435.6ZM440.8 175.3C440.2 175.3 439.4 175 438.7 174.4V169.2C439.5 168.4 440.2 168 441 168C442.6 168 443.3 169.2 443.3 171.5C443.3 174 442.2 175.3 440.8 175.3ZM449.1 177.5H452.2V165.7H449.1ZM450.7 163.8C451.7 163.8 452.5 163.2 452.5 162.1C452.5 161.1 451.7 160.5 450.7 160.5C449.6 160.5 448.9 161.1 448.9 162.1C448.9 163.2 449.6 163.8 450.7 163.8ZM457.3 177.8C458.4 177.8 459.2 176.9 459.2 175.8C459.2 174.6 458.4 173.8 457.3 173.8C456.1 173.8 455.3 174.6 455.3 175.8C455.3 176.9 456.1 177.8 457.3 177.8ZM465.2 177.8C466.6 177.8 467.7 177.1 468.7 176.2H468.9L469.1 177.5H471.6V170.6C471.6 167.2 470.1 165.4 467.1 165.4C465.2 165.4 463.5 166.2 462.2 167L463.3 169.1C464.4 168.4 465.4 167.9 466.5 167.9C467.9 167.9 468.5 168.8 468.5 170C463.8 170.5 461.7 171.8 461.7 174.3C461.7 176.3 463.1 177.8 465.2 177.8ZM466.2 175.4C465.3 175.4 464.7 175 464.7 174.1C464.7 173 465.6 172.2 468.5 171.9V174.2C467.8 175 467.1 175.4 466.2 175.4ZM474.7 177.5H477.8V165.7H474.7ZM476.3 163.8C477.3 163.8 478.1 163.2 478.1 162.1C478.1 161.1 477.3 160.5 476.3 160.5C475.2 160.5 474.5 161.1 474.5 162.1C474.5 163.2 475.2 163.8 476.3 163.8Z" fill="#635BFF"/>
|
||||
<path d="M488.5 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#635BFF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
|
||||
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
|
||||
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
|
||||
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
|
||||
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
|
||||
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
|
||||
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#0A2540"></path></g>
|
||||
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
|
||||
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
|
||||
<path d="M1644.6 120.5V128H1646.6L1644.9 128.6C1645.5 129.4 1646.1 130.1 1646.8 130.7C1645.8 131.1 1644.4 131.4 1642.7 131.7C1643.2 132.2 1643.8 133.1 1644 133.6C1646.1 133.2 1647.7 132.6 1648.9 131.9C1651.5 133.1 1654.8 133.3 1658.8 133.4C1658.9 132.7 1659.3 131.8 1659.7 131.3C1656 131.3 1653 131.2 1650.7 130.5C1651.4 129.7 1651.8 128.9 1652 128H1657.8V120.5H1652.3V119.5H1658.9V117.5H1643.1V119.5H1650V120.5ZM1646.7 125H1650V125.6L1650 126.2H1646.7ZM1652.3 126.2 1652.3 125.6V125H1655.7V126.2ZM1646.7 122.2H1650V123.4H1646.7ZM1652.3 122.2H1655.7V123.4H1652.3ZM1649.7 128C1649.5 128.5 1649.1 129 1648.6 129.5C1648 129.1 1647.4 128.6 1646.9 128ZM1667.9 116.6C1666.6 118.1 1664.5 119.6 1661.6 120.7C1662.1 121 1662.7 121.7 1663 122.2C1664.5 121.6 1665.8 120.9 1666.9 120.1H1671.4C1670.6 120.9 1669.6 121.6 1668.4 122.2C1667.9 121.7 1667.2 121.2 1666.6 120.8L1665 121.8C1665.5 122.2 1666 122.6 1666.5 123.1C1664.8 123.7 1663 124.2 1661.1 124.4C1661.5 124.9 1661.9 125.8 1662.1 126.3C1667.3 125.3 1672.5 123.1 1674.8 118.9L1673.4 118.1L1673 118.2H1669.2C1669.5 117.9 1669.9 117.5 1670.2 117.2ZM1670.8 123.1C1669.5 124.9 1667 126.6 1663.3 127.8C1663.7 128.2 1664.3 129 1664.6 129.5C1666.6 128.7 1668.4 127.8 1669.8 126.8H1673.9C1673.1 127.8 1672.1 128.6 1670.9 129.2C1670.3 128.7 1669.7 128.2 1669.1 127.8L1667.3 128.8C1667.8 129.2 1668.4 129.7 1668.9 130.1C1666.6 130.9 1663.9 131.4 1661 131.6C1661.3 132.1 1661.7 133.1 1661.8 133.7C1668.7 133 1674.7 131.1 1677.2 125.6L1675.7 124.7L1675.3 124.9H1672.1C1672.5 124.5 1672.9 124 1673.2 123.6Z" fill="#fff"/>
|
||||
</g>
|
||||
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#E3E8EE" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,57 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
|
||||
<defs>
|
||||
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
|
||||
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#000000" stop-opacity=".45"/><stop offset="1" stop-color="#000000" stop-opacity="0"/></radialGradient>
|
||||
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
|
||||
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#frame)">
|
||||
<rect width="1760" height="220" fill="#0A2540"/>
|
||||
<g clip-path="url(#slant)">
|
||||
<rect x="900" width="860" height="220" fill="url(#band)"/>
|
||||
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
|
||||
</g>
|
||||
<g transform="translate(72 36) scale(0.7)">
|
||||
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
|
||||
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
|
||||
<g stroke="#FFFFFF"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
|
||||
<g stroke="#8C86FF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
|
||||
</g>
|
||||
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#8C86FF"/>
|
||||
</g>
|
||||
<path d="M89.7 128.6C98.7 128.6 104.9 121.9 104.9 110.8C104.9 99.8 98.7 93.3 89.7 93.3C80.7 93.3 74.5 99.8 74.5 110.8C74.5 121.9 80.7 128.6 89.7 128.6ZM89.7 122.8C84.7 122.8 81.5 118.1 81.5 110.8C81.5 103.5 84.7 99.2 89.7 99.2C94.8 99.2 98 103.5 98 110.8C98 118.1 94.8 122.8 89.7 122.8ZM111.1 128H117.8V110.3C119.7 108.4 121.1 107.4 123.2 107.4C125.7 107.4 126.8 108.8 126.8 112.8V128H133.5V111.9C133.5 105.5 131.2 101.6 125.6 101.6C122.1 101.6 119.5 103.4 117.2 105.6H117.1L116.6 102.2H111.1ZM151.8 128.6C154.9 128.6 158.2 127.5 160.7 125.8L158.4 121.7C156.5 122.8 154.8 123.4 152.7 123.4C148.8 123.4 146.1 121.2 145.5 117.1H161.4C161.6 116.4 161.7 115.2 161.7 113.9C161.7 106.7 158 101.6 150.9 101.6C144.8 101.6 138.9 106.8 138.9 115.1C138.9 123.6 144.5 128.6 151.8 128.6ZM145.4 112.5C145.9 108.8 148.3 106.8 151 106.8C154.4 106.8 155.9 109 155.9 112.5ZM173.9 128H180.8L183.2 119.3H194.2L196.6 128H203.7L192.8 93.9H184.8ZM184.7 114 185.7 110.2C186.7 106.7 187.6 102.8 188.6 99.1H188.7C189.8 102.7 190.7 106.7 191.7 110.2L192.8 114ZM207.7 128H214.6V115.9H219.1C226.4 115.9 232.3 112.4 232.3 104.6C232.3 96.6 226.5 93.9 218.9 93.9H207.7ZM214.6 110.5V99.3H218.4C223.1 99.3 225.6 100.7 225.6 104.6C225.6 108.5 223.3 110.5 218.6 110.5ZM238.4 128H245.2V93.9H238.4ZM263.5 128H270.2V121.5L273.8 117.3L280 128H287.4L277.7 112.9L286.5 102.2H279.1L270.4 113.3H270.2V91.3H263.5ZM302.5 128.6C305.7 128.6 308.9 127.5 311.5 125.8L309.2 121.7C307.3 122.8 305.5 123.4 303.4 123.4C299.6 123.4 296.8 121.2 296.2 117.1H312.1C312.3 116.4 312.4 115.2 312.4 113.9C312.4 106.7 308.8 101.6 301.7 101.6C295.6 101.6 289.7 106.8 289.7 115.1C289.7 123.6 295.3 128.6 302.5 128.6ZM296.1 112.5C296.7 108.8 299.1 106.8 301.8 106.8C305.1 106.8 306.6 109 306.6 112.5ZM320.3 138.3C326 138.3 328.8 134.9 331 128.8L340.2 102.2H333.7L330.2 114.2C329.5 116.6 328.9 119.1 328.3 121.5H328.1C327.3 119 326.7 116.5 325.9 114.2L321.8 102.2H315L325 127.5L324.6 129.1C323.8 131.3 322.4 133 319.8 133C319.2 133 318.4 132.8 318 132.6L316.7 137.8C317.7 138.1 318.7 138.3 320.3 138.3ZM348.3 128.6C350.7 128.6 352.5 126.7 352.5 124.2C352.5 121.7 350.7 119.8 348.3 119.8C345.8 119.8 344 121.7 344 124.2C344 126.7 345.8 128.6 348.3 128.6ZM370.4 128H391.7V122.3H377.2V113.2H389.1V107.5H377.2V99.6H391.2V93.9H370.4ZM403.9 128H411.7L420.3 102.2H413.8L410.1 115.1C409.4 117.6 408.7 120.3 408 122.9H407.8C407 120.3 406.4 117.6 405.6 115.1L401.9 102.2H395.1ZM435.8 128.6C439 128.6 442.3 127.5 444.8 125.8L442.5 121.7C440.6 122.8 438.8 123.4 436.7 123.4C432.9 123.4 430.1 121.2 429.6 117.1H445.4C445.6 116.4 445.7 115.2 445.7 113.9C445.7 106.7 442.1 101.6 435 101.6C428.9 101.6 423 106.8 423 115.1C423 123.6 428.6 128.6 435.8 128.6ZM429.4 112.5C430 108.8 432.4 106.8 435.1 106.8C438.4 106.8 440 109 440 112.5ZM451.3 128H458.1V112.6C459.5 108.9 461.9 107.6 463.9 107.6C465 107.6 465.8 107.7 466.7 108L467.8 102.1C467 101.8 466.2 101.6 464.8 101.6C462.1 101.6 459.4 103.4 457.5 106.8H457.3L456.8 102.2H451.3ZM473.6 138.3C479.4 138.3 482.1 134.9 484.4 128.8L493.5 102.2H487.1L483.5 114.2C482.9 116.6 482.2 119.1 481.7 121.5H481.4C480.7 119 480.1 116.5 479.3 114.2L475.2 102.2H468.4L478.4 127.5L477.9 129.1C477.2 131.3 475.7 133 473.1 133C472.5 133 471.8 132.8 471.3 132.6L470.1 137.8C471.1 138.1 472.1 138.3 473.6 138.3ZM517.6 128.6C519.9 128.6 521.7 128.1 523.1 127.7L522 122.8C521.3 123 520.3 123.3 519.4 123.3C517.1 123.3 515.9 121.9 515.9 119V107.6H522.3V102.2H515.9V95.3H510.3L509.6 102.2L505.5 102.6V107.6H509.2V119C509.2 124.7 511.5 128.6 517.6 128.6ZM538.3 128.6C544.8 128.6 550.7 123.7 550.7 115.1C550.7 106.6 544.8 101.6 538.3 101.6C531.9 101.6 526 106.6 526 115.1C526 123.7 531.9 128.6 538.3 128.6ZM538.3 123.1C534.8 123.1 532.9 120 532.9 115.1C532.9 110.3 534.8 107.1 538.3 107.1C541.8 107.1 543.8 110.3 543.8 115.1C543.8 120 541.8 123.1 538.3 123.1ZM556.4 137.9H563.1V130L562.9 125.8C564.8 127.6 567.1 128.6 569.3 128.6C575 128.6 580.3 123.5 580.3 114.7C580.3 106.8 576.4 101.6 570.1 101.6C567.3 101.6 564.7 103.1 562.5 104.9H562.4L561.9 102.2H556.4ZM567.8 123.1C566.4 123.1 564.8 122.6 563.1 121.1V109.8C564.9 108 566.5 107.2 568.2 107.2C571.7 107.2 573.3 109.9 573.3 114.8C573.3 120.4 570.9 123.1 567.8 123.1ZM592.6 128H599.5L601.9 119.3H612.9L615.3 128H622.5L611.6 93.9H603.5ZM603.4 114 604.4 110.2C605.4 106.7 606.4 102.8 607.3 99.1H607.5C608.5 102.7 609.4 106.7 610.5 110.2L611.5 114ZM626.5 128H633.3V93.9H626.5ZM651.6 128H658.3V110.3C660.1 108.3 661.8 107.4 663.2 107.4C665.7 107.4 666.9 108.8 666.9 112.8V128H673.6V110.3C675.4 108.3 677.1 107.4 678.6 107.4C681 107.4 682.1 108.8 682.1 112.8V128H688.9V111.9C688.9 105.5 686.4 101.6 680.9 101.6C677.6 101.6 675.1 103.6 672.7 106.1C671.5 103.3 669.3 101.6 665.6 101.6C662.3 101.6 659.9 103.4 657.7 105.7H657.6L657.1 102.2H651.6ZM706.7 128.6C713.1 128.6 719 123.7 719 115.1C719 106.6 713.1 101.6 706.7 101.6C700.2 101.6 694.3 106.6 694.3 115.1C694.3 123.7 700.2 128.6 706.7 128.6ZM706.7 123.1C703.1 123.1 701.2 120 701.2 115.1C701.2 110.3 703.1 107.1 706.7 107.1C710.2 107.1 712.1 110.3 712.1 11Line truncated
|
||||
<rect x="72" y="148" width="262.7" height="44" rx="22" fill="#635BFF"/>
|
||||
<path d="M102.6 177.8C104.7 177.8 106.6 177 107.7 175.9V168.9H102.1V171.5H104.9V174.5C104.4 174.9 103.7 175.1 102.9 175.1C99.9 175.1 98.3 173.1 98.3 169.7C98.3 166.3 100.1 164.3 102.7 164.3C104.1 164.3 105 164.9 105.7 165.6L107.4 163.7C106.4 162.6 104.8 161.7 102.6 161.7C98.5 161.7 95.1 164.7 95.1 169.8C95.1 175 98.4 177.8 102.6 177.8ZM115.8 177.8C117.3 177.8 118.8 177.3 119.9 176.5L118.9 174.6C118 175.1 117.2 175.4 116.3 175.4C114.5 175.4 113.2 174.4 113 172.5H120.2C120.3 172.2 120.4 171.6 120.4 171.1C120.4 167.8 118.7 165.4 115.5 165.4C112.7 165.4 110 167.8 110 171.6C110 175.5 112.5 177.8 115.8 177.8ZM112.9 170.4C113.2 168.7 114.3 167.8 115.5 167.8C117 167.8 117.7 168.8 117.7 170.4ZM127.2 177.8C128.3 177.8 129.1 177.5 129.7 177.4L129.2 175.1C128.9 175.2 128.4 175.4 128 175.4C127 175.4 126.4 174.7 126.4 173.4V168.2H129.3V165.7H126.4V162.6H123.9L123.5 165.7L121.7 165.9V168.2H123.4V173.4C123.4 176 124.4 177.8 127.2 177.8ZM135.5 168.2H137.1V177.5H140.1V168.2H142.4V165.7H140.1V164.7C140.1 163.4 140.6 162.9 141.5 162.9C142 162.9 142.4 163 142.8 163.2L143.4 160.8C142.8 160.6 142 160.4 141.1 160.4C138.2 160.4 137.1 162.4 137.1 164.8V165.8L135.5 165.9ZM144.3 177.5H147.4V170.5C148.1 168.8 149.2 168.2 150.1 168.2C150.6 168.2 150.9 168.2 151.4 168.4L151.9 165.7C151.5 165.6 151.1 165.4 150.5 165.4C149.3 165.4 148 166.3 147.2 167.8H147.1L146.9 165.7H144.3ZM158.6 177.8C160.1 177.8 161.6 177.3 162.7 176.5L161.7 174.6C160.8 175.1 160 175.4 159 175.4C157.3 175.4 156 174.4 155.8 172.5H163C163.1 172.2 163.2 171.6 163.2 171.1C163.2 167.8 161.5 165.4 158.2 165.4C155.4 165.4 152.8 167.8 152.8 171.6C152.8 175.5 155.3 177.8 158.6 177.8ZM155.7 170.4C156 168.7 157 167.8 158.3 167.8C159.8 167.8 160.5 168.8 160.5 170.4ZM170.8 177.8C172.3 177.8 173.8 177.3 174.9 176.5L173.9 174.6C173 175.1 172.2 175.4 171.2 175.4C169.5 175.4 168.2 174.4 168 172.5H175.2C175.3 172.2 175.4 171.6 175.4 171.1C175.4 167.8 173.7 165.4 170.4 165.4C167.6 165.4 165 167.8 165 171.6C165 175.5 167.5 177.8 170.8 177.8ZM167.9 170.4C168.2 168.7 169.2 167.8 170.5 167.8C172 167.8 172.7 168.8 172.7 170.4ZM187 177.8C188 177.8 188.8 177.5 189.5 177.4L188.9 175.1C188.6 175.2 188.2 175.4 187.8 175.4C186.7 175.4 186.2 174.7 186.2 173.4V168.2H189.1V165.7H186.2V162.6H183.6L183.3 165.7L181.4 165.9V168.2H183.1V173.4C183.1 176 184.2 177.8 187 177.8ZM191.5 177.5H194.6V170.5C195.3 168.8 196.4 168.2 197.3 168.2C197.8 168.2 198.1 168.2 198.5 168.4L199 165.7C198.7 165.6 198.3 165.4 197.7 165.4C196.4 165.4 195.2 166.3 194.3 167.8H194.3L194 165.7H191.5ZM200.7 177.5H203.7V165.7H200.7ZM202.2 163.8C203.3 163.8 204 163.2 204 162.1C204 161.1 203.3 160.5 202.2 160.5C201.1 160.5 200.4 161.1 200.4 162.1C200.4 163.2 201.1 163.8 202.2 163.8ZM209.9 177.8C211.3 177.8 212.5 177.1 213.5 176.2H213.6L213.8 177.5H216.3V170.6C216.3 167.2 214.8 165.4 211.8 165.4C209.9 165.4 208.3 166.2 206.9 167L208 169.1C209.1 168.4 210.1 167.9 211.2 167.9C212.7 167.9 213.2 168.8 213.2 170C208.5 170.5 206.5 171.8 206.5 174.3C206.5 176.3 207.8 177.8 209.9 177.8ZM210.9 175.4C210 175.4 209.4 175 209.4 174.1C209.4 173 210.3 172.2 213.2 171.9V174.2C212.5 175 211.8 175.4 210.9 175.4ZM222.4 177.8C223.1 177.8 223.6 177.7 223.9 177.5L223.6 175.2C223.4 175.3 223.3 175.3 223.2 175.3C222.9 175.3 222.5 175 222.5 174.3V160.7H219.5V174.2C219.5 176.4 220.2 177.8 222.4 177.8ZM235.8 177.8C237.1 177.8 238.6 177.4 239.7 176.4L238.5 174.3C237.8 174.9 237 175.3 236.2 175.3C234.5 175.3 233.3 173.8 233.3 171.6C233.3 169.4 234.5 168 236.3 168C236.9 168 237.5 168.2 238.1 168.7L239.5 166.8C238.7 166 237.6 165.4 236.1 165.4C232.9 165.4 230.1 167.7 230.1 171.6C230.1 175.5 232.6 177.8 235.8 177.8ZM241.9 177.5H245V170.5C245.7 168.8 246.8 168.2 247.7 168.2C248.2 168.2 248.5 168.2 248.9 168.4L249.4 165.7C249.1 165.6 248.7 165.4 248.1 165.4C246.8 165.4 245.6 166.3 244.7 167.8H244.7L244.4 165.7H241.9ZM256.2 177.8C257.6 177.8 259.1 177.3 260.3 176.5L259.2 174.6C258.4 175.1 257.5 175.4 256.6 175.4C254.8 175.4 253.6 174.4 253.3 172.5H260.6C260.7 172.2 260.7 171.6 260.7 171.1C260.7 167.8 259 165.4 255.8 165.4C253 165.4 250.3 167.8 250.3 171.6C250.3 175.5 252.9 177.8 256.2 177.8ZM253.3 170.4C253.5 168.7 254.6 167.8 255.8 167.8C257.4 167.8 258.1 168.8 258.1 170.4ZM267.4 177.8C268.6 177.8 269.8 177.1 270.7 176.3H270.7L271 177.5H273.5V160.7H270.4V164.9L270.5 166.7C269.7 165.9 268.8 165.4 267.5 165.4C265 165.4 262.6 167.8 262.6 171.6C262.6 175.5 264.5 177.8 267.4 177.8ZM268.2 175.3C266.6 175.3 265.8 174 265.8 171.6C265.8 169.2 266.9 168 268.2 168C269 168 269.7 168.2 270.4 168.9V174C269.7 174.9 269 175.3 268.2 175.3ZM276.8 177.5H279.9V165.7H276.8ZM278.3 163.8C279.4 163.8 280.1 163.2 280.1 162.1C280.1 161.1 279.4 160.5 278.3 160.5C277.2 160.5 276.6 161.1 276.6 162.1C276.6 163.2 277.2 163.8 278.3 163.8ZM287.5 177.8C288.5 177.8 289.3 177.5 290 177.4L289.4 175.1C289.1 175.2 288.7 175.4 288.3 175.4C287.2 175.4 286.7 174.7 286.7 173.4V168.2H289.6V165.7H286.7V162.6H284.1L283.8 165.7L282 165.9V168.2H283.6V173.4C283.6 176 284.7 177.8 287.5 177.8ZM295.4 177.8C298.4 177.8 30Line truncated
|
||||
<path d="M311.7 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M364.4 177.5H367.9L369.1 172.4C369.3 171.3 369.5 170.2 369.7 168.9H369.8C370 170.2 370.3 171.3 370.5 172.4L371.7 177.5H375.4L378.3 165.7H375.4L374.1 171.5C373.9 172.7 373.8 173.8 373.6 175H373.5C373.2 173.8 373 172.7 372.7 171.5L371.2 165.7H368.5L367.1 171.5C366.8 172.7 366.6 173.8 366.4 175H366.2C366.1 173.8 365.9 172.7 365.7 171.5L364.4 165.7H361.3ZM383.4 177.8C384.8 177.8 385.9 177.1 387 176.2H387.1L387.3 177.5H389.8V170.6C389.8 167.2 388.3 165.4 385.3 165.4C383.4 165.4 381.7 166.2 380.4 167L381.5 169.1C382.6 168.4 383.6 167.9 384.7 167.9C386.2 167.9 386.7 168.8 386.7 170C382 170.5 379.9 171.8 379.9 174.3C379.9 176.3 381.3 177.8 383.4 177.8ZM384.4 175.4C383.5 175.4 382.9 175 382.9 174.1C382.9 173 383.8 172.2 386.7 171.9V174.2C386 175 385.3 175.4 384.4 175.4ZM392.9 177.5H396V169.4C396.9 168.6 397.5 168.1 398.5 168.1C399.6 168.1 400.1 168.7 400.1 170.5V177.5H403.2V170.2C403.2 167.2 402.1 165.4 399.6 165.4C398 165.4 396.8 166.3 395.8 167.3H395.7L395.5 165.7H392.9ZM410.5 177.8C411.8 177.8 412.9 177.1 413.8 176.3H413.9L414.1 177.5H416.6V160.7H413.5V164.9L413.6 166.7C412.8 165.9 412 165.4 410.7 165.4C408.1 165.4 405.7 167.8 405.7 171.6C405.7 175.5 407.6 177.8 410.5 177.8ZM411.3 175.3C409.8 175.3 408.9 174 408.9 171.6C408.9 169.2 410 168 411.3 168C412.1 168 412.8 168.2 413.5 168.9V174C412.9 174.9 412.2 175.3 411.3 175.3ZM422.8 177.8C424.2 177.8 425.3 177.1 426.3 176.2H426.5L426.7 177.5H429.2V170.6C429.2 167.2 427.7 165.4 424.7 165.4C422.8 165.4 421.1 166.2 419.8 167L420.9 169.1C422 168.4 423 167.9 424.1 167.9C425.6 167.9 426.1 168.8 426.1 170C421.4 170.5 419.3 171.8 419.3 174.3C419.3 176.3 420.7 177.8 422.8 177.8ZM423.8 175.4C422.9 175.4 422.3 175 422.3 174.1C422.3 173 423.2 172.2 426.1 171.9V174.2C425.4 175 424.7 175.4 423.8 175.4ZM432.3 182H435.4V178.4L435.3 176.5C436.2 177.3 437.2 177.8 438.2 177.8C440.8 177.8 443.2 175.5 443.2 171.4C443.2 167.8 441.5 165.4 438.6 165.4C437.3 165.4 436.1 166.1 435.1 167H435.1L434.9 165.7H432.3ZM437.6 175.3C436.9 175.3 436.2 175 435.4 174.4V169.2C436.2 168.4 436.9 168 437.7 168C439.3 168 440.1 169.2 440.1 171.5C440.1 174 438.9 175.3 437.6 175.3ZM445.9 177.5H448.9V165.7H445.9ZM447.4 163.8C448.5 163.8 449.2 163.2 449.2 162.1C449.2 161.1 448.5 160.5 447.4 160.5C446.3 160.5 445.6 161.1 445.6 162.1C445.6 163.2 446.3 163.8 447.4 163.8ZM454 177.8C455.1 177.8 455.9 176.9 455.9 175.8C455.9 174.6 455.1 173.8 454 173.8C452.9 173.8 452.1 174.6 452.1 175.8C452.1 176.9 452.9 177.8 454 177.8ZM461.9 177.8C463.3 177.8 464.5 177.1 465.5 176.2H465.6L465.8 177.5H468.3V170.6C468.3 167.2 466.8 165.4 463.8 165.4C462 165.4 460.3 166.2 458.9 167L460 169.1C461.1 168.4 462.2 167.9 463.2 167.9C464.7 167.9 465.2 168.8 465.2 170C460.5 170.5 458.5 171.8 458.5 174.3C458.5 176.3 459.8 177.8 461.9 177.8ZM463 175.4C462.1 175.4 461.4 175 461.4 174.1C461.4 173 462.4 172.2 465.2 171.9V174.2C464.5 175 463.9 175.4 463 175.4ZM471.5 177.5H474.6V165.7H471.5ZM473 163.8C474.1 163.8 474.8 163.2 474.8 162.1C474.8 161.1 474.1 160.5 473 160.5C471.9 160.5 471.2 161.1 471.2 162.1C471.2 163.2 471.9 163.8 473 163.8Z" fill="#8C86FF"/>
|
||||
<path d="M485.2 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#8C86FF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
|
||||
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
|
||||
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
|
||||
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
|
||||
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#FFFFFF" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
|
||||
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
|
||||
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#0A2540" stroke="#2A4A70" stroke-width="1.5"/>
|
||||
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#FFFFFF"></path></g>
|
||||
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
|
||||
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
|
||||
<path d="M1639.2 132H1641.6V126.4C1641.6 125.2 1641.4 123.3 1641.2 122.1H1641.3L1642.4 125.2L1644.4 130.8H1646L1648 125.2L1649.1 122.1H1649.2C1649 123.3 1648.8 125.2 1648.8 126.4V132H1651.3V118.7H1648.3L1646.1 124.9C1645.8 125.7 1645.6 126.6 1645.3 127.5H1645.2C1644.9 126.6 1644.7 125.7 1644.4 124.9L1642.1 118.7H1639.2ZM1658.5 132.3C1661 132.3 1663.4 130.3 1663.4 127C1663.4 123.6 1661 121.7 1658.5 121.7C1656 121.7 1653.7 123.6 1653.7 127C1653.7 130.3 1656 132.3 1658.5 132.3ZM1658.5 130.1C1657.1 130.1 1656.4 128.9 1656.4 127C1656.4 125.1 1657.1 123.8 1658.5 123.8C1659.9 123.8 1660.7 125.1 1660.7 127C1660.7 128.9 1659.9 130.1 1658.5 130.1ZM1665.6 132H1668.2V126C1668.8 124.5 1669.7 124 1670.5 124C1670.9 124 1671.2 124.1 1671.6 124.2L1672 121.9C1671.7 121.8 1671.4 121.7 1670.9 121.7C1669.8 121.7 1668.7 122.4 1668 123.7H1667.9L1667.7 121.9H1665.6ZM1677.8 132.3C1679.1 132.3 1680.3 131.8 1681.3 131.1L1680.4 129.5C1679.7 130 1679 130.2 1678.2 130.2C1676.7 130.2 1675.6 129.4 1675.4 127.7H1681.6C1681.7 127.5 1681.7 127 1681.7 126.5C1681.7 123.7 1680.3 121.7 1677.5 121.7C1675.1 121.7 1672.8 123.7 1672.8 127C1672.8 130.3 1675 132.3 1677.8 132.3ZM1675.3 125.9C1675.5 124.5 1676.5 123.7 1677.5 123.7C1678.8 123.7 1679.4 124.6 1679.4 125.9Z" fill="#fff"/>
|
||||
</g>
|
||||
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#1F3A5C" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,57 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1760" height="220" viewBox="0 0 1760 220" role="img" aria-label="WandAPI">
|
||||
<defs>
|
||||
<linearGradient id="logoW" gradientUnits="userSpaceOnUse" x1="4" y1="8" x2="44" y2="44"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<linearGradient id="band" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#635BFF"/><stop offset="1" stop-color="#00C2FF"/></linearGradient>
|
||||
<radialGradient id="bA" cx="1200" cy="-20" r="280" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#A960EE" stop-opacity="0.95"/><stop offset="1" stop-color="#A960EE" stop-opacity="0"/></radialGradient><radialGradient id="bB" cx="1720" cy="20" r="300" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#00D4FF" stop-opacity="0.9"/><stop offset="1" stop-color="#00D4FF" stop-opacity="0"/></radialGradient><radialGradient id="bC" cx="1500" cy="260" r="260" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#FF80B5" stop-opacity="0.65"/><stop offset="1" stop-color="#FF80B5" stop-opacity="0"/></radialGradient><radialGradient id="bD" cx="1000" cy="260" r="240" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#7A73FF" stop-opacity="0.9"/><stop offset="1" stop-color="#7A73FF" stop-opacity="0"/></radialGradient><radialGradient id="bE" cx="1380" cy="110" r="200" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#90E0FF" stop-opacity="0.55"/><stop offset="1" stop-color="#90E0FF" stop-opacity="0"/></radialGradient>
|
||||
<radialGradient id="shadow" cx=".5" cy=".5" r=".5"><stop offset="0" stop-color="#32325D" stop-opacity=".30"/><stop offset="1" stop-color="#32325D" stop-opacity="0"/></radialGradient>
|
||||
<clipPath id="frame"><rect width="1760" height="220" rx="20"/></clipPath>
|
||||
<clipPath id="slant"><polygon points="980,0 1760,0 1760,220 900,220"/></clipPath>
|
||||
</defs>
|
||||
<g clip-path="url(#frame)">
|
||||
<rect width="1760" height="220" fill="#FFFFFF"/>
|
||||
<g clip-path="url(#slant)">
|
||||
<rect x="900" width="860" height="220" fill="url(#band)"/>
|
||||
<rect x="900" width="860" height="220" fill="url(#bA)"/><rect x="900" width="860" height="220" fill="url(#bB)"/><rect x="900" width="860" height="220" fill="url(#bC)"/><rect x="900" width="860" height="220" fill="url(#bD)"/><rect x="900" width="860" height="220" fill="url(#bE)"/>
|
||||
</g>
|
||||
<g transform="translate(72 36) scale(0.7)">
|
||||
<g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="8">
|
||||
<polyline points="4,8 14,44 24,22 34,44 44,8" stroke="url(#logoW)"/>
|
||||
<g stroke="#0A2540"><circle cx="70" cy="32" r="12"/><line x1="82" y1="20" x2="82" y2="44"/><path d="M96 20V44M96 32a12 12 0 0 1 24 0V44"/><circle cx="146" cy="32" r="12"/><line x1="158" y1="8" x2="158" y2="44"/></g>
|
||||
<g stroke="#635BFF"><polyline points="172,44 188,8 204,44"/><path d="M218 44V8h8a10 10 0 0 1 0 20h-8"/><line x1="250" y1="8" x2="250" y2="44"/></g>
|
||||
</g>
|
||||
<path d="M24 -1Q24.9 5.1 31 6Q24.9 6.9 24 13Q23.1 6.9 17 6Q23.1 5.1 24 -1Z" fill="#635BFF"/>
|
||||
</g>
|
||||
<path d="M89.7 128.6C98.7 128.6 104.9 121.9 104.9 110.8C104.9 99.8 98.7 93.3 89.7 93.3C80.7 93.3 74.5 99.8 74.5 110.8C74.5 121.9 80.7 128.6 89.7 128.6ZM89.7 122.8C84.7 122.8 81.5 118.1 81.5 110.8C81.5 103.5 84.7 99.2 89.7 99.2C94.8 99.2 98 103.5 98 110.8C98 118.1 94.8 122.8 89.7 122.8ZM111.1 128H117.8V110.3C119.7 108.4 121.1 107.4 123.2 107.4C125.7 107.4 126.8 108.8 126.8 112.8V128H133.5V111.9C133.5 105.5 131.2 101.6 125.6 101.6C122.1 101.6 119.5 103.4 117.2 105.6H117.1L116.6 102.2H111.1ZM151.8 128.6C154.9 128.6 158.2 127.5 160.7 125.8L158.4 121.7C156.5 122.8 154.8 123.4 152.7 123.4C148.8 123.4 146.1 121.2 145.5 117.1H161.4C161.6 116.4 161.7 115.2 161.7 113.9C161.7 106.7 158 101.6 150.9 101.6C144.8 101.6 138.9 106.8 138.9 115.1C138.9 123.6 144.5 128.6 151.8 128.6ZM145.4 112.5C145.9 108.8 148.3 106.8 151 106.8C154.4 106.8 155.9 109 155.9 112.5ZM173.9 128H180.8L183.2 119.3H194.2L196.6 128H203.7L192.8 93.9H184.8ZM184.7 114 185.7 110.2C186.7 106.7 187.6 102.8 188.6 99.1H188.7C189.8 102.7 190.7 106.7 191.7 110.2L192.8 114ZM207.7 128H214.6V115.9H219.1C226.4 115.9 232.3 112.4 232.3 104.6C232.3 96.6 226.5 93.9 218.9 93.9H207.7ZM214.6 110.5V99.3H218.4C223.1 99.3 225.6 100.7 225.6 104.6C225.6 108.5 223.3 110.5 218.6 110.5ZM238.4 128H245.2V93.9H238.4ZM263.5 128H270.2V121.5L273.8 117.3L280 128H287.4L277.7 112.9L286.5 102.2H279.1L270.4 113.3H270.2V91.3H263.5ZM302.5 128.6C305.7 128.6 308.9 127.5 311.5 125.8L309.2 121.7C307.3 122.8 305.5 123.4 303.4 123.4C299.6 123.4 296.8 121.2 296.2 117.1H312.1C312.3 116.4 312.4 115.2 312.4 113.9C312.4 106.7 308.8 101.6 301.7 101.6C295.6 101.6 289.7 106.8 289.7 115.1C289.7 123.6 295.3 128.6 302.5 128.6ZM296.1 112.5C296.7 108.8 299.1 106.8 301.8 106.8C305.1 106.8 306.6 109 306.6 112.5ZM320.3 138.3C326 138.3 328.8 134.9 331 128.8L340.2 102.2H333.7L330.2 114.2C329.5 116.6 328.9 119.1 328.3 121.5H328.1C327.3 119 326.7 116.5 325.9 114.2L321.8 102.2H315L325 127.5L324.6 129.1C323.8 131.3 322.4 133 319.8 133C319.2 133 318.4 132.8 318 132.6L316.7 137.8C317.7 138.1 318.7 138.3 320.3 138.3ZM348.3 128.6C350.7 128.6 352.5 126.7 352.5 124.2C352.5 121.7 350.7 119.8 348.3 119.8C345.8 119.8 344 121.7 344 124.2C344 126.7 345.8 128.6 348.3 128.6ZM370.4 128H391.7V122.3H377.2V113.2H389.1V107.5H377.2V99.6H391.2V93.9H370.4ZM403.9 128H411.7L420.3 102.2H413.8L410.1 115.1C409.4 117.6 408.7 120.3 408 122.9H407.8C407 120.3 406.4 117.6 405.6 115.1L401.9 102.2H395.1ZM435.8 128.6C439 128.6 442.3 127.5 444.8 125.8L442.5 121.7C440.6 122.8 438.8 123.4 436.7 123.4C432.9 123.4 430.1 121.2 429.6 117.1H445.4C445.6 116.4 445.7 115.2 445.7 113.9C445.7 106.7 442.1 101.6 435 101.6C428.9 101.6 423 106.8 423 115.1C423 123.6 428.6 128.6 435.8 128.6ZM429.4 112.5C430 108.8 432.4 106.8 435.1 106.8C438.4 106.8 440 109 440 112.5ZM451.3 128H458.1V112.6C459.5 108.9 461.9 107.6 463.9 107.6C465 107.6 465.8 107.7 466.7 108L467.8 102.1C467 101.8 466.2 101.6 464.8 101.6C462.1 101.6 459.4 103.4 457.5 106.8H457.3L456.8 102.2H451.3ZM473.6 138.3C479.4 138.3 482.1 134.9 484.4 128.8L493.5 102.2H487.1L483.5 114.2C482.9 116.6 482.2 119.1 481.7 121.5H481.4C480.7 119 480.1 116.5 479.3 114.2L475.2 102.2H468.4L478.4 127.5L477.9 129.1C477.2 131.3 475.7 133 473.1 133C472.5 133 471.8 132.8 471.3 132.6L470.1 137.8C471.1 138.1 472.1 138.3 473.6 138.3ZM517.6 128.6C519.9 128.6 521.7 128.1 523.1 127.7L522 122.8C521.3 123 520.3 123.3 519.4 123.3C517.1 123.3 515.9 121.9 515.9 119V107.6H522.3V102.2H515.9V95.3H510.3L509.6 102.2L505.5 102.6V107.6H509.2V119C509.2 124.7 511.5 128.6 517.6 128.6ZM538.3 128.6C544.8 128.6 550.7 123.7 550.7 115.1C550.7 106.6 544.8 101.6 538.3 101.6C531.9 101.6 526 106.6 526 115.1C526 123.7 531.9 128.6 538.3 128.6ZM538.3 123.1C534.8 123.1 532.9 120 532.9 115.1C532.9 110.3 534.8 107.1 538.3 107.1C541.8 107.1 543.8 110.3 543.8 115.1C543.8 120 541.8 123.1 538.3 123.1ZM556.4 137.9H563.1V130L562.9 125.8C564.8 127.6 567.1 128.6 569.3 128.6C575 128.6 580.3 123.5 580.3 114.7C580.3 106.8 576.4 101.6 570.1 101.6C567.3 101.6 564.7 103.1 562.5 104.9H562.4L561.9 102.2H556.4ZM567.8 123.1C566.4 123.1 564.8 122.6 563.1 121.1V109.8C564.9 108 566.5 107.2 568.2 107.2C571.7 107.2 573.3 109.9 573.3 114.8C573.3 120.4 570.9 123.1 567.8 123.1ZM592.6 128H599.5L601.9 119.3H612.9L615.3 128H622.5L611.6 93.9H603.5ZM603.4 114 604.4 110.2C605.4 106.7 606.4 102.8 607.3 99.1H607.5C608.5 102.7 609.4 106.7 610.5 110.2L611.5 114ZM626.5 128H633.3V93.9H626.5ZM651.6 128H658.3V110.3C660.1 108.3 661.8 107.4 663.2 107.4C665.7 107.4 666.9 108.8 666.9 112.8V128H673.6V110.3C675.4 108.3 677.1 107.4 678.6 107.4C681 107.4 682.1 108.8 682.1 112.8V128H688.9V111.9C688.9 105.5 686.4 101.6 680.9 101.6C677.6 101.6 675.1 103.6 672.7 106.1C671.5 103.3 669.3 101.6 665.6 101.6C662.3 101.6 659.9 103.4 657.7 105.7H657.6L657.1 102.2H651.6ZM706.7 128.6C713.1 128.6 719 123.7 719 115.1C719 106.6 713.1 101.6 706.7 101.6C700.2 101.6 694.3 106.6 694.3 115.1C694.3 123.7 700.2 128.6 706.7 128.6ZM706.7 123.1C703.1 123.1 701.2 120 701.2 115.1C701.2 110.3 703.1 107.1 706.7 107.1C710.2 107.1 712.1 110.3 712.1 11Line truncated
|
||||
<rect x="72" y="148" width="262.7" height="44" rx="22" fill="#635BFF"/>
|
||||
<path d="M102.6 177.8C104.7 177.8 106.6 177 107.7 175.9V168.9H102.1V171.5H104.9V174.5C104.4 174.9 103.7 175.1 102.9 175.1C99.9 175.1 98.3 173.1 98.3 169.7C98.3 166.3 100.1 164.3 102.7 164.3C104.1 164.3 105 164.9 105.7 165.6L107.4 163.7C106.4 162.6 104.8 161.7 102.6 161.7C98.5 161.7 95.1 164.7 95.1 169.8C95.1 175 98.4 177.8 102.6 177.8ZM115.8 177.8C117.3 177.8 118.8 177.3 119.9 176.5L118.9 174.6C118 175.1 117.2 175.4 116.3 175.4C114.5 175.4 113.2 174.4 113 172.5H120.2C120.3 172.2 120.4 171.6 120.4 171.1C120.4 167.8 118.7 165.4 115.5 165.4C112.7 165.4 110 167.8 110 171.6C110 175.5 112.5 177.8 115.8 177.8ZM112.9 170.4C113.2 168.7 114.3 167.8 115.5 167.8C117 167.8 117.7 168.8 117.7 170.4ZM127.2 177.8C128.3 177.8 129.1 177.5 129.7 177.4L129.2 175.1C128.9 175.2 128.4 175.4 128 175.4C127 175.4 126.4 174.7 126.4 173.4V168.2H129.3V165.7H126.4V162.6H123.9L123.5 165.7L121.7 165.9V168.2H123.4V173.4C123.4 176 124.4 177.8 127.2 177.8ZM135.5 168.2H137.1V177.5H140.1V168.2H142.4V165.7H140.1V164.7C140.1 163.4 140.6 162.9 141.5 162.9C142 162.9 142.4 163 142.8 163.2L143.4 160.8C142.8 160.6 142 160.4 141.1 160.4C138.2 160.4 137.1 162.4 137.1 164.8V165.8L135.5 165.9ZM144.3 177.5H147.4V170.5C148.1 168.8 149.2 168.2 150.1 168.2C150.6 168.2 150.9 168.2 151.4 168.4L151.9 165.7C151.5 165.6 151.1 165.4 150.5 165.4C149.3 165.4 148 166.3 147.2 167.8H147.1L146.9 165.7H144.3ZM158.6 177.8C160.1 177.8 161.6 177.3 162.7 176.5L161.7 174.6C160.8 175.1 160 175.4 159 175.4C157.3 175.4 156 174.4 155.8 172.5H163C163.1 172.2 163.2 171.6 163.2 171.1C163.2 167.8 161.5 165.4 158.2 165.4C155.4 165.4 152.8 167.8 152.8 171.6C152.8 175.5 155.3 177.8 158.6 177.8ZM155.7 170.4C156 168.7 157 167.8 158.3 167.8C159.8 167.8 160.5 168.8 160.5 170.4ZM170.8 177.8C172.3 177.8 173.8 177.3 174.9 176.5L173.9 174.6C173 175.1 172.2 175.4 171.2 175.4C169.5 175.4 168.2 174.4 168 172.5H175.2C175.3 172.2 175.4 171.6 175.4 171.1C175.4 167.8 173.7 165.4 170.4 165.4C167.6 165.4 165 167.8 165 171.6C165 175.5 167.5 177.8 170.8 177.8ZM167.9 170.4C168.2 168.7 169.2 167.8 170.5 167.8C172 167.8 172.7 168.8 172.7 170.4ZM187 177.8C188 177.8 188.8 177.5 189.5 177.4L188.9 175.1C188.6 175.2 188.2 175.4 187.8 175.4C186.7 175.4 186.2 174.7 186.2 173.4V168.2H189.1V165.7H186.2V162.6H183.6L183.3 165.7L181.4 165.9V168.2H183.1V173.4C183.1 176 184.2 177.8 187 177.8ZM191.5 177.5H194.6V170.5C195.3 168.8 196.4 168.2 197.3 168.2C197.8 168.2 198.1 168.2 198.5 168.4L199 165.7C198.7 165.6 198.3 165.4 197.7 165.4C196.4 165.4 195.2 166.3 194.3 167.8H194.3L194 165.7H191.5ZM200.7 177.5H203.7V165.7H200.7ZM202.2 163.8C203.3 163.8 204 163.2 204 162.1C204 161.1 203.3 160.5 202.2 160.5C201.1 160.5 200.4 161.1 200.4 162.1C200.4 163.2 201.1 163.8 202.2 163.8ZM209.9 177.8C211.3 177.8 212.5 177.1 213.5 176.2H213.6L213.8 177.5H216.3V170.6C216.3 167.2 214.8 165.4 211.8 165.4C209.9 165.4 208.3 166.2 206.9 167L208 169.1C209.1 168.4 210.1 167.9 211.2 167.9C212.7 167.9 213.2 168.8 213.2 170C208.5 170.5 206.5 171.8 206.5 174.3C206.5 176.3 207.8 177.8 209.9 177.8ZM210.9 175.4C210 175.4 209.4 175 209.4 174.1C209.4 173 210.3 172.2 213.2 171.9V174.2C212.5 175 211.8 175.4 210.9 175.4ZM222.4 177.8C223.1 177.8 223.6 177.7 223.9 177.5L223.6 175.2C223.4 175.3 223.3 175.3 223.2 175.3C222.9 175.3 222.5 175 222.5 174.3V160.7H219.5V174.2C219.5 176.4 220.2 177.8 222.4 177.8ZM235.8 177.8C237.1 177.8 238.6 177.4 239.7 176.4L238.5 174.3C237.8 174.9 237 175.3 236.2 175.3C234.5 175.3 233.3 173.8 233.3 171.6C233.3 169.4 234.5 168 236.3 168C236.9 168 237.5 168.2 238.1 168.7L239.5 166.8C238.7 166 237.6 165.4 236.1 165.4C232.9 165.4 230.1 167.7 230.1 171.6C230.1 175.5 232.6 177.8 235.8 177.8ZM241.9 177.5H245V170.5C245.7 168.8 246.8 168.2 247.7 168.2C248.2 168.2 248.5 168.2 248.9 168.4L249.4 165.7C249.1 165.6 248.7 165.4 248.1 165.4C246.8 165.4 245.6 166.3 244.7 167.8H244.7L244.4 165.7H241.9ZM256.2 177.8C257.6 177.8 259.1 177.3 260.3 176.5L259.2 174.6C258.4 175.1 257.5 175.4 256.6 175.4C254.8 175.4 253.6 174.4 253.3 172.5H260.6C260.7 172.2 260.7 171.6 260.7 171.1C260.7 167.8 259 165.4 255.8 165.4C253 165.4 250.3 167.8 250.3 171.6C250.3 175.5 252.9 177.8 256.2 177.8ZM253.3 170.4C253.5 168.7 254.6 167.8 255.8 167.8C257.4 167.8 258.1 168.8 258.1 170.4ZM267.4 177.8C268.6 177.8 269.8 177.1 270.7 176.3H270.7L271 177.5H273.5V160.7H270.4V164.9L270.5 166.7C269.7 165.9 268.8 165.4 267.5 165.4C265 165.4 262.6 167.8 262.6 171.6C262.6 175.5 264.5 177.8 267.4 177.8ZM268.2 175.3C266.6 175.3 265.8 174 265.8 171.6C265.8 169.2 266.9 168 268.2 168C269 168 269.7 168.2 270.4 168.9V174C269.7 174.9 269 175.3 268.2 175.3ZM276.8 177.5H279.9V165.7H276.8ZM278.3 163.8C279.4 163.8 280.1 163.2 280.1 162.1C280.1 161.1 279.4 160.5 278.3 160.5C277.2 160.5 276.6 161.1 276.6 162.1C276.6 163.2 277.2 163.8 278.3 163.8ZM287.5 177.8C288.5 177.8 289.3 177.5 290 177.4L289.4 175.1C289.1 175.2 288.7 175.4 288.3 175.4C287.2 175.4 286.7 174.7 286.7 173.4V168.2H289.6V165.7H286.7V162.6H284.1L283.8 165.7L282 165.9V168.2H283.6V173.4C283.6 176 284.7 177.8 287.5 177.8ZM295.4 177.8C298.4 177.8 30Line truncated
|
||||
<path d="M311.7 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#fff" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<path d="M364.4 177.5H367.9L369.1 172.4C369.3 171.3 369.5 170.2 369.7 168.9H369.8C370 170.2 370.3 171.3 370.5 172.4L371.7 177.5H375.4L378.3 165.7H375.4L374.1 171.5C373.9 172.7 373.8 173.8 373.6 175H373.5C373.2 173.8 373 172.7 372.7 171.5L371.2 165.7H368.5L367.1 171.5C366.8 172.7 366.6 173.8 366.4 175H366.2C366.1 173.8 365.9 172.7 365.7 171.5L364.4 165.7H361.3ZM383.4 177.8C384.8 177.8 385.9 177.1 387 176.2H387.1L387.3 177.5H389.8V170.6C389.8 167.2 388.3 165.4 385.3 165.4C383.4 165.4 381.7 166.2 380.4 167L381.5 169.1C382.6 168.4 383.6 167.9 384.7 167.9C386.2 167.9 386.7 168.8 386.7 170C382 170.5 379.9 171.8 379.9 174.3C379.9 176.3 381.3 177.8 383.4 177.8ZM384.4 175.4C383.5 175.4 382.9 175 382.9 174.1C382.9 173 383.8 172.2 386.7 171.9V174.2C386 175 385.3 175.4 384.4 175.4ZM392.9 177.5H396V169.4C396.9 168.6 397.5 168.1 398.5 168.1C399.6 168.1 400.1 168.7 400.1 170.5V177.5H403.2V170.2C403.2 167.2 402.1 165.4 399.6 165.4C398 165.4 396.8 166.3 395.8 167.3H395.7L395.5 165.7H392.9ZM410.5 177.8C411.8 177.8 412.9 177.1 413.8 176.3H413.9L414.1 177.5H416.6V160.7H413.5V164.9L413.6 166.7C412.8 165.9 412 165.4 410.7 165.4C408.1 165.4 405.7 167.8 405.7 171.6C405.7 175.5 407.6 177.8 410.5 177.8ZM411.3 175.3C409.8 175.3 408.9 174 408.9 171.6C408.9 169.2 410 168 411.3 168C412.1 168 412.8 168.2 413.5 168.9V174C412.9 174.9 412.2 175.3 411.3 175.3ZM422.8 177.8C424.2 177.8 425.3 177.1 426.3 176.2H426.5L426.7 177.5H429.2V170.6C429.2 167.2 427.7 165.4 424.7 165.4C422.8 165.4 421.1 166.2 419.8 167L420.9 169.1C422 168.4 423 167.9 424.1 167.9C425.6 167.9 426.1 168.8 426.1 170C421.4 170.5 419.3 171.8 419.3 174.3C419.3 176.3 420.7 177.8 422.8 177.8ZM423.8 175.4C422.9 175.4 422.3 175 422.3 174.1C422.3 173 423.2 172.2 426.1 171.9V174.2C425.4 175 424.7 175.4 423.8 175.4ZM432.3 182H435.4V178.4L435.3 176.5C436.2 177.3 437.2 177.8 438.2 177.8C440.8 177.8 443.2 175.5 443.2 171.4C443.2 167.8 441.5 165.4 438.6 165.4C437.3 165.4 436.1 166.1 435.1 167H435.1L434.9 165.7H432.3ZM437.6 175.3C436.9 175.3 436.2 175 435.4 174.4V169.2C436.2 168.4 436.9 168 437.7 168C439.3 168 440.1 169.2 440.1 171.5C440.1 174 438.9 175.3 437.6 175.3ZM445.9 177.5H448.9V165.7H445.9ZM447.4 163.8C448.5 163.8 449.2 163.2 449.2 162.1C449.2 161.1 448.5 160.5 447.4 160.5C446.3 160.5 445.6 161.1 445.6 162.1C445.6 163.2 446.3 163.8 447.4 163.8ZM454 177.8C455.1 177.8 455.9 176.9 455.9 175.8C455.9 174.6 455.1 173.8 454 173.8C452.9 173.8 452.1 174.6 452.1 175.8C452.1 176.9 452.9 177.8 454 177.8ZM461.9 177.8C463.3 177.8 464.5 177.1 465.5 176.2H465.6L465.8 177.5H468.3V170.6C468.3 167.2 466.8 165.4 463.8 165.4C462 165.4 460.3 166.2 458.9 167L460 169.1C461.1 168.4 462.2 167.9 463.2 167.9C464.7 167.9 465.2 168.8 465.2 170C460.5 170.5 458.5 171.8 458.5 174.3C458.5 176.3 459.8 177.8 461.9 177.8ZM463 175.4C462.1 175.4 461.4 175 461.4 174.1C461.4 173 462.4 172.2 465.2 171.9V174.2C464.5 175 463.9 175.4 463 175.4ZM471.5 177.5H474.6V165.7H471.5ZM473 163.8C474.1 163.8 474.8 163.2 474.8 162.1C474.8 161.1 474.1 160.5 473 160.5C471.9 160.5 471.2 161.1 471.2 162.1C471.2 163.2 471.9 163.8 473 163.8Z" fill="#635BFF"/>
|
||||
<path d="M485.2 164.5l5.5 5.5-5.5 5.5" fill="none" stroke="#635BFF" stroke-width="2.75" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<rect x="1024" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1036" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1055.0 93.0) scale(1.4166666666666667)" ><path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fill-rule="nonzero"></path></g>
|
||||
<rect x="1108" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1120" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1139.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"></path></g>
|
||||
<rect x="1192" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1204" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1223.0 93.0) scale(1.4166666666666667)" ><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-0-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-1-_R_0_)"></path><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#lobe-icons-gemini-2-_R_0_)"></path><defs><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-0-_R_0_" x1="7" x2="11" y1="15.5" y2="12"><stop stop-color="#08B962"></stop><stop offset="1" stop-color="#08B962" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-1-_R_0_" x1="8" x2="11.5" y1="5.5" y2="11"><stop stop-color="#F94543"></stop><stop offset="1" stop-color="#F94543" stop-opacity="0"></stop></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="lobe-icons-gemini-2-_R_0_" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stop-color="#FABC12"></stop><stop offset=".46" stop-color="#FABC12" stop-opacity="0"></stop></linearGradient></defs></g>
|
||||
<rect x="1276" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1288" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1307.0 93.0) scale(1.4166666666666667)" ><path d="M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z" fill="#4D6BFE"></path></g>
|
||||
<rect x="1360" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1372" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1391.0 93.0) scale(1.4166666666666667)" fill="#0A2540" fill-rule="evenodd"><path d="M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184 1.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"></path></g>
|
||||
<rect x="1444" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1456" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1475.0 93.0) scale(1.4166666666666667)" ><path d="M19.713 2.825h-5.907c0-.251-.066-.503-.196-.728L12.819.728A1.46 1.46 0 0 0 11.559 0h-1.58c-.52 0-1 .275-1.26.728l-2.42 4.19a1.45 1.45 0 0 0 0 1.453l.791 1.37c.26.448.74.727 1.26.727h11.36c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-.79-1.37a1.46 1.46 0 0 0-1.26-.728zM.195 9.905l2.951 5.115a1.46 1.46 0 0 0-.531.531l-.791 1.37a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h4.84c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451L5.086 7.083a1.46 1.46 0 0 0-1.26-.728h-1.58c-.52 0-1 .276-1.26.728l-.79 1.37a1.45 1.45 0 0 0 0 1.452m15.888 13.367 2.951-5.115c.217.125.469.196.728.196h1.582c.52 0 1-.275 1.26-.728l.79-1.37a1.45 1.45 0 0 0 0-1.451l-2.42-4.191a1.46 1.46 0 0 0-1.259-.728h-1.582c-.52 0-1 .276-1.259.728l-5.678 9.838a1.45 1.45 0 0 0 0 1.452l.79 1.37c.26.448.74.727 1.26.727h1.582c.52 0 1-.275 1.26-.728z" fill="#082dff"></path></g>
|
||||
<rect x="1528" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1540" y="74" width="72" height="72" rx="18" fill="#FFFFFF" stroke="none" stroke-width="1.5"/>
|
||||
<g transform="translate(1559.0 93.0) scale(1.4166666666666667)" ><path d="M21.846 0a1.923 1.923 0 110 3.846H20.15a.226.226 0 01-.227-.226V1.923C19.923.861 20.784 0 21.846 0z" fill="#1783FF"></path><path d="M11.065 11.199l7.257-7.2c.137-.136.06-.41-.116-.41H14.3a.164.164 0 00-.117.051l-7.82 7.756c-.122.12-.302.013-.302-.179V3.82c0-.127-.083-.23-.185-.23H3.186c-.103 0-.186.103-.186.23V19.77c0 .128.083.23.186.23h2.69c.103 0 .186-.102.186-.23v-3.25c0-.069.025-.135.069-.178l2.424-2.406a.158.158 0 01.205-.023l6.484 4.772a7.677 7.677 0 003.453 1.283c.108.012.2-.095.2-.23v-3.06c0-.117-.07-.212-.164-.227a5.028 5.028 0 01-2.027-.807l-5.613-4.064c-.117-.078-.132-.279-.028-.381z" fill="#0A2540"></path></g>
|
||||
<rect x="1612" y="82" width="96" height="94" fill="url(#shadow)"/>
|
||||
<rect x="1624" y="74" width="72" height="72" rx="18" fill="#635BFF"/><rect x="1624.75" y="74.75" width="70.5" height="70.5" rx="17.25" fill="none" stroke="#fff" stroke-opacity=".35" stroke-width="1.5"/>
|
||||
<path d="M1651.0 99H1669.0M1660.0 90V108" stroke="#fff" stroke-width="3.5" stroke-linecap="round"/>
|
||||
<path d="M1639.2 132H1641.6V126.4C1641.6 125.2 1641.4 123.3 1641.2 122.1H1641.3L1642.4 125.2L1644.4 130.8H1646L1648 125.2L1649.1 122.1H1649.2C1649 123.3 1648.8 125.2 1648.8 126.4V132H1651.3V118.7H1648.3L1646.1 124.9C1645.8 125.7 1645.6 126.6 1645.3 127.5H1645.2C1644.9 126.6 1644.7 125.7 1644.4 124.9L1642.1 118.7H1639.2ZM1658.5 132.3C1661 132.3 1663.4 130.3 1663.4 127C1663.4 123.6 1661 121.7 1658.5 121.7C1656 121.7 1653.7 123.6 1653.7 127C1653.7 130.3 1656 132.3 1658.5 132.3ZM1658.5 130.1C1657.1 130.1 1656.4 128.9 1656.4 127C1656.4 125.1 1657.1 123.8 1658.5 123.8C1659.9 123.8 1660.7 125.1 1660.7 127C1660.7 128.9 1659.9 130.1 1658.5 130.1ZM1665.6 132H1668.2V126C1668.8 124.5 1669.7 124 1670.5 124C1670.9 124 1671.2 124.1 1671.6 124.2L1672 121.9C1671.7 121.8 1671.4 121.7 1670.9 121.7C1669.8 121.7 1668.7 122.4 1668 123.7H1667.9L1667.7 121.9H1665.6ZM1677.8 132.3C1679.1 132.3 1680.3 131.8 1681.3 131.1L1680.4 129.5C1679.7 130 1679 130.2 1678.2 130.2C1676.7 130.2 1675.6 129.4 1675.4 127.7H1681.6C1681.7 127.5 1681.7 127 1681.7 126.5C1681.7 123.7 1680.3 121.7 1677.5 121.7C1675.1 121.7 1672.8 123.7 1672.8 127C1672.8 130.3 1675 132.3 1677.8 132.3ZM1675.3 125.9C1675.5 124.5 1676.5 123.7 1677.5 123.7C1678.8 123.7 1679.4 124.6 1679.4 125.9Z" fill="#fff"/>
|
||||
</g>
|
||||
<rect x=".75" y=".75" width="1758.5" height="218.5" rx="19.25" fill="none" stroke="#E3E8EE" stroke-width="1.5"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 58 KiB |
@@ -1 +1 @@
|
||||
0.2.18
|
||||
0.2.19
|
||||
@@ -49,10 +49,11 @@ 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)
|
||||
settingService := service.ProvideSettingService(settingRepository, groupRepository, proxyRepository, configConfig)
|
||||
settingService := service.ProvideSettingService(scopedAdminKeyRepository, settingRepository, groupRepository, proxyRepository, configConfig)
|
||||
emailCache := repository.NewEmailCache(redisClient)
|
||||
emailService := service.NewEmailService(settingRepository, emailCache)
|
||||
turnstileVerifier := repository.NewTurnstileVerifier()
|
||||
@@ -82,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)
|
||||
@@ -97,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)
|
||||
@@ -327,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)
|
||||
|
||||
+12
-1
@@ -64,6 +64,8 @@ type Group struct {
|
||||
AllowImageGeneration bool `json:"allow_image_generation,omitempty"`
|
||||
// 是否允许该分组使用批量图片生成能力
|
||||
AllowBatchImageGeneration bool `json:"allow_batch_image_generation,omitempty"`
|
||||
// 图片生成是否按实际出图张数计费
|
||||
ImageCountBilling bool `json:"image_count_billing,omitempty"`
|
||||
// 图片生成是否使用独立倍率;false 表示共享分组有效倍率
|
||||
ImageRateIndependent bool `json:"image_rate_independent,omitempty"`
|
||||
// 图片生成独立倍率,仅 image_rate_independent=true 时生效
|
||||
@@ -262,7 +264,7 @@ func (*Group) scanValues(columns []string) ([]any, error) {
|
||||
switch columns[i] {
|
||||
case group.FieldI18n, group.FieldVideoModelPrices, group.FieldModelPricing, group.FieldModelRouting, group.FieldSupportedModelScopes, group.FieldMessagesDispatchModelConfig, group.FieldModelAllowlist, group.FieldCodexModelsManifestConfig, group.FieldReasoningEffortMappings:
|
||||
values[i] = new([]byte)
|
||||
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
|
||||
case group.FieldPeakRateEnabled, group.FieldIsExclusive, group.FieldAllowImageGeneration, group.FieldAllowBatchImageGeneration, group.FieldImageCountBilling, group.FieldImageRateIndependent, group.FieldVideoRateIndependent, group.FieldLongContextPricingEnabled, group.FieldClaudeCodeOnly, group.FieldModelRoutingEnabled, group.FieldMcpXMLInject, group.FieldAllowMessagesDispatch, group.FieldAllowLive, group.FieldForceOpenaiFast, group.FieldFreeOpenaiFast, group.FieldRequireOauthOnly, group.FieldRequirePrivacySet, group.FieldProfitControlEnabled:
|
||||
values[i] = new(sql.NullBool)
|
||||
case group.FieldRateMultiplier, group.FieldPeakRateMultiplier, group.FieldDailyLimitUsd, group.FieldWeeklyLimitUsd, group.FieldMonthlyLimitUsd, group.FieldImageRateMultiplier, group.FieldImagePrice1k, group.FieldImagePrice2k, group.FieldImagePrice4k, group.FieldBatchImageDiscountMultiplier, group.FieldBatchImageHoldMultiplier, group.FieldVideoRateMultiplier, group.FieldVideoPrice480p, group.FieldVideoPrice720p, group.FieldVideoPrice1080p, group.FieldWebSearchPricePerCall, group.FieldSearchPricePer1k, group.FieldAudioRealtimePricePerMin, group.FieldAudioTtsPricePerMillionChars, group.FieldAudioSttPricePerHour, group.FieldProfitMinMargin, group.FieldProfitSafetyBuffer:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
@@ -433,6 +435,12 @@ func (_m *Group) assignValues(columns []string, values []any) error {
|
||||
} else if value.Valid {
|
||||
_m.AllowBatchImageGeneration = value.Bool
|
||||
}
|
||||
case group.FieldImageCountBilling:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field image_count_billing", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ImageCountBilling = value.Bool
|
||||
}
|
||||
case group.FieldImageRateIndependent:
|
||||
if value, ok := values[i].(*sql.NullBool); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field image_rate_independent", values[i])
|
||||
@@ -886,6 +894,9 @@ func (_m *Group) String() string {
|
||||
builder.WriteString("allow_batch_image_generation=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.AllowBatchImageGeneration))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("image_count_billing=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ImageCountBilling))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("image_rate_independent=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ImageRateIndependent))
|
||||
builder.WriteString(", ")
|
||||
|
||||
@@ -60,6 +60,8 @@ const (
|
||||
FieldAllowImageGeneration = "allow_image_generation"
|
||||
// FieldAllowBatchImageGeneration holds the string denoting the allow_batch_image_generation field in the database.
|
||||
FieldAllowBatchImageGeneration = "allow_batch_image_generation"
|
||||
// FieldImageCountBilling holds the string denoting the image_count_billing field in the database.
|
||||
FieldImageCountBilling = "image_count_billing"
|
||||
// FieldImageRateIndependent holds the string denoting the image_rate_independent field in the database.
|
||||
FieldImageRateIndependent = "image_rate_independent"
|
||||
// FieldImageRateMultiplier holds the string denoting the image_rate_multiplier field in the database.
|
||||
@@ -247,6 +249,7 @@ var Columns = []string{
|
||||
FieldDefaultValidityDays,
|
||||
FieldAllowImageGeneration,
|
||||
FieldAllowBatchImageGeneration,
|
||||
FieldImageCountBilling,
|
||||
FieldImageRateIndependent,
|
||||
FieldImageRateMultiplier,
|
||||
FieldImagePrice1k,
|
||||
@@ -367,6 +370,8 @@ var (
|
||||
DefaultAllowImageGeneration bool
|
||||
// DefaultAllowBatchImageGeneration holds the default value on creation for the "allow_batch_image_generation" field.
|
||||
DefaultAllowBatchImageGeneration bool
|
||||
// DefaultImageCountBilling holds the default value on creation for the "image_count_billing" field.
|
||||
DefaultImageCountBilling bool
|
||||
// DefaultImageRateIndependent holds the default value on creation for the "image_rate_independent" field.
|
||||
DefaultImageRateIndependent bool
|
||||
// DefaultImageRateMultiplier holds the default value on creation for the "image_rate_multiplier" field.
|
||||
@@ -554,6 +559,11 @@ func ByAllowBatchImageGeneration(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAllowBatchImageGeneration, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByImageCountBilling orders the results by the image_count_billing field.
|
||||
func ByImageCountBilling(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldImageCountBilling, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByImageRateIndependent orders the results by the image_rate_independent field.
|
||||
func ByImageRateIndependent(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldImageRateIndependent, opts...).ToFunc()
|
||||
|
||||
@@ -160,6 +160,11 @@ func AllowBatchImageGeneration(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldAllowBatchImageGeneration, v))
|
||||
}
|
||||
|
||||
// ImageCountBilling applies equality check predicate on the "image_count_billing" field. It's identical to ImageCountBillingEQ.
|
||||
func ImageCountBilling(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldImageCountBilling, v))
|
||||
}
|
||||
|
||||
// ImageRateIndependent applies equality check predicate on the "image_rate_independent" field. It's identical to ImageRateIndependentEQ.
|
||||
func ImageRateIndependent(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldImageRateIndependent, v))
|
||||
@@ -1325,6 +1330,16 @@ func AllowBatchImageGenerationNEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldAllowBatchImageGeneration, v))
|
||||
}
|
||||
|
||||
// ImageCountBillingEQ applies the EQ predicate on the "image_count_billing" field.
|
||||
func ImageCountBillingEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldImageCountBilling, v))
|
||||
}
|
||||
|
||||
// ImageCountBillingNEQ applies the NEQ predicate on the "image_count_billing" field.
|
||||
func ImageCountBillingNEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldNEQ(FieldImageCountBilling, v))
|
||||
}
|
||||
|
||||
// ImageRateIndependentEQ applies the EQ predicate on the "image_rate_independent" field.
|
||||
func ImageRateIndependentEQ(v bool) predicate.Group {
|
||||
return predicate.Group(sql.FieldEQ(FieldImageRateIndependent, v))
|
||||
|
||||
@@ -322,6 +322,20 @@ func (_c *GroupCreate) SetNillableAllowBatchImageGeneration(v *bool) *GroupCreat
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (_c *GroupCreate) SetImageCountBilling(v bool) *GroupCreate {
|
||||
_c.mutation.SetImageCountBilling(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableImageCountBilling sets the "image_count_billing" field if the given value is not nil.
|
||||
func (_c *GroupCreate) SetNillableImageCountBilling(v *bool) *GroupCreate {
|
||||
if v != nil {
|
||||
_c.SetImageCountBilling(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (_c *GroupCreate) SetImageRateIndependent(v bool) *GroupCreate {
|
||||
_c.mutation.SetImageRateIndependent(v)
|
||||
@@ -1105,6 +1119,10 @@ func (_c *GroupCreate) defaults() error {
|
||||
v := group.DefaultAllowBatchImageGeneration
|
||||
_c.mutation.SetAllowBatchImageGeneration(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ImageCountBilling(); !ok {
|
||||
v := group.DefaultImageCountBilling
|
||||
_c.mutation.SetImageCountBilling(v)
|
||||
}
|
||||
if _, ok := _c.mutation.ImageRateIndependent(); !ok {
|
||||
v := group.DefaultImageRateIndependent
|
||||
_c.mutation.SetImageRateIndependent(v)
|
||||
@@ -1309,6 +1327,9 @@ func (_c *GroupCreate) check() error {
|
||||
if _, ok := _c.mutation.AllowBatchImageGeneration(); !ok {
|
||||
return &ValidationError{Name: "allow_batch_image_generation", err: errors.New(`ent: missing required field "Group.allow_batch_image_generation"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ImageCountBilling(); !ok {
|
||||
return &ValidationError{Name: "image_count_billing", err: errors.New(`ent: missing required field "Group.image_count_billing"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ImageRateIndependent(); !ok {
|
||||
return &ValidationError{Name: "image_rate_independent", err: errors.New(`ent: missing required field "Group.image_rate_independent"`)}
|
||||
}
|
||||
@@ -1546,6 +1567,10 @@ func (_c *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(group.FieldAllowBatchImageGeneration, field.TypeBool, value)
|
||||
_node.AllowBatchImageGeneration = value
|
||||
}
|
||||
if value, ok := _c.mutation.ImageCountBilling(); ok {
|
||||
_spec.SetField(group.FieldImageCountBilling, field.TypeBool, value)
|
||||
_node.ImageCountBilling = value
|
||||
}
|
||||
if value, ok := _c.mutation.ImageRateIndependent(); ok {
|
||||
_spec.SetField(group.FieldImageRateIndependent, field.TypeBool, value)
|
||||
_node.ImageRateIndependent = value
|
||||
@@ -2188,6 +2213,18 @@ func (u *GroupUpsert) UpdateAllowBatchImageGeneration() *GroupUpsert {
|
||||
return u
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (u *GroupUpsert) SetImageCountBilling(v bool) *GroupUpsert {
|
||||
u.Set(group.FieldImageCountBilling, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateImageCountBilling sets the "image_count_billing" field to the value that was provided on create.
|
||||
func (u *GroupUpsert) UpdateImageCountBilling() *GroupUpsert {
|
||||
u.SetExcluded(group.FieldImageCountBilling)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (u *GroupUpsert) SetImageRateIndependent(v bool) *GroupUpsert {
|
||||
u.Set(group.FieldImageRateIndependent, v)
|
||||
@@ -3355,6 +3392,20 @@ func (u *GroupUpsertOne) UpdateAllowBatchImageGeneration() *GroupUpsertOne {
|
||||
})
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (u *GroupUpsertOne) SetImageCountBilling(v bool) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetImageCountBilling(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateImageCountBilling sets the "image_count_billing" field to the value that was provided on create.
|
||||
func (u *GroupUpsertOne) UpdateImageCountBilling() *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateImageCountBilling()
|
||||
})
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (u *GroupUpsertOne) SetImageRateIndependent(v bool) *GroupUpsertOne {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
@@ -4815,6 +4866,20 @@ func (u *GroupUpsertBulk) UpdateAllowBatchImageGeneration() *GroupUpsertBulk {
|
||||
})
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (u *GroupUpsertBulk) SetImageCountBilling(v bool) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.SetImageCountBilling(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateImageCountBilling sets the "image_count_billing" field to the value that was provided on create.
|
||||
func (u *GroupUpsertBulk) UpdateImageCountBilling() *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
s.UpdateImageCountBilling()
|
||||
})
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (u *GroupUpsertBulk) SetImageRateIndependent(v bool) *GroupUpsertBulk {
|
||||
return u.Update(func(s *GroupUpsert) {
|
||||
|
||||
@@ -373,6 +373,20 @@ func (_u *GroupUpdate) SetNillableAllowBatchImageGeneration(v *bool) *GroupUpdat
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (_u *GroupUpdate) SetImageCountBilling(v bool) *GroupUpdate {
|
||||
_u.mutation.SetImageCountBilling(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableImageCountBilling sets the "image_count_billing" field if the given value is not nil.
|
||||
func (_u *GroupUpdate) SetNillableImageCountBilling(v *bool) *GroupUpdate {
|
||||
if v != nil {
|
||||
_u.SetImageCountBilling(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (_u *GroupUpdate) SetImageRateIndependent(v bool) *GroupUpdate {
|
||||
_u.mutation.SetImageRateIndependent(v)
|
||||
@@ -1665,6 +1679,9 @@ func (_u *GroupUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if value, ok := _u.mutation.AllowBatchImageGeneration(); ok {
|
||||
_spec.SetField(group.FieldAllowBatchImageGeneration, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ImageCountBilling(); ok {
|
||||
_spec.SetField(group.FieldImageCountBilling, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ImageRateIndependent(); ok {
|
||||
_spec.SetField(group.FieldImageRateIndependent, field.TypeBool, value)
|
||||
}
|
||||
@@ -2576,6 +2593,20 @@ func (_u *GroupUpdateOne) SetNillableAllowBatchImageGeneration(v *bool) *GroupUp
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (_u *GroupUpdateOne) SetImageCountBilling(v bool) *GroupUpdateOne {
|
||||
_u.mutation.SetImageCountBilling(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableImageCountBilling sets the "image_count_billing" field if the given value is not nil.
|
||||
func (_u *GroupUpdateOne) SetNillableImageCountBilling(v *bool) *GroupUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetImageCountBilling(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (_u *GroupUpdateOne) SetImageRateIndependent(v bool) *GroupUpdateOne {
|
||||
_u.mutation.SetImageRateIndependent(v)
|
||||
@@ -3898,6 +3929,9 @@ func (_u *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error)
|
||||
if value, ok := _u.mutation.AllowBatchImageGeneration(); ok {
|
||||
_spec.SetField(group.FieldAllowBatchImageGeneration, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ImageCountBilling(); ok {
|
||||
_spec.SetField(group.FieldImageCountBilling, field.TypeBool, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ImageRateIndependent(); ok {
|
||||
_spec.SetField(group.FieldImageRateIndependent, field.TypeBool, value)
|
||||
}
|
||||
|
||||
@@ -925,6 +925,7 @@ var (
|
||||
{Name: "default_validity_days", Type: field.TypeInt, Default: 30},
|
||||
{Name: "allow_image_generation", Type: field.TypeBool, Default: false},
|
||||
{Name: "allow_batch_image_generation", Type: field.TypeBool, Default: false},
|
||||
{Name: "image_count_billing", Type: field.TypeBool, Default: false},
|
||||
{Name: "image_rate_independent", Type: field.TypeBool, Default: false},
|
||||
{Name: "image_rate_multiplier", Type: field.TypeFloat64, Default: 1, SchemaType: map[string]string{"postgres": "decimal(10,4)"}},
|
||||
{Name: "image_price_1k", Type: field.TypeFloat64, Nullable: true, SchemaType: map[string]string{"postgres": "decimal(20,8)"}},
|
||||
@@ -1005,7 +1006,7 @@ var (
|
||||
{
|
||||
Name: "group_sort_order",
|
||||
Unique: false,
|
||||
Columns: []*schema.Column{GroupsColumns[50]},
|
||||
Columns: []*schema.Column{GroupsColumns[51]},
|
||||
},
|
||||
{
|
||||
Name: "idx_groups_duplicate_operation_id_active",
|
||||
|
||||
+55
-1
@@ -22109,6 +22109,7 @@ type GroupMutation struct {
|
||||
adddefault_validity_days *int
|
||||
allow_image_generation *bool
|
||||
allow_batch_image_generation *bool
|
||||
image_count_billing *bool
|
||||
image_rate_independent *bool
|
||||
image_rate_multiplier *float64
|
||||
addimage_rate_multiplier *float64
|
||||
@@ -23293,6 +23294,42 @@ func (m *GroupMutation) ResetAllowBatchImageGeneration() {
|
||||
m.allow_batch_image_generation = nil
|
||||
}
|
||||
|
||||
// SetImageCountBilling sets the "image_count_billing" field.
|
||||
func (m *GroupMutation) SetImageCountBilling(b bool) {
|
||||
m.image_count_billing = &b
|
||||
}
|
||||
|
||||
// ImageCountBilling returns the value of the "image_count_billing" field in the mutation.
|
||||
func (m *GroupMutation) ImageCountBilling() (r bool, exists bool) {
|
||||
v := m.image_count_billing
|
||||
if v == nil {
|
||||
return
|
||||
}
|
||||
return *v, true
|
||||
}
|
||||
|
||||
// OldImageCountBilling returns the old "image_count_billing" field's value of the Group entity.
|
||||
// If the Group object wasn't provided to the builder, the object is fetched from the database.
|
||||
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
|
||||
func (m *GroupMutation) OldImageCountBilling(ctx context.Context) (v bool, err error) {
|
||||
if !m.op.Is(OpUpdateOne) {
|
||||
return v, errors.New("OldImageCountBilling is only allowed on UpdateOne operations")
|
||||
}
|
||||
if m.id == nil || m.oldValue == nil {
|
||||
return v, errors.New("OldImageCountBilling requires an ID field in the mutation")
|
||||
}
|
||||
oldValue, err := m.oldValue(ctx)
|
||||
if err != nil {
|
||||
return v, fmt.Errorf("querying old value for OldImageCountBilling: %w", err)
|
||||
}
|
||||
return oldValue.ImageCountBilling, nil
|
||||
}
|
||||
|
||||
// ResetImageCountBilling resets all changes to the "image_count_billing" field.
|
||||
func (m *GroupMutation) ResetImageCountBilling() {
|
||||
m.image_count_billing = nil
|
||||
}
|
||||
|
||||
// SetImageRateIndependent sets the "image_rate_independent" field.
|
||||
func (m *GroupMutation) SetImageRateIndependent(b bool) {
|
||||
m.image_rate_independent = &b
|
||||
@@ -25958,7 +25995,7 @@ func (m *GroupMutation) Type() string {
|
||||
// order to get all numeric fields that were incremented/decremented, call
|
||||
// AddedFields().
|
||||
func (m *GroupMutation) Fields() []string {
|
||||
fields := make([]string, 0, 67)
|
||||
fields := make([]string, 0, 68)
|
||||
if m.created_at != nil {
|
||||
fields = append(fields, group.FieldCreatedAt)
|
||||
}
|
||||
@@ -26025,6 +26062,9 @@ func (m *GroupMutation) Fields() []string {
|
||||
if m.allow_batch_image_generation != nil {
|
||||
fields = append(fields, group.FieldAllowBatchImageGeneration)
|
||||
}
|
||||
if m.image_count_billing != nil {
|
||||
fields = append(fields, group.FieldImageCountBilling)
|
||||
}
|
||||
if m.image_rate_independent != nil {
|
||||
fields = append(fields, group.FieldImageRateIndependent)
|
||||
}
|
||||
@@ -26212,6 +26252,8 @@ func (m *GroupMutation) Field(name string) (ent.Value, bool) {
|
||||
return m.AllowImageGeneration()
|
||||
case group.FieldAllowBatchImageGeneration:
|
||||
return m.AllowBatchImageGeneration()
|
||||
case group.FieldImageCountBilling:
|
||||
return m.ImageCountBilling()
|
||||
case group.FieldImageRateIndependent:
|
||||
return m.ImageRateIndependent()
|
||||
case group.FieldImageRateMultiplier:
|
||||
@@ -26355,6 +26397,8 @@ func (m *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, e
|
||||
return m.OldAllowImageGeneration(ctx)
|
||||
case group.FieldAllowBatchImageGeneration:
|
||||
return m.OldAllowBatchImageGeneration(ctx)
|
||||
case group.FieldImageCountBilling:
|
||||
return m.OldImageCountBilling(ctx)
|
||||
case group.FieldImageRateIndependent:
|
||||
return m.OldImageRateIndependent(ctx)
|
||||
case group.FieldImageRateMultiplier:
|
||||
@@ -26608,6 +26652,13 @@ func (m *GroupMutation) SetField(name string, value ent.Value) error {
|
||||
}
|
||||
m.SetAllowBatchImageGeneration(v)
|
||||
return nil
|
||||
case group.FieldImageCountBilling:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field %s", value, name)
|
||||
}
|
||||
m.SetImageCountBilling(v)
|
||||
return nil
|
||||
case group.FieldImageRateIndependent:
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
@@ -27500,6 +27551,9 @@ func (m *GroupMutation) ResetField(name string) error {
|
||||
case group.FieldAllowBatchImageGeneration:
|
||||
m.ResetAllowBatchImageGeneration()
|
||||
return nil
|
||||
case group.FieldImageCountBilling:
|
||||
m.ResetImageCountBilling()
|
||||
return nil
|
||||
case group.FieldImageRateIndependent:
|
||||
m.ResetImageRateIndependent()
|
||||
return nil
|
||||
|
||||
@@ -1103,142 +1103,146 @@ func init() {
|
||||
groupDescAllowBatchImageGeneration := groupFields[18].Descriptor()
|
||||
// group.DefaultAllowBatchImageGeneration holds the default value on creation for the allow_batch_image_generation field.
|
||||
group.DefaultAllowBatchImageGeneration = groupDescAllowBatchImageGeneration.Default.(bool)
|
||||
// groupDescImageCountBilling is the schema descriptor for image_count_billing field.
|
||||
groupDescImageCountBilling := groupFields[19].Descriptor()
|
||||
// group.DefaultImageCountBilling holds the default value on creation for the image_count_billing field.
|
||||
group.DefaultImageCountBilling = groupDescImageCountBilling.Default.(bool)
|
||||
// groupDescImageRateIndependent is the schema descriptor for image_rate_independent field.
|
||||
groupDescImageRateIndependent := groupFields[19].Descriptor()
|
||||
groupDescImageRateIndependent := groupFields[20].Descriptor()
|
||||
// group.DefaultImageRateIndependent holds the default value on creation for the image_rate_independent field.
|
||||
group.DefaultImageRateIndependent = groupDescImageRateIndependent.Default.(bool)
|
||||
// groupDescImageRateMultiplier is the schema descriptor for image_rate_multiplier field.
|
||||
groupDescImageRateMultiplier := groupFields[20].Descriptor()
|
||||
groupDescImageRateMultiplier := groupFields[21].Descriptor()
|
||||
// group.DefaultImageRateMultiplier holds the default value on creation for the image_rate_multiplier field.
|
||||
group.DefaultImageRateMultiplier = groupDescImageRateMultiplier.Default.(float64)
|
||||
// groupDescBatchImageDiscountMultiplier is the schema descriptor for batch_image_discount_multiplier field.
|
||||
groupDescBatchImageDiscountMultiplier := groupFields[24].Descriptor()
|
||||
groupDescBatchImageDiscountMultiplier := groupFields[25].Descriptor()
|
||||
// group.DefaultBatchImageDiscountMultiplier holds the default value on creation for the batch_image_discount_multiplier field.
|
||||
group.DefaultBatchImageDiscountMultiplier = groupDescBatchImageDiscountMultiplier.Default.(float64)
|
||||
// groupDescBatchImageHoldMultiplier is the schema descriptor for batch_image_hold_multiplier field.
|
||||
groupDescBatchImageHoldMultiplier := groupFields[25].Descriptor()
|
||||
groupDescBatchImageHoldMultiplier := groupFields[26].Descriptor()
|
||||
// group.DefaultBatchImageHoldMultiplier holds the default value on creation for the batch_image_hold_multiplier field.
|
||||
group.DefaultBatchImageHoldMultiplier = groupDescBatchImageHoldMultiplier.Default.(float64)
|
||||
// groupDescVideoRateIndependent is the schema descriptor for video_rate_independent field.
|
||||
groupDescVideoRateIndependent := groupFields[26].Descriptor()
|
||||
groupDescVideoRateIndependent := groupFields[27].Descriptor()
|
||||
// group.DefaultVideoRateIndependent holds the default value on creation for the video_rate_independent field.
|
||||
group.DefaultVideoRateIndependent = groupDescVideoRateIndependent.Default.(bool)
|
||||
// groupDescVideoRateMultiplier is the schema descriptor for video_rate_multiplier field.
|
||||
groupDescVideoRateMultiplier := groupFields[27].Descriptor()
|
||||
groupDescVideoRateMultiplier := groupFields[28].Descriptor()
|
||||
// group.DefaultVideoRateMultiplier holds the default value on creation for the video_rate_multiplier field.
|
||||
group.DefaultVideoRateMultiplier = groupDescVideoRateMultiplier.Default.(float64)
|
||||
// groupDescSearchPricePer1k is the schema descriptor for search_price_per_1k field.
|
||||
groupDescSearchPricePer1k := groupFields[33].Descriptor()
|
||||
groupDescSearchPricePer1k := groupFields[34].Descriptor()
|
||||
// group.SearchPricePer1kValidator is a validator for the "search_price_per_1k" field. It is called by the builders before save.
|
||||
group.SearchPricePer1kValidator = groupDescSearchPricePer1k.Validators[0].(func(float64) error)
|
||||
// groupDescAudioRealtimePricePerMin is the schema descriptor for audio_realtime_price_per_min field.
|
||||
groupDescAudioRealtimePricePerMin := groupFields[34].Descriptor()
|
||||
groupDescAudioRealtimePricePerMin := groupFields[35].Descriptor()
|
||||
// group.AudioRealtimePricePerMinValidator is a validator for the "audio_realtime_price_per_min" field. It is called by the builders before save.
|
||||
group.AudioRealtimePricePerMinValidator = groupDescAudioRealtimePricePerMin.Validators[0].(func(float64) error)
|
||||
// groupDescAudioTtsPricePerMillionChars is the schema descriptor for audio_tts_price_per_million_chars field.
|
||||
groupDescAudioTtsPricePerMillionChars := groupFields[35].Descriptor()
|
||||
groupDescAudioTtsPricePerMillionChars := groupFields[36].Descriptor()
|
||||
// group.AudioTtsPricePerMillionCharsValidator is a validator for the "audio_tts_price_per_million_chars" field. It is called by the builders before save.
|
||||
group.AudioTtsPricePerMillionCharsValidator = groupDescAudioTtsPricePerMillionChars.Validators[0].(func(float64) error)
|
||||
// groupDescAudioSttPricePerHour is the schema descriptor for audio_stt_price_per_hour field.
|
||||
groupDescAudioSttPricePerHour := groupFields[36].Descriptor()
|
||||
groupDescAudioSttPricePerHour := groupFields[37].Descriptor()
|
||||
// group.AudioSttPricePerHourValidator is a validator for the "audio_stt_price_per_hour" field. It is called by the builders before save.
|
||||
group.AudioSttPricePerHourValidator = groupDescAudioSttPricePerHour.Validators[0].(func(float64) error)
|
||||
// groupDescLongContextPricingEnabled is the schema descriptor for long_context_pricing_enabled field.
|
||||
groupDescLongContextPricingEnabled := groupFields[37].Descriptor()
|
||||
groupDescLongContextPricingEnabled := groupFields[38].Descriptor()
|
||||
// group.DefaultLongContextPricingEnabled holds the default value on creation for the long_context_pricing_enabled field.
|
||||
group.DefaultLongContextPricingEnabled = groupDescLongContextPricingEnabled.Default.(bool)
|
||||
// groupDescClaudeCodeOnly is the schema descriptor for claude_code_only field.
|
||||
groupDescClaudeCodeOnly := groupFields[39].Descriptor()
|
||||
groupDescClaudeCodeOnly := groupFields[40].Descriptor()
|
||||
// group.DefaultClaudeCodeOnly holds the default value on creation for the claude_code_only field.
|
||||
group.DefaultClaudeCodeOnly = groupDescClaudeCodeOnly.Default.(bool)
|
||||
// groupDescModelRoutingEnabled is the schema descriptor for model_routing_enabled field.
|
||||
groupDescModelRoutingEnabled := groupFields[43].Descriptor()
|
||||
groupDescModelRoutingEnabled := groupFields[44].Descriptor()
|
||||
// group.DefaultModelRoutingEnabled holds the default value on creation for the model_routing_enabled field.
|
||||
group.DefaultModelRoutingEnabled = groupDescModelRoutingEnabled.Default.(bool)
|
||||
// groupDescMcpXMLInject is the schema descriptor for mcp_xml_inject field.
|
||||
groupDescMcpXMLInject := groupFields[44].Descriptor()
|
||||
groupDescMcpXMLInject := groupFields[45].Descriptor()
|
||||
// group.DefaultMcpXMLInject holds the default value on creation for the mcp_xml_inject field.
|
||||
group.DefaultMcpXMLInject = groupDescMcpXMLInject.Default.(bool)
|
||||
// groupDescSupportedModelScopes is the schema descriptor for supported_model_scopes field.
|
||||
groupDescSupportedModelScopes := groupFields[45].Descriptor()
|
||||
groupDescSupportedModelScopes := groupFields[46].Descriptor()
|
||||
// group.DefaultSupportedModelScopes holds the default value on creation for the supported_model_scopes field.
|
||||
group.DefaultSupportedModelScopes = groupDescSupportedModelScopes.Default.([]string)
|
||||
// groupDescSortOrder is the schema descriptor for sort_order field.
|
||||
groupDescSortOrder := groupFields[46].Descriptor()
|
||||
groupDescSortOrder := groupFields[47].Descriptor()
|
||||
// group.DefaultSortOrder holds the default value on creation for the sort_order field.
|
||||
group.DefaultSortOrder = groupDescSortOrder.Default.(int)
|
||||
// groupDescAllowMessagesDispatch is the schema descriptor for allow_messages_dispatch field.
|
||||
groupDescAllowMessagesDispatch := groupFields[47].Descriptor()
|
||||
groupDescAllowMessagesDispatch := groupFields[48].Descriptor()
|
||||
// group.DefaultAllowMessagesDispatch holds the default value on creation for the allow_messages_dispatch field.
|
||||
group.DefaultAllowMessagesDispatch = groupDescAllowMessagesDispatch.Default.(bool)
|
||||
// groupDescAllowLive is the schema descriptor for allow_live field.
|
||||
groupDescAllowLive := groupFields[48].Descriptor()
|
||||
groupDescAllowLive := groupFields[49].Descriptor()
|
||||
// group.DefaultAllowLive holds the default value on creation for the allow_live field.
|
||||
group.DefaultAllowLive = groupDescAllowLive.Default.(bool)
|
||||
// groupDescForceOpenaiFast is the schema descriptor for force_openai_fast field.
|
||||
groupDescForceOpenaiFast := groupFields[49].Descriptor()
|
||||
groupDescForceOpenaiFast := groupFields[50].Descriptor()
|
||||
// group.DefaultForceOpenaiFast holds the default value on creation for the force_openai_fast field.
|
||||
group.DefaultForceOpenaiFast = groupDescForceOpenaiFast.Default.(bool)
|
||||
// groupDescFreeOpenaiFast is the schema descriptor for free_openai_fast field.
|
||||
groupDescFreeOpenaiFast := groupFields[50].Descriptor()
|
||||
groupDescFreeOpenaiFast := groupFields[51].Descriptor()
|
||||
// group.DefaultFreeOpenaiFast holds the default value on creation for the free_openai_fast field.
|
||||
group.DefaultFreeOpenaiFast = groupDescFreeOpenaiFast.Default.(bool)
|
||||
// groupDescRequireOauthOnly is the schema descriptor for require_oauth_only field.
|
||||
groupDescRequireOauthOnly := groupFields[51].Descriptor()
|
||||
groupDescRequireOauthOnly := groupFields[52].Descriptor()
|
||||
// group.DefaultRequireOauthOnly holds the default value on creation for the require_oauth_only field.
|
||||
group.DefaultRequireOauthOnly = groupDescRequireOauthOnly.Default.(bool)
|
||||
// groupDescRequirePrivacySet is the schema descriptor for require_privacy_set field.
|
||||
groupDescRequirePrivacySet := groupFields[52].Descriptor()
|
||||
groupDescRequirePrivacySet := groupFields[53].Descriptor()
|
||||
// group.DefaultRequirePrivacySet holds the default value on creation for the require_privacy_set field.
|
||||
group.DefaultRequirePrivacySet = groupDescRequirePrivacySet.Default.(bool)
|
||||
// groupDescDefaultMappedModel is the schema descriptor for default_mapped_model field.
|
||||
groupDescDefaultMappedModel := groupFields[53].Descriptor()
|
||||
groupDescDefaultMappedModel := groupFields[54].Descriptor()
|
||||
// group.DefaultDefaultMappedModel holds the default value on creation for the default_mapped_model field.
|
||||
group.DefaultDefaultMappedModel = groupDescDefaultMappedModel.Default.(string)
|
||||
// group.DefaultMappedModelValidator is a validator for the "default_mapped_model" field. It is called by the builders before save.
|
||||
group.DefaultMappedModelValidator = groupDescDefaultMappedModel.Validators[0].(func(string) error)
|
||||
// groupDescMessagesDispatchModelConfig is the schema descriptor for messages_dispatch_model_config field.
|
||||
groupDescMessagesDispatchModelConfig := groupFields[54].Descriptor()
|
||||
groupDescMessagesDispatchModelConfig := groupFields[55].Descriptor()
|
||||
// group.DefaultMessagesDispatchModelConfig holds the default value on creation for the messages_dispatch_model_config field.
|
||||
group.DefaultMessagesDispatchModelConfig = groupDescMessagesDispatchModelConfig.Default.(domain.OpenAIMessagesDispatchModelConfig)
|
||||
// groupDescModelAllowlist is the schema descriptor for model_allowlist field.
|
||||
groupDescModelAllowlist := groupFields[55].Descriptor()
|
||||
groupDescModelAllowlist := groupFields[56].Descriptor()
|
||||
// group.DefaultModelAllowlist holds the default value on creation for the model_allowlist field.
|
||||
group.DefaultModelAllowlist = groupDescModelAllowlist.Default.(domain.GroupModelAllowlist)
|
||||
// groupDescCodexModelsManifestConfig is the schema descriptor for codex_models_manifest_config field.
|
||||
groupDescCodexModelsManifestConfig := groupFields[56].Descriptor()
|
||||
groupDescCodexModelsManifestConfig := groupFields[57].Descriptor()
|
||||
// group.DefaultCodexModelsManifestConfig holds the default value on creation for the codex_models_manifest_config field.
|
||||
group.DefaultCodexModelsManifestConfig = groupDescCodexModelsManifestConfig.Default.(domain.GroupCodexModelsManifestConfig)
|
||||
// groupDescRpmLimit is the schema descriptor for rpm_limit field.
|
||||
groupDescRpmLimit := groupFields[57].Descriptor()
|
||||
groupDescRpmLimit := groupFields[58].Descriptor()
|
||||
// group.DefaultRpmLimit holds the default value on creation for the rpm_limit field.
|
||||
group.DefaultRpmLimit = groupDescRpmLimit.Default.(int)
|
||||
// groupDescMaxReasoningEffort is the schema descriptor for max_reasoning_effort field.
|
||||
groupDescMaxReasoningEffort := groupFields[58].Descriptor()
|
||||
groupDescMaxReasoningEffort := groupFields[59].Descriptor()
|
||||
// group.DefaultMaxReasoningEffort holds the default value on creation for the max_reasoning_effort field.
|
||||
group.DefaultMaxReasoningEffort = groupDescMaxReasoningEffort.Default.(string)
|
||||
// group.MaxReasoningEffortValidator is a validator for the "max_reasoning_effort" field. It is called by the builders before save.
|
||||
group.MaxReasoningEffortValidator = groupDescMaxReasoningEffort.Validators[0].(func(string) error)
|
||||
// groupDescMaxReasoningEffortOverLimit is the schema descriptor for max_reasoning_effort_over_limit field.
|
||||
groupDescMaxReasoningEffortOverLimit := groupFields[59].Descriptor()
|
||||
groupDescMaxReasoningEffortOverLimit := groupFields[60].Descriptor()
|
||||
// group.DefaultMaxReasoningEffortOverLimit holds the default value on creation for the max_reasoning_effort_over_limit field.
|
||||
group.DefaultMaxReasoningEffortOverLimit = groupDescMaxReasoningEffortOverLimit.Default.(string)
|
||||
// group.MaxReasoningEffortOverLimitValidator is a validator for the "max_reasoning_effort_over_limit" field. It is called by the builders before save.
|
||||
group.MaxReasoningEffortOverLimitValidator = groupDescMaxReasoningEffortOverLimit.Validators[0].(func(string) error)
|
||||
// groupDescReasoningEffortMappings is the schema descriptor for reasoning_effort_mappings field.
|
||||
groupDescReasoningEffortMappings := groupFields[60].Descriptor()
|
||||
groupDescReasoningEffortMappings := groupFields[61].Descriptor()
|
||||
// group.DefaultReasoningEffortMappings holds the default value on creation for the reasoning_effort_mappings field.
|
||||
group.DefaultReasoningEffortMappings = groupDescReasoningEffortMappings.Default.([]domain.ReasoningEffortMapping)
|
||||
// groupDescProfitControlEnabled is the schema descriptor for profit_control_enabled field.
|
||||
groupDescProfitControlEnabled := groupFields[61].Descriptor()
|
||||
groupDescProfitControlEnabled := groupFields[62].Descriptor()
|
||||
// group.DefaultProfitControlEnabled holds the default value on creation for the profit_control_enabled field.
|
||||
group.DefaultProfitControlEnabled = groupDescProfitControlEnabled.Default.(bool)
|
||||
// groupDescProfitMinMargin is the schema descriptor for profit_min_margin field.
|
||||
groupDescProfitMinMargin := groupFields[62].Descriptor()
|
||||
groupDescProfitMinMargin := groupFields[63].Descriptor()
|
||||
// group.DefaultProfitMinMargin holds the default value on creation for the profit_min_margin field.
|
||||
group.DefaultProfitMinMargin = groupDescProfitMinMargin.Default.(float64)
|
||||
// groupDescProfitSafetyBuffer is the schema descriptor for profit_safety_buffer field.
|
||||
groupDescProfitSafetyBuffer := groupFields[63].Descriptor()
|
||||
groupDescProfitSafetyBuffer := groupFields[64].Descriptor()
|
||||
// group.DefaultProfitSafetyBuffer holds the default value on creation for the profit_safety_buffer field.
|
||||
group.DefaultProfitSafetyBuffer = groupDescProfitSafetyBuffer.Default.(float64)
|
||||
idempotencyrecordMixin := schema.IdempotencyRecord{}.Mixin()
|
||||
|
||||
@@ -109,6 +109,9 @@ func (Group) Fields() []ent.Field {
|
||||
field.Bool("allow_batch_image_generation").
|
||||
Default(false).
|
||||
Comment("是否允许该分组使用批量图片生成能力"),
|
||||
field.Bool("image_count_billing").
|
||||
Default(false).
|
||||
Comment("图片生成是否按实际出图张数计费"),
|
||||
field.Bool("image_rate_independent").
|
||||
Default(false).
|
||||
Comment("图片生成是否使用独立倍率;false 表示共享分组有效倍率"),
|
||||
|
||||
+13
-7
@@ -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
@@ -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=
|
||||
|
||||
@@ -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 {
|
||||
@@ -1109,6 +1160,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 +2135,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 +2488,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)
|
||||
@@ -2856,6 +2911,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)
|
||||
@@ -3371,6 +3429,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")
|
||||
|
||||
@@ -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()
|
||||
@@ -1887,6 +1900,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)
|
||||
}
|
||||
@@ -964,7 +964,11 @@ func (h *AccountHandler) GetByID(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
response.Success(c, h.buildAccountResponseWithRuntime(c.Request.Context(), account))
|
||||
result := h.buildAccountResponseWithRuntime(c.Request.Context(), account)
|
||||
if h.accountTestService != nil && account != nil && account.IsGrok() {
|
||||
result.GrokModelDiagnostics = h.accountTestService.GetGrokModelDiagnostics(c.Request.Context(), account)
|
||||
}
|
||||
response.Success(c, result)
|
||||
}
|
||||
|
||||
// CheckMixedChannel handles checking mixed channel risk for account-group binding.
|
||||
@@ -1419,7 +1423,9 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
|
||||
tokenInfo, err := h.openaiOAuthService.RefreshAccountToken(ctx, account)
|
||||
if err != nil {
|
||||
// 刷新失败但 access_token 可能仍有效,尝试设置隐私
|
||||
h.adminService.EnsureOpenAIPrivacy(ctx, account)
|
||||
service.AfterAccountCommit(ctx, func(committed context.Context) {
|
||||
h.adminService.EnsureOpenAIPrivacy(committed, account)
|
||||
})
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
@@ -1471,7 +1477,10 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
|
||||
if updateErr != nil {
|
||||
return nil, "", fmt.Errorf("failed to update credentials: %w", updateErr)
|
||||
}
|
||||
h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount)
|
||||
h.invalidateScopedAccountToken(ctx, updatedAccount)
|
||||
service.AfterAccountCommit(ctx, func(committed context.Context) {
|
||||
h.adminService.EnsureAntigravityPrivacy(committed, updatedAccount)
|
||||
})
|
||||
return updatedAccount, "missing_project_id_temporary", nil
|
||||
}
|
||||
|
||||
@@ -1527,17 +1536,19 @@ func (h *AccountHandler) refreshSingleAccount(ctx context.Context, account *serv
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// 刷新成功后,清除 token 缓存,确保下次请求使用新 token
|
||||
if h.tokenCacheInvalidator != nil {
|
||||
if invalidateErr := h.tokenCacheInvalidator.InvalidateToken(ctx, updatedAccount); invalidateErr != nil {
|
||||
log.Printf("[WARN] Failed to invalidate token cache for account %d: %v", updatedAccount.ID, invalidateErr)
|
||||
service.AfterAccountCommit(ctx, func(ctx context.Context) {
|
||||
// 刷新成功后,清除 token 缓存,确保下次请求使用新 token
|
||||
if h.tokenCacheInvalidator != nil {
|
||||
if invalidateErr := h.tokenCacheInvalidator.InvalidateToken(ctx, updatedAccount); invalidateErr != nil {
|
||||
log.Printf("[WARN] Failed to invalidate token cache for account %d: %v", updatedAccount.ID, invalidateErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// OpenAI OAuth: 刷新成功后检查并设置 privacy_mode
|
||||
h.adminService.EnsureOpenAIPrivacy(ctx, updatedAccount)
|
||||
// Antigravity OAuth: 刷新成功后检查并设置 privacy_mode
|
||||
h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount)
|
||||
// OpenAI OAuth: 刷新成功后检查并设置 privacy_mode
|
||||
h.adminService.EnsureOpenAIPrivacy(ctx, updatedAccount)
|
||||
// Antigravity OAuth: 刷新成功后检查并设置 privacy_mode
|
||||
h.adminService.EnsureAntigravityPrivacy(ctx, updatedAccount)
|
||||
})
|
||||
|
||||
return updatedAccount, "", nil
|
||||
}
|
||||
@@ -2804,6 +2815,10 @@ func (h *AccountHandler) GetAvailableModels(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
h.respondAvailableModels(c, account)
|
||||
}
|
||||
|
||||
func (h *AccountHandler) respondAvailableModels(c *gin.Context, account *service.Account) {
|
||||
// Handle OpenAI accounts
|
||||
if account.IsOpenAI() {
|
||||
// Prefer the shared, account-keyed upstream catalog. If discovery fails,
|
||||
@@ -3079,6 +3094,11 @@ func (h *AccountHandler) SyncUpstreamModels(c *gin.Context) {
|
||||
response.Error(c, http.StatusBadGateway, "Failed to sync upstream models from upstream")
|
||||
return
|
||||
}
|
||||
if catalog != nil && account != nil && account.IsGrok() && account.ID > 0 && h.accountTestService != nil {
|
||||
if latest, readErr := h.adminService.GetAccount(c.Request.Context(), account.ID); readErr == nil && latest != nil {
|
||||
catalog.GrokModelDiagnostics = h.accountTestService.GetGrokModelDiagnostics(c.Request.Context(), latest)
|
||||
}
|
||||
}
|
||||
|
||||
response.Success(c, catalog)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestAccountHandlerGrokModelDiagnosticsGetByID(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
upstream := &grokDiagHandlerUpstream{}
|
||||
account := grokDiagDetailAccount(t)
|
||||
account.Credentials["access_token"] = "access-secret"
|
||||
account.Credentials["refresh_token"] = "refresh-secret"
|
||||
handler, router := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: account}, upstream)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/accounts/25", nil))
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
body := rec.Body.String()
|
||||
require.Contains(t, body, `"current_concurrency"`)
|
||||
diag := grokDiagResponseObject(t, body)
|
||||
require.Equal(t, "fresh", diag["state"])
|
||||
require.Equal(t, "https://cli-chat-proxy.grok.com/v1/models", diag["endpoint"])
|
||||
require.Equal(t, []any{"grok-4.7"}, diag["models"])
|
||||
mappings, ok := diag["mappings"].([]any)
|
||||
require.True(t, ok)
|
||||
require.NotEmpty(t, mappings)
|
||||
got := grokDiagMappingsByRequested(t, mappings)
|
||||
require.Equal(t, "listed", got["friendly"]["status"])
|
||||
require.Equal(t, "grok-4.7", got["friendly"]["upstream"])
|
||||
require.Equal(t, "not_listed", got["composer-2.5"]["status"])
|
||||
require.Equal(t, "grok-composer-2.5-fast", got["composer-2.5"]["upstream"])
|
||||
require.Zero(t, upstream.calls)
|
||||
require.NotContains(t, body, "access-secret")
|
||||
require.NotContains(t, body, "refresh-secret")
|
||||
require.NotContains(t, body, `"models":null`)
|
||||
require.NotContains(t, body, `"mappings":null`)
|
||||
|
||||
raw, err := json.Marshal(handler.buildAccountResponseWithRuntime(context.Background(), &account))
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(raw), "grok_model_diagnostics")
|
||||
}
|
||||
|
||||
func TestAccountHandlerGrokModelDiagnosticsOmitsNonGrokAndMissingSnapshot(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
nonGrok := service.Account{ID: 3, Name: "claude", Platform: service.PlatformAnthropic, Type: service.AccountTypeOAuth, Status: service.StatusActive}
|
||||
_, nonGrokRouter := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: nonGrok}, &grokDiagHandlerUpstream{})
|
||||
nonGrokRec := httptest.NewRecorder()
|
||||
nonGrokRouter.ServeHTTP(nonGrokRec, httptest.NewRequest(http.MethodGet, "/accounts/3", nil))
|
||||
require.Equal(t, http.StatusOK, nonGrokRec.Code, nonGrokRec.Body.String())
|
||||
require.NotContains(t, nonGrokRec.Body.String(), "grok_model_diagnostics")
|
||||
|
||||
old := service.Account{
|
||||
ID: 25, Name: "old-grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, Status: service.StatusActive,
|
||||
Credentials: map[string]any{"access_token": "old-access-secret"},
|
||||
}
|
||||
_, oldRouter := newGrokDiagDetailRouter(&simpleModeAccountService{stubAdminService: newStubAdminService(), account: old}, &grokDiagHandlerUpstream{})
|
||||
oldRec := httptest.NewRecorder()
|
||||
oldRouter.ServeHTTP(oldRec, httptest.NewRequest(http.MethodGet, "/accounts/25", nil))
|
||||
require.Equal(t, http.StatusOK, oldRec.Code, oldRec.Body.String())
|
||||
diag := grokDiagResponseObject(t, oldRec.Body.String())
|
||||
require.Equal(t, "unknown", diag["state"])
|
||||
require.Empty(t, diag["models"])
|
||||
require.IsType(t, []any{}, diag["models"])
|
||||
require.IsType(t, []any{}, diag["mappings"])
|
||||
require.NotContains(t, oldRec.Body.String(), "old-access-secret")
|
||||
require.NotContains(t, oldRec.Body.String(), `"models":null`)
|
||||
require.NotContains(t, oldRec.Body.String(), `"mappings":null`)
|
||||
}
|
||||
|
||||
func TestAccountHandlerGrokModelDiagnosticsSyncRereadsLatestAccount(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
initial := &service.Account{
|
||||
ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey, Status: service.StatusActive,
|
||||
Credentials: map[string]any{
|
||||
"api_key": "sync-secret",
|
||||
"base_url": "https://relay.example.com/v1",
|
||||
"model_mapping": map[string]any{"friendly": "grok-4.7"},
|
||||
},
|
||||
}
|
||||
scope, err := service.NewGrokCatalogScope(25, service.AccountTypeAPIKey, "https://relay.example.com/v1/models")
|
||||
require.NoError(t, err)
|
||||
latestSnap := &service.GrokObservedModelsSnapshot{
|
||||
Models: []string{"grok-from-reread"},
|
||||
FetchedAt: time.Now().UTC().Add(-time.Minute).Format(time.RFC3339Nano),
|
||||
Scope: scope,
|
||||
}
|
||||
rawSnap, err := json.Marshal(latestSnap)
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(rawSnap, &decoded))
|
||||
latest := *initial
|
||||
latest.Extra = map[string]any{"grok_observed_models": decoded}
|
||||
adminSvc := &grokDiagRereadAdmin{stubAdminService: newStubAdminService(), first: initial, latest: &latest}
|
||||
repo := &grokDiagCatalogRepo{account: cloneGrokDiagAccount(initial)}
|
||||
upstream := &grokDiagHandlerUpstream{responses: []*http.Response{
|
||||
{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`))},
|
||||
{StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":"registry-down"}`))},
|
||||
}}
|
||||
router := newGrokDiagSyncRouter(adminSvc, repo, upstream)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/25/models/sync-upstream", nil))
|
||||
|
||||
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
|
||||
body := rec.Body.String()
|
||||
var payload struct {
|
||||
Data struct {
|
||||
Models []string `json:"models"`
|
||||
DiscoverySource string `json:"discovery_source"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &payload))
|
||||
require.Equal(t, []string{"grok-4.7"}, payload.Data.Models)
|
||||
require.Equal(t, "upstream", payload.Data.DiscoverySource)
|
||||
diag := grokDiagResponseObject(t, body)
|
||||
require.Equal(t, []any{"grok-from-reread"}, diag["models"])
|
||||
require.Equal(t, "fresh", diag["state"])
|
||||
require.GreaterOrEqual(t, adminSvc.calls, 2)
|
||||
require.NotContains(t, body, "sync-secret")
|
||||
require.NotContains(t, body, "registry-down")
|
||||
require.NotContains(t, body, `"models":null`)
|
||||
require.NotContains(t, body, `"mappings":null`)
|
||||
}
|
||||
|
||||
func TestAccountHandlerGrokModelDiagnosticsSyncErrorAndPreviewStayUnchanged(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
adminSvc := &simpleModeAccountService{stubAdminService: newStubAdminService(), account: service.Account{
|
||||
ID: 44, Platform: service.PlatformGrok, Type: service.AccountTypeAPIKey, Status: service.StatusActive,
|
||||
Credentials: map[string]any{"base_url": "https://relay.example.com/v1"},
|
||||
}}
|
||||
router := newGrokDiagSyncRouter(adminSvc, nil, &grokDiagHandlerUpstream{})
|
||||
errorRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(errorRec, httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/44/models/sync-upstream", nil))
|
||||
require.Equal(t, http.StatusBadRequest, errorRec.Code, errorRec.Body.String())
|
||||
require.Contains(t, errorRec.Body.String(), "No Grok API key is available")
|
||||
require.NotContains(t, errorRec.Body.String(), "grok_model_diagnostics")
|
||||
|
||||
previewRouter := newGrokDiagSyncRouter(newStubAdminService(), nil, &grokDiagHandlerUpstream{responses: []*http.Response{
|
||||
{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`))},
|
||||
{StatusCode: http.StatusBadGateway, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":"registry-secret"}`))},
|
||||
}})
|
||||
previewRec := httptest.NewRecorder()
|
||||
previewReq := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/models/sync-upstream-preview", bytes.NewBufferString(`{
|
||||
"platform":"grok","type":"apikey","base_url":"https://relay.example.com/v1","api_key":"preview-secret",
|
||||
"model_mapping":{"friendly":"grok-4.7"}
|
||||
}`))
|
||||
previewReq.Header.Set("Content-Type", "application/json")
|
||||
previewRouter.ServeHTTP(previewRec, previewReq)
|
||||
require.Equal(t, http.StatusOK, previewRec.Code, previewRec.Body.String())
|
||||
require.Contains(t, previewRec.Body.String(), `"models":["grok-4.7"]`)
|
||||
require.NotContains(t, previewRec.Body.String(), "grok_model_diagnostics")
|
||||
require.NotContains(t, previewRec.Body.String(), "preview-secret")
|
||||
require.NotContains(t, previewRec.Body.String(), "registry-secret")
|
||||
}
|
||||
|
||||
func newGrokDiagDetailRouter(adminSvc service.AdminService, upstream *grokDiagHandlerUpstream) (*AccountHandler, *gin.Engine) {
|
||||
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, newGrokDiagTestService(nil, upstream), nil, nil, nil, nil, nil)
|
||||
router := gin.New()
|
||||
router.GET("/accounts/:id", handler.GetByID)
|
||||
return handler, router
|
||||
}
|
||||
|
||||
func newGrokDiagSyncRouter(adminSvc service.AdminService, repo service.AccountRepository, upstream *grokDiagHandlerUpstream) *gin.Engine {
|
||||
handler := NewAccountHandler(adminSvc, nil, nil, nil, nil, nil, nil, nil, newGrokDiagTestService(repo, upstream), nil, nil, nil, nil, nil)
|
||||
router := gin.New()
|
||||
router.POST("/api/v1/admin/accounts/:id/models/sync-upstream", handler.SyncUpstreamModels)
|
||||
router.POST("/api/v1/admin/accounts/models/sync-upstream-preview", handler.SyncUpstreamModelsPreview)
|
||||
return router
|
||||
}
|
||||
|
||||
func newGrokDiagTestService(repo service.AccountRepository, upstream service.HTTPUpstream) *service.AccountTestService {
|
||||
return service.NewAccountTestService(repo, nil, nil, nil, nil, upstream, &config.Config{
|
||||
Security: config.SecurityConfig{URLAllowlist: config.URLAllowlistConfig{Enabled: false}},
|
||||
}, nil)
|
||||
}
|
||||
|
||||
func grokDiagDetailAccount(t *testing.T) service.Account {
|
||||
t.Helper()
|
||||
scope, err := service.NewGrokCatalogScope(25, service.AccountTypeOAuth, "https://cli-chat-proxy.grok.com/v1/models")
|
||||
require.NoError(t, err)
|
||||
snap := &service.GrokObservedModelsSnapshot{
|
||||
Models: []string{"grok-4.7"},
|
||||
FetchedAt: time.Now().UTC().Add(-time.Hour).Format(time.RFC3339Nano),
|
||||
Scope: scope,
|
||||
}
|
||||
raw, err := json.Marshal(snap)
|
||||
require.NoError(t, err)
|
||||
var decoded map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &decoded))
|
||||
return service.Account{
|
||||
ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, Status: service.StatusActive,
|
||||
Credentials: map[string]any{"model_mapping": map[string]any{
|
||||
"friendly": "grok-4.7",
|
||||
"composer-2.5": "composer-2.5",
|
||||
}},
|
||||
Extra: map[string]any{"grok_observed_models": decoded},
|
||||
}
|
||||
}
|
||||
|
||||
func grokDiagResponseObject(t *testing.T, body string) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &payload))
|
||||
data, ok := payload["data"].(map[string]any)
|
||||
require.True(t, ok, body)
|
||||
diag, ok := data["grok_model_diagnostics"].(map[string]any)
|
||||
require.True(t, ok, body)
|
||||
return diag
|
||||
}
|
||||
|
||||
func grokDiagMappingsByRequested(t *testing.T, mappings []any) map[string]map[string]any {
|
||||
t.Helper()
|
||||
out := make(map[string]map[string]any, len(mappings))
|
||||
for _, raw := range mappings {
|
||||
item, ok := raw.(map[string]any)
|
||||
require.True(t, ok)
|
||||
requested, _ := item["requested"].(string)
|
||||
out[requested] = item
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type grokDiagRereadAdmin struct {
|
||||
*stubAdminService
|
||||
first *service.Account
|
||||
latest *service.Account
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *grokDiagRereadAdmin) GetAccount(context.Context, int64) (*service.Account, error) {
|
||||
s.calls++
|
||||
if s.calls == 1 {
|
||||
return cloneGrokDiagAccount(s.first), nil
|
||||
}
|
||||
return cloneGrokDiagAccount(s.latest), nil
|
||||
}
|
||||
|
||||
type grokDiagCatalogRepo struct {
|
||||
service.AccountRepository
|
||||
mu sync.Mutex
|
||||
account *service.Account
|
||||
}
|
||||
|
||||
func (r *grokDiagCatalogRepo) GetByID(_ context.Context, id int64) (*service.Account, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.account == nil || r.account.ID != id {
|
||||
return nil, service.ErrAccountNotFound
|
||||
}
|
||||
return cloneGrokDiagAccount(r.account), nil
|
||||
}
|
||||
|
||||
func (r *grokDiagCatalogRepo) UpdateExtra(context.Context, int64, map[string]any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *grokDiagCatalogRepo) CompareAndSwapGrokObservedModels(_ context.Context, id int64, expected, next json.RawMessage) (bool, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.account == nil || r.account.ID != id {
|
||||
return false, nil
|
||||
}
|
||||
var current any
|
||||
if r.account.Extra != nil {
|
||||
current = r.account.Extra["grok_observed_models"]
|
||||
}
|
||||
currentJSON, err := json.Marshal(current)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var expectedValue any
|
||||
var currentValue any
|
||||
if err := json.Unmarshal(expected, &expectedValue); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := json.Unmarshal(currentJSON, ¤tValue); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !reflect.DeepEqual(expectedValue, currentValue) {
|
||||
return false, nil
|
||||
}
|
||||
var decoded any
|
||||
if err := json.Unmarshal(next, &decoded); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if r.account.Extra == nil {
|
||||
r.account.Extra = map[string]any{}
|
||||
}
|
||||
r.account.Extra["grok_observed_models"] = decoded
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func cloneGrokDiagAccount(src *service.Account) *service.Account {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := json.Marshal(src)
|
||||
if err != nil {
|
||||
copied := *src
|
||||
return &copied
|
||||
}
|
||||
var dst service.Account
|
||||
if err := json.Unmarshal(raw, &dst); err != nil {
|
||||
copied := *src
|
||||
return &copied
|
||||
}
|
||||
return &dst
|
||||
}
|
||||
|
||||
type grokDiagHandlerUpstream struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
responses []*http.Response
|
||||
}
|
||||
|
||||
func (u *grokDiagHandlerUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
u.calls++
|
||||
if len(u.responses) == 0 {
|
||||
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"grok-4.7"}]}`)), Header: make(http.Header)}, nil
|
||||
}
|
||||
resp := u.responses[0]
|
||||
u.responses = u.responses[1:]
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (u *grokDiagHandlerUpstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
|
||||
return u.Do(req, proxyURL, accountID, accountConcurrency)
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
@@ -136,6 +138,7 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) {
|
||||
"/?page=0",
|
||||
"/?page_size=0",
|
||||
"/?page_size=101",
|
||||
"/?page=9223372036854775807",
|
||||
}
|
||||
|
||||
gin.SetMode(gin.TestMode)
|
||||
@@ -149,6 +152,32 @@ func TestParseOpsOpenAITokenStatsFilter_InvalidParams(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOpsOpenAITokenStatsFilter_PaginationBoundaries(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, size := range []int{1, 20, 21, 100} {
|
||||
bound := math.MaxInt / size
|
||||
pages := []int{bound}
|
||||
if bound < math.MaxInt {
|
||||
pages = append(pages, bound+1)
|
||||
}
|
||||
for _, page := range pages {
|
||||
query := fmt.Sprintf("/?page=%d&page_size=%d", page, size)
|
||||
t.Run(query, func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodGet, query, nil)
|
||||
filter, err := parseOpsOpenAITokenStatsFilter(c)
|
||||
if page > bound {
|
||||
require.ErrorContains(t, err, "invalid page")
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, page, filter.Page)
|
||||
require.Equal(t, size, filter.PageSize)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOpsTimeRange(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
@@ -252,5 +252,5 @@ func (h *AnnouncementHandler) ListReadStatus(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Paginated(c, items, paginationResult.Total, page, pageSize)
|
||||
response.Paginated(c, adminAnnouncementReadResponse(c, items), paginationResult.Total, page, pageSize)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H {
|
||||
resource := adminaccess.Account{ID: a.ID, Type: a.Type, Platform: a.Platform, GroupIDs: a.GroupIDs}
|
||||
groups := []int64{}
|
||||
for _, g := range a.GroupIDs {
|
||||
if p.AllowsGroup("accounts.read", resource, g) {
|
||||
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}
|
||||
// 兼容原账户读取结构,仅返回模型映射,凭证及扩展字段继续脱敏。
|
||||
if p.AllowsAccount("accounts.read", resource) {
|
||||
mapping := map[string]string{}
|
||||
switch raw := a.Credentials["model_mapping"].(type) {
|
||||
case map[string]string:
|
||||
for source, target := range raw {
|
||||
mapping[source] = target
|
||||
}
|
||||
case map[string]any:
|
||||
for source, target := range raw {
|
||||
if value, ok := target.(string); ok {
|
||||
mapping[source] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
result["credentials"] = gin.H{"model_mapping": mapping}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// ScopedAdminKeyAccounts 在原处理器前完成独立授权和安全输出。
|
||||
func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) {
|
||||
principal := adminaccess.FromContext(c.Request.Context())
|
||||
if principal == nil {
|
||||
return
|
||||
}
|
||||
path := c.FullPath()
|
||||
if !strings.HasPrefix(path, "/api/v1/admin/accounts") {
|
||||
return
|
||||
}
|
||||
c.Abort()
|
||||
base := "/api/v1/admin/accounts"
|
||||
// 静态默认映射不读取任何账户;权限独立于账户查看及凭证写入。
|
||||
if path == base+"/antigravity/default-model-mapping" && c.Request.Method == "GET" {
|
||||
if !adminaccess.RouteAllowed(principal.Policy, c.Request.Method, path) {
|
||||
response.Error(c, 403, "默认模型读取未授权")
|
||||
return
|
||||
}
|
||||
h.GetAntigravityDefaultModelMapping(c)
|
||||
return
|
||||
}
|
||||
if path == base+"/import/codex-session" && c.Request.Method == "POST" {
|
||||
h.scopedAdminImportCodexSession(c)
|
||||
return
|
||||
}
|
||||
api, ok := h.adminService.(service.ScopedAdminAccounts)
|
||||
if !ok {
|
||||
response.Error(c, 503, "受限账户服务不可用")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
if path == base && c.Request.Method == "GET" {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
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"))
|
||||
if err != nil {
|
||||
response.Error(c, 503, "账户查询失败")
|
||||
return
|
||||
}
|
||||
items := make([]gin.H, 0, len(accounts))
|
||||
for i := range accounts {
|
||||
if principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: accounts[i].ID, GroupIDs: accounts[i].GroupIDs, Type: accounts[i].Type, Platform: accounts[i].Platform}) {
|
||||
items = append(items, scopedAdminAccountDTO(&accounts[i], principal.Policy))
|
||||
}
|
||||
}
|
||||
response.Success(c, gin.H{"items": items, "total": total, "page": page, "page_size": 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)}) {
|
||||
response.Error(c, 404, "账户不存在")
|
||||
return
|
||||
}
|
||||
if path == base+"/:id/models" {
|
||||
h.respondAvailableModels(c, a)
|
||||
return
|
||||
}
|
||||
response.Success(c, scopedAdminAccountDTO(a, principal.Policy))
|
||||
return
|
||||
}
|
||||
if path == base+"/bulk-update" && c.Request.Method == "POST" {
|
||||
h.scopedAdminBulkUpdate(c, api)
|
||||
return
|
||||
}
|
||||
|
||||
fields := map[string]json.RawMessage{}
|
||||
action := ""
|
||||
var run func(context.Context, *service.Account) (*service.Account, error)
|
||||
switch {
|
||||
case path == base && c.Request.Method == "POST":
|
||||
id = 0
|
||||
if c.ShouldBindJSON(&fields) != nil || fields == nil {
|
||||
response.Error(c, 400, "请求格式无效")
|
||||
return
|
||||
}
|
||||
case path == base+"/:id" && c.Request.Method == "PUT":
|
||||
if c.ShouldBindJSON(&fields) != nil || len(fields) == 0 {
|
||||
response.Error(c, 400, "请求格式无效")
|
||||
return
|
||||
}
|
||||
case path == base+"/:id" && c.Request.Method == "DELETE":
|
||||
action = "accounts.delete"
|
||||
case path == base+"/:id/schedulable" && c.Request.Method == "POST":
|
||||
if c.ShouldBindJSON(&fields) != nil || len(fields) != 1 || fields["schedulable"] == nil {
|
||||
response.Error(c, 400, "仅支持 schedulable 字段")
|
||||
return
|
||||
}
|
||||
case path == base+"/:id/clear-error" && c.Request.Method == "POST":
|
||||
action = "accounts.recover"
|
||||
case path == base+"/:id/refresh" && c.Request.Method == "POST":
|
||||
action = "accounts.refresh"
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
|
||||
defer cancel()
|
||||
a, err := h.adminService.GetAccount(ctx, id)
|
||||
if err != nil || a == nil || !principal.Policy.AllowsAccount(action, adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) {
|
||||
response.Error(c, 404, "账户不存在")
|
||||
return
|
||||
}
|
||||
|
||||
run = func(txctx context.Context, a *service.Account) (*service.Account, error) {
|
||||
updated, _, err := h.refreshSingleAccount(txctx, a)
|
||||
if err != nil {
|
||||
code := infraerrors.Code(err)
|
||||
if code != 400 && code != 403 && code != 404 && code != 409 && code != 503 {
|
||||
return nil, infraerrors.New(502, "SCOPED_REFRESH_FAILED", "上游刷新失败")
|
||||
}
|
||||
}
|
||||
return updated, err
|
||||
}
|
||||
default:
|
||||
response.Error(c, 403, "此账户操作未开放给受限管理密钥")
|
||||
return
|
||||
}
|
||||
if id <= 0 && path != base {
|
||||
response.Error(c, 400, "账户 ID 无效")
|
||||
return
|
||||
}
|
||||
a, err := api.ScopedAdminWrite(ctx, id, action, fields, run)
|
||||
if err != nil {
|
||||
scopedAdminAccountError(c, err)
|
||||
return
|
||||
}
|
||||
if id > 0 && fields["credentials"] != nil {
|
||||
h.invalidateScopedAccountToken(ctx, a)
|
||||
}
|
||||
response.Success(c, gin.H{"id": a.ID, "status": a.Status})
|
||||
}
|
||||
func accountGroupIDs(a *service.Account) []int64 {
|
||||
if a == nil {
|
||||
return nil
|
||||
}
|
||||
return a.GroupIDs
|
||||
}
|
||||
func accountType(a *service.Account) string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
return a.Type
|
||||
}
|
||||
func accountPlatform(a *service.Account) string {
|
||||
if a == nil {
|
||||
return ""
|
||||
}
|
||||
return a.Platform
|
||||
}
|
||||
|
||||
func scopedAdminAccountError(c *gin.Context, err error) {
|
||||
code, message := scopedAdminAccountErrorDetails(err)
|
||||
response.Error(c, code, message)
|
||||
}
|
||||
|
||||
func scopedAdminAccountErrorDetails(err error) (int, string) {
|
||||
code := infraerrors.Code(err)
|
||||
message := "账户服务暂不可用"
|
||||
switch code {
|
||||
case 400:
|
||||
message = "请求参数无效"
|
||||
case 403:
|
||||
message = "操作未授权"
|
||||
case 404:
|
||||
message = "账户不存在"
|
||||
case 409:
|
||||
message = "账户正在处理,请稍后重试"
|
||||
case 502:
|
||||
message = "上游刷新失败"
|
||||
default:
|
||||
code = 503
|
||||
}
|
||||
return code, message
|
||||
}
|
||||
|
||||
// scopedAdminBulkUpdate 沿用旧批量接口与结果结构,每个账户仍走锁内逐字段验权。
|
||||
func (h *AccountHandler) scopedAdminBulkUpdate(c *gin.Context, api service.ScopedAdminAccounts) {
|
||||
var fields map[string]json.RawMessage
|
||||
if c.ShouldBindJSON(&fields) != nil || fields == nil {
|
||||
response.Error(c, 400, "请求格式无效")
|
||||
return
|
||||
}
|
||||
var ids []int64
|
||||
if json.Unmarshal(fields["account_ids"], &ids) != nil || len(ids) == 0 || len(ids) > 100 {
|
||||
response.Error(c, 400, "请明确指定 1 至 100 个账户 ID")
|
||||
return
|
||||
}
|
||||
delete(fields, "account_ids")
|
||||
// 不把全站筛选条件传给原批量服务,以免绕开账户范围。
|
||||
if _, exists := fields["filters"]; exists || len(fields) == 0 {
|
||||
response.Error(c, 400, "受限批量更新须明确指定账户及修改字段")
|
||||
return
|
||||
}
|
||||
uniqueIDs := make([]int64, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if id <= 0 {
|
||||
response.Error(c, 400, "账户 ID 无效")
|
||||
return
|
||||
}
|
||||
if !slices.Contains(uniqueIDs, id) {
|
||||
uniqueIDs = append(uniqueIDs, id)
|
||||
}
|
||||
}
|
||||
result := service.BulkUpdateAccountsResult{SuccessIDs: []int64{}, FailedIDs: []int64{}, Results: []service.BulkUpdateAccountResult{}}
|
||||
for _, id := range uniqueIDs {
|
||||
account, err := api.ScopedAdminWrite(c.Request.Context(), id, "", fields, nil)
|
||||
item := service.BulkUpdateAccountResult{AccountID: id, Success: err == nil}
|
||||
if err != nil {
|
||||
_, item.Error = scopedAdminAccountErrorDetails(err)
|
||||
result.Failed++
|
||||
result.FailedIDs = append(result.FailedIDs, id)
|
||||
} else {
|
||||
if fields["credentials"] != nil {
|
||||
h.invalidateScopedAccountToken(c.Request.Context(), account)
|
||||
}
|
||||
result.Success++
|
||||
result.SuccessIDs = append(result.SuccessIDs, id)
|
||||
}
|
||||
result.Results = append(result.Results, item)
|
||||
}
|
||||
response.Success(c, result)
|
||||
}
|
||||
|
||||
// 凭证写入必须在数据库提交成功后清理令牌缓存,回滚不能发布旧状态。
|
||||
func (h *AccountHandler) invalidateScopedAccountToken(ctx context.Context, account *service.Account) {
|
||||
if h.tokenCacheInvalidator == nil || account == nil {
|
||||
return
|
||||
}
|
||||
service.AfterAccountCommit(ctx, func(committed context.Context) {
|
||||
_ = h.tokenCacheInvalidator.InvalidateToken(committed, account)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestScopedAdminAccountDTORedactsSecretsAndForeignGroups(t *testing.T) {
|
||||
p := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}
|
||||
a := &service.Account{ID: 9, Type: "oauth", GroupIDs: []int64{1, 2}, Credentials: map[string]any{"access_token": "TOP_SECRET", "refresh_token": "REFRESH_SECRET", "base_url": "URL_SECRET", "model_mapping": map[string]any{"alias": "target", "invalid": map[string]any{"token": "NESTED_SECRET"}}}, Extra: map[string]any{"private": "EXTRA_SECRET"}}
|
||||
body, _ := json.Marshal(scopedAdminAccountDTO(a, p))
|
||||
s := string(body)
|
||||
if strings.Contains(s, "SECRET") || strings.Contains(s, "extra") {
|
||||
t.Fatalf("泄漏敏感字段: %s", s)
|
||||
}
|
||||
require.Contains(t, s, `"credentials":{"model_mapping":{"alias":"target"}}`)
|
||||
if !strings.Contains(s, `"group_ids":[1]`) {
|
||||
t.Fatalf("泄漏越权组: %s", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedAdminAccountErrorsAreClassifiedAndRedacted(t *testing.T) {
|
||||
for _, code := range []int{400, 403, 404, 409, 502, 503, 500} {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
scopedAdminAccountError(c, infraerrors.New(code, "secret", "TOP_SECRET"))
|
||||
want := code
|
||||
if code == 500 {
|
||||
want = 503
|
||||
}
|
||||
if w.Code != want || strings.Contains(w.Body.String(), "TOP_SECRET") {
|
||||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
scopedAdminAccountError(c, errors.New("TOP_SECRET"))
|
||||
if w.Code != 503 || strings.Contains(w.Body.String(), "TOP_SECRET") {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
}
|
||||
func TestScopedAdminAccountMiddlewareKeepsJWTAndDeniesUnavailableService(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, restricted := range []bool{false, true} {
|
||||
r := gin.New()
|
||||
h := &AccountHandler{}
|
||||
r.Use(func(c *gin.Context) {
|
||||
if restricted {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{}))
|
||||
}
|
||||
})
|
||||
r.Use(h.ScopedAdminKeyAccounts)
|
||||
r.GET("/api/v1/admin/accounts", func(c *gin.Context) { c.Status(204) })
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts", nil))
|
||||
want := 204
|
||||
if restricted {
|
||||
want = 503
|
||||
}
|
||||
if w.Code != want {
|
||||
t.Fatalf("restricted=%v status=%d", restricted, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 批量入口必须使用受限服务,不得回落到嵌入的全权 BulkUpdateAccounts。
|
||||
type scopedBulkAccountService struct {
|
||||
service.AdminService
|
||||
calls []int64
|
||||
fields map[string]json.RawMessage
|
||||
}
|
||||
|
||||
func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]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) {
|
||||
s.calls = append(s.calls, id)
|
||||
s.fields = fields
|
||||
switch id {
|
||||
case 2:
|
||||
return nil, infraerrors.NotFound("SECRET", "TOP_SECRET")
|
||||
case 3:
|
||||
return nil, infraerrors.Forbidden("SECRET", "TOP_SECRET")
|
||||
case 4:
|
||||
return nil, errors.New("TOP_SECRET")
|
||||
}
|
||||
return &service.Account{ID: id}, nil
|
||||
}
|
||||
|
||||
func TestScopedAdminBulkUpdateValidatesTargetsAndRedactsResults(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tc := range []struct {
|
||||
body string
|
||||
status int
|
||||
ids []int64
|
||||
}{
|
||||
{`{"account_ids":[1,2,1,3,4],"credentials":{"model_mapping":{"alias":"target"}}}`, 200, []int64{1, 2, 3, 4}},
|
||||
{`null`, 400, nil},
|
||||
{`{"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
{`{"account_ids":[],"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
{`{"account_ids":[1,0],"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
{`{"account_ids":[1,-1],"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
{`{"account_ids":[1]}`, 400, nil},
|
||||
{`{"account_ids":[1],"filters":{},"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
{`{"account_ids":[1.5],"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
{`{"account_ids":[` + strings.Repeat("1,", 100) + `1],"credentials":{"model_mapping":{}}}`, 400, nil},
|
||||
} {
|
||||
t.Run(tc.body, func(t *testing.T) {
|
||||
svc := &scopedBulkAccountService{}
|
||||
h := &AccountHandler{adminService: svc}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("POST", "/api/v1/admin/accounts/bulk-update", strings.NewReader(tc.body))
|
||||
h.scopedAdminBulkUpdate(c, svc)
|
||||
require.Equal(t, tc.status, w.Code, w.Body.String())
|
||||
require.Equal(t, tc.ids, svc.calls)
|
||||
require.NotContains(t, w.Body.String(), "SECRET")
|
||||
if tc.status == 200 {
|
||||
body, err := json.Marshal(svc.fields)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `{"credentials":{"model_mapping":{"alias":"target"}}}`, string(body))
|
||||
var result struct {
|
||||
Data service.BulkUpdateAccountsResult `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
|
||||
require.Equal(t, 1, result.Data.Success)
|
||||
require.Equal(t, 3, result.Data.Failed)
|
||||
require.Equal(t, []int64{1}, result.Data.SuccessIDs)
|
||||
require.Equal(t, []int64{2, 3, 4}, result.Data.FailedIDs)
|
||||
require.Equal(t, "账户不存在", result.Data.Results[1].Error)
|
||||
require.Equal(t, "操作未授权", result.Data.Results[2].Error)
|
||||
require.Equal(t, "账户服务暂不可用", result.Data.Results[3].Error)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type scopedCodexSessionImportRequest struct {
|
||||
CodexSessionImportRequest
|
||||
ProxyMode string `json:"proxy_mode"`
|
||||
RandomProxy bool `json:"random_proxy"`
|
||||
}
|
||||
|
||||
func validateScopedCodexRequest(req scopedCodexSessionImportRequest) error {
|
||||
if _, err := service.NormalizeAccountProxyMode(req.ProxyMode, req.ProxyID, req.RandomProxy); err != nil {
|
||||
return err
|
||||
}
|
||||
if req.GroupIDs == nil || (req.ConfirmMixedChannelRisk != nil && *req.ConfirmMixedChannelRisk) {
|
||||
return infraerrors.BadRequest("SCOPED_CODEX_INPUT", "须明确提供 group_ids,不能跳过分组风险检查")
|
||||
}
|
||||
if (req.Concurrency != nil && *req.Concurrency < 0) || (req.Priority != nil && *req.Priority < 0) || (req.LoadFactor != nil && (*req.LoadFactor < 1 || *req.LoadFactor > 10000)) || (req.RateMultiplier != nil && *req.RateMultiplier < 0) {
|
||||
return infraerrors.BadRequest("SCOPED_CODEX_INPUT", "导入参数无效")
|
||||
}
|
||||
for key := range req.CredentialExtras {
|
||||
if key != "base_url" && key != "model_mapping" {
|
||||
return infraerrors.BadRequest("SCOPED_CODEX_FIELD", "credential_extras 仅支持独立授权的 base_url 和 model_mapping")
|
||||
}
|
||||
}
|
||||
for key, value := range req.Extra {
|
||||
valid := false
|
||||
switch key {
|
||||
case "codex_fingerprint_mode", "openai_oauth_responses_websockets_v2_mode":
|
||||
_, valid = value.(string)
|
||||
case "openai_oauth_responses_websockets_v2_enabled":
|
||||
_, valid = value.(bool)
|
||||
}
|
||||
if !valid {
|
||||
return infraerrors.BadRequest("SCOPED_CODEX_FIELD", "extra 包含不支持的字段或值类型")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *AccountHandler) scopedAdminImportCodexSession(c *gin.Context) {
|
||||
var req scopedCodexSessionImportRequest
|
||||
if c.ShouldBindJSON(&req) != nil {
|
||||
response.BadRequest(c, "导入请求格式无效")
|
||||
return
|
||||
}
|
||||
if err := validateScopedCodexRequest(req); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
|
||||
if err != nil || len(entries) == 0 {
|
||||
response.BadRequest(c, "请输入有效的 accessToken 或 Codex session JSON")
|
||||
return
|
||||
}
|
||||
api, ok := h.adminService.(service.ScopedAdminCodexAccounts)
|
||||
if !ok {
|
||||
response.Error(c, 503, "受限导入服务不可用")
|
||||
return
|
||||
}
|
||||
principal := adminaccess.FromContext(c.Request.Context())
|
||||
if principal == nil || !adminaccess.RouteAllowed(principal.Policy, c.Request.Method, c.FullPath()) {
|
||||
response.Error(c, 403, "导入未授权")
|
||||
return
|
||||
}
|
||||
// 隔离完整管理员、不同 Key 和权限修改前后的幂等结果。
|
||||
policy, _ := json.Marshal(principal.Policy)
|
||||
digest := sha256.Sum256(policy)
|
||||
scope := "scoped.codex:" + principal.KeyID + ":" + hex.EncodeToString(digest[:])
|
||||
executeAdminIdempotentJSON(c, scope, req, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
|
||||
result, err := h.importScopedCodexSessions(ctx, api, req, entries)
|
||||
if err != nil {
|
||||
code, message := scopedAdminAccountErrorDetails(err)
|
||||
return nil, infraerrors.New(code, "SCOPED_CODEX_FAILED", message)
|
||||
}
|
||||
return result, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AccountHandler) importScopedCodexSessions(ctx context.Context, api service.ScopedAdminCodexAccounts, req scopedCodexSessionImportRequest, entries []codexImportEntry) (CodexSessionImportResult, error) {
|
||||
proxyMode, err := service.NormalizeAccountProxyMode(req.ProxyMode, req.ProxyID, req.RandomProxy)
|
||||
if err != nil {
|
||||
return CodexSessionImportResult{}, err
|
||||
}
|
||||
result := CodexSessionImportResult{Total: len(entries), Items: make([]CodexSessionImportItem, 0, len(entries))}
|
||||
updateExisting := req.UpdateExisting == nil || *req.UpdateExisting
|
||||
seen := map[string]codexSeenIdentity{}
|
||||
fail := func(entry int, err error) {
|
||||
_, message := scopedAdminAccountErrorDetails(err)
|
||||
result.Failed++
|
||||
result.Items = append(result.Items, CodexSessionImportItem{Index: entry, Action: "failed", Message: message})
|
||||
result.Errors = append(result.Errors, CodexSessionImportMessage{Index: entry, Message: message})
|
||||
}
|
||||
for _, entry := range entries {
|
||||
item, err := normalizeCodexImportEntry(entry)
|
||||
if err != nil {
|
||||
fail(entry.Index, infraerrors.BadRequest("SCOPED_CODEX_PARSE", "认证内容无效"))
|
||||
continue
|
||||
}
|
||||
expires, credentialExpiry, autoPause, warnings, err := resolveCodexImportExpiry(req.CodexSessionImportRequest, item)
|
||||
if err != nil {
|
||||
fail(entry.Index, infraerrors.BadRequest("SCOPED_CODEX_EXPIRY", "认证有效期无效"))
|
||||
continue
|
||||
}
|
||||
if credentialExpiry != nil {
|
||||
item.Credentials["expires_at"] = credentialExpiry.Format(time.RFC3339)
|
||||
}
|
||||
if _, duplicate := firstSeenCodexIdentity(seen, item.IdentityKeys, item.UserID); duplicate {
|
||||
result.Skipped++
|
||||
result.Items = append(result.Items, CodexSessionImportItem{Index: entry.Index, Action: "skipped", Message: "同批次重复导入项"})
|
||||
continue
|
||||
}
|
||||
markCodexIdentitySeen(seen, item.IdentityKeys, entry.Index, item.UserID)
|
||||
credentials := mergeCodexImportMap(item.Credentials, req.CredentialExtras)
|
||||
extra := mergeCodexImportMap(req.Extra, item.Extra)
|
||||
name := buildCodexCreateAccountName(req.Name, item, entry.Index, len(entries))
|
||||
var account *service.Account
|
||||
action := "created"
|
||||
var existing *service.Account
|
||||
if updateExisting {
|
||||
candidates, lookupErr := api.ScopedAdminCodexCandidates(ctx, service.ScopedCodexIdentity{
|
||||
AccountID: item.AccountID, UserID: item.UserID, Email: item.Email, AccessToken: item.AccessToken,
|
||||
AccessTokenOnly: item.RefreshToken == "" && item.AccessToken != "", AgentIdentity: item.IsAgentIdentity,
|
||||
})
|
||||
if lookupErr != nil {
|
||||
return result, lookupErr
|
||||
}
|
||||
existing, _ = buildCodexAccountIndex(candidates).Find(item.IdentityKeys, item.UserID)
|
||||
}
|
||||
if updateExisting && existing != nil {
|
||||
action = "updated"
|
||||
input := &service.UpdateAccountInput{ProxyMode: proxyMode, Credentials: credentials, Extra: extra, ProxyID: req.ProxyID, Concurrency: req.Concurrency, Priority: req.Priority, RateMultiplier: req.RateMultiplier, LoadFactor: req.LoadFactor, ExpiresAt: expires, AutoPauseOnExpired: autoPause}
|
||||
if len(req.GroupIDs) > 0 {
|
||||
input.GroupIDs = &req.GroupIDs
|
||||
}
|
||||
account, err = api.ScopedAdminUpdateCodex(ctx, existing.ID, input, func(current *service.Account, safe *service.UpdateAccountInput) error {
|
||||
// 锁内重新匹配,不能将候选快照匹配结果应用到已被其他操作换绑的身份。
|
||||
fresh := buildCodexAccountIndex([]service.Account{*current})
|
||||
if matched, _ := fresh.Find(item.IdentityKeys, item.UserID); matched == nil {
|
||||
return infraerrors.Conflict("SCOPED_CODEX_CHANGED", "账户身份已变更")
|
||||
}
|
||||
safe.Credentials = mergeCodexImportCredentials(current.Credentials, credentials, item)
|
||||
safe.Extra = mergeCodexImportMap(current.Extra, extra)
|
||||
if item.RefreshToken == "" && codexCredentialString(current.Credentials, "refresh_token") != "" {
|
||||
safe.ExpiresAt = nil
|
||||
safe.AutoPauseOnExpired = nil
|
||||
}
|
||||
return nil
|
||||
})
|
||||
} else {
|
||||
concurrency, priority := 3, 50
|
||||
if req.Concurrency != nil {
|
||||
concurrency = *req.Concurrency
|
||||
}
|
||||
if req.Priority != nil {
|
||||
priority = *req.Priority
|
||||
}
|
||||
account, err = api.ScopedAdminCreateCodex(ctx, &service.CreateAccountInput{ProxyMode: proxyMode, Name: name, Notes: req.Notes, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: credentials, Extra: extra, GroupIDs: req.GroupIDs, ProxyID: req.ProxyID, Concurrency: concurrency, Priority: priority, RateMultiplier: req.RateMultiplier, LoadFactor: req.LoadFactor, ExpiresAt: expires, AutoPauseOnExpired: autoPause, SkipDefaultGroupBind: true})
|
||||
}
|
||||
if err != nil {
|
||||
fail(entry.Index, err)
|
||||
continue
|
||||
}
|
||||
if action == "updated" {
|
||||
result.Updated++
|
||||
h.invalidateScopedAccountToken(ctx, account)
|
||||
} else {
|
||||
result.Created++
|
||||
}
|
||||
// 不返回候选名称或任何已有凭证,仅返回本次操作结果。
|
||||
result.Items = append(result.Items, CodexSessionImportItem{Index: entry.Index, Action: action, AccountID: account.ID})
|
||||
for _, warning := range append(item.WarningTexts, warnings...) {
|
||||
result.Warnings = append(result.Warnings, CodexSessionImportMessage{Index: entry.Index, Message: warning})
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type scopedCodexMemoryService struct {
|
||||
*codexImportMemoryAdminService
|
||||
fresh *service.Account
|
||||
err error
|
||||
lookups []service.ScopedCodexIdentity
|
||||
}
|
||||
|
||||
func (s *scopedCodexMemoryService) ScopedAdminCodexCandidates(_ context.Context, identity service.ScopedCodexIdentity) ([]service.Account, error) {
|
||||
s.lookups = append(s.lookups, identity)
|
||||
return s.accounts, nil
|
||||
}
|
||||
func (s *scopedCodexMemoryService) ScopedAdminCreateCodex(ctx context.Context, input *service.CreateAccountInput) (*service.Account, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
return s.CreateAccount(ctx, input)
|
||||
}
|
||||
func (s *scopedCodexMemoryService) ScopedAdminUpdateCodex(ctx context.Context, id int64, input *service.UpdateAccountInput, prepare func(*service.Account, *service.UpdateAccountInput) error) (*service.Account, error) {
|
||||
current := s.fresh
|
||||
if current == nil {
|
||||
var err error
|
||||
current, err = s.GetAccount(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := prepare(current, input); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.UpdateAccount(ctx, id, input)
|
||||
}
|
||||
|
||||
func TestScopedCodexImportCapturedRequestAndSafeResponse(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
|
||||
h := &AccountHandler{adminService: memory}
|
||||
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{KeyID: "fixture", Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}})
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) { c.Request = c.Request.WithContext(ctx) })
|
||||
r.Use(h.ScopedAdminKeyAccounts)
|
||||
r.POST("/api/v1/admin/accounts/import/codex-session", func(c *gin.Context) { t.Fatal("不能回退到完整管理员导入") })
|
||||
content := `{"access_token":"private-access-fixture","refresh_token":"private-refresh-fixture","email":"test@example.com"}`
|
||||
req := map[string]any{"content": content, "name": "推送账户", "notes": "测试", "group_ids": []int64{2, 14}, "concurrency": 40, "priority": 0, "expires_at": nil, "auto_pause_on_expired": true, "proxy_id": nil, "rate_multiplier": 1, "update_existing": true, "extra": map[string]any{"codex_fingerprint_mode": "off", "openai_oauth_responses_websockets_v2_enabled": true, "openai_oauth_responses_websockets_v2_mode": "shared"}}
|
||||
raw, err := json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
call := func() *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(string(raw))))
|
||||
return w
|
||||
}
|
||||
w := call()
|
||||
require.Equal(t, 200, w.Code, w.Body.String())
|
||||
require.Contains(t, w.Body.String(), `"created":1`)
|
||||
require.NotContains(t, w.Body.String(), "private-")
|
||||
require.Len(t, memory.createdAccounts, 1)
|
||||
input := memory.createdAccounts[0]
|
||||
require.Equal(t, []int64{2, 14}, input.GroupIDs)
|
||||
require.Equal(t, 40, input.Concurrency)
|
||||
require.True(t, input.SkipDefaultGroupBind)
|
||||
require.Equal(t, "private-refresh-fixture", input.Credentials["refresh_token"])
|
||||
require.Equal(t, "off", input.Extra["codex_fingerprint_mode"])
|
||||
memory.err = infraerrors.BadRequest("UPSTREAM_SECRET", "private-refresh-fixture")
|
||||
// update_existing=false 沿用原接口语义:新建;错误也必须脱敏。
|
||||
req["update_existing"] = false
|
||||
raw, err = json.Marshal(req)
|
||||
require.NoError(t, err)
|
||||
w = call()
|
||||
require.Equal(t, 200, w.Code)
|
||||
require.Contains(t, w.Body.String(), `"failed":1`)
|
||||
require.NotContains(t, w.Body.String(), "private-")
|
||||
}
|
||||
|
||||
func TestScopedCodexImportRevalidatesIdentityAndMergesFreshCredentials(t *testing.T) {
|
||||
token := buildCodexAccessToken(t, "account", "user", time.Now().Add(time.Hour))
|
||||
stale := service.Account{ID: 1, Credentials: map[string]any{"access_token": token, "refresh_token": "stale"}, Extra: map[string]any{"quota_used": 1}}
|
||||
fresh := stale
|
||||
fresh.Credentials = map[string]any{"access_token": token, "refresh_token": "latest", "base_url": "https://example.com"}
|
||||
fresh.Extra = map[string]any{"quota_used": 9}
|
||||
for _, changed := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "锁内合并", true: "身份已更换"}[changed], func(t *testing.T) {
|
||||
current := fresh
|
||||
if changed {
|
||||
current.Credentials = map[string]any{"access_token": "different", "refresh_token": "other"}
|
||||
}
|
||||
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService([]service.Account{stale}), fresh: ¤t}
|
||||
h := &AccountHandler{adminService: memory}
|
||||
req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: token, GroupIDs: []int64{1}}}
|
||||
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
|
||||
require.NoError(t, err)
|
||||
result, err := h.importScopedCodexSessions(context.Background(), memory, req, entries)
|
||||
require.NoError(t, err)
|
||||
if changed {
|
||||
require.Equal(t, 1, result.Failed)
|
||||
require.Empty(t, memory.updatedAccounts)
|
||||
return
|
||||
}
|
||||
require.Equal(t, 1, result.Updated)
|
||||
require.Len(t, memory.updatedAccounts, 1)
|
||||
input := memory.updatedAccounts[0].input
|
||||
require.Equal(t, "latest", input.Credentials["refresh_token"])
|
||||
require.Equal(t, "https://example.com", input.Credentials["base_url"])
|
||||
require.Equal(t, 9, input.Extra["quota_used"])
|
||||
require.Nil(t, input.ExpiresAt)
|
||||
require.Nil(t, input.AutoPauseOnExpired)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedCodexRequestRejectsUnopenedFields(t *testing.T) {
|
||||
for _, body := range []string{`{"content":"x"}`, `{"group_ids":[1],"confirm_mixed_channel_risk":true}`, `{"group_ids":[1],"extra":{"quota_used":0}}`, `{"group_ids":[1],"credential_extras":{"refresh_token":"x"}}`, `{"group_ids":[1],"extra":{"openai_oauth_responses_websockets_v2_enabled":"true"}}`} {
|
||||
var req scopedCodexSessionImportRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(body), &req))
|
||||
require.Error(t, validateScopedCodexRequest(req), body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedCodexImportIdempotencySeparatesKeysAndPolicy(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
previous := service.DefaultIdempotencyCoordinator()
|
||||
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
|
||||
repo := newMemoryIdempotencyRepoStub()
|
||||
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(repo, service.DefaultIdempotencyConfig()))
|
||||
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
|
||||
h := &AccountHandler{adminService: memory}
|
||||
principal := &adminaccess.Principal{KeyID: "aaaaaaaaaaaaaaaaaaaaaaaa", Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.schedule", "accounts.network"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}}
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if principal != nil {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), principal))
|
||||
}
|
||||
})
|
||||
r.Use(h.ScopedAdminKeyAccounts)
|
||||
r.POST("/api/v1/admin/accounts/import/codex-session", h.ImportCodexSession)
|
||||
call := func() *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest("POST", "/api/v1/admin/accounts/import/codex-session", strings.NewReader(`{"content":"{\"access_token\":\"fixture-access\",\"refresh_token\":\"fixture-refresh\"}","group_ids":[2],"update_existing":false}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", "same-import")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
require.Equal(t, 200, w.Code, w.Body.String())
|
||||
require.NotContains(t, w.Body.String(), "fixture-")
|
||||
return w
|
||||
}
|
||||
first := call()
|
||||
require.Len(t, memory.createdAccounts, 1)
|
||||
replay := call()
|
||||
require.Equal(t, "true", replay.Header().Get("X-Idempotency-Replayed"))
|
||||
require.JSONEq(t, first.Body.String(), replay.Body.String())
|
||||
require.Len(t, memory.createdAccounts, 1)
|
||||
principal.KeyID = "bbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
other := call()
|
||||
require.Empty(t, other.Header().Get("X-Idempotency-Replayed"))
|
||||
require.Len(t, memory.createdAccounts, 2)
|
||||
principal.Policy.Rules[0].Permissions = []string{"accounts.create"}
|
||||
memory.err = infraerrors.Forbidden("SCOPED_CODEX_FORBIDDEN", "权限已收回")
|
||||
restricted := call()
|
||||
require.Empty(t, restricted.Header().Get("X-Idempotency-Replayed"))
|
||||
require.Contains(t, restricted.Body.String(), `"failed":1`)
|
||||
require.Len(t, memory.createdAccounts, 2)
|
||||
principal = nil
|
||||
memory.err = nil
|
||||
full := call()
|
||||
require.Empty(t, full.Header().Get("X-Idempotency-Replayed"))
|
||||
require.Len(t, memory.createdAccounts, 3)
|
||||
for _, record := range repo.data {
|
||||
require.LessOrEqual(t, len(record.Scope), 128, "生产数据库 scope 最大长度")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedCodexImportProxyModeForwarding(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
body, mode string
|
||||
id int64
|
||||
}{
|
||||
{`"proxy_id":7`, "", 7}, {`"proxy_mode":"specified","proxy_id":7`, "specified", 7},
|
||||
{`"random_proxy":true`, "random", 0}, {`"proxy_mode":"random"`, "random", 0},
|
||||
{`"proxy_mode":"least_used"`, "least_used", 0}, {`"proxy_mode":"direct"`, "direct", 0},
|
||||
} {
|
||||
t.Run(tc.body, func(t *testing.T) {
|
||||
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
|
||||
h := &AccountHandler{adminService: memory}
|
||||
var req scopedCodexSessionImportRequest
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"content":"{\"access_token\":\"fixture\",\"refresh_token\":\"refresh\"}","group_ids":[1],`+tc.body+`}`), &req))
|
||||
require.NoError(t, validateScopedCodexRequest(req))
|
||||
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
|
||||
require.NoError(t, err)
|
||||
result, err := h.importScopedCodexSessions(context.Background(), memory, req, entries)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, result.Created)
|
||||
require.Len(t, memory.createdAccounts, 1)
|
||||
require.Equal(t, tc.mode, memory.createdAccounts[0].ProxyMode)
|
||||
if tc.id > 0 {
|
||||
require.Equal(t, tc.id, *memory.createdAccounts[0].ProxyID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedCodexImportLooksUpOnlyValidatedEntryIdentity(t *testing.T) {
|
||||
token := buildCodexAccessToken(t, "workspace", "member", time.Now().Add(time.Hour))
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
content string
|
||||
update bool
|
||||
wantLookups int
|
||||
wantSkipped int
|
||||
onlyAccess bool
|
||||
}{
|
||||
{"有效身份与批内重复", token + "\n" + token, true, 1, 1, true},
|
||||
{"无效内容无需读取候选", `{"refresh_token":"fixture"}`, true, 0, 0, false},
|
||||
{"禁用更新无需读取候选", token, false, 0, 0, true},
|
||||
{"有refresh保留身份匹配", `{"access_token":"` + token + `","refresh_token":"fixture"}`, true, 1, 0, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService(nil)}
|
||||
req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: tc.content, GroupIDs: []int64{1}, UpdateExisting: &tc.update}}
|
||||
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
|
||||
require.NoError(t, err)
|
||||
result, err := (&AccountHandler{adminService: memory}).importScopedCodexSessions(context.Background(), memory, req, entries)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.wantSkipped, result.Skipped)
|
||||
require.Len(t, memory.lookups, tc.wantLookups)
|
||||
if tc.wantLookups > 0 {
|
||||
lookup := memory.lookups[0]
|
||||
require.Equal(t, "workspace", lookup.AccountID)
|
||||
require.Equal(t, "member", lookup.UserID)
|
||||
require.Equal(t, token, lookup.AccessToken)
|
||||
require.Equal(t, tc.onlyAccess, lookup.AccessTokenOnly)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
entsql "entgo.io/ent/dialect/sql"
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type scopedCommitInvalidator struct {
|
||||
ids []int64
|
||||
transactionContexts int
|
||||
}
|
||||
|
||||
func (s *scopedCommitInvalidator) InvalidateToken(ctx context.Context, account *service.Account) error {
|
||||
s.ids = append(s.ids, account.ID)
|
||||
if dbent.TxFromContext(ctx) != nil {
|
||||
s.transactionContexts++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type scopedCommitAccounts struct {
|
||||
service.AdminService
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]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) {
|
||||
if s.fail {
|
||||
return nil, errors.New("模拟写入失败")
|
||||
}
|
||||
return &service.Account{ID: id, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth}, nil
|
||||
}
|
||||
|
||||
func TestScopedAdminCredentialWritesInvalidateAfterCommit(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, endpoint := range []string{"single", "bulk"} {
|
||||
for _, mode := range []string{"commit", "rollback", "commit_failure", "write_failure", "name_only"} {
|
||||
t.Run(endpoint+"/"+mode, func(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
mock.ExpectBegin()
|
||||
tx, err := client.Tx(context.Background())
|
||||
require.NoError(t, err)
|
||||
ctx := dbent.NewTxContext(context.Background(), tx)
|
||||
ctx = adminaccess.WithPrincipal(ctx, &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.credentials"}, AllGroups: true}}}})
|
||||
cache := &scopedCommitInvalidator{}
|
||||
h := &AccountHandler{adminService: &scopedCommitAccounts{fail: mode == "write_failure"}, tokenCacheInvalidator: cache}
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) { c.Request = c.Request.WithContext(ctx) })
|
||||
r.Use(h.ScopedAdminKeyAccounts)
|
||||
r.PUT("/api/v1/admin/accounts/:id", func(*gin.Context) { t.Fatal("不得进入完整管理员处理器") })
|
||||
r.POST("/api/v1/admin/accounts/bulk-update", func(*gin.Context) { t.Fatal("不得进入完整管理员处理器") })
|
||||
method, path, body := "PUT", "/api/v1/admin/accounts/7", `{"credentials":{"access_token":"fixture"}}`
|
||||
if mode == "name_only" {
|
||||
body = `{"name":"新名称"}`
|
||||
}
|
||||
if endpoint == "bulk" {
|
||||
method, path = "POST", "/api/v1/admin/accounts/bulk-update"
|
||||
body = `{"account_ids":[7],` + body[1:]
|
||||
}
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
want := 200
|
||||
if mode == "write_failure" && endpoint == "single" {
|
||||
want = 503
|
||||
}
|
||||
require.Equal(t, want, w.Code, w.Body.String())
|
||||
require.Empty(t, cache.ids, "事务提交前不得使令牌缓存失效")
|
||||
if mode == "rollback" || mode == "write_failure" {
|
||||
mock.ExpectRollback()
|
||||
require.NoError(t, tx.Rollback())
|
||||
} else if mode == "commit_failure" {
|
||||
mock.ExpectCommit().WillReturnError(errors.New("提交失败"))
|
||||
require.Error(t, tx.Commit())
|
||||
} else {
|
||||
mock.ExpectCommit()
|
||||
require.NoError(t, tx.Commit())
|
||||
}
|
||||
if mode == "commit" {
|
||||
require.Equal(t, []int64{7}, cache.ids)
|
||||
} else {
|
||||
require.Empty(t, cache.ids)
|
||||
}
|
||||
require.Zero(t, cache.transactionContexts, "提交后的缓存清理不能携带已关闭事务")
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type scopedRefreshPrivacyService struct {
|
||||
*stubAdminService
|
||||
privacy int
|
||||
}
|
||||
|
||||
func (s *scopedRefreshPrivacyService) EnsureOpenAIPrivacy(context.Context, *service.Account) string {
|
||||
s.privacy++
|
||||
return ""
|
||||
}
|
||||
func (s *scopedRefreshPrivacyService) EnsureAntigravityPrivacy(context.Context, *service.Account) string {
|
||||
s.privacy++
|
||||
return ""
|
||||
}
|
||||
func TestScopedAdminRefreshFailureDoesNotTriggerPrivacyBeforeRollback(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
mock.ExpectBegin()
|
||||
tx, err := client.Tx(context.Background())
|
||||
require.NoError(t, err)
|
||||
svc := &scopedRefreshPrivacyService{stubAdminService: newStubAdminService()}
|
||||
h := &AccountHandler{adminService: svc, openaiOAuthService: service.NewOpenAIOAuthService(nil, nil)}
|
||||
_, _, err = h.refreshSingleAccount(dbent.NewTxContext(context.Background(), tx), &service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth})
|
||||
require.Error(t, err)
|
||||
require.Zero(t, svc.privacy, "刷新失败导致回滚时,不应提前调用上游隐私接口")
|
||||
mock.ExpectRollback()
|
||||
require.NoError(t, tx.Rollback())
|
||||
require.Zero(t, svc.privacy)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
// 完整管理员没有外层事务,沿用原刷新失败后的隐私检查行为。
|
||||
_, _, err = h.refreshSingleAccount(context.Background(), &service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth})
|
||||
require.Error(t, err)
|
||||
require.Equal(t, 1, svc.privacy)
|
||||
}
|
||||
|
||||
func TestScopedAdminCodexUpdatesInvalidateOnlyAfterCommit(t *testing.T) {
|
||||
for _, mode := range []string{"commit", "rollback", "commit_failure", "identity_changed"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
db, mock, err := sqlmock.New()
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
mock.ExpectBegin()
|
||||
tx, err := client.Tx(context.Background())
|
||||
require.NoError(t, err)
|
||||
token := buildCodexAccessToken(t, "account", "user", time.Now().Add(time.Hour))
|
||||
existing := service.Account{ID: 7, Platform: service.PlatformOpenAI, Type: service.AccountTypeOAuth, Credentials: map[string]any{"access_token": token, "auth_mode": service.OpenAIAuthModePersonalAccessToken}}
|
||||
memory := &scopedCodexMemoryService{codexImportMemoryAdminService: newCodexImportMemoryAdminService([]service.Account{existing})}
|
||||
if mode == "identity_changed" {
|
||||
memory.fresh = &service.Account{ID: 7, Credentials: map[string]any{"access_token": "changed-private"}}
|
||||
}
|
||||
cache := &scopedCommitInvalidator{}
|
||||
h := &AccountHandler{adminService: memory, tokenCacheInvalidator: cache}
|
||||
req := scopedCodexSessionImportRequest{CodexSessionImportRequest: CodexSessionImportRequest{Content: token, GroupIDs: []int64{1}}}
|
||||
entries, err := parseCodexSessionImportEntries(req.CodexSessionImportRequest)
|
||||
require.NoError(t, err)
|
||||
result, err := h.importScopedCodexSessions(dbent.NewTxContext(context.Background(), tx), memory, req, entries)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, cache.ids)
|
||||
if mode == "rollback" || mode == "identity_changed" {
|
||||
mock.ExpectRollback()
|
||||
require.NoError(t, tx.Rollback())
|
||||
} else if mode == "commit_failure" {
|
||||
mock.ExpectCommit().WillReturnError(errors.New("提交失败"))
|
||||
require.Error(t, tx.Commit())
|
||||
} else {
|
||||
mock.ExpectCommit()
|
||||
require.NoError(t, tx.Commit())
|
||||
}
|
||||
if mode == "commit" {
|
||||
require.Equal(t, []int64{7}, cache.ids)
|
||||
} else {
|
||||
require.Empty(t, cache.ids)
|
||||
}
|
||||
if mode == "identity_changed" {
|
||||
require.Equal(t, 1, result.Failed)
|
||||
} else {
|
||||
require.Equal(t, 1, result.Updated)
|
||||
require.Equal(t, service.OpenAIAuthModePersonalAccessToken, memory.updatedAccounts[0].input.Credentials["auth_mode"])
|
||||
}
|
||||
require.Zero(t, cache.transactionContexts)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func scopedAdminGroupModelsDTO(g *service.Group) gin.H {
|
||||
return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "model_allowlist": g.ModelAllowlist}
|
||||
}
|
||||
|
||||
// ScopedAdminKeyGroupModels 接管分组模型接口,禁止复用可修改费率等字段的完整处理器。
|
||||
func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) {
|
||||
p := adminaccess.FromContext(c.Request.Context())
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
base := "/api/v1/admin/groups/:id"
|
||||
path := c.FullPath()
|
||||
fullRead := slices.Contains(p.Policy.GlobalPermissions, "groups.read")
|
||||
if c.Request.Method == http.MethodGet && (path == "/api/v1/admin/groups" || path == "/api/v1/admin/groups/all") {
|
||||
if fullRead {
|
||||
return
|
||||
}
|
||||
c.Abort()
|
||||
h.scopedAdminListGroupModels(c)
|
||||
return
|
||||
}
|
||||
// 完整分组读取继续沿用原处理器的简易模式响应。
|
||||
if fullRead && path == base && c.Request.Method == http.MethodGet && h.isSimpleMode() {
|
||||
return
|
||||
}
|
||||
candidates := path == base+"/model-allowlist-candidates"
|
||||
if !candidates && path != base {
|
||||
return
|
||||
}
|
||||
c.Abort()
|
||||
if h.rejectUnsupportedSimpleModeOperation(c, "advanced") {
|
||||
return
|
||||
}
|
||||
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil || id < 0 || (id == 0 && !candidates) {
|
||||
response.BadRequest(c, "分组 ID 无效")
|
||||
return
|
||||
}
|
||||
if candidates && c.Request.Method == http.MethodGet && id == 0 {
|
||||
if !slices.Contains(p.Policy.GlobalPermissions, "models.defaults.read") {
|
||||
response.Error(c, 403, "默认模型读取未授权")
|
||||
return
|
||||
}
|
||||
h.GetGroupModelAllowlistCandidates(c)
|
||||
return
|
||||
}
|
||||
g, err := h.adminService.GetGroup(c.Request.Context(), id)
|
||||
if err != nil || g == nil {
|
||||
response.Error(c, 404, "分组不存在")
|
||||
return
|
||||
}
|
||||
permission := "groups.models.read"
|
||||
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)
|
||||
if !allowed {
|
||||
response.Error(c, 404, "分组不存在")
|
||||
return
|
||||
}
|
||||
if c.Request.Method == http.MethodGet {
|
||||
if candidates {
|
||||
if platform := strings.TrimSpace(c.Query("platform")); platform != "" && platform != g.Platform {
|
||||
response.BadRequest(c, "候选模型平台必须与分组一致")
|
||||
return
|
||||
}
|
||||
h.GetGroupModelAllowlistCandidates(c)
|
||||
return
|
||||
}
|
||||
if fullRead {
|
||||
response.Success(c, dto.GroupFromServiceAdmin(g))
|
||||
} else {
|
||||
response.Success(c, scopedAdminGroupModelsDTO(g))
|
||||
}
|
||||
return
|
||||
}
|
||||
if c.Request.Method != http.MethodPut || candidates {
|
||||
response.Error(c, 403, "此分组操作未开放给受限管理密钥")
|
||||
return
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 65536)
|
||||
var fields map[string]json.RawMessage
|
||||
if c.ShouldBindJSON(&fields) != nil || len(fields) != 1 {
|
||||
response.BadRequest(c, "仅支持单独提交 model_allowlist")
|
||||
return
|
||||
}
|
||||
raw := fields["model_allowlist"]
|
||||
var cfg *service.GroupModelAllowlist
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&cfg) != nil || cfg == nil {
|
||||
response.BadRequest(c, "模型白名单格式无效")
|
||||
return
|
||||
}
|
||||
api, ok := h.adminService.(interface {
|
||||
ScopedAdminUpdateGroupModels(context.Context, int64, service.GroupModelAllowlist) (*service.Group, error)
|
||||
})
|
||||
if !ok {
|
||||
response.Error(c, 503, "受限分组模型服务不可用")
|
||||
return
|
||||
}
|
||||
updated, err := api.ScopedAdminUpdateGroupModels(c.Request.Context(), id, *cfg)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, scopedAdminGroupModelsDTO(updated))
|
||||
}
|
||||
|
||||
func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) {
|
||||
if h.rejectUnsupportedSimpleModeOperation(c, "advanced") {
|
||||
return
|
||||
}
|
||||
api, ok := h.adminService.(interface {
|
||||
ScopedAdminListGroupModels(context.Context, pagination.PaginationParams, bool, string, string, string) ([]service.Group, int64, error)
|
||||
})
|
||||
if !ok {
|
||||
response.Error(c, 503, "受限分组模型服务不可用")
|
||||
return
|
||||
}
|
||||
page, size := response.ParsePagination(c)
|
||||
all := strings.HasSuffix(c.FullPath(), "/all")
|
||||
status := c.Query("status")
|
||||
if all {
|
||||
status = service.StatusActive
|
||||
if c.Query("include_inactive") == "true" {
|
||||
status = ""
|
||||
}
|
||||
}
|
||||
search := strings.TrimSpace(c.Query("search"))
|
||||
if len(search) > 100 {
|
||||
search = search[:100]
|
||||
}
|
||||
groups, total, err := api.ScopedAdminListGroupModels(c.Request.Context(), pagination.PaginationParams{Page: page, PageSize: size}, all, c.Query("platform"), status, search)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]gin.H, 0, len(groups))
|
||||
for i := range groups {
|
||||
out = append(out, scopedAdminGroupModelsDTO(&groups[i]))
|
||||
}
|
||||
if all {
|
||||
response.Success(c, out)
|
||||
} else {
|
||||
response.Paginated(c, out, total, page, size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// scopedProxyOption 显式列出可公开字段,不能复用含用户名、密码的管理 DTO。
|
||||
type scopedProxyOption struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Protocol string `json:"protocol"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Status string `json:"status"`
|
||||
ExpiresAt *time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
func scopedProxyDTO(p service.Proxy) scopedProxyOption {
|
||||
return scopedProxyOption{ID: p.ID, Name: p.Name, Protocol: p.Protocol, Host: p.Host, Port: p.Port, Status: p.Status, ExpiresAt: p.ExpiresAt}
|
||||
}
|
||||
|
||||
// scopedAdminProxyRead 对代理读取限定数量;无分页的 /all 从全池抽样。
|
||||
func (h *ProxyHandler) scopedAdminProxyRead(c *gin.Context) bool {
|
||||
principal := adminaccess.FromContext(c.Request.Context())
|
||||
if principal == nil {
|
||||
return false
|
||||
}
|
||||
if !slices.Contains(principal.Policy.GlobalPermissions, "proxies.read") {
|
||||
response.Error(c, 403, "代理读取未授权")
|
||||
return true
|
||||
}
|
||||
if raw := c.Param("id"); raw != "" {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id < 1 {
|
||||
response.BadRequest(c, "代理 ID 无效")
|
||||
return true
|
||||
}
|
||||
p, err := h.adminService.GetProxy(c.Request.Context(), id)
|
||||
if err != nil || p == nil {
|
||||
response.Error(c, 404, "代理不存在")
|
||||
return true
|
||||
}
|
||||
response.Success(c, scopedProxyDTO(*p))
|
||||
return true
|
||||
}
|
||||
page, size := 1, 50
|
||||
for key, dest := range map[string]*int{"page": &page, "page_size": &size} {
|
||||
if raw, ok := c.GetQuery(key); ok {
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 1000000 {
|
||||
response.BadRequest(c, "分页参数必须为正整数且不超过 1000000")
|
||||
return true
|
||||
}
|
||||
*dest = n
|
||||
}
|
||||
}
|
||||
if size > 100 {
|
||||
size = 100
|
||||
}
|
||||
var proxies []service.Proxy
|
||||
var total int64
|
||||
var err error
|
||||
if raw, ok := c.Request.URL.Query()["ids"]; ok {
|
||||
ids := []int64{}
|
||||
for _, part := range strings.Split(strings.Join(raw, ","), ",") {
|
||||
if strings.TrimSpace(part) == "" {
|
||||
continue
|
||||
}
|
||||
id, e := strconv.ParseInt(strings.TrimSpace(part), 10, 64)
|
||||
if e != nil || id < 1 {
|
||||
response.BadRequest(c, "代理 ID 无效")
|
||||
return true
|
||||
}
|
||||
if !slices.Contains(ids, id) {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) > 100 {
|
||||
response.BadRequest(c, "一次最多读取 100 个已选代理")
|
||||
return true
|
||||
}
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
proxies, err = h.adminService.GetProxiesByIDs(c.Request.Context(), ids)
|
||||
}
|
||||
// 最多 100 个 ID 的回显按实际存在的记录分页,保留请求顺序。
|
||||
byID := make(map[int64]service.Proxy, len(proxies))
|
||||
for _, p := range proxies {
|
||||
byID[p.ID] = p
|
||||
}
|
||||
proxies = nil
|
||||
for _, id := range ids {
|
||||
if p, ok := byID[id]; ok {
|
||||
proxies = append(proxies, p)
|
||||
}
|
||||
}
|
||||
total = int64(len(proxies))
|
||||
start := (page - 1) * size
|
||||
if start < len(proxies) {
|
||||
proxies = proxies[start:min(start+size, len(proxies))]
|
||||
} else {
|
||||
proxies = nil
|
||||
}
|
||||
} else {
|
||||
search := strings.TrimSpace(c.Query("search"))
|
||||
if len(search) > 100 {
|
||||
response.BadRequest(c, "搜索关键词不能超过 100 字节")
|
||||
return true
|
||||
}
|
||||
query := c.Request.URL.Query()
|
||||
if strings.HasSuffix(c.FullPath(), "/proxies/all") && !query.Has("page") && !query.Has("page_size") {
|
||||
sampler, ok := h.adminService.(interface {
|
||||
SampleProxyOptions(context.Context, string) ([]service.Proxy, int64, error)
|
||||
})
|
||||
if !ok {
|
||||
response.Error(c, 503, "代理查询暂不可用")
|
||||
return true
|
||||
}
|
||||
proxies, total, err = sampler.SampleProxyOptions(c.Request.Context(), search)
|
||||
// 旧客户端重复加载时必须重新抽样,不能复用上一次缓存的候选。
|
||||
c.Header("Cache-Control", "no-store")
|
||||
} else {
|
||||
proxies, total, err = scopedProxyOptions(c.Request.Context(), h.adminService, page, size, search)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
response.Error(c, 503, "代理查询暂不可用")
|
||||
return true
|
||||
}
|
||||
out := make([]scopedProxyOption, 0, min(len(proxies), size))
|
||||
for _, p := range proxies[:min(len(proxies), size)] {
|
||||
out = append(out, scopedProxyDTO(p))
|
||||
}
|
||||
if strings.HasSuffix(c.FullPath(), "/proxies/all") {
|
||||
c.Header("X-Total-Count", strconv.FormatInt(total, 10))
|
||||
c.Header("X-Page", strconv.Itoa(page))
|
||||
c.Header("X-Page-Size", strconv.Itoa(size))
|
||||
c.Header("X-Total-Pages", strconv.FormatInt((total+int64(size)-1)/int64(size), 10))
|
||||
response.Success(c, out)
|
||||
} else {
|
||||
response.Paginated(c, out, total, page, size)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func scopedProxyOptions(ctx context.Context, admin service.AdminService, page, size int, search string) ([]service.Proxy, int64, error) {
|
||||
api, ok := admin.(interface {
|
||||
ListProxyOptions(context.Context, int, int, string) ([]service.Proxy, int64, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, 0, fmt.Errorf("代理查询不可用")
|
||||
}
|
||||
return api.ListProxyOptions(ctx, page, size, search)
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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 scopedProxyReadTestService struct {
|
||||
service.AdminService
|
||||
page, size, calls int
|
||||
ids []int64
|
||||
}
|
||||
|
||||
func (s *scopedProxyReadTestService) ListProxyOptions(_ context.Context, page, size int, _ string) ([]service.Proxy, int64, error) {
|
||||
s.page = page
|
||||
s.size = size
|
||||
s.calls++
|
||||
items := make([]service.Proxy, size)
|
||||
for i := range items {
|
||||
items[i] = service.Proxy{ID: int64((page-1)*size + i + 1), Host: "192.0.2.1", Username: "secret-user", Password: "secret-password", Status: service.StatusActive}
|
||||
}
|
||||
return items, 20001, nil
|
||||
}
|
||||
func (s *scopedProxyReadTestService) GetProxiesByIDs(_ context.Context, ids []int64) ([]service.Proxy, error) {
|
||||
s.ids = ids
|
||||
s.calls++
|
||||
items := []service.Proxy{}
|
||||
for _, id := range ids {
|
||||
if id == 999 {
|
||||
continue
|
||||
}
|
||||
items = append(items, service.Proxy{ID: id, Username: "secret-user", Password: "secret-password"})
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
func (s *scopedProxyReadTestService) GetProxy(_ context.Context, id int64) (*service.Proxy, error) {
|
||||
s.calls++
|
||||
return &service.Proxy{ID: id, Username: "secret-user", Password: "secret-password"}, nil
|
||||
}
|
||||
|
||||
func TestScopedProxyReadBoundedPaginationAndProjection(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tc := range []struct {
|
||||
query string
|
||||
status, page, size, count int
|
||||
}{
|
||||
{"", 200, 1, 50, 50}, {"?page=2&page_size=50000", 200, 2, 100, 100}, {"?page=201&page_size=100", 200, 201, 100, 100},
|
||||
{"?page=-1", 400, 0, 0, 0}, {"?page_size=0", 400, 0, 0, 0}, {"?page_size=no", 400, 0, 0, 0}, {"?page=999999999999999999999", 400, 0, 0, 0},
|
||||
{"?ids=1,2,3&page=2&page_size=2", 200, 2, 2, 1}, {"?ids=", 200, 1, 50, 0},
|
||||
{"?ids=999,1&page_size=1", 200, 1, 1, 1}, {"?ids=1,2,2&page=4&page_size=1", 200, 4, 1, 0},
|
||||
} {
|
||||
t.Run(tc.query, func(t *testing.T) {
|
||||
svc := &scopedProxyReadTestService{}
|
||||
h := NewProxyHandler(svc)
|
||||
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{"proxies.read"}}}))
|
||||
})
|
||||
r.GET("/proxies", h.List)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies"+tc.query, nil))
|
||||
require.Equal(t, tc.status, w.Code, w.Body.String())
|
||||
require.NotContains(t, w.Body.String(), "secret-")
|
||||
require.NotContains(t, w.Body.String(), "username")
|
||||
require.NotContains(t, w.Body.String(), "password")
|
||||
if tc.status != 200 {
|
||||
require.Zero(t, svc.calls)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Data struct {
|
||||
Items []map[string]any `json:"items"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
}
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
|
||||
require.Equal(t, tc.page, body.Data.Page)
|
||||
require.Equal(t, tc.size, body.Data.PageSize)
|
||||
require.Len(t, body.Data.Items, tc.count)
|
||||
if strings.Contains(tc.query, "ids=999,1") {
|
||||
require.EqualValues(t, 1, body.Data.Total)
|
||||
require.EqualValues(t, 1, body.Data.Items[0]["id"])
|
||||
}
|
||||
if strings.Contains(tc.query, "ids=1,2,3") {
|
||||
require.Equal(t, []int64{1, 2, 3}, svc.ids)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedProxyReadRejectsLargeIDBatchAndRequiresPermission(t *testing.T) {
|
||||
for _, allowed := range []bool{false, true} {
|
||||
svc := &scopedProxyReadTestService{}
|
||||
h := NewProxyHandler(svc)
|
||||
r := gin.New()
|
||||
p := &adminaccess.Principal{}
|
||||
if allowed {
|
||||
p.Policy.GlobalPermissions = []string{"proxies.read"}
|
||||
}
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(context.Background(), p))
|
||||
})
|
||||
r.GET("/proxies", h.GetAll)
|
||||
r.GET("/proxies/:id", h.GetByID)
|
||||
ids := []string{}
|
||||
for i := 1; i <= 101; i++ {
|
||||
ids = append(ids, strconv.Itoa(i))
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies?ids="+strings.Join(ids, ","), nil))
|
||||
if allowed {
|
||||
require.Equal(t, 400, w.Code)
|
||||
} else {
|
||||
require.Equal(t, 403, w.Code)
|
||||
}
|
||||
require.Zero(t, svc.calls)
|
||||
w = httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", "/proxies/1", nil))
|
||||
if allowed {
|
||||
require.Equal(t, 200, w.Code)
|
||||
require.NotContains(t, w.Body.String(), "secret-")
|
||||
require.NotContains(t, w.Body.String(), "username")
|
||||
} else {
|
||||
require.Equal(t, 403, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type scopedProxySampleTestService struct {
|
||||
scopedProxyReadTestService
|
||||
samples int
|
||||
search string
|
||||
}
|
||||
|
||||
func (s *scopedProxySampleTestService) SampleProxyOptions(_ context.Context, search string) ([]service.Proxy, int64, error) {
|
||||
s.samples++
|
||||
s.search = search
|
||||
return []service.Proxy{{ID: 12345, Host: "192.0.2.1", Username: "secret-user", Password: "secret-password"}}, 20000, nil
|
||||
}
|
||||
func TestScopedProxyAllSamplesOnlyWithoutPagination(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, tc := range []struct {
|
||||
path, query string
|
||||
sample bool
|
||||
status int
|
||||
}{
|
||||
{"/api/v1/admin/proxies/all", "", true, 200},
|
||||
{"/api/v1/admin/proxies/all", "?search=region", true, 200},
|
||||
{"/api/v1/admin/proxies/all", "?page=1", false, 200},
|
||||
{"/api/v1/admin/proxies/all", "?page_size=100", false, 200},
|
||||
{"/api/v1/admin/proxies/all", "?page=", false, 400},
|
||||
{"/api/v1/admin/proxies/all", "?ids=1,2", false, 200},
|
||||
{"/api/v1/admin/proxies", "", false, 200},
|
||||
} {
|
||||
t.Run(tc.path+tc.query, func(t *testing.T) {
|
||||
svc := &scopedProxySampleTestService{}
|
||||
h := NewProxyHandler(svc)
|
||||
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{"proxies.read"}}}))
|
||||
})
|
||||
r.GET("/api/v1/admin/proxies/all", h.GetAll)
|
||||
r.GET("/api/v1/admin/proxies", h.List)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", tc.path+tc.query, nil))
|
||||
require.Equal(t, tc.status, w.Code, w.Body.String())
|
||||
if tc.sample {
|
||||
require.Equal(t, 1, svc.samples)
|
||||
require.Zero(t, svc.calls)
|
||||
require.Contains(t, w.Body.String(), `"data":[`)
|
||||
require.Contains(t, w.Body.String(), `"id":12345`)
|
||||
require.Equal(t, "20000", w.Header().Get("X-Total-Count"))
|
||||
require.Equal(t, "50", w.Header().Get("X-Page-Size"))
|
||||
require.Equal(t, "no-store", w.Header().Get("Cache-Control"))
|
||||
if tc.query != "" {
|
||||
require.Equal(t, "region", svc.search)
|
||||
}
|
||||
} else {
|
||||
require.Zero(t, svc.samples)
|
||||
}
|
||||
require.NotContains(t, w.Body.String(), "secret-")
|
||||
require.NotContains(t, w.Body.String(), "password")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// adminUserResponse 对受限密钥使用字段白名单,避免完整管理员 DTO 新增字段时隐式扩大授权。
|
||||
// 订阅及用量由各自的独立接口提供,用户资料接口不嵌入这些关联数据。
|
||||
func adminUserResponse(c *gin.Context, user *service.User) any {
|
||||
principal := adminaccess.FromContext(c.Request.Context())
|
||||
if principal == nil {
|
||||
return dto.UserFromServiceAdmin(user)
|
||||
}
|
||||
if user == nil {
|
||||
return nil
|
||||
}
|
||||
out := gin.H{"id": user.ID}
|
||||
permissions := principal.Policy.GlobalPermissions
|
||||
if slices.Contains(permissions, "users.read") {
|
||||
out["email"] = user.Email
|
||||
out["username"] = user.Username
|
||||
out["role"] = user.Role
|
||||
out["status"] = user.Status
|
||||
out["concurrency"] = user.Concurrency
|
||||
out["rpm_limit"] = user.RPMLimit
|
||||
out["last_active_at"] = user.LastActiveAt
|
||||
out["created_at"] = user.CreatedAt
|
||||
out["updated_at"] = user.UpdatedAt
|
||||
out["deleted_at"] = user.DeletedAt
|
||||
}
|
||||
if slices.Contains(permissions, "users.balance.read") {
|
||||
out["balance"] = user.Balance
|
||||
out["frozen_balance"] = user.FrozenBalance
|
||||
out["total_recharged"] = user.TotalRecharged
|
||||
}
|
||||
if slices.Contains(permissions, "groups.read") {
|
||||
out["allowed_groups"] = user.AllowedGroups
|
||||
out["restrict_public_groups"] = user.RestrictPublicGroups
|
||||
out["group_rates"] = user.GroupRates
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type scopedUserResponseService struct {
|
||||
service.AdminService
|
||||
filters service.UserListFilters
|
||||
writes int
|
||||
}
|
||||
|
||||
func (*scopedUserResponseService) user() *service.User {
|
||||
return &service.User{ID: 7, Email: "user@example.com", Notes: "内部备注", Balance: 123,
|
||||
APIKeys: []service.APIKey{{Key: "内部密钥"}}, Subscriptions: []service.UserSubscription{{ID: 8, DailyUsageUSD: 10}}}
|
||||
}
|
||||
func (s *scopedUserResponseService) ListUsers(_ context.Context, _, _ int, filters service.UserListFilters, _, _ string) ([]service.User, int64, error) {
|
||||
s.filters = filters
|
||||
return []service.User{*s.user()}, 1, nil
|
||||
}
|
||||
func (s *scopedUserResponseService) GetUser(context.Context, int64) (*service.User, error) {
|
||||
return s.user(), nil
|
||||
}
|
||||
func (s *scopedUserResponseService) UpdateUserBalance(context.Context, int64, float64, string, string) (*service.User, error) {
|
||||
s.writes++
|
||||
return s.user(), nil
|
||||
}
|
||||
|
||||
func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
svc := &scopedUserResponseService{}
|
||||
h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil)
|
||||
r := gin.New()
|
||||
r.GET("/users", h.List)
|
||||
r.GET("/users/:id", h.GetByID)
|
||||
for _, path := range []string{"/users", "/users?include_subscriptions=true", "/users/7"} {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
|
||||
require.Equal(t, 200, w.Code)
|
||||
for _, field := range []string{`"notes":"内部备注"`, `"balance":123`, `"subscriptions":`, `"daily_usage_usd":10`, `"api_keys":`} {
|
||||
require.Contains(t, w.Body.String(), field)
|
||||
}
|
||||
if path == "/users" {
|
||||
require.Nil(t, svc.filters.IncludeSubscriptions)
|
||||
}
|
||||
if strings.Contains(path, "include_subscriptions") {
|
||||
require.NotNil(t, svc.filters.IncludeSubscriptions)
|
||||
require.True(t, *svc.filters.IncludeSubscriptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedAdminUserBalanceResponseRedactsCachedFullAdminResult(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
previous := service.DefaultIdempotencyCoordinator()
|
||||
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
|
||||
for _, scopedFirst := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "完整管理员先执行", true: "受限Key先执行"}[scopedFirst], func(t *testing.T) {
|
||||
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
|
||||
svc := &scopedUserResponseService{}
|
||||
h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9})
|
||||
if c.GetHeader("X-Test-Scoped") == "true" {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{
|
||||
KeyID: "test-key", Policy: adminaccess.Policy{GlobalPermissions: []string{"users.balance.write"}},
|
||||
}))
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
r.POST("/users/:id/balance", h.UpdateBalance)
|
||||
for i, scoped := range []bool{scopedFirst, !scopedFirst, true} {
|
||||
req := httptest.NewRequest("POST", "/users/7/balance", strings.NewReader(`{"balance":1,"operation":"add"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", "same-operation")
|
||||
if scoped {
|
||||
req.Header.Set("X-Test-Scoped", "true")
|
||||
}
|
||||
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"))
|
||||
}
|
||||
var result struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
|
||||
if scoped {
|
||||
require.Len(t, result.Data, 1)
|
||||
require.JSONEq(t, `7`, string(result.Data["id"]))
|
||||
} else {
|
||||
require.Contains(t, result.Data, "notes")
|
||||
require.Contains(t, result.Data, "balance")
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, svc.writes, "重放只改变当前响应的权限投影,不能重复修改余额")
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"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"
|
||||
)
|
||||
|
||||
func requireAdminKeyJWT(c *gin.Context) bool {
|
||||
if c.GetString("auth_method") != service.AuditAuthMethodJWT {
|
||||
response.Error(c, 403, "仅管理员 JWT 会话可管理密钥")
|
||||
return false
|
||||
}
|
||||
role, ok := middleware.GetUserRoleFromContext(c)
|
||||
if !ok || role != "admin" {
|
||||
response.Error(c, 403, "需要管理员权限")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (h *SettingHandler) ListScopedAdminKeys(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
items, e := h.settingService.ListScopedAdminKeys(c.Request.Context())
|
||||
if e != nil {
|
||||
response.ErrorFrom(c, e)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"items": items, "permissions": adminaccess.PermissionCatalog()})
|
||||
}
|
||||
func (h *SettingHandler) CreateScopedAdminKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
var in service.ScopedAdminKeyInput
|
||||
if e := c.ShouldBindJSON(&in); e != nil {
|
||||
response.Error(c, 400, "请求格式无效")
|
||||
return
|
||||
}
|
||||
subject, ok := middleware.GetAuthSubjectFromContext(c)
|
||||
if !ok {
|
||||
response.Error(c, 403, "需要管理员身份")
|
||||
return
|
||||
}
|
||||
key, item, e := h.settingService.CreateScopedAdminKey(c.Request.Context(), in, subject.UserID)
|
||||
if e != nil {
|
||||
response.ErrorFrom(c, e)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"key": key, "item": item})
|
||||
}
|
||||
func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
var in service.ScopedAdminKeyInput
|
||||
if e := c.ShouldBindJSON(&in); e != nil {
|
||||
response.Error(c, 400, "请求格式无效")
|
||||
return
|
||||
}
|
||||
item, e := h.settingService.UpdateScopedAdminKey(c.Request.Context(), c.Param("id"), in)
|
||||
if e != nil {
|
||||
response.ErrorFrom(c, e)
|
||||
return
|
||||
}
|
||||
response.Success(c, item)
|
||||
}
|
||||
func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
key, item, e := h.settingService.RotateScopedAdminKey(c.Request.Context(), c.Param("id"))
|
||||
if e != nil {
|
||||
response.ErrorFrom(c, e)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"key": key, "item": item})
|
||||
}
|
||||
func (h *SettingHandler) RevokeScopedAdminKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
if e := h.settingService.RevokeScopedAdminKey(c.Request.Context(), c.Param("id")); e != nil {
|
||||
response.ErrorFrom(c, e)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"message": "管理密钥已永久撤销"})
|
||||
}
|
||||
|
||||
func (h *SettingHandler) DeleteScopedAdminKeyRecord(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
if e := h.settingService.DeleteScopedAdminKeyRecord(c.Request.Context(), c.Param("id")); e != nil {
|
||||
response.ErrorFrom(c, e)
|
||||
return
|
||||
}
|
||||
response.Success(c, gin.H{"message": "密钥已从列表移除,历史操作记录仍会继续保留"})
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestScopedAdminKeyHandlersRejectNonJWT(t *testing.T) {
|
||||
h := &SettingHandler{}
|
||||
for _, fn := range []gin.HandlerFunc{h.ListScopedAdminKeys, h.CreateScopedAdminKey, h.UpdateScopedAdminKey, h.RotateScopedAdminKey, h.RevokeScopedAdminKey, h.DeleteScopedAdminKeyRecord, h.GetAdminAPIKey, h.RegenerateAdminAPIKey, h.DeleteAdminAPIKey} {
|
||||
for _, method := range []string{"", "admin_api_key"} {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Set("auth_method", method)
|
||||
fn(c)
|
||||
if w.Code != 403 {
|
||||
t.Fatalf("%s 应拒绝,返回 %d", method, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type deleteScopedKeyRecordRepo struct {
|
||||
service.ScopedAdminKeyRepository
|
||||
err error
|
||||
id string
|
||||
}
|
||||
|
||||
func (r *deleteScopedKeyRecordRepo) DeleteScopedAdminKeyRecord(_ context.Context, id string, at time.Time) error {
|
||||
r.id = id
|
||||
if at.IsZero() {
|
||||
panic("删除时间不能为空")
|
||||
}
|
||||
return r.err
|
||||
}
|
||||
|
||||
func TestScopedAdminKeyDeleteRecordHandler(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, role string
|
||||
err error
|
||||
status int
|
||||
}{
|
||||
{"仅列表移除", "admin", nil, 200},
|
||||
{"未撤销或已移除", "admin", service.ErrScopedAdminKeyNotFound, 404},
|
||||
{"普通用户拒绝", "user", nil, 403},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := &deleteScopedKeyRecordRepo{err: tc.err}
|
||||
settings := service.NewSettingService(nil, nil)
|
||||
settings.SetScopedAdminKeyRepository(repo)
|
||||
h := &SettingHandler{settingService: settings}
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("DELETE", "/api/v1/admin/settings/admin-api-keys/key-1/record", nil)
|
||||
c.Params = gin.Params{{Key: "id", Value: "key-1"}}
|
||||
c.Set("auth_method", service.AuditAuthMethodJWT)
|
||||
c.Set("user_role", tc.role)
|
||||
h.DeleteScopedAdminKeyRecord(c)
|
||||
require.Equal(t, tc.status, w.Code)
|
||||
if tc.role != "admin" {
|
||||
require.Empty(t, repo.id)
|
||||
} else {
|
||||
require.Equal(t, "key-1", repo.id)
|
||||
}
|
||||
if tc.status == 200 {
|
||||
require.Contains(t, w.Body.String(), "历史操作记录仍会继续保留")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect"
|
||||
entsql "entgo.io/ent/dialect/sql"
|
||||
dbent "github.com/Wei-Shaw/sub2api/ent"
|
||||
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
|
||||
"github.com/Wei-Shaw/sub2api/internal/repository"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
_ "github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// 在轮换读取旧值后暂停,让删除在恢复轮换之前完整提交。
|
||||
type legacyKeyReadBarrier struct {
|
||||
service.SettingRepository
|
||||
read chan struct{}
|
||||
resume chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (r *legacyKeyReadBarrier) GetValue(ctx context.Context, key string) (string, error) {
|
||||
value, err := r.SettingRepository.GetValue(ctx, key)
|
||||
if key == service.SettingKeyAdminAPIKey && err == nil {
|
||||
r.once.Do(func() { close(r.read); <-r.resume })
|
||||
}
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (r *legacyKeyReadBarrier) ReplaceExistingAdminAPIKey(ctx context.Context, value string) (bool, error) {
|
||||
return r.SettingRepository.(interface {
|
||||
ReplaceExistingAdminAPIKey(context.Context, string) (bool, error)
|
||||
}).ReplaceExistingAdminAPIKey(ctx, value)
|
||||
}
|
||||
|
||||
func legacyKeyRequest(handler gin.HandlerFunc) *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("POST", "/api/v1/admin/settings/admin-api-key/regenerate", nil)
|
||||
c.Set("auth_method", service.AuditAuthMethodJWT)
|
||||
c.Set("user_role", "admin")
|
||||
handler(c)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestLegacyAdminKeyRotationPostgres(t *testing.T) {
|
||||
dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN")
|
||||
}
|
||||
base, err := sql.Open("postgres", dsn)
|
||||
require.NoError(t, err)
|
||||
schema := fmt.Sprintf("legacy_key_test_%d", time.Now().UnixNano())
|
||||
_, err = base.Exec(`CREATE SCHEMA ` + schema)
|
||||
require.NoError(t, err)
|
||||
db, err := sql.Open("postgres", dsn+" search_path="+schema)
|
||||
require.NoError(t, err)
|
||||
client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))
|
||||
t.Cleanup(func() { _ = client.Close(); _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`); _ = base.Close() })
|
||||
_, err = db.Exec(`CREATE TABLE settings(id BIGSERIAL PRIMARY KEY, key VARCHAR(100) UNIQUE NOT NULL, value TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`)
|
||||
require.NoError(t, err)
|
||||
repo := repository.NewSettingRepository(client)
|
||||
settings := service.NewSettingService(repo, nil)
|
||||
h := &SettingHandler{settingService: settings}
|
||||
ctx := context.Background()
|
||||
|
||||
t.Run("删除先完成不得被轮换重建", func(t *testing.T) {
|
||||
require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "admin-test-old-key"))
|
||||
barrier := &legacyKeyReadBarrier{SettingRepository: repo, read: make(chan struct{}), resume: make(chan struct{})}
|
||||
var release sync.Once
|
||||
unblock := func() { release.Do(func() { close(barrier.resume) }) }
|
||||
defer unblock()
|
||||
rotating := &SettingHandler{settingService: service.NewSettingService(barrier, nil)}
|
||||
done := make(chan *httptest.ResponseRecorder, 1)
|
||||
go func() { done <- legacyKeyRequest(rotating.RegenerateAdminAPIKey) }()
|
||||
select {
|
||||
case <-barrier.read:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("轮换未进入读取屏障")
|
||||
}
|
||||
require.Equal(t, 200, legacyKeyRequest(h.DeleteAdminAPIKey).Code)
|
||||
var afterDelete int
|
||||
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM settings WHERE key=$1`, service.SettingKeyAdminAPIKey).Scan(&afterDelete))
|
||||
require.Zero(t, afterDelete, "恢复轮换前删除必须已经落库")
|
||||
unblock()
|
||||
var response *httptest.ResponseRecorder
|
||||
select {
|
||||
case response = <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("轮换未结束")
|
||||
}
|
||||
var count int
|
||||
require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM settings WHERE key=$1`, service.SettingKeyAdminAPIKey).Scan(&count))
|
||||
require.Zero(t, count, "已删除旧版密钥被轮换重新创建")
|
||||
require.Equal(t, 403, response.Code)
|
||||
require.NotContains(t, response.Body.String(), `"key":`)
|
||||
})
|
||||
|
||||
t.Run("已有密钥可轮换且随后可删除", func(t *testing.T) {
|
||||
require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, "admin-test-old-key"))
|
||||
response := legacyKeyRequest(h.RegenerateAdminAPIKey)
|
||||
require.Equal(t, 200, response.Code)
|
||||
key, err := settings.GetAdminAPIKey(ctx)
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, "admin-test-old-key", key)
|
||||
require.NotEmpty(t, key)
|
||||
require.Contains(t, response.Body.String(), key)
|
||||
require.Equal(t, 200, legacyKeyRequest(h.DeleteAdminAPIKey).Code)
|
||||
key, err = settings.GetAdminAPIKey(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, key)
|
||||
})
|
||||
|
||||
t.Run("缺失与空值不能新建", func(t *testing.T) {
|
||||
for _, emptyRow := range []bool{false, true} {
|
||||
require.NoError(t, settings.DeleteAdminAPIKey(ctx))
|
||||
if emptyRow {
|
||||
require.NoError(t, repo.Set(ctx, service.SettingKeyAdminAPIKey, ""))
|
||||
}
|
||||
require.Equal(t, 403, legacyKeyRequest(h.RegenerateAdminAPIKey).Code)
|
||||
key, err := settings.GenerateAdminAPIKey(ctx)
|
||||
require.Error(t, err, "服务层也必须拒绝从无到有创建")
|
||||
require.Empty(t, key)
|
||||
stored, err := settings.GetAdminAPIKey(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, stored)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -200,6 +200,7 @@ type CreateGroupRequest struct {
|
||||
// 图片生成计费配置(antigravity 和 gemini 平台使用,负数表示清除配置)
|
||||
AllowImageGeneration bool `json:"allow_image_generation"`
|
||||
AllowBatchImageGeneration bool `json:"allow_batch_image_generation"`
|
||||
ImageCountBilling bool `json:"image_count_billing"`
|
||||
ImageRateIndependent bool `json:"image_rate_independent"`
|
||||
ImageRateMultiplier *float64 `json:"image_rate_multiplier"`
|
||||
BatchImageDiscountMultiplier *float64 `json:"batch_image_discount_multiplier"`
|
||||
@@ -276,6 +277,7 @@ type UpdateGroupRequest struct {
|
||||
// 图片生成计费配置(antigravity 和 gemini 平台使用,负数表示清除配置)
|
||||
AllowImageGeneration *bool `json:"allow_image_generation"`
|
||||
AllowBatchImageGeneration *bool `json:"allow_batch_image_generation"`
|
||||
ImageCountBilling *bool `json:"image_count_billing"`
|
||||
ImageRateIndependent *bool `json:"image_rate_independent"`
|
||||
ImageRateMultiplier *float64 `json:"image_rate_multiplier"`
|
||||
BatchImageDiscountMultiplier *float64 `json:"batch_image_discount_multiplier"`
|
||||
@@ -681,6 +683,7 @@ func (h *GroupHandler) Create(c *gin.Context) {
|
||||
ModelPricing: req.ModelPricing,
|
||||
AllowImageGeneration: req.AllowImageGeneration,
|
||||
AllowBatchImageGeneration: req.AllowBatchImageGeneration,
|
||||
ImageCountBilling: req.ImageCountBilling,
|
||||
ImageRateIndependent: req.ImageRateIndependent,
|
||||
ImageRateMultiplier: req.ImageRateMultiplier,
|
||||
BatchImageDiscountMultiplier: req.BatchImageDiscountMultiplier,
|
||||
@@ -828,6 +831,7 @@ func (h *GroupHandler) Update(c *gin.Context) {
|
||||
ModelPricing: req.ModelPricing,
|
||||
AllowImageGeneration: req.AllowImageGeneration,
|
||||
AllowBatchImageGeneration: req.AllowBatchImageGeneration,
|
||||
ImageCountBilling: req.ImageCountBilling,
|
||||
ImageRateIndependent: req.ImageRateIndependent,
|
||||
ImageRateMultiplier: req.ImageRateMultiplier,
|
||||
BatchImageDiscountMultiplier: req.BatchImageDiscountMultiplier,
|
||||
|
||||
@@ -115,6 +115,18 @@ func executeAdminIdempotentJSONWithMode(
|
||||
mode idempotencyStoreUnavailableMode,
|
||||
execute func(context.Context) (any, error),
|
||||
) {
|
||||
executeAdminIdempotentJSONWithProjection(c, scope, payload, ttl, executionTimeout, mode, execute, nil)
|
||||
}
|
||||
|
||||
// executeAdminIdempotentJSONWithResponse 在实际执行及缓存重放之后统一约束响应。
|
||||
func executeAdminIdempotentJSONWithResponse(c *gin.Context, scope string, payload any, ttl time.Duration, execute func(context.Context) (any, error), present func(any) any) {
|
||||
executeAdminIdempotentJSONWithProjection(c, scope, payload, ttl, 0, idempotencyStoreUnavailableFailClose, execute, present)
|
||||
}
|
||||
|
||||
func executeAdminIdempotentJSONWithProjection(c *gin.Context, scope string, payload any, ttl time.Duration, executionTimeout time.Duration, mode idempotencyStoreUnavailableMode, execute func(context.Context) (any, error), present func(any) any) {
|
||||
if present == nil {
|
||||
present = func(data any) any { return data }
|
||||
}
|
||||
result, err := executeAdminIdempotentWithTimeout(c, scope, payload, ttl, executionTimeout, execute)
|
||||
if err != nil {
|
||||
if infraerrors.Code(err) == infraerrors.Code(service.ErrIdempotencyStoreUnavail) {
|
||||
@@ -131,7 +143,7 @@ func executeAdminIdempotentJSONWithMode(
|
||||
return
|
||||
}
|
||||
c.Header("X-Idempotency-Degraded", "store-unavailable")
|
||||
response.Success(c, data)
|
||||
response.Success(c, present(data))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -144,5 +156,5 @@ func executeAdminIdempotentJSONWithMode(
|
||||
if result != nil && result.Replayed {
|
||||
c.Header("X-Idempotency-Replayed", "true")
|
||||
}
|
||||
response.Success(c, result.Data)
|
||||
response.Success(c, present(result.Data))
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -309,6 +310,9 @@ func parseOpsOpenAITokenStatsFilter(c *gin.Context) (*service.OpsOpenAITokenStat
|
||||
}
|
||||
filter.PageSize = pageSize
|
||||
}
|
||||
if filter.Page > math.MaxInt/filter.PageSize {
|
||||
return nil, fmt.Errorf("invalid page")
|
||||
}
|
||||
return filter, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -207,5 +207,5 @@ func (h *PromoHandler) GetUsages(c *gin.Context) {
|
||||
for i := range usages {
|
||||
out = append(out, *dto.PromoCodeUsageFromService(&usages[i]))
|
||||
}
|
||||
response.Paginated(c, out, paginationResult.Total, page, pageSize)
|
||||
response.Paginated(c, adminPromoUsagesResponse(c, out), paginationResult.Total, page, pageSize)
|
||||
}
|
||||
@@ -57,6 +57,9 @@ type UpdateProxyRequest struct {
|
||||
// List handles listing all proxies with pagination
|
||||
// GET /api/v1/admin/proxies
|
||||
func (h *ProxyHandler) List(c *gin.Context) {
|
||||
if h.scopedAdminProxyRead(c) {
|
||||
return
|
||||
}
|
||||
page, pageSize := response.ParsePagination(c)
|
||||
protocol := c.Query("protocol")
|
||||
status := c.Query("status")
|
||||
@@ -86,6 +89,9 @@ func (h *ProxyHandler) List(c *gin.Context) {
|
||||
// GET /api/v1/admin/proxies/all
|
||||
// Optional query param: with_count=true to include account count per proxy
|
||||
func (h *ProxyHandler) GetAll(c *gin.Context) {
|
||||
if h.scopedAdminProxyRead(c) {
|
||||
return
|
||||
}
|
||||
withCount := c.Query("with_count") == "true"
|
||||
|
||||
if withCount {
|
||||
@@ -118,6 +124,9 @@ func (h *ProxyHandler) GetAll(c *gin.Context) {
|
||||
// GetByID handles getting a proxy by ID
|
||||
// GET /api/v1/admin/proxies/:id
|
||||
func (h *ProxyHandler) GetByID(c *gin.Context) {
|
||||
if h.scopedAdminProxyRead(c) {
|
||||
return
|
||||
}
|
||||
proxyID, err := strconv.ParseInt(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "Invalid proxy ID")
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 受限密钥仅接收记录自身字段;不嵌入完整用户资料或实时财务数据。
|
||||
type scopedPromoUsageResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
PromoCodeID int64 `json:"promo_code_id"`
|
||||
UserID int64 `json:"user_id"`
|
||||
BonusAmount float64 `json:"bonus_amount"`
|
||||
UsedAt time.Time `json:"used_at"`
|
||||
}
|
||||
|
||||
func adminPromoUsagesResponse(c *gin.Context, items []dto.PromoCodeUsage) any {
|
||||
if adminaccess.FromContext(c.Request.Context()) == nil {
|
||||
return items
|
||||
}
|
||||
out := make([]scopedPromoUsageResponse, 0, len(items))
|
||||
for _, item := range items {
|
||||
out = append(out, scopedPromoUsageResponse{ID: item.ID, PromoCodeID: item.PromoCodeID, UserID: item.UserID, BonusAmount: item.BonusAmount, UsedAt: item.UsedAt})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
type scopedAnnouncementReadResponse struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
Eligible bool `json:"eligible"`
|
||||
ReadAt *time.Time `json:"read_at,omitempty"`
|
||||
}
|
||||
|
||||
func adminAnnouncementReadResponse(c *gin.Context, items []service.AnnouncementUserReadStatus) any {
|
||||
if adminaccess.FromContext(c.Request.Context()) == nil {
|
||||
return items
|
||||
}
|
||||
out := make([]scopedAnnouncementReadResponse, 0, len(items))
|
||||
for _, item := range items {
|
||||
out = append(out, scopedAnnouncementReadResponse{UserID: item.UserID, Eligible: item.Eligible, ReadAt: item.ReadAt})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type scopedContentPromoRepo struct{ service.PromoCodeRepository }
|
||||
|
||||
func (scopedContentPromoRepo) ListUsagesByPromoCode(context.Context, int64, pagination.PaginationParams) ([]service.PromoCodeUsage, *pagination.PaginationResult, error) {
|
||||
return []service.PromoCodeUsage{{ID: 1, PromoCodeID: 2, UserID: 3, BonusAmount: 4, User: &service.User{ID: 3, Email: "private@example.com", Balance: 999, FrozenBalance: 888, TotalRecharged: 777}}}, &pagination.PaginationResult{Total: 1}, nil
|
||||
}
|
||||
|
||||
type scopedContentUsers struct{ service.UserRepository }
|
||||
|
||||
func (scopedContentUsers) ListWithFilters(context.Context, pagination.PaginationParams, service.UserListFilters) ([]service.User, *pagination.PaginationResult, error) {
|
||||
return []service.User{{ID: 3, Email: "private@example.com", Balance: 999}}, &pagination.PaginationResult{Total: 1}, nil
|
||||
}
|
||||
|
||||
type scopedContentSubs struct {
|
||||
service.UserSubscriptionRepository
|
||||
}
|
||||
|
||||
func (scopedContentSubs) ListActiveByUserID(context.Context, int64) ([]service.UserSubscription, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type scopedContentReads struct {
|
||||
service.AnnouncementReadRepository
|
||||
}
|
||||
|
||||
func (scopedContentReads) GetReadMapByUsers(context.Context, int64, []int64) (map[int64]time.Time, error) {
|
||||
return map[int64]time.Time{3: time.Unix(100, 0).UTC()}, nil
|
||||
}
|
||||
func TestScopedAdminContentHandlersResponseBoundary(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
promo := NewPromoHandler(service.NewPromoService(scopedContentPromoRepo{}, nil, nil, nil, nil))
|
||||
announcement := NewAnnouncementHandler(service.NewAnnouncementService(&announcementRepoCapture{}, scopedContentReads{}, scopedContentUsers{}, scopedContentSubs{}))
|
||||
for _, endpoint := range []struct {
|
||||
name, path, request string
|
||||
handler gin.HandlerFunc
|
||||
}{{"优惠码", "/promo-codes/:id/usages", "/promo-codes/2/usages", promo.GetUsages}, {"公告", "/announcements/:id/read-status", "/announcements/2/read-status", announcement.ListReadStatus}} {
|
||||
for _, scoped := range []bool{false, true} {
|
||||
t.Run(endpoint.name+map[bool]string{true: "受限", false: "普通"}[scoped], func(t *testing.T) {
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if scoped {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"promo.read", "announcements.read"}}}))
|
||||
}
|
||||
c.Next()
|
||||
})
|
||||
r.GET(endpoint.path, endpoint.handler)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", endpoint.request, nil))
|
||||
require.Equal(t, 200, w.Code)
|
||||
var body struct {
|
||||
Data struct {
|
||||
Items []map[string]json.RawMessage `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
|
||||
require.Len(t, body.Data.Items, 1)
|
||||
item := body.Data.Items[0]
|
||||
if scoped {
|
||||
require.NotContains(t, w.Body.String(), "private@example.com")
|
||||
require.NotContains(t, w.Body.String(), "999")
|
||||
require.NotContains(t, item, "user")
|
||||
require.NotContains(t, item, "balance")
|
||||
require.Contains(t, item, "user_id")
|
||||
if endpoint.name == "优惠码" {
|
||||
require.Contains(t, item, "bonus_amount")
|
||||
require.Contains(t, item, "used_at")
|
||||
} else {
|
||||
require.Contains(t, item, "eligible")
|
||||
require.Contains(t, item, "read_at")
|
||||
}
|
||||
} else {
|
||||
require.Contains(t, w.Body.String(), "private@example.com")
|
||||
require.Contains(t, w.Body.String(), "999")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func scopedAdminWriteOnly(c *gin.Context, readPermission string) bool {
|
||||
p := adminaccess.FromContext(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 {
|
||||
return data
|
||||
}
|
||||
raw, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return projectSubscriptionJSON(raw, !scopedAdminWriteOnly(c, "subscriptions.read"))
|
||||
}
|
||||
|
||||
func projectSubscriptionJSON(raw json.RawMessage, readable bool) any {
|
||||
var list []json.RawMessage
|
||||
if len(raw) > 0 && raw[0] == '[' && json.Unmarshal(raw, &list) == nil {
|
||||
out := make([]any, 0, len(list))
|
||||
for _, item := range list {
|
||||
out = append(out, projectSubscriptionJSON(item, readable))
|
||||
}
|
||||
return out
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &fields) != nil || fields == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]any)
|
||||
if subscriptions, ok := fields["subscriptions"]; ok {
|
||||
for _, key := range []string{"success_count", "created_count", "reused_count", "failed_count", "errors", "statuses"} {
|
||||
if value, exists := fields[key]; exists {
|
||||
out[key] = value
|
||||
}
|
||||
}
|
||||
out["subscriptions"] = projectSubscriptionJSON(subscriptions, readable)
|
||||
return out
|
||||
}
|
||||
keys := []string{"id"}
|
||||
if readable {
|
||||
keys = append(keys, "user_id", "group_id", "starts_at", "expires_at", "status",
|
||||
"daily_window_start", "weekly_window_start", "monthly_window_start",
|
||||
"daily_usage_usd", "weekly_usage_usd", "monthly_usage_usd",
|
||||
"created_at", "updated_at", "revoked_at", "assigned_by", "assigned_at", "notes")
|
||||
}
|
||||
for _, key := range keys {
|
||||
if value, exists := fields[key]; exists {
|
||||
out[key] = value
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
|
||||
"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 scopedSubscriptionRepo struct {
|
||||
service.UserSubscriptionRepository
|
||||
writes int
|
||||
}
|
||||
|
||||
func (*scopedSubscriptionRepo) GetByID(context.Context, int64) (*service.UserSubscription, error) {
|
||||
return &service.UserSubscription{ID: 1, UserID: 2, GroupID: 3, DailyUsageUSD: 4, ExpiresAt: time.Now().Add(time.Hour),
|
||||
User: &service.User{ID: 2, Email: "private-user@example.com", Balance: 987},
|
||||
AssignedByUser: &service.User{ID: 8, Email: "private-admin@example.com", Balance: 654},
|
||||
Group: &service.Group{ID: 3, Name: "group", RateMultiplier: 42}}, nil
|
||||
}
|
||||
func TestScopedAdminSubscriptionDoesNotExposeAssociatedUserAndPricing(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
s := service.NewSubscriptionService(nil, &scopedSubscriptionRepo{}, nil, nil, nil)
|
||||
defer s.Stop()
|
||||
h := NewSubscriptionHandler(s)
|
||||
for _, scoped := range []bool{false, true} {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest("GET", "/subscriptions/1", nil)
|
||||
c.Params = gin.Params{{Key: "id", Value: "1"}}
|
||||
if scoped {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"subscriptions.read"}}}))
|
||||
}
|
||||
h.GetByID(c)
|
||||
require.Equal(t, 200, w.Code)
|
||||
require.Contains(t, w.Body.String(), `"daily_usage_usd":4`)
|
||||
for _, field := range []string{"private-user@example.com", "private-admin@example.com", `"balance"`, `"rate_multiplier"`} {
|
||||
if scoped {
|
||||
require.NotContains(t, w.Body.String(), field)
|
||||
} else {
|
||||
require.Contains(t, w.Body.String(), field)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestScopedAdminQuotaWriteDoesNotGrantQuotaRead(t *testing.T) {
|
||||
repo := &upsertCapturingQuotaRepo{listRecords: []service.UserPlatformQuotaRecord{{UserID: 42, Platform: "anthropic"}}}
|
||||
h := buildTestHandler(repo, &billingCacheStub{})
|
||||
c, w := putReq(t, `{"quotas":[{"platform":"anthropic","daily_limit_usd":10}]}`)
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"users.quotas.write"}}}))
|
||||
h.UpdateUserPlatformQuotas(c)
|
||||
require.Equal(t, 200, w.Code)
|
||||
require.NotContains(t, w.Body.String(), "platform_quotas")
|
||||
require.NotContains(t, w.Body.String(), "usage")
|
||||
require.Len(t, repo.upsertCalls, 1)
|
||||
}
|
||||
|
||||
func (r *scopedSubscriptionRepo) GetByIDForUpdate(ctx context.Context, id int64) (*service.UserSubscription, error) {
|
||||
return r.GetByID(ctx, id)
|
||||
}
|
||||
func (r *scopedSubscriptionRepo) ExtendExpiry(context.Context, int64, time.Time) error {
|
||||
r.writes++
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestScopedAdminSubscriptionExtendReplayRespectsReadPermission(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
previous := service.DefaultIdempotencyCoordinator()
|
||||
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
|
||||
service.SetDefaultIdempotencyCoordinator(service.NewIdempotencyCoordinator(newMemoryIdempotencyRepoStub(), service.DefaultIdempotencyConfig()))
|
||||
repo := &scopedSubscriptionRepo{}
|
||||
svc := service.NewSubscriptionService(nil, repo, nil, nil, nil)
|
||||
defer svc.Stop()
|
||||
h := NewSubscriptionHandler(svc)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if c.GetHeader("X-Test-Mode") != "admin" {
|
||||
permissions := []string{"subscriptions.extend"}
|
||||
if c.GetHeader("X-Test-Mode") == "read" {
|
||||
permissions = append(permissions, "subscriptions.read")
|
||||
}
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: permissions}}))
|
||||
}
|
||||
})
|
||||
r.POST("/subscriptions/:id/extend", h.Extend)
|
||||
for i, mode := range []string{"admin", "write", "read"} {
|
||||
req := httptest.NewRequest("POST", "/subscriptions/1/extend", strings.NewReader(`{"days":1}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", "same-extension")
|
||||
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"))
|
||||
}
|
||||
var result struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
|
||||
if mode == "admin" {
|
||||
require.Contains(t, result.Data, "user")
|
||||
} else {
|
||||
require.NotContains(t, result.Data, "user")
|
||||
require.NotContains(t, result.Data, "group")
|
||||
require.NotContains(t, result.Data, "assigned_by_user")
|
||||
if mode == "write" {
|
||||
require.Len(t, result.Data, 1)
|
||||
} else {
|
||||
require.Contains(t, result.Data, "daily_usage_usd")
|
||||
}
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, repo.writes)
|
||||
}
|
||||
|
||||
func TestScopedAdminSubscriptionBulkProjectionPreservesIDs(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest("GET", "/", nil)
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{}))
|
||||
sub, _ := (&scopedSubscriptionRepo{}).GetByID(context.Background(), 1)
|
||||
sub.ID = 9007199254740993
|
||||
data := &dto.BulkAssignResult{SuccessCount: 1, Subscriptions: []dto.AdminUserSubscription{*dto.UserSubscriptionFromServiceAdmin(sub)}}
|
||||
raw, err := json.Marshal(adminSubscriptionResponse(c, data))
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(raw), `"id":9007199254740993`)
|
||||
require.Contains(t, string(raw), `"success_count":1`)
|
||||
for _, field := range []string{"daily_usage_usd", "user_id", "balance", "group", "private-user"} {
|
||||
require.NotContains(t, string(raw), field)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedAdminQuotaResetRequiresReadToReturnUsage(t *testing.T) {
|
||||
for _, readable := range []bool{false, true} {
|
||||
repo := &upsertCapturingQuotaRepo{listRecords: []service.UserPlatformQuotaRecord{{UserID: 42, Platform: "anthropic"}}}
|
||||
cache := &billingCacheStub{}
|
||||
h := buildTestHandler(repo, cache)
|
||||
c, w := postReq(t, `{"platform":"anthropic","window":"daily"}`)
|
||||
permissions := []string{"users.quotas.write"}
|
||||
if readable {
|
||||
permissions = append(permissions, "users.quotas.read")
|
||||
}
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: permissions}}))
|
||||
h.ResetUserPlatformQuotaWindow(c)
|
||||
require.Equal(t, 200, w.Code, w.Body.String())
|
||||
require.Len(t, repo.resetCalls, 1)
|
||||
require.Len(t, cache.deleteCalls, 1)
|
||||
if readable {
|
||||
require.Contains(t, w.Body.String(), "platform_quotas")
|
||||
} else {
|
||||
require.NotContains(t, w.Body.String(), "platform_quotas")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// scopedAdminUsageLogResponse 仅公开该次请求的用量、计费快照和请求元数据。
|
||||
// 关联资源只返回 ID;新增通用 DTO 字段不会自动获得受限密钥的读取权限。
|
||||
func scopedAdminUsageLogResponse(record *service.UsageLog) gin.H {
|
||||
if record == nil {
|
||||
return nil
|
||||
}
|
||||
// 在转换前移除关联,避免构造含原始密钥、用户余额等内容的嵌套 DTO。
|
||||
flat := *record
|
||||
flat.User, flat.APIKey, flat.Group, flat.Subscription, flat.Account = nil, nil, nil, nil, nil
|
||||
usage := dto.UsageLogFromServiceAdmin(&flat)
|
||||
return gin.H{
|
||||
"id": usage.ID,
|
||||
"user_id": usage.UserID,
|
||||
"api_key_id": usage.APIKeyID,
|
||||
"account_id": usage.AccountID,
|
||||
"request_id": usage.RequestID,
|
||||
"model": usage.Model,
|
||||
"service_tier": usage.ServiceTier,
|
||||
"reasoning_effort": usage.ReasoningEffort,
|
||||
"inbound_endpoint": usage.InboundEndpoint,
|
||||
"upstream_endpoint": usage.UpstreamEndpoint,
|
||||
"group_id": usage.GroupID,
|
||||
"subscription_id": usage.SubscriptionID,
|
||||
"input_tokens": usage.InputTokens,
|
||||
"output_tokens": usage.OutputTokens,
|
||||
"cache_creation_tokens": usage.CacheCreationTokens,
|
||||
"cache_read_tokens": usage.CacheReadTokens,
|
||||
"cache_creation_5m_tokens": usage.CacheCreation5mTokens,
|
||||
"cache_creation_1h_tokens": usage.CacheCreation1hTokens,
|
||||
"input_cost": usage.InputCost,
|
||||
"output_cost": usage.OutputCost,
|
||||
"cache_creation_cost": usage.CacheCreationCost,
|
||||
"cache_read_cost": usage.CacheReadCost,
|
||||
"total_cost": usage.TotalCost,
|
||||
"actual_cost": usage.ActualCost,
|
||||
"rate_multiplier": usage.RateMultiplier,
|
||||
"long_context_billing_applied": usage.LongContextBillingApplied,
|
||||
"billing_type": usage.BillingType,
|
||||
"request_type": usage.RequestType,
|
||||
"stream": usage.Stream,
|
||||
"openai_ws_mode": usage.OpenAIWSMode,
|
||||
"native_compaction_v2": usage.NativeCompactionV2,
|
||||
"duration_ms": usage.DurationMs,
|
||||
"first_token_ms": usage.FirstTokenMs,
|
||||
"image_count": usage.ImageCount,
|
||||
"image_size": usage.ImageSize,
|
||||
"image_input_size": usage.ImageInputSize,
|
||||
"image_output_size": usage.ImageOutputSize,
|
||||
"image_input_tokens": usage.ImageInputTokens,
|
||||
"image_input_cost": usage.ImageInputCost,
|
||||
"image_output_tokens": usage.ImageOutputTokens,
|
||||
"image_output_cost": usage.ImageOutputCost,
|
||||
"image_size_source": usage.ImageSizeSource,
|
||||
"image_size_breakdown": usage.ImageSizeBreakdown,
|
||||
"media_type": usage.MediaType,
|
||||
"user_agent": usage.UserAgent,
|
||||
"ip_address": usage.IPAddress,
|
||||
"session_id": usage.SessionID,
|
||||
"cache_ttl_overridden": usage.CacheTTLOverridden,
|
||||
"billing_mode": usage.BillingMode,
|
||||
"created_at": usage.CreatedAt,
|
||||
"upstream_model": usage.UpstreamModel,
|
||||
"upstream_reasoning_effort": usage.UpstreamReasoningEffort,
|
||||
"upstream_response_model": usage.UpstreamResponseModel,
|
||||
"upstream_model_mismatch": usage.UpstreamModelMismatch,
|
||||
"channel_id": usage.ChannelID,
|
||||
"model_mapping_chain": usage.ModelMappingChain,
|
||||
"upstream_request_id": usage.UpstreamRequestID,
|
||||
"billing_tier": usage.BillingTier,
|
||||
"account_rate_multiplier": usage.AccountRateMultiplier,
|
||||
"account_stats_cost": usage.AccountStatsCost,
|
||||
}
|
||||
}
|
||||
|
||||
func adminUsageLogResponses(c *gin.Context, records []service.UsageLog) any {
|
||||
if adminaccess.FromContext(c.Request.Context()) != nil {
|
||||
out := make([]gin.H, 0, len(records))
|
||||
for i := range records {
|
||||
out = append(out, scopedAdminUsageLogResponse(&records[i]))
|
||||
}
|
||||
return out
|
||||
}
|
||||
out := make([]dto.AdminUsageLog, 0, len(records))
|
||||
for i := range records {
|
||||
out = append(out, *dto.UsageLogFromServiceAdmin(&records[i]))
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build unit
|
||||
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type scopedUsageResponseRepo struct {
|
||||
service.UsageLogRepository
|
||||
records []service.UsageLog
|
||||
}
|
||||
|
||||
func (r *scopedUsageResponseRepo) ListWithFilters(context.Context, pagination.PaginationParams, usagestats.UsageLogFilters) ([]service.UsageLog, *pagination.PaginationResult, error) {
|
||||
return r.records, &pagination.PaginationResult{Total: int64(len(r.records))}, nil
|
||||
}
|
||||
func TestScopedAdminUsageListDoesNotGrantNestedResourceRead(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
privateUser := &service.User{ID: 7, Email: "private-email@example.invalid", Balance: 97531, Notes: "private-user-notes"}
|
||||
privateKey := &service.APIKey{ID: 8, Key: "private-api-key-secret", Name: "private-key-name", User: privateUser}
|
||||
privateGroup := &service.Group{ID: 9, Name: "private-group-name", Description: "private-group-description", RateMultiplier: 7}
|
||||
privateSub := &service.UserSubscription{ID: 10, User: privateUser, Group: privateGroup, DailyUsageUSD: 100}
|
||||
privateAccount := &service.Account{ID: 11, Name: "private-account-name", Credentials: map[string]any{"access_token": "private-account-token"}}
|
||||
for _, scoped := range []bool{true, false} {
|
||||
t.Run(map[bool]string{true: "受限用量读取", false: "完整管理员保留响应"}[scoped], func(t *testing.T) {
|
||||
repo := &scopedUsageResponseRepo{records: []service.UsageLog{{ID: 12, UserID: 7, APIKeyID: 8, AccountID: 11, RequestID: "request-public", RequestedModel: "requested-model", Model: "effective-model", InputTokens: 123, OutputTokens: 456, TotalCost: 1.25, ActualCost: 1, User: privateUser, APIKey: privateKey, Group: privateGroup, Subscription: privateSub, Account: privateAccount}}}
|
||||
h := NewUsageHandler(service.NewUsageService(repo, nil, nil, nil), nil, nil, nil)
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) {
|
||||
if scoped {
|
||||
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"usage.read"}}}))
|
||||
}
|
||||
})
|
||||
r.GET("/api/v1/admin/usage", h.List)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/usage", nil))
|
||||
require.Equal(t, 200, w.Code, w.Body.String())
|
||||
var result struct {
|
||||
Data struct {
|
||||
Items []map[string]json.RawMessage `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &result))
|
||||
require.Len(t, result.Data.Items, 1)
|
||||
require.EqualValues(t, 1, result.Data.Total)
|
||||
item := result.Data.Items[0]
|
||||
require.JSONEq(t, `123`, string(item["input_tokens"]))
|
||||
require.JSONEq(t, `456`, string(item["output_tokens"]))
|
||||
require.JSONEq(t, `1.25`, string(item["total_cost"]))
|
||||
require.JSONEq(t, `"requested-model"`, string(item["model"]))
|
||||
require.JSONEq(t, `8`, string(item["api_key_id"]))
|
||||
if scoped {
|
||||
require.NotContains(t, w.Body.String(), "private-")
|
||||
require.NotContains(t, w.Body.String(), "97531")
|
||||
for _, field := range []string{"user", "api_key", "group", "subscription", "account", "balance", "credentials"} {
|
||||
require.NotContains(t, item, field)
|
||||
}
|
||||
} else {
|
||||
require.Contains(t, w.Body.String(), "private-api-key-secret")
|
||||
require.Contains(t, w.Body.String(), "private-email@example.invalid")
|
||||
require.Contains(t, item, "user")
|
||||
require.Contains(t, item, "api_key")
|
||||
require.Contains(t, item, "account")
|
||||
}
|
||||
require.Equal(t, "private-api-key-secret", repo.records[0].APIKey.Key, "输出投影不得修改服务返回对象")
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestScopedAdminUsageListEmptyRemainsArray(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
h := NewUsageHandler(service.NewUsageService(&scopedUsageResponseRepo{}, 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{}))
|
||||
})
|
||||
r.GET("/usage", h.List)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("GET", "/usage", nil))
|
||||
require.Equal(t, 200, w.Code)
|
||||
require.Contains(t, w.Body.String(), `"items":[]`)
|
||||
}
|
||||
@@ -13,6 +13,9 @@ import (
|
||||
// GetAdminAPIKey 获取管理员 API Key 状态
|
||||
// GET /api/v1/admin/settings/admin-api-key
|
||||
func (h *SettingHandler) GetAdminAPIKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
maskedKey, exists, err := h.settingService.GetAdminAPIKeyStatus(c.Request.Context())
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
@@ -25,9 +28,21 @@ func (h *SettingHandler) GetAdminAPIKey(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// RegenerateAdminAPIKey 生成/重新生成管理员 API Key
|
||||
// RegenerateAdminAPIKey 轮换已存在的旧版管理员 API Key
|
||||
// POST /api/v1/admin/settings/admin-api-key/regenerate
|
||||
func (h *SettingHandler) RegenerateAdminAPIKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
_, exists, err := h.settingService.GetAdminAPIKeyStatus(c.Request.Context())
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
response.Error(c, 403, "旧版密钥已停止新建,请创建权限管理密钥")
|
||||
return
|
||||
}
|
||||
key, err := h.settingService.GenerateAdminAPIKey(c.Request.Context())
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
@@ -42,6 +57,9 @@ func (h *SettingHandler) RegenerateAdminAPIKey(c *gin.Context) {
|
||||
// DeleteAdminAPIKey 删除管理员 API Key
|
||||
// DELETE /api/v1/admin/settings/admin-api-key
|
||||
func (h *SettingHandler) DeleteAdminAPIKey(c *gin.Context) {
|
||||
if !requireAdminKeyJWT(c) {
|
||||
return
|
||||
}
|
||||
if err := h.settingService.DeleteAdminAPIKey(c.Request.Context()); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -94,7 +94,7 @@ func (h *SubscriptionHandler) List(c *gin.Context) {
|
||||
for i := range subscriptions {
|
||||
out = append(out, *dto.UserSubscriptionFromServiceAdmin(&subscriptions[i]))
|
||||
}
|
||||
response.PaginatedWithResult(c, out, toResponsePagination(pagination))
|
||||
response.PaginatedWithResult(c, adminSubscriptionResponse(c, out), toResponsePagination(pagination))
|
||||
}
|
||||
|
||||
// GetByID handles getting a subscription by ID
|
||||
@@ -112,7 +112,7 @@ func (h *SubscriptionHandler) GetByID(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription))
|
||||
response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(subscription)))
|
||||
}
|
||||
|
||||
// GetProgress handles getting subscription usage progress
|
||||
@@ -157,7 +157,7 @@ func (h *SubscriptionHandler) Assign(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription))
|
||||
response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(subscription)))
|
||||
}
|
||||
|
||||
// BulkAssign handles bulk assigning subscriptions to multiple users
|
||||
@@ -184,7 +184,7 @@ func (h *SubscriptionHandler) BulkAssign(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, dto.BulkAssignResultFromService(result))
|
||||
response.Success(c, adminSubscriptionResponse(c, dto.BulkAssignResultFromService(result)))
|
||||
}
|
||||
|
||||
// BulkAction applies one operation to selected subscriptions, returning each outcome.
|
||||
@@ -226,13 +226,13 @@ func (h *SubscriptionHandler) Extend(c *gin.Context) {
|
||||
SubscriptionID: subscriptionID,
|
||||
Body: req,
|
||||
}
|
||||
executeAdminIdempotentJSON(c, "admin.subscriptions.extend", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
|
||||
executeAdminIdempotentJSONWithResponse(c, "admin.subscriptions.extend", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
|
||||
subscription, execErr := h.subscriptionService.ExtendSubscription(ctx, subscriptionID, req.Days)
|
||||
if execErr != nil {
|
||||
return nil, execErr
|
||||
}
|
||||
return dto.UserSubscriptionFromServiceAdmin(subscription), nil
|
||||
})
|
||||
}, func(data any) any { return adminSubscriptionResponse(c, data) })
|
||||
}
|
||||
|
||||
// ResetSubscriptionQuotaRequest represents the reset quota request
|
||||
@@ -264,7 +264,7 @@ func (h *SubscriptionHandler) ResetQuota(c *gin.Context) {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
response.Success(c, dto.UserSubscriptionFromServiceAdmin(sub))
|
||||
response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(sub)))
|
||||
}
|
||||
|
||||
// Revoke handles revoking a subscription.
|
||||
@@ -301,7 +301,7 @@ func (h *SubscriptionHandler) Restore(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, dto.UserSubscriptionFromServiceAdmin(subscription))
|
||||
response.Success(c, adminSubscriptionResponse(c, dto.UserSubscriptionFromServiceAdmin(subscription)))
|
||||
}
|
||||
|
||||
// ListByGroup handles listing subscriptions for a specific group
|
||||
@@ -325,7 +325,7 @@ func (h *SubscriptionHandler) ListByGroup(c *gin.Context) {
|
||||
for i := range subscriptions {
|
||||
out = append(out, *dto.UserSubscriptionFromServiceAdmin(&subscriptions[i]))
|
||||
}
|
||||
response.PaginatedWithResult(c, out, toResponsePagination(pagination))
|
||||
response.PaginatedWithResult(c, adminSubscriptionResponse(c, out), toResponsePagination(pagination))
|
||||
}
|
||||
|
||||
// ListByUser handles listing subscriptions for a specific user
|
||||
@@ -347,7 +347,7 @@ func (h *SubscriptionHandler) ListByUser(c *gin.Context) {
|
||||
for i := range subscriptions {
|
||||
out = append(out, *dto.UserSubscriptionFromServiceAdmin(&subscriptions[i]))
|
||||
}
|
||||
response.Success(c, out)
|
||||
response.Success(c, adminSubscriptionResponse(c, out))
|
||||
}
|
||||
|
||||
// Helper function to get admin ID from context
|
||||
|
||||
@@ -213,11 +213,7 @@ func (h *UsageHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
out := make([]dto.AdminUsageLog, 0, len(records))
|
||||
for i := range records {
|
||||
out = append(out, *dto.UsageLogFromServiceAdmin(&records[i]))
|
||||
}
|
||||
response.Paginated(c, out, result.Total, page, pageSize)
|
||||
response.Paginated(c, adminUsageLogResponses(c, records), result.Total, page, pageSize)
|
||||
}
|
||||
|
||||
// Stats handles getting usage statistics with filters
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/quotaview"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -150,6 +151,11 @@ func (h *UserHandler) List(c *gin.Context) {
|
||||
includeSubscriptions := parseBoolQueryWithDefault(raw, true)
|
||||
filters.IncludeSubscriptions = &includeSubscriptions
|
||||
}
|
||||
principal := adminaccess.FromContext(c.Request.Context())
|
||||
if principal != nil {
|
||||
includeSubscriptions := false
|
||||
filters.IncludeSubscriptions = &includeSubscriptions
|
||||
}
|
||||
|
||||
users, total, err := h.adminService.ListUsers(c.Request.Context(), page, pageSize, filters, sortBy, sortOrder)
|
||||
if err != nil {
|
||||
@@ -157,6 +163,15 @@ func (h *UserHandler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if principal != nil {
|
||||
out := make([]any, len(users))
|
||||
for i := range users {
|
||||
out[i] = adminUserResponse(c, &users[i])
|
||||
}
|
||||
response.Paginated(c, out, total, page, pageSize)
|
||||
return
|
||||
}
|
||||
|
||||
// Batch get current concurrency (nil map if unavailable)
|
||||
var loadInfo map[int64]*service.UserLoadInfo
|
||||
if len(users) > 0 && h.concurrencyService != nil {
|
||||
@@ -227,7 +242,7 @@ func (h *UserHandler) GetByID(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, dto.UserFromServiceAdmin(user))
|
||||
response.Success(c, adminUserResponse(c, user))
|
||||
}
|
||||
|
||||
// BindAuthIdentity manually binds a canonical auth identity to a user.
|
||||
@@ -407,12 +422,18 @@ func (h *UserHandler) UpdateBalance(c *gin.Context) {
|
||||
UserID: userID,
|
||||
Body: req,
|
||||
}
|
||||
executeAdminIdempotentJSON(c, "admin.users.balance.update", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
|
||||
executeAdminIdempotentJSONWithResponse(c, "admin.users.balance.update", idempotencyPayload, service.DefaultWriteIdempotencyTTL(), func(ctx context.Context) (any, error) {
|
||||
user, execErr := h.adminService.UpdateUserBalance(ctx, userID, req.Balance, req.Operation, req.Notes)
|
||||
if execErr != nil {
|
||||
return nil, execErr
|
||||
}
|
||||
return dto.UserFromServiceAdmin(user), nil
|
||||
}, func(data any) any {
|
||||
// 成功确认不隐式授予用户资料或余额读取权限;缓存重放也必须经过此边界。
|
||||
if adminaccess.FromContext(c.Request.Context()) != nil {
|
||||
return gin.H{"id": userID}
|
||||
}
|
||||
return data
|
||||
})
|
||||
}
|
||||
|
||||
@@ -884,6 +905,10 @@ func (h *UserHandler) UpdateUserPlatformQuotas(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 返回最新状态
|
||||
if scopedAdminWriteOnly(c, "users.quotas.read") {
|
||||
response.Success(c, gin.H{"id": userID})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
records2, err := h.userPlatformQuotaRepo.ListByUser(ctx, userID)
|
||||
if err != nil {
|
||||
@@ -966,6 +991,11 @@ func (h *UserHandler) ResetUserPlatformQuotaWindow(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
if scopedAdminWriteOnly(c, "users.quotas.read") {
|
||||
response.Success(c, gin.H{"id": userID})
|
||||
return
|
||||
}
|
||||
|
||||
records, err := h.userPlatformQuotaRepo.ListByUser(ctx, userID)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
|
||||
@@ -100,3 +100,58 @@ func TestAccountFromServiceShallow_NilCredentialsOmitsStatus(t *testing.T) {
|
||||
require.Nil(t, got.Credentials)
|
||||
require.Nil(t, got.CredentialsStatus)
|
||||
}
|
||||
|
||||
func TestAccountFromService_RedactsGrokModelDiagnostics(t *testing.T) {
|
||||
src := &service.Account{
|
||||
ID: 25, Name: "grok", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth,
|
||||
Credentials: map[string]any{
|
||||
"access_token": "access-secret",
|
||||
"refresh_token": "refresh-secret",
|
||||
"api_key": "sk-secret",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
"model_mapping": map[string]any{"friendly": "grok-4.7"},
|
||||
},
|
||||
Extra: map[string]any{"grok_observed_models": map[string]any{"models": []any{"grok-4.7"}}},
|
||||
}
|
||||
|
||||
got := AccountFromService(src)
|
||||
require.Nil(t, got.GrokModelDiagnostics)
|
||||
shallow := AccountFromServiceShallow(src)
|
||||
require.Nil(t, shallow.GrokModelDiagnostics)
|
||||
|
||||
diagnostics := &service.GrokModelDiagnostics{
|
||||
State: "fresh",
|
||||
Endpoint: "https://cli-chat-proxy.grok.com/v1/models",
|
||||
Models: []string{"grok-4.7"},
|
||||
Mappings: []service.GrokModelDiagnosticItem{{Requested: "friendly", Upstream: "grok-4.7", Status: "listed"}},
|
||||
LastAttempt: &service.GrokCatalogAttempt{
|
||||
StartedAt: "2026-10-25T06:00:00Z", FinishedAt: "2026-10-25T06:00:01Z", Status: "failed", ErrorCode: "http_error",
|
||||
Scope: &service.GrokCatalogScope{AccountID: 25, AccountType: service.AccountTypeOAuth, Endpoint: "https://cli-chat-proxy.grok.com/v1/models"},
|
||||
},
|
||||
}
|
||||
diagRaw, err := json.Marshal(diagnostics)
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(diagRaw), "access-secret")
|
||||
require.NotContains(t, string(diagRaw), "query-secret")
|
||||
require.NotContains(t, string(diagRaw), "s3cret")
|
||||
require.NotContains(t, string(diagRaw), "user:")
|
||||
require.Contains(t, string(diagRaw), `"models":["grok-4.7"]`)
|
||||
require.NotContains(t, string(diagRaw), `"models":null`)
|
||||
require.NotContains(t, string(diagRaw), `"mappings":null`)
|
||||
got.GrokModelDiagnostics = diagnostics
|
||||
raw, err := json.Marshal(got)
|
||||
require.NoError(t, err)
|
||||
body := string(raw)
|
||||
require.Contains(t, body, `"grok_model_diagnostics"`)
|
||||
require.Contains(t, body, `"mappings":[`)
|
||||
require.NotContains(t, body, "access-secret")
|
||||
require.NotContains(t, body, "refresh-secret")
|
||||
require.NotContains(t, body, "sk-secret")
|
||||
require.NotContains(t, body, "query-secret")
|
||||
require.NotContains(t, body, "s3cret")
|
||||
|
||||
listRaw, err := json.Marshal(AccountListItemFromAccount(got))
|
||||
require.NoError(t, err)
|
||||
require.NotContains(t, string(listRaw), "grok_model_diagnostics")
|
||||
require.NotContains(t, string(listRaw), "access-secret")
|
||||
}
|
||||
@@ -194,6 +194,7 @@ func groupFromServiceBase(g *service.Group) Group {
|
||||
LongContextPricingEnabled: g.LongContextPricingEnabled,
|
||||
AllowImageGeneration: g.AllowImageGeneration,
|
||||
AllowBatchImageGeneration: g.AllowBatchImageGeneration,
|
||||
ImageCountBilling: g.ImageCountBilling,
|
||||
ImageRateIndependent: g.ImageRateIndependent,
|
||||
ImageRateMultiplier: g.ImageRateMultiplier,
|
||||
BatchImageDiscountMultiplier: g.BatchImageDiscountMultiplier,
|
||||
|
||||
@@ -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 /
|
||||
|
||||
@@ -112,6 +112,7 @@ type Group struct {
|
||||
// 图片生成计费配置(仅 antigravity 平台使用)
|
||||
AllowImageGeneration bool `json:"allow_image_generation"`
|
||||
AllowBatchImageGeneration bool `json:"allow_batch_image_generation"`
|
||||
ImageCountBilling bool `json:"image_count_billing"`
|
||||
ImageRateIndependent bool `json:"image_rate_independent"`
|
||||
ImageRateMultiplier float64 `json:"image_rate_multiplier"`
|
||||
BatchImageDiscountMultiplier float64 `json:"batch_image_discount_multiplier"`
|
||||
@@ -327,6 +328,9 @@ type Account struct {
|
||||
|
||||
GroupIDs []int64 `json:"group_ids,omitempty"`
|
||||
Groups []*Group `json:"groups,omitempty"`
|
||||
|
||||
// 仅账号详情填充。列表和公共 mapper 不计算,避免把目录诊断扩散到调度响应。
|
||||
GrokModelDiagnostics *service.GrokModelDiagnostics `json:"grok_model_diagnostics,omitempty"`
|
||||
}
|
||||
|
||||
// AccountListItem is the compact representation returned by the admin account
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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 账户可用
|
||||
|
||||
@@ -49,6 +49,7 @@ type AdminHandlers struct {
|
||||
type Handlers struct {
|
||||
Auth *AuthHandler
|
||||
User *UserHandler
|
||||
MCPOAuth *MCPOAuthHandler
|
||||
APIKey *APIKeyHandler
|
||||
Usage *UsageHandler
|
||||
Redeem *RedeemHandler
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 ©, 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")
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package adminaccess
|
||||
|
||||
import "slices"
|
||||
|
||||
type Permission struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Category string `json:"category"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
|
||||
type permissionDefinition struct {
|
||||
Permission
|
||||
Routes []string
|
||||
}
|
||||
|
||||
// 接口按方法和 Gin 完整路径精确登记;新增接口不会继承同目录权限。
|
||||
// 全站权限与账户规则独立,选中分组绝不会隐式授予全站操作。
|
||||
var definitions = []permissionDefinition{
|
||||
{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"}},
|
||||
{Permission{"accounts.credentials", "写入凭证(不包含读取)", "账户", "account"}, []string{"PUT /accounts/:id"}},
|
||||
{Permission{"accounts.models.write", "编辑账户白名单模型 ID 与映射", "账户", "account"}, []string{"PUT /accounts/:id", "POST /accounts/bulk-update"}},
|
||||
{Permission{"accounts.network", "修改接入地址、代理与连接选项", "账户", "account"}, []string{"PUT /accounts/:id"}},
|
||||
{Permission{"accounts.status", "启用、停用与调度开关", "账户", "account"}, []string{"PUT /accounts/:id", "POST /accounts/:id/schedulable"}},
|
||||
{Permission{"accounts.schedule", "修改并发、优先级与有效期", "账户", "account"}, []string{"PUT /accounts/:id"}},
|
||||
{Permission{"accounts.refresh", "刷新 OAuth 凭证", "账户", "account"}, []string{"POST /accounts/:id/refresh"}},
|
||||
{Permission{"accounts.recover", "清除账户错误与限流状态", "账户", "account"}, []string{"POST /accounts/:id/clear-error"}},
|
||||
{Permission{"accounts.delete", "删除账户(影响共享分组)", "账户", "account"}, []string{"DELETE /accounts/:id"}},
|
||||
{Permission{"accounts.groups", "调整授权分组关联", "账户", "account"}, []string{"PUT /accounts/:id"}},
|
||||
{Permission{"groups.models.read", "读取所选分组模型白名单与候选 ID", "分组模型", "group"}, []string{"GET /groups", "GET /groups/all", "GET /groups/:id", "GET /groups/:id/model-allowlist-candidates"}},
|
||||
{Permission{"groups.models.write", "编辑所选分组模型白名单(影响整个分组)", "分组模型", "group"}, []string{"PUT /groups/:id"}},
|
||||
{Permission{"proxies.read", "读取代理 IP 候选(分页,不含认证凭证)", "代理", "global"}, []string{"GET /proxies", "GET /proxies/all", "GET /proxies/:id"}},
|
||||
{Permission{"models.defaults.read", "读取默认白名单模型 ID(含默认映射)", "模型", "global"}, []string{"GET /accounts/antigravity/default-model-mapping", "GET /groups/:id/model-allowlist-candidates"}},
|
||||
{Permission{"dashboard.read", "读取全站经营报表", "报表", "global"}, []string{"GET /dashboard/snapshot-v2", "GET /dashboard/stats", "GET /dashboard/realtime", "GET /dashboard/trend", "GET /dashboard/models", "GET /dashboard/groups", "GET /dashboard/api-keys-trend", "GET /dashboard/users-trend", "GET /dashboard/users-ranking", "POST /dashboard/users-usage", "POST /dashboard/api-keys-usage", "GET /dashboard/user-breakdown"}},
|
||||
{Permission{"users.read", "读取全站用户资料(含联系方式)", "用户", "global"}, []string{"GET /users", "GET /users/:id", "GET /users/:id/rpm-status", "GET /users/:id/attributes"}},
|
||||
{Permission{"users.balance.read", "读取全站用户余额及流水", "财务", "global"}, []string{"GET /users/:id/balance-history"}},
|
||||
{Permission{"users.balance.write", "增减任意用户余额", "财务", "global"}, []string{"POST /users/:id/balance"}},
|
||||
{Permission{"users.quotas.read", "读取全站用户平台额度", "用户", "global"}, []string{"GET /users/:id/platform-quotas"}},
|
||||
{Permission{"users.quotas.write", "修改与重置全站用户平台额度", "用户", "global"}, []string{"PUT /users/:id/platform-quotas", "POST /users/:id/platform-quotas/reset"}},
|
||||
{Permission{"groups.read", "读取所有分组配置", "分组", "global"}, []string{"GET /groups", "GET /groups/all", "GET /groups/:id", "GET /groups/:id/rate-multipliers", "GET /groups/:id/composite-routes", "GET /groups/:id/model-allowlist-candidates"}},
|
||||
{Permission{"usage.read", "读取全站用量明细及用户用量", "报表", "global"}, []string{"GET /usage", "GET /usage/stats", "GET /users/:id/usage"}},
|
||||
{Permission{"payment.read", "读取全站支付订单与报表", "财务", "global"}, []string{"GET /payment/dashboard", "GET /payment/orders", "GET /payment/orders/:id"}},
|
||||
{Permission{"payment.cancel", "取消支付订单", "财务", "global"}, []string{"POST /payment/orders/:id/cancel"}},
|
||||
{Permission{"payment.fulfill", "重新履约支付订单", "财务", "global"}, []string{"POST /payment/orders/:id/retry"}},
|
||||
{Permission{"payment.refund", "发起退款及确认退款结果", "财务", "global"}, []string{"POST /payment/orders/:id/refund", "POST /payment/orders/:id/refund/query"}},
|
||||
{Permission{"payment.plans.read", "读取全部支付套餐", "财务", "global"}, []string{"GET /payment/plans"}},
|
||||
{Permission{"payment.plans.write", "创建、修改和删除支付套餐", "财务", "global"}, []string{"POST /payment/plans", "PUT /payment/plans/:id", "DELETE /payment/plans/:id"}},
|
||||
{Permission{"subscriptions.read", "读取全站订阅记录", "订阅", "global"}, []string{"GET /subscriptions", "GET /subscriptions/:id", "GET /subscriptions/:id/progress", "GET /groups/:id/subscriptions", "GET /users/:id/subscriptions"}},
|
||||
{Permission{"subscriptions.assign", "分配全站用户订阅", "订阅", "global"}, []string{"POST /subscriptions/assign", "POST /subscriptions/bulk-assign"}},
|
||||
{Permission{"subscriptions.extend", "延长订阅有效期", "订阅", "global"}, []string{"POST /subscriptions/:id/extend"}},
|
||||
{Permission{"subscriptions.revoke", "撤销订阅", "订阅", "global"}, []string{"POST /subscriptions/:id/revoke", "DELETE /subscriptions/:id"}},
|
||||
{Permission{"subscriptions.restore", "恢复订阅", "订阅", "global"}, []string{"POST /subscriptions/:id/restore"}},
|
||||
{Permission{"subscriptions.reset", "重置订阅额度", "订阅", "global"}, []string{"POST /subscriptions/:id/reset-quota"}},
|
||||
{Permission{"announcements.read", "读取所有公告与阅读记录", "内容", "global"}, []string{"GET /announcements", "GET /announcements/:id", "GET /announcements/:id/read-status"}},
|
||||
{Permission{"announcements.write", "创建、发布与修改公告", "内容", "global"}, []string{"POST /announcements", "PUT /announcements/:id"}},
|
||||
{Permission{"announcements.delete", "删除公告", "内容", "global"}, []string{"DELETE /announcements/:id"}},
|
||||
{Permission{"promo.read", "读取优惠码及使用记录", "财务", "global"}, []string{"GET /promo-codes", "GET /promo-codes/:id", "GET /promo-codes/:id/usages"}},
|
||||
{Permission{"promo.write", "创建与修改优惠码权益", "财务", "global"}, []string{"POST /promo-codes", "PUT /promo-codes/:id"}},
|
||||
{Permission{"promo.delete", "删除优惠码", "财务", "global"}, []string{"DELETE /promo-codes/:id"}},
|
||||
{Permission{"ops.read", "读取全站运维指标", "监控", "global"}, []string{"GET /ops/concurrency", "GET /ops/user-concurrency", "GET /ops/account-availability", "GET /ops/realtime-traffic", "GET /ops/ingress-rejections", "GET /ops/ingress-rejections/health", "GET /ops/auth-cache-invalidation/health", "GET /ops/dashboard/snapshot-v2", "GET /ops/dashboard/overview", "GET /ops/dashboard/throughput-trend", "GET /ops/dashboard/latency-histogram", "GET /ops/dashboard/error-trend", "GET /ops/dashboard/error-distribution", "GET /ops/dashboard/openai-token-stats"}},
|
||||
{Permission{"ops.errors.read", "读取全站请求错误详情(敏感)", "监控", "global"}, []string{"GET /ops/errors", "GET /ops/errors/:id", "GET /ops/request-errors", "GET /ops/request-errors/:id", "GET /ops/request-errors/:id/upstream-errors", "GET /ops/upstream-errors", "GET /ops/upstream-errors/:id", "GET /ops/requests"}},
|
||||
{Permission{"ops.errors.resolve", "标记请求错误处理状态", "监控", "global"}, []string{"PUT /ops/errors/:id/resolve", "PUT /ops/request-errors/:id/resolve", "PUT /ops/upstream-errors/:id/resolve"}},
|
||||
{Permission{"ops.alerts.read", "读取全站告警规则与事件", "监控", "global"}, []string{"GET /ops/alert-rules", "GET /ops/alert-events", "GET /ops/alert-events/:id"}},
|
||||
{Permission{"ops.alerts.write", "修改告警规则、状态与静默", "监控", "global"}, []string{"POST /ops/alert-rules", "PUT /ops/alert-rules/:id", "DELETE /ops/alert-rules/:id", "PUT /ops/alert-events/:id/status", "POST /ops/alert-silences"}},
|
||||
{Permission{"system.read", "读取系统版本与可更新版本", "系统", "global"}, []string{"GET /system/version", "GET /system/check-updates", "GET /system/rollback-versions"}},
|
||||
}
|
||||
|
||||
func PermissionCatalog() []Permission {
|
||||
result := make([]Permission, 0, len(definitions))
|
||||
for _, definition := range definitions {
|
||||
result = append(result, definition.Permission)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// RouteAllowed 只检查动作准入;账户资源及字段必须再由专用处理器检查。
|
||||
func RouteAllowed(policy Policy, method, path string) bool {
|
||||
target := method + " " + path
|
||||
for _, definition := range definitions {
|
||||
matched := false
|
||||
for _, route := range definition.Routes {
|
||||
// route 的方法前缀与资源路径固定,不做前缀通配或按 HTTP 方法推断读写。
|
||||
for i, ch := range route {
|
||||
if ch == ' ' {
|
||||
matched = target == route[:i]+" /api/v1/admin"+route[i+1:]
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
if definition.Scope == "global" && slices.Contains(policy.GlobalPermissions, definition.ID) {
|
||||
return true
|
||||
}
|
||||
if (definition.Scope == "account" || definition.Scope == "group") && len(policy.RulesFor(definition.ID)) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// Package adminaccess 定义管理密钥的显式授权,不依赖 HTTP 或数据库实现。
|
||||
package adminaccess
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Rule struct {
|
||||
Permissions []string `json:"permissions"`
|
||||
GroupIDs []int64 `json:"group_ids"`
|
||||
AllGroups bool `json:"all_groups"`
|
||||
IncludeUngrouped bool `json:"include_ungrouped"`
|
||||
AccountTypes []string `json:"account_types"`
|
||||
Platforms []string `json:"platforms"`
|
||||
}
|
||||
|
||||
type Policy struct {
|
||||
Rules []Rule `json:"rules"`
|
||||
GlobalPermissions []string `json:"global_permissions"`
|
||||
}
|
||||
|
||||
type Principal struct {
|
||||
KeyID string
|
||||
KeyName string
|
||||
CreatorID int64
|
||||
Policy Policy
|
||||
}
|
||||
|
||||
type Account struct {
|
||||
ID int64
|
||||
GroupIDs []int64
|
||||
Type string
|
||||
Platform string
|
||||
}
|
||||
|
||||
type principalContextKey struct{}
|
||||
|
||||
func WithPrincipal(ctx context.Context, principal *Principal) context.Context {
|
||||
return context.WithValue(ctx, principalContextKey{}, principal)
|
||||
}
|
||||
|
||||
func FromContext(ctx context.Context) *Principal {
|
||||
principal, _ := ctx.Value(principalContextKey{}).(*Principal)
|
||||
return principal
|
||||
}
|
||||
|
||||
// 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)) {
|
||||
return false
|
||||
}
|
||||
if len(a.GroupIDs) == 0 {
|
||||
return r.IncludeUngrouped
|
||||
}
|
||||
if r.AllGroups {
|
||||
return true
|
||||
}
|
||||
for _, id := range a.GroupIDs {
|
||||
if id > 0 && slices.Contains(r.GroupIDs, id) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p Policy) RulesFor(permission string) []Rule {
|
||||
rules := make([]Rule, 0)
|
||||
for _, r := range p.Rules {
|
||||
if slices.Contains(r.Permissions, permission) {
|
||||
rules = append(rules, r)
|
||||
}
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
func (p Policy) AllowsAccount(permission string, a Account) bool {
|
||||
for _, r := range p.RulesFor(permission) {
|
||||
if r.Matches(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AllowsGroup 只有当前账户及目标分组在同一授权规则内,才能调整该关联。
|
||||
func (p Policy) AllowsGroup(permission string, a Account, groupID int64) bool {
|
||||
if groupID <= 0 {
|
||||
return false
|
||||
}
|
||||
for _, r := range p.RulesFor(permission) {
|
||||
if r.Matches(a) && (r.AllGroups || slices.Contains(r.GroupIDs, groupID)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AllowsGroupConfig 只授权显式勾选的分组配置动作;账户类型不适用于整个分组的配置。
|
||||
// 分组与平台仍须命中同一规则,不能从不同规则拼接授权。
|
||||
func (p Policy) AllowsGroupConfig(permission string, id int64, platform string) bool {
|
||||
if id <= 0 {
|
||||
return false
|
||||
}
|
||||
for _, r := range p.RulesFor(permission) {
|
||||
if (r.AllGroups || slices.Contains(r.GroupIDs, id)) && (len(r.Platforms) == 0 || slices.Contains(r.Platforms, platform)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func ValidatePolicy(p Policy) error {
|
||||
if len(p.Rules) > 32 || len(p.GlobalPermissions) > 128 {
|
||||
return fmt.Errorf("授权规则数量超过限制")
|
||||
}
|
||||
catalog := make(map[string]string)
|
||||
for _, permission := range PermissionCatalog() {
|
||||
catalog[permission.ID] = permission.Scope
|
||||
}
|
||||
for _, permission := range p.GlobalPermissions {
|
||||
if catalog[permission] != "global" {
|
||||
return fmt.Errorf("无效的全站权限:%s", permission)
|
||||
}
|
||||
}
|
||||
for _, r := range p.Rules {
|
||||
if len(r.Permissions) > 64 || len(r.GroupIDs) > 1000 || len(r.AccountTypes) > 32 || len(r.Platforms) > 64 {
|
||||
return fmt.Errorf("授权范围超过限制")
|
||||
}
|
||||
for _, permission := range r.Permissions {
|
||||
if catalog[permission] != "account" && catalog[permission] != "group" {
|
||||
return fmt.Errorf("无效的资源权限:%s", permission)
|
||||
}
|
||||
}
|
||||
for _, id := range r.GroupIDs {
|
||||
if id <= 0 {
|
||||
return fmt.Errorf("分组 ID 必须是正整数")
|
||||
}
|
||||
}
|
||||
for _, kind := range r.AccountTypes {
|
||||
if !slices.Contains([]string{"oauth", "setup-token", "apikey", "upstream", "bedrock", "service_account"}, kind) {
|
||||
return fmt.Errorf("无效的账户类型:%s", kind)
|
||||
}
|
||||
}
|
||||
for _, platform := range r.Platforms {
|
||||
if strings.TrimSpace(platform) != platform || platform == "" || len(platform) > 64 || platform == "*" {
|
||||
return fmt.Errorf("无效的平台")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
//go:build unit
|
||||
|
||||
package adminaccess
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestScopedAdminPolicyDefaultDeny(t *testing.T) {
|
||||
selectedGroupsOnly := Policy{Rules: []Rule{{GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}
|
||||
for _, policy := range []Policy{{}, selectedGroupsOnly} {
|
||||
for _, route := range []struct{ method, path string }{
|
||||
{"GET", "/api/v1/admin/accounts"}, {"GET", "/api/v1/admin/accounts/:id"},
|
||||
{"PUT", "/api/v1/admin/settings"}, {"GET", "/api/v1/admin/users"},
|
||||
{"POST", "/api/v1/admin/payment/orders/:id/refund"},
|
||||
{"POST", "/api/v1/admin/settings/admin-api-keys"},
|
||||
} {
|
||||
require.False(t, RouteAllowed(policy, route.method, route.path), route.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedAdminModelPermissionsAreIndependent(t *testing.T) {
|
||||
write := Policy{Rules: []Rule{{Permissions: []string{"accounts.models.write"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}
|
||||
read := Policy{GlobalPermissions: []string{"models.defaults.read"}}
|
||||
require.NoError(t, ValidatePolicy(write))
|
||||
require.NoError(t, ValidatePolicy(read))
|
||||
require.True(t, RouteAllowed(write, "PUT", "/api/v1/admin/accounts/:id"))
|
||||
for _, path := range []string{"/api/v1/admin/accounts/antigravity/default-model-mapping"} {
|
||||
require.True(t, RouteAllowed(read, "GET", path))
|
||||
require.False(t, RouteAllowed(write, "GET", path))
|
||||
require.False(t, RouteAllowed(Policy{}, "GET", path))
|
||||
}
|
||||
for _, policy := range []Policy{write, read} {
|
||||
require.False(t, RouteAllowed(policy, "PUT", "/api/v1/admin/model-catalog/:platform"))
|
||||
require.False(t, RouteAllowed(policy, "DELETE", "/api/v1/admin/model-catalog/:platform"))
|
||||
require.False(t, RouteAllowed(policy, "GET", "/api/v1/admin/accounts/:id/models"))
|
||||
require.False(t, RouteAllowed(policy, "POST", "/api/v1/admin/accounts/:id/models/sync-upstream"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedAdminPolicyAccountRulesNeverCrossProduct(t *testing.T) {
|
||||
p := Policy{Rules: []Rule{
|
||||
{Permissions: []string{"accounts.read", "accounts.refresh"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}},
|
||||
{Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"apikey"}},
|
||||
}}
|
||||
for _, tc := range []struct {
|
||||
name, permission string
|
||||
account Account
|
||||
allowed bool
|
||||
}{
|
||||
{"组内OAuth", "accounts.refresh", Account{GroupIDs: []int64{1}, Type: "oauth", Platform: "openai"}, true},
|
||||
{"共享账户任一组匹配", "accounts.refresh", Account{GroupIDs: []int64{1, 9}, Type: "oauth", Platform: "openai"}, true},
|
||||
{"其他类型拒绝", "accounts.refresh", Account{GroupIDs: []int64{1}, Type: "apikey", Platform: "openai"}, false},
|
||||
{"其他组拒绝", "accounts.refresh", Account{GroupIDs: []int64{9}, Type: "oauth", Platform: "openai"}, false},
|
||||
{"其他平台拒绝", "accounts.refresh", Account{GroupIDs: []int64{1}, Type: "oauth", Platform: "anthropic"}, false},
|
||||
{"不能借另一规则提权", "accounts.refresh", Account{GroupIDs: []int64{2}, Type: "apikey", Platform: "openai"}, false},
|
||||
{"setup-token不能冒充OAuth", "accounts.read", Account{GroupIDs: []int64{1}, Type: "setup-token", Platform: "openai"}, false},
|
||||
{"未分组默认拒绝", "accounts.read", Account{Type: "oauth", Platform: "openai"}, false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) { require.Equal(t, tc.allowed, p.AllowsAccount(tc.permission, tc.account)) })
|
||||
}
|
||||
require.True(t, RouteAllowed(p, "GET", "/api/v1/admin/accounts"))
|
||||
require.False(t, RouteAllowed(p, "DELETE", "/api/v1/admin/accounts/:id"))
|
||||
require.False(t, RouteAllowed(p, "GET", "/api/v1/admin/groups"))
|
||||
require.False(t, RouteAllowed(p, "POST", "/api/v1/admin/openai/refresh-token"))
|
||||
}
|
||||
|
||||
func TestScopedAdminPolicyGroupChanges(t *testing.T) {
|
||||
a := Account{GroupIDs: []int64{1, 2}, Type: "oauth", Platform: "openai"}
|
||||
p := Policy{Rules: []Rule{{Permissions: []string{"accounts.groups"}, GroupIDs: []int64{1, 3}, AccountTypes: []string{"oauth"}}}}
|
||||
require.True(t, p.AllowsGroup("accounts.groups", a, 1))
|
||||
require.True(t, p.AllowsGroup("accounts.groups", a, 3))
|
||||
require.False(t, p.AllowsGroup("accounts.groups", a, 2))
|
||||
require.False(t, p.AllowsGroup("accounts.groups", Account{GroupIDs: []int64{2}, Type: "oauth"}, 1))
|
||||
require.False(t, p.AllowsGroup("accounts.groups", a, 0))
|
||||
}
|
||||
|
||||
func TestScopedAdminPolicyExplicitAllAndUngrouped(t *testing.T) {
|
||||
p := Policy{Rules: []Rule{{Permissions: []string{"accounts.read"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}
|
||||
require.True(t, p.AllowsAccount("accounts.read", Account{GroupIDs: []int64{999}, Type: "oauth"}))
|
||||
require.False(t, p.AllowsAccount("accounts.read", Account{Type: "oauth"}))
|
||||
p.Rules[0].IncludeUngrouped = true
|
||||
require.True(t, p.AllowsAccount("accounts.read", Account{Type: "oauth"}))
|
||||
p.Rules[0].AccountTypes = nil
|
||||
require.False(t, p.AllowsAccount("accounts.read", Account{Type: "oauth"}))
|
||||
}
|
||||
|
||||
func TestScopedAdminPolicyValidationAndGlobalIsolation(t *testing.T) {
|
||||
require.NoError(t, ValidatePolicy(Policy{}))
|
||||
for _, p := range []Policy{
|
||||
{GlobalPermissions: []string{"*"}}, {GlobalPermissions: []string{"accounts.read"}},
|
||||
{Rules: []Rule{{Permissions: []string{"users.read"}}}},
|
||||
{Rules: []Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{-1}}}},
|
||||
{Rules: []Rule{{AccountTypes: []string{"future_type"}}}},
|
||||
} {
|
||||
require.Error(t, ValidatePolicy(p))
|
||||
}
|
||||
p := Policy{GlobalPermissions: []string{"users.read"}}
|
||||
require.NoError(t, ValidatePolicy(p))
|
||||
require.True(t, RouteAllowed(p, "GET", "/api/v1/admin/users"))
|
||||
require.False(t, RouteAllowed(p, "PUT", "/api/v1/admin/users/:id"))
|
||||
require.False(t, RouteAllowed(p, "POST", "/api/v1/admin/users/:id/balance"))
|
||||
require.False(t, RouteAllowed(p, "GET", "/api/v1/admin/accounts/:id"))
|
||||
all := Policy{}
|
||||
for _, perm := range PermissionCatalog() {
|
||||
if perm.Scope == "global" {
|
||||
all.GlobalPermissions = append(all.GlobalPermissions, perm.ID)
|
||||
} else {
|
||||
all.Rules = append(all.Rules, Rule{Permissions: []string{perm.ID}, AllGroups: true, IncludeUngrouped: true, AccountTypes: []string{"oauth", "apikey"}})
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/api/v1/admin/future-endpoint", "/api/v1/admin/settings/admin-api-key/regenerate", "/api/v1/admin/settings/admin-api-keys", "/api/v1/admin/system/restart", "/api/v1/admin/accounts/data", "/api/v1/admin/backups/:id/download-url"} {
|
||||
for _, method := range []string{"GET", "POST", "PUT", "DELETE"} {
|
||||
require.False(t, RouteAllowed(all, method, path), method+" "+path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopedAdminPrincipalContext(t *testing.T) {
|
||||
require.Nil(t, FromContext(context.Background()))
|
||||
p := &Principal{KeyID: "key-1", KeyName: "只读"}
|
||||
require.Same(t, p, FromContext(WithPrincipal(context.Background(), p)))
|
||||
}
|
||||
|
||||
func TestScopedAdminGroupModelsAreExplicitAndScoped(t *testing.T) {
|
||||
p := Policy{Rules: []Rule{
|
||||
{Permissions: []string{"groups.models.read"}, GroupIDs: []int64{2}, Platforms: []string{"openai"}},
|
||||
{Permissions: []string{"groups.models.write"}, GroupIDs: []int64{3}, Platforms: []string{"anthropic"}},
|
||||
}}
|
||||
require.NoError(t, ValidatePolicy(p))
|
||||
require.True(t, p.AllowsGroupConfig("groups.models.read", 2, "openai"))
|
||||
require.False(t, p.AllowsGroupConfig("groups.models.write", 2, "openai"))
|
||||
require.False(t, p.AllowsGroupConfig("groups.models.read", 3, "openai"))
|
||||
require.False(t, p.AllowsGroupConfig("groups.models.read", 2, "anthropic"))
|
||||
require.False(t, p.AllowsGroupConfig("groups.models.read", 0, "openai"))
|
||||
require.False(t, p.AllowsAccount("accounts.read", Account{GroupIDs: []int64{2}, Type: "oauth", Platform: "openai"}))
|
||||
require.True(t, RouteAllowed(p, "GET", "/api/v1/admin/groups"))
|
||||
require.False(t, RouteAllowed(p, "DELETE", "/api/v1/admin/groups/:id"))
|
||||
require.Error(t, ValidatePolicy(Policy{GlobalPermissions: []string{"groups.models.write"}}))
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package antigravity
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
@@ -10,6 +11,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrMalformedFunctionCall = errors.New("upstream returned MALFORMED_FUNCTION_CALL")
|
||||
|
||||
// TransformGeminiToClaude 将 Gemini 响应转换为 Claude 格式(非流式)
|
||||
func TransformGeminiToClaude(geminiResp []byte, originalModel string) ([]byte, *ClaudeUsage, error) {
|
||||
// 解包 v1internal 响应
|
||||
@@ -34,6 +37,10 @@ func TransformGeminiToClaude(geminiResp []byte, originalModel string) ([]byte, *
|
||||
v1Resp.ModelVersion = directResp.ModelVersion
|
||||
}
|
||||
|
||||
if len(v1Resp.Response.Candidates) > 0 && v1Resp.Response.Candidates[0].FinishReason == "MALFORMED_FUNCTION_CALL" {
|
||||
return nil, nil, ErrMalformedFunctionCall
|
||||
}
|
||||
|
||||
// 使用处理器转换
|
||||
processor := NewNonStreamingProcessor()
|
||||
claudeResp := processor.Process(&v1Resp.Response, v1Resp.ResponseID, originalModel)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package antigravity
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMalformedFunctionCallTransform(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"candidates":[{"finishReason":"MALFORMED_FUNCTION_CALL","content":{"parts":[{"thoughtSignature":"test-signature"}]}}]}`,
|
||||
`{"response":{"candidates":[{"finishReason":"MALFORMED_FUNCTION_CALL"}]}}`,
|
||||
} {
|
||||
response, _, err := TransformGeminiToClaude([]byte(body), "test-model")
|
||||
if !errors.Is(err, ErrMalformedFunctionCall) || response != nil {
|
||||
t.Fatalf("expected malformed call error without successful response: %s %v", response, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ func AnthropicToResponsesWithMinOutputTokens(req *AnthropicRequest, minOutputTok
|
||||
|
||||
// An explicit thinking disable takes precedence over output_config.effort.
|
||||
effort := anthropicReasoningEffort(req)
|
||||
if openai.IsGPT61SolModelSpelling(req.Model) && req.OutputConfig != nil && req.OutputConfig.Effort == "max" && effort != "none" {
|
||||
if (openai.IsGPT61SolModelSpelling(req.Model) || openai.IsGPT61TerraModelSpelling(req.Model)) && req.OutputConfig != nil && req.OutputConfig.Effort == "max" && effort != "none" {
|
||||
effort = "max"
|
||||
}
|
||||
out.Reasoning = &ResponsesReasoning{
|
||||
|
||||
@@ -18,16 +18,22 @@ type ModelsListResponse struct {
|
||||
func DefaultModels() []Model {
|
||||
methods := []string{"generateContent", "streamGenerateContent"}
|
||||
return []Model{
|
||||
{Name: "models/gemini-2.0-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-2.5-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-2.5-flash-image", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-2.5-pro", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.5-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-image-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-lite-image", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3-pro-image", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3-pro-image-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3-flash-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3-pro-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-pro-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-pro-preview-customtools", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-image", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-lite", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.1-flash-lite-preview", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.5-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.5-flash-lite", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.6-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.7-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-3.8-flash", SupportedGenerationMethods: methods},
|
||||
{Name: "models/gemini-4-argon", SupportedGenerationMethods: methods},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ func TestDefaultModels_ContainsFallbackCatalogModels(t *testing.T) {
|
||||
}
|
||||
|
||||
required := []string{
|
||||
"models/gemini-2.5-flash-image",
|
||||
"models/gemini-3-pro-image",
|
||||
"models/gemini-3.1-pro-preview-customtools",
|
||||
"models/gemini-3.1-flash-image",
|
||||
}
|
||||
|
||||
@@ -11,15 +11,22 @@ type Model struct {
|
||||
|
||||
// DefaultModels is the curated Gemini model list used by the admin UI "test account" flow.
|
||||
var DefaultModels = []Model{
|
||||
{ID: "gemini-2.0-flash", Type: "model", DisplayName: "Gemini 2.0 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-2.5-flash", Type: "model", DisplayName: "Gemini 2.5 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-2.5-flash-image", Type: "model", DisplayName: "Gemini 2.5 Flash Image", CreatedAt: ""},
|
||||
{ID: "gemini-2.5-pro", Type: "model", DisplayName: "Gemini 2.5 Pro", CreatedAt: ""},
|
||||
{ID: "gemini-3.5-flash", Type: "model", DisplayName: "Gemini 3.5 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-3-flash-preview", Type: "model", DisplayName: "Gemini 3 Flash Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3-pro-preview", Type: "model", DisplayName: "Gemini 3 Pro Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-flash-image", Type: "model", DisplayName: "Gemini 3.1 Flash Image", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-flash-image-preview", Type: "model", DisplayName: "Gemini 3.1 Flash Image Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-flash-lite-image", Type: "model", DisplayName: "Gemini 3.1 Flash Lite Image", CreatedAt: ""},
|
||||
{ID: "gemini-3-pro-image", Type: "model", DisplayName: "Gemini 3 Pro Image", CreatedAt: ""},
|
||||
{ID: "gemini-3-pro-image-preview", Type: "model", DisplayName: "Gemini 3 Pro Image Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3-flash", Type: "model", DisplayName: "Gemini 3 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-3-flash-preview", Type: "model", DisplayName: "Gemini 3 Flash Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-pro-preview", Type: "model", DisplayName: "Gemini 3.1 Pro Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-pro-preview-customtools", Type: "model", DisplayName: "Gemini 3.1 Pro Preview Custom Tools", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-flash-lite", Type: "model", DisplayName: "Gemini 3.1 Flash Lite", CreatedAt: ""},
|
||||
{ID: "gemini-3.1-flash-lite-preview", Type: "model", DisplayName: "Gemini 3.1 Flash Lite Preview", CreatedAt: ""},
|
||||
{ID: "gemini-3.5-flash", Type: "model", DisplayName: "Gemini 3.5 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-3.5-flash-lite", Type: "model", DisplayName: "Gemini 3.5 Flash Lite", CreatedAt: ""},
|
||||
{ID: "gemini-3.6-flash", Type: "model", DisplayName: "Gemini 3.6 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-3.7-flash", Type: "model", DisplayName: "Gemini 3.7 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-3.8-flash", Type: "model", DisplayName: "Gemini 3.8 Flash", CreatedAt: ""},
|
||||
{ID: "gemini-4-argon", Type: "model", DisplayName: "Gemini 4 Argon", CreatedAt: ""},
|
||||
}
|
||||
|
||||
@@ -43,4 +50,4 @@ func GoogleOneModelMapping() map[string]string {
|
||||
}
|
||||
|
||||
// DefaultTestModel is the default model to preselect in test flows.
|
||||
const DefaultTestModel = "gemini-2.0-flash"
|
||||
const DefaultTestModel = "gemini-3.5-flash"
|
||||
@@ -11,8 +11,9 @@ func TestDefaultModels_ContainsImageModels(t *testing.T) {
|
||||
}
|
||||
|
||||
required := []string{
|
||||
"gemini-2.5-flash-image",
|
||||
"gemini-3.1-flash-image",
|
||||
"gemini-3-pro-image",
|
||||
DefaultTestModel,
|
||||
}
|
||||
|
||||
for _, id := range required {
|
||||
|
||||
@@ -25,6 +25,7 @@ var DefaultModels = []Model{
|
||||
{ID: "gpt-5.6", Object: "model", Created: 1780876800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.6 (Sol)"},
|
||||
{ID: "gpt-5.6-terra", Object: "model", Created: 1780876800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.6 Terra"},
|
||||
{ID: "gpt-5.6-luna", Object: "model", Created: 1780876800, OwnedBy: "openai", Type: "model", DisplayName: "GPT-5.6 Luna"},
|
||||
{ID: "gpt-6.1-terra", Object: "model", Created: 1704067200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6.1 Terra"},
|
||||
{ID: "gpt-6.1-sol", Object: "model", Created: 1790640000, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6.1 Sol"},
|
||||
{ID: "gpt-6-sol", Object: "model", Created: 1790035200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6 Sol"},
|
||||
{ID: "gpt-6-luna", Object: "model", Created: 1790035200, OwnedBy: "openai", Type: "model", DisplayName: "GPT-6 Luna"},
|
||||
@@ -216,6 +217,27 @@ func IsGPT61SolModelSpelling(model string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
func IsGPT61TerraModelSpelling(model string) bool {
|
||||
canonical := CanonicalizeOpenAIModelAliasSpelling(model)
|
||||
if canonical == "gpt-6.1-terra" {
|
||||
return true
|
||||
}
|
||||
suffix, ok := strings.CutPrefix(canonical, "gpt-6.1-terra-")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
switch suffix {
|
||||
case "none", "low", "medium", "high", "xhigh", "max", "openai-compact":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func RequiresResponsesForToolCalls(model string) bool {
|
||||
return IsGPT61SolModelSpelling(model) || IsGPT61TerraModelSpelling(model)
|
||||
}
|
||||
|
||||
// ValidateGPT61SolReasoningEffort rejects disabled reasoning instead of silently
|
||||
// increasing the client's requested effort on compatibility paths.
|
||||
func ValidateGPT61SolReasoningEffort(model, effort string) error {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
// Package pagination provides types and helpers for paginated responses.
|
||||
package pagination
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"math"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
SortOrderAsc = "asc"
|
||||
@@ -38,7 +41,12 @@ func (p PaginationParams) Offset() int {
|
||||
if p.Page < 1 {
|
||||
p.Page = 1
|
||||
}
|
||||
return (p.Page - 1) * p.Limit()
|
||||
limit := p.Limit()
|
||||
// Saturate the page so both the offset and offset+limit stay within int.
|
||||
if p.Page > math.MaxInt/limit {
|
||||
p.Page = math.MaxInt / limit
|
||||
}
|
||||
return (p.Page - 1) * limit
|
||||
}
|
||||
|
||||
// Limit 获取限制数
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package pagination
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeSortOrder(t *testing.T) {
|
||||
t.Parallel()
|
||||
@@ -84,6 +87,11 @@ func TestPaginationParamsOffsetUsesNormalizedLimit(t *testing.T) {
|
||||
{name: "negative page size uses default", page: 2, pageSize: -1, want: 20},
|
||||
{name: "normal values", page: 3, pageSize: 50, want: 100},
|
||||
{name: "page size beyond max is clamped", page: 2, pageSize: 1500, want: 1000},
|
||||
{name: "max int page saturates", page: math.MaxInt, pageSize: 20, want: (math.MaxInt/20 - 1) * 20},
|
||||
{name: "max int page with odd page size saturates", page: math.MaxInt, pageSize: 21, want: (math.MaxInt/21 - 1) * 21},
|
||||
{name: "max int page with max page size saturates", page: math.MaxInt, pageSize: 1000, want: (math.MaxInt/1000 - 1) * 1000},
|
||||
{name: "page at saturation bound keeps", page: math.MaxInt / 20, pageSize: 20, want: (math.MaxInt/20 - 1) * 20},
|
||||
{name: "page just past saturation bound saturates", page: math.MaxInt/20 + 1, pageSize: 20, want: (math.MaxInt/20 - 1) * 20},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -96,3 +104,22 @@ func TestPaginationParamsOffsetUsesNormalizedLimit(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaginationParamsOffsetDoesNotOverflow(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
pages := []int{math.MinInt, -1, 0, 1, math.MaxInt, math.MaxInt - 1, math.MaxInt / 2, math.MaxInt/20 + 1, math.MaxInt/1000 + 1}
|
||||
pageSizes := []int{math.MinInt, -1, 0, 1, 2, 3, 20, 21, 999, 1000, 1001, math.MaxInt}
|
||||
for _, page := range pages {
|
||||
for _, pageSize := range pageSizes {
|
||||
params := PaginationParams{Page: page, PageSize: pageSize}
|
||||
offset, limit := params.Offset(), params.Limit()
|
||||
if offset < 0 || offset > math.MaxInt-limit {
|
||||
t.Fatalf("Offset() for Page=%d, PageSize=%d = %d, want 0 <= offset <= MaxInt-%d", page, pageSize, offset, limit)
|
||||
}
|
||||
if again := params.Offset(); again != offset {
|
||||
t.Fatalf("Offset() for Page=%d, PageSize=%d is unstable: %d then %d", page, pageSize, offset, again)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/util/logredact"
|
||||
@@ -166,7 +167,8 @@ func PaginatedWithResult(c *gin.Context, items any, pagination *PaginationResult
|
||||
})
|
||||
}
|
||||
|
||||
// ParsePagination 解析分页参数
|
||||
// ParsePagination 解析分页参数。无效或超出 int 范围的值使用默认值;
|
||||
// 有效页码按 pageSize 限制上限,返回可安全计算 offset 和 offset+pageSize 的页码。
|
||||
func ParsePagination(c *gin.Context) (page, pageSize int) {
|
||||
page = 1
|
||||
pageSize = 20
|
||||
@@ -188,16 +190,16 @@ func ParsePagination(c *gin.Context) (page, pageSize int) {
|
||||
}
|
||||
}
|
||||
|
||||
// Clamp the page so both offset and offset+pageSize stay within int.
|
||||
if page > math.MaxInt/pageSize {
|
||||
page = math.MaxInt / pageSize
|
||||
}
|
||||
|
||||
return page, pageSize
|
||||
}
|
||||
|
||||
func parseInt(s string) (int, error) {
|
||||
var result int
|
||||
for _, c := range s {
|
||||
if c < '0' || c > '9' {
|
||||
return 0, nil
|
||||
}
|
||||
result = result*10 + int(c-'0')
|
||||
}
|
||||
return result, nil
|
||||
// Parse unsigned decimal digits within the positive range of the native int.
|
||||
value, err := strconv.ParseUint(s, 10, strconv.IntSize-1)
|
||||
return int(value), err
|
||||
}
|
||||
@@ -5,8 +5,11 @@ package response
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
errors2 "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
@@ -691,6 +694,60 @@ func TestParsePagination(t *testing.T) {
|
||||
wantPage: 1,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "page为MaxInt_钳制到不溢出的上限",
|
||||
query: "page=" + strconv.Itoa(math.MaxInt),
|
||||
wantPage: math.MaxInt / 20,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "page为MaxInt且page_size为1000_钳制到不溢出的上限",
|
||||
query: "page=" + strconv.Itoa(math.MaxInt) + "&page_size=1000",
|
||||
wantPage: math.MaxInt / 1000,
|
||||
wantPageSize: 1000,
|
||||
},
|
||||
{
|
||||
name: "page恰好在上限_有效",
|
||||
query: "page=" + strconv.Itoa(math.MaxInt/20),
|
||||
wantPage: math.MaxInt / 20,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "page刚超过上限_钳制",
|
||||
query: "page=" + strconv.Itoa(math.MaxInt/20+1),
|
||||
wantPage: math.MaxInt / 20,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "page超过MaxInt_使用默认值",
|
||||
query: "page=" + strconv.FormatUint(uint64(math.MaxInt)+1, 10),
|
||||
wantPage: 1,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "page超过uint64范围_不能回绕为2",
|
||||
query: "page=18446744073709551618",
|
||||
wantPage: 1,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "page_size超过uint64范围_不能回绕为21",
|
||||
query: "page_size=18446744073709551637&limit=50",
|
||||
wantPage: 1,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "limit超过uint64范围_不能回绕为21",
|
||||
query: "limit=18446744073709551637",
|
||||
wantPage: 1,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
{
|
||||
name: "超长数字_使用默认值",
|
||||
query: "page=" + strings.Repeat("9", 100),
|
||||
wantPage: 1,
|
||||
wantPageSize: 20,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -705,6 +762,38 @@ func TestParsePagination(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePaginationBoundariesAndResponse(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, sizeParam := range []string{"page_size", "limit"} {
|
||||
for _, size := range []int{1, 2, 3, 20, 21, 999, 1000} {
|
||||
bound := math.MaxInt / size
|
||||
pages := []int{bound - 1, bound, math.MaxInt}
|
||||
if bound < math.MaxInt {
|
||||
pages = append(pages, bound+1)
|
||||
}
|
||||
for _, requestedPage := range pages {
|
||||
query := "page=" + strconv.Itoa(requestedPage) + "&" + sizeParam + "=" + strconv.Itoa(size)
|
||||
t.Run(query, func(t *testing.T) {
|
||||
w, c := newContextWithQuery(query)
|
||||
page, pageSize := ParsePagination(c)
|
||||
require.Equal(t, min(requestedPage, bound), page)
|
||||
require.Equal(t, size, pageSize)
|
||||
offset := (page - 1) * pageSize
|
||||
require.GreaterOrEqual(t, offset, 0)
|
||||
require.LessOrEqual(t, offset, math.MaxInt-pageSize)
|
||||
|
||||
Paginated(c, []string{}, 0, page, pageSize)
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
_, data := parsePaginatedBody(t, w)
|
||||
require.Equal(t, page, data.Page)
|
||||
require.Equal(t, pageSize, data.PageSize)
|
||||
require.Empty(t, data.Items)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Test_parseInt(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -740,37 +829,58 @@ func Test_parseInt(t *testing.T) {
|
||||
name: "包含字母_返回0",
|
||||
input: "abc",
|
||||
wantVal: 0,
|
||||
wantErr: false,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "数字开头接字母_返回0",
|
||||
input: "12a",
|
||||
wantVal: 0,
|
||||
wantErr: false,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "包含负号_返回0",
|
||||
input: "-1",
|
||||
wantVal: 0,
|
||||
wantErr: false,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "包含小数点_返回0",
|
||||
input: "1.5",
|
||||
wantVal: 0,
|
||||
wantErr: false,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "包含空格_返回0",
|
||||
input: "1 2",
|
||||
wantVal: 0,
|
||||
wantErr: false,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "空字符串",
|
||||
input: "",
|
||||
wantVal: 0,
|
||||
wantErr: false,
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "前导零_有效",
|
||||
input: "000123",
|
||||
wantVal: 123,
|
||||
},
|
||||
{
|
||||
name: "正号_无效",
|
||||
input: "+1",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "MaxInt_有效",
|
||||
input: strconv.Itoa(math.MaxInt),
|
||||
wantVal: math.MaxInt,
|
||||
},
|
||||
{
|
||||
name: "超过MaxInt_返回范围错误",
|
||||
input: strconv.FormatUint(uint64(math.MaxInt)+1, 10),
|
||||
wantVal: math.MaxInt,
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
dbgroup "github.com/Wei-Shaw/sub2api/ent/group"
|
||||
dbpredicate "github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
dbproxy "github.com/Wei-Shaw/sub2api/ent/proxy"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -125,6 +126,9 @@ func newAccountRepositoryWithSQL(client *dbent.Client, sqlq sqlExecutor, schedul
|
||||
}
|
||||
|
||||
func (r *accountRepository) Create(ctx context.Context, account *service.Account) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.Create(ctx, account)
|
||||
}
|
||||
if err := createAccountRecord(ctx, r.client, account); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -263,6 +267,9 @@ func (r *accountRepository) CreateWithAccountGroups(ctx context.Context, account
|
||||
}
|
||||
|
||||
func (r *accountRepository) GetByID(ctx context.Context, id int64) (*service.Account, error) {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.GetByID(ctx, id)
|
||||
}
|
||||
m, err := r.client.Account.Query().Where(dbaccount.IDEQ(id)).Only(ctx)
|
||||
if err != nil {
|
||||
return nil, translatePersistenceError(err, service.ErrAccountNotFound, nil)
|
||||
@@ -439,6 +446,9 @@ func (r *accountRepository) ListCRSAccountIDs(ctx context.Context) (map[string]i
|
||||
}
|
||||
|
||||
func (r *accountRepository) Update(ctx context.Context, account *service.Account) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.Update(ctx, account)
|
||||
}
|
||||
return r.updateAccount(ctx, account, nil, nil, account.RateMultiplier)
|
||||
}
|
||||
|
||||
@@ -670,7 +680,9 @@ func lockAndMergeAccountProbeExtra(
|
||||
false
|
||||
),
|
||||
extra -> 'opencode_go_usage_auto_refresh',
|
||||
extra -> 'opencode_go_usage_snapshot'
|
||||
extra -> 'opencode_go_usage_snapshot',
|
||||
extra -> 'grok_observed_models',
|
||||
extra -> 'upstream_model_metadata'
|
||||
FROM accounts
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
FOR NO KEY UPDATE
|
||||
@@ -699,6 +711,8 @@ func lockAndMergeAccountProbeExtra(
|
||||
currentOllamaSnapshot []byte
|
||||
currentOpenCodeAutoRefresh []byte
|
||||
currentOpenCodeSnapshot []byte
|
||||
currentGrokObservedModels []byte
|
||||
currentUpstreamModelMetadata []byte
|
||||
)
|
||||
if err := rows.Scan(
|
||||
&identityUnchanged,
|
||||
@@ -713,6 +727,8 @@ func lockAndMergeAccountProbeExtra(
|
||||
&opencodeGroupIdentityUnchanged,
|
||||
¤tOpenCodeAutoRefresh,
|
||||
¤tOpenCodeSnapshot,
|
||||
¤tGrokObservedModels,
|
||||
¤tUpstreamModelMetadata,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -826,6 +842,21 @@ func lockAndMergeAccountProbeExtra(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Grok 目录和能力 metadata 是同步写入的受管状态。普通更新在行锁内采用最新
|
||||
// 数据库值,忽略表单旧值、缺键和注入。来源身份变化不删除已有成功快照。
|
||||
for key, raw := range map[string][]byte{
|
||||
"grok_observed_models": currentGrokObservedModels,
|
||||
service.UpstreamModelMetadataExtraKey: currentUpstreamModelMetadata,
|
||||
} {
|
||||
delete(extra, key)
|
||||
value, ok, err := decodeAccountExtraJSON(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ok {
|
||||
extra[key] = value
|
||||
}
|
||||
}
|
||||
return extra, nil
|
||||
}
|
||||
|
||||
@@ -958,6 +989,9 @@ func (r *accountRepository) UpdateCredentials(ctx context.Context, id int64, cre
|
||||
}
|
||||
|
||||
func (r *accountRepository) Delete(ctx context.Context, id int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.Delete(ctx, id)
|
||||
}
|
||||
groupIDs, err := r.loadAccountGroupIDs(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -1846,6 +1880,9 @@ func (r *accountRepository) syncSchedulerAccountSnapshots(ctx context.Context, a
|
||||
}
|
||||
|
||||
func (r *accountRepository) ClearError(ctx context.Context, id int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearError(ctx, id)
|
||||
}
|
||||
_, err := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
SetStatus(service.StatusActive).
|
||||
@@ -1929,6 +1966,12 @@ func (r *accountRepository) GetGroups(ctx context.Context, accountID int64) ([]s
|
||||
}
|
||||
|
||||
func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, groupIDs []int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.BindGroups(ctx, accountID, groupIDs)
|
||||
}
|
||||
if adminaccess.FromContext(ctx) != nil {
|
||||
return r.scopedAdminBindGroups(ctx, accountID, groupIDs)
|
||||
}
|
||||
existingGroupIDs, err := r.loadAccountGroupIDs(ctx, accountID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -2551,6 +2594,9 @@ func (r *accountRepository) SetGrokCredentialTempUnschedulableIfMatch(
|
||||
}
|
||||
|
||||
func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearTempUnschedulable(ctx, id)
|
||||
}
|
||||
_, err := r.sql.ExecContext(ctx, `
|
||||
UPDATE accounts
|
||||
SET temp_unschedulable_until = NULL,
|
||||
@@ -2570,6 +2616,9 @@ func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64
|
||||
}
|
||||
|
||||
func (r *accountRepository) ClearRateLimit(ctx context.Context, id int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearRateLimit(ctx, id)
|
||||
}
|
||||
_, err := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
ClearRateLimitedAt().
|
||||
@@ -2587,6 +2636,9 @@ func (r *accountRepository) ClearRateLimit(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
func (r *accountRepository) ClearAntigravityQuotaScopes(ctx context.Context, id int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearAntigravityQuotaScopes(ctx, id)
|
||||
}
|
||||
client := clientFromContext(ctx, r.client)
|
||||
result, err := client.ExecContext(
|
||||
ctx,
|
||||
@@ -2611,6 +2663,9 @@ func (r *accountRepository) ClearAntigravityQuotaScopes(ctx context.Context, id
|
||||
}
|
||||
|
||||
func (r *accountRepository) ClearModelRateLimits(ctx context.Context, id int64) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ClearModelRateLimits(ctx, id)
|
||||
}
|
||||
client := clientFromContext(ctx, r.client)
|
||||
result, err := client.ExecContext(
|
||||
ctx,
|
||||
@@ -2673,6 +2728,9 @@ func (r *accountRepository) UpdateSessionWindowEnd(ctx context.Context, id int64
|
||||
}
|
||||
|
||||
func (r *accountRepository) SetSchedulable(ctx context.Context, id int64, schedulable bool) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.SetSchedulable(ctx, id, schedulable)
|
||||
}
|
||||
_, err := r.client.Account.Update().
|
||||
Where(dbaccount.IDEQ(id)).
|
||||
SetSchedulable(schedulable).
|
||||
@@ -2731,6 +2789,9 @@ func (r *accountRepository) AutoPauseExpiredAccounts(ctx context.Context, now ti
|
||||
}
|
||||
|
||||
func (r *accountRepository) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.UpdateExtra(ctx, id, updates)
|
||||
}
|
||||
updates = stripCodexFingerprintSeedFromExtraUpdate(updates)
|
||||
if len(updates) == 0 {
|
||||
return nil
|
||||
@@ -4072,6 +4133,9 @@ func (r *accountRepository) RevertProxyFallback(ctx context.Context, accountID i
|
||||
// ⚠️ 新增影子维度时:须更新此函数(或新增维度专用列举),并检查所有调用点(级联删除/一母一影校验/type 守卫),否则会静默漏掉新维度。
|
||||
// 软删除行由 SoftDeleteMixin 拦截器自动排除,无需手写 deleted_at IS NULL。
|
||||
func (r *accountRepository) ListShadowsByParent(ctx context.Context, parentID int64) ([]*service.Account, error) {
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.ListShadowsByParent(ctx, parentID)
|
||||
}
|
||||
rows, err := r.client.Account.Query().
|
||||
Where(dbaccount.ParentAccountIDEQ(parentID), dbaccount.QuotaDimensionEQ(dbaccount.QuotaDimensionSpark)).
|
||||
All(ctx)
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
//go:build integration
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestGrokManagedExtraSurvivesOrdinaryUpdate(t *testing.T) {
|
||||
freshModels := map[string]any{
|
||||
"models": []any{"fresh-model"},
|
||||
"fetched_at": "2026-10-25T12:00:00Z",
|
||||
}
|
||||
freshMetadata := map[string]any{
|
||||
"models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}},
|
||||
}
|
||||
failedModels := map[string]any{
|
||||
"models": []any{"fresh-model"},
|
||||
"fetched_at": "2026-10-25T12:00:00Z",
|
||||
"last_attempt": map[string]any{
|
||||
"status": "failed",
|
||||
"error_code": "transport",
|
||||
"started_at": "2026-10-25T13:00:00Z",
|
||||
"finished_at": "2026-10-25T13:00:01Z",
|
||||
},
|
||||
}
|
||||
oldModels := map[string]any{
|
||||
"models": []any{"old-model"},
|
||||
"fetched_at": "2026-10-24T12:00:00Z",
|
||||
}
|
||||
oldMetadata := map[string]any{
|
||||
"models": map[string]any{"old-model": map[string]any{"id": "old-model"}},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
accountType string
|
||||
credentials map[string]any
|
||||
storedExtra map[string]any
|
||||
updateExtra map[string]any
|
||||
updateCreds map[string]any
|
||||
wantModels map[string]any
|
||||
wantMetadata map[string]any
|
||||
wantBaseURL string
|
||||
}{
|
||||
{
|
||||
name: "oauth old form",
|
||||
accountType: service.AccountTypeOAuth,
|
||||
credentials: map[string]any{"access_token": "token-keep"},
|
||||
storedExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"grok_observed_models": freshModels,
|
||||
service.UpstreamModelMetadataExtraKey: freshMetadata,
|
||||
},
|
||||
updateExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"note": "from-form",
|
||||
"grok_observed_models": oldModels,
|
||||
service.UpstreamModelMetadataExtraKey: oldMetadata,
|
||||
},
|
||||
wantModels: freshModels,
|
||||
wantMetadata: freshMetadata,
|
||||
},
|
||||
{
|
||||
name: "apikey missing keys",
|
||||
accountType: service.AccountTypeAPIKey,
|
||||
credentials: map[string]any{"api_key": "sk-keep", "base_url": "https://api.example.test/v1"},
|
||||
storedExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"grok_observed_models": freshModels,
|
||||
service.UpstreamModelMetadataExtraKey: freshMetadata,
|
||||
},
|
||||
updateExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"note": "from-form",
|
||||
},
|
||||
wantModels: freshModels,
|
||||
wantMetadata: freshMetadata,
|
||||
},
|
||||
{
|
||||
name: "injection when absent",
|
||||
accountType: service.AccountTypeOAuth,
|
||||
credentials: map[string]any{"access_token": "token-keep"},
|
||||
storedExtra: map[string]any{"unrelated": "keep"},
|
||||
updateExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"note": "from-form",
|
||||
"grok_observed_models": oldModels,
|
||||
service.UpstreamModelMetadataExtraKey: oldMetadata,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "failed attempt",
|
||||
accountType: service.AccountTypeAPIKey,
|
||||
credentials: map[string]any{"api_key": "sk-keep"},
|
||||
storedExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"grok_observed_models": failedModels,
|
||||
service.UpstreamModelMetadataExtraKey: freshMetadata,
|
||||
},
|
||||
updateExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"note": "from-form",
|
||||
"grok_observed_models": oldModels,
|
||||
service.UpstreamModelMetadataExtraKey: oldMetadata,
|
||||
},
|
||||
wantModels: failedModels,
|
||||
wantMetadata: freshMetadata,
|
||||
},
|
||||
{
|
||||
name: "source identity change keeps success",
|
||||
accountType: service.AccountTypeOAuth,
|
||||
credentials: map[string]any{
|
||||
"access_token": "token-keep",
|
||||
"base_url": "https://old.example.test/v1",
|
||||
},
|
||||
storedExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"grok_observed_models": freshModels,
|
||||
service.UpstreamModelMetadataExtraKey: freshMetadata,
|
||||
},
|
||||
updateExtra: map[string]any{
|
||||
"unrelated": "keep",
|
||||
"note": "from-form",
|
||||
"grok_observed_models": nil,
|
||||
},
|
||||
updateCreds: map[string]any{
|
||||
"access_token": "token-keep",
|
||||
"base_url": "https://new.example.test/v1",
|
||||
},
|
||||
wantModels: freshModels,
|
||||
wantMetadata: freshMetadata,
|
||||
wantBaseURL: "https://new.example.test/v1",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
tx := testEntTx(t)
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
|
||||
account := mustCreateAccount(t, tx.Client(), &service.Account{
|
||||
Name: "grok-managed-" + tt.name,
|
||||
Platform: service.PlatformGrok,
|
||||
Type: tt.accountType,
|
||||
Credentials: tt.credentials,
|
||||
Extra: tt.storedExtra,
|
||||
})
|
||||
account.Name = "renamed"
|
||||
account.Extra = tt.updateExtra
|
||||
if tt.updateCreds != nil {
|
||||
account.Credentials = tt.updateCreds
|
||||
}
|
||||
|
||||
require.NoError(t, repo.Update(context.Background(), account))
|
||||
|
||||
got := readGrokManagedExtra(t, tx, account.ID)
|
||||
require.Equal(t, "renamed", got.name)
|
||||
require.Equal(t, "from-form", got.note)
|
||||
require.Equal(t, "keep", got.unrelated)
|
||||
require.Equal(t, tt.wantModels, got.models)
|
||||
require.Equal(t, tt.wantMetadata, got.metadata)
|
||||
if tt.wantBaseURL != "" {
|
||||
require.Equal(t, tt.wantBaseURL, got.baseURL)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGrokManagedExtraUpdateOverlapsCatalogCAS(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
account := mustCreateGrokCatalogAccount(t, testEntClient(t), "grok-managed-overlap")
|
||||
t.Cleanup(func() {
|
||||
cleanupCtx := context.Background()
|
||||
_, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM scheduler_outbox WHERE account_id = $1", account.ID)
|
||||
_, _ = integrationDB.ExecContext(cleanupCtx, "DELETE FROM accounts WHERE id = $1", account.ID)
|
||||
})
|
||||
|
||||
freshModels := `{"models":["fresh-model"],"fetched_at":"2026-10-25T12:00:00Z","last_attempt":{"status":"failed","error_code":"transport","started_at":"2026-10-25T13:00:00Z","finished_at":"2026-10-25T13:00:01Z"}}`
|
||||
freshMetadata := `{"models":{"fresh-model":{"id":"fresh-model"}}}`
|
||||
|
||||
tx, err := integrationEntClient.Tx(ctx)
|
||||
require.NoError(t, err)
|
||||
t.Cleanup(func() { _ = tx.Rollback() })
|
||||
|
||||
locked := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
holderDone := make(chan struct{})
|
||||
var holderErr error
|
||||
go func() {
|
||||
defer close(holderDone)
|
||||
rows, queryErr := tx.QueryContext(ctx, `SELECT id FROM accounts WHERE id = $1 FOR NO KEY UPDATE`, account.ID)
|
||||
if queryErr != nil {
|
||||
holderErr = queryErr
|
||||
return
|
||||
}
|
||||
if !rows.Next() {
|
||||
holderErr = rows.Err()
|
||||
if holderErr == nil {
|
||||
holderErr = errors.New("catalog account row was not locked")
|
||||
}
|
||||
_ = rows.Close()
|
||||
return
|
||||
}
|
||||
var id int64
|
||||
if scanErr := rows.Scan(&id); scanErr != nil {
|
||||
holderErr = scanErr
|
||||
_ = rows.Close()
|
||||
return
|
||||
}
|
||||
if closeErr := rows.Close(); closeErr != nil {
|
||||
holderErr = closeErr
|
||||
return
|
||||
}
|
||||
close(locked)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
holderErr = ctx.Err()
|
||||
return
|
||||
}
|
||||
_, execErr := tx.ExecContext(ctx, `
|
||||
UPDATE accounts
|
||||
SET extra = jsonb_set(
|
||||
jsonb_set(COALESCE(extra, '{}'::jsonb), '{grok_observed_models}', $2::jsonb, true),
|
||||
'{upstream_model_metadata}', $3::jsonb, true)
|
||||
WHERE id = $1`, account.ID, freshModels, freshMetadata)
|
||||
if execErr != nil {
|
||||
holderErr = execErr
|
||||
return
|
||||
}
|
||||
holderErr = tx.Commit()
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-locked:
|
||||
case <-holderDone:
|
||||
t.Fatalf("catalog lock holder finished early: %v", holderErr)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("timed out waiting for the catalog row lock")
|
||||
}
|
||||
|
||||
updateDone := make(chan error, 1)
|
||||
go func() {
|
||||
repo := newAccountRepositoryWithSQL(integrationEntClient, integrationDB, nil)
|
||||
account.Name = "saved-during-cas"
|
||||
account.Extra = map[string]any{
|
||||
"unrelated": "keep",
|
||||
"note": "from-form",
|
||||
"grok_observed_models": map[string]any{
|
||||
"models": []any{"old-model"}, "fetched_at": "2026-10-24T12:00:00Z",
|
||||
},
|
||||
service.UpstreamModelMetadataExtraKey: map[string]any{
|
||||
"models": map[string]any{"old-model": map[string]any{"id": "old-model"}},
|
||||
},
|
||||
}
|
||||
updateDone <- repo.Update(ctx, account)
|
||||
}()
|
||||
close(release)
|
||||
|
||||
select {
|
||||
case err = <-updateDone:
|
||||
require.NoError(t, err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("timed out waiting for the overlapping account update")
|
||||
}
|
||||
<-holderDone
|
||||
require.NoError(t, holderErr)
|
||||
|
||||
got := readGrokManagedExtra(t, integrationDB, account.ID)
|
||||
require.Equal(t, "saved-during-cas", got.name)
|
||||
require.Equal(t, "from-form", got.note)
|
||||
require.Equal(t, "keep", got.unrelated)
|
||||
require.Equal(t, []any{"fresh-model"}, got.models["models"])
|
||||
require.Equal(t, "2026-10-25T12:00:00Z", got.models["fetched_at"])
|
||||
attempt, ok := got.models["last_attempt"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "failed", attempt["status"])
|
||||
require.Equal(t, "transport", attempt["error_code"])
|
||||
require.Equal(t, map[string]any{
|
||||
"models": map[string]any{"fresh-model": map[string]any{"id": "fresh-model"}},
|
||||
}, got.metadata)
|
||||
}
|
||||
|
||||
type grokManagedExtraRow struct {
|
||||
name string
|
||||
note string
|
||||
unrelated string
|
||||
baseURL string
|
||||
models map[string]any
|
||||
metadata map[string]any
|
||||
}
|
||||
|
||||
func readGrokManagedExtra(t *testing.T, q grokCatalogSQL, id int64) grokManagedExtraRow {
|
||||
t.Helper()
|
||||
rows, err := q.QueryContext(context.Background(), `
|
||||
SELECT name,
|
||||
COALESCE(extra->>'note', ''),
|
||||
COALESCE(extra->>'unrelated', ''),
|
||||
COALESCE(credentials->>'base_url', ''),
|
||||
COALESCE((extra->'grok_observed_models')::text, 'null'),
|
||||
COALESCE((extra->'upstream_model_metadata')::text, 'null')
|
||||
FROM accounts
|
||||
WHERE id = $1`, id)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = rows.Close() }()
|
||||
require.True(t, rows.Next())
|
||||
var row grokManagedExtraRow
|
||||
var modelsRaw, metadataRaw string
|
||||
require.NoError(t, rows.Scan(&row.name, &row.note, &row.unrelated, &row.baseURL, &modelsRaw, &metadataRaw))
|
||||
require.NoError(t, rows.Err())
|
||||
if modelsRaw != "null" {
|
||||
require.NoError(t, json.Unmarshal([]byte(modelsRaw), &row.models))
|
||||
}
|
||||
if metadataRaw != "null" {
|
||||
require.NoError(t, json.Unmarshal([]byte(metadataRaw), &row.metadata))
|
||||
}
|
||||
return row
|
||||
}
|
||||
Loaded 100 of 335 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user