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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#![allow(clippy::derive_partial_eq_without_eq)]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
rustdoc::missing_crate_level_docs,
unreachable_pub
)]
//! `aws-config` provides implementations of region and credential resolution.
//!
//! These implementations can be used either via the default chain implementation
//! [`from_env`]/[`ConfigLoader`] or ad-hoc individual credential and region providers.
//!
//! [`ConfigLoader`](ConfigLoader) can combine different configuration sources into an AWS shared-config:
//! [`SdkConfig`](aws_types::SdkConfig). [`SdkConfig`](aws_types::SdkConfig) can be used configure
//! an AWS service client.
//!
//! # Examples
//!
//! Load default SDK configuration:
//! ```no_run
//! # mod aws_sdk_dynamodb {
//! # pub struct Client;
//! # impl Client {
//! # pub fn new(config: &aws_types::SdkConfig) -> Self { Client }
//! # }
//! # }
//! # async fn docs() {
//! let config = aws_config::load_from_env().await;
//! let client = aws_sdk_dynamodb::Client::new(&config);
//! # }
//! ```
//!
//! Load SDK configuration with a region override:
//! ```no_run
//! # mod aws_sdk_dynamodb {
//! # pub struct Client;
//! # impl Client {
//! # pub fn new(config: &aws_types::SdkConfig) -> Self { Client }
//! # }
//! # }
//! # async fn docs() {
//! # use aws_config::meta::region::RegionProviderChain;
//! let region_provider = RegionProviderChain::default_provider().or_else("us-east-1");
//! let config = aws_config::from_env().region(region_provider).load().await;
//! let client = aws_sdk_dynamodb::Client::new(&config);
//! # }
//! ```
//!
//! Override configuration after construction of `SdkConfig`:
//!
//! ```no_run
//! # use aws_credential_types::provider::ProvideCredentials;
//! # use aws_types::SdkConfig;
//! # mod aws_sdk_dynamodb {
//! # pub mod config {
//! # pub struct Builder;
//! # impl Builder {
//! # pub fn credentials_provider(
//! # self,
//! # credentials_provider: impl aws_credential_types::provider::ProvideCredentials + 'static) -> Self { self }
//! # pub fn build(self) -> Builder { self }
//! # }
//! # impl From<&aws_types::SdkConfig> for Builder {
//! # fn from(_: &aws_types::SdkConfig) -> Self {
//! # todo!()
//! # }
//! # }
//! # }
//! # pub struct Client;
//! # impl Client {
//! # pub fn from_conf(conf: config::Builder) -> Self { Client }
//! # pub fn new(config: &aws_types::SdkConfig) -> Self { Client }
//! # }
//! # }
//! # async fn docs() {
//! # use aws_config::meta::region::RegionProviderChain;
//! # fn custom_provider(base: &SdkConfig) -> impl ProvideCredentials {
//! # base.credentials_provider().unwrap().clone()
//! # }
//! let sdk_config = aws_config::load_from_env().await;
//! let custom_credentials_provider = custom_provider(&sdk_config);
//! let dynamo_config = aws_sdk_dynamodb::config::Builder::from(&sdk_config)
//! .credentials_provider(custom_credentials_provider)
//! .build();
//! let client = aws_sdk_dynamodb::Client::from_conf(dynamo_config);
//! # }
//! ```
pub use aws_smithy_http::endpoint;
// Re-export types from aws-types
pub use aws_types::{
app_name::{AppName, InvalidAppName},
SdkConfig,
};
/// Load default sources for all configuration with override support
pub use loader::ConfigLoader;
/// Types for configuring identity caching.
pub mod identity {
pub use aws_smithy_runtime::client::identity::IdentityCache;
pub use aws_smithy_runtime::client::identity::LazyCacheBuilder;
}
#[allow(dead_code)]
const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
#[cfg(test)]
mod test_case;
mod fs_util;
mod http_credential_provider;
mod json_credentials;
pub mod credential_process;
pub mod default_provider;
pub mod ecs;
pub mod environment;
pub mod imds;
pub mod meta;
pub mod profile;
pub mod provider_config;
pub mod retry;
mod sensitive_command;
#[cfg(feature = "sso")]
pub mod sso;
pub(crate) mod standard_property;
pub mod sts;
pub mod timeout;
pub mod web_identity_token;
/// Create an environment loader for AWS Configuration
///
/// # Examples
/// ```no_run
/// # async fn create_config() {
/// use aws_types::region::Region;
/// let config = aws_config::from_env().region("us-east-1").load().await;
/// # }
/// ```
pub fn from_env() -> ConfigLoader {
ConfigLoader::default()
}
/// Load a default configuration from the environment
///
/// Convenience wrapper equivalent to `aws_config::from_env().load().await`
pub async fn load_from_env() -> aws_types::SdkConfig {
from_env().load().await
}
mod loader {
use crate::default_provider::use_dual_stack::use_dual_stack_provider;
use crate::default_provider::use_fips::use_fips_provider;
use crate::default_provider::{app_name, credentials, region, retry_config, timeout_config};
use crate::meta::region::ProvideRegion;
use crate::profile::profile_file::ProfileFiles;
use crate::provider_config::ProviderConfig;
use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
use aws_smithy_async::rt::sleep::{default_async_sleep, AsyncSleep, SharedAsyncSleep};
use aws_smithy_async::time::{SharedTimeSource, TimeSource};
use aws_smithy_runtime_api::client::http::HttpClient;
use aws_smithy_runtime_api::client::identity::{ResolveCachedIdentity, SharedIdentityCache};
use aws_smithy_runtime_api::shared::IntoShared;
use aws_smithy_types::retry::RetryConfig;
use aws_smithy_types::timeout::TimeoutConfig;
use aws_types::app_name::AppName;
use aws_types::docs_for;
use aws_types::os_shim_internal::{Env, Fs};
use aws_types::sdk_config::SharedHttpClient;
use aws_types::SdkConfig;
#[derive(Default, Debug)]
enum CredentialsProviderOption {
/// No provider was set by the user. We can set up the default credentials provider chain.
#[default]
NotSet,
/// The credentials provider was explicitly unset. Do not set up a default chain.
ExplicitlyUnset,
/// Use the given credentials provider.
Set(SharedCredentialsProvider),
}
/// Load a cross-service [`SdkConfig`](aws_types::SdkConfig) from the environment
///
/// This builder supports overriding individual components of the generated config. Overriding a component
/// will skip the standard resolution chain from **for that component**. For example,
/// if you override the region provider, _even if that provider returns None_, the default region provider
/// chain will not be used.
#[derive(Default, Debug)]
pub struct ConfigLoader {
app_name: Option<AppName>,
identity_cache: Option<SharedIdentityCache>,
credentials_provider: CredentialsProviderOption,
endpoint_url: Option<String>,
region: Option<Box<dyn ProvideRegion>>,
retry_config: Option<RetryConfig>,
sleep: Option<SharedAsyncSleep>,
timeout_config: Option<TimeoutConfig>,
provider_config: Option<ProviderConfig>,
http_client: Option<SharedHttpClient>,
profile_name_override: Option<String>,
profile_files_override: Option<ProfileFiles>,
use_fips: Option<bool>,
use_dual_stack: Option<bool>,
time_source: Option<SharedTimeSource>,
env: Option<Env>,
fs: Option<Fs>,
}
impl ConfigLoader {
/// Override the region used to build [`SdkConfig`](aws_types::SdkConfig).
///
/// # Examples
/// ```no_run
/// # async fn create_config() {
/// use aws_types::region::Region;
/// let config = aws_config::from_env()
/// .region(Region::new("us-east-1"))
/// .load().await;
/// # }
/// ```
pub fn region(mut self, region: impl ProvideRegion + 'static) -> Self {
self.region = Some(Box::new(region));
self
}
/// Override the retry_config used to build [`SdkConfig`](aws_types::SdkConfig).
///
/// # Examples
/// ```no_run
/// # async fn create_config() {
/// use aws_config::retry::RetryConfig;
///
/// let config = aws_config::from_env()
/// .retry_config(RetryConfig::standard().with_max_attempts(2))
/// .load()
/// .await;
/// # }
/// ```
pub fn retry_config(mut self, retry_config: RetryConfig) -> Self {
self.retry_config = Some(retry_config);
self
}
/// Override the timeout config used to build [`SdkConfig`](aws_types::SdkConfig).
///
/// **Note: This only sets timeouts for calls to AWS services.** Timeouts for the credentials
/// provider chain are configured separately.
///
/// # Examples
/// ```no_run
/// # use std::time::Duration;
/// # async fn create_config() {
/// use aws_config::timeout::TimeoutConfig;
///
/// let config = aws_config::from_env()
/// .timeout_config(
/// TimeoutConfig::builder()
/// .operation_timeout(Duration::from_secs(5))
/// .build()
/// )
/// .load()
/// .await;
/// # }
/// ```
pub fn timeout_config(mut self, timeout_config: TimeoutConfig) -> Self {
self.timeout_config = Some(timeout_config);
self
}
/// Override the sleep implementation for this [`ConfigLoader`].
///
/// The sleep implementation is used to create timeout futures.
/// You generally won't need to change this unless you're using an async runtime other
/// than Tokio.
pub fn sleep_impl(mut self, sleep: impl AsyncSleep + 'static) -> Self {
// it's possible that we could wrapping an `Arc in an `Arc` and that's OK
self.sleep = Some(sleep.into_shared());
self
}
/// Set the time source used for tasks like signing requests.
///
/// You generally won't need to change this unless you're compiling for a target
/// that can't provide a default, such as WASM, or unless you're writing a test against
/// the client that needs a fixed time.
pub fn time_source(mut self, time_source: impl TimeSource + 'static) -> Self {
self.time_source = Some(time_source.into_shared());
self
}
/// Deprecated. Don't use.
#[deprecated(
note = "HTTP connector configuration changed. See https://github.com/awslabs/smithy-rs/discussions/3022 for upgrade guidance."
)]
pub fn http_connector(self, http_client: impl HttpClient + 'static) -> Self {
self.http_client(http_client)
}
/// Override the [`HttpClient`](aws_smithy_runtime_api::client::http::HttpClient) for this [`ConfigLoader`].
///
/// The HTTP client will be used for both AWS services and credentials providers.
///
/// If you wish to use a separate HTTP client for credentials providers when creating clients,
/// then override the HTTP client set with this function on the client-specific `Config`s.
///
/// ## Examples
///
/// ```no_run
/// # use aws_smithy_async::rt::sleep::SharedAsyncSleep;
/// #[cfg(feature = "client-hyper")]
/// # async fn create_config() {
/// use std::time::Duration;
/// use aws_smithy_runtime::client::http::hyper_014::HyperClientBuilder;
///
/// let tls_connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_webpki_roots()
/// // NOTE: setting `https_only()` will not allow this connector to work with IMDS.
/// .https_only()
/// .enable_http1()
/// .enable_http2()
/// .build();
///
/// let hyper_client = HyperClientBuilder::new().build(tls_connector);
/// let sdk_config = aws_config::from_env()
/// .http_client(hyper_client)
/// .load()
/// .await;
/// # }
/// ```
pub fn http_client(mut self, http_client: impl HttpClient + 'static) -> Self {
self.http_client = Some(http_client.into_shared());
self
}
/// The credentials cache has been replaced. Use the identity_cache() method instead. See its rustdoc for an example.
#[deprecated(
note = "The credentials cache has been replaced. Use the identity_cache() method instead for equivalent functionality. See its rustdoc for an example."
)]
pub fn credentials_cache(self) -> Self {
self
}
/// Override the identity cache used to build [`SdkConfig`](aws_types::SdkConfig).
///
/// The identity cache caches AWS credentials and SSO tokens. By default, a lazy cache is used
/// that will load credentials upon first request, cache them, and then reload them during
/// another request when they are close to expiring.
///
/// # Examples
///
/// Change a setting on the default lazy caching implementation:
/// ```no_run
/// use aws_config::identity::IdentityCache;
/// use std::time::Duration;
///
/// # async fn create_config() {
/// let config = aws_config::from_env()
/// .identity_cache(
/// IdentityCache::lazy()
/// // Change the load timeout to 10 seconds.
/// // Note: there are other timeouts that could trigger if the load timeout is too long.
/// .load_timeout(Duration::from_secs(10))
/// .build()
/// )
/// .load()
/// .await;
/// # }
/// ```
pub fn identity_cache(
mut self,
identity_cache: impl ResolveCachedIdentity + 'static,
) -> Self {
self.identity_cache = Some(identity_cache.into_shared());
self
}
/// Override the credentials provider used to build [`SdkConfig`](aws_types::SdkConfig).
///
/// # Examples
///
/// Override the credentials provider but load the default value for region:
/// ```no_run
/// # use aws_credential_types::Credentials;
/// # fn create_my_credential_provider() -> Credentials {
/// # Credentials::new("example", "example", None, None, "example")
/// # }
/// # async fn create_config() {
/// let config = aws_config::from_env()
/// .credentials_provider(create_my_credential_provider())
/// .load()
/// .await;
/// # }
/// ```
pub fn credentials_provider(
mut self,
credentials_provider: impl ProvideCredentials + 'static,
) -> Self {
self.credentials_provider = CredentialsProviderOption::Set(
SharedCredentialsProvider::new(credentials_provider),
);
self
}
/// Don't use credentials to sign requests.
///
/// Turning off signing with credentials is necessary in some cases, such as using
/// anonymous auth for S3, calling operations in STS that don't require a signature,
/// or using token-based auth.
///
/// # Examples
///
/// Turn off credentials in order to call a service without signing:
/// ```no_run
/// # async fn create_config() {
/// let config = aws_config::from_env()
/// .no_credentials()
/// .load()
/// .await;
/// # }
/// ```
pub fn no_credentials(mut self) -> Self {
self.credentials_provider = CredentialsProviderOption::ExplicitlyUnset;
self
}
/// Override the name of the app used to build [`SdkConfig`](aws_types::SdkConfig).
///
/// This _optional_ name is used to identify the application in the user agent that
/// gets sent along with requests.
///
/// # Examples
/// ```no_run
/// # async fn create_config() {
/// use aws_config::AppName;
/// let config = aws_config::from_env()
/// .app_name(AppName::new("my-app-name").expect("valid app name"))
/// .load().await;
/// # }
/// ```
pub fn app_name(mut self, app_name: AppName) -> Self {
self.app_name = Some(app_name);
self
}
/// Provides the ability to programmatically override the profile files that get loaded by the SDK.
///
/// The [`Default`] for `ProfileFiles` includes the default SDK config and credential files located in
/// `~/.aws/config` and `~/.aws/credentials` respectively.
///
/// Any number of config and credential files may be added to the `ProfileFiles` file set, with the
/// only requirement being that there is at least one of each. Profile file locations will produce an
/// error if they don't exist, but the default config/credentials files paths are exempt from this validation.
///
/// # Example: Using a custom profile file path
///
/// ```no_run
/// use aws_config::profile::{ProfileFileCredentialsProvider, ProfileFileRegionProvider};
/// use aws_config::profile::profile_file::{ProfileFiles, ProfileFileKind};
///
/// # async fn example() {
/// let profile_files = ProfileFiles::builder()
/// .with_file(ProfileFileKind::Credentials, "some/path/to/credentials-file")
/// .build();
/// let sdk_config = aws_config::from_env()
/// .profile_files(profile_files)
/// .load()
/// .await;
/// # }
pub fn profile_files(mut self, profile_files: ProfileFiles) -> Self {
self.profile_files_override = Some(profile_files);
self
}
/// Override the profile name used by configuration providers
///
/// Profile name is selected from an ordered list of sources:
/// 1. This override.
/// 2. The value of the `AWS_PROFILE` environment variable.
/// 3. `default`
///
/// Each AWS profile has a name. For example, in the file below, the profiles are named
/// `dev`, `prod` and `staging`:
/// ```ini
/// [dev]
/// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
///
/// [staging]
/// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
///
/// [prod]
/// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
/// ```
///
/// See [Named profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html)
/// for more information about naming profiles.
///
/// # Example: Using a custom profile name
///
/// ```no_run
/// use aws_config::profile::{ProfileFileCredentialsProvider, ProfileFileRegionProvider};
/// use aws_config::profile::profile_file::{ProfileFiles, ProfileFileKind};
///
/// # async fn example() {
/// let sdk_config = aws_config::from_env()
/// .profile_name("prod")
/// .load()
/// .await;
/// # }
pub fn profile_name(mut self, profile_name: impl Into<String>) -> Self {
self.profile_name_override = Some(profile_name.into());
self
}
/// Override the endpoint URL used for **all** AWS services.
///
/// This method will override the endpoint URL used for **all** AWS services. This primarily
/// exists to set a static endpoint for tools like `LocalStack`. When sending requests to
/// production AWS services, this method should only be used for service-specific behavior.
///
/// When this method is used, the [`Region`](aws_types::region::Region) is only used for
/// signing; it is not used to route the request.
///
/// # Examples
///
/// Use a static endpoint for all services
/// ```no_run
/// # async fn create_config() {
/// let sdk_config = aws_config::from_env()
/// .endpoint_url("http://localhost:1234")
/// .load()
/// .await;
/// # }
pub fn endpoint_url(mut self, endpoint_url: impl Into<String>) -> Self {
self.endpoint_url = Some(endpoint_url.into());
self
}
#[doc = docs_for!(use_fips)]
pub fn use_fips(mut self, use_fips: bool) -> Self {
self.use_fips = Some(use_fips);
self
}
#[doc = docs_for!(use_dual_stack)]
pub fn use_dual_stack(mut self, use_dual_stack: bool) -> Self {
self.use_dual_stack = Some(use_dual_stack);
self
}
/// Set configuration for all sub-loaders (credentials, region etc.)
///
/// Update the `ProviderConfig` used for all nested loaders. This can be used to override
/// the HTTPs connector used by providers or to stub in an in memory `Env` or `Fs` for testing.
///
/// # Examples
/// ```no_run
/// # #[cfg(feature = "hyper-client")]
/// # async fn create_config() {
/// use aws_config::provider_config::ProviderConfig;
/// let custom_https_connector = hyper_rustls::HttpsConnectorBuilder::new()
/// .with_webpki_roots()
/// .https_only()
/// .enable_http1()
/// .build();
/// let provider_config = ProviderConfig::default().with_tcp_connector(custom_https_connector);
/// let shared_config = aws_config::from_env().configure(provider_config).load().await;
/// # }
/// ```
#[deprecated(
note = "Use setters on this builder instead. configure is very hard to use correctly."
)]
pub fn configure(mut self, provider_config: ProviderConfig) -> Self {
self.provider_config = Some(provider_config);
self
}
/// Load the default configuration chain
///
/// If fields have been overridden during builder construction, the override values will be used.
///
/// Otherwise, the default values for each field will be provided.
///
/// NOTE: When an override is provided, the default implementation is **not** used as a fallback.
/// This means that if you provide a region provider that does not return a region, no region will
/// be set in the resulting [`SdkConfig`](aws_types::SdkConfig)
pub async fn load(self) -> SdkConfig {
let time_source = self.time_source.unwrap_or_default();
let sleep_impl = if self.sleep.is_some() {
self.sleep
} else {
if default_async_sleep().is_none() {
tracing::warn!(
"An implementation of AsyncSleep was requested by calling default_async_sleep \
but no default was set.
This happened when ConfigLoader::load was called during Config construction. \
You can fix this by setting a sleep_impl on the ConfigLoader before calling \
load or by enabling the rt-tokio feature"
);
}
default_async_sleep()
};
let conf = self
.provider_config
.unwrap_or_else(|| {
let mut config = ProviderConfig::init(time_source.clone(), sleep_impl.clone())
.with_fs(self.fs.unwrap_or_default())
.with_env(self.env.unwrap_or_default());
if let Some(http_client) = self.http_client.clone() {
config = config.with_http_client(http_client);
}
config
})
.with_profile_config(self.profile_files_override, self.profile_name_override);
let use_fips = if let Some(use_fips) = self.use_fips {
Some(use_fips)
} else {
use_fips_provider(&conf).await
};
let use_dual_stack = if let Some(use_dual_stack) = self.use_dual_stack {
Some(use_dual_stack)
} else {
use_dual_stack_provider(&conf).await
};
let conf = conf
.with_use_fips(use_fips)
.with_use_dual_stack(use_dual_stack);
let region = if let Some(provider) = self.region {
provider.region().await
} else {
region::Builder::default()
.configure(&conf)
.build()
.region()
.await
};
let retry_config = if let Some(retry_config) = self.retry_config {
retry_config
} else {
retry_config::default_provider()
.configure(&conf)
.retry_config()
.await
};
let app_name = if self.app_name.is_some() {
self.app_name
} else {
app_name::default_provider()
.configure(&conf)
.app_name()
.await
};
let timeout_config = if let Some(timeout_config) = self.timeout_config {
timeout_config
} else {
timeout_config::default_provider()
.configure(&conf)
.timeout_config()
.await
};
let credentials_provider = match self.credentials_provider {
CredentialsProviderOption::Set(provider) => Some(provider),
CredentialsProviderOption::NotSet => {
let mut builder =
credentials::DefaultCredentialsChain::builder().configure(conf.clone());
builder.set_region(region.clone());
Some(SharedCredentialsProvider::new(builder.build().await))
}
CredentialsProviderOption::ExplicitlyUnset => None,
};
let mut builder = SdkConfig::builder()
.region(region)
.retry_config(retry_config)
.timeout_config(timeout_config)
.time_source(time_source);
builder.set_http_client(self.http_client);
builder.set_app_name(app_name);
builder.set_identity_cache(self.identity_cache);
builder.set_credentials_provider(credentials_provider);
builder.set_sleep_impl(sleep_impl);
builder.set_endpoint_url(self.endpoint_url);
builder.set_use_fips(use_fips);
builder.set_use_dual_stack(use_dual_stack);
builder.build()
}
}
#[cfg(test)]
impl ConfigLoader {
pub(crate) fn env(mut self, env: Env) -> Self {
self.env = Some(env);
self
}
pub(crate) fn fs(mut self, fs: Fs) -> Self {
self.fs = Some(fs);
self
}
}
#[cfg(test)]
mod test {
use crate::profile::profile_file::{ProfileFileKind, ProfileFiles};
use crate::test_case::{no_traffic_client, InstantSleep};
use crate::{from_env, ConfigLoader};
use aws_credential_types::provider::ProvideCredentials;
use aws_smithy_async::rt::sleep::TokioSleep;
use aws_smithy_runtime::client::http::test_util::{infallible_client_fn, NeverClient};
use aws_types::app_name::AppName;
use aws_types::os_shim_internal::{Env, Fs};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tracing_test::traced_test;
#[tokio::test]
#[traced_test]
async fn provider_config_used() {
let env = Env::from_slice(&[
("AWS_MAX_ATTEMPTS", "10"),
("AWS_REGION", "us-west-4"),
("AWS_ACCESS_KEY_ID", "akid"),
("AWS_SECRET_ACCESS_KEY", "secret"),
]);
let fs =
Fs::from_slice(&[("test_config", "[profile custom]\nsdk-ua-app-id = correct")]);
let loader = from_env()
.sleep_impl(TokioSleep::new())
.env(env)
.fs(fs)
.http_client(NeverClient::new())
.profile_name("custom")
.profile_files(
ProfileFiles::builder()
.with_file(ProfileFileKind::Config, "test_config")
.build(),
)
.load()
.await;
assert_eq!(10, loader.retry_config().unwrap().max_attempts());
assert_eq!("us-west-4", loader.region().unwrap().as_ref());
assert_eq!(
"akid",
loader
.credentials_provider()
.unwrap()
.provide_credentials()
.await
.unwrap()
.access_key_id(),
);
assert_eq!(Some(&AppName::new("correct").unwrap()), loader.app_name());
logs_assert(|lines| {
let num_config_loader_logs = lines
.iter()
.filter(|l| l.contains("provider_config_used"))
.filter(|l| l.contains("config file loaded"))
.count();
match num_config_loader_logs {
0 => Err("no config file logs found!".to_string()),
1 => Ok(()),
more => Err(format!(
"the config file was parsed more than once! (parsed {})",
more
)),
}
});
}
fn base_conf() -> ConfigLoader {
from_env()
.sleep_impl(InstantSleep)
.http_client(no_traffic_client())
}
#[tokio::test]
async fn load_fips() {
let conf = base_conf().use_fips(true).load().await;
assert_eq!(Some(true), conf.use_fips());
}
#[tokio::test]
async fn load_dual_stack() {
let conf = base_conf().use_dual_stack(false).load().await;
assert_eq!(Some(false), conf.use_dual_stack());
let conf = base_conf().load().await;
assert_eq!(None, conf.use_dual_stack());
}
#[tokio::test]
async fn app_name() {
let app_name = AppName::new("my-app-name").unwrap();
let conf = base_conf().app_name(app_name.clone()).load().await;
assert_eq!(Some(&app_name), conf.app_name());
}
#[cfg(feature = "rustls")]
#[tokio::test]
async fn disable_default_credentials() {
let config = from_env().no_credentials().load().await;
assert!(config.identity_cache().is_none());
assert!(config.credentials_provider().is_none());
}
#[tokio::test]
async fn connector_is_shared() {
let num_requests = Arc::new(AtomicUsize::new(0));
let movable = num_requests.clone();
let http_client = infallible_client_fn(move |_req| {
movable.fetch_add(1, Ordering::Relaxed);
http::Response::new("ok!")
});
let config = from_env()
.fs(Fs::from_slice(&[]))
.env(Env::from_slice(&[]))
.http_client(http_client.clone())
.load()
.await;
config
.credentials_provider()
.unwrap()
.provide_credentials()
.await
.expect_err("did not expect credentials to be loaded—no traffic is allowed");
let num_requests = num_requests.load(Ordering::Relaxed);
assert!(num_requests > 0, "{}", num_requests);
}
}
}