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