Repository navigation
Expand file tree
/
Copy pathcredentials.js
More file actions
285 lines (274 loc) · 12.7 KB
/
Copy pathcredentials.js
File metadata and controls
285 lines (274 loc) · 12.7 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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright (c) Microsoft Corporation. All rights reserved.
'use strict';
const { AsyncLocalStorage } = require('node:async_hooks');
const { inspect } = require('node:util');
const { LRUCache } = require('lru-cache');
const { createDefaultHttpClient } = require('@azure/core-rest-pipeline');
const { AzureAuthorityHosts, ClientAssertionCredential, ManagedIdentityCredential } = require('@azure/identity');
const { SecretClient } = require('@azure/keyvault-secrets');
const { AzureLogger } = require('@azure/logger');
const API_KEY_MODE = 'apiKey';
const OAUTH_MODE = 'oauth';
const BUNDLE_KEY = 'bundle';
const TOKEN_EXCHANGE_SCOPE = 'api://AzureADTokenExchange/.default';
const ACQUISITION_TIMEOUT_MS = 2500;
const REFRESH_POLL_MS = 30000;
const SECRET_TTL_MS = 300000;
const SECRET_REFRESH_MS = 240000;
const TOKEN_SKEW_MS = 30000;
const unavailable = () => new Error('provider credential unavailable');
/** @type {AsyncLocalStorage<AbortSignal>} */
const acquisition = new AsyncLocalStorage();
/** @type {typeof AzureLogger.log | undefined} */
let filteredLogger;
function reportRefreshFailure(cacheKind) {
console.warn(JSON.stringify({ logType: 'service', eventName: 'credential_refresh_failed',
cacheKind, failureReason: 'credential_unavailable' }));
}
// The installed identity SDK does not propagate every getToken abort signal to HTTP.
/** @returns {import('@azure/core-rest-pipeline').HttpClient} */
function credentialHttpClient() {
const client = createDefaultHttpClient();
return {
async sendRequest(request) {
const signal = acquisition.getStore();
if (!signal) return client.sendRequest(request);
const controller = new AbortController();
const existing = request.abortSignal;
const abort = () => controller.abort();
signal.addEventListener('abort', abort, { once: true });
existing?.addEventListener('abort', abort);
if (signal.aborted || existing?.aborted) controller.abort();
request.abortSignal = controller.signal;
try {
controller.signal.throwIfAborted();
return await client.sendRequest(request);
} finally {
signal.removeEventListener('abort', abort);
existing?.removeEventListener('abort', abort);
}
},
};
}
const sdkOptions = () => ({ retryOptions: { maxRetries: 0 }, httpClient: credentialHttpClient() });
/** @param {import('@azure/core-auth').AccessToken | null} token */
function checkToken(token, now) {
if (typeof token?.token !== 'string' || !token.token.trim() || !Number.isFinite(token.expiresOnTimestamp)
|| token.expiresOnTimestamp <= now + TOKEN_SKEW_MS) throw unavailable();
return token;
}
/**
* @typedef {{mode: 'apiKey', secret: string, identity: string}} ApiKeyCredential
* @typedef {{mode: 'oauth', accessToken: string}} OAuthCredential
* @typedef {ReturnType<typeof import('./config').readConfig>} AppConfig
* @typedef {{mode?: string, keyVaultSecretName?: string, identityKeyVaultSecretName?: string}} AuthConfig
* @typedef {{now?: () => number, schedule?: typeof setInterval, cancel?: typeof clearInterval}} RefreshOptions
*/
/** @param {AuthConfig} auth @param {AppConfig} config */
function isCacheEnabled(auth, config) {
const mode = auth.mode || API_KEY_MODE;
if (mode !== API_KEY_MODE && mode !== OAUTH_MODE) throw unavailable();
const setting = mode === API_KEY_MODE ? config.keyVaultCacheEnabled : config.accessTokenCacheEnabled;
if (setting == null) return true;
const value = setting.trim().toLowerCase();
if (value !== 'true' && value !== 'false') throw unavailable();
return value === 'true';
}
class ApiKeyCache {
/** @param {AuthConfig} auth @param {AppConfig} config */
constructor(auth, config, now = Date.now) {
this.now = now;
this.auth = { ...auth };
this.vaultUrl = config.keyVaultUrl;
this.identityClientId = config.managedIdentityClientId;
/** @type {SecretClient | undefined} */
this.client = undefined;
/** @type {LRUCache<string, {value: ApiKeyCredential, expiresAt: number}>} */
this.values = new LRUCache({ max: 1, ttlResolution: 0 });
this.refreshAt = 0;
this.stage = 'key_vault';
this.closed = false;
}
get() {
const entry = this.closed ? undefined : this.values.get(BUNDLE_KEY);
return entry && entry.expiresAt > this.now() ? entry.value : null;
}
async refresh(signal) {
if (this.closed) throw unavailable();
if (this.get() && this.refreshAt > this.now()) return;
const { keyVaultSecretName: key, identityKeyVaultSecretName: account } = this.auth;
if (!key || !this.vaultUrl) throw unavailable();
this.client ??= new SecretClient(this.vaultUrl,
new ManagedIdentityCredential({ clientId: this.identityClientId || undefined, ...sdkOptions() }), sdkOptions());
const [secret, identity] = await Promise.all([
this.client.getSecret(key, { abortSignal: signal }),
account ? this.client.getSecret(account, { abortSignal: signal }) : null,
]);
const now = this.now();
let expiresAt = now + SECRET_TTL_MS;
for (const item of [secret, identity]) {
if (!item) continue;
if (!item.value?.trim() || item.properties?.enabled === false || item.properties?.notBefore?.getTime() > now) throw unavailable();
if (item.properties?.expiresOn) expiresAt = Math.min(expiresAt, item.properties.expiresOn.getTime());
}
if (!secret.value?.trim() || (account && !identity?.value?.trim())
|| !Number.isFinite(expiresAt) || expiresAt <= now || this.closed) throw unavailable();
signal.throwIfAborted();
this.values.set(BUNDLE_KEY, { value: Object.freeze({ mode: API_KEY_MODE, secret: secret.value, identity: identity?.value || '' }),
expiresAt }, { ttl: expiresAt - now });
this.refreshAt = Math.min(now + SECRET_REFRESH_MS, expiresAt - TOKEN_SKEW_MS);
}
stop() { this.closed = true; this.values.clear(); }
[inspect.custom]() { return '[ApiKeyCache]'; }
toJSON() { return '[ApiKeyCache]'; }
}
class AccessTokenCache {
/** @param {AppConfig} config */
constructor(config, now = Date.now) {
if (!config.providerTenantId || !config.providerScope || !config.outboundClientId
|| !config.outboundManagedIdentityClientId) throw unavailable();
this.now = now;
this.scope = config.providerScope;
this.identity = new ManagedIdentityCredential({ clientId: config.outboundManagedIdentityClientId, ...sdkOptions() });
this.credential = new ClientAssertionCredential(config.providerTenantId, config.outboundClientId,
async () => (await this.assertion(acquisition.getStore())).token,
{ authorityHost: AzureAuthorityHosts.AzurePublicCloud, ...sdkOptions() });
/** @type {import('@azure/core-auth').AccessToken | null} */
this.token = null;
this.stage = 'provider_token';
this.closed = false;
}
get() {
if (this.closed || !this.token || this.token.expiresOnTimestamp <= this.now() + TOKEN_SKEW_MS) return null;
/** @type {OAuthCredential} */
const value = { mode: OAUTH_MODE, accessToken: this.token.token };
return Object.defineProperty(value, 'accessToken', { enumerable: false });
}
async assertion(signal) {
return checkToken(await this.identity.getToken(TOKEN_EXCHANGE_SCOPE, { abortSignal: signal }), this.now());
}
async refresh(signal) {
if (this.closed) throw unavailable();
this.stage = 'managed_identity';
await this.assertion(signal);
this.stage = 'provider_token';
const token = checkToken(await this.credential.getToken(this.scope, { abortSignal: signal }), this.now());
signal.throwIfAborted();
if (this.closed) throw unavailable();
this.token = token;
}
stop() { this.closed = true; this.token = null; }
[inspect.custom]() { return '[AccessTokenCache]'; }
toJSON() { return '[AccessTokenCache]'; }
}
// Disabled caches use request-scoped acquisition without starting the worker's refresh loop.
class CredentialTokenService {
/** @param {{cacheOptions?: RefreshOptions, reportFailure?: (kind: string) => void}} [options] */
constructor({ cacheOptions = {}, reportFailure = reportRefreshFailure } = {}) {
this.now = cacheOptions.now || Date.now;
this.schedule = cacheOptions.schedule || setInterval;
this.cancel = cacheOptions.cancel || clearInterval;
this.reportFailure = reportFailure;
/** @type {ApiKeyCache | AccessTokenCache | null} */
this.current = null;
/** @type {Promise<void> | null} */
this.pending = null;
/** @type {ReturnType<typeof setInterval> | null} */
this.timer = null;
/** @type {Set<AbortController>} */
this.controllers = new Set();
this.nextAttemptAt = 0;
this.closed = false;
}
/** @param {AuthConfig} auth @param {AppConfig} config */
async getCredentials(auth, config) {
if (this.closed) throw unavailable();
let enabled;
let cache;
try {
enabled = isCacheEnabled(auth, config);
cache = enabled && this.current ? this.current : this.createCache(auth, config);
}
catch { this.reportFailure('configuration'); throw unavailable(); }
if (!enabled) {
try {
await this.acquire(cache);
const value = cache.get();
if (!value || this.closed) throw unavailable();
return value;
} finally { cache.stop(); }
}
if (!this.current) {
try {
this.current = cache;
this.timer = this.schedule(() => { void this.refresh().catch(() => {}); }, REFRESH_POLL_MS);
this.timer.unref?.();
} catch { this.reportFailure('configuration'); throw unavailable(); }
}
const cached = this.current.get();
if (cached) return cached;
await this.refresh();
const value = this.current.get();
if (!value) throw unavailable();
return value;
}
resolve(auth, config) { return this.getCredentials(auth, config); }
/** @param {AuthConfig} auth @param {AppConfig} config */
createCache(auth, config) {
return (auth.mode || API_KEY_MODE) === API_KEY_MODE
? new ApiKeyCache(auth, config, this.now)
: new AccessTokenCache(config, this.now);
}
refresh() {
if (this.closed || !this.current) return Promise.reject(unavailable());
if (this.pending) return this.pending;
if (this.nextAttemptAt > this.now()) return Promise.reject(unavailable());
this.nextAttemptAt = this.now() + REFRESH_POLL_MS;
this.pending = this.acquire(this.current).finally(() => { this.pending = null; });
return this.pending;
}
/** @param {ApiKeyCache | AccessTokenCache} cache */
acquire(cache) {
const controller = new AbortController();
this.controllers.add(controller);
if (AzureLogger.log !== filteredLogger) {
const previous = AzureLogger.log;
filteredLogger = (...args) => { if (!acquisition.getStore()) previous(...args); };
AzureLogger.log = filteredLogger;
}
const timeout = setTimeout(() => controller.abort(), ACQUISITION_TIMEOUT_MS);
const interrupted = new Promise((_, reject) =>
controller.signal.addEventListener('abort', () => reject(unavailable()), { once: true }));
return acquisition.run(controller.signal, () => Promise.race([
Promise.resolve().then(() => { controller.signal.throwIfAborted(); return cache.refresh(controller.signal); }), interrupted,
])).catch(() => {
controller.abort();
if (!this.closed) this.reportFailure(cache.stage);
throw unavailable();
}).finally(() => {
clearTimeout(timeout);
this.controllers.delete(controller);
});
}
close() {
this.closed = true;
if (this.timer) this.cancel(this.timer);
for (const controller of this.controllers) controller.abort();
this.current?.stop();
}
[inspect.custom]() { return '[CredentialTokenService]'; }
toJSON() { return '[CredentialTokenService]'; }
}
const credentialTokenService = new CredentialTokenService();
const ProviderCredentials = CredentialTokenService;
const providerCredentials = credentialTokenService;
module.exports = {
ApiKeyCache,
AccessTokenCache,
CredentialTokenService,
credentialTokenService,
ProviderCredentials,
providerCredentials,
reportRefreshFailure,
isCacheEnabled,
};