forked from microsoft/rushstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzureAuthenticationBase.ts
More file actions
388 lines (353 loc) · 12.5 KB
/
AzureAuthenticationBase.ts
File metadata and controls
388 lines (353 loc) · 12.5 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
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
388
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import {
DeviceCodeCredential,
type DeviceCodeInfo,
AzureAuthorityHosts,
type DeviceCodeCredentialOptions,
type InteractiveBrowserCredentialInBrowserOptions,
InteractiveBrowserCredential,
type InteractiveBrowserCredentialNodeOptions,
type TokenCredential,
ChainedTokenCredential,
VisualStudioCodeCredential,
AzureCliCredential,
AzureDeveloperCliCredential,
AzurePowerShellCredential
} from '@azure/identity';
import type { TokenCredentialOptions } from '@azure/identity';
import { AdoCodespacesAuthCredential } from './AdoCodespacesAuthCredential';
import type { ITerminal } from '@rushstack/terminal';
import { CredentialCache } from '@rushstack/rush-sdk';
// Use a separate import line so the .d.ts file ends up with an `import type { ... }`
// See https://github.com/microsoft/rushstack/issues/3432
import type { ICredentialCacheEntry } from '@rushstack/rush-sdk';
import { PrintUtilities } from '@rushstack/terminal';
/**
* @public
*/
export type ExpiredCredentialBehavior = 'logWarning' | 'throwError' | 'ignore';
/**
* @public
*/
export interface ITryGetCachedCredentialOptionsBase {
/**
* The behavior to take when the cached credential has expired.
* Defaults to 'throwError'
*/
expiredCredentialBehavior?: ExpiredCredentialBehavior;
terminal?: ITerminal;
}
/**
* @public
*/
export interface ITryGetCachedCredentialOptionsLogWarning extends ITryGetCachedCredentialOptionsBase {
/**
* {@inheritdoc ITryGetCachedCredentialOptionsBase.expiredCredentialBehavior}
*/
expiredCredentialBehavior: 'logWarning';
terminal: ITerminal;
}
/**
* @public
*/
export interface ITryGetCachedCredentialOptionsThrow extends ITryGetCachedCredentialOptionsBase {
/**
* {@inheritdoc ITryGetCachedCredentialOptionsBase.expiredCredentialBehavior}
*/
expiredCredentialBehavior: 'throwError';
}
/**
* @public
*/
export interface ITryGetCachedCredentialOptionsIgnore extends ITryGetCachedCredentialOptionsBase {
/**
* {@inheritdoc ITryGetCachedCredentialOptionsBase.expiredCredentialBehavior}
*/
expiredCredentialBehavior: 'ignore';
}
export type ITryGetCachedCredentialOptions =
| ITryGetCachedCredentialOptionsLogWarning
| ITryGetCachedCredentialOptionsThrow
| ITryGetCachedCredentialOptionsIgnore;
/**
* @public
*/
export type AzureEnvironmentName = keyof typeof AzureAuthorityHosts;
/**
* @public
*/
export type LoginFlowType =
| 'DeviceCode'
| 'InteractiveBrowser'
| 'AdoCodespacesAuth'
| 'VisualStudioCode'
| 'AzureCli'
| 'AzureDeveloperCli'
| 'AzurePowerShell';
/**
* @public
*/
export interface IAzureAuthenticationBaseOptions {
azureEnvironment?: AzureEnvironmentName;
credentialUpdateCommandForLogging?: string | undefined;
loginFlow?: LoginFlowType;
/**
* A map to define the failover order for login flows. When a login flow fails to get a credential,
* the next login flow in the map will be attempted. If the login flow fails and there is no next
* login flow, the error will be thrown.
*
* @defaultValue
* ```json
* {
* "AdoCodespacesAuth": "VisualStudioCode",
* "VisualStudioCode": "AzureCli",
* "AzureCli": "AzureDeveloperCli",
* "AzureDeveloperCli": "AzurePowerShell",
* "AzurePowerShell": "InteractiveBrowser",
* "InteractiveBrowser": "DeviceCode",
* "DeviceCode": undefined
* }
* ```
*/
loginFlowFailover?: {
[key in LoginFlowType]?: LoginFlowType;
};
}
/**
* @public
*/ export interface ICredentialResult {
credentialString: string;
expiresOn?: Date;
credentialMetadata?: object;
}
/**
* @public
*/
export abstract class AzureAuthenticationBase {
protected abstract readonly _credentialNameForCache: string;
protected abstract readonly _credentialKindForLogging: string;
protected readonly _credentialUpdateCommandForLogging: string | undefined;
protected readonly _additionalDeviceCodeCredentialOptions: DeviceCodeCredentialOptions | undefined;
protected readonly _additionalInteractiveCredentialOptions:
| InteractiveBrowserCredentialNodeOptions
| undefined;
protected readonly _azureEnvironment: AzureEnvironmentName;
protected readonly _loginFlow: LoginFlowType;
protected readonly _failoverOrder:
| {
[key in LoginFlowType]?: LoginFlowType;
}
| undefined;
private __credentialCacheId: string | undefined;
protected get _credentialCacheId(): string {
if (!this.__credentialCacheId) {
const cacheIdParts: string[] = [
this._credentialNameForCache,
this._azureEnvironment,
...this._getCacheIdParts()
];
this.__credentialCacheId = cacheIdParts.join('|');
}
return this.__credentialCacheId;
}
public constructor(options: IAzureAuthenticationBaseOptions) {
const {
azureEnvironment = 'AzurePublicCloud',
loginFlow = process.env.CODESPACES === 'true' ? 'AdoCodespacesAuth' : 'VisualStudioCode'
} = options;
this._azureEnvironment = azureEnvironment;
this._credentialUpdateCommandForLogging = options.credentialUpdateCommandForLogging;
this._loginFlow = loginFlow;
this._failoverOrder = options.loginFlowFailover || {
AdoCodespacesAuth: 'VisualStudioCode',
VisualStudioCode: 'AzureCli',
AzureCli: 'AzureDeveloperCli',
AzureDeveloperCli: 'AzurePowerShell',
AzurePowerShell: 'InteractiveBrowser',
InteractiveBrowser: 'DeviceCode',
DeviceCode: undefined
};
}
public async updateCachedCredentialAsync(terminal: ITerminal, credential: string): Promise<void> {
await CredentialCache.usingAsync(
{
supportEditing: true
},
async (credentialsCache: CredentialCache) => {
credentialsCache.setCacheEntry(this._credentialCacheId, {
credential
});
await credentialsCache.saveIfModifiedAsync();
}
);
}
/**
* Launches an interactive flow to renew a cached credential.
*
* @param terminal - The terminal to log output to
* @param onlyIfExistingCredentialExpiresBefore - If specified, and a cached credential exists, action will only
* be taken if the cached credential expires before the specified date.
*/
public async updateCachedCredentialInteractiveAsync(
terminal: ITerminal,
onlyIfExistingCredentialExpiresBefore?: Date
): Promise<void> {
await CredentialCache.usingAsync(
{
supportEditing: true
},
async (credentialsCache: CredentialCache) => {
if (onlyIfExistingCredentialExpiresBefore) {
const existingCredentialExpiration: Date | undefined = credentialsCache.tryGetCacheEntry(
this._credentialCacheId
)?.expires;
if (
existingCredentialExpiration &&
existingCredentialExpiration > onlyIfExistingCredentialExpiresBefore
) {
return;
}
}
const credential: ICredentialResult = await this._getCredentialAsync(
terminal,
this._loginFlow,
credentialsCache
);
credentialsCache.setCacheEntry(this._credentialCacheId, {
credential: credential.credentialString,
expires: credential.expiresOn,
credentialMetadata: credential.credentialMetadata
});
await credentialsCache.saveIfModifiedAsync();
}
);
}
public async deleteCachedCredentialsAsync(terminal: ITerminal): Promise<void> {
await CredentialCache.usingAsync(
{
supportEditing: true
},
async (credentialsCache: CredentialCache) => {
credentialsCache.deleteCacheEntry(this._credentialCacheId);
await credentialsCache.saveIfModifiedAsync();
}
);
}
public async tryGetCachedCredentialAsync(
options?: ITryGetCachedCredentialOptionsThrow | ITryGetCachedCredentialOptionsIgnore
): Promise<ICredentialCacheEntry | undefined>;
public async tryGetCachedCredentialAsync(
options: ITryGetCachedCredentialOptionsLogWarning
): Promise<ICredentialCacheEntry | undefined>;
public async tryGetCachedCredentialAsync(
{ expiredCredentialBehavior, terminal }: ITryGetCachedCredentialOptions = {
expiredCredentialBehavior: 'throwError'
}
): Promise<ICredentialCacheEntry | undefined> {
let cacheEntry: ICredentialCacheEntry | undefined;
await CredentialCache.usingAsync(
{
supportEditing: false
},
(credentialsCache: CredentialCache) => {
cacheEntry = credentialsCache.tryGetCacheEntry(this._credentialCacheId);
}
);
const expirationTime: number | undefined = cacheEntry?.expires?.getTime();
if (expirationTime && expirationTime < Date.now()) {
if (expiredCredentialBehavior === 'logWarning' || expiredCredentialBehavior === 'throwError') {
let errorMessage: string = `Cached Azure ${this._credentialKindForLogging} credentials have expired.`;
if (this._credentialUpdateCommandForLogging) {
errorMessage += ` Update the credentials by running "${this._credentialUpdateCommandForLogging}".`;
}
if (expiredCredentialBehavior === 'logWarning') {
terminal.writeWarningLine(errorMessage);
} else if (expiredCredentialBehavior === 'throwError') {
throw new Error(errorMessage);
}
}
return undefined;
} else {
return cacheEntry;
}
}
/**
* Get parts of the cache ID that are specific to the credential type. Note that this should
* not contain the Azure environment or the {@link AzureAuthenticationBase._credentialNameForCache}
* value, as those are added automatically.
*/
protected abstract _getCacheIdParts(): string[];
protected abstract _getCredentialFromTokenAsync(
terminal: ITerminal,
tokenCredential: TokenCredential,
credentialsCache: CredentialCache
): Promise<ICredentialResult>;
private async _getCredentialAsync(
terminal: ITerminal,
loginFlow: LoginFlowType,
credentialsCache: CredentialCache
): Promise<ICredentialResult> {
const authorityHost: string | undefined = AzureAuthorityHosts[this._azureEnvironment];
if (!authorityHost) {
throw new Error(`Unexpected Azure environment: ${this._azureEnvironment}`);
}
const interactiveCredentialOptions: (
| InteractiveBrowserCredentialNodeOptions
| InteractiveBrowserCredentialInBrowserOptions
) &
DeviceCodeCredentialOptions = {
...this._additionalInteractiveCredentialOptions,
authorityHost
};
const deviceCodeCredentialOptions: DeviceCodeCredentialOptions = {
...this._additionalDeviceCodeCredentialOptions,
...interactiveCredentialOptions,
userPromptCallback: (deviceCodeInfo: DeviceCodeInfo) => {
PrintUtilities.printMessageInBox(deviceCodeInfo.message, terminal);
}
};
const options: TokenCredentialOptions = { authorityHost };
const priority: Set<LoginFlowType> = new Set([loginFlow]);
for (const credType of priority) {
const next: LoginFlowType | undefined = this._failoverOrder?.[credType];
if (next) {
priority.add(next);
}
}
const knownCredentialTypes: Record<
LoginFlowType,
new (options: TokenCredentialOptions) => TokenCredential
> = {
DeviceCode: class extends DeviceCodeCredential {
public new(credentialOptions: DeviceCodeCredentialOptions): DeviceCodeCredential {
return new DeviceCodeCredential({
...deviceCodeCredentialOptions,
...credentialOptions
});
}
},
InteractiveBrowser: class extends InteractiveBrowserCredential {
public new(credentialOptions: InteractiveBrowserCredentialNodeOptions): InteractiveBrowserCredential {
return new InteractiveBrowserCredential({ ...interactiveCredentialOptions, ...credentialOptions });
}
},
AdoCodespacesAuth: AdoCodespacesAuthCredential,
VisualStudioCode: VisualStudioCodeCredential,
AzureCli: AzureCliCredential,
AzureDeveloperCli: AzureDeveloperCliCredential,
AzurePowerShell: AzurePowerShellCredential
};
const credentials: TokenCredential[] = Array.from(
priority,
(credType) => new knownCredentialTypes[credType](options)
);
const tokenCredential: TokenCredential = new ChainedTokenCredential(...credentials);
try {
return await this._getCredentialFromTokenAsync(terminal, tokenCredential, credentialsCache);
} catch (error) {
terminal.writeVerbose(`Failed to get credentials with ${loginFlow}: ${error}`);
throw error;
}
}
}