use aws_credential_types::provider::{
self, error::CredentialsError, future, ProvideCredentials, SharedCredentialsProvider,
};
use aws_sdk_sts::operation::assume_role::builders::AssumeRoleFluentBuilder;
use aws_sdk_sts::operation::assume_role::AssumeRoleError;
use aws_sdk_sts::types::PolicyDescriptorType;
use aws_sdk_sts::Client as StsClient;
use aws_smithy_runtime::client::identity::IdentityCache;
use aws_smithy_runtime_api::client::result::SdkError;
use aws_smithy_types::error::display::DisplayErrorContext;
use aws_types::region::Region;
use aws_types::SdkConfig;
use std::time::Duration;
use tracing::Instrument;
#[derive(Debug)]
pub struct AssumeRoleProvider {
inner: Inner,
}
#[derive(Debug)]
struct Inner {
fluent_builder: AssumeRoleFluentBuilder,
}
impl AssumeRoleProvider {
pub fn builder(role: impl Into<String>) -> AssumeRoleProviderBuilder {
AssumeRoleProviderBuilder::new(role.into())
}
}
#[derive(Debug)]
pub struct AssumeRoleProviderBuilder {
role_arn: String,
external_id: Option<String>,
session_name: Option<String>,
session_length: Option<Duration>,
policy: Option<String>,
policy_arns: Option<Vec<PolicyDescriptorType>>,
region_override: Option<Region>,
sdk_config: Option<SdkConfig>,
}
impl AssumeRoleProviderBuilder {
pub fn new(role: impl Into<String>) -> Self {
Self {
role_arn: role.into(),
external_id: None,
session_name: None,
session_length: None,
policy: None,
policy_arns: None,
sdk_config: None,
region_override: None,
}
}
pub fn external_id(mut self, id: impl Into<String>) -> Self {
self.external_id = Some(id.into());
self
}
pub fn session_name(mut self, name: impl Into<String>) -> Self {
self.session_name = Some(name.into());
self
}
pub fn policy(mut self, policy: impl Into<String>) -> Self {
self.policy = Some(policy.into());
self
}
pub fn policy_arns(mut self, policy_arns: Vec<String>) -> Self {
self.policy_arns = Some(
policy_arns
.into_iter()
.map(|arn| PolicyDescriptorType::builder().arn(arn).build())
.collect::<Vec<_>>(),
);
self
}
pub fn session_length(mut self, length: Duration) -> Self {
self.session_length = Some(length);
self
}
pub fn region(mut self, region: Region) -> Self {
self.region_override = Some(region);
self
}
pub fn configure(mut self, conf: &SdkConfig) -> Self {
self.sdk_config = Some(conf.clone());
self
}
pub async fn build(self) -> AssumeRoleProvider {
let mut conf = match self.sdk_config {
Some(conf) => conf,
None => crate::load_defaults(crate::BehaviorVersion::latest()).await,
};
conf = conf
.into_builder()
.identity_cache(IdentityCache::no_cache())
.build();
if let Some(region) = self.region_override {
conf = conf.into_builder().region(region).build()
}
let config = aws_sdk_sts::config::Builder::from(&conf);
let time_source = conf.time_source().expect("A time source must be provided.");
let session_name = self.session_name.unwrap_or_else(|| {
super::util::default_session_name("assume-role-provider", time_source.now())
});
let sts_client = StsClient::from_conf(config.build());
let fluent_builder = sts_client
.assume_role()
.set_role_arn(Some(self.role_arn))
.set_external_id(self.external_id)
.set_role_session_name(Some(session_name))
.set_policy(self.policy)
.set_policy_arns(self.policy_arns)
.set_duration_seconds(self.session_length.map(|dur| dur.as_secs() as i32));
AssumeRoleProvider {
inner: Inner { fluent_builder },
}
}
pub async fn build_from_provider(
mut self,
provider: impl ProvideCredentials + 'static,
) -> AssumeRoleProvider {
let conf = match self.sdk_config {
Some(conf) => conf,
None => crate::load_defaults(crate::BehaviorVersion::latest()).await,
};
let conf = conf
.into_builder()
.credentials_provider(SharedCredentialsProvider::new(provider))
.build();
self.sdk_config = Some(conf);
self.build().await
}
}
impl Inner {
async fn credentials(&self) -> provider::Result {
tracing::debug!("retrieving assumed credentials");
let assumed = self.fluent_builder.clone().send().in_current_span().await;
match assumed {
Ok(assumed) => {
tracing::debug!(
access_key_id = ?assumed.credentials.as_ref().map(|c| &c.access_key_id),
"obtained assumed credentials"
);
super::util::into_credentials(assumed.credentials, "AssumeRoleProvider")
}
Err(SdkError::ServiceError(ref context))
if matches!(
context.err(),
AssumeRoleError::RegionDisabledException(_)
| AssumeRoleError::MalformedPolicyDocumentException(_)
) =>
{
Err(CredentialsError::invalid_configuration(
assumed.err().unwrap(),
))
}
Err(SdkError::ServiceError(ref context)) => {
tracing::warn!(error = %DisplayErrorContext(context.err()), "STS refused to grant assume role");
Err(CredentialsError::provider_error(assumed.err().unwrap()))
}
Err(err) => Err(CredentialsError::provider_error(err)),
}
}
}
impl ProvideCredentials for AssumeRoleProvider {
fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'_>
where
Self: 'a,
{
future::ProvideCredentials::new(
self.inner
.credentials()
.instrument(tracing::debug_span!("assume_role")),
)
}
}
#[cfg(test)]
mod test {
use crate::sts::AssumeRoleProvider;
use aws_credential_types::credential_fn::provide_credentials_fn;
use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
use aws_credential_types::Credentials;
use aws_smithy_async::rt::sleep::{SharedAsyncSleep, TokioSleep};
use aws_smithy_async::test_util::instant_time_and_sleep;
use aws_smithy_async::time::StaticTimeSource;
use aws_smithy_runtime::client::http::test_util::{
capture_request, ReplayEvent, StaticReplayClient,
};
use aws_smithy_runtime::test_util::capture_test_logs::capture_test_logs;
use aws_smithy_runtime_api::client::behavior_version::BehaviorVersion;
use aws_smithy_types::body::SdkBody;
use aws_types::os_shim_internal::Env;
use aws_types::region::Region;
use aws_types::SdkConfig;
use http::header::AUTHORIZATION;
use std::time::{Duration, UNIX_EPOCH};
#[tokio::test]
async fn configures_session_length() {
let (http_client, request) = capture_request(None);
let sdk_config = SdkConfig::builder()
.sleep_impl(SharedAsyncSleep::new(TokioSleep::new()))
.time_source(StaticTimeSource::new(
UNIX_EPOCH + Duration::from_secs(1234567890 - 120),
))
.http_client(http_client)
.region(Region::from_static("this-will-be-overridden"))
.behavior_version(crate::BehaviorVersion::latest())
.build();
let provider = AssumeRoleProvider::builder("myrole")
.configure(&sdk_config)
.region(Region::new("us-east-1"))
.session_length(Duration::from_secs(1234567))
.build_from_provider(provide_credentials_fn(|| async {
Ok(Credentials::for_tests())
}))
.await;
let _ = dbg!(provider.provide_credentials().await);
let req = request.expect_request();
let str_body = std::str::from_utf8(req.body().bytes().unwrap()).unwrap();
assert!(str_body.contains("1234567"), "{}", str_body);
assert_eq!(req.uri(), "https://sts.us-east-1.amazonaws.com/");
}
#[tokio::test]
async fn loads_region_from_sdk_config() {
let (http_client, request) = capture_request(None);
let sdk_config = SdkConfig::builder()
.behavior_version(crate::BehaviorVersion::latest())
.sleep_impl(SharedAsyncSleep::new(TokioSleep::new()))
.time_source(StaticTimeSource::new(
UNIX_EPOCH + Duration::from_secs(1234567890 - 120),
))
.http_client(http_client)
.credentials_provider(SharedCredentialsProvider::new(provide_credentials_fn(
|| async {
panic!("don't call me — will be overridden");
},
)))
.region(Region::from_static("us-west-2"))
.build();
let provider = AssumeRoleProvider::builder("myrole")
.configure(&sdk_config)
.session_length(Duration::from_secs(1234567))
.build_from_provider(provide_credentials_fn(|| async {
Ok(Credentials::for_tests())
}))
.await;
let _ = dbg!(provider.provide_credentials().await);
let req = request.expect_request();
assert_eq!(req.uri(), "https://sts.us-west-2.amazonaws.com/");
}
#[tokio::test]
async fn build_method_from_sdk_config() {
let _guard = capture_test_logs();
let (http_client, request) = capture_request(Some(
http::Response::builder()
.status(404)
.body(SdkBody::from(""))
.unwrap(),
));
let conf = crate::defaults(BehaviorVersion::latest())
.env(Env::from_slice(&[
("AWS_ACCESS_KEY_ID", "123-key"),
("AWS_SECRET_ACCESS_KEY", "456"),
("AWS_REGION", "us-west-17"),
]))
.use_dual_stack(true)
.use_fips(true)
.time_source(StaticTimeSource::from_secs(1234567890))
.http_client(http_client)
.load()
.await;
let provider = AssumeRoleProvider::builder("role")
.configure(&conf)
.build()
.await;
let _ = dbg!(provider.provide_credentials().await);
let req = request.expect_request();
let auth_header = req.headers().get(AUTHORIZATION).unwrap().to_string();
let expect = "Credential=123-key/20090213/us-west-17/sts/aws4_request";
assert!(
auth_header.contains(expect),
"Expected header to contain {expect} but it was {auth_header}"
);
assert_eq!("https://sts-fips.us-west-17.api.aws/", req.uri())
}
#[tokio::test]
async fn provider_does_not_cache_credentials_by_default() {
let http_client = StaticReplayClient::new(vec![
ReplayEvent::new(http::Request::new(SdkBody::from("request body")),
http::Response::builder().status(200).body(SdkBody::from(
"<AssumeRoleResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n <AssumeRoleResult>\n <AssumedRoleUser>\n <AssumedRoleId>AROAR42TAWARILN3MNKUT:assume-role-from-profile-1632246085998</AssumedRoleId>\n <Arn>arn:aws:sts::130633740322:assumed-role/assume-provider-test/assume-role-from-profile-1632246085998</Arn>\n </AssumedRoleUser>\n <Credentials>\n <AccessKeyId>ASIARCORRECT</AccessKeyId>\n <SecretAccessKey>secretkeycorrect</SecretAccessKey>\n <SessionToken>tokencorrect</SessionToken>\n <Expiration>2009-02-13T23:31:30Z</Expiration>\n </Credentials>\n </AssumeRoleResult>\n <ResponseMetadata>\n <RequestId>d9d47248-fd55-4686-ad7c-0fb7cd1cddd7</RequestId>\n </ResponseMetadata>\n</AssumeRoleResponse>\n"
)).unwrap()),
ReplayEvent::new(http::Request::new(SdkBody::from("request body")),
http::Response::builder().status(200).body(SdkBody::from(
"<AssumeRoleResponse xmlns=\"https://sts.amazonaws.com/doc/2011-06-15/\">\n <AssumeRoleResult>\n <AssumedRoleUser>\n <AssumedRoleId>AROAR42TAWARILN3MNKUT:assume-role-from-profile-1632246085998</AssumedRoleId>\n <Arn>arn:aws:sts::130633740322:assumed-role/assume-provider-test/assume-role-from-profile-1632246085998</Arn>\n </AssumedRoleUser>\n <Credentials>\n <AccessKeyId>ASIARCORRECT</AccessKeyId>\n <SecretAccessKey>TESTSECRET</SecretAccessKey>\n <SessionToken>tokencorrect</SessionToken>\n <Expiration>2009-02-13T23:33:30Z</Expiration>\n </Credentials>\n </AssumeRoleResult>\n <ResponseMetadata>\n <RequestId>c2e971c2-702d-4124-9b1f-1670febbea18</RequestId>\n </ResponseMetadata>\n</AssumeRoleResponse>\n"
)).unwrap()),
]);
let (testing_time_source, sleep) = instant_time_and_sleep(
UNIX_EPOCH + Duration::from_secs(1234567890 - 120), );
let sdk_config = SdkConfig::builder()
.sleep_impl(SharedAsyncSleep::new(sleep))
.time_source(testing_time_source.clone())
.http_client(http_client)
.behavior_version(crate::BehaviorVersion::latest())
.build();
let credentials_list = std::sync::Arc::new(std::sync::Mutex::new(vec![
Credentials::new(
"test",
"test",
None,
Some(UNIX_EPOCH + Duration::from_secs(1234567890 + 1)),
"test",
),
Credentials::new(
"test",
"test",
None,
Some(UNIX_EPOCH + Duration::from_secs(1234567890 + 120)),
"test",
),
]));
let credentials_list_cloned = credentials_list.clone();
let provider = AssumeRoleProvider::builder("myrole")
.configure(&sdk_config)
.region(Region::new("us-east-1"))
.build_from_provider(provide_credentials_fn(move || {
let list = credentials_list.clone();
async move {
let next = list.lock().unwrap().remove(0);
Ok(next)
}
}))
.await;
let creds_first = provider
.provide_credentials()
.await
.expect("should return valid credentials");
testing_time_source.advance(Duration::from_secs(120));
let creds_second = provider
.provide_credentials()
.await
.expect("should return the second credentials");
assert_ne!(creds_first, creds_second);
assert!(credentials_list_cloned.lock().unwrap().is_empty());
}
}