-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathaws-oidc-token-provider.js
More file actions
264 lines (237 loc) · 8.28 KB
/
Copy pathaws-oidc-token-provider.js
File metadata and controls
264 lines (237 loc) · 8.28 KB
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
'use strict';
/**
* OIDC Token Provider for AWS Workload Identity Federation.
*
* Mints a GitHub Actions OIDC token, exchanges it for temporary AWS
* credentials via STS AssumeRoleWithWebIdentity, caches the result,
* and proactively refreshes before expiry.
*
* Token flow:
* 1. Request GitHub OIDC JWT from Actions runtime (audience: sts.amazonaws.com)
* 2. Exchange JWT for temporary AWS credentials via STS AssumeRoleWithWebIdentity
* 3. Cache credentials, schedule refresh at 75% of lifetime
* 4. Serve cached credentials synchronously via getCredentials()
*
* Note: AWS uses SigV4 request signing, not Bearer tokens. The consumer
* must use getCredentials() and sign the complete request (method, path,
* headers, body hash) with the returned access key, secret key, and
* session token.
*/
const { mintGitHubOidcToken, httpGet } = require('./github-oidc');
const { logRequest } = require('./logging');
// Refresh at 75% of credential lifetime (STS default is 3600s)
const REFRESH_FACTOR = 0.75;
const MIN_REFRESH_MARGIN_SECS = 300;
const REFRESH_RETRY_DELAY_MS = 30_000;
const MAX_INIT_RETRIES = 3;
/**
* @typedef {Object} AwsCredentials
* @property {string} accessKeyId
* @property {string} secretAccessKey
* @property {string} sessionToken
*/
/**
* @typedef {Object} AwsOidcTokenProviderConfig
* @property {string} requestUrl - ACTIONS_ID_TOKEN_REQUEST_URL
* @property {string} requestToken - ACTIONS_ID_TOKEN_REQUEST_TOKEN
* @property {string} roleArn - AWS IAM role ARN to assume
* @property {string} region - AWS region (e.g., us-east-1)
* @property {string} [roleSessionName] - Session name (default: awf-oidc-session)
* @property {string} [oidcAudience] - Audience for GitHub OIDC token (default: sts.amazonaws.com)
* @property {number} [retryDelayMs] - Retry delay after failed refresh (default: 30000)
* @property {number} [maxInitRetries] - Maximum retries for initial token acquisition (default: 3)
*/
class AwsOidcTokenProvider {
/**
* @param {AwsOidcTokenProviderConfig} config
*/
constructor(config) {
this._requestUrl = config.requestUrl;
this._requestToken = config.requestToken;
this._roleArn = config.roleArn;
this._region = config.region;
this._roleSessionName = config.roleSessionName || 'awf-oidc-session';
this._oidcAudience = config.oidcAudience || 'sts.amazonaws.com';
this._retryDelayMs = config.retryDelayMs ?? REFRESH_RETRY_DELAY_MS;
this._maxInitRetries = config.maxInitRetries ?? MAX_INIT_RETRIES;
/** @type {AwsCredentials|null} */
this._cachedCredentials = null;
this._expiresAt = 0;
this._refreshTimer = null;
this._refreshInFlight = null;
this._initialized = false;
this._initError = null;
}
/**
* Initialize by acquiring the first set of credentials.
* @returns {Promise<void>}
*/
async initialize() {
for (let attempt = 1; attempt <= this._maxInitRetries; attempt++) {
try {
await this._refreshCredentials();
this._initialized = true;
this._initError = null;
logRequest('info', 'aws_oidc_init_success', {
role_arn: this._roleArn,
region: this._region,
expires_in_secs: this._expiresAt - Math.floor(Date.now() / 1000),
});
return;
} catch (err) {
this._initError = err;
logRequest('warn', 'aws_oidc_init_retry', {
attempt,
max_retries: this._maxInitRetries,
error: err.message,
});
if (attempt < this._maxInitRetries) {
await this._sleep(this._retryDelayMs * attempt);
}
}
}
logRequest('error', 'aws_oidc_init_failed', {
error: this._initError?.message,
role_arn: this._roleArn,
});
}
/**
* Get the current cached AWS credentials synchronously.
* Returns null if no valid credentials are available.
* @returns {AwsCredentials|null}
*/
getCredentials() {
const now = Math.floor(Date.now() / 1000);
if (this._cachedCredentials && this._expiresAt > now) {
return this._cachedCredentials;
}
if (!this._refreshInFlight) {
this._scheduleRefresh(0);
}
return null;
}
/**
* Get the AWS region for this provider.
* @returns {string}
*/
getRegion() {
return this._region;
}
/** @returns {boolean} */
isReady() {
const now = Math.floor(Date.now() / 1000);
return !!(this._cachedCredentials && this._expiresAt > now);
}
shutdown() {
if (this._refreshTimer) {
clearTimeout(this._refreshTimer);
this._refreshTimer = null;
}
}
/**
* Exchange GitHub OIDC JWT for temporary AWS credentials via STS.
* Uses the HTTPS query API (no SDK dependency).
* @param {string} oidcJwt
* @returns {Promise<{credentials: AwsCredentials, expires_in: number}>}
*/
async _assumeRoleWithWebIdentity(oidcJwt) {
const params = new URLSearchParams({
Action: 'AssumeRoleWithWebIdentity',
Version: '2011-06-15',
RoleArn: this._roleArn,
RoleSessionName: this._roleSessionName,
WebIdentityToken: oidcJwt,
});
const stsHost = this._resolveStsHost();
const url = `https://${stsHost}/?${params.toString()}`;
const response = await httpGet(url, {
'Accept': 'application/json',
});
if (response.statusCode !== 200) {
throw new Error(`AWS STS AssumeRoleWithWebIdentity failed: HTTP ${response.statusCode} — ${response.body}`);
}
// STS returns XML by default, but JSON when Accept: application/json is set
// Parse the response to extract credentials
const data = JSON.parse(response.body);
const result = data.AssumeRoleWithWebIdentityResponse?.AssumeRoleWithWebIdentityResult;
if (!result?.Credentials) {
throw new Error('AWS STS response missing Credentials');
}
const creds = result.Credentials;
const expiration = new Date(creds.Expiration);
const expiresIn = Math.floor((expiration.getTime() - Date.now()) / 1000);
return {
credentials: {
accessKeyId: creds.AccessKeyId,
secretAccessKey: creds.SecretAccessKey,
sessionToken: creds.SessionToken,
},
expires_in: expiresIn > 0 ? expiresIn : 3600,
};
}
/**
* Resolve the STS endpoint for the configured region.
* Uses regional STS endpoints for lower latency.
* @returns {string}
*/
_resolveStsHost() {
// China regions use a separate partition
if (this._region.startsWith('cn-')) {
return `sts.${this._region}.amazonaws.com.cn`;
}
// GovCloud
if (this._region.startsWith('us-gov-')) {
return `sts.${this._region}.amazonaws.com`;
}
// Standard regions — use regional endpoint
return `sts.${this._region}.amazonaws.com`;
}
/**
* Full credential refresh: GitHub OIDC → AWS STS.
*/
async _refreshCredentials() {
const oidcJwt = await mintGitHubOidcToken({
requestUrl: this._requestUrl,
requestToken: this._requestToken,
audience: this._oidcAudience,
});
const { credentials, expires_in } = await this._assumeRoleWithWebIdentity(oidcJwt);
const now = Math.floor(Date.now() / 1000);
this._cachedCredentials = credentials;
this._expiresAt = now + expires_in;
const refreshInSecs = Math.max(
0,
Math.min(
expires_in * REFRESH_FACTOR,
expires_in - MIN_REFRESH_MARGIN_SECS
)
);
this._scheduleRefresh(Math.floor(refreshInSecs * 1000));
}
/** @param {number} delayMs */
_scheduleRefresh(delayMs) {
if (this._refreshTimer) clearTimeout(this._refreshTimer);
this._refreshTimer = setTimeout(() => {
this._refreshInFlight = this._refreshCredentials()
.then(() => {
logRequest('info', 'aws_oidc_refresh_success', {
expires_in_secs: this._expiresAt - Math.floor(Date.now() / 1000),
});
})
.catch((err) => {
logRequest('error', 'aws_oidc_refresh_failed', { error: err.message });
const now = Math.floor(Date.now() / 1000);
if (this._expiresAt > now) {
this._scheduleRefresh(this._retryDelayMs);
}
})
.finally(() => { this._refreshInFlight = null; });
}, delayMs);
if (this._refreshTimer.unref) this._refreshTimer.unref();
}
/** @param {number} ms */
_sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
module.exports = { AwsOidcTokenProvider };