From 6664da0f2aec9d7c458efacdc337a2829fe51957 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 29 Sep 2026 13:53:14 +0800 Subject: [PATCH] fix(gateway): report a Bedrock API key that is not valid as rejected Checking a Bedrock upstream took any AccessDeniedException from the model listing to mean the credential works but may not list models. AWS answers a Bedrock API key that is not valid with AccessDeniedException too ("Authentication failed: Please make sure your API Key is valid.", "Invalid API Key format: ..."), so a mistyped key passed the check and the background model fetch said the credential works. Only an AccessDeniedException whose message says the identity "is not authorized" (IAM's "User: arn:... is not authorized to perform: ...") now counts as missing list permission; any other one is a rejected key. AWS's message is only inspected, never passed on. Co-Authored-By: Claude Opus 5.5 --- crates/tw-bedrock/src/catalog.rs | 5 +- crates/tw-control/tests/bedrock.rs | 29 +++++++++++- crates/tw-gateway/src/probe.rs | 73 ++++++++++++++++++------------ 3 files changed, 75 insertions(+), 32 deletions(-) diff --git a/crates/tw-bedrock/src/catalog.rs b/crates/tw-bedrock/src/catalog.rs index 09e68b42..81f3faac 100644 --- a/crates/tw-bedrock/src/catalog.rs +++ b/crates/tw-bedrock/src/catalog.rs @@ -51,8 +51,9 @@ pub struct Auth<'a> { #[derive(Debug, Clone, PartialEq, Eq)] pub enum Failure { /// AWS 回答了,拒绝了。`kind` 是异常名,比如 `AccessDeniedException`、 - /// `UnrecognizedClientException` —— 凭证不对和凭证对但没有列模型的权限, - /// 靠它分开。`message` 是 AWS 的原话,**可能点名账号**,见 [`crate::error`] + /// `UnrecognizedClientException`;`message` 是 AWS 的原话,**可能点名账号**,见 + /// [`crate::error`]。凭证不对和凭证对但没有列模型的权限要两样一起看:Bedrock API Key + /// 不对时回的也是 `AccessDeniedException`,只有原话不同 Status { status: u16, kind: Option, diff --git a/crates/tw-control/tests/bedrock.rs b/crates/tw-control/tests/bedrock.rs index 6bb5bf31..21b36f92 100644 --- a/crates/tw-control/tests/bedrock.rs +++ b/crates/tw-control/tests/bedrock.rs @@ -284,7 +284,7 @@ async fn no_permission_to_list_is_not_a_rejected_key() { ( 403, Some("AccessDeniedException:http://internal.amazon.com/coral/com.amazon.bedrock/"), - json!({"message": "User: arn:aws:iam::123456789012:user/alice is not authorized"}), + json!({"message": "User: arn:aws:iam::123456789012:user/alice is not authorized to perform: bedrock:ListFoundationModels because no identity-based policy allows the bedrock:ListFoundationModels action"}), ) }) .await; @@ -307,3 +307,30 @@ async fn no_permission_to_list_is_not_a_rejected_key() { assert_eq!(v["ok"], false, "{v}"); assert_eq!(v["error"]["code"], "gw.probe.key_rejected", "{v}"); } + +/// Bedrock API Key 本身不对时,AWS 回的**也是** `AccessDeniedException`,只是原话不同(这两句 +/// 是拿格式不对、和格式对但不存在的 key 实际问出来的)。那是密钥被拒,不能说成「凭证能用、 +/// 只是列不了」—— 那样填错了 key,「检查连接」反倒说没问题 +#[tokio::test] +async fn a_bedrock_api_key_that_is_not_valid_is_rejected() { + for message in [ + "Authentication failed: Please make sure your API Key is valid.", + "Invalid API Key format: Must start with pre-defined prefix", + ] { + let up = control_plane(move |_| { + ( + 403, + Some("AccessDeniedException:http://internal.amazon.com/coral/com.amazon.coral.service/"), + json!({"Message": message}), + ) + }) + .await; + let b = bed(BASE); + let v = test_with(&b, up).await; + assert_eq!(v["ok"], false, "{message}: {v}"); + assert_eq!( + v["error"]["code"], "gw.probe.key_rejected", + "{message}: {v}" + ); + } +} diff --git a/crates/tw-gateway/src/probe.rs b/crates/tw-gateway/src/probe.rs index bb3782ce..271119f7 100644 --- a/crates/tw-gateway/src/probe.rs +++ b/crates/tw-gateway/src/probe.rs @@ -86,6 +86,11 @@ const BEDROCK_PROBE_TIMEOUT: Duration = Duration::from_secs(16); /// **403 不一定是凭证不对。**AWS 认出了身份、只是没给列模型的权限时回的是 /// `AccessDeniedException`:凭证能用,请求照样能发,只是这里列不出清单 —— 那要说成 /// 「列不了」,不能说成「密钥被拒」。AWS 的原话会点名账号和 IAM 身份,不往外说。 +/// +/// **反过来也一样:`AccessDeniedException` 不一定是凭证能用。**Bedrock API Key 本身不对时 +/// 回的也是它,原话是「Authentication failed: …」「Invalid API Key format: …」。所以还要看 +/// 原话:说「is not authorized」的(`User: arn:… is not authorized to perform: …`)才是认出了 +/// 身份([`identified`])。 pub async fn probe_bedrock( http: &reqwest::Client, provider: &tw_config::Provider, @@ -127,37 +132,39 @@ pub async fn probe_bedrock( ), 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." - ), + Ok(Err(Failure::Status { + status, + kind, + message, + })) if status == 401 || status == 403 => match kind.as_deref() { + Some("AccessDeniedException") if identified(&message) => 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." - ), + ), + _ => 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( @@ -171,6 +178,14 @@ pub async fn probe_bedrock( } } +/// AWS 拒绝的原话说的是「认出了你、但你没有这个权限」。 +/// +/// IAM 的拒绝一律是 `User: arn:… is not authorized to perform: <动作> …`;认证就没过的(API Key +/// 不对、格式不对)说的是别的。**只拿来判断,原话不往外说**:它点名账号和 IAM 身份 +fn identified(message: &str) -> bool { + message.contains("is not authorized") +} + /// 验一个上游能不能用。 /// /// 判据是**「这把 key 能过认证吗」**,不是「有没有模型列表」。这两件事