/
auth.spec.ts
3977 lines (3602 loc) · 170 KB
/
auth.spec.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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* @license
* 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.
*/
'use strict';
import * as jwt from 'jsonwebtoken';
import * as _ from 'lodash';
import * as chai from 'chai';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as utils from '../utils';
import * as mocks from '../../resources/mocks';
import { FirebaseApp } from '../../../src/app/firebase-app';
import {
AuthRequestHandler, TenantAwareAuthRequestHandler, AbstractAuthRequestHandler,
} from '../../../src/auth/auth-api-request';
import { AuthClientErrorCode, FirebaseAuthError } from '../../../src/utils/error';
import * as validator from '../../../src/utils/validator';
import { DecodedAuthBlockingToken, FirebaseTokenVerifier } from '../../../src/auth/token-verifier';
import {
OIDCConfig, SAMLConfig, OIDCConfigServerResponse, SAMLConfigServerResponse,
} from '../../../src/auth/auth-config';
import { deepCopy } from '../../../src/utils/deep-copy';
import { ServiceAccountCredential } from '../../../src/app/credential-internal';
import { HttpClient } from '../../../src/utils/api-request';
import {
Auth, TenantAwareAuth, BaseAuth, UserRecord, DecodedIdToken,
UpdateRequest, AuthProviderConfigFilter, TenantManager,
} from '../../../src/auth/index';
chai.should();
chai.use(sinonChai);
chai.use(chaiAsPromised);
const expect = chai.expect;
interface AuthTest {
name: string;
supportsTenantManagement: boolean;
Auth: new (...args: any[]) => BaseAuth;
RequestHandler: new (...args: any[]) => AbstractAuthRequestHandler;
init(app: FirebaseApp): BaseAuth;
}
interface EmailActionTest {
api: string;
requestType: string;
requiresSettings: boolean;
}
/**
* @param {string=} tenantId The optional tenant Id.
* @return {object} A sample valid server response as returned from getAccountInfo
* endpoint.
*/
function getValidGetAccountInfoResponse(tenantId?: string): {kind: string; users: any[]} {
const userResponse: any = {
localId: 'abcdefghijklmnopqrstuvwxyz',
email: 'user@gmail.com',
emailVerified: true,
displayName: 'John Doe',
phoneNumber: '+11234567890',
providerUserInfo: [
{
providerId: 'google.com',
displayName: 'John Doe',
photoUrl: 'https://lh3.googleusercontent.com/1234567890/photo.jpg',
federatedId: '1234567890',
email: 'user@gmail.com',
rawId: '1234567890',
},
{
providerId: 'facebook.com',
displayName: 'John Smith',
photoUrl: 'https://facebook.com/0987654321/photo.jpg',
federatedId: '0987654321',
email: 'user@facebook.com',
rawId: '0987654321',
},
{
providerId: 'phone',
phoneNumber: '+11234567890',
rawId: '+11234567890',
},
],
mfaInfo: [
{
mfaEnrollmentId: 'enrolledSecondFactor1',
phoneInfo: '+16505557348',
displayName: 'Spouse\'s phone number',
enrolledAt: new Date().toISOString(),
},
{
mfaEnrollmentId: 'enrolledSecondFactor2',
phoneInfo: '+16505551000',
},
],
photoUrl: 'https://lh3.googleusercontent.com/1234567890/photo.jpg',
validSince: '1476136676',
lastLoginAt: '1476235905000',
createdAt: '1476136676000',
};
if (typeof tenantId !== 'undefined') {
userResponse.tenantId = tenantId;
}
return {
kind: 'identitytoolkit#GetAccountInfoResponse',
users: [userResponse],
};
}
/**
* Returns a user record corresponding to the getAccountInfo response.
*
* @param {any} serverResponse Raw getAccountInfo response.
* @return {Object} The corresponding user record.
*/
function getValidUserRecord(serverResponse: any): UserRecord {
return new UserRecord(serverResponse.users[0]);
}
/**
* Generates a mock decoded ID token with the provided parameters.
*
* @param {string} uid The uid corresponding to the ID token.
* @param {Date} authTime The authentication time of the ID token.
* @param {string=} tenantId The optional tenant ID.
* @return {DecodedIdToken} The generated decoded ID token.
*/
function getDecodedIdToken(uid: string, authTime: Date, tenantId?: string): DecodedIdToken {
return {
iss: 'https://securetoken.google.com/project123456789',
aud: 'project123456789',
auth_time: Math.floor(authTime.getTime() / 1000),
sub: uid,
iat: Math.floor(authTime.getTime() / 1000),
exp: Math.floor(authTime.getTime() / 1000 + 3600),
firebase: {
identities: {},
sign_in_provider: 'custom',
tenant: tenantId,
},
uid,
};
}
/**
* Generates a mock decoded Auth Blocking token with the provided parameters.
*
* @param uid The uid corresponding to the Auth Blocking token.
* @param authTime The authentication time of the Auth Blocking token.
* @return The generated decoded Auth Blocking token.
*/
function getDecodedAuthBlockingToken(uid: string, authTime: Date): DecodedAuthBlockingToken {
return {
iss: 'https://securetoken.google.com/project123456789',
aud: 'https://us-central1-project123456789.cloudfunctions.net/functionName',
auth_time: Math.floor(authTime.getTime() / 1000),
sub: uid,
iat: Math.floor(authTime.getTime() / 1000),
exp: Math.floor(authTime.getTime() / 1000 + 3600),
uid,
event_id: 'abcdefgh',
event_type: 'beforeCreate',
ip_address: '1234556',
};
}
/**
* Generates a mock decoded session cookie with the provided parameters.
*
* @param {string} uid The uid corresponding to the session cookie.
* @param {Date} authTime The authentication time of the session cookie.
* @param {string=} tenantId The optional tenant ID.
* @return {DecodedIdToken} The generated decoded session cookie.
*/
function getDecodedSessionCookie(uid: string, authTime: Date, tenantId?: string): DecodedIdToken {
return {
iss: 'https://session.firebase.google.com/project123456789',
aud: 'project123456789',
auth_time: Math.floor(authTime.getTime() / 1000),
sub: uid,
iat: Math.floor(authTime.getTime() / 1000),
exp: Math.floor(authTime.getTime() / 1000 + 3600),
firebase: {
identities: {},
sign_in_provider: 'custom',
tenant: tenantId,
},
uid,
};
}
/**
* Generates a mock OIDC config server response for the corresponding provider ID.
*
* @param {string} providerId The provider ID whose sample OIDCConfigServerResponse is to be returned.
* @return {OIDCConfigServerResponse} The corresponding sample OIDCConfigServerResponse.
*/
function getOIDCConfigServerResponse(providerId: string): OIDCConfigServerResponse {
return {
name: `projects/project_id/oauthIdpConfigs/${providerId}`,
displayName: 'OIDC_DISPLAY_NAME',
enabled: true,
clientId: 'CLIENT_ID',
issuer: 'https://oidc.com/issuer',
};
}
/**
* Generates a mock SAML config server response for the corresponding provider ID.
*
* @param {string} providerId The provider ID whose sample SAMLConfigServerResponse is to be returned.
* @return {SAMLConfigServerResponse} The corresponding sample SAMLConfigServerResponse.
*/
function getSAMLConfigServerResponse(providerId: string): SAMLConfigServerResponse {
return {
name: `projects/project_id/inboundSamlConfigs/${providerId}`,
idpConfig: {
idpEntityId: 'IDP_ENTITY_ID',
ssoUrl: 'https://example.com/login',
signRequest: true,
idpCertificates: [
{ x509Certificate: 'CERT1' },
{ x509Certificate: 'CERT2' },
],
},
spConfig: {
spEntityId: 'RP_ENTITY_ID',
callbackUri: 'https://projectId.firebaseapp.com/__/auth/handler',
},
displayName: 'SAML_DISPLAY_NAME',
enabled: true,
};
}
const INVALID_PROVIDER_IDS = [
undefined, null, NaN, 0, 1, true, false, '', [], [1, 'a'], {}, { a: 1 }, _.noop];
const TENANT_ID = 'tenantId';
const AUTH_CONFIGS: AuthTest[] = [
{
name: 'Auth',
Auth,
supportsTenantManagement: true,
RequestHandler: AuthRequestHandler,
init: (app: FirebaseApp) => {
return new Auth(app);
},
},
{
name: 'TenantAwareAuth',
Auth: TenantAwareAuth,
supportsTenantManagement: false,
RequestHandler: TenantAwareAuthRequestHandler,
init: (app: FirebaseApp) => {
return new TenantAwareAuth(app, TENANT_ID);
},
},
];
AUTH_CONFIGS.forEach((testConfig) => {
describe(testConfig.name, () => {
let auth: BaseAuth;
let mockApp: FirebaseApp;
let getTokenStub: sinon.SinonStub;
let oldProcessEnv: NodeJS.ProcessEnv;
let nullAccessTokenAuth: BaseAuth;
let malformedAccessTokenAuth: BaseAuth;
let rejectedPromiseAccessTokenAuth: BaseAuth;
beforeEach(() => {
mockApp = mocks.app();
getTokenStub = utils.stubGetAccessToken(undefined, mockApp);
auth = testConfig.init(mockApp);
nullAccessTokenAuth = testConfig.init(mocks.appReturningNullAccessToken());
malformedAccessTokenAuth = testConfig.init(mocks.appReturningMalformedAccessToken());
rejectedPromiseAccessTokenAuth = testConfig.init(mocks.appRejectedWhileFetchingAccessToken());
oldProcessEnv = process.env;
// Project ID not set in the environment.
delete process.env.GOOGLE_CLOUD_PROJECT;
delete process.env.GCLOUD_PROJECT;
});
afterEach(() => {
getTokenStub.restore();
process.env = oldProcessEnv;
return mockApp.delete();
});
if (testConfig.Auth === Auth) {
// Run tests for Auth.
describe('Constructor', () => {
const invalidApps = [null, NaN, 0, 1, true, false, '', 'a', [], [1, 'a'], {}, { a: 1 }, _.noop];
invalidApps.forEach((invalidApp) => {
it('should throw given invalid app: ' + JSON.stringify(invalidApp), () => {
expect(() => {
const authAny: any = Auth;
return new authAny(invalidApp);
}).to.throw('First argument passed to admin.auth() must be a valid Firebase app instance.');
});
});
it('should throw given no app', () => {
expect(() => {
const authAny: any = Auth;
return new authAny();
}).to.throw('First argument passed to admin.auth() must be a valid Firebase app instance.');
});
it('should reject given no project ID', () => {
const authWithoutProjectId = new Auth(mocks.mockCredentialApp());
authWithoutProjectId.getUser('uid')
.should.eventually.be.rejectedWith(
'Failed to determine project ID for Auth. Initialize the SDK with service '
+ 'account credentials or set project ID as an app option. Alternatively set the '
+ 'GOOGLE_CLOUD_PROJECT environment variable.');
});
it('should not throw given a valid app', () => {
expect(() => {
return new Auth(mockApp);
}).not.to.throw();
});
});
describe('app', () => {
it('returns the app from the constructor', () => {
// We expect referential equality here
expect((auth as Auth).app).to.equal(mockApp);
});
it('is read-only', () => {
expect(() => {
(auth as any).app = mockApp;
}).to.throw('Cannot set property app of #<Auth> which has only a getter');
});
});
describe('tenantManager()', () => {
it('should return a TenantManager with the expected attributes', () => {
const tenantManager1 = (auth as Auth).tenantManager();
const tenantManager2 = new TenantManager(mockApp);
expect(tenantManager1).to.deep.equal(tenantManager2);
});
it('should return the same cached instance', () => {
const tenantManager1 = (auth as Auth).tenantManager();
const tenantManager2 = (auth as Auth).tenantManager();
expect(tenantManager1).to.equal(tenantManager2);
});
});
}
describe('createCustomToken()', () => {
it('should return a jwt', async () => {
const token = await auth.createCustomToken('uid1');
const decodedToken = jwt.decode(token, { complete: true });
expect(decodedToken).to.have.property('header').that.has.property('typ', 'JWT');
});
if (testConfig.Auth === TenantAwareAuth) {
it('should contain tenant_id', async () => {
const token = await auth.createCustomToken('uid1');
expect(jwt.decode(token)).to.have.property('tenant_id', TENANT_ID);
});
} else {
it('should not contain tenant_id', async () => {
const token = await auth.createCustomToken('uid1');
expect(jwt.decode(token)).to.not.have.property('tenant_id');
});
}
it('should be eventually rejected if a cert credential is not specified', () => {
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
// Force the service account ID discovery to fail.
getTokenStub = sinon.stub(HttpClient.prototype, 'send').rejects(utils.errorFrom({}));
return mockCredentialAuth.createCustomToken(mocks.uid, mocks.developerClaims)
.should.eventually.be.rejected.and.have.property('code', 'auth/invalid-credential');
});
it('should be fulfilled given an app which returns null access tokens', () => {
getTokenStub = sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken')
.resolves(null as any);
// createCustomToken() does not rely on an access token and therefore works in this scenario.
return auth.createCustomToken(mocks.uid, mocks.developerClaims)
.should.eventually.be.fulfilled;
});
it('should be fulfilled given an app which returns invalid access tokens', () => {
getTokenStub = sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken')
.resolves('malformed' as any);
// createCustomToken() does not rely on an access token and therefore works in this scenario.
return auth.createCustomToken(mocks.uid, mocks.developerClaims)
.should.eventually.be.fulfilled;
});
it('should be fulfilled given an app which fails to generate access tokens', () => {
getTokenStub = sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken').rejects('error');
// createCustomToken() does not rely on an access token and therefore works in this scenario.
return auth.createCustomToken(mocks.uid, mocks.developerClaims)
.should.eventually.be.fulfilled;
});
});
it('verifyIdToken() should reject when project ID is not specified', () => {
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
const expected = 'Must initialize app with a cert credential or set your Firebase project ID ' +
'as the GOOGLE_CLOUD_PROJECT environment variable to call verifyIdToken().';
return mockCredentialAuth.verifyIdToken(mocks.generateIdToken())
.should.eventually.be.rejectedWith(expected);
});
it('verifySessionCookie() should reject when project ID is not specified', () => {
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
const expected = 'Must initialize app with a cert credential or set your Firebase project ID ' +
'as the GOOGLE_CLOUD_PROJECT environment variable to call verifySessionCookie().';
return mockCredentialAuth.verifySessionCookie(mocks.generateSessionCookie())
.should.eventually.be.rejectedWith(expected);
});
it('_verifyAuthBlockingToken() should reject when project ID is not specified', () => {
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
const expected = 'Must initialize app with a cert credential or set your Firebase project ID ' +
'as the GOOGLE_CLOUD_PROJECT environment variable to call _verifyAuthBlockingToken().';
return mockCredentialAuth._verifyAuthBlockingToken(mocks.generateAuthBlockingToken())
.should.eventually.be.rejectedWith(expected);
});
describe('verifyIdToken()', () => {
let stub: sinon.SinonStub;
let mockIdToken: string;
const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID;
const expectedUserRecord = getValidUserRecord(getValidGetAccountInfoResponse(tenantId));
// Set auth_time of token to expected user's tokensValidAfterTime.
expect(
expectedUserRecord.tokensValidAfterTime,
"getValidUserRecord didn't properly set tokensValueAfterTime",
).to.exist;
const validSince = new Date(expectedUserRecord.tokensValidAfterTime!);
// Set expected uid to expected user's.
const uid = expectedUserRecord.uid;
// Set expected decoded ID token with expected UID and auth time.
const decodedIdToken = getDecodedIdToken(uid, validSince, tenantId);
let clock: sinon.SinonFakeTimers;
// Stubs used to simulate underlying api calls.
const stubs: sinon.SinonStub[] = [];
beforeEach(() => {
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(decodedIdToken);
stubs.push(stub);
mockIdToken = mocks.generateIdToken();
clock = sinon.useFakeTimers(validSince.getTime());
});
afterEach(() => {
_.forEach(stubs, (s) => s.restore());
clock.restore();
});
it('should forward on the call to the token generator\'s verifyIdToken() method', () => {
// Stub getUser call.
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser');
stubs.push(getUserStub);
return auth.verifyIdToken(mockIdToken).then((result) => {
// Confirm getUser never called.
expect(getUserStub).not.to.have.been.called;
expect(result).to.deep.equal(decodedIdToken);
expect(stub).to.have.been.calledOnce.and.calledWith(mockIdToken);
});
});
it('should reject when underlying idTokenVerifier.verifyJWT() rejects with expected error', () => {
const expectedError = new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT, 'Decoding Firebase ID token failed');
// Restore verifyIdToken stub.
stub.restore();
// Simulate ID token is invalid.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.rejects(expectedError);
stubs.push(stub);
return auth.verifyIdToken(mockIdToken)
.should.eventually.be.rejectedWith('Decoding Firebase ID token failed');
});
it('should be rejected with checkRevoked set to true and corresponding user disabled', () => {
const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId);
expectedAccountInfoResponse.users[0].disabled = true;
const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponse);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecordDisabled);
expect(expectedUserRecordDisabled.disabled).to.be.equal(true);
stubs.push(getUserStub);
return auth.verifyIdToken(mockIdToken, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
// Confirm expected error returned.
expect(error).to.have.property('code', 'auth/user-disabled');
});
});
it('verifyIdToken() should reject user disabled before ID tokens revoked', () => {
const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId);
const expectedAccountInfoResponseUserDisabled = Object.assign({}, expectedAccountInfoResponse);
expectedAccountInfoResponseUserDisabled.users[0].disabled = true;
const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponseUserDisabled);
const validSince = new Date(expectedUserRecordDisabled.tokensValidAfterTime!);
// Restore verifyIdToken stub.
stub.restore();
// One second before validSince.
const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000);
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(getDecodedIdToken(expectedUserRecordDisabled.uid, oneSecBeforeValidSince));
stubs.push(stub);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecordDisabled);
expect(expectedUserRecordDisabled.disabled).to.be.equal(true);
stubs.push(getUserStub);
return auth.verifyIdToken(mockIdToken, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm expected error returned.
expect(error).to.have.property('code', 'auth/user-disabled');
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(expectedUserRecordDisabled.uid);
});
});
it('should work with a non-cert credential when the GOOGLE_CLOUD_PROJECT environment variable is present', () => {
process.env.GOOGLE_CLOUD_PROJECT = mocks.projectId;
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
return mockCredentialAuth.verifyIdToken(mockIdToken).then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith(mockIdToken);
});
});
it('should work with a non-cert credential when the GCLOUD_PROJECT environment variable is present', () => {
process.env.GCLOUD_PROJECT = mocks.projectId;
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
return mockCredentialAuth.verifyIdToken(mockIdToken).then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith(mockIdToken);
});
});
it('should be fulfilled given an app which returns null access tokens', () => {
// verifyIdToken() does not rely on an access token and therefore works in this scenario.
return nullAccessTokenAuth.verifyIdToken(mockIdToken)
.should.eventually.be.fulfilled;
});
it('should be fulfilled given an app which returns invalid access tokens', () => {
// verifyIdToken() does not rely on an access token and therefore works in this scenario.
return malformedAccessTokenAuth.verifyIdToken(mockIdToken)
.should.eventually.be.fulfilled;
});
it('should be fulfilled given an app which fails to generate access tokens', () => {
// verifyIdToken() does not rely on an access token and therefore works in this scenario.
return rejectedPromiseAccessTokenAuth.verifyIdToken(mockIdToken)
.should.eventually.be.fulfilled;
});
it('should be fulfilled with checkRevoked set to true using an unrevoked ID token', () => {
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecord);
stubs.push(getUserStub);
// Verify ID token while checking if revoked.
return auth.verifyIdToken(mockIdToken, true)
.then((result) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
expect(result).to.deep.equal(decodedIdToken);
});
});
it('should be rejected with checkRevoked set to true using a revoked ID token', () => {
// One second before validSince.
const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000);
// Restore verifyIdToken stub.
stub.restore();
// Simulate revoked ID token returned with auth_time one second before validSince.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(getDecodedIdToken(uid, oneSecBeforeValidSince));
stubs.push(stub);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecord);
stubs.push(getUserStub);
// Verify ID token while checking if revoked.
return auth.verifyIdToken(mockIdToken, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
// Confirm expected error returned.
expect(error).to.have.property('code', 'auth/id-token-revoked');
});
});
it('should be fulfilled with checkRevoked set to false using a revoked ID token', () => {
// One second before validSince.
const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000);
const oneSecBeforeValidSinceDecodedIdToken =
getDecodedIdToken(uid, oneSecBeforeValidSince, tenantId);
// Restore verifyIdToken stub.
stub.restore();
// Simulate revoked ID token returned with auth_time one second before validSince.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(oneSecBeforeValidSinceDecodedIdToken);
stubs.push(stub);
// Verify ID token without checking if revoked.
// This call should succeed.
return auth.verifyIdToken(mockIdToken, false)
.then((result) => {
expect(result).to.deep.equal(oneSecBeforeValidSinceDecodedIdToken);
});
});
it('should be rejected with checkRevoked set to true if underlying RPC fails', () => {
const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.rejects(expectedError);
stubs.push(getUserStub);
// Verify ID token while checking if revoked.
// This should fail with the underlying RPC error.
return auth.verifyIdToken(mockIdToken, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
// Confirm expected error returned.
expect(error).to.equal(expectedError);
});
});
it('should be fulfilled with checkRevoked set to true when no validSince available', () => {
// Simulate no validSince set on the user.
const noValidSinceGetAccountInfoResponse = getValidGetAccountInfoResponse(tenantId);
delete (noValidSinceGetAccountInfoResponse.users[0] as any).validSince;
const noValidSinceExpectedUserRecord =
getValidUserRecord(noValidSinceGetAccountInfoResponse);
// Confirm null tokensValidAfterTime on user.
expect(noValidSinceExpectedUserRecord.tokensValidAfterTime).to.be.undefined;
// Simulate getUser returns the expected user with no validSince.
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(noValidSinceExpectedUserRecord);
stubs.push(getUserStub);
// Verify ID token while checking if revoked.
return auth.verifyIdToken(mockIdToken, true)
.then((result) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
expect(result).to.deep.equal(decodedIdToken);
});
});
it('should be rejected with checkRevoked set to true using an invalid ID token', () => {
const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CREDENTIAL);
// Restore verifyIdToken stub.
stub.restore();
// Simulate ID token is invalid.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.rejects(expectedError);
stubs.push(stub);
// Verify ID token while checking if revoked.
// This should fail with the underlying token generator verifyIdToken error.
return auth.verifyIdToken(mockIdToken, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm expected error returned.
expect(error).to.equal(expectedError);
});
});
if (testConfig.Auth === TenantAwareAuth) {
it('should be rejected with ID token missing tenant ID', () => {
const expectedError = new FirebaseAuthError(AuthClientErrorCode.MISMATCHING_TENANT_ID);
// Restore verifyIdToken stub.
stub.restore();
// Simulate JWT does not contain tenant ID.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.returns(Promise.resolve(getDecodedIdToken(uid, validSince)));
// Verify ID token.
return auth.verifyIdToken(mockIdToken)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm expected error returned.
expect(error).to.deep.include(expectedError);
});
});
it('should be rejected with ID token containing mismatching tenant ID', () => {
const expectedError = new FirebaseAuthError(AuthClientErrorCode.MISMATCHING_TENANT_ID);
// Restore verifyIdToken stub.
stub.restore();
// Simulate JWT does not contain matching tenant ID.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.returns(Promise.resolve(getDecodedIdToken(uid, validSince, 'otherTenantId')));
// Verify ID token.
return auth.verifyIdToken(mockIdToken)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm expected error returned.
expect(error).to.deep.include(expectedError);
});
});
}
});
describe('verifySessionCookie()', () => {
let stub: sinon.SinonStub;
let mockSessionCookie: string;
const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID;
const expectedUserRecord = getValidUserRecord(getValidGetAccountInfoResponse(tenantId));
// Set auth_time of token to expected user's tokensValidAfterTime.
if (!expectedUserRecord.tokensValidAfterTime) {
throw new Error("getValidUserRecord didn't properly set tokensValidAfterTime.");
}
const validSince = new Date(expectedUserRecord.tokensValidAfterTime);
// Set expected uid to expected user's.
const uid = expectedUserRecord.uid;
// Set expected decoded session cookie with expected UID and auth time.
const decodedSessionCookie = getDecodedSessionCookie(uid, validSince, tenantId);
let clock: sinon.SinonFakeTimers;
// Stubs used to simulate underlying api calls.
const stubs: sinon.SinonStub[] = [];
beforeEach(() => {
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(decodedSessionCookie);
stubs.push(stub);
mockSessionCookie = mocks.generateSessionCookie();
clock = sinon.useFakeTimers(validSince.getTime());
});
afterEach(() => {
_.forEach(stubs, (s) => s.restore());
clock.restore();
});
it('should forward on the call to the token verifier\'s verifySessionCookie() method', () => {
// Stub getUser call.
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser');
stubs.push(getUserStub);
return auth.verifySessionCookie(mockSessionCookie).then((result) => {
// Confirm getUser never called.
expect(getUserStub).not.to.have.been.called;
expect(result).to.deep.equal(decodedSessionCookie);
expect(stub).to.have.been.calledOnce.and.calledWith(mockSessionCookie);
});
});
it('should reject when underlying sessionCookieVerifier.verifyJWT() rejects with expected error', () => {
const expectedError = new FirebaseAuthError(
AuthClientErrorCode.INVALID_ARGUMENT, 'Decoding Firebase session cookie failed');
// Restore verifySessionCookie stub.
stub.restore();
// Simulate session cookie is invalid.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.rejects(expectedError);
stubs.push(stub);
return auth.verifySessionCookie(mockSessionCookie)
.should.eventually.be.rejectedWith('Decoding Firebase session cookie failed');
});
it('should work with a non-cert credential when the GOOGLE_CLOUD_PROJECT environment variable is present', () => {
process.env.GOOGLE_CLOUD_PROJECT = mocks.projectId;
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
return mockCredentialAuth.verifySessionCookie(mockSessionCookie).then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith(mockSessionCookie);
});
});
it('should work with a non-cert credential when the GCLOUD_PROJECT environment variable is present', () => {
process.env.GCLOUD_PROJECT = mocks.projectId;
const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp());
return mockCredentialAuth.verifySessionCookie(mockSessionCookie).then(() => {
expect(stub).to.have.been.calledOnce.and.calledWith(mockSessionCookie);
});
});
it('should be fulfilled given an app which returns null access tokens', () => {
// verifySessionCookie() does not rely on an access token and therefore works in this scenario.
return nullAccessTokenAuth.verifySessionCookie(mockSessionCookie)
.should.eventually.be.fulfilled;
});
it('should be fulfilled given an app which returns invalid access tokens', () => {
// verifySessionCookie() does not rely on an access token and therefore works in this scenario.
return malformedAccessTokenAuth.verifySessionCookie(mockSessionCookie)
.should.eventually.be.fulfilled;
});
it('should be fulfilled given an app which fails to generate access tokens', () => {
// verifySessionCookie() does not rely on an access token and therefore works in this scenario.
return rejectedPromiseAccessTokenAuth.verifySessionCookie(mockSessionCookie)
.should.eventually.be.fulfilled;
});
it('should be fulfilled with checkRevoked set to true using an unrevoked session cookie', () => {
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecord);
stubs.push(getUserStub);
// Verify ID token while checking if revoked.
return auth.verifySessionCookie(mockSessionCookie, true)
.then((result) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
expect(result).to.deep.equal(decodedSessionCookie);
});
});
it('should be rejected with checkRevoked set to true using a revoked session cookie', () => {
// One second before validSince.
const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000);
// Restore verifySessionCookie stub.
stub.restore();
// Simulate revoked session cookie returned with auth_time one second before validSince.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(getDecodedSessionCookie(uid, oneSecBeforeValidSince));
stubs.push(stub);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecord);
stubs.push(getUserStub);
// Verify session cookie while checking if revoked.
return auth.verifySessionCookie(mockSessionCookie, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
// Confirm expected error returned.
expect(error).to.have.property('code', 'auth/session-cookie-revoked');
});
});
it('should be fulfilled with checkRevoked set to false using a revoked session cookie', () => {
// One second before validSince.
const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000);
const oneSecBeforeValidSinceDecodedSessionCookie =
getDecodedSessionCookie(uid, oneSecBeforeValidSince, tenantId);
// Restore verifySessionCookie stub.
stub.restore();
// Simulate revoked session cookie returned with auth_time one second before validSince.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(oneSecBeforeValidSinceDecodedSessionCookie);
stubs.push(stub);
// Verify session cookie without checking if revoked.
// This call should succeed.
return auth.verifySessionCookie(mockSessionCookie, false)
.then((result) => {
expect(result).to.deep.equal(oneSecBeforeValidSinceDecodedSessionCookie);
});
});
it('should be rejected with checkRevoked set to true if underlying RPC fails', () => {
const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.rejects(expectedError);
stubs.push(getUserStub);
// Verify session cookie while checking if revoked.
// This should fail with the underlying RPC error.
return auth.verifySessionCookie(mockSessionCookie, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
// Confirm expected error returned.
expect(error).to.equal(expectedError);
});
});
it('should be rejected with checkRevoked set to true and corresponding user disabled', () => {
const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId);
expectedAccountInfoResponse.users[0].disabled = true;
const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponse);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecordDisabled);
expect(expectedUserRecordDisabled.disabled).to.be.equal(true);
stubs.push(getUserStub);
return auth.verifySessionCookie(mockSessionCookie, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
// Confirm expected error returned.
expect(error).to.have.property('code', 'auth/user-disabled');
});
});
it('verifySessionCookie() should reject user disabled before ID tokens revoked', () => {
const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId);
const expectedAccountInfoResponseUserDisabled = Object.assign({}, expectedAccountInfoResponse);
expectedAccountInfoResponseUserDisabled.users[0].disabled = true;
const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponseUserDisabled);
const validSince = new Date(expectedUserRecordDisabled.tokensValidAfterTime!);
// Restore verifySessionCookie stub.
stub.restore();
// One second before validSince.
const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000);
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.resolves(getDecodedIdToken(expectedUserRecordDisabled.uid, oneSecBeforeValidSince));
stubs.push(stub);
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(expectedUserRecordDisabled);
expect(expectedUserRecordDisabled.disabled).to.be.equal(true);
stubs.push(getUserStub);
return auth.verifySessionCookie(mockSessionCookie, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(expectedUserRecordDisabled.uid);
// Confirm expected error returned.
expect(error).to.have.property('code', 'auth/user-disabled');
});
});
it('should be fulfilled with checkRevoked set to true when no validSince available', () => {
// Simulate no validSince set on the user.
const noValidSinceGetAccountInfoResponse = getValidGetAccountInfoResponse(tenantId);
delete (noValidSinceGetAccountInfoResponse.users[0] as any).validSince;
const noValidSinceExpectedUserRecord =
getValidUserRecord(noValidSinceGetAccountInfoResponse);
// Confirm null tokensValidAfterTime on user.
expect(noValidSinceExpectedUserRecord.tokensValidAfterTime).to.be.undefined;
// Simulate getUser returns the expected user with no validSince.
const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser')
.resolves(noValidSinceExpectedUserRecord);
stubs.push(getUserStub);
// Verify session cookie while checking if revoked.
return auth.verifySessionCookie(mockSessionCookie, true)
.then((result) => {
// Confirm underlying API called with expected parameters.
expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid);
expect(result).to.deep.equal(decodedSessionCookie);
});
});
it('should be rejected with checkRevoked set to true using an invalid session cookie', () => {
const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CREDENTIAL);
// Restore verifySessionCookie stub.
stub.restore();
// Simulate session cookie is invalid.
stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT')
.rejects(expectedError);
stubs.push(stub);
// Verify session cookie while checking if revoked.
// This should fail with the underlying token generator verifySessionCookie error.
return auth.verifySessionCookie(mockSessionCookie, true)
.then(() => {
throw new Error('Unexpected success');
}, (error) => {
// Confirm expected error returned.
expect(error).to.equal(expectedError);
});
});