forked from firebase/firebase-admin-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.spec.ts
More file actions
executable file
·1636 lines (1525 loc) · 60.7 KB
/
auth.spec.ts
File metadata and controls
executable file
·1636 lines (1525 loc) · 60.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
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
/*!
* Copyright 2018 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 * as admin from '../../lib/index';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as crypto from 'crypto';
import * as bcrypt from 'bcrypt';
import * as scrypt from 'scrypt';
import firebase from '@firebase/app';
import '@firebase/auth';
import {clone} from 'lodash';
import {
generateRandomString, projectId, apiKey, noServiceAccountApp, cmdArgs,
} from './setup';
import url = require('url');
import * as mocks from '../resources/mocks';
import { AuthProviderConfig } from '../../src/auth/auth-config';
import { deepExtend, deepCopy } from '../../src/utils/deep-copy';
/* tslint:disable:no-var-requires */
const chalk = require('chalk');
/* tslint:enable:no-var-requires */
chai.should();
chai.use(chaiAsPromised);
const expect = chai.expect;
const newUserUid = generateRandomString(20);
const nonexistentUid = generateRandomString(20);
const sessionCookieUids = [
generateRandomString(20),
generateRandomString(20),
generateRandomString(20),
];
const testPhoneNumber = '+11234567890';
const testPhoneNumber2 = '+16505550101';
const nonexistentPhoneNumber = '+18888888888';
const updatedEmail = generateRandomString(20).toLowerCase() + '@example.com';
const updatedPhone = '+16505550102';
const customClaims: {[key: string]: any} = {
admin: true,
groupId: '1234',
};
const uids = [newUserUid + '-1', newUserUid + '-2', newUserUid + '-3'];
const mockUserData = {
email: newUserUid.toLowerCase() + '@example.com',
emailVerified: false,
phoneNumber: testPhoneNumber,
password: 'password',
displayName: 'Random User ' + newUserUid,
photoURL: 'http://www.example.com/' + newUserUid + '/photo.png',
disabled: false,
};
const actionCodeSettings = {
url: 'http://localhost/?a=1&b=2#c=3',
handleCodeInApp: false,
};
let deleteQueue = Promise.resolve();
interface UserImportTest {
name: string;
importOptions: admin.auth.UserImportOptions;
rawPassword: string;
rawSalt?: string;
computePasswordHash(userImportTest: UserImportTest): Buffer;
}
/** @return Random generated SAML provider ID. */
function randomSamlProviderId(): string {
return 'saml.' + generateRandomString(10, false).toLowerCase();
}
/** @return Random generated OIDC provider ID. */
function randomOidcProviderId(): string {
return 'oidc.' + generateRandomString(10, false).toLowerCase();
}
describe('admin.auth', () => {
let uidFromCreateUserWithoutUid: string;
before(() => {
firebase.initializeApp({
apiKey,
authDomain: projectId + '.firebaseapp.com',
});
return cleanup();
});
after(() => {
return cleanup();
});
it('createUser() creates a new user when called without a UID', () => {
const newUserData = clone(mockUserData);
newUserData.email = generateRandomString(20).toLowerCase() + '@example.com';
newUserData.phoneNumber = testPhoneNumber2;
return admin.auth().createUser(newUserData)
.then((userRecord) => {
uidFromCreateUserWithoutUid = userRecord.uid;
expect(typeof userRecord.uid).to.equal('string');
// Confirm expected email.
expect(userRecord.email).to.equal(newUserData.email);
// Confirm expected phone number.
expect(userRecord.phoneNumber).to.equal(newUserData.phoneNumber);
});
});
it('createUser() creates a new user with the specified UID', () => {
const newUserData: any = clone(mockUserData);
newUserData.uid = newUserUid;
return admin.auth().createUser(newUserData)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
// Confirm expected email.
expect(userRecord.email).to.equal(newUserData.email);
// Confirm expected phone number.
expect(userRecord.phoneNumber).to.equal(newUserData.phoneNumber);
});
});
it('createUser() fails when the UID is already in use', () => {
const newUserData: any = clone(mockUserData);
newUserData.uid = newUserUid;
return admin.auth().createUser(newUserData)
.should.eventually.be.rejected.and.have.property('code', 'auth/uid-already-exists');
});
it('getUser() returns a user record with the matching UID', () => {
return admin.auth().getUser(newUserUid)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByEmail() returns a user record with the matching email', () => {
return admin.auth().getUserByEmail(mockUserData.email)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('getUserByPhoneNumber() returns a user record with the matching phone number', () => {
return admin.auth().getUserByPhoneNumber(mockUserData.phoneNumber)
.then((userRecord) => {
expect(userRecord.uid).to.equal(newUserUid);
});
});
it('listUsers() returns up to the specified number of users', () => {
const promises: Array<Promise<admin.auth.UserRecord>> = [];
uids.forEach((uid) => {
const tempUserData = {
uid,
password: 'password',
};
promises.push(admin.auth().createUser(tempUserData));
});
return Promise.all(promises)
.then(() => {
// Return 2 users with the provided page token.
// This test will fail if other users are created in between.
return admin.auth().listUsers(2, uids[0]);
})
.then((listUsersResult) => {
// Confirm expected number of users.
expect(listUsersResult.users.length).to.equal(2);
// Confirm next page token present.
expect(typeof listUsersResult.pageToken).to.equal('string');
// Confirm each user's uid and the hashed passwords.
expect(listUsersResult.users[0].uid).to.equal(uids[1]);
expect(listUsersResult.users[0].passwordHash.length).greaterThan(0);
expect(listUsersResult.users[0].passwordSalt.length).greaterThan(0);
expect(listUsersResult.users[1].uid).to.equal(uids[2]);
expect(listUsersResult.users[1].passwordHash.length).greaterThan(0);
expect(listUsersResult.users[1].passwordSalt.length).greaterThan(0);
});
});
it('revokeRefreshTokens() invalidates existing sessions and ID tokens', () => {
let currentIdToken: string = null;
let currentUser: any = null;
// Sign in with an email and password account.
return firebase.auth().signInWithEmailAndPassword(mockUserData.email, mockUserData.password)
.then(({user}) => {
currentUser = user;
// Get user's ID token.
return user.getIdToken();
})
.then((idToken) => {
currentIdToken = idToken;
// Verify that user's ID token while checking for revocation.
return admin.auth().verifyIdToken(currentIdToken, true);
})
.then((decodedIdToken) => {
// Verification should succeed. Revoke that user's session.
return new Promise((resolve) => setTimeout(() => resolve(
admin.auth().revokeRefreshTokens(decodedIdToken.sub),
), 1000));
})
.then(() => {
// verifyIdToken without checking revocation should still succeed.
return admin.auth().verifyIdToken(currentIdToken)
.should.eventually.be.fulfilled;
})
.then(() => {
// verifyIdToken while checking for revocation should fail.
return admin.auth().verifyIdToken(currentIdToken, true)
.should.eventually.be.rejected.and.have.property('code', 'auth/id-token-revoked');
})
.then(() => {
// Confirm token revoked on client.
return currentUser.reload()
.should.eventually.be.rejected.and.have.property('code', 'auth/user-token-expired');
})
.then(() => {
// New sign-in should succeed.
return firebase.auth().signInWithEmailAndPassword(
mockUserData.email, mockUserData.password);
})
.then(({user}) => {
// Get new session's ID token.
return user.getIdToken();
})
.then((idToken) => {
// ID token for new session should be valid even with revocation check.
return admin.auth().verifyIdToken(idToken, true)
.should.eventually.be.fulfilled;
});
});
it('setCustomUserClaims() sets claims that are accessible via user\'s ID token', () => {
// Set custom claims on the user.
return admin.auth().setCustomUserClaims(newUserUid, customClaims)
.then(() => {
return admin.auth().getUser(newUserUid);
})
.then((userRecord) => {
// Confirm custom claims set on the UserRecord.
expect(userRecord.customClaims).to.deep.equal(customClaims);
return firebase.auth().signInWithEmailAndPassword(
userRecord.email, mockUserData.password);
})
.then(({user}) => {
// Get the user's ID token.
return user.getIdToken();
})
.then((idToken) => {
// Verify ID token contents.
return admin.auth().verifyIdToken(idToken);
})
.then((decodedIdToken: {[key: string]: any}) => {
// Confirm expected claims set on the user's ID token.
for (const key in customClaims) {
if (customClaims.hasOwnProperty(key)) {
expect(decodedIdToken[key]).to.equal(customClaims[key]);
}
}
});
});
it('updateUser() updates the user record with the given parameters', () => {
const updatedDisplayName = 'Updated User ' + newUserUid;
return admin.auth().updateUser(newUserUid, {
email: updatedEmail,
phoneNumber: updatedPhone,
emailVerified: true,
displayName: updatedDisplayName,
})
.then((userRecord) => {
expect(userRecord.emailVerified).to.be.true;
expect(userRecord.displayName).to.equal(updatedDisplayName);
// Confirm expected email.
expect(userRecord.email).to.equal(updatedEmail);
// Confirm expected phone number.
expect(userRecord.phoneNumber).to.equal(updatedPhone);
});
});
it('getUser() fails when called with a non-existing UID', () => {
return admin.auth().getUser(nonexistentUid)
.should.eventually.be.rejected.and.have.property('code', 'auth/user-not-found');
});
it('getUserByEmail() fails when called with a non-existing email', () => {
return admin.auth().getUserByEmail(nonexistentUid + '@example.com')
.should.eventually.be.rejected.and.have.property('code', 'auth/user-not-found');
});
it('getUserByPhoneNumber() fails when called with a non-existing phone number', () => {
return admin.auth().getUserByPhoneNumber(nonexistentPhoneNumber)
.should.eventually.be.rejected.and.have.property('code', 'auth/user-not-found');
});
it('updateUser() fails when called with a non-existing UID', () => {
return admin.auth().updateUser(nonexistentUid, {
emailVerified: true,
}).should.eventually.be.rejected.and.have.property('code', 'auth/user-not-found');
});
it('deleteUser() fails when called with a non-existing UID', () => {
return admin.auth().deleteUser(nonexistentUid)
.should.eventually.be.rejected.and.have.property('code', 'auth/user-not-found');
});
it('createCustomToken() mints a JWT that can be used to sign in', () => {
return admin.auth().createCustomToken(newUserUid, {
isAdmin: true,
})
.then((customToken) => {
return firebase.auth().signInWithCustomToken(customToken);
})
.then(({user}) => {
return user.getIdToken();
})
.then((idToken) => {
return admin.auth().verifyIdToken(idToken);
})
.then((token) => {
expect(token.uid).to.equal(newUserUid);
expect(token.isAdmin).to.be.true;
});
});
it('createCustomToken() can mint JWTs without a service account', () => {
return admin.auth(noServiceAccountApp).createCustomToken(newUserUid, {
isAdmin: true,
})
.then((customToken) => {
return firebase.auth().signInWithCustomToken(customToken);
})
.then(({user}) => {
return user.getIdToken();
})
.then((idToken) => {
return admin.auth(noServiceAccountApp).verifyIdToken(idToken);
})
.then((token) => {
expect(token.uid).to.equal(newUserUid);
expect(token.isAdmin).to.be.true;
});
});
it('verifyIdToken() fails when called with an invalid token', () => {
return admin.auth().verifyIdToken('invalid-token')
.should.eventually.be.rejected.and.have.property('code', 'auth/argument-error');
});
describe('Link operations', () => {
const uid = generateRandomString(20).toLowerCase();
const email = uid + '@example.com';
const newPassword = 'newPassword';
const userData = {
uid,
email,
emailVerified: false,
password: 'password',
};
// Create the test user before running this suite of tests.
before(() => {
return admin.auth().createUser(userData);
});
// Sign out after each test.
afterEach(() => {
return firebase.auth().signOut();
});
// Delete test user at the end of test suite.
after(() => {
return safeDelete(uid);
});
it('generatePasswordResetLink() should return a password reset link', () => {
// Ensure old password set on created user.
return admin.auth().updateUser(uid, {password: 'password'})
.then((userRecord) => {
return admin.auth().generatePasswordResetLink(email, actionCodeSettings);
})
.then((link) => {
const code = getActionCode(link);
expect(getContinueUrl(link)).equal(actionCodeSettings.url);
return firebase.auth().confirmPasswordReset(code, newPassword);
})
.then(() => {
return firebase.auth().signInWithEmailAndPassword(email, newPassword);
})
.then((result) => {
expect(result.user.email).to.equal(email);
// Password reset also verifies the user's email.
expect(result.user.emailVerified).to.be.true;
});
});
it('generateEmailVerificationLink() should return a verification link', () => {
// Ensure the user's email is unverified.
return admin.auth().updateUser(uid, {password: 'password', emailVerified: false})
.then((userRecord) => {
expect(userRecord.emailVerified).to.be.false;
return admin.auth().generateEmailVerificationLink(email, actionCodeSettings);
})
.then((link) => {
const code = getActionCode(link);
expect(getContinueUrl(link)).equal(actionCodeSettings.url);
return firebase.auth().applyActionCode(code);
})
.then(() => {
return firebase.auth().signInWithEmailAndPassword(email, userData.password);
})
.then((result) => {
expect(result.user.email).to.equal(email);
expect(result.user.emailVerified).to.be.true;
});
});
it('generateSignInWithEmailLink() should return a sign-in link', () => {
return admin.auth().generateSignInWithEmailLink(email, actionCodeSettings)
.then((link) => {
expect(getContinueUrl(link)).equal(actionCodeSettings.url);
return firebase.auth().signInWithEmailLink(email, link);
})
.then((result) => {
expect(result.user.email).to.equal(email);
expect(result.user.emailVerified).to.be.true;
});
});
});
describe('Tenant management operations', () => {
let createdTenantId: string;
const createdTenants: string[] = [];
const tenantOptions: admin.auth.CreateTenantRequest = {
displayName: 'testTenant1',
emailSignInConfig: {
enabled: true,
passwordRequired: true,
},
};
const expectedCreatedTenant: any = {
displayName: 'testTenant1',
emailSignInConfig: {
enabled: true,
passwordRequired: true,
},
};
const expectedUpdatedTenant: any = {
displayName: 'testTenantUpdated',
emailSignInConfig: {
enabled: false,
passwordRequired: true,
},
};
const expectedUpdatedTenant2: any = {
displayName: 'testTenantUpdated',
emailSignInConfig: {
enabled: true,
passwordRequired: false,
},
};
// https://mochajs.org/
// Passing arrow functions (aka "lambdas") to Mocha is discouraged.
// Lambdas lexically bind this and cannot access the Mocha context.
before(function() {
/* tslint:disable:no-console */
if (!cmdArgs.testMultiTenancy) {
// To enable, run: npm run test:integration -- --testMultiTenancy
// By default we skip multi-tenancy as it is a Google Cloud Identity Platform
// feature only and requires to be enabled via the Cloud Console.
console.log(chalk.yellow(' Skipping multi-tenancy tests.'));
this.skip();
}
/* tslint:enable:no-console */
});
// Delete test tenants at the end of test suite.
after(() => {
const promises: Array<Promise<any>> = [];
createdTenants.forEach((tenantId) => {
promises.push(
admin.auth().tenantManager().deleteTenant(tenantId)
.catch((error) => {/** Ignore. */}));
});
return Promise.all(promises);
});
it('createTenant() should resolve with a new tenant', () => {
return admin.auth().tenantManager().createTenant(tenantOptions)
.then((actualTenant) => {
createdTenantId = actualTenant.tenantId;
createdTenants.push(createdTenantId);
expectedCreatedTenant.tenantId = createdTenantId;
expect(actualTenant.toJSON()).to.deep.equal(expectedCreatedTenant);
});
});
// Sanity check user management + email link generation + custom attribute APIs.
// TODO: Confirm behavior in client SDK when it starts supporting it.
describe('supports user management, email link generation, custom attribute and token revocation APIs', () => {
let tenantAwareAuth: admin.auth.TenantAwareAuth;
let createdUserUid: string;
let lastValidSinceTime: number;
const newUserData = clone(mockUserData);
newUserData.email = generateRandomString(20).toLowerCase() + '@example.com';
newUserData.phoneNumber = testPhoneNumber;
const importOptions: any = {
hash: {
algorithm: 'HMAC_SHA256',
key: Buffer.from('secret'),
},
};
const rawPassword = 'password';
const rawSalt = 'NaCl';
before(function() {
if (!createdTenantId) {
this.skip();
} else {
tenantAwareAuth = admin.auth().tenantManager().authForTenant(createdTenantId);
}
});
// Delete test user at the end of test suite.
after(() => {
// If user successfully created, make sure it is deleted at the end of the test suite.
if (createdUserUid) {
return tenantAwareAuth.deleteUser(createdUserUid)
.catch((error) => {
// Ignore error.
});
}
});
it('createUser() should create a user in the expected tenant', () => {
return tenantAwareAuth.createUser(newUserData)
.then((userRecord) => {
createdUserUid = userRecord.uid;
expect(userRecord.tenantId).to.equal(createdTenantId);
expect(userRecord.email).to.equal(newUserData.email);
expect(userRecord.phoneNumber).to.equal(newUserData.phoneNumber);
});
});
it('setCustomUserClaims() should set custom attributes on the tenant specific user', () => {
return tenantAwareAuth.setCustomUserClaims(createdUserUid, customClaims)
.then(() => {
return tenantAwareAuth.getUser(createdUserUid);
})
.then((userRecord) => {
expect(userRecord.uid).to.equal(createdUserUid);
expect(userRecord.tenantId).to.equal(createdTenantId);
// Confirm custom claims set on the UserRecord.
expect(userRecord.customClaims).to.deep.equal(customClaims);
});
});
it('updateUser() should update the tenant specific user', () => {
return tenantAwareAuth.updateUser(createdUserUid, {
email: updatedEmail,
phoneNumber: updatedPhone,
})
.then((userRecord) => {
expect(userRecord.uid).to.equal(createdUserUid);
expect(userRecord.tenantId).to.equal(createdTenantId);
expect(userRecord.email).to.equal(updatedEmail);
expect(userRecord.phoneNumber).to.equal(updatedPhone);
});
});
it('generateEmailVerificationLink() should generate the link for tenant specific user', () => {
// Generate email verification link to confirm it is generated in the expected
// tenant context.
return tenantAwareAuth.generateEmailVerificationLink(updatedEmail, actionCodeSettings)
.then((link) => {
// Confirm tenant ID set in link.
expect(getTenantId(link)).equal(createdTenantId);
});
});
it('generatePasswordResetLink() should generate the link for tenant specific user', () => {
// Generate password reset link to confirm it is generated in the expected
// tenant context.
return tenantAwareAuth.generatePasswordResetLink(updatedEmail, actionCodeSettings)
.then((link) => {
// Confirm tenant ID set in link.
expect(getTenantId(link)).equal(createdTenantId);
});
});
it('generateSignInWithEmailLink() should generate the link for tenant specific user', () => {
// Generate link for sign-in to confirm it is generated in the expected
// tenant context.
return tenantAwareAuth.generateSignInWithEmailLink(updatedEmail, actionCodeSettings)
.then((link) => {
// Confirm tenant ID set in link.
expect(getTenantId(link)).equal(createdTenantId);
});
});
it('revokeRefreshTokens() should revoke the tokens for the tenant specific user', () => {
// Revoke refresh tokens.
// On revocation, tokensValidAfterTime will be updated to current time. All tokens issued
// before that time will be rejected. As the underlying backend field is rounded to the nearest
// second, we are subtracting one second.
lastValidSinceTime = new Date().getTime() - 1000;
return tenantAwareAuth.revokeRefreshTokens(createdUserUid)
.then(() => {
return tenantAwareAuth.getUser(createdUserUid);
})
.then((userRecord) => {
expect(new Date(userRecord.tokensValidAfterTime).getTime())
.to.be.greaterThan(lastValidSinceTime);
});
});
it('listUsers() should list tenant specific users', () => {
return tenantAwareAuth.listUsers(100)
.then((listUsersResult) => {
// Confirm expected user returned in the list and all users returned
// belong to the expected tenant.
const allUsersBelongToTenant =
listUsersResult.users.every((user) => user.tenantId === createdTenantId);
expect(allUsersBelongToTenant).to.be.true;
const knownUserInTenant =
listUsersResult.users.some((user) => user.uid === createdUserUid);
expect(knownUserInTenant).to.be.true;
});
});
it('deleteUser() should delete the tenant specific user', () => {
return tenantAwareAuth.deleteUser(createdUserUid)
.then(() => {
return tenantAwareAuth.getUser(createdUserUid)
.should.eventually.be.rejected.and.have.property('code', 'auth/user-not-found');
});
});
it('importUsers() should upload a user to the specified tenant', () => {
const currentHashKey = importOptions.hash.key.toString('utf8');
const passwordHash =
crypto.createHmac('sha256', currentHashKey).update(rawPassword + rawSalt).digest();
const importUserRecord: any = {
uid: createdUserUid,
email: createdUserUid + '@example.com',
passwordHash,
passwordSalt: Buffer.from(rawSalt),
};
return tenantAwareAuth.importUsers([importUserRecord], importOptions)
.then(() => {
return tenantAwareAuth.getUser(createdUserUid);
})
.then((userRecord) => {
// Confirm user uploaded successfully.
expect(userRecord.tenantId).to.equal(createdTenantId);
expect(userRecord.uid).to.equal(createdUserUid);
});
});
});
// Sanity check OIDC/SAML config management API.
describe('SAML management APIs', () => {
let tenantAwareAuth: admin.auth.TenantAwareAuth;
const authProviderConfig = {
providerId: randomSamlProviderId(),
displayName: 'SAML_DISPLAY_NAME1',
enabled: true,
idpEntityId: 'IDP_ENTITY_ID1',
ssoURL: 'https://example.com/login1',
x509Certificates: [mocks.x509CertPairs[0].public],
rpEntityId: 'RP_ENTITY_ID1',
callbackURL: 'https://projectId.firebaseapp.com/__/auth/handler',
enableRequestSigning: true,
};
const modifiedConfigOptions = {
displayName: 'SAML_DISPLAY_NAME3',
enabled: false,
idpEntityId: 'IDP_ENTITY_ID3',
ssoURL: 'https://example.com/login3',
x509Certificates: [mocks.x509CertPairs[1].public],
rpEntityId: 'RP_ENTITY_ID3',
callbackURL: 'https://projectId3.firebaseapp.com/__/auth/handler',
enableRequestSigning: false,
};
before(function() {
if (!createdTenantId) {
this.skip();
} else {
tenantAwareAuth = admin.auth().tenantManager().authForTenant(createdTenantId);
}
});
// Delete SAML configuration at the end of test suite.
after(() => {
if (tenantAwareAuth) {
return tenantAwareAuth.deleteProviderConfig(authProviderConfig.providerId)
.catch((error) => {
// Ignore error.
});
}
});
it('should support CRUD operations', () => {
return tenantAwareAuth.createProviderConfig(authProviderConfig)
.then((config) => {
assertDeepEqualUnordered(authProviderConfig, config);
return tenantAwareAuth.getProviderConfig(authProviderConfig.providerId);
})
.then((config) => {
assertDeepEqualUnordered(authProviderConfig, config);
return tenantAwareAuth.updateProviderConfig(
authProviderConfig.providerId, modifiedConfigOptions);
})
.then((config) => {
const modifiedConfig = deepExtend(
{providerId: authProviderConfig.providerId}, modifiedConfigOptions);
assertDeepEqualUnordered(modifiedConfig, config);
return tenantAwareAuth.deleteProviderConfig(authProviderConfig.providerId);
})
.then(() => {
return tenantAwareAuth.getProviderConfig(authProviderConfig.providerId)
.should.eventually.be.rejected.and.have.property('code', 'auth/configuration-not-found');
});
});
});
describe('OIDC management APIs', () => {
let tenantAwareAuth: admin.auth.TenantAwareAuth;
const authProviderConfig = {
providerId: randomOidcProviderId(),
displayName: 'OIDC_DISPLAY_NAME1',
enabled: true,
issuer: 'https://oidc.com/issuer1',
clientId: 'CLIENT_ID1',
};
const modifiedConfigOptions = {
displayName: 'OIDC_DISPLAY_NAME3',
enabled: false,
issuer: 'https://oidc.com/issuer3',
clientId: 'CLIENT_ID3',
};
before(function() {
if (!createdTenantId) {
this.skip();
} else {
tenantAwareAuth = admin.auth().tenantManager().authForTenant(createdTenantId);
}
});
// Delete OIDC configuration at the end of test suite.
after(() => {
if (tenantAwareAuth) {
return tenantAwareAuth.deleteProviderConfig(authProviderConfig.providerId)
.catch((error) => {
// Ignore error.
});
}
});
it('should support CRUD operations', () => {
return tenantAwareAuth.createProviderConfig(authProviderConfig)
.then((config) => {
assertDeepEqualUnordered(authProviderConfig, config);
return tenantAwareAuth.getProviderConfig(authProviderConfig.providerId);
})
.then((config) => {
assertDeepEqualUnordered(authProviderConfig, config);
return tenantAwareAuth.updateProviderConfig(
authProviderConfig.providerId, modifiedConfigOptions);
})
.then((config) => {
const modifiedConfig = deepExtend(
{providerId: authProviderConfig.providerId}, modifiedConfigOptions);
assertDeepEqualUnordered(modifiedConfig, config);
return tenantAwareAuth.deleteProviderConfig(authProviderConfig.providerId);
})
.then(() => {
return tenantAwareAuth.getProviderConfig(authProviderConfig.providerId)
.should.eventually.be.rejected.and.have.property('code', 'auth/configuration-not-found');
});
});
});
it('getTenant() should resolve with expected tenant', () => {
return admin.auth().tenantManager().getTenant(createdTenantId)
.then((actualTenant) => {
expect(actualTenant.toJSON()).to.deep.equal(expectedCreatedTenant);
});
});
it('updateTenant() should resolve with the updated tenant', () => {
expectedUpdatedTenant.tenantId = createdTenantId;
expectedUpdatedTenant2.tenantId = createdTenantId;
const updatedOptions: admin.auth.UpdateTenantRequest = {
displayName: expectedUpdatedTenant.displayName,
emailSignInConfig: {
enabled: false,
},
};
const updatedOptions2: admin.auth.UpdateTenantRequest = {
emailSignInConfig: {
enabled: true,
passwordRequired: false,
},
};
return admin.auth().tenantManager().updateTenant(createdTenantId, updatedOptions)
.then((actualTenant) => {
expect(actualTenant.toJSON()).to.deep.equal(expectedUpdatedTenant);
return admin.auth().tenantManager().updateTenant(createdTenantId, updatedOptions2);
})
.then((actualTenant) => {
expect(actualTenant.toJSON()).to.deep.equal(expectedUpdatedTenant2);
});
});
it('listTenants() should resolve with expected number of tenants', () => {
const allTenantIds: string[] = [];
const tenantOptions2 = deepCopy(tenantOptions);
tenantOptions2.displayName = 'testTenant2';
const listAllTenantIds = (tenantIds: string[], nextPageToken?: string): Promise<void> => {
return admin.auth().tenantManager().listTenants(100, nextPageToken)
.then((result) => {
result.tenants.forEach((tenant) => {
tenantIds.push(tenant.tenantId);
});
if (result.pageToken) {
return listAllTenantIds(tenantIds, result.pageToken);
}
});
};
return admin.auth().tenantManager().createTenant(tenantOptions2)
.then((actualTenant) => {
createdTenants.push(actualTenant.tenantId);
// Test listTenants returns the expected tenants.
return listAllTenantIds(allTenantIds);
})
.then(() => {
// All created tenants should be in the list of tenants.
createdTenants.forEach((tenantId) => {
expect(allTenantIds).to.contain(tenantId);
});
});
});
it('deleteTenant() should successfully delete the provided tenant', () => {
return admin.auth().tenantManager().deleteTenant(createdTenantId)
.then(() => {
return admin.auth().tenantManager().getTenant(createdTenantId);
})
.then((result) => {
throw new Error('unexpected success');
})
.catch((error) => {
expect(error.code).to.equal('auth/tenant-not-found');
});
});
});
describe('SAML configuration operations', () => {
const authProviderConfig1 = {
providerId: randomSamlProviderId(),
displayName: 'SAML_DISPLAY_NAME1',
enabled: true,
idpEntityId: 'IDP_ENTITY_ID1',
ssoURL: 'https://example.com/login1',
x509Certificates: [mocks.x509CertPairs[0].public],
rpEntityId: 'RP_ENTITY_ID1',
callbackURL: 'https://projectId.firebaseapp.com/__/auth/handler',
enableRequestSigning: true,
};
const authProviderConfig2 = {
providerId: randomSamlProviderId(),
displayName: 'SAML_DISPLAY_NAME2',
enabled: true,
idpEntityId: 'IDP_ENTITY_ID2',
ssoURL: 'https://example.com/login2',
x509Certificates: [mocks.x509CertPairs[1].public],
rpEntityId: 'RP_ENTITY_ID2',
callbackURL: 'https://projectId.firebaseapp.com/__/auth/handler',
enableRequestSigning: true,
};
const removeTempConfigs = () => {
return Promise.all([
admin.auth().deleteProviderConfig(authProviderConfig1.providerId).catch((error) => {/* empty */}),
admin.auth().deleteProviderConfig(authProviderConfig2.providerId).catch((error) => {/* empty */}),
]);
};
// Clean up temp configurations used for test.
before(() => {
return removeTempConfigs().then(() => admin.auth().createProviderConfig(authProviderConfig1));
});
after(() => {
return removeTempConfigs();
});
it('createProviderConfig() successfully creates a SAML config', () => {
return admin.auth().createProviderConfig(authProviderConfig2)
.then((config) => {
assertDeepEqualUnordered(authProviderConfig2, config);
});
});
it('getProviderConfig() successfully returns the expected SAML config', () => {
return admin.auth().getProviderConfig(authProviderConfig1.providerId)
.then((config) => {
assertDeepEqualUnordered(authProviderConfig1, config);
});
});
it('listProviderConfig() successfully returns the list of SAML providers', () => {
const configs: AuthProviderConfig[] = [];
const listProviders: any = (type: 'saml' | 'oidc', maxResults?: number, pageToken?: string) => {
return admin.auth().listProviderConfigs({type, maxResults, pageToken})
.then((result) => {
result.providerConfigs.forEach((config: AuthProviderConfig) => {
configs.push(config);
});
if (result.pageToken) {
return listProviders(type, maxResults, result.pageToken);
}
});
};
// In case the project already has existing providers, list all configurations and then
// check the 2 test configs are available.
return listProviders('saml', 1)
.then(() => {
let index1 = 0;
let index2 = 0;
for (let i = 0; i < configs.length; i++) {
if (configs[i].providerId === authProviderConfig1.providerId) {
index1 = i;
} else if (configs[i].providerId === authProviderConfig2.providerId) {
index2 = i;
}
}
assertDeepEqualUnordered(authProviderConfig1, configs[index1]);
assertDeepEqualUnordered(authProviderConfig2, configs[index2]);
});
});
it('updateProviderConfig() successfully overwrites a SAML config', () => {
const modifiedConfigOptions = {
displayName: 'SAML_DISPLAY_NAME3',
enabled: false,
idpEntityId: 'IDP_ENTITY_ID3',
ssoURL: 'https://example.com/login3',
x509Certificates: [mocks.x509CertPairs[1].public],
rpEntityId: 'RP_ENTITY_ID3',
callbackURL: 'https://projectId3.firebaseapp.com/__/auth/handler',
enableRequestSigning: false,
};
return admin.auth().updateProviderConfig(authProviderConfig1.providerId, modifiedConfigOptions)
.then((config) => {
const modifiedConfig = deepExtend(
{providerId: authProviderConfig1.providerId}, modifiedConfigOptions);
assertDeepEqualUnordered(modifiedConfig, config);
});
});
it('updateProviderConfig() successfully partially modifies a SAML config', () => {
const deltaChanges = {
displayName: 'SAML_DISPLAY_NAME4',
x509Certificates: [mocks.x509CertPairs[0].public],
// Note, currently backend has a bug where error is thrown when callbackURL is not
// passed event though it is not required. Fix is on the way.
callbackURL: 'https://projectId3.firebaseapp.com/__/auth/handler',
rpEntityId: 'RP_ENTITY_ID4',
};
// Only above fields should be modified.
const modifiedConfigOptions = {
displayName: 'SAML_DISPLAY_NAME4',
enabled: false,
idpEntityId: 'IDP_ENTITY_ID3',
ssoURL: 'https://example.com/login3',
x509Certificates: [mocks.x509CertPairs[0].public],
rpEntityId: 'RP_ENTITY_ID4',
callbackURL: 'https://projectId3.firebaseapp.com/__/auth/handler',
enableRequestSigning: false,