From acf7210c984b41b1dcfa8911af0a0ed022b25d7e Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:36:45 +0800 Subject: [PATCH] feat(config): read a Bedrock upstream's keys from an AWS profile `aws.profile` names a profile in the AWS credential files (`~/.aws/credentials`, `~/.aws/config`, or the files that AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE name) instead of writing the keys in the configuration. The files are looked at on every request and read again only when they change, so a tool that refreshes temporary keys in the credentials file needs no configuration change and no restart; before, an expired session token meant editing the configuration or restarting core. Nothing is run: a profile that signs in through IAM Identity Center, runs a `credential_process`, assumes a role or uses a web identity token is refused, naming the setting, in the order the AWS CLI applies them. The profile and the keys are alternatives; an expired token on a profile upstream says to refresh the profile. Co-Authored-By: Claude Opus 5.5 --- bin/twcore/src/main.rs | 10 +- crates/tw-api/msg-codes.txt | 8 + crates/tw-api/src/lib.rs | 21 +- crates/tw-config/src/aws_profile.rs | 408 +++++++++++++++++++ crates/tw-config/src/credential.rs | 93 ++++- crates/tw-config/src/lib.rs | 16 +- crates/tw-config/tests/manual/schema.rs | 28 +- crates/tw-control/src/lib.rs | 14 +- crates/tw-control/src/resources.rs | 8 +- crates/tw-control/tests/bedrock.rs | 41 ++ crates/tw-gateway/src/server/pipeline/hop.rs | 14 +- crates/tw-gateway/tests/bedrock.rs | 6 +- crates/tw-gateway/tests/bedrock_profile.rs | 121 ++++++ docs/config.md | 28 +- docs/config.zh-CN.md | 14 +- 15 files changed, 766 insertions(+), 64 deletions(-) create mode 100644 crates/tw-config/src/aws_profile.rs create mode 100644 crates/tw-gateway/tests/bedrock_profile.rs diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index fc89db13..815ee3fc 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -617,10 +617,14 @@ fn cmd_check(path: &Path) -> Result<()> { format!("API key {} ({})", k.describe(), p.auth_header().0) } (None, Some(_), _) => "OAuth".to_string(), - // 签名用的密钥:说来源(环境变量还是写死的),不说值 + // 签名用的密钥:说来源(环境变量、写死的还是 profile),不说值 (None, None, Some(a)) => format!( - "AWS access key {}, signed for {}", - a.access_key_id.describe(), + "{}, signed for {}", + match (&a.profile, &a.access_key_id) { + (Some(profile), _) => format!("AWS profile `{profile}`"), + (None, Some(id)) => format!("AWS access key {}", id.describe()), + (None, None) => "no AWS access key".to_string(), + }, p.bedrock_region().unwrap_or("an unknown region") ), (None, None, None) if !p.headers.is_empty() => "headers".to_string(), diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index e42c329e..f324c5c5 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -3,6 +3,11 @@ # A second column marks codes a UI does not translate: # passthrough the sentence is only placeholders (system or upstream text); show `text` # test only produced by tests; never reaches a UI +config.aws_profile.no_home +config.aws_profile.no_keys +config.aws_profile.not_found +config.aws_profile.unreadable +config.aws_profile.unsupported config.bad_allow_from config.bad_base_url config.bad_remote_allow_from @@ -11,8 +16,10 @@ config.control_key_invalid config.control_key_missing config.credential.aws_bad_region config.credential.aws_empty +config.credential.aws_empty_profile config.credential.aws_no_region config.credential.aws_not_bedrock +config.credential.aws_profile_and_keys config.credential.aws_region_mismatch config.credential.aws_signed_header config.credential.bad_header_name @@ -267,6 +274,7 @@ gw.route.selected_upstream_missing gw.route.upstream_missing gw.toolcall.blocked gw.toolcall.cut +gw.upstream.aws_profile_expired gw.upstream.aws_token_expired gw.upstream.bedrock_refused gw.upstream.eventstream_broken diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 694682ce..24513766 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -631,7 +631,8 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// 写的界面不认那个新事件。 /// /// **28 起有 Bedrock 上游**:[`Protocol`] 多了 `bedrock`,[`ProviderInput::aws`] / -/// [`ProviderView::aws`]([`AwsKeys`]:AWS 访问密钥,每个请求签名)、 +/// [`ProviderView::aws`]([`AwsKeys`]:AWS 访问密钥,写在配置里或者从 AWS 的 profile 读, +/// 每个请求签名)、 /// [`ProviderView::region`] 和 [`ProviderPreview::region`]。Bedrock API Key 走 /// 原来的 `key`,放进 `Authorization: Bearer`。照 27 写的界面解析不了带 `bedrock` 的 /// 上游列表。 @@ -1711,18 +1712,26 @@ pub struct HeaderView { pub value: String, } -/// Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。每一项都可以写 -/// `${NAME}` 从环境变量读。视图和保存用的是同一个:配置里写的原样。 -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +/// Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。视图和保存用的是同一个: +/// 配置里写的原样。 +/// +/// **两种写法二选一**:密钥写在这里(每一项都可以写 `${NAME}` 从环境变量读),或者 +/// 写一个 `profile`,从 core 所在机器的 AWS 凭证文件里读,文件变了下一个请求就用新的。 +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct AwsKeys { /// 访问密钥 ID - pub access_key_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub access_key_id: Option, /// 私有访问密钥 - pub secret_access_key: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret_access_key: Option, /// 会话令牌:临时凭证才有 #[serde(default, skip_serializing_if = "Option::is_none")] pub session_token: Option, + /// AWS 凭证文件(`~/.aws/credentials`、`~/.aws/config`)里的 profile 名 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, /// 签名用的区域。地址是标准的 `https://bedrock-runtime.<区域>.amazonaws.com` /// 时不用给,从地址读 #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/tw-config/src/aws_profile.rs b/crates/tw-config/src/aws_profile.rs new file mode 100644 index 00000000..2a49bcac --- /dev/null +++ b/crates/tw-config/src/aws_profile.rs @@ -0,0 +1,408 @@ +//! AWS 的共享凭证文件:`~/.aws/credentials` 和 `~/.aws/config` 里的 profile。 +//! +//! Bedrock 上游写 `aws.profile`,请求就用那个 profile 的访问密钥签名。**每个请求都按 +//! 文件现在的样子取**:刷新临时凭证的工具(aws-vault、saml2aws、公司自己的脚本)把新 +//! 的密钥写回这个文件,下一个请求就用上了,不用改配置、不用重启。文件没变就不重读, +//! 每个请求只多一次 stat。 +//! +//! **只读文件里写着的密钥,不执行任何东西**(见 [`crate::credential`] 的模块注释)。 +//! 要跑程序、要联网才拿得到凭证的 profile —— IAM Identity Center 登录、 +//! `credential_process`、扮演角色、Web 身份令牌 —— 这里接不了,会说清是哪一种。 +//! +//! 文件在哪儿和 AWS CLI 一样:`AWS_SHARED_CREDENTIALS_FILE`、`AWS_CONFIG_FILE` 优先, +//! 没有就是用户目录下的 `.aws`。**读的是 core 所在的那台机器**:连着远程 core 时是 +//! 服务器上的文件。 + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, LazyLock, Mutex}; +use std::time::SystemTime; + +use tw_types::{Msg, msg}; + +/// 要跑程序或者联网才拿得到凭证的写法,按 AWS CLI 认它们的先后排。 +/// +/// AWS CLI 先看扮演角色、Web 身份和 IAM Identity Center,再看文件里的密钥 —— 一个写了 +/// `role_arn` 的 profile 就是要扮演那个角色,旁边写着的密钥只是扮演用的,拿它直接签名 +/// 签出来的是另一个身份。`credential_process` 排在凭证文件的密钥之后、配置文件的密钥 +/// 之前。 +const BEFORE_KEYS: &[&str] = &[ + "role_arn", + "web_identity_token_file", + "sso_session", + "sso_start_url", + "sso_account_id", +]; +const PROCESS: &str = "credential_process"; + +/// 取凭证失败的原因。 +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ProfileError { + #[error("{}", self.msg())] + NoHome, + #[error("{}", self.msg())] + Unreadable { path: String, detail: String }, + #[error("{}", self.msg())] + NotFound { + profile: String, + credentials: String, + config: String, + }, + #[error("{}", self.msg())] + Unsupported { + profile: String, + setting: &'static str, + }, + #[error("{}", self.msg())] + NoKeys { profile: String }, +} + +impl ProfileError { + pub fn msg(&self) -> Msg { + match self { + Self::NoHome => msg!( + "config.aws_profile.no_home" => + "the home directory is unknown, so the AWS credential files cannot be found; set \ + AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE" + ), + Self::Unreadable { path, detail } => msg!( + "config.aws_profile.unreadable", path = path, detail = detail => + "{path} could not be read: {detail}" + ), + Self::NotFound { + profile, + credentials, + config, + } => msg!( + "config.aws_profile.not_found", + profile = profile, credentials = credentials, config = config => + "AWS profile `{profile}` is in neither {credentials} nor {config}" + ), + Self::Unsupported { profile, setting } => msg!( + "config.aws_profile.unsupported", profile = profile, setting = setting => + "AWS profile `{profile}` gets its credential through `{setting}`, which ThinkWatch \ + does not run; it only reads access keys written in the profile" + ), + Self::NoKeys { profile } => msg!( + "config.aws_profile.no_keys", profile = profile => + "AWS profile `{profile}` has no access keys: aws_access_key_id and \ + aws_secret_access_key are both needed" + ), + } + } +} + +/// 两个文件在哪儿。 +#[derive(Debug, Clone, PartialEq)] +pub struct Files { + pub credentials: PathBuf, + pub config: PathBuf, +} + +impl Files { + /// 和 AWS CLI 同一个找法。 + pub fn locate() -> Result { + let env = |k: &str| { + std::env::var_os(k) + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + }; + // Windows 上 AWS CLI 找的是 USERPROFILE,不是 HOME(Git Bash 会设一个 HOME) + let home = || { + let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; + env(var).map(|h| h.join(".aws")).ok_or(ProfileError::NoHome) + }; + Ok(Files { + credentials: match env("AWS_SHARED_CREDENTIALS_FILE") { + Some(p) => p, + None => home()?.join("credentials"), + }, + config: match env("AWS_CONFIG_FILE") { + Some(p) => p, + None => home()?.join("config"), + }, + }) + } +} + +/// profile 的访问密钥,按文件现在的样子。 +pub fn credentials(profile: &str) -> Result { + credentials_in(profile, &Files::locate()?) +} + +/// 同上,文件由调用方指定。 +pub fn credentials_in( + profile: &str, + files: &Files, +) -> Result { + let creds = read(&files.credentials)?; + let config = read(&files.config)?; + // 凭证文件里写 `[名字]`;配置文件里写 `[profile 名字]`,只有 default 是 `[default]` + let in_creds = creds.as_ref().and_then(|ini| ini.get(profile)); + let in_config = config.as_ref().and_then(|ini| { + ini.get(&format!("profile {profile}")) + .or_else(|| ini.get(profile).filter(|_| profile == "default")) + }); + if in_creds.is_none() && in_config.is_none() { + return Err(ProfileError::NotFound { + profile: profile.to_string(), + credentials: shown(&files.credentials), + config: shown(&files.config), + }); + } + let sections = || [in_creds, in_config].into_iter().flatten(); + let unsupported = |setting: &'static str| ProfileError::Unsupported { + profile: profile.to_string(), + setting, + }; + if let Some(s) = BEFORE_KEYS + .iter() + .find(|s| sections().any(|sec| sec.contains_key(**s))) + { + return Err(unsupported(s)); + } + if let Some(c) = in_creds.and_then(keys) { + return Ok(c); + } + if sections().any(|sec| sec.contains_key(PROCESS)) { + return Err(unsupported(PROCESS)); + } + in_config.and_then(keys).ok_or(ProfileError::NoKeys { + profile: profile.to_string(), + }) +} + +type Section = HashMap; +type Ini = HashMap; + +/// 一节里的访问密钥。两样都在才算有 +fn keys(sec: &Section) -> Option { + let get = |k: &str| sec.get(k).filter(|v| !v.is_empty()).cloned(); + Some(tw_bedrock::Credentials { + access_key_id: get("aws_access_key_id")?, + secret_access_key: get("aws_secret_access_key")?, + session_token: get("aws_session_token"), + }) +} + +/// 解析过的文件,和解析时它的样子(修改时间、长度)。 +struct Cached { + stamp: (Option, u64), + ini: Arc, +} + +static CACHE: LazyLock>> = LazyLock::new(Default::default); + +/// 读一个文件。**没变就用上次解析的**;不存在是 `None`(两个文件缺一个是常事)。 +fn read(path: &Path) -> Result>, ProfileError> { + let unreadable = |e: std::io::Error| ProfileError::Unreadable { + path: shown(path), + detail: e.to_string(), + }; + let meta = match std::fs::metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(unreadable(e)), + }; + let stamp = (meta.modified().ok(), meta.len()); + let mut cache = CACHE.lock().unwrap_or_else(|p| p.into_inner()); + if let Some(c) = cache.get(path).filter(|c| c.stamp == stamp) { + return Ok(Some(c.ini.clone())); + } + let ini = Arc::new(parse(&std::fs::read_to_string(path).map_err(unreadable)?)); + cache.insert( + path.to_path_buf(), + Cached { + stamp, + ini: ini.clone(), + }, + ); + Ok(Some(ini)) +} + +/// AWS 那种 INI。 +/// +/// - 节名里的空白压成一个空格:`[profile dev]` 就是 `profile dev` +/// - 键不分大小写,值去掉两头空白。**行尾的 `#` 不是注释** —— AWS CLI 也不这么认, +/// 密钥里可以有它 +/// - 缩进的行是上一个键的子项(`s3 =` 下面那种),不是这一节的键 +fn parse(text: &str) -> Ini { + let mut out = Ini::new(); + let mut current: Option = None; + for line in text.lines() { + let l = line.trim(); + if l.is_empty() || l.starts_with('#') || l.starts_with(';') { + continue; + } + if let Some(name) = l.strip_prefix('[').and_then(|r| r.strip_suffix(']')) { + let name = name.split_whitespace().collect::>().join(" "); + out.entry(name.clone()).or_default(); + current = Some(name); + continue; + } + if line.starts_with(char::is_whitespace) { + continue; + } + if let (Some(sec), Some((k, v))) = (current.as_ref(), l.split_once('=')) + && let Some(s) = out.get_mut(sec) + { + s.insert(k.trim().to_ascii_lowercase(), v.trim().to_string()); + } + } + out +} + +/// 报错里的路径:用户目录写成 `~`。 +fn shown(path: &Path) -> String { + let var = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; + match std::env::var_os(var) + .filter(|h| !h.is_empty()) + .and_then(|h| path.strip_prefix(h).ok().map(Path::to_path_buf)) + { + Some(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()), + None => path.display().to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// 一个临时目录里的两个文件。每条测试各用各的目录:缓存按路径记 + fn files(credentials: Option<&str>, config: Option<&str>) -> (tempfile::TempDir, Files) { + let dir = tempfile::tempdir().unwrap(); + let f = Files { + credentials: dir.path().join("credentials"), + config: dir.path().join("config"), + }; + if let Some(t) = credentials { + std::fs::write(&f.credentials, t).unwrap(); + } + if let Some(t) = config { + std::fs::write(&f.config, t).unwrap(); + } + (dir, f) + } + + #[test] + fn keys_come_from_the_credentials_file_then_from_the_config_file() { + let (_d, f) = files( + Some( + "[default]\naws_access_key_id = AKIADEFAULT\naws_secret_access_key = s1\n\n[dev]\naws_access_key_id=AKIADEV\naws_secret_access_key=s2\naws_session_token = t2\n", + ), + Some("[profile ci]\naws_access_key_id = AKIACI\naws_secret_access_key = s3\n"), + ); + let dev = credentials_in("dev", &f).unwrap(); + assert_eq!( + (dev.access_key_id.as_str(), dev.secret_access_key.as_str()), + ("AKIADEV", "s2") + ); + assert_eq!(dev.session_token.as_deref(), Some("t2")); + assert_eq!( + credentials_in("default", &f).unwrap().access_key_id, + "AKIADEFAULT" + ); + // 配置文件里也可以写密钥 + assert_eq!(credentials_in("ci", &f).unwrap().access_key_id, "AKIACI"); + } + + #[test] + fn a_profile_that_needs_a_program_or_a_sign_in_says_which_it_is() { + let (_d, f) = files( + Some("[mixed]\naws_access_key_id = AKIASOURCE\naws_secret_access_key = s\n"), + Some( + "[profile sso]\nsso_session = corp\nsso_account_id = 1\n\n\ + [profile proc]\ncredential_process = /usr/local/bin/get-creds\n\n\ + [profile mixed]\nrole_arn = arn:aws:iam::123456789012:role/Dev\nsource_profile = default\n", + ), + ); + let setting = |p: &str| match credentials_in(p, &f) { + Err(ProfileError::Unsupported { setting, .. }) => setting, + other => panic!("{p}: {other:?}"), + }; + assert_eq!(setting("sso"), "sso_session"); + assert_eq!(setting("proc"), "credential_process"); + // 写了 role_arn 就是要扮演角色:旁边的密钥不能拿来直接签名 + assert_eq!(setting("mixed"), "role_arn"); + } + + #[test] + fn a_missing_profile_and_a_profile_without_keys_are_told_apart() { + let (_d, f) = files( + Some("[half]\naws_access_key_id = AKIAHALF\n"), + Some("[profile regional]\nregion = us-west-2\n"), + ); + assert!(matches!( + credentials_in("nope", &f), + Err(ProfileError::NotFound { .. }) + )); + assert!(matches!( + credentials_in("half", &f), + Err(ProfileError::NoKeys { .. }) + )); + assert!(matches!( + credentials_in("regional", &f), + Err(ProfileError::NoKeys { .. }) + )); + // `[profile default]` 不是写 default 的地方,但 `[default]` 在配置文件里是 + let (_d, f) = files( + None, + Some("[default]\naws_access_key_id = AKIAD\naws_secret_access_key = s\n"), + ); + assert_eq!( + credentials_in("default", &f).unwrap().access_key_id, + "AKIAD" + ); + // 两个文件都没有 + let (_d, f) = files(None, None); + assert!(matches!( + credentials_in("default", &f), + Err(ProfileError::NotFound { .. }) + )); + } + + #[test] + fn a_rewritten_file_is_read_again() { + let (_d, f) = files( + Some("[dev]\naws_access_key_id = AKIAOLD\naws_secret_access_key = s\n"), + None, + ); + assert_eq!(credentials_in("dev", &f).unwrap().access_key_id, "AKIAOLD"); + // 同样长短的新密钥,改动时间往后挪:只看长度的话会认成没变 + std::fs::write( + &f.credentials, + "[dev]\naws_access_key_id = AKIANEW\naws_secret_access_key = s\n", + ) + .unwrap(); + let later = SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options() + .write(true) + .open(&f.credentials) + .unwrap() + .set_modified(later) + .unwrap(); + assert_eq!(credentials_in("dev", &f).unwrap().access_key_id, "AKIANEW"); + } + + #[test] + fn the_format_is_read_the_way_the_aws_cli_reads_it() { + let ini = parse( + "# comment\n; also a comment\n[profile spaced]\nAWS_Access_Key_ID = AKIA#1\n\ + s3 =\n max_concurrent_requests = 20\n role_arn = nested\n", + ); + let sec = &ini["profile spaced"]; + assert_eq!(sec["aws_access_key_id"], "AKIA#1", "行尾的 # 是值的一部分"); + assert!(!sec.contains_key("role_arn"), "缩进的行是 s3 的子项"); + assert!(!sec.contains_key("max_concurrent_requests")); + } + + #[test] + fn nothing_the_files_say_ends_up_in_the_error_text() { + let (_d, f) = files( + Some("[x]\naws_secret_access_key = wJalrXUtnFEMI/K7MDENG\n"), + None, + ); + let e = credentials_in("x", &f).unwrap_err().msg(); + assert!(!e.text.contains("wJalr"), "{}", e.text); + } +} diff --git a/crates/tw-config/src/credential.rs b/crates/tw-config/src/credential.rs index 9ca69bb0..37051a85 100644 --- a/crates/tw-config/src/credential.rs +++ b/crates/tw-config/src/credential.rs @@ -333,6 +333,13 @@ pub enum CredentialError { #[error("{}", self.msg())] AwsEmpty, #[error("{}", self.msg())] + AwsProfileAndKeys, + #[error("{}", self.msg())] + AwsEmptyProfile, + /// profile 读不出密钥。只在转发、检查连接时出现:文件是那台机器上的,随时会变 + #[error("{}", self.msg())] + AwsProfile(crate::aws_profile::ProfileError), + #[error("{}", self.msg())] AwsSignedHeader(String), #[error("{}", self.msg())] AwsNoRegion, @@ -448,6 +455,16 @@ impl CredentialError { "the access key ID, the secret access key and a session token, when given, cannot \ be empty" ), + AwsProfileAndKeys => msg!( + "config.credential.aws_profile_and_keys" => + "aws.profile and the access keys are alternatives: keys read from an AWS profile, \ + or keys written here" + ), + AwsEmptyProfile => msg!( + "config.credential.aws_empty_profile" => + "aws.profile names no profile; write a profile name such as default" + ), + AwsProfile(e) => e.msg(), AwsSignedHeader(h) => msg!( "config.credential.aws_signed_header", header = h => "requests to this upstream are signed with its AWS access keys, and signing sets \ @@ -631,11 +648,22 @@ impl Provider { 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); + let keys = aws.access_key_id.is_some() + || aws.secret_access_key.is_some() + || aws.session_token.is_some(); + match &aws.profile { + Some(_) if keys => return Err(CredentialError::AwsProfileAndKeys), + Some(p) if p.trim().is_empty() => return Err(CredentialError::AwsEmptyProfile), + Some(_) => {} + None => { + let blank = |s: &Option| s.as_ref().is_none_or(Secret::is_blank); + if blank(&aws.access_key_id) + || blank(&aws.secret_access_key) + || 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() => { @@ -663,14 +691,24 @@ impl Provider { Ok(()) } - /// 签名用的 AWS 凭证,`${ENV}` 已经展开。不用访问密钥的上游是 `None`。 + /// 签名用的 AWS 凭证,`${ENV}` 已经展开,profile 按文件现在的样子读。不用访问密钥 + /// 的上游是 `None`。 pub fn aws_credentials(&self) -> Result, CredentialError> { let Some(aws) = &self.aws else { return Ok(None); }; + if let Some(profile) = &aws.profile { + return crate::aws_profile::credentials(profile.trim()) + .map(Some) + .map_err(CredentialError::AwsProfile); + } + // 写法检查保证了两样都在;走到这里还缺,是没经过检查的配置 + let (Some(id), Some(secret)) = (&aws.access_key_id, &aws.secret_access_key) else { + return Err(CredentialError::AwsEmpty); + }; Ok(Some(tw_bedrock::Credentials { - access_key_id: aws.access_key_id.resolve()?, - secret_access_key: aws.secret_access_key.resolve()?, + access_key_id: id.resolve()?, + secret_access_key: secret.resolve()?, session_token: aws .session_token .as_ref() @@ -727,14 +765,15 @@ impl Provider { s.push_str(h.value.raw()); } if let Some(a) = &self.aws { + fn raw(v: &Option) -> &str { + v.as_ref().map(Secret::raw).unwrap_or_default() + } 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(), + "|aws|{}|{}|{}|{}|{}", + raw(&a.access_key_id), + raw(&a.secret_access_key), + raw(&a.session_token), + a.profile.as_deref().unwrap_or_default(), a.region.as_deref().unwrap_or_default() )); } @@ -1083,6 +1122,30 @@ mod tests { bedrock("aws:\n access_key_id: ''\n secret_access_key: s\n").check_credential(), Err(AwsEmpty) ); + // 只写了一半的密钥 + assert_eq!( + bedrock("aws:\n access_key_id: AKIA\n").check_credential(), + Err(AwsEmpty) + ); + assert_eq!(bedrock("aws: {}\n").check_credential(), Err(AwsEmpty)); + } + + #[test] + fn a_profile_stands_in_for_the_keys_and_not_beside_them() { + use CredentialError::*; + assert_eq!(bedrock("aws:\n profile: dev\n").check_credential(), Ok(())); + assert_eq!( + bedrock(&format!("{KEYS} profile: dev\n")).check_credential(), + Err(AwsProfileAndKeys) + ); + assert_eq!( + bedrock("aws:\n profile: dev\n session_token: t\n").check_credential(), + Err(AwsProfileAndKeys) + ); + assert_eq!( + bedrock("aws:\n profile: ' '\n").check_credential(), + Err(AwsEmptyProfile) + ); } #[test] diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 9f81a39c..bb456fef 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; +pub mod aws_profile; pub mod chatgpt; pub mod control_key; pub mod credential; @@ -670,21 +671,28 @@ pub struct OAuth { pub refresh_before: Option, } -/// Bedrock 的 AWS 访问密钥。 +/// Bedrock 的 AWS 访问密钥:写在这里,或者从 AWS 的凭证文件里按 profile 读。 /// /// 每个请求用它们签一次名(SigV4):签的是方法、地址、时间和请求体,所以签名在 /// 转发时、请求体定稿之后才做,配置里只放密钥本身。每一项都可以写 `${ENV}`。 /// /// **只读密钥,不执行命令**:`aws sso login`、`credential_process` 这类要跑程序才拿得到 /// 的凭证这里接不了,见 [`credential`]。 -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Aws { - pub access_key_id: Secret, - pub secret_access_key: Secret, + /// 访问密钥 ID。和 `profile` 二选一 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub access_key_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub secret_access_key: Option, /// 临时凭证(STS 发的)才有 #[serde(default, skip_serializing_if = "Option::is_none")] pub session_token: Option, + /// 从 AWS 的凭证文件(`~/.aws/credentials`、`~/.aws/config`)读这个 profile 的密钥。 + /// **文件变了下一个请求就用新的**,见 [`aws_profile`] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub profile: Option, /// 签名用的区域。地址是标准的 `https://bedrock-runtime.<区域>.amazonaws.com` 时从 /// 地址读,不用写;地址是 VPC 端点或代理时必须写 #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 6b691808..b65337e7 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -455,8 +455,8 @@ pub fn sections() -> Vec
{ 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)二选一。", + "AWS access keys of a Bedrock upstream, written there or read from an AWS profile: every request is signed with them (SigV4). Instead of `key`, which holds a Bedrock API key.", + "Bedrock 上游的 AWS 访问密钥,写在这里或者从 AWS 的 profile 读:每个请求用它们签名(SigV4)。与 `key`(Bedrock API Key)二选一。", ), ), row( @@ -544,21 +544,22 @@ pub fn sections() -> Vec
{ }, Section { path: "providers[].aws", - ty: checked!( - Aws, - "{access_key_id: AKIAIOSFODNN7EXAMPLE, secret_access_key: s}" - ), + // 字段都可选:写访问密钥还是写 profile,由写法检查管二选一 + ty: checked!(Aws, "{}"), rows: vec![ row( "access_key_id", Kind::Secret, - Def::Required, - t("Access key ID.", "访问密钥 ID。"), + Def::Unset, + t( + "Access key ID. Written together with `secret_access_key`; `profile` instead.", + "访问密钥 ID。与 `secret_access_key` 一起写;也可以改写 `profile`。", + ), ), row( "secret_access_key", Kind::Secret, - Def::Required, + Def::Unset, t("Secret access key.", "私有访问密钥。"), ), row( @@ -570,6 +571,15 @@ pub fn sections() -> Vec
{ "临时凭证(如 STS 签发的)的会话令牌。过期之后请求会被拒绝,直到换上新的。", ), ), + row( + "profile", + Kind::Str, + Def::Unset, + t( + "Profile in the AWS credential files to read the access keys from, instead of writing them here: `~/.aws/credentials` and `~/.aws/config`, or the files `AWS_SHARED_CREDENTIALS_FILE` and `AWS_CONFIG_FILE` name, on the machine core runs on. The files are read again when they change.", + "从 AWS 凭证文件读访问密钥时用的 profile,代替把密钥写在这里:`~/.aws/credentials` 和 `~/.aws/config`,或 `AWS_SHARED_CREDENTIALS_FILE`、`AWS_CONFIG_FILE` 指定的文件,读的是 core 所在机器上的。文件变了会重新读。", + ), + ), row( "region", Kind::Str, diff --git a/crates/tw-control/src/lib.rs b/crates/tw-control/src/lib.rs index b6852c18..c76add74 100644 --- a/crates/tw-control/src/lib.rs +++ b/crates/tw-control/src/lib.rs @@ -440,11 +440,15 @@ 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(), + aws: p.aws.as_ref().map(|a| { + let raw = |s: &Option| s.as_ref().map(|s| s.raw().to_string()); + tw_api::AwsKeys { + access_key_id: raw(&a.access_key_id), + secret_access_key: raw(&a.secret_access_key), + session_token: raw(&a.session_token), + profile: a.profile.clone(), + region: a.region.clone(), + } }), region: p .is_bedrock() diff --git a/crates/tw-control/src/resources.rs b/crates/tw-control/src/resources.rs index e636530b..d64096ee 100644 --- a/crates/tw-control/src/resources.rs +++ b/crates/tw-control/src/resources.rs @@ -386,17 +386,19 @@ fn to_provider( }) } }; - // 会话令牌空着就是没有:界面交上来的是一个空的框 + // 空着的框就是没写:界面交上来的是空串 let nonblank = |v: &Option| { v.as_deref() .map(str::trim) .filter(|x| !x.is_empty()) .map(str::to_string) }; + // 密钥和 profile 二选一由写法检查说(保存时校验) 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()), + access_key_id: nonblank(&a.access_key_id).map(tw_config::Secret::new), + secret_access_key: nonblank(&a.secret_access_key).map(tw_config::Secret::new), session_token: nonblank(&a.session_token).map(tw_config::Secret::new), + profile: nonblank(&a.profile), region: nonblank(&a.region), }); let provider = tw_config::Provider { diff --git a/crates/tw-control/tests/bedrock.rs b/crates/tw-control/tests/bedrock.rs index 49bb2886..6bb5bf31 100644 --- a/crates/tw-control/tests/bedrock.rs +++ b/crates/tw-control/tests/bedrock.rs @@ -143,6 +143,38 @@ async fn access_keys_are_saved_and_shown_as_written() { assert!(p.get("key").is_none(), "{p}"); } +/// profile 只存名字:密钥留在 AWS 的凭证文件里,**配置里一个字都不抄** +#[tokio::test] +async fn a_profile_is_saved_by_name_alone() { + let b = bed(BASE); + let (st, v) = call( + &b.app, + "POST", + "/providers", + json!({"provider": { + "name": "bedrock", + "base_url": "https://bedrock-runtime.us-west-2.amazonaws.com", + "aws": {"profile": " dev ", "access_key_id": "", "secret_access_key": ""}, + }}), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + let file = b.file(); + assert!(file.contains("profile: dev"), "{file}"); + assert!(!file.contains("access_key_id"), "{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["aws"], json!({"profile": "dev"}), "{p}"); + assert_eq!(p["region"], "us-west-2"); +} + #[tokio::test] async fn a_bedrock_upstream_is_refused_without_exactly_one_credential() { let b = bed(BASE); @@ -165,6 +197,15 @@ async fn a_bedrock_upstream_is_refused_without_exactly_one_credential() { json!({"name": "b", "base_url": url, "aws": {"access_key_id": "AKIA", "secret_access_key": "s", "region": "eu-west-1"}}), "config.credential.aws_region_mismatch", ), + ( + json!({"name": "b", "base_url": url, "aws": {"access_key_id": "AKIA", "secret_access_key": "s", "profile": "dev"}}), + "config.credential.aws_profile_and_keys", + ), + ( + // 界面的空框什么都不算:既没有密钥,也没有 profile + json!({"name": "b", "base_url": url, "aws": {"access_key_id": " ", "profile": ""}}), + "config.credential.aws_empty", + ), ] { let (st, v) = call(&b.app, "POST", "/providers", json!({"provider": provider})).await; assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); diff --git a/crates/tw-gateway/src/server/pipeline/hop.rs b/crates/tw-gateway/src/server/pipeline/hop.rs index 071250e4..da93df34 100644 --- a/crates/tw-gateway/src/server/pipeline/hop.rs +++ b/crates/tw-gateway/src/server/pipeline/hop.rs @@ -786,13 +786,21 @@ async fn bedrock_refusal( .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!( + let profile = provider.aws.as_ref().and_then(|a| a.profile.clone()); + let text = match (kind.as_deref(), profile) { + // profile 的密钥由刷新它的工具写回文件,下一个请求就读新的:不用改配置 + (Some("ExpiredTokenException"), Some(profile)) => msg!( + "gw.upstream.aws_profile_expired", + upstream = provider.name.clone(), profile = profile => + "[ThinkWatch] The temporary AWS credential of upstream `{upstream}` has expired. \ + Refresh AWS profile `{profile}`; the next request reads it again." + ), + (Some("ExpiredTokenException"), None) => 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!( + (other, _) => msg!( "gw.upstream.bedrock_refused", upstream = provider.name.clone(), status = status.as_u16(), kind = other.unwrap_or("no exception name") => diff --git a/crates/tw-gateway/tests/bedrock.rs b/crates/tw-gateway/tests/bedrock.rs index 7707e0ea..6f9f7cad 100644 --- a/crates/tw-gateway/tests/bedrock.rs +++ b/crates/tw-gateway/tests/bedrock.rs @@ -150,10 +150,10 @@ fn with_keys(up: SocketAddr) -> Provider { 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, + access_key_id: Some(Secret::new(AK)), + secret_access_key: Some(Secret::new(SK)), region: Some(REGION.into()), + ..Default::default() }), ..Default::default() } diff --git a/crates/tw-gateway/tests/bedrock_profile.rs b/crates/tw-gateway/tests/bedrock_profile.rs new file mode 100644 index 00000000..a44f976e --- /dev/null +++ b/crates/tw-gateway/tests/bedrock_profile.rs @@ -0,0 +1,121 @@ +//! Bedrock 上游用 AWS 的 profile:密钥从凭证文件读,**文件变了下一个请求就用新的**。 +//! +//! 单独一个测试程序:凭证文件在哪儿由环境变量 `AWS_SHARED_CREDENTIALS_FILE` 说,而 +//! 进程里改环境变量要保证没有别的线程同时在读 —— 和别的测试放在一起就保证不了。 + +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime}; + +use axum::Router; +use axum::http::HeaderMap; +use serde_json::json; +use tw_config::{Aws, Client, Config, Listen, Protocol, Provider}; + +const MODEL: &str = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"; + +/// 假的 Bedrock:记下每个请求的 `authorization`,回一段 Converse 的回答 +async fn bedrock() -> (SocketAddr, Arc>>) { + let seen: Arc>> = Arc::default(); + let log = seen.clone(); + let app = Router::new().fallback(move |headers: HeaderMap| { + let log = log.clone(); + async move { + let auth = headers + .get("authorization") + .and_then(|v| v.to_str().ok()) + .unwrap_or_default() + .to_string(); + log.lock().unwrap().push(auth); + axum::Json(json!({ + "output": {"message": {"role": "assistant", "content": [{"text": "hi"}]}}, + "stopReason": "end_turn", + "usage": {"inputTokens": 3, "outputTokens": 1, "totalTokens": 4} + })) + } + }); + 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 credentials(key_id: &str) -> String { + format!("[dev]\naws_access_key_id = {key_id}\naws_secret_access_key = secret-{key_id}\n") +} + +#[tokio::test] +async fn a_profile_signs_with_what_its_file_says_now() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("credentials"); + std::fs::write(&file, credentials("AKIAPROFILEONE")).unwrap(); + // SAFETY: 这个测试程序里只有这一条测试,改的时候还没有别的线程在读环境变量 + unsafe { + std::env::set_var("AWS_SHARED_CREDENTIALS_FILE", &file); + std::env::set_var("AWS_CONFIG_FILE", dir.path().join("config")); + } + + let (up, seen) = bedrock().await; + let cfg = Config { + version: 1, + listen: Listen::default(), + clients: vec![Client { + name: "c".into(), + key: "tw-k".into(), + ..Default::default() + }], + providers: vec![Provider { + name: "br".into(), + base_url: format!("http://{up}"), + protocol: Some(Protocol::Bedrock), + aws: Some(Aws { + profile: Some("dev".into()), + region: Some("us-west-2".into()), + ..Default::default() + }), + ..Default::default() + }], + ..Default::default() + }; + let state = tw_gateway::AppState::new(cfg).unwrap(); + let gw = tw_gateway::serve(state, ([127, 0, 0, 1], 0).into()) + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(50)).await; + let ask = || async { + reqwest::Client::new() + .post(format!("http://{gw}/v1/chat/completions")) + .bearer_auth("tw-k") + .json(&json!({"model": MODEL, "messages": [{"role": "user", "content": "hi"}]})) + .send() + .await + .unwrap() + .status() + .as_u16() + }; + + assert_eq!(ask().await, 200); + // 刷新凭证的工具把新的密钥写回同一个文件 + std::fs::write(&file, credentials("AKIAPROFILETWO")).unwrap(); + std::fs::File::options() + .write(true) + .open(&file) + .unwrap() + .set_modified(SystemTime::now() + Duration::from_secs(5)) + .unwrap(); + assert_eq!(ask().await, 200); + + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2); + assert!( + seen[0].starts_with("AWS4-HMAC-SHA256 Credential=AKIAPROFILEONE/") + && seen[0].contains("/us-west-2/bedrock/aws4_request"), + "{}", + seen[0] + ); + assert!( + seen[1].starts_with("AWS4-HMAC-SHA256 Credential=AKIAPROFILETWO/"), + "the rewritten file was not read again: {}", + seen[1] + ); +} diff --git a/docs/config.md b/docs/config.md index cbab399b..19df823f 100644 --- a/docs/config.md +++ b/docs/config.md @@ -313,7 +313,7 @@ Upstreams: the APIs requests are forwarded to. | `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`. | -| `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. | +| `aws` | object, [`providers[].aws`](#cfg-providers-aws) | — | AWS access keys of a Bedrock upstream, written there or read from an AWS profile: 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`. | @@ -401,19 +401,24 @@ the token goes: | Field | Type | Default | Description | |---|---|---|---| -| `access_key_id` | string, `${VAR}` allowed | **required** | Access key ID. | -| `secret_access_key` | string, `${VAR}` allowed | **required** | Secret access key. | +| `access_key_id` | string, `${VAR}` allowed | — | Access key ID. Written together with `secret_access_key`; `profile` instead. | +| `secret_access_key` | string, `${VAR}` allowed | — | 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. | +| `profile` | string | — | Profile in the AWS credential files to read the access keys from, instead of writing them here: `~/.aws/credentials` and `~/.aws/config`, or the files `AWS_SHARED_CREDENTIALS_FILE` and `AWS_CONFIG_FILE` name, on the machine core runs on. The files are read again when they change. | | `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. +`key` and is sent as `Authorization: Bearer`. AWS access keys go in `aws`, +written there or read with `aws.profile` from a profile in the AWS credential +files: every request is signed with them (SigV4) once its body is final, and the +keys themselves are never sent. Keys written in the configuration can be read +from the environment with `${VAR}`. A profile is read from the files on the +machine core runs on, and read again when they change, so a tool that refreshes +temporary keys in `~/.aws/credentials` needs no restart. Nothing runs a command +to obtain a credential, so a profile that signs in through IAM Identity Center +(`aws sso login`), runs a `credential_process` or assumes a role cannot be used; +export the keys it produces instead. ```yaml providers: @@ -427,6 +432,11 @@ providers: access_key_id: ${AWS_ACCESS_KEY_ID} secret_access_key: ${AWS_SECRET_ACCESS_KEY} session_token: ${AWS_SESSION_TOKEN} + + - name: bedrock-profile + base_url: https://bedrock-runtime.us-west-2.amazonaws.com + aws: + profile: dev ``` Requests are converted to Converse. The model list comes from the region's diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 553b8e29..8ec901c4 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -237,7 +237,7 @@ clients: | `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` 二选一。 | -| `aws` | 对象,见 [`providers[].aws`](#cfg-providers-aws) | — | Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。与 `key`(Bedrock API Key)二选一。 | +| `aws` | 对象,见 [`providers[].aws`](#cfg-providers-aws) | — | Bedrock 上游的 AWS 访问密钥,写在这里或者从 AWS 的 profile 读:每个请求用它们签名(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` 中某一项的名字。 | @@ -310,13 +310,14 @@ access token 默认放进协议的鉴权请求头。要放在别处,在 `heade | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| -| `access_key_id` | 字符串,可写 `${VAR}` | **必填** | 访问密钥 ID。 | -| `secret_access_key` | 字符串,可写 `${VAR}` | **必填** | 私有访问密钥。 | +| `access_key_id` | 字符串,可写 `${VAR}` | — | 访问密钥 ID。与 `secret_access_key` 一起写;也可以改写 `profile`。 | +| `secret_access_key` | 字符串,可写 `${VAR}` | — | 私有访问密钥。 | | `session_token` | 字符串,可写 `${VAR}` | — | 临时凭证(如 STS 签发的)的会话令牌。过期之后请求会被拒绝,直到换上新的。 | +| `profile` | 字符串 | — | 从 AWS 凭证文件读访问密钥时用的 profile,代替把密钥写在这里:`~/.aws/credentials` 和 `~/.aws/config`,或 `AWS_SHARED_CREDENTIALS_FILE`、`AWS_CONFIG_FILE` 指定的文件,读的是 core 所在机器上的。文件变了会重新读。 | | `region` | 字符串 | — | 签名用的区域。不写:取 `base_url` 里的区域,这时 `base_url` 必须是标准的推理地址。`base_url` 是 VPC 端点或代理时必须写。 | -Bedrock 上游有两种认证方式。Bedrock API Key 写在 `key` 中,以 `Authorization: Bearer` 发送。AWS 访问密钥写在 `aws` 中:每个请求在请求体定稿之后用它们签名(SigV4),密钥本身不会发送。两者都可以用 `${VAR}` 从环境变量读取。获取凭证时不执行任何命令,因此需要 `aws sso login` 或 `credential_process` 的配置文件无法使用,请改为导出它们生成的密钥。 +Bedrock 上游有两种认证方式。Bedrock API Key 写在 `key` 中,以 `Authorization: Bearer` 发送。AWS 访问密钥写在 `aws` 中,或者用 `aws.profile` 从 AWS 凭证文件里的某个 profile 读取:每个请求在请求体定稿之后用它们签名(SigV4),密钥本身不会发送。写在配置中的密钥可以用 `${VAR}` 从环境变量读取。profile 读的是 core 所在机器上的文件,文件变了会重新读,因此把临时密钥刷新进 `~/.aws/credentials` 的工具不需要重启 core。获取凭证时不执行任何命令,因此经 IAM Identity Center 登录(`aws sso login`)、运行 `credential_process` 或扮演角色的 profile 无法使用,请改为导出它们生成的密钥。 ```yaml providers: @@ -330,6 +331,11 @@ providers: access_key_id: ${AWS_ACCESS_KEY_ID} secret_access_key: ${AWS_SECRET_ACCESS_KEY} session_token: ${AWS_SESSION_TOKEN} + + - name: bedrock-profile + base_url: https://bedrock-runtime.us-west-2.amazonaws.com + aws: + profile: dev ``` 请求转换为 Converse 格式。模型清单取自所在区域的控制面:可按需调用的基础模型、AWS 预设的推理配置(`us.anthropic.claude-…`),以及账号自己创建的应用推理配置(按调用时使用的 ARN 列出)。列出清单需要 `bedrock:ListFoundationModels` 和 `bedrock:ListInferenceProfiles` 权限;没有这两项权限时请求照常转发,可以在 `models` 中手动列出模型。使用 VPC 端点或代理时,在 `base_url` 中写它的地址,在 `aws.region` 中写区域;模型清单也向该地址获取。