-
Notifications
You must be signed in to change notification settings - Fork 356
/
token-generator.ts
345 lines (315 loc) · 11.7 KB
/
token-generator.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
/*!
* Copyright 2017 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 { FirebaseApp } from '../firebase-app';
import {ServiceAccountCredential} from './credential';
import {AuthClientErrorCode, FirebaseAuthError } from '../utils/error';
import { AuthorizedHttpClient, HttpError, HttpRequestConfig, HttpClient } from '../utils/api-request';
import * as validator from '../utils/validator';
import { toWebSafeBase64 } from '../utils';
const ALGORITHM_RS256 = 'RS256';
const ONE_HOUR_IN_SECONDS = 60 * 60;
// List of blacklisted claims which cannot be provided when creating a custom token
export const BLACKLISTED_CLAIMS = [
'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti',
'nbf', 'nonce',
];
// Audience to use for Firebase Auth Custom tokens
const FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit';
/**
* CryptoSigner interface represents an object that can be used to sign JWTs.
*/
export interface CryptoSigner {
/**
* Cryptographically signs a buffer of data.
*
* @param {Buffer} buffer The data to be signed.
* @return {Promise<Buffer>} A promise that resolves with the raw bytes of a signature.
*/
sign(buffer: Buffer): Promise<Buffer>;
/**
* Returns the ID of the service account used to sign tokens.
*
* @return {Promise<string>} A promise that resolves with a service account ID.
*/
getAccountId(): Promise<string>;
}
/**
* Represents the header of a JWT.
*/
interface JWTHeader {
alg: string;
typ: string;
}
/**
* Represents the body of a JWT.
*/
interface JWTBody {
claims?: object;
uid: string;
aud: string;
iat: number;
exp: number;
iss: string;
sub: string;
tenant_id?: string;
}
/**
* A CryptoSigner implementation that uses an explicitly specified service account private key to
* sign data. Performs all operations locally, and does not make any RPC calls.
*/
export class ServiceAccountSigner implements CryptoSigner {
/**
* Creates a new CryptoSigner instance from the given service account credential.
*
* @param {ServiceAccountCredential} credential A service account credential.
*/
constructor(private readonly credential: ServiceAccountCredential) {
if (!credential) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CREDENTIAL,
'INTERNAL ASSERT: Must provide a service account credential to initialize ServiceAccountSigner.',
);
}
}
/**
* @inheritDoc
*/
public sign(buffer: Buffer): Promise<Buffer> {
const crypto = require('crypto');
const sign = crypto.createSign('RSA-SHA256');
sign.update(buffer);
return Promise.resolve(sign.sign(this.credential.privateKey));
}
/**
* @inheritDoc
*/
public getAccountId(): Promise<string> {
return Promise.resolve(this.credential.clientEmail);
}
}
/**
* A CryptoSigner implementation that uses the remote IAM service to sign data. If initialized without
* a service account ID, attempts to discover a service account ID by consulting the local Metadata
* service. This will succeed in managed environments like Google Cloud Functions and App Engine.
*
* @see https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob
* @see https://cloud.google.com/compute/docs/storing-retrieving-metadata
*/
export class IAMSigner implements CryptoSigner {
private readonly httpClient: AuthorizedHttpClient;
private serviceAccountId?: string;
constructor(httpClient: AuthorizedHttpClient, serviceAccountId?: string) {
if (!httpClient) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'INTERNAL ASSERT: Must provide a HTTP client to initialize IAMSigner.',
);
}
if (typeof serviceAccountId !== 'undefined' && !validator.isNonEmptyString(serviceAccountId)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'INTERNAL ASSERT: Service account ID must be undefined or a non-empty string.',
);
}
this.httpClient = httpClient;
this.serviceAccountId = serviceAccountId;
}
/**
* @inheritDoc
*/
public sign(buffer: Buffer): Promise<Buffer> {
return this.getAccountId().then((serviceAccount) => {
const request: HttpRequestConfig = {
method: 'POST',
url: `https://iam.googleapis.com/v1/projects/-/serviceAccounts/${serviceAccount}:signBlob`,
data: {bytesToSign: buffer.toString('base64')},
};
return this.httpClient.send(request);
}).then((response: any) => {
// Response from IAM is base64 encoded. Decode it into a buffer and return.
return Buffer.from(response.data.signature, 'base64');
}).catch((err) => {
if (err instanceof HttpError) {
const error = err.response.data;
if (validator.isNonNullObject(error) && error.error) {
const errorCode = error.error.status;
const description = 'Please refer to https://firebase.google.com/docs/auth/admin/create-custom-tokens ' +
'for more details on how to use and troubleshoot this feature.';
const errorMsg = `${error.error.message}; ${description}`;
throw FirebaseAuthError.fromServerError(errorCode, errorMsg, error);
}
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'Error returned from server: ' + error + '. Additionally, an ' +
'internal error occurred while attempting to extract the ' +
'errorcode from the error.',
);
}
throw err;
});
}
/**
* @inheritDoc
*/
public getAccountId(): Promise<string> {
if (validator.isNonEmptyString(this.serviceAccountId)) {
return Promise.resolve(this.serviceAccountId);
}
const request: HttpRequestConfig = {
method: 'GET',
url: 'http://metadata/computeMetadata/v1/instance/service-accounts/default/email',
headers: {
'Metadata-Flavor': 'Google',
},
};
const client = new HttpClient();
return client.send(request).then((response) => {
if (!response.text) {
throw new FirebaseAuthError(
AuthClientErrorCode.INTERNAL_ERROR,
'HTTP Response missing payload',
);
}
this.serviceAccountId = response.text;
return response.text;
}).catch((err) => {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CREDENTIAL,
`Failed to determine service account. Make sure to initialize ` +
`the SDK with a service account credential. Alternatively specify a service ` +
`account with iam.serviceAccounts.signBlob permission. Original error: ${err}`,
);
});
}
}
/**
* Create a new CryptoSigner instance for the given app. If the app has been initialized with a service
* account credential, creates a ServiceAccountSigner. Otherwise creates an IAMSigner.
*
* @param {FirebaseApp} app A FirebaseApp instance.
* @return {CryptoSigner} A CryptoSigner instance.
*/
export function cryptoSignerFromApp(app: FirebaseApp): CryptoSigner {
const credential = app.options.credential;
if (credential instanceof ServiceAccountCredential) {
return new ServiceAccountSigner(credential);
}
return new IAMSigner(new AuthorizedHttpClient(app), app.options.serviceAccountId);
}
/**
* Class for generating different types of Firebase Auth tokens (JWTs).
*/
export class FirebaseTokenGenerator {
private readonly signer: CryptoSigner;
/**
* @param tenantId The tenant ID to use for the generated Firebase Auth
* Custom token. If absent, then no tenant ID claim will be set in the
* resulting JWT.
*/
constructor(signer: CryptoSigner, public readonly tenantId?: string) {
if (!validator.isNonNullObject(signer)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_CREDENTIAL,
'INTERNAL ASSERT: Must provide a CryptoSigner to use FirebaseTokenGenerator.',
);
}
if (typeof tenantId !== 'undefined' && !validator.isNonEmptyString(tenantId)) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
'`tenantId` argument must be a non-empty string.');
}
this.signer = signer;
}
/**
* Creates a new Firebase Auth Custom token.
*
* @param uid The user ID to use for the generated Firebase Auth Custom token.
* @param developerClaims Optional developer claims to include in the generated Firebase
* Auth Custom token.
* @return A Promise fulfilled with a Firebase Auth Custom token signed with a
* service account key and containing the provided payload.
*/
public createCustomToken(uid: string, developerClaims?: {[key: string]: any}): Promise<string> {
let errorMessage: string | undefined;
if (!validator.isNonEmptyString(uid)) {
errorMessage = '`uid` argument must be a non-empty string uid.';
} else if (uid.length > 128) {
errorMessage = '`uid` argument must a uid with less than or equal to 128 characters.';
} else if (!this.isDeveloperClaimsValid_(developerClaims)) {
errorMessage = '`developerClaims` argument must be a valid, non-null object containing the developer claims.';
}
if (errorMessage) {
throw new FirebaseAuthError(AuthClientErrorCode.INVALID_ARGUMENT, errorMessage);
}
const claims: {[key: string]: any} = {};
if (typeof developerClaims !== 'undefined') {
for (const key in developerClaims) {
/* istanbul ignore else */
if (developerClaims.hasOwnProperty(key)) {
if (BLACKLISTED_CLAIMS.indexOf(key) !== -1) {
throw new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT,
`Developer claim "${key}" is reserved and cannot be specified.`,
);
}
claims[key] = developerClaims[key];
}
}
}
return this.signer.getAccountId().then((account) => {
const header: JWTHeader = {
alg: ALGORITHM_RS256,
typ: 'JWT',
};
const iat = Math.floor(Date.now() / 1000);
const body: JWTBody = {
aud: FIREBASE_AUDIENCE,
iat,
exp: iat + ONE_HOUR_IN_SECONDS,
iss: account,
sub: account,
uid,
};
if (this.tenantId) {
body.tenant_id = this.tenantId;
}
if (Object.keys(claims).length > 0) {
body.claims = claims;
}
const token = `${this.encodeSegment(header)}.${this.encodeSegment(body)}`;
const signPromise = this.signer.sign(Buffer.from(token));
return Promise.all([token, signPromise]);
}).then(([token, signature]) => {
return `${token}.${this.encodeSegment(signature)}`;
});
}
private encodeSegment(segment: object | Buffer) {
const buffer: Buffer = (segment instanceof Buffer) ? segment : Buffer.from(JSON.stringify(segment));
return toWebSafeBase64(buffer).replace(/\=+$/, '');
}
/**
* Returns whether or not the provided developer claims are valid.
*
* @param {object} [developerClaims] Optional developer claims to validate.
* @return {boolean} True if the provided claims are valid; otherwise, false.
*/
private isDeveloperClaimsValid_(developerClaims?: object): boolean {
if (typeof developerClaims === 'undefined') {
return true;
}
return validator.isNonNullObject(developerClaims);
}
}