-
Notifications
You must be signed in to change notification settings - Fork 373
/
credential-internal.ts
628 lines (553 loc) · 22.5 KB
/
credential-internal.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
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
/*!
* @license
* Copyright 2020 Google Inc.
*
* 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 fs = require('fs');
import os = require('os');
import path = require('path');
import { Agent } from 'http';
import { Credential, GoogleOAuthAccessToken } from './credential';
import { AppErrorCodes, FirebaseAppError } from '../utils/error';
import { HttpClient, HttpRequestConfig, HttpError, HttpResponse } from '../utils/api-request';
import * as util from '../utils/validator';
const GOOGLE_TOKEN_AUDIENCE = 'https://accounts.google.com/o/oauth2/token';
const GOOGLE_AUTH_TOKEN_HOST = 'accounts.google.com';
const GOOGLE_AUTH_TOKEN_PATH = '/o/oauth2/token';
// NOTE: the Google Metadata Service uses HTTP over a vlan
const GOOGLE_METADATA_SERVICE_HOST = 'metadata.google.internal';
const GOOGLE_METADATA_SERVICE_TOKEN_PATH = '/computeMetadata/v1/instance/service-accounts/default/token';
const GOOGLE_METADATA_SERVICE_IDENTITY_PATH = '/computeMetadata/v1/instance/service-accounts/default/identity';
const GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH = '/computeMetadata/v1/project/project-id';
const GOOGLE_METADATA_SERVICE_ACCOUNT_ID_PATH = '/computeMetadata/v1/instance/service-accounts/default/email';
const configDir = (() => {
// Windows has a dedicated low-rights location for apps at ~/Application Data
const sys = os.platform();
if (sys && sys.length >= 3 && sys.substring(0, 3).toLowerCase() === 'win') {
return process.env.APPDATA;
}
// On *nix the gcloud cli creates a . dir.
return process.env.HOME && path.resolve(process.env.HOME, '.config');
})();
const GCLOUD_CREDENTIAL_SUFFIX = 'gcloud/application_default_credentials.json';
const GCLOUD_CREDENTIAL_PATH = configDir && path.resolve(configDir, GCLOUD_CREDENTIAL_SUFFIX);
const REFRESH_TOKEN_HOST = 'www.googleapis.com';
const REFRESH_TOKEN_PATH = '/oauth2/v4/token';
const ONE_HOUR_IN_SECONDS = 60 * 60;
const JWT_ALGORITHM = 'RS256';
/**
* Implementation of Credential that uses a service account.
*/
export class ServiceAccountCredential implements Credential {
public readonly projectId: string;
public readonly privateKey: string;
public readonly clientEmail: string;
private readonly httpClient: HttpClient;
/**
* Creates a new ServiceAccountCredential from the given parameters.
*
* @param serviceAccountPathOrObject - Service account json object or path to a service account json file.
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
* @param implicit - An optinal boolean indicating whether this credential was implicitly discovered from the
* environment, as opposed to being explicitly specified by the developer.
*
* @constructor
*/
constructor(
serviceAccountPathOrObject: string | object,
private readonly httpAgent?: Agent,
readonly implicit: boolean = false) {
const serviceAccount = (typeof serviceAccountPathOrObject === 'string') ?
ServiceAccount.fromPath(serviceAccountPathOrObject)
: new ServiceAccount(serviceAccountPathOrObject);
this.projectId = serviceAccount.projectId;
this.privateKey = serviceAccount.privateKey;
this.clientEmail = serviceAccount.clientEmail;
this.httpClient = new HttpClient();
}
public getAccessToken(): Promise<GoogleOAuthAccessToken> {
const token = this.createAuthJwt_();
const postData = 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3A' +
'grant-type%3Ajwt-bearer&assertion=' + token;
const request: HttpRequestConfig = {
method: 'POST',
url: `https://${GOOGLE_AUTH_TOKEN_HOST}${GOOGLE_AUTH_TOKEN_PATH}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: postData,
httpAgent: this.httpAgent,
};
return requestAccessToken(this.httpClient, request);
}
// eslint-disable-next-line @typescript-eslint/naming-convention
private createAuthJwt_(): string {
const claims = {
scope: [
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/firebase.messaging',
'https://www.googleapis.com/auth/identitytoolkit',
'https://www.googleapis.com/auth/userinfo.email',
].join(' '),
};
// eslint-disable-next-line @typescript-eslint/no-var-requires
const jwt = require('jsonwebtoken');
// This method is actually synchronous so we can capture and return the buffer.
return jwt.sign(claims, this.privateKey, {
audience: GOOGLE_TOKEN_AUDIENCE,
expiresIn: ONE_HOUR_IN_SECONDS,
issuer: this.clientEmail,
algorithm: JWT_ALGORITHM,
});
}
}
/**
* A struct containing the properties necessary to use service account JSON credentials.
*/
class ServiceAccount {
public readonly projectId: string;
public readonly privateKey: string;
public readonly clientEmail: string;
public static fromPath(filePath: string): ServiceAccount {
try {
return new ServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8')));
} catch (error) {
// Throw a nicely formed error message if the file contents cannot be parsed
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Failed to parse service account json file: ' + error,
);
}
}
constructor(json: object) {
if (!util.isNonNullObject(json)) {
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Service account must be an object.',
);
}
copyAttr(this, json, 'projectId', 'project_id');
copyAttr(this, json, 'privateKey', 'private_key');
copyAttr(this, json, 'clientEmail', 'client_email');
let errorMessage;
if (!util.isNonEmptyString(this.projectId)) {
errorMessage = 'Service account object must contain a string "project_id" property.';
} else if (!util.isNonEmptyString(this.privateKey)) {
errorMessage = 'Service account object must contain a string "private_key" property.';
} else if (!util.isNonEmptyString(this.clientEmail)) {
errorMessage = 'Service account object must contain a string "client_email" property.';
}
if (typeof errorMessage !== 'undefined') {
throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const forge = require('node-forge');
try {
forge.pki.privateKeyFromPem(this.privateKey);
} catch (error) {
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Failed to parse private key: ' + error);
}
}
}
/**
* Implementation of Credential that gets access tokens from the metadata service available
* in the Google Cloud Platform. This authenticates the process as the default service account
* of an App Engine instance or Google Compute Engine machine.
*/
export class ComputeEngineCredential implements Credential {
private readonly httpClient = new HttpClient();
private readonly httpAgent?: Agent;
private projectId?: string;
private accountId?: string;
constructor(httpAgent?: Agent) {
this.httpAgent = httpAgent;
}
public getAccessToken(): Promise<GoogleOAuthAccessToken> {
const request = this.buildRequest(GOOGLE_METADATA_SERVICE_TOKEN_PATH);
return requestAccessToken(this.httpClient, request);
}
/**
* getIDToken returns a OIDC token from the compute metadata service
* that can be used to make authenticated calls to audience
* @param audience the URL the returned ID token will be used to call.
*/
public getIDToken(audience: string): Promise<string> {
const request = this.buildRequest(`${GOOGLE_METADATA_SERVICE_IDENTITY_PATH}?audience=${audience}`);
return requestIDToken(this.httpClient, request);
}
public getProjectId(): Promise<string> {
if (this.projectId) {
return Promise.resolve(this.projectId);
}
const request = this.buildRequest(GOOGLE_METADATA_SERVICE_PROJECT_ID_PATH);
return this.httpClient.send(request)
.then((resp) => {
this.projectId = resp.text!;
return this.projectId;
})
.catch((err) => {
const detail: string = (err instanceof HttpError) ? getDetailFromResponse(err.response) : err.message;
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
`Failed to determine project ID: ${detail}`);
});
}
public getServiceAccountEmail(): Promise<string> {
if (this.accountId) {
return Promise.resolve(this.accountId);
}
const request = this.buildRequest(GOOGLE_METADATA_SERVICE_ACCOUNT_ID_PATH);
return this.httpClient.send(request)
.then((resp) => {
this.accountId = resp.text!;
return this.accountId;
})
.catch((err) => {
const detail: string = (err instanceof HttpError) ? getDetailFromResponse(err.response) : err.message;
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
`Failed to determine service account email: ${detail}`);
});
}
private buildRequest(urlPath: string): HttpRequestConfig {
return {
method: 'GET',
url: `http://${GOOGLE_METADATA_SERVICE_HOST}${urlPath}`,
headers: {
'Metadata-Flavor': 'Google',
},
httpAgent: this.httpAgent,
};
}
}
/**
* Implementation of Credential that gets access tokens from refresh tokens.
*/
export class RefreshTokenCredential implements Credential {
private readonly refreshToken: RefreshToken;
private readonly httpClient: HttpClient;
/**
* Creates a new RefreshTokenCredential from the given parameters.
*
* @param refreshTokenPathOrObject - Refresh token json object or path to a refresh token
* (user credentials) json file.
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
* @param implicit - An optinal boolean indicating whether this credential was implicitly
* discovered from the environment, as opposed to being explicitly specified by the developer.
*
* @constructor
*/
constructor(
refreshTokenPathOrObject: string | object,
private readonly httpAgent?: Agent,
readonly implicit: boolean = false) {
this.refreshToken = (typeof refreshTokenPathOrObject === 'string') ?
RefreshToken.fromPath(refreshTokenPathOrObject)
: new RefreshToken(refreshTokenPathOrObject);
this.httpClient = new HttpClient();
}
public getAccessToken(): Promise<GoogleOAuthAccessToken> {
const postData =
'client_id=' + this.refreshToken.clientId + '&' +
'client_secret=' + this.refreshToken.clientSecret + '&' +
'refresh_token=' + this.refreshToken.refreshToken + '&' +
'grant_type=refresh_token';
const request: HttpRequestConfig = {
method: 'POST',
url: `https://${REFRESH_TOKEN_HOST}${REFRESH_TOKEN_PATH}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: postData,
httpAgent: this.httpAgent,
};
return requestAccessToken(this.httpClient, request);
}
}
class RefreshToken {
public readonly clientId: string;
public readonly clientSecret: string;
public readonly refreshToken: string;
public readonly type: string;
/*
* Tries to load a RefreshToken from a path. Throws if the path doesn't exist or the
* data at the path is invalid.
*/
public static fromPath(filePath: string): RefreshToken {
try {
return new RefreshToken(JSON.parse(fs.readFileSync(filePath, 'utf8')));
} catch (error) {
// Throw a nicely formed error message if the file contents cannot be parsed
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Failed to parse refresh token file: ' + error,
);
}
}
constructor(json: object) {
copyAttr(this, json, 'clientId', 'client_id');
copyAttr(this, json, 'clientSecret', 'client_secret');
copyAttr(this, json, 'refreshToken', 'refresh_token');
copyAttr(this, json, 'type', 'type');
let errorMessage;
if (!util.isNonEmptyString(this.clientId)) {
errorMessage = 'Refresh token must contain a "client_id" property.';
} else if (!util.isNonEmptyString(this.clientSecret)) {
errorMessage = 'Refresh token must contain a "client_secret" property.';
} else if (!util.isNonEmptyString(this.refreshToken)) {
errorMessage = 'Refresh token must contain a "refresh_token" property.';
} else if (!util.isNonEmptyString(this.type)) {
errorMessage = 'Refresh token must contain a "type" property.';
}
if (typeof errorMessage !== 'undefined') {
throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
}
}
}
/**
* Implementation of Credential that uses impersonated service account.
*/
export class ImpersonatedServiceAccountCredential implements Credential {
private readonly impersonatedServiceAccount: ImpersonatedServiceAccount;
private readonly httpClient: HttpClient;
/**
* Creates a new ImpersonatedServiceAccountCredential from the given parameters.
*
* @param impersonatedServiceAccountPathOrObject - Impersonated Service account json object or
* path to a service account json file.
* @param httpAgent - Optional http.Agent to use when calling the remote token server.
* @param implicit - An optional boolean indicating whether this credential was implicitly
* discovered from the environment, as opposed to being explicitly specified by the developer.
*
* @constructor
*/
constructor(
impersonatedServiceAccountPathOrObject: string | object,
private readonly httpAgent?: Agent,
readonly implicit: boolean = false) {
this.impersonatedServiceAccount = (typeof impersonatedServiceAccountPathOrObject === 'string') ?
ImpersonatedServiceAccount.fromPath(impersonatedServiceAccountPathOrObject)
: new ImpersonatedServiceAccount(impersonatedServiceAccountPathOrObject);
this.httpClient = new HttpClient();
}
public getAccessToken(): Promise<GoogleOAuthAccessToken> {
const postData =
'client_id=' + this.impersonatedServiceAccount.clientId + '&' +
'client_secret=' + this.impersonatedServiceAccount.clientSecret + '&' +
'refresh_token=' + this.impersonatedServiceAccount.refreshToken + '&' +
'grant_type=refresh_token';
const request: HttpRequestConfig = {
method: 'POST',
url: `https://${REFRESH_TOKEN_HOST}${REFRESH_TOKEN_PATH}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: postData,
httpAgent: this.httpAgent,
};
return requestAccessToken(this.httpClient, request);
}
}
/**
* A struct containing the properties necessary to use impersonated service account JSON credentials.
*/
class ImpersonatedServiceAccount {
public readonly clientId: string;
public readonly clientSecret: string;
public readonly refreshToken: string;
public readonly type: string;
/*
* Tries to load a ImpersonatedServiceAccount from a path. Throws if the path doesn't exist or the
* data at the path is invalid.
*/
public static fromPath(filePath: string): ImpersonatedServiceAccount {
try {
return new ImpersonatedServiceAccount(JSON.parse(fs.readFileSync(filePath, 'utf8')));
} catch (error) {
// Throw a nicely formed error message if the file contents cannot be parsed
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Failed to parse impersonated service account file: ' + error,
);
}
}
constructor(json: object) {
const sourceCredentials = (json as {[key: string]: any})['source_credentials']
if (sourceCredentials) {
copyAttr(this, sourceCredentials, 'clientId', 'client_id');
copyAttr(this, sourceCredentials, 'clientSecret', 'client_secret');
copyAttr(this, sourceCredentials, 'refreshToken', 'refresh_token');
copyAttr(this, sourceCredentials, 'type', 'type');
}
let errorMessage;
if (!util.isNonEmptyString(this.clientId)) {
errorMessage = 'Impersonated Service Account must contain a "source_credentials.client_id" property.';
} else if (!util.isNonEmptyString(this.clientSecret)) {
errorMessage = 'Impersonated Service Account must contain a "source_credentials.client_secret" property.';
} else if (!util.isNonEmptyString(this.refreshToken)) {
errorMessage = 'Impersonated Service Account must contain a "source_credentials.refresh_token" property.';
} else if (!util.isNonEmptyString(this.type)) {
errorMessage = 'Impersonated Service Account must contain a "source_credentials.type" property.';
}
if (typeof errorMessage !== 'undefined') {
throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, errorMessage);
}
}
}
/**
* Checks if the given credential was loaded via the application default credentials mechanism. This
* includes all ComputeEngineCredential instances, and the ServiceAccountCredential and RefreshTokenCredential
* instances that were loaded from well-known files or environment variables, rather than being explicitly
* instantiated.
*
* @param credential - The credential instance to check.
*/
export function isApplicationDefault(credential?: Credential): boolean {
return credential instanceof ComputeEngineCredential ||
(credential instanceof ServiceAccountCredential && credential.implicit) ||
(credential instanceof RefreshTokenCredential && credential.implicit) ||
(credential instanceof ImpersonatedServiceAccountCredential && credential.implicit);
}
export function getApplicationDefault(httpAgent?: Agent): Credential {
if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
return credentialFromFile(process.env.GOOGLE_APPLICATION_CREDENTIALS, httpAgent, false)!;
}
// It is OK to not have this file. If it is present, it must be valid.
if (GCLOUD_CREDENTIAL_PATH) {
const credential = credentialFromFile(GCLOUD_CREDENTIAL_PATH, httpAgent, true);
if (credential) return credential
}
return new ComputeEngineCredential(httpAgent);
}
/**
* Copies the specified property from one object to another.
*
* If no property exists by the given "key", looks for a property identified by "alt", and copies it instead.
* This can be used to implement behaviors such as "copy property myKey or my_key".
*
* @param to - Target object to copy the property into.
* @param from - Source object to copy the property from.
* @param key - Name of the property to copy.
* @param alt - Alternative name of the property to copy.
*/
function copyAttr(to: {[key: string]: any}, from: {[key: string]: any}, key: string, alt: string): void {
const tmp = from[key] || from[alt];
if (typeof tmp !== 'undefined') {
to[key] = tmp;
}
}
/**
* Obtain a new OAuth2 token by making a remote service call.
*/
function requestAccessToken(client: HttpClient, request: HttpRequestConfig): Promise<GoogleOAuthAccessToken> {
return client.send(request).then((resp) => {
const json = resp.data;
if (!json.access_token || !json.expires_in) {
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
`Unexpected response while fetching access token: ${ JSON.stringify(json) }`,
);
}
return json;
}).catch((err) => {
throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, getErrorMessage(err));
});
}
/**
* Obtain a new OIDC token by making a remote service call.
*/
function requestIDToken(client: HttpClient, request: HttpRequestConfig): Promise<string> {
return client.send(request).then((resp) => {
if (!resp.text) {
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Unexpected response while fetching id token: response.text is undefined',
);
}
return resp.text;
}).catch((err) => {
throw new FirebaseAppError(AppErrorCodes.INVALID_CREDENTIAL, getErrorMessage(err));
});
}
/**
* Constructs a human-readable error message from the given Error.
*/
function getErrorMessage(err: Error): string {
const detail: string = (err instanceof HttpError) ? getDetailFromResponse(err.response) : err.message;
return `Error fetching access token: ${detail}`;
}
/**
* Extracts details from the given HTTP error response, and returns a human-readable description. If
* the response is JSON-formatted, looks up the error and error_description fields sent by the
* Google Auth servers. Otherwise returns the entire response payload as the error detail.
*/
function getDetailFromResponse(response: HttpResponse): string {
if (response.isJson() && response.data.error) {
const json = response.data;
let detail = json.error;
if (json.error_description) {
detail += ' (' + json.error_description + ')';
}
return detail;
}
return response.text || 'Missing error payload';
}
function credentialFromFile(filePath: string, httpAgent?: Agent, ignoreMissing?: boolean): Credential | null {
const credentialsFile = readCredentialFile(filePath, ignoreMissing);
if (typeof credentialsFile !== 'object' || credentialsFile === null) {
if (ignoreMissing) { return null; }
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Failed to parse contents of the credentials file as an object',
);
}
if (credentialsFile.type === 'service_account') {
return new ServiceAccountCredential(credentialsFile, httpAgent, true);
}
if (credentialsFile.type === 'authorized_user') {
return new RefreshTokenCredential(credentialsFile, httpAgent, true);
}
if (credentialsFile.type === 'impersonated_service_account') {
return new ImpersonatedServiceAccountCredential(credentialsFile, httpAgent, true)
}
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Invalid contents in the credentials file',
);
}
function readCredentialFile(filePath: string, ignoreMissing?: boolean): {[key: string]: any} | null {
let fileText: string;
try {
fileText = fs.readFileSync(filePath, 'utf8');
} catch (error) {
if (ignoreMissing) {
return null;
}
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
`Failed to read credentials from file ${filePath}: ` + error,
);
}
try {
return JSON.parse(fileText);
} catch (error) {
throw new FirebaseAppError(
AppErrorCodes.INVALID_CREDENTIAL,
'Failed to parse contents of the credentials file as an object: ' + error,
);
}
}