diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 3a0bcd2e..d8da90a1 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -654,7 +654,7 @@ fn cmd_check(path: &Path) -> Result<()> { println!( " · OAuth: getting a token needs the network, and happens once the gateway starts" ); - } else if let Err(e) = p.outbound_headers(None, None) { + } else if let Err(e) = p.outbound_headers(None) { println!(" ⚠ the credential could not be obtained: {e}"); } } diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index de9bd5c5..8cb62cdd 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -11,8 +11,7 @@ //! - **`oauth`**:access token 由 refresh token 换发。token 默认放进协议的鉴权头, //! 也可以在 `headers` 里用 `{{access_token}}` 指定放在哪儿、怎么拼。 //! -//! 值里可以写 `${ENV}` 从环境变量读;`{{client}}` 换成发起这次请求的那把网关 -//! 密钥的名字,给按调用方记账的中转站用。 +//! 值里可以写 `${ENV}` 从环境变量读。 //! //! **没有「跑一条命令拿密钥」这一类,而且不会有**:配置文件不该能执行程序 —— //! 「配置被同步、被分享、被 AI 改」都是目标场景,那时抄一份配置就等于跑一段代码。 @@ -24,8 +23,6 @@ use tw_types::{Msg, msg}; /// `headers` 里换成 OAuth access token 的占位符。 pub const ACCESS_TOKEN: &str = "{{access_token}}"; -/// `headers` 里换成网关密钥名字的占位符。 -pub const CLIENT: &str = "{{client}}"; /// 一个请求头最多几行、名字和值最长多少。**上限是给写错兜底的** —— 一个把整段 /// PEM 贴进请求头的配置,该在加载时被拦下,而不是在上游那边变成一个 431。 @@ -347,9 +344,8 @@ impl CredentialError { characters" ), UnknownPlaceholder { name, placeholder } => msg!( - "config.credential.unknown_placeholder", header = name, placeholder = placeholder => - "{placeholder} in the `{header}` header is not recognized; only {{{{access_token}}}} \ - and {{{{client}}}} are" + "config.credential.unrecognized_placeholder", header = name, placeholder = placeholder => + "{placeholder} in the `{header}` header is not recognized; only {{{{access_token}}}} is" ), TokenWithoutOauth(h) => msg!( "config.credential.token_without_oauth", header = h => @@ -493,7 +489,7 @@ impl Provider { return Err(CredentialError::BadHeaderValue(h.name.clone())); } for p in placeholders(raw) { - if p != ACCESS_TOKEN && p != CLIENT { + if p != ACCESS_TOKEN { return Err(CredentialError::UnknownPlaceholder { name: h.name.clone(), placeholder: p.to_string(), @@ -518,11 +514,9 @@ impl Provider { /// 要发给这家的全部请求头,值已经展开。 /// /// `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); @@ -538,9 +532,6 @@ impl Provider { 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) @@ -596,17 +587,17 @@ mod tests { 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(), + anthropic.outbound_headers(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(), + openai.outbound_headers(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(), + gemini.outbound_headers(None).unwrap(), vec![("x-goog-api-key".to_string(), "g-k".to_string())] ); } @@ -614,14 +605,14 @@ mod tests { #[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", + "name: r\nbase_url: https://relay.example\nkey: sk-r\nheaders:\n anthropic-version: 2023-06-01\n X-Tenant: team-a\n", ); assert_eq!( - x.outbound_headers(None, Some("laptop")).unwrap(), + x.outbound_headers(None).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()), + ("X-Tenant".to_string(), "team-a".to_string()), ] ); // 往返一次顺序不变 @@ -634,7 +625,7 @@ mod tests { 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(), + x.outbound_headers(None).unwrap(), vec![("X-Relay-Token".to_string(), "t-1".to_string())] ); } @@ -645,7 +636,7 @@ mod tests { x.oauth = Some(oauth()); x.check_credential().unwrap(); assert_eq!( - x.outbound_headers(Some("at-1"), None).unwrap(), + x.outbound_headers(Some("at-1")).unwrap(), vec![("authorization".to_string(), "Bearer at-1".to_string())] ); x.headers = Headers::new(vec![Header { @@ -654,7 +645,7 @@ mod tests { }]); x.check_credential().unwrap(); assert_eq!( - x.outbound_headers(Some("at-2"), None).unwrap(), + x.outbound_headers(Some("at-2")).unwrap(), vec![("X-Token".to_string(), "Token at-2".to_string())] ); } @@ -703,6 +694,16 @@ mod tests { unknown.check_credential(), Err(CredentialError::UnknownPlaceholder { .. }) )); + // 按调用方填网关密钥名的 {{client}} 已经不支持了 + let client = + p("name: r\nbase_url: https://relay.example\nheaders:\n X-A: \"{{client}}\"\n"); + assert_eq!( + client.check_credential(), + Err(CredentialError::UnknownPlaceholder { + name: "X-A".into(), + placeholder: "{{client}}".into(), + }) + ); let no_oauth = p("name: r\nbase_url: https://relay.example\nheaders:\n X-A: \"{{access_token}}\"\n"); assert_eq!( @@ -768,7 +769,7 @@ mod tests { }); login.check_credential().unwrap(); assert_eq!( - login.outbound_headers(Some("at"), None).unwrap(), + login.outbound_headers(Some("at")).unwrap(), vec![ ("authorization".to_string(), "Bearer at".to_string()), ("ChatGPT-Account-Id".to_string(), "acc-1".to_string()), @@ -810,7 +811,7 @@ mod tests { "name: r\nbase_url: https://relay.example\nheaders:\n Authorization: Token ${TW_TEST_RELAY_TOKEN}\n", ); assert_eq!( - x.outbound_headers(None, None).unwrap(), + x.outbound_headers(None).unwrap(), vec![("Authorization".to_string(), "Token from-env".to_string())] ); } diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index ea2aa11a..3d87857d 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -1327,7 +1327,7 @@ providers: ..Default::default() }; assert_eq!( - p.outbound_headers(None, None).unwrap(), + p.outbound_headers(None).unwrap(), vec![("x-api-key".to_string(), "sk-from-env".to_string())] ); } diff --git a/crates/tw-control/src/chatgpt.rs b/crates/tw-control/src/chatgpt.rs index da140a81..0496476f 100644 --- a/crates/tw-control/src/chatgpt.rs +++ b/crates/tw-control/src/chatgpt.rs @@ -885,13 +885,13 @@ async fn account_call( }; let headers = s .gateway - .headers_for(p, &http, None) + .headers_for(p, &http) .await .map_err(no_credential)?; let sent_at = std::time::Instant::now(); let mut resp = send(&http, method.clone(), &url, &headers, body).await?; if resp.status() == StatusCode::UNAUTHORIZED - && let Ok(fresh) = s.gateway.headers_after_401(p, &http, None, sent_at).await + && let Ok(fresh) = s.gateway.headers_after_401(p, &http, sent_at).await && fresh != headers { resp = send(&http, method, &url, &fresh, body).await?; diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index fa38ddb9..241176f8 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -830,7 +830,7 @@ async fn speed_run( // OAuth 那类要联网换 token,所以走网关那条 async 的路。 // **用这一家自己的 client** —— 换 token 要走它的代理。 let pk_http = s.gateway.client_for(&p.name); - let headers = match s.gateway.headers_for(p, &pk_http, None).await { + let headers = match s.gateway.headers_for(p, &pk_http).await { Ok(h) => h, Err(e) => { out.push(tw_api::SpeedResult { diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index c6ccbc83..4c6d9f89 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -176,7 +176,7 @@ pub async fn run( let pk_http = s.gateway.client_for(&provider.name); let headers = s .gateway - .headers_for(provider, &pk_http, None) + .headers_for(provider, &pk_http) .await .map_err(|e| { fail( diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index 8b6bacb1..95fd1569 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -227,7 +227,7 @@ async fn test_provider( } _ => None, }; - let headers = match p.outbound_headers(token.as_deref(), None) { + let headers = match p.outbound_headers(token.as_deref()) { Ok(h) => h, Err(e) => return Ok(Json(failed(e.to_string()))), }; diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index 3a063034..4e977970 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -371,7 +371,7 @@ 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 headers = match state.headers_for(p, http, None).await { + let headers = match state.headers_for(p, http).await { Ok(h) => h, Err(e) => return Answer::Failed(format!("the credential could not be obtained: {e}")), }; diff --git a/crates/tw-gateway/src/oauth.rs b/crates/tw-gateway/src/oauth.rs index 12acb4d8..be8db8f3 100644 --- a/crates/tw-gateway/src/oauth.rs +++ b/crates/tw-gateway/src/oauth.rs @@ -662,7 +662,7 @@ mod tests { ..Default::default() }; assert_eq!( - p.outbound_headers(None, None), + p.outbound_headers(None), Err(tw_config::CredentialError::NoToken) ); } diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 7450585a..f62c93b1 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -374,19 +374,16 @@ impl AppState { /// `http` 必须是**这一家自己的** client:换 token 要走它该走的代理。 /// 用一个干净的 client 去换,代理后面的用户会得到一个 /// 「数据面通、刷新不通」的组合 —— 而那个症状看起来完全不像凭据问题。 - /// - /// `client`:发起请求的网关密钥名,填 `{{client}}` 用。后台的探测没有这个人。 pub async fn headers_for( &self, p: &tw_config::Provider, http: &reqwest::Client, - 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) + p.outbound_headers(token.as_deref()) .map_err(|e| e.to_string()) } @@ -413,7 +410,6 @@ impl AppState { &self, p: &tw_config::Provider, http: &reqwest::Client, - client: Option<&str>, sent_at: std::time::Instant, ) -> Result, String> { let o = p @@ -425,8 +421,7 @@ impl AppState { .invalidate_and_refresh(&p.name, o, http, sent_at) .await; let token = self.settle_token(p, got)?; - p.outbound_headers(Some(&token), client) - .map_err(|e| e.to_string()) + p.outbound_headers(Some(&token)).map_err(|e| e.to_string()) } /// 换一个 access token,服务器换发了新的 refresh token 就交给控制面写回。 @@ -1047,15 +1042,12 @@ async fn ws_upgrade( ))); } let http = rt.clients.get(&name).unwrap_or(&state.http); - let upstream_headers = state - .headers_for(provider, http, Some(&client_name)) - .await - .map_err(|e| { - GatewayError::config(msg!( - "gw.credentials.failed", upstream = name.clone(), detail = e => - "The credential for upstream `{upstream}` could not be obtained: {detail}" - )) - })?; + let upstream_headers = state.headers_for(provider, http).await.map_err(|e| { + GatewayError::config(msg!( + "gw.credentials.failed", upstream = name.clone(), detail = e => + "The credential for upstream `{upstream}` could not be obtained: {detail}" + )) + })?; let id = state.bus.next_id(); state.bus.emit(tw_api::Event::RequestStarted { id, @@ -1921,7 +1913,7 @@ async fn pipeline( // 用这个 provider 自己的 Client —— 它带着该走的代理。**在取密钥 // 之前拿到**:OAuth 换 token 也要走这条代理。 let http = rt.clients.get(&provider.name).unwrap_or(&state.http); - let upstream_headers = match state.headers_for(provider, http, Some(&client_name)).await { + let upstream_headers = match state.headers_for(provider, http).await { Ok(h) => h, Err(e) => { // 密钥取不到是这一家的问题(环境变量没设、token 端点 @@ -1996,10 +1988,7 @@ async fn pipeline( // 吊销了、提前失效了;不重试的话,这个请求连同之后每一个请求都会原样失败,直到 // 缓存里那个 token 按时间过期。换回来的还是 401,说明问题不在 token if provider.oauth.is_some() && matches!(&sent, Ok(r) if r.status() == 401) { - match state - .headers_after_401(provider, http, Some(&client_name), sent_at) - .await - { + match state.headers_after_401(provider, http, sent_at).await { // 换回来的还是同一个(刚换过不久):再发一次也是 401 Ok(fresh) if fresh != upstream_headers => { sent = build(&fresh).body(outbound.clone()).send().await; diff --git a/crates/tw-gateway/tests/chatgpt.rs b/crates/tw-gateway/tests/chatgpt.rs index c11cd43f..62105ea4 100644 --- a/crates/tw-gateway/tests/chatgpt.rs +++ b/crates/tw-gateway/tests/chatgpt.rs @@ -668,7 +668,7 @@ async fn an_inference_test_reaches_the_codex_backend_and_times_the_first_token() assert_eq!(cap, None); let http = state.client_for(&p.name); - let headers = state.headers_for(&p, &http, None).await.unwrap(); + let headers = state.headers_for(&p, &http).await.unwrap(); let r = tw_gateway::l3::run(&http, &p, &headers, "gpt-5.5", cap).await; assert!(r.ok, "{:?}", r.error); @@ -709,7 +709,7 @@ async fn a_refused_inference_test_carries_what_the_backend_said() { }) .unwrap(); let http = state.client_for(&p.name); - let headers = state.headers_for(&p, &http, None).await.unwrap(); + let headers = state.headers_for(&p, &http).await.unwrap(); let r = tw_gateway::l3::run(&http, &p, &headers, "gpt-5.5", None).await; assert!(!r.ok); let e = r.error.expect("没有错误"); diff --git a/crates/tw-gateway/tests/headers_and_paths.rs b/crates/tw-gateway/tests/headers_and_paths.rs index 52a2150d..e278abd6 100644 --- a/crates/tw-gateway/tests/headers_and_paths.rs +++ b/crates/tw-gateway/tests/headers_and_paths.rs @@ -185,7 +185,7 @@ async fn configured_headers_are_sent_and_replace_the_ones_the_client_sent() { }, Header { name: "X-Relay-Caller".into(), - value: Secret::new("{{client}}"), + value: Secret::new("thinkwatch"), }, ]); let gw = start_gateway(p).await; @@ -204,7 +204,7 @@ async fn configured_headers_are_sent_and_replace_the_ones_the_client_sent() { 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_eq!(g.headers.get("x-relay-caller").unwrap(), "thinkwatch"); assert!(g.headers.get("x-thinkwatch-client").is_none()); }