aws_config/imds/
credentials.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! IMDSv2 Credentials Provider
7//!
8//! # Important
9//! This credential provider will NOT fallback to IMDSv1. Ensure that IMDSv2 is enabled on your instances.
10
11use super::client::error::ImdsError;
12use crate::imds::{self, Client};
13use crate::json_credentials::{parse_json_credentials, JsonCredentials, RefreshableCredentials};
14use crate::provider_config::ProviderConfig;
15use aws_credential_types::provider::{self, error::CredentialsError, future, ProvideCredentials};
16use aws_credential_types::Credentials;
17use aws_smithy_async::time::SharedTimeSource;
18use aws_types::os_shim_internal::Env;
19use std::borrow::Cow;
20use std::error::Error as StdError;
21use std::fmt;
22use std::sync::{Arc, RwLock};
23use std::time::{Duration, SystemTime};
24
25const CREDENTIAL_EXPIRATION_INTERVAL: Duration = Duration::from_secs(10 * 60);
26const WARNING_FOR_EXTENDING_CREDENTIALS_EXPIRY: &str =
27    "Attempting credential expiration extension due to a credential service availability issue. \
28    A refresh of these credentials will be attempted again within the next";
29
30#[derive(Debug)]
31struct ImdsCommunicationError {
32    source: Box<dyn StdError + Send + Sync + 'static>,
33}
34
35impl fmt::Display for ImdsCommunicationError {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(f, "could not communicate with IMDS")
38    }
39}
40
41impl StdError for ImdsCommunicationError {
42    fn source(&self) -> Option<&(dyn StdError + 'static)> {
43        Some(self.source.as_ref())
44    }
45}
46
47/// IMDSv2 Credentials Provider
48///
49/// _Note: This credentials provider will NOT fallback to the IMDSv1 flow._
50#[derive(Debug)]
51pub struct ImdsCredentialsProvider {
52    client: Client,
53    env: Env,
54    profile: Option<String>,
55    time_source: SharedTimeSource,
56    last_retrieved_credentials: Arc<RwLock<Option<Credentials>>>,
57}
58
59/// Builder for [`ImdsCredentialsProvider`]
60#[derive(Default, Debug)]
61pub struct Builder {
62    provider_config: Option<ProviderConfig>,
63    profile_override: Option<String>,
64    imds_override: Option<imds::Client>,
65    last_retrieved_credentials: Option<Credentials>,
66}
67
68impl Builder {
69    /// Override the configuration used for this provider
70    pub fn configure(mut self, provider_config: &ProviderConfig) -> Self {
71        self.provider_config = Some(provider_config.clone());
72        self
73    }
74
75    /// Override the [instance profile](instance-profile) used for this provider.
76    ///
77    /// When retrieving IMDS credentials, a call must first be made to
78    /// `<IMDS_BASE_URL>/latest/meta-data/iam/security-credentials/`. This returns the instance
79    /// profile used. By setting this parameter, retrieving the profile is skipped
80    /// and the provided value is used instead.
81    ///
82    /// [instance-profile]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html#ec2-instance-profile
83    pub fn profile(mut self, profile: impl Into<String>) -> Self {
84        self.profile_override = Some(profile.into());
85        self
86    }
87
88    /// Override the IMDS client used for this provider
89    ///
90    /// The IMDS client will be loaded and configured via `~/.aws/config` and environment variables,
91    /// however, if necessary the entire client may be provided directly.
92    ///
93    /// For more information about IMDS client configuration loading see [`imds::Client`]
94    pub fn imds_client(mut self, client: imds::Client) -> Self {
95        self.imds_override = Some(client);
96        self
97    }
98
99    #[allow(dead_code)]
100    #[cfg(test)]
101    fn last_retrieved_credentials(mut self, credentials: Credentials) -> Self {
102        self.last_retrieved_credentials = Some(credentials);
103        self
104    }
105
106    /// Create an [`ImdsCredentialsProvider`] from this builder.
107    pub fn build(self) -> ImdsCredentialsProvider {
108        let provider_config = self.provider_config.unwrap_or_default();
109        let env = provider_config.env();
110        let client = self
111            .imds_override
112            .unwrap_or_else(|| imds::Client::builder().configure(&provider_config).build());
113        ImdsCredentialsProvider {
114            client,
115            env,
116            profile: self.profile_override,
117            time_source: provider_config.time_source(),
118            last_retrieved_credentials: Arc::new(RwLock::new(self.last_retrieved_credentials)),
119        }
120    }
121}
122
123mod codes {
124    pub(super) const ASSUME_ROLE_UNAUTHORIZED_ACCESS: &str = "AssumeRoleUnauthorizedAccess";
125}
126
127impl ProvideCredentials for ImdsCredentialsProvider {
128    fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
129    where
130        Self: 'a,
131    {
132        future::ProvideCredentials::new(self.credentials())
133    }
134
135    fn fallback_on_interrupt(&self) -> Option<Credentials> {
136        self.last_retrieved_credentials.read().unwrap().clone()
137    }
138}
139
140impl ImdsCredentialsProvider {
141    /// Builder for [`ImdsCredentialsProvider`]
142    pub fn builder() -> Builder {
143        Builder::default()
144    }
145
146    fn imds_disabled(&self) -> bool {
147        match self.env.get(super::env::EC2_METADATA_DISABLED) {
148            Ok(value) => value.eq_ignore_ascii_case("true"),
149            _ => false,
150        }
151    }
152
153    /// Retrieve the instance profile from IMDS
154    async fn get_profile_uncached(&self) -> Result<String, CredentialsError> {
155        match self
156            .client
157            .get("/latest/meta-data/iam/security-credentials/")
158            .await
159        {
160            Ok(profile) => Ok(profile.as_ref().into()),
161            Err(ImdsError::ErrorResponse(context))
162                if context.response().status().as_u16() == 404 =>
163            {
164                tracing::warn!(
165                    "received 404 from IMDS when loading profile information. \
166                    Hint: This instance may not have an IAM role associated."
167                );
168                Err(CredentialsError::not_loaded("received 404 from IMDS"))
169            }
170            Err(ImdsError::FailedToLoadToken(context)) if context.is_dispatch_failure() => {
171                Err(CredentialsError::not_loaded(ImdsCommunicationError {
172                    source: context.into_source().into(),
173                }))
174            }
175            Err(other) => Err(CredentialsError::provider_error(other)),
176        }
177    }
178
179    // Extend the cached expiration time if necessary
180    //
181    // This allows continued use of the credentials even when IMDS returns expired ones.
182    fn maybe_extend_expiration(&self, expiration: SystemTime) -> SystemTime {
183        let now = self.time_source.now();
184        // If credentials from IMDS are not stale, use them as they are.
185        if now < expiration {
186            return expiration;
187        }
188
189        let mut rng = fastrand::Rng::with_seed(
190            now.duration_since(SystemTime::UNIX_EPOCH)
191                .expect("now should be after UNIX EPOCH")
192                .as_secs(),
193        );
194        // Calculate credentials' refresh offset with jitter, which should be less than 15 minutes
195        // the smallest amount of time credentials are valid for.
196        // Setting it to something longer than that may have the risk of the credentials expiring
197        // before the next refresh.
198        let refresh_offset = CREDENTIAL_EXPIRATION_INTERVAL + Duration::from_secs(rng.u64(0..=300));
199        let new_expiry = now + refresh_offset;
200
201        tracing::warn!(
202            "{WARNING_FOR_EXTENDING_CREDENTIALS_EXPIRY} {:.2} minutes.",
203            refresh_offset.as_secs_f64() / 60.0,
204        );
205
206        new_expiry
207    }
208
209    async fn retrieve_credentials(&self) -> provider::Result {
210        if self.imds_disabled() {
211            tracing::debug!(
212                "IMDS disabled because AWS_EC2_METADATA_DISABLED env var was set to `true`"
213            );
214            return Err(CredentialsError::not_loaded(
215                "IMDS disabled by AWS_ECS_METADATA_DISABLED env var",
216            ));
217        }
218        tracing::debug!("loading credentials from IMDS");
219        let profile: Cow<'_, str> = match &self.profile {
220            Some(profile) => profile.into(),
221            None => self.get_profile_uncached().await?.into(),
222        };
223        tracing::debug!(profile = %profile, "loaded profile");
224        let credentials = self
225            .client
226            .get(format!(
227                "/latest/meta-data/iam/security-credentials/{}",
228                profile
229            ))
230            .await
231            .map_err(CredentialsError::provider_error)?;
232        match parse_json_credentials(credentials.as_ref()) {
233            Ok(JsonCredentials::RefreshableCredentials(RefreshableCredentials {
234                access_key_id,
235                secret_access_key,
236                session_token,
237                expiration,
238                ..
239            })) => {
240                let expiration = self.maybe_extend_expiration(expiration);
241                let creds = Credentials::new(
242                    access_key_id,
243                    secret_access_key,
244                    Some(session_token.to_string()),
245                    expiration.into(),
246                    "IMDSv2",
247                );
248                *self.last_retrieved_credentials.write().unwrap() = Some(creds.clone());
249                Ok(creds)
250            }
251            Ok(JsonCredentials::Error { code, message })
252                if code == codes::ASSUME_ROLE_UNAUTHORIZED_ACCESS =>
253            {
254                Err(CredentialsError::invalid_configuration(format!(
255                    "Incorrect IMDS/IAM configuration: [{}] {}. \
256                        Hint: Does this role have a trust relationship with EC2?",
257                    code, message
258                )))
259            }
260            Ok(JsonCredentials::Error { code, message }) => {
261                Err(CredentialsError::provider_error(format!(
262                    "Error retrieving credentials from IMDS: {} {}",
263                    code, message
264                )))
265            }
266            // got bad data from IMDS, should not occur during normal operation:
267            Err(invalid) => Err(CredentialsError::unhandled(invalid)),
268        }
269    }
270
271    async fn credentials(&self) -> provider::Result {
272        match self.retrieve_credentials().await {
273            creds @ Ok(_) => creds,
274            // Any failure while retrieving credentials MUST NOT impede use of existing credentials.
275            err => match &*self.last_retrieved_credentials.read().unwrap() {
276                Some(creds) => Ok(creds.clone()),
277                _ => err,
278            },
279        }
280    }
281}
282
283#[cfg(test)]
284mod test {
285    use super::*;
286    use crate::imds::client::test::{
287        imds_request, imds_response, make_imds_client, token_request, token_response,
288    };
289    use crate::provider_config::ProviderConfig;
290    use aws_credential_types::provider::ProvideCredentials;
291    use aws_smithy_async::test_util::instant_time_and_sleep;
292    use aws_smithy_runtime::client::http::test_util::{ReplayEvent, StaticReplayClient};
293    use aws_smithy_types::body::SdkBody;
294    use std::time::{Duration, UNIX_EPOCH};
295    use tracing_test::traced_test;
296
297    const TOKEN_A: &str = "token_a";
298
299    #[tokio::test]
300    async fn profile_is_not_cached() {
301        let http_client = StaticReplayClient::new(vec![
302            ReplayEvent::new(
303                token_request("http://169.254.169.254", 21600),
304                token_response(21600, TOKEN_A),
305            ),
306            ReplayEvent::new(
307                imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
308                imds_response(r#"profile-name"#),
309            ),
310            ReplayEvent::new(
311                imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/profile-name", TOKEN_A),
312                imds_response("{\n  \"Code\" : \"Success\",\n  \"LastUpdated\" : \"2021-09-20T21:42:26Z\",\n  \"Type\" : \"AWS-HMAC\",\n  \"AccessKeyId\" : \"ASIARTEST\",\n  \"SecretAccessKey\" : \"testsecret\",\n  \"Token\" : \"testtoken\",\n  \"Expiration\" : \"2021-09-21T04:16:53Z\"\n}"),
313            ),
314            ReplayEvent::new(
315                imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
316                imds_response(r#"different-profile"#),
317            ),
318            ReplayEvent::new(
319                imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/different-profile", TOKEN_A),
320                imds_response("{\n  \"Code\" : \"Success\",\n  \"LastUpdated\" : \"2021-09-20T21:42:26Z\",\n  \"Type\" : \"AWS-HMAC\",\n  \"AccessKeyId\" : \"ASIARTEST2\",\n  \"SecretAccessKey\" : \"testsecret\",\n  \"Token\" : \"testtoken\",\n  \"Expiration\" : \"2021-09-21T04:16:53Z\"\n}"),
321            ),
322        ]);
323        let client = ImdsCredentialsProvider::builder()
324            .imds_client(make_imds_client(&http_client))
325            .build();
326        let creds1 = client.provide_credentials().await.expect("valid creds");
327        let creds2 = client.provide_credentials().await.expect("valid creds");
328        assert_eq!(creds1.access_key_id(), "ASIARTEST");
329        assert_eq!(creds2.access_key_id(), "ASIARTEST2");
330        http_client.assert_requests_match(&[]);
331    }
332
333    #[tokio::test]
334    #[traced_test]
335    async fn credentials_not_stale_should_be_used_as_they_are() {
336        let http_client = StaticReplayClient::new(vec![
337            ReplayEvent::new(
338                token_request("http://169.254.169.254", 21600),
339                token_response(21600, TOKEN_A),
340            ),
341            ReplayEvent::new(
342                imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
343                imds_response(r#"profile-name"#),
344            ),
345            ReplayEvent::new(
346                imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/profile-name", TOKEN_A),
347                imds_response("{\n  \"Code\" : \"Success\",\n  \"LastUpdated\" : \"2021-09-20T21:42:26Z\",\n  \"Type\" : \"AWS-HMAC\",\n  \"AccessKeyId\" : \"ASIARTEST\",\n  \"SecretAccessKey\" : \"testsecret\",\n  \"Token\" : \"testtoken\",\n  \"Expiration\" : \"2021-09-21T04:16:53Z\"\n}"),
348            ),
349        ]);
350
351        // set to 2021-09-21T04:16:50Z that makes returned credentials' expiry (2021-09-21T04:16:53Z)
352        // not stale
353        let time_of_request_to_fetch_credentials = UNIX_EPOCH + Duration::from_secs(1632197810);
354        let (time_source, sleep) = instant_time_and_sleep(time_of_request_to_fetch_credentials);
355
356        let provider_config = ProviderConfig::no_configuration()
357            .with_http_client(http_client.clone())
358            .with_sleep_impl(sleep)
359            .with_time_source(time_source);
360        let client = crate::imds::Client::builder()
361            .configure(&provider_config)
362            .build();
363        let provider = ImdsCredentialsProvider::builder()
364            .configure(&provider_config)
365            .imds_client(client)
366            .build();
367        let creds = provider.provide_credentials().await.expect("valid creds");
368        // The expiry should be equal to what is originally set (==2021-09-21T04:16:53Z).
369        assert_eq!(
370            creds.expiry(),
371            UNIX_EPOCH.checked_add(Duration::from_secs(1632197813))
372        );
373        http_client.assert_requests_match(&[]);
374
375        // There should not be logs indicating credentials are extended for stability.
376        assert!(!logs_contain(WARNING_FOR_EXTENDING_CREDENTIALS_EXPIRY));
377    }
378    #[tokio::test]
379    #[traced_test]
380    async fn expired_credentials_should_be_extended() {
381        let http_client = StaticReplayClient::new(vec![
382                ReplayEvent::new(
383                    token_request("http://169.254.169.254", 21600),
384                    token_response(21600, TOKEN_A),
385                ),
386                ReplayEvent::new(
387                    imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
388                    imds_response(r#"profile-name"#),
389                ),
390                ReplayEvent::new(
391                    imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/profile-name", TOKEN_A),
392                    imds_response("{\n  \"Code\" : \"Success\",\n  \"LastUpdated\" : \"2021-09-20T21:42:26Z\",\n  \"Type\" : \"AWS-HMAC\",\n  \"AccessKeyId\" : \"ASIARTEST\",\n  \"SecretAccessKey\" : \"testsecret\",\n  \"Token\" : \"testtoken\",\n  \"Expiration\" : \"2021-09-21T04:16:53Z\"\n}"),
393                ),
394            ]);
395
396        // set to 2021-09-21T17:41:25Z that renders fetched credentials already expired (2021-09-21T04:16:53Z)
397        let time_of_request_to_fetch_credentials = UNIX_EPOCH + Duration::from_secs(1632246085);
398        let (time_source, sleep) = instant_time_and_sleep(time_of_request_to_fetch_credentials);
399
400        let provider_config = ProviderConfig::no_configuration()
401            .with_http_client(http_client.clone())
402            .with_sleep_impl(sleep)
403            .with_time_source(time_source);
404        let client = crate::imds::Client::builder()
405            .configure(&provider_config)
406            .build();
407        let provider = ImdsCredentialsProvider::builder()
408            .configure(&provider_config)
409            .imds_client(client)
410            .build();
411        let creds = provider.provide_credentials().await.expect("valid creds");
412        assert!(creds.expiry().unwrap() > time_of_request_to_fetch_credentials);
413        http_client.assert_requests_match(&[]);
414
415        // We should inform customers that expired credentials are being used for stability.
416        assert!(logs_contain(WARNING_FOR_EXTENDING_CREDENTIALS_EXPIRY));
417    }
418
419    #[tokio::test]
420    #[cfg(feature = "rustls")]
421    async fn read_timeout_during_credentials_refresh_should_yield_last_retrieved_credentials() {
422        let client = crate::imds::Client::builder()
423            // 240.* can never be resolved
424            .endpoint("http://240.0.0.0")
425            .unwrap()
426            .build();
427        let expected = aws_credential_types::Credentials::for_tests();
428        let provider = ImdsCredentialsProvider::builder()
429            .imds_client(client)
430            // seed fallback credentials for testing
431            .last_retrieved_credentials(expected.clone())
432            .build();
433        let actual = provider.provide_credentials().await;
434        assert_eq!(actual.unwrap(), expected);
435    }
436
437    #[tokio::test]
438    #[cfg(feature = "rustls")]
439    async fn read_timeout_during_credentials_refresh_should_error_without_last_retrieved_credentials(
440    ) {
441        let client = crate::imds::Client::builder()
442            // 240.* can never be resolved
443            .endpoint("http://240.0.0.0")
444            .unwrap()
445            .build();
446        let provider = ImdsCredentialsProvider::builder()
447            .imds_client(client)
448            // no fallback credentials provided
449            .build();
450        let actual = provider.provide_credentials().await;
451        assert!(
452            matches!(actual, Err(CredentialsError::CredentialsNotLoaded(_))),
453            "\nexpected: Err(CredentialsError::CredentialsNotLoaded(_))\nactual: {actual:?}"
454        );
455    }
456
457    // TODO(https://github.com/awslabs/aws-sdk-rust/issues/1117) This test is ignored on Windows because it uses Unix-style paths
458    #[cfg_attr(windows, ignore)]
459    #[tokio::test]
460    #[cfg(feature = "rustls")]
461    async fn external_timeout_during_credentials_refresh_should_yield_last_retrieved_credentials() {
462        use aws_smithy_async::rt::sleep::AsyncSleep;
463        let client = crate::imds::Client::builder()
464            // 240.* can never be resolved
465            .endpoint("http://240.0.0.0")
466            .unwrap()
467            .build();
468        let expected = aws_credential_types::Credentials::for_tests();
469        let provider = ImdsCredentialsProvider::builder()
470            .imds_client(client)
471            // seed fallback credentials for testing
472            .last_retrieved_credentials(expected.clone())
473            .build();
474        let sleeper = aws_smithy_async::rt::sleep::TokioSleep::new();
475        let timeout = aws_smithy_async::future::timeout::Timeout::new(
476            provider.provide_credentials(),
477            // make sure `sleeper.sleep` will be timed out first by setting a shorter duration than connect timeout
478            sleeper.sleep(std::time::Duration::from_millis(100)),
479        );
480        match timeout.await {
481            Ok(_) => panic!("provide_credentials completed before timeout future"),
482            Err(_err) => match provider.fallback_on_interrupt() {
483                Some(actual) => assert_eq!(actual, expected),
484                None => panic!(
485                    "provide_credentials timed out and no credentials returned from fallback_on_interrupt"
486                ),
487            },
488        };
489    }
490
491    #[tokio::test]
492    async fn fallback_credentials_should_be_used_when_imds_returns_500_during_credentials_refresh()
493    {
494        let http_client = StaticReplayClient::new(vec![
495                // The next three request/response pairs will correspond to the first call to `provide_credentials`.
496                // During the call, it populates last_retrieved_credentials.
497                ReplayEvent::new(
498                    token_request("http://169.254.169.254", 21600),
499                    token_response(21600, TOKEN_A),
500                ),
501                ReplayEvent::new(
502                    imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
503                    imds_response(r#"profile-name"#),
504                ),
505                ReplayEvent::new(
506                    imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/profile-name", TOKEN_A),
507                    imds_response("{\n  \"Code\" : \"Success\",\n  \"LastUpdated\" : \"2021-09-20T21:42:26Z\",\n  \"Type\" : \"AWS-HMAC\",\n  \"AccessKeyId\" : \"ASIARTEST\",\n  \"SecretAccessKey\" : \"testsecret\",\n  \"Token\" : \"testtoken\",\n  \"Expiration\" : \"2021-09-21T04:16:53Z\"\n}"),
508                ),
509                // The following request/response pair corresponds to the second call to `provide_credentials`.
510                // During the call, IMDS returns response code 500.
511                ReplayEvent::new(
512                    imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
513                    http::Response::builder().status(500).body(SdkBody::empty()).unwrap(),
514                ),
515            ]);
516        let provider = ImdsCredentialsProvider::builder()
517            .imds_client(make_imds_client(&http_client))
518            .build();
519        let creds1 = provider.provide_credentials().await.expect("valid creds");
520        assert_eq!(creds1.access_key_id(), "ASIARTEST");
521        // `creds1` should be returned as fallback credentials and assigned to `creds2`
522        let creds2 = provider.provide_credentials().await.expect("valid creds");
523        assert_eq!(creds1, creds2);
524        http_client.assert_requests_match(&[]);
525    }
526}