mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-03 01:38:46 +00:00
* build(rust): upgrade reqwest to 0.13 and move MCP out of litellm-http The workspace moves to reqwest 0.13, so litellm-http no longer carries a second reqwest just for rmcp. The mcp feature, its pool and its proxy conversion go away, and the gateway hands rmcp a pooled NoRedirect client that already carries the TLS, proxy and timeout settings The Client test helpers collapse into for_test, a no-redirect client without TLS or proxy settings, and wrap_for_test for the few tests that need a hand-built reqwest client Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(http): honor transport settings for Rust WebSockets The Responses WebSocket connected through tokio-tungstenite with its own native-roots TLS, so it ignored the configured CA bundle, verify flag, client certificate, proxies and timeouts. The handshake now goes through a pooled reqwest client (ClientVariant::WebSocket, HTTP/1.1, no redirects) and upgrades the response, so it shares the settings every other outbound request uses The upgrade response is checked for the Sec-WebSocket-Accept key, the Upgrade and Connection headers and a subprotocol that was offered Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(http): build outbound requests as reqwest::Request OutboundRequest was a hand-rolled copy of reqwest::Request. Routes now build a reqwest::Request directly and RequestSigner reads the body bytes back out of it, so the signer still covers exactly what is sent. SigV4 signing moves onto HeaderMap and takes the method, which drops the BTreeMap plumbing and the header casing table Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(http): make litellm_http::Error the one opaque error transport::Error and media::Error fold into litellm_http::Error, an Arc<Repr> newtype whose private variants keep the typed reqwest, io, rustls and tungstenite causes and own every message. Callers can no longer build an error with a message of their own. They ask through dispatched, is_request, status, upstream_response and tls_source One From<reqwest::Error> now classifies connect, network and timeout and strips the URL. The WebSocket handshake reports each failed check as its own variant and owns its connect timeout. OCR drops the media variants it mirrored, and inference::Error maps a header the signer computes to Unsupported for every route, not only chat The error rules move out of AGENTS.md into the rust-error skill, which also records the decisions behind this design Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(rust): split rust-error skill into thin SKILL.md with references Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): render causes once and ask predicates at the boundaries The four WebSocket handshake variants collapse into Handshake(HandshakeFault), and media download failures no longer answer dispatched() since they happen before the provider call ErrorDetail in llms and auth-types, the inference error and the OCR error now store their cause in a field named cause with no #[source], so to_string() carries it exactly once and source() is None. Tests that walked the chain now destructure the variant and downcast the cause The gateway asks is_unsupported() and is_missing_credential() on the inference and OCR errors instead of matching through nested enums, and litellm_auth::Error answers is_missing_credential() for both The rust-error skill gains axum and pyo3 references, boundaries.md describes the real predicate order and the known divergences, the testing example asserts dispatched() correctly, and shape, classification, conversions, messages-and-causes and recipes agree with the code again * docs(rust): focus the rust-error gateway page on the error flow and add a rust-gateway skill The former axum page toured gateway-inference: its status match, the envelope table, an extractor, the unsupported route and the Sse closure. Those details belong to the gateway crates and go stale with them. The page is now gateway.md and follows an error from the provider failure through each From into IntoResponse, where it is classified once and rendered by surface and framing. The gateway-structure material moves to a new rust-gateway skill: envelopes per API surface, extractors and path registration, SSE relay, and the router test harness. * test(inference): pin provider URL redaction on every route's transport error Chat, Messages, Responses and transcription each get a route-level test that fails if a reqwest error reaches the caller with its URL. The Messages stream decoder also takes body errors through litellm_http::Error like every other reqwest error Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(rust-error): adopt std source chains and add litellm-error Report Messages describe their own layer and the cause is the source, boundaries render the chain once with litellm_error::Report. Corrects skill claims the audit found stale against the code. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): keep causes as sources across http, auth, secrets, cache and utility crates Messages describe their own layer and every cause is a typed source, predicates match exhaustively, and boundaries render with litellm_error::Report. Media downloads no longer count as dispatched, Error::upstream bounds the provider body itself, and a forwarded header SigV4 cannot sign is the caller's fault. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): keep causes as sources in llms and the gateway crates ErrorDetail loses its string variant, OCR provider variants become data, host faults stop counting as the caller's, a tunnelled transport error classifies the same on every stream path, and each gateway crate has one Error with one status() and extractors that reject in its envelope. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): nest llms errors in inference and ask predicates in route tests litellm_inference::Error nests litellm_llms::Error instead of mirroring its variants, host driver faults get their own variant, every predicate matches exhaustively, and route tests ask predicates instead of matching transport variants. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): map bridge and gateway-inference errors once and render them with Report RustUpstreamError has one constructor that always sets headers, argument checks raise typed errors mapped once, OCR asks upstream_response(), the Responses stream error event comes from the error type, gateway-inference loses its string variants, and auth faults classify through one litellm_auth predicate on every route. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(rust-error): carry OCR provider headers as a HeaderMap and keep outages off the caller The OCR provider error and get_error_class take reqwest's HeaderMap, the bridge turns it into Python's (name, value) pairs once. Credential acquisition and provider SDK failures are no longer the caller's fault, the UI hides auth and backend causes, and chat keeps a provider answer as is. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(rust-error): correct skill claims against the aligned code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): fix the remaining sweep findings in gateway, llms, auth and cache crates Auth rejections hide their backend cause on every inference renderer, path parameters reject in the surface envelope, Textract's unsupported document and Azure DI's unparseable poll URL get typed variants, the credential chain exposes its last failure as the source, gateway-mcp asks predicates over rmcp errors, and the S3 and Azure blob transports classify through litellm_http::Error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(rust-error): fix the remaining sweep findings on the Python side host-python keeps a native error's chain and returns blocking-pool cancellation instead of panicking, Vault transport failures convert through litellm_http::Error so no URL reaches Python, the bridge asks predicates instead of matching three levels into Vault errors, and the last string-built PyErrs become typed errors mapped once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * build(deps): refresh compatible dependencies flagged by OSV * refactor(rust): remove redundant client construction comment * test(rust): cover configured MCP proxy and CA bundle * fix(http): preserve native WebSocket trust and optional protocols * fix(http): allow plain WebSockets without native roots * fix(http): normalize provider URLs before building outbound requests * fix(rust): preserve OCR download status and reduce error size * fix(rust): preserve upstream bodies and bound diagnostics only * test(rust): preserve bridge serialization boundary in body regression --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1194 lines
42 KiB
Rust
1194 lines
42 KiB
Rust
use std::time::Duration;
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
use moka::sync::Cache;
|
|
use sha2::{Digest, Sha256};
|
|
|
|
use aws_credential_types::Credentials;
|
|
use aws_credential_types::provider::ProvideCredentials;
|
|
use aws_sigv4::http_request::{
|
|
SignableBody, SignableRequest, SigningParams, SigningSettings, sign,
|
|
};
|
|
use aws_sigv4::sign::v4;
|
|
use aws_smithy_runtime_api::client::identity::Identity;
|
|
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
|
|
|
use litellm_auth_types::AwsParams;
|
|
|
|
use super::constants::{
|
|
AWS_ACCESS_KEY_ID, AWS_EXTERNAL_ID, AWS_PROFILE_NAME, AWS_REGION_NAME, AWS_ROLE_ARN,
|
|
AWS_ROLE_NAME, AWS_SECRET_ACCESS_KEY, AWS_SESSION_NAME, AWS_SESSION_TOKEN,
|
|
AWS_SIGNED_HEADER_NAMES, AWS_STS_ENDPOINT, AWS_WEB_IDENTITY_TOKEN, AWS_WEB_IDENTITY_TOKEN_FILE,
|
|
DEFAULT_BEDROCK_REGION, DEFAULT_SESSION_NAME_PREFIX, SIGV4_COMPUTED_HEADER_NAMES,
|
|
};
|
|
use crate::error::{CredentialFlow, Error, SigningStage};
|
|
|
|
const STATIC_CREDENTIALS_TTL: Duration = Duration::from_secs(3600 - 60);
|
|
const AMBIENT_CREDENTIALS_TTL: Duration = Duration::from_secs(600);
|
|
|
|
#[derive(Clone)]
|
|
pub struct AwsAuthService {
|
|
static_credentials: Cache<String, Credentials>,
|
|
ambient_credentials: Cache<String, Credentials>,
|
|
}
|
|
|
|
impl Default for AwsAuthService {
|
|
fn default() -> Self {
|
|
Self {
|
|
static_credentials: Cache::builder()
|
|
.max_capacity(200)
|
|
.time_to_live(STATIC_CREDENTIALS_TTL)
|
|
.build(),
|
|
ambient_credentials: Cache::builder()
|
|
.max_capacity(200)
|
|
.time_to_live(AMBIENT_CREDENTIALS_TTL)
|
|
.build(),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn credential_cache_ttl(flow: &AwsAuthFlow) -> Option<Duration> {
|
|
match flow {
|
|
AwsAuthFlow::StaticKeys { .. } => Some(STATIC_CREDENTIALS_TTL),
|
|
AwsAuthFlow::DefaultChain => Some(AMBIENT_CREDENTIALS_TTL),
|
|
AwsAuthFlow::WebIdentity { .. }
|
|
| AwsAuthFlow::AssumeRole { .. }
|
|
| AwsAuthFlow::Profile { .. }
|
|
| AwsAuthFlow::SessionToken { .. } => None,
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
pub struct AwsAuthConfig {
|
|
pub access_key_id: Option<String>,
|
|
pub secret_access_key: Option<String>,
|
|
pub session_token: Option<String>,
|
|
pub region_name: Option<String>,
|
|
pub session_name: Option<String>,
|
|
pub profile_name: Option<String>,
|
|
pub role_name: Option<String>,
|
|
pub web_identity_token: Option<String>,
|
|
pub sts_endpoint: Option<String>,
|
|
pub external_id: Option<String>,
|
|
}
|
|
|
|
impl AwsAuthConfig {
|
|
fn with_environment(self, env_lookup: &(dyn Fn(&str) -> Option<String> + Sync)) -> Self {
|
|
Self {
|
|
access_key_id: self.access_key_id.or_else(|| env_lookup(AWS_ACCESS_KEY_ID)),
|
|
secret_access_key: self
|
|
.secret_access_key
|
|
.or_else(|| env_lookup(AWS_SECRET_ACCESS_KEY)),
|
|
session_token: self.session_token.or_else(|| env_lookup(AWS_SESSION_TOKEN)),
|
|
region_name: self.region_name.or_else(|| env_lookup(AWS_REGION_NAME)),
|
|
session_name: self.session_name.or_else(|| env_lookup(AWS_SESSION_NAME)),
|
|
profile_name: self.profile_name.or_else(|| env_lookup(AWS_PROFILE_NAME)),
|
|
role_name: self.role_name.or_else(|| env_lookup(AWS_ROLE_NAME)),
|
|
web_identity_token: self
|
|
.web_identity_token
|
|
.or_else(|| env_lookup(AWS_WEB_IDENTITY_TOKEN)),
|
|
sts_endpoint: self.sts_endpoint.or_else(|| env_lookup(AWS_STS_ENDPOINT)),
|
|
external_id: self.external_id.or_else(|| env_lookup(AWS_EXTERNAL_ID)),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
pub enum AwsAuthFlow {
|
|
WebIdentity {
|
|
token: String,
|
|
role: String,
|
|
session_name: String,
|
|
},
|
|
AssumeRole {
|
|
role: String,
|
|
session_name: Option<String>,
|
|
},
|
|
Profile {
|
|
name: String,
|
|
},
|
|
SessionToken {
|
|
access_key_id: String,
|
|
secret_access_key: String,
|
|
session_token: String,
|
|
},
|
|
StaticKeys {
|
|
access_key_id: String,
|
|
secret_access_key: String,
|
|
region_name: String,
|
|
},
|
|
DefaultChain,
|
|
}
|
|
|
|
fn cache_key(config: &AwsAuthConfig, flow: &AwsAuthFlow) -> String {
|
|
let mut hasher = Sha256::new();
|
|
hasher.update(format!("{config:?}:{flow:?}"));
|
|
format!("{:x}", hasher.finalize())
|
|
}
|
|
|
|
impl AwsAuthService {
|
|
fn get_cached_credentials(&self, key: &str) -> Option<Credentials> {
|
|
self.static_credentials
|
|
.get(key)
|
|
.or_else(|| self.ambient_credentials.get(key))
|
|
}
|
|
|
|
fn set_cached_credentials(&self, key: String, credentials: Credentials, ttl: Duration) {
|
|
if ttl == STATIC_CREDENTIALS_TTL {
|
|
self.static_credentials.insert(key, credentials);
|
|
} else {
|
|
self.ambient_credentials.insert(key, credentials);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn role_identity(arn: &str) -> Option<(&str, &str, &str)> {
|
|
let mut parts = arn.splitn(6, ':');
|
|
let ("arn", partition, _, _, account, resource) = (
|
|
parts.next()?,
|
|
parts.next()?,
|
|
parts.next()?,
|
|
parts.next()?,
|
|
parts.next()?,
|
|
parts.next()?,
|
|
) else {
|
|
return None;
|
|
};
|
|
let role = if let Some(role) = resource.strip_prefix("role/") {
|
|
role.rsplit('/').next()?
|
|
} else {
|
|
resource.strip_prefix("assumed-role/")?.split('/').next()?
|
|
};
|
|
Some((partition, account, role))
|
|
}
|
|
|
|
fn same_role_arns(target: &str, caller: &str) -> bool {
|
|
role_identity(target) == role_identity(caller)
|
|
}
|
|
|
|
pub fn classify_auth(
|
|
config: AwsAuthConfig,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> AwsAuthFlow {
|
|
let config = config.with_environment(env_lookup);
|
|
if let (Some(token), Some(role), Some(session_name)) = (
|
|
config.web_identity_token.clone(),
|
|
config.role_name.clone(),
|
|
config.session_name.clone(),
|
|
) {
|
|
return AwsAuthFlow::WebIdentity {
|
|
token,
|
|
role,
|
|
session_name,
|
|
};
|
|
}
|
|
if let Some(role) = config.role_name.clone() {
|
|
return AwsAuthFlow::AssumeRole {
|
|
role,
|
|
session_name: config.session_name.clone(),
|
|
};
|
|
}
|
|
if let Some(name) = config.profile_name {
|
|
return AwsAuthFlow::Profile { name };
|
|
}
|
|
if let (Some(access_key_id), Some(secret_access_key), Some(session_token)) = (
|
|
config.access_key_id.clone(),
|
|
config.secret_access_key.clone(),
|
|
config.session_token,
|
|
) {
|
|
return AwsAuthFlow::SessionToken {
|
|
access_key_id,
|
|
secret_access_key,
|
|
session_token,
|
|
};
|
|
}
|
|
if let (Some(access_key_id), Some(secret_access_key), Some(region_name)) = (
|
|
config.access_key_id,
|
|
config.secret_access_key,
|
|
config.region_name,
|
|
) {
|
|
return AwsAuthFlow::StaticKeys {
|
|
access_key_id,
|
|
secret_access_key,
|
|
region_name,
|
|
};
|
|
}
|
|
AwsAuthFlow::DefaultChain
|
|
}
|
|
|
|
impl AwsAuthService {
|
|
pub async fn resolve_credentials(
|
|
&self,
|
|
config: AwsAuthConfig,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> Result<Credentials, Error> {
|
|
let resolved = config.clone().with_environment(env_lookup);
|
|
let flow = classify_auth(config, env_lookup);
|
|
match flow {
|
|
AwsAuthFlow::SessionToken {
|
|
access_key_id,
|
|
secret_access_key,
|
|
session_token,
|
|
} => Ok(Credentials::new(
|
|
access_key_id,
|
|
secret_access_key,
|
|
Some(session_token),
|
|
None,
|
|
"litellm-static-session",
|
|
)),
|
|
AwsAuthFlow::StaticKeys {
|
|
access_key_id,
|
|
secret_access_key,
|
|
region_name,
|
|
} => {
|
|
let flow = AwsAuthFlow::StaticKeys {
|
|
access_key_id: access_key_id.clone(),
|
|
secret_access_key: secret_access_key.clone(),
|
|
region_name,
|
|
};
|
|
let key = cache_key(&resolved, &flow);
|
|
if let Some(credentials) = self.get_cached_credentials(&key) {
|
|
return Ok(credentials);
|
|
}
|
|
let credentials = Credentials::new(
|
|
access_key_id,
|
|
secret_access_key,
|
|
None,
|
|
None,
|
|
"litellm-static",
|
|
);
|
|
self.set_cached_credentials(
|
|
key,
|
|
credentials.clone(),
|
|
credential_cache_ttl(&flow).unwrap_or(STATIC_CREDENTIALS_TTL),
|
|
);
|
|
Ok(credentials)
|
|
}
|
|
AwsAuthFlow::Profile { name } => {
|
|
let provider = aws_config::profile::ProfileFileCredentialsProvider::builder()
|
|
.profile_name(name)
|
|
.build();
|
|
provider
|
|
.provide_credentials()
|
|
.await
|
|
.map_err(Error::credentials(CredentialFlow::Profile))
|
|
}
|
|
AwsAuthFlow::AssumeRole { role, session_name } => {
|
|
if is_already_running_as_role(&role, &resolved).await? {
|
|
let ambient_flow = AwsAuthFlow::DefaultChain;
|
|
let key = cache_key(&resolved, &ambient_flow);
|
|
if let Some(credentials) = self.get_cached_credentials(&key) {
|
|
return Ok(credentials);
|
|
}
|
|
let provider =
|
|
aws_config::default_provider::credentials::DefaultCredentialsChain::builder()
|
|
.build()
|
|
.await;
|
|
let credentials = provider
|
|
.provide_credentials()
|
|
.await
|
|
.map_err(Error::credentials(CredentialFlow::DefaultChain))?;
|
|
self.set_cached_credentials(
|
|
key,
|
|
credentials.clone(),
|
|
credential_cache_ttl(&ambient_flow).unwrap_or(AMBIENT_CREDENTIALS_TTL),
|
|
);
|
|
return Ok(credentials);
|
|
}
|
|
let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
|
|
if let Some(region) = resolved.region_name.clone() {
|
|
loader = loader.region(aws_types::region::Region::new(region));
|
|
}
|
|
if let Some(endpoint) = resolved.sts_endpoint.clone() {
|
|
loader = loader.endpoint_url(endpoint);
|
|
}
|
|
if let (Some(access_key_id), Some(secret_access_key)) =
|
|
(resolved.access_key_id, resolved.secret_access_key)
|
|
{
|
|
loader = loader.credentials_provider(Credentials::new(
|
|
access_key_id,
|
|
secret_access_key,
|
|
resolved.session_token,
|
|
None,
|
|
"litellm-role-source",
|
|
));
|
|
}
|
|
let sdk_config = loader.load().await;
|
|
let builder = aws_config::sts::AssumeRoleProvider::builder(role);
|
|
let builder = match session_name {
|
|
Some(name) => builder.session_name(name),
|
|
None => builder.session_name(default_session_name()),
|
|
};
|
|
let builder = match resolved.external_id {
|
|
Some(id) => builder.external_id(id),
|
|
None => builder,
|
|
};
|
|
let provider = builder.configure(&sdk_config).build().await;
|
|
provider
|
|
.provide_credentials()
|
|
.await
|
|
.map_err(Error::credentials(CredentialFlow::AssumeRole))
|
|
}
|
|
AwsAuthFlow::WebIdentity {
|
|
token,
|
|
role,
|
|
session_name,
|
|
} => {
|
|
let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
|
|
if let Some(region) = resolved.region_name {
|
|
loader = loader.region(aws_types::region::Region::new(region));
|
|
}
|
|
if let Some(endpoint) = resolved.sts_endpoint {
|
|
loader = loader.endpoint_url(endpoint);
|
|
}
|
|
let sdk_config = loader.load().await;
|
|
let client = aws_sdk_sts::Client::new(&sdk_config);
|
|
let response = client
|
|
.assume_role_with_web_identity()
|
|
.role_arn(role)
|
|
.role_session_name(session_name)
|
|
.web_identity_token(token)
|
|
.send()
|
|
.await
|
|
.map_err(Error::credentials(CredentialFlow::WebIdentity))?;
|
|
let credentials = response
|
|
.credentials()
|
|
.ok_or(Error::MissingWebIdentityCredentials)?;
|
|
let expiration =
|
|
SystemTime::try_from(*credentials.expiration()).map_err(|source| {
|
|
Error::WebIdentityExpiration(litellm_error::Source::new(source))
|
|
})?;
|
|
Ok(Credentials::new(
|
|
credentials.access_key_id(),
|
|
credentials.secret_access_key(),
|
|
Some(credentials.session_token().to_string()),
|
|
Some(expiration),
|
|
"litellm-web-identity",
|
|
))
|
|
}
|
|
AwsAuthFlow::DefaultChain => {
|
|
let key = cache_key(&resolved, &AwsAuthFlow::DefaultChain);
|
|
if let Some(credentials) = self.get_cached_credentials(&key) {
|
|
return Ok(credentials);
|
|
}
|
|
let provider =
|
|
aws_config::default_provider::credentials::DefaultCredentialsChain::builder()
|
|
.build()
|
|
.await;
|
|
let credentials = provider
|
|
.provide_credentials()
|
|
.await
|
|
.map_err(Error::credentials(CredentialFlow::DefaultChain))?;
|
|
self.set_cached_credentials(
|
|
key,
|
|
credentials.clone(),
|
|
credential_cache_ttl(&AwsAuthFlow::DefaultChain)
|
|
.unwrap_or(AMBIENT_CREDENTIALS_TTL),
|
|
);
|
|
Ok(credentials)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn is_already_running_as_role(role: &str, config: &AwsAuthConfig) -> Result<bool, Error> {
|
|
if role_identity(role).is_none() {
|
|
return Ok(false);
|
|
}
|
|
if let (Ok(current_role), Ok(token_file)) = (
|
|
std::env::var(AWS_ROLE_ARN),
|
|
std::env::var(AWS_WEB_IDENTITY_TOKEN_FILE),
|
|
) && !token_file.is_empty()
|
|
{
|
|
return Ok(same_role_arns(role, ¤t_role));
|
|
}
|
|
|
|
let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
|
|
if let Some(region) = config.region_name.clone() {
|
|
loader = loader.region(aws_types::region::Region::new(region));
|
|
}
|
|
if let Some(endpoint) = config.sts_endpoint.clone() {
|
|
loader = loader.endpoint_url(endpoint);
|
|
}
|
|
let sdk_config = loader.load().await;
|
|
let response = match aws_sdk_sts::Client::new(&sdk_config)
|
|
.get_caller_identity()
|
|
.send()
|
|
.await
|
|
{
|
|
Ok(response) => response,
|
|
Err(_) => return Ok(false),
|
|
};
|
|
Ok(response
|
|
.arn()
|
|
.is_some_and(|caller| same_role_arns(role, caller)))
|
|
}
|
|
|
|
fn default_session_name() -> String {
|
|
let seconds = SystemTime::now()
|
|
.duration_since(UNIX_EPOCH)
|
|
.map_or(0, |duration| duration.as_secs());
|
|
format!("{DEFAULT_SESSION_NAME_PREFIX}-{seconds}")
|
|
}
|
|
|
|
/// The subset of `headers` SigV4 should cover.
|
|
///
|
|
/// Python signs only these and reattaches the rest afterwards, so a forwarded
|
|
/// client header cannot change the canonical request and invalidate the
|
|
/// signature. Signing everything instead makes the request 403 on a header the
|
|
/// caller supplied, on a deployment that works on the Python path.
|
|
pub fn aws_signature_headers(headers: &HeaderMap) -> HeaderMap {
|
|
headers
|
|
.iter()
|
|
.filter(|(name, _)| {
|
|
let name = name.as_str();
|
|
AWS_SIGNED_HEADER_NAMES.contains(&name)
|
|
|| name.starts_with("x-amz-")
|
|
|| name.starts_with("x-amzn-")
|
|
})
|
|
.map(|(name, value)| (name.clone(), value.clone()))
|
|
.collect()
|
|
}
|
|
|
|
/// Whether the signer produces `name` itself.
|
|
///
|
|
/// Python's reattach loop skips these, so a caller-supplied copy never reaches
|
|
/// the wire next to the computed one.
|
|
pub fn is_sigv4_computed_header(name: &str) -> bool {
|
|
SIGV4_COMPUTED_HEADER_NAMES.contains(&name.to_ascii_lowercase().as_str())
|
|
}
|
|
|
|
#[derive(Clone, Copy, Debug)]
|
|
pub struct SigningScope<'a> {
|
|
pub region: &'a str,
|
|
pub service: &'a str,
|
|
pub credentials: &'a Credentials,
|
|
pub time: SystemTime,
|
|
}
|
|
|
|
pub fn sign_headers(
|
|
method: &str,
|
|
url: &str,
|
|
body: &[u8],
|
|
headers: &HeaderMap,
|
|
scope: SigningScope<'_>,
|
|
) -> Result<HeaderMap, Error> {
|
|
let identity: Identity = scope.credentials.clone().into();
|
|
let params = v4::SigningParams::builder()
|
|
.identity(&identity)
|
|
.region(scope.region)
|
|
.name(scope.service)
|
|
.time(scope.time)
|
|
.settings(SigningSettings::default())
|
|
.build()
|
|
.map(SigningParams::from)
|
|
.map_err(Error::signing(SigningStage::Parameters))?;
|
|
let header_refs = headers
|
|
.iter()
|
|
.map(|(name, value)| {
|
|
value
|
|
.to_str()
|
|
.map(|value| (name.as_str(), value))
|
|
.map_err(|_| Error::NonAsciiHeader {
|
|
name: name.to_string(),
|
|
})
|
|
})
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
let request = SignableRequest::new(
|
|
method,
|
|
url,
|
|
header_refs.into_iter(),
|
|
SignableBody::Bytes(body),
|
|
)
|
|
.map_err(Error::signing(SigningStage::Request))?;
|
|
let (instructions, _) = sign(request, ¶ms)
|
|
.map_err(Error::signing(SigningStage::Signature))?
|
|
.into_parts();
|
|
instructions
|
|
.headers()
|
|
.map(|(name, value)| {
|
|
let name = HeaderName::from_bytes(name.as_bytes())
|
|
.map_err(Error::signing(SigningStage::Output))?;
|
|
let value =
|
|
HeaderValue::from_str(value).map_err(Error::signing(SigningStage::Output))?;
|
|
Ok((name, value))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Model-id and region parsing shared by every Bedrock route.
|
|
pub fn bedrock_model_id_and_region(model: &str) -> (String, Option<String>) {
|
|
let mut stripped = model;
|
|
for prefix in ["bedrock/converse/", "bedrock/", "converse/"] {
|
|
if let Some(value) = stripped.strip_prefix(prefix) {
|
|
stripped = value;
|
|
break;
|
|
}
|
|
}
|
|
let mut region = None;
|
|
if let Some((candidate, remainder)) = stripped.split_once('/')
|
|
&& is_bedrock_region(candidate)
|
|
{
|
|
region = Some(candidate.to_string());
|
|
stripped = remainder;
|
|
}
|
|
for prefix in ["nova-2/", "nova/"] {
|
|
if let Some(value) = stripped.strip_prefix(prefix) {
|
|
stripped = value;
|
|
break;
|
|
}
|
|
}
|
|
if region.is_none() {
|
|
// Python splits the whole ARN and takes field 3, the region. Stripping
|
|
// `arn:` first shifts every field down one, so the region is field 2
|
|
// here; field 3 is the account id.
|
|
region = stripped
|
|
.strip_prefix("arn:")
|
|
.and_then(|value| value.split(':').nth(2))
|
|
.filter(|value| !value.is_empty())
|
|
.map(str::to_string);
|
|
}
|
|
(stripped.to_string(), region)
|
|
}
|
|
|
|
fn is_bedrock_region(value: &str) -> bool {
|
|
value.len() > 3
|
|
&& value.contains('-')
|
|
&& value
|
|
.chars()
|
|
.all(|char| char.is_ascii_alphanumeric() || char == '-')
|
|
}
|
|
|
|
/// The region a caller configured: `aws_region_name`, then the model's own
|
|
/// region, then the environment. Each service decides what a missing one means.
|
|
pub fn resolve_aws_region(
|
|
model_region: Option<&str>,
|
|
params: &AwsParams,
|
|
env_lookup: &dyn Fn(&str) -> Option<String>,
|
|
) -> Option<String> {
|
|
params
|
|
.resolve(&AwsParams::REGION, &|_| None)
|
|
.or_else(|| model_region.map(str::to_string))
|
|
.or_else(|| AwsParams::REGION.resolve(&|_| None, env_lookup))
|
|
}
|
|
|
|
pub fn resolve_bedrock_region(
|
|
model_region: Option<&str>,
|
|
params: &AwsParams,
|
|
env_lookup: &dyn Fn(&str) -> Option<String>,
|
|
) -> String {
|
|
resolve_aws_region(model_region, params, env_lookup)
|
|
.unwrap_or_else(|| DEFAULT_BEDROCK_REGION.to_string())
|
|
}
|
|
|
|
pub fn aws_auth_config(
|
|
params: &AwsParams,
|
|
env_lookup: &dyn Fn(&str) -> Option<String>,
|
|
) -> AwsAuthConfig {
|
|
AwsAuthConfig {
|
|
access_key_id: params.resolve(&AwsParams::ACCESS_KEY_ID, env_lookup),
|
|
secret_access_key: params.resolve(&AwsParams::SECRET_ACCESS_KEY, env_lookup),
|
|
session_token: params.resolve(&AwsParams::SESSION_TOKEN, env_lookup),
|
|
region_name: params.resolve(&AwsParams::REGION, env_lookup),
|
|
session_name: params.resolve(&AwsParams::SESSION_NAME, env_lookup),
|
|
profile_name: params.resolve(&AwsParams::PROFILE_NAME, env_lookup),
|
|
role_name: params.resolve(&AwsParams::ROLE_NAME, env_lookup),
|
|
web_identity_token: params.resolve(&AwsParams::WEB_IDENTITY_TOKEN, env_lookup),
|
|
sts_endpoint: params.resolve(&AwsParams::STS_ENDPOINT, env_lookup),
|
|
external_id: params.resolve(&AwsParams::EXTERNAL_ID, env_lookup),
|
|
}
|
|
}
|
|
|
|
/// Where the credentials that sign a request come from, decided when the request is
|
|
/// prepared and resolved when it is sent.
|
|
#[derive(Clone, Debug, PartialEq)]
|
|
pub enum AwsCredentialSource {
|
|
HostSupplied(Credentials),
|
|
Chain(AwsAuthConfig),
|
|
}
|
|
|
|
impl AwsCredentialSource {
|
|
pub fn from_params(params: &AwsParams, env_lookup: &dyn Fn(&str) -> Option<String>) -> Self {
|
|
match host_supplied_credentials(params) {
|
|
Some(credentials) => Self::HostSupplied(credentials),
|
|
None => Self::Chain(aws_auth_config(params, env_lookup)),
|
|
}
|
|
}
|
|
|
|
pub async fn resolve(
|
|
self,
|
|
auth: &AwsAuthService,
|
|
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
|
|
) -> Result<Credentials, Error> {
|
|
match self {
|
|
Self::HostSupplied(credentials) => Ok(credentials),
|
|
Self::Chain(config) => auth.resolve_credentials(config, env_lookup).await,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Credentials a host resolved through its own chain and handed down verbatim.
|
|
///
|
|
/// A host with its own resolution (LiteLLM's Python `BaseAWSLLM`, which reads
|
|
/// profiles, STS and boto sessions) passes the result here so the core signs
|
|
/// with exactly those. Without this the core would re-derive from ambient
|
|
/// state, where an unrelated `AWS_ROLE_NAME` or `AWS_PROFILE_NAME` in the
|
|
/// environment outranks explicit keys in [`classify_auth`] and the two sides
|
|
/// would sign as different principals.
|
|
pub fn host_supplied_credentials(params: &AwsParams) -> Option<Credentials> {
|
|
let value = |value: &Option<String>| {
|
|
value
|
|
.as_deref()
|
|
.map(str::trim)
|
|
.filter(|value| !value.is_empty())
|
|
.map(str::to_string)
|
|
};
|
|
let access_key_id = value(¶ms.aws_access_key_id)?;
|
|
let secret_access_key = value(¶ms.aws_secret_access_key)?;
|
|
Some(Credentials::new(
|
|
access_key_id,
|
|
secret_access_key,
|
|
value(¶ms.aws_session_token),
|
|
None,
|
|
"litellm-host-supplied",
|
|
))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::constants::{AWS_REGION, BEDROCK_SERVICE};
|
|
use reqwest::header::CONTENT_TYPE;
|
|
|
|
fn no_env(_: &str) -> Option<String> {
|
|
None
|
|
}
|
|
|
|
#[test]
|
|
fn secret_names_cover_environment_reads() {
|
|
let seen = std::sync::Arc::new(std::sync::Mutex::new(
|
|
std::collections::BTreeSet::<String>::new(),
|
|
));
|
|
let recorded = seen.clone();
|
|
let env = |name: &str| {
|
|
recorded.lock().unwrap().insert(name.to_string());
|
|
None
|
|
};
|
|
resolve_aws_region(None, &AwsParams::default(), &env);
|
|
aws_auth_config(&AwsParams::default(), &env);
|
|
assert!(
|
|
seen.lock()
|
|
.unwrap()
|
|
.iter()
|
|
.all(|name| AwsParams::secret_names().contains(&name.as_str()))
|
|
);
|
|
}
|
|
|
|
#[rstest::rstest]
|
|
#[case::param_wins(Some("from-params"), &[(AWS_SECRET_ACCESS_KEY, "from-env")], Some("from-params"))]
|
|
#[case::blank_param_falls_to_environment(Some(" "), &[(AWS_SECRET_ACCESS_KEY, "from-env")], Some("from-env"))]
|
|
#[case::absent_param_falls_to_environment(None, &[(AWS_SECRET_ACCESS_KEY, "from-env")], Some("from-env"))]
|
|
#[case::nothing(None, &[], None)]
|
|
fn auth_config_reads_each_spec_from_params_then_the_environment(
|
|
#[case] aws_secret_access_key: Option<&str>,
|
|
#[case] environment: &[(&str, &str)],
|
|
#[case] expected: Option<&str>,
|
|
) {
|
|
let params = AwsParams {
|
|
aws_secret_access_key: aws_secret_access_key.map(str::to_string),
|
|
..AwsParams::default()
|
|
};
|
|
let env = |key: &str| {
|
|
environment
|
|
.iter()
|
|
.find(|(name, _)| *name == key)
|
|
.map(|(_, value)| value.to_string())
|
|
};
|
|
|
|
assert_eq!(
|
|
aws_auth_config(¶ms, &env).secret_access_key.as_deref(),
|
|
expected
|
|
);
|
|
assert_eq!(
|
|
aws_auth_config(&AwsParams::default(), &|key: &str| (key == AWS_REGION)
|
|
.then(|| "sa-east-1".to_string()))
|
|
.region_name
|
|
.as_deref(),
|
|
Some("sa-east-1")
|
|
);
|
|
}
|
|
|
|
#[rstest::rstest]
|
|
#[case::call_params(Some("us-east-2"), Some("eu-west-1"), &[(AWS_REGION_NAME, "ap-south-1")], Some("eu-west-1"))]
|
|
#[case::model_region(Some("us-east-2"), None, &[(AWS_REGION_NAME, "ap-south-1")], Some("us-east-2"))]
|
|
#[case::aws_region_name(None, None, &[(AWS_REGION_NAME, "ap-south-1")], Some("ap-south-1"))]
|
|
#[case::aws_region(None, None, &[(AWS_REGION, "sa-east-1")], Some("sa-east-1"))]
|
|
#[case::nothing(None, None, &[], None)]
|
|
fn a_region_comes_from_the_call_then_the_model_then_the_environment(
|
|
#[case] model_region: Option<&str>,
|
|
#[case] aws_region_name: Option<&str>,
|
|
#[case] environment: &[(&str, &str)],
|
|
#[case] expected: Option<&str>,
|
|
) {
|
|
let params = AwsParams {
|
|
aws_region_name: aws_region_name.map(str::to_string),
|
|
..AwsParams::default()
|
|
};
|
|
let env = |key: &str| {
|
|
environment
|
|
.iter()
|
|
.find(|(name, _)| *name == key)
|
|
.map(|(_, value)| value.to_string())
|
|
};
|
|
|
|
assert_eq!(
|
|
resolve_aws_region(model_region, ¶ms, &env).as_deref(),
|
|
expected
|
|
);
|
|
assert_eq!(
|
|
resolve_bedrock_region(model_region, ¶ms, &env),
|
|
expected.unwrap_or(DEFAULT_BEDROCK_REGION)
|
|
);
|
|
}
|
|
|
|
fn parity_inputs() -> (String, Vec<u8>, HeaderMap) {
|
|
(
|
|
"https://bedrock-runtime.us-east-1.amazonaws.com/model/amazon.titan-text-express-v1/invoke"
|
|
.to_string(),
|
|
br#"{"input":"hello"}"#.to_vec(),
|
|
HeaderMap::from_iter([(CONTENT_TYPE, HeaderValue::from_static("application/json"))]),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn reads_the_region_field_of_a_model_arn_not_the_account_id() {
|
|
// Python's `_get_aws_region_from_model_arn` splits the whole ARN and
|
|
// takes field 3. Stripping `arn:` first shifts every field down one, so
|
|
// the region is field 2 here. Taking field 3 after the strip returns
|
|
// the account id, which is not a region at all.
|
|
let (_, region) = bedrock_model_id_and_region(
|
|
"bedrock/arn:aws:bedrock:us-west-2:123456789012:foundation-model/anthropic.claude-v2",
|
|
);
|
|
assert_eq!(region.as_deref(), Some("us-west-2"));
|
|
}
|
|
|
|
#[test]
|
|
fn classification_preserves_python_precedence() {
|
|
let config = AwsAuthConfig {
|
|
access_key_id: Some("ak".into()),
|
|
secret_access_key: Some("sk".into()),
|
|
session_token: Some("token".into()),
|
|
region_name: Some("us-east-1".into()),
|
|
session_name: Some("session".into()),
|
|
profile_name: Some("profile".into()),
|
|
role_name: Some("role".into()),
|
|
web_identity_token: Some("oidc".into()),
|
|
..Default::default()
|
|
};
|
|
assert!(matches!(
|
|
classify_auth(config, &no_env),
|
|
AwsAuthFlow::WebIdentity { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn classification_covers_fallthroughs() {
|
|
let env = |key: &str| match key {
|
|
AWS_PROFILE_NAME => Some("profile".into()),
|
|
_ => None,
|
|
};
|
|
assert!(matches!(
|
|
classify_auth(AwsAuthConfig::default(), &env),
|
|
AwsAuthFlow::Profile { .. }
|
|
));
|
|
assert!(matches!(
|
|
classify_auth(
|
|
AwsAuthConfig {
|
|
access_key_id: Some("ak".into()),
|
|
secret_access_key: Some("sk".into()),
|
|
session_token: Some("token".into()),
|
|
..Default::default()
|
|
},
|
|
&no_env
|
|
),
|
|
AwsAuthFlow::SessionToken { .. }
|
|
));
|
|
assert!(matches!(
|
|
classify_auth(
|
|
AwsAuthConfig {
|
|
access_key_id: Some("ak".into()),
|
|
secret_access_key: Some("sk".into()),
|
|
region_name: Some("us-east-1".into()),
|
|
..Default::default()
|
|
},
|
|
&no_env
|
|
),
|
|
AwsAuthFlow::StaticKeys { .. }
|
|
));
|
|
assert_eq!(
|
|
classify_auth(AwsAuthConfig::default(), &no_env),
|
|
AwsAuthFlow::DefaultChain
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn static_credentials_do_not_use_network() {
|
|
let credentials = AwsAuthService::default()
|
|
.resolve_credentials(
|
|
AwsAuthConfig {
|
|
access_key_id: Some("ak".into()),
|
|
secret_access_key: Some("sk".into()),
|
|
region_name: Some("us-east-1".into()),
|
|
..Default::default()
|
|
},
|
|
&no_env,
|
|
)
|
|
.await
|
|
.expect("static credentials");
|
|
assert_eq!(credentials.access_key_id(), "ak");
|
|
assert_eq!(credentials.session_token(), None);
|
|
}
|
|
|
|
#[test]
|
|
fn cache_policy_matches_python_flows() {
|
|
assert_eq!(
|
|
credential_cache_ttl(&AwsAuthFlow::StaticKeys {
|
|
access_key_id: "ak".into(),
|
|
secret_access_key: "sk".into(),
|
|
region_name: "us-east-1".into(),
|
|
}),
|
|
Some(STATIC_CREDENTIALS_TTL)
|
|
);
|
|
assert_eq!(
|
|
credential_cache_ttl(&AwsAuthFlow::DefaultChain),
|
|
Some(AMBIENT_CREDENTIALS_TTL)
|
|
);
|
|
assert_eq!(
|
|
credential_cache_ttl(&AwsAuthFlow::SessionToken {
|
|
access_key_id: "ak".into(),
|
|
secret_access_key: "sk".into(),
|
|
session_token: "token".into(),
|
|
}),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
credential_cache_ttl(&AwsAuthFlow::Profile {
|
|
name: "profile".into()
|
|
}),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
credential_cache_ttl(&AwsAuthFlow::AssumeRole {
|
|
role: "arn:aws:iam::123456789012:role/demo".into(),
|
|
session_name: None,
|
|
}),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
credential_cache_ttl(&AwsAuthFlow::WebIdentity {
|
|
token: "token".into(),
|
|
role: "arn:aws:iam::123456789012:role/demo".into(),
|
|
session_name: "session".into(),
|
|
}),
|
|
None
|
|
);
|
|
}
|
|
|
|
#[rstest::rstest]
|
|
fn cache_round_trip_preserves_credentials() {
|
|
let auth = AwsAuthService::default();
|
|
let key = format!("cache-test-{}", std::process::id());
|
|
let credentials = Credentials::new("cache-ak", "cache-sk", None, None, "test");
|
|
auth.set_cached_credentials(key.clone(), credentials.clone(), STATIC_CREDENTIALS_TTL);
|
|
assert_eq!(
|
|
auth.get_cached_credentials(&key)
|
|
.map(|value| value.access_key_id().to_string()),
|
|
Some("cache-ak".to_string())
|
|
);
|
|
}
|
|
|
|
#[rstest::rstest]
|
|
#[tokio::test]
|
|
async fn cloned_services_reuse_credentials_but_independent_services_do_not() {
|
|
let auth = AwsAuthService::default();
|
|
let config = AwsAuthConfig {
|
|
access_key_id: Some("configured-key".into()),
|
|
secret_access_key: Some("configured-secret".into()),
|
|
region_name: Some("us-east-1".into()),
|
|
..AwsAuthConfig::default()
|
|
};
|
|
let flow = classify_auth(config.clone(), &no_env);
|
|
let cached = Credentials::new("cached-key", "cached-secret", None, None, "test");
|
|
auth.set_cached_credentials(
|
|
cache_key(&config, &flow),
|
|
cached.clone(),
|
|
STATIC_CREDENTIALS_TTL,
|
|
);
|
|
|
|
let reused = auth
|
|
.clone()
|
|
.resolve_credentials(config.clone(), &no_env)
|
|
.await
|
|
.unwrap();
|
|
let independent = AwsAuthService::default()
|
|
.resolve_credentials(config.clone(), &no_env)
|
|
.await
|
|
.unwrap();
|
|
let different = AwsAuthConfig {
|
|
access_key_id: Some("different-key".into()),
|
|
..config.clone()
|
|
};
|
|
let other_identity = auth
|
|
.resolve_credentials(different.clone(), &no_env)
|
|
.await
|
|
.unwrap();
|
|
|
|
assert_eq!(reused.access_key_id(), cached.access_key_id());
|
|
assert_eq!(reused.secret_access_key(), cached.secret_access_key());
|
|
assert_eq!(
|
|
Some(independent.access_key_id()),
|
|
config.access_key_id.as_deref()
|
|
);
|
|
assert_eq!(
|
|
Some(other_identity.access_key_id()),
|
|
different.access_key_id.as_deref()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn same_role_comparison_matches_partition_account_and_role() {
|
|
assert!(same_role_arns(
|
|
"arn:aws:iam::123456789012:role/path/demo",
|
|
"arn:aws:sts::123456789012:assumed-role/demo/session"
|
|
));
|
|
assert!(!same_role_arns(
|
|
"arn:aws:iam::123456789012:role/demo",
|
|
"arn:aws:iam::999999999999:role/demo"
|
|
));
|
|
assert!(!same_role_arns(
|
|
"arn:aws:iam::123456789012:role/demo",
|
|
"arn:aws-cn:iam::123456789012:role/demo"
|
|
));
|
|
assert!(!same_role_arns(
|
|
"arn:aws:iam::123456789012:user/demo",
|
|
"arn:aws:iam::123456789012:role/demo"
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn a_forwarded_client_header_is_not_folded_into_the_signature() {
|
|
// Python signs only the AWS header set, so a header a caller forwarded
|
|
// cannot change the canonical request. Signing it instead makes the
|
|
// request 403 the moment anything on the wire rewrites or drops it.
|
|
let (url, body, mut headers) = parity_inputs();
|
|
headers.insert("x-request-id", HeaderValue::from_static("abc-123"));
|
|
headers.insert("Accept-Encoding", HeaderValue::from_static("gzip"));
|
|
headers.insert("x-amzn-trace-id", HeaderValue::from_static("Root=1-abc"));
|
|
let signable = aws_signature_headers(&headers);
|
|
|
|
assert!(!signable.contains_key("x-request-id"));
|
|
assert!(!signable.contains_key("Accept-Encoding"));
|
|
// The AWS-prefixed one is genuinely part of the signature.
|
|
assert!(signable.contains_key("x-amzn-trace-id"));
|
|
assert!(signable.contains_key("Content-Type"));
|
|
|
|
let credentials = Credentials::new(
|
|
"AKIDEXAMPLE",
|
|
"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
|
None,
|
|
None,
|
|
"test",
|
|
);
|
|
let signed = sign_headers(
|
|
"POST",
|
|
&url,
|
|
&body,
|
|
&signable,
|
|
SigningScope {
|
|
region: "us-east-1",
|
|
service: BEDROCK_SERVICE,
|
|
credentials: &credentials,
|
|
time: SystemTime::UNIX_EPOCH,
|
|
},
|
|
)
|
|
.expect("signs");
|
|
let authorization = signed["Authorization"]
|
|
.to_str()
|
|
.expect("carries an authorization header");
|
|
assert!(
|
|
!authorization.contains("x-request-id"),
|
|
"forwarded header reached SignedHeaders: {authorization}"
|
|
);
|
|
assert!(
|
|
!authorization.contains("accept-encoding"),
|
|
"forwarded header reached SignedHeaders: {authorization}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn signing_matches_botocore_golden_vector() {
|
|
let (url, body, headers) = parity_inputs();
|
|
let credentials = Credentials::new(
|
|
"AKIDEXAMPLE",
|
|
"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
|
Some("session-token".to_string()),
|
|
None,
|
|
"test",
|
|
);
|
|
let signed = sign_headers(
|
|
"POST",
|
|
&url,
|
|
&body,
|
|
&headers,
|
|
SigningScope {
|
|
region: "us-east-1",
|
|
service: BEDROCK_SERVICE,
|
|
credentials: &credentials,
|
|
time: UNIX_EPOCH + std::time::Duration::from_secs(1_704_164_645),
|
|
},
|
|
)
|
|
.expect("golden signature");
|
|
assert_eq!(signed["X-Amz-Date"], "20240102T030405Z");
|
|
assert_eq!(signed["X-Amz-Security-Token"], "session-token");
|
|
assert_eq!(
|
|
signed["Authorization"],
|
|
"AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20240102/us-east-1/bedrock/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-security-token, Signature=55c027ef47527d3ad63f1735f9d099efdbc99f296ff914bd94e727e24ec0e464"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn signing_without_session_token_omits_security_header() {
|
|
let (url, body, headers) = parity_inputs();
|
|
let credentials = Credentials::new(
|
|
"AKIDEXAMPLE",
|
|
"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
|
None,
|
|
None,
|
|
"test",
|
|
);
|
|
let signed = sign_headers(
|
|
"POST",
|
|
&url,
|
|
&body,
|
|
&headers,
|
|
SigningScope {
|
|
region: "us-east-1",
|
|
service: BEDROCK_SERVICE,
|
|
credentials: &credentials,
|
|
time: UNIX_EPOCH + std::time::Duration::from_secs(1_704_164_645),
|
|
},
|
|
)
|
|
.expect("signature");
|
|
assert!(!signed.contains_key("X-Amz-Security-Token"));
|
|
}
|
|
|
|
#[test]
|
|
fn a_header_value_outside_visible_ascii_is_named_instead_of_signed() {
|
|
let (url, body, mut headers) = parity_inputs();
|
|
headers.insert("x-amz-meta-note", HeaderValue::from_str("café").unwrap());
|
|
let credentials = Credentials::new("AKIDEXAMPLE", "secret", None, None, "test");
|
|
|
|
let error = sign_headers(
|
|
"POST",
|
|
&url,
|
|
&body,
|
|
&headers,
|
|
SigningScope {
|
|
region: "us-east-1",
|
|
service: BEDROCK_SERVICE,
|
|
credentials: &credentials,
|
|
time: UNIX_EPOCH,
|
|
},
|
|
)
|
|
.unwrap_err();
|
|
|
|
assert_eq!(
|
|
error,
|
|
Error::NonAsciiHeader {
|
|
name: "x-amz-meta-note".into()
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_shared_auth_error_nests_the_aws_failure_and_its_cause() {
|
|
let cause = std::io::Error::new(std::io::ErrorKind::NotFound, "profile not found");
|
|
let error =
|
|
litellm_auth_types::Error::from(Error::credentials(CredentialFlow::Profile)(cause));
|
|
|
|
assert!(matches!(
|
|
litellm_error::find::<Error>(&error),
|
|
Some(Error::Credentials {
|
|
flow: CredentialFlow::Profile,
|
|
..
|
|
})
|
|
));
|
|
let report = litellm_error::Report::new(&error).to_string();
|
|
assert!(
|
|
report.contains("could not load AWS profile credentials"),
|
|
"{report}"
|
|
);
|
|
assert_eq!(report.matches("profile not found").count(), 1, "{report}");
|
|
}
|
|
|
|
#[ignore]
|
|
#[tokio::test]
|
|
async fn live_bedrock_invoke_model_returns_200() -> Result<(), Box<dyn std::error::Error>> {
|
|
let access_key_id = std::env::var("AWS_BEDROCK_TEST_ACCESS_KEY_ID")?;
|
|
let secret_access_key = std::env::var("AWS_BEDROCK_TEST_SECRET_ACCESS_KEY")?;
|
|
let body = br#"{"anthropic_version":"bedrock-2023-05-31","max_tokens":1,"messages":[{"role":"user","content":[{"type":"text","text":"ping"}]}]}"#.to_vec();
|
|
let headers =
|
|
HeaderMap::from_iter([(CONTENT_TYPE, HeaderValue::from_static("application/json"))]);
|
|
let credentials = AwsAuthService::default()
|
|
.resolve_credentials(
|
|
AwsAuthConfig {
|
|
access_key_id: Some(access_key_id),
|
|
secret_access_key: Some(secret_access_key),
|
|
region_name: Some("us-west-2".to_string()),
|
|
..Default::default()
|
|
},
|
|
&no_env,
|
|
)
|
|
.await?;
|
|
let client = litellm_http::Client::for_test();
|
|
let mut failures = Vec::new();
|
|
|
|
for region in ["us-west-2", "us-east-1"] {
|
|
let url = format!(
|
|
"https://bedrock-runtime.{region}.amazonaws.com/model/us.anthropic.claude-opus-4-8/invoke"
|
|
);
|
|
let signed_headers = sign_headers(
|
|
"POST",
|
|
&url,
|
|
&body,
|
|
&headers,
|
|
SigningScope {
|
|
region,
|
|
service: BEDROCK_SERVICE,
|
|
credentials: &credentials,
|
|
time: SystemTime::now(),
|
|
},
|
|
)?;
|
|
let response = client
|
|
.post(&url)
|
|
.headers(headers.clone())
|
|
.headers(signed_headers)
|
|
.body(body.clone())
|
|
.send()
|
|
.await?;
|
|
let status = response.status();
|
|
let response_body = response.text().await?;
|
|
let snippet: String = response_body.chars().take(240).collect();
|
|
println!("region={region} status={status} response={snippet}");
|
|
if status == reqwest::StatusCode::OK {
|
|
return Ok(());
|
|
}
|
|
failures.push(format!("{region}: {status} {snippet}"));
|
|
}
|
|
|
|
panic!(
|
|
"no Bedrock region returned HTTP 200: {}",
|
|
failures.join("; ")
|
|
);
|
|
}
|
|
}
|