From ca71af3310faa95da745a0afea258b75b35e564b Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 17 Sep 2026 19:03:04 +0800 Subject: [PATCH] feat: upstream request headers, and the client API read from the path Upstream credentials follow the enterprise gateway's header model: - `key` is one API key, sent in the header the protocol uses (`x-api-key`, `Authorization: Bearer`, `x-goog-api-key`) - `headers` is an ordered map of any other headers to send, or the whole credential for relays that authenticate with their own header. Values may use `${ENV}`, `{{client}}` (the calling gateway key's name) and `{{access_token}}` (requires `oauth`). Configured headers replace the ones the client sent under the same name - `oauth` moves out of `key` into its own block. OAuth credentials for Claude subscriptions and the Gemini CLI's Google login are rejected The control API mirrors this: `ProviderView` carries a masked `key`, `auth_header`, masked `headers` and `oauth`; `ProviderInput` takes `SecretChange` / `HeaderInput` / `OAuthChange`, where a missing header value keeps the saved one. Provider preview accepts the chosen protocol so the UI can say which header the key goes in. The client API is now read from the request path instead of where the gateway key was put. Fixes found along the way: - Claude Code adopted with `ANTHROPIC_AUTH_TOKEN` sends a Bearer key and was treated as an OpenAI client: Anthropic models were refused by model admission and errors came back in OpenAI shape - `POST /v1beta/models/{model}:generateContent` returned 405 - the gateway key in `?key=` was forwarded to the upstream URL - `x-thinkwatch-*` request headers were forwarded upstream `GET /v1/models` has no path to go by, so an `anthropic-version` header or a key in `x-api-key` marks an Anthropic client there. Co-Authored-By: Claude Opus 5 --- Cargo.lock | 40 +- Cargo.toml | 2 +- bin/twcore/src/main.rs | 28 +- crates/tw-api/src/lib.rs | 105 ++- crates/tw-config/src/credential.rs | 679 +++++++++++++++++++ crates/tw-config/src/lib.rs | 168 +---- crates/tw-config/src/proxy.rs | 6 +- crates/tw-config/src/validate.rs | 97 +-- crates/tw-control/src/lib.rs | 57 +- crates/tw-control/src/replay.rs | 18 +- crates/tw-control/src/resources.rs | 181 ++--- crates/tw-control/src/rotation.rs | 13 +- crates/tw-control/tests/models.rs | 22 + crates/tw-control/tests/resources.rs | 96 ++- crates/tw-engine/src/catalog.rs | 48 +- crates/tw-gateway/src/auth.rs | 26 +- crates/tw-gateway/src/client_api.rs | 167 +++++ crates/tw-gateway/src/forward.rs | 94 ++- crates/tw-gateway/src/l3.rs | 10 +- crates/tw-gateway/src/lib.rs | 1 + crates/tw-gateway/src/models.rs | 27 +- crates/tw-gateway/src/oauth.rs | 25 +- crates/tw-gateway/src/probe.rs | 4 +- crates/tw-gateway/src/server.rs | 183 +++-- crates/tw-gateway/src/translate.rs | 36 +- crates/tw-gateway/src/ws.rs | 24 +- crates/tw-gateway/tests/dialect.rs | 2 +- crates/tw-gateway/tests/endings.rs | 2 +- crates/tw-gateway/tests/headers_and_paths.rs | 239 +++++++ crates/tw-gateway/tests/hotreload.rs | 4 +- crates/tw-gateway/tests/live.rs | 2 +- crates/tw-gateway/tests/m1_acceptance.rs | 2 +- crates/tw-gateway/tests/m5_redact.rs | 2 +- crates/tw-gateway/tests/m5_toolwall.rs | 2 +- crates/tw-gateway/tests/models.rs | 2 +- crates/tw-gateway/tests/oauth.rs | 27 +- crates/tw-gateway/tests/passthrough.rs | 182 ++--- crates/tw-gateway/tests/ws.rs | 2 +- crates/tw-secret/src/lib.rs | 5 +- crates/tw-secret/src/mask.rs | 149 +++- 40 files changed, 2118 insertions(+), 661 deletions(-) create mode 100644 crates/tw-config/src/credential.rs create mode 100644 crates/tw-gateway/src/client_api.rs create mode 100644 crates/tw-gateway/tests/headers_and_paths.rs diff --git a/Cargo.lock b/Cargo.lock index 472ea070..ce240f5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2775,7 +2775,7 @@ dependencies = [ [[package]] name = "tw-adopt" -version = "0.2.2" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -2789,7 +2789,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.2.2" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -2797,7 +2797,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.2.2" +version = "0.3.0" dependencies = [ "blake3", "notify", @@ -2817,7 +2817,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.2.2" +version = "0.3.0" dependencies = [ "axum", "bytes", @@ -2852,7 +2852,7 @@ dependencies = [ [[package]] name = "tw-crypto" -version = "0.2.2" +version = "0.3.0" dependencies = [ "aes-gcm", "anyhow", @@ -2864,7 +2864,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.2.2" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -2872,7 +2872,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.2.2" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -2884,7 +2884,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.2.2" +version = "0.3.0" dependencies = [ "arc-swap", "async-stream", @@ -2924,7 +2924,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.2.2" +version = "0.3.0" dependencies = [ "tokio", "tracing", @@ -2933,7 +2933,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.2.2" +version = "0.3.0" dependencies = [ "arc-swap", "flate2", @@ -2945,7 +2945,7 @@ dependencies = [ [[package]] name = "tw-protocol" -version = "0.2.2" +version = "0.3.0" dependencies = [ "bytes", "futures", @@ -2957,7 +2957,7 @@ dependencies = [ [[package]] name = "tw-provider" -version = "0.2.2" +version = "0.3.0" dependencies = [ "async-stream", "aws-credential-types", @@ -2982,7 +2982,7 @@ dependencies = [ [[package]] name = "tw-redact" -version = "0.2.2" +version = "0.3.0" dependencies = [ "base64", "serde", @@ -2992,7 +2992,7 @@ dependencies = [ [[package]] name = "tw-resil" -version = "0.2.2" +version = "0.3.0" dependencies = [ "futures", "metrics", @@ -3005,7 +3005,7 @@ dependencies = [ [[package]] name = "tw-scan" -version = "0.2.2" +version = "0.3.0" dependencies = [ "notify", "regex", @@ -3022,14 +3022,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.2.2" +version = "0.3.0" dependencies = [ "thiserror", ] [[package]] name = "tw-store" -version = "0.2.2" +version = "0.3.0" dependencies = [ "bytes", "libc", @@ -3047,7 +3047,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.2.2" +version = "0.3.0" dependencies = [ "serde", "serde_json", @@ -3056,7 +3056,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.2.2" +version = "0.3.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -3065,7 +3065,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.2.2" +version = "0.3.0" dependencies = [ "anyhow", "chrono", diff --git a/Cargo.toml b/Cargo.toml index b6eed9da..d706e808 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ repository = "https://github.com/ThinkWatchProject/ThinkWatch-Core" # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.2.2" +version = "0.3.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index d00202a2..43c943a8 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -551,18 +551,34 @@ fn cmd_check(path: &Path) -> Result<()> { // 猜不出来不是错误,但值得说一句 —— M0 按 Anthropic 走。 None => "未知(按 Anthropic 转发)".to_string(), }; + // 说来源而不是值。 + let credential = match (&p.key, &p.oauth) { + (Some(k), _) => format!("密钥 {}({})", k.describe(), p.auth_header().0), + (None, Some(_)) => "OAuth".to_string(), + (None, None) if !p.headers.is_empty() => "请求头".to_string(), + (None, None) => "无凭据".to_string(), + }; println!( - " · {} → {} [{}] 密钥 {}", + " · {} → {} [{}] {credential}", p.name, tw_secret::redact_url(&p.base_url), proto, - // 说来源而不是值。 - p.key.describe() ); + for h in p.headers.iter() { + let raw = h.value.raw(); + let shown = if tw_secret::is_public_header(&h.name) + || tw_secret::is_reference_only(raw) + { + raw.to_string() + } else { + tw_secret::mask_secret(raw) + }; + println!(" · 请求头 {}: {shown}", h.name); + } // OAuth 不在这里换 token:那是一次网络往返,而 check // 是个用户期望立刻返回的命令。但**能离线查的都要查** —— // 这几样写错了,症状全是网关起来之后一片 401。 - if let Some(o) = p.key.oauth() { + if let Some(o) = &p.oauth { if o.refresh.trim().is_empty() { println!(" ⚠ refresh token 是空的 —— 这家换不出 token"); } @@ -591,8 +607,8 @@ fn cmd_check(path: &Path) -> Result<()> { ); } println!(" · OAuth 凭据:换 token 要联网,网关起来之后才做"); - } else if let Err(e) = p.resolved_key() { - println!(" ⚠ 密钥取不到:{e}"); + } else if let Err(e) = p.outbound_headers(None, None) { + println!(" ⚠ 凭据取不到:{e}"); } } Ok(()) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 33156cf2..abd1a6f4 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -539,19 +539,17 @@ pub struct ProviderView { pub base_url: String, /// 地址里有被打码的部分(userinfo 之类) pub base_url_masked: bool, - /// 密钥的**来源**,不是值 - pub key_source: String, - /// `key` / `env` / `oauth` - pub key_kind: String, - /// `env` 时是哪个变量。变量名不是秘密,而它正是编辑时要回填的东西 + /// API 密钥:打过码的值,或者环境变量名。没有密钥是空 #[serde(default, skip_serializing_if = "Option::is_none")] - pub key_env: Option, - /// `oauth` 时的 token 端点和 client id。**refresh token 和 client - /// secret 永远不出这个进程** - #[serde(default, skip_serializing_if = "Option::is_none")] - pub oauth_endpoint: Option, + pub key: Option, + /// 密钥放在哪个请求头里发:`x-api-key` / `authorization` / `x-goog-api-key` + pub auth_header: String, + /// 其余请求头,按配置里的顺序 + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub headers: Vec, + /// OAuth 的 token 端点和 client id。**refresh token 和 client secret 永远不出这个进程** #[serde(default, skip_serializing_if = "Option::is_none")] - pub oauth_client_id: Option, + pub oauth: Option, /// 实际生效的协议:`anthropic` / `openai-chat` / `openai-responses` / /// `gemini`。猜不出来时为空 pub protocol: Option, @@ -600,6 +598,34 @@ pub struct ProviderView { pub pricing: Option, } +/// 一个可能是密钥的值给界面看的样子。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct SecretView { + /// 打过码的值,或者 `环境变量 ${NAME}` + pub display: String, + /// 整个值恰好是一个 `${NAME}` 时的变量名。变量名不是秘密,编辑时要回填 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub env: Option, +} + +/// 一行请求头给界面看的样子。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct HeaderView { + pub name: String, + /// **可能是密钥的值是打过码的**;公开的头(`anthropic-version` 之类)、 + /// 只由环境变量和占位符组成的值原样给 + pub value: String, + /// 值打过码。编辑时这一行不回填,留空表示保持原值 + pub masked: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct OAuthView { + pub endpoint: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_id: Option, +} + /// 配置里引用了某个上游的一处。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(tag = "kind", rename_all = "snake_case")] @@ -1049,9 +1075,16 @@ pub struct ProviderInput { /// 会把码写进配置 #[serde(default, skip_serializing_if = "Option::is_none")] pub base_url: Option, - /// 修改时**不给就是保持原样** —— 界面拿不到原值,也不该拿到 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub key: Option, + /// API 密钥。修改时默认保持原样 —— 界面拿不到原值,也不该拿到 + #[serde(default)] + pub key: SecretChange, + /// 请求头,按顺序。**整张表就是保存之后的样子**:没列出来的行被删掉, + /// 某一行不给 `value` 表示沿用同名那一行的原值 + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub headers: Vec, + /// OAuth。修改时默认保持原样 + #[serde(default)] + pub oauth: OAuthChange, /// `anthropic` / `openai-chat` / `openai-responses` / `gemini`。 /// 不给就按地址推断 #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1090,6 +1123,9 @@ pub struct ProviderInput { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProviderPreviewRequest { pub base_url: String, + /// 表单里选定的协议。不给就是「自动识别」。只影响 `auth_header` + #[serde(default, skip_serializing_if = "Option::is_none")] + pub protocol: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1101,6 +1137,9 @@ pub struct ProviderPreview { pub official: bool, /// 自动识别时发送前脱敏的类别 pub redact: Vec, + /// API 密钥放在哪个请求头里:`x-api-key` / `authorization` / `x-goog-api-key`。 + /// 选定了协议按选定的算,否则按推断出的 + pub auth_header: String, } /// 一个上游的模型清单。 @@ -1144,16 +1183,34 @@ fn fail_closed() -> String { "fail".to_string() } -/// 凭据的三种写法。 -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum CredentialInput { - /// 明文写进配置 - Key { value: String }, - /// 从环境变量读,只写变量名 - Env { var: String }, - /// OAuth,带自动刷新 - Oauth { +/// 一个密钥类的值怎么改。**三态**,因为视图里拿不到原值:不动就得有「保持原样」。 +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(tag = "mode", rename_all = "snake_case")] +pub enum SecretChange { + #[default] + Keep, + None, + /// 可以写 `${ENV}` 从环境变量读 + Set { + value: String, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct HeaderInput { + pub name: String, + /// 不给表示沿用同名那一行的原值 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] +#[serde(tag = "mode", rename_all = "snake_case")] +pub enum OAuthChange { + #[default] + Keep, + None, + Set { refresh: String, endpoint: String, #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs new file mode 100644 index 00000000..0a8134b1 --- /dev/null +++ b/crates/tw-config/src/credential.rs @@ -0,0 +1,679 @@ +//! 上游凭据:密钥、请求头、OAuth。 +//! +//! # 三样东西,各管一件事 +//! +//! - **`key`**:一把 API 密钥。放进哪个请求头由接口协议决定 —— Anthropic 是 +//! `x-api-key`,OpenAI 是 `Authorization: Bearer`,Gemini 是 `x-goog-api-key`。 +//! 绝大多数上游只要这一行,写配置的人不该为此去查每家把密钥放在哪儿。 +//! - **`headers`**:其余要发的请求头,或者完全自己决定凭据怎么发 —— 中转站自己的 +//! 鉴权头、`anthropic-version`、组织 ID。以前只能填一把密钥,一个要求 +//! `X-Relay-Token` 的中转站就接不进来。 +//! - **`oauth`**:access token 由 refresh token 换发。token 默认放进协议的鉴权头, +//! 也可以在 `headers` 里用 `{{access_token}}` 指定放在哪儿、怎么拼。 +//! +//! 值里可以写 `${ENV}` 从环境变量读;`{{client}}` 换成发起这次请求的那把网关 +//! 密钥的名字,给按调用方记账的中转站用。 +//! +//! **没有「跑一条命令拿密钥」这一类,而且不会有**:配置文件不该能执行程序 —— +//! 「配置被同步、被分享、被 AI 改」都是目标场景,那时抄一份配置就等于跑一段代码。 + +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +use crate::{Protocol, Provider}; + +/// `headers` 里换成 OAuth access token 的占位符。 +pub const ACCESS_TOKEN: &str = "{{access_token}}"; +/// `headers` 里换成网关密钥名字的占位符。 +pub const CLIENT: &str = "{{client}}"; + +/// 一个请求头最多几行、名字和值最长多少。**上限是给写错兜底的** —— 一个把整段 +/// PEM 贴进请求头的配置,该在加载时被拦下,而不是在上游那边变成一个 431。 +pub const MAX_HEADERS: usize = 32; +pub const MAX_HEADER_NAME: usize = 128; +pub const MAX_HEADER_VALUE: usize = 4096; + +/// 这些头由 HTTP 本身或网关管,**配置里写了只会把转发弄坏**:`host` 写错整个请求 +/// 发错地方,`content-length` 写错体被截断,`connection` 一类是逐跳的, +/// `proxy-authorization` 属于代理那一段。 +const RESERVED: &[&str] = &[ + "host", + "content-length", + "transfer-encoding", + "connection", + "keep-alive", + "te", + "trailer", + "upgrade", + "proxy-connection", + "proxy-authorization", +]; + +/// 可以带 `${ENV}` 的字符串:密钥、代理密码、请求头的值。 +/// +/// 明文写在配置里(不做 keychain)。配置文件里看不出 `${ENV}` 和明文的区别, +/// 也不该看出 —— 两种写法对读的人是一回事。 +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Secret(String); + +impl Secret { + pub fn new(s: impl Into) -> Self { + Self(s.into()) + } + + /// 写在配置里的原文。**可能是明文密钥** —— 只给要写回配置的调用方用。 + pub fn raw(&self) -> &str { + &self.0 + } + + /// 展开 `${ENV}` 之后的值。 + pub fn resolve(&self) -> Result { + Ok(tw_secret::expand_from_env(&self.0)?) + } + + /// 给人看的形态,**永远不含真实密钥**。 + pub fn describe(&self) -> String { + if self.0.contains("${") { + format!("环境变量 {}", self.0) + } else { + tw_secret::mask_secret(&self.0) + } + } + + /// 整个值恰好是一个 `${VAR}` 时,那个变量名。 + pub fn env_var(&self) -> Option<&str> { + let inner = self.0.trim().strip_prefix("${")?.strip_suffix('}')?; + let ok = !inner.is_empty() + && !inner.starts_with(|c: char| c.is_ascii_digit()) + && inner.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + ok.then_some(inner) + } + + pub fn is_blank(&self) -> bool { + self.0.trim().is_empty() + } +} + +impl From<&str> for Secret { + fn from(s: &str) -> Self { + Self(s.to_string()) + } +} + +impl From for Secret { + fn from(s: String) -> Self { + Self(s) + } +} + +impl Serialize for Secret { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.0) + } +} + +impl<'de> Deserialize<'de> for Secret { + fn deserialize>(d: D) -> Result { + struct V; + impl serde::de::Visitor<'_> for V { + type Value = Secret; + // **说清楚该怎么写。**serde 默认只会说「expected a string」,而写错成 + // `key: { oauth: ... }` 的人要知道的是 OAuth 放在哪儿 + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("一个字符串(可以带 ${VAR})。OAuth 凭据写在上游的 `oauth` 字段里") + } + fn visit_str(self, v: &str) -> Result { + Ok(Secret(v.to_string())) + } + // 纯数字的密钥(有些自建服务就是一串数字)不该因为 YAML 把它读成整数而失败 + fn visit_u64(self, v: u64) -> Result { + Ok(Secret(v.to_string())) + } + fn visit_i64(self, v: i64) -> Result { + Ok(Secret(v.to_string())) + } + fn visit_f64(self, v: f64) -> Result { + Ok(Secret(v.to_string())) + } + fn visit_bool(self, v: bool) -> Result { + Ok(Secret(v.to_string())) + } + } + d.deserialize_any(V) + } +} + +#[derive(Debug, thiserror::Error)] +pub enum SecretResolveError { + #[error(transparent)] + Env(#[from] tw_secret::SecretError), +} + +/// 一行请求头。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Header { + pub name: String, + pub value: Secret, +} + +/// 要发给上游的请求头,**按写的顺序**。 +/// +/// 配置里是一个映射(`名字: 值`),读起来和 HTTP 报文一个样子。不用 `HashMap` +/// 是因为顺序要保住 —— 往返一次把用户写的顺序打乱,是一次他没要求的改动。 +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Headers(Vec
); + +impl Headers { + pub fn new(headers: Vec
) -> Self { + Self(headers) + } + + pub fn iter(&self) -> std::slice::Iter<'_, Header> { + self.0.iter() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + /// 按名字找,**不分大小写** —— HTTP 头名本来就不分。 + pub fn get(&self, name: &str) -> Option<&Header> { + self.0.iter().find(|h| h.name.eq_ignore_ascii_case(name)) + } + + /// 有没有哪个值用到了这个占位符。 + pub fn uses(&self, placeholder: &str) -> bool { + self.0.iter().any(|h| h.value.raw().contains(placeholder)) + } +} + +impl Serialize for Headers { + fn serialize(&self, s: S) -> Result { + use serde::ser::SerializeMap; + let mut m = s.serialize_map(Some(self.0.len()))?; + for h in &self.0 { + m.serialize_entry(&h.name, &h.value)?; + } + m.end() + } +} + +impl<'de> Deserialize<'de> for Headers { + fn deserialize>(d: D) -> Result { + struct V; + impl<'de> serde::de::Visitor<'de> for V { + type Value = Headers; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("一组「请求头名: 值」") + } + fn visit_map>( + self, + mut m: A, + ) -> Result { + let mut out: Vec
= Vec::new(); + while let Some((name, value)) = m.next_entry::()? { + out.push(Header { name, value }); + } + Ok(Headers(out)) + } + } + d.deserialize_map(V) + } +} + +/// 协议的鉴权头:名字,和值前面要拼的东西。 +/// +/// **猜不出协议时按 Anthropic 放**:桌面版的主用例是 Claude Code,而中转站绝大多数 +/// 说的是 Anthropic 方言。模型目录那边按同一个默认算协议,两处不一致会让 +/// 「列出来了但发过去 401」变成可能。 +pub fn auth_header(protocol: Option) -> (&'static str, &'static str) { + match protocol { + Some(Protocol::Gemini) => ("x-goog-api-key", ""), + Some(Protocol::OpenaiChat) | Some(Protocol::OpenaiResponses) => { + ("authorization", "Bearer ") + } + Some(Protocol::Anthropic) | None => ("x-api-key", ""), + } +} + +/// 凭据写法上的问题。**每一条都指到具体的那一行**,而不是「凭据无效」。 +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CredentialError { + #[error("密钥是空的")] + EmptyKey, + #[error("`key` 和 `oauth` 只能写一个")] + KeyAndOauth, + #[error("oauth 的 refresh 和 endpoint 都不能为空")] + EmptyOauth, + #[error("Claude 订阅账号的登录凭据不能接入,请改用 Anthropic API 密钥")] + ClaudeSubscription, + #[error("Gemini CLI 的 Google 登录凭据不能接入,请改用 Gemini API 密钥")] + GoogleSubscription, + #[error("请求头最多 {MAX_HEADERS} 个")] + TooManyHeaders, + #[error( + "请求头名「{0}」不合法:只能由字母、数字和 - _ . ~ 组成,最长 {MAX_HEADER_NAME} 个字符" + )] + BadHeaderName(String), + #[error("请求头「{0}」由网关管理,不能在配置里设置")] + ReservedHeader(String), + #[error("请求头「{0}」写了两次(请求头名不分大小写)")] + DuplicateHeader(String), + #[error("请求头「{0}」的值不能包含换行,最长 {MAX_HEADER_VALUE} 个字符")] + BadHeaderValue(String), + #[error( + "请求头「{name}」里的 {placeholder} 认不出来。能用的只有 {{{{access_token}}}} 和 {{{{client}}}}" + )] + UnknownPlaceholder { name: String, placeholder: String }, + #[error("请求头「{0}」用了 {{{{access_token}}}},但这个上游没有配置 oauth")] + TokenWithoutOauth(String), + #[error("已经写了 `key`,请求头里不能再写「{0}」—— 密钥就是放在这个头里发的")] + KeyAndAuthHeader(String), + #[error( + "配置了 oauth 时 token 默认放在「{0}」里。要自己写这个头,请在值里用 {{{{access_token}}}} 指定 token 的位置" + )] + OauthAndAuthHeader(String), + #[error("取不到 OAuth access token")] + NoToken, + /// 环境变量没设之类。存成文字:这个错误要能比较,而底下那个类型不能 + #[error("{0}")] + Env(String), +} + +impl From for CredentialError { + fn from(e: SecretResolveError) -> Self { + CredentialError::Env(e.to_string()) + } +} + +fn host_of(url: &str) -> String { + let h = url.trim().to_ascii_lowercase(); + h.split("://") + .nth(1) + .unwrap_or(&h) + .split('/') + .next() + .unwrap_or("") + .split('@') + .next_back() + .unwrap_or("") + .split(':') + .next() + .unwrap_or("") + .to_string() +} + +fn is_or_under(host: &str, domain: &str) -> bool { + host == domain || host.ends_with(&format!(".{domain}")) +} + +/// 值里出现的全部 `{{…}}`。 +fn placeholders(value: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut rest = value; + while let Some(start) = rest.find("{{") { + match rest[start..].find("}}") { + Some(len) => { + out.push(&rest[start..start + len + 2]); + rest = &rest[start + len + 2..]; + } + None => break, + } + } + out +} + +impl Provider { + /// 这家的鉴权头:名字和值的前缀。 + pub fn auth_header(&self) -> (&'static str, &'static str) { + auth_header(self.effective_protocol()) + } + + /// 凭据写法对不对。**不联网,不读环境变量** —— 那是转发时的事。 + pub fn check_credential(&self) -> Result<(), CredentialError> { + if let Some(k) = &self.key + && k.is_blank() + { + return Err(CredentialError::EmptyKey); + } + if let Some(o) = &self.oauth { + if self.key.is_some() { + return Err(CredentialError::KeyAndOauth); + } + if o.refresh.trim().is_empty() || o.endpoint.trim().is_empty() { + return Err(CredentialError::EmptyOauth); + } + // **订阅账号的令牌不接。**Anthropic 规定 Claude 订阅的 OAuth 令牌不得由 + // 第三方产品收集、保存或转接;Gemini CLI 的条款把借用它的 Google 登录访问 + // 后端列为违规。能接的只是 OAuth2 保护的自建或企业服务 + let base = host_of(&self.base_url); + let token = host_of(&o.endpoint); + let claude = |h: &str| { + ["anthropic.com", "claude.ai", "claude.com"] + .iter() + .any(|d| is_or_under(h, d)) + }; + if claude(&base) || claude(&token) { + return Err(CredentialError::ClaudeSubscription); + } + if is_or_under(&base, "cloudcode-pa.googleapis.com") { + return Err(CredentialError::GoogleSubscription); + } + } + if self.headers.len() > MAX_HEADERS { + return Err(CredentialError::TooManyHeaders); + } + let (auth_name, _) = self.auth_header(); + let mut seen: Vec = Vec::new(); + for h in self.headers.iter() { + let name = h.name.trim(); + let valid = !name.is_empty() + && name.len() <= MAX_HEADER_NAME + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.~".contains(&b)); + if !valid { + return Err(CredentialError::BadHeaderName(h.name.clone())); + } + let lower = name.to_ascii_lowercase(); + if RESERVED.contains(&lower.as_str()) { + return Err(CredentialError::ReservedHeader(h.name.clone())); + } + if seen.contains(&lower) { + return Err(CredentialError::DuplicateHeader(h.name.clone())); + } + seen.push(lower.clone()); + let raw = h.value.raw(); + if raw.len() > MAX_HEADER_VALUE || raw.contains(['\r', '\n']) { + return Err(CredentialError::BadHeaderValue(h.name.clone())); + } + for p in placeholders(raw) { + if p != ACCESS_TOKEN && p != CLIENT { + return Err(CredentialError::UnknownPlaceholder { + name: h.name.clone(), + placeholder: p.to_string(), + }); + } + } + if raw.contains(ACCESS_TOKEN) && self.oauth.is_none() { + return Err(CredentialError::TokenWithoutOauth(h.name.clone())); + } + if lower == auth_name { + if self.key.is_some() { + return Err(CredentialError::KeyAndAuthHeader(h.name.clone())); + } + if self.oauth.is_some() && !self.headers.uses(ACCESS_TOKEN) { + return Err(CredentialError::OauthAndAuthHeader(h.name.clone())); + } + } + } + Ok(()) + } + + /// 要发给这家的全部请求头,值已经展开。 + /// + /// `access_token`:配了 oauth 时由调用方换好传进来(换 token 要联网,这里是同步的)。 + /// `client`:发起请求的那把网关密钥的名字,没有就换成空串。 + pub fn outbound_headers( + &self, + access_token: Option<&str>, + client: Option<&str>, + ) -> Result, CredentialError> { + let (auth_name, prefix) = self.auth_header(); + let mut out = Vec::with_capacity(self.headers.len() + 1); + if let Some(k) = &self.key { + out.push((auth_name.to_string(), format!("{prefix}{}", k.resolve()?))); + } + if self.oauth.is_some() && !self.headers.uses(ACCESS_TOKEN) { + let t = access_token.ok_or(CredentialError::NoToken)?; + out.push((auth_name.to_string(), format!("{prefix}{t}"))); + } + for h in self.headers.iter() { + let mut v = h.value.resolve()?; + if v.contains(ACCESS_TOKEN) { + v = v.replace(ACCESS_TOKEN, access_token.ok_or(CredentialError::NoToken)?); + } + if v.contains(CLIENT) { + v = v.replace(CLIENT, client.unwrap_or_default()); + } + out.push((h.name.trim().to_string(), v)); + } + Ok(out) + } + + /// 凭据的身份:地址或凭据变了,之前问到的模型清单就不再作数。 + /// + /// **OAuth 只看账号,不看 token**:refresh token 轮换一次就重问一遍,问到的是同一份清单。 + pub fn credential_identity(&self) -> String { + let mut s = String::new(); + if let Some(k) = &self.key { + s.push_str(k.raw()); + } + if let Some(o) = &self.oauth { + s.push_str(&format!( + "oauth|{}|{}", + o.endpoint, + o.client_id.as_deref().unwrap_or_default() + )); + } + for h in self.headers.iter() { + s.push('|'); + s.push_str(&h.name.to_ascii_lowercase()); + s.push('='); + s.push_str(h.value.raw()); + } + s + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::OAuth; + + fn p(yaml: &str) -> Provider { + serde_yaml_ng::from_str(yaml).unwrap() + } + + fn oauth() -> OAuth { + OAuth { + access: None, + refresh: "r".into(), + endpoint: "https://auth.example.com/token".into(), + client_id: None, + client_secret: None, + refresh_before: None, + } + } + + #[test] + fn a_key_goes_into_the_header_its_protocol_expects() { + let anthropic = p("name: a\nbase_url: https://api.anthropic.com\nkey: sk-a\n"); + assert_eq!( + anthropic.outbound_headers(None, None).unwrap(), + vec![("x-api-key".to_string(), "sk-a".to_string())] + ); + let openai = p("name: o\nbase_url: https://api.openai.com\nkey: sk-o\n"); + assert_eq!( + openai.outbound_headers(None, None).unwrap(), + vec![("authorization".to_string(), "Bearer sk-o".to_string())] + ); + let gemini = p("name: g\nbase_url: https://generativelanguage.googleapis.com\nkey: g-k\n"); + assert_eq!( + gemini.outbound_headers(None, None).unwrap(), + vec![("x-goog-api-key".to_string(), "g-k".to_string())] + ); + } + + #[test] + fn headers_keep_their_order_and_come_after_the_key() { + let x = p( + "name: r\nbase_url: https://relay.example\nkey: sk-r\nheaders:\n anthropic-version: 2023-06-01\n X-Tenant: team-{{client}}\n", + ); + assert_eq!( + x.outbound_headers(None, Some("laptop")).unwrap(), + vec![ + ("x-api-key".to_string(), "sk-r".to_string()), + ("anthropic-version".to_string(), "2023-06-01".to_string()), + ("X-Tenant".to_string(), "team-laptop".to_string()), + ] + ); + // 往返一次顺序不变 + let back = serde_yaml_ng::to_string(&x.headers).unwrap(); + assert!(back.find("anthropic-version").unwrap() < back.find("X-Tenant").unwrap()); + } + + #[test] + fn a_relay_can_take_its_credential_in_any_header() { + let x = p("name: r\nbase_url: https://relay.example\nheaders:\n X-Relay-Token: t-1\n"); + x.check_credential().unwrap(); + assert_eq!( + x.outbound_headers(None, None).unwrap(), + vec![("X-Relay-Token".to_string(), "t-1".to_string())] + ); + } + + #[test] + fn an_oauth_token_goes_into_the_auth_header_unless_a_header_says_where() { + let mut x = p("name: r\nbase_url: https://relay.example\nprotocol: openai-chat\n"); + x.oauth = Some(oauth()); + x.check_credential().unwrap(); + assert_eq!( + x.outbound_headers(Some("at-1"), None).unwrap(), + vec![("authorization".to_string(), "Bearer at-1".to_string())] + ); + x.headers = Headers::new(vec![Header { + name: "X-Token".into(), + value: Secret::new("Token {{access_token}}"), + }]); + x.check_credential().unwrap(); + assert_eq!( + x.outbound_headers(Some("at-2"), None).unwrap(), + vec![("X-Token".to_string(), "Token at-2".to_string())] + ); + } + + #[test] + fn writing_the_auth_header_twice_is_refused() { + let x = p( + "name: r\nbase_url: https://api.anthropic.com\nkey: sk-a\nheaders:\n X-Api-Key: sk-b\n", + ); + assert_eq!( + x.check_credential(), + Err(CredentialError::KeyAndAuthHeader("X-Api-Key".into())) + ); + } + + #[test] + fn headers_that_would_break_forwarding_are_refused() { + for (h, want) in [ + ("Host: x", CredentialError::ReservedHeader("Host".into())), + ( + "content-length: 3", + CredentialError::ReservedHeader("content-length".into()), + ), + ( + "\"bad name\": x", + CredentialError::BadHeaderName("bad name".into()), + ), + ] { + let x = p(&format!( + "name: r\nbase_url: https://relay.example\nheaders:\n {h}\n" + )); + assert_eq!(x.check_credential(), Err(want), "{h}"); + } + let dup = p("name: r\nbase_url: https://relay.example\nheaders:\n X-A: 1\n x-a: 2\n"); + assert_eq!( + dup.check_credential(), + Err(CredentialError::DuplicateHeader("x-a".into())) + ); + } + + #[test] + fn placeholders_are_checked() { + let unknown = + p("name: r\nbase_url: https://relay.example\nheaders:\n X-A: \"{{user}}\"\n"); + assert!(matches!( + unknown.check_credential(), + Err(CredentialError::UnknownPlaceholder { .. }) + )); + let no_oauth = + p("name: r\nbase_url: https://relay.example\nheaders:\n X-A: \"{{access_token}}\"\n"); + assert_eq!( + no_oauth.check_credential(), + Err(CredentialError::TokenWithoutOauth("X-A".into())) + ); + } + + #[test] + fn subscription_logins_cannot_be_configured_as_oauth() { + let mut claude = p("name: c\nbase_url: https://api.anthropic.com\n"); + claude.oauth = Some(oauth()); + assert_eq!( + claude.check_credential(), + Err(CredentialError::ClaudeSubscription) + ); + + // 地址是中转站,但 token 从 Claude 的授权端点换来 —— 一样不行 + let mut via_relay = p("name: r\nbase_url: https://relay.example\n"); + via_relay.oauth = Some(OAuth { + endpoint: "https://console.anthropic.com/v1/oauth/token".into(), + ..oauth() + }); + assert_eq!( + via_relay.check_credential(), + Err(CredentialError::ClaudeSubscription) + ); + + let mut gemini_cli = p("name: g\nbase_url: https://cloudcode-pa.googleapis.com\n"); + gemini_cli.oauth = Some(oauth()); + assert_eq!( + gemini_cli.check_credential(), + Err(CredentialError::GoogleSubscription) + ); + + // `evil.com/api.anthropic.com` 不是 Anthropic,也不该被当成它拦下或放过 + let mut lookalike = p("name: l\nbase_url: https://notanthropic.com/api.anthropic.com\n"); + lookalike.oauth = Some(oauth()); + lookalike.check_credential().unwrap(); + } + + #[test] + fn a_key_written_as_a_mapping_says_where_oauth_goes() { + let e = serde_yaml_ng::from_str::( + "name: a\nbase_url: https://x\nkey:\n oauth:\n refresh: r\n", + ) + .unwrap_err() + .to_string(); + assert!(e.contains("oauth"), "{e}"); + } + + #[test] + fn a_numeric_key_is_still_a_key() { + let x = p("name: a\nbase_url: https://x\nkey: 12345678\n"); + assert_eq!(x.key.unwrap().raw(), "12345678"); + } + + #[test] + fn env_vars_expand_inside_header_values() { + // SAFETY: 测试里设一个只有这个测试读的变量 + unsafe { std::env::set_var("TW_TEST_RELAY_TOKEN", "from-env") }; + let x = p( + "name: r\nbase_url: https://relay.example\nheaders:\n Authorization: Token ${TW_TEST_RELAY_TOKEN}\n", + ); + assert_eq!( + x.outbound_headers(None, None).unwrap(), + vec![("Authorization".to_string(), "Token from-env".to_string())] + ); + } + + #[test] + fn the_env_var_name_is_recognised_only_when_it_is_the_whole_value() { + assert_eq!(Secret::new("${RELAY_KEY}").env_var(), Some("RELAY_KEY")); + assert_eq!(Secret::new("Bearer ${RELAY_KEY}").env_var(), None); + assert_eq!(Secret::new("sk-plain").env_var(), None); + } +} diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 8b5bfd22..7754bf71 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; pub use tw_types::Limits; +pub mod credential; pub mod edit; pub mod history; mod init; @@ -19,6 +20,7 @@ pub mod store; mod validate; pub mod watch; +pub use credential::{CredentialError, Header, Headers, Secret, SecretResolveError, auth_header}; pub use init::{generate_initial, generate_key}; pub use proxy::{DIRECT, OnProxyFail, Proxy, ProxyKind, SYSTEM}; pub use validate::ValidationError; @@ -129,13 +131,15 @@ impl Default for Client { } } -/// 同上。`name` / `base_url` / `key` 空着的 provider 过不了校验。 +/// 同上。`name` / `base_url` 空着的 provider 过不了校验。 impl Default for Provider { fn default() -> Self { Self { name: String::new(), base_url: String::new(), - key: Secret::Literal(String::new()), + key: None, + headers: Headers::default(), + oauth: None, protocol: None, proxy: default_proxy(), on_proxy_fail: OnProxyFail::default(), @@ -358,39 +362,6 @@ pub struct Client { pub key: String, } -/// 密钥怎么来。 -/// -/// 两种形态:绝大多数人写一个字符串就完了(明确说了密钥就明文写在 -/// 配置里,不做 keychain),字符串里可以带 `${ENV}`;另一种是 OAuth, -/// 带自动刷新。 -/// -/// serde 的 untagged 让第一种是裸字符串 —— 配置文件里看不出 `${ENV}` -/// 和明文的区别,也不该看出。 -/// -/// **没有「跑一条命令拿密钥」这一类,而且不会有**:配置文件 -/// 不该能执行程序 —— 「配置被同步、被分享、被 AI 改」都是目标 -/// 场景,那时抄一份配置就等于跑一段代码。 -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum Secret { - /// 明文,或含 `${ENV}` 的字符串 - Literal(String), - /// OAuth,带自动刷新。 - OAuth { oauth: OAuth }, - /// 什么形状都没匹配上。**存在的唯一理由是报一句人话。** - /// - /// serde 的 untagged 在全部变体都不匹配时只会说 - /// 「data did not match any variant of untagged enum Secret」—— - /// 而这是配置里最重要的那个字段,那句话对着它等于什么都没说。 - /// 更糟的是它把**每一种**写错都塌成同一句:`oauth` 少写一个必填 - /// 字段和随手打错一个键名,报出来一模一样。 - /// - /// 有了这个兜底,`validate` 那一关才有机会拿着真实的值去说清楚 - /// 到底哪儿不对。**注意它必须排在最后** —— untagged 是按顺序试的。 - #[serde(skip_serializing)] - Unknown(serde_yaml_ng::Value), -} - /// OAuth 凭据(第 3 类)。 /// /// # 轮换 @@ -448,90 +419,22 @@ pub fn parse_duration_secs(s: &str) -> Option { num.trim().parse::().ok().map(|n| n * mult) } -impl Secret { - /// 拿到真正的密钥。 - /// - /// **同步**:展开 `${ENV}` 就到头了。OAuth 那一类要联网换 token, - /// 走不了这条路 —— 它返回 `NeedsRefresh`,由网关那边的异步路径处理。 - pub fn resolve(&self) -> Result { - match self { - Secret::Literal(s) => Ok(tw_secret::expand_from_env(s)?), - // **OAuth 走不了同步这条路**:换 token 是一次网络往返。 - // 调用方要么走异步那条(网关),要么把这一句原样说给用户听 - // (`twcore check`)—— 都比在这里编一个值好 - Secret::OAuth { .. } => Err(SecretResolveError::NeedsRefresh), - // 到不了这儿:校验那一关先把整份配置拒了 - Secret::Unknown(_) => Err(SecretResolveError::Unreadable), - } - } - - /// 是不是 OAuth。调用方据此决定走异步那条路。 - pub fn is_oauth(&self) -> bool { - matches!(self, Secret::OAuth { .. }) - } - - pub fn oauth(&self) -> Option<&OAuth> { - match self { - Secret::OAuth { oauth } => Some(oauth), - _ => None, - } - } - - /// 给人看的形态,**永远不含真实密钥**。 - pub fn describe(&self) -> String { - match self { - Secret::Literal(s) if s.contains("${") => format!("环境变量 {s}"), - Secret::Literal(s) => tw_secret::mask_secret(s), - // **不回显任何一段 token** —— refresh token 比 access token - // 更值钱,它换得出无数个 access - Secret::OAuth { oauth } => format!("OAuth({})", oauth.endpoint), - Secret::Unknown(_) => "(这个 key 读不懂)".to_string(), - } - } - - pub(crate) fn is_blank(&self) -> bool { - match self { - Secret::Literal(s) => s.trim().is_empty(), - Secret::OAuth { oauth } => { - oauth.refresh.trim().is_empty() || oauth.endpoint.trim().is_empty() - } - // 「读不懂」是另一回事,由 `BadKeyShape` 单独报 - Secret::Unknown(_) => false, - } - } -} - -/// 裸字符串是绝大多数人的写法,所以让它在 Rust 侧也是最省事的那个。 -impl From<&str> for Secret { - fn from(s: &str) -> Self { - Secret::Literal(s.to_string()) - } -} - -impl From for Secret { - fn from(s: String) -> Self { - Secret::Literal(s) - } -} - -#[derive(Debug, thiserror::Error)] -pub enum SecretResolveError { - #[error(transparent)] - Env(#[from] tw_secret::SecretError), - /// OAuth 凭据要去换 token,那是一次网络往返,同步这条路走不了。 - #[error("这是一个 OAuth 凭据,要联网换 token —— 网关起来之后才会去换")] - NeedsRefresh, - #[error("这个 key 的写法读不懂")] - Unreadable, -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Provider { pub name: String, pub base_url: String, - /// 明文、`${ENV}`、或 `{ oauth: {...} }`。**不做 keychain。** - pub key: Secret, + /// API 密钥,按接口协议放进它认的请求头。可以写 `${ENV}`。**不做 keychain。** + /// + /// 不需要密钥的上游(本地 Ollama)不写;密钥要放在别的头里时写在 `headers`。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub key: Option, + /// 其余要发的请求头,或者自己决定凭据怎么发。见 [`credential`]。 + #[serde(default, skip_serializing_if = "Headers::is_empty")] + pub headers: Headers, + /// OAuth:access token 由 refresh token 换发,默认放进协议的鉴权头。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub oauth: Option, /// 不写就从 base_url 猜(最小配置)。 #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option, @@ -796,11 +699,6 @@ impl Provider { Trust::Untrusted }) } - - /// 拿到真正的 key(展开 `${ENV}`)。 - pub fn resolved_key(&self) -> Result { - self.key.resolve() - } } /// 把 token 端点换发的新 refresh token 写回 config.yaml 的**那一个标量**。 @@ -831,7 +729,7 @@ pub fn patch_oauth_refresh( let idx = provider_index(text, provider).ok_or_else(|| RotateError::NoProvider { provider: provider.to_string(), })?; - let path = tw_yaml::path!["providers", idx, "key", "oauth", "refresh"]; + let path = tw_yaml::path!["providers", idx, "oauth", "refresh"]; // 先确认它在那儿。`set` 对不存在的路径行为是另一回事,而这里 // 「不在那儿」本身就是「别写」的理由 tw_yaml::find(text, &path).map_err(|source| RotateError::Shape { @@ -855,7 +753,7 @@ pub fn patch_oauth_refresh( .providers .iter() .find(|p| p.name == provider) - .and_then(|p| p.key.oauth()) + .and_then(|p| p.oauth.as_ref()) .is_some_and(|o| o.refresh == new_refresh); if !ok { return Err(RotateError::Broke { @@ -879,7 +777,7 @@ pub enum RotateError { /// **说清「形状不对」而不是「写失败」。**用户可能把凭据写成了 /// 别的形状(锚点、块标量),那时正确的动作是他自己去改, /// 而不是让我们猜。 - #[error("`{provider}` 的 key.oauth.refresh 不在预期的位置上:{source}")] + #[error("`{provider}` 的 oauth.refresh 不在预期的位置上:{source}")] Shape { provider: String, source: tw_yaml::PatchError, @@ -1022,7 +920,7 @@ providers: let p = Provider { name: "x".into(), base_url: "https://api.anthropic.com".into(), - key: Secret::Literal("k".into()), + key: Some(Secret::new("k")), protocol: Some(Protocol::OpenaiChat), ..Default::default() }; @@ -1078,17 +976,19 @@ providers: } #[test] - fn a_bare_string_key_still_parses_the_way_it_always_did() { - // untagged 的第一条:配置文件里绝大多数人写的还是一个裸字符串, - // 而且不该看出这里有个枚举。 + fn a_key_is_a_bare_string() { + // 配置文件里绝大多数人写的就是一个裸字符串 let cfg: Config = serde_yaml_ng::from_str(MINIMAL).unwrap(); - assert!(matches!(cfg.providers[0].key, Secret::Literal(ref s) if s == "sk-xxx")); + assert_eq!( + cfg.providers[0].key.as_ref().map(Secret::raw), + Some("sk-xxx") + ); } #[test] fn describe_never_leaks_a_literal_key() { // 这个方法会出现在 UI、日志、错误信息里。 - let s = Secret::Literal("sk-ant-api03-verysecretvalue".into()); + let s = Secret::new("sk-ant-api03-verysecretvalue"); let d = s.describe(); assert!(!d.contains("verysecret"), "{d}"); assert!(d.contains('…'), "{d}"); @@ -1097,10 +997,7 @@ providers: #[test] fn describe_shows_the_env_var_name_not_its_value() { // 变量名不是秘密,而它恰恰是用户排查时要看的东西。 - assert_eq!( - Secret::Literal("${MY_KEY}".into()).describe(), - "环境变量 ${MY_KEY}" - ); + assert_eq!(Secret::new("${MY_KEY}").describe(), "环境变量 ${MY_KEY}"); } #[test] @@ -1109,10 +1006,13 @@ providers: let p = Provider { name: "x".into(), base_url: "https://x".into(), - key: Secret::Literal("${TW_TEST_KEY}".into()), + key: Some(Secret::new("${TW_TEST_KEY}")), ..Default::default() }; - assert_eq!(p.resolved_key().unwrap(), "sk-from-env"); + assert_eq!( + p.outbound_headers(None, None).unwrap(), + vec![("x-api-key".to_string(), "sk-from-env".to_string())] + ); } } diff --git a/crates/tw-config/src/proxy.rs b/crates/tw-config/src/proxy.rs index 7bbfae59..3eac31d6 100644 --- a/crates/tw-config/src/proxy.rs +++ b/crates/tw-config/src/proxy.rs @@ -40,7 +40,7 @@ impl ProxyKind { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProxyAuth { pub user: String, - /// 支持 `${ENV}`,和 provider 的 key 同一套 + /// 支持 `${ENV}`,和上游的密钥同一套 pub pass: crate::Secret, } @@ -174,7 +174,7 @@ mod tests { // 而表现是一个费解的「代理地址不对」。 let auth = ProxyAuth { user: "alice".into(), - pass: crate::Secret::Literal("p@ss:w/rd".into()), + pass: crate::Secret::new("p@ss:w/rd"), }; let url = p(ProxyKind::Http, Some(auth)).url().unwrap(); assert!(!url.contains("p@ss"), "{url}"); @@ -188,7 +188,7 @@ mod tests { unsafe { std::env::set_var("TW_TEST_PROXY_PASS", "hunter2") }; let auth = ProxyAuth { user: "alice".into(), - pass: crate::Secret::Literal("${TW_TEST_PROXY_PASS}".into()), + pass: crate::Secret::new("${TW_TEST_PROXY_PASS}"), }; assert!( p(ProxyKind::Socks5h, Some(auth)) diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 450229d1..b0d8f1f1 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -22,18 +22,17 @@ pub enum ValidationError { BadBaseUrl { name: String, url: String }, #[error("client `{name}` 的密钥是空的")] EmptyKey { name: String }, - #[error( - "provider `{name}` 的密钥是空的。要连不需要密钥的上游(比如本地 Ollama),写一个占位值即可。" - )] - EmptyProviderKey { name: String }, #[error("路由配置有问题:{0}")] Routing(#[from] tw_engine::RouteError), #[error("`{0}` 既是 provider 名又是组名。规则里的 `to` 会指向哪个是不确定的,改掉其中一个。")] NameCollision(String), #[error("listen.gateway.allow_from 里的 `{entry}` 写错了:{reason}")] BadCidr { entry: String, reason: String }, - #[error("provider `{name}` 的 key 写法读不懂:{why}")] - BadKeyShape { name: String, why: String }, + #[error("上游「{name}」的凭据:{source}")] + Credential { + name: String, + source: crate::CredentialError, + }, #[error("{0}")] Pricing(#[from] tw_pricing::SheetError), #[error("上游「{provider}」选的价目表「{sheet}」不存在")] @@ -46,36 +45,6 @@ pub enum ValidationError { BlankModelsOnly { name: String }, } -/// `key:` 到底哪儿写错了。 -/// -/// **有 `oauth:` 的时候要让 serde 自己说。**「unknown field `refresh_befor`, -/// expected one of ...」比我们能补的任何一句话都准(那条,只是它 -/// 在 untagged 枚举上失效了,得手动把那条路走一遍)。 -fn explain_key(v: &serde_yaml_ng::Value) -> String { - if let Some(inner) = v.get("oauth") { - return match serde_yaml_ng::from_value::(inner.clone()) { - Ok(_) => "oauth 里面看起来是对的,但整体没匹配上".to_string(), - Err(e) => format!("oauth 里 {e}"), - }; - } - let keys: Vec = v - .as_mapping() - .map(|m| { - m.keys() - .filter_map(|k| k.as_str().map(|s| s.to_string())) - .collect() - }) - .unwrap_or_default(); - if keys.is_empty() { - "要么直接写一个字符串(可以带 ${VAR}),要么写 { oauth: {...} }".to_string() - } else { - format!( - "认不出 `{}`。key 要么是一个字符串(可以带 ${{VAR}}),要么是 {{ oauth: {{...}} }}", - keys.join("`、`") - ) - } -} - pub fn validate(cfg: &Config) -> Result<(), ValidationError> { // 版本检查放在最前面:一个来自更新版本的配置,我们对它的任何 // 其他判断都不作数(「schema 太新」)。 @@ -110,21 +79,11 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { url: p.base_url.clone(), }); } - // **`key:` 写错时要说清楚哪儿错了。**serde 的 untagged 在全部 - // 变体都不匹配时只会说「data did not match any variant」,而这是 - // 配置里最重要的那个字段 —— 那句话对着它等于什么都没说,还把 - // 每一种写错都塌成同一句。 - if let crate::Secret::Unknown(v) = &p.key { - return Err(ValidationError::BadKeyShape { - name: p.name.clone(), - why: explain_key(v), - }); - } - if p.key.is_blank() { - return Err(ValidationError::EmptyProviderKey { + p.check_credential() + .map_err(|source| ValidationError::Credential { name: p.name.clone(), - }); - } + source, + })?; // **空范围不是「全部」,也不是一个合理的「停用」。**两种读法各有 // 人会当真,而停用有自己的开关 if let Some(only) = &p.models_only { @@ -247,7 +206,7 @@ mod tests { Provider { name: name.into(), base_url: url.into(), - key: crate::Secret::Literal("sk-x".into()), + key: Some(crate::Secret::new("sk-x")), protocol: None, ..Default::default() } @@ -281,32 +240,46 @@ mod tests { } #[test] - fn a_key_written_in_a_shape_we_do_not_accept_says_which_shape_it_saw() { - // untagged 枚举全部不匹配时,serde 只会说「data did not match any - // variant」—— 而这是配置里最重要的那个字段 + fn a_key_written_as_a_mapping_says_what_to_write_instead() { let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n key:\n whatever: 1\n"; let e = crate::try_parse(y).unwrap_err().message; - assert!(e.contains("whatever"), "没说看见了什么:{e}"); - assert!(e.contains("oauth"), "没说该写成什么:{e}"); + assert!(e.contains("字符串"), "没说该写成什么:{e}"); } #[test] - fn an_oauth_key_with_a_typo_lets_serde_say_which_field() { - // **serde 自己的话比我们能补的任何一句都准** —— - // 只是在 untagged 枚举上它不出声,得手动把那条路再走一遍 - let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n key:\n oauth:\n refresh: r\n endpoint: https://a/token\n refresh_befor: 5m\n"; + fn an_oauth_typo_lets_serde_say_which_field() { + // **serde 自己的话比我们能补的任何一句都准** + let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n oauth:\n refresh: r\n endpoint: https://a/token\n refresh_befor: 5m\n"; let e = crate::try_parse(y).unwrap_err().message; assert!(e.contains("refresh_befor"), "{e}"); assert!(e.contains("refresh_before"), "没提示正确的拼法:{e}"); } #[test] - fn an_oauth_key_missing_a_required_field_says_which_one() { - let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n key:\n oauth:\n endpoint: https://a/token\n"; + fn an_oauth_missing_a_required_field_says_which_one() { + let y = "version: 1\nclients:\n - name: c\n key: tw-k\nproviders:\n - name: p\n base_url: https://api.example.com\n oauth:\n endpoint: https://a/token\n"; let e = crate::try_parse(y).unwrap_err().message; assert!(e.contains("refresh"), "{e}"); } + #[test] + fn a_credential_problem_names_the_upstream() { + let mut x = p("r", "https://relay.example"); + x.key = Some(crate::Secret::new(" ")); + let e = validate(&cfg(vec![c("d", "tw-1")], vec![x])) + .unwrap_err() + .to_string(); + assert!(e.contains("「r」"), "{e}"); + } + + #[test] + fn an_upstream_without_any_credential_is_valid() { + // 本地 Ollama 这类不要密钥。以前要写一个占位值,那是在让配置说谎 + let mut x = p("ollama", "http://127.0.0.1:11434"); + x.key = None; + assert!(validate(&cfg(vec![c("d", "tw-1")], vec![x])).is_ok()); + } + #[test] fn a_config_with_no_providers_is_valid_because_the_app_must_still_open() { // 首次运行生成的就是这种配置。如果它过不了校验,core 起不来, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 43a4d42c..c0b1292c 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -334,6 +334,26 @@ async fn overview(State(s): State) -> Json { }) } +/// 一行请求头给界面看的样子。 +/// +/// **不知道是不是密钥的,一律按密钥打码。**请求头名说明不了什么 —— +/// `X-Relay-Token` 和 `X-Tenant` 看不出哪个是秘密。原样给的只有两类:已知 +/// 公开的头(`anthropic-version` 之类),和只由环境变量、占位符加上一个短前缀 +/// 组成的值(`Bearer ${RELAY_TOKEN}`)—— 那里面没有秘密可泄。 +fn header_view(h: &tw_config::Header) -> tw_api::HeaderView { + let raw = h.value.raw(); + let masked = !(tw_secret::is_public_header(&h.name) || tw_secret::is_reference_only(raw)); + tw_api::HeaderView { + name: h.name.clone(), + value: if masked { + tw_secret::mask_secret(raw) + } else { + raw.to_string() + }, + masked, + } +} + /// 一个上游给界面看的样子。**任何一个字段都不带密钥原文。** fn provider_view( s: &ControlState, @@ -341,31 +361,20 @@ fn provider_view( p: &tw_config::Provider, ) -> tw_api::ProviderView { let base_url = tw_secret::redact_url(&p.base_url); - // `${NAME}` 整个是一个变量时才算「环境变量」。混着明文的写法 - // (`sk-${SUFFIX}`)界面编辑不了,按明文密钥显示,改的时候整个替换 - let env = match &p.key { - tw_config::Secret::Literal(v) => v - .strip_prefix("${") - .and_then(|r| r.strip_suffix('}')) - .filter(|n| !n.is_empty() && !n.contains(['$', '{', '}'])) - .map(str::to_string), - _ => None, - }; - let oauth = p.key.oauth(); tw_api::ProviderView { name: p.name.clone(), base_url_masked: base_url != p.base_url, base_url, - key_source: p.key.describe(), - key_kind: match (&p.key, &env) { - (tw_config::Secret::OAuth { .. }, _) => "oauth", - (_, Some(_)) => "env", - _ => "key", - } - .to_string(), - key_env: env, - oauth_endpoint: oauth.map(|o| o.endpoint.clone()), - oauth_client_id: oauth.and_then(|o| o.client_id.clone()), + key: p.key.as_ref().map(|k| tw_api::SecretView { + display: k.describe(), + env: k.env_var().map(str::to_string), + }), + auth_header: p.auth_header().0.to_string(), + headers: p.headers.iter().map(header_view).collect(), + oauth: p.oauth.as_ref().map(|o| tw_api::OAuthView { + endpoint: o.endpoint.clone(), + client_id: o.client_id.clone(), + }), protocol: p.effective_protocol().map(|x| x.slug().to_string()), protocol_explicit: p.protocol.is_some(), proxy: p.proxy.clone(), @@ -728,8 +737,8 @@ async fn speed_run( // OAuth 那类要联网换 token,所以走网关那条 async 的路。 // **用这一家自己的 client** —— 换 token 要走它的代理。 let pk_http = s.gateway.client_for(&p.name); - let key = match s.gateway.key_for(p, &pk_http).await { - Ok(k) => k, + let headers = match s.gateway.headers_for(p, &pk_http, None).await { + Ok(h) => h, Err(e) => { out.push(tw_api::SpeedResult { provider: p.name.clone(), @@ -750,7 +759,7 @@ async fn speed_run( let r = tw_gateway::l3::run( &pk_http, &p.base_url, - &key, + &headers, p.effective_protocol(), &p.name, &req.model, diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index 0bbb9dd8..5829e7a2 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -165,12 +165,16 @@ pub async fn run( // OAuth 要联网换 token。重放不经过数据面,但**凭据这一层 // 必须走同一条路** —— 否则一个 OAuth 上游在重放里永远是「密钥取不到」 let pk_http = s.gateway.client_for(&provider.name); - let key = s.gateway.key_for(provider, &pk_http).await.map_err(|e| { - fail( - StatusCode::BAD_REQUEST, - format!("`{}` 的密钥取不到:{e}", provider.name), - ) - })?; + let headers = s + .gateway + .headers_for(provider, &pk_http, None) + .await + .map_err(|e| { + fail( + StatusCode::BAD_REQUEST, + format!("`{}` 的凭据取不到:{e}", provider.name), + ) + })?; // **脱敏照做。**重放不经过数据面的管线,少了这一行,一条本来会被 // 脱敏的请求会因为「重放」这个动作把密钥原样发给中转站 @@ -185,7 +189,7 @@ pub async fn run( let http = s.http().clone(); let started = Instant::now(); let mut r = http.post(&url).header("content-type", "application/json"); - r = tw_gateway::forward::apply_credential(r, provider.effective_protocol(), &key); + r = tw_gateway::forward::apply_headers(r, &headers); let resp = r.body(body).send().await.map_err(|e| { fail( StatusCode::BAD_GATEWAY, diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 0bb88e60..7617f5c7 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -113,12 +113,22 @@ async fn delete_provider( /// 这个选项说清楚它此刻会选成什么 —— 这套判断只在 core 里写一遍。 async fn preview_provider( Json(req): Json, -) -> Json { +) -> Result, Fail> { let p = tw_config::Provider { base_url: req.base_url.trim().to_string(), ..Default::default() }; - Json(tw_api::ProviderPreview { + // 选定了协议,密钥就按选定的协议放;「自动识别」那一项要说的仍是按地址推断的结果 + let chosen = tw_config::Provider { + protocol: req + .protocol + .as_deref() + .map(|v| slug("接口协议", v)) + .transpose() + .map_err(|e| fail(StatusCode::BAD_REQUEST, e))?, + ..p.clone() + }; + Ok(Json(tw_api::ProviderPreview { protocol: p.effective_protocol().map(|x| x.slug().to_string()), official: p.is_official_endpoint(), redact: p @@ -126,7 +136,8 @@ async fn preview_provider( .iter() .map(|k| k.slug().to_string()) .collect(), - }) + auth_header: chosen.auth_header().0.to_string(), + })) } /// 检测一个上游,**不保存**。 @@ -162,27 +173,35 @@ async fn test_provider( Ok(h) => h, Err(e) => return Ok(Json(failed(e.message))), }; - let key = match (&req.provider.key, existing) { - // 凭据没改:走网关那条路。OAuth 的缓存和轮换写回都在那儿 - (None, Some(e)) => s.gateway.key_for(e, &http).await, - (Some(tw_api::CredentialInput::Oauth { access, .. }), _) => { + // OAuth 的 token:新填的那份只能用现成的 access token;沿用原来那份时走网关, + // **按原来的名字换** —— 缓存和轮换写回都认名字,而表单里可能刚改了名 + let token = match (&req.provider.oauth, existing) { + (tw_api::OAuthChange::Set { access, .. }, _) => { // **不拿 refresh token 去换。**服务端可能当场作废旧的那把,而 // 新换到的那把还没有地方写 —— 检测一次就把凭据弄坏了 - match access.as_deref().filter(|a| !a.is_empty()) { - Some(a) => Ok(a.to_string()), - None => Err( - "OAuth 凭据需要保存后才能检测。要现在检测,请同时填写 access token。" - .to_string(), - ), + match access.as_deref().map(str::trim).filter(|a| !a.is_empty()) { + Some(a) => Some(a.to_string()), + None => { + return Ok(Json(failed( + "OAuth 凭据需要保存后才能检测。要现在检测,请同时填写 access token。" + .to_string(), + ))); + } + } + } + (tw_api::OAuthChange::Keep, Some(e)) if e.oauth.is_some() && p.oauth.is_some() => { + match s.gateway.oauth_token_for(e, &http).await { + Ok(t) => Some(t), + Err(e) => return Ok(Json(failed(e))), } } - _ => p.resolved_key().map_err(|e| e.to_string()), + _ => None, }; - let key = match key { - Ok(k) => k, - Err(e) => return Ok(Json(failed(e))), + let headers = match p.outbound_headers(token.as_deref(), None) { + Ok(h) => h, + Err(e) => return Ok(Json(failed(e.to_string()))), }; - let r = tw_gateway::probe(&http, &p.base_url, &key, protocol).await; + let r = tw_gateway::probe(&http, &p.base_url, &headers, protocol).await; Ok(Json(tw_api::ProviderTestResult { ok: r.ok, protocol: protocol.map(|x| x.slug().to_string()), @@ -268,14 +287,70 @@ fn to_provider( (None, None) => return Err("接口地址不能为空".to_string()), }; let key = match (&input.key, existing) { - (Some(c), _) => credential(c)?, - (None, Some(e)) => e.key.clone(), - (None, None) => return Err("缺少凭据".to_string()), + (tw_api::SecretChange::Keep, Some(e)) => e.key.clone(), + (tw_api::SecretChange::Keep, None) | (tw_api::SecretChange::None, _) => None, + (tw_api::SecretChange::Set { value }, _) => { + let v = value.trim(); + if v.is_empty() { + return Err("密钥不能为空".to_string()); + } + Some(tw_config::Secret::new(v)) + } + }; + let headers = input + .headers + .iter() + .map(|h| { + let name = h.name.trim().to_string(); + let value = match &h.value { + Some(v) => tw_config::Secret::new(v.trim()), + // 沿用原值:界面拿不到打码之前的值,这一行不动就不传 + None => existing + .and_then(|e| e.headers.get(&name)) + .map(|x| x.value.clone()) + .ok_or_else(|| format!("请求头「{name}」缺少值"))?, + }; + Ok(tw_config::Header { name, value }) + }) + .collect::, String>>()?; + let oauth = match (&input.oauth, existing) { + (tw_api::OAuthChange::Keep, Some(e)) => e.oauth.clone(), + (tw_api::OAuthChange::Keep, None) | (tw_api::OAuthChange::None, _) => None, + ( + tw_api::OAuthChange::Set { + refresh, + endpoint, + client_id, + client_secret, + access, + }, + _, + ) => { + let nonempty = |v: &Option| { + v.as_deref() + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(str::to_string) + }; + Some(tw_config::OAuth { + access: nonempty(access), + refresh: refresh.trim().to_string(), + endpoint: endpoint.trim().to_string(), + client_id: nonempty(client_id), + client_secret: nonempty(client_secret), + // 沿用原来写的提前量:界面不编辑它 + refresh_before: existing + .and_then(|e| e.oauth.as_ref()) + .and_then(|o| o.refresh_before.clone()), + }) + } }; - Ok(tw_config::Provider { + let provider = tw_config::Provider { name, base_url, key, + headers: tw_config::Headers::new(headers), + oauth, protocol: input .protocol .as_deref() @@ -314,61 +389,11 @@ fn to_provider( .map(|ms| ms.iter().map(|m| m.trim().to_string()).collect::>()), pricing: input.pricing.clone(), disabled: input.disabled, - }) -} - -fn credential(c: &tw_api::CredentialInput) -> Result { - use tw_api::CredentialInput::*; - Ok(match c { - Key { value } => { - let v = value.trim(); - if v.is_empty() { - return Err("密钥不能为空".to_string()); - } - // `${` 在配置里表示「从环境变量读」。一把真的含 `${` 的明文密钥 - // 写进去会被当成变量展开 —— 说清楚,而不是写一个读回来就变了的值 - if v.contains("${") { - return Err("密钥里不能出现 `${`。要从环境变量读,请选择「环境变量」".to_string()); - } - tw_config::Secret::Literal(v.to_string()) - } - Env { var } => { - let v = var.trim(); - let ok = !v.is_empty() - && !v.starts_with(|c: char| c.is_ascii_digit()) - && v.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); - if !ok { - return Err(format!( - "环境变量名「{v}」不合法:只能由字母、数字和下划线组成,且不以数字开头" - )); - } - tw_config::Secret::Literal(format!("${{{v}}}")) - } - Oauth { - refresh, - endpoint, - client_id, - client_secret, - access, - } => { - let nonempty = |v: &Option| { - v.as_deref() - .map(str::trim) - .filter(|x| !x.is_empty()) - .map(str::to_string) - }; - tw_config::Secret::OAuth { - oauth: tw_config::OAuth { - access: nonempty(access), - refresh: refresh.trim().to_string(), - endpoint: endpoint.trim().to_string(), - client_id: nonempty(client_id), - client_secret: nonempty(client_secret), - refresh_before: None, - }, - } - } - }) + }; + // **保存和检测之前就说清楚凭据写法哪儿不对**,而不是等整份配置校验时 + // 报一条指着 YAML 的错误 + provider.check_credential().map_err(|e| e.to_string())?; + Ok(provider) } // ─────────────────────────────────────────────────────────── 代理 @@ -488,7 +513,7 @@ fn to_proxy( } Some(tw_config::proxy::ProxyAuth { user: user.to_string(), - pass: tw_config::Secret::Literal(pass.clone()), + pass: tw_config::Secret::new(pass.clone()), }) } }; diff --git a/crates/tw-control/src/rotation.rs b/crates/tw-control/src/rotation.rs index b8c1447b..07d5a8ff 100644 --- a/crates/tw-control/src/rotation.rs +++ b/crates/tw-control/src/rotation.rs @@ -116,11 +116,10 @@ providers: key: sk-ant-literal - name: oauth-家 base_url: https://api.example.com - key: - oauth: - refresh: rt-OLD-ONE # 这个会被换掉 - endpoint: https://auth.example.com/token - refresh_before: 5m + oauth: + refresh: rt-OLD-ONE # 这个会被换掉 + endpoint: https://auth.example.com/token + refresh_before: 5m "#; #[test] @@ -151,7 +150,7 @@ providers: } #[test] - fn a_key_that_is_not_oauth_shaped_is_refused_rather_than_rewritten() { + fn a_provider_without_oauth_is_refused_rather_than_rewritten() { let e = tw_config::patch_oauth_refresh(CFG, "官方", "rt-NEW").unwrap_err(); assert!(e.to_string().contains("不在预期的位置上"), "{e}"); } @@ -176,7 +175,7 @@ providers: .providers .iter() .find(|p| p.name == "oauth-家") - .and_then(|p| p.key.oauth()) + .and_then(|p| p.oauth.as_ref()) .unwrap(); assert_eq!(got.refresh, t, "读回来不是原值:{out}"); } diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index 7470d785..c6306aac 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -293,6 +293,28 @@ async fn an_address_being_typed_previews_what_automatic_detection_will_pick() { assert_eq!(v["protocol"], "anthropic"); assert_eq!(v["official"], true); assert_eq!(v["redact"], serde_json::json!([]), "官方端点不脱敏"); + assert_eq!(v["auth_header"], "x-api-key"); + + // 选了协议:密钥按选的协议放,「自动识别」那一项仍然说按地址推断的结果 + let (st, v) = call( + &b.app, + "POST", + "/providers/preview", + serde_json::json!({ "base_url": "https://api.anthropic.com", "protocol": "openai-chat" }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["protocol"], "anthropic"); + assert_eq!(v["auth_header"], "authorization"); + + let (st, _) = call( + &b.app, + "POST", + "/providers/preview", + serde_json::json!({ "base_url": "https://api.anthropic.com", "protocol": "grpc" }), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); let (_, v) = call( &b.app, diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 2228cb28..674a909f 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -99,7 +99,7 @@ fn relay(name: &str) -> serde_json::Value { serde_json::json!({ "name": name, "base_url": "https://relay.example", - "key": { "kind": "key", "value": "sk-relay#1: x" }, + "key": { "mode": "set", "value": "sk-relay#1: x" }, "protocol": "anthropic", }) } @@ -120,7 +120,10 @@ async fn a_new_upstream_lands_with_its_key_intact_and_every_comment_kept() { assert_eq!(st, StatusCode::OK, "{body}"); let cfg = b.parsed(); let p = cfg.providers.iter().find(|p| p.name == "relay").unwrap(); - assert!(matches!(&p.key, tw_config::Secret::Literal(k) if k == "sk-relay#1: x")); + assert_eq!( + p.key.as_ref().map(tw_config::Secret::raw), + Some("sk-relay#1: x") + ); assert_eq!(p.protocol, Some(tw_config::Protocol::Anthropic)); let file = b.file(); assert!(file.contains("# 这家是官方的,别动"), "{file}"); @@ -227,32 +230,99 @@ async fn a_duplicate_name_and_a_stale_version_are_both_conflicts() { } #[tokio::test] -async fn the_overview_says_what_kind_of_credential_it_is_and_never_the_value() { +async fn the_overview_says_where_a_credential_comes_from_and_never_the_value() { let b = bed(BASE); - call( + let (st, body) = call( &b.app, "POST", "/providers", serde_json::json!({ "provider": { "name": "env", "base_url": "https://relay.example", - "key": { "kind": "env", "var": "RELAY_KEY" }, + "key": { "mode": "set", "value": "${RELAY_KEY}" }, + "headers": [ + { "name": "X-Relay-Tenant", "value": "tenant-verysecretvalue" }, + { "name": "anthropic-version", "value": "2023-06-01" }, + ], }}), ) .await; + assert_eq!(st, StatusCode::OK, "{body}"); let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; assert!(!body.contains("sk-official"), "{body}"); + assert!(!body.contains("tenant-verysecretvalue"), "{body}"); let v = json(&body); let providers = v["providers"].as_array().unwrap(); let official = &providers[0]; - assert_eq!(official["key_kind"], "key"); + assert!( + official["key"]["display"].as_str().unwrap().contains('…'), + "{body}" + ); + assert_eq!(official["auth_header"], "x-api-key"); assert_eq!(official["protocol"], "anthropic"); assert_eq!(official["protocol_explicit"], false); assert_eq!(official["trust"], "official"); assert_eq!(official["references"][0]["kind"], "group"); let env = providers.iter().find(|p| p["name"] == "env").unwrap(); - assert_eq!(env["key_kind"], "env"); - assert_eq!(env["key_env"], "RELAY_KEY"); + assert_eq!(env["key"]["env"], "RELAY_KEY"); + assert_eq!(env["headers"][0]["name"], "X-Relay-Tenant"); + assert_eq!(env["headers"][0]["masked"], true); + assert_eq!(env["headers"][1]["value"], "2023-06-01"); + assert_eq!(env["headers"][1]["masked"], false); +} + +#[tokio::test] +async fn a_header_saved_without_a_value_keeps_the_stored_one() { + // 视图里的值是打过码的,界面不回填 —— 不改的那一行就不带值 + let b = bed(BASE); + call( + &b.app, + "POST", + "/providers", + serde_json::json!({ "provider": { + "name": "relay", + "base_url": "https://relay.example", + "headers": [{ "name": "X-Relay-Token", "value": "rt-1" }], + }}), + ) + .await; + let (st, body) = call( + &b.app, + "PUT", + "/providers/relay", + serde_json::json!({ "provider": { + "name": "relay", + "headers": [ + { "name": "X-Relay-Token" }, + { "name": "X-Extra", "value": "e" }, + ], + }}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + let cfg = b.parsed(); + let p = cfg.providers.iter().find(|p| p.name == "relay").unwrap(); + assert_eq!(p.headers.get("x-relay-token").unwrap().value.raw(), "rt-1"); + assert_eq!(p.headers.get("X-Extra").unwrap().value.raw(), "e"); +} + +#[tokio::test] +async fn a_claude_subscription_login_cannot_be_saved_as_oauth() { + let b = bed(BASE); + let (st, body) = call( + &b.app, + "POST", + "/providers", + serde_json::json!({ "provider": { + "name": "max", + "base_url": "https://api.anthropic.com", + "oauth": { "mode": "set", "refresh": "rt", "endpoint": "https://console.anthropic.com/v1/oauth/token" }, + }}), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + assert!(body.contains("Claude 订阅账号"), "{body}"); + assert_eq!(b.parsed().providers.len(), 1); } // ─────────────────────────────────────────────────────────── 代理 @@ -286,7 +356,7 @@ async fn a_proxy_password_is_written_intact_kept_on_edit_and_never_shown() { let cfg = b.parsed(); let auth = cfg.proxies[0].auth.as_ref().expect("没动认证,认证不该丢"); assert_eq!(auth.user, "svc"); - assert!(matches!(&auth.pass, tw_config::Secret::Literal(p) if p == "p@ss #1: x")); + assert_eq!(auth.pass.raw(), "p@ss #1: x"); assert_eq!(cfg.proxies[0].addr, "10.0.0.2:8080"); let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; @@ -379,7 +449,7 @@ async fn testing_an_unsaved_upstream_uses_the_protocol_and_lists_the_models() { serde_json::json!({ "provider": { "name": "relay", "base_url": format!("http://{up}"), - "key": { "kind": "key", "value": "sk-good" }, + "key": { "mode": "set", "value": "sk-good" }, "protocol": "anthropic", }}), ) @@ -419,9 +489,9 @@ async fn an_unsaved_oauth_credential_is_not_refreshed_just_to_test_it() { "POST", "/providers/test", serde_json::json!({ "provider": { - "name": "max", - "base_url": "https://api.anthropic.com", - "key": { "kind": "oauth", "refresh": "rt", "endpoint": "https://auth.example/token" }, + "name": "corp-llm", + "base_url": "https://llm.corp.example", + "oauth": { "mode": "set", "refresh": "rt", "endpoint": "https://auth.example/token" }, }}), ) .await; diff --git a/crates/tw-engine/src/catalog.rs b/crates/tw-engine/src/catalog.rs index 27721841..53da1f3d 100644 --- a/crates/tw-engine/src/catalog.rs +++ b/crates/tw-engine/src/catalog.rs @@ -113,15 +113,21 @@ impl Catalog { /// - `None`(不写)→ 只按方言过滤。默认,绝大多数情况 /// - `Some(非空)` → 在方言过滤的基础上再按 glob 保留 /// - `Some(空)` → **一个都不给**。「临时禁用这个客户端」的正当用法 - pub fn resolve_allowed(&self, dialect: Option<&str>, allow: Option<&[String]>) -> Vec { + pub fn resolve_allowed( + &self, + protocols: Option<&[&str]>, + allow: Option<&[String]>, + ) -> Vec { let by_dialect: BTreeSet<&str> = self .by_model .iter() - .filter(|(_, provs)| match dialect { - // 至少有一家说这个方言的上游能提供它 - Some(d) => provs - .iter() - .any(|p| self.protocols.get(p).map(|x| x.as_str()) == Some(d)), + .filter(|(_, provs)| match protocols { + // 至少有一家能服务这种请求的上游提供它(同协议,或者有现成转换) + Some(ok) => provs.iter().any(|p| { + self.protocols + .get(p) + .is_some_and(|x| ok.contains(&x.as_str())) + }), // 不知道方言就不过滤 —— 猜错了会把用户能用的模型藏起来, // 而那比多列几个更难查。 None => true, @@ -140,8 +146,13 @@ impl Catalog { } /// 这个客户端能用这个模型吗。和上面同一套逻辑。 - pub fn admits(&self, model: &str, dialect: Option<&str>, allow: Option<&[String]>) -> bool { - self.resolve_allowed(dialect, allow) + pub fn admits( + &self, + model: &str, + protocols: Option<&[&str]>, + allow: Option<&[String]>, + ) -> bool { + self.resolve_allowed(protocols, allow) .iter() .any(|m| m == model) } @@ -220,11 +231,11 @@ mod tests { // Claude Code 说 anthropic 方言 → 看不到 ollama 的模型。 let c = catalog(); assert_eq!( - c.resolve_allowed(Some("anthropic"), None), + c.resolve_allowed(Some(&["anthropic"]), None), owned(&["claude-haiku-4-5", "claude-opus-4-1", "claude-sonnet-4-5"]) ); assert_eq!( - c.resolve_allowed(Some("openai-chat"), None), + c.resolve_allowed(Some(&["openai-chat"]), None), owned(&["llama-4", "qwen3-coder"]) ); } @@ -241,7 +252,7 @@ mod tests { fn allow_narrows_on_top_of_the_dialect_filter() { let c = catalog(); assert_eq!( - c.resolve_allowed(Some("anthropic"), Some(&owned(&["claude-haiku-*"]))), + c.resolve_allowed(Some(&["anthropic"]), Some(&owned(&["claude-haiku-*"]))), owned(&["claude-haiku-4-5"]) ); } @@ -252,8 +263,11 @@ mod tests { // 分歧本身就说明容易搞错。YAML 里「字段缺失」和「空数组」天然 // 可区分,所以我们能表达得清楚。 let c = catalog(); - assert!(c.resolve_allowed(Some("anthropic"), Some(&[])).is_empty()); - assert!(!c.resolve_allowed(Some("anthropic"), None).is_empty()); + assert!( + c.resolve_allowed(Some(&["anthropic"]), Some(&[])) + .is_empty() + ); + assert!(!c.resolve_allowed(Some(&["anthropic"]), None).is_empty()); } #[test] @@ -262,7 +276,7 @@ mod tests { let c = catalog(); assert_eq!( c.resolve_allowed( - Some("anthropic"), + Some(&["anthropic"]), Some(&owned(&["claude-opus-4-1", "claude-sonnet-4-5"])) ), owned(&["claude-opus-4-1", "claude-sonnet-4-5"]) @@ -275,7 +289,7 @@ mod tests { // 否则它不会凭空出现。 let c = catalog(); assert!( - c.resolve_allowed(Some("anthropic"), Some(&owned(&["gpt-9"]))) + c.resolve_allowed(Some(&["anthropic"]), Some(&owned(&["gpt-9"]))) .is_empty() ); } @@ -285,7 +299,7 @@ mod tests { // 这是这个模块存在的核心理由:**一个函数,两处调用**。 // 两处各写一遍的话,「列表里有但用不了」这种状态迟早出现。 let c = catalog(); - for dialect in [Some("anthropic"), Some("openai-chat"), None] { + for dialect in [Some(&["anthropic"][..]), Some(&["openai-chat"][..]), None] { for allow in [None, Some(owned(&["claude-*"])), Some(vec![])] { let listed = c.resolve_allowed(dialect, allow.as_deref()); for m in &listed { @@ -305,7 +319,7 @@ mod tests { // 上游一个都没探到时(都不实现 /v1/models 且没写 models 兜底)。 let c = Catalog::default(); assert!(c.is_empty()); - assert!(c.resolve_allowed(Some("anthropic"), None).is_empty()); + assert!(c.resolve_allowed(Some(&["anthropic"]), None).is_empty()); assert!(!c.admits("anything", None, None)); } } diff --git a/crates/tw-gateway/src/auth.rs b/crates/tw-gateway/src/auth.rs index 791ae1c3..3a18c02b 100644 --- a/crates/tw-gateway/src/auth.rs +++ b/crates/tw-gateway/src/auth.rs @@ -22,21 +22,6 @@ pub enum KeyPosition { Bearer, } -impl KeyPosition { - /// 对应的上游协议名。和 `tw_config::Protocol` 的 Debug 形态对齐。 - /// - /// **Bearer 映射到 `OpenaiChat` 是一个近似**:Responses 方言也用 - /// Bearer。方言过滤只用来决定「列不列出来」,猜宽一点的代价是多列 - /// 几个模型,猜窄了的代价是用户能用的模型凭空消失 —— 后者难查得多。 - pub fn dialect(&self) -> &'static str { - match self { - KeyPosition::AnthropicHeader => "Anthropic", - KeyPosition::GoogleHeader => "Gemini", - KeyPosition::Bearer => "OpenaiChat", - } - } -} - /// 四个位置,因为四种客户端各写各的。 /// /// 顺序有讲究:**先看专用头,最后才看 query**。query 里的 key 会进访问 @@ -159,7 +144,7 @@ mod tests { } #[test] - fn the_position_of_the_key_tells_us_the_dialect() { + fn the_position_of_the_key_is_reported() { // 按方言过滤靠这个。这个信息我们本来就要读 —— 不必再 // 发明一个探测手段。 let pos = |m: &HeaderMap, q: Option<&str>| extract_key_with_position(m, q).map(|(_, p)| p); @@ -182,15 +167,6 @@ mod tests { ); } - #[test] - fn dialects_line_up_with_the_protocol_names() { - // 对不上的话,方言过滤会把所有模型都滤掉 —— 而那看起来像 - // 「一个模型都没探到」。 - assert_eq!(KeyPosition::AnthropicHeader.dialect(), "Anthropic"); - assert_eq!(KeyPosition::GoogleHeader.dialect(), "Gemini"); - assert_eq!(KeyPosition::Bearer.dialect(), "OpenaiChat"); - } - #[test] fn key_comparison_is_length_safe_and_correct() { assert!(key_eq("tw-abc", "tw-abc")); diff --git a/crates/tw-gateway/src/client_api.rs b/crates/tw-gateway/src/client_api.rs new file mode 100644 index 00000000..66e87ec7 --- /dev/null +++ b/crates/tw-gateway/src/client_api.rs @@ -0,0 +1,167 @@ +//! 客户端调的是哪一种 API。 +//! +//! # 看路径,不看密钥放在哪儿 +//! +//! 以前按「网关密钥放在哪个请求头」猜:`x-api-key` 是 Anthropic、`Bearer` 是 +//! OpenAI。理由是那个位置由 SDK 决定,而路径可能被中间层改写。 +//! +//! **这个理由在最主要的那个客户端上就不成立。**Claude Code 用 +//! `ANTHROPIC_AUTH_TOKEN` 配密钥时发的是 `Authorization: Bearer` —— 一键接管写的 +//! 正是这个变量。于是被接管的 Claude Code 被当成 OpenAI 客户端:模型准入只放行 +//! OpenAI 协议的上游,请求 Claude 模型被拒,出错时回的也是 OpenAI 的错误格式。 +//! +//! 路径才是 API 本身:`/v1/messages` 就是 Anthropic Messages,不管密钥放在哪儿。 +//! 认不出的路径(`None`)照旧直通,出错时的格式退回按密钥位置猜。 + +use tw_config::Protocol; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ClientApi { + /// `/v1/messages` + AnthropicMessages, + /// `/v1/chat/completions`、`/v1/completions`、`/v1/embeddings` + OpenaiChat, + /// `/v1/responses`、Codex 的 `/backend-api/codex/responses` + OpenaiResponses, + /// `/v1beta/models/{model}:generateContent` 一类 + Gemini, +} + +/// Gemini 在模型名后面用 `:动作` 表示调什么。 +const GEMINI_ACTIONS: &[&str] = &[ + ":generateContent", + ":streamGenerateContent", + ":countTokens", + ":embedContent", + ":batchEmbedContents", +]; + +impl ClientApi { + /// 按请求路径认。**认不出就是 `None`**,不猜 —— 猜错一个方向的代价是 + /// 请求被按另一种格式处理。 + pub fn of_path(path: &str) -> Option { + let p = path.trim_end_matches('/'); + // 有的客户端把 base_url 写成带 `/v1` 的,有的不带 —— 两种都认 + let tail = p.strip_prefix("/v1").unwrap_or(p); + if tail == "/messages" || tail == "/messages/count_tokens" || tail == "/complete" { + return Some(ClientApi::AnthropicMessages); + } + if tail == "/chat/completions" || tail == "/completions" || tail == "/embeddings" { + return Some(ClientApi::OpenaiChat); + } + if tail == "/responses" + || tail.starts_with("/responses/") + || p == "/backend-api/codex/responses" + || p.starts_with("/backend-api/codex/responses/") + { + return Some(ClientApi::OpenaiResponses); + } + if p.contains("/models/") && GEMINI_ACTIONS.iter().any(|a| p.ends_with(a)) { + return Some(ClientApi::Gemini); + } + None + } + + /// 和它同格式的上游协议。 + pub fn protocol(&self) -> Protocol { + match self { + ClientApi::AnthropicMessages => Protocol::Anthropic, + ClientApi::OpenaiChat => Protocol::OpenaiChat, + ClientApi::OpenaiResponses => Protocol::OpenaiResponses, + ClientApi::Gemini => Protocol::Gemini, + } + } + + /// 路由规则里 `when.dialect` 写的词,和上游协议的写法一致。 + pub fn slug(&self) -> &'static str { + self.protocol().slug() + } + + /// 能服务这种请求的上游协议:同格式的直通,加上有现成转换的。 + /// + /// **模型准入、`/v1/models` 和转发时选不选这家,用的都是这一张表** —— + /// 列出来的模型发过去一定有人能接。 + pub fn servable_by(&self) -> &'static [Protocol] { + match self { + // 手上一把 DeepSeek / Kimi 的 key 想让 Claude Code 用上:见 `translate` + ClientApi::AnthropicMessages => &[Protocol::Anthropic, Protocol::OpenaiChat], + ClientApi::OpenaiChat => &[Protocol::OpenaiChat], + ClientApi::OpenaiResponses => &[Protocol::OpenaiResponses], + ClientApi::Gemini => &[Protocol::Gemini], + } + } + + /// 出错时用哪种格式回。 + pub fn error_dialect(&self) -> crate::error::Dialect { + match self { + ClientApi::AnthropicMessages => crate::error::Dialect::Anthropic, + ClientApi::OpenaiChat | ClientApi::OpenaiResponses => crate::error::Dialect::Openai, + ClientApi::Gemini => crate::error::Dialect::Gemini, + } + } +} + +/// 这些协议写进模型目录时的名字,给目录的过滤用。 +pub fn slugs(protocols: &[Protocol]) -> Vec<&'static str> { + protocols.iter().map(|p| p.slug()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_api_is_recognised_by_its_path() { + for (path, want) in [ + ("/v1/messages", ClientApi::AnthropicMessages), + ("/v1/messages/count_tokens", ClientApi::AnthropicMessages), + ("/messages", ClientApi::AnthropicMessages), + ("/v1/chat/completions", ClientApi::OpenaiChat), + ("/chat/completions", ClientApi::OpenaiChat), + ("/v1/embeddings", ClientApi::OpenaiChat), + ("/v1/responses", ClientApi::OpenaiResponses), + ("/v1/responses/compact", ClientApi::OpenaiResponses), + ("/backend-api/codex/responses", ClientApi::OpenaiResponses), + ( + "/v1beta/models/gemini-2.5-pro:generateContent", + ClientApi::Gemini, + ), + ( + "/v1beta/models/gemini-2.5-pro:streamGenerateContent", + ClientApi::Gemini, + ), + ("/v1/models/gemini-2.5-flash:countTokens", ClientApi::Gemini), + ] { + assert_eq!(ClientApi::of_path(path), Some(want), "{path}"); + } + } + + #[test] + fn a_path_we_do_not_know_is_not_guessed() { + for path in ["/v1/models", "/v1/files", "/healthz", "/v1/messagesx", "/"] { + assert_eq!(ClientApi::of_path(path), None, "{path}"); + } + } + + #[test] + fn claude_code_is_an_anthropic_client_wherever_it_puts_the_key() { + // 这正是改成看路径的原因:`ANTHROPIC_AUTH_TOKEN` 发的是 Bearer + let api = ClientApi::of_path("/v1/messages").unwrap(); + assert_eq!(api.error_dialect(), crate::error::Dialect::Anthropic); + assert!(api.servable_by().contains(&Protocol::Anthropic)); + } + + #[test] + fn an_anthropic_client_can_be_served_by_an_openai_chat_upstream_but_not_the_reverse() { + assert!( + ClientApi::AnthropicMessages + .servable_by() + .contains(&Protocol::OpenaiChat) + ); + assert!( + !ClientApi::OpenaiChat + .servable_by() + .contains(&Protocol::Anthropic) + ); + } +} diff --git a/crates/tw-gateway/src/forward.rs b/crates/tw-gateway/src/forward.rs index 4a0300c8..f76168d1 100644 --- a/crates/tw-gateway/src/forward.rs +++ b/crates/tw-gateway/src/forward.rs @@ -27,35 +27,32 @@ const STRIP: &[&str] = &[ fn should_strip(name: &HeaderName) -> bool { let n = name.as_str(); - STRIP.contains(&n) + // `x-thinkwatch-*` 是客户端写给网关的(接管 Codex 时写进去的 + // `X-ThinkWatch-Client`),上游不该看见 + STRIP.contains(&n) || n.starts_with("x-thinkwatch-") } -/// 按上游协议把凭据放到它认的位置。 -pub fn apply_credential( +/// 把这家上游的请求头放上去。**凭据就在里面**(见 `tw_config::credential`)。 +/// +/// **WS 升级那条路也走同一份** `Provider::outbound_headers`:各写一份的话, +/// 两条路迟早会在「Gemini 用哪个头」这种事上不一致,而那时只有一条路是对的。 +pub fn apply_headers( builder: reqwest::RequestBuilder, - protocol: Option, - key: &str, + headers: &[(String, String)], ) -> reqwest::RequestBuilder { - let (name, value) = credential_header(protocol, key); - builder.header(name, value) + let mut b = builder; + for (name, value) in headers { + b = b.header(name.as_str(), value.as_str()); + } + b } -/// 这个方言把凭据放在哪个头上。 +/// 客户端带来的这个头,是不是被这家上游配置的同名头盖掉了。 /// -/// **WS 升级那条路也走它**:各写一份的话,两条路迟早会在 -/// 「Gemini 用哪个头」这种事上不一致,而那时只有一条路是对的。 -pub fn credential_header( - protocol: Option, - key: &str, -) -> (&'static str, String) { - use tw_config::Protocol::*; - match protocol { - // 猜不出协议时按 Anthropic 走:桌面版的主用例是 Claude Code, - // 而中转站绝大多数说的是 Anthropic 方言。 - Some(Anthropic) | None => ("x-api-key", key.to_string()), - Some(Gemini) => ("x-goog-api-key", key.to_string()), - Some(OpenaiChat) | Some(OpenaiResponses) => ("authorization", format!("Bearer {key}")), - } +/// **盖掉,而不是并存。**配置里写的 `anthropic-version` 和客户端自己带的 +/// 那一个同时发出去,上游收到的是两个值 —— 有的取第一个、有的直接 400。 +pub fn overridden(headers: &[(String, String)], name: &str) -> bool { + headers.iter().any(|(n, _)| n.eq_ignore_ascii_case(name)) } /// 把客户端的请求头搬到上游请求上,剔掉不该走的那些。 @@ -91,12 +88,26 @@ pub fn forward_headers_filtered( pub fn upstream_url(base_url: &str, path: &str, query: Option<&str>) -> String { let base = base_url.trim_end_matches('/'); let path = path.trim_start_matches('/'); + let query = query.map(without_gateway_key); match query { Some(q) if !q.is_empty() => format!("{base}/{path}?{q}"), _ => format!("{base}/{path}"), } } +/// 去掉查询串里的 `key=`。 +/// +/// **那是网关密钥。**Gemini 的 REST 写法把密钥放在查询串里,网关认完身份之后 +/// 原样把整个查询串拼到上游地址上,等于把它发给了上游。上游的凭据走请求头, +/// 用不着这一项。 +fn without_gateway_key(query: &str) -> String { + query + .split('&') + .filter(|pair| *pair != "key" && !pair.starts_with("key=")) + .collect::>() + .join("&") +} + /// 上游响应里也有不该原样回给客户端的头。 pub fn response_headers(upstream: &reqwest::header::HeaderMap) -> HeaderMap { let mut out = HeaderMap::new(); @@ -215,6 +226,45 @@ mod tests { ); } + #[test] + fn the_gateway_key_in_the_query_never_reaches_the_upstream() { + assert_eq!( + upstream_url( + "https://g.example", + "/v1beta/models/m:generateContent", + Some("key=tw-secret&alt=sse") + ), + "https://g.example/v1beta/models/m:generateContent?alt=sse" + ); + assert_eq!( + upstream_url( + "https://g.example", + "/v1beta/models/m", + Some("key=tw-secret") + ), + "https://g.example/v1beta/models/m" + ); + // 名字只是以 key 开头的参数不受影响 + assert_eq!( + upstream_url("https://g.example", "/x", Some("keyword=a")), + "https://g.example/x?keyword=a" + ); + } + + #[test] + fn headers_meant_for_the_gateway_never_reach_the_upstream() { + assert!(should_strip(&HeaderName::from_static( + "x-thinkwatch-client" + ))); + } + + #[test] + fn a_configured_header_replaces_the_one_the_client_sent() { + let configured = vec![("Anthropic-Version".to_string(), "2023-06-01".to_string())]; + assert!(overridden(&configured, "anthropic-version")); + assert!(!overridden(&configured, "anthropic-beta")); + } + #[test] fn our_own_auth_headers_never_reach_the_upstream() { // 客户端带的是**我们的**网关密钥。原样转出去等于把它送给中转站。 diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index 69559eb0..c6cbab72 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -137,7 +137,7 @@ pub fn probe_request(protocol: Option, model: &str) -> Opti pub async fn run( http: &reqwest::Client, base_url: &str, - key: &str, + headers: &[(String, String)], protocol: Option, provider: &str, model: &str, @@ -165,9 +165,11 @@ pub async fn run( // 测速不该无限等。**但也不能太短** —— 一个排队中的上游正是我们 // 想量的东西,掐早了会把「慢」误报成「不通」。 .timeout(Duration::from_secs(60)); - req = crate::forward::apply_credential(req, protocol, key); + req = crate::forward::apply_headers(req, headers); for (name, value) in probe.headers { - req = req.header(*name, *value); + if !crate::forward::overridden(headers, name) { + req = req.header(*name, *value); + } } let fail = |e: String, connect_ms: u64| L3Result { provider: provider.to_string(), @@ -334,7 +336,7 @@ mod tests { let r = run( &reqwest::Client::new(), "http://127.0.0.1:9", - "k", + &[("x-goog-api-key".to_string(), "k".to_string())], Some(tw_config::Protocol::Gemini), "g", "gemini-2.5-pro", diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 2535be03..1154f2ad 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -8,6 +8,7 @@ pub mod access; pub mod auth; pub mod bodies; +pub mod client_api; pub mod clientprobe; pub mod ending; pub mod error; diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index a23799a5..0cdb90d2 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -100,15 +100,7 @@ pub struct Directory { /// **OAuth 只看账号,不看 token**:refresh token 轮换一次就重问一遍,问到的 /// 是同一份清单。 fn identity(cfg: &tw_config::Config, p: &tw_config::Provider) -> String { - let key = match &p.key { - tw_config::Secret::Literal(v) => v.clone(), - tw_config::Secret::OAuth { oauth } => format!( - "oauth|{}|{}", - oauth.endpoint, - oauth.client_id.as_deref().unwrap_or_default() - ), - tw_config::Secret::Unknown(_) => String::new(), - }; + let key = p.credential_identity(); let raw = format!( "{}|{key}|{:?}|{}", p.base_url, @@ -180,11 +172,12 @@ impl Directory { provider: p.name.clone(), protocol: p .effective_protocol() - .map(|x| format!("{x:?}")) - // 猜不出协议时按 Anthropic 算 —— 和转发时的默认一致 - // (forward::apply_credential)。两处不一致会让「列出来 + // 猜不出协议时按 Anthropic 算 —— 和放凭据时的默认一致 + // (`tw_config::auth_header`)。两处不一致会让「列出来 // 了但发过去 401」变成可能。 - .unwrap_or_else(|| "Anthropic".to_string()), + .unwrap_or(tw_config::Protocol::Anthropic) + .slug() + .to_string(), known: l.source != Source::None, models: l.models.into_iter().filter(|m| p.uses_model(m)).collect(), } @@ -261,11 +254,11 @@ fn listing_of(entry: Option<&Entry>, p: &tw_config::Provider) -> Listing { async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer { // 用这一家自己的 client:它带着该走的代理,换 OAuth token 也要走那条路 let http = rt.clients.get(&p.name).unwrap_or(&state.http); - let key = match state.key_for(p, http).await { - Ok(k) => k, + let headers = match state.headers_for(p, http, None).await { + Ok(h) => h, Err(e) => return Answer::Failed(format!("取不到凭据:{e}")), }; - let r = crate::probe::probe(http, &p.base_url, &key, p.effective_protocol()).await; + let r = crate::probe::probe(http, &p.base_url, &headers, p.effective_protocol()).await; if !r.ok { return Answer::Failed(r.error.unwrap_or_else(|| "检测失败".to_string())); } @@ -458,7 +451,7 @@ mod tests { tw_config::Provider { name: name.into(), base_url: format!("https://{name}.example"), - key: "sk".into(), + key: Some("sk".into()), ..Default::default() } } diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index 21ca3d7e..286f7f3b 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -411,20 +411,17 @@ mod tests { } #[test] - fn describing_an_oauth_credential_never_shows_a_token() { - // **refresh token 比 access token 更值钱**,它换得出无数个 access。 - let s = tw_config::Secret::OAuth { - oauth: cfg("https://auth.example.com/token"), + fn headers_without_a_token_say_so_instead_of_inventing_a_value() { + // OAuth 的 token 要联网换,同步那条路给不出来 —— 说出来,而不是发一个空的鉴权头 + let p = tw_config::Provider { + name: "o".into(), + base_url: "https://relay.example".into(), + oauth: Some(cfg("https://auth.example.com/token")), + ..Default::default() }; - let d = s.describe(); - assert!(!d.contains("r-original"), "{d}"); - assert!(d.contains("auth.example.com"), "{d}"); - } - - #[test] - fn a_sync_resolve_says_what_is_going_on_instead_of_inventing_a_value() { - let s = tw_config::Secret::OAuth { oauth: cfg("x") }; - let e = s.resolve().unwrap_err(); - assert!(e.to_string().contains("换 token"), "{e}"); + assert_eq!( + p.outbound_headers(None, None), + Err(tw_config::CredentialError::NoToken) + ); } } diff --git a/crates/tw-gateway/src/probe.rs b/crates/tw-gateway/src/probe.rs index 1ad656be..39205160 100644 --- a/crates/tw-gateway/src/probe.rs +++ b/crates/tw-gateway/src/probe.rs @@ -80,7 +80,7 @@ impl ProbeResult { pub async fn probe( http: &reqwest::Client, base_url: &str, - key: &str, + headers: &[(String, String)], protocol: Option, ) -> ProbeResult { let proto = protocol.or_else(|| tw_config::Provider::guess_protocol(base_url)); @@ -89,7 +89,7 @@ pub async fn probe( let url = crate::forward::upstream_url(base_url, "/v1/models", None); let mut req = http.get(&url).timeout(PROBE_TIMEOUT); - req = crate::forward::apply_credential(req, proto, key); + req = crate::forward::apply_headers(req, headers); let resp = match req.send().await { Ok(r) => r, diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 1c73a67d..9633d9cf 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -315,20 +315,50 @@ impl AppState { self.models.publish(|| self.config(), &self.catalog); } - /// 取这一家的密钥。**OAuth 那一类要联网换 token,所以这条路是 - /// async 的**;明文和 `${ENV}` 走同步那条,零额外成本。 + /// 要发给这一家的请求头,凭据在里面。**OAuth 那一类要联网换 token,所以这条路是 + /// async 的**;密钥和 `${ENV}` 走同步那条,零额外成本。 /// /// `http` 必须是**这一家自己的** client:换 token 要走它该走的代理。 /// 用一个干净的 client 去换,代理后面的用户会得到一个 /// 「数据面通、刷新不通」的组合 —— 而那个症状看起来完全不像凭据问题。 - pub async fn key_for( + /// + /// `client`:发起请求的网关密钥名,填 `{{client}}` 用。后台的探测没有这个人。 + pub async fn headers_for( &self, p: &tw_config::Provider, http: &reqwest::Client, - ) -> Result { - let Some(o) = p.key.oauth() else { - return p.resolved_key().map_err(|e| e.to_string()); + client: Option<&str>, + ) -> Result, String> { + let token = match &p.oauth { + Some(o) => Some(self.oauth_token(p, o, http).await?), + None => None, }; + p.outbound_headers(token.as_deref(), client) + .map_err(|e| e.to_string()) + } + + /// 这一家的 OAuth access token。没配 oauth 是错误。 + /// + /// 检测一个沿用原凭据的上游时用:**按原来那一家的名字换**,缓存和轮换写回都认名字。 + pub async fn oauth_token_for( + &self, + p: &tw_config::Provider, + http: &reqwest::Client, + ) -> Result { + let o = p + .oauth + .as_ref() + .ok_or_else(|| format!("上游「{}」没有配置 OAuth", p.name))?; + self.oauth_token(p, o, http).await + } + + /// 换一个 access token,服务器换发了新的 refresh token 就交给控制面写回。 + async fn oauth_token( + &self, + p: &tw_config::Provider, + o: &tw_config::OAuth, + http: &reqwest::Client, + ) -> Result { let (token, rotated) = self .oauth .token(&p.name, o, http) @@ -592,9 +622,17 @@ pub fn router(state: AppState) -> Router { // 模型的 client,`GET /v1/models/claude-opus-4` 照样拿 200。 // 这个洞在别的项目里点过名(「都没做过滤」),而我们自己 // 也漏了。**同一个 `admits` 函数,列表和单点不可能不一致。** - .route("/v1/models/{model}", get(get_model)) - // Gemini 方言的路径。它的客户端问的是 `/v1beta/models/x` - .route("/v1beta/models/{model}", get(get_model)) + // + // **只截 GET。**Gemini 把调用写成 `POST /v1beta/models/{model}:generateContent`, + // 和单点查询是同一个路径模式 —— 没有这个 `fallback`,那些请求会被这条只认 + // GET 的路由拒成 405,永远到不了透传 + .route("/v1/models/{model}", get(get_model).fallback(passthrough)) + // Gemini 方言的路径。它的客户端问的是 `/v1beta/models` 和 `/v1beta/models/x` + .route("/v1beta/models", get(list_models)) + .route( + "/v1beta/models/{model}", + get(get_model).fallback(passthrough), + ) // M0 只有透传:任何方法、任何路径都往上游送。M1 加路由时, // 这里会先过规则引擎再决定送给谁。 .fallback(any(passthrough)) @@ -651,10 +689,10 @@ async fn ws_upgrade( ))); } let http = rt.clients.get(&name).unwrap_or(&state.http); - let key = state - .key_for(provider, http) + let upstream_headers = state + .headers_for(provider, http, Some(&client_name)) .await - .map_err(|e| GatewayError::config(format!("`{name}` 的密钥取不到:{e}")))?; + .map_err(|e| GatewayError::config(format!("`{name}` 的凭据取不到:{e}")))?; let url = crate::ws::upstream_url(&provider.base_url, uri.path(), query.as_deref()); let id = state.bus.next_id(); state.bus.emit(tw_api::Event::RequestStarted { @@ -675,19 +713,71 @@ async fn ws_upgrade( let provider = provider.clone(); let guard = decision.guard.clone(); let rules = rt.rules.clone(); - let protocol = provider.effective_protocol(); Ok(ws.on_upgrade(move |sock| async move { // 一条 WS 连接活多久,这个请求就算在服务中多久 let _live = live; let mut ending = ending; ending.responded(101); crate::ws::proxy( - state, sock, url, key, protocol, provider, guard, rules, id, ending, + state, + sock, + url, + upstream_headers, + provider, + guard, + rules, + id, + ending, ) .await; })) } +/// 列模型、查单个模型时,客户端是哪一种。 +/// +/// 这两个请求没有体,路径也分不出 Anthropic 和 OpenAI(都是 `/v1/models`), +/// 只能看请求头: +/// +/// - `/v1beta` 路径、或者把密钥放在 Google 位置上的是 Gemini +/// - 带 `anthropic-version`、或者把密钥放在 `x-api-key` 的是 Anthropic —— +/// 两个信号**任一个**就算:Claude Code 用 `ANTHROPIC_AUTH_TOKEN` 时密钥走 +/// Bearer,但版本头照带;手写的脚本常常只放 `x-api-key` +/// - 其余按 OpenAI 算 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ListingShape { + Anthropic, + Openai, + Gemini, +} + +impl ListingShape { + fn of(path: &str, headers: &HeaderMap, position: crate::auth::KeyPosition) -> Self { + if path.starts_with("/v1beta") || position == crate::auth::KeyPosition::GoogleHeader { + ListingShape::Gemini + } else if headers.contains_key("anthropic-version") + || position == crate::auth::KeyPosition::AnthropicHeader + { + ListingShape::Anthropic + } else { + ListingShape::Openai + } + } + + /// 这种客户端能用哪些协议的上游的模型。和请求那条路用同一张表 + fn protocols(&self) -> Vec<&'static str> { + use crate::client_api::{ClientApi, slugs}; + match self { + ListingShape::Anthropic => slugs(ClientApi::AnthropicMessages.servable_by()), + ListingShape::Openai => { + let mut v = slugs(ClientApi::OpenaiChat.servable_by()); + v.extend(slugs(ClientApi::OpenaiResponses.servable_by())); + v + } + ListingShape::Gemini => slugs(ClientApi::Gemini.servable_by()), + } + } +} + /// `GET /v1/models`。 /// /// 三种方言的响应结构不同,但**列表内容来自同一个函数** —— 差别只在 @@ -695,6 +785,7 @@ async fn ws_upgrade( async fn list_models( State(state): State, axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo, + OriginalUri(uri): OriginalUri, RawQuery(query): RawQuery, headers: HeaderMap, ) -> Result { @@ -712,14 +803,15 @@ async fn list_models( .iter() .find(|c| c.name == client) .and_then(|c| c.allow.clone()); + let shape = ListingShape::of(uri.path(), &headers, position); let models = state .catalog .load() - .resolve_allowed(Some(position.dialect()), allow.as_deref()); + .resolve_allowed(Some(&shape.protocols()), allow.as_deref()); let now = now_ms() / 1000; - let body = match position { - crate::auth::KeyPosition::GoogleHeader => serde_json::json!({ + let body = match shape { + ListingShape::Gemini => serde_json::json!({ "models": models.iter().map(|m| serde_json::json!({ "name": format!("models/{m}"), })).collect::>() @@ -744,6 +836,7 @@ async fn get_model( State(state): State, axum::extract::ConnectInfo(peer): axum::extract::ConnectInfo, axum::extract::Path(model): axum::extract::Path, + OriginalUri(uri): OriginalUri, RawQuery(query): RawQuery, headers: HeaderMap, ) -> Result { @@ -764,15 +857,16 @@ async fn get_model( let catalog = state.catalog.load(); // 目录空着时不拦 —— 那说明探测还没回来或者上游都不给列表,这时候 // 拦等于把整个网关关掉(和请求那条路同一个判断) - if !catalog.is_empty() && !catalog.admits(&model, Some(position.dialect()), allow.as_deref()) { + let shape = ListingShape::of(uri.path(), &headers, position); + if !catalog.is_empty() && !catalog.admits(&model, Some(&shape.protocols()), allow.as_deref()) { return Err(GatewayError::new( crate::error::Source::Request, format!("没有叫 `{model}` 的模型。能用的见 GET /v1/models。"), )); } let now = now_ms() / 1000; - let body = match position { - crate::auth::KeyPosition::GoogleHeader => { + let body = match shape { + ListingShape::Gemini => { serde_json::json!({ "name": format!("models/{model}") }) } _ => serde_json::json!({ "id": model, "object": "model", "created": now }), @@ -828,10 +922,15 @@ async fn passthrough( ) .await; } + // 客户端调的是哪种 API:**看路径**(见 `client_api`)。认不出的路径照旧 + // 直通,出错时的格式退回按密钥位置猜。 + let api = crate::client_api::ClientApi::of_path(uri.path()); // 从这里往下,所有错误都要用客户端自己那套结构回。 // **认证失败在这一行之前,那时方言还猜不出来** —— key 就是没认出来 // 的,只能退回 Anthropic 形状,而那是桌面版的主用例。 - let dialect = crate::error::Dialect::from_key_position(position); + let dialect = api + .map(|a| a.error_dialect()) + .unwrap_or_else(|| crate::error::Dialect::from_key_position(position)); // // 这个请求的结局(见 `crate::ending`)。**管线发出开始事件时把它放 // 进来。** @@ -852,7 +951,8 @@ async fn passthrough( headers, body, client_name, - position, + api, + dialect, started, live, &mut ending, @@ -932,7 +1032,8 @@ async fn pipeline( headers: HeaderMap, body: Bytes, client_name: String, - position: crate::auth::KeyPosition, + api: Option, + dialect: crate::error::Dialect, started: std::time::Instant, live: crate::live::Pass, ending: &mut Option, @@ -1000,6 +1101,8 @@ async fn pipeline( }; f.client = client_name.clone(); f.intent = intent; + // **按路径认出来的 API**,规则里的 `when.dialect` 比的就是它 + f.dialect = api.map(|a| a.slug()).unwrap_or_default().to_string(); f }; // 管线第 1.5 步:模型准入。**和 `GET /v1/models` 共用同一个函数** @@ -1016,7 +1119,8 @@ async fn pipeline( .iter() .find(|c| c.name == client_name) .and_then(|c| c.allow.clone()); - if !catalog.admits(&facts.model, Some(position.dialect()), allow.as_deref()) { + let servable = api.map(|a| crate::client_api::slugs(a.servable_by())); + if !catalog.admits(&facts.model, servable.as_deref(), allow.as_deref()) { // 错误信息要说清是哪一种:没有上游提供它,和这个客户端不让用它, // 该去改的地方不一样 let msg = if catalog.providers_for(&facts.model).is_empty() { @@ -1201,10 +1305,6 @@ async fn pipeline( // 「尝试链」要留下来:用户能看见故障转移在替他工作,**这是信任的 // 来源**。一个静默切换过的请求和一个一次就成的请求,在用户眼里 // 应该是不同的。 - // 客户端说什么方言。**唯一可靠的线索是它把 key 放在哪儿** —— - // 路径和 UA 都可以被中间层改写。方言互转和错误格式都要用它, - // 所以在循环之前就算好 - let dialect = crate::error::Dialect::from_key_position(position); let mut attempts: Vec = Vec::new(); // 成功那一次的脱敏账本。**必须是成功那一次的** —— 故障转移从官方切到 // 中转时,两次的脱敏规格不一样,拿错一本就还原不回来 @@ -1280,8 +1380,8 @@ async fn pipeline( // 用这个 provider 自己的 Client —— 它带着该走的代理。**在取密钥 // 之前拿到**:OAuth 换 token 也要走这条代理。 let http = rt.clients.get(&provider.name).unwrap_or(&state.http); - let key = match state.key_for(provider, http).await { - Ok(k) => k, + let upstream_headers = match state.headers_for(provider, http, Some(&client_name)).await { + Ok(h) => h, Err(e) => { // 密钥取不到是这一家的问题(环境变量没设、token 端点 // 连不上),换下一家是合理的 —— 而且**必须**换:不换的话 @@ -1292,9 +1392,9 @@ async fn pipeline( &provider.name, state.health.record_failure(&provider.name), ); - chain.push(hop(&provider.name, format!("密钥取不到:{e}"), hop_started)); + chain.push(hop(&provider.name, format!("凭据取不到:{e}"), hop_started)); last_err = Some(GatewayError::config(format!( - "provider `{}` 的密钥取不到:{e}", + "provider `{}` 的凭据取不到:{e}", provider.name ))); continue; @@ -1302,7 +1402,7 @@ async fn pipeline( }; // 方言互转(M6+)。**同方言时这一整段是零成本** —— // `plan()` 返回 Passthrough,body 和路径都原样 - let xlate = crate::translate::plan(dialect, provider.effective_protocol()); + let xlate = crate::translate::plan(api, provider.effective_protocol()); let outbound = match (xlate.active(), parsed.as_ref()) { (true, Some(v)) => { let c = tw_dialect::req::to_openai(v); @@ -1338,8 +1438,10 @@ async fn pipeline( ); let mut req = http.request(method, &url); - req = forward::forward_headers_filtered(req, &headers, |n| xlate.keeps_header(n)); - req = forward::apply_credential(req, provider.effective_protocol(), &key); + req = forward::forward_headers_filtered(req, &headers, |n| { + xlate.keeps_header(n) && !forward::overridden(&upstream_headers, n) + }); + req = forward::apply_headers(req, &upstream_headers); match req.body(outbound.clone()).send().await { Ok(r) if r.status().is_server_error() || r.status() == 429 => { // 5xx 和限流:换一家有意义,那边可能有不同的额度或地域。 @@ -1875,7 +1977,7 @@ mod tests { providers: vec![Provider { name: "r".into(), base_url: "https://example.invalid".into(), - key: "sk-1".into(), + key: Some("sk-1".into()), protocol: None, ..Default::default() }], @@ -1893,7 +1995,7 @@ mod tests { tw_config::Provider { name: "p".into(), base_url: "https://x.com".into(), - key: "k".into(), + key: Some("k".into()), proxy: proxy.into(), ..Default::default() } @@ -1958,13 +2060,13 @@ mod tests { tw_config::Provider { name: "a".into(), base_url: "https://a.com".into(), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, tw_config::Provider { name: "b".into(), base_url: "https://b.com".into(), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -1981,8 +2083,7 @@ mod tests { let s = AppState::new(cfg()).unwrap(); let (name, pos) = s.identify(&hdr("x-api-key", "tw-good"), None).unwrap(); assert_eq!(name, "default"); - // 位置带出来的方言是按方言过滤的依据 - assert_eq!(pos.dialect(), "Anthropic"); + assert_eq!(pos, crate::auth::KeyPosition::AnthropicHeader); } #[test] diff --git a/crates/tw-gateway/src/translate.rs b/crates/tw-gateway/src/translate.rs index fc7dc527..a16b7edf 100644 --- a/crates/tw-gateway/src/translate.rs +++ b/crates/tw-gateway/src/translate.rs @@ -12,7 +12,7 @@ use tw_config::Protocol; -use crate::error::Dialect; +use crate::client_api::ClientApi; /// 这一次要不要翻译,往哪个方向。 #[derive(Debug, Clone, Copy, PartialEq)] @@ -28,9 +28,9 @@ pub enum Plan { /// **认不出来就直通。**猜一个转换方向的代价是「请求被改成了另一个样子 /// 然后上游 400」,比不转难查得多 —— 而不转的表现是上游直接告诉你 /// 「我不认识这个格式」,那条错误信息本身就是线索。 -pub fn plan(client: Dialect, upstream: Option) -> Plan { +pub fn plan(client: Option, upstream: Option) -> Plan { match (client, upstream) { - (Dialect::Anthropic, Some(Protocol::OpenaiChat)) => Plan::AnthropicToOpenai, + (Some(ClientApi::AnthropicMessages), Some(Protocol::OpenaiChat)) => Plan::AnthropicToOpenai, _ => Plan::Passthrough, } } @@ -71,14 +71,23 @@ mod tests { fn same_dialect_is_always_passthrough() { // **九成五走这条**,它一个字节都不该被碰。 assert_eq!( - plan(Dialect::Anthropic, Some(Protocol::Anthropic)), + plan( + Some(ClientApi::AnthropicMessages), + Some(Protocol::Anthropic) + ), Plan::Passthrough ); assert_eq!( - plan(Dialect::Openai, Some(Protocol::OpenaiChat)), + plan(Some(ClientApi::OpenaiChat), Some(Protocol::OpenaiChat)), Plan::Passthrough ); - assert!(!plan(Dialect::Anthropic, Some(Protocol::Anthropic)).active()); + assert!( + !plan( + Some(ClientApi::AnthropicMessages), + Some(Protocol::Anthropic) + ) + .active() + ); } #[test] @@ -86,7 +95,10 @@ mod tests { // 那是这个功能存在的全部理由:手上一把 DeepSeek 的 key, // 想让 Claude Code 用上。 assert_eq!( - plan(Dialect::Anthropic, Some(Protocol::OpenaiChat)), + plan( + Some(ClientApi::AnthropicMessages), + Some(Protocol::OpenaiChat) + ), Plan::AnthropicToOpenai ); } @@ -101,14 +113,18 @@ mod tests { Some(Protocol::OpenaiResponses), None, ] { - assert_eq!(plan(Dialect::Anthropic, up), Plan::Passthrough, "{up:?}"); + assert_eq!( + plan(Some(ClientApi::AnthropicMessages), up), + Plan::Passthrough, + "{up:?}" + ); } assert_eq!( - plan(Dialect::Openai, Some(Protocol::Anthropic)), + plan(Some(ClientApi::OpenaiChat), Some(Protocol::Anthropic)), Plan::Passthrough ); assert_eq!( - plan(Dialect::Gemini, Some(Protocol::OpenaiChat)), + plan(Some(ClientApi::Gemini), Some(Protocol::OpenaiChat)), Plan::Passthrough ); } diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index f67ce534..fd3ae335 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -114,8 +114,7 @@ pub async fn proxy( state: AppState, client: WebSocket, upstream_url: String, - key: String, - protocol: Option, + upstream_headers: Vec<(String, String)>, provider: tw_config::Provider, guard: tw_engine::Guard, rules: Arc, @@ -134,16 +133,19 @@ pub async fn proxy( return; } }; - { - let (name, value) = crate::forward::credential_header(protocol, &key); - match value.parse() { - Ok(v) => { - req.headers_mut().insert(name, v); + for (name, value) in &upstream_headers { + let parsed = ( + name.parse::(), + value.parse::(), + ); + match parsed { + (Ok(n), Ok(v)) => { + req.headers_mut().insert(n, v); } - Err(_) => { - let why = "这家的密钥里有不能放进请求头的字符"; - ending.failed("config", why.to_string()); - close_with(client, why).await; + _ => { + let why = format!("这家的请求头「{name}」里有不能放进请求头的字符"); + ending.failed("config", why.clone()); + close_with(client, &why).await; return; } } diff --git a/crates/tw-gateway/tests/dialect.rs b/crates/tw-gateway/tests/dialect.rs index 32fb8ccd..1c699a7d 100644 --- a/crates/tw-gateway/tests/dialect.rs +++ b/crates/tw-gateway/tests/dialect.rs @@ -104,7 +104,7 @@ async fn start_gateway( providers: vec![Provider { name: "deepseek".into(), base_url: format!("http://{up}"), - key: "sk-deepseek".into(), + key: Some("sk-deepseek".into()), // **这一行是整个功能的开关** protocol: Some(tw_config::Protocol::OpenaiChat), redact: Some(vec![]), diff --git a/crates/tw-gateway/tests/endings.rs b/crates/tw-gateway/tests/endings.rs index c0612416..f578a78f 100644 --- a/crates/tw-gateway/tests/endings.rs +++ b/crates/tw-gateway/tests/endings.rs @@ -176,7 +176,7 @@ fn provider(upstream: SocketAddr) -> Provider { Provider { name: "up".into(), base_url: format!("http://{upstream}"), - key: "sk-x".into(), + key: Some("sk-x".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() } diff --git a/crates/tw-gateway/tests/headers_and_paths.rs b/crates/tw-gateway/tests/headers_and_paths.rs new file mode 100644 index 00000000..5728b0e5 --- /dev/null +++ b/crates/tw-gateway/tests/headers_and_paths.rs @@ -0,0 +1,239 @@ +//! 端到端:上游的请求头,和按路径认出来的客户端 API。 +//! +//! 这几条各对着一个真实出过的问题: +//! +//! - 一键接管的 Claude Code 用 `Authorization: Bearer` 发网关密钥,被当成 OpenAI +//! 客户端,请求 Claude 模型被模型准入拒掉 +//! - Gemini 的 `POST /v1beta/models/{model}:generateContent` 被只认 GET 的路由拒成 405 +//! - 查询串里的 `key=`(网关密钥)被原样拼到上游地址上 +//! - 只能填一把密钥,要求自定义鉴权头的中转站接不进来 + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::Router; +use axum::extract::{OriginalUri, State}; +use axum::http::{HeaderMap, Method}; +use tw_config::{Client, Config, Header, Headers, Listen, Protocol, Provider, Secret}; + +#[derive(Default, Debug)] +struct Seen { + method: Option, + uri: String, + headers: HeaderMap, +} + +async fn start_upstream() -> (SocketAddr, Arc>) { + let seen = Arc::new(Mutex::new(Seen::default())); + let app = Router::new() + .fallback( + |State(s): State>>, + method: Method, + OriginalUri(uri): OriginalUri, + headers: HeaderMap| async move { + let mut g = s.lock().unwrap(); + g.method = Some(method); + g.uri = uri.to_string(); + g.headers = headers; + axum::response::Response::builder() + .header("content-type", "application/json") + .body(axum::body::Body::from(r#"{"ok":true}"#)) + .unwrap() + }, + ) + .with_state(seen.clone()); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + (addr, seen) +} + +async fn start_gateway(provider: Provider) -> SocketAddr { + let cfg = Config { + version: 1, + listen: Listen::default(), + clients: vec![Client { + name: "laptop".into(), + key: "tw-testkey".into(), + ..Default::default() + }], + providers: vec![provider], + ..Default::default() + }; + let state = tw_gateway::AppState::new(cfg).unwrap(); + let addr = { + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + l.local_addr().unwrap() + }; + tokio::spawn(async move { tw_gateway::serve(state, addr).await.unwrap() }); + tokio::time::sleep(Duration::from_millis(50)).await; + addr +} + +fn anthropic(upstream: SocketAddr) -> Provider { + Provider { + name: "official".into(), + base_url: format!("http://{upstream}"), + key: Some("sk-upstream".into()), + protocol: Some(Protocol::Anthropic), + // 手写清单让模型目录不为空 —— 准入只在目录不为空时才拦 + models: vec!["claude-sonnet-4-5".into()], + redact: Some(vec![]), + ..Default::default() + } +} + +const BODY: &str = + r#"{"model":"claude-sonnet-4-5","max_tokens":16,"messages":[{"role":"user","content":"hi"}]}"#; + +#[tokio::test] +async fn claude_code_with_a_bearer_key_can_use_an_anthropic_upstream() { + let (up, seen) = start_upstream().await; + let gw = start_gateway(anthropic(up)).await; + + let resp = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + // 接管写的是 ANTHROPIC_AUTH_TOKEN,Claude Code 把它发成 Bearer + .header("authorization", "Bearer tw-testkey") + .header("anthropic-version", "2023-06-01") + .header("content-type", "application/json") + .body(BODY) + .send() + .await + .unwrap(); + let status = resp.status(); + let text = resp.text().await.unwrap(); + assert_eq!(status, 200, "{text}"); + let g = seen.lock().unwrap(); + assert_eq!(g.headers.get("x-api-key").unwrap(), "sk-upstream"); + assert!( + g.headers.get("authorization").is_none(), + "网关密钥被转给了上游" + ); +} + +#[tokio::test] +async fn a_bearer_key_with_the_anthropic_version_header_lists_anthropic_models() { + let (up, _) = start_upstream().await; + let gw = start_gateway(anthropic(up)).await; + + let body: serde_json::Value = reqwest::Client::new() + .get(format!("http://{gw}/v1/models")) + .header("authorization", "Bearer tw-testkey") + .header("anthropic-version", "2023-06-01") + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + let ids: Vec<&str> = body["data"] + .as_array() + .unwrap() + .iter() + .filter_map(|m| m["id"].as_str()) + .collect(); + assert_eq!(ids, ["claude-sonnet-4-5"], "{body}"); +} + +#[tokio::test] +async fn a_gemini_generate_content_call_is_forwarded_without_the_gateway_key() { + let (up, seen) = start_upstream().await; + let gw = start_gateway(Provider { + name: "gemini".into(), + base_url: format!("http://{up}"), + key: Some("g-upstream".into()), + protocol: Some(Protocol::Gemini), + redact: Some(vec![]), + ..Default::default() + }) + .await; + + let resp = reqwest::Client::new() + .post(format!( + "http://{gw}/v1beta/models/gemini-2.5-pro:generateContent?key=tw-testkey&alt=sse" + )) + .header("content-type", "application/json") + .body(r#"{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}"#) + .send() + .await + .unwrap(); + let status = resp.status(); + let text = resp.text().await.unwrap(); + assert_eq!(status, 200, "被路由挡掉了:{text}"); + let g = seen.lock().unwrap(); + assert_eq!(g.method, Some(Method::POST)); + assert_eq!( + g.uri, + "/v1beta/models/gemini-2.5-pro:generateContent?alt=sse" + ); + assert!( + !g.uri.contains("tw-testkey"), + "网关密钥进了上游地址:{}", + g.uri + ); + assert_eq!(g.headers.get("x-goog-api-key").unwrap(), "g-upstream"); +} + +#[tokio::test] +async fn configured_headers_are_sent_and_replace_the_ones_the_client_sent() { + let (up, seen) = start_upstream().await; + let mut p = anthropic(up); + p.headers = Headers::new(vec![ + Header { + name: "anthropic-version".into(), + value: Secret::new("2099-01-01"), + }, + Header { + name: "X-Relay-Caller".into(), + value: Secret::new("{{client}}"), + }, + ]); + let gw = start_gateway(p).await; + + let resp = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-testkey") + .header("anthropic-version", "2023-06-01") + .header("x-thinkwatch-client", "codex") + .header("content-type", "application/json") + .body(BODY) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 200); + let g = seen.lock().unwrap(); + let versions: Vec<_> = g.headers.get_all("anthropic-version").iter().collect(); + assert_eq!(versions, ["2099-01-01"], "同名头应该被盖掉,而不是并存"); + assert_eq!(g.headers.get("x-relay-caller").unwrap(), "laptop"); + assert!(g.headers.get("x-thinkwatch-client").is_none()); +} + +#[tokio::test] +async fn a_relay_can_take_its_credential_in_its_own_header() { + let (up, seen) = start_upstream().await; + let mut p = anthropic(up); + p.key = None; + p.headers = Headers::new(vec![Header { + name: "X-Relay-Token".into(), + value: Secret::new("rt-1"), + }]); + let gw = start_gateway(p).await; + + let resp = reqwest::Client::new() + .post(format!("http://{gw}/v1/messages")) + .header("x-api-key", "tw-testkey") + .header("content-type", "application/json") + .body(BODY) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 200); + let g = seen.lock().unwrap(); + assert_eq!(g.headers.get("x-relay-token").unwrap(), "rt-1"); + assert!( + g.headers.get("x-api-key").is_none(), + "没写 key 就不该发鉴权头" + ); +} diff --git a/crates/tw-gateway/tests/hotreload.rs b/crates/tw-gateway/tests/hotreload.rs index 9b56cd03..70256628 100644 --- a/crates/tw-gateway/tests/hotreload.rs +++ b/crates/tw-gateway/tests/hotreload.rs @@ -53,7 +53,7 @@ fn provider(name: &str, at: SocketAddr) -> Provider { Provider { name: name.into(), base_url: format!("http://{at}"), - key: "k".into(), + key: Some("k".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() } @@ -302,7 +302,7 @@ async fn a_connection_pool_survives_an_unrelated_edit() { // 换一把 key 更不该重建:Client 不绑凭据,凭据是每个请求现加的 let mut next2 = c.clone(); - next2.providers[0].key = "另一把".into(); + next2.providers[0].key = Some("另一把".into()); state.reload(next2).unwrap(); ask(gw).await; assert_eq!(conns.load(Ordering::SeqCst), 1, "改一把 key 就把连接池扔了"); diff --git a/crates/tw-gateway/tests/live.rs b/crates/tw-gateway/tests/live.rs index e0cc60fa..50af585c 100644 --- a/crates/tw-gateway/tests/live.rs +++ b/crates/tw-gateway/tests/live.rs @@ -59,7 +59,7 @@ async fn serve(upstream: SocketAddr) -> (SocketAddr, tw_gateway::live::Live) { providers: vec![Provider { name: "up".into(), base_url: format!("http://{upstream}"), - key: "sk-x".into(), + key: Some("sk-x".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }], diff --git a/crates/tw-gateway/tests/m1_acceptance.rs b/crates/tw-gateway/tests/m1_acceptance.rs index 356d53e1..67781755 100644 --- a/crates/tw-gateway/tests/m1_acceptance.rs +++ b/crates/tw-gateway/tests/m1_acceptance.rs @@ -39,7 +39,7 @@ fn provider(name: &str, at: SocketAddr) -> Provider { Provider { name: name.into(), base_url: format!("http://{at}"), - key: "sk-x".into(), + key: Some("sk-x".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() } diff --git a/crates/tw-gateway/tests/m5_redact.rs b/crates/tw-gateway/tests/m5_redact.rs index 7a0291c9..616e6d18 100644 --- a/crates/tw-gateway/tests/m5_redact.rs +++ b/crates/tw-gateway/tests/m5_redact.rs @@ -106,7 +106,7 @@ fn provider(name: &str, base: SocketAddr, official: bool) -> Provider { Provider { name: name.into(), base_url: format!("http://{base}"), - key: "sk-upstream".into(), + key: Some("sk-upstream".into()), protocol: Some(tw_config::Protocol::Anthropic), // 测试里连的是 127.0.0.1,域名判据用不上,所以直接写清楚 redact: Some(if official { diff --git a/crates/tw-gateway/tests/m5_toolwall.rs b/crates/tw-gateway/tests/m5_toolwall.rs index 0e520b1d..aa1c2bae 100644 --- a/crates/tw-gateway/tests/m5_toolwall.rs +++ b/crates/tw-gateway/tests/m5_toolwall.rs @@ -74,7 +74,7 @@ fn config(up: SocketAddr, mode: SecurityMode, trust: Trust) -> Config { providers: vec![Provider { name: "relay".into(), base_url: format!("http://{up}"), - key: "sk-upstream".into(), + key: Some("sk-upstream".into()), protocol: Some(tw_config::Protocol::Anthropic), trust: Some(trust), redact: Some(vec![]), diff --git a/crates/tw-gateway/tests/models.rs b/crates/tw-gateway/tests/models.rs index 93297b8f..9310aa98 100644 --- a/crates/tw-gateway/tests/models.rs +++ b/crates/tw-gateway/tests/models.rs @@ -53,7 +53,7 @@ fn provider(name: &str, at: SocketAddr) -> Provider { Provider { name: name.into(), base_url: format!("http://{at}"), - key: "k".into(), + key: Some("k".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() } diff --git a/crates/tw-gateway/tests/oauth.rs b/crates/tw-gateway/tests/oauth.rs index 8d69635a..dc248785 100644 --- a/crates/tw-gateway/tests/oauth.rs +++ b/crates/tw-gateway/tests/oauth.rs @@ -13,7 +13,7 @@ use std::time::Duration; use axum::Router; use axum::extract::State; use axum::routing::post; -use tw_config::{Client, Config, Listen, OAuth, Provider, Secret}; +use tw_config::{Client, Config, Listen, OAuth, Provider}; const REFRESH: &str = "rt-ORIGINAL-refresh-token"; /// 服务器换发的那个。**每次都不一样** —— 真的会轮换的服务器就是这样, @@ -130,16 +130,14 @@ fn oauth_provider(name: &str, upstream: SocketAddr, token_url: &str) -> Provider Provider { name: name.into(), base_url: format!("http://{upstream}"), - key: Secret::OAuth { - oauth: OAuth { - access: None, - refresh: REFRESH.into(), - endpoint: token_url.into(), - client_id: Some("tw-test".into()), - client_secret: None, - refresh_before: Some("5m".into()), - }, - }, + oauth: Some(OAuth { + access: None, + refresh: REFRESH.into(), + endpoint: token_url.into(), + client_id: Some("tw-test".into()), + client_secret: None, + refresh_before: Some("5m".into()), + }), protocol: Some(tw_config::Protocol::Anthropic), redact: Some(vec![]), ..Default::default() @@ -304,7 +302,7 @@ async fn a_dead_token_endpoint_fails_over_instead_of_taking_the_gateway_down() { let backup = Provider { name: "backup".into(), base_url: format!("http://{up}"), - key: "sk-plain-backup".into(), + key: Some("sk-plain-backup".into()), protocol: Some(tw_config::Protocol::Anthropic), redact: Some(vec![]), ..Default::default() @@ -439,10 +437,7 @@ async fn editing_the_refresh_token_in_the_config_invalidates_the_cache() { let cache = tw_gateway::oauth::Cache::new(); let http = reqwest::Client::new(); - let mut cfg = match oauth_provider("p", up, &url).key { - Secret::OAuth { oauth } => oauth, - _ => unreachable!(), - }; + let mut cfg = oauth_provider("p", up, &url).oauth.unwrap(); let (a, _) = cache.token("p", &cfg, &http).await.unwrap(); assert_eq!(a, "at-issued-1"); // 没改配置:不再换 diff --git a/crates/tw-gateway/tests/passthrough.rs b/crates/tw-gateway/tests/passthrough.rs index 89723c2b..2b7fc574 100644 --- a/crates/tw-gateway/tests/passthrough.rs +++ b/crates/tw-gateway/tests/passthrough.rs @@ -74,7 +74,7 @@ async fn start_gateway(upstream: SocketAddr) -> SocketAddr { providers: vec![Provider { name: "mock".into(), base_url: format!("http://{upstream}"), - key: "sk-upstream-secret".into(), + key: Some("sk-upstream-secret".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }], @@ -247,7 +247,7 @@ async fn a_request_emits_the_four_lifecycle_events_in_order() { providers: vec![Provider { name: "mock".into(), base_url: format!("http://{up}"), - key: "sk-x".into(), + key: Some("sk-x".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }], @@ -357,7 +357,7 @@ async fn an_unreachable_upstream_emits_a_failure_event_and_a_502() { providers: vec![Provider { name: "dead".into(), base_url: format!("http://127.0.0.1:{dead_port}"), - key: "sk-x".into(), + key: Some("sk-x".into()), protocol: None, ..Default::default() }], @@ -424,14 +424,14 @@ async fn a_rule_sends_opus_to_one_upstream_and_everything_else_to_another() { Provider { name: "official".into(), base_url: format!("http://{a}"), - key: "sk-official".into(), + key: Some("sk-official".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }, Provider { name: "relay".into(), base_url: format!("http://{b}"), - key: "sk-relay".into(), + key: Some("sk-relay".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }, @@ -530,7 +530,7 @@ async fn with_no_routes_at_all_requests_still_go_somewhere() { providers: vec![Provider { name: "only".into(), base_url: format!("http://{up}"), - key: "sk-x".into(), + key: Some("sk-x".into()), protocol: None, ..Default::default() }], @@ -619,13 +619,13 @@ async fn a_dead_first_provider_fails_over_to_the_next_one() { Provider { name: "dead".into(), base_url: format!("http://{dead}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "good".into(), base_url: format!("http://{good}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -652,13 +652,13 @@ async fn a_client_error_does_not_burn_the_other_providers() { Provider { name: "first".into(), base_url: format!("http://{bad_request}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "backup".into(), base_url: format!("http://{backup}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -681,13 +681,13 @@ async fn rate_limiting_does_fail_over_because_another_account_may_have_quota() { Provider { name: "limited".into(), base_url: format!("http://{limited}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "good".into(), base_url: format!("http://{good}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -707,7 +707,7 @@ async fn the_only_provider_keeps_being_tried_no_matter_how_broken() { vec![Provider { name: "only".into(), base_url: format!("http://{dead}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -733,13 +733,13 @@ async fn everything_broken_still_tries_rather_than_refusing() { Provider { name: "a".into(), base_url: format!("http://{a}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "b".into(), base_url: format!("http://{b}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -789,7 +789,7 @@ fn cfg_with_limits(up: SocketAddr, limits: tw_config::Limits) -> Config { providers: vec![Provider { name: "slow".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], limits, @@ -919,7 +919,7 @@ async fn listing_and_admission_come_from_the_same_place() { vec![Provider { name: "relay".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), protocol: Some(tw_config::Protocol::Anthropic), // 这家不实现 /v1/models,所以手写兜底 models: vec!["claude-sonnet-4-5".into(), "claude-haiku-4-5".into()], @@ -982,7 +982,7 @@ async fn an_empty_allow_list_disables_the_client_entirely() { vec![Provider { name: "relay".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), protocol: Some(tw_config::Protocol::Anthropic), models: vec!["claude-sonnet-4-5".into()], ..Default::default() @@ -1022,7 +1022,7 @@ async fn with_nothing_discovered_the_gateway_does_not_lock_itself_shut() { vec![Provider { name: "relay".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1084,14 +1084,14 @@ async fn a_phase_two_rule_is_recomputed_after_failover() { Provider { name: "official".into(), base_url: format!("http://{official}"), - key: "k".into(), + key: Some("k".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }, Provider { name: "relay".into(), base_url: format!("http://{relay}"), - key: "k".into(), + key: Some("k".into()), protocol: Some(tw_config::Protocol::Anthropic), ..Default::default() }, @@ -1158,7 +1158,7 @@ async fn a_phase_two_deny_reaches_the_client_with_its_reason() { vec![Provider { name: "relay".into(), base_url: format!("http://{relay}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![ @@ -1204,7 +1204,7 @@ async fn a_set_that_changes_nothing_leaves_the_body_byte_for_byte() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1238,13 +1238,13 @@ async fn a_phase_one_set_applies_on_every_attempt_including_after_failover() { Provider { name: "dead".into(), base_url: format!("http://{dead}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "good".into(), base_url: format!("http://{good}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -1288,7 +1288,7 @@ async fn a_health_check_is_answered_locally_and_never_reaches_the_upstream() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1324,7 +1324,7 @@ async fn a_health_check_still_works_with_every_upstream_dead() { name: "dead".into(), // 连端口都没人听 base_url: format!("http://{dead}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1350,7 +1350,7 @@ async fn a_titling_request_goes_to_the_upstream_untouched() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1383,7 +1383,7 @@ async fn intercepting_a_probe_emits_its_own_event_not_a_request_pair() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1431,7 +1431,7 @@ async fn turning_off_the_interception_sends_the_health_check_upstream() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1461,13 +1461,13 @@ async fn a_probe_set_to_route_can_be_sent_somewhere_cheaper() { Provider { name: "便宜的".into(), base_url: format!("http://{cheap}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "正常的".into(), base_url: format!("http://{normal}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -1526,13 +1526,13 @@ async fn an_intent_rule_does_not_fire_while_the_probe_is_still_passthrough() { Provider { name: "便宜的".into(), base_url: format!("http://{cheap}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "正常的".into(), base_url: format!("http://{normal}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -1602,55 +1602,63 @@ async fn a_health_check_works_before_any_upstream_is_configured() { /// **错误必须用入站方言的原生格式返回。**一个 Anthropic 客户端 /// 收到 OpenAI 形状的 error body,会在解析时炸掉,然后报一个和真实原因 /// 完全无关的错。 +/// +/// 方言按路径认,不按密钥放在哪儿认。 #[tokio::test] async fn an_error_comes_back_in_the_dialect_the_client_speaks() { let gw = serve_cfg(cfg_with(vec![], vec![])).await; let c = reqwest::Client::new(); - let url = format!("http://{gw}/v1/messages"); - let body = r#"{"model":"claude-sonnet-4-5","messages":[]}"#; + let post = |path: &str, auth: &str| { + let r = c + .post(format!("http://{gw}{path}")) + .body(r#"{"model":"m","messages":[]}"#); + match auth { + "bearer" => r.bearer_auth("tw-k"), + h => r.header(h, "tw-k"), + } + }; // Anthropic:`{type:"error", error:{type,message}}` - let v: serde_json::Value = c - .post(&url) - .header("x-api-key", "tw-k") - .body(body) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - assert_eq!(v["type"], "error"); - assert_eq!(v["error"]["type"], "api_error"); + for auth in ["x-api-key", "bearer"] { + // Bearer 是 Claude Code 用 `ANTHROPIC_AUTH_TOKEN` 时的发法 —— 照样是 Anthropic + let v: serde_json::Value = post("/v1/messages", auth) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(v["type"], "error", "{auth}: {v}"); + assert_eq!(v["error"]["type"], "api_error", "{auth}: {v}"); + } // OpenAI:没有外层 type,多了 param / code - let v: serde_json::Value = c - .post(&url) - .bearer_auth("tw-k") - .body(body) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - assert!(v.get("type").is_none(), "OpenAI 没有外层 type:{v}"); - assert_eq!(v["error"]["type"], "server_error"); - assert!(v["error"].get("param").is_some()); + for path in ["/v1/chat/completions", "/v1/responses"] { + let v: serde_json::Value = post(path, "bearer") + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert!(v.get("type").is_none(), "{path}: OpenAI 没有外层 type:{v}"); + assert_eq!(v["error"]["type"], "server_error", "{path}: {v}"); + assert!(v["error"].get("param").is_some(), "{path}: {v}"); + } // Gemini:`{error:{code,message,status}}` - let v: serde_json::Value = c - .post(&url) - .header("x-goog-api-key", "tw-k") - .body(body) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - assert_eq!(v["error"]["status"], "UNAVAILABLE"); - assert_eq!(v["error"]["code"], 500); + let v: serde_json::Value = post( + "/v1beta/models/gemini-2.5-pro:generateContent", + "x-goog-api-key", + ) + .send() + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(v["error"]["status"], "UNAVAILABLE", "{v}"); + assert_eq!(v["error"]["code"], 500, "{v}"); } #[tokio::test] @@ -1684,7 +1692,7 @@ async fn a_deny_rule_is_403_not_400() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![ @@ -1764,7 +1772,7 @@ async fn a_stream_that_dies_midway_says_so_instead_of_just_stopping() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1819,7 +1827,7 @@ async fn an_upstream_rate_limit_stays_a_429_instead_of_becoming_a_502() { vec![Provider { name: "limited".into(), base_url: format!("http://{limited}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1859,7 +1867,7 @@ async fn the_upstream_usage_reaches_the_event_stream_without_buffering_the_respo vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1913,7 +1921,7 @@ async fn an_upstream_that_gives_no_usage_reports_none_rather_than_zeroes() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -1948,7 +1956,7 @@ async fn a_key_pasted_into_a_prompt_is_noticed_but_the_request_goes_through_unto vec![Provider { name: "中转".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -2008,7 +2016,7 @@ async fn turning_the_detector_off_stops_it_looking_at_all() { vec![Provider { name: "up".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -2051,19 +2059,19 @@ async fn the_attempt_chain_records_every_hop_and_why_each_one_failed() { Provider { name: "挂了的".into(), base_url: format!("http://{dead}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "限流的".into(), base_url: format!("http://{limited}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, Provider { name: "好的".into(), base_url: format!("http://{good}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }, ], @@ -2132,7 +2140,7 @@ async fn a_request_that_succeeds_first_try_still_has_a_chain_of_one() { vec![Provider { name: "官方".into(), base_url: format!("http://{good}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -2168,7 +2176,7 @@ async fn a_request_that_fails_everywhere_still_reports_the_chain() { vec![Provider { name: "挂了的".into(), base_url: format!("http://{dead}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -2219,7 +2227,7 @@ async fn an_upstream_that_reports_quota_is_treated_as_subscription_from_then_on( vec![Provider { name: "订阅账号".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], @@ -2255,7 +2263,7 @@ async fn writing_billing_in_the_config_removes_the_first_request_ambiguity() { vec![Provider { name: "订阅账号".into(), base_url: format!("http://{up}"), - key: "k".into(), + key: Some("k".into()), ..Default::default() }], vec![], diff --git a/crates/tw-gateway/tests/ws.rs b/crates/tw-gateway/tests/ws.rs index c3a34dd8..9e6747f7 100644 --- a/crates/tw-gateway/tests/ws.rs +++ b/crates/tw-gateway/tests/ws.rs @@ -74,7 +74,7 @@ async fn start_gateway(up: SocketAddr, mode: SecurityMode, inspect: SecurityMode providers: vec![Provider { name: "中转".into(), base_url: format!("http://{up}"), - key: "sk-upstream".into(), + key: Some("sk-upstream".into()), protocol: Some(tw_config::Protocol::Anthropic), // 测试连的是 127.0.0.1,域名判据用不上,所以写清楚 redact: Some(vec![tw_redact::rules::Kind::ApiKeys]), diff --git a/crates/tw-secret/src/lib.rs b/crates/tw-secret/src/lib.rs index efdbc140..10722dcb 100644 --- a/crates/tw-secret/src/lib.rs +++ b/crates/tw-secret/src/lib.rs @@ -8,7 +8,10 @@ use std::collections::HashMap; pub mod mask; -pub use mask::{mask_body, mask_config_yaml, mask_line, mask_secret, redact_url}; +pub use mask::{ + is_public_header, is_reference_only, mask_body, mask_config_yaml, mask_line, mask_secret, + redact_url, +}; #[derive(Debug, thiserror::Error)] pub enum SecretError { diff --git a/crates/tw-secret/src/mask.rs b/crates/tw-secret/src/mask.rs index 51044e2b..9e9ca775 100644 --- a/crates/tw-secret/src/mask.rs +++ b/crates/tw-secret/src/mask.rs @@ -117,6 +117,84 @@ fn mask_line_by_field(line: &str) -> String { format!("{head}{lead}{q}{masked}{q}{comment}") } +/// `headers:` 段里的一行:公开的头和只由引用组成的值原样留着,其余打码。 +fn mask_header_line(line: &str) -> String { + let Some(colon) = line.find(':') else { + return line.to_string(); + }; + let (head, rest) = line.split_at(colon + 1); + let name = head.trim_end_matches(':').trim().trim_matches(['"', '\'']); + let (value_raw, comment) = match rest.find(" #") { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, ""), + }; + let value = value_raw.trim(); + let quoted = value.starts_with(['"', '\'']) && value.len() >= 2; + let bare = if quoted { + &value[1..value.len() - 1] + } else { + value + }; + if bare.is_empty() || is_public_header(name) || is_reference_only(bare) { + return line.to_string(); + } + let q = if quoted { &value[..1] } else { "" }; + format!("{head} {q}{}{q}{comment}", mask_secret(bare)) +} + +/// 值不是秘密的请求头。**只列确定的** —— 名单外的一律当密钥处理, +/// 打错一个的代价是界面上多一处打码,漏掉一个的代价是密钥进了诊断包。 +pub fn is_public_header(name: &str) -> bool { + matches!( + name.trim().to_ascii_lowercase().as_str(), + "anthropic-version" + | "anthropic-beta" + | "openai-organization" + | "openai-project" + | "openai-beta" + | "user-agent" + | "http-referer" + | "referer" + | "x-title" + | "accept" + | "accept-language" + | "content-type" + ) +} + +/// 值里只有环境变量引用、占位符,加上一个短前缀(`Bearer ${TOKEN}`、 +/// `{{access_token}}`)—— 这样的值里没有秘密可泄。 +pub fn is_reference_only(value: &str) -> bool { + if !value.contains("${") && !value.contains("{{") { + return false; + } + let mut rest = String::new(); + let mut s = value; + loop { + let next = [("${", "}"), ("{{", "}}")] + .iter() + .filter_map(|(open, close)| s.find(open).map(|i| (i, *open, *close))) + .min_by_key(|(i, _, _)| *i); + let Some((i, open, close)) = next else { + rest.push_str(s); + break; + }; + rest.push_str(&s[..i]); + match s[i + open.len()..].find(close) { + Some(j) => s = &s[i + open.len() + j + close.len()..], + // 没闭合:不是引用,剩下的全算文字 + None => { + rest.push_str(&s[i..]); + break; + } + } + } + let rest = rest.trim(); + // 前缀只认字母和空格(`Bearer `、`Token `):`sk-live-${SUFFIX}` 里那段 + // `sk-live-` 就是密钥的一部分 + rest.len() <= 16 && rest.chars().all(|c| c.is_ascii_alphabetic() || c == ' ') +} + /// 这个值本身是不是一个 URL(而不是「一段包含 URL 的文本」)。 fn is_url(v: &str) -> bool { let Some(i) = v.find("://") else { @@ -320,10 +398,9 @@ mod line_tests { /// /// ```yaml /// key: mycompany-internal-token-9911 # 自建中转的 key -/// key: -/// oauth: -/// refresh: 1//0gLdOPAQUE # OAuth 的 refresh token -/// client_secret: cs-whatever +/// oauth: +/// refresh: 1//0gLdOPAQUE # OAuth 的 refresh token +/// client_secret: cs-whatever /// ``` /// /// 而诊断包的第一句话是「这份内容里的密钥都已经打码」—— **一个做不到 @@ -343,6 +420,9 @@ pub fn mask_config_yaml(text: &str) -> String { // 块标量(`key: |`)的内容在后面几行上。`mask_line` 只看一行,看不见 // 这种情况 —— 记住宿主那一层的缩进,把整块吃掉 let mut block: Option = None; + // 上游的 `headers:` 那一段。**请求头名说明不了值是不是秘密** + // (`X-Relay-Token`),所以这一段里按请求头的规矩打码,不按字段名 + let mut headers: Option = None; for line in text.lines() { let indent = line.len() - line.trim_start().len(); if let Some(owner) = block { @@ -352,6 +432,32 @@ pub fn mask_config_yaml(text: &str) -> String { } block = None; } + if let Some(owner) = headers { + if line.trim().is_empty() || line.trim_start().starts_with('#') { + out.push_str(line); + out.push('\n'); + continue; + } + if indent > owner { + out.push_str(&mask_header_line(line)); + out.push('\n'); + continue; + } + headers = None; + } + if let Some((name, rest)) = line.trim_start().trim_start_matches("- ").split_once(':') + && name.trim() == "headers" + { + let value = rest.split(" #").next().unwrap_or("").trim(); + if value.is_empty() { + headers = Some(indent); + } else { + // 流式写法(`headers: { X-Token: t }`)整段打掉 + let head = &line[..line.find(':').unwrap_or(0) + 1]; + out.push_str(&format!("{head} {{…}}\n")); + continue; + } + } // **块标量要在打码之前认出来。**`mask_line` 会把 `|` 自己也当成 // 一个值打掉(变成 `key: …`),那之后就再也看不出这里开了个块 —— // 而密钥在下面几行上 @@ -506,7 +612,7 @@ mod body_tests { fn the_config_secrets_that_have_no_recognisable_shape_are_still_masked() { // **这三种实测都能原样穿过 `mask_body`。**它们是这个函数存在的理由 let out = mask_config_yaml( - "providers:\n - name: b\n key: mycompany-internal-token-9911\n - name: c\n key:\n oauth:\n refresh: 1//0gLdOPAQUE-REFRESH\n client_secret: cs-OPAQUE-SECRET\n endpoint: https://auth.example.com/token\n", + "providers:\n - name: b\n key: mycompany-internal-token-9911\n - name: c\n oauth:\n refresh: 1//0gLdOPAQUE-REFRESH\n client_secret: cs-OPAQUE-SECRET\n endpoint: https://auth.example.com/token\n", ); assert!( !out.contains("internal-token-9911"), @@ -600,3 +706,36 @@ mod body_tests { } } } + +#[cfg(test)] +mod header_tests { + use super::*; + + #[test] + fn header_values_in_a_config_are_masked_unless_public_or_references() { + let cfg = "providers:\n - name: relay\n base_url: https://relay.example\n headers:\n X-Relay-Token: rt-verysecretvalue123\n anthropic-version: 2023-06-01\n Authorization: Bearer ${RELAY_TOKEN}\n X-Tenant: \"team-alpha-verysecret\" # 注释留着\n proxy: direct\n"; + let out = mask_config_yaml(cfg); + assert!(!out.contains("verysecretvalue123"), "{out}"); + assert!(!out.contains("team-alpha-verysecret"), "{out}"); + assert!(out.contains("anthropic-version: 2023-06-01"), "{out}"); + assert!(out.contains("Bearer ${RELAY_TOKEN}"), "{out}"); + assert!(out.contains("# 注释留着"), "{out}"); + // 段落结束之后恢复按字段名打码的规矩 + assert!(out.contains("proxy: direct"), "{out}"); + } + + #[test] + fn a_flow_style_headers_map_is_masked_whole() { + let out = mask_config_yaml(" headers: { X-Token: t-verysecretvalue }\n"); + assert!(!out.contains("verysecret"), "{out}"); + } + + #[test] + fn reference_only_values_are_recognised() { + assert!(is_reference_only("${KEY}")); + assert!(is_reference_only("Bearer ${KEY}")); + assert!(is_reference_only("Token {{access_token}}")); + assert!(!is_reference_only("sk-live-${SUFFIX}")); + assert!(!is_reference_only("plain-secret")); + } +}