|
| 1 | +# Copyright 2016 Google Inc. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import datetime |
| 16 | +import os |
| 17 | +import time |
| 18 | + |
| 19 | +# Remove any existing pyjwt handlers, as firebase_helper will register |
| 20 | +# its own. |
| 21 | +try: |
| 22 | + import jwt |
| 23 | + jwt.unregister_algorithm('RS256') |
| 24 | +except KeyError: |
| 25 | + pass |
| 26 | + |
| 27 | +import mock |
| 28 | +import pytest |
| 29 | + |
| 30 | +import firebase_helper |
| 31 | + |
| 32 | + |
| 33 | +def test_get_firebase_certificates(testbed): |
| 34 | + certs = firebase_helper.get_firebase_certificates() |
| 35 | + assert certs |
| 36 | + assert len(certs.keys()) |
| 37 | + |
| 38 | + |
| 39 | +@pytest.fixture |
| 40 | +def test_certificate(): |
| 41 | + from cryptography import utils |
| 42 | + from cryptography import x509 |
| 43 | + from cryptography.hazmat.backends import default_backend |
| 44 | + from cryptography.hazmat.primitives import hashes |
| 45 | + from cryptography.hazmat.primitives.asymmetric import rsa |
| 46 | + from cryptography.hazmat.primitives import serialization |
| 47 | + from cryptography.x509.oid import NameOID |
| 48 | + |
| 49 | + one_day = datetime.timedelta(1, 0, 0) |
| 50 | + private_key = rsa.generate_private_key( |
| 51 | + public_exponent=65537, |
| 52 | + key_size=2048, |
| 53 | + backend=default_backend()) |
| 54 | + public_key = private_key.public_key() |
| 55 | + builder = x509.CertificateBuilder() |
| 56 | + |
| 57 | + builder = builder.subject_name(x509.Name([ |
| 58 | + x509.NameAttribute(NameOID.COMMON_NAME, u'example.com'), |
| 59 | + ])) |
| 60 | + builder = builder.issuer_name(x509.Name([ |
| 61 | + x509.NameAttribute(NameOID.COMMON_NAME, u'example.com'), |
| 62 | + ])) |
| 63 | + builder = builder.not_valid_before(datetime.datetime.today() - one_day) |
| 64 | + builder = builder.not_valid_after(datetime.datetime.today() + one_day) |
| 65 | + builder = builder.serial_number( |
| 66 | + utils.int_from_bytes(os.urandom(20), "big") >> 1) |
| 67 | + builder = builder.public_key(public_key) |
| 68 | + |
| 69 | + builder = builder.add_extension( |
| 70 | + x509.BasicConstraints(ca=False, path_length=None), critical=True) |
| 71 | + |
| 72 | + certificate = builder.sign( |
| 73 | + private_key=private_key, algorithm=hashes.SHA256(), |
| 74 | + backend=default_backend()) |
| 75 | + |
| 76 | + certificate_pem = certificate.public_bytes(serialization.Encoding.PEM) |
| 77 | + public_key_bytes = certificate.public_key().public_bytes( |
| 78 | + serialization.Encoding.DER, |
| 79 | + serialization.PublicFormat.SubjectPublicKeyInfo) |
| 80 | + private_key_bytes = private_key.private_bytes( |
| 81 | + encoding=serialization.Encoding.PEM, |
| 82 | + format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 83 | + encryption_algorithm=serialization.NoEncryption()) |
| 84 | + |
| 85 | + yield certificate, certificate_pem, public_key_bytes, private_key_bytes |
| 86 | + |
| 87 | + |
| 88 | +def test_extract_public_key_from_certificate(test_certificate): |
| 89 | + _, certificate_pem, public_key_bytes, _ = test_certificate |
| 90 | + public_key = firebase_helper.extract_public_key_from_certificate( |
| 91 | + certificate_pem) |
| 92 | + assert public_key == public_key_bytes |
| 93 | + |
| 94 | + |
| 95 | +def make_jwt(private_key_bytes, claims=None, headers=None): |
| 96 | + jwt_claims = { |
| 97 | + 'iss': 'http://example.com', |
| 98 | + 'aud': 'test_audience', |
| 99 | + 'user_id': '123', |
| 100 | + 'sub': '123', |
| 101 | + 'iat': int(time.time()), |
| 102 | + 'exp': int(time.time()) + 60, |
| 103 | + |
| 104 | + } |
| 105 | + |
| 106 | + jwt_claims.update(claims if claims else {}) |
| 107 | + if not headers: |
| 108 | + headers = {} |
| 109 | + |
| 110 | + return jwt.encode( |
| 111 | + jwt_claims, private_key_bytes, algorithm='RS256', |
| 112 | + headers=headers) |
| 113 | + |
| 114 | + |
| 115 | +def test_verify_auth_token(test_certificate, monkeypatch): |
| 116 | + _, certificate_pem, _, private_key_bytes = test_certificate |
| 117 | + |
| 118 | + # The Firebase project ID is used as the JWT audience. |
| 119 | + monkeypatch.setenv('FIREBASE_PROJECT_ID', 'test_audience') |
| 120 | + |
| 121 | + # Generate a jwt to include in the request. |
| 122 | + jwt = make_jwt(private_key_bytes, headers={'kid': '1'}) |
| 123 | + |
| 124 | + # Make a mock request |
| 125 | + request = mock.Mock() |
| 126 | + request.headers = {'Authorization': 'Bearer {}'.format(jwt)} |
| 127 | + |
| 128 | + get_cert_patch = mock.patch('firebase_helper.get_firebase_certificates') |
| 129 | + with get_cert_patch as get_cert_mock: |
| 130 | + # Make get_firebase_certificates return our test certificate. |
| 131 | + get_cert_mock.return_value = {'1': certificate_pem} |
| 132 | + claims = firebase_helper.verify_auth_token(request) |
| 133 | + |
| 134 | + assert claims['user_id'] == '123' |
| 135 | + |
| 136 | + |
| 137 | +def test_verify_auth_token_no_auth_header(): |
| 138 | + request = mock.Mock() |
| 139 | + request.headers = {} |
| 140 | + assert firebase_helper.verify_auth_token(request) is None |
| 141 | + |
| 142 | + |
| 143 | +def test_verify_auth_token_invalid_key_id(test_certificate): |
| 144 | + _, _, _, private_key_bytes = test_certificate |
| 145 | + jwt = make_jwt(private_key_bytes, headers={'kid': 'invalid'}) |
| 146 | + request = mock.Mock() |
| 147 | + request.headers = {'Authorization': 'Bearer {}'.format(jwt)} |
| 148 | + |
| 149 | + get_cert_patch = mock.patch('firebase_helper.get_firebase_certificates') |
| 150 | + with get_cert_patch as get_cert_mock: |
| 151 | + # Make get_firebase_certificates return no certificates |
| 152 | + get_cert_mock.return_value = {} |
| 153 | + assert firebase_helper.verify_auth_token(request) is None |
| 154 | + |
| 155 | + |
| 156 | +def test_verify_auth_token_expired(test_certificate, monkeypatch): |
| 157 | + _, certificate_pem, _, private_key_bytes = test_certificate |
| 158 | + |
| 159 | + # The Firebase project ID is used as the JWT audience. |
| 160 | + monkeypatch.setenv('FIREBASE_PROJECT_ID', 'test_audience') |
| 161 | + |
| 162 | + # Generate a jwt to include in the request. |
| 163 | + jwt = make_jwt( |
| 164 | + private_key_bytes, |
| 165 | + claims={'exp': int(time.time()) - 60}, |
| 166 | + headers={'kid': '1'}) |
| 167 | + |
| 168 | + # Make a mock request |
| 169 | + request = mock.Mock() |
| 170 | + request.headers = {'Authorization': 'Bearer {}'.format(jwt)} |
| 171 | + |
| 172 | + get_cert_patch = mock.patch('firebase_helper.get_firebase_certificates') |
| 173 | + with get_cert_patch as get_cert_mock: |
| 174 | + # Make get_firebase_certificates return our test certificate. |
| 175 | + get_cert_mock.return_value = {'1': certificate_pem} |
| 176 | + assert firebase_helper.verify_auth_token(request) is None |
0 commit comments