def test_get_token(self, init_app): mock_response = { 'access_token': 'mock_access_token_1', 'expires_in': 3600 } credentials._request = testutils.MockRequest(200, json.dumps(mock_response)) assert init_app._get_token() == 'mock_access_token_1' mock_response = { 'access_token': 'mock_access_token_2', 'expires_in': 3600 } credentials._request = testutils.MockRequest(200, json.dumps(mock_response)) expiry = init_app._token.expiry # should return same token from cache firebase_admin._clock = lambda: expiry - datetime.timedelta( seconds=firebase_admin._CLOCK_SKEW_SECONDS + 1) assert init_app._get_token() == 'mock_access_token_1' # should return new token from RPC call firebase_admin._clock = lambda: expiry - datetime.timedelta( seconds=firebase_admin._CLOCK_SKEW_SECONDS) assert init_app._get_token() == 'mock_access_token_2'
def test_sign_with_discovered_service_account(self): request = testutils.MockRequest(200, 'discovered-service-account') options = {'projectId': 'mock-project-id'} app = firebase_admin.initialize_app(testutils.MockCredential(), name='iam-signer-app', options=options) try: _overwrite_iam_request(app, request) # Force initialization of the signing provider. This will invoke the Metadata service. client = auth._get_client(app) assert client._token_generator.signing_provider is not None # Now invoke the IAM signer. signature = base64.b64encode(b'test').decode() request.response = testutils.MockResponse( 200, '{{"signature": "{0}"}}'.format(signature)) custom_token = auth.create_custom_token(MOCK_UID, app=app).decode() assert custom_token.endswith('.' + signature.rstrip('=')) self._verify_signer(custom_token, 'discovered-service-account') assert len(request.log) == 2 assert request.log[0][1]['headers'] == { 'Metadata-Flavor': 'Google' } finally: firebase_admin.delete_app(app)
def verify_custom_token(custom_token, expected_claims, tenant_id=None): assert isinstance(custom_token, bytes) expected_email = MOCK_SERVICE_ACCOUNT_EMAIL if _is_emulated(): expected_email = _token_gen.AUTH_EMULATOR_EMAIL token = jwt.decode(custom_token, verify=False) else: token = google.oauth2.id_token.verify_token( custom_token, testutils.MockRequest(200, MOCK_PUBLIC_CERTS), _token_gen.FIREBASE_AUDIENCE) assert token['uid'] == MOCK_UID assert token['iss'] == expected_email assert token['sub'] == expected_email if tenant_id is None: assert 'tenant_id' not in token else: assert token['tenant_id'] == tenant_id header = jwt.decode_header(custom_token) assert header.get('typ') == 'JWT' assert header.get('alg') == 'RS256' if expected_claims: for key, value in expected_claims.items(): assert value == token['claims'][key]
def test_certificate_request_failure(self, user_mgt_app): _overwrite_cert_request(user_mgt_app, testutils.MockRequest(404, 'not found')) with pytest.raises(auth.CertificateFetchError) as excinfo: auth.verify_session_cookie(TEST_SESSION_COOKIE, app=user_mgt_app) assert 'Could not fetch certificates' in str(excinfo.value) assert isinstance(excinfo.value, exceptions.UnknownError) assert excinfo.value.cause is not None assert excinfo.value.http_response is None
def test_certificate_request_failure(self, user_mgt_app): _overwrite_cert_request(user_mgt_app, testutils.MockRequest(404, 'not found')) if _is_emulated(): # Shouldn't fetch certificates in emulator mode. self._assert_valid_token(TEST_ID_TOKEN, app=user_mgt_app) return with pytest.raises(auth.CertificateFetchError) as excinfo: auth.verify_id_token(TEST_ID_TOKEN, app=user_mgt_app) assert 'Could not fetch certificates' in str(excinfo.value) assert isinstance(excinfo.value, exceptions.UnknownError) assert excinfo.value.cause is not None assert excinfo.value.http_response is None
def test_sign_with_iam_error(self): options = {'serviceAccountId': 'test-service-account', 'projectId': 'mock-project-id'} app = firebase_admin.initialize_app( testutils.MockCredential(), name='iam-signer-app', options=options) try: iam_resp = '{"error": {"code": 403, "message": "test error"}}' _overwrite_iam_request(app, testutils.MockRequest(403, iam_resp)) with pytest.raises(auth.AuthError) as excinfo: auth.create_custom_token(MOCK_UID, app=app) assert excinfo.value.code == _token_gen.TOKEN_SIGN_ERROR assert iam_resp in str(excinfo.value) finally: firebase_admin.delete_app(app)
def test_sign_with_iam(self): options = {'serviceAccountId': 'test-service-account', 'projectId': 'mock-project-id'} app = firebase_admin.initialize_app( testutils.MockCredential(), name='iam-signer-app', options=options) try: signature = base64.b64encode(b'test').decode() iam_resp = '{{"signature": "{0}"}}'.format(signature) _overwrite_iam_request(app, testutils.MockRequest(200, iam_resp)) custom_token = auth.create_custom_token(MOCK_UID, app=app).decode() assert custom_token.endswith('.' + signature.rstrip('=')) self._verify_signer(custom_token, 'test-service-account') finally: firebase_admin.delete_app(app)
def verify_custom_token(custom_token, expected_claims): assert isinstance(custom_token, six.binary_type) token = google.oauth2.id_token.verify_token( custom_token, testutils.MockRequest(200, MOCK_PUBLIC_CERTS), FIREBASE_AUDIENCE) assert token['uid'] == MOCK_UID assert token['iss'] == MOCK_SERVICE_ACCOUNT_EMAIL assert token['sub'] == MOCK_SERVICE_ACCOUNT_EMAIL header = jwt.decode_header(custom_token) assert header.get('typ') == 'JWT' assert header.get('alg') == 'RS256' if expected_claims: for key, value in expected_claims.items(): assert value == token['claims'][key]
def test_init(self, app_default): # pylint: disable=unused-argument credential = credentials.ApplicationDefault() assert credential.project_id == 'mock-project-id' g_credential = credential.get_credential() assert isinstance(g_credential, google.auth.credentials.Credentials) assert g_credential.token is None check_scopes(g_credential) mock_response = {'access_token': 'mock_access_token', 'expires_in': 3600} credentials._request = testutils.MockRequest(200, json.dumps(mock_response)) access_token = credential.get_access_token() assert access_token.access_token == 'mock_access_token' assert isinstance(access_token.expiry, datetime.datetime)
def _verify_credential(self, credential): assert credential.project_id == 'mock-project-id' assert credential.service_account_email == '*****@*****.**' assert isinstance(credential.signer, crypt.Signer) g_credential = credential.get_credential() assert isinstance(g_credential, service_account.Credentials) assert g_credential.token is None check_scopes(g_credential) mock_response = {'access_token': 'mock_access_token', 'expires_in': 3600} credentials._request = testutils.MockRequest(200, json.dumps(mock_response)) access_token = credential.get_access_token() assert access_token.access_token == 'mock_access_token' assert isinstance(access_token.expiry, datetime.datetime)
def test_sign_with_iam_error(self): options = {'serviceAccountId': 'test-service-account', 'projectId': 'mock-project-id'} app = firebase_admin.initialize_app( testutils.MockCredential(), name='iam-signer-app', options=options) try: iam_resp = '{"error": {"code": 403, "message": "test error"}}' _overwrite_iam_request(app, testutils.MockRequest(403, iam_resp)) with pytest.raises(auth.TokenSignError) as excinfo: auth.create_custom_token(MOCK_UID, app=app) error = excinfo.value assert error.code == exceptions.UNKNOWN assert iam_resp in str(error) assert isinstance(error.cause, google.auth.exceptions.TransportError) finally: firebase_admin.delete_app(app)
def _verify_credential(self, credential): assert credential.client_id == 'mock.apps.googleusercontent.com' assert credential.client_secret == 'mock-secret' assert credential.refresh_token == 'mock-refresh-token' g_credential = credential.get_credential() assert isinstance(g_credential, gcredentials.Credentials) assert g_credential.token is None check_scopes(g_credential) mock_response = { 'access_token': 'mock_access_token', 'expires_in': 3600 } credentials._request = testutils.MockRequest(200, json.dumps(mock_response)) access_token = credential.get_access_token() assert access_token.access_token == 'mock_access_token' assert isinstance(access_token.expiry, datetime.datetime)
def test_certificate_request_failure(self, user_mgt_app): _overwrite_cert_request(user_mgt_app, testutils.MockRequest(404, 'not found')) with pytest.raises(exceptions.TransportError): auth.verify_session_cookie(TEST_SESSION_COOKIE, app=user_mgt_app)
def test_certificate_request_failure(self, user_mgt_app): _overwrite_cert_request(user_mgt_app, testutils.MockRequest(404, 'not found')) with pytest.raises(exceptions.TransportError): auth.verify_id_token(TEST_ID_TOKEN, app=user_mgt_app)
def setup_method(self): auth._request = testutils.MockRequest(200, MOCK_PUBLIC_CERTS)
def test_certificate_request_failure(self, authtest): auth._request = testutils.MockRequest(404, 'not found') with pytest.raises(exceptions.TransportError): authtest.verify_id_token(TEST_ID_TOKEN)
from pytest_localserver import plugin import six import firebase_admin from firebase_admin import auth from firebase_admin import credentials from firebase_admin import _token_gen from tests import testutils MOCK_UID = 'user1' MOCK_CREDENTIAL = credentials.Certificate( testutils.resource_filename('service_account.json')) MOCK_PUBLIC_CERTS = testutils.resource('public_certs.json') MOCK_PRIVATE_KEY = testutils.resource('private_key.pem') MOCK_SERVICE_ACCOUNT_EMAIL = MOCK_CREDENTIAL.service_account_email MOCK_REQUEST = testutils.MockRequest(200, MOCK_PUBLIC_CERTS) INVALID_STRINGS = [None, '', 0, 1, True, False, list(), tuple(), dict()] INVALID_BOOLS = [None, '', 'foo', 0, 1, list(), tuple(), dict()] # Fixture for mocking a HTTP server httpserver = plugin.httpserver def _merge_jwt_claims(defaults, overrides): defaults.update(overrides) for key, value in overrides.items(): if value is None: del defaults[key] return defaults