-
Notifications
You must be signed in to change notification settings - Fork 961
/
Copy pathapiv2.ts
563 lines (507 loc) · 17.3 KB
/
apiv2.ts
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
import { AbortSignal } from "abort-controller";
import { URL, URLSearchParams } from "url";
import { Readable } from "stream";
import { ProxyAgent } from "proxy-agent";
import * as retry from "retry";
import AbortController from "abort-controller";
import fetch, { HeadersInit, Response, RequestInit, Headers } from "node-fetch";
import util from "util";
import * as auth from "./auth";
import { FirebaseError } from "./error";
import { logger } from "./logger";
import { responseToError } from "./responseToError";
import * as FormData from "form-data";
// Using import would require resolveJsonModule, which seems to break the
// build/output format.
const pkg = require("../package.json");
const CLI_VERSION: string = pkg.version;
export const STANDARD_HEADERS: Record<string, string> = {
Connection: "keep-alive",
"User-Agent": `FirebaseCLI/${CLI_VERSION}`,
"X-Client-Version": `FirebaseCLI/${CLI_VERSION}`,
};
const GOOG_QUOTA_USER_HEADER = "x-goog-quota-user";
const GOOG_USER_PROJECT_HEADER = "x-goog-user-project";
const GOOGLE_CLOUD_QUOTA_PROJECT = process.env.GOOGLE_CLOUD_QUOTA_PROJECT;
export type HttpMethod =
| "GET"
| "PUT"
| "POST"
| "DELETE"
| "PATCH"
| "OPTIONS"
| "HEAD"
| "CONNECT"
| "TRACE";
interface BaseRequestOptions<T> extends VerbOptions {
method: HttpMethod;
path: string;
body?: T | string | NodeJS.ReadableStream;
responseType?: "json" | "xml" | "stream" | "arraybuffer" | "blob" | "text" | "unknown";
redirect?: "error" | "follow" | "manual";
compress?: boolean;
ignoreQuotaProject?: boolean;
}
interface RequestOptionsWithSignal<T> extends BaseRequestOptions<T> {
// Signal is used to cancel a request. Cannot be used with `timeout`.
signal?: AbortSignal;
timeout?: never;
}
interface RequestOptionsWithTimeout<T> extends BaseRequestOptions<T> {
signal?: never;
// Timeout, in ms. 0 is no timeout. Cannot be used with `signal`.
timeout?: number;
}
type RequestOptions<T> = RequestOptionsWithSignal<T> | RequestOptionsWithTimeout<T>;
interface VerbOptions {
method?: HttpMethod;
headers?: HeadersInit;
queryParams?: URLSearchParams | { [key: string]: string | number };
}
interface ClientHandlingOptions {
skipLog?: {
queryParams?: boolean;
body?: boolean;
resBody?: boolean;
};
resolveOnHTTPError?: boolean;
/** Codes on which to retry. Defaults to none. */
retryCodes?: number[];
/** Number of retries. Defaults to 0 (one attempt) with no retryCodes, 1 with retryCodes. */
retries?: number;
/** Minimum timeout between retries. Defaults to 1s. */
retryMinTimeout?: number;
/** Maximum timeout between retries. Defaults to 5s. */
retryMaxTimeout?: number;
}
export type ClientRequestOptions<T> = RequestOptions<T> & ClientVerbOptions;
interface BaseInternalClientRequestOptions {
headers?: Headers;
}
type InternalClientRequestOptions<T> = BaseInternalClientRequestOptions & ClientRequestOptions<T>;
export type ClientVerbOptions = VerbOptions & ClientHandlingOptions;
export type ClientResponse<T> = {
status: number;
response: Response;
body: T;
};
let accessToken = "";
let refreshToken = "";
/**
* Sets the refresh token.
* @param token refresh token.
*/
export function setRefreshToken(token = ""): void {
refreshToken = token;
}
/**
* Sets the access token.
* @param token access token.
*/
export function setAccessToken(token = ""): void {
accessToken = token;
}
/**
* Gets a singleton access token
* @returns An access token
*/
export async function getAccessToken(): Promise<string> {
const valid = auth.haveValidTokens(refreshToken, []);
const usingADC = !auth.loggedIn();
if (accessToken && (valid || usingADC)) {
return accessToken;
}
const data = await auth.getAccessToken(refreshToken, []);
return data.access_token;
}
function proxyURIFromEnv(): string | undefined {
return (
process.env.HTTPS_PROXY ||
process.env.https_proxy ||
process.env.HTTP_PROXY ||
process.env.http_proxy ||
undefined
);
}
export type ClientOptions = {
urlPrefix: string;
apiVersion?: string;
auth?: boolean;
};
export class Client {
constructor(private opts: ClientOptions) {
if (this.opts.auth === undefined) {
this.opts.auth = true;
}
if (this.opts.urlPrefix.endsWith("/")) {
this.opts.urlPrefix = this.opts.urlPrefix.substring(0, this.opts.urlPrefix.length - 1);
}
}
get<ResT>(path: string, options: ClientVerbOptions = {}): Promise<ClientResponse<ResT>> {
const reqOptions: ClientRequestOptions<unknown> = Object.assign(options, {
method: "GET",
path,
});
return this.request<unknown, ResT>(reqOptions);
}
post<ReqT, ResT>(
path: string,
json?: ReqT,
options: ClientVerbOptions = {},
): Promise<ClientResponse<ResT>> {
const reqOptions: ClientRequestOptions<ReqT> = Object.assign(options, {
method: "POST",
path,
body: json,
});
return this.request<ReqT, ResT>(reqOptions);
}
patch<ReqT, ResT>(
path: string,
json?: ReqT,
options: ClientVerbOptions = {},
): Promise<ClientResponse<ResT>> {
const reqOptions: ClientRequestOptions<ReqT> = Object.assign(options, {
method: "PATCH",
path,
body: json,
});
return this.request<ReqT, ResT>(reqOptions);
}
put<ReqT, ResT>(
path: string,
json?: ReqT,
options: ClientVerbOptions = {},
): Promise<ClientResponse<ResT>> {
const reqOptions: ClientRequestOptions<ReqT> = Object.assign(options, {
method: "PUT",
path,
body: json,
});
return this.request<ReqT, ResT>(reqOptions);
}
delete<ResT>(path: string, options: ClientVerbOptions = {}): Promise<ClientResponse<ResT>> {
const reqOptions: ClientRequestOptions<unknown> = Object.assign(options, {
method: "DELETE",
path,
});
return this.request<unknown, ResT>(reqOptions);
}
options<ResT>(path: string, options: ClientVerbOptions = {}): Promise<ClientResponse<ResT>> {
const reqOptions: ClientRequestOptions<unknown> = Object.assign(options, {
method: "OPTIONS",
path,
});
return this.request<unknown, ResT>(reqOptions);
}
/**
* Makes a request as specified by the options.
* By default, this will:
* - use content-type: application/json
* - assume the HTTP GET method
*
* @example
* const res = apiv2.request<ResourceType>({
* method: "POST",
* path: "/some/resource",
* queryParams: { updateMask: "key" },
* json: { name: "resource-name", key: "updated-value" }
* });
* // typeof res.body === ResourceType
* @param reqOptions request options.
* @return the response.
*/
async request<ReqT, ResT>(reqOptions: ClientRequestOptions<ReqT>): Promise<ClientResponse<ResT>> {
// All requests default to JSON content types.
if (!reqOptions.responseType) {
reqOptions.responseType = "json";
}
// TODO(bkendall): stream + !resolveOnHTTPError makes for difficult handling.
// Figure out if there's a better way to handle streamed >=400 responses.
if (reqOptions.responseType === "stream" && !reqOptions.resolveOnHTTPError) {
throw new FirebaseError(
"apiv2 will not handle HTTP errors while streaming and you must set `resolveOnHTTPError` and check for res.status >= 400 on your own",
{ exit: 2 },
);
}
let internalReqOptions: InternalClientRequestOptions<ReqT> = Object.assign(reqOptions, {
headers: new Headers(reqOptions.headers),
});
internalReqOptions = this.addRequestHeaders(internalReqOptions);
if (this.opts.auth) {
internalReqOptions = await this.addAuthHeader(internalReqOptions);
}
try {
return await this.doRequest<ReqT, ResT>(internalReqOptions);
} catch (thrown: any) {
if (thrown instanceof FirebaseError) {
throw thrown;
}
// Though it should never happen in practice, a non-Error type can be thrown
let err: Error;
if (thrown instanceof Error) {
err = thrown;
} else {
err = new Error(thrown);
}
throw new FirebaseError(`Failed to make request: ${err.message}`, { original: err });
}
}
private addRequestHeaders<T>(
reqOptions: InternalClientRequestOptions<T>,
): InternalClientRequestOptions<T> {
if (!reqOptions.headers) {
reqOptions.headers = new Headers();
}
for (const [h, v] of Object.entries(STANDARD_HEADERS)) {
if (!reqOptions.headers.has(h)) {
reqOptions.headers.set(h, v);
}
}
if (!reqOptions.headers.has("Content-Type")) {
if (reqOptions.responseType === "json") {
reqOptions.headers.set("Content-Type", "application/json");
}
}
if (
!reqOptions.ignoreQuotaProject &&
GOOGLE_CLOUD_QUOTA_PROJECT &&
GOOGLE_CLOUD_QUOTA_PROJECT !== ""
) {
reqOptions.headers.set(GOOG_USER_PROJECT_HEADER, GOOGLE_CLOUD_QUOTA_PROJECT);
}
return reqOptions;
}
private async addAuthHeader<T>(
reqOptions: InternalClientRequestOptions<T>,
): Promise<InternalClientRequestOptions<T>> {
if (!reqOptions.headers) {
reqOptions.headers = new Headers();
}
let token: string;
if (isLocalInsecureRequest(this.opts.urlPrefix)) {
token = "owner";
} else {
token = await getAccessToken();
}
reqOptions.headers.set("Authorization", `Bearer ${token}`);
return reqOptions;
}
private requestURL(options: InternalClientRequestOptions<unknown>): string {
const versionPath = this.opts.apiVersion ? `/${this.opts.apiVersion}` : "";
return `${this.opts.urlPrefix}${versionPath}${options.path}`;
}
private async doRequest<ReqT, ResT>(
options: InternalClientRequestOptions<ReqT>,
): Promise<ClientResponse<ResT>> {
if (!options.path.startsWith("/")) {
options.path = "/" + options.path;
}
let fetchURL = this.requestURL(options);
if (options.queryParams) {
if (!(options.queryParams instanceof URLSearchParams)) {
const sp = new URLSearchParams();
for (const key of Object.keys(options.queryParams)) {
const value = options.queryParams[key];
sp.append(key, `${value}`);
}
options.queryParams = sp;
}
const queryString = options.queryParams.toString();
if (queryString) {
fetchURL += `?${queryString}`;
}
}
const fetchOptions: RequestInit = {
headers: options.headers,
method: options.method,
redirect: options.redirect,
compress: options.compress,
};
if (proxyURIFromEnv()) {
fetchOptions.agent = new ProxyAgent();
}
if (options.signal) {
fetchOptions.signal = options.signal;
}
let reqTimeout: NodeJS.Timeout | undefined;
if (options.timeout) {
const controller = new AbortController();
reqTimeout = setTimeout(() => {
controller.abort();
}, options.timeout);
fetchOptions.signal = controller.signal;
}
if (typeof options.body === "string" || isStream(options.body)) {
fetchOptions.body = options.body;
} else if (options.body !== undefined) {
fetchOptions.body = JSON.stringify(options.body);
}
// TODO(bkendall): Refactor this to use Throttler _or_ refactor Throttle to use `retry`.
const operationOptions: retry.OperationOptions = {
retries: options.retryCodes?.length ? 1 : 2,
minTimeout: 1 * 1000,
maxTimeout: 5 * 1000,
};
if (typeof options.retries === "number") {
operationOptions.retries = options.retries;
}
if (typeof options.retryMinTimeout === "number") {
operationOptions.minTimeout = options.retryMinTimeout;
}
if (typeof options.retryMaxTimeout === "number") {
operationOptions.maxTimeout = options.retryMaxTimeout;
}
const operation = retry.operation(operationOptions);
return await new Promise<ClientResponse<ResT>>((resolve, reject) => {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
operation.attempt(async (currentAttempt): Promise<void> => {
let res: Response;
let body: ResT;
try {
if (currentAttempt > 1) {
logger.debug(
`*** [apiv2] Attempting the request again. Attempt number ${currentAttempt}`,
);
}
this.logRequest(options);
try {
res = await fetch(fetchURL, fetchOptions);
} catch (thrown: any) {
const err = thrown instanceof Error ? thrown : new Error(thrown);
logger.debug(
`*** [apiv2] error from fetch(${fetchURL}, ${JSON.stringify(fetchOptions)}): ${err}`,
);
const isAbortError = err.name.includes("AbortError");
if (isAbortError) {
throw new FirebaseError(`Timeout reached making request to ${fetchURL}`, {
original: err,
});
}
throw new FirebaseError(`Failed to make request to ${fetchURL}`, { original: err });
} finally {
// If we succeed or failed, clear the timeout.
if (reqTimeout) {
clearTimeout(reqTimeout);
}
}
if (options.responseType === "json") {
const text = await res.text();
// Some responses, such as 204 and occasionally 202s don't have
// any content. We can't just rely on response code (202 may have conent)
// and unfortuantely res.length is unreliable (many requests return zero).
if (!text.length) {
body = undefined as unknown as ResT;
} else {
try {
body = JSON.parse(text) as ResT;
} catch (err: unknown) {
// JSON-parse errors are useless. Log the response for better debugging.
this.logResponse(res, text, options);
throw new FirebaseError(`Unable to parse JSON: ${err}`);
}
}
} else if (options.responseType === "xml") {
body = (await res.text()) as unknown as ResT;
} else if (options.responseType === "stream") {
body = res.body as unknown as ResT;
} else {
throw new FirebaseError(`Unable to interpret response. Please set responseType.`, {
exit: 2,
});
}
} catch (err: unknown) {
return err instanceof FirebaseError ? reject(err) : reject(new FirebaseError(`${err}`));
}
this.logResponse(res, body, options);
if (res.status >= 400) {
if (res.status === 401 && this.opts.auth) {
// If we get a 401, access token is expired or otherwise invalid.
// Throw it away and get a new one. We check for validity before using
// tokens, so this should not happen.
logger.debug(
"Got a 401 Unauthenticated error for a call that required authentication. Refreshing tokens.",
);
setAccessToken();
setAccessToken(await getAccessToken());
}
if (options.retryCodes?.includes(res.status)) {
const err = responseToError({ statusCode: res.status }, body, fetchURL) || undefined;
if (operation.retry(err)) {
return;
}
}
if (!options.resolveOnHTTPError) {
return reject(responseToError({ statusCode: res.status }, body, fetchURL));
}
}
resolve({
status: res.status,
response: res,
body,
});
});
});
}
private logRequest(options: InternalClientRequestOptions<unknown>): void {
let queryParamsLog = "[none]";
if (options.queryParams) {
queryParamsLog = "[omitted]";
if (!options.skipLog?.queryParams) {
queryParamsLog =
options.queryParams instanceof URLSearchParams
? options.queryParams.toString()
: JSON.stringify(options.queryParams);
}
}
const logURL = this.requestURL(options);
logger.debug(`>>> [apiv2][query] ${options.method} ${logURL} ${queryParamsLog}`);
const headers = options.headers;
if (headers && headers.has(GOOG_QUOTA_USER_HEADER)) {
logger.debug(
`>>> [apiv2][(partial)header] ${options.method} ${logURL} x-goog-quota-user=${
headers.get(GOOG_QUOTA_USER_HEADER) || ""
}`,
);
}
if (options.body !== undefined) {
let logBody = "[omitted]";
if (!options.skipLog?.body) {
logBody = bodyToString(options.body);
}
logger.debug(`>>> [apiv2][body] ${options.method} ${logURL} ${logBody}`);
}
}
private logResponse(
res: Response,
body: unknown,
options: InternalClientRequestOptions<unknown>,
): void {
const logURL = this.requestURL(options);
logger.debug(`<<< [apiv2][status] ${options.method} ${logURL} ${res.status}`);
let logBody = "[omitted]";
if (!options.skipLog?.resBody) {
logBody = bodyToString(body);
}
logger.debug(`<<< [apiv2][body] ${options.method} ${logURL} ${logBody}`);
}
}
function isLocalInsecureRequest(urlPrefix: string): boolean {
const u = new URL(urlPrefix);
return u.protocol === "http:";
}
function bodyToString(body: unknown): string {
if (isStream(body)) {
// Don't attempt to read any stream type, in case the caller needs it.
return "[stream]";
} else {
try {
return JSON.stringify(body);
} catch (_) {
return util.inspect(body);
}
}
}
function isStream(o: unknown): o is NodeJS.ReadableStream {
return o instanceof Readable || o instanceof FormData;
}