-
Notifications
You must be signed in to change notification settings - Fork 665
Expand file tree
/
Copy pathauthclient.ts
More file actions
651 lines (581 loc) · 19.7 KB
/
authclient.ts
File metadata and controls
651 lines (581 loc) · 19.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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// Copyright 2012 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {EventEmitter} from 'events';
import {Gaxios, GaxiosOptions, GaxiosPromise, GaxiosResponse} from 'gaxios';
import {Credentials} from './credentials';
import {OriginalAndCamel, originalOrCamelOptions} from '../util';
import {log as makeLog} from 'google-logging-utils';
import {PRODUCT_NAME, USER_AGENT} from '../shared.cjs';
import {
RegionalAccessBoundaryData,
RegionalAccessBoundaryManager,
} from './regionalaccessboundary';
/**
* An interface for enforcing `fetch`-type compliance.
*
* @remarks
*
* This provides type guarantees during build-time, ensuring the `fetch` method is 1:1
* compatible with the `Gaxios#fetch` API.
*/
interface GaxiosFetchCompliance {
fetch: typeof fetch | Gaxios['fetch'];
}
/**
* Easy access to symbol-indexed strings on config objects.
*/
export type SymbolIndexString = {
[key: symbol]: string | undefined;
};
/**
* Base auth configurations (e.g. from JWT or `.json` files) with conventional
* camelCased options.
*
* @privateRemarks
*
* This interface is purposely not exported so that it can be removed once
* {@link https://github.com/microsoft/TypeScript/issues/50715} has been
* resolved. Then, we can use {@link OriginalAndCamel} to shrink this interface.
*
* Tracking: {@link https://github.com/googleapis/google-auth-library-nodejs/issues/1686}
*/
interface AuthJSONOptions {
/**
* The project ID corresponding to the current credentials if available.
*/
project_id: string | null;
/**
* An alias for {@link AuthJSONOptions.project_id `project_id`}.
*/
projectId: AuthJSONOptions['project_id'];
/**
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
* See {@link https://cloud.google.com/docs/quota Working with quotas}
*/
quota_project_id: string;
/**
* An alias for {@link AuthJSONOptions.quota_project_id `quota_project_id`}.
*/
quotaProjectId: AuthJSONOptions['quota_project_id'];
/**
* The default service domain for a given Cloud universe.
*
* @example
* 'googleapis.com'
*/
universe_domain: string;
/**
* An alias for {@link AuthJSONOptions.universe_domain `universe_domain`}.
*/
universeDomain: AuthJSONOptions['universe_domain'];
}
/**
* Base `AuthClient` configuration.
*
* The camelCased options are aliases of the snake_cased options, supporting both
* JSON API and JS conventions.
*/
export interface AuthClientOptions
extends Partial<OriginalAndCamel<AuthJSONOptions>> {
/**
* An API key to use, optional.
*/
apiKey?: string;
credentials?: Credentials;
/**
* The {@link Gaxios `Gaxios`} instance used for making requests.
*
* @see {@link AuthClientOptions.useAuthRequestParameters}
*/
transporter?: Gaxios;
/**
* Provides default options to the transporter, such as {@link GaxiosOptions.agent `agent`} or
* {@link GaxiosOptions.retryConfig `retryConfig`}.
*
* This option is ignored if {@link AuthClientOptions.transporter `gaxios`} has been provided
*/
transporterOptions?: GaxiosOptions;
/**
* The expiration threshold in milliseconds before forcing token refresh of
* unexpired tokens.
*/
eagerRefreshThresholdMillis?: number;
/**
* Whether to attempt to refresh tokens on status 401/403 responses
* even if an attempt is made to refresh the token preemptively based
* on the expiry_date.
*/
forceRefreshOnFailure?: boolean;
/**
* Enables/disables the adding of the AuthClient's default interceptor.
*
* @see {@link AuthClientOptions.transporter}
*
* @remarks
*
* Disabling is useful for debugging and experimentation.
*
* @default true
*/
useAuthRequestParameters?: boolean;
}
/**
* The default cloud universe
*
* @see {@link AuthJSONOptions.universe_domain}
*/
export const DEFAULT_UNIVERSE = 'googleapis.com';
/**
* The default {@link AuthClientOptions.eagerRefreshThresholdMillis}
*/
export const DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000;
/**
* Defines the root interface for all clients that generate credentials
* for calling Google APIs. All clients should implement this interface.
*/
export interface CredentialsClient {
projectId?: AuthClientOptions['projectId'];
eagerRefreshThresholdMillis: NonNullable<
AuthClientOptions['eagerRefreshThresholdMillis']
>;
forceRefreshOnFailure: NonNullable<
AuthClientOptions['forceRefreshOnFailure']
>;
/**
* @return A promise that resolves with the current GCP access token
* response. If the current credential is expired, a new one is retrieved.
*/
getAccessToken(): Promise<GetAccessTokenResponse>;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* { authorization: 'Bearer <access_token_value>' }
* @param url The URI being authorized.
*/
getRequestHeaders(url?: string | URL): Promise<Headers>;
/**
* Provides an alternative Gaxios request implementation with auth credentials
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
/**
* Sets the auth credentials.
*/
setCredentials(credentials: Credentials): void;
/**
* Subscribes a listener to the tokens event triggered when a token is
* generated.
*
* @param event The tokens event to subscribe to.
* @param listener The listener that triggers on event trigger.
* @return The current client instance.
*/
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export declare interface AuthClient {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
/**
* The base of all Auth Clients.
*/
export abstract class AuthClient
extends EventEmitter
implements CredentialsClient, GaxiosFetchCompliance
{
apiKey?: string;
projectId?: string | null;
/**
* The quota project ID. The quota project can be used by client libraries for the billing purpose.
* See {@link https://cloud.google.com/docs/quota Working with quotas}
*/
quotaProjectId?: string;
/**
* The {@link Gaxios `Gaxios`} instance used for making requests.
*/
transporter: Gaxios;
credentials: Credentials = {};
eagerRefreshThresholdMillis = DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;
forceRefreshOnFailure = false;
universeDomain = DEFAULT_UNIVERSE;
protected regionalAccessBoundaryManager: RegionalAccessBoundaryManager;
/**
* Symbols that can be added to GaxiosOptions to specify the method name that is
* making an RPC call, for logging purposes, as well as a string ID that can be
* used to correlate calls and responses.
*/
static readonly RequestMethodNameSymbol: unique symbol = Symbol(
'request method name',
);
static readonly RequestLogIdSymbol: unique symbol = Symbol('request log id');
constructor(opts: AuthClientOptions = {}) {
super();
const options = originalOrCamelOptions(opts);
// Shared auth options
this.apiKey = opts.apiKey;
this.projectId = options.get('project_id') ?? null;
this.quotaProjectId = options.get('quota_project_id');
this.credentials = options.get('credentials') ?? {};
this.universeDomain = options.get('universe_domain') ?? DEFAULT_UNIVERSE;
// Shared client options
this.transporter = opts.transporter ?? new Gaxios(opts.transporterOptions);
this.regionalAccessBoundaryManager = new RegionalAccessBoundaryManager({
transporter: this.transporter,
getLookupUrl: async () => this.getRegionalAccessBoundaryUrl(),
isUniverseDomainDefault: () => this.universeDomain === DEFAULT_UNIVERSE,
});
if (options.get('useAuthRequestParameters') !== false) {
this.transporter.interceptors.request.add(
AuthClient.DEFAULT_REQUEST_INTERCEPTOR,
);
this.transporter.interceptors.response.add(
AuthClient.DEFAULT_RESPONSE_INTERCEPTOR,
);
}
if (opts.eagerRefreshThresholdMillis) {
this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis;
}
this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false;
}
/**
* A {@link fetch `fetch`} compliant API for {@link AuthClient}.
*
* @see {@link AuthClient.request} for the classic method.
*
* @remarks
*
* This is useful as a drop-in replacement for `fetch` API usage.
*
* @example
*
* ```ts
* const authClient = new AuthClient();
* const fetchWithAuthClient: typeof fetch = (...args) => authClient.fetch(...args);
* await fetchWithAuthClient('https://example.com');
* ```
*
* @param args `fetch` API or {@link Gaxios.fetch `Gaxios#fetch`} parameters
* @returns the {@link GaxiosResponse} with Gaxios-added properties
*/
fetch<T>(...args: Parameters<Gaxios['fetch']>): GaxiosPromise<T> {
// Up to 2 parameters in either overload
const input = args[0];
const init = args[1];
let url: URL | undefined = undefined;
const headers = new Headers();
// prepare URL
if (typeof input === 'string') {
url = new URL(input);
} else if (input instanceof URL) {
url = input;
} else if (input && input.url) {
url = new URL(input.url);
}
// prepare headers
if (input && typeof input === 'object' && 'headers' in input) {
Gaxios.mergeHeaders(headers, input.headers);
}
if (init) {
Gaxios.mergeHeaders(headers, new Headers(init.headers));
}
// prepare request
if (typeof input === 'object' && !(input instanceof URL)) {
// input must have been a non-URL object
return this.request({...init, ...input, headers, url});
} else {
// input must have been a string or URL
return this.request({...init, headers, url});
}
}
/**
* The public request API in which credentials may be added to the request.
*
* @see {@link AuthClient.fetch} for the modern method.
*
* @param options options for `gaxios`
*/
abstract request<T>(options: GaxiosOptions): GaxiosPromise<T>;
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* ```ts
* new Headers({'authorization': 'Bearer <access_token_value>'});
* ```
*
* @param url The URI being authorized.
*/
abstract getRequestHeaders(url?: string | URL): Promise<Headers>;
/**
* @return A promise that resolves with the current GCP access token
* response. If the current credential is expired, a new one is retrieved.
*/
abstract getAccessToken(): Promise<{
token?: string | null;
res?: GaxiosResponse | null;
}>;
/**
* Returns the regional access boundary lookup URL for the current client.
* This method is intended for internal use by the RegionalAccessBoundaryManager
* and should not be called directly by users.
*
* @return The regional access boundary URL string, or `null` if the client type
* does not support regional access boundaries.
* @throws {Error} If the URL cannot be constructed for a compatible client,
* for instance, if a required property like a service account email is missing.
* @internal
*/
public async getRegionalAccessBoundaryUrl(): Promise<string | null> {
return null;
}
/**
* Sets the auth credentials.
*/
setCredentials(credentials: Credentials) {
this.credentials = credentials;
}
/**
* Returns the current regional access boundary data.
* @internal
*/
getRegionalAccessBoundary(): RegionalAccessBoundaryData | null {
return this.regionalAccessBoundaryManager.data;
}
/**
* Returns the current regional access boundary cooldown time in milliseconds.
* @internal
*/
getRegionalAccessBoundaryCooldownTime(): number {
return this.regionalAccessBoundaryManager.cooldownTime;
}
/**
* Append additional headers, e.g., x-goog-user-project, shared across the
* classes inheriting AuthClient. This method should be used by any method
* that overrides getRequestMetadataAsync(), which is a shared helper for
* setting request information in both gRPC and HTTP API calls.
*
* @param headers object to append additional headers to.
*/
protected addSharedMetadataHeaders(headers: Headers): Headers {
// quota_project_id, stored in application_default_credentials.json, is set in
// the x-goog-user-project header, to indicate an alternate account for
// billing and quota:
if (
!headers.has('x-goog-user-project') && // don't override a value the user sets.
this.quotaProjectId
) {
headers.set('x-goog-user-project', this.quotaProjectId);
}
return headers;
}
/**
* Applies regional access boundary rules to the provided headers.
* This includes adding the x-allowed-locations header and triggering
* a background refresh if needed.
* @param headers The headers to update.
* @param url Optional destination URL of the request. If missing, assumed global.
*/
protected applyRegionalAccessBoundary(
headers: Headers,
url?: string | URL,
): void {
const rabHeader =
this.regionalAccessBoundaryManager.getRegionalAccessBoundaryHeader(
url,
headers,
);
if (rabHeader) {
headers.set('x-allowed-locations', rabHeader);
}
}
/**
* Adds the `x-goog-user-project`, `authorization`, and 'x-allowed-locations'
* headers to the target Headers
* object, if they exist on the source.
*
* @param target the headers to target
* @param source the headers to source from
* @returns the target headers
*/
protected applyHeadersFromSource<T extends Headers>(
target: T,
source: Headers,
): T {
const xGoogUserProject = source.get('x-goog-user-project');
const authorizationHeader = source.get('authorization');
const xGoogAllowedLocs = source.get('x-allowed-locations');
if (xGoogUserProject) {
target.set('x-goog-user-project', xGoogUserProject);
}
if (authorizationHeader) {
target.set('authorization', authorizationHeader);
}
if (xGoogAllowedLocs) {
target.set('x-allowed-locations', xGoogAllowedLocs);
}
return target;
}
static log = makeLog('auth');
static readonly DEFAULT_REQUEST_INTERCEPTOR: Parameters<
Gaxios['interceptors']['request']['add']
>[0] = {
resolved: async config => {
// Set `x-goog-api-client`, if not already set
if (!config.headers.has('x-goog-api-client')) {
const nodeVersion = process.version.replace(/^v/, '');
config.headers.set('x-goog-api-client', `gl-node/${nodeVersion}`);
}
// Set `User-Agent`
const userAgent = config.headers.get('User-Agent');
if (!userAgent) {
config.headers.set('User-Agent', USER_AGENT);
} else if (!userAgent.includes(`${PRODUCT_NAME}/`)) {
config.headers.set('User-Agent', `${userAgent} ${USER_AGENT}`);
}
try {
const symbols: SymbolIndexString =
config as unknown as SymbolIndexString;
const methodName = symbols[AuthClient.RequestMethodNameSymbol];
// This doesn't need to be very unique or interesting, it's just an aid for
// matching requests to responses.
const logId = `${Math.floor(Math.random() * 1000)}`;
symbols[AuthClient.RequestLogIdSymbol] = logId;
// Boil down the object we're printing out.
const logObject = {
url: config.url,
headers: config.headers,
};
if (methodName) {
AuthClient.log.info(
'%s [%s] request %j',
methodName,
logId,
logObject,
);
} else {
AuthClient.log.info('[%s] request %j', logId, logObject);
}
} catch (e) {
// Logging must not create new errors; swallow them all.
}
return config;
},
};
static readonly DEFAULT_RESPONSE_INTERCEPTOR: Parameters<
Gaxios['interceptors']['response']['add']
>[0] = {
resolved: async response => {
try {
const symbols: SymbolIndexString =
response.config as unknown as SymbolIndexString;
const methodName = symbols[AuthClient.RequestMethodNameSymbol];
const logId = symbols[AuthClient.RequestLogIdSymbol];
if (methodName) {
AuthClient.log.info(
'%s [%s] response %j',
methodName,
logId,
response.data,
);
} else {
AuthClient.log.info('[%s] response %j', logId, response.data);
}
} catch (e) {
// Logging must not create new errors; swallow them all.
}
return response;
},
rejected: async error => {
try {
const symbols: SymbolIndexString =
error.config as unknown as SymbolIndexString;
const methodName = symbols[AuthClient.RequestMethodNameSymbol];
const logId = symbols[AuthClient.RequestLogIdSymbol];
if (methodName) {
AuthClient.log.info(
'%s [%s] error %j',
methodName,
logId,
error.response?.data,
);
} else {
AuthClient.log.error('[%s] error %j', logId, error.response?.data);
}
} catch (e) {
// Logging must not create new errors; swallow them all.
}
// Re-throw the error.
throw error;
},
};
/**
* Sets the method name that is making a Gaxios request, so that logging may tag
* log lines with the operation.
* @param config A Gaxios request config
* @param methodName The method name making the call
*/
static setMethodName(config: GaxiosOptions, methodName: string) {
try {
const symbols: SymbolIndexString = config as unknown as SymbolIndexString;
symbols[AuthClient.RequestMethodNameSymbol] = methodName;
} catch (e) {
// Logging must not create new errors; swallow them all.
}
}
/**
* Retry config for Auth-related requests.
*
* @remarks
*
* This is not a part of the default {@link AuthClient.transporter transporter/gaxios}
* config as some downstream APIs would prefer if customers explicitly enable retries,
* such as GCS.
*/
protected static get RETRY_CONFIG(): GaxiosOptions {
return {
retry: true,
retryConfig: {
httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'],
},
};
}
/**
* Returns whether the provided credentials are expired or will expire within
* eagerRefreshThresholdMillismilliseconds.
* If there is no expiry time, assumes the token is not expired or expiring.
* @param credentials The credentials to check for expiration.
* @return Whether the credentials are expired or not.
*/
protected isExpired(credentials: Credentials = this.credentials): boolean {
const now = new Date().getTime();
return credentials.expiry_date
? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis
: false;
}
}
// TypeScript does not have `HeadersInit` in the standard types yet
export type HeadersInit = ConstructorParameters<typeof Headers>[0];
export interface GetAccessTokenResponse {
token?: string | null;
res?: GaxiosResponse | null;
}
/**
* @deprecated - use the Promise API instead
*/
export interface BodyResponseCallback<T> {
(err: Error | null, res?: GaxiosResponse<T> | null): void;
}