From a0824900cda8da3b53968d45bd3dc4e2f914b0ff Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Sat, 26 Sep 2026 19:29:23 +0800 Subject: [PATCH] feat(control): hand the UI upstream and proxy settings as written The upstream and proxy views masked what they showed. The base URL was cut down to its origin, so `https://bedrock-mantle.us-east-1.api.aws/v1` came back without `/v1` and with a note that credentials had been hidden when there were none. The API key and header values were masked, and the OAuth refresh token, the client secret and the proxy credentials were left out. The edit dialog could not fill them in, so every write carried "keep what is saved" states instead of values. `GET /config` hands the UI the same file unmasked, so the masking kept nothing from the UI; it only kept the form from showing what is set. Views: - ProviderView: `base_url` and `key` as written (`key` is the value or the `${NAME}` reference); `base_url_masked` and `SecretView` are gone. - HeaderView: `name` and `value` as written; `masked` is gone. - OAuthView gains `refresh` and `client_secret`. The access token stays out: the gateway renews it and writes it back. - ProxyView: `auth` ({ user, pass }) replaces `has_auth`. Writes carry the whole definition: - ProviderInput: `base_url` is required, `key` is an optional string (no key when absent) and every header has a value. `SecretChange` is gone. - ProxyInput: `auth` is optional (no authentication when absent). `ProxyAuthInput` is gone. - OAuthChange keeps `Keep`: while the dialog is open the gateway may renew the token and write back a new refresh token, which revokes the one in the view. - A proxy password may be a `${NAME}` reference, as the configuration reference shows (`pass: ${PROXY_PASSWORD}`), so the dialog can hand it back as written. `control.pass_has_expansion` is gone. Diagnostics bundles and logs still mask; they do not use these views. `Secret::shown` and `Secret::env_var` had no other caller and are gone. CONTROL_API_VERSION is now 25. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/msg-codes.txt | 1 - crates/tw-api/src/lib.rs | 127 +++++++++----------- crates/tw-config/src/credential.rs | 29 +---- crates/tw-control/src/lib.rs | 49 +++----- crates/tw-control/src/resources.rs | 100 +++++++--------- crates/tw-control/tests/chatgpt.rs | 11 +- crates/tw-control/tests/keys.rs | 3 +- crates/tw-control/tests/models.rs | 4 + crates/tw-control/tests/pricing.rs | 17 ++- crates/tw-control/tests/resources.rs | 166 ++++++++++++++------------- 10 files changed, 226 insertions(+), 281 deletions(-) diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 65e6ba0a..06dd8009 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -116,7 +116,6 @@ control.no_keys control.no_such_endpoint control.no_such_version control.not_a_chatgpt_account -control.pass_has_expansion control.patch.no_entry control.patch.not_an_entry control.pricing.broke_off diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 03386352..fb39ab11 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -605,7 +605,16 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// **额度撤下也有事件**:GLM 的 key 被判定没有套餐、core 清掉这一家的额度时,报一条 /// `windows` 为空的 [`Event::QuotaSeen`],界面当场收起那一格,不用等下一次读 `/quota`。 /// 照 23 写的界面不知道空的 `QuotaSeen` 是撤下,还给一个再也不会来的 `monthly` 留着位置。 -pub const CONTROL_API_VERSION: u32 = 24; +/// +/// **25 起上游和代理的设置原样给界面**:[`ProviderView`] 的地址、密钥、请求头值, +/// [`OAuthView`] 的 refresh token 和 client secret,[`ProxyView::auth`] 的用户名和密码, +/// 都是配置里写的样子,不再打码;`base_url_masked`、`SecretView`、`HeaderView.masked`、 +/// `ProxyView.has_auth` 删了。于是保存交的是整份定义:[`ProviderInput`] 的 +/// `base_url` 必给,`key` 不给就是没有密钥,每行请求头都带值,[`ProxyInput::auth`] +/// 不给就是不需要认证 —— `SecretChange` 和 `ProxyAuthInput` 这两个「保持原样」都删了。 +/// 只有 OAuth 还能「保持原样」,见 [`OAuthChange::Keep`]。照 24 写的界面会去 +/// `key.display` 里找密钥,保存时不给地址会被拒。 +pub const CONTROL_API_VERSION: u32 = 25; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1488,11 +1497,8 @@ pub struct PriceSheetView { pub used_by: Vec, } -/// 一个出站代理。 -/// -/// **密码不在这里。**`ProxyAuth.pass` 和上游的 key 是同一类东西 —— -/// 这个视图会进日志、进诊断包、进用户贴出来的截图。有没有认证是要 -/// 显示的,认证内容不是。 +/// 一个出站代理,**认证原样给**:编辑对话框回填的就是它,密码由界面按需隐藏。 +/// 诊断包和日志里的代理另外打码,不用这个视图。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxyView { @@ -1500,9 +1506,9 @@ pub struct ProxyView { /// `socks5h` / `socks5` / `http` / `https` pub kind: ProxyKind, pub addr: String, - /// 有没有认证。**用户名和密码都不在这里** —— 用户名是凭据的一半, - /// 而这个视图会进日志、进诊断包、进用户贴出来的截图 - pub has_auth: bool, + /// 用户名和密码。不需要认证是空 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth: Option, /// 哪些上游在用它。删之前要知道,改名时它们会跟着改 pub used_by: Vec, /// 网关发现它不通了:经它转发的请求连不上之后检过一次,卡在哪一步、为什么。 @@ -1571,24 +1577,23 @@ pub struct SecurityView { pub output_limit: GuardMode, } +/// 一个上游。**设置是配置里写的原样**,密钥也不打码:编辑对话框回填的就是它, +/// 密钥由界面按需隐藏。`GET /config` 本来就给原文,这里打码挡不住什么,只让表单 +/// 回填不了。诊断包和日志里的上游另外打码,不用这个视图。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderView { pub name: String, - /// 已脱敏。**编辑时不要原样写回** —— 地址里带了凭据的话,写回去的 - /// 是打过码的那一份。`base_url_masked` 告诉界面这一点 + /// 配置里写的地址,原样 pub base_url: String, - /// 地址里有被打码的部分(userinfo 之类) - pub base_url_masked: bool, - /// API 密钥:打过码的值,或者环境变量名。没有密钥是空 + /// API 密钥,配置里写的原样:密钥本身,或者 `${NAME}`。没有密钥是空 #[serde(default, skip_serializing_if = "Option::is_none")] - pub key: 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: Option, /// 实际生效的协议:`anthropic` / `openai-chat` / `openai-responses` / @@ -1643,35 +1648,25 @@ pub struct ProviderView { pub pricing: Option, } -/// 一个可能是密钥的值给界面看的样子。 -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -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)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct HeaderView { pub name: String, - /// **可能是密钥的值是打过码的**;公开的头(`anthropic-version` 之类)、 - /// 只由环境变量和占位符组成的值原样给 pub value: String, - /// 值打过码。编辑时这一行不回填,留空表示保持原值 - pub masked: bool, } +/// OAuth 凭据,配置里写的原样。**access token 不在这里**:它由网关换发、写回, +/// 界面拿到的那一把很快就过期。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct OAuthView { pub endpoint: String, + pub refresh: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub client_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_secret: Option, /// access token 什么时候过期,RFC 3339。不知道就没有 #[serde(default, skip_serializing_if = "Option::is_none")] pub expires_at: Option, @@ -2376,19 +2371,18 @@ pub struct ConfigWritten { /// /// **结构,不是 YAML。**以前界面拼一段 YAML 交给补丁接口 —— 拼字符串的 /// 那一方不知道引号规则,一个带 `#` 的值就能写坏整份配置。 +/// +/// **整份定义就是保存之后的样子**:视图给的是原样的设置,界面回填、改完整份交回来。 +/// 只有 OAuth 能「保持原样」,见 [`OAuthChange::Keep`]。 #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderInput { pub name: String, - /// 修改时**不给就是保持原样**:视图里的地址是打过码的,原样写回去 - /// 会把码写进配置 + pub base_url: String, + /// API 密钥,可以写 `${NAME}` 从环境变量读。不给就是没有密钥 #[serde(default, skip_serializing_if = "Option::is_none")] - pub base_url: Option, - /// API 密钥。修改时默认保持原样 —— 界面拿不到原值,也不该拿到 - #[serde(default)] - pub key: SecretChange, - /// 请求头,按顺序。**整张表就是保存之后的样子**:没列出来的行被删掉, - /// 某一行不给 `value` 表示沿用同名那一行的原值 + pub key: Option, + /// 请求头,按顺序。没列出来的行被删掉 #[serde(default, skip_serializing_if = "Vec::is_empty")] pub headers: Vec, /// OAuth。修改时默认保持原样 @@ -2511,33 +2505,22 @@ fn fail_closed() -> OnProxyFail { OnProxyFail::Fail } -/// 一个密钥类的值怎么改。**三态**,因为视图里拿不到原值:不动就得有「保持原样」。 -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] -#[cfg_attr(feature = "ts", derive(ts_rs::TS))] -#[serde(tag = "mode", rename_all = "snake_case")] -pub enum SecretChange { - #[default] - Keep, - None, - /// 可以写 `${ENV}` 从环境变量读 - Set { - value: String, - }, -} - #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct HeaderInput { pub name: String, - /// 不给表示沿用同名那一行的原值 - #[serde(default, skip_serializing_if = "Option::is_none")] - pub value: Option, + /// 可以写 `${NAME}` + pub value: String, } +/// OAuth 凭据怎么改。 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] #[serde(tag = "mode", rename_all = "snake_case")] pub enum OAuthChange { + /// 保持原样,界面没改这几项时交它。**不能拿视图里的值交 `Set`**:网关随时会 + /// 换发 token、把新的 refresh token 写回(服务端同时作废旧的),视图里的那把 + /// 可能已经不能用了;access token 和过期时间视图里也没有 #[default] Keep, None, @@ -2570,7 +2553,8 @@ pub struct ProviderSave { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProviderTest { pub provider: ProviderInput, - /// 正在编辑的是哪一家。给了的话,表单里没改的凭据和地址从它那儿取 + /// 正在编辑的是哪一家。OAuth 交的是 [`OAuthChange::Keep`] 时,按这个原来的名字 + /// 向网关取 token —— 缓存和轮换写回都认名字,而表单里可能刚改了名 #[serde(default, skip_serializing_if = "Option::is_none")] pub current: Option, } @@ -2583,23 +2567,17 @@ pub struct ProxyInput { pub kind: ProxyKind, /// `host:port` pub addr: String, - pub auth: ProxyAuthInput, + /// 不给就是不需要认证 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub auth: Option, } -/// 代理的认证怎么处理。 -/// -/// **三态**,因为视图里拿不到原来的用户名和密码:编辑时不动认证,就得有 -/// 一个「保持原样」的说法,而不是把空值当成「清掉」。 -#[derive(Debug, Clone, Serialize, Deserialize)] +/// 代理的用户名和密码。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] -#[serde(tag = "mode", rename_all = "snake_case")] -pub enum ProxyAuthInput { - /// 保持原来的认证(新建时等同于不需要认证) - Keep, - /// 不需要认证 - None, - /// 设成这一对 - Set { user: String, pass: String }, +pub struct ProxyAuth { + pub user: String, + pub pass: String, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -2615,6 +2593,7 @@ pub struct ProxySave { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct ProxyTest { pub proxy: ProxyInput, + /// 正在编辑的是哪一个。握手的目标取它原来服务的上游 #[serde(default, skip_serializing_if = "Option::is_none")] pub current: Option, } @@ -4518,7 +4497,9 @@ mod tests { ); let mut o = OAuthView { endpoint: "https://auth.example/token".into(), + refresh: "rt".into(), client_id: None, + client_secret: None, expires_at: None, failure: None, needs_login: false, diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index edcb4b2d..38b1655c 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -58,7 +58,8 @@ impl Secret { Self(s.into()) } - /// 写在配置里的原文。**可能是明文密钥** —— 只给要写回配置的调用方用。 + /// 写在配置里的原文。**可能是明文密钥** —— 给要写回配置的调用方,和编辑 + /// 对话框要回填的上游视图。 pub fn raw(&self) -> &str { &self.0 } @@ -68,16 +69,6 @@ impl Secret { Ok(tw_secret::expand_from_env(&self.0)?) } - /// 给界面的形态,**永远不含真实密钥**:带 `${NAME}` 的原样给(写的是 - /// 从哪个环境变量读),其余打码。怎么称呼它由界面决定。 - pub fn shown(&self) -> String { - if self.0.contains("${") { - self.0.clone() - } else { - tw_secret::mask_secret(&self.0) - } - } - /// 命令行和诊断包里的说法,**永远不含真实密钥**。 pub fn describe(&self) -> String { if self.0.contains("${") { @@ -87,15 +78,6 @@ impl Secret { } } - /// 整个值恰好是一个 `${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() } @@ -849,11 +831,4 @@ mod tests { 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-control/src/lib.rs b/crates/tw-control/src/lib.rs index 9d563330..9714661a 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -313,9 +313,10 @@ async fn overview(State(s): State) -> Json { name: x.name.clone(), kind: x.kind.into(), addr: x.addr.clone(), - // **密码不出这个函数。**它和上游的 key 是同一类东西, - // 而这个视图会进日志、进诊断包、进用户贴出来的截图。 - has_auth: x.auth.is_some(), + auth: x.auth.as_ref().map(|a| tw_api::ProxyAuth { + user: a.user.clone(), + pass: a.pass.raw().to_string(), + }), used_by: tw_config::refs::proxy_users(cfg, &x.name), unreachable: s.gateway.proxy_fault(&x.name), }) @@ -404,49 +405,33 @@ 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, - } -} - -/// 一个上游给界面看的样子。**任何一个字段都不带密钥原文。** +/// 一个上游给界面看的样子:设置是配置里写的原样,见 [`tw_api::ProviderView`]。 fn provider_view( s: &ControlState, cfg: &tw_config::Config, p: &tw_config::Provider, ) -> tw_api::ProviderView { - let base_url = tw_secret::redact_url(&p.base_url); let listing = s.gateway.models.listing(p); tw_api::ProviderView { name: p.name.clone(), - base_url_masked: base_url != p.base_url, - base_url, - key: p.key.as_ref().map(|k| tw_api::SecretView { - display: k.shown(), - env: k.env_var().map(str::to_string), - }), + base_url: p.base_url.clone(), + key: p.key.as_ref().map(|k| k.raw().to_string()), auth_header: p.auth_header().0.to_string(), - headers: p.headers.iter().map(header_view).collect(), + headers: p + .headers + .iter() + .map(|h| tw_api::HeaderView { + name: h.name.clone(), + value: h.value.raw().to_string(), + }) + .collect(), oauth: p.oauth.as_ref().map(|o| { let failure = s.gateway.oauth.failure(&p.name, o); tw_api::OAuthView { endpoint: o.endpoint.clone(), + refresh: o.refresh.clone(), client_id: o.client_id.clone(), + client_secret: o.client_secret.clone(), expires_at: o.expires_at.clone(), needs_login: failure.as_ref().is_some_and(|(_, relogin)| *relogin), failure: failure.map(|(why, _)| why), diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index a4cd2c49..d1c801eb 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -316,42 +316,32 @@ fn to_provider( existing: Option<&tw_config::Provider>, ) -> Result { let name = checked_name(&input.name, "upstream")?; - let base_url = match (&input.base_url, existing) { - (Some(u), _) => u.trim().to_string(), - (None, Some(e)) => e.base_url.clone(), - (None, None) => { - return Err(msg!( - "control.base_url_empty" => "The endpoint address cannot be empty." - )); - } - }; - let key = match (&input.key, existing) { - (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(msg!("control.api_key_empty" => "The API key cannot be empty.")); - } - Some(tw_config::Secret::new(v)) - } + let base_url = input.base_url.trim().to_string(); + if base_url.is_empty() { + return Err(msg!( + "control.base_url_empty" => "The endpoint address cannot be empty." + )); + } + let key = match input.key.as_deref().map(str::trim) { + Some("") => return Err(msg!("control.api_key_empty" => "The API key cannot be empty.")), + Some(v) => Some(tw_config::Secret::new(v)), + None => None, }; 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(|| { - msg!("control.header_no_value", header = name.clone() => "Header `{header}` has no value.") - })?, - }; - Ok(tw_config::Header { name, value }) + let value = h.value.trim(); + if value.is_empty() { + return Err( + msg!("control.header_no_value", header = name => "Header `{header}` has no value."), + ); + } + Ok(tw_config::Header { + name, + value: tw_config::Secret::new(value), + }) }) .collect::, Msg>>()?; let oauth = match (&input.oauth, existing) { @@ -425,7 +415,7 @@ async fn create_proxy( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { - let px = to_proxy(&req.proxy, None).map_err(invalid)?; + let px = to_proxy(&req.proxy).map_err(invalid)?; Ok(edit::upsert(text, edit::PROXIES, None, &mapping(&px)?)?) }) .await @@ -441,12 +431,10 @@ async fn update_proxy( let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, cfg| { - let existing = cfg - .proxies - .iter() - .find(|p| p.name == name) - .ok_or_else(|| not_found("proxy", &name))?; - let px = to_proxy(&req.proxy, Some(existing)).map_err(invalid)?; + if !cfg.proxies.iter().any(|p| p.name == name) { + return Err(not_found("proxy", &name)); + } + let px = to_proxy(&req.proxy).map_err(invalid)?; let mut out = edit::upsert(text, edit::PROXIES, Some(&name), &mapping(&px)?)?; if px.name != name { out = refs::rename_proxy(&out, cfg, &name, &px.name)?; @@ -487,16 +475,15 @@ async fn test_proxy( Json(req): Json, ) -> Result, Fail> { let cfg = s.config(); - let existing = match req.current.as_deref() { - Some(n) => Some(cfg.proxies.iter().find(|p| p.name == n).ok_or_else(|| { - fail( - StatusCode::NOT_FOUND, - msg!("control.proxy_not_found", proxy = n => "There is no proxy named `{proxy}`."), - ) - })?), - None => None, - }; - let px = to_proxy(&req.proxy, existing).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; + if let Some(n) = req.current.as_deref() + && !cfg.proxies.iter().any(|p| p.name == n) + { + return Err(fail( + StatusCode::NOT_FOUND, + msg!("control.proxy_not_found", proxy = n => "There is no proxy named `{proxy}`."), + )); + } + let px = to_proxy(&req.proxy).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; let hop = tw_gateway::hop_of(&px).map_err(|e| fail(StatusCode::BAD_REQUEST, e))?; // 握手的目标:正在编辑的那个代理原来服务的上游 let (host, port) = tw_gateway::proxy_target(&cfg, req.current.as_deref().unwrap_or(&px.name)); @@ -504,10 +491,7 @@ async fn test_proxy( Ok(Json(crate::l1_view(px.name.clone(), None, r))) } -fn to_proxy( - input: &tw_api::ProxyInput, - existing: Option<&tw_config::Proxy>, -) -> Result { +fn to_proxy(input: &tw_api::ProxyInput) -> Result { let name = checked_name(&input.name, "proxy")?; if matches!(name.as_str(), tw_config::DIRECT | tw_config::SYSTEM) { return Err(msg!( @@ -526,20 +510,14 @@ fn to_proxy( )); } let auth = match &input.auth { - // 没动认证:沿用原来那一份,**原值不经过界面** - tw_api::ProxyAuthInput::Keep => existing.and_then(|e| e.auth.clone()), - tw_api::ProxyAuthInput::None => None, - tw_api::ProxyAuthInput::Set { user, pass } => { + None => None, + Some(tw_api::ProxyAuth { user, pass }) => { let user = user.trim(); if user.is_empty() { return Err(msg!("control.user_empty" => "The user name cannot be empty.")); } - // `${` 在配置里表示「从环境变量读」 - if pass.contains("${") { - return Err( - msg!("control.pass_has_expansion" => "A password cannot contain `${{`."), - ); - } + // 和密钥一样可以写 `${NAME}`:界面回填的是配置里写的原样,手写的 + // `pass: ${PROXY_PASSWORD}` 原样交回来 Some(tw_config::proxy::ProxyAuth { user: user.to_string(), pass: tw_config::Secret::new(pass.clone()), diff --git a/crates/tw-control/tests/chatgpt.rs b/crates/tw-control/tests/chatgpt.rs index 2706789c..cb5d78f0 100644 --- a/crates/tw-control/tests/chatgpt.rs +++ b/crates/tw-control/tests/chatgpt.rs @@ -1151,12 +1151,13 @@ async fn who_is_signed_in_is_read_from_the_stored_credential_without_asking_anyo o["account"], json!({"email": "someone@example.com", "plan": "plus"}) ); - // 令牌本身不出这个进程 + // refresh token 是配置里写的,原样给;access token 由网关换发、写回,不在概览里 + assert_eq!(o["refresh"], "rt-cfg"); let (_, all) = b.call("GET", "/overview", Value::Null).await; - let text = all.to_string(); - for secret in [access.as_str(), "rt-cfg", "rt-sso", "rt-opaque"] { - assert!(!text.contains(secret), "{secret} 出现在概览里"); - } + assert!( + !all.to_string().contains(access.as_str()), + "access token 出现在概览里" + ); // 不是 ChatGPT 账号:套餐这个说法对它不成立,令牌里有邮箱也不读 let sso = b.oauth_view("company-sso").await; assert!(sso.get("account").is_none(), "{sso}"); diff --git a/crates/tw-control/tests/keys.rs b/crates/tw-control/tests/keys.rs index a74f8083..d607b17c 100644 --- a/crates/tw-control/tests/keys.rs +++ b/crates/tw-control/tests/keys.rs @@ -120,10 +120,9 @@ async fn the_list_shows_the_value_and_says_which_one_is_the_default() { let (st, v) = call(&b.app, "GET", "/keys/codex/value", serde_json::Value::Null).await; assert_eq!((st, v["key"].as_str()), (StatusCode::OK, Some("tw-bbbb"))); - // 概览到处都在读,它那份是脱敏的;上游的凭据哪里都不出现 + // 概览到处都在读,它那份网关密钥是脱敏的 let (_, ov) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; assert_ne!(ov["clients"][0]["key"], "tw-aaaa"); - assert!(!ov.to_string().contains("sk-official")); } #[tokio::test] diff --git a/crates/tw-control/tests/models.rs b/crates/tw-control/tests/models.rs index 3c54a4a1..17b92c52 100644 --- a/crates/tw-control/tests/models.rs +++ b/crates/tw-control/tests/models.rs @@ -267,6 +267,8 @@ async fn disabling_and_scoping_an_upstream_is_written_and_an_empty_scope_is_refu "/providers/relay", serde_json::json!({ "provider": { "name": "relay", + "base_url": format!("http://{up}"), + "key": "sk-good", "protocol": "anthropic", "models_only": ["claude-*"], "disabled": true, @@ -289,6 +291,8 @@ async fn disabling_and_scoping_an_upstream_is_written_and_an_empty_scope_is_refu "/providers/relay", serde_json::json!({ "provider": { "name": "relay", + "base_url": format!("http://{up}"), + "key": "sk-good", "protocol": "anthropic", "models_only": [], }}), diff --git a/crates/tw-control/tests/pricing.rs b/crates/tw-control/tests/pricing.rs index 60e12ace..838c150d 100644 --- a/crates/tw-control/tests/pricing.rs +++ b/crates/tw-control/tests/pricing.rs @@ -29,6 +29,17 @@ providers: key: sk-relay "; +/// `BASE` 里的 relay-hk 整份定义,选的是 `pricing` 这张价目表(空 = 默认的)。 +/// 保存交的是整份:少交一项就是把它删了 +fn relay_hk(pricing: Option<&str>) -> serde_json::Value { + serde_json::json!({ + "name": "relay-hk", + "base_url": "https://relay.example", + "key": "sk-relay", + "pricing": pricing, + }) +} + struct Bed { dir: tempfile::TempDir, state: ControlState, @@ -139,7 +150,7 @@ async fn a_sheet_is_created_chosen_renamed_and_deleted_only_once_nobody_uses_it( &b.app, "PUT", "/providers/relay-hk", - serde_json::json!({ "provider": { "name": "relay-hk", "pricing": "中转协议价" } }), + serde_json::json!({ "provider": relay_hk(Some("中转协议价")) }), ) .await; assert_eq!(st, StatusCode::OK, "{body}"); @@ -181,7 +192,7 @@ async fn a_sheet_is_created_chosen_renamed_and_deleted_only_once_nobody_uses_it( &b.app, "PUT", "/providers/relay-hk", - serde_json::json!({ "provider": { "name": "relay-hk" } }), + serde_json::json!({ "provider": relay_hk(None) }), ) .await; assert_eq!(st, StatusCode::OK, "{body}"); @@ -279,7 +290,7 @@ async fn an_upstream_cannot_choose_a_sheet_that_does_not_exist() { &b.app, "PUT", "/providers/relay-hk", - serde_json::json!({ "provider": { "name": "relay-hk", "pricing": "没有这张" } }), + serde_json::json!({ "provider": relay_hk(Some("没有这张")) }), ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); diff --git a/crates/tw-control/tests/resources.rs b/crates/tw-control/tests/resources.rs index 7925a3ae..80caf7bd 100644 --- a/crates/tw-control/tests/resources.rs +++ b/crates/tw-control/tests/resources.rs @@ -103,11 +103,25 @@ fn relay(name: &str) -> serde_json::Value { serde_json::json!({ "name": name, "base_url": "https://relay.example", - "key": { "mode": "set", "value": "sk-relay#1: x" }, + "key": "sk-relay#1: x", "protocol": "anthropic", }) } +/// `BASE` 里的「官方」整份定义,`changes` 里的几项替换上去。**保存交的是整份**: +/// 少交一项就是把它删了 +fn official(changes: serde_json::Value) -> serde_json::Value { + let mut p = serde_json::json!({ + "name": "官方", + "base_url": "https://api.anthropic.com", + "key": "sk-official", + }); + for (k, v) in changes.as_object().unwrap() { + p[k] = v.clone(); + } + p +} + // ─────────────────────────────────────────────────────────── 概览 /// 概览自带改配置要用的版本号:和 `GET /config` 的一样,改完跟着换。 @@ -186,14 +200,19 @@ async fn a_new_upstream_lands_with_its_key_intact_and_every_comment_kept() { } #[tokio::test] -async fn editing_without_a_key_keeps_the_key_and_touches_only_what_changed() { +async fn saving_an_upstream_as_the_overview_shows_it_touches_only_what_changed() { + // 界面回填的就是概览里的样子:地址和密钥原样交回去,文件里那两行一个字节不动 let b = bed(BASE); + let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; + let shown = &json(&body)["providers"][0]; let (st, body) = call( &b.app, "PUT", "/providers/官方", serde_json::json!({ "provider": { "name": "官方", + "base_url": shown["base_url"], + "key": shown["key"], "proxy": "system", "billing": "free", }}), @@ -201,7 +220,6 @@ async fn editing_without_a_key_keeps_the_key_and_touches_only_what_changed() { .await; assert_eq!(st, StatusCode::OK, "{body}"); let file = b.file(); - // 没交地址和凭据 = 保持原样 assert!(file.contains("key: sk-official"), "{file}"); assert!( file.contains("base_url: https://api.anthropic.com # 直连"), @@ -222,7 +240,7 @@ async fn billing_is_per_token_or_free_and_nothing_else() { &b.app, "PUT", "/providers/官方", - serde_json::json!({ "provider": { "name": "官方", "billing": gone }}), + serde_json::json!({ "provider": official(serde_json::json!({ "billing": gone })) }), ) .await; // 取值不在集合里:请求体本身读不成 @@ -238,7 +256,7 @@ async fn renaming_an_upstream_moves_its_references_in_the_same_version() { &b.app, "PUT", "/providers/官方", - serde_json::json!({ "provider": { "name": "anthropic" } }), + serde_json::json!({ "provider": official(serde_json::json!({ "name": "anthropic" })) }), ) .await; assert_eq!(st, StatusCode::OK, "{body}"); @@ -304,7 +322,8 @@ async fn a_duplicate_name_and_a_stale_version_are_both_conflicts() { } #[tokio::test] -async fn the_overview_says_where_a_credential_comes_from_and_never_the_value() { +async fn the_overview_shows_the_settings_as_written() { + // 编辑对话框回填的就是它:地址带着路径、密钥和请求头都是原样,由界面决定藏不藏 let b = bed(BASE); let (st, body) = call( &b.app, @@ -312,8 +331,8 @@ async fn the_overview_says_where_a_credential_comes_from_and_never_the_value() { "/providers", serde_json::json!({ "provider": { "name": "env", - "base_url": "https://relay.example", - "key": { "mode": "set", "value": "${RELAY_KEY}" }, + "base_url": "https://relay.example/v1", + "key": "${RELAY_KEY}", "headers": [ { "name": "X-Relay-Tenant", "value": "tenant-verysecretvalue" }, { "name": "anthropic-version", "value": "2023-06-01" }, @@ -323,15 +342,11 @@ async fn the_overview_says_where_a_credential_comes_from_and_never_the_value() { .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!( - official["key"]["display"].as_str().unwrap().contains('…'), - "{body}" - ); + assert_eq!(official["base_url"], "https://api.anthropic.com", "{body}"); + assert_eq!(official["key"], "sk-official", "{body}"); assert_eq!(official["auth_header"], "x-api-key"); assert_eq!(official["protocol"], "anthropic"); assert_eq!(official["protocol_explicit"], false); @@ -339,46 +354,35 @@ async fn the_overview_says_where_a_credential_comes_from_and_never_the_value() { assert!(official.get("trust").is_none(), "{body}"); assert_eq!(official["references"][0]["kind"], "group"); let env = providers.iter().find(|p| p["name"] == "env").unwrap(); - 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); + assert_eq!(env["base_url"], "https://relay.example/v1", "{body}"); + assert_eq!(env["key"], "${RELAY_KEY}"); + assert_eq!( + env["headers"], + serde_json::json!([ + { "name": "X-Relay-Tenant", "value": "tenant-verysecretvalue" }, + { "name": "anthropic-version", "value": "2023-06-01" }, + ]) + ); } #[tokio::test] -async fn a_header_saved_without_a_value_keeps_the_stored_one() { - // 视图里的值是打过码的,界面不回填 —— 不改的那一行就不带值 +async fn a_header_without_a_value_is_refused() { let b = bed(BASE); - call( + let before = b.file(); + let (st, body) = call( &b.app, "POST", "/providers", serde_json::json!({ "provider": { "name": "relay", "base_url": "https://relay.example", - "headers": [{ "name": "X-Relay-Token", "value": "rt-1" }], + "headers": [{ "name": "X-Relay-Token", "value": " " }], }}), ) .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"); + assert_eq!(st, StatusCode::BAD_REQUEST, "{body}"); + assert_eq!(json(&body)["code"], "control.header_no_value", "{body}"); + assert_eq!(b.file(), before); } #[tokio::test] @@ -407,37 +411,52 @@ fn corp(auth: serde_json::Value) -> serde_json::Value { } #[tokio::test] -async fn a_proxy_password_is_written_intact_kept_on_edit_and_never_shown() { +async fn a_proxy_password_is_written_intact_and_shown_as_written() { let b = bed(BASE); + let auth = serde_json::json!({ "user": "svc", "pass": "p@ss #1: x" }); let (st, body) = call( &b.app, "POST", "/proxies", - serde_json::json!({ "proxy": corp(serde_json::json!({ "mode": "set", "user": "svc", "pass": "p@ss #1: x" })) }), + serde_json::json!({ "proxy": corp(auth.clone()) }), ) .await; assert_eq!(st, StatusCode::OK, "{body}"); - // 改地址、不动认证 + let (_, body) = call(&b.app, "GET", "/overview", serde_json::Value::Null).await; + assert_eq!(json(&body)["proxies"][0]["auth"], auth, "{body}"); + + // 改地址,认证照概览里的样子交回去 let (st, body) = call( &b.app, "PUT", "/proxies/corp", serde_json::json!({ "proxy": { - "name": "corp", "kind": "http", "addr": "10.0.0.2:8080", "auth": { "mode": "keep" } + "name": "corp", "kind": "http", "addr": "10.0.0.2:8080", "auth": auth }}), ) .await; assert_eq!(st, StatusCode::OK, "{body}"); let cfg = b.parsed(); - let auth = cfg.proxies[0].auth.as_ref().expect("没动认证,认证不该丢"); - assert_eq!(auth.user, "svc"); - assert_eq!(auth.pass.raw(), "p@ss #1: x"); + let written = cfg.proxies[0].auth.as_ref().unwrap(); + assert_eq!(written.user, "svc"); + assert_eq!(written.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; - assert!(!body.contains("p@ss"), "{body}"); - assert!(!body.contains("\"svc\""), "用户名也是凭据的一半:{body}"); - assert_eq!(json(&body)["proxies"][0]["has_auth"], true); +#[tokio::test] +async fn a_proxy_password_read_from_the_environment_round_trips() { + // 文档里的写法:`pass: ${PROXY_PASSWORD}`。概览原样给,界面原样交回来 + let b = bed(BASE); + let auth = serde_json::json!({ "user": "svc", "pass": "${PROXY_PASSWORD}" }); + let (st, body) = call( + &b.app, + "POST", + "/proxies", + serde_json::json!({ "proxy": corp(auth) }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{body}"); + assert!(b.file().contains("pass: ${PROXY_PASSWORD}"), "{}", b.file()); } #[tokio::test] @@ -447,7 +466,7 @@ async fn renaming_a_proxy_moves_the_upstreams_that_use_it_and_a_used_proxy_is_no &b.app, "POST", "/proxies", - serde_json::json!({ "proxy": corp(serde_json::json!({ "mode": "none" })) }), + serde_json::json!({ "proxy": corp(serde_json::Value::Null) }), ) .await; let mut r = relay("relay"); @@ -470,7 +489,7 @@ async fn renaming_a_proxy_moves_the_upstreams_that_use_it_and_a_used_proxy_is_no "PUT", "/proxies/corp", serde_json::json!({ "proxy": { - "name": "corp-http", "kind": "http", "addr": "10.0.0.1:8080", "auth": { "mode": "keep" } + "name": "corp-http", "kind": "http", "addr": "10.0.0.1:8080" }}), ) .await; @@ -524,7 +543,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": { "mode": "set", "value": "sk-good" }, + "key": "sk-good", "protocol": "anthropic", }}), ) @@ -540,19 +559,20 @@ async fn testing_an_unsaved_upstream_uses_the_protocol_and_lists_the_models() { } #[tokio::test] -async fn testing_an_edited_upstream_without_a_new_key_uses_the_stored_one() { +async fn testing_an_edited_upstream_checks_what_the_form_holds() { + // 存着的是 `sk-official`,表单里改成了什么就测什么 let up = fake_upstream().await; - let b = bed(&BASE - .replace("https://api.anthropic.com # 直连", &format!("http://{up}")) - .replace("sk-official", "sk-good")); - let (_, body) = call( - &b.app, - "POST", - "/providers/test", - serde_json::json!({ "provider": { "name": "官方" }, "current": "官方" }), - ) - .await; + let b = bed(BASE); + let test = |key: &str| { + serde_json::json!({ + "provider": official(serde_json::json!({ "base_url": format!("http://{up}"), "key": key })), + "current": "官方", + }) + }; + let (_, body) = call(&b.app, "POST", "/providers/test", test("sk-good")).await; assert_eq!(json(&body)["ok"], true, "{body}"); + let (_, body) = call(&b.app, "POST", "/providers/test", test("sk-official")).await; + assert_eq!(json(&body)["ok"], false, "{body}"); } #[tokio::test] @@ -612,7 +632,7 @@ async fn fake_connect_proxy() -> std::net::SocketAddr { } #[tokio::test] -async fn testing_a_proxy_checks_its_credentials_including_the_stored_ones() { +async fn testing_a_proxy_checks_its_credentials() { let px = fake_connect_proxy().await; let b = bed(BASE); let with = |auth: serde_json::Value| serde_json::json!({ "name": "corp", "kind": "http", "addr": px.to_string(), "auth": auth }); @@ -621,7 +641,7 @@ async fn testing_a_proxy_checks_its_credentials_including_the_stored_ones() { &b.app, "POST", "/proxies/test", - serde_json::json!({ "proxy": with(serde_json::json!({ "mode": "set", "user": "svc", "pass": "bad" })) }), + serde_json::json!({ "proxy": with(serde_json::json!({ "user": "svc", "pass": "bad" })) }), ) .await; let v = json(&body); @@ -629,19 +649,11 @@ async fn testing_a_proxy_checks_its_credentials_including_the_stored_ones() { // 按码断言:这条测的是「握手做完了、认证验过了」,不是那句话怎么写 assert_eq!(v["error"]["code"], "l1.http_proxy.auth_required", "{body}"); - // 存下正确的,再用「保持原样」检测 —— 用的是存着的那份 - call( - &b.app, - "POST", - "/proxies", - serde_json::json!({ "proxy": with(serde_json::json!({ "mode": "set", "user": "svc", "pass": "good" })) }), - ) - .await; let (_, body) = call( &b.app, "POST", "/proxies/test", - serde_json::json!({ "proxy": with(serde_json::json!({ "mode": "keep" })), "current": "corp" }), + serde_json::json!({ "proxy": with(serde_json::json!({ "user": "svc", "pass": "good" })) }), ) .await; assert_eq!(json(&body)["ok"], true, "{body}");