diff --git a/THREAT_MODEL.md b/THREAT_MODEL.md index 1c2d212d..9e9c5ee4 100644 --- a/THREAT_MODEL.md +++ b/THREAT_MODEL.md @@ -280,6 +280,12 @@ select a different identity. This policy belongs to the AWS default provider; caller-constructed `ProvideCredentialChain` values retain their own error policy. Disabling the SSO slot prevents it from participating. +A selected AWS role profile resolves only its `source_profile` graph and the +static or SSO credentials configured for that graph. Missing source profiles, +cycles, conflicting `credential_source`, and an SSO source whose slot was +removed fail without selecting a later provider. The STS requests use only the +regional endpoint implied by the selected signing region. + AWS shared configuration and region discovery are separate from credential acquisition. Loading `SharedConfig` does not execute credential processes or contact the network. IMDSv2 region fallback requires explicit opt-in and applies diff --git a/services/aws-core/src/config.rs b/services/aws-core/src/config.rs index 66ed0171..31331ca4 100644 --- a/services/aws-core/src/config.rs +++ b/services/aws-core/src/config.rs @@ -159,6 +159,15 @@ impl SharedConfig { }) } + /// Read another profile with the same explicit and environment file selection. + /// + /// This keeps the region and endpoint overrides of the caller. It does not + /// execute role chains or credential sources. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) async fn load_profile(&self, ctx: &Context, name: &str) -> Result { + self.clone().with_profile(name).load(ctx).await + } + /// Resolve region independently of credentials, optionally falling back to IMDSv2. /// /// Explicit/environment regions skip file reads. A profile region skips metadata. @@ -214,6 +223,11 @@ impl Profile { pub fn endpoint_url(&self) -> Option<&str> { self.endpoint_url.as_deref() } + /// Return whether the selected profile section exists in either shared file. + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn is_empty(&self) -> bool { + self.properties.is_empty() + } } pub(crate) fn config_section(profile: &str) -> String { diff --git a/services/aws-core/src/provide_credential/default.rs b/services/aws-core/src/provide_credential/default.rs index 0e5b5252..413ef12f 100644 --- a/services/aws-core/src/provide_credential/default.rs +++ b/services/aws-core/src/provide_credential/default.rs @@ -16,12 +16,14 @@ // under the License. use crate::Credential; +#[cfg(not(target_arch = "wasm32"))] +use crate::provide_credential::{ + AssumeRoleChainCredentialProvider, ProcessCredentialProvider, SSOCredentialProvider, +}; use crate::provide_credential::{ AssumeRoleWithWebIdentityCredentialProvider, ECSCredentialProvider, EnvCredentialProvider, IMDSv2CredentialProvider, ProfileCredentialProvider, }; -#[cfg(not(target_arch = "wasm32"))] -use crate::provide_credential::{ProcessCredentialProvider, SSOCredentialProvider}; use reqsign_core::{Context, ProvideCredential, ProvideCredentialChain, Result}; /// DefaultCredentialProvider is a loader that will try to load credential via default chains. @@ -29,18 +31,24 @@ use reqsign_core::{Context, ProvideCredential, ProvideCredentialChain, Result}; /// Resolution order: /// /// 1. Environment variables -/// 2. Shared config (`~/.aws/config`, `~/.aws/credentials`) +/// 2. Shared config (`~/.aws/config`, `~/.aws/credentials`), including +/// assume-role profile chains backed by static credentials or SSO /// 3. SSO credentials /// 4. Web Identity Tokens /// 5. Process credentials /// 6. ECS (IAM Roles for Tasks) & Container credentials /// 7. EC2 IMDSv2 /// -/// Once SSO configuration is selected, SSO errors stop resolution to avoid -/// silently switching identities. An absent SSO configuration continues the chain. +/// A selected profile with `role_arn` is resolved through `source_profile` +/// until a supported source is reached, then each role is assumed in order. +/// Role-chain and SSO errors stop resolution to avoid silently switching +/// identities. An absent SSO configuration continues the chain. #[derive(Debug)] pub struct DefaultCredentialProvider { - chain: ProvideCredentialChain, + env_chain: ProvideCredentialChain, + profile_chain: ProvideCredentialChain, + #[cfg(not(target_arch = "wasm32"))] + role_chain: Option, #[cfg(not(target_arch = "wasm32"))] sso: Option, fallback: ProvideCredentialChain, @@ -66,7 +74,10 @@ impl DefaultCredentialProvider { /// Create with a custom credential chain. pub fn with_chain(chain: ProvideCredentialChain) -> Self { Self { - chain, + env_chain: chain, + profile_chain: ProvideCredentialChain::new(), + #[cfg(not(target_arch = "wasm32"))] + role_chain: None, #[cfg(not(target_arch = "wasm32"))] sso: None, fallback: ProvideCredentialChain::new(), @@ -90,7 +101,7 @@ impl DefaultCredentialProvider { mut self, provider: impl ProvideCredential + 'static, ) -> Self { - self.chain = self.chain.push_front(provider); + self.env_chain = self.env_chain.push_front(provider); self } } @@ -251,14 +262,19 @@ impl DefaultCredentialProviderBuilder { /// Build the `DefaultCredentialProvider` with the configured options. pub fn build(self) -> DefaultCredentialProvider { - let mut chain = ProvideCredentialChain::new(); + #[cfg(not(target_arch = "wasm32"))] + let role_chain = self.profile.as_ref().map(|profile| { + AssumeRoleChainCredentialProvider::new(profile.clone(), self.sso.clone()) + }); + let mut env_chain = ProvideCredentialChain::new(); if let Some(p) = self.env { - chain = chain.push(p); + env_chain = env_chain.push(p); } + let mut profile_chain = ProvideCredentialChain::new(); if let Some(p) = self.profile { - chain = chain.push(p); + profile_chain = profile_chain.push(p); } let mut fallback = ProvideCredentialChain::new(); @@ -283,7 +299,10 @@ impl DefaultCredentialProviderBuilder { } DefaultCredentialProvider { - chain, + env_chain, + profile_chain, + #[cfg(not(target_arch = "wasm32"))] + role_chain, #[cfg(not(target_arch = "wasm32"))] sso: self.sso, fallback, @@ -294,7 +313,18 @@ impl ProvideCredential for DefaultCredentialProvider { type Credential = Credential; async fn provide_credential(&self, ctx: &Context) -> Result> { - if let Some(credential) = self.chain.provide_credential(ctx).await? { + if let Some(credential) = self.env_chain.provide_credential(ctx).await? { + return Ok(Some(credential)); + } + // A selected role profile owns its identity. Resolve its graph before + // static profile or independent SSO providers can select another identity. + #[cfg(not(target_arch = "wasm32"))] + if let Some(role_chain) = &self.role_chain { + if let Some(credential) = role_chain.provide_credential(ctx).await? { + return Ok(Some(credential)); + } + } + if let Some(credential) = self.profile_chain.provide_credential(ctx).await? { return Ok(Some(credential)); } // SSO selects an identity. Its failure must not switch to a later source. diff --git a/services/aws-core/src/provide_credential/mod.rs b/services/aws-core/src/provide_credential/mod.rs index 035153e8..b54f3a1a 100644 --- a/services/aws-core/src/provide_credential/mod.rs +++ b/services/aws-core/src/provide_credential/mod.rs @@ -44,6 +44,11 @@ pub use process::ProcessCredentialProvider; mod profile; pub use profile::ProfileCredentialProvider; +#[cfg(not(target_arch = "wasm32"))] +mod role_chain; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use role_chain::AssumeRoleChainCredentialProvider; + #[cfg(not(target_arch = "wasm32"))] mod sso; #[cfg(not(target_arch = "wasm32"))] diff --git a/services/aws-core/src/provide_credential/profile.rs b/services/aws-core/src/provide_credential/profile.rs index 53fac75b..18ddd625 100644 --- a/services/aws-core/src/provide_credential/profile.rs +++ b/services/aws-core/src/provide_credential/profile.rs @@ -76,7 +76,7 @@ impl ProfileCredentialProvider { } #[cfg(not(target_arch = "wasm32"))] - fn shared_config(&self) -> crate::SharedConfig { + pub(crate) fn shared_config(&self) -> crate::SharedConfig { let mut config = crate::SharedConfig::new(); if let Some(v) = &self.profile { config = config.with_profile(v); diff --git a/services/aws-core/src/provide_credential/role_chain.rs b/services/aws-core/src/provide_credential/role_chain.rs new file mode 100644 index 00000000..d76b04fe --- /dev/null +++ b/services/aws-core/src/provide_credential/role_chain.rs @@ -0,0 +1,251 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::collections::HashSet; + +use reqsign_core::time::Timestamp; +use reqsign_core::{Context, Error, ProvideCredential, Result}; + +use crate::assume_role::{AssumeRoleOperation, regional_sts_endpoint}; +use crate::signing::{SigV4SigningOptions, sign_request_parts}; +use crate::{ + AssumeRoleGrant, Credential, Profile, ProfileCredentialProvider, SSOCredentialProvider, + SharedConfig, +}; + +const AWS_ACCESS_KEY_ID: &str = "aws_access_key_id"; +const AWS_CREDENTIAL_SOURCE: &str = "credential_source"; +const AWS_ROLE_ARN: &str = "role_arn"; +const AWS_ROLE_SESSION_NAME: &str = "role_session_name"; +const AWS_SECRET_ACCESS_KEY: &str = "aws_secret_access_key"; +const AWS_SOURCE_PROFILE: &str = "source_profile"; +const AWS_EXTERNAL_ID: &str = "external_id"; +const AWS_DURATION_SECONDS: &str = "duration_seconds"; +const DEFAULT_ROLE_SESSION_NAME: &str = "reqsign"; + +/// Resolves the selected AWS shared profile as an assume-role credential graph. +/// +/// The graph is read from `source_profile` references until a profile with +/// static credentials or SSO configuration is reached. Each role transition is +/// returned by an STS `AssumeRole` call signed with the previous hop's +/// credential. +/// +/// The default provider runs this provider after the environment and static +/// profile slots and before the independent SSO slot. Disabling the profile +/// slot removes the graph, while disabling the SSO slot prevents a graph from +/// using an SSO source. +#[derive(Debug, Clone)] +pub(crate) struct AssumeRoleChainCredentialProvider { + profile: ProfileCredentialProvider, + sso: Option, +} + +impl AssumeRoleChainCredentialProvider { + pub(crate) fn new( + profile: ProfileCredentialProvider, + sso: Option, + ) -> Self { + Self { profile, sso } + } + + async fn source_credential( + &self, + ctx: &Context, + shared: &SharedConfig, + profile: &Profile, + ) -> Result { + if profile.get(AWS_ACCESS_KEY_ID).is_some() && profile.get(AWS_SECRET_ACCESS_KEY).is_some() + { + return self + .profile + .clone() + .with_profile(profile.name()) + .provide_credential(ctx) + .await? + .ok_or_else(|| { + Error::config_invalid(format!( + "AWS role profile source '{}' has incomplete static credentials", + profile.name() + )) + }); + } + + if has_sso_configuration(profile) { + let Some(sso) = &self.sso else { + return Err(Error::config_invalid(format!( + "AWS role profile source '{}' requires SSO, but the SSO provider is disabled", + profile.name() + ))); + }; + return sso + .clone() + .with_shared_config(shared.clone()) + .provide_credential_for_profile(ctx, profile.name()) + .await? + .ok_or_else(|| { + Error::config_invalid(format!( + "AWS role profile source '{}' does not provide SSO credentials", + profile.name() + )) + }); + } + + Err(Error::config_invalid(format!( + "AWS role profile source '{}' does not provide static credentials or SSO configuration", + profile.name() + ))) + } +} + +impl ProvideCredential for AssumeRoleChainCredentialProvider { + type Credential = Credential; + + async fn provide_credential(&self, ctx: &Context) -> Result> { + let shared = self.profile.shared_config(); + let selected = match shared.load(ctx).await { + Ok(selected) => selected, + // The shared profile slot already permits a malformed profile to + // fall through to later providers. Do not change that policy when + // the selected profile cannot be read well enough to identify a + // role graph. + Err(_) => return Ok(None), + }; + if selected.get(AWS_ROLE_ARN).is_none() { + return Ok(None); + } + + let region = selected.region().map(str::to_owned).ok_or_else(|| { + Error::config_invalid(format!( + "AWS role profile '{}' requires a region for STS", + selected.name() + )) + })?; + let mut operations = Vec::new(); + let mut seen = HashSet::new(); + let mut current = selected; + let mut current_name = current.name().to_owned(); + + loop { + if !seen.insert(current_name.clone()) { + return Err(Error::config_invalid(format!( + "AWS profile role chain contains a cycle at '{current_name}'" + ))); + } + + let Some(role_arn) = current.get(AWS_ROLE_ARN) else { + break; + }; + let source_profile = current.get(AWS_SOURCE_PROFILE); + let credential_source = current.get(AWS_CREDENTIAL_SOURCE); + if source_profile.is_some() && credential_source.is_some() { + return Err(Error::config_invalid(format!( + "AWS role profile '{current_name}' cannot set both source_profile and credential_source" + ))); + } + if credential_source.is_some() { + return Err(Error::config_invalid(format!( + "AWS role profile '{current_name}' uses credential_source, which is not supported; set source_profile" + ))); + } + let Some(source_profile) = source_profile else { + return Err(Error::config_invalid(format!( + "AWS role profile '{current_name}' requires source_profile" + ))); + }; + + let grant = role_grant(¤t, role_arn)?; + let endpoint = regional_sts_endpoint(®ion, &grant)?; + let operation = AssumeRoleOperation::new(endpoint, &grant, role_duration(¤t)?)?; + operations.push(operation); + + current_name = source_profile.to_owned(); + current = shared.load_profile(ctx, ¤t_name).await?; + if current.is_empty() { + return Err(Error::config_invalid(format!( + "AWS profile role chain references missing source profile '{current_name}'" + ))); + } + } + + let mut credential = self.source_credential(ctx, &shared, ¤t).await?; + for operation in operations.into_iter().rev() { + let request = operation.build_request()?; + let (mut parts, body) = request.into_parts(); + sign_request_parts( + &mut parts, + &credential, + None, + Timestamp::now(), + SigV4SigningOptions { + service: "sts", + region: ®ion, + percent_encoding_mode: crate::PercentEncodingMode::Single, + uses_s3_express_session_token: false, + }, + )?; + credential = operation + .send(ctx, http::Request::from_parts(parts, body)) + .await?; + } + Ok(Some(credential)) + } +} + +fn role_grant(profile: &Profile, role_arn: &str) -> Result { + let role_session_name = profile + .get(AWS_ROLE_SESSION_NAME) + .unwrap_or(DEFAULT_ROLE_SESSION_NAME); + let mut grant = AssumeRoleGrant::new(role_arn.to_owned(), role_session_name); + if let Some(id) = profile.get(AWS_EXTERNAL_ID) { + grant = grant.with_external_id(id.to_owned()); + } + Ok(grant) +} + +fn role_duration(profile: &Profile) -> Result> { + let Some(value) = profile.get(AWS_DURATION_SECONDS) else { + return Ok(None); + }; + let seconds = value.parse::().map_err(|_| { + Error::config_invalid(format!( + "AWS role profile '{}' has an invalid duration_seconds", + profile.name() + )) + })?; + if !(900..=43_200).contains(&seconds) { + return Err(Error::config_invalid(format!( + "AWS role profile '{}' duration_seconds must be between 900 and 43200", + profile.name() + ))); + } + Ok(Some(seconds)) +} + +fn has_sso_configuration(profile: &Profile) -> bool { + [ + "sso_session", + "sso_start_url", + "sso_region", + "sso_account_id", + "sso_role_name", + ] + .iter() + .any(|key| profile.get(key).is_some()) +} + +#[cfg(test)] +mod tests; diff --git a/services/aws-core/src/provide_credential/role_chain/tests.rs b/services/aws-core/src/provide_credential/role_chain/tests.rs new file mode 100644 index 00000000..8f7773ae --- /dev/null +++ b/services/aws-core/src/provide_credential/role_chain/tests.rs @@ -0,0 +1,516 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use super::*; +use crate::{DefaultCredentialProvider, DefaultCredentialProviderBuilder}; +use bytes::Bytes; +use http::{Request, Response, StatusCode, header}; +use reqsign_core::{ErrorKind, FileRead, HttpSend, StaticEnv}; +use serde_json::json; +use sha1::{Digest, Sha1}; +use std::collections::{HashMap, VecDeque}; +use std::sync::{Arc, Mutex}; + +const REGION: &str = "us-east-1"; +const OPERATOR_ROLE: &str = "arn:aws:iam::111122223333:role/Operator"; +const INTERMEDIATE_ROLE: &str = "arn:aws:iam::111122223333:role/Intermediate"; +const SOURCE_ACCESS_KEY: &str = "ASIASOURCE0000000001"; +const INTERMEDIATE_ACCESS_KEY: &str = "ASIAINTERMEDIATE001"; +const OPERATOR_ACCESS_KEY: &str = "ASIAOPERATOR0000001"; +const SSO_SOURCE_ACCESS_KEY: &str = "ASIASSOSOURCE000001"; +const SSO_ACCESS_TOKEN: &str = "cached-sso-access-token"; + +#[derive(Debug, Default)] +struct Files(Mutex>>); + +impl FileRead for Files { + async fn file_read(&self, path: &str) -> Result> { + self.0 + .lock() + .expect("lock poisoned") + .get(path) + .cloned() + .ok_or_else(|| Error::unexpected("file not found")) + } +} + +impl Files { + fn put(&self, path: &str, content: impl Into>) { + self.0 + .lock() + .expect("lock poisoned") + .insert(path.to_owned(), content.into()); + } + + fn sso_token(&self, home: &str, session: &str) { + let digest = Sha1::digest(session.as_bytes()); + self.put( + &format!("{home}/.aws/sso/cache/{}.json", hex::encode(digest)), + json!({ + "accessToken": SSO_ACCESS_TOKEN, + "expiresAt": "2099-01-01T00:00:00Z", + }) + .to_string(), + ); + } +} + +#[derive(Debug, Default)] +struct Http { + requests: Mutex>>, + responses: Mutex>>, +} + +impl HttpSend for Http { + async fn http_send(&self, request: Request) -> Result> { + self.requests.lock().expect("lock poisoned").push(request); + self.responses + .lock() + .expect("lock poisoned") + .pop_front() + .ok_or_else(|| Error::unexpected("unexpected HTTP request")) + } +} + +impl Http { + fn reply(&self, response: Response) { + self.responses + .lock() + .expect("lock poisoned") + .push_back(response); + } + + fn sso_role(&self) { + self.reply( + Response::builder() + .status(StatusCode::OK) + .body(Bytes::from( + json!({ + "roleCredentials": { + "accessKeyId": SSO_SOURCE_ACCESS_KEY, + "secretAccessKey": "sso-source-secret", + "sessionToken": "sso-source-session-token", + "expiration": 2000000000000i64, + } + }) + .to_string(), + )) + .expect("response must build"), + ); + } + + fn assumed_role(&self, access_key: &str, token: &str) { + self.reply( + Response::builder() + .status(StatusCode::OK) + .body(Bytes::from(format!( + "\ + {access_key}\ + {access_key}-secret\ + {token}\ + 2099-11-09T13:34:41Z\ + " + ))) + .expect("response must build"), + ); + } + + fn calls(&self) -> usize { + self.requests.lock().expect("lock poisoned").len() + } + + fn requests(&self) -> Vec> { + self.requests.lock().expect("lock poisoned").clone() + } +} + +fn sso_chain_config() -> String { + format!( + "[profile operator]\n\ + role_arn = {OPERATOR_ROLE}\n\ + source_profile = intermediate\n\ + role_session_name = operator-session\n\ + region = {REGION}\n\ + \n\ + [profile intermediate]\n\ + role_arn = {INTERMEDIATE_ROLE}\n\ + source_profile = sso-source\n\ + role_session_name = intermediate-session\n\ + \n\ + [profile sso-source]\n\ + sso_session = example-session\n\ + sso_account_id = 111122223333\n\ + sso_role_name = ExampleAccess\n\ + \n\ + [sso-session example-session]\n\ + sso_start_url = https://example.awsapps.com/start\n\ + sso_region = {REGION}\n" + ) +} + +fn single_hop_sso_config() -> String { + format!( + "[profile operator]\n\ + role_arn = {OPERATOR_ROLE}\n\ + source_profile = sso-source\n\ + role_session_name = operator-session\n\ + region = {REGION}\n\ + \n\ + [profile sso-source]\n\ + sso_session = example-session\n\ + sso_account_id = 111122223333\n\ + sso_role_name = ExampleAccess\n\ + \n\ + [sso-session example-session]\n\ + sso_start_url = https://example.awsapps.com/start\n\ + sso_region = {REGION}\n\ + \n\ + [profile other]\n\ + aws_access_key_id = ASIAOTHER00000000001\n\ + aws_secret_access_key = other-secret\n\ + region = {REGION}\n" + ) +} + +fn single_hop_static_config() -> String { + format!( + "[profile operator]\n\ + role_arn = {OPERATOR_ROLE}\n\ + source_profile = static-source\n\ + role_session_name = operator-session\n\ + {AWS_EXTERNAL_ID} = local-tenant\n\ + duration_seconds = 3600\n\ + region = {REGION}\n\ + \n\ + [profile static-source]\n\ + aws_access_key_id = {SOURCE_ACCESS_KEY}\n\ + aws_secret_access_key = source-secret\n" + ) +} + +fn fixture(config: &str, envs: HashMap) -> (Context, Arc) { + let files = Arc::new(Files::default()); + files.put("/config", config.to_owned()); + files.sso_token("/home", "example-session"); + let http = Arc::new(Http::default()); + let ctx = Context::new() + .with_file_read(files) + .with_http_send(http.clone()) + .with_env(StaticEnv { + home_dir: Some("/home".into()), + envs: HashMap::from([ + ("AWS_CONFIG_FILE".to_owned(), "/config".to_owned()), + ( + "AWS_SHARED_CREDENTIALS_FILE".to_owned(), + "/credentials".to_owned(), + ), + ]) + .into_iter() + .chain(envs) + .collect(), + }); + (ctx, http) +} + +fn isolated_builder(profile: &str) -> DefaultCredentialProviderBuilder { + DefaultCredentialProvider::builder() + .no_env() + .no_web_identity() + .no_process() + .no_ecs() + .no_imds() + .with_profile(profile) +} + +fn query_value(request: &Request, key: &str) -> String { + form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes()) + .find(|(name, _)| name == key) + .map(|(_, value)| value.into_owned()) + .unwrap_or_else(|| panic!("query parameter {key} is missing")) +} + +fn authorization_access_key(request: &Request) -> String { + let authorization = request.headers()[header::AUTHORIZATION] + .to_str() + .expect("authorization must be text"); + let credential = authorization + .split_once("Credential=") + .expect("credential must be present") + .1; + credential + .split_once('/') + .expect("credential scope must be present") + .0 + .to_owned() +} + +#[tokio::test] +async fn resolves_explicit_role_profile_through_named_sso_in_order() { + let (ctx, http) = fixture(&sso_chain_config(), HashMap::new()); + http.sso_role(); + http.assumed_role(INTERMEDIATE_ACCESS_KEY, "intermediate-token"); + http.assumed_role(OPERATOR_ACCESS_KEY, "operator-token"); + + let credential = isolated_builder("operator") + .build() + .provide_credential(&ctx) + .await + .expect("role chain must resolve") + .expect("role chain must return a credential"); + + assert_eq!(credential.access_key_id, OPERATOR_ACCESS_KEY); + assert_eq!(credential.session_token.as_deref(), Some("operator-token")); + let requests = http.requests(); + assert_eq!(requests.len(), 3); + + assert_eq!( + requests[0].uri().to_string(), + format!( + "https://portal.sso.{REGION}.amazonaws.com/federation/credentials?role_name=ExampleAccess&account_id=111122223333" + ) + ); + assert_eq!( + requests[0].headers()["x-amz-sso_bearer_token"], + SSO_ACCESS_TOKEN + ); + + assert_eq!(query_value(&requests[1], "RoleArn"), INTERMEDIATE_ROLE); + assert_eq!( + query_value(&requests[1], "RoleSessionName"), + "intermediate-session" + ); + assert_eq!( + authorization_access_key(&requests[1]), + SSO_SOURCE_ACCESS_KEY + ); + assert_eq!( + requests[1].headers()["x-amz-security-token"], + "sso-source-session-token" + ); + assert!(requests[1].headers().get("x-amz-s3session-token").is_none()); + + assert_eq!(query_value(&requests[2], "RoleArn"), OPERATOR_ROLE); + assert_eq!( + query_value(&requests[2], "RoleSessionName"), + "operator-session" + ); + assert_eq!( + authorization_access_key(&requests[2]), + INTERMEDIATE_ACCESS_KEY + ); + assert_eq!( + requests[2].headers()["x-amz-security-token"], + "intermediate-token" + ); +} + +#[tokio::test] +async fn aws_profile_selects_role_chain_through_default_provider() { + let (ctx, http) = fixture( + &single_hop_sso_config(), + HashMap::from([("AWS_PROFILE".to_owned(), "operator".to_owned())]), + ); + http.sso_role(); + http.assumed_role(OPERATOR_ACCESS_KEY, "operator-token"); + + let credential = DefaultCredentialProvider::new() + .provide_credential(&ctx) + .await + .expect("default provider must resolve the selected role profile") + .expect("default provider must return a credential"); + + assert_eq!(credential.access_key_id, OPERATOR_ACCESS_KEY); + let requests = http.requests(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].headers()["x-amz-sso_bearer_token"], + SSO_ACCESS_TOKEN + ); + assert_eq!(query_value(&requests[1], "RoleArn"), OPERATOR_ROLE); +} + +#[tokio::test] +async fn explicit_profile_overrides_aws_profile_for_role_chain() { + let (ctx, http) = fixture( + &single_hop_sso_config(), + HashMap::from([("AWS_PROFILE".to_owned(), "other".to_owned())]), + ); + http.sso_role(); + http.assumed_role(OPERATOR_ACCESS_KEY, "operator-token"); + + let credential = isolated_builder("operator") + .build() + .provide_credential(&ctx) + .await + .expect("explicit profile must resolve") + .expect("role chain must return a credential"); + + assert_eq!(credential.access_key_id, OPERATOR_ACCESS_KEY); + let requests = http.requests(); + assert_eq!(requests.len(), 2); + assert_eq!(query_value(&requests[1], "RoleArn"), OPERATOR_ROLE); +} + +#[tokio::test] +async fn static_source_profile_chains_with_the_source_credential() { + let (ctx, http) = fixture(&single_hop_static_config(), HashMap::new()); + http.assumed_role(OPERATOR_ACCESS_KEY, "operator-token"); + + let credential = isolated_builder("operator") + .build() + .provide_credential(&ctx) + .await + .expect("static source must resolve") + .expect("role chain must return a credential"); + + assert_eq!(credential.access_key_id, OPERATOR_ACCESS_KEY); + let requests = http.requests(); + assert_eq!(requests.len(), 1); + assert_eq!(query_value(&requests[0], "RoleArn"), OPERATOR_ROLE); + assert_eq!(query_value(&requests[0], "ExternalId"), "local-tenant"); + assert_eq!(query_value(&requests[0], "DurationSeconds"), "3600"); + assert_eq!(authorization_access_key(&requests[0]), SOURCE_ACCESS_KEY); + assert!(requests[0].headers().get("x-amz-security-token").is_none()); +} + +#[tokio::test] +async fn rejects_invalid_role_graphs_before_http() { + let cases = [ + ( + "missing source profile", + format!( + "[profile operator]\nrole_arn = {OPERATOR_ROLE}\nsource_profile = missing\nregion = {REGION}\n" + ), + "missing source profile", + ), + ( + "cycle", + format!( + "[profile operator]\nrole_arn = {OPERATOR_ROLE}\nsource_profile = second\nregion = {REGION}\n\ + [profile second]\nrole_arn = {INTERMEDIATE_ROLE}\nsource_profile = operator\n" + ), + "cycle", + ), + ( + "conflicting source_profile and credential_source", + format!( + "[profile operator]\nrole_arn = {OPERATOR_ROLE}\nsource_profile = source\ncredential_source = Environment\nregion = {REGION}\n\ + [profile source]\naws_access_key_id = {SOURCE_ACCESS_KEY}\naws_secret_access_key = source-secret\n" + ), + "both source_profile and credential_source", + ), + ( + "unsupported credential_source", + format!( + "[profile operator]\nrole_arn = {OPERATOR_ROLE}\ncredential_source = Environment\nregion = {REGION}\n" + ), + "credential_source", + ), + ( + "missing region", + format!( + "[profile operator]\nrole_arn = {OPERATOR_ROLE}\nsource_profile = source\n\ + [profile source]\naws_access_key_id = {SOURCE_ACCESS_KEY}\naws_secret_access_key = source-secret\n" + ), + "requires a region", + ), + ( + "invalid role ARN", + format!( + "[profile operator]\nrole_arn = not-an-arn\nsource_profile = source\nregion = {REGION}\n\ + [profile source]\naws_access_key_id = {SOURCE_ACCESS_KEY}\naws_secret_access_key = source-secret\n" + ), + "role ARN", + ), + ]; + + for (name, config, expected) in cases { + let (ctx, http) = fixture(&config, HashMap::new()); + let error = isolated_builder("operator") + .build() + .provide_credential(&ctx) + .await + .expect_err(name); + assert!( + error.to_string().contains(expected), + "{name}: unexpected error: {error}" + ); + assert!( + matches!( + error.kind(), + ErrorKind::ConfigInvalid | ErrorKind::RequestInvalid + ), + "{name}: unexpected error kind" + ); + assert_eq!(http.calls(), 0, "{name} must fail before HTTP"); + } +} + +#[tokio::test] +async fn no_sso_disables_the_sso_source_without_fallback() { + let (ctx, http) = fixture(&single_hop_sso_config(), HashMap::new()); + let provider = DefaultCredentialProvider::builder() + .no_env() + .no_sso() + .no_web_identity() + .no_process() + .no_ecs() + .no_imds() + .with_profile("operator") + .build(); + + let error = provider + .provide_credential(&ctx) + .await + .expect_err("a role profile that requires SSO must not use a removed slot"); + assert!( + error + .to_string() + .contains("requires SSO, but the SSO provider is disabled") + ); + assert_eq!(error.kind(), ErrorKind::ConfigInvalid); + assert_eq!(http.calls(), 0); +} + +#[tokio::test] +async fn sso_source_failure_is_not_swallowed() { + let files = Arc::new(Files::default()); + files.put("/config", single_hop_sso_config()); + let http = Arc::new(Http::default()); + // No cached token exists, so the SSO source must fail before STS. + let ctx = Context::new() + .with_file_read(files) + .with_http_send(http.clone()) + .with_env(StaticEnv { + home_dir: Some("/home".into()), + envs: HashMap::from([ + ("AWS_CONFIG_FILE".to_owned(), "/config".to_owned()), + ( + "AWS_SHARED_CREDENTIALS_FILE".to_owned(), + "/credentials".to_owned(), + ), + ]), + }); + + let error = isolated_builder("operator") + .build() + .provide_credential(&ctx) + .await + .expect_err("the selected SSO source must not fall back"); + assert!(error.to_string().contains("SSO token cache not found")); + assert_eq!(http.calls(), 0); +} diff --git a/services/aws-core/src/provide_credential/sso.rs b/services/aws-core/src/provide_credential/sso.rs index 627c048b..4f588cee 100644 --- a/services/aws-core/src/provide_credential/sso.rs +++ b/services/aws-core/src/provide_credential/sso.rs @@ -61,7 +61,8 @@ const AWS_SSO_SESSION_NAME: &str = "sso_session"; /// /// Legacy inline `sso_start_url` / `sso_region` profiles and configuration supplied /// directly through the setters remain non-refreshable. This provider never -/// starts interactive login and does not resolve assume-role profile chains. +/// starts interactive login. It resolves the selected SSO profile itself; the +/// AWS default provider resolves assume-role profiles that use an SSO source. /// The AWS default provider propagates SSO errors. A custom credential chain /// retains its own error policy. #[derive(Debug, Clone)] @@ -72,6 +73,7 @@ pub struct SSOCredentialProvider { sso_role_name: Option, sso_start_url: Option, sso_endpoint: Option, // Allow custom endpoint for testing + shared: Option, sessions: Arc>>>, } @@ -91,6 +93,7 @@ impl SSOCredentialProvider { sso_role_name: None, sso_start_url: None, sso_endpoint: None, + shared: None, sessions: Arc::new(Mutex::new(HashMap::new())), } } @@ -131,6 +134,31 @@ impl SSOCredentialProvider { self } + /// Reuse the shared configuration selection of the AWS default provider. + pub(crate) fn with_shared_config(mut self, shared: crate::SharedConfig) -> Self { + self.shared = Some(shared); + self + } + + /// Load the SSO credential for a source profile of an assume-role chain. + /// + /// Directly configured SSO values describe the selected SSO profile, not a + /// source profile, so they are ignored here. The configured endpoint and + /// in-memory session state are retained. + pub(crate) async fn provide_credential_for_profile( + &self, + ctx: &Context, + profile: &str, + ) -> Result> { + let mut provider = self.clone(); + provider.profile = Some(profile.to_owned()); + provider.sso_account_id = None; + provider.sso_region = None; + provider.sso_role_name = None; + provider.sso_start_url = None; + provider.provide_with_clock(ctx, Timestamp::now).await + } + async fn load_sso_config(&self, ctx: &Context) -> Result> { // If all fields are provided directly, use them if let (Some(account_id), Some(region), Some(role_name), Some(start_url)) = ( @@ -149,7 +177,7 @@ impl SSOCredentialProvider { })); } - let mut shared = crate::SharedConfig::new(); + let mut shared = self.shared.clone().unwrap_or_default(); if let Some(profile) = &self.profile { shared = shared.with_profile(profile); } diff --git a/services/aws-core/src/signing.rs b/services/aws-core/src/signing.rs index 0a5d18c9..3ea79e43 100644 --- a/services/aws-core/src/signing.rs +++ b/services/aws-core/src/signing.rs @@ -19,13 +19,14 @@ use std::fmt::Write; use std::time::Duration; use http::{HeaderValue, Uri, header}; +use log::debug; use percent_encoding::{AsciiSet, percent_decode_str, utf8_percent_encode}; use reqsign_core::time::Timestamp; use reqsign_core::{Result, SigningRequest}; use crate::constants::{ AWS_QUERY_ENCODE_SET, AWS_URI_ENCODE_SET, X_AMZ_CONTENT_SHA_256, X_AMZ_DATE, - X_AMZ_SECURITY_TOKEN, + X_AMZ_S3_SESSION_TOKEN, X_AMZ_SECURITY_TOKEN, }; use crate::{Credential, PercentEncodingMode}; @@ -279,6 +280,222 @@ pub fn append_query_fragment(uri: &Uri, fragment: &str) -> Result { }) } +/// Service-selected options for the shared SigV4 request implementation. +#[doc(hidden)] +#[derive(Clone, Copy, Debug)] +pub struct SigV4SigningOptions<'a> { + /// AWS signing service name. + pub service: &'a str, + /// AWS signing region. + pub region: &'a str, + /// Canonical URI percent-encoding mode. + pub percent_encoding_mode: PercentEncodingMode, + /// Whether the signing service selected the S3 Express CreateSession token. + pub uses_s3_express_session_token: bool, +} + +/// Sign a wire-ready request with AWS Signature Version 4. +/// +/// This is the shared implementation used by the public SigV4 signer and by +/// reqsign's internal STS operations. `expires_in` selects query-string +/// authentication and the signature deadline; `None` selects header +/// authentication for a request that must complete within the standard +/// operation headroom. +#[doc(hidden)] +pub fn sign_request_parts( + req: &mut http::request::Parts, + credential: &Credential, + expires_in: Option, + now: Timestamp, + options: SigV4SigningOptions<'_>, +) -> Result<()> { + use reqsign_core::SigningCredential; + + let required_until = now + expires_in.unwrap_or(Duration::from_secs(10)); + if !credential.is_valid_at(required_until) { + return Err(reqsign_core::Error::credential_invalid( + "credential expires before the requested signing operation deadline", + )); + } + + let original_uri = req.uri.clone(); + let mut signed_req = SigningRequest::build(req)?; + + canonicalize_signing_headers( + &mut signed_req, + credential, + expires_in, + now, + options.uses_s3_express_session_token, + )?; + let authentication_query = sigv4_authentication_query( + &signed_req, + credential, + expires_in, + now, + options.service, + options.region, + options.uses_s3_express_session_token, + ); + let canonical_query = canonicalize_query(&signed_req, &authentication_query); + + // build canonical request and string to sign. + let creq = canonical_request_string_with_encoding( + &signed_req, + &canonical_query, + options.percent_encoding_mode, + )?; + let encoded_req = reqsign_core::hash::hex_sha256(creq.as_bytes()); + + // Scope: "20220313///aws4_request" + let scope = format!( + "{}/{}/{}/aws4_request", + now.format_date(), + options.region, + options.service + ); + debug!("calculated scope: {scope}"); + + // StringToSign: + // + // AWS4-HMAC-SHA256 + // 20220313T072004Z + // 20220313///aws4_request + // + let string_to_sign = { + let mut f = String::new(); + writeln!(f, "AWS4-HMAC-SHA256").map_err(|e| { + reqsign_core::Error::unexpected(format!("failed to write algorithm: {e}")) + })?; + writeln!(f, "{}", now.format_iso8601()).map_err(|e| { + reqsign_core::Error::unexpected(format!("failed to write timestamp: {e}")) + })?; + writeln!(f, "{scope}") + .map_err(|e| reqsign_core::Error::unexpected(format!("failed to write scope: {e}")))?; + write!(f, "{encoded_req}").map_err(|e| { + reqsign_core::Error::unexpected(format!("failed to write encoded request: {e}")) + })?; + f + }; + debug!("calculated string to sign: {string_to_sign}"); + + let signing_key = generate_signing_key( + &credential.secret_access_key, + now, + options.region, + options.service, + ); + let signature = reqsign_core::hash::hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()); + + let final_uri = if expires_in.is_some() { + let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; + Some(append_query_fragment( + &unsigned_uri, + &format!("X-Amz-Signature={signature}"), + )?) + } else { + let mut authorization = HeaderValue::from_str(&format!( + "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}", + credential.access_key_id, + scope, + signed_req.header_name_to_vec_sorted().join(";"), + signature + )) + .map_err(|e| { + reqsign_core::Error::unexpected(format!("failed to create authorization header: {e}")) + })?; + authorization.set_sensitive(true); + + signed_req + .headers + .insert(header::AUTHORIZATION, authorization); + None + }; + + signed_req.apply(req)?; + if let Some(uri) = final_uri { + req.uri = uri; + } + Ok(()) +} + +/// Add shared SigV4 headers and apply the service-selected session token choice. +#[doc(hidden)] +pub fn canonicalize_signing_headers( + request: &mut SigningRequest, + credential: &Credential, + expires_in: Option, + now: Timestamp, + uses_s3_express_session_token: bool, +) -> Result<()> { + canonicalize_headers(request, credential, expires_in, now)?; + + if !uses_s3_express_session_token || expires_in.is_some() || credential.session_token.is_none() + { + return Ok(()); + } + + // Shared canonicalization writes the standard header. S3 Express selects + // its representation from the signing service, so move the same sensitive + // header value before the canonical request is built. + if let Some(value) = request.headers.remove(X_AMZ_SECURITY_TOKEN) { + request.headers.insert(X_AMZ_S3_SESSION_TOKEN, value); + } + + Ok(()) +} + +#[doc(hidden)] +pub fn sigv4_authentication_query( + ctx: &SigningRequest, + cred: &Credential, + expires_in: Option, + now: Timestamp, + service: &str, + region: &str, + uses_s3_express_session_token: bool, +) -> Vec<(String, String)> { + let mut query = Vec::new(); + if let Some(expire) = expires_in { + query.push(("X-Amz-Algorithm".into(), "AWS4-HMAC-SHA256".into())); + query.push(( + "X-Amz-Credential".into(), + format!( + "{}/{}/{}/{}/aws4_request", + cred.access_key_id, + now.format_date(), + region, + service + ), + )); + query.push(("X-Amz-Date".into(), now.format_iso8601())); + query.push(("X-Amz-Expires".into(), expire.as_secs().to_string())); + query.push(( + "X-Amz-SignedHeaders".into(), + ctx.header_name_to_vec_sorted().join(";"), + )); + + if let Some(token) = &cred.session_token { + let name = if uses_s3_express_session_token { + "X-Amz-S3session-Token" + } else { + "X-Amz-Security-Token" + }; + query.push((name.into(), token.into())); + } + } + query +} + +fn generate_signing_key(secret: &str, time: Timestamp, region: &str, service: &str) -> Vec { + let secret = format!("AWS4{secret}"); + let sign_date = + reqsign_core::hash::hmac_sha256(secret.as_bytes(), time.format_date().as_bytes()); + let sign_region = reqsign_core::hash::hmac_sha256(sign_date.as_slice(), region.as_bytes()); + let sign_service = reqsign_core::hash::hmac_sha256(sign_region.as_slice(), service.as_bytes()); + reqsign_core::hash::hmac_sha256(sign_service.as_slice(), "aws4_request".as_bytes()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/services/aws-v4/README.md b/services/aws-v4/README.md index 2a8dd548..8e280289 100644 --- a/services/aws-v4/README.md +++ b/services/aws-v4/README.md @@ -121,6 +121,11 @@ payload signatures. 6. `ecs` 7. `imds` +The `profile` stage also resolves an assume-role profile through its +`source_profile` chain. A named SSO source profile uses the `sso` slot; each +role is assumed with the previous hop's credential. `.no_profile()` disables +the graph and `.no_sso()` prevents an SSO source from participating. + On `wasm32`, the non-portable `sso` and `process` slots are not available. ## S3 Express Authentication diff --git a/services/aws-v4/src/sign_request.rs b/services/aws-v4/src/sign_request.rs index 5084eab6..73564dc0 100644 --- a/services/aws-v4/src/sign_request.rs +++ b/services/aws-v4/src/sign_request.rs @@ -17,17 +17,9 @@ use crate::{Credential, PercentEncodingMode}; use http::request::Parts; -use http::{HeaderValue, header}; -use log::debug; -use reqsign_aws_core::constants::{X_AMZ_S3_SESSION_TOKEN, X_AMZ_SECURITY_TOKEN}; -use reqsign_aws_core::signing::{ - append_query_fragment, append_query_pairs, canonical_request_string_with_encoding, - canonicalize_headers, canonicalize_query, -}; -use reqsign_core::hash::{hex_hmac_sha256, hex_sha256, hmac_sha256}; +use reqsign_aws_core::signing::{SigV4SigningOptions, sign_request_parts}; use reqsign_core::time::Timestamp; -use reqsign_core::{Context, Result, SignRequest, SigningCredential, SigningRequest}; -use std::fmt::Write; +use reqsign_core::{Context, Result, SignRequest}; use std::time::Duration; const CREDENTIAL_OPERATION_HEADROOM: Duration = Duration::from_secs(10); @@ -207,198 +199,23 @@ impl SignRequest for RequestSigner { credential: Option<&Self::Credential>, expires_in: Option, ) -> Result<()> { - let Some(cred) = credential else { + let Some(credential) = credential else { return Ok(()); }; - let now = self.get_time(); - let required_until = self.required_valid_until_at(now, expires_in); - if !cred.is_valid_at(required_until) { - return Err(reqsign_core::Error::credential_invalid( - "credential expires before the requested signing operation deadline", - )); - } - - let original_uri = req.uri.clone(); - let mut signed_req = SigningRequest::build(req)?; - - // canonicalize context - let uses_s3_express_session_token = self.uses_s3_express_session_token(); - canonicalize_signing_headers( - &mut signed_req, - cred, - expires_in, - now, - uses_s3_express_session_token, - )?; - let authentication_query = authentication_query( - &signed_req, - cred, + sign_request_parts( + req, + credential, expires_in, - now, - &self.service, - &self.region, - uses_s3_express_session_token, - ); - let canonical_query = canonicalize_query(&signed_req, &authentication_query); - - // build canonical request and string to sign. - let creq = canonical_request_string_with_encoding( - &signed_req, - &canonical_query, - self.percent_encoding_mode, - )?; - let encoded_req = hex_sha256(creq.as_bytes()); - - // Scope: "20220313///aws4_request" - let scope = format!( - "{}/{}/{}/aws4_request", - now.format_date(), - self.region, - self.service - ); - debug!("calculated scope: {scope}"); - - // StringToSign: - // - // AWS4-HMAC-SHA256 - // 20220313T072004Z - // 20220313///aws4_request - // - let string_to_sign = { - let mut f = String::new(); - writeln!(f, "AWS4-HMAC-SHA256").map_err(|e| { - reqsign_core::Error::unexpected(format!("failed to write algorithm: {e}")) - })?; - writeln!(f, "{}", now.format_iso8601()).map_err(|e| { - reqsign_core::Error::unexpected(format!("failed to write timestamp: {e}")) - })?; - writeln!(f, "{}", scope).map_err(|e| { - reqsign_core::Error::unexpected(format!("failed to write scope: {e}")) - })?; - write!(f, "{}", encoded_req).map_err(|e| { - reqsign_core::Error::unexpected(format!("failed to write encoded request: {e}")) - })?; - f - }; - debug!("calculated string to sign: {string_to_sign}"); - - let signing_key = - generate_signing_key(&cred.secret_access_key, now, &self.region, &self.service); - let signature = hex_hmac_sha256(&signing_key, string_to_sign.as_bytes()); - - let final_uri = if expires_in.is_some() { - let unsigned_uri = append_query_pairs(&original_uri, &authentication_query)?; - Some(append_query_fragment( - &unsigned_uri, - &format!("X-Amz-Signature={signature}"), - )?) - } else { - let mut authorization = HeaderValue::from_str(&format!( - "AWS4-HMAC-SHA256 Credential={}/{}, SignedHeaders={}, Signature={}", - cred.access_key_id, - scope, - signed_req.header_name_to_vec_sorted().join(";"), - signature - )) - .map_err(|e| { - reqsign_core::Error::unexpected(format!( - "failed to create authorization header: {e}" - )) - })?; - authorization.set_sensitive(true); - - signed_req - .headers - .insert(header::AUTHORIZATION, authorization); - None - }; - - // Apply to the request. - signed_req.apply(req)?; - if let Some(uri) = final_uri { - req.uri = uri; - } - Ok(()) - } -} - -fn canonicalize_signing_headers( - request: &mut SigningRequest, - credential: &Credential, - expires_in: Option, - now: Timestamp, - uses_s3_express_session_token: bool, -) -> Result<()> { - canonicalize_headers(request, credential, expires_in, now)?; - - if !uses_s3_express_session_token || expires_in.is_some() || credential.session_token.is_none() - { - return Ok(()); - } - - // Shared canonicalization writes the standard header. S3 Express selects - // its representation from the signing service, so move the same sensitive - // header value before the canonical request is built. - if let Some(value) = request.headers.remove(X_AMZ_SECURITY_TOKEN) { - request.headers.insert(X_AMZ_S3_SESSION_TOKEN, value); - } - - Ok(()) -} - -fn authentication_query( - ctx: &SigningRequest, - cred: &Credential, - expires_in: Option, - now: Timestamp, - service: &str, - region: &str, - uses_s3_express_session_token: bool, -) -> Vec<(String, String)> { - let mut query = Vec::new(); - if let Some(expire) = expires_in { - query.push(("X-Amz-Algorithm".into(), "AWS4-HMAC-SHA256".into())); - query.push(( - "X-Amz-Credential".into(), - format!( - "{}/{}/{}/{}/aws4_request", - cred.access_key_id, - now.format_date(), - region, - service - ), - )); - query.push(("X-Amz-Date".into(), now.format_iso8601())); - query.push(("X-Amz-Expires".into(), expire.as_secs().to_string())); - query.push(( - "X-Amz-SignedHeaders".into(), - ctx.header_name_to_vec_sorted().join(";"), - )); - - if let Some(token) = &cred.session_token { - let name = if uses_s3_express_session_token { - "X-Amz-S3session-Token" - } else { - "X-Amz-Security-Token" - }; - query.push((name.into(), token.into())); - } + self.get_time(), + SigV4SigningOptions { + service: &self.service, + region: &self.region, + percent_encoding_mode: self.percent_encoding_mode, + uses_s3_express_session_token: self.uses_s3_express_session_token(), + }, + ) } - query -} - -fn generate_signing_key(secret: &str, time: Timestamp, region: &str, service: &str) -> Vec { - // Sign secret - let secret = format!("AWS4{secret}"); - // Sign date - let sign_date = hmac_sha256(secret.as_bytes(), time.format_date().as_bytes()); - // Sign region - let sign_region = hmac_sha256(sign_date.as_slice(), region.as_bytes()); - // Sign service - let sign_service = hmac_sha256(sign_region.as_slice(), service.as_bytes()); - // Sign request - hmac_sha256(sign_service.as_slice(), "aws4_request".as_bytes()) } #[cfg(test)] @@ -416,11 +233,18 @@ mod tests { use aws_sigv4::http_request::SigningSettings; use aws_sigv4::http_request::UriPathNormalizationMode; use aws_sigv4::sign::v4; + use http::HeaderValue; use http::Request; use http::header; - use reqsign_aws_core::constants::X_AMZ_CONTENT_SHA_256; - use reqsign_aws_core::signing::{canonical_request_string, canonical_uri}; - use reqsign_core::{ErrorKind, ProvideCredential, Signer}; + use reqsign_aws_core::constants::{ + X_AMZ_CONTENT_SHA_256, X_AMZ_S3_SESSION_TOKEN, X_AMZ_SECURITY_TOKEN, + }; + use reqsign_aws_core::signing::{ + canonical_request_string, canonical_uri, canonicalize_query, canonicalize_signing_headers, + sigv4_authentication_query, + }; + use reqsign_core::hash::hex_sha256; + use reqsign_core::{ErrorKind, ProvideCredential, Signer, SigningRequest}; use reqsign_file_read_tokio::TokioFileRead; use reqsign_http_send_reqwest::ReqwestHttpSend; use std::collections::VecDeque; @@ -510,7 +334,7 @@ mod tests { now, !use_standard_session_token, )?; - let authentication_query = authentication_query( + let authentication_query = sigv4_authentication_query( &signing_request, &credential, expires_in, @@ -1493,7 +1317,7 @@ mod tests { now, false, )?; - let auth_query = authentication_query( + let auth_query = sigv4_authentication_query( &signing_req, &credential, Some(Duration::from_secs(60)), diff --git a/services/aws-v4/tests/credential_providers/default.rs b/services/aws-v4/tests/credential_providers/default.rs index 1bbace40..83e23cd4 100644 --- a/services/aws-v4/tests/credential_providers/default.rs +++ b/services/aws-v4/tests/credential_providers/default.rs @@ -36,3 +36,105 @@ async fn test_default_credential_provider_live() { .expect("DefaultCredentialProvider should return credentials"); assert_credentials_work(&ctx, &credential).await; } + +#[tokio::test] +async fn test_default_provider_role_chain_is_consumed_by_signer() { + use bytes::Bytes; + use http::{Request, Response, StatusCode, header}; + use reqsign_aws_v4::RequestSigner; + use reqsign_core::{Context, FileRead, HttpSend, Signer, StaticEnv}; + use std::collections::HashMap; + use std::sync::Mutex; + + #[derive(Debug, Default)] + struct Files(Mutex>>); + + impl FileRead for Files { + async fn file_read(&self, path: &str) -> reqsign_core::Result> { + self.0 + .lock() + .expect("lock poisoned") + .get(path) + .cloned() + .ok_or_else(|| reqsign_core::Error::unexpected("file not found")) + } + } + + #[derive(Debug)] + struct Http { + request: Mutex>>, + } + + impl HttpSend for Http { + async fn http_send( + &self, + request: Request, + ) -> reqsign_core::Result> { + *self.request.lock().expect("lock poisoned") = Some(request); + Ok(Response::builder() + .status(StatusCode::OK) + .body(Bytes::from_static( + b"\ + ASIAOPERATOR0000001\ + operator-secret\ + operator-token\ + 2099-11-09T13:34:41Z\ + ", + )) + .expect("response must build")) + } + } + + let files = Files::default(); + files.0.lock().expect("lock poisoned").insert( + "/config".to_owned(), + b"[profile operator]\n\ + role_arn = arn:aws:iam::111122223333:role/Operator\n\ + source_profile = static-source\n\ + role_session_name = operator-session\n\ + region = us-east-1\n\ + \n\ + [profile static-source]\n\ + aws_access_key_id = ASIASOURCE0000000001\n\ + aws_secret_access_key = source-secret\n" + .to_vec(), + ); + let http = Http { + request: Mutex::new(None), + }; + let ctx = Context::new() + .with_file_read(files) + .with_http_send(http) + .with_env(StaticEnv { + home_dir: Some("/home".into()), + envs: HashMap::from([ + ("AWS_CONFIG_FILE".to_owned(), "/config".to_owned()), + ( + "AWS_SHARED_CREDENTIALS_FILE".to_owned(), + "/credentials".to_owned(), + ), + ("AWS_PROFILE".to_owned(), "operator".to_owned()), + ]), + }); + let signer = Signer::new( + ctx, + DefaultCredentialProvider::new(), + RequestSigner::new("s3", "us-east-1"), + ); + let mut request = http::Request::get("https://bucket.s3.us-east-1.amazonaws.com/object") + .body(()) + .expect("request must build") + .into_parts() + .0; + + signer + .sign(&mut request, None) + .await + .expect("signer must consume the role-chain credential"); + + let authorization = request.headers[header::AUTHORIZATION] + .to_str() + .expect("authorization must be text"); + assert!(authorization.contains("Credential=ASIAOPERATOR0000001/")); + assert_eq!(request.headers["x-amz-security-token"], "operator-token"); +} diff --git a/website/docs/guides/credentials.md b/website/docs/guides/credentials.md index 16eb37a3..17f24d91 100644 --- a/website/docs/guides/credentials.md +++ b/website/docs/guides/credentials.md @@ -37,7 +37,7 @@ SDKs consult, in a documented order. Each use reqsign::aws::DefaultCredentialProvider; // The documented default chain for AWS: -// env → profiles → SSO → OIDC → process → ECS → IMDS +// env → profiles (including assume-role chains) → SSO → OIDC → process → ECS → IMDS let provider = DefaultCredentialProvider::new(); ``` diff --git a/website/docs/providers/aws-sigv4.mdx b/website/docs/providers/aws-sigv4.mdx index 569e614d..0dbb5baa 100644 --- a/website/docs/providers/aws-sigv4.mdx +++ b/website/docs/providers/aws-sigv4.mdx @@ -37,7 +37,7 @@ cargo add reqsign --features aws use reqsign::aws; // Credentials resolve through the default chain: -// env → profiles → SSO → OIDC → process → ECS → IMDS. +// env → profiles (including assume-role chains) → SSO → OIDC → process → ECS → IMDS. let signer = aws::default_signer("s3", "us-east-1"); let mut req = http::Request::builder()