Skip to main content

aws_config/imds/
client.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! Raw IMDSv2 Client
7//!
8//! Client for direct access to IMDSv2.
9
10use crate::imds::client::error::{BuildError, ImdsError, InnerImdsError, InvalidEndpointMode};
11use crate::imds::client::token::TokenRuntimePlugin;
12use crate::provider_config::ProviderConfig;
13use crate::PKG_VERSION;
14use aws_runtime::user_agent::{ApiMetadata, AwsUserAgent, UserAgentInterceptor};
15use aws_smithy_runtime::client::metrics::MetricsRuntimePlugin;
16use aws_smithy_runtime::client::orchestrator::operation::Operation;
17use aws_smithy_runtime::client::retries::strategy::StandardRetryStrategy;
18use aws_smithy_runtime_api::box_error::BoxError;
19use aws_smithy_runtime_api::client::auth::AuthSchemeOptionResolverParams;
20use aws_smithy_runtime_api::client::endpoint::{
21    EndpointFuture, EndpointResolverParams, ResolveEndpoint,
22};
23use aws_smithy_runtime_api::client::interceptors::context::InterceptorContext;
24use aws_smithy_runtime_api::client::orchestrator::{
25    HttpRequest, Metadata, OrchestratorError, SensitiveOutput,
26};
27use aws_smithy_runtime_api::client::result::ConnectorError;
28use aws_smithy_runtime_api::client::result::SdkError;
29use aws_smithy_runtime_api::client::retries::classifiers::{
30    ClassifyRetry, RetryAction, SharedRetryClassifier,
31};
32use aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder;
33use aws_smithy_runtime_api::client::runtime_plugin::{RuntimePlugin, SharedRuntimePlugin};
34use aws_smithy_types::body::SdkBody;
35use aws_smithy_types::config_bag::{FrozenLayer, Layer};
36use aws_smithy_types::endpoint::Endpoint;
37use aws_smithy_types::retry::RetryConfig;
38use aws_smithy_types::timeout::TimeoutConfig;
39use aws_types::os_shim_internal::Env;
40use http::Uri;
41use std::borrow::Cow;
42use std::error::Error as _;
43use std::fmt;
44use std::str::FromStr;
45use std::sync::Arc;
46use std::time::Duration;
47
48pub mod error;
49mod token;
50
51// 6 hours
52const DEFAULT_TOKEN_TTL: Duration = Duration::from_secs(21_600);
53const DEFAULT_ATTEMPTS: u32 = 4;
54const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(1);
55const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(1);
56const DEFAULT_OPERATION_TIMEOUT: Duration = Duration::from_secs(30);
57const DEFAULT_OPERATION_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(10);
58
59fn user_agent() -> AwsUserAgent {
60    AwsUserAgent::new_from_environment(Env::real(), ApiMetadata::new("imds", PKG_VERSION))
61}
62
63/// IMDSv2 Client
64///
65/// Client for IMDSv2. This client handles fetching tokens, retrying on failure, and token
66/// caching according to the specified token TTL.
67///
68/// _Note: This client ONLY supports IMDSv2. It will not fallback to IMDSv1. See
69/// [transitioning to IMDSv2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html#instance-metadata-transition-to-version-2)
70/// for more information._
71///
72/// **Note**: When running in a Docker container, all network requests will incur an additional hop. When combined with the default IMDS hop limit of 1, this will cause requests to IMDS to timeout! To fix this issue, you'll need to set the following instance metadata settings :
73/// ```txt
74/// amazonec2-metadata-token=required
75/// amazonec2-metadata-token-response-hop-limit=2
76/// ```
77///
78/// On an instance that is already running, these can be set with [ModifyInstanceMetadataOptions](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceMetadataOptions.html). On a new instance, these can be set with the `MetadataOptions` field on [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html).
79///
80/// For more information about IMDSv2 vs. IMDSv1 see [this guide](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/configuring-instance-metadata-service.html)
81///
82/// # Client Configuration
83/// The IMDS client can load configuration explicitly, via environment variables, or via
84/// `~/.aws/config`. It will first attempt to resolve an endpoint override. If no endpoint
85/// override exists, it will attempt to resolve an [`EndpointMode`]. If no
86/// [`EndpointMode`] override exists, it will fallback to [`IpV4`](EndpointMode::IpV4). An exhaustive
87/// list is below:
88///
89/// ## Endpoint configuration list
90/// 1. Explicit configuration of `Endpoint` via the [builder](Builder):
91/// ```no_run
92/// use aws_config::imds::client::Client;
93/// # async fn docs() {
94/// let client = Client::builder()
95///   .endpoint("http://customimds:456/").expect("valid URI")
96///   .build();
97/// # }
98/// ```
99///
100/// 2. The `AWS_EC2_METADATA_SERVICE_ENDPOINT` environment variable. Note: If this environment variable
101///    is set, it MUST contain a valid URI or client construction will fail.
102///
103/// 3. The `ec2_metadata_service_endpoint` field in `~/.aws/config`:
104/// ```ini
105/// [default]
106/// # ... other configuration
107/// ec2_metadata_service_endpoint = http://my-custom-endpoint:444
108/// ```
109///
110/// 4. An explicitly set endpoint mode:
111/// ```no_run
112/// use aws_config::imds::client::{Client, EndpointMode};
113/// # async fn docs() {
114/// let client = Client::builder().endpoint_mode(EndpointMode::IpV6).build();
115/// # }
116/// ```
117///
118/// 5. An [endpoint mode](EndpointMode) loaded from the `AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE` environment
119///    variable. Valid values: `IPv4`, `IPv6`
120///
121/// 6. An [endpoint mode](EndpointMode) loaded from the `ec2_metadata_service_endpoint_mode` field in
122///    `~/.aws/config`:
123/// ```ini
124/// [default]
125/// # ... other configuration
126/// ec2_metadata_service_endpoint_mode = IPv4
127/// ```
128///
129/// 7. The default value of `http://169.254.169.254` will be used.
130///
131#[derive(Clone, Debug)]
132pub struct Client {
133    operation: Operation<String, SensitiveString, InnerImdsError>,
134}
135
136impl Client {
137    /// IMDS client builder
138    pub fn builder() -> Builder {
139        Builder::default()
140    }
141
142    /// Retrieve information from IMDS
143    ///
144    /// This method will handle loading and caching a session token, combining the `path` with the
145    /// configured IMDS endpoint, and retrying potential errors.
146    ///
147    /// For more information about IMDSv2 methods and functionality, see
148    /// [Instance metadata and user data](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)
149    ///
150    /// # Examples
151    ///
152    /// ```no_run
153    /// use aws_config::imds::client::Client;
154    /// # async fn docs() {
155    /// let client = Client::builder().build();
156    /// let ami_id = client
157    ///   .get("/latest/meta-data/ami-id")
158    ///   .await
159    ///   .expect("failure communicating with IMDS");
160    /// # }
161    /// ```
162    pub async fn get(&self, path: impl Into<String>) -> Result<SensitiveString, ImdsError> {
163        self.operation
164            .invoke(path.into())
165            .await
166            .map_err(|err| match err {
167                SdkError::ConstructionFailure(_) if err.source().is_some() => {
168                    match err.into_source().map(|e| e.downcast::<ImdsError>()) {
169                        Ok(Ok(token_failure)) => *token_failure,
170                        Ok(Err(err)) => ImdsError::unexpected(err),
171                        Err(err) => ImdsError::unexpected(err),
172                    }
173                }
174                SdkError::ConstructionFailure(_) => ImdsError::unexpected(err),
175                SdkError::ServiceError(context) => match context.err() {
176                    InnerImdsError::InvalidUtf8 => {
177                        ImdsError::unexpected("IMDS returned invalid UTF-8")
178                    }
179                    InnerImdsError::BadStatus => ImdsError::error_response(context.into_raw()),
180                },
181                // If the error source is an ImdsError, then we need to directly return that source.
182                // That way, the IMDS token provider's errors can become the top-level ImdsError.
183                // There is a unit test that checks the correct error is being extracted.
184                err @ SdkError::DispatchFailure(_) => match err.into_source() {
185                    Ok(source) => match source.downcast::<ConnectorError>() {
186                        Ok(source) => match source.into_source().downcast::<ImdsError>() {
187                            Ok(source) => *source,
188                            Err(err) => ImdsError::unexpected(err),
189                        },
190                        Err(err) => ImdsError::unexpected(err),
191                    },
192                    Err(err) => ImdsError::unexpected(err),
193                },
194                SdkError::TimeoutError(_) | SdkError::ResponseError(_) => ImdsError::io_error(err),
195                _ => ImdsError::unexpected(err),
196            })
197    }
198}
199
200/// New-type around `String` that doesn't emit the string value in the `Debug` impl.
201#[derive(Clone)]
202pub struct SensitiveString(String);
203
204impl fmt::Debug for SensitiveString {
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        f.debug_tuple("SensitiveString")
207            .field(&"** redacted **")
208            .finish()
209    }
210}
211
212impl AsRef<str> for SensitiveString {
213    fn as_ref(&self) -> &str {
214        &self.0
215    }
216}
217
218impl From<String> for SensitiveString {
219    fn from(value: String) -> Self {
220        Self(value)
221    }
222}
223
224impl From<SensitiveString> for String {
225    fn from(value: SensitiveString) -> Self {
226        value.0
227    }
228}
229
230/// Runtime plugin that is used by both the IMDS client and the inner client that resolves
231/// the IMDS token and attaches it to requests. This runtime plugin marks the responses as
232/// sensitive, configures user agent headers, and sets up retries and timeouts.
233#[derive(Debug)]
234struct ImdsCommonRuntimePlugin {
235    config: FrozenLayer,
236    components: RuntimeComponentsBuilder,
237}
238
239impl ImdsCommonRuntimePlugin {
240    fn new(
241        config: &ProviderConfig,
242        endpoint_resolver: ImdsEndpointResolver,
243        retry_config: RetryConfig,
244        retry_classifier: SharedRetryClassifier,
245        timeout_config: TimeoutConfig,
246    ) -> Self {
247        let mut layer = Layer::new("ImdsCommonRuntimePlugin");
248        layer.store_put(AuthSchemeOptionResolverParams::new(()));
249        layer.store_put(EndpointResolverParams::new(()));
250        layer.store_put(SensitiveOutput);
251        layer.store_put(retry_config);
252        layer.store_put(timeout_config);
253        layer.store_put(user_agent());
254
255        Self {
256            config: layer.freeze(),
257            components: RuntimeComponentsBuilder::new("ImdsCommonRuntimePlugin")
258                .with_http_client(config.http_client())
259                .with_endpoint_resolver(Some(endpoint_resolver))
260                .with_interceptor(UserAgentInterceptor::new())
261                .with_retry_classifier(retry_classifier)
262                .with_retry_strategy(Some(StandardRetryStrategy::new()))
263                .with_time_source(Some(config.time_source()))
264                .with_sleep_impl(config.sleep_impl()),
265        }
266    }
267}
268
269impl RuntimePlugin for ImdsCommonRuntimePlugin {
270    fn config(&self) -> Option<FrozenLayer> {
271        Some(self.config.clone())
272    }
273
274    fn runtime_components(
275        &self,
276        _current_components: &RuntimeComponentsBuilder,
277    ) -> Cow<'_, RuntimeComponentsBuilder> {
278        Cow::Borrowed(&self.components)
279    }
280}
281
282/// IMDSv2 Endpoint Mode
283///
284/// IMDS can be accessed in two ways:
285/// 1. Via the IpV4 endpoint: `http://169.254.169.254`
286/// 2. Via the Ipv6 endpoint: `http://[fd00:ec2::254]`
287#[derive(Debug, Clone)]
288#[non_exhaustive]
289pub enum EndpointMode {
290    /// IpV4 mode: `http://169.254.169.254`
291    ///
292    /// This mode is the default unless otherwise specified.
293    IpV4,
294    /// IpV6 mode: `http://[fd00:ec2::254]`
295    IpV6,
296}
297
298impl FromStr for EndpointMode {
299    type Err = InvalidEndpointMode;
300
301    fn from_str(value: &str) -> Result<Self, Self::Err> {
302        match value {
303            _ if value.eq_ignore_ascii_case("ipv4") => Ok(EndpointMode::IpV4),
304            _ if value.eq_ignore_ascii_case("ipv6") => Ok(EndpointMode::IpV6),
305            other => Err(InvalidEndpointMode::new(other.to_owned())),
306        }
307    }
308}
309
310impl EndpointMode {
311    /// IMDS URI for this endpoint mode
312    fn endpoint(&self) -> Uri {
313        match self {
314            EndpointMode::IpV4 => Uri::from_static("http://169.254.169.254"),
315            EndpointMode::IpV6 => Uri::from_static("http://[fd00:ec2::254]"),
316        }
317    }
318}
319
320/// IMDSv2 Client Builder
321#[derive(Default, Debug, Clone)]
322pub struct Builder {
323    max_attempts: Option<u32>,
324    endpoint: Option<EndpointSource>,
325    mode_override: Option<EndpointMode>,
326    token_ttl: Option<Duration>,
327    connect_timeout: Option<Duration>,
328    read_timeout: Option<Duration>,
329    operation_timeout: Option<Duration>,
330    operation_attempt_timeout: Option<Duration>,
331    config: Option<ProviderConfig>,
332    retry_classifier: Option<SharedRetryClassifier>,
333    #[cfg(test)]
334    use_static_exponential_base: bool,
335}
336
337impl Builder {
338    /// Override the number of retries for fetching tokens & metadata
339    ///
340    /// By default, 4 attempts will be made.
341    pub fn max_attempts(mut self, max_attempts: u32) -> Self {
342        self.max_attempts = Some(max_attempts);
343        self
344    }
345
346    /// Configure generic options of the [`Client`]
347    ///
348    /// # Examples
349    /// ```no_run
350    /// # async fn test() {
351    /// use aws_config::imds::Client;
352    /// use aws_config::provider_config::ProviderConfig;
353    ///
354    /// let provider = Client::builder()
355    ///     .configure(&ProviderConfig::with_default_region().await)
356    ///     .build();
357    /// # }
358    /// ```
359    pub fn configure(mut self, provider_config: &ProviderConfig) -> Self {
360        self.config = Some(provider_config.clone());
361        self
362    }
363
364    /// Override the endpoint for the [`Client`]
365    ///
366    /// By default, the client will resolve an endpoint from the environment, AWS config, and endpoint mode.
367    ///
368    /// See [`Client`] for more information.
369    pub fn endpoint(mut self, endpoint: impl AsRef<str>) -> Result<Self, BoxError> {
370        let uri: Uri = endpoint.as_ref().parse()?;
371        self.endpoint = Some(EndpointSource::Explicit(uri));
372        Ok(self)
373    }
374
375    /// Override the endpoint mode for [`Client`]
376    ///
377    /// * When set to [`IpV4`](EndpointMode::IpV4), the endpoint will be `http://169.254.169.254`.
378    /// * When set to [`IpV6`](EndpointMode::IpV6), the endpoint will be `http://[fd00:ec2::254]`.
379    pub fn endpoint_mode(mut self, mode: EndpointMode) -> Self {
380        self.mode_override = Some(mode);
381        self
382    }
383
384    /// Override the time-to-live for the session token
385    ///
386    /// Requests to IMDS utilize a session token for authentication. By default, session tokens last
387    /// for 6 hours. When the TTL for the token expires, a new token must be retrieved from the
388    /// metadata service.
389    pub fn token_ttl(mut self, ttl: Duration) -> Self {
390        self.token_ttl = Some(ttl);
391        self
392    }
393
394    /// Override the connect timeout for IMDS
395    ///
396    /// This value defaults to 1 second
397    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
398        self.connect_timeout = Some(timeout);
399        self
400    }
401
402    /// Override the read timeout for IMDS
403    ///
404    /// This value defaults to 1 second
405    pub fn read_timeout(mut self, timeout: Duration) -> Self {
406        self.read_timeout = Some(timeout);
407        self
408    }
409
410    /// Override the operation timeout for IMDS
411    ///
412    /// This value defaults to 1 second
413    pub fn operation_timeout(mut self, timeout: Duration) -> Self {
414        self.operation_timeout = Some(timeout);
415        self
416    }
417
418    /// Override the operation attempt timeout for IMDS
419    ///
420    /// This value defaults to 1 second
421    pub fn operation_attempt_timeout(mut self, timeout: Duration) -> Self {
422        self.operation_attempt_timeout = Some(timeout);
423        self
424    }
425
426    /// Override the retry classifier for IMDS
427    ///
428    /// This defaults to only retrying on server errors and 401s. The [ImdsResponseRetryClassifier] in this
429    /// module offers some configuration options and can be wrapped by[SharedRetryClassifier::new()] for use
430    /// here or you can create your own fully customized [SharedRetryClassifier].
431    pub fn retry_classifier(mut self, retry_classifier: SharedRetryClassifier) -> Self {
432        self.retry_classifier = Some(retry_classifier);
433        self
434    }
435
436    /// Remove the random jitter from retry backoff so tests can assert exact delays
437    #[cfg(test)]
438    fn use_static_exponential_base(mut self) -> Self {
439        self.use_static_exponential_base = true;
440        self
441    }
442
443    /* TODO(https://github.com/awslabs/aws-sdk-rust/issues/339): Support customizing the port explicitly */
444    /*
445    pub fn port(mut self, port: u32) -> Self {
446        self.port_override = Some(port);
447        self
448    }*/
449
450    /// Build an IMDSv2 Client
451    pub fn build(self) -> Client {
452        let config = self.config.unwrap_or_default();
453        let timeout_config = TimeoutConfig::builder()
454            .connect_timeout(self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT))
455            .read_timeout(self.read_timeout.unwrap_or(DEFAULT_READ_TIMEOUT))
456            .operation_attempt_timeout(
457                self.operation_attempt_timeout
458                    .unwrap_or(DEFAULT_OPERATION_ATTEMPT_TIMEOUT),
459            )
460            .operation_timeout(self.operation_timeout.unwrap_or(DEFAULT_OPERATION_TIMEOUT))
461            .build();
462        let endpoint_source = self
463            .endpoint
464            .unwrap_or_else(|| EndpointSource::Env(config.clone()));
465        let endpoint_resolver = ImdsEndpointResolver {
466            endpoint_source: Arc::new(endpoint_source),
467            mode_override: self.mode_override,
468        };
469        let retry_config = RetryConfig::standard()
470            .with_max_attempts(self.max_attempts.unwrap_or(DEFAULT_ATTEMPTS));
471        #[cfg(test)]
472        let retry_config =
473            retry_config.with_use_static_exponential_base(self.use_static_exponential_base);
474        let retry_classifier = self.retry_classifier.unwrap_or(SharedRetryClassifier::new(
475            ImdsResponseRetryClassifier::default(),
476        ));
477        let common_plugin = SharedRuntimePlugin::new(ImdsCommonRuntimePlugin::new(
478            &config,
479            endpoint_resolver,
480            retry_config,
481            retry_classifier,
482            timeout_config,
483        ));
484        let operation = Operation::builder()
485            .service_name("imds")
486            .operation_name("get")
487            .runtime_plugin(common_plugin.clone())
488            .runtime_plugin(TokenRuntimePlugin::new(
489                common_plugin,
490                self.token_ttl.unwrap_or(DEFAULT_TOKEN_TTL),
491                config.behavior_version(),
492            ))
493            .runtime_plugin(
494                MetricsRuntimePlugin::builder()
495                    .with_scope("aws_config::imds_credentials")
496                    .with_time_source(config.time_source())
497                    .with_metadata(Metadata::new("get_credentials", "imds"))
498                    .build()
499                    .expect("All required fields have been set"),
500            )
501            .with_connection_poisoning()
502            .serializer(|path| {
503                Ok(HttpRequest::try_from(
504                    http::Request::builder()
505                        .uri(path)
506                        .body(SdkBody::empty())
507                        .expect("valid request"),
508                )
509                .unwrap())
510            })
511            .deserializer(|response| {
512                if response.status().is_success() {
513                    std::str::from_utf8(response.body().bytes().expect("non-streaming response"))
514                        .map(|data| SensitiveString::from(data.to_string()))
515                        .map_err(|_| OrchestratorError::operation(InnerImdsError::InvalidUtf8))
516                } else {
517                    Err(OrchestratorError::operation(InnerImdsError::BadStatus))
518                }
519            });
520        let operation = if let Some(bv) = config.behavior_version() {
521            operation.behavior_version(bv).build()
522        } else {
523            operation.build()
524        };
525        Client { operation }
526    }
527}
528
529mod env {
530    pub(super) const ENDPOINT: &str = "AWS_EC2_METADATA_SERVICE_ENDPOINT";
531    pub(super) const ENDPOINT_MODE: &str = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE";
532}
533
534mod profile_keys {
535    pub(super) const ENDPOINT: &str = "ec2_metadata_service_endpoint";
536    pub(super) const ENDPOINT_MODE: &str = "ec2_metadata_service_endpoint_mode";
537}
538
539/// Endpoint Configuration Abstraction
540#[derive(Debug, Clone)]
541enum EndpointSource {
542    Explicit(Uri),
543    Env(ProviderConfig),
544}
545
546impl EndpointSource {
547    async fn endpoint(&self, mode_override: Option<EndpointMode>) -> Result<Uri, BuildError> {
548        match self {
549            EndpointSource::Explicit(uri) => {
550                if mode_override.is_some() {
551                    tracing::warn!(endpoint = ?uri, mode = ?mode_override,
552                        "Endpoint mode override was set in combination with an explicit endpoint. \
553                        The mode override will be ignored.")
554                }
555                Ok(uri.clone())
556            }
557            EndpointSource::Env(conf) => {
558                let env = conf.env();
559                // load an endpoint override from the environment
560                let profile = conf.profile().await;
561                let uri_override = if let Ok(uri) = env.get(env::ENDPOINT) {
562                    Some(Cow::Owned(uri))
563                } else {
564                    profile
565                        .and_then(|profile| profile.get(profile_keys::ENDPOINT))
566                        .map(Cow::Borrowed)
567                };
568                if let Some(uri) = uri_override {
569                    return Uri::try_from(uri.as_ref()).map_err(BuildError::invalid_endpoint_uri);
570                }
571
572                // if not, load a endpoint mode from the environment
573                let mode = if let Some(mode) = mode_override {
574                    mode
575                } else if let Ok(mode) = env.get(env::ENDPOINT_MODE) {
576                    mode.parse::<EndpointMode>()
577                        .map_err(BuildError::invalid_endpoint_mode)?
578                } else if let Some(mode) = profile.and_then(|p| p.get(profile_keys::ENDPOINT_MODE))
579                {
580                    mode.parse::<EndpointMode>()
581                        .map_err(BuildError::invalid_endpoint_mode)?
582                } else {
583                    EndpointMode::IpV4
584                };
585
586                Ok(mode.endpoint())
587            }
588        }
589    }
590}
591
592#[derive(Clone, Debug)]
593struct ImdsEndpointResolver {
594    endpoint_source: Arc<EndpointSource>,
595    mode_override: Option<EndpointMode>,
596}
597
598impl ResolveEndpoint for ImdsEndpointResolver {
599    fn resolve_endpoint<'a>(&'a self, _: &'a EndpointResolverParams) -> EndpointFuture<'a> {
600        EndpointFuture::new(async move {
601            self.endpoint_source
602                .endpoint(self.mode_override.clone())
603                .await
604                .map(|uri| Endpoint::builder().url(uri.to_string()).build())
605                .map_err(|err| err.into())
606        })
607    }
608}
609
610/// IMDS Response Retry Classifier
611///
612/// Possible status codes:
613/// - 200 (OK)
614/// - 400 (Missing or invalid parameters) **Not Retryable**
615/// - 401 (Unauthorized, expired token) **Retryable**
616/// - 403 (IMDS disabled): **Not Retryable**
617/// - 404 (Not found): **Not Retryable**
618/// - >=500 (server error): **Retryable**
619/// - Timeouts: Not retried by default, but this is configurable via [Self::with_retry_connect_timeouts()]
620#[derive(Clone, Debug, Default)]
621#[non_exhaustive]
622pub struct ImdsResponseRetryClassifier {
623    retry_connect_timeouts: bool,
624}
625
626impl ImdsResponseRetryClassifier {
627    /// Indicate whether the IMDS client should retry on connection timeouts
628    pub fn with_retry_connect_timeouts(mut self, retry_connect_timeouts: bool) -> Self {
629        self.retry_connect_timeouts = retry_connect_timeouts;
630        self
631    }
632}
633
634impl ClassifyRetry for ImdsResponseRetryClassifier {
635    fn name(&self) -> &'static str {
636        "ImdsResponseRetryClassifier"
637    }
638
639    fn classify_retry(&self, ctx: &InterceptorContext) -> RetryAction {
640        if let Some(response) = ctx.response() {
641            let status = response.status();
642            match status {
643                _ if status.is_server_error() => RetryAction::server_error(),
644                // 401 indicates that the token has expired, this is retryable
645                _ if status.as_u16() == 401 => RetryAction::server_error(),
646                // This catch-all includes successful responses that fail to parse. These should not be retried.
647                _ => RetryAction::NoActionIndicated,
648            }
649        } else if self.retry_connect_timeouts {
650            RetryAction::server_error()
651        } else {
652            // This is the default behavior.
653            // Don't retry timeouts for IMDS, or else it will take ~30 seconds for the default
654            // credentials provider chain to fail to provide credentials.
655            // Also don't retry non-responses.
656            RetryAction::NoActionIndicated
657        }
658    }
659}
660
661#[cfg(test)]
662pub(crate) mod test {
663    use crate::imds::client::{Client, EndpointMode, ImdsResponseRetryClassifier};
664    use crate::provider_config::ProviderConfig;
665    use aws_smithy_async::rt::sleep::TokioSleep;
666    use aws_smithy_async::test_util::{instant_time_and_sleep, InstantSleep};
667    use aws_smithy_http_client::test_util::{capture_request, ReplayEvent, StaticReplayClient};
668    use aws_smithy_runtime::test_util::capture_test_logs::capture_test_logs;
669    use aws_smithy_runtime_api::client::behavior_version::BehaviorVersion;
670    use aws_smithy_runtime_api::client::http::{
671        HttpClient, HttpConnector, HttpConnectorFuture, HttpConnectorSettings, SharedHttpConnector,
672    };
673    use aws_smithy_runtime_api::client::interceptors::context::{
674        Input, InterceptorContext, Output,
675    };
676    use aws_smithy_runtime_api::client::orchestrator::OrchestratorError;
677    use aws_smithy_runtime_api::client::orchestrator::{HttpRequest, HttpResponse};
678    use aws_smithy_runtime_api::client::result::ConnectorError;
679    use aws_smithy_runtime_api::client::retries::classifiers::{
680        ClassifyRetry, RetryAction, SharedRetryClassifier,
681    };
682    use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
683    use aws_smithy_runtime_api::shared::IntoShared;
684    use aws_smithy_types::body::SdkBody;
685    use aws_smithy_types::error::display::DisplayErrorContext;
686    use aws_types::os_shim_internal::{Env, Fs};
687    use http::header::USER_AGENT;
688    use http::Uri;
689    use serde::Deserialize;
690    use std::collections::HashMap;
691    use std::error::Error;
692    use std::io;
693    use std::sync::atomic::{AtomicUsize, Ordering};
694    use std::sync::Arc;
695    use std::time::{Duration, UNIX_EPOCH};
696    use tracing_test::traced_test;
697
698    macro_rules! assert_full_error_contains {
699        ($err:expr, $contains:expr) => {
700            let err = $err;
701            let message = format!(
702                "{}",
703                aws_smithy_types::error::display::DisplayErrorContext(&err)
704            );
705            assert!(
706                message.contains($contains),
707                "Error message '{message}' didn't contain text '{}'",
708                $contains
709            );
710        };
711    }
712
713    const TOKEN_A: &str = "AQAEAFTNrA4eEGx0AQgJ1arIq_Cc-t4tWt3fB0Hd8RKhXlKc5ccvhg==";
714    const TOKEN_B: &str = "alternatetoken==";
715
716    /// Create a simple token request
717    pub(crate) fn token_request(base: &str, ttl: u32) -> HttpRequest {
718        http::Request::builder()
719            .uri(format!("{}/latest/api/token", base))
720            .header("x-aws-ec2-metadata-token-ttl-seconds", ttl)
721            .method("PUT")
722            .body(SdkBody::empty())
723            .unwrap()
724            .try_into()
725            .unwrap()
726    }
727
728    /// Create a simple token response
729    pub(crate) fn token_response(ttl: u32, token: &'static str) -> HttpResponse {
730        HttpResponse::try_from(
731            http::Response::builder()
732                .status(200)
733                .header("X-aws-ec2-metadata-token-ttl-seconds", ttl)
734                .body(SdkBody::from(token))
735                .unwrap(),
736        )
737        .unwrap()
738    }
739
740    /// Create a simple IMDS request
741    pub(crate) fn imds_request(path: &'static str, token: &str) -> HttpRequest {
742        http::Request::builder()
743            .uri(Uri::from_static(path))
744            .method("GET")
745            .header("x-aws-ec2-metadata-token", token)
746            .body(SdkBody::empty())
747            .unwrap()
748            .try_into()
749            .unwrap()
750    }
751
752    /// Create a simple IMDS response
753    pub(crate) fn imds_response(body: &'static str) -> HttpResponse {
754        HttpResponse::try_from(
755            http::Response::builder()
756                .status(200)
757                .body(SdkBody::from(body))
758                .unwrap(),
759        )
760        .unwrap()
761    }
762
763    /// Create an IMDS client with an underlying [StaticReplayClient]
764    pub(crate) fn make_imds_client(http_client: &StaticReplayClient) -> super::Client {
765        tokio::time::pause();
766        super::Client::builder()
767            .configure(
768                &ProviderConfig::no_configuration()
769                    .with_sleep_impl(InstantSleep::unlogged())
770                    .with_http_client(http_client.clone()),
771            )
772            .build()
773    }
774
775    fn mock_imds_client(events: Vec<ReplayEvent>) -> (Client, StaticReplayClient) {
776        let http_client = StaticReplayClient::new(events);
777        let client = make_imds_client(&http_client);
778        (client, http_client)
779    }
780
781    #[tokio::test]
782    async fn client_caches_token() {
783        let (client, http_client) = mock_imds_client(vec![
784            ReplayEvent::new(
785                token_request("http://169.254.169.254", 21600),
786                token_response(21600, TOKEN_A),
787            ),
788            ReplayEvent::new(
789                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
790                imds_response(r#"test-imds-output"#),
791            ),
792            ReplayEvent::new(
793                imds_request("http://169.254.169.254/latest/metadata2", TOKEN_A),
794                imds_response("output2"),
795            ),
796        ]);
797        // load once
798        let metadata = client.get("/latest/metadata").await.expect("failed");
799        assert_eq!("test-imds-output", metadata.as_ref());
800        // load again: the cached token should be used
801        let metadata = client.get("/latest/metadata2").await.expect("failed");
802        assert_eq!("output2", metadata.as_ref());
803        http_client.assert_requests_match(&[]);
804    }
805
806    #[tokio::test]
807    async fn token_can_expire() {
808        let (_, http_client) = mock_imds_client(vec![
809            ReplayEvent::new(
810                token_request("http://[fd00:ec2::254]", 600),
811                token_response(600, TOKEN_A),
812            ),
813            ReplayEvent::new(
814                imds_request("http://[fd00:ec2::254]/latest/metadata", TOKEN_A),
815                imds_response(r#"test-imds-output1"#),
816            ),
817            ReplayEvent::new(
818                token_request("http://[fd00:ec2::254]", 600),
819                token_response(600, TOKEN_B),
820            ),
821            ReplayEvent::new(
822                imds_request("http://[fd00:ec2::254]/latest/metadata", TOKEN_B),
823                imds_response(r#"test-imds-output2"#),
824            ),
825        ]);
826        let (time_source, sleep) = instant_time_and_sleep(UNIX_EPOCH);
827        let client = super::Client::builder()
828            .configure(
829                &ProviderConfig::no_configuration()
830                    .with_http_client(http_client.clone())
831                    .with_time_source(time_source.clone())
832                    .with_sleep_impl(sleep),
833            )
834            .endpoint_mode(EndpointMode::IpV6)
835            .token_ttl(Duration::from_secs(600))
836            .build();
837
838        let resp1 = client.get("/latest/metadata").await.expect("success");
839        // now the cached credential has expired
840        time_source.advance(Duration::from_secs(600));
841        let resp2 = client.get("/latest/metadata").await.expect("success");
842        http_client.assert_requests_match(&[]);
843        assert_eq!("test-imds-output1", resp1.as_ref());
844        assert_eq!("test-imds-output2", resp2.as_ref());
845    }
846
847    /// Tokens are refreshed up to 120 seconds early to avoid using an expired token.
848    #[tokio::test]
849    async fn token_refresh_buffer() {
850        let _logs = capture_test_logs();
851        let (_, http_client) = mock_imds_client(vec![
852            ReplayEvent::new(
853                token_request("http://[fd00:ec2::254]", 600),
854                token_response(600, TOKEN_A),
855            ),
856            // t = 0
857            ReplayEvent::new(
858                imds_request("http://[fd00:ec2::254]/latest/metadata", TOKEN_A),
859                imds_response(r#"test-imds-output1"#),
860            ),
861            // t = 400 (no refresh)
862            ReplayEvent::new(
863                imds_request("http://[fd00:ec2::254]/latest/metadata", TOKEN_A),
864                imds_response(r#"test-imds-output2"#),
865            ),
866            // t = 550 (within buffer)
867            ReplayEvent::new(
868                token_request("http://[fd00:ec2::254]", 600),
869                token_response(600, TOKEN_B),
870            ),
871            ReplayEvent::new(
872                imds_request("http://[fd00:ec2::254]/latest/metadata", TOKEN_B),
873                imds_response(r#"test-imds-output3"#),
874            ),
875        ]);
876        let (time_source, sleep) = instant_time_and_sleep(UNIX_EPOCH);
877        let client = super::Client::builder()
878            .configure(
879                &ProviderConfig::no_configuration()
880                    .with_sleep_impl(sleep)
881                    .with_http_client(http_client.clone())
882                    .with_time_source(time_source.clone()),
883            )
884            .endpoint_mode(EndpointMode::IpV6)
885            .token_ttl(Duration::from_secs(600))
886            .build();
887
888        tracing::info!("resp1 -----------------------------------------------------------");
889        let resp1 = client.get("/latest/metadata").await.expect("success");
890        // now the cached credential has expired
891        time_source.advance(Duration::from_secs(400));
892        tracing::info!("resp2 -----------------------------------------------------------");
893        let resp2 = client.get("/latest/metadata").await.expect("success");
894        time_source.advance(Duration::from_secs(150));
895        tracing::info!("resp3 -----------------------------------------------------------");
896        let resp3 = client.get("/latest/metadata").await.expect("success");
897        http_client.assert_requests_match(&[]);
898        assert_eq!("test-imds-output1", resp1.as_ref());
899        assert_eq!("test-imds-output2", resp2.as_ref());
900        assert_eq!("test-imds-output3", resp3.as_ref());
901    }
902
903    /// 500 error during the GET should be retried
904    #[tokio::test]
905    #[traced_test]
906    async fn retry_500() {
907        let (client, http_client) = mock_imds_client(vec![
908            ReplayEvent::new(
909                token_request("http://169.254.169.254", 21600),
910                token_response(21600, TOKEN_A),
911            ),
912            ReplayEvent::new(
913                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
914                http::Response::builder()
915                    .status(500)
916                    .body(SdkBody::empty())
917                    .unwrap(),
918            ),
919            ReplayEvent::new(
920                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
921                imds_response("ok"),
922            ),
923        ]);
924        assert_eq!(
925            "ok",
926            client
927                .get("/latest/metadata")
928                .await
929                .expect("success")
930                .as_ref()
931        );
932        http_client.assert_requests_match(&[]);
933
934        // all requests should have a user agent header
935        for request in http_client.actual_requests() {
936            assert!(request.headers().get(USER_AGENT).is_some());
937        }
938    }
939
940    /// 500 error during token acquisition should be retried
941    #[tokio::test]
942    #[traced_test]
943    async fn retry_token_failure() {
944        let (client, http_client) = mock_imds_client(vec![
945            ReplayEvent::new(
946                token_request("http://169.254.169.254", 21600),
947                http::Response::builder()
948                    .status(500)
949                    .body(SdkBody::empty())
950                    .unwrap(),
951            ),
952            ReplayEvent::new(
953                token_request("http://169.254.169.254", 21600),
954                token_response(21600, TOKEN_A),
955            ),
956            ReplayEvent::new(
957                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
958                imds_response("ok"),
959            ),
960        ]);
961        assert_eq!(
962            "ok",
963            client
964                .get("/latest/metadata")
965                .await
966                .expect("success")
967                .as_ref()
968        );
969        http_client.assert_requests_match(&[]);
970    }
971
972    /// 401 error during metadata retrieval must be retried
973    #[tokio::test]
974    #[traced_test]
975    async fn retry_metadata_401() {
976        let (client, http_client) = mock_imds_client(vec![
977            ReplayEvent::new(
978                token_request("http://169.254.169.254", 21600),
979                token_response(0, TOKEN_A),
980            ),
981            ReplayEvent::new(
982                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
983                http::Response::builder()
984                    .status(401)
985                    .body(SdkBody::empty())
986                    .unwrap(),
987            ),
988            ReplayEvent::new(
989                token_request("http://169.254.169.254", 21600),
990                token_response(21600, TOKEN_B),
991            ),
992            ReplayEvent::new(
993                imds_request("http://169.254.169.254/latest/metadata", TOKEN_B),
994                imds_response("ok"),
995            ),
996        ]);
997        assert_eq!(
998            "ok",
999            client
1000                .get("/latest/metadata")
1001                .await
1002                .expect("success")
1003                .as_ref()
1004        );
1005        http_client.assert_requests_match(&[]);
1006    }
1007
1008    /// 403 responses from IMDS during token acquisition MUST NOT be retried
1009    #[tokio::test]
1010    #[traced_test]
1011    async fn no_403_retry() {
1012        let (client, http_client) = mock_imds_client(vec![ReplayEvent::new(
1013            token_request("http://169.254.169.254", 21600),
1014            http::Response::builder()
1015                .status(403)
1016                .body(SdkBody::empty())
1017                .unwrap(),
1018        )]);
1019        let err = client.get("/latest/metadata").await.expect_err("no token");
1020        assert_full_error_contains!(err, "forbidden");
1021        http_client.assert_requests_match(&[]);
1022    }
1023
1024    /// The classifier should return `None` when classifying a successful response.
1025    #[test]
1026    fn successful_response_properly_classified() {
1027        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
1028        ctx.set_output_or_error(Ok(Output::doesnt_matter()));
1029        ctx.set_response(imds_response("").map(|_| SdkBody::empty()));
1030        let classifier = ImdsResponseRetryClassifier::default();
1031        assert_eq!(
1032            RetryAction::NoActionIndicated,
1033            classifier.classify_retry(&ctx)
1034        );
1035
1036        // Emulate a failure to parse the response body (using an io error since it's easy to construct in a test)
1037        let mut ctx = InterceptorContext::new(Input::doesnt_matter());
1038        ctx.set_output_or_error(Err(OrchestratorError::connector(ConnectorError::io(
1039            io::Error::new(io::ErrorKind::BrokenPipe, "fail to parse").into(),
1040        ))));
1041        assert_eq!(
1042            RetryAction::NoActionIndicated,
1043            classifier.classify_retry(&ctx)
1044        );
1045    }
1046
1047    /// User provided retry classifier works
1048    #[tokio::test]
1049    async fn user_provided_retry_classifier() {
1050        #[derive(Clone, Debug)]
1051        struct UserProvidedRetryClassifier;
1052
1053        impl ClassifyRetry for UserProvidedRetryClassifier {
1054            fn name(&self) -> &'static str {
1055                "UserProvidedRetryClassifier"
1056            }
1057
1058            // Don't retry anything
1059            fn classify_retry(&self, _ctx: &InterceptorContext) -> RetryAction {
1060                RetryAction::RetryForbidden
1061            }
1062        }
1063
1064        let events = vec![
1065            ReplayEvent::new(
1066                token_request("http://169.254.169.254", 21600),
1067                token_response(0, TOKEN_A),
1068            ),
1069            ReplayEvent::new(
1070                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
1071                http::Response::builder()
1072                    .status(401)
1073                    .body(SdkBody::empty())
1074                    .unwrap(),
1075            ),
1076            ReplayEvent::new(
1077                token_request("http://169.254.169.254", 21600),
1078                token_response(21600, TOKEN_B),
1079            ),
1080            ReplayEvent::new(
1081                imds_request("http://169.254.169.254/latest/metadata", TOKEN_B),
1082                imds_response("ok"),
1083            ),
1084        ];
1085        let http_client = StaticReplayClient::new(events);
1086
1087        let imds_client = super::Client::builder()
1088            .configure(
1089                &ProviderConfig::no_configuration()
1090                    .with_sleep_impl(InstantSleep::unlogged())
1091                    .with_http_client(http_client.clone()),
1092            )
1093            .retry_classifier(SharedRetryClassifier::new(UserProvidedRetryClassifier))
1094            .build();
1095
1096        let res = imds_client
1097            .get("/latest/metadata")
1098            .await
1099            .expect_err("Client should error");
1100
1101        // Assert that the operation errored on the initial 401 and did not retry and get
1102        // the 200 (since the user provided retry classifier never retries)
1103        assert_full_error_contains!(res, "401");
1104    }
1105
1106    // since tokens are sent as headers, the tokens need to be valid header values
1107    #[tokio::test]
1108    async fn invalid_token() {
1109        let (client, http_client) = mock_imds_client(vec![ReplayEvent::new(
1110            token_request("http://169.254.169.254", 21600),
1111            token_response(21600, "invalid\nheader\nvalue\0"),
1112        )]);
1113        let err = client.get("/latest/metadata").await.expect_err("no token");
1114        assert_full_error_contains!(err, "invalid token");
1115        http_client.assert_requests_match(&[]);
1116    }
1117
1118    #[tokio::test]
1119    async fn non_utf8_response() {
1120        let (client, http_client) = mock_imds_client(vec![
1121            ReplayEvent::new(
1122                token_request("http://169.254.169.254", 21600),
1123                token_response(21600, TOKEN_A).map(SdkBody::from),
1124            ),
1125            ReplayEvent::new(
1126                imds_request("http://169.254.169.254/latest/metadata", TOKEN_A),
1127                http::Response::builder()
1128                    .status(200)
1129                    .body(SdkBody::from(vec![0xA0, 0xA1]))
1130                    .unwrap(),
1131            ),
1132        ]);
1133        let err = client.get("/latest/metadata").await.expect_err("no token");
1134        assert_full_error_contains!(err, "invalid UTF-8");
1135        http_client.assert_requests_match(&[]);
1136    }
1137
1138    // TODO(https://github.com/awslabs/aws-sdk-rust/issues/1117) This test is ignored on Windows because it uses Unix-style paths
1139    #[cfg_attr(windows, ignore)]
1140    /// Verify that the end-to-end real client has a 1-second connect timeout
1141    #[tokio::test]
1142    #[cfg(feature = "default-https-client")]
1143    async fn one_second_connect_timeout() {
1144        use crate::imds::client::ImdsError;
1145        use std::time::SystemTime;
1146        let client = Client::builder()
1147            // 240.* can never be resolved
1148            .endpoint("http://240.0.0.0")
1149            .expect("valid uri")
1150            .build();
1151        let now = SystemTime::now();
1152        let resp = client
1153            .get("/latest/metadata")
1154            .await
1155            .expect_err("240.0.0.0 will never resolve");
1156        match resp {
1157            err @ ImdsError::FailedToLoadToken(_)
1158                if format!("{}", DisplayErrorContext(&err)).contains("timeout") => {} // ok,
1159            other => panic!(
1160                "wrong error, expected construction failure with TimedOutError inside: {}",
1161                DisplayErrorContext(&other)
1162            ),
1163        }
1164        let time_elapsed = now.elapsed().unwrap();
1165        assert!(
1166            time_elapsed > Duration::from_secs(1),
1167            "time_elapsed should be greater than 1s but was {:?}",
1168            time_elapsed
1169        );
1170        assert!(
1171            time_elapsed < Duration::from_secs(2),
1172            "time_elapsed should be less than 2s but was {:?}",
1173            time_elapsed
1174        );
1175    }
1176
1177    /// HTTP client whose connection attempts all time out. It counts the attempts.
1178    #[derive(Clone, Debug, Default)]
1179    struct ConnectTimeoutClient {
1180        attempts: Arc<AtomicUsize>,
1181    }
1182
1183    impl HttpConnector for ConnectTimeoutClient {
1184        fn call(&self, _request: HttpRequest) -> HttpConnectorFuture {
1185            self.attempts.fetch_add(1, Ordering::SeqCst);
1186            HttpConnectorFuture::ready(Err(ConnectorError::timeout("connect timed out".into())))
1187        }
1188    }
1189
1190    impl HttpClient for ConnectTimeoutClient {
1191        fn http_connector(
1192            &self,
1193            _: &HttpConnectorSettings,
1194            _: &RuntimeComponents,
1195        ) -> SharedHttpConnector {
1196            self.clone().into_shared()
1197        }
1198    }
1199
1200    /// Make one IMDS request whose connections all time out, with 2 attempts per request and no
1201    /// backoff jitter. Returns the number of connection attempts and each backoff delay, in order.
1202    ///
1203    /// Sleeps return immediately and are only recorded, so this neither depends on nor spends
1204    /// wall-clock time.
1205    async fn connection_attempts_and_backoffs(
1206        retry_classifier: Option<ImdsResponseRetryClassifier>,
1207        behavior_version: BehaviorVersion,
1208    ) -> (usize, Vec<Duration>) {
1209        let http_client = ConnectTimeoutClient::default();
1210        let sleep = InstantSleep::unlogged();
1211        let mut builder = super::Client::builder()
1212            .max_attempts(2)
1213            .use_static_exponential_base()
1214            .configure(
1215                &ProviderConfig::no_configuration()
1216                    .with_http_client(http_client.clone())
1217                    .with_sleep_impl(sleep.clone())
1218                    .with_behavior_version(Some(behavior_version)),
1219            );
1220        if let Some(retry_classifier) = retry_classifier {
1221            builder = builder.retry_classifier(SharedRetryClassifier::new(retry_classifier));
1222        }
1223        let err = builder
1224            .build()
1225            .get("/latest/metadata")
1226            .await
1227            .expect_err("every connection attempt times out");
1228        assert_full_error_contains!(err, "connect timed out");
1229        (http_client.attempts.load(Ordering::SeqCst), sleep.logs())
1230    }
1231
1232    /// Retry classifier properly retries connect timeouts when configured to, using the backoff of
1233    /// the caller's behavior version for both the token request and the metadata request
1234    #[tokio::test]
1235    async fn retry_connect_timeouts() {
1236        let retry_connect_timeouts =
1237            || Some(ImdsResponseRetryClassifier::default().with_retry_connect_timeouts(true));
1238        // Each metadata attempt first loads a token, and each token load makes 2 attempts, so
1239        // there are 4 connection attempts. The backoffs are, in order: the first token load's,
1240        // the one between metadata attempts, and the second token load's.
1241        #[allow(deprecated)]
1242        let legacy = BehaviorVersion::v2024_03_28();
1243        assert_eq!(
1244            connection_attempts_and_backoffs(retry_connect_timeouts(), legacy).await,
1245            (4, vec![Duration::from_secs(1); 3]),
1246        );
1247        // Retry Behavior 2.1 lowers the base backoff for non-throttling errors to 50ms
1248        #[allow(deprecated)]
1249        let retry_2_1 = BehaviorVersion::v2026_11_10();
1250        assert_eq!(
1251            connection_attempts_and_backoffs(retry_connect_timeouts(), retry_2_1).await,
1252            (4, vec![Duration::from_millis(50); 3]),
1253        );
1254    }
1255
1256    /// The default retry classifier doesn't retry connect timeouts
1257    #[tokio::test]
1258    async fn connect_timeouts_not_retried_by_default() {
1259        assert_eq!(
1260            connection_attempts_and_backoffs(None, BehaviorVersion::latest()).await,
1261            (1, vec![]),
1262        );
1263    }
1264
1265    #[derive(Debug, Deserialize)]
1266    struct ImdsConfigTest {
1267        env: HashMap<String, String>,
1268        fs: HashMap<String, String>,
1269        endpoint_override: Option<String>,
1270        mode_override: Option<String>,
1271        result: Result<String, String>,
1272        docs: String,
1273    }
1274
1275    #[tokio::test]
1276    async fn endpoint_config_tests() -> Result<(), Box<dyn Error>> {
1277        let _logs = capture_test_logs();
1278
1279        let test_cases = std::fs::read_to_string("test-data/imds-config/imds-endpoint-tests.json")?;
1280        #[derive(Deserialize)]
1281        struct TestCases {
1282            tests: Vec<ImdsConfigTest>,
1283        }
1284
1285        let test_cases: TestCases = serde_json::from_str(&test_cases)?;
1286        let test_cases = test_cases.tests;
1287        for test in test_cases {
1288            check(test).await;
1289        }
1290        Ok(())
1291    }
1292
1293    async fn check(test_case: ImdsConfigTest) {
1294        let (http_client, watcher) = capture_request(None);
1295        let provider_config = ProviderConfig::no_configuration()
1296            .with_sleep_impl(TokioSleep::new())
1297            .with_env(Env::from(test_case.env))
1298            .with_fs(Fs::from_map(test_case.fs))
1299            .with_http_client(http_client);
1300        let mut imds_client = Client::builder().configure(&provider_config);
1301        if let Some(endpoint_override) = test_case.endpoint_override {
1302            imds_client = imds_client
1303                .endpoint(endpoint_override)
1304                .expect("invalid URI");
1305        }
1306
1307        if let Some(mode_override) = test_case.mode_override {
1308            imds_client = imds_client.endpoint_mode(mode_override.parse().unwrap());
1309        }
1310
1311        let imds_client = imds_client.build();
1312        match &test_case.result {
1313            Ok(uri) => {
1314                // this request will fail, we just want to capture the endpoint configuration
1315                let _ = imds_client.get("/hello").await;
1316                assert_eq!(&watcher.expect_request().uri().to_string(), uri);
1317            }
1318            Err(expected) => {
1319                let err = imds_client.get("/hello").await.expect_err("it should fail");
1320                let message = format!("{}", DisplayErrorContext(&err));
1321                assert!(
1322                    message.contains(expected),
1323                    "{}\nexpected error: {expected}\nactual error: {message}",
1324                    test_case.docs
1325                );
1326            }
1327        };
1328    }
1329}