aws_config/lib.rs
1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6/* Automatically managed default lints */
7#![cfg_attr(docsrs, feature(doc_cfg))]
8/* End of automatically managed default lints */
9#![allow(clippy::derive_partial_eq_without_eq)]
10#![warn(
11 missing_debug_implementations,
12 missing_docs,
13 rust_2018_idioms,
14 rustdoc::missing_crate_level_docs,
15 unreachable_pub
16)]
17// Allow disallowed methods in tests
18#![cfg_attr(test, allow(clippy::disallowed_methods))]
19
20//! `aws-config` provides implementations of region and credential resolution.
21//!
22//! These implementations can be used either via the default chain implementation
23//! [`from_env`]/[`ConfigLoader`] or ad-hoc individual credential and region providers.
24//!
25//! [`ConfigLoader`] can combine different configuration sources into an AWS shared-config:
26//! [`SdkConfig`]. `SdkConfig` can be used configure an AWS service client.
27//!
28//! # Examples
29//!
30//! Load default SDK configuration:
31//! ```no_run
32//! use aws_config::BehaviorVersion;
33//! mod aws_sdk_dynamodb {
34//! # pub struct Client;
35//! # impl Client {
36//! # pub fn new(config: &aws_types::SdkConfig) -> Self { Client }
37//! # }
38//! # }
39//! # async fn docs() {
40//! let config = aws_config::load_defaults(BehaviorVersion::v2023_11_09()).await;
41//! let client = aws_sdk_dynamodb::Client::new(&config);
42//! # }
43//! ```
44//!
45//! Load SDK configuration with a region override:
46//! ```no_run
47//! # mod aws_sdk_dynamodb {
48//! # pub struct Client;
49//! # impl Client {
50//! # pub fn new(config: &aws_types::SdkConfig) -> Self { Client }
51//! # }
52//! # }
53//! # async fn docs() {
54//! # use aws_config::meta::region::RegionProviderChain;
55//! let region_provider = RegionProviderChain::default_provider().or_else("us-east-1");
56//! // Note: requires the `behavior-version-latest` feature enabled
57//! let config = aws_config::from_env().region(region_provider).load().await;
58//! let client = aws_sdk_dynamodb::Client::new(&config);
59//! # }
60//! ```
61//!
62//! Override configuration after construction of `SdkConfig`:
63//!
64//! ```no_run
65//! # use aws_credential_types::provider::ProvideCredentials;
66//! # use aws_types::SdkConfig;
67//! # mod aws_sdk_dynamodb {
68//! # pub mod config {
69//! # pub struct Builder;
70//! # impl Builder {
71//! # pub fn credentials_provider(
72//! # self,
73//! # credentials_provider: impl aws_credential_types::provider::ProvideCredentials + 'static) -> Self { self }
74//! # pub fn build(self) -> Builder { self }
75//! # }
76//! # impl From<&aws_types::SdkConfig> for Builder {
77//! # fn from(_: &aws_types::SdkConfig) -> Self {
78//! # todo!()
79//! # }
80//! # }
81//! # }
82//! # pub struct Client;
83//! # impl Client {
84//! # pub fn from_conf(conf: config::Builder) -> Self { Client }
85//! # pub fn new(config: &aws_types::SdkConfig) -> Self { Client }
86//! # }
87//! # }
88//! # async fn docs() {
89//! # use aws_config::meta::region::RegionProviderChain;
90//! # fn custom_provider(base: &SdkConfig) -> impl ProvideCredentials {
91//! # base.credentials_provider().unwrap().clone()
92//! # }
93//! let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
94//! let custom_credentials_provider = custom_provider(&sdk_config);
95//! let dynamo_config = aws_sdk_dynamodb::config::Builder::from(&sdk_config)
96//! .credentials_provider(custom_credentials_provider)
97//! .build();
98//! let client = aws_sdk_dynamodb::Client::from_conf(dynamo_config);
99//! # }
100//! ```
101
102pub use aws_smithy_runtime_api::client::behavior_version::BehaviorVersion;
103// Re-export types from aws-types
104pub use aws_types::{
105 app_name::{AppName, InvalidAppName},
106 region::Region,
107 SdkConfig,
108};
109/// Load default sources for all configuration with override support
110pub use loader::ConfigLoader;
111
112/// Types for configuring identity caching.
113pub mod identity {
114 pub use aws_smithy_runtime::client::identity::IdentityCache;
115 pub use aws_smithy_runtime::client::identity::LazyCacheBuilder;
116}
117
118#[allow(dead_code)]
119const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
120
121mod http_credential_provider;
122mod json_credentials;
123#[cfg(test)]
124mod test_case;
125
126pub mod credential_process;
127pub mod default_provider;
128pub mod ecs;
129mod env_service_config;
130pub mod environment;
131pub mod imds;
132#[cfg(feature = "credentials-login")]
133pub mod login;
134pub mod meta;
135pub mod profile;
136pub mod provider_config;
137pub mod retry;
138mod sensitive_command;
139#[cfg(feature = "sso")]
140pub mod sso;
141pub mod stalled_stream_protection;
142pub mod sts;
143pub mod timeout;
144pub mod web_identity_token;
145
146/// Create a config loader with the _latest_ defaults.
147///
148/// This loader will always set [`BehaviorVersion::latest`].
149///
150/// For more information about default configuration, refer to the AWS SDKs and Tools [shared configuration documentation](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html).
151///
152/// # Examples
153/// ```no_run
154/// # async fn create_config() {
155/// let config = aws_config::from_env().region("us-east-1").load().await;
156/// # }
157/// ```
158#[cfg(feature = "behavior-version-latest")]
159pub fn from_env() -> ConfigLoader {
160 ConfigLoader::default().behavior_version(BehaviorVersion::latest())
161}
162
163/// Load default configuration with the _latest_ defaults.
164///
165/// Convenience wrapper equivalent to `aws_config::load_defaults(BehaviorVersion::latest()).await`
166///
167/// For more information about default configuration, refer to the AWS SDKs and Tools [shared configuration documentation](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html).
168#[cfg(feature = "behavior-version-latest")]
169pub async fn load_from_env() -> SdkConfig {
170 from_env().load().await
171}
172
173/// Create a config loader with the _latest_ defaults.
174#[cfg(not(feature = "behavior-version-latest"))]
175#[deprecated(
176 note = "Use the `aws_config::defaults` function. If you don't care about future default behavior changes, you can continue to use this function by enabling the `behavior-version-latest` feature. Doing so will make this deprecation notice go away."
177)]
178pub fn from_env() -> ConfigLoader {
179 ConfigLoader::default().behavior_version(BehaviorVersion::latest())
180}
181
182/// Load default configuration with the _latest_ defaults.
183#[cfg(not(feature = "behavior-version-latest"))]
184#[deprecated(
185 note = "Use the `aws_config::load_defaults` function. If you don't care about future default behavior changes, you can continue to use this function by enabling the `behavior-version-latest` feature. Doing so will make this deprecation notice go away."
186)]
187pub async fn load_from_env() -> SdkConfig {
188 load_defaults(BehaviorVersion::latest()).await
189}
190
191/// Create a config loader with the defaults for the given behavior version.
192///
193/// For more information about default configuration, refer to the AWS SDKs and Tools [shared configuration documentation](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html).
194///
195/// # Examples
196/// ```no_run
197/// # async fn create_config() {
198/// use aws_config::BehaviorVersion;
199/// let config = aws_config::defaults(BehaviorVersion::v2023_11_09())
200/// .region("us-east-1")
201/// .load()
202/// .await;
203/// # }
204/// ```
205pub fn defaults(version: BehaviorVersion) -> ConfigLoader {
206 ConfigLoader::default().behavior_version(version)
207}
208
209/// Load default configuration with the given behavior version.
210///
211/// Convenience wrapper equivalent to `aws_config::defaults(behavior_version).load().await`
212///
213/// For more information about default configuration, refer to the AWS SDKs and Tools [shared configuration documentation](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html).
214pub async fn load_defaults(version: BehaviorVersion) -> SdkConfig {
215 defaults(version).load().await
216}
217
218mod loader {
219 use crate::env_service_config::EnvServiceConfig;
220 use aws_credential_types::provider::{
221 token::{ProvideToken, SharedTokenProvider},
222 ProvideCredentials, SharedCredentialsProvider,
223 };
224 use aws_credential_types::Credentials;
225 use aws_smithy_async::rt::sleep::{default_async_sleep, AsyncSleep, SharedAsyncSleep};
226 use aws_smithy_async::time::{SharedTimeSource, TimeSource};
227 use aws_smithy_runtime::client::identity::IdentityCache;
228 use aws_smithy_runtime_api::client::auth::AuthSchemePreference;
229 use aws_smithy_runtime_api::client::behavior_version::BehaviorVersion;
230 use aws_smithy_runtime_api::client::http::HttpClient;
231 use aws_smithy_runtime_api::client::identity::{ResolveCachedIdentity, SharedIdentityCache};
232 use aws_smithy_runtime_api::client::stalled_stream_protection::StalledStreamProtectionConfig;
233 use aws_smithy_runtime_api::shared::IntoShared;
234 use aws_smithy_types::checksum_config::{
235 RequestChecksumCalculation, ResponseChecksumValidation,
236 };
237 use aws_smithy_types::retry::RetryConfig;
238 use aws_smithy_types::timeout::TimeoutConfig;
239 use aws_types::app_name::AppName;
240 use aws_types::docs_for;
241 use aws_types::endpoint_config::AccountIdEndpointMode;
242 use aws_types::origin::Origin;
243 use aws_types::os_shim_internal::{Env, Fs};
244 use aws_types::region::SigningRegionSet;
245 use aws_types::sdk_config::SharedHttpClient;
246 use aws_types::SdkConfig;
247
248 use crate::default_provider::{
249 account_id_endpoint_mode, app_name, auth_scheme_preference, checksums, credentials,
250 disable_request_compression, endpoint_url, ignore_configured_endpoint_urls as ignore_ep,
251 region, request_min_compression_size_bytes, retry_config, sigv4a_signing_region_set,
252 timeout_config, use_dual_stack, use_fips,
253 };
254 use crate::meta::region::ProvideRegion;
255 #[allow(deprecated)]
256 use crate::profile::profile_file::ProfileFiles;
257 use crate::provider_config::ProviderConfig;
258
259 #[derive(Default, Debug)]
260 enum TriStateOption<T> {
261 /// No option was set by the user. We can set up the default.
262 #[default]
263 NotSet,
264 /// The option was explicitly unset. Do not set up a default.
265 ExplicitlyUnset,
266 /// Use the given user provided option.
267 Set(T),
268 }
269
270 /// Load a cross-service [`SdkConfig`] from the environment
271 ///
272 /// This builder supports overriding individual components of the generated config. Overriding a component
273 /// will skip the standard resolution chain from **for that component**. For example,
274 /// if you override the region provider, _even if that provider returns None_, the default region provider
275 /// chain will not be used.
276 #[derive(Default, Debug)]
277 pub struct ConfigLoader {
278 app_name: Option<AppName>,
279 auth_scheme_preference: Option<AuthSchemePreference>,
280 sigv4a_signing_region_set: Option<SigningRegionSet>,
281 identity_cache: Option<SharedIdentityCache>,
282 credentials_provider: TriStateOption<SharedCredentialsProvider>,
283 token_provider: Option<SharedTokenProvider>,
284 account_id_endpoint_mode: Option<AccountIdEndpointMode>,
285 endpoint_url: Option<String>,
286 region: Option<Box<dyn ProvideRegion>>,
287 retry_config: Option<RetryConfig>,
288 sleep: Option<SharedAsyncSleep>,
289 timeout_config: Option<TimeoutConfig>,
290 provider_config: Option<ProviderConfig>,
291 http_client: Option<SharedHttpClient>,
292 profile_name_override: Option<String>,
293 #[allow(deprecated)]
294 profile_files_override: Option<ProfileFiles>,
295 use_fips: Option<bool>,
296 use_dual_stack: Option<bool>,
297 time_source: Option<SharedTimeSource>,
298 disable_request_compression: Option<bool>,
299 request_min_compression_size_bytes: Option<u32>,
300 stalled_stream_protection_config: Option<StalledStreamProtectionConfig>,
301 env: Option<Env>,
302 fs: Option<Fs>,
303 behavior_version: Option<BehaviorVersion>,
304 request_checksum_calculation: Option<RequestChecksumCalculation>,
305 response_checksum_validation: Option<ResponseChecksumValidation>,
306 }
307
308 impl ConfigLoader {
309 /// Sets the [`BehaviorVersion`] used to build [`SdkConfig`].
310 pub fn behavior_version(mut self, behavior_version: BehaviorVersion) -> Self {
311 self.behavior_version = Some(behavior_version);
312 self
313 }
314
315 /// Override the region used to build [`SdkConfig`].
316 ///
317 /// # Examples
318 /// ```no_run
319 /// # async fn create_config() {
320 /// use aws_types::region::Region;
321 /// let config = aws_config::from_env()
322 /// .region(Region::new("us-east-1"))
323 /// .load().await;
324 /// # }
325 /// ```
326 pub fn region(mut self, region: impl ProvideRegion + 'static) -> Self {
327 self.region = Some(Box::new(region));
328 self
329 }
330
331 /// Override the retry_config used to build [`SdkConfig`].
332 ///
333 /// # Examples
334 /// ```no_run
335 /// # async fn create_config() {
336 /// use aws_config::retry::RetryConfig;
337 ///
338 /// let config = aws_config::from_env()
339 /// .retry_config(RetryConfig::standard().with_max_attempts(2))
340 /// .load()
341 /// .await;
342 /// # }
343 /// ```
344 pub fn retry_config(mut self, retry_config: RetryConfig) -> Self {
345 self.retry_config = Some(retry_config);
346 self
347 }
348
349 /// Override the timeout config used to build [`SdkConfig`].
350 ///
351 /// This will be merged with timeouts coming from the timeout information provider, which
352 /// currently includes a default `CONNECT` timeout of `3.1s`.
353 ///
354 /// If you want to disable timeouts, use [`TimeoutConfig::disabled`]. If you want to disable
355 /// a specific timeout, use `TimeoutConfig::set_<type>(None)`.
356 ///
357 /// **Note: This only sets timeouts for calls to AWS services.** Timeouts for the credentials
358 /// provider chain are configured separately.
359 ///
360 /// # Examples
361 /// ```no_run
362 /// # use std::time::Duration;
363 /// # async fn create_config() {
364 /// use aws_config::timeout::TimeoutConfig;
365 ///
366 /// let config = aws_config::from_env()
367 /// .timeout_config(
368 /// TimeoutConfig::builder()
369 /// .operation_timeout(Duration::from_secs(5))
370 /// .build()
371 /// )
372 /// .load()
373 /// .await;
374 /// # }
375 /// ```
376 pub fn timeout_config(mut self, timeout_config: TimeoutConfig) -> Self {
377 self.timeout_config = Some(timeout_config);
378 self
379 }
380
381 /// Override the sleep implementation for this [`ConfigLoader`].
382 ///
383 /// The sleep implementation is used to create timeout futures.
384 /// You generally won't need to change this unless you're using an async runtime other
385 /// than Tokio.
386 pub fn sleep_impl(mut self, sleep: impl AsyncSleep + 'static) -> Self {
387 // it's possible that we could wrapping an `Arc in an `Arc` and that's OK
388 self.sleep = Some(sleep.into_shared());
389 self
390 }
391
392 /// Set the time source used for tasks like signing requests.
393 ///
394 /// You generally won't need to change this unless you're compiling for a target
395 /// that can't provide a default, such as WASM, or unless you're writing a test against
396 /// the client that needs a fixed time.
397 pub fn time_source(mut self, time_source: impl TimeSource + 'static) -> Self {
398 self.time_source = Some(time_source.into_shared());
399 self
400 }
401
402 /// Override the [`HttpClient`] for this [`ConfigLoader`].
403 ///
404 /// The HTTP client will be used for both AWS services and credentials providers.
405 ///
406 /// If you wish to use a separate HTTP client for credentials providers when creating clients,
407 /// then override the HTTP client set with this function on the client-specific `Config`s.
408 pub fn http_client(mut self, http_client: impl HttpClient + 'static) -> Self {
409 self.http_client = Some(http_client.into_shared());
410 self
411 }
412
413 #[doc = docs_for!(auth_scheme_preference)]
414 ///
415 /// # Examples
416 /// ```no_run
417 /// # use aws_smithy_runtime_api::client::auth::AuthSchemeId;
418 /// # async fn create_config() {
419 /// let config = aws_config::from_env()
420 /// // Favors a custom auth scheme over the SigV4 auth scheme.
421 /// // Note: This will not result in an error, even if the custom scheme is missing from the resolved auth schemes.
422 /// .auth_scheme_preference([AuthSchemeId::from("custom"), aws_runtime::auth::sigv4::SCHEME_ID])
423 /// .load()
424 /// .await;
425 /// # }
426 /// ```
427 pub fn auth_scheme_preference(
428 mut self,
429 auth_scheme_preference: impl Into<AuthSchemePreference>,
430 ) -> Self {
431 self.auth_scheme_preference = Some(auth_scheme_preference.into());
432 self
433 }
434
435 #[doc = docs_for!(sigv4a_signing_region_set)]
436 pub fn sigv4a_signing_region_set(
437 mut self,
438 sigv4a_signing_region_set: impl Into<SigningRegionSet>,
439 ) -> Self {
440 self.sigv4a_signing_region_set = Some(sigv4a_signing_region_set.into());
441 self
442 }
443
444 /// Override the identity cache used to build [`SdkConfig`].
445 ///
446 /// The identity cache caches AWS credentials and SSO tokens. By default, a lazy cache is used
447 /// that will load credentials upon first request, cache them, and then reload them during
448 /// another request when they are close to expiring.
449 ///
450 /// # Examples
451 ///
452 /// Change a setting on the default lazy caching implementation:
453 /// ```no_run
454 /// use aws_config::identity::IdentityCache;
455 /// use std::time::Duration;
456 ///
457 /// # async fn create_config() {
458 /// let config = aws_config::from_env()
459 /// .identity_cache(
460 /// IdentityCache::lazy()
461 /// // Change the load timeout to 10 seconds.
462 /// // Note: there are other timeouts that could trigger if the load timeout is too long.
463 /// .load_timeout(Duration::from_secs(10))
464 /// .build()
465 /// )
466 /// .load()
467 /// .await;
468 /// # }
469 /// ```
470 pub fn identity_cache(
471 mut self,
472 identity_cache: impl ResolveCachedIdentity + 'static,
473 ) -> Self {
474 self.identity_cache = Some(identity_cache.into_shared());
475 self
476 }
477
478 /// Override the credentials provider used to build [`SdkConfig`].
479 ///
480 /// # Examples
481 ///
482 /// Override the credentials provider but load the default value for region:
483 /// ```no_run
484 /// # use aws_credential_types::Credentials;
485 /// # fn create_my_credential_provider() -> Credentials {
486 /// # Credentials::new("example", "example", None, None, "example")
487 /// # }
488 /// # async fn create_config() {
489 /// let config = aws_config::from_env()
490 /// .credentials_provider(create_my_credential_provider())
491 /// .load()
492 /// .await;
493 /// # }
494 /// ```
495 pub fn credentials_provider(
496 mut self,
497 credentials_provider: impl ProvideCredentials + 'static,
498 ) -> Self {
499 self.credentials_provider =
500 TriStateOption::Set(SharedCredentialsProvider::new(credentials_provider));
501 self
502 }
503
504 /// Don't use credentials to sign requests.
505 ///
506 /// Turning off signing with credentials is necessary in some cases, such as using
507 /// anonymous auth for S3, calling operations in STS that don't require a signature,
508 /// or using token-based auth.
509 ///
510 /// **Note**: For tests, e.g. with a service like DynamoDB Local, this is **not** what you
511 /// want. If credentials are disabled, requests cannot be signed. For these use cases, use
512 /// [`test_credentials`](Self::test_credentials).
513 ///
514 /// # Examples
515 ///
516 /// Turn off credentials in order to call a service without signing:
517 /// ```no_run
518 /// # async fn create_config() {
519 /// let config = aws_config::from_env()
520 /// .no_credentials()
521 /// .load()
522 /// .await;
523 /// # }
524 /// ```
525 pub fn no_credentials(mut self) -> Self {
526 self.credentials_provider = TriStateOption::ExplicitlyUnset;
527 self
528 }
529
530 /// Set test credentials for use when signing requests
531 pub fn test_credentials(self) -> Self {
532 #[allow(unused_mut)]
533 let mut ret = self.credentials_provider(Credentials::for_tests());
534 #[cfg(feature = "sso")]
535 {
536 use aws_smithy_runtime_api::client::identity::http::Token;
537 ret = ret.token_provider(Token::for_tests());
538 }
539 ret
540 }
541
542 /// Ignore any environment variables on the host during config resolution
543 ///
544 /// This allows for testing in a reproducible environment that ensures any
545 /// environment variables from the host do not influence environment variable
546 /// resolution.
547 pub fn empty_test_environment(mut self) -> Self {
548 self.env = Some(Env::from_slice(&[]));
549 self
550 }
551
552 /// Override the access token provider used to build [`SdkConfig`].
553 ///
554 /// # Examples
555 ///
556 /// Override the token provider but load the default value for region:
557 /// ```no_run
558 /// # use aws_credential_types::Token;
559 /// # fn create_my_token_provider() -> Token {
560 /// # Token::new("example", None)
561 /// # }
562 /// # async fn create_config() {
563 /// let config = aws_config::from_env()
564 /// .token_provider(create_my_token_provider())
565 /// .load()
566 /// .await;
567 /// # }
568 /// ```
569 pub fn token_provider(mut self, token_provider: impl ProvideToken + 'static) -> Self {
570 self.token_provider = Some(SharedTokenProvider::new(token_provider));
571 self
572 }
573
574 /// Override the name of the app used to build [`SdkConfig`].
575 ///
576 /// This _optional_ name is used to identify the application in the user agent header that
577 /// gets sent along with requests.
578 ///
579 /// The app name is selected from an ordered list of sources:
580 /// 1. This override.
581 /// 2. The value of the `AWS_SDK_UA_APP_ID` environment variable.
582 /// 3. Profile files from the key `sdk_ua_app_id`
583 ///
584 /// If none of those sources are set the value is `None` and it is not added to the user agent header.
585 ///
586 /// # Examples
587 /// ```no_run
588 /// # async fn create_config() {
589 /// use aws_config::AppName;
590 /// let config = aws_config::from_env()
591 /// .app_name(AppName::new("my-app-name").expect("valid app name"))
592 /// .load().await;
593 /// # }
594 /// ```
595 pub fn app_name(mut self, app_name: AppName) -> Self {
596 self.app_name = Some(app_name);
597 self
598 }
599
600 /// Provides the ability to programmatically override the profile files that get loaded by the SDK.
601 ///
602 /// The [`Default`] for `ProfileFiles` includes the default SDK config and credential files located in
603 /// `~/.aws/config` and `~/.aws/credentials` respectively.
604 ///
605 /// Any number of config and credential files may be added to the `ProfileFiles` file set, with the
606 /// only requirement being that there is at least one of each. Profile file locations will produce an
607 /// error if they don't exist, but the default config/credentials files paths are exempt from this validation.
608 ///
609 /// # Example: Using a custom profile file path
610 ///
611 /// ```no_run
612 /// use aws_config::profile::{ProfileFileCredentialsProvider, ProfileFileRegionProvider};
613 /// use aws_config::profile::profile_file::{ProfileFiles, ProfileFileKind};
614 ///
615 /// # async fn example() {
616 /// let profile_files = ProfileFiles::builder()
617 /// .with_file(ProfileFileKind::Credentials, "some/path/to/credentials-file")
618 /// .build();
619 /// let sdk_config = aws_config::from_env()
620 /// .profile_files(profile_files)
621 /// .load()
622 /// .await;
623 /// # }
624 #[allow(deprecated)]
625 pub fn profile_files(mut self, profile_files: ProfileFiles) -> Self {
626 self.profile_files_override = Some(profile_files);
627 self
628 }
629
630 /// Override the profile name used by configuration providers
631 ///
632 /// Profile name is selected from an ordered list of sources:
633 /// 1. This override.
634 /// 2. The value of the `AWS_PROFILE` environment variable.
635 /// 3. `default`
636 ///
637 /// Each AWS profile has a name. For example, in the file below, the profiles are named
638 /// `dev`, `prod` and `staging`:
639 /// ```ini
640 /// [dev]
641 /// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
642 ///
643 /// [staging]
644 /// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
645 ///
646 /// [prod]
647 /// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
648 /// ```
649 ///
650 /// See [Named profiles](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html)
651 /// for more information about naming profiles.
652 ///
653 /// # Example: Using a custom profile name
654 ///
655 /// ```no_run
656 /// use aws_config::profile::{ProfileFileCredentialsProvider, ProfileFileRegionProvider};
657 ///
658 /// # async fn example() {
659 /// let sdk_config = aws_config::from_env()
660 /// .profile_name("prod")
661 /// .load()
662 /// .await;
663 /// # }
664 pub fn profile_name(mut self, profile_name: impl Into<String>) -> Self {
665 self.profile_name_override = Some(profile_name.into());
666 self
667 }
668
669 #[doc = docs_for!(account_id_endpoint_mode)]
670 pub fn account_id_endpoint_mode(
671 mut self,
672 account_id_endpoint_mode: AccountIdEndpointMode,
673 ) -> Self {
674 self.account_id_endpoint_mode = Some(account_id_endpoint_mode);
675 self
676 }
677
678 /// Override the endpoint URL used for **all** AWS services.
679 ///
680 /// This method will override the endpoint URL used for **all** AWS services. This primarily
681 /// exists to set a static endpoint for tools like `LocalStack`. When sending requests to
682 /// production AWS services, this method should only be used for service-specific behavior.
683 ///
684 /// When this method is used, the [`Region`](aws_types::region::Region) is only used for signing;
685 /// It is **not** used to route the request.
686 ///
687 /// # Examples
688 ///
689 /// Use a static endpoint for all services
690 /// ```no_run
691 /// # async fn create_config() {
692 /// let sdk_config = aws_config::from_env()
693 /// .endpoint_url("http://localhost:1234")
694 /// .load()
695 /// .await;
696 /// # }
697 pub fn endpoint_url(mut self, endpoint_url: impl Into<String>) -> Self {
698 self.endpoint_url = Some(endpoint_url.into());
699 self
700 }
701
702 #[doc = docs_for!(use_fips)]
703 pub fn use_fips(mut self, use_fips: bool) -> Self {
704 self.use_fips = Some(use_fips);
705 self
706 }
707
708 #[doc = docs_for!(use_dual_stack)]
709 pub fn use_dual_stack(mut self, use_dual_stack: bool) -> Self {
710 self.use_dual_stack = Some(use_dual_stack);
711 self
712 }
713
714 #[doc = docs_for!(disable_request_compression)]
715 pub fn disable_request_compression(mut self, disable_request_compression: bool) -> Self {
716 self.disable_request_compression = Some(disable_request_compression);
717 self
718 }
719
720 #[doc = docs_for!(request_min_compression_size_bytes)]
721 pub fn request_min_compression_size_bytes(mut self, size: u32) -> Self {
722 self.request_min_compression_size_bytes = Some(size);
723 self
724 }
725
726 /// Override the [`StalledStreamProtectionConfig`] used to build [`SdkConfig`].
727 ///
728 /// This configures stalled stream protection. When enabled, download streams
729 /// that stop (stream no data) for longer than a configured grace period will return an error.
730 ///
731 /// By default, streams that transmit less than one byte per-second for five seconds will
732 /// be cancelled.
733 ///
734 /// _Note_: When an override is provided, the default implementation is replaced.
735 ///
736 /// # Examples
737 /// ```no_run
738 /// # async fn create_config() {
739 /// use aws_config::stalled_stream_protection::StalledStreamProtectionConfig;
740 /// use std::time::Duration;
741 /// let config = aws_config::from_env()
742 /// .stalled_stream_protection(
743 /// StalledStreamProtectionConfig::enabled()
744 /// .grace_period(Duration::from_secs(1))
745 /// .build()
746 /// )
747 /// .load()
748 /// .await;
749 /// # }
750 /// ```
751 pub fn stalled_stream_protection(
752 mut self,
753 stalled_stream_protection_config: StalledStreamProtectionConfig,
754 ) -> Self {
755 self.stalled_stream_protection_config = Some(stalled_stream_protection_config);
756 self
757 }
758
759 /// Set the checksum calculation strategy to use when making requests.
760 /// # Examples
761 /// ```
762 /// use aws_types::SdkConfig;
763 /// use aws_smithy_types::checksum_config::RequestChecksumCalculation;
764 /// let config = SdkConfig::builder().request_checksum_calculation(RequestChecksumCalculation::WhenSupported).build();
765 /// ```
766 pub fn request_checksum_calculation(
767 mut self,
768 request_checksum_calculation: RequestChecksumCalculation,
769 ) -> Self {
770 self.request_checksum_calculation = Some(request_checksum_calculation);
771 self
772 }
773
774 /// Set the checksum calculation strategy to use for responses.
775 /// # Examples
776 /// ```
777 /// use aws_types::SdkConfig;
778 /// use aws_smithy_types::checksum_config::ResponseChecksumValidation;
779 /// let config = SdkConfig::builder().response_checksum_validation(ResponseChecksumValidation::WhenSupported).build();
780 /// ```
781 pub fn response_checksum_validation(
782 mut self,
783 response_checksum_validation: ResponseChecksumValidation,
784 ) -> Self {
785 self.response_checksum_validation = Some(response_checksum_validation);
786 self
787 }
788
789 /// Load the default configuration chain
790 ///
791 /// If fields have been overridden during builder construction, the override values will be used.
792 ///
793 /// Otherwise, the default values for each field will be provided.
794 ///
795 /// NOTE: When an override is provided, the default implementation is **not** used as a fallback.
796 /// This means that if you provide a region provider that does not return a region, no region will
797 /// be set in the resulting [`SdkConfig`].
798 pub async fn load(self) -> SdkConfig {
799 let time_source = self.time_source.unwrap_or_default();
800
801 let sleep_impl = if self.sleep.is_some() {
802 self.sleep
803 } else {
804 if default_async_sleep().is_none() {
805 tracing::warn!(
806 "An implementation of AsyncSleep was requested by calling default_async_sleep \
807 but no default was set.
808 This happened when ConfigLoader::load was called during Config construction. \
809 You can fix this by setting a sleep_impl on the ConfigLoader before calling \
810 load or by enabling the rt-tokio feature"
811 );
812 }
813 default_async_sleep()
814 };
815
816 let conf = self
817 .provider_config
818 .unwrap_or_else(|| {
819 let mut config = ProviderConfig::init(time_source.clone(), sleep_impl.clone())
820 .with_fs(self.fs.unwrap_or_default())
821 .with_env(self.env.unwrap_or_default());
822 if let Some(http_client) = self.http_client.clone() {
823 config = config.with_http_client(http_client);
824 }
825 config
826 })
827 .with_profile_config(self.profile_files_override, self.profile_name_override);
828
829 let use_fips = if let Some(use_fips) = self.use_fips {
830 Some(use_fips)
831 } else {
832 use_fips::use_fips_provider(&conf).await
833 };
834
835 let use_dual_stack = if let Some(use_dual_stack) = self.use_dual_stack {
836 Some(use_dual_stack)
837 } else {
838 use_dual_stack::use_dual_stack_provider(&conf).await
839 };
840
841 let conf = conf
842 .with_use_fips(use_fips)
843 .with_use_dual_stack(use_dual_stack);
844
845 let region = if let Some(provider) = self.region {
846 provider.region().await
847 } else {
848 region::Builder::default()
849 .configure(&conf)
850 .build()
851 .region()
852 .await
853 };
854 let conf = conf.with_region(region.clone());
855
856 let retry_config = if let Some(retry_config) = self.retry_config {
857 retry_config
858 } else {
859 retry_config::default_provider()
860 .configure(&conf)
861 .retry_config()
862 .await
863 };
864
865 let app_name = if self.app_name.is_some() {
866 self.app_name
867 } else {
868 app_name::default_provider()
869 .configure(&conf)
870 .app_name()
871 .await
872 };
873
874 let disable_request_compression = if self.disable_request_compression.is_some() {
875 self.disable_request_compression
876 } else {
877 disable_request_compression::disable_request_compression_provider(&conf).await
878 };
879
880 let request_min_compression_size_bytes =
881 if self.request_min_compression_size_bytes.is_some() {
882 self.request_min_compression_size_bytes
883 } else {
884 request_min_compression_size_bytes::request_min_compression_size_bytes_provider(
885 &conf,
886 )
887 .await
888 };
889
890 let base_config = timeout_config::default_provider()
891 .configure(&conf)
892 .timeout_config()
893 .await;
894 let mut timeout_config = self
895 .timeout_config
896 .unwrap_or_else(|| TimeoutConfig::builder().build());
897 timeout_config.take_defaults_from(&base_config);
898
899 let credentials_provider = match self.credentials_provider {
900 TriStateOption::Set(provider) => Some(provider),
901 TriStateOption::NotSet => {
902 let mut builder =
903 credentials::DefaultCredentialsChain::builder().configure(conf.clone());
904 builder.set_region(region.clone());
905 Some(SharedCredentialsProvider::new(builder.build().await))
906 }
907 TriStateOption::ExplicitlyUnset => None,
908 };
909
910 let profiles = conf.profile().await;
911 let service_config = EnvServiceConfig {
912 env: conf.env(),
913 env_config_sections: profiles.cloned().unwrap_or_default(),
914 };
915 let mut builder = SdkConfig::builder()
916 .region(region.clone())
917 .retry_config(retry_config)
918 .timeout_config(timeout_config)
919 .time_source(time_source)
920 .service_config(service_config);
921
922 // If an endpoint URL is set programmatically, then our work is done.
923 let endpoint_url = if self.endpoint_url.is_some() {
924 builder.insert_origin("endpoint_url", Origin::shared_config());
925 self.endpoint_url
926 } else {
927 // Otherwise, check to see if we should ignore EP URLs set in the environment.
928 let ignore_configured_endpoint_urls =
929 ignore_ep::ignore_configured_endpoint_urls_provider(&conf)
930 .await
931 .unwrap_or_default();
932
933 if ignore_configured_endpoint_urls {
934 // If yes, log a trace and return `None`.
935 tracing::trace!(
936 "`ignore_configured_endpoint_urls` is set, any endpoint URLs configured in the environment will be ignored. \
937 NOTE: Endpoint URLs set programmatically WILL still be respected"
938 );
939 None
940 } else {
941 // Otherwise, attempt to resolve one.
942 let (v, origin) = endpoint_url::endpoint_url_provider_with_origin(&conf).await;
943 builder.insert_origin("endpoint_url", origin);
944 v
945 }
946 };
947
948 let token_provider = match self.token_provider {
949 Some(provider) => {
950 builder.insert_origin("token_provider", Origin::shared_config());
951 Some(provider)
952 }
953 None => {
954 #[cfg(feature = "sso")]
955 {
956 let mut builder =
957 crate::default_provider::token::DefaultTokenChain::builder()
958 .configure(conf.clone());
959 builder.set_region(region);
960 Some(SharedTokenProvider::new(builder.build().await))
961 }
962 #[cfg(not(feature = "sso"))]
963 {
964 None
965 }
966 // Not setting `Origin` in this arm, and that's good for now as long as we know
967 // it's not programmatically set in the shared config.
968 // We can consider adding `Origin::Default` if needed.
969 }
970 };
971
972 builder.set_endpoint_url(endpoint_url);
973 builder.set_behavior_version(self.behavior_version);
974 builder.set_http_client(self.http_client);
975 builder.set_app_name(app_name);
976
977 let identity_cache = match self.identity_cache {
978 None => match self.behavior_version {
979 #[allow(deprecated)]
980 Some(bv) if bv.is_at_least(BehaviorVersion::v2024_03_28()) => {
981 Some(IdentityCache::lazy().build())
982 }
983 _ => None,
984 },
985 Some(user_cache) => Some(user_cache),
986 };
987
988 let request_checksum_calculation =
989 if let Some(request_checksum_calculation) = self.request_checksum_calculation {
990 Some(request_checksum_calculation)
991 } else {
992 checksums::request_checksum_calculation_provider(&conf).await
993 };
994
995 let response_checksum_validation =
996 if let Some(response_checksum_validation) = self.response_checksum_validation {
997 Some(response_checksum_validation)
998 } else {
999 checksums::response_checksum_validation_provider(&conf).await
1000 };
1001
1002 let account_id_endpoint_mode =
1003 if let Some(acccount_id_endpoint_mode) = self.account_id_endpoint_mode {
1004 Some(acccount_id_endpoint_mode)
1005 } else {
1006 account_id_endpoint_mode::account_id_endpoint_mode_provider(&conf).await
1007 };
1008
1009 let auth_scheme_preference =
1010 if let Some(auth_scheme_preference) = self.auth_scheme_preference {
1011 builder.insert_origin("auth_scheme_preference", Origin::shared_config());
1012 Some(auth_scheme_preference)
1013 } else {
1014 auth_scheme_preference::auth_scheme_preference_provider(&conf).await
1015 // Not setting `Origin` in this arm, and that's good for now as long as we know
1016 // it's not programmatically set in the shared config.
1017 };
1018
1019 let sigv4a_signing_region_set =
1020 if let Some(sigv4a_signing_region_set) = self.sigv4a_signing_region_set {
1021 Some(sigv4a_signing_region_set)
1022 } else {
1023 sigv4a_signing_region_set::sigv4a_signing_region_set_provider(&conf).await
1024 };
1025
1026 builder.set_request_checksum_calculation(request_checksum_calculation);
1027 builder.set_response_checksum_validation(response_checksum_validation);
1028 builder.set_identity_cache(identity_cache);
1029 builder.set_credentials_provider(credentials_provider);
1030 builder.set_token_provider(token_provider);
1031 builder.set_sleep_impl(sleep_impl);
1032 builder.set_use_fips(use_fips);
1033 builder.set_use_dual_stack(use_dual_stack);
1034 builder.set_disable_request_compression(disable_request_compression);
1035 builder.set_request_min_compression_size_bytes(request_min_compression_size_bytes);
1036 builder.set_stalled_stream_protection(self.stalled_stream_protection_config);
1037 builder.set_account_id_endpoint_mode(account_id_endpoint_mode);
1038 builder.set_auth_scheme_preference(auth_scheme_preference);
1039 builder.set_sigv4a_signing_region_set(sigv4a_signing_region_set);
1040 builder.build()
1041 }
1042 }
1043
1044 #[cfg(test)]
1045 impl ConfigLoader {
1046 pub(crate) fn env(mut self, env: Env) -> Self {
1047 self.env = Some(env);
1048 self
1049 }
1050
1051 pub(crate) fn fs(mut self, fs: Fs) -> Self {
1052 self.fs = Some(fs);
1053 self
1054 }
1055 }
1056
1057 #[cfg(test)]
1058 mod test {
1059 #[allow(deprecated)]
1060 use crate::profile::profile_file::{ProfileFileKind, ProfileFiles};
1061 use crate::test_case::{no_traffic_client, InstantSleep};
1062 use crate::BehaviorVersion;
1063 use crate::{defaults, ConfigLoader};
1064 use aws_credential_types::provider::ProvideCredentials;
1065 use aws_smithy_async::rt::sleep::TokioSleep;
1066 use aws_smithy_http_client::test_util::{infallible_client_fn, NeverClient};
1067 use aws_smithy_runtime::test_util::capture_test_logs::capture_test_logs;
1068 use aws_types::app_name::AppName;
1069 use aws_types::origin::Origin;
1070 use aws_types::os_shim_internal::{Env, Fs};
1071 use aws_types::sdk_config::{RequestChecksumCalculation, ResponseChecksumValidation};
1072 use std::sync::atomic::{AtomicUsize, Ordering};
1073 use std::sync::Arc;
1074
1075 #[tokio::test]
1076 async fn provider_config_used() {
1077 let (_guard, logs_rx) = capture_test_logs();
1078 let env = Env::from_slice(&[
1079 ("AWS_MAX_ATTEMPTS", "10"),
1080 ("AWS_REGION", "us-west-4"),
1081 ("AWS_ACCESS_KEY_ID", "akid"),
1082 ("AWS_SECRET_ACCESS_KEY", "secret"),
1083 ]);
1084 let fs =
1085 Fs::from_slice(&[("test_config", "[profile custom]\nsdk-ua-app-id = correct")]);
1086 let loader = defaults(BehaviorVersion::latest())
1087 .sleep_impl(TokioSleep::new())
1088 .env(env)
1089 .fs(fs)
1090 .http_client(NeverClient::new())
1091 .profile_name("custom")
1092 .profile_files(
1093 #[allow(deprecated)]
1094 ProfileFiles::builder()
1095 .with_file(
1096 #[allow(deprecated)]
1097 ProfileFileKind::Config,
1098 "test_config",
1099 )
1100 .build(),
1101 )
1102 .load()
1103 .await;
1104 assert_eq!(10, loader.retry_config().unwrap().max_attempts());
1105 assert_eq!("us-west-4", loader.region().unwrap().as_ref());
1106 assert_eq!(
1107 "akid",
1108 loader
1109 .credentials_provider()
1110 .unwrap()
1111 .provide_credentials()
1112 .await
1113 .unwrap()
1114 .access_key_id(),
1115 );
1116 assert_eq!(Some(&AppName::new("correct").unwrap()), loader.app_name());
1117
1118 let num_config_loader_logs = logs_rx.contents()
1119 .lines()
1120 // The logger uses fancy formatting, so we have to account for that.
1121 .filter(|l| l.contains("config file loaded \u{1b}[3mpath\u{1b}[0m\u{1b}[2m=\u{1b}[0mSome(\"test_config\") \u{1b}[3msize\u{1b}[0m\u{1b}[2m=\u{1b}"))
1122 .count();
1123
1124 match num_config_loader_logs {
1125 0 => panic!("no config file logs found!"),
1126 1 => (),
1127 more => panic!("the config file was parsed more than once! (parsed {more})",),
1128 };
1129 }
1130
1131 fn base_conf() -> ConfigLoader {
1132 defaults(BehaviorVersion::latest())
1133 .sleep_impl(InstantSleep)
1134 .http_client(no_traffic_client())
1135 }
1136
1137 #[tokio::test]
1138 async fn test_origin_programmatic() {
1139 let _ = tracing_subscriber::fmt::try_init();
1140 let loader = base_conf()
1141 .test_credentials()
1142 .profile_name("custom")
1143 .profile_files(
1144 #[allow(deprecated)]
1145 ProfileFiles::builder()
1146 .with_contents(
1147 #[allow(deprecated)]
1148 ProfileFileKind::Config,
1149 "[profile custom]\nendpoint_url = http://localhost:8989",
1150 )
1151 .build(),
1152 )
1153 .endpoint_url("http://localhost:1111")
1154 .load()
1155 .await;
1156 assert_eq!(Origin::shared_config(), loader.get_origin("endpoint_url"));
1157 }
1158
1159 #[tokio::test]
1160 async fn test_origin_env() {
1161 let _ = tracing_subscriber::fmt::try_init();
1162 let env = Env::from_slice(&[("AWS_ENDPOINT_URL", "http://localhost:7878")]);
1163 let loader = base_conf()
1164 .test_credentials()
1165 .env(env)
1166 .profile_name("custom")
1167 .profile_files(
1168 #[allow(deprecated)]
1169 ProfileFiles::builder()
1170 .with_contents(
1171 #[allow(deprecated)]
1172 ProfileFileKind::Config,
1173 "[profile custom]\nendpoint_url = http://localhost:8989",
1174 )
1175 .build(),
1176 )
1177 .load()
1178 .await;
1179 assert_eq!(
1180 Origin::shared_environment_variable(),
1181 loader.get_origin("endpoint_url")
1182 );
1183 }
1184
1185 #[tokio::test]
1186 async fn test_origin_fs() {
1187 let _ = tracing_subscriber::fmt::try_init();
1188 let loader = base_conf()
1189 .test_credentials()
1190 .profile_name("custom")
1191 .profile_files(
1192 #[allow(deprecated)]
1193 ProfileFiles::builder()
1194 .with_contents(
1195 #[allow(deprecated)]
1196 ProfileFileKind::Config,
1197 "[profile custom]\nendpoint_url = http://localhost:8989",
1198 )
1199 .build(),
1200 )
1201 .load()
1202 .await;
1203 assert_eq!(
1204 Origin::shared_profile_file(),
1205 loader.get_origin("endpoint_url")
1206 );
1207 }
1208
1209 #[tokio::test]
1210 async fn load_use_fips() {
1211 let conf = base_conf().use_fips(true).load().await;
1212 assert_eq!(Some(true), conf.use_fips());
1213 }
1214
1215 #[tokio::test]
1216 async fn load_dual_stack() {
1217 let conf = base_conf().use_dual_stack(false).load().await;
1218 assert_eq!(Some(false), conf.use_dual_stack());
1219
1220 let conf = base_conf().load().await;
1221 assert_eq!(None, conf.use_dual_stack());
1222 }
1223
1224 #[tokio::test]
1225 async fn load_disable_request_compression() {
1226 let conf = base_conf().disable_request_compression(true).load().await;
1227 assert_eq!(Some(true), conf.disable_request_compression());
1228
1229 let conf = base_conf().load().await;
1230 assert_eq!(None, conf.disable_request_compression());
1231 }
1232
1233 #[tokio::test]
1234 async fn load_request_min_compression_size_bytes() {
1235 let conf = base_conf()
1236 .request_min_compression_size_bytes(99)
1237 .load()
1238 .await;
1239 assert_eq!(Some(99), conf.request_min_compression_size_bytes());
1240
1241 let conf = base_conf().load().await;
1242 assert_eq!(None, conf.request_min_compression_size_bytes());
1243 }
1244
1245 #[tokio::test]
1246 async fn app_name() {
1247 let app_name = AppName::new("my-app-name").unwrap();
1248 let conf = base_conf().app_name(app_name.clone()).load().await;
1249 assert_eq!(Some(&app_name), conf.app_name());
1250 }
1251
1252 #[tokio::test]
1253 async fn request_checksum_calculation() {
1254 let conf = base_conf()
1255 .request_checksum_calculation(RequestChecksumCalculation::WhenRequired)
1256 .load()
1257 .await;
1258 assert_eq!(
1259 Some(RequestChecksumCalculation::WhenRequired),
1260 conf.request_checksum_calculation()
1261 );
1262 }
1263
1264 #[tokio::test]
1265 async fn response_checksum_validation() {
1266 let conf = base_conf()
1267 .response_checksum_validation(ResponseChecksumValidation::WhenRequired)
1268 .load()
1269 .await;
1270 assert_eq!(
1271 Some(ResponseChecksumValidation::WhenRequired),
1272 conf.response_checksum_validation()
1273 );
1274 }
1275
1276 #[cfg(feature = "default-https-client")]
1277 #[tokio::test]
1278 async fn disable_default_credentials() {
1279 let config = defaults(BehaviorVersion::latest())
1280 .no_credentials()
1281 .load()
1282 .await;
1283 assert!(config.credentials_provider().is_none());
1284 }
1285
1286 #[cfg(feature = "default-https-client")]
1287 #[tokio::test]
1288 async fn identity_cache_defaulted() {
1289 let config = defaults(BehaviorVersion::latest()).load().await;
1290
1291 assert!(config.identity_cache().is_some());
1292 }
1293
1294 #[cfg(feature = "default-https-client")]
1295 #[allow(deprecated)]
1296 #[tokio::test]
1297 async fn identity_cache_old_behavior_version() {
1298 let config = defaults(BehaviorVersion::v2023_11_09()).load().await;
1299
1300 assert!(config.identity_cache().is_none());
1301 }
1302
1303 #[tokio::test]
1304 async fn connector_is_shared() {
1305 let num_requests = Arc::new(AtomicUsize::new(0));
1306 let movable = num_requests.clone();
1307 let http_client = infallible_client_fn(move |_req| {
1308 movable.fetch_add(1, Ordering::Relaxed);
1309 http::Response::new("ok!")
1310 });
1311 let config = defaults(BehaviorVersion::latest())
1312 .fs(Fs::from_slice(&[]))
1313 .env(Env::from_slice(&[]))
1314 .http_client(http_client.clone())
1315 .load()
1316 .await;
1317 config
1318 .credentials_provider()
1319 .unwrap()
1320 .provide_credentials()
1321 .await
1322 .expect_err("did not expect credentials to be loaded—no traffic is allowed");
1323 let num_requests = num_requests.load(Ordering::Relaxed);
1324 assert!(num_requests > 0, "{}", num_requests);
1325 }
1326
1327 #[tokio::test]
1328 async fn endpoint_urls_may_be_ignored_from_env() {
1329 let fs = Fs::from_slice(&[(
1330 "test_config",
1331 "[profile custom]\nendpoint_url = http://profile",
1332 )]);
1333 let env = Env::from_slice(&[("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "true")]);
1334
1335 let conf = base_conf().use_dual_stack(false).load().await;
1336 assert_eq!(Some(false), conf.use_dual_stack());
1337
1338 let conf = base_conf().load().await;
1339 assert_eq!(None, conf.use_dual_stack());
1340
1341 // Check that we get nothing back because the env said we should ignore endpoints
1342 let config = base_conf()
1343 .fs(fs.clone())
1344 .env(env)
1345 .profile_name("custom")
1346 .profile_files(
1347 #[allow(deprecated)]
1348 ProfileFiles::builder()
1349 .with_file(
1350 #[allow(deprecated)]
1351 ProfileFileKind::Config,
1352 "test_config",
1353 )
1354 .build(),
1355 )
1356 .load()
1357 .await;
1358 assert_eq!(None, config.endpoint_url());
1359
1360 // Check that without the env, we DO get something back
1361 let config = base_conf()
1362 .fs(fs)
1363 .profile_name("custom")
1364 .profile_files(
1365 #[allow(deprecated)]
1366 ProfileFiles::builder()
1367 .with_file(
1368 #[allow(deprecated)]
1369 ProfileFileKind::Config,
1370 "test_config",
1371 )
1372 .build(),
1373 )
1374 .load()
1375 .await;
1376 assert_eq!(Some("http://profile"), config.endpoint_url());
1377 }
1378
1379 #[tokio::test]
1380 async fn endpoint_urls_may_be_ignored_from_profile() {
1381 let fs = Fs::from_slice(&[(
1382 "test_config",
1383 "[profile custom]\nignore_configured_endpoint_urls = true",
1384 )]);
1385 let env = Env::from_slice(&[("AWS_ENDPOINT_URL", "http://environment")]);
1386
1387 // Check that we get nothing back because the profile said we should ignore endpoints
1388 let config = base_conf()
1389 .fs(fs)
1390 .env(env.clone())
1391 .profile_name("custom")
1392 .profile_files(
1393 #[allow(deprecated)]
1394 ProfileFiles::builder()
1395 .with_file(
1396 #[allow(deprecated)]
1397 ProfileFileKind::Config,
1398 "test_config",
1399 )
1400 .build(),
1401 )
1402 .load()
1403 .await;
1404 assert_eq!(None, config.endpoint_url());
1405
1406 // Check that without the profile, we DO get something back
1407 let config = base_conf().env(env).load().await;
1408 assert_eq!(Some("http://environment"), config.endpoint_url());
1409 }
1410
1411 #[tokio::test]
1412 async fn programmatic_endpoint_urls_may_not_be_ignored() {
1413 let fs = Fs::from_slice(&[(
1414 "test_config",
1415 "[profile custom]\nignore_configured_endpoint_urls = true",
1416 )]);
1417 let env = Env::from_slice(&[("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "true")]);
1418
1419 // Check that we get something back because we explicitly set the loader's endpoint URL
1420 let config = base_conf()
1421 .fs(fs)
1422 .env(env)
1423 .endpoint_url("http://localhost")
1424 .profile_name("custom")
1425 .profile_files(
1426 #[allow(deprecated)]
1427 ProfileFiles::builder()
1428 .with_file(
1429 #[allow(deprecated)]
1430 ProfileFileKind::Config,
1431 "test_config",
1432 )
1433 .build(),
1434 )
1435 .load()
1436 .await;
1437 assert_eq!(Some("http://localhost"), config.endpoint_url());
1438 }
1439 }
1440}