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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include <zenutil/cloud/imdscredentials.h>
#include <zenutil/cloud/mockimds.h>
#include <zencore/string.h>
#include <zencore/testing.h>
#include <zencore/testutils.h>
#include <zenhttp/httpserver.h>
#include <thread>
ZEN_THIRD_PARTY_INCLUDES_START
#include <fmt/format.h>
#include <json11.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
namespace zen {
namespace {
/// Margin before expiration at which we proactively refresh credentials.
constexpr auto kRefreshMargin = std::chrono::minutes(5);
/// Parse an ISO 8601 UTC timestamp (e.g. "2026-03-14T20:00:00Z") into a system_clock time_point.
/// Returns epoch on failure.
std::chrono::system_clock::time_point ParseIso8601(std::string_view Timestamp)
{
// Expected format: YYYY-MM-DDTHH:MM:SSZ
if (Timestamp.size() < 19)
{
return {};
}
std::tm Tm = {};
// Manual parse since std::get_time is locale-dependent
Tm.tm_year = ParseInt<int>(Timestamp.substr(0, 4)).value_or(1970) - 1900;
Tm.tm_mon = ParseInt<int>(Timestamp.substr(5, 2)).value_or(1) - 1;
Tm.tm_mday = ParseInt<int>(Timestamp.substr(8, 2)).value_or(1);
Tm.tm_hour = ParseInt<int>(Timestamp.substr(11, 2)).value_or(0);
Tm.tm_min = ParseInt<int>(Timestamp.substr(14, 2)).value_or(0);
Tm.tm_sec = ParseInt<int>(Timestamp.substr(17, 2)).value_or(0);
#if ZEN_PLATFORM_WINDOWS
time_t EpochSeconds = _mkgmtime(&Tm);
#else
time_t EpochSeconds = timegm(&Tm);
#endif
if (EpochSeconds == -1)
{
return {};
}
return std::chrono::system_clock::from_time_t(EpochSeconds);
}
} // namespace
ImdsCredentialProvider::ImdsCredentialProvider(const ImdsCredentialProviderOptions& Options)
: m_Log(logging::Get("imds"))
, m_HttpClient(Options.Endpoint,
HttpClientSettings{
.LogCategory = "imds",
.ConnectTimeout = Options.ConnectTimeout,
.Timeout = Options.RequestTimeout,
})
{
ZEN_INFO("IMDS credential provider configured (endpoint: {})", m_HttpClient.GetBaseUri());
}
ImdsCredentialProvider::~ImdsCredentialProvider() = default;
SigV4Credentials
ImdsCredentialProvider::GetCredentials()
{
// Fast path: shared lock for cache hit
{
RwLock::SharedLockScope SharedLock(m_Lock);
if (!m_CachedCredentials.AccessKeyId.empty() && std::chrono::steady_clock::now() < m_ExpiresAt)
{
return m_CachedCredentials;
}
}
// Slow path: exclusive lock to refresh
RwLock::ExclusiveLockScope ExclusiveLock(m_Lock);
// Double-check after acquiring exclusive lock
if (!m_CachedCredentials.AccessKeyId.empty() && std::chrono::steady_clock::now() < m_ExpiresAt)
{
return m_CachedCredentials;
}
if (!FetchCredentials())
{
ZEN_WARN("failed to fetch credentials from IMDS");
return {};
}
return m_CachedCredentials;
}
void
ImdsCredentialProvider::InvalidateCache()
{
RwLock::ExclusiveLockScope ExclusiveLock(m_Lock);
m_CachedCredentials = {};
m_ExpiresAt = {};
}
bool
ImdsCredentialProvider::FetchToken()
{
HttpClient::KeyValueMap Headers;
Headers->emplace("X-aws-ec2-metadata-token-ttl-seconds", "21600");
HttpClient::Response Response = m_HttpClient.Put("/latest/api/token", Headers);
if (!Response.IsSuccess())
{
ZEN_WARN("IMDS token request failed: {}", Response.ErrorMessage("PUT /latest/api/token"));
return false;
}
m_ImdsToken = std::string(Response.AsText());
if (m_ImdsToken.empty())
{
ZEN_WARN("IMDS returned empty token");
return false;
}
return true;
}
bool
ImdsCredentialProvider::FetchCredentials()
{
// Step 1: Get IMDSv2 session token
if (!FetchToken())
{
return false;
}
HttpClient::KeyValueMap TokenHeader;
TokenHeader->emplace("X-aws-ec2-metadata-token", m_ImdsToken);
// Step 2: Discover IAM role name (if not already known)
if (m_RoleName.empty())
{
HttpClient::Response RoleResponse = m_HttpClient.Get("/latest/meta-data/iam/security-credentials/", TokenHeader);
if (!RoleResponse.IsSuccess())
{
ZEN_WARN("IMDS role discovery failed: {}", RoleResponse.ErrorMessage("GET iam/security-credentials/"));
return false;
}
m_RoleName = std::string(RoleResponse.AsText());
// Trim any trailing whitespace/newlines
while (!m_RoleName.empty() && (m_RoleName.back() == '\n' || m_RoleName.back() == '\r' || m_RoleName.back() == ' '))
{
m_RoleName.pop_back();
}
if (m_RoleName.empty())
{
ZEN_WARN("IMDS returned empty IAM role name");
return false;
}
ZEN_INFO("IMDS discovered IAM role: {}", m_RoleName);
}
// Step 3: Fetch credentials for the role
std::string CredentialPath = fmt::format("/latest/meta-data/iam/security-credentials/{}", m_RoleName);
HttpClient::Response CredResponse = m_HttpClient.Get(CredentialPath, TokenHeader);
if (!CredResponse.IsSuccess())
{
ZEN_WARN("IMDS credential fetch failed: {}", CredResponse.ErrorMessage("GET iam/security-credentials/" + m_RoleName));
return false;
}
// Step 4: Parse JSON response
std::string JsonError;
const json11::Json Json = json11::Json::parse(std::string(CredResponse.AsText()), JsonError);
if (!JsonError.empty())
{
ZEN_WARN("IMDS credential response JSON parse error: {}", JsonError);
return false;
}
std::string AccessKeyId = Json["AccessKeyId"].string_value();
std::string SecretAccessKey = Json["SecretAccessKey"].string_value();
std::string SessionToken = Json["Token"].string_value();
std::string Expiration = Json["Expiration"].string_value();
if (AccessKeyId.empty() || SecretAccessKey.empty())
{
ZEN_WARN("IMDS credential response missing AccessKeyId or SecretAccessKey");
return false;
}
// Compute local expiration time based on the Expiration field
auto ExpirationTime = ParseIso8601(Expiration);
auto Now = std::chrono::system_clock::now();
std::chrono::steady_clock::time_point NewExpiresAt;
if (ExpirationTime > Now)
{
auto TimeUntilExpiry = ExpirationTime - Now;
NewExpiresAt = std::chrono::steady_clock::now() + TimeUntilExpiry - kRefreshMargin;
}
else
{
// Expiration is in the past or unparseable — force refresh next time
NewExpiresAt = std::chrono::steady_clock::now();
}
bool KeyChanged = (m_CachedCredentials.AccessKeyId != AccessKeyId);
m_CachedCredentials.AccessKeyId = std::move(AccessKeyId);
m_CachedCredentials.SecretAccessKey = std::move(SecretAccessKey);
m_CachedCredentials.SessionToken = std::move(SessionToken);
m_ExpiresAt = NewExpiresAt;
if (KeyChanged)
{
ZEN_INFO("IMDS credentials refreshed (AccessKeyId: {}...)", m_CachedCredentials.AccessKeyId.substr(0, 8));
}
else
{
ZEN_DEBUG("IMDS credentials refreshed (unchanged key)");
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// Tests
#if ZEN_WITH_TESTS
void
imdscredentials_forcelink()
{
}
TEST_SUITE_BEGIN("util.cloud.imdscredentials");
TEST_CASE("imdscredentials.parse_iso8601")
{
// Verify basic ISO 8601 parsing
auto Tp = ParseIso8601("2026-03-14T20:00:00Z");
CHECK(Tp != std::chrono::system_clock::time_point{});
auto Epoch = std::chrono::system_clock::to_time_t(Tp);
std::tm Tm;
# if ZEN_PLATFORM_WINDOWS
gmtime_s(&Tm, &Epoch);
# else
gmtime_r(&Epoch, &Tm);
# endif
CHECK(Tm.tm_year + 1900 == 2026);
CHECK(Tm.tm_mon + 1 == 3);
CHECK(Tm.tm_mday == 14);
CHECK(Tm.tm_hour == 20);
CHECK(Tm.tm_min == 0);
CHECK(Tm.tm_sec == 0);
// Invalid input
auto Bad = ParseIso8601("bad");
CHECK(Bad == std::chrono::system_clock::time_point{});
}
// ---------------------------------------------------------------------------
// Integration test with mock IMDS server
// ---------------------------------------------------------------------------
struct TestImdsServer
{
compute::MockImdsService Mock;
void Start()
{
m_TmpDir.emplace();
m_Server = CreateHttpServer(HttpServerConfig{.ServerClass = "asio"});
m_Port = m_Server->Initialize(7576, m_TmpDir->Path() / "http");
REQUIRE(m_Port != -1);
m_Server->RegisterService(Mock);
m_ServerThread = std::thread([this]() { m_Server->Run(false); });
}
std::string Endpoint() const { return fmt::format("http://127.0.0.1:{}", m_Port); }
~TestImdsServer()
{
if (m_Server)
{
m_Server->RequestExit();
}
if (m_ServerThread.joinable())
{
m_ServerThread.join();
}
if (m_Server)
{
m_Server->Close();
}
}
private:
std::optional<ScopedTemporaryDirectory> m_TmpDir;
Ref<HttpServer> m_Server;
std::thread m_ServerThread;
int m_Port = -1;
};
TEST_CASE("imdscredentials.fetch_from_mock")
{
TestImdsServer Imds;
Imds.Mock.ActiveProvider = compute::CloudProvider::AWS;
Imds.Start();
ImdsCredentialProviderOptions Opts;
Opts.Endpoint = Imds.Endpoint();
Ref<ImdsCredentialProvider> Provider(new ImdsCredentialProvider(Opts));
SUBCASE("basic_credential_fetch")
{
SigV4Credentials Creds = Provider->GetCredentials();
CHECK(!Creds.AccessKeyId.empty());
CHECK(Creds.AccessKeyId == "ASIAIOSFODNN7EXAMPLE");
CHECK(Creds.SecretAccessKey == "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
CHECK(Creds.SessionToken == "FwoGZXIvYXdzEBYaDEXAMPLETOKEN");
}
SUBCASE("credentials_are_cached")
{
SigV4Credentials First = Provider->GetCredentials();
SigV4Credentials Second = Provider->GetCredentials();
CHECK(First.AccessKeyId == Second.AccessKeyId);
CHECK(First.SecretAccessKey == Second.SecretAccessKey);
}
SUBCASE("invalidate_forces_refresh")
{
SigV4Credentials First = Provider->GetCredentials();
CHECK(!First.AccessKeyId.empty());
// Change the credentials on the mock
Imds.Mock.Aws.IamAccessKeyId = "ASIANEWKEYEXAMPLE12";
Provider->InvalidateCache();
SigV4Credentials Second = Provider->GetCredentials();
CHECK(Second.AccessKeyId == "ASIANEWKEYEXAMPLE12");
}
SUBCASE("custom_role_name")
{
Imds.Mock.Aws.IamRoleName = "my-custom-role";
Ref<ImdsCredentialProvider> Provider2(new ImdsCredentialProvider(Opts));
SigV4Credentials Creds = Provider2->GetCredentials();
CHECK(!Creds.AccessKeyId.empty());
}
}
TEST_CASE("imdscredentials.unreachable_endpoint")
{
// Point at a non-existent server — should return empty credentials, not crash
ImdsCredentialProviderOptions Opts;
Opts.Endpoint = "http://127.0.0.1:1"; // unlikely to have anything listening
Opts.ConnectTimeout = std::chrono::milliseconds(100);
Opts.RequestTimeout = std::chrono::milliseconds(200);
Ref<ImdsCredentialProvider> Provider(new ImdsCredentialProvider(Opts));
SigV4Credentials Creds = Provider->GetCredentials();
CHECK(Creds.AccessKeyId.empty());
}
TEST_SUITE_END();
#endif
} // namespace zen
|