1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
use super::client::error::ImdsError;
use crate::imds;
use crate::imds::client::LazyClient;
use crate::json_credentials::{parse_json_credentials, JsonCredentials, RefreshableCredentials};
use crate::provider_config::ProviderConfig;
use aws_credential_types::provider::{self, error::CredentialsError, future, ProvideCredentials};
use aws_credential_types::Credentials;
use aws_types::os_shim_internal::Env;
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;
#[derive(Debug)]
struct ImdsCommunicationError {
source: Box<dyn StdError + Send + Sync + 'static>,
}
impl fmt::Display for ImdsCommunicationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "could not communicate with IMDS")
}
}
impl StdError for ImdsCommunicationError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(self.source.as_ref())
}
}
#[derive(Debug)]
pub struct ImdsCredentialsProvider {
client: LazyClient,
env: Env,
profile: Option<String>,
}
#[derive(Default, Debug)]
pub struct Builder {
provider_config: Option<ProviderConfig>,
profile_override: Option<String>,
imds_override: Option<imds::Client>,
}
impl Builder {
pub fn configure(mut self, provider_config: &ProviderConfig) -> Self {
self.provider_config = Some(provider_config.clone());
self
}
pub fn profile(mut self, profile: impl Into<String>) -> Self {
self.profile_override = Some(profile.into());
self
}
pub fn imds_client(mut self, client: imds::Client) -> Self {
self.imds_override = Some(client);
self
}
pub fn build(self) -> ImdsCredentialsProvider {
let provider_config = self.provider_config.unwrap_or_default();
let env = provider_config.env();
let client = self
.imds_override
.map(LazyClient::from_ready_client)
.unwrap_or_else(|| {
imds::Client::builder()
.configure(&provider_config)
.build_lazy()
});
ImdsCredentialsProvider {
client,
env,
profile: self.profile_override,
}
}
}
mod codes {
pub(super) const ASSUME_ROLE_UNAUTHORIZED_ACCESS: &str = "AssumeRoleUnauthorizedAccess";
}
impl ProvideCredentials for ImdsCredentialsProvider {
fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
where
Self: 'a,
{
future::ProvideCredentials::new(self.credentials())
}
}
impl ImdsCredentialsProvider {
pub fn builder() -> Builder {
Builder::default()
}
fn imds_disabled(&self) -> bool {
match self.env.get(super::env::EC2_METADATA_DISABLED) {
Ok(value) => value.eq_ignore_ascii_case("true"),
_ => false,
}
}
async fn client(&self) -> Result<&imds::Client, CredentialsError> {
self.client.client().await.map_err(|build_error| {
CredentialsError::invalid_configuration(format!("{}", build_error))
})
}
async fn get_profile_uncached(&self) -> Result<String, CredentialsError> {
match self
.client()
.await?
.get("/latest/meta-data/iam/security-credentials/")
.await
{
Ok(profile) => Ok(profile),
Err(ImdsError::ErrorResponse(context))
if context.response().status().as_u16() == 404 =>
{
tracing::warn!(
"received 404 from IMDS when loading profile information. \
Hint: This instance may not have an IAM role associated."
);
Err(CredentialsError::not_loaded("received 404 from IMDS"))
}
Err(ImdsError::FailedToLoadToken(context)) if context.is_dispatch_failure() => {
Err(CredentialsError::not_loaded(ImdsCommunicationError {
source: context.into_source().into(),
}))
}
Err(other) => Err(CredentialsError::provider_error(other)),
}
}
async fn credentials(&self) -> provider::Result {
if self.imds_disabled() {
tracing::debug!("IMDS disabled because $AWS_EC2_METADATA_DISABLED was set to `true`");
return Err(CredentialsError::not_loaded(
"IMDS disabled by $AWS_ECS_METADATA_DISABLED",
));
}
tracing::debug!("loading credentials from IMDS");
let profile: Cow<'_, str> = match &self.profile {
Some(profile) => profile.into(),
None => self.get_profile_uncached().await?.into(),
};
tracing::debug!(profile = %profile, "loaded profile");
let credentials = self
.client()
.await?
.get(&format!(
"/latest/meta-data/iam/security-credentials/{}",
profile
))
.await
.map_err(CredentialsError::provider_error)?;
match parse_json_credentials(&credentials) {
Ok(JsonCredentials::RefreshableCredentials(RefreshableCredentials {
access_key_id,
secret_access_key,
session_token,
expiration,
..
})) => Ok(Credentials::new(
access_key_id,
secret_access_key,
Some(session_token.to_string()),
expiration.into(),
"IMDSv2",
)),
Ok(JsonCredentials::Error { code, message })
if code == codes::ASSUME_ROLE_UNAUTHORIZED_ACCESS =>
{
Err(CredentialsError::invalid_configuration(format!(
"Incorrect IMDS/IAM configuration: [{}] {}. \
Hint: Does this role have a trust relationship with EC2?",
code, message
)))
}
Ok(JsonCredentials::Error { code, message }) => {
Err(CredentialsError::provider_error(format!(
"Error retrieving credentials from IMDS: {} {}",
code, message
)))
}
Err(invalid) => Err(CredentialsError::unhandled(invalid)),
}
}
}
#[cfg(test)]
mod test {
use crate::imds::client::test::{
imds_request, imds_response, make_client, token_request, token_response,
};
use crate::imds::credentials::ImdsCredentialsProvider;
use aws_credential_types::provider::ProvideCredentials;
use aws_smithy_client::test_connection::TestConnection;
const TOKEN_A: &str = "token_a";
#[tokio::test]
async fn profile_is_not_cached() {
let connection = TestConnection::new(vec![
(
token_request("http://169.254.169.254", 21600),
token_response(21600, TOKEN_A),
),
(
imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
imds_response(r#"profile-name"#),
),
(
imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/profile-name", TOKEN_A),
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}"),
),
(
imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/", TOKEN_A),
imds_response(r#"different-profile"#),
),
(
imds_request("http://169.254.169.254/latest/meta-data/iam/security-credentials/different-profile", TOKEN_A),
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}"),
),
]);
let client = ImdsCredentialsProvider::builder()
.imds_client(make_client(&connection).await)
.build();
let creds1 = client.provide_credentials().await.expect("valid creds");
let creds2 = client.provide_credentials().await.expect("valid creds");
assert_eq!(creds1.access_key_id(), "ASIARTEST");
assert_eq!(creds2.access_key_id(), "ASIARTEST2");
connection.assert_requests_match(&[]);
}
}