aws_config/profile/token.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
//! Profile File Based Token Providers
use crate::profile::cell::ErrorTakingOnceCell;
#[allow(deprecated)]
use crate::profile::profile_file::ProfileFiles;
use crate::profile::ProfileSet;
use crate::provider_config::ProviderConfig;
use crate::sso::SsoTokenProvider;
use aws_credential_types::provider::{
error::TokenError, future, token::ProvideToken, token::Result as TokenResult,
};
use aws_types::{region::Region, SdkConfig};
async fn load_profile_set(provider_config: &ProviderConfig) -> Result<&ProfileSet, TokenError> {
provider_config
.try_profile()
.await
.map_err(|parse_err| TokenError::invalid_configuration(parse_err.clone()))
}
fn create_token_provider(
sdk_config: &SdkConfig,
provider_config: &ProviderConfig,
profile_set: &ProfileSet,
) -> Result<SsoTokenProvider, TokenError> {
let repr = crate::profile::credentials::repr::resolve_chain(profile_set)
.map_err(TokenError::invalid_configuration)?;
match repr.base {
crate::profile::credentials::repr::BaseProvider::Sso {
sso_session_name,
sso_region,
sso_start_url,
..
} => {
let mut builder = SsoTokenProvider::builder().configure(sdk_config);
builder.set_session_name(sso_session_name.map(|s| s.to_string()));
Ok(builder
.region(Region::new(sso_region.to_string()))
.start_url(sso_start_url)
.build_with(provider_config.env(), provider_config.fs()))
}
_ => Err(TokenError::not_loaded(
"no sso-session configured in profile file",
)),
}
}
/// AWS profile-based access token provider
///
/// This token provider loads SSO session config from `~/.aws/config`,
/// and uses that config to resolve a cached SSO token from `~/.aws/sso/cache`.
/// The AWS CLI can be used to establish the cached SSO token.
///
/// Generally, this provider is constructed via the default provider chain. However,
/// it can also be manually constructed with the builder:
/// ```rust,no_run
/// use aws_config::profile::ProfileFileTokenProvider;
/// let provider = ProfileFileTokenProvider::builder().build();
/// ```
/// _Note: this provider, when called, will load and parse the `~/.aws/config` file
/// only once. Parsed file contents will be cached indefinitely._
///
/// This provider requires a profile with a `sso_session` configured. For example,
/// ```ini
/// [default]
/// sso_session = example
/// region = us-west-2
///
/// [sso-session example]
/// sso_start_url = https://example.awsapps.com/start
/// sso_region = us-west-2
/// ```
#[derive(Debug)]
pub struct ProfileFileTokenProvider {
sdk_config: SdkConfig,
provider_config: ProviderConfig,
inner_provider: ErrorTakingOnceCell<SsoTokenProvider, TokenError>,
}
impl ProfileFileTokenProvider {
/// Builder for this token provider.
pub fn builder() -> Builder {
Builder::default()
}
async fn load_token(&self) -> TokenResult {
let inner_provider = self
.inner_provider
.get_or_init(
{
let sdk_config = self.sdk_config.clone();
let provider_config = self.provider_config.clone();
move || async move {
let profile_set = load_profile_set(&provider_config).await?;
create_token_provider(&sdk_config, &provider_config, profile_set)
}
},
TokenError::unhandled(
"profile file token provider initialization error already taken",
),
)
.await?;
inner_provider.provide_token().await
}
}
impl ProvideToken for ProfileFileTokenProvider {
fn provide_token<'a>(&'a self) -> future::ProvideToken<'a>
where
Self: 'a,
{
future::ProvideToken::new(self.load_token())
}
}
/// Builder for [`ProfileFileTokenProvider`].
#[derive(Debug, Default)]
pub struct Builder {
provider_config: Option<ProviderConfig>,
profile_override: Option<String>,
#[allow(deprecated)]
profile_files: Option<ProfileFiles>,
}
impl Builder {
/// Override the configuration for the [`ProfileFileTokenProvider`]
pub(crate) fn configure(mut self, provider_config: &ProviderConfig) -> Self {
self.provider_config = Some(provider_config.clone());
self
}
/// Override the profile name used by the [`ProfileFileTokenProvider`]
pub fn profile_name(mut self, profile_name: impl Into<String>) -> Self {
self.profile_override = Some(profile_name.into());
self
}
/// Set the profile file that should be used by the [`ProfileFileTokenProvider`]
#[allow(deprecated)]
pub fn profile_files(mut self, profile_files: ProfileFiles) -> Self {
self.profile_files = Some(profile_files);
self
}
/// Builds a [`ProfileFileTokenProvider`]
pub fn build(self) -> ProfileFileTokenProvider {
let build_span = tracing::debug_span!("build_profile_token_provider");
let _enter = build_span.enter();
let conf = self
.provider_config
.unwrap_or_default()
.with_profile_config(self.profile_files, self.profile_override);
ProfileFileTokenProvider {
sdk_config: conf.client_config(),
provider_config: conf,
inner_provider: ErrorTakingOnceCell::new(),
}
}
}
#[cfg(test)]
mod test {
use aws_credential_types::provider::token::ProvideToken;
/// Test generation macro
///
/// # Examples
/// **Run the test case in `test-data/default-token-provider-chain/test_name`
/// ```no_run
/// make_test!(test_name);
/// ```
///
/// **Update (responses are replayed but new requests are recorded) the test case**:
/// ```no_run
/// make_test!(update: test_name)
/// ```
///
/// **Run the test case against a real HTTPS connection:**
/// > Note: Be careful to remove sensitive information before committing. Always use a temporary
/// > AWS account when recording live traffic.
/// ```no_run
/// make_test!(live: test_name)
/// ```
macro_rules! make_test {
($name:ident $(#[$m:meta])*) => {
make_test!($name, execute, $(#[$m])*);
};
(update: $name:ident) => {
make_test!($name, execute_and_update);
};
(live: $name:ident) => {
make_test!($name, execute_from_live_traffic);
};
($name:ident, $func:ident, $(#[$m:meta])*) => {
make_test!($name, $func, std::convert::identity $(, #[$m])*);
};
($name:ident, builder: $provider_config_builder:expr) => {
make_test!($name, execute, $provider_config_builder);
};
($name:ident, $func:ident, $provider_config_builder:expr $(, #[$m:meta])*) => {
$(#[$m])*
#[tokio::test]
async fn $name() {
let _ = crate::test_case::TestEnvironment::from_dir(
concat!(
"./test-data/default-token-provider-chain/",
stringify!($name)
),
crate::test_case::test_token_provider(|config| {
async move {
crate::default_provider::token::Builder::default()
.configure(config)
.build()
.await
.provide_token()
.await
}
}),
)
.await
.unwrap()
.map_provider_config($provider_config_builder)
.$func()
.await;
}
};
}
make_test!(profile_keys);
make_test!(profile_keys_case_insensitive);
make_test!(profile_name);
}