Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
}
Expand Down
49 changes: 25 additions & 24 deletions crates/tw-config/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
//! - **`oauth`**:access token 由 refresh token 换发。token 默认放进协议的鉴权头,
//! 也可以在 `headers` 里用 `{{access_token}}` 指定放在哪儿、怎么拼。
//!
//! 值里可以写 `${ENV}` 从环境变量读;`{{client}}` 换成发起这次请求的那把网关
//! 密钥的名字,给按调用方记账的中转站用。
//! 值里可以写 `${ENV}` 从环境变量读。
//!
//! **没有「跑一条命令拿密钥」这一类,而且不会有**:配置文件不该能执行程序 ——
//! 「配置被同步、被分享、被 AI 改」都是目标场景,那时抄一份配置就等于跑一段代码。
Expand All @@ -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。
Expand Down Expand Up @@ -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 =>
Expand Down Expand Up @@ -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(),
Expand All @@ -518,11 +514,9 @@ impl Provider {
/// 要发给这家的全部请求头,值已经展开。
///
/// `access_token`:配了 oauth 时由调用方换好传进来(换 token 要联网,这里是同步的)。
/// `client`:发起请求的那把网关密钥的名字,没有就换成空串。
pub fn outbound_headers(
&self,
access_token: Option<&str>,
client: Option<&str>,
) -> Result<Vec<(String, String)>, CredentialError> {
let (auth_name, prefix) = self.auth_header();
let mut out = Vec::with_capacity(self.headers.len() + 1);
Expand All @@ -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)
Expand Down Expand Up @@ -596,32 +587,32 @@ 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())]
);
}

#[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()),
]
);
// 往返一次顺序不变
Expand All @@ -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())]
);
}
Expand All @@ -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 {
Expand All @@ -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())]
);
}
Expand Down Expand Up @@ -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!(
Expand Down Expand Up @@ -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()),
Expand Down Expand Up @@ -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())]
);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())]
);
}
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-control/src/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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?;
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/src/replay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-control/src/resources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()))),
};
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-gateway/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}")),
};
Expand Down
2 changes: 1 addition & 1 deletion crates/tw-gateway/src/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,7 @@ mod tests {
..Default::default()
};
assert_eq!(
p.outbound_headers(None, None),
p.outbound_headers(None),
Err(tw_config::CredentialError::NoToken)
);
}
Expand Down
31 changes: 10 additions & 21 deletions crates/tw-gateway/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<(String, String)>, 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())
}

Expand All @@ -413,7 +410,6 @@ impl AppState {
&self,
p: &tw_config::Provider,
http: &reqwest::Client,
client: Option<&str>,
sent_at: std::time::Instant,
) -> Result<Vec<(String, String)>, String> {
let o = p
Expand All @@ -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 就交给控制面写回。
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 端点
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-gateway/tests/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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("没有错误");
Expand Down
4 changes: 2 additions & 2 deletions crates/tw-gateway/tests/headers_and_paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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());
}

Expand Down
Loading