From 9ede90b06eee5d5d33b0932725a5eee717431ba0 Mon Sep 17 00:00:00 2001 From: admin Date: Sat, 12 Sep 2026 12:27:41 +0800 Subject: [PATCH] =?UTF-8?q?docs(llm):=20=E5=A4=9A=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E4=B8=8E=E9=89=B4=E6=9D=83=E5=A4=B4=E8=B0=83?= =?UTF-8?q?=E7=A0=94=EF=BC=88=E5=BC=80=E6=BA=90=E5=AE=9E=E7=8E=B0=20+=20?= =?UTF-8?q?=E5=AE=98=E6=96=B9=E6=8C=87=E5=BC=95=20+=20=E5=AE=9E=E6=B5=8B?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - LiteLLM:/anthropic/* 路径前缀路由;clean_headers 的 authenticated_with_header 语义 + 默认摘凭据头 + 双层 allowlist + 日志/转发两副本分离 - one-api:根地址 + 路径天然区分,model 只选 channel,出站三头齐设 - Higress:Automatic Protocol Detection;v2.2.3 把按模型名宽泛匹配改成路径后缀判断 - Anthropic 官方:走网关用 ANTHROPIC_AUTH_TOKEN(发 Authorization),直连才用 ANTHROPIC_API_KEY(发 X-Api-Key) - 靶机改为记录全部收到的头:手挑字段会让未替换的头在回归里全绿通过 结论:协议由客户端路径表达,不需要网关分发;统一注册的实体是 base 写到 host。 鉴权头两种修法与 off 模式的必注入清单(漏 Content-Type 会让所有 POST 废)见文档。 --- docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md | 271 +++++++++++++++++++++++++ tests/llm/upstream.py | 8 +- 2 files changed, 276 insertions(+), 3 deletions(-) create mode 100644 docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md diff --git a/docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md b/docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md new file mode 100644 index 0000000..cd980e1 --- /dev/null +++ b/docs/llm/UPSTREAM_PROTOCOL_AND_AUTH.md @@ -0,0 +1,271 @@ +# LLM 多协议网关:上游路由与鉴权头的成熟做法 + +> 调研日期 2026-09-12。目的:回答「上游同时有 OpenAI 与 Anthropic 两套协议时, +> 统一注册再分发、还是注册两条」,以及「网关 Key 经请求头泄漏给上游」怎么修。 +> **结论全部来自开源实现或厂商官方文档,并附本机靶机实测证据**(本项目硬规矩: +> 验证请求头替换必须看上游收到的请求)。 + +涉及文件:`conf/nginx.conf`(LLM server)、`rust/src/llm.rs`、`rust/src/upstreams.rs`、 +`tests/llm/upstream.py`。 + +--- + +## 一、结论速览 + +| 问题 | 成熟做法 | 我们的对应 | +|---|---|---| +| 协议怎么区分 | **路径**,三个主流网关一致 | 已有:slot 在前 + 客户端路径在后 | +| 要不要网关分发 | **不要**。「统一注册」= 一条记录 + base 写到 host | 改 base 粒度即可,零代码 | +| 出站凭据头 | **默认不放行**(allowlist)或**按「哪个头用于网关鉴权」摘除** | 待改:现在漏 `x-api-key` | +| 客户端该用哪个变量 | Anthropic 官方:走网关用 `ANTHROPIC_AUTH_TOKEN` | 文档引导即可 | + +--- + +## 二、三个开源方案的实际做法 + +### 2.1 LiteLLM(最主流,Python) + +**协议路由**:路径前缀即 provider 路由。官方文档原话—— +"Anything after `http://0.0.0.0:4000/anthropic` is treated as a provider-specific route"。 +客户端把 `https://api.anthropic.com` 换成 `{网关}/anthropic`,其余路径照抄。 + +**鉴权头**(`litellm/proxy/litellm_pre_call_utils.py`,真实源码): + +```python +# clean_headers() —— 决定哪些头**能**被转发 +for header, value in headers.items(): + header_lower = header.lower() + + if header_lower == "authorization" and is_anthropic_oauth_key(value): + # 只有「不是用来做网关鉴权的那把」才转发 + if authenticated_with_header is None or authenticated_with_header.lower() != "authorization": + clean_headers[header] = value + continue + elif header_lower == "x-api-key": + # 默认不转发;仅 BYOK 且「不是网关鉴权用的那个头」才转发 + if forward_llm_provider_auth_headers and ( + authenticated_with_header is None or authenticated_with_header.lower() != "x-api-key" + ): + clean_headers[header] = value + elif forward_llm_provider_auth_headers and header_lower in _SPECIAL_HEADERS_CACHE: + if litellm_key_lower and header_lower == litellm_key_lower: + continue + if header_lower == "authorization": + continue # ★ Authorization 永不转发给上游 + if header_lower == "x-litellm-api-key": + continue + clean_headers[header] = value + elif header_lower not in _SPECIAL_HEADERS_CACHE and ( + litellm_key_lower is None or header_lower != litellm_key_lower + ): + clean_headers[header] = value +``` + +```python +# _get_forwardable_headers() —— 第二层:allowlist +for header, value in headers.items(): + if ( + header.lower().startswith("x-") + and not header.lower().startswith("x-stainless") # 会让 OpenAI SDK 出错 + or header.lower().startswith("anthropic-beta") + ): + forwarded_headers[header] = value +``` + +**三条可直接借用的原则**: + +1. **`authenticated_with_header`** —— 记录「客户端用哪个头做了网关自身鉴权」, + **那个头绝不转发**。比按名字硬编码精确:同一个 `x-api-key`,用来过网关时要摘掉, + 作为 BYOK 凭据时要转发,区别就在这里。 +2. **默认摘除凭据头**,官方文档明确列了 `x-api-key` / `x-goog-api-key` / `api-key`, + 理由是 "these are typically used to authenticate with the proxy itself"。 +3. **双层防护**:`clean_headers` 先摘凭据头,`_get_forwardable_headers` 再 allowlist + (只放行 `x-*` 与 `anthropic-beta`)。且日志副本走 `redact_credential_headers()` + 把凭据值替换成 `***REDACTED***`,**转发的副本保留真值** —— 凭据与可观测性两副本分离。 + +BYOK(客户端自带厂商 Key)是**显式开关**:`forward_llm_provider_auth_headers: true`。 + +### 2.2 one-api / new-api(国内主流,Go) + +**路由**:客户端 `ANTHROPIC_BASE_URL` 指向网关**根**,路径天然区分 +(`/v1/messages` 是 Anthropic、`/v1/chat/completions` 是 OpenAI); +`model` 字段只用于**选 channel**,不用于判协议。 + +官方 README 给的 Claude Code 用法: +```bash +export ANTHROPIC_BASE_URL="https://oneapi.laisky.com/" # 根,不带 /anthropic +export ANTHROPIC_AUTH_TOKEN="sk-xxxxxxx" # 注意用的是 AUTH_TOKEN +``` + +**鉴权头**(`relay/adaptor/anthropic/adaptor.go`):出站同时设三个头 —— +`x-api-key: <上游真Key>` + `anthropic_version` + `Authorization: Bearer <上游真Key>`。 +即**入站的客户端凭据被完全替换**,不存在"另一个头漏过去"。 + +它的 adaptor 接口把「建 URL / 设鉴权头」拆成 `GetRequestURL()` / `SetupRequestHeader()` +两个独立职责,与我们 `llm.rs` 的 `$llm_target` / `$llm_auth` 分工一致。 + +### 2.3 Higress(阿里,Envoy/Wasm,CNCF Sandbox) + +**协议路由**:官方文档称 **Automatic Protocol Detection** —— +"allowing it to simultaneously handle OpenAI and Claude protocols **without explicit configuration**"。 + +值得注意的是它的演进方向:v2.2.3 release notes 提到 +「Claude API 名称识别从**宽泛匹配**改成更准确的**后缀判断**(#3839),减少同一套客户端换个模型就出现异常 400 的概率」。 + +即:**从"猜"(按模型名)改成"看确定判据"(按路径后缀)**。这正是不该按 body 猜协议的权威背书。 + +同版本还有一条:「AI Proxy 支持 vLLM 透传 Anthropic Messages 和新版 OpenAI endpoints(#3989)。 +**能原样透传的请求不再做多余转换**,链路更短,排查也更轻。」—— 与我们的纯透传定位一致。 + +--- + +## 三、决定性事实:Anthropic 官方对网关场景的指引 + +Claude Code 官方文档(`code.claude.com/docs/en/authentication`)原文: + +> **`ANTHROPIC_AUTH_TOKEN`** environment variable. Sent as the **Authorization: Bearer** header. +> **Use this when routing through an LLM gateway or proxy** that authenticates with bearer tokens +> rather than Anthropic API keys. +> +> **`ANTHROPIC_API_KEY`** environment variable. Sent as the **X-Api-Key** header. +> **Use this for direct Anthropic API access** with a key from the Claude Console. + +**这条改变了问题的定性**: + +- Claude Code **走网关的正确姿势就是 `ANTHROPIC_AUTH_TOKEN`** → 发 `Authorization: Bearer`, + **根本不会发 `x-api-key`**。所以「支持 x-api-key 入站」不是必需能力,是兼容 bonus。 +- 反过来说,客户端发 `x-api-key` 只有两种情形:(a) 用户把网关 Key 错放进 `ANTHROPIC_API_KEY`; + (b) 真的有客户端偏好这个头。两种情形下**漏给上游都是缺陷**,不是"预期行为"。 +- 所以修法优先级:**出站摘除**(必做)> 文档引导用户用 `ANTHROPIC_AUTH_TOKEN`(配套)。 + +--- + +## 四、本机靶机实测(证据) + +靶机 `tests/llm/upstream.py` 改为记录**全部**收到的头(不再手挑字段——第一版只记 +`Authorization`,于是 `x-api-key` 泄漏**在整轮 155 条回归里全绿通过**,完全不可见)。 + +### 4.1 现状(`proxy_pass_request_headers on`,默认) + +客户端用 `x-api-key: sk_<网关Key>` 调用: + +| 上游收到 | 值 | +|---|---| +| `authorization` | `Bearer sk-UPSTREAM-REAL-SECRET` ✅ 已替换 | +| **`x-api-key`** | **`sk_bob_bbbb…`(网关自己的 Key)❌ 泄漏** | +| `anthropic-version` | `2023-06-01` ✅ | +| `anthropic-beta` | `prompt-caching-2024-07-31` ✅ | +| `content-type` / `accept` / `user-agent` | 透传 | + +生产侧 A/B(`.11:88`,`Host: lm.mayishangshu.cn`):`/minimax/anthropic/v1/messages` 两种携带方式 +**都返回 200** —— MiniMax 两处都认,宽松厂商**掩盖**了缺陷。换到只认 `x-api-key` 的严格厂商 +会 401,且报错形状像「上游密钥配错」。 + +### 4.2 `proxy_pass_request_headers off` + 显式注入(allowlist) + +同样客户端用 `x-api-key` 调用: + +| 上游收到 | 值 | +|---|---| +| `authorization` | `Bearer sk-UPSTREAM-REAL-SECRET` ✅ | +| `x-api-key` | **不存在** ✅ 不再泄漏 | +| `anthropic-version` / `anthropic-beta` | ✅(来自显式注入) | +| `content-type` / `accept` | ✅(来自显式注入) | +| `user-agent` | 被丢弃(未注入) | + +### 4.3 `off` 模式下**必须显式注入**的清单(反推实测) + +只注入 `Host` / `Authorization` / `anthropic-version` 时,实测丢失: + +| 头 | 后果 | +|---|---| +| **`Content-Type`** | **所有 POST 失效** —— 上游收到无 content-type 的 body | +| **`anthropic-version`** | Anthropic 协议必填,缺失即被拒 | +| **`anthropic-beta`** | Claude Code 的 prompt caching 等扩展能力静默失效 | +| `Accept` | SSE 流式可能受影响 | + +自动保留:`Content-Length`(nginx 自动生成)。`X-Real-IP` / `X-Forwarded-*` / `Connection` +本就是自己设的,不受 `off` 影响。 + +**代价**:清单需要维护。将来厂商新增扩展头(如 `openai-beta`)必须记得加, +漏一个就是**静默功能缺失**,而 `Content-Type` 这种漏了是全量故障。 + +--- + +## 五、落到我们的网关 + +### 5.1 协议与 base 粒度(对用户问题的直接回答) + +三个开源方案**都用路径区分协议**,无一按 body 的 `model` 猜。而我们的 +「slot 在前 + 客户端路径在后」**就是 LiteLLM 的 `/anthropic/...` 模式**: + +``` +base = https://api.minimaxi.com (只到 host) + ├─ /minimax/v1/chat/completions → …/v1/chat/completions + └─ /minimax/anthropic/v1/messages → …/anthropic/v1/messages +``` + +**所以不需要任何分发代码**。「统一注册」不是"网关分发",是 **base 粒度写到 host**。 +`base = …/anthropic`(`.11` 上 `minimax` 现状)等于把记录钉死在该前缀下,另一协议 404。 + +代价:host 粒度把厂商整个路径空间开放给客户端。要收敛就用全路径 + 两条记录, +那时"两条"是自然结果,不是设计选择。 + +### 5.2 鉴权头(待修) + +推荐组合(贴合 LiteLLM 的双层 + 保留我们的透传定位): + +```nginx +location / { + ipass_llm on; + + # 第一层:默认不放行客户端头(allowlist 语义) + proxy_pass_request_headers off; + + # 第二层:显式注入上游真正需要的头 + proxy_set_header Host $llm_host; + proxy_set_header Authorization $llm_auth; # 换上游真 Key + proxy_set_header anthropic-version $http_anthropic_version; + proxy_set_header anthropic-beta $http_anthropic_beta; + proxy_set_header Content-Type $content_type; + proxy_set_header Accept $http_accept; + # 自己产生的头 + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Connection ""; + ... +} +``` + +**最小改动替代方案**(若不愿维护清单):保留 `on`,逐个抹除凭据头: + +```nginx +proxy_set_header x-api-key ""; # nginx 空串 = 不发该头 +proxy_set_header api-key ""; +``` + +两者取舍:`off` 默认安全、未知头一律不放行(LiteLLM 思路),但清单要维护; +blocklist 改动一行、不影响现有透传,但将来厂商新增凭据头得记得补。 + +**长期正确解**是 LiteLLM 的 `authenticated_with_header` 语义:`llm::downstream_key` +已经知道客户端用哪个头鉴权,把这个信息暴露成变量后按需摘除。当前阶段两种方案都能先堵住泄漏。 + +### 5.3 严格厂商(只认 x-api-key)的支持 + +`.11` 上 deepseek/minimax 都是宽松厂商(两处都认),所以现在不阻塞。 +若要支持严格厂商,最省的做法是在上游记录里加一个鉴权风格字段(`bearer` / `x-api-key` / `both`), +由 `llm.rs` 算出 `$llm_auth` 与 `$llm_auth_x_api_key` 两个变量,nginx 侧按需注入。 +**别按厂商名硬编码** —— 那是 Higress 已经改掉的"宽泛匹配"老路。 + +--- + +## 六、参考来源 + +- LiteLLM `litellm/proxy/litellm_pre_call_utils.py`(`clean_headers` / `_get_forwardable_headers`) +- LiteLLM 文档:Anthropic Passthrough、Forward Client Headers to LLM API、Native `/v1/messages` Passthrough +- one-api `relay/adaptor/anthropic/adaptor.go`、README(Claude Code 段) +- new-api `relay/channel/claude/adaptor.go` +- Higress `plugins/wasm-go/extensions/ai-proxy/`、v2.2.3 release notes(#3839 / #3989) +- Anthropic 官方:Claude Code Authentication(`ANTHROPIC_AUTH_TOKEN` vs `ANTHROPIC_API_KEY`) +- nginx `proxy_pass_request_headers` 语义(默认 on = 透传客户端头) diff --git a/tests/llm/upstream.py b/tests/llm/upstream.py index 745eec6..d538d59 100644 --- a/tests/llm/upstream.py +++ b/tests/llm/upstream.py @@ -22,13 +22,15 @@ class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def _record(self, body: bytes): + # 记录**全部**收到的头,而不是手挑几个字段。 + # 教训:手挑字段会漏掉"没被替换的那个头"——第一版只记 Authorization, + # 于是 x-api-key 泄漏在整轮回归里全绿通过,完全看不见。 rec = { "path": self.path, "method": self.command, + "headers": {k.lower(): v for k, v in self.headers.items()}, + # 下面几个是长期被断言的字段,保留以免旧断言失效 "auth": self.headers.get("Authorization", "-"), - # x-api-key / anthropic-version 必须记:Anthropic 协议的上游只认 - # `x-api-key`,而网关当前只覆写 Authorization。**不记就意味着 - # 「下游那把 sk_ 是否被原样漏给上游」这件事在这里是看不见的**。 "x_api_key": self.headers.get("x-api-key", "-"), "anthropic_version": self.headers.get("anthropic-version", "-"), "host": self.headers.get("Host", "-"),