From ec35c246e9460a807962929c93b738a6b5d80e9c Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:08:55 +0800 Subject: [PATCH 1/3] fix(secret): mask AWS access keys in configuration excerpts Configuration excerpts (diagnostics bundles, rejected-config messages) mask values by field name, and an AWS secret access key has no shape to catch otherwise: 40 characters, often with only one or two digits. access_key_id, secret_access_key and session_token are now secret names, and ASIA (a temporary access key ID) joins AKIA among the credential-looking prefixes. Co-Authored-By: Claude Opus 5.5 --- crates/tw-secret/src/mask.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/tw-secret/src/mask.rs b/crates/tw-secret/src/mask.rs index 2b8598a9..606b5597 100644 --- a/crates/tw-secret/src/mask.rs +++ b/crates/tw-secret/src/mask.rs @@ -273,6 +273,11 @@ fn is_secret_name(name: &str) -> bool { "access", "access_token", "client_secret", + // Bedrock 的 AWS 访问密钥(`aws:` 那一段)。**私有访问密钥长得不像密钥**: + // 40 个字符,数字常常只有一两个,按形状认不出来 + "access_key_id", + "secret_access_key", + "session_token", ]; NAMES.contains(&name) } @@ -289,6 +294,8 @@ fn looks_like_credential(v: &str) -> bool { "github_pat_", "xoxb-", "AKIA", + // AWS 的临时访问密钥 ID + "ASIA", "AIza", "ya29.", "Bearer ", @@ -671,6 +678,18 @@ mod body_tests { ); } + #[test] + fn a_bedrock_upstreams_aws_keys_are_masked() { + let cfg = "providers:\n - name: bedrock\n base_url: https://bedrock-runtime.us-east-1.amazonaws.com\n aws:\n access_key_id: AKIAIOSFODNN7EXAMPLE\n secret_access_key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n session_token: FwoGZXIvYXdzEXAMPLE\n region: us-east-1\n - name: from-env\n base_url: https://bedrock-runtime.us-east-1.amazonaws.com\n aws:\n access_key_id: ${AWS_ACCESS_KEY_ID}\n secret_access_key: ${AWS_SECRET_ACCESS_KEY}\n"; + let out = mask_config_yaml(cfg); + for secret in ["IOSFODNN7", "K7MDENG", "FwoGZXIvYXdz"] { + assert!(!out.contains(secret), "{secret} leaked: {out}"); + } + assert!(out.contains("region: us-east-1"), "{out}"); + // 临时凭证的访问密钥 ID 出现在别处(请求体、报错)也认得出 + assert!(!mask_body("the key is ASIAIOSFODNN7EXAMPLE here").contains("IOSFODNN7")); + } + #[test] fn a_field_that_merely_ends_in_key_is_not_a_secret() { // `api_key_env` 之类装的是环境变量名,不是密钥。多打码的代价小, From a3a2cd57d12d1a9c41f4e6d83372d5a43aef31e4 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:08:55 +0800 Subject: [PATCH 2/3] feat(bedrock): name the anthropic-beta values Bedrock takes A client talking to Anthropic sends its betas in the anthropic-beta header; converted to Converse, Claude on Bedrock takes them in additionalModelRequestFields.anthropic_beta, as Claude Code does when it calls Bedrock itself. Only the ones AWS lists for Claude on Bedrock and that still mean something after conversion are passed on; forwarding the whole list would get the request refused for a beta Bedrock does not know (oauth-, prompt-caching-scope- and the like). Co-Authored-By: Claude Opus 5.5 --- crates/tw-bedrock/src/beta.rs | 103 ++++++++++++++++++++++++++++++++++ crates/tw-bedrock/src/lib.rs | 2 + 2 files changed, 105 insertions(+) create mode 100644 crates/tw-bedrock/src/beta.rs diff --git a/crates/tw-bedrock/src/beta.rs b/crates/tw-bedrock/src/beta.rs new file mode 100644 index 00000000..989d0174 --- /dev/null +++ b/crates/tw-bedrock/src/beta.rs @@ -0,0 +1,103 @@ +//! Anthropic 的 beta 功能在 Bedrock 上怎么开。 +//! +//! 客户端直连 Anthropic 时把 beta 写在 `anthropic-beta` 请求头里。转成 Converse 之后 +//! 没有这个头可发,Claude 的 beta 放进请求体的 `additionalModelRequestFields.anthropic_beta` +//! —— Claude Code 自己连 Bedrock 时也是把头里的值搬进请求体的 `anthropic_beta`。 +//! +//! **只带 Bedrock 认的那几个。**直连 Anthropic 的客户端会带上一整串只有 Anthropic +//! 认的 beta(`oauth-…`、`prompt-caching-scope-…` 这些),原样交给 Bedrock,整个请求 +//! 会因为不认识的 beta 被拒。名单取自 AWS 为 Bedrock 上的 Claude 列出的 beta,只留 +//! 转成 Converse 之后还有意义的:服务端工具、上下文管理、压缩这些对应的请求字段在 +//! 转换时已经丢掉了,只开 beta 没有用处。 + +use serde_json::{Map, Value}; + +/// Bedrock 上的 Claude 认、转成 Converse 之后仍然有用的 beta。 +pub const SUPPORTED: &[&str] = &[ + // 思考和工具调用交替进行(Claude 4 起) + "interleaved-thinking-2025-05-14", + // 100 万 token 的上下文 + "context-1m-2025-08-07", + // Claude 3.7 Sonnet 的 128k 输出 + "output-128k-2025-02-19", + // 工具调用少用一些输出 token + "token-efficient-tools-2025-02-19", + // 工具参数边生成边流出来 + "fine-grained-tool-streaming-2025-05-14", +]; + +/// 客户端 `anthropic-beta` 头里 Bedrock 认的那些,去重、保持顺序。头可能分几行写, +/// 每行也可能是逗号隔开的一串。 +pub fn supported<'a>(header_values: impl IntoIterator) -> Vec { + let mut out: Vec = Vec::new(); + for v in header_values { + for b in v.split(',').map(str::trim) { + if SUPPORTED.contains(&b) && !out.iter().any(|x| x == b) { + out.push(b.to_string()); + } + } + } + out +} + +/// 把 beta 写进一份 Converse 请求体的 `additionalModelRequestFields.anthropic_beta`。 +/// 请求体读不成 JSON 对象时原样返回 `None`,不猜。 +pub fn with_betas(body: &[u8], betas: &[String]) -> Option> { + if betas.is_empty() { + return None; + } + let mut v: Value = serde_json::from_slice(body).ok()?; + let fields = v + .as_object_mut()? + .entry("additionalModelRequestFields") + .or_insert_with(|| Value::Object(Map::new())) + .as_object_mut()?; + fields.insert( + "anthropic_beta".into(), + Value::Array(betas.iter().cloned().map(Value::String).collect()), + ); + serde_json::to_vec(&v).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_what_bedrock_takes_is_kept_once_in_order() { + let got = supported([ + "claude-code-20250219,interleaved-thinking-2025-05-14, oauth-2025-04-20", + "context-1m-2025-08-07,interleaved-thinking-2025-05-14", + "prompt-caching-scope-2026-01-05", + ]); + assert_eq!( + got, + ["interleaved-thinking-2025-05-14", "context-1m-2025-08-07"] + ); + assert!(supported(["claude-code-20250219"]).is_empty()); + } + + #[test] + fn betas_join_whatever_else_goes_to_the_model() { + let body = + br#"{"messages":[],"additionalModelRequestFields":{"thinking":{"type":"adaptive"}}}"#; + let out = with_betas(body, &["context-1m-2025-08-07".to_string()]).unwrap(); + let v: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!( + v["additionalModelRequestFields"], + serde_json::json!({ + "thinking": {"type": "adaptive"}, + "anthropic_beta": ["context-1m-2025-08-07"], + }) + ); + } + + #[test] + fn a_body_without_the_pocket_gets_one_and_nothing_is_touched_without_betas() { + let out = with_betas(br#"{"messages":[]}"#, &["x".to_string()]).unwrap(); + let v: Value = serde_json::from_slice(&out).unwrap(); + assert_eq!(v["additionalModelRequestFields"]["anthropic_beta"][0], "x"); + assert!(with_betas(br#"{"messages":[]}"#, &[]).is_none()); + assert!(with_betas(b"not json", &["x".to_string()]).is_none()); + } +} diff --git a/crates/tw-bedrock/src/lib.rs b/crates/tw-bedrock/src/lib.rs index 4d0ce765..0b48b678 100644 --- a/crates/tw-bedrock/src/lib.rs +++ b/crates/tw-bedrock/src/lib.rs @@ -1,6 +1,7 @@ //! Amazon Bedrock 在线路上要的东西,两个网关共用。 //! //! - [`endpoint`]:区域、runtime 和控制面的地址、模型 id 怎么写进路径 +//! - [`beta`]:客户端的 `anthropic-beta` 里哪些能带给 Bedrock 上的 Claude //! - [`sign`]:SigV4 签名,以及「带 API Key 就不签」这条规则 //! - [`eventstream`]:ConverseStream 的二进制帧 → SSE //! - [`catalog`]:一个区域能路由到哪些模型 @@ -13,6 +14,7 @@ //! 这是第一层:只依赖第三方 crate 和第一层的彼此(`tw-dialect` 的 //! `layer_one_depends_only_on_itself` 守着)。 +pub mod beta; pub mod catalog; pub mod endpoint; pub mod error; From 0be55721efdef1bdc67747ca6ea115417af19574 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:08:55 +0800 Subject: [PATCH 3/3] feat(gateway): AWS Bedrock upstreams A new protocol, bedrock, for Amazon Bedrock's Converse API, built on the shared tw-bedrock crate. Configuration - A Bedrock API key goes in `key` and is sent as Authorization: Bearer. AWS access keys go in a new `aws` block (access_key_id, secret_access_key, optional session_token, all `${VAR}`-capable); every request is signed with them. Exactly one of the two; no oauth; the signed headers cannot be set among `headers`. Nothing runs a command to obtain a credential. - The region comes from a standard runtime address (https://bedrock-runtime[-fips]..amazonaws.com), which is also how the protocol is recognized. Any other address (a VPC endpoint, a proxy, a local test server) needs `aws.region`, and the model list is asked of that address too. - Secret's Debug no longer prints a key. Forwarding - Generation requests are always converted to Converse. The model id is escaped into /model/{id}/converse[-stream] (an ARN's slash), and the request is signed last, over the URL reqwest actually sends and the final body. The same helper signs the speed test. - The betas Bedrock takes are carried into additionalModelRequestFields.anthropic_beta for Claude. - ConverseStream answers in AWS eventstream frames. The relay unframes them to SSE where the bytes come in, so usage, first token, the stored response, placeholder restoration, conversion and tool inspection all read SSE; an exception frame ends the stream as a failed request, a throttling one as rate-limited. - A 401/403 from Bedrock names the AWS account and IAM principal, so its body is replaced with our own sentence (with the exception name, and a separate one for an expired session token) before it reaches the client or the request log. Control plane - Test connection and the model directory list the region's catalog: foundation models, AWS-defined inference profiles and application inference profiles by ARN. AccessDeniedException there means the credential works and may not list models; it is not a rejected key. - The preview and the upstream view carry the region; the view carries the aws block as written. Control API version 28. - A replay sends the recorded request as it was, which a Bedrock upstream cannot take; it is refused with a sentence saying so. The config manuals, the message-code manifest and smoke.sh (a fake Bedrock that checks the signed body hash and answers in real eventstream frames) cover the new protocol. twcore grows by 393 KB (2.2%) on arm64 macOS. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 5 + bin/twcore/src/main.rs | 20 +- crates/tw-api/msg-codes.txt | 18 + crates/tw-api/src/lib.rs | 47 +- crates/tw-config/Cargo.toml | 2 + crates/tw-config/src/credential.rs | 322 ++++++++- crates/tw-config/src/lib.rs | 78 +++ crates/tw-config/src/wire.rs | 2 + crates/tw-config/tests/manual/schema.rs | 60 +- crates/tw-control/Cargo.toml | 2 + crates/tw-control/src/lib.rs | 10 + crates/tw-control/src/replay.rs | 22 + crates/tw-control/src/resources.rs | 25 +- crates/tw-control/tests/bedrock.rs | 268 ++++++++ crates/tw-control/tests/replay.rs | 29 + crates/tw-gateway/Cargo.toml | 5 + crates/tw-gateway/src/bedrock.rs | 42 ++ crates/tw-gateway/src/client_api.rs | 3 +- crates/tw-gateway/src/egress.rs | 12 +- crates/tw-gateway/src/l3.rs | 72 ++- crates/tw-gateway/src/lib.rs | 3 +- crates/tw-gateway/src/models.rs | 21 +- crates/tw-gateway/src/probe.rs | 98 +++ crates/tw-gateway/src/server/pipeline/hop.rs | 163 ++++- .../tw-gateway/src/server/pipeline/relay.rs | 64 ++ crates/tw-gateway/src/translate.rs | 1 + crates/tw-gateway/tests/bedrock.rs | 609 ++++++++++++++++++ docs/config.md | 61 +- docs/config.zh-CN.md | 40 +- scripts/smoke.sh | 99 ++- 30 files changed, 2144 insertions(+), 59 deletions(-) create mode 100644 crates/tw-control/tests/bedrock.rs create mode 100644 crates/tw-gateway/src/bedrock.rs create mode 100644 crates/tw-gateway/tests/bedrock.rs diff --git a/Cargo.lock b/Cargo.lock index cfae742d..8f422489 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2794,6 +2794,7 @@ dependencies = [ "thiserror", "tokio", "tw-api", + "tw-bedrock", "tw-engine", "tw-guard", "tw-pricing", @@ -2830,6 +2831,7 @@ dependencies = [ "tower", "tracing", "tw-api", + "tw-bedrock", "tw-config", "tw-engine", "tw-gateway", @@ -2870,6 +2872,8 @@ version = "0.54.0" dependencies = [ "arc-swap", "async-stream", + "aws-smithy-eventstream", + "aws-smithy-types", "axum", "base64", "blake3", @@ -2896,6 +2900,7 @@ dependencies = [ "tower", "tracing", "tw-api", + "tw-bedrock", "tw-breaker", "tw-config", "tw-dialect", diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index d092a2c1..fc89db13 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -612,11 +612,19 @@ fn cmd_check(path: &Path) -> Result<()> { None => "not recognized (forwarded in the Anthropic format)".to_string(), }; // 说来源而不是值。 - let credential = match (&p.key, &p.oauth) { - (Some(k), _) => format!("API key {} ({})", k.describe(), p.auth_header().0), - (None, Some(_)) => "OAuth".to_string(), - (None, None) if !p.headers.is_empty() => "headers".to_string(), - (None, None) => "no credential".to_string(), + let credential = match (&p.key, &p.oauth, &p.aws) { + (Some(k), _, _) => { + format!("API key {} ({})", k.describe(), p.auth_header().0) + } + (None, Some(_), _) => "OAuth".to_string(), + // 签名用的密钥:说来源(环境变量还是写死的),不说值 + (None, None, Some(a)) => format!( + "AWS access key {}, signed for {}", + a.access_key_id.describe(), + p.bedrock_region().unwrap_or("an unknown region") + ), + (None, None, None) if !p.headers.is_empty() => "headers".to_string(), + (None, None, None) => "no credential".to_string(), }; println!( " · {} → {} [{}] {credential}", @@ -673,6 +681,8 @@ fn cmd_check(path: &Path) -> Result<()> { ); } else if let Err(e) = p.outbound_headers(None) { println!(" ⚠ the credential could not be obtained: {e}"); + } else if let Err(e) = p.aws_credentials() { + println!(" ⚠ the AWS access keys could not be obtained: {e}"); } } Ok(()) diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index 8984ec0b..e8fa1e44 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -9,8 +9,16 @@ config.bad_remote_allow_from config.blank_models_only config.control_key_invalid config.control_key_missing +config.credential.aws_bad_region +config.credential.aws_empty +config.credential.aws_no_region +config.credential.aws_not_bedrock +config.credential.aws_region_mismatch +config.credential.aws_signed_header config.credential.bad_header_name config.credential.bad_header_value +config.credential.bedrock_no_credential +config.credential.bedrock_oauth config.credential.chatgpt_client_identity config.credential.chatgpt_without_login config.credential.claude_subscription @@ -20,6 +28,7 @@ config.credential.empty_oauth config.credential.google_subscription config.credential.identity_header config.credential.key_and_auth_header +config.credential.key_and_aws config.credential.key_and_oauth config.credential.no_token config.credential.oauth_and_auth_header @@ -135,6 +144,7 @@ control.redirect_must_be_app_scheme control.remote.control_section_locked control.remote.diagnostics_refused control.remote.shutdown_refused +control.replay_bedrock control.request_body_gone control.request_body_truncated control.request_not_found @@ -238,6 +248,8 @@ gw.oauth.status gw.oauth.unreachable gw.output_limit.cut gw.output_limit.withheld +gw.probe.aws_token_expired +gw.probe.bedrock_list_denied gw.probe.connect gw.probe.key_rejected gw.probe.request_failed @@ -253,9 +265,14 @@ gw.route.selected_upstream_missing gw.route.upstream_missing gw.toolcall.blocked gw.toolcall.cut +gw.upstream.aws_token_expired +gw.upstream.bedrock_refused +gw.upstream.eventstream_broken gw.upstream.forward_failed gw.upstream.rate_limited +gw.upstream.sign_failed gw.upstream.status +gw.upstream.stream_exception gw.upstream.timeout gw.upstream.unreachable gw.ws.bad_header @@ -323,6 +340,7 @@ l1.tls.failed l1.unreachable l3.not_streamed l3.refused +l3.sign_failed l3.stream_failed pricing.sheet.bad_multiplier pricing.sheet.bad_price diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index a3424d5f..0e2ddfc6 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -100,6 +100,8 @@ slug_enum! { Gemini = "gemini", /// ChatGPT 账号登录的 Codex 后端 Chatgpt = "chatgpt", + /// Amazon Bedrock 的 Converse 接口:Bedrock API Key,或者 AWS 访问密钥签名 + Bedrock = "bedrock", } } @@ -110,7 +112,7 @@ slug_enum! { OpenaiChat = "openai-chat", OpenaiResponses = "openai-responses", Gemini = "gemini", - /// 只有企业版接 Bedrock;桌面版不会发出这个词 + /// Bedrock 的 Converse。只会是上游的格式:客户端不说它 Bedrock = "bedrock", } } @@ -627,7 +629,13 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// `/latency` 两个端点和 [`LiveView::tokens_per_sec`] 同版改成从第一个 token 算:以前 /// 从响应头算,非流式请求的响应头要等整段生成完才到,一条就能把速度顶到几万。照 26 /// 写的界面不认那个新事件。 -pub const CONTROL_API_VERSION: u32 = 27; +/// +/// **28 起有 Bedrock 上游**:[`Protocol`] 多了 `bedrock`,[`ProviderInput::aws`] / +/// [`ProviderView::aws`]([`AwsKeys`]:AWS 访问密钥,每个请求签名)、 +/// [`ProviderView::region`] 和 [`ProviderPreview::region`]。Bedrock API Key 走 +/// 原来的 `key`,放进 `Authorization: Bearer`。照 27 写的界面解析不了带 `bedrock` 的 +/// 上游列表。 +pub const CONTROL_API_VERSION: u32 = 28; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -1629,8 +1637,14 @@ pub struct ProviderView { pub headers: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub oauth: Option, + /// Bedrock 的 AWS 访问密钥,配置里写的原样。用 API Key 的、别的协议的都是空 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws: Option, + /// Bedrock 的区域:标准地址里的那个,或者 `aws.region`。别的协议是空 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub region: Option, /// 实际生效的协议:`anthropic` / `openai-chat` / `openai-responses` / - /// `gemini`。猜不出来时为空 + /// `gemini` / `bedrock`。猜不出来时为空 pub protocol: Option, /// 协议是配置里写明的,还是按地址推断的 pub protocol_explicit: bool, @@ -1691,6 +1705,24 @@ pub struct HeaderView { pub value: String, } +/// Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。每一项都可以写 +/// `${NAME}` 从环境变量读。视图和保存用的是同一个:配置里写的原样。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct AwsKeys { + /// 访问密钥 ID + pub access_key_id: String, + /// 私有访问密钥 + pub secret_access_key: String, + /// 会话令牌:临时凭证才有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_token: Option, + /// 签名用的区域。地址是标准的 `https://bedrock-runtime.<区域>.amazonaws.com` + /// 时不用给,从地址读 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub region: Option, +} + /// OAuth 凭据,配置里写的原样。**access token 不在这里**:它由网关换发、写回, /// 界面拿到的那一把很快就过期。 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -2423,7 +2455,10 @@ pub struct ProviderInput { /// OAuth。修改时默认保持原样 #[serde(default)] pub oauth: OAuthChange, - /// `anthropic` / `openai-chat` / `openai-responses` / `gemini`。 + /// Bedrock 的 AWS 访问密钥。和 `key`(Bedrock API Key)二选一;不给就是不用 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws: Option, + /// `anthropic` / `openai-chat` / `openai-responses` / `gemini` / `bedrock`。 /// 不给就按地址推断 #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option, @@ -2473,6 +2508,10 @@ pub struct ProviderPreview { /// API 密钥放在哪个请求头里:`x-api-key` / `authorization` / `x-goog-api-key`。 /// 选定了协议按选定的算,否则按推断出的 pub auth_header: String, + /// 标准 Bedrock 地址(`https://bedrock-runtime.<区域>.amazonaws.com`)里的区域。 + /// 别的地址是空 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub region: Option, } slug_enum! { diff --git a/crates/tw-config/Cargo.toml b/crates/tw-config/Cargo.toml index 84dadad0..15f8a800 100644 --- a/crates/tw-config/Cargo.toml +++ b/crates/tw-config/Cargo.toml @@ -18,6 +18,8 @@ tw-api = { workspace = true } tw-secret = { workspace = true } # 校验要认得出配置里写到的内置脱敏规则 id tw-guard = { workspace = true } +# Bedrock 的区域:认标准地址、校验区域代码,和转发时用的是同一份 +tw-bedrock = { workspace = true } regex = { workspace = true } tw-pricing = { workspace = true } # 凭据轮换要把一个标量写回 config.yaml。**span 补丁,不是 diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index 3f2a9c7e..9ca69bb0 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -10,6 +10,8 @@ //! `X-Relay-Token` 的中转站就接不进来。 //! - **`oauth`**:access token 由 refresh token 换发。token 默认放进协议的鉴权头, //! 也可以在 `headers` 里用 `{{access_token}}` 指定放在哪儿、怎么拼。 +//! - **`aws`**:Bedrock 的 AWS 访问密钥。它们不放进哪个头:每个请求在转发时用它们 +//! 签名(SigV4)。Bedrock 的 API Key 走 `key`,和别家一样。 //! //! 值里可以写 `${ENV}` 从环境变量读。 //! @@ -46,13 +48,29 @@ const RESERVED: &[&str] = &[ "proxy-authorization", ]; +/// 用 AWS 访问密钥签名时由签名写的头。配置里再写一份,发出去的请求就对不上签名 +const SIGNED: &[&str] = &[ + "authorization", + "x-amz-date", + "x-amz-content-sha256", + "x-amz-security-token", +]; + /// 可以带 `${ENV}` 的字符串:密钥、代理密码、请求头的值。 /// /// 明文写在配置里(不做 keychain)。配置文件里看不出 `${ENV}` 和明文的区别, /// 也不该看出 —— 两种写法对读的人是一回事。 -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Clone, Default, PartialEq, Eq)] pub struct Secret(String); +/// **Debug 不打印密钥**:`Provider` 这些带着它的结构会进日志和 panic 信息。 +/// `${ENV}` 照写(那不是密钥),明文只留头尾几个字符。 +impl std::fmt::Debug for Secret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_tuple("Secret").field(&self.describe()).finish() + } +} + impl Secret { pub fn new(s: impl Into) -> Self { Self(s.into()) @@ -255,9 +273,10 @@ impl<'de> Deserialize<'de> for Headers { 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) | Some(Protocol::Chatgpt) => { - ("authorization", "Bearer ") - } + Some(Protocol::OpenaiChat) + | Some(Protocol::OpenaiResponses) + | Some(Protocol::Chatgpt) + | Some(Protocol::Bedrock) => ("authorization", "Bearer "), Some(Protocol::Anthropic) | None => ("x-api-key", ""), } } @@ -303,6 +322,24 @@ pub enum CredentialError { OauthAndAuthHeader(String), #[error("{}", self.msg())] NoToken, + #[error("{}", self.msg())] + BedrockOauth, + #[error("{}", self.msg())] + KeyAndAws, + #[error("{}", self.msg())] + BedrockNoCredential, + #[error("{}", self.msg())] + AwsNotBedrock, + #[error("{}", self.msg())] + AwsEmpty, + #[error("{}", self.msg())] + AwsSignedHeader(String), + #[error("{}", self.msg())] + AwsNoRegion, + #[error("{}", self.msg())] + AwsBadRegion(String), + #[error("{}", self.msg())] + AwsRegionMismatch { given: String, host: String }, /// 环境变量没设之类 #[error("{}", self.msg())] Env(SecretResolveError), @@ -390,6 +427,47 @@ impl CredentialError { "config.credential.no_token" => "an OAuth access token could not be obtained" ), + BedrockOauth => msg!( + "config.credential.bedrock_oauth" => + "a Bedrock upstream takes a Bedrock API key (key) or AWS access keys (aws), not oauth" + ), + KeyAndAws => msg!( + "config.credential.key_and_aws" => + "key and aws are alternatives: a Bedrock API key, or AWS access keys" + ), + BedrockNoCredential => msg!( + "config.credential.bedrock_no_credential" => + "a Bedrock upstream needs a Bedrock API key (key) or AWS access keys (aws)" + ), + AwsNotBedrock => msg!( + "config.credential.aws_not_bedrock" => + "aws (AWS access keys) is only for a Bedrock upstream" + ), + AwsEmpty => msg!( + "config.credential.aws_empty" => + "the access key ID, the secret access key and a session token, when given, cannot \ + be empty" + ), + AwsSignedHeader(h) => msg!( + "config.credential.aws_signed_header", header = h => + "requests to this upstream are signed with its AWS access keys, and signing sets \ + the `{header}` header; it cannot also be set among the headers" + ), + AwsNoRegion => msg!( + "config.credential.aws_no_region" => + "the address is not a standard Bedrock address \ + (https://bedrock-runtime..amazonaws.com), so aws.region has to name the \ + region to sign for" + ), + AwsBadRegion(r) => msg!( + "config.credential.aws_bad_region", region = r => + "`{region}` is not an AWS region code such as us-east-1" + ), + AwsRegionMismatch { given, host } => msg!( + "config.credential.aws_region_mismatch", given = given, host = host => + "aws.region is {given}, and the address is in {host}; the region comes from the \ + address, so aws.region can be left out" + ), // 只在转发时出现(展开 `${VAR}`),写法检查碰不到它 Env(e) => e.msg(), } @@ -452,6 +530,7 @@ impl Provider { { return Err(CredentialError::EmptyKey); } + self.check_bedrock()?; if let Some(o) = &self.oauth { if self.key.is_some() { return Err(CredentialError::KeyAndOauth); @@ -507,6 +586,9 @@ impl Provider { if chatgpt && crate::chatgpt::IDENTITY_HEADERS.contains(&lower.as_str()) { return Err(CredentialError::IdentityHeader(h.name.clone())); } + if self.aws.is_some() && SIGNED.contains(&lower.as_str()) { + return Err(CredentialError::AwsSignedHeader(h.name.clone())); + } if seen.contains(&lower) { return Err(CredentialError::DuplicateHeader(h.name.clone())); } @@ -538,6 +620,65 @@ impl Provider { Ok(()) } + /// Bedrock 的规矩:凭证二选一、访问密钥不能空、签名要知道区域。 + fn check_bedrock(&self) -> Result<(), CredentialError> { + let bedrock = self.effective_protocol() == Some(Protocol::Bedrock); + let host_region = tw_bedrock::endpoint::region_of(&self.base_url); + if let Some(aws) = &self.aws { + if !bedrock { + return Err(CredentialError::AwsNotBedrock); + } + if self.key.is_some() { + return Err(CredentialError::KeyAndAws); + } + if aws.access_key_id.is_blank() + || aws.secret_access_key.is_blank() + || aws.session_token.as_ref().is_some_and(Secret::is_blank) + { + return Err(CredentialError::AwsEmpty); + } + match (host_region, aws.region.as_deref().map(str::trim)) { + (_, Some(given)) if tw_bedrock::endpoint::validate_region(given).is_err() => { + return Err(CredentialError::AwsBadRegion(given.to_string())); + } + (Some(host), Some(given)) if host != given => { + return Err(CredentialError::AwsRegionMismatch { + given: given.to_string(), + host: host.to_string(), + }); + } + (None, None) => return Err(CredentialError::AwsNoRegion), + _ => {} + } + } + if bedrock { + if self.oauth.is_some() { + return Err(CredentialError::BedrockOauth); + } + // AWS 自己的地址一定要凭证;代理(非标准地址)可以自己管认证 + if self.key.is_none() && self.aws.is_none() && host_region.is_some() { + return Err(CredentialError::BedrockNoCredential); + } + } + Ok(()) + } + + /// 签名用的 AWS 凭证,`${ENV}` 已经展开。不用访问密钥的上游是 `None`。 + pub fn aws_credentials(&self) -> Result, CredentialError> { + let Some(aws) = &self.aws else { + return Ok(None); + }; + Ok(Some(tw_bedrock::Credentials { + access_key_id: aws.access_key_id.resolve()?, + secret_access_key: aws.secret_access_key.resolve()?, + session_token: aws + .session_token + .as_ref() + .map(Secret::resolve) + .transpose()?, + })) + } + /// 要发给这家的全部请求头,值已经展开。 /// /// `access_token`:配了 oauth 时由调用方换好传进来(换 token 要联网,这里是同步的)。 @@ -585,6 +726,18 @@ impl Provider { s.push('='); s.push_str(h.value.raw()); } + if let Some(a) = &self.aws { + s.push_str(&format!( + "|aws|{}|{}|{}|{}", + a.access_key_id.raw(), + a.secret_access_key.raw(), + a.session_token + .as_ref() + .map(Secret::raw) + .unwrap_or_default(), + a.region.as_deref().unwrap_or_default() + )); + } s } } @@ -852,4 +1005,165 @@ mod tests { vec![("Authorization".to_string(), "Token from-env".to_string())] ); } + + fn bedrock(extra: &str) -> Provider { + p(&format!( + "name: b\nbase_url: https://bedrock-runtime.us-east-1.amazonaws.com\n{extra}" + )) + } + + const KEYS: &str = + "aws:\n access_key_id: AKIAIOSFODNN7EXAMPLE\n secret_access_key: wJalrXUtnFEMI\n"; + + #[test] + fn a_bedrock_api_key_is_a_bearer_token() { + let b = bedrock("key: ABSK-test\n"); + assert_eq!(b.effective_protocol(), Some(Protocol::Bedrock)); + assert_eq!(b.check_credential(), Ok(())); + assert_eq!( + b.outbound_headers(None).unwrap(), + vec![("authorization".to_string(), "Bearer ABSK-test".to_string())] + ); + assert_eq!(b.aws_credentials(), Ok(None)); + } + + #[test] + fn access_keys_are_not_a_header_they_sign() { + let b = bedrock(KEYS); + assert_eq!(b.check_credential(), Ok(())); + assert!(b.outbound_headers(None).unwrap().is_empty()); + let c = b.aws_credentials().unwrap().unwrap(); + assert_eq!(c.access_key_id, "AKIAIOSFODNN7EXAMPLE"); + assert_eq!(c.session_token, None); + assert_eq!(b.bedrock_region(), Some("us-east-1")); + assert_eq!( + b.bedrock_control_base(), + "https://bedrock.us-east-1.amazonaws.com" + ); + } + + #[test] + fn access_keys_can_come_from_the_environment() { + let b = bedrock( + "aws:\n access_key_id: ${TW_TEST_BEDROCK_AK}\n secret_access_key: ${TW_TEST_BEDROCK_SK}\n session_token: ${TW_TEST_BEDROCK_ST}\n", + ); + assert_eq!(b.check_credential(), Ok(())); + // SAFETY: 测试里只有这一处设这几个变量 + unsafe { + std::env::set_var("TW_TEST_BEDROCK_AK", "ASIAEXAMPLE"); + std::env::set_var("TW_TEST_BEDROCK_SK", "secret"); + } + // 没设的那个变量是这一家拿不到凭证,不是一个空字符串 + assert!(matches!( + b.aws_credentials(), + Err(CredentialError::Env(SecretResolveError::MissingEnv(v))) if v == "TW_TEST_BEDROCK_ST" + )); + unsafe { std::env::set_var("TW_TEST_BEDROCK_ST", "token") }; + let c = b.aws_credentials().unwrap().unwrap(); + assert_eq!( + (c.access_key_id.as_str(), c.session_token.as_deref()), + ("ASIAEXAMPLE", Some("token")) + ); + } + + #[test] + fn a_bedrock_upstream_takes_one_credential() { + use CredentialError::*; + assert_eq!( + bedrock(&format!("key: ABSK-test\n{KEYS}")).check_credential(), + Err(KeyAndAws) + ); + assert_eq!(bedrock("").check_credential(), Err(BedrockNoCredential)); + assert_eq!( + bedrock("oauth:\n refresh: r\n endpoint: https://auth.example.com/token\n") + .check_credential(), + Err(BedrockOauth) + ); + assert_eq!( + bedrock("aws:\n access_key_id: ''\n secret_access_key: s\n").check_credential(), + Err(AwsEmpty) + ); + } + + #[test] + fn access_keys_belong_to_bedrock_only() { + let x = p(&format!( + "name: o\nbase_url: https://api.openai.com\n{KEYS}" + )); + assert_eq!(x.check_credential(), Err(CredentialError::AwsNotBedrock)); + } + + #[test] + fn a_signed_upstream_cannot_set_what_signing_sets() { + let b = bedrock(&format!( + "{KEYS}headers:\n X-Amz-Date: '20260101T000000Z'\n" + )); + assert_eq!( + b.check_credential(), + Err(CredentialError::AwsSignedHeader("X-Amz-Date".into())) + ); + let b = bedrock(&format!("{KEYS}headers:\n Authorization: Bearer x\n")); + assert_eq!( + b.check_credential(), + Err(CredentialError::AwsSignedHeader("Authorization".into())) + ); + } + + #[test] + fn the_region_comes_from_the_address_or_has_to_be_written() { + use CredentialError::*; + // 地址里有区域:写一个不一样的是写错了 + assert_eq!( + bedrock(&format!("{KEYS} region: eu-west-1\n")).check_credential(), + Err(AwsRegionMismatch { + given: "eu-west-1".into(), + host: "us-east-1".into() + }) + ); + assert_eq!( + bedrock(&format!("{KEYS} region: us-east-1\n")).check_credential(), + Ok(()) + ); + // 代理或 VPC 端点:地址里没有区域,签名要知道 + let proxy = |extra: &str| { + p(&format!( + "name: b\nbase_url: https://vpce-0a1b.bedrock-runtime.us-east-1.vpce.amazonaws.com\nprotocol: bedrock\n{KEYS}{extra}" + )) + }; + assert_eq!(proxy("").check_credential(), Err(AwsNoRegion)); + assert_eq!( + proxy(" region: us.east.1\n").check_credential(), + Err(AwsBadRegion("us.east.1".into())) + ); + let ok = proxy(" region: us-east-1\n"); + assert_eq!(ok.check_credential(), Ok(())); + assert_eq!(ok.bedrock_region(), Some("us-east-1")); + // 列模型也问它:控制面的路径和推理的不重叠 + assert_eq!( + ok.bedrock_control_base(), + "https://vpce-0a1b.bedrock-runtime.us-east-1.vpce.amazonaws.com" + ); + // 一个自己管认证的代理可以不带凭证 + let bare = p("name: b\nbase_url: http://127.0.0.1:8080\nprotocol: bedrock\n"); + assert_eq!(bare.check_credential(), Ok(())); + } + + #[test] + fn debug_never_shows_a_plain_secret() { + let b = bedrock("key: ABSK-abcdefghijklmnopqrstuvwxyz0123\n"); + let shown = format!("{b:?}"); + assert!(!shown.contains("abcdefghijklmnopqrstuvwxyz"), "{shown}"); + let env = bedrock("key: ${BEDROCK_KEY}\n"); + assert!(format!("{env:?}").contains("${BEDROCK_KEY}")); + let keys = bedrock(KEYS); + assert!(!format!("{keys:?}").contains("wJalrXUtnFEMI")); + } + + #[test] + fn changing_the_access_keys_changes_the_identity() { + let a = bedrock(KEYS); + let b = + bedrock("aws:\n access_key_id: AKIAIOSFODNN7EXAMPLE\n secret_access_key: another\n"); + assert_ne!(a.credential_identity(), b.credential_identity()); + } } diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 69bb8697..9f81a39c 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -157,6 +157,7 @@ impl Default for Provider { key: None, headers: Headers::default(), oauth: None, + aws: None, protocol: None, forward_client_identity: false, proxy: default_proxy(), @@ -669,6 +670,27 @@ pub struct OAuth { pub refresh_before: Option, } +/// Bedrock 的 AWS 访问密钥。 +/// +/// 每个请求用它们签一次名(SigV4):签的是方法、地址、时间和请求体,所以签名在 +/// 转发时、请求体定稿之后才做,配置里只放密钥本身。每一项都可以写 `${ENV}`。 +/// +/// **只读密钥,不执行命令**:`aws sso login`、`credential_process` 这类要跑程序才拿得到 +/// 的凭证这里接不了,见 [`credential`]。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Aws { + pub access_key_id: Secret, + pub secret_access_key: Secret, + /// 临时凭证(STS 发的)才有 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_token: Option, + /// 签名用的区域。地址是标准的 `https://bedrock-runtime.<区域>.amazonaws.com` 时从 + /// 地址读,不用写;地址是 VPC 端点或代理时必须写 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub region: Option, +} + impl OAuth { /// 提前量。写坏了按默认走 —— **一个写错的提前量不该让上游整个不可用**。 pub fn refresh_before(&self) -> std::time::Duration { @@ -712,6 +734,10 @@ pub struct Provider { /// OAuth:access token 由 refresh token 换发,默认放进协议的鉴权头。 #[serde(default, skip_serializing_if = "Option::is_none")] pub oauth: Option, + /// Bedrock 的 AWS 访问密钥:每个请求用它们签名(SigV4)。和 `key`(Bedrock API + /// Key)二选一。见 [`Aws`] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub aws: Option, /// 不写就从 base_url 猜(最小配置)。 #[serde(default, skip_serializing_if = "Option::is_none")] pub protocol: Option, @@ -831,6 +857,9 @@ pub enum Protocol { /// ChatGPT 账号:Codex 后端。说的是 OpenAI Responses 格式,但只接受流式、 /// 不认 `max_output_tokens`、身份头由网关填(见 [`chatgpt`]) Chatgpt, + /// Amazon Bedrock 的 Converse。生成请求一律转成它;流不是 SSE,是 AWS + /// eventstream 的二进制帧。凭证是 Bedrock API Key(`key`)或者访问密钥(`aws`) + Bedrock, } impl Protocol { @@ -842,6 +871,7 @@ impl Protocol { Protocol::OpenaiResponses => "openai-responses", Protocol::Gemini => "gemini", Protocol::Chatgpt => "chatgpt", + Protocol::Bedrock => "bedrock", } } } @@ -853,6 +883,9 @@ impl Provider { if chatgpt::is_backend(base_url) { return Some(Protocol::Chatgpt); } + if tw_bedrock::endpoint::region_of(base_url).is_some() { + return Some(Protocol::Bedrock); + } let h = base_url.to_ascii_lowercase(); if h.contains("api.anthropic.com") { Some(Protocol::Anthropic) @@ -869,6 +902,26 @@ impl Provider { self.protocol .or_else(|| Self::guess_protocol(&self.base_url)) } + + /// 这家是不是 Bedrock。 + pub fn is_bedrock(&self) -> bool { + self.effective_protocol() == Some(Protocol::Bedrock) + } + + /// Bedrock 的区域:标准地址里的那个,没有就是 `aws.region`。 + pub fn bedrock_region(&self) -> Option<&str> { + tw_bedrock::endpoint::region_of(&self.base_url) + .or_else(|| self.aws.as_ref().and_then(|a| a.region.as_deref())) + } + + /// Bedrock 列模型的地方。标准地址对应区域的控制面;别的地址(代理、测试用的 + /// 本地服务)由它自己回答 —— 控制面的路径和推理的不重叠。 + pub fn bedrock_control_base(&self) -> String { + match tw_bedrock::endpoint::region_of(&self.base_url) { + Some(region) => tw_bedrock::endpoint::control_base(region), + None => self.base_url.trim_end_matches('/').to_string(), + } + } } /// 刷新之后要写回配置的值。 @@ -1223,6 +1276,31 @@ providers: ); } + #[test] + fn a_bedrock_runtime_address_is_recognized_and_nothing_that_merely_looks_like_one() { + for url in [ + "https://bedrock-runtime.us-east-1.amazonaws.com", + "https://bedrock-runtime-fips.us-gov-west-1.amazonaws.com/", + ] { + assert_eq!( + Provider::guess_protocol(url), + Some(Protocol::Bedrock), + "{url}" + ); + } + for url in [ + "https://bedrock.us-east-1.amazonaws.com", + "https://relay.example/bedrock-runtime.us-east-1.amazonaws.com", + "https://bedrock-runtime.us-east-1.amazonaws.com.evil.example", + ] { + assert_ne!( + Provider::guess_protocol(url), + Some(Protocol::Bedrock), + "{url}" + ); + } + } + #[test] fn explicit_protocol_wins_over_the_guess() { let p = Provider { diff --git a/crates/tw-config/src/wire.rs b/crates/tw-config/src/wire.rs index f2940cf7..b1580473 100644 --- a/crates/tw-config/src/wire.rs +++ b/crates/tw-config/src/wire.rs @@ -29,6 +29,7 @@ impl From for tw_api::Protocol { Protocol::OpenaiResponses => Self::OpenaiResponses, Protocol::Gemini => Self::Gemini, Protocol::Chatgpt => Self::Chatgpt, + Protocol::Bedrock => Self::Bedrock, } } } @@ -41,6 +42,7 @@ impl From for Protocol { tw_api::Protocol::OpenaiResponses => Self::OpenaiResponses, tw_api::Protocol::Gemini => Self::Gemini, tw_api::Protocol::Chatgpt => Self::Chatgpt, + tw_api::Protocol::Bedrock => Self::Bedrock, } } } diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 8c5877bd..32f8a9d5 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -419,8 +419,8 @@ pub fn sections() -> Vec
{ Kind::Str, Def::Required, t( - "Endpoint, `http://` or `https://`, up to the version segment where the provider documents one (`https://api.anthropic.com`, `https://api.openai.com/v1`).", - "接口地址,`http://` 或 `https://`,按服务商文档写到版本段为止(`https://api.anthropic.com`、`https://api.openai.com/v1`)。", + "Endpoint, `http://` or `https://`, up to the version segment where the provider documents one (`https://api.anthropic.com`, `https://api.openai.com/v1`). For Bedrock, the region's runtime endpoint: `https://bedrock-runtime..amazonaws.com`.", + "接口地址,`http://` 或 `https://`,按服务商文档写到版本段为止(`https://api.anthropic.com`、`https://api.openai.com/v1`)。Bedrock 写所在区域的推理地址:`https://bedrock-runtime.<区域>.amazonaws.com`。", ), ), row( @@ -428,8 +428,8 @@ pub fn sections() -> Vec
{ Kind::Secret, Def::Unset, t( - "API key. It goes in the header the protocol expects: `x-api-key` (Anthropic), `Authorization: Bearer` (OpenAI), `x-goog-api-key` (Gemini). Leave it out for upstreams without a key, or when the credential is written in `headers`. Cannot be combined with `oauth`.", - "API 密钥,放进协议规定的请求头:`x-api-key`(Anthropic)、`Authorization: Bearer`(OpenAI)、`x-goog-api-key`(Gemini)。上游不需要密钥、或凭据写在 `headers` 里时不写。不能和 `oauth` 同时写。", + "API key. It goes in the header the protocol expects: `x-api-key` (Anthropic), `Authorization: Bearer` (OpenAI, and a Bedrock API key), `x-goog-api-key` (Gemini). Leave it out for upstreams without a key, or when the credential is written in `headers`. Cannot be combined with `oauth` or `aws`.", + "API 密钥,放进协议规定的请求头:`x-api-key`(Anthropic)、`Authorization: Bearer`(OpenAI,以及 Bedrock API Key)、`x-goog-api-key`(Gemini)。上游不需要密钥、或凭据写在 `headers` 里时不写。不能和 `oauth`、`aws` 同时写。", ), ), row( @@ -450,13 +450,22 @@ pub fn sections() -> Vec
{ "OAuth 凭据:用 refresh token 换取 access token。与 `key` 二选一。", ), ), + row( + "aws", + Kind::Obj("providers[].aws"), + Def::Unset, + t( + "AWS access keys of a Bedrock upstream: every request is signed with them (SigV4). Instead of `key`, which holds a Bedrock API key.", + "Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。与 `key`(Bedrock API Key)二选一。", + ), + ), row( "protocol", Kind::Enum(protocols), Def::Unset, t( - "API format of the upstream. Unset: recognized from `base_url` for the official endpoints, otherwise treated as `anthropic`.", - "上游的接口格式。不写:官方地址按 `base_url` 识别,其余按 `anthropic` 处理。", + "API format of the upstream. Unset: recognized from `base_url` for the official endpoints (a Bedrock runtime endpoint is `bedrock`), otherwise treated as `anthropic`.", + "上游的接口格式。不写:官方地址按 `base_url` 识别(Bedrock 的推理地址是 `bedrock`),其余按 `anthropic` 处理。", ), ), row( @@ -533,6 +542,45 @@ pub fn sections() -> Vec
{ ), ], }, + Section { + path: "providers[].aws", + ty: checked!( + Aws, + "{access_key_id: AKIAIOSFODNN7EXAMPLE, secret_access_key: s}" + ), + rows: vec![ + row( + "access_key_id", + Kind::Secret, + Def::Required, + t("Access key ID.", "访问密钥 ID。"), + ), + row( + "secret_access_key", + Kind::Secret, + Def::Required, + t("Secret access key.", "私有访问密钥。"), + ), + row( + "session_token", + Kind::Secret, + Def::Unset, + t( + "Session token of temporary credentials, such as those STS issues. When it expires, requests are refused until it is replaced.", + "临时凭证(如 STS 签发的)的会话令牌。过期之后请求会被拒绝,直到换上新的。", + ), + ), + row( + "region", + Kind::Str, + Def::Unset, + t( + "Region to sign for. Unset: the one in `base_url`, which must then be a standard runtime endpoint. Required when `base_url` is a VPC endpoint or a proxy.", + "签名用的区域。不写:取 `base_url` 里的区域,这时 `base_url` 必须是标准的推理地址。`base_url` 是 VPC 端点或代理时必须写。", + ), + ), + ], + }, Section { path: "providers[].oauth", ty: checked!( diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index d7e9cd55..45957a67 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -24,6 +24,8 @@ tw-guard = { workspace = true } bytes = { workspace = true } tw-engine = { workspace = true } tw-gateway = { workspace = true } +# 重放发给 Bedrock 的请求要签名、拆帧 +tw-bedrock = { workspace = true } tw-observe = { workspace = true } tw-secret = { workspace = true } tw-store = { workspace = true } diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index 687266d4..b6852c18 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -440,6 +440,16 @@ fn provider_view( account: chatgpt::account_view(s, p, o), } }), + aws: p.aws.as_ref().map(|a| tw_api::AwsKeys { + access_key_id: a.access_key_id.raw().to_string(), + secret_access_key: a.secret_access_key.raw().to_string(), + session_token: a.session_token.as_ref().map(|t| t.raw().to_string()), + region: a.region.clone(), + }), + region: p + .is_bedrock() + .then(|| p.bedrock_region().map(str::to_string)) + .flatten(), protocol: p.effective_protocol().map(Into::into), protocol_explicit: p.protocol.is_some(), forward_client_identity: p.forward_client_identity, diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index bf39b3af..13f44156 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -79,6 +79,26 @@ fn stored_body( Ok((row, raw)) } +/// 这家能不能收一次重放。 +/// +/// 重放发的是录下来的那份请求体,原样,发到原来的路径上:它只对说客户端那种格式的 +/// 上游有意义。**Bedrock 只收 Converse,而没有客户端说 Converse**,发过去只会得到一个 +/// 让人摸不着头脑的错误 —— 不如先说清楚。 +fn replayable_to(provider: &tw_config::Provider) -> Result<(), Fail> { + if provider.is_bedrock() { + return Err(fail( + StatusCode::CONFLICT, + msg!( + "control.replay_bedrock", upstream = provider.name.clone() => + "A replay sends the recorded request exactly as it was, and `{upstream}` is a \ + Bedrock upstream, which takes only the Converse format no client sends. Replay \ + it to an upstream that speaks the client's format." + ), + )); + } + Ok(()) +} + /// 报价。**不发任何请求。** pub async fn quote( State(s): State, @@ -108,6 +128,7 @@ pub async fn quote( ), ) })?; + replayable_to(provider)?; // 输入 token 用记录里的真值 —— 那是上游报回来的,比任何估算都准。 // 没有的话按字节粗估(和路由用的是同一个系数) @@ -171,6 +192,7 @@ pub async fn run( ), ) })?; + replayable_to(provider)?; // **这一家自己的 client,和数据面转发用的是同一个**:它带着这家该走的 // 代理(`direct` 就是不走任何代理,连系统代理也不读)。换 token 和发请求 // 都用它 —— 用别的 client,重放就会走一条和原请求不同的出站路径:本机 diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index c0fb82be..e636530b 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -161,6 +161,7 @@ async fn preview_provider( Ok(Json(tw_api::ProviderPreview { protocol: p.effective_protocol().map(Into::into), auth_header: chosen.auth_header().0.to_string(), + region: p.bedrock_region().map(str::to_string), })) } @@ -226,7 +227,15 @@ async fn test_provider( Ok(h) => h, Err(e) => return Ok(Json(failed(e.msg()))), }; - let r = tw_gateway::probe(&http, &p.base_url, &headers, protocol).await; + let r = if p.is_bedrock() { + let credentials = match p.aws_credentials() { + Ok(c) => c, + Err(e) => return Ok(Json(failed(e.msg()))), + }; + tw_gateway::probe_bedrock(&http, &p, &headers, credentials.as_ref()).await + } else { + tw_gateway::probe(&http, &p.base_url, &headers, protocol).await + }; Ok(Json(tw_api::ProviderTestResult { ok: r.ok, protocol: protocol.map(Into::into), @@ -377,12 +386,26 @@ fn to_provider( }) } }; + // 会话令牌空着就是没有:界面交上来的是一个空的框 + let nonblank = |v: &Option| { + v.as_deref() + .map(str::trim) + .filter(|x| !x.is_empty()) + .map(str::to_string) + }; + let aws = input.aws.as_ref().map(|a| tw_config::Aws { + access_key_id: tw_config::Secret::new(a.access_key_id.trim()), + secret_access_key: tw_config::Secret::new(a.secret_access_key.trim()), + session_token: nonblank(&a.session_token).map(tw_config::Secret::new), + region: nonblank(&a.region), + }); let provider = tw_config::Provider { name, base_url, key, headers: tw_config::Headers::new(headers), oauth, + aws, protocol: input.protocol.map(Into::into), forward_client_identity: input.forward_client_identity, models: input diff --git a/crates/tw-control/tests/bedrock.rs b/crates/tw-control/tests/bedrock.rs new file mode 100644 index 00000000..49bb2886 --- /dev/null +++ b/crates/tw-control/tests/bedrock.rs @@ -0,0 +1,268 @@ +//! Bedrock 上游在控制面上:按地址认出区域、访问密钥原样存取、凭证二选一、 +//! 检查连接走区域的控制面。 + +use std::sync::Arc; + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use serde_json::{Value, json}; +use tower::ServiceExt; +use tw_control::{ConfigManager, ControlState}; + +const BASE: &str = "version: 1 +listen: + control: + key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00 +clients: + - name: c + key: tw-k +providers: + - name: 官方 + base_url: https://api.anthropic.com + key: sk-official +"; + +struct Bed { + dir: tempfile::TempDir, + app: axum::Router, +} + +impl Bed { + fn file(&self) -> String { + std::fs::read_to_string(self.dir.path().join("config.yaml")).unwrap() + } +} + +fn bed(yaml: &str) -> Bed { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("config.yaml"); + std::fs::write(&p, yaml).unwrap(); + let cfg = tw_config::try_parse(yaml).unwrap(); + let gw = tw_gateway::AppState::new(cfg).unwrap(); + let bus = gw.bus.clone(); + let state = ControlState { + shutdown: Default::default(), + remote: Default::default(), + cfg: Arc::new(ConfigManager::new(p, gw.clone(), bus)), + gateway: gw, + store: None, + started: std::time::Instant::now(), + price_updater: Default::default(), + chatgpt: Default::default(), + zai: Default::default(), + }; + Bed { + app: tw_control::router(state), + dir: d, + } +} + +async fn call(app: &axum::Router, method: &str, path: &str, body: Value) -> (StatusCode, Value) { + let r = app + .clone() + .oneshot( + Request::builder() + .method(method) + .uri(path) + .header("content-type", "application/json") + .body(Body::from(body.to_string())) + .unwrap(), + ) + .await + .unwrap(); + let status = r.status(); + let b = axum::body::to_bytes(r.into_body(), 1 << 22).await.unwrap(); + (status, serde_json::from_slice(&b).unwrap_or(Value::Null)) +} + +#[tokio::test] +async fn a_bedrock_address_is_previewed_with_its_protocol_and_region() { + let b = bed(BASE); + let (st, v) = call( + &b.app, + "POST", + "/providers/preview", + json!({"base_url": "https://bedrock-runtime.eu-west-3.amazonaws.com"}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(v["protocol"], "bedrock"); + assert_eq!(v["auth_header"], "authorization"); + assert_eq!(v["region"], "eu-west-3"); + + let (_, v) = call( + &b.app, + "POST", + "/providers/preview", + json!({"base_url": "https://api.anthropic.com"}), + ) + .await; + assert!(v.get("region").is_none(), "{v}"); +} + +#[tokio::test] +async fn access_keys_are_saved_and_shown_as_written() { + let b = bed(BASE); + let (st, v) = call( + &b.app, + "POST", + "/providers", + json!({"provider": { + "name": "bedrock", + "base_url": "https://bedrock-runtime.us-east-1.amazonaws.com", + "aws": { + "access_key_id": "${AWS_ACCESS_KEY_ID}", + "secret_access_key": "${AWS_SECRET_ACCESS_KEY}", + // 界面交上来的空框:就是没有 + "session_token": " ", + }, + }}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + let file = b.file(); + assert!( + file.contains("access_key_id: ${AWS_ACCESS_KEY_ID}"), + "{file}" + ); + assert!(!file.contains("session_token"), "{file}"); + + let (_, v) = call(&b.app, "GET", "/overview", Value::Null).await; + let p = v["providers"] + .as_array() + .unwrap() + .iter() + .find(|p| p["name"] == "bedrock") + .unwrap() + .clone(); + assert_eq!(p["protocol"], "bedrock"); + assert_eq!(p["region"], "us-east-1"); + assert_eq!(p["aws"]["access_key_id"], "${AWS_ACCESS_KEY_ID}"); + assert_eq!(p["aws"]["secret_access_key"], "${AWS_SECRET_ACCESS_KEY}"); + assert!(p["aws"].get("session_token").is_none(), "{p}"); + assert!(p.get("key").is_none(), "{p}"); +} + +#[tokio::test] +async fn a_bedrock_upstream_is_refused_without_exactly_one_credential() { + let b = bed(BASE); + let url = "https://bedrock-runtime.us-east-1.amazonaws.com"; + let keys = json!({"access_key_id": "AKIAIOSFODNN7EXAMPLE", "secret_access_key": "s"}); + for (provider, code) in [ + ( + json!({"name": "b", "base_url": url, "key": "ABSK-x", "aws": keys}), + "config.credential.key_and_aws", + ), + ( + json!({"name": "b", "base_url": url}), + "config.credential.bedrock_no_credential", + ), + ( + json!({"name": "b", "base_url": "https://api.openai.com", "aws": keys}), + "config.credential.aws_not_bedrock", + ), + ( + json!({"name": "b", "base_url": url, "aws": {"access_key_id": "AKIA", "secret_access_key": "s", "region": "eu-west-1"}}), + "config.credential.aws_region_mismatch", + ), + ] { + let (st, v) = call(&b.app, "POST", "/providers", json!({"provider": provider})).await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); + assert_eq!(v["code"], code, "{v}"); + } +} + +/// 一个假的控制面:`answer` 决定怎么回 +async fn control_plane( + answer: impl Fn(&str) -> (u16, Option<&'static str>, Value) + Clone + Send + Sync + 'static, +) -> std::net::SocketAddr { + let app = axum::Router::new().fallback(move |uri: axum::http::Uri| { + let answer = answer.clone(); + async move { + let (status, kind, body) = answer(uri.path()); + let mut r = axum::response::Response::builder() + .status(status) + .header("content-type", "application/json"); + if let Some(k) = kind { + r = r.header("x-amzn-errortype", k); + } + r.body(Body::from(body.to_string())).unwrap() + } + }); + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let a = l.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(l, app).await.unwrap() }); + a +} + +async fn test_with(b: &Bed, up: std::net::SocketAddr) -> Value { + let (st, v) = call( + &b.app, + "POST", + "/providers/test", + json!({"provider": { + "name": "b", + "base_url": format!("http://{up}"), + "protocol": "bedrock", + "key": "ABSK-x", + }}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + v +} + +#[tokio::test] +async fn testing_a_bedrock_upstream_lists_what_it_can_route_to() { + let up = control_plane(|path| match path { + "/foundation-models" => ( + 200, + None, + json!({"modelSummaries": [{"modelId": "amazon.nova-lite-v1:0"}]}), + ), + _ => ( + 200, + None, + json!({"inferenceProfileSummaries": [{"inferenceProfileId": "us.anthropic.claude-sonnet-4-5-20250929-v1:0", "inferenceProfileArn": "arn:x"}]}), + ), + }) + .await; + let b = bed(BASE); + let v = test_with(&b, up).await; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(v["protocol"], "bedrock"); + assert_eq!(v["models"]["kind"], "listed"); + let models = v["models"]["models"].as_array().unwrap(); + assert!(models.iter().any(|m| m == "amazon.nova-lite-v1:0"), "{v}"); +} + +#[tokio::test] +async fn no_permission_to_list_is_not_a_rejected_key() { + // AWS 认出了身份,只是不给列:凭证能用 + let denied = control_plane(|_| { + ( + 403, + Some("AccessDeniedException:http://internal.amazon.com/coral/com.amazon.bedrock/"), + json!({"message": "User: arn:aws:iam::123456789012:user/alice is not authorized"}), + ) + }) + .await; + let b = bed(BASE); + let v = test_with(&b, denied).await; + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(v["models"]["kind"], "not_implemented", "{v}"); + assert_eq!(v["error"]["code"], "gw.probe.bedrock_list_denied", "{v}"); + assert!(!v.to_string().contains("123456789012"), "{v}"); + + let rejected = control_plane(|_| { + ( + 403, + Some("UnrecognizedClientException"), + json!({"message": "The security token included in the request is invalid."}), + ) + }) + .await; + let v = test_with(&b, rejected).await; + assert_eq!(v["ok"], false, "{v}"); + assert_eq!(v["error"]["code"], "gw.probe.key_rejected", "{v}"); +} diff --git a/crates/tw-control/tests/replay.rs b/crates/tw-control/tests/replay.rs index b5ca929a..b4cef214 100644 --- a/crates/tw-control/tests/replay.rs +++ b/crates/tw-control/tests/replay.rs @@ -208,3 +208,32 @@ async fn an_upstream_with_a_proxy_is_replayed_through_that_proxy() { assert_eq!(v["status"], 200, "{v}"); assert_eq!(v["body"], "via its own proxy", "{v}"); } + +/// Bedrock 只收 Converse,而录下来的请求是客户端的格式:先说清楚,不发 +#[tokio::test] +async fn a_bedrock_upstream_is_not_offered_a_replay_it_cannot_take() { + let (_d, app) = app( + "version: 1\nlisten:\n control:\n key: c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00c0ffee00\nclients:\n - name: 我\n key: tw-一把钥匙就够\nproviders:\n \ + - name: br\n base_url: https://bedrock-runtime.us-east-1.amazonaws.com\n key: ABSK-x\n", + ); + for path in ["/replay/quote", "/replay/run"] { + let req = tw_api::ReplayRequest { + id: 1, + provider: "br".into(), + }; + let r = app + .clone() + .oneshot( + Request::post(path) + .header("content-type", "application/json") + .body(Body::from(serde_json::to_vec(&req).unwrap())) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(r.status(), StatusCode::CONFLICT, "{path}"); + let b = axum::body::to_bytes(r.into_body(), 1 << 20).await.unwrap(); + let v: serde_json::Value = serde_json::from_slice(&b).unwrap(); + assert_eq!(v["code"], "control.replay_bedrock", "{path}: {v}"); + } +} diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index a374c3b3..1e82713a 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -16,6 +16,8 @@ categories.workspace = true tw-api = { workspace = true } tw-config = { workspace = true } tw-breaker = { workspace = true } +# Bedrock:SigV4 签名、eventstream 拆帧、推理地址和模型目录,和企业版共用一份 +tw-bedrock = { workspace = true } tw-engine = { workspace = true } tw-observe = { workspace = true } tw-secret = { workspace = true } @@ -49,6 +51,9 @@ tracing = { workspace = true } zstd = { workspace = true } [dev-dependencies] +# 假的 Bedrock 要回 eventstream 的二进制帧 +aws-smithy-eventstream = { workspace = true } +aws-smithy-types = { workspace = true } # 集成测试里要当 WS 客户端 —— 那一侧需要 connect tokio-tungstenite = { workspace = true, features = ["connect", "stream"] } tempfile = "3" diff --git a/crates/tw-gateway/src/bedrock.rs b/crates/tw-gateway/src/bedrock.rs new file mode 100644 index 00000000..7ae2dcfc --- /dev/null +++ b/crates/tw-gateway/src/bedrock.rs @@ -0,0 +1,42 @@ +//! Bedrock 在网关里几处共用的一步:给一个定稿的请求签名。 +//! +//! 转发、测速、重放都往 Bedrock 发请求,签名都要在**地址、请求头、请求体全部定稿之后** +//! 做,签的是 reqwest 实际要发的那个地址 —— 写三份的话,迟早有一份签的和发的不一样, +//! 而那时的症状只是上游一句 `SignatureDoesNotMatch`。 + +use std::time::SystemTime; + +/// 用 `credentials` 给 `request` 签名,签出来的头写进去(覆盖同名的)。 +/// +/// 请求体必须是定长的(转发、测速、重放发的都是):签名覆盖它的哈希。 +pub fn sign_request( + request: &mut reqwest::Request, + credentials: &tw_bedrock::Credentials, + region: &str, +) -> Result<(), tw_bedrock::SignError> { + let body = request + .body() + .and_then(reqwest::Body::as_bytes) + .unwrap_or_default() + .to_vec(); + let headers = tw_bedrock::sign::sign( + credentials, + region, + request.method().as_str(), + request.url().as_str(), + Some(&body), + SystemTime::now(), + )?; + for (name, value) in headers { + let (Ok(n), Ok(v)) = ( + http::HeaderName::from_bytes(name.as_bytes()), + http::HeaderValue::from_str(&value), + ) else { + return Err(tw_bedrock::SignError(format!( + "the signature produced an unusable {name} header" + ))); + }; + request.headers_mut().insert(n, v); + } + Ok(()) +} diff --git a/crates/tw-gateway/src/client_api.rs b/crates/tw-gateway/src/client_api.rs index f5d1a768..90431017 100644 --- a/crates/tw-gateway/src/client_api.rs +++ b/crates/tw-gateway/src/client_api.rs @@ -117,6 +117,7 @@ impl ClientApi { Protocol::OpenaiResponses, Protocol::Gemini, Protocol::Chatgpt, + Protocol::Bedrock, ]; } match self { @@ -255,7 +256,7 @@ mod tests { ] { assert_eq!(ClientApi::generates(path), generates, "{path}"); } - assert_eq!(ClientApi::OpenaiChat.servable_by(true).len(), 5); + assert_eq!(ClientApi::OpenaiChat.servable_by(true).len(), 6); assert_eq!( ClientApi::AnthropicMessages.servable_by(false), [Protocol::Anthropic] diff --git a/crates/tw-gateway/src/egress.rs b/crates/tw-gateway/src/egress.rs index 95dac383..be407ae9 100644 --- a/crates/tw-gateway/src/egress.rs +++ b/crates/tw-gateway/src/egress.rs @@ -50,8 +50,8 @@ impl Hop { Dialect::Chat => Some(Protocol::OpenaiChat), Dialect::Responses => Some(Protocol::OpenaiResponses), Dialect::Gemini => Some(Protocol::Gemini), - // Bedrock 不是一种上游协议:认不出的上游收到 Bedrock 格式也只能原样直通 - Dialect::Bedrock => None, + // 客户端不说 Converse(`client_api` 认不出它的路径),走不到这里 + Dialect::Bedrock => Some(Protocol::Bedrock), }) } } @@ -117,7 +117,8 @@ pub fn takes_from_client(hop: &Hop, name: &str) -> bool { && !(hop.harness_elsewhere && n == "anthropic-beta") } Some(Protocol::OpenaiChat | Protocol::OpenaiResponses) => OPENAI.contains(&n.as_str()), - Some(Protocol::Gemini | Protocol::Chatgpt) | None => false, + // Bedrock 的请求一律是转换过的,头由网关和签名填 + Some(Protocol::Gemini | Protocol::Chatgpt | Protocol::Bedrock) | None => false, } } @@ -378,7 +379,10 @@ mod tests { Hop::protocol_for(Some(Protocol::Gemini), Some(Dialect::Anthropic)), Some(Protocol::Gemini) ); - assert_eq!(Hop::protocol_for(None, Some(Dialect::Bedrock)), None); + assert_eq!( + Hop::protocol_for(None, Some(Dialect::Bedrock)), + Some(Protocol::Bedrock) + ); } #[test] diff --git a/crates/tw-gateway/src/l3.rs b/crates/tw-gateway/src/l3.rs index 6b4a6a10..1e5f1e3a 100644 --- a/crates/tw-gateway/src/l3.rs +++ b/crates/tw-gateway/src/l3.rs @@ -71,7 +71,7 @@ pub fn probe_input_tokens() -> u64 { /// - 其余:一句话的长度就够 /// /// Anthropic 那边不看模型会不会推理:**要推理得在请求里写**,而探测请求不写, -/// 所以它不会花额度在推理上。 +/// 所以它不会花额度在推理上。Bedrock 上的 Claude 也一样。 pub fn max_output_tokens( book: &tw_pricing::PriceBook, model: &str, @@ -80,8 +80,12 @@ pub fn max_output_tokens( if protocol == Some(Protocol::Chatgpt) { return None; } - let reasons = dialect_for(protocol) != Dialect::Anthropic - && book.table().get(model).is_some_and(|p| p.reasoning); + let asks_to_think = match dialect_for(protocol) { + Dialect::Anthropic => true, + Dialect::Bedrock => model.to_ascii_lowercase().contains("anthropic.claude"), + _ => false, + }; + let reasons = !asks_to_think && book.table().get(model).is_some_and(|p| p.reasoning); Some(if reasons { REASONING_MAX_TOKENS } else { @@ -210,7 +214,12 @@ pub async fn run( let started = Instant::now(); let dialect = dialect_for(provider.effective_protocol()); let probe = probe_request(provider, model, max_output_tokens, headers); - let url = crate::forward::upstream_url(&provider.base_url, &probe.path, probe.query.as_deref()); + let bedrock = provider.is_bedrock(); + let url = if bedrock { + tw_bedrock::endpoint::runtime_url(&provider.base_url, &probe.path) + } else { + crate::forward::upstream_url(&provider.base_url, &probe.path, probe.query.as_deref()) + }; let mut req = http .post(&url) // 测速不该无限等。**但也不能太短** —— 一个排队中的上游正是我们 @@ -236,7 +245,37 @@ pub async fn run( error, }; - let resp = match req.body(probe.body).send().await { + // Bedrock 的访问密钥:和转发时一样,全部定稿之后最后一步签名 + let aws = match provider.aws_credentials() { + Ok(c) => { + c.filter(|_| !tw_bedrock::carries_api_key(headers.iter().map(|(k, _)| k.as_str()))) + } + Err(e) => { + let why = crate::state::credential_failed(e.msg(), &provider.name); + return result(false, 0, Some(why)); + } + }; + let sent = match aws { + None => req.body(probe.body).send().await, + Some(credentials) => match req.body(probe.body).build() { + Ok(mut request) => { + let region = provider.bedrock_region().unwrap_or_default(); + if let Err(e) = crate::bedrock::sign_request(&mut request, &credentials, region) { + return result( + false, + 0, + Some(msg!( + "l3.sign_failed", detail = e.0 => + "The request could not be signed with the AWS access keys: {detail}" + )), + ); + } + http.execute(request).await + } + Err(e) => Err(e), + }, + }; + let resp = match sent { Ok(r) => r, Err(e) => { let detail = crate::forward::map_reqwest_error(e).detail; @@ -262,12 +301,34 @@ pub async fn run( // `response.created` 这些是上游收到请求立刻就发的,拿它们当 TTFT 会让所有上游 // 看起来一样快 —— 而那正好抹掉了这次测速的全部信息。 let mut reader = tw_dialect::convert::Reader::new(dialect); + // Bedrock 的流是 AWS eventstream 的二进制帧:先拆成 SSE,读法和转发时一样 + let mut unframe = (bedrock + && resp + .headers() + .get(axum::http::header::CONTENT_TYPE) + .is_some_and(|v| { + v.as_bytes() + .starts_with(tw_bedrock::eventstream::CONTENT_TYPE.as_bytes()) + })) + .then(tw_bedrock::eventstream::Transcoder::new); let mut stream = resp.bytes_stream(); use futures::StreamExt; // **时刻在收到那一块时就记下来**,不能等流结束再算 let mut events: Vec<(u64, ir::Event)> = Vec::new(); + let mut stream_error = None; while let Some(chunk) = stream.next().await { let Ok(chunk) = chunk else { break }; + let chunk = match unframe.as_mut() { + None => chunk.to_vec(), + Some(t) => match t.feed(&chunk) { + Ok(sse) => sse, + // 流里的异常(半路被限流之类)和坏帧:这次测速没有跑完 + Err(e) => { + stream_error = Some(e.to_string()); + break; + } + }, + }; events.extend(reader.feed(&chunk).into_iter().map(|e| (at(&started), e))); } events.extend(reader.finish().into_iter().map(|e| (at(&started), e))); @@ -275,7 +336,6 @@ pub async fn run( let answered = !events.is_empty(); let mut ttft_ms = None; let mut usage: Option = None; - let mut stream_error = None; for (ms, e) in events { match e { // 推理也算开口了:会推理的模型先吐推理 token,把它排除掉的话,测出来的 diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index 628e30b1..4d9a127d 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -7,6 +7,7 @@ pub mod access; pub mod auth; +pub mod bedrock; pub mod bodies; pub mod chatgpt; pub mod client_api; @@ -51,7 +52,7 @@ pub use l3::{Estimate, L3Result}; pub use limits::Gate; pub use listen::{Listening, bind_failure, serve_at}; pub use outbound::{client_for_provider, public_client}; -pub use probe::{ModelList, ProbeResult, probe}; +pub use probe::{ModelList, ProbeResult, probe, probe_bedrock}; pub use quote::Quote; pub use server::{router, serve}; pub use state::credential_failed; diff --git a/crates/tw-gateway/src/models.rs b/crates/tw-gateway/src/models.rs index 1d1bc5dc..0687c766 100644 --- a/crates/tw-gateway/src/models.rs +++ b/crates/tw-gateway/src/models.rs @@ -378,7 +378,15 @@ async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer return Answer::Failed(crate::state::credential_failed(e, &p.name)); } }; - let r = crate::probe::probe(http, &p.base_url, &headers, p.effective_protocol()).await; + let r = if p.is_bedrock() { + let credentials = match p.aws_credentials() { + Ok(c) => c, + Err(e) => return Answer::Failed(crate::state::credential_failed(e.msg(), &p.name)), + }; + crate::probe::probe_bedrock(http, p, &headers, credentials.as_ref()).await + } else { + crate::probe::probe(http, &p.base_url, &headers, p.effective_protocol()).await + }; if !r.ok { return Answer::Failed( r.error @@ -387,10 +395,13 @@ async fn ask(state: &AppState, rt: &Runtime, p: &tw_config::Provider) -> Answer } match r.models { ModelList::Listed { models } => Answer::Listed(models), - ModelList::NotImplemented { status } => Answer::NoList(msg!( - "gw.models.no_endpoint", status = status => - "The upstream has no model-list endpoint (HTTP {status})." - )), + // 探测说了为什么列不出(Bedrock 没有列模型的权限)就用它的话 + ModelList::NotImplemented { status } => Answer::NoList(r.error.unwrap_or_else(|| { + msg!( + "gw.models.no_endpoint", status = status => + "The upstream has no model-list endpoint (HTTP {status})." + ) + })), ModelList::Unrecognized { .. } => Answer::NoList(msg!( "gw.models.unrecognized" => "The model list the upstream returned is in an unrecognized format." diff --git a/crates/tw-gateway/src/probe.rs b/crates/tw-gateway/src/probe.rs index 8862cbd8..bb3782ce 100644 --- a/crates/tw-gateway/src/probe.rs +++ b/crates/tw-gateway/src/probe.rs @@ -73,6 +73,104 @@ impl ProbeResult { } } +/// Bedrock 的清单要列好几页(基础模型、预设和应用推理配置),给得比一次请求宽 +const BEDROCK_PROBE_TIMEOUT: Duration = Duration::from_secs(16); + +/// 验一家 Bedrock 上游能不能用,顺带列出它能路由到的模型。 +/// +/// Bedrock 的推理地址没有 `/v1/models`:清单在区域的控制面上,由 +/// [`tw_bedrock::catalog`] 列(基础模型、AWS 预设的推理配置,和账号自己建的应用 +/// 推理配置)。认证和转发时一样:请求头里有 Bedrock API Key 就原样带上,否则用 +/// `credentials` 签名。 +/// +/// **403 不一定是凭证不对。**AWS 认出了身份、只是没给列模型的权限时回的是 +/// `AccessDeniedException`:凭证能用,请求照样能发,只是这里列不出清单 —— 那要说成 +/// 「列不了」,不能说成「密钥被拒」。AWS 的原话会点名账号和 IAM 身份,不往外说。 +pub async fn probe_bedrock( + http: &reqwest::Client, + provider: &tw_config::Provider, + headers: &[(String, String)], + credentials: Option<&tw_bedrock::Credentials>, +) -> ProbeResult { + use tw_bedrock::catalog::{Auth, Failure, Profiles, list_models}; + + let proto_name = Some(format!("{:?}", tw_config::Protocol::Bedrock)); + let started = Instant::now(); + let auth = Auth { + headers, + credentials, + region: provider.bedrock_region().unwrap_or_default(), + }; + let control = provider.bedrock_control_base(); + let listing = tokio::time::timeout( + BEDROCK_PROBE_TIMEOUT, + list_models(http, &control, &auth, Profiles::WithApplication), + ) + .await; + let ms = started.elapsed().as_millis() as u64; + let ok = |models: ModelList, note: Option| ProbeResult { + ok: true, + protocol: proto_name.clone(), + latency_ms: ms, + models, + error: note, + }; + match listing { + Err(_) => ProbeResult::fail( + ms, + proto_name.clone(), + msg!( + "gw.probe.timeout", secs = BEDROCK_PROBE_TIMEOUT.as_secs() => + "No answer within {secs} seconds. Check the endpoint address, or whether this \ + upstream has to be reached through a proxy." + ), + ), + Ok(Ok(models)) if models.is_empty() => ok(ModelList::Empty, None), + Ok(Ok(models)) => ok(ModelList::Listed { models }, None), + Ok(Err(Failure::Status { status, kind, .. })) if status == 401 || status == 403 => { + match kind.as_deref() { + Some("AccessDeniedException") => ok( + ModelList::NotImplemented { status }, + Some(msg!( + "gw.probe.bedrock_list_denied" => + "The credential works, and it has no permission to list models \ + (bedrock:ListFoundationModels and bedrock:ListInferenceProfiles). \ + Requests are still forwarded; to route by model, list the models by hand." + )), + ), + Some("ExpiredTokenException") => ProbeResult::fail( + ms, + proto_name.clone(), + msg!( + "gw.probe.aws_token_expired" => + "The temporary AWS credential has expired. Replace the session token and \ + the access keys that came with it." + ), + ), + _ => ProbeResult::fail( + ms, + proto_name.clone(), + msg!( + "gw.probe.key_rejected", status = status => + "The upstream rejected this key (HTTP {status}). Check the key for stray \ + whitespace, and that it belongs to this upstream." + ), + ), + } + } + // 认证这一关过了,列表本身没列出来 + Ok(Err(Failure::Status { status, .. })) => ok(ModelList::NotImplemented { status }, None), + Ok(Err(Failure::Request(detail))) => ProbeResult::fail( + ms, + proto_name.clone(), + msg!( + "gw.probe.request_failed", detail = detail => + "The request failed: {detail}" + ), + ), + } +} + /// 验一个上游能不能用。 /// /// 判据是**「这把 key 能过认证吗」**,不是「有没有模型列表」。这两件事 diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 08985995..5f1fe643 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -164,17 +164,47 @@ pub(super) async fn try_upstreams<'a>( } }; + // Bedrock 的访问密钥:每个请求签名要用。**和请求头在同一处取**:环境变量没设是 + // 这一家的问题,换下一家 + let aws = match provider.aws_credentials() { + Ok(c) => c, + Err(e) => { + note_health( + &state.bus, + &state.health, + &provider.name, + state.health.record_failure(&provider.name), + ); + let err = + GatewayError::config(crate::state::credential_failed(e.msg(), &provider.name)); + chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); + last_err = Some(err); + continue; + } + }; + tracing::debug!( client = %req.client_name, provider = %provider.name, rule = %decision.matched_rule, group = ?decision.via_group, - url = %tw_secret::redact_url(&forward::upstream_url(&provider.base_url, &out.path, out.query.as_deref())), + url = %tw_secret::redact_url(&hop_url(provider, &out)), attempt = attempts.len(), "forwarding" ); - match send(state, req, provider, http, &out, body, upstream_headers).await { + match send( + state, + req, + provider, + http, + &out, + body, + upstream_headers, + aws.as_ref(), + ) + .await + { Ok(r) if r.status().is_server_error() || r.status() == 429 => { // 额度用完时上游回的正是 429,这一跳的额度头也要读 state.note_quota(id, &provider.name, r.headers()); @@ -216,6 +246,12 @@ pub(super) async fn try_upstreams<'a>( continue; } Ok(r) => { + // Bedrock 拒绝凭证时的原话会点名账号和 IAM 身份:换成我们自己的话再交出去 + let r = if provider.is_bedrock() && matches!(r.status().as_u16(), 401 | 403) { + bedrock_refusal(provider, r).await + } else { + r + }; note_health( &state.bus, &state.health, @@ -243,9 +279,19 @@ pub(super) async fn try_upstreams<'a>( &provider.name, state.health.record_failure(&provider.name), ); - // 连不上的可能是代理而不是上游 —— 检一次那个代理,说清是哪一件事 - state.check_proxy(&provider.proxy); - let err = forward::map_reqwest_error(e); + let err = match e { + SendError::Http(e) => { + // 连不上的可能是代理而不是上游 —— 检一次那个代理,说清是哪一件事 + state.check_proxy(&provider.proxy); + forward::map_reqwest_error(e) + } + SendError::Sign(e) => GatewayError::config(msg!( + "gw.upstream.sign_failed", + upstream = provider.name.clone(), detail = e.0 => + "The request to upstream `{upstream}` could not be signed with its AWS \ + access keys: {detail}" + )), + }; chain.push(hop_failed(&provider.name, err.detail.clone(), hop_started)); last_err = Some(err); continue; @@ -478,9 +524,28 @@ fn prepare( }); path = p.path.clone(); query = p.query.clone(); + // Bedrock 上的 Claude:客户端 `anthropic-beta` 里 Bedrock 认的那几个放进请求体 + let claude_on_bedrock = dialect == tw_dialect::ir::Dialect::Bedrock + && d.client == tw_dialect::ir::Dialect::Anthropic + && d.request + .model + .to_ascii_lowercase() + .contains("anthropic.claude"); + let betas = if claude_on_bedrock { + tw_bedrock::beta::supported( + req.headers + .get_all("anthropic-beta") + .iter() + .filter_map(|v| v.to_str().ok()), + ) + } else { + Vec::new() + }; // **客户端要不要流由会话记着**,发给 Codex 后端的这一份一律是流式 let body = if chatgpt { Bytes::from(crate::chatgpt::force_stream(p.body.clone())) + } else if let Some(b) = tw_bedrock::beta::with_betas(&p.body, &betas) { + Bytes::from(b) } else if harness && to_deepseek { // 转换成另一种格式发给 DeepSeek 官方:直连时它收得到的扩展照样带上 Bytes::from( @@ -517,7 +582,31 @@ fn prepare( }) } +/// 这一跳发往的完整地址。 +/// +/// Bedrock 的模型 id 写在路径里,按 AWS 的规矩转义(ARN 里的 `/`),见 +/// [`tw_bedrock::endpoint::runtime_url`]。 +fn hop_url(provider: &tw_config::Provider, out: &Outbound) -> String { + if provider.is_bedrock() { + tw_bedrock::endpoint::runtime_url(&provider.base_url, &out.path) + } else { + forward::upstream_url(&provider.base_url, &out.path, out.query.as_deref()) + } +} + +/// 一跳没发出去的原因。 +enum SendError { + Http(reqwest::Error), + /// Bedrock 的请求没签成名 + Sign(tw_bedrock::SignError), +} + /// 发出这一跳。OAuth 上游回 401 时换一个 token 再发一次。 +/// +/// `aws` 是 Bedrock 的访问密钥:有的话,请求在**全部定稿之后**(地址、请求头、请求体) +/// 最后一步签名,签的就是 reqwest 实际要发的那个地址。上游自己的请求头里带着 Bedrock +/// API Key 时不签。 +#[allow(clippy::too_many_arguments)] async fn send( state: &AppState, req: &Inbound, @@ -526,8 +615,9 @@ async fn send( out: &Outbound, body: Bytes, upstream_headers: Vec<(String, String)>, -) -> Result { - let url = forward::upstream_url(&provider.base_url, &out.path, out.query.as_deref()); + aws: Option<&tw_bedrock::Credentials>, +) -> Result { + let url = hop_url(provider, out); let method = reqwest::Method::from_bytes(b"POST").expect("POST is a valid method"); let (target, chatgpt, hop, headers) = (out.target, out.chatgpt, out.hop, &req.headers); let required = target @@ -598,6 +688,17 @@ async fn send( req }; let sent_at = std::time::Instant::now(); + let signer = aws + .filter(|_| !tw_bedrock::carries_api_key(upstream_headers.iter().map(|(k, _)| k.as_str()))) + .map(|c| (c, provider.bedrock_region().unwrap_or_default())); + if let Some((credentials, region)) = signer { + let mut request = build(&upstream_headers) + .body(body.clone()) + .build() + .map_err(SendError::Http)?; + crate::bedrock::sign_request(&mut request, credentials, region).map_err(SendError::Sign)?; + return http.execute(request).await.map_err(SendError::Http); + } let mut sent = build(&upstream_headers).body(body.clone()).send().await; // **OAuth 上游回 401:换一个 access token 再发一次,只一次。**token 可能在别处被 // 吊销了、提前失效了;不重试的话,这个请求连同之后每一个请求都会原样失败,直到 @@ -614,5 +715,51 @@ async fn send( } } } - sent + sent.map_err(SendError::Http) +} + +/// Bedrock 拒绝了凭证(401/403):状态码和响应头照原样,正文换成我们自己的一句话。 +/// +/// **AWS 的原话会点名账号 ID 和 IAM 身份**(`User: arn:aws:iam::…` is not authorized…), +/// 那不能交给客户端,也不能进请求记录。能说的是异常名:凭证被拒、过期、没有权限,是 +/// 哪一种由它分开。 +async fn bedrock_refusal( + provider: &tw_config::Provider, + r: reqwest::Response, +) -> reqwest::Response { + let status = r.status(); + let mut headers = r.headers().clone(); + let named = headers + .get(tw_bedrock::error::ERROR_TYPE) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + let body = r.bytes().await.unwrap_or_default(); + let kind = tw_bedrock::error::kind_of(named.as_deref(), &body); + let text = match kind.as_deref() { + Some("ExpiredTokenException") => msg!( + "gw.upstream.aws_token_expired", upstream = provider.name.clone() => + "[ThinkWatch] The temporary AWS credential of upstream `{upstream}` has expired. \ + Replace its session token and the access keys that came with it." + ), + other => msg!( + "gw.upstream.bedrock_refused", + upstream = provider.name.clone(), status = status.as_u16(), + kind = other.unwrap_or("no exception name") => + "[ThinkWatch] AWS refused the credential of upstream `{upstream}` (HTTP {status}, \ + {kind}). Check that the credential is valid and may use this model. AWS's own \ + message names the account, so it is not passed on." + ), + }; + for h in ["content-length", "content-type", "transfer-encoding"] { + headers.remove(h); + } + let body = serde_json::json!({ "message": text.text }).to_string(); + let mut resp = http::Response::new(body); + *resp.status_mut() = status; + *resp.headers_mut() = headers; + resp.headers_mut().insert( + http::header::CONTENT_TYPE, + http::HeaderValue::from_static("application/json"), + ); + reqwest::Response::from(resp) } diff --git a/crates/tw-gateway/src/server/pipeline/relay.rs b/crates/tw-gateway/src/server/pipeline/relay.rs index 643c6ace..eb967e1c 100644 --- a/crates/tw-gateway/src/server/pipeline/relay.rs +++ b/crates/tw-gateway/src/server/pipeline/relay.rs @@ -74,6 +74,27 @@ pub(super) fn respond( out_headers.insert("x-thinkwatch-upstream", v); } + // **Bedrock 的流不是 SSE**,是 AWS eventstream 的二进制帧。在字节进门的地方就转成 + // SSE(`event:` 是事件名,`data:` 是载荷),后面的一切 —— 用量、首 token、留档、 + // 回显还原、转换、工具审查 —— 读的都是 SSE,不需要知道 Bedrock 有什么不同。 + // 请求记录里留的也是转好的这一份:二进制帧存下来没人看得懂 + let eventstream = provider.is_bedrock() + && status.is_success() + && out_headers + .get(axum::http::header::CONTENT_TYPE) + .is_some_and(|v| { + v.as_bytes() + .starts_with(tw_bedrock::eventstream::CONTENT_TYPE.as_bytes()) + }); + if eventstream { + out_headers.insert( + axum::http::header::CONTENT_TYPE, + axum::http::HeaderValue::from_static("text/event-stream"), + ); + } + let mut unframe = eventstream.then(tw_bedrock::eventstream::Transcoder::new); + let upstream_name = provider.name.clone(); + // 流结束时才知道总字节数和真实耗时 —— 对一个跑了六分钟的任务, // 这两个数字在响应头那一刻都还不存在。 // @@ -149,6 +170,21 @@ pub(super) fn respond( }, }; let Some(item) = next else { break }; + // eventstream 拆成 SSE。一帧没收齐时这一块什么都转不出来,等下一块 + let item = match (item, unframe.as_mut()) { + (Ok(raw), Some(t)) => { + upstream_since = tokio::time::Instant::now(); + match t.feed(&raw) { + Ok(sse) if sse.is_empty() => continue, + Ok(sse) => Ok(Bytes::from(sse)), + Err(e) => { + broke = Some(stream_error(&upstream_name, e).in_dialect(dialect)); + break; + } + } + } + (item, _) => item, + }; match item { Ok(chunk) => { upstream_since = tokio::time::Instant::now(); @@ -733,3 +769,31 @@ impl Relay { } } } + +/// Bedrock 的流断在半路:帧坏了,或者上游在流里报了异常(半路被限流之类)。 +/// +/// 异常名决定这是哪一种错:限流按限流报,客户端才知道该退避而不是换一家;其余的按 +/// 上游出错报。**流里的异常不带账号信息**(限流、校验、服务不可用这些),原话照说, +/// 太长的截断。 +fn stream_error(upstream: &str, e: tw_bedrock::eventstream::StreamError) -> GatewayError { + use tw_bedrock::eventstream::StreamError; + match e { + StreamError::Malformed(detail) => GatewayError::upstream(msg!( + "gw.upstream.eventstream_broken", upstream = upstream, detail = detail => + "Upstream `{upstream}` sent a damaged AWS eventstream frame: {detail}" + )), + StreamError::Upstream { kind, message } => { + let message: String = message.chars().take(500).collect(); + let detail = msg!( + "gw.upstream.stream_exception", + upstream = upstream, kind = kind.clone(), message = message => + "Upstream `{upstream}` ended the stream with {kind}: {message}" + ); + if tw_bedrock::error::status_of(&kind) == 429 { + GatewayError::rate_limited(detail) + } else { + GatewayError::upstream(detail) + } + } + } +} diff --git a/crates/tw-gateway/src/translate.rs b/crates/tw-gateway/src/translate.rs index 8832c710..c714ac5f 100644 --- a/crates/tw-gateway/src/translate.rs +++ b/crates/tw-gateway/src/translate.rs @@ -23,6 +23,7 @@ pub fn dialect_of(p: Protocol) -> Dialect { Protocol::OpenaiChat => Dialect::Chat, Protocol::OpenaiResponses | Protocol::Chatgpt => Dialect::Responses, Protocol::Gemini => Dialect::Gemini, + Protocol::Bedrock => Dialect::Bedrock, } } diff --git a/crates/tw-gateway/tests/bedrock.rs b/crates/tw-gateway/tests/bedrock.rs new file mode 100644 index 00000000..8a5650ed --- /dev/null +++ b/crates/tw-gateway/tests/bedrock.rs @@ -0,0 +1,609 @@ +//! Bedrock 上游,端到端。 +//! +//! 假的 Bedrock 是一个本地服务:地址不是 AWS 的标准地址,所以签名用的区域写在 +//! `aws.region`,模型目录也由它回答。验的是网关把几件事接对了: +//! +//! - 生成请求转成 Converse,发到 `/model/{id}/converse[-stream]`,ARN 的 `/` 转义 +//! - 访问密钥:签名覆盖实际发出的地址和请求体;API Key:原样 Bearer,不签 +//! - eventstream 的流转成客户端的格式,用量照记;流里的异常让请求失败 +//! - 拒绝凭证时 AWS 的原话(点名账号)不交给客户端 +//! - 缓存断点和 Bedrock 认的 beta 带过去 +//! - 回显的占位符切在两帧里也还原得回来 +//! - 模型目录:基础模型、预设和应用推理配置 + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; + +use aws_smithy_eventstream::frame::write_message_to; +use aws_smithy_types::event_stream::{Header, HeaderValue, Message}; +use axum::Router; +use axum::extract::{OriginalUri, State}; +use axum::http::HeaderMap; +use serde_json::{Value, json}; +use tw_config::{ + Aws, Client, Config, Listen, Protocol, Provider, RedactPolicy, Secret, Security, SecurityMode, +}; + +const AK: &str = "AKIAIOSFODNN7EXAMPLE"; +const SK: &str = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"; +const REGION: &str = "us-east-1"; +const MODEL: &str = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"; + +#[derive(Debug, Clone)] +struct Seen { + method: String, + /// 原样,没解码 + uri: String, + headers: HeaderMap, + body: Vec, +} + +/// 假 Bedrock 怎么回答 +type Answer = Arc axum::response::Response + Send + Sync>; + +async fn bedrock(answer: Answer) -> (SocketAddr, Arc>>) { + let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + let app = Router::new() + .fallback( + move |State(log): State>>>, + method: axum::http::Method, + OriginalUri(uri): OriginalUri, + headers: HeaderMap, + body: bytes::Bytes| { + let answer = answer.clone(); + async move { + let s = Seen { + method: method.to_string(), + uri: uri.to_string(), + headers, + body: body.to_vec(), + }; + let resp = answer(&s); + log.lock().unwrap().push(s); + resp + } + }, + ) + .with_state(log); + 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) +} + +fn json_answer(status: u16, v: Value) -> axum::response::Response { + axum::response::Response::builder() + .status(status) + .header("content-type", "application/json") + .body(axum::body::Body::from(v.to_string())) + .unwrap() +} + +fn converse_reply(text: &str) -> Value { + json!({ + "output": {"message": {"role": "assistant", "content": [{"text": text}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 11, "outputTokens": 7, "totalTokens": 18} + }) +} + +/// 一帧 eventstream +fn frame(message_type: &str, kind: &str, payload: Value) -> Vec { + let kind_header = if message_type == "exception" { + ":exception-type" + } else { + ":event-type" + }; + let m = Message::new(payload.to_string().into_bytes()) + .add_header(Header::new( + ":message-type", + HeaderValue::String(message_type.to_string().into()), + )) + .add_header(Header::new( + kind_header, + HeaderValue::String(kind.to_string().into()), + )) + .add_header(Header::new( + ":content-type", + HeaderValue::String("application/json".into()), + )); + let mut out = Vec::new(); + write_message_to(&m, &mut out).unwrap(); + out +} + +fn event(kind: &str, payload: Value) -> Vec { + frame("event", kind, payload) +} + +/// ConverseStream 的一次回答:`texts` 一段一帧 +fn stream_frames(texts: &[&str]) -> Vec { + let mut out = event("messageStart", json!({"role": "assistant"})); + for t in texts { + out.extend(event( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": t}}), + )); + } + out.extend(event("contentBlockStop", json!({"contentBlockIndex": 0}))); + out.extend(event("messageStop", json!({"stopReason": "end_turn"}))); + out.extend(event( + "metadata", + json!({"usage": {"inputTokens": 21, "outputTokens": 9, "totalTokens": 30}, "metrics": {"latencyMs": 5}}), + )); + out +} + +fn eventstream_answer(bytes: Vec) -> axum::response::Response { + axum::response::Response::builder() + .status(200) + .header("content-type", "application/vnd.amazon.eventstream") + .body(axum::body::Body::from(bytes)) + .unwrap() +} + +fn with_keys(up: SocketAddr) -> Provider { + Provider { + name: "br".into(), + base_url: format!("http://{up}"), + protocol: Some(Protocol::Bedrock), + aws: Some(Aws { + access_key_id: Secret::new(AK), + secret_access_key: Secret::new(SK), + session_token: None, + region: Some(REGION.into()), + }), + ..Default::default() + } +} + +fn with_api_key(up: SocketAddr) -> Provider { + Provider { + name: "br".into(), + base_url: format!("http://{up}"), + protocol: Some(Protocol::Bedrock), + key: Some("ABSK-test".into()), + ..Default::default() + } +} + +async fn gateway_with( + p: Provider, + security: Security, +) -> ( + SocketAddr, + tw_gateway::AppState, + tokio::sync::broadcast::Receiver, +) { + let cfg = Config { + version: 1, + listen: Listen::default(), + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![p], + security, + ..Default::default() + }; + let state = tw_gateway::AppState::new(cfg).unwrap(); + let rx = state.bus.subscribe(); + let addr = tw_gateway::serve(state.clone(), ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + (addr, state, rx) +} + +async fn gateway( + p: Provider, +) -> ( + SocketAddr, + tw_gateway::AppState, + tokio::sync::broadcast::Receiver, +) { + gateway_with(p, Security::default()).await +} + +async fn post(gw: SocketAddr, path: &str, headers: &[(&str, &str)], body: Value) -> (u16, String) { + let mut r = reqwest::Client::new() + .post(format!("http://{gw}{path}")) + .header("content-type", "application/json"); + for (k, v) in headers { + r = r.header(*k, *v); + } + let resp = r.body(body.to_string()).send().await.unwrap(); + let status = resp.status().as_u16(); + (status, resp.text().await.unwrap()) +} + +/// 这条请求的结局 +async fn ending(rx: &mut tokio::sync::broadcast::Receiver) -> tw_api::Event { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + let e = tokio::time::timeout_at(deadline, rx.recv()) + .await + .expect("no ending within 5 s") + .unwrap(); + if matches!( + e, + tw_api::Event::RequestFinished { .. } + | tw_api::Event::RequestFailed { .. } + | tw_api::Event::RequestCancelled { .. } + ) { + return e; + } + } +} + +/// `x-amz-date` → 签名时刻 +fn signed_at(s: &Seen) -> SystemTime { + let d = s.headers["x-amz-date"].to_str().unwrap(); + let n = |a: usize, b: usize| d[a..b].parse::().unwrap(); + let (y, mo, day, h, mi, sec) = (n(0, 4), n(4, 6), n(6, 8), n(9, 11), n(11, 13), n(13, 15)); + // 公历日期 → 1970 年起的天数(Howard Hinnant 的算法) + let y2 = if mo <= 2 { y - 1 } else { y }; + let era = y2.div_euclid(400); + let yoe = y2 - era * 400; + let doy = (153 * (if mo > 2 { mo - 3 } else { mo + 9 }) + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146097 + doe - 719468; + SystemTime::UNIX_EPOCH + Duration::from_secs((days * 86400 + h * 3600 + mi * 60 + sec) as u64) +} + +/// 收到的请求自称的签名,就是拿同样的密钥、在同一时刻、对**收到的**地址和请求体签出来的 +/// 那个。签名算法本身对着 SigV4 规范的核对在 tw-bedrock 里;这里验的是网关签的正是它发的 +fn assert_signed_as_sent(s: &Seen) { + let url = format!("http://{}{}", s.headers["host"].to_str().unwrap(), s.uri); + let expected = tw_bedrock::sign::sign( + &tw_bedrock::Credentials { + access_key_id: AK.into(), + secret_access_key: SK.into(), + session_token: None, + }, + REGION, + &s.method, + &url, + Some(&s.body), + signed_at(s), + ) + .unwrap(); + let auth = expected + .iter() + .find(|(k, _)| k == "authorization") + .map(|(_, v)| v.clone()) + .unwrap(); + assert_eq!(s.headers["authorization"].to_str().unwrap(), auth, "{s:?}"); + assert_eq!(s.headers["content-type"], "application/json"); +} + +#[tokio::test] +async fn a_chat_client_reaches_claude_on_bedrock_signed_with_access_keys() { + let (up, seen) = bedrock(Arc::new(|_| json_answer(200, converse_reply("晴")))).await; + let (gw, _, mut rx) = gateway(with_keys(up)).await; + let (status, body) = post( + gw, + "/v1/chat/completions", + &[("authorization", "Bearer tw-k")], + json!({"model": MODEL, "messages": [{"role": "user", "content": "天气?"}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + let v: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(v["choices"][0]["message"]["content"], "晴"); + + let s = seen.lock().unwrap()[0].clone(); + assert_eq!(s.uri, format!("/model/{MODEL}/converse")); + let sent: Value = serde_json::from_slice(&s.body).unwrap(); + assert_eq!(sent["messages"][0]["content"][0]["text"], "天气?"); + assert!( + s.headers["authorization"] + .to_str() + .unwrap() + .starts_with("AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/"), + "{s:?}" + ); + assert_signed_as_sent(&s); + + match ending(&mut rx).await { + tw_api::Event::RequestFinished { usage: Some(u), .. } => { + assert_eq!((u.input, u.output), (11, 7)); + } + other => panic!("{other:?}"), + } +} + +#[tokio::test] +async fn an_api_key_goes_out_as_bearer_and_nothing_is_signed() { + let (up, seen) = bedrock(Arc::new(|_| json_answer(200, converse_reply("ok")))).await; + let (gw, _, _) = gateway(with_api_key(up)).await; + let (status, body) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + json!({"model": MODEL, "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + let s = seen.lock().unwrap()[0].clone(); + assert_eq!(s.headers["authorization"], "Bearer ABSK-test"); + assert!(s.headers.get("x-amz-date").is_none(), "{s:?}"); +} + +#[tokio::test] +async fn a_converse_stream_reaches_an_anthropic_client_as_its_own_sse() { + let (up, seen) = bedrock(Arc::new(|_| { + eventstream_answer(stream_frames(&["sun", "ny"])) + })) + .await; + let (gw, _, mut rx) = gateway(with_keys(up)).await; + let (status, body) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + json!({"model": MODEL, "max_tokens": 64, "stream": true, + "messages": [{"role": "user", "content": "weather?"}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + assert_eq!( + seen.lock().unwrap()[0].uri, + format!("/model/{MODEL}/converse-stream") + ); + let text: String = body + .lines() + .filter_map(|l| l.strip_prefix("data: ")) + .filter_map(|d| serde_json::from_str::(d).ok()) + .filter_map(|v| v["delta"]["text"].as_str().map(str::to_string)) + .collect(); + assert_eq!(text, "sunny", "{body}"); + assert!(body.contains("message_stop"), "{body}"); + match ending(&mut rx).await { + tw_api::Event::RequestFinished { usage: Some(u), .. } => { + assert_eq!((u.input, u.output), (21, 9)); + } + other => panic!("{other:?}"), + } +} + +#[tokio::test] +async fn an_exception_inside_the_stream_fails_the_request() { + let mut wire = event("messageStart", json!({"role": "assistant"})); + wire.extend(event( + "contentBlockDelta", + json!({"contentBlockIndex": 0, "delta": {"text": "半"}}), + )); + wire.extend(frame( + "exception", + "throttlingException", + json!({"message": "Too many tokens, please wait before trying again."}), + )); + let (up, _) = bedrock(Arc::new(move |_| eventstream_answer(wire.clone()))).await; + let (gw, _, mut rx) = gateway(with_keys(up)).await; + let (status, body) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + json!({"model": MODEL, "max_tokens": 64, "stream": true, + "messages": [{"role": "user", "content": "hi"}]}), + ) + .await; + // 200 早就发出去了,错误只能在流里说 + assert_eq!(status, 200); + assert!(body.contains("event: error"), "{body}"); + assert!(body.contains("throttlingException"), "{body}"); + match ending(&mut rx).await { + tw_api::Event::RequestFailed { + message, source, .. + } => { + assert_eq!(message.code, "gw.upstream.stream_exception", "{message:?}"); + assert_eq!(message.arg("kind"), "throttlingException"); + // 限流按限流记:客户端该退避,不是这家坏了 + assert_eq!(source, tw_api::FailureSource::RateLimited); + } + other => panic!("{other:?}"), + } +} + +#[tokio::test] +async fn a_refused_credential_does_not_pass_on_what_aws_said_about_the_account() { + let (up, _) = bedrock(Arc::new(|_| { + axum::response::Response::builder() + .status(403) + .header("content-type", "application/json") + .header( + "x-amzn-errortype", + "AccessDeniedException:http://internal.amazon.com/coral/com.amazon.bedrock/", + ) + .body(axum::body::Body::from( + json!({"message": "User: arn:aws:iam::123456789012:user/alice is not authorized to perform: bedrock:InvokeModel"}).to_string(), + )) + .unwrap() + })) + .await; + let (gw, _, _) = gateway(with_keys(up)).await; + let (status, body) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + json!({"model": MODEL, "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}), + ) + .await; + assert_eq!(status, 403); + assert!(!body.contains("123456789012"), "{body}"); + assert!(!body.contains("alice"), "{body}"); + assert!(body.contains("AccessDeniedException"), "{body}"); + assert!(body.contains("[ThinkWatch]"), "{body}"); +} + +#[tokio::test] +async fn cache_points_and_the_betas_bedrock_takes_reach_it() { + let (up, seen) = bedrock(Arc::new(|_| json_answer(200, converse_reply("ok")))).await; + let (gw, _, _) = gateway(with_keys(up)).await; + let (status, body) = post( + gw, + "/v1/messages", + &[ + ("x-api-key", "tw-k"), + ( + "anthropic-beta", + "claude-code-20250219,interleaved-thinking-2025-05-14,oauth-2025-04-20", + ), + ], + json!({ + "model": MODEL, + "max_tokens": 16, + "system": [{"type": "text", "text": "rules", "cache_control": {"type": "ephemeral"}}], + "messages": [{"role": "user", "content": "hi"}] + }), + ) + .await; + assert_eq!(status, 200, "{body}"); + let s = seen.lock().unwrap()[0].clone(); + let sent: Value = serde_json::from_slice(&s.body).unwrap(); + assert_eq!( + sent["system"], + json!([{"text": "rules"}, {"cachePoint": {"type": "default"}}]) + ); + assert_eq!( + sent["additionalModelRequestFields"]["anthropic_beta"], + json!(["interleaved-thinking-2025-05-14"]) + ); + assert!(s.headers.get("anthropic-beta").is_none(), "{s:?}"); + assert_signed_as_sent(&s); +} + +#[tokio::test] +async fn an_arn_model_keeps_its_slash_inside_the_path_and_the_signature_holds() { + const ARN: &str = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/a1b2c3"; + let (up, seen) = bedrock(Arc::new(|_| json_answer(200, converse_reply("ok")))).await; + let (gw, _, _) = gateway(with_keys(up)).await; + let (status, body) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + json!({"model": ARN, "max_tokens": 16, "messages": [{"role": "user", "content": "hi"}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + let s = seen.lock().unwrap()[0].clone(); + assert_eq!( + s.uri, + "/model/arn:aws:bedrock:us-east-1:123456789012:application-inference-profile%2Fa1b2c3/converse" + ); + assert_signed_as_sent(&s); +} + +#[tokio::test] +async fn a_placeholder_echoed_across_two_deltas_comes_back_as_the_secret() { + const USER_KEY: &str = "sk-ant-api03-USERSOWNKEYAAAAAAAAAAAAAA"; + // 把收到的占位符拆成两半,分在两帧里回显 + let (up, seen) = bedrock(Arc::new(|s: &Seen| { + let text = String::from_utf8_lossy(&s.body).to_string(); + let start = text.find("<>").unwrap() + 2; + let placeholder = &text[start..end]; + let (a, b) = placeholder.split_at(placeholder.len() / 2); + eventstream_answer(stream_frames(&["key 是 ", a, b])) + })) + .await; + let security = Security { + redact: RedactPolicy { + mode: SecurityMode::Enforce, + ..Default::default() + }, + ..Default::default() + }; + let (gw, _, _) = gateway_with(with_keys(up), security).await; + let (status, body) = post( + gw, + "/v1/messages", + &[("x-api-key", "tw-k")], + json!({"model": MODEL, "max_tokens": 64, "stream": true, + "messages": [{"role": "user", "content": format!("我的 key 是 {USER_KEY}")}]}), + ) + .await; + assert_eq!(status, 200, "{body}"); + let sent = String::from_utf8_lossy(&seen.lock().unwrap()[0].body).to_string(); + assert!(!sent.contains(USER_KEY), "{sent}"); + let text: String = body + .lines() + .filter_map(|l| l.strip_prefix("data: ")) + .filter_map(|d| serde_json::from_str::(d).ok()) + .filter_map(|v| v["delta"]["text"].as_str().map(str::to_string)) + .collect(); + assert_eq!(text, format!("key 是 {USER_KEY}"), "{body}"); +} + +#[tokio::test] +async fn the_catalog_lists_foundation_models_and_both_kinds_of_inference_profile() { + const ARN: &str = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/a1b2c3"; + let (up, seen) = bedrock(Arc::new(|s: &Seen| { + let path = s.uri.split('?').next().unwrap(); + let q = s.uri.split('?').nth(1).unwrap_or_default(); + match path { + "/foundation-models" => json_answer( + 200, + json!({"modelSummaries": [{"modelId": "amazon.nova-lite-v1:0"}]}), + ), + "/inference-profiles" if q.contains("type=APPLICATION") => json_answer( + 200, + json!({"inferenceProfileSummaries": [{"inferenceProfileId": "a1b2c3", "inferenceProfileArn": ARN}]}), + ), + "/inference-profiles" => json_answer( + 200, + json!({"inferenceProfileSummaries": [{"inferenceProfileId": MODEL}]}), + ), + _ => json_answer(404, json!({"message": "no"})), + } + })) + .await; + let (_, state, _) = gateway(with_keys(up)).await; + let listing = tw_gateway::models::refresh_one(&state, "br").await.unwrap(); + assert_eq!(listing.models, ["amazon.nova-lite-v1:0", ARN, MODEL]); + for s in seen.lock().unwrap().iter() { + assert_eq!(s.method, "GET"); + assert!( + s.headers["authorization"] + .to_str() + .unwrap() + .starts_with("AWS4-HMAC-SHA256"), + "{s:?}" + ); + } +} + +#[tokio::test] +async fn a_speed_test_signs_its_request_and_reads_the_converse_stream() { + let (up, seen) = bedrock(Arc::new(|_| { + eventstream_answer(stream_frames(&["Hi", "!"])) + })) + .await; + let p = with_keys(up); + let r = tw_gateway::l3::run(&reqwest::Client::new(), &p, &[], MODEL, Some(8)).await; + assert!(r.ok, "{r:?}"); + assert!(r.ttft_ms.is_some(), "{r:?}"); + assert_eq!(r.output_tokens, Some(9), "{r:?}"); + let s = seen.lock().unwrap()[0].clone(); + assert_eq!(s.uri, format!("/model/{MODEL}/converse-stream")); + assert_signed_as_sent(&s); +} + +#[tokio::test] +async fn a_speed_test_reports_an_exception_inside_the_stream() { + let mut wire = event("messageStart", json!({"role": "assistant"})); + wire.extend(frame( + "exception", + "serviceUnavailableException", + json!({"message": "Bedrock is unable to process your request."}), + )); + let (up, _) = bedrock(Arc::new(move |_| eventstream_answer(wire.clone()))).await; + let r = tw_gateway::l3::run(&reqwest::Client::new(), &with_keys(up), &[], MODEL, Some(8)).await; + assert!(!r.ok, "{r:?}"); + let e = r.error.unwrap(); + assert_eq!(e.code, "l3.stream_failed", "{e:?}"); + assert!(e.text.contains("serviceUnavailableException"), "{e:?}"); +} diff --git a/docs/config.md b/docs/config.md index ffa84583..5078d92c 100644 --- a/docs/config.md +++ b/docs/config.md @@ -309,11 +309,12 @@ Upstreams: the APIs requests are forwarded to. | Field | Type | Default | Description | |---|---|---|---| | `name` | string | **required** | Name of the upstream; unique, and not the name of a group. Names starting with `__` are reserved. | -| `base_url` | string | **required** | Endpoint, `http://` or `https://`, up to the version segment where the provider documents one (`https://api.anthropic.com`, `https://api.openai.com/v1`). | -| `key` | string, `${VAR}` allowed | — | API key. It goes in the header the protocol expects: `x-api-key` (Anthropic), `Authorization: Bearer` (OpenAI), `x-goog-api-key` (Gemini). Leave it out for upstreams without a key, or when the credential is written in `headers`. Cannot be combined with `oauth`. | +| `base_url` | string | **required** | Endpoint, `http://` or `https://`, up to the version segment where the provider documents one (`https://api.anthropic.com`, `https://api.openai.com/v1`). For Bedrock, the region's runtime endpoint: `https://bedrock-runtime..amazonaws.com`. | +| `key` | string, `${VAR}` allowed | — | API key. It goes in the header the protocol expects: `x-api-key` (Anthropic), `Authorization: Bearer` (OpenAI, and a Bedrock API key), `x-goog-api-key` (Gemini). Leave it out for upstreams without a key, or when the credential is written in `headers`. Cannot be combined with `oauth` or `aws`. | | `headers` | map of header name → value | `{}` | Additional request headers, in the order written; values may use `${VAR}`, and `{{access_token}}` where `oauth` is set. At most 32. Headers HTTP or the gateway manages (`host`, `content-length`, `connection`, …) cannot be set. | | `oauth` | object, [`providers[].oauth`](#cfg-providers-oauth) | — | OAuth credential: an access token obtained from a refresh token. Instead of `key`. | -| `protocol` | `anthropic` \| `openai-chat` \| `openai-responses` \| `gemini` \| `chatgpt` | — | API format of the upstream. Unset: recognized from `base_url` for the official endpoints, otherwise treated as `anthropic`. | +| `aws` | object, [`providers[].aws`](#cfg-providers-aws) | — | AWS access keys of a Bedrock upstream: every request is signed with them (SigV4). Instead of `key`, which holds a Bedrock API key. | +| `protocol` | `anthropic` \| `openai-chat` \| `openai-responses` \| `gemini` \| `chatgpt` \| `bedrock` | — | API format of the upstream. Unset: recognized from `base_url` for the official endpoints (a Bedrock runtime endpoint is `bedrock`), otherwise treated as `anthropic`. | | `forward_client_identity` | bool | `false` | Also send the client's own identity: its `User-Agent`, identity headers such as `x-app` and `originator`, and identity fields in the request body such as `metadata.user_id`. Values are the client's, never made up. Off: requests carry ThinkWatch's `User-Agent` and no client identity. For upstreams that admit only certain clients (Kimi For Coding, Bailian Coding Plan, relays restricted to official clients). Not available for `chatgpt`. | | `proxy` | string | `direct` | `direct`; `system`, the proxy in the core process's `HTTPS_PROXY`, `HTTP_PROXY` or `ALL_PROXY` environment variables; or the name of an entry in `proxies`. | | `on_proxy_fail` | `fail` \| `direct` | `fail` | When the proxy cannot be reached: `fail` the request, or go `direct`. | @@ -324,11 +325,11 @@ Upstreams: the APIs requests are forwarded to. | `disabled` | bool | `false` | Take the upstream out of routing and out of the model list, and keep its configuration. | -A credential is one of three things: `key`, which goes in the header the -protocol expects; `oauth`, a token obtained from a refresh token; or -`headers`, when the upstream wants something of its own. `headers` can be -combined with the other two, except for the header that already carries the -credential. +A credential is one of four things: `key`, which goes in the header the +protocol expects; `oauth`, a token obtained from a refresh token; `aws`, the +access keys a Bedrock upstream signs its requests with; or `headers`, when the +upstream wants something of its own. `headers` can be combined with the +others, except for the header that already carries the credential. ```yaml providers: @@ -393,6 +394,50 @@ the token goes: X-Access: Token {{access_token}} ``` +#### `providers[].aws` + + + + +| Field | Type | Default | Description | +|---|---|---|---| +| `access_key_id` | string, `${VAR}` allowed | **required** | Access key ID. | +| `secret_access_key` | string, `${VAR}` allowed | **required** | Secret access key. | +| `session_token` | string, `${VAR}` allowed | — | Session token of temporary credentials, such as those STS issues. When it expires, requests are refused until it is replaced. | +| `region` | string | — | Region to sign for. Unset: the one in `base_url`, which must then be a standard runtime endpoint. Required when `base_url` is a VPC endpoint or a proxy. | + + +A Bedrock upstream authenticates in one of two ways. A Bedrock API key goes in +`key` and is sent as `Authorization: Bearer`. AWS access keys go in `aws`: +every request is signed with them (SigV4) once its body is final, and the keys +themselves are never sent. Both can be read from the environment with +`${VAR}`. Nothing runs a command to obtain a credential, so a profile that needs +`aws sso login` or a `credential_process` cannot be used; export the keys it +produces instead. + +```yaml +providers: + - name: bedrock + base_url: https://bedrock-runtime.us-east-1.amazonaws.com + key: ${AWS_BEARER_TOKEN_BEDROCK} + + - name: bedrock-keys + base_url: https://bedrock-runtime.eu-west-1.amazonaws.com + aws: + access_key_id: ${AWS_ACCESS_KEY_ID} + secret_access_key: ${AWS_SECRET_ACCESS_KEY} + session_token: ${AWS_SESSION_TOKEN} +``` + +Requests are converted to Converse. The model list comes from the region's +control plane: the foundation models that can be invoked on demand, the +inference profiles AWS defines (`us.anthropic.claude-…`), and the account's +application inference profiles, listed by the ARN they are invoked by. Listing +needs `bedrock:ListFoundationModels` and `bedrock:ListInferenceProfiles`; +without them requests are still forwarded, and `models` can list the models by +hand. For a VPC endpoint or a proxy, write its address in `base_url` and the +region in `aws.region`; the model list is asked of that address too. + ### `proxies` Outbound proxies. Different upstreams often need different ones, so there diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index ce0898bb..ca05423b 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -233,11 +233,12 @@ clients: | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| | `name` | 字符串 | **必填** | 上游的名字,不能重复,也不能和策略组同名。以 `__` 开头的名字保留给内置项。 | -| `base_url` | 字符串 | **必填** | 接口地址,`http://` 或 `https://`,按服务商文档写到版本段为止(`https://api.anthropic.com`、`https://api.openai.com/v1`)。 | -| `key` | 字符串,可写 `${VAR}` | — | API 密钥,放进协议规定的请求头:`x-api-key`(Anthropic)、`Authorization: Bearer`(OpenAI)、`x-goog-api-key`(Gemini)。上游不需要密钥、或凭据写在 `headers` 里时不写。不能和 `oauth` 同时写。 | +| `base_url` | 字符串 | **必填** | 接口地址,`http://` 或 `https://`,按服务商文档写到版本段为止(`https://api.anthropic.com`、`https://api.openai.com/v1`)。Bedrock 写所在区域的推理地址:`https://bedrock-runtime.<区域>.amazonaws.com`。 | +| `key` | 字符串,可写 `${VAR}` | — | API 密钥,放进协议规定的请求头:`x-api-key`(Anthropic)、`Authorization: Bearer`(OpenAI,以及 Bedrock API Key)、`x-goog-api-key`(Gemini)。上游不需要密钥、或凭据写在 `headers` 里时不写。不能和 `oauth`、`aws` 同时写。 | | `headers` | 请求头名 → 值的映射 | `{}` | 额外的请求头,按书写顺序发送;值可以用 `${VAR}`,配置了 `oauth` 时可以用 `{{access_token}}`。最多 32 个。HTTP 或网关管理的请求头(`host`、`content-length`、`connection` 等)不能设置。 | | `oauth` | 对象,见 [`providers[].oauth`](#cfg-providers-oauth) | — | OAuth 凭据:用 refresh token 换取 access token。与 `key` 二选一。 | -| `protocol` | `anthropic` \| `openai-chat` \| `openai-responses` \| `gemini` \| `chatgpt` | — | 上游的接口格式。不写:官方地址按 `base_url` 识别,其余按 `anthropic` 处理。 | +| `aws` | 对象,见 [`providers[].aws`](#cfg-providers-aws) | — | Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。与 `key`(Bedrock API Key)二选一。 | +| `protocol` | `anthropic` \| `openai-chat` \| `openai-responses` \| `gemini` \| `chatgpt` \| `bedrock` | — | 上游的接口格式。不写:官方地址按 `base_url` 识别(Bedrock 的推理地址是 `bedrock`),其余按 `anthropic` 处理。 | | `forward_client_identity` | 布尔 | `false` | 同时发送客户端自己的身份:它的 `User-Agent`、`x-app` 和 `originator` 等身份请求头,以及请求体中的身份字段(如 `metadata.user_id`)。发送的都是客户端的原值,不做伪造。关闭时请求使用 ThinkWatch 的 `User-Agent`,不带客户端身份。用于只接受特定客户端的上游(Kimi For Coding、百炼 Coding Plan、只允许官方客户端的中转站)。`chatgpt` 不可用。 | | `proxy` | 字符串 | `direct` | `direct`;`system`,即 core 进程环境变量 `HTTPS_PROXY`、`HTTP_PROXY`、`ALL_PROXY` 中的代理;或 `proxies` 中某一项的名字。 | | `on_proxy_fail` | `fail` \| `direct` | `fail` | 代理不可用时:请求失败(`fail`),或改为直连(`direct`)。 | @@ -248,7 +249,7 @@ clients: | `disabled` | 布尔 | `false` | 不参与路由,模型也不出现在模型列表里;配置原样保留。 | -凭据有三种写法:`key`,放进协议规定的请求头;`oauth`,用 refresh token 换取 token;`headers`,用于上游自有的鉴权方式。`headers` 可以和前两者同时使用,但不能再设置已经承载凭据的那个请求头。 +凭据有四种写法:`key`,放进协议规定的请求头;`oauth`,用 refresh token 换取 token;`aws`,Bedrock 上游签名请求用的访问密钥;`headers`,用于上游自有的鉴权方式。`headers` 可以和其余几种同时使用,但不能再设置已经承载凭据的那个请求头。 ```yaml providers: @@ -302,6 +303,37 @@ access token 默认放进协议的鉴权请求头。要放在别处,在 `heade X-Access: Token {{access_token}} ``` +#### `providers[].aws` + + + + +| 字段 | 类型 | 默认值 | 说明 | +|---|---|---|---| +| `access_key_id` | 字符串,可写 `${VAR}` | **必填** | 访问密钥 ID。 | +| `secret_access_key` | 字符串,可写 `${VAR}` | **必填** | 私有访问密钥。 | +| `session_token` | 字符串,可写 `${VAR}` | — | 临时凭证(如 STS 签发的)的会话令牌。过期之后请求会被拒绝,直到换上新的。 | +| `region` | 字符串 | — | 签名用的区域。不写:取 `base_url` 里的区域,这时 `base_url` 必须是标准的推理地址。`base_url` 是 VPC 端点或代理时必须写。 | + + +Bedrock 上游有两种认证方式。Bedrock API Key 写在 `key` 中,以 `Authorization: Bearer` 发送。AWS 访问密钥写在 `aws` 中:每个请求在请求体定稿之后用它们签名(SigV4),密钥本身不会发送。两者都可以用 `${VAR}` 从环境变量读取。获取凭证时不执行任何命令,因此需要 `aws sso login` 或 `credential_process` 的配置文件无法使用,请改为导出它们生成的密钥。 + +```yaml +providers: + - name: bedrock + base_url: https://bedrock-runtime.us-east-1.amazonaws.com + key: ${AWS_BEARER_TOKEN_BEDROCK} + + - name: bedrock-keys + base_url: https://bedrock-runtime.eu-west-1.amazonaws.com + aws: + access_key_id: ${AWS_ACCESS_KEY_ID} + secret_access_key: ${AWS_SECRET_ACCESS_KEY} + session_token: ${AWS_SESSION_TOKEN} +``` + +请求转换为 Converse 格式。模型清单取自所在区域的控制面:可按需调用的基础模型、AWS 预设的推理配置(`us.anthropic.claude-…`),以及账号自己创建的应用推理配置(按调用时使用的 ARN 列出)。列出清单需要 `bedrock:ListFoundationModels` 和 `bedrock:ListInferenceProfiles` 权限;没有这两项权限时请求照常转发,可以在 `models` 中手动列出模型。使用 VPC 端点或代理时,在 `base_url` 中写它的地址,在 `aws.region` 中写区域;模型清单也向该地址获取。 + ### `proxies` 出站代理。不同上游需要的代理往往不同,因此没有全局开关:由每个上游用 `proxy` 选择。 diff --git a/scripts/smoke.sh b/scripts/smoke.sh index e86bfaf5..af0e8b1e 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -51,7 +51,31 @@ trap cleanup EXIT # ---------------------------------------------------------------- 假上游 cat > "$TMP/upstream.py" <<'PY' -import http.server, json, sys, time +import hashlib, http.server, json, struct, sys, time, zlib + +# ── 假的 Bedrock:Converse、ConverseStream(AWS eventstream 的二进制帧)和模型目录 +def frame(headers, payload): + """一帧 eventstream:前导(总长、头长、前导 CRC)、头、载荷、整帧 CRC""" + hb = b'' + for k, v in headers: + kb, vb = k.encode(), v.encode() + hb += bytes([len(kb)]) + kb + bytes([7]) + struct.pack('>H', len(vb)) + vb + prelude = struct.pack('>II', 12 + len(hb) + len(payload) + 4, len(hb)) + prelude += struct.pack('>I', zlib.crc32(prelude) & 0xffffffff) + msg = prelude + hb + payload + return msg + struct.pack('>I', zlib.crc32(msg) & 0xffffffff) + +def ev(kind, obj): + return frame([(':message-type', 'event'), (':event-type', kind), + (':content-type', 'application/json')], json.dumps(obj).encode()) + +def signed(headers, body): + """访问密钥签过名:签名覆盖的请求体哈希就是收到的这一份""" + auth = headers.get('authorization', '') + return (auth.startswith('AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7SMOKE/') + and 'x-amz-date' in headers + and headers.get('x-amz-content-sha256') == hashlib.sha256(body).hexdigest()) + class H(http.server.BaseHTTPRequestHandler): # **关掉 Nagle。**这个处理器先写响应头、再单独写正文,两次小写。开着 # Nagle 的话,正文要等对端确认了响应头才发;而 core 用的是池里的旧 @@ -65,13 +89,39 @@ class H(http.server.BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass + def reply(self, status, ctype, out): + self.send_response(status); self.send_header('content-type', ctype) + self.send_header('content-length', str(len(out))); self.end_headers(); self.wfile.write(out) def do_GET(self): + if self.path.startswith('/foundation-models'): + return self.reply(200, 'application/json', json.dumps( + {"modelSummaries": [{"modelId": "amazon.nova-lite-v1:0"}]}).encode()) + if self.path.startswith('/inference-profiles'): + return self.reply(200, 'application/json', json.dumps( + {"inferenceProfileSummaries": [ + {"inferenceProfileId": "us.anthropic.claude-sonnet-4-5-20250929-v1:0"}]}).encode()) out = json.dumps({"data": [{"id": "claude-sonnet-4-5"}]}).encode() self.send_response(200); self.send_header('content-type','application/json') self.send_header('content-length', str(len(out))); self.end_headers(); self.wfile.write(out) def do_POST(self): n = int(self.headers.get('content-length', 0) or 0) body = self.rfile.read(n) + if self.path.startswith('/model/'): + if not signed(self.headers, body): + return self.reply(403, 'application/json', json.dumps( + {"message": "The request signature we calculated does not match"}).encode()) + if self.path.endswith('/converse-stream'): + out = (ev('messageStart', {"role": "assistant"}) + + ev('contentBlockDelta', {"contentBlockIndex": 0, "delta": {"text": "bedrock-"}}) + + ev('contentBlockDelta', {"contentBlockIndex": 0, "delta": {"text": "stream"}}) + + ev('contentBlockStop', {"contentBlockIndex": 0}) + + ev('messageStop', {"stopReason": "end_turn"}) + + ev('metadata', {"usage": {"inputTokens": 31, "outputTokens": 3, "totalTokens": 34}})) + return self.reply(200, 'application/vnd.amazon.eventstream', out) + return self.reply(200, 'application/json', json.dumps({ + "output": {"message": {"role": "assistant", "content": [{"text": "bedrock-ok"}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 30, "outputTokens": 2, "totalTokens": 32}}).encode()) saw = "yes" if b"sk-ant-api03-SMOKEKEY" in body else "no" if b"SLOWSTREAM" in body: # 先吐第一帧(输入用量就在里面),然后长时间「思考」—— 客户端 @@ -154,6 +204,14 @@ providers: base_url: http://127.0.0.1:{upport} key: sk-upstream-smoke protocol: anthropic + # 假的 Bedrock 和它们是同一个服务:地址不是 AWS 的,签名用的区域写在 aws.region + - name: bedrock + base_url: http://127.0.0.1:{upport} + protocol: bedrock + aws: + access_key_id: AKIAIOSFODNN7SMOKE + secret_access_key: SMOKEsecretAccessKeyWithoutMuchShape + region: us-east-1 # **把流量钉在 relay 上。**脱敏是全局的,走哪家都会换;钉住是为了让 # 「这一条走了哪条路由」也有一个确定的答案,失败时少猜一件事。 # @@ -166,6 +224,10 @@ groups: routes: - name: 默认 rules: + - name: Bedrock 的模型走 Bedrock + when: + model: "us.anthropic.*" + to: bedrock - name: 冒烟:这条必须走 relay,不许转移 to: 只走中转 security: @@ -313,6 +375,39 @@ print("ok" if good else json.dumps(r, ensure_ascii=False, sort_keys=True))' 2>/d || bad "客户端中途走掉的请求没有按取消落库" "$GOT" fi +# ---------------------------------------------------------------- Bedrock +step "Bedrock" +# 转成 Converse、访问密钥签名(假 Bedrock 核对签名覆盖的请求体哈希)、 +# eventstream 的流转成客户端的 SSE、用量照记 +BR='{"model":"us.anthropic.claude-sonnet-4-5-20250929-v1:0","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}' +BRS='{"model":"us.anthropic.claude-sonnet-4-5-20250929-v1:0","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}' +R=$(curl -s -XPOST "http://127.0.0.1:$PORT/v1/messages" -H 'x-api-key: tw-smoketestkey0123456789' \ + -H 'content-type: application/json' -d "$BR") +echo "$R" | grep -q 'bedrock-ok' && ok "Anthropic 格式的请求经 Converse 到了 Bedrock,签名对得上" \ + || bad "Bedrock 的整包请求没通" "$R" +S=$(curl -s -XPOST "http://127.0.0.1:$PORT/v1/messages" -H 'x-api-key: tw-smoketestkey0123456789' \ + -H 'content-type: application/json' -d "$BRS") +TEXT=$(printf '%s' "$S" | python3 -c 'import sys, json +t = "" +for line in sys.stdin.read().splitlines(): + if line.startswith("data: "): + try: t += json.loads(line[6:]).get("delta", {}).get("text", "") + except Exception: pass +print(t)') +[ "$TEXT" = "bedrock-stream" ] && ok "eventstream 的流转成了客户端的 SSE" || bad "Bedrock 的流没转过来" "$S" +GOT="" +for _ in $(seq 1 20); do + GOT=$(ctl "/history?limit=1" 2>/dev/null \ + | python3 -c 'import sys, json +rows = json.load(sys.stdin) +r = rows[0] if rows else {} +good = r.get("provider") == "bedrock" and r.get("input_tokens") == 31 and r.get("output_tokens") == 3 +print("ok" if good else json.dumps(r, ensure_ascii=False, sort_keys=True))' 2>/dev/null) + [ "$GOT" = "ok" ] && break + sleep 0.25 +done +[ "$GOT" = "ok" ] && ok "Bedrock 的流式请求落了库,带着用量" || bad "Bedrock 的请求没带着用量落库" "$GOT" + # ---------------------------------------------------------------- 控制面 step "控制面要握手" sleep 1 @@ -386,7 +481,7 @@ fi # ---------------------------------------------------------------- 诊断包 step "诊断包不带密钥出门" get /diagnostics >/dev/null -if grep -qE "sk-upstream-smoke|tw-smoketestkey0123456789|$KEY" "$TMP/out"; then +if grep -qE "sk-upstream-smoke|tw-smoketestkey0123456789|SMOKEsecretAccessKey|$KEY" "$TMP/out"; then bad "诊断包里有真密钥" else ok "诊断包里没有真密钥"