From f34ba3d19859fabd4d064ce1e9225284c1d50c8a Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 14 Sep 2026 14:21:48 +0800 Subject: [PATCH] =?UTF-8?q?fix(llm):=20auth=20=E8=A7=84=E8=8C=83=E5=8C=96?= =?UTF-8?q?=E5=85=9C=E4=BD=8F=E3=80=8C=E5=8F=AA=E5=A1=AB=E8=A3=B8=20key?= =?UTF-8?q?=E3=80=8D+=20=E6=8E=92=E9=9A=9C=E5=AD=90=E5=91=BD=E4=BB=A4=20(1?= =?UTF-8?q?.0.15)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 线上 minimax 2 把 Key 点「测试」红字:1004 Please carry the API secret key —— 根因是表单 placeholder 写 sk-...,用户照着填了**裸 key**(无 Bearer ), 而 accounts[].auth 语义是「完整 Authorization 头值」,转发时原样发就 1004。 agent.sh upstreams 一打就看出对照组:deepseek=Bearer s...d425(正常), minimax=sk-cp-...(**无 Bearer **)——光看截图红字只会猜「额度用完」。 plugin-llm - upstreams::normalize_auth:trim 后含空白→已完整;否则补「Bearer 」。 **双处应用**:upsert 写入(下次保存自愈) + read_upa 读出(让线上坏数据 立即可用,无需用户重填——存量 10 把 Key 根本不可能通知用户重填)。 - 兼容 Basic / 自定义 scheme / 前后空格 / 内部含空格共 6 个边界, 干跑 + e2e 2 条新断言全过(裸 key 200 + 靶机实收 Bearer sk-NORM-NO-SCHEME)。 前端 - placeholder 改为「Bearer sk-…(... 留空=保留原值;只填裸 key 也会自动补 Bearer)」 ——placeholder 写「前缀」会诱导漏填必要部分,写「字面值」才能正确引导。 - 多账号小节加说明文字(只填裸 key 也会自动补 Bearer)。 deploy/agent.sh - 新增 upstreams(逐账号掩码/冷却/今日负载;掩码为空显式标 **空** —— 这条 是发现「只填裸 key」类问题的关键指示器,旧镜像的回显脱敏后看不出问题) - 新增 upstream-test (调测试接口并打印厂商真实 status_code + body), 避免再靠「管理台截图 OCR」排障。 回归 281 全绿(网关 102 + LLM 179);专章 docs/llm/MULTI_ACCOUNT_ROUTING.md §10 记录现象/规则/兼容表/自检工具。 --- CLAUDE.md | 3 +- deploy/agent.sh | 73 +++++++++++++++++++++++++ docs/llm/MULTI_ACCOUNT_ROUTING.md | 59 +++++++++++++++++++- readme.md | 32 ++++++++++- rust/crates/plugin-llm/src/upstreams.rs | 30 +++++++++- tests/llm/e2e.sh | 7 +++ tests/llm/fixtures/llm-upstreams.json | 10 ++++ www/assets/upstreams.js | 3 +- 8 files changed, 209 insertions(+), 8 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4798d19..7f05354 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -192,7 +192,7 @@ POST /openai/v1/chat/completions Authorization: Bearer sk_<本网关签 | 位置 | 职责 | | --- | --- | | `crates/plugin-llm/src/llm.rs` | 热路径:slot 解析、Bearer 提取、身份查询、OpenAI 兼容错误体、三个变量的 get_handler | -| `crates/plugin-llm/src/upstreams.rs` | 上游校验/读写/写穿共享内存,是域名插件在 LLM 侧的翻版;`models` 登记 + `available()` / `models_flat()` 模型发现;**多账号路由**(`pick_account` 粘性 + FNV-1a 冷分散 + 天锚定冷却 `cool_until_until`)与**账号级负载**(`uda:`/`uex:` 日桶,`view()` 投影) | +| `crates/plugin-llm/src/upstreams.rs` | 上游校验/读写/写穿共享内存,是域名插件在 LLM 侧的翻版;`models` 登记 + `available()` / `models_flat()` 模型发现;**多账号路由**(`pick_account` 粘性 + FNV-1a 冷分散 + 天锚定冷却 `cool_until_until`)、**账号级负载**(`uda:`/`uex:` 日桶,`view()` 投影)、**`normalize_auth`**(裸 key 自动补 `Bearer `,写入 `upsert` + 读出 `read_upa` 双处应用) | | `crates/plugin-llm/src/stats.rs` | 用量账本(`ust:` 每账号 / `ums:` 每账号×上游,请求级、只读 shm)与 `overview()` 投影;**唯一写点在 `LlmHandler` 鉴权全通过之后** | | `data/llm-upstreams.json` | 上游表(**含真实密钥**);`base` 可带路径,`auth` 是完整的 Authorization 值,`models` 仅供模型发现 | | `conf/nginx.conf` | `lm.mayishangshu.cn:18098` server;SSE 三件套 + `proxy_ssl_server_name` | @@ -267,6 +267,7 @@ location 与 80 端口 LLM server 是两份拷贝,改一处记得同步另一 | 同一下游 Key 每次换上游账号 | 粘性绑定 `ukb:` 没写(下行 Key 缺失时本就不写);或该 Key 哈希落点恰好在冷却账号上 | | 流式退化成一次性返回 | `proxy_buffering off` 丢了 | | 上游报 Host / 证书错 | `proxy_set_header Host $llm_host` 或 `proxy_ssl_server_name on` 丢了 | +| 上游回 1004 / "Please carry the API secret key" | 账号 `auth` 存成**裸 key**(无 `Bearer `)。`plugin-llm` 1.0.15+ 的 `normalize_auth` 会兜底(`upsert` 写入 + `read_upa` 读出双处应用),但**首选排查**是 `bash deploy/agent.sh upstreams` 看掩码:旧镜像只回脱敏后的掩码看不出问题,新镜像掩码为空会显式标 `**空**` | | query 参数丢失 | 变量形式的 `proxy_pass` 不会自动追加 args,靠 `llm::upstream_uri` 拼好 | **本机验证夹具**:`tests/llm/`,由 `bash tests/run.sh llm` 一并起假上游(18999)、LLM 网关(18090) diff --git a/deploy/agent.sh b/deploy/agent.sh index aabd315..013307e 100755 --- a/deploy/agent.sh +++ b/deploy/agent.sh @@ -206,6 +206,74 @@ print("old")' 2>/dev/null || echo '')" return $rc } +# 上游诊断(排障多账号路由 / 额度切换):登录管理台拉完整投影, +# 逐账号打印 **Authorization 掩码** / 冷却 / 重置周期 / 今日负载。 +# 掩码为空会显式标 `**空**`——「配了 Key 却 401」最常见的原因就是它。 +# ⚠️ 只回掩码(模块的 view() 本来也不回真值),真 Key 永不出容器。 +cmd_upstreams() { + local jar json + jar="$(mktemp -t ipass-up.XXXXXX)" + if ! live_login "$jar"; then + echo "✗ 登录失败(HTTP 非 200)"; rm -f "$jar"; return 1 + fi + json="$(live_curl -b "$jar" "https://$LIVE_HOST:$LIVE_PORT/api/admin/upstreams")" + rm -f "$jar" + if [ -z "$PY" ]; then printf '%s\n' "$json"; return 0; fi + printf '%s' "$json" | "$PY" -c ' +import json, sys +d = json.load(sys.stdin).get("data") or {} +items = d.get("items") or [] if isinstance(d, dict) else (d if isinstance(d, list) else []) +if not items: + print("(线上没有任何上游)"); raise SystemExit(0) +for u in items: + accts = u.get("accounts") or [] + print("%s base=%s enabled=%s 账号=%d" % ( + u.get("slot"), u.get("base"), u.get("enabled"), len(accts))) + if not accts: + print(" (无账号 —— 转发时不会带 Authorization 头)") + for a in accts: + ld = a.get("load") or {} + m = a.get("auth_mask") + if not m or m == "-": + m = "**空** (转发不带 Authorization 头 → 上游报鉴权错)" + print(" #%s Authorization=%s%s resets=%s 今日 %s 请求 / 入 %s / 出 %s%s" % ( + a.get("idx"), m, + " [冷却中]" if a.get("cooled") else "", + a.get("resets_text") or "-", + ld.get("requests", 0), ld.get("tokens_in", 0), ld.get("tokens_out", 0), + (" 耗尽%s" % ld["exhausts"]) if ld.get("exhausts") else "")) +' +} + +# 上游连通性测试(不靠管理台浏览器):登录后调 /api/admin/upstreams/test, +# 把上游真实响应的 code / 关键错误体打出来。比点面板按钮的「测试」多两个价值: +# ① agent 自动化可调;② 出错时直接看厂商原话(不用肉眼对截图 OCR)。 +# 用法:bash deploy/agent.sh upstream-test minimax +cmd_upstream_test() { + local slot="$1" jar body + jar="$(mktemp -t ipass-uptest.XXXXXX)" + if ! live_login "$jar"; then + echo "✗ 登录失败"; rm -f "$jar"; return 1 + fi + body="$(live_curl -b "$jar" -H 'Content-Type: application/json' \ + -d "{\"slot\":\"$slot\"}" \ + "https://$LIVE_HOST:$LIVE_PORT/api/admin/upstreams/test")" + rm -f "$jar" + if [ -z "$PY" ]; then printf '%s\n' "$body"; return 0; fi + printf '%s' "$body" | "$PY" -c ' +import json, sys +d = json.load(sys.stdin) +data = d.get("data") or {} +code = data.get("status_code") or d.get("code") +status = data.get("status") or d.get("msg", "") +body = data.get("body") or "" +print(f" 上游 HTTP {code} {status}") +if body: + short = body if len(body) <= 300 else body[:300] + "…" + print(" body:", short) +' +} + CMD="${1:-}"; shift || true case "$CMD" in @@ -217,6 +285,9 @@ case "$CMD" in get "/jobs/$1?offset=${2:-0}" | pretty ;; data) [ -n "${1:-}" ] || { echo "用法: bash deploy/agent.sh data users|domains|upstreams" >&2; exit 2; } get "/data?file=$1" | pretty ;; + upstreams) cmd_upstreams ;; + upstream-test) [ -n "${1:-}" ] || { echo "用法: bash deploy/agent.sh upstream-test " >&2; exit 2; } + cmd_upstream_test "$1" ;; pull) IMG="$(resolve_image "${1:-}")"; echo "· 拉取 $IMG" post "/pull" "{\"image\":\"$IMG\"}" | pretty ;; update) IMG="$(resolve_image "${1:-}")"; echo "· 更新到 $IMG" @@ -253,6 +324,8 @@ iPass 控制面包装(凭据只从 .env 读,命令行里不出现任何 key bash deploy/agent.sh containers # 所有容器(标出受管容器) bash deploy/agent.sh logs [tail] # 受管容器日志 bash deploy/agent.sh data users|domains|upstreams + bash deploy/agent.sh upstreams # 上游排障:逐账号掩码/冷却/今日负载 + bash deploy/agent.sh upstream-test # 上游连通性:调测试接口并打印厂商真实响应 变更 bash deploy/agent.sh update [tag] # 拉镜像 + 重建容器(缺省用 .env 的 IPASS_IMAGE_TAG) diff --git a/docs/llm/MULTI_ACCOUNT_ROUTING.md b/docs/llm/MULTI_ACCOUNT_ROUTING.md index 91c8868..6d669a2 100644 --- a/docs/llm/MULTI_ACCOUNT_ROUTING.md +++ b/docs/llm/MULTI_ACCOUNT_ROUTING.md @@ -40,7 +40,7 @@ | 字段 | 含义 | |---|---| | `accounts` | 多账号数组。**取代旧版单 `auth` 字段**;`accounts` 为空时由顶层 `auth` 兼容合成单账号 | -| `accounts[].auth` | 完整的 `Authorization` 头值(如 `Bearer sk-xxx`)。留空表示免鉴权后端 | +| `accounts[].auth` | 完整的 `Authorization` 头值(如 `Bearer sk-xxx`)。**只填裸 key 也行**——读出时 `normalize_auth` 自动补 `Bearer `,避免上游回 1004(详情见 §10) | | `accounts[].note` | 备注(如「华东主账号」),仅展示 | | `accounts[].resets` | 该账号的**额度重置周期(秒)数组**,如 `[604800, 18000]` = 周 + 5 小时。全空=不自动切换 | | `exhaust_status` | 命中即判「额度耗尽」的 HTTP 状态码(**上游级,所有账号共用**)。如 `[401,402,429,403]` | @@ -193,3 +193,60 @@ log : read_llm_acct(r) 取本次选中账号(NOCACHEABLE,与 access 同 - **前端渲染**:以真实 `admin.css` + 真实 `upstreams.js` 渲染路径做无头浏览器断言—— 比例条宽度与负载成比例(412 vs 96 → 100% / 23%)、每账号 14 个条块、悬停峰值日期与数据逐位吻合、 单账号老记录与无账号上游兜底正常、无横向溢出、零 JS 错误。 + +--- + +## 十、auth 规范化(兜住「只填裸 key」的历史坏数据) + +> **适用版本**:`ipass-1.0.15+` + +### 现象 + +线上某 slot(如 `minimax`)管理台「密钥」列能看到 `accounts[]`,但点「测试」按钮上游回: + +``` +minimax 不通:login fail: Please carry the API secret key in the +'Authorization' field of the request header (1004) (195 ms) +``` + +**1004 是 MiniMax 的「缺鉴权头」错误码**,与额度耗尽无关。原因:表单 placeholder 写的是 +`sk-...`,用户照着填了**裸 key**,而 `accounts[].auth` 字段语义是「**完整的 Authorization +头值**」——转发时网关原样发出 `Authorization: sk-cp-...`,上游只认 `Bearer sk-cp-...`, +于是 1004。**唯一让用户感知到的现象就是「测试按钮红字」**——靶机层面的真实状态码与 +厂商错误体都看不到(管理台没回显原始 body;点「测试」之前的旧版本会回 401 而非厂商原话, +更易让人误判成「Key 失效」)。 + +### 解决:`normalize_auth` + +`plugin-llm/src/upstreams.rs` 新增 `normalize_auth(auth: &str) -> String`, +**两处应用**: + +1. **写入(`upsert`)**:用户保存时若填了裸 key(无空格),自动补 `Bearer ` 前缀存盘—— + 历史坏数据在下次保存时归正,无需用户手动重填。 +2. **读出(`read_upa`)**:转发时不管盘上存的是「裸 key」、「已带 Bearer」还是「Basic 自定义」, + 读出即归一化后发往上游——**这一道是给存量坏数据用的兜底**,免去强制让用户重存的运维。 + +### 规则 + +| 输入 | 输出 | 说明 | +|---|---|---| +| `""`(空) | `""` | 未配 Key 是合法状态 | +| `sk-cp-xxx`(裸 key) | `Bearer sk-cp-xxx` | 兜住"只填裸 key" | +| `Bearer sk-cp-xxx` | `Bearer sk-cp-xxx` | 已完整,不动 | +| `Basic dGVzdA==` | `Basic dGVzdA==` | 非 Bearer scheme 也放过 | +| ` sk-cp-xxx ` | `Bearer sk-cp-xxx` | trim 后判定 | +| `Bearer sk cp` | `Bearer sk cp` | 含空格 = 已完整,不动 | + +判定逻辑一句话:**「trim 后还含空白字符 → 视为已完整;否则补 `Bearer `」**。 + +### 自检工具 + +发版后用控制面脚本自助验证(不靠用户点管理台按钮): + +```bash +bash deploy/agent.sh upstreams # 逐账号 Authorization 掩码 + 冷却 + 今日负载 +bash deploy/agent.sh upstream-test minimax # 真实打上游 → 打印 status_code + 厂商响应体 +``` + +`upstreams` 输出的「掩码为空 → 显式标 `**空**`」是发现这类问题的关键指示器:旧镜像没有这个 +输出(直接回脱敏后的掩码,肉眼对比看不出问题),新镜像会显式标红。 diff --git a/readme.md b/readme.md index 24bef27..2e63117 100755 --- a/readme.md +++ b/readme.md @@ -213,10 +213,10 @@ subdomain/ │ ├── usage.html # 用量统计(趋势 · 按人 · 按 API 组 · token) │ ├── apix.html # API 代理(列表 + 弹出卡片编辑 + 免费预估测试) │ └── assets/ # admin.css + core.js + chart.js + 各页 JS -├── tests/ # ★ 本机回归夹具(bash tests/run.sh [gateway|llm|all],279 项) +├── tests/ # ★ 本机回归夹具(bash tests/run.sh [gateway|llm|all],281 项) │ ├── run.sh # 统一入口:编译 + 渲染配置 + 起停 nginx + 跑断言 │ ├── gateway/ # 域名网关:nginx.conf.in + e2e.sh(102 条断言)+ 转发靶机 -│ └── llm/ # LLM 代理:nginx.conf.in + e2e.sh(177 条)+ 假上游 + 合成夹具 +│ └── llm/ # LLM 代理:nginx.conf.in + e2e.sh(179 条)+ 假上游 + 合成夹具 │ # (.run/ 是运行目录,已 gitignore) ├── data/ # ★ 状态目录(需可写;运行期真源在共享内存) │ ├── users.json # 账号表(含口令哈希与 API Key) @@ -532,6 +532,9 @@ LLM 代理读 `Authorization: Bearer`。重置 Key 会同时影响两个入口 - `resets` 是该账号的**额度重置周期(秒)**数组;冷却边界**锚定当天 0 点**(MiniMax 的 5 小时窗口在 20:00–24:00 只有 4 小时、随天重置,不能按 `now + 5h` 滚动) +- `accounts[].auth` 是完整的 `Authorization` 头值(如 `Bearer sk-…`)。**只填裸 key 也行**—— + 读出时 `normalize_auth` 自动补 `Bearer `,免去用户照着 placeholder 填了裸 key 而回 1004 + (详见 `docs/llm/MULTI_ACCOUNT_ROUTING.md` §10) - `exhaust_status` / `exhaust_markers` 是**上游级**耗尽判据(所有账号共用): HTTP 状态码命中,或响应体流式扫描到标记子串,即判该账号额度耗尽 - 无绑定时按 `FNV-1a(下游 Key) % 可用账号数` **分散**(避免全压第一个账号触发厂商 @@ -599,7 +602,7 @@ cp -a data /path/to/backup/ 夹具在仓库里 `tests/`,**不进 Docker**,直接在本机跑(秒级): ```bash -bash tests/run.sh # 全部:域名网关 102 条 + LLM 代理 177 条 +bash tests/run.sh # 全部:域名网关 102 条 + LLM 代理 179 条 bash tests/run.sh gateway # 只跑域名网关 bash tests/run.sh llm # 只跑 LLM 代理 ``` @@ -803,6 +806,7 @@ DRY_RUN=1 bash deploy/release.sh 1.0.3 # 只构建不推送 | `ipass-1.0.12` | **插件化重构**:workspace 化(ipass-core + 三插件 crate + gateway 唯一 cdylib),行为完全等价,262 项回归全绿。commit `ddd4172`。架构见 `docs/plugin/PLUGIN_ARCHITECTURE.md`。 | | `ipass-1.0.13` | 采纳 sso 上游化建议 4 条(`User.extra` flatten / `split_value` rposition / `iter_prefix_ex` / `users::update_extra`)。commit `ee05b27`,评估记录 `docs/plugin/SSO_UPSTREAM_DECISIONS.md`。 | | `ipass-1.0.14` | **LLM 上游多账号路由 + 额度耗尽自动切换 + 粘性绑定**(见 §15「上游配置」与 `docs/llm/MULTI_ACCOUNT_ROUTING.md`):一个 slot 挂多个账号 Key,下游 Key 与上游账号粘性绑定(`ukb:`,仅共享内存、重启重绑);无绑定时按 `FNV-1a(下游 Key) % n` 分散(均匀铺开避开厂商单账号并发上限,同时落点固定保住 prompt/token 缓存);厂商判额度耗尽(HTTP 状态码 或 响应体 marker,流式也扫)即冷却该账号并切下一个,冷却边界**天锚定**(对齐 MiniMax「5h 窗口、末段 4h 随天重置」)。**新增账号级负载统计**(`uda:`/`uex:` 日桶,复用内核 `usage` 原语、零新依赖):管理台「上游」页密钥列展示各 Key 今日请求/token/耗尽次数 + 负载比例条 + 14 天迷你趋势。回归 279 条全绿(网关 102 + LLM 177)。 | +| `ipass-1.0.15` | **auth 规范化(`normalize_auth`)+ 排障子命令**。表单 placeholder 写的是 `sk-...`,用户照着填了**裸 key**(无 `Bearer `),转发时原样发出 → 上游回 1004。`plugin-llm` 新增 `normalize_auth`:trim 后无空白即自动补 `Bearer `,**写入(`upsert`)+ 读出(`read_upa`)双处应用**——前者让存量在下次保存时归正,后者让线上坏数据立即可用、无需用户重填。`deploy/agent.sh` 新增 `upstreams`(逐账号掩码/冷却/今日负载,掩码为空显式标红)与 `upstream-test `(调测试接口并打厂商真实响应,不靠管理台按钮)两个排障子命令。回归 281 条全绿(网关 102 + LLM 179)。 | --- @@ -1132,6 +1136,28 @@ GET /apix/search?q=nginx Authorization: Bearer sk_<本网关签 `admin.css` + `upstreams.js` 渲染路径做无头浏览器断言(比例条成比例、条块数、悬停日期、无溢出)。 - 专章:`docs/llm/MULTI_ACCOUNT_ROUTING.md`(数据模型 / 路由 / 冷却数学 / shm 布局 / 负载统计)。 +- **2026-09-14(续15)auth 规范化 + 排障子命令(`ipass-1.0.15`)** + - **根因**:表单 placeholder 写 `sk-...`,用户照着填了**裸 key**(无 `Bearer `), + 转发时原样发 → 上游回 1004。`agent.sh upstreams` 一打就看出来:deepseek 掩码是 + `Bearer s...d425`(正常),minimax 掩码是 `sk-cp-...`(**无 `Bearer `**), + 完美的对照组。 + - **`normalize_auth` 兜底**:`plugin-llm` 新增,规则「trim 后含空白 → 已完整; + 否则补 `Bearer `」。**两处应用**——`upsert` 写入时归正(下次保存自愈)、 + `read_upa` 读出时归正(**让线上坏数据立即可用,无需用户重填**)。 + 兼容 Basic / 自定义 scheme / 前后空格 / 内部含空格的特殊情况(详见 §15 与 + `docs/llm/MULTI_ACCOUNT_ROUTING.md` §10)。 + - **`agent.sh` 加两个排障子命令**:`upstreams` 逐账号打掩码/冷却/今日负载 + (**掩码为空显式标 `**空**`**——这是发现「只填了裸 key」类问题的关键指示器, + 旧镜像的回显脱敏后看不出问题);`upstream-test ` 调测试接口并打印 + 厂商真实响应(不靠管理台按钮 OCR 截图)。 + - 回归 **281 条全绿**(网关 102 + LLM 179,新增 2 条 normalize 断言:裸 key 200 + + 靶机实收 `Bearer sk-NORM-NO-SCHEME`)。 + - 教训:**placeholder 写「前缀而不是字面值」会诱导用户漏填必要部分**——正确写法是 + `Bearer sk-…` + 表单说明「只填裸 key 也会自动补 Bearer」(已改)。 + 上游回 1004 / "Please carry the API secret key" 之类的**厂商原话**比"401"这种 + 通用状态码更能锁定根因——管理台测试按钮旧版本不回 body,是这个 bug 没被立刻发现 + 的次因。 + - **2026-09-13(续11)插件化重构(`ipass-1.0.12`)** - 单 crate 拆为 **workspace**:`ipass-core`(内核)+ `plugin-domain` / `plugin-llm` / `plugin-apix` 三个插件 crate(一律 rlib)+ `gateway`(**唯一 cdylib**,产物仍为 `libipass_gateway.so`)。 diff --git a/rust/crates/plugin-llm/src/upstreams.rs b/rust/crates/plugin-llm/src/upstreams.rs index 0cf8d2b..d08584b 100644 --- a/rust/crates/plugin-llm/src/upstreams.rs +++ b/rust/crates/plugin-llm/src/upstreams.rs @@ -266,6 +266,29 @@ pub fn read_up(slot: &str) -> Option<(String, usize)> { Some((base.to_owned(), n)) } +/// 规范化账号 Authorization 头值:缺 scheme 时自动补 `Bearer `。 +/// +/// 用途:**兜住「只填了裸 key 没填 `Bearer `」这种历史坏数据**。表单 placeholder +/// 写的是 `sk-...`,用户照着填 → 之前保存的就是 `sk-cp-...` 这种裸 key, +/// 上游(MiniMax)只认 `Bearer `,于是回 1004。 +/// +/// 规则: +/// * 空 → 原样返回("未配 Key"是合法状态,不是数据错); +/// * 含空格 → 原样返回(已是完整头值,如 `Bearer xxx` / `Basic xxx`,别动); +/// * 不含空格 → 补 `Bearer ` 前缀。 +/// +/// 同时也在 `upsert` 里应用:下次保存时旧数据自动归正,无需用户手动重填。 +pub fn normalize_auth(auth: &str) -> String { + let t = auth.trim(); + if t.is_empty() { + return String::new(); + } + if t.contains(char::is_whitespace) { + return t.to_owned(); + } + format!("Bearer {}", t) +} + /// 读 `upa::`:`(auth, resets)`。 pub fn read_upa(slot: &str, i: usize) -> Option<(String, Vec)> { let (payload, _) = state::get(KEY_UPA_PREFIX, format!("{slot}:{i}").as_bytes())?; @@ -277,7 +300,7 @@ pub fn read_upa(slot: &str, i: usize) -> Option<(String, Vec)> { .filter_map(|s| s.trim().parse::().ok()) .collect() }; - Some((auth.to_owned(), resets)) + Some((normalize_auth(auth), resets)) } /// 读 `upe:`:`(status 列表, markers 列表)`。 @@ -710,6 +733,9 @@ pub fn upsert( if let Some(old) = existing_accounts.get(i) { a.auth = old.auth.clone(); } + } else { + // 缺 scheme 自动补 `Bearer `(兜住「只填裸 key」的历史坏数据) + a.auth = normalize_auth(&a.auth); } a }) @@ -719,7 +745,7 @@ pub fn upsert( None => ( Vec::new(), match auth_raw { - Some(a) => util::trim(a).to_owned(), + Some(a) => normalize_auth(a), None => existing.as_ref().map(|e| e.auth.clone()).unwrap_or_default(), }, ), diff --git a/tests/llm/e2e.sh b/tests/llm/e2e.sh index f394e68..e9b7104 100755 --- a/tests/llm/e2e.sh +++ b/tests/llm/e2e.sh @@ -548,6 +548,13 @@ ck "multi 冷却期间保持 acct=1(不回退坏账号)" 1 "$(echo "$M3" | a M4=$(mh multi multi-model) ck "multi 切换后下游 Key 真换成 acct-good" "Bearer acct-good" "$(up_hdr Authorization)" +# ---- auth 规范化(normalize_auth)---- +# fixture `normalize` 账号 auth 写成裸 key(`sk-NORM-NO-SCHEME`,无 `Bearer `), +# 期望:转发时网关自动补 `Bearer `,靶机实收完整头值(不会因缺 scheme 触发 1004)。 +N1=$(mh normalize normalize-model) +ck "normalize 初次 200(裸 key 被补 Bearer 后 200)" 200 "$(echo "$N1" | awk '/^HTTP/{print $2}')" +ck "normalize 靶机实收 Bearer sk-NORM-NO-SCHEME" "Bearer sk-NORM-NO-SCHEME" "$(up_hdr Authorization)" + # ---- 账号级负载统计(管理台「密钥 / 负载」列的数据源)---- # 每次真实转发在 log 阶段落到「本次选中的那个账号」的日桶 uda:::; # 额度耗尽另记 uex:。用同一份 /api/admin/upstreams 投影断言负载分布是否正确。 diff --git a/tests/llm/fixtures/llm-upstreams.json b/tests/llm/fixtures/llm-upstreams.json index 051b74d..a164bee 100644 --- a/tests/llm/fixtures/llm-upstreams.json +++ b/tests/llm/fixtures/llm-upstreams.json @@ -55,5 +55,15 @@ "exhaust_status": [401], "note": "两账号均好,验证同一下游 key 粘性绑定到首个账号", "created_at": 1757500000 + }, + "normalize": { + "base": "http://127.0.0.1:18999", + "models": ["normalize-model"], + "enabled": true, + "accounts": [ + {"auth": "sk-NORM-NO-SCHEME", "note": "裸 key 无 Bearer", "resets": []} + ], + "note": "验证 normalize_auth:账号 auth 写成裸 key,转发时网关自动补 `Bearer `", + "created_at": 1757500000 } } diff --git a/www/assets/upstreams.js b/www/assets/upstreams.js index 7b7aba5..f522013 100644 --- a/www/assets/upstreams.js +++ b/www/assets/upstreams.js @@ -52,7 +52,7 @@ (a.cooled ? "冷却中" : "") + "" + "" + - "" + + "" + "" + "" + ""; @@ -75,6 +75,7 @@ '
' + '
' + '
' + + '
每行填 Authorization 头值(Bearer sk-…)。只填裸 key 也会自动补 Bearer 。
' + '
' + rows + '
' + "" + '
' +