-
Notifications
You must be signed in to change notification settings - Fork 330
/
Copy pathtest_auth.py
524 lines (458 loc) · 20.6 KB
/
test_auth.py
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
# 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.
"""Integration tests for firebase_admin.auth module."""
import base64
import datetime
import random
import time
import uuid
import six
import pytest
import requests
import firebase_admin
from firebase_admin import auth
from firebase_admin import credentials
import google.oauth2.credentials
from google.auth import transport
_verify_token_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken'
_verify_password_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword'
_password_reset_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/resetPassword'
_verify_email_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/setAccountInfo'
_email_sign_in_url = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/emailLinkSignin'
ACTION_LINK_CONTINUE_URL = 'http://localhost?a=1&b=5#f=1'
def _sign_in(custom_token, api_key):
body = {'token' : custom_token.decode(), 'returnSecureToken' : True}
params = {'key' : api_key}
resp = requests.request('post', _verify_token_url, params=params, json=body)
resp.raise_for_status()
return resp.json().get('idToken')
def _sign_in_with_password(email, password, api_key):
body = {'email': email, 'password': password}
params = {'key' : api_key}
resp = requests.request('post', _verify_password_url, params=params, json=body)
resp.raise_for_status()
return resp.json().get('idToken')
def _random_id():
random_id = str(uuid.uuid4()).lower().replace('-', '')
email = 'test{0}@example.{1}.com'.format(random_id[:12], random_id[12:])
return random_id, email
def _random_phone():
return '+1' + ''.join([str(random.randint(0, 9)) for _ in range(0, 10)])
def _reset_password(oob_code, new_password, api_key):
body = {'oobCode': oob_code, 'newPassword': new_password}
params = {'key' : api_key}
resp = requests.request('post', _password_reset_url, params=params, json=body)
resp.raise_for_status()
return resp.json().get('email')
def _verify_email(oob_code, api_key):
body = {'oobCode': oob_code}
params = {'key' : api_key}
resp = requests.request('post', _verify_email_url, params=params, json=body)
resp.raise_for_status()
return resp.json().get('email')
def _sign_in_with_email_link(email, oob_code, api_key):
body = {'oobCode': oob_code, 'email': email}
params = {'key' : api_key}
resp = requests.request('post', _email_sign_in_url, params=params, json=body)
resp.raise_for_status()
return resp.json().get('idToken')
def _extract_link_params(link):
query = six.moves.urllib.parse.urlparse(link).query
query_dict = dict(six.moves.urllib.parse.parse_qsl(query))
return query_dict
def test_custom_token(api_key):
custom_token = auth.create_custom_token('user1')
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['uid'] == 'user1'
def test_custom_token_without_service_account(api_key):
google_cred = firebase_admin.get_app().credential.get_credential()
cred = CredentialWrapper.from_existing_credential(google_cred)
custom_app = firebase_admin.initialize_app(cred, {
'serviceAccountId': google_cred.service_account_email,
'projectId': firebase_admin.get_app().project_id
}, 'temp-app')
try:
custom_token = auth.create_custom_token('user1', app=custom_app)
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['uid'] == 'user1'
finally:
firebase_admin.delete_app(custom_app)
def test_custom_token_with_claims(api_key):
dev_claims = {'premium' : True, 'subscription' : 'silver'}
custom_token = auth.create_custom_token('user2', dev_claims)
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['uid'] == 'user2'
assert claims['premium'] is True
assert claims['subscription'] == 'silver'
def test_session_cookies(api_key):
dev_claims = {'premium' : True, 'subscription' : 'silver'}
custom_token = auth.create_custom_token('user3', dev_claims)
id_token = _sign_in(custom_token, api_key)
expires_in = datetime.timedelta(days=1)
session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in)
claims = auth.verify_session_cookie(session_cookie)
assert claims['uid'] == 'user3'
assert claims['premium'] is True
assert claims['subscription'] == 'silver'
assert claims['iss'].startswith('https://session.firebase.google.com')
estimated_exp = int(time.time() + expires_in.total_seconds())
assert abs(claims['exp'] - estimated_exp) < 5
def test_session_cookie_error():
expires_in = datetime.timedelta(days=1)
with pytest.raises(auth.InvalidIdTokenError):
auth.create_session_cookie('not.a.token', expires_in=expires_in)
def test_get_non_existing_user():
with pytest.raises(auth.UserNotFoundError) as excinfo:
auth.get_user('non.existing')
assert str(excinfo.value) == 'No user record found for the provided user ID: non.existing.'
def test_get_non_existing_user_by_email():
with pytest.raises(auth.UserNotFoundError) as excinfo:
auth.get_user_by_email('[email protected]')
error_msg = ('No user record found for the provided email: '
assert str(excinfo.value) == error_msg
def test_update_non_existing_user():
with pytest.raises(auth.UserNotFoundError):
auth.update_user('non.existing')
def test_delete_non_existing_user():
with pytest.raises(auth.UserNotFoundError):
auth.delete_user('non.existing')
@pytest.fixture
def new_user():
user = auth.create_user()
yield user
auth.delete_user(user.uid)
@pytest.fixture
def new_user_with_params():
random_id, email = _random_id()
phone = _random_phone()
user = auth.create_user(
uid=random_id,
email=email,
phone_number=phone,
display_name='Random User',
photo_url='https://example.com/photo.png',
email_verified=True,
password='secret',
)
yield user
auth.delete_user(user.uid)
@pytest.fixture
def new_user_list():
users = [
auth.create_user(password='password').uid,
auth.create_user(password='password').uid,
auth.create_user(password='password').uid,
]
yield users
for uid in users:
auth.delete_user(uid)
@pytest.fixture
def new_user_email_unverified():
random_id, email = _random_id()
user = auth.create_user(
uid=random_id,
email=email,
email_verified=False,
password='password'
)
yield user
auth.delete_user(user.uid)
def test_get_user(new_user_with_params):
user = auth.get_user(new_user_with_params.uid)
assert user.uid == new_user_with_params.uid
assert user.display_name == 'Random User'
assert user.email == new_user_with_params.email
assert user.phone_number == new_user_with_params.phone_number
assert user.photo_url == 'https://example.com/photo.png'
assert user.email_verified is True
assert user.disabled is False
user = auth.get_user_by_email(new_user_with_params.email)
assert user.uid == new_user_with_params.uid
user = auth.get_user_by_phone_number(new_user_with_params.phone_number)
assert user.uid == new_user_with_params.uid
assert len(user.provider_data) == 2
provider_ids = sorted([provider.provider_id for provider in user.provider_data])
assert provider_ids == ['password', 'phone']
def test_list_users(new_user_list):
err_msg_template = (
'Missing {field} field. A common cause would be forgetting to add the "Firebase ' +
'Authentication Admin" permission. See instructions in CONTRIBUTING.md')
fetched = []
# Test exporting all user accounts.
page = auth.list_users()
while page:
for user in page.users:
assert isinstance(user, auth.ExportedUserRecord)
if user.uid in new_user_list:
fetched.append(user.uid)
assert user.password_hash is not None, (
err_msg_template.format(field='password_hash'))
assert user.password_salt is not None, (
err_msg_template.format(field='password_salt'))
page = page.get_next_page()
assert len(fetched) == len(new_user_list)
fetched = []
page = auth.list_users()
for user in page.iterate_all():
assert isinstance(user, auth.ExportedUserRecord)
if user.uid in new_user_list:
fetched.append(user.uid)
assert user.password_hash is not None, (
err_msg_template.format(field='password_hash'))
assert user.password_salt is not None, (
err_msg_template.format(field='password_salt'))
assert len(fetched) == len(new_user_list)
def test_create_user(new_user):
user = auth.get_user(new_user.uid)
assert user.uid == new_user.uid
assert user.display_name is None
assert user.email is None
assert user.phone_number is None
assert user.photo_url is None
assert user.email_verified is False
assert user.disabled is False
assert user.custom_claims is None
assert user.user_metadata.creation_timestamp > 0
assert user.user_metadata.last_sign_in_timestamp is None
assert len(user.provider_data) is 0
with pytest.raises(auth.UidAlreadyExistsError):
auth.create_user(uid=new_user.uid)
def test_update_user(new_user):
_, email = _random_id()
phone = _random_phone()
user = auth.update_user(
new_user.uid,
email=email,
phone_number=phone,
display_name='Updated Name',
photo_url='https://example.com/photo.png',
email_verified=True,
password='secret')
assert user.uid == new_user.uid
assert user.display_name == 'Updated Name'
assert user.email == email
assert user.phone_number == phone
assert user.photo_url == 'https://example.com/photo.png'
assert user.email_verified is True
assert user.disabled is False
assert user.custom_claims is None
assert len(user.provider_data) == 2
user = auth.update_user(
new_user.uid,
link_provider=auth.UserProvider(
uid='test', provider_id='google.com', email='[email protected]',
display_name='Test Name', photo_url='https://test.com/user.png'))
assert user.uid == new_user.uid
assert len(user.provider_data) == 3
user = auth.update_user(
new_user.uid,
phone_number=auth.DELETE_ATTRIBUTE,
delete_provider_ids=['google.com'])
assert user.uid == new_user.uid
assert user.phone_number is None
assert len(user.provider_data) == 1
user = auth.update_user(
new_user.uid,
phone_number=phone)
assert user.uid == new_user.uid
assert user.phone_number == phone
assert len(user.provider_data) == 2
user = auth.update_user(
new_user.uid,
delete_provider_ids=['phone', 'google.com'])
assert user.uid == new_user.uid
assert user.phone_number is None
assert len(user.provider_data) == 1
def test_set_custom_user_claims(new_user, api_key):
claims = {'admin' : True, 'package' : 'gold'}
auth.set_custom_user_claims(new_user.uid, claims)
user = auth.get_user(new_user.uid)
assert user.custom_claims == claims
custom_token = auth.create_custom_token(new_user.uid)
id_token = _sign_in(custom_token, api_key)
dev_claims = auth.verify_id_token(id_token)
for key, value in claims.items():
assert dev_claims[key] == value
def test_update_custom_user_claims(new_user):
assert new_user.custom_claims is None
claims = {'admin' : True, 'package' : 'gold'}
auth.set_custom_user_claims(new_user.uid, claims)
user = auth.get_user(new_user.uid)
assert user.custom_claims == claims
claims = {'admin' : False, 'subscription' : 'guest'}
auth.set_custom_user_claims(new_user.uid, claims)
user = auth.get_user(new_user.uid)
assert user.custom_claims == claims
auth.set_custom_user_claims(new_user.uid, None)
user = auth.get_user(new_user.uid)
assert user.custom_claims is None
def test_disable_user(new_user_with_params):
user = auth.update_user(
new_user_with_params.uid,
display_name=auth.DELETE_ATTRIBUTE,
photo_url=auth.DELETE_ATTRIBUTE,
phone_number=auth.DELETE_ATTRIBUTE,
disabled=True)
assert user.uid == new_user_with_params.uid
assert user.email == new_user_with_params.email
assert user.display_name is None
assert user.phone_number is None
assert user.photo_url is None
assert user.email_verified is True
assert user.disabled is True
assert len(user.provider_data) == 1
def test_delete_user():
user = auth.create_user()
auth.delete_user(user.uid)
with pytest.raises(auth.UserNotFoundError):
auth.get_user(user.uid)
def test_revoke_refresh_tokens(new_user):
user = auth.get_user(new_user.uid)
old_valid_after = user.tokens_valid_after_timestamp
time.sleep(1)
auth.revoke_refresh_tokens(new_user.uid)
user = auth.get_user(new_user.uid)
new_valid_after = user.tokens_valid_after_timestamp
assert new_valid_after > old_valid_after
def test_verify_id_token_revoked(new_user, api_key):
custom_token = auth.create_custom_token(new_user.uid)
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token)
assert claims['iat'] * 1000 >= new_user.tokens_valid_after_timestamp
time.sleep(1)
auth.revoke_refresh_tokens(new_user.uid)
claims = auth.verify_id_token(id_token, check_revoked=False)
user = auth.get_user(new_user.uid)
# verify_id_token succeeded because it didn't check revoked.
assert claims['iat'] * 1000 < user.tokens_valid_after_timestamp
with pytest.raises(auth.RevokedIdTokenError) as excinfo:
claims = auth.verify_id_token(id_token, check_revoked=True)
assert str(excinfo.value) == 'The Firebase ID token has been revoked.'
# Sign in again, verify works.
id_token = _sign_in(custom_token, api_key)
claims = auth.verify_id_token(id_token, check_revoked=True)
assert claims['iat'] * 1000 >= user.tokens_valid_after_timestamp
def test_verify_session_cookie_revoked(new_user, api_key):
custom_token = auth.create_custom_token(new_user.uid)
id_token = _sign_in(custom_token, api_key)
session_cookie = auth.create_session_cookie(id_token, expires_in=datetime.timedelta(days=1))
time.sleep(1)
auth.revoke_refresh_tokens(new_user.uid)
claims = auth.verify_session_cookie(session_cookie, check_revoked=False)
user = auth.get_user(new_user.uid)
# verify_session_cookie succeeded because it didn't check revoked.
assert claims['iat'] * 1000 < user.tokens_valid_after_timestamp
with pytest.raises(auth.RevokedSessionCookieError) as excinfo:
claims = auth.verify_session_cookie(session_cookie, check_revoked=True)
assert str(excinfo.value) == 'The Firebase session cookie has been revoked.'
# Sign in again, verify works.
id_token = _sign_in(custom_token, api_key)
session_cookie = auth.create_session_cookie(id_token, expires_in=datetime.timedelta(days=1))
claims = auth.verify_session_cookie(session_cookie, check_revoked=True)
assert claims['iat'] * 1000 >= user.tokens_valid_after_timestamp
def test_import_users():
uid, email = _random_id()
user = auth.ImportUserRecord(uid=uid, email=email)
result = auth.import_users([user])
try:
assert result.success_count == 1
assert result.failure_count == 0
saved_user = auth.get_user(uid)
assert saved_user.email == email
finally:
auth.delete_user(uid)
def test_import_users_with_password(api_key):
uid, email = _random_id()
password_hash = base64.b64decode(
'V358E8LdWJXAO7muq0CufVpEOXaj8aFiC7T/rcaGieN04q/ZPJ08WhJEHGjj9lz/2TT+/86N5VjVoc5DdBhBiw==')
user = auth.ImportUserRecord(
uid=uid, email=email, password_hash=password_hash, password_salt=b'NaCl')
scrypt_key = base64.b64decode(
'jxspr8Ki0RYycVU8zykbdLGjFQ3McFUH0uiiTvC8pVMXAn210wjLNmdZJzxUECKbm0QsEmYUSDzZvpjeJ9WmXA==')
salt_separator = base64.b64decode('Bw==')
scrypt = auth.UserImportHash.scrypt(
key=scrypt_key, salt_separator=salt_separator, rounds=8, memory_cost=14)
result = auth.import_users([user], hash_alg=scrypt)
try:
assert result.success_count == 1
assert result.failure_count == 0
saved_user = auth.get_user(uid)
assert saved_user.email == email
id_token = _sign_in_with_password(email, 'password', api_key)
assert len(id_token) > 0
finally:
auth.delete_user(uid)
def test_password_reset(new_user_email_unverified, api_key):
link = auth.generate_password_reset_link(new_user_email_unverified.email)
assert isinstance(link, six.string_types)
query_dict = _extract_link_params(link)
user_email = _reset_password(query_dict['oobCode'], 'newPassword', api_key)
assert new_user_email_unverified.email == user_email
# password reset also set email_verified to True
assert auth.get_user(new_user_email_unverified.uid).email_verified
def test_email_verification(new_user_email_unverified, api_key):
link = auth.generate_email_verification_link(new_user_email_unverified.email)
assert isinstance(link, six.string_types)
query_dict = _extract_link_params(link)
user_email = _verify_email(query_dict['oobCode'], api_key)
assert new_user_email_unverified.email == user_email
assert auth.get_user(new_user_email_unverified.uid).email_verified
def test_password_reset_with_settings(new_user_email_unverified, api_key):
action_code_settings = auth.ActionCodeSettings(ACTION_LINK_CONTINUE_URL)
link = auth.generate_password_reset_link(new_user_email_unverified.email,
action_code_settings=action_code_settings)
assert isinstance(link, six.string_types)
query_dict = _extract_link_params(link)
assert query_dict['continueUrl'] == ACTION_LINK_CONTINUE_URL
user_email = _reset_password(query_dict['oobCode'], 'newPassword', api_key)
assert new_user_email_unverified.email == user_email
# password reset also set email_verified to True
assert auth.get_user(new_user_email_unverified.uid).email_verified
def test_email_verification_with_settings(new_user_email_unverified, api_key):
action_code_settings = auth.ActionCodeSettings(ACTION_LINK_CONTINUE_URL)
link = auth.generate_email_verification_link(new_user_email_unverified.email,
action_code_settings=action_code_settings)
assert isinstance(link, six.string_types)
query_dict = _extract_link_params(link)
assert query_dict['continueUrl'] == ACTION_LINK_CONTINUE_URL
user_email = _verify_email(query_dict['oobCode'], api_key)
assert new_user_email_unverified.email == user_email
assert auth.get_user(new_user_email_unverified.uid).email_verified
def test_email_sign_in_with_settings(new_user_email_unverified, api_key):
action_code_settings = auth.ActionCodeSettings(ACTION_LINK_CONTINUE_URL)
link = auth.generate_sign_in_with_email_link(new_user_email_unverified.email,
action_code_settings=action_code_settings)
assert isinstance(link, six.string_types)
query_dict = _extract_link_params(link)
assert query_dict['continueUrl'] == ACTION_LINK_CONTINUE_URL
oob_code = query_dict['oobCode']
id_token = _sign_in_with_email_link(new_user_email_unverified.email, oob_code, api_key)
assert id_token is not None and len(id_token) > 0
assert auth.get_user(new_user_email_unverified.uid).email_verified
class CredentialWrapper(credentials.Base):
"""A custom Firebase credential that wraps an OAuth2 token."""
def __init__(self, token):
self._delegate = google.oauth2.credentials.Credentials(token)
def get_credential(self):
return self._delegate
@classmethod
def from_existing_credential(cls, google_cred):
if not google_cred.token:
request = transport.requests.Request()
google_cred.refresh(request)
return CredentialWrapper(google_cred.token)