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_behavior_version(self.behavior_version)
828                .with_profile_config(self.profile_files_override, self.profile_name_override);
829
830            let use_fips = if let Some(use_fips) = self.use_fips {
831                Some(use_fips)
832            } else {
833                use_fips::use_fips_provider(&conf).await
834            };
835
836            let use_dual_stack = if let Some(use_dual_stack) = self.use_dual_stack {
837                Some(use_dual_stack)
838            } else {
839                use_dual_stack::use_dual_stack_provider(&conf).await
840            };
841
842            let conf = conf
843                .with_use_fips(use_fips)
844                .with_use_dual_stack(use_dual_stack);
845
846            let region = if let Some(provider) = self.region {
847                provider.region().await
848            } else {
849                region::Builder::default()
850                    .configure(&conf)
851                    .build()
852                    .region()
853                    .await
854            };
855            let conf = conf.with_region(region.clone());
856
857            let retry_config = if let Some(retry_config) = self.retry_config {
858                retry_config
859            } else {
860                retry_config::default_provider()
861                    .configure(&conf)
862                    .retry_config()
863                    .await
864            };
865
866            let app_name = if self.app_name.is_some() {
867                self.app_name
868            } else {
869                app_name::default_provider()
870                    .configure(&conf)
871                    .app_name()
872                    .await
873            };
874
875            let disable_request_compression = if self.disable_request_compression.is_some() {
876                self.disable_request_compression
877            } else {
878                disable_request_compression::disable_request_compression_provider(&conf).await
879            };
880
881            let request_min_compression_size_bytes =
882                if self.request_min_compression_size_bytes.is_some() {
883                    self.request_min_compression_size_bytes
884                } else {
885                    request_min_compression_size_bytes::request_min_compression_size_bytes_provider(
886                        &conf,
887                    )
888                    .await
889                };
890
891            let base_config = timeout_config::default_provider()
892                .configure(&conf)
893                .timeout_config()
894                .await;
895            let mut timeout_config = self
896                .timeout_config
897                .unwrap_or_else(|| TimeoutConfig::builder().build());
898            timeout_config.take_defaults_from(&base_config);
899
900            let credentials_provider = match self.credentials_provider {
901                TriStateOption::Set(provider) => Some(provider),
902                TriStateOption::NotSet => {
903                    let mut builder =
904                        credentials::DefaultCredentialsChain::builder().configure(conf.clone());
905                    builder.set_region(region.clone());
906                    Some(SharedCredentialsProvider::new(builder.build().await))
907                }
908                TriStateOption::ExplicitlyUnset => None,
909            };
910
911            let profiles = conf.profile().await;
912            let service_config = EnvServiceConfig {
913                env: conf.env(),
914                env_config_sections: profiles.cloned().unwrap_or_default(),
915            };
916            let mut builder = SdkConfig::builder()
917                .region(region.clone())
918                .retry_config(retry_config)
919                .timeout_config(timeout_config)
920                .time_source(time_source)
921                .service_config(service_config);
922
923            // If an endpoint URL is set programmatically, then our work is done.
924            let endpoint_url = if self.endpoint_url.is_some() {
925                builder.insert_origin("endpoint_url", Origin::shared_config());
926                self.endpoint_url
927            } else {
928                // Otherwise, check to see if we should ignore EP URLs set in the environment.
929                let ignore_configured_endpoint_urls =
930                    ignore_ep::ignore_configured_endpoint_urls_provider(&conf)
931                        .await
932                        .unwrap_or_default();
933
934                if ignore_configured_endpoint_urls {
935                    // If yes, log a trace and return `None`.
936                    tracing::trace!(
937                        "`ignore_configured_endpoint_urls` is set, any endpoint URLs configured in the environment will be ignored. \
938                        NOTE: Endpoint URLs set programmatically WILL still be respected"
939                    );
940                    None
941                } else {
942                    // Otherwise, attempt to resolve one.
943                    let (v, origin) = endpoint_url::endpoint_url_provider_with_origin(&conf).await;
944                    builder.insert_origin("endpoint_url", origin);
945                    v
946                }
947            };
948
949            let token_provider = match self.token_provider {
950                Some(provider) => {
951                    builder.insert_origin("token_provider", Origin::shared_config());
952                    Some(provider)
953                }
954                None => {
955                    #[cfg(feature = "sso")]
956                    {
957                        let mut builder =
958                            crate::default_provider::token::DefaultTokenChain::builder()
959                                .configure(conf.clone());
960                        builder.set_region(region);
961                        Some(SharedTokenProvider::new(builder.build().await))
962                    }
963                    #[cfg(not(feature = "sso"))]
964                    {
965                        None
966                    }
967                    // Not setting `Origin` in this arm, and that's good for now as long as we know
968                    // it's not programmatically set in the shared config.
969                    // We can consider adding `Origin::Default` if needed.
970                }
971            };
972
973            builder.set_endpoint_url(endpoint_url);
974            builder.set_behavior_version(self.behavior_version);
975            builder.set_http_client(self.http_client);
976            builder.set_app_name(app_name);
977
978            let identity_cache = match self.identity_cache {
979                None => match self.behavior_version {
980                    #[allow(deprecated)]
981                    Some(bv) if bv.is_at_least(BehaviorVersion::v2024_03_28()) => {
982                        Some(IdentityCache::lazy().build())
983                    }
984                    _ => None,
985                },
986                Some(user_cache) => Some(user_cache),
987            };
988
989            let request_checksum_calculation =
990                if let Some(request_checksum_calculation) = self.request_checksum_calculation {
991                    Some(request_checksum_calculation)
992                } else {
993                    checksums::request_checksum_calculation_provider(&conf).await
994                };
995
996            let response_checksum_validation =
997                if let Some(response_checksum_validation) = self.response_checksum_validation {
998                    Some(response_checksum_validation)
999                } else {
1000                    checksums::response_checksum_validation_provider(&conf).await
1001                };
1002
1003            let account_id_endpoint_mode =
1004                if let Some(acccount_id_endpoint_mode) = self.account_id_endpoint_mode {
1005                    Some(acccount_id_endpoint_mode)
1006                } else {
1007                    account_id_endpoint_mode::account_id_endpoint_mode_provider(&conf).await
1008                };
1009
1010            let auth_scheme_preference =
1011                if let Some(auth_scheme_preference) = self.auth_scheme_preference {
1012                    builder.insert_origin("auth_scheme_preference", Origin::shared_config());
1013                    Some(auth_scheme_preference)
1014                } else {
1015                    auth_scheme_preference::auth_scheme_preference_provider(&conf).await
1016                    // Not setting `Origin` in this arm, and that's good for now as long as we know
1017                    // it's not programmatically set in the shared config.
1018                };
1019
1020            let sigv4a_signing_region_set =
1021                if let Some(sigv4a_signing_region_set) = self.sigv4a_signing_region_set {
1022                    Some(sigv4a_signing_region_set)
1023                } else {
1024                    sigv4a_signing_region_set::sigv4a_signing_region_set_provider(&conf).await
1025                };
1026
1027            builder.set_request_checksum_calculation(request_checksum_calculation);
1028            builder.set_response_checksum_validation(response_checksum_validation);
1029            builder.set_identity_cache(identity_cache);
1030            builder.set_credentials_provider(credentials_provider);
1031            builder.set_token_provider(token_provider);
1032            builder.set_sleep_impl(sleep_impl);
1033            builder.set_use_fips(use_fips);
1034            builder.set_use_dual_stack(use_dual_stack);
1035            builder.set_disable_request_compression(disable_request_compression);
1036            builder.set_request_min_compression_size_bytes(request_min_compression_size_bytes);
1037            builder.set_stalled_stream_protection(self.stalled_stream_protection_config);
1038            builder.set_account_id_endpoint_mode(account_id_endpoint_mode);
1039            builder.set_auth_scheme_preference(auth_scheme_preference);
1040            builder.set_sigv4a_signing_region_set(sigv4a_signing_region_set);
1041            builder.build()
1042        }
1043    }
1044
1045    #[cfg(test)]
1046    impl ConfigLoader {
1047        pub(crate) fn env(mut self, env: Env) -> Self {
1048            self.env = Some(env);
1049            self
1050        }
1051
1052        pub(crate) fn fs(mut self, fs: Fs) -> Self {
1053            self.fs = Some(fs);
1054            self
1055        }
1056    }
1057
1058    #[cfg(test)]
1059    mod test {
1060        #[allow(deprecated)]
1061        use crate::profile::profile_file::{ProfileFileKind, ProfileFiles};
1062        use crate::test_case::{no_traffic_client, InstantSleep};
1063        use crate::BehaviorVersion;
1064        use crate::{defaults, ConfigLoader};
1065        use aws_credential_types::provider::ProvideCredentials;
1066        use aws_smithy_async::rt::sleep::TokioSleep;
1067        use aws_smithy_http_client::test_util::{infallible_client_fn, NeverClient};
1068        use aws_smithy_runtime::test_util::capture_test_logs::capture_test_logs;
1069        use aws_types::app_name::AppName;
1070        use aws_types::origin::Origin;
1071        use aws_types::os_shim_internal::{Env, Fs};
1072        use aws_types::sdk_config::{RequestChecksumCalculation, ResponseChecksumValidation};
1073        use std::sync::atomic::{AtomicUsize, Ordering};
1074        use std::sync::Arc;
1075
1076        #[tokio::test]
1077        async fn provider_config_used() {
1078            let (_guard, logs_rx) = capture_test_logs();
1079            let env = Env::from_slice(&[
1080                ("AWS_MAX_ATTEMPTS", "10"),
1081                ("AWS_REGION", "us-west-4"),
1082                ("AWS_ACCESS_KEY_ID", "akid"),
1083                ("AWS_SECRET_ACCESS_KEY", "secret"),
1084            ]);
1085            let fs =
1086                Fs::from_slice(&[("test_config", "[profile custom]\nsdk-ua-app-id = correct")]);
1087            let loader = defaults(BehaviorVersion::latest())
1088                .sleep_impl(TokioSleep::new())
1089                .env(env)
1090                .fs(fs)
1091                .http_client(NeverClient::new())
1092                .profile_name("custom")
1093                .profile_files(
1094                    #[allow(deprecated)]
1095                    ProfileFiles::builder()
1096                        .with_file(
1097                            #[allow(deprecated)]
1098                            ProfileFileKind::Config,
1099                            "test_config",
1100                        )
1101                        .build(),
1102                )
1103                .load()
1104                .await;
1105            assert_eq!(10, loader.retry_config().unwrap().max_attempts());
1106            assert_eq!("us-west-4", loader.region().unwrap().as_ref());
1107            assert_eq!(
1108                "akid",
1109                loader
1110                    .credentials_provider()
1111                    .unwrap()
1112                    .provide_credentials()
1113                    .await
1114                    .unwrap()
1115                    .access_key_id(),
1116            );
1117            assert_eq!(Some(&AppName::new("correct").unwrap()), loader.app_name());
1118
1119            let num_config_loader_logs = logs_rx.contents()
1120                .lines()
1121                // The logger uses fancy formatting, so we have to account for that.
1122                .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}"))
1123                .count();
1124
1125            match num_config_loader_logs {
1126                0 => panic!("no config file logs found!"),
1127                1 => (),
1128                more => panic!("the config file was parsed more than once! (parsed {more})",),
1129            };
1130        }
1131
1132        fn base_conf() -> ConfigLoader {
1133            defaults(BehaviorVersion::latest())
1134                .sleep_impl(InstantSleep)
1135                .http_client(no_traffic_client())
1136        }
1137
1138        #[tokio::test]
1139        async fn test_origin_programmatic() {
1140            let _ = tracing_subscriber::fmt::try_init();
1141            let loader = base_conf()
1142                .test_credentials()
1143                .profile_name("custom")
1144                .profile_files(
1145                    #[allow(deprecated)]
1146                    ProfileFiles::builder()
1147                        .with_contents(
1148                            #[allow(deprecated)]
1149                            ProfileFileKind::Config,
1150                            "[profile custom]\nendpoint_url = http://localhost:8989",
1151                        )
1152                        .build(),
1153                )
1154                .endpoint_url("http://localhost:1111")
1155                .load()
1156                .await;
1157            assert_eq!(Origin::shared_config(), loader.get_origin("endpoint_url"));
1158        }
1159
1160        #[tokio::test]
1161        async fn test_origin_env() {
1162            let _ = tracing_subscriber::fmt::try_init();
1163            let env = Env::from_slice(&[("AWS_ENDPOINT_URL", "http://localhost:7878")]);
1164            let loader = base_conf()
1165                .test_credentials()
1166                .env(env)
1167                .profile_name("custom")
1168                .profile_files(
1169                    #[allow(deprecated)]
1170                    ProfileFiles::builder()
1171                        .with_contents(
1172                            #[allow(deprecated)]
1173                            ProfileFileKind::Config,
1174                            "[profile custom]\nendpoint_url = http://localhost:8989",
1175                        )
1176                        .build(),
1177                )
1178                .load()
1179                .await;
1180            assert_eq!(
1181                Origin::shared_environment_variable(),
1182                loader.get_origin("endpoint_url")
1183            );
1184        }
1185
1186        #[tokio::test]
1187        async fn test_origin_fs() {
1188            let _ = tracing_subscriber::fmt::try_init();
1189            let loader = base_conf()
1190                .test_credentials()
1191                .profile_name("custom")
1192                .profile_files(
1193                    #[allow(deprecated)]
1194                    ProfileFiles::builder()
1195                        .with_contents(
1196                            #[allow(deprecated)]
1197                            ProfileFileKind::Config,
1198                            "[profile custom]\nendpoint_url = http://localhost:8989",
1199                        )
1200                        .build(),
1201                )
1202                .load()
1203                .await;
1204            assert_eq!(
1205                Origin::shared_profile_file(),
1206                loader.get_origin("endpoint_url")
1207            );
1208        }
1209
1210        #[tokio::test]
1211        async fn load_use_fips() {
1212            let conf = base_conf().use_fips(true).load().await;
1213            assert_eq!(Some(true), conf.use_fips());
1214        }
1215
1216        #[tokio::test]
1217        async fn load_dual_stack() {
1218            let conf = base_conf().use_dual_stack(false).load().await;
1219            assert_eq!(Some(false), conf.use_dual_stack());
1220
1221            let conf = base_conf().load().await;
1222            assert_eq!(None, conf.use_dual_stack());
1223        }
1224
1225        #[tokio::test]
1226        async fn load_disable_request_compression() {
1227            let conf = base_conf().disable_request_compression(true).load().await;
1228            assert_eq!(Some(true), conf.disable_request_compression());
1229
1230            let conf = base_conf().load().await;
1231            assert_eq!(None, conf.disable_request_compression());
1232        }
1233
1234        #[tokio::test]
1235        async fn load_request_min_compression_size_bytes() {
1236            let conf = base_conf()
1237                .request_min_compression_size_bytes(99)
1238                .load()
1239                .await;
1240            assert_eq!(Some(99), conf.request_min_compression_size_bytes());
1241
1242            let conf = base_conf().load().await;
1243            assert_eq!(None, conf.request_min_compression_size_bytes());
1244        }
1245
1246        #[tokio::test]
1247        async fn app_name() {
1248            let app_name = AppName::new("my-app-name").unwrap();
1249            let conf = base_conf().app_name(app_name.clone()).load().await;
1250            assert_eq!(Some(&app_name), conf.app_name());
1251        }
1252
1253        #[tokio::test]
1254        async fn request_checksum_calculation() {
1255            let conf = base_conf()
1256                .request_checksum_calculation(RequestChecksumCalculation::WhenRequired)
1257                .load()
1258                .await;
1259            assert_eq!(
1260                Some(RequestChecksumCalculation::WhenRequired),
1261                conf.request_checksum_calculation()
1262            );
1263        }
1264
1265        #[tokio::test]
1266        async fn response_checksum_validation() {
1267            let conf = base_conf()
1268                .response_checksum_validation(ResponseChecksumValidation::WhenRequired)
1269                .load()
1270                .await;
1271            assert_eq!(
1272                Some(ResponseChecksumValidation::WhenRequired),
1273                conf.response_checksum_validation()
1274            );
1275        }
1276
1277        #[cfg(feature = "default-https-client")]
1278        #[tokio::test]
1279        async fn disable_default_credentials() {
1280            let config = defaults(BehaviorVersion::latest())
1281                .no_credentials()
1282                .load()
1283                .await;
1284            assert!(config.credentials_provider().is_none());
1285        }
1286
1287        #[cfg(feature = "default-https-client")]
1288        #[tokio::test]
1289        async fn identity_cache_defaulted() {
1290            let config = defaults(BehaviorVersion::latest()).load().await;
1291
1292            assert!(config.identity_cache().is_some());
1293        }
1294
1295        #[cfg(feature = "default-https-client")]
1296        #[allow(deprecated)]
1297        #[tokio::test]
1298        async fn identity_cache_old_behavior_version() {
1299            // Previously, `load()` did not need an explicit HTTP client because
1300            // internal providers (e.g. IMDS) built their Operation without a
1301            // BehaviorVersion, so default_plugins defaulted to latest() and the
1302            // `default-https-client` code path provided one automatically.
1303            //
1304            // Now that BehaviorVersion is threaded through to Operation::builder(),
1305            // the old BV here (v2023_11_09) causes default_plugins to use the
1306            // legacy hyper 0.14 code path, which returns None without
1307            // `legacy-rustls-ring`. NeverClient satisfies the debug_assertions
1308            // check in Operation::build() without additional TLS dependencies.
1309            let config = defaults(BehaviorVersion::v2023_11_09())
1310                .http_client(NeverClient::new())
1311                .sleep_impl(InstantSleep)
1312                .load()
1313                .await;
1314
1315            assert!(config.identity_cache().is_none());
1316        }
1317
1318        #[tokio::test]
1319        async fn connector_is_shared() {
1320            let num_requests = Arc::new(AtomicUsize::new(0));
1321            let movable = num_requests.clone();
1322            let http_client = infallible_client_fn(move |_req| {
1323                movable.fetch_add(1, Ordering::Relaxed);
1324                http::Response::new("ok!")
1325            });
1326            let config = defaults(BehaviorVersion::latest())
1327                .fs(Fs::from_slice(&[]))
1328                .env(Env::from_slice(&[]))
1329                .http_client(http_client.clone())
1330                .load()
1331                .await;
1332            config
1333                .credentials_provider()
1334                .unwrap()
1335                .provide_credentials()
1336                .await
1337                .expect_err("did not expect credentials to be loaded—no traffic is allowed");
1338            let num_requests = num_requests.load(Ordering::Relaxed);
1339            assert!(num_requests > 0, "{}", num_requests);
1340        }
1341
1342        #[tokio::test]
1343        async fn endpoint_urls_may_be_ignored_from_env() {
1344            let fs = Fs::from_slice(&[(
1345                "test_config",
1346                "[profile custom]\nendpoint_url = http://profile",
1347            )]);
1348            let env = Env::from_slice(&[("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "true")]);
1349
1350            let conf = base_conf().use_dual_stack(false).load().await;
1351            assert_eq!(Some(false), conf.use_dual_stack());
1352
1353            let conf = base_conf().load().await;
1354            assert_eq!(None, conf.use_dual_stack());
1355
1356            // Check that we get nothing back because the env said we should ignore endpoints
1357            let config = base_conf()
1358                .fs(fs.clone())
1359                .env(env)
1360                .profile_name("custom")
1361                .profile_files(
1362                    #[allow(deprecated)]
1363                    ProfileFiles::builder()
1364                        .with_file(
1365                            #[allow(deprecated)]
1366                            ProfileFileKind::Config,
1367                            "test_config",
1368                        )
1369                        .build(),
1370                )
1371                .load()
1372                .await;
1373            assert_eq!(None, config.endpoint_url());
1374
1375            // Check that without the env, we DO get something back
1376            let config = base_conf()
1377                .fs(fs)
1378                .profile_name("custom")
1379                .profile_files(
1380                    #[allow(deprecated)]
1381                    ProfileFiles::builder()
1382                        .with_file(
1383                            #[allow(deprecated)]
1384                            ProfileFileKind::Config,
1385                            "test_config",
1386                        )
1387                        .build(),
1388                )
1389                .load()
1390                .await;
1391            assert_eq!(Some("http://profile"), config.endpoint_url());
1392        }
1393
1394        #[tokio::test]
1395        async fn endpoint_urls_may_be_ignored_from_profile() {
1396            let fs = Fs::from_slice(&[(
1397                "test_config",
1398                "[profile custom]\nignore_configured_endpoint_urls = true",
1399            )]);
1400            let env = Env::from_slice(&[("AWS_ENDPOINT_URL", "http://environment")]);
1401
1402            // Check that we get nothing back because the profile said we should ignore endpoints
1403            let config = base_conf()
1404                .fs(fs)
1405                .env(env.clone())
1406                .profile_name("custom")
1407                .profile_files(
1408                    #[allow(deprecated)]
1409                    ProfileFiles::builder()
1410                        .with_file(
1411                            #[allow(deprecated)]
1412                            ProfileFileKind::Config,
1413                            "test_config",
1414                        )
1415                        .build(),
1416                )
1417                .load()
1418                .await;
1419            assert_eq!(None, config.endpoint_url());
1420
1421            // Check that without the profile, we DO get something back
1422            let config = base_conf().env(env).load().await;
1423            assert_eq!(Some("http://environment"), config.endpoint_url());
1424        }
1425
1426        #[tokio::test]
1427        async fn programmatic_endpoint_urls_may_not_be_ignored() {
1428            let fs = Fs::from_slice(&[(
1429                "test_config",
1430                "[profile custom]\nignore_configured_endpoint_urls = true",
1431            )]);
1432            let env = Env::from_slice(&[("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "true")]);
1433
1434            // Check that we get something back because we explicitly set the loader's endpoint URL
1435            let config = base_conf()
1436                .fs(fs)
1437                .env(env)
1438                .endpoint_url("http://localhost")
1439                .profile_name("custom")
1440                .profile_files(
1441                    #[allow(deprecated)]
1442                    ProfileFiles::builder()
1443                        .with_file(
1444                            #[allow(deprecated)]
1445                            ProfileFileKind::Config,
1446                            "test_config",
1447                        )
1448                        .build(),
1449                )
1450                .load()
1451                .await;
1452            assert_eq!(Some("http://localhost"), config.endpoint_url());
1453        }
1454    }
1455}