Jon Wayne Parrott | 5824ad8 | 2016-10-06 09:27:44 -0700 | [diff] [blame] | 1 | # Copyright 2014 Google Inc. |
| 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 base64 |
| 16 | import datetime |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 17 | import json |
Jon Wayne Parrott | 5824ad8 | 2016-10-06 09:27:44 -0700 | [diff] [blame] | 18 | import os |
| 19 | |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 20 | import mock |
Jon Wayne Parrott | 5824ad8 | 2016-10-06 09:27:44 -0700 | [diff] [blame] | 21 | import pytest |
| 22 | |
| 23 | from google.auth import _helpers |
| 24 | from google.auth import crypt |
| 25 | from google.auth import jwt |
| 26 | |
| 27 | |
| 28 | DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') |
| 29 | |
| 30 | with open(os.path.join(DATA_DIR, 'privatekey.pem'), 'rb') as fh: |
| 31 | PRIVATE_KEY_BYTES = fh.read() |
| 32 | |
| 33 | with open(os.path.join(DATA_DIR, 'public_cert.pem'), 'rb') as fh: |
| 34 | PUBLIC_CERT_BYTES = fh.read() |
| 35 | |
| 36 | with open(os.path.join(DATA_DIR, 'other_cert.pem'), 'rb') as fh: |
| 37 | OTHER_CERT_BYTES = fh.read() |
| 38 | |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 39 | SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, 'service_account.json') |
| 40 | |
| 41 | with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh: |
| 42 | SERVICE_ACCOUNT_INFO = json.load(fh) |
| 43 | |
Jon Wayne Parrott | 5824ad8 | 2016-10-06 09:27:44 -0700 | [diff] [blame] | 44 | |
| 45 | @pytest.fixture |
| 46 | def signer(): |
Jon Wayne Parrott | 254befe | 2017-02-22 14:37:31 -0800 | [diff] [blame] | 47 | return crypt.RSASigner.from_string(PRIVATE_KEY_BYTES, '1') |
Jon Wayne Parrott | 5824ad8 | 2016-10-06 09:27:44 -0700 | [diff] [blame] | 48 | |
| 49 | |
| 50 | def test_encode_basic(signer): |
| 51 | test_payload = {'test': 'value'} |
| 52 | encoded = jwt.encode(signer, test_payload) |
| 53 | header, payload, _, _ = jwt._unverified_decode(encoded) |
| 54 | assert payload == test_payload |
| 55 | assert header == {'typ': 'JWT', 'alg': 'RS256', 'kid': signer.key_id} |
| 56 | |
| 57 | |
| 58 | def test_encode_extra_headers(signer): |
| 59 | encoded = jwt.encode(signer, {}, header={'extra': 'value'}) |
| 60 | header = jwt.decode_header(encoded) |
| 61 | assert header == { |
| 62 | 'typ': 'JWT', 'alg': 'RS256', 'kid': signer.key_id, 'extra': 'value'} |
| 63 | |
| 64 | |
| 65 | @pytest.fixture |
| 66 | def token_factory(signer): |
| 67 | def factory(claims=None, key_id=None): |
| 68 | now = _helpers.datetime_to_secs(_helpers.utcnow()) |
| 69 | payload = { |
| 70 | 'aud': 'audience@example.com', |
| 71 | 'iat': now, |
| 72 | 'exp': now + 300, |
| 73 | 'user': 'billy bob', |
| 74 | 'metadata': {'meta': 'data'} |
| 75 | } |
| 76 | payload.update(claims or {}) |
| 77 | |
| 78 | # False is specified to remove the signer's key id for testing |
| 79 | # headers without key ids. |
| 80 | if key_id is False: |
Jon Wayne Parrott | 254befe | 2017-02-22 14:37:31 -0800 | [diff] [blame] | 81 | signer._key_id = None |
Jon Wayne Parrott | 5824ad8 | 2016-10-06 09:27:44 -0700 | [diff] [blame] | 82 | key_id = None |
| 83 | |
| 84 | return jwt.encode(signer, payload, key_id=key_id) |
| 85 | return factory |
| 86 | |
| 87 | |
| 88 | def test_decode_valid(token_factory): |
| 89 | payload = jwt.decode(token_factory(), certs=PUBLIC_CERT_BYTES) |
| 90 | assert payload['aud'] == 'audience@example.com' |
| 91 | assert payload['user'] == 'billy bob' |
| 92 | assert payload['metadata']['meta'] == 'data' |
| 93 | |
| 94 | |
| 95 | def test_decode_valid_with_audience(token_factory): |
| 96 | payload = jwt.decode( |
| 97 | token_factory(), certs=PUBLIC_CERT_BYTES, |
| 98 | audience='audience@example.com') |
| 99 | assert payload['aud'] == 'audience@example.com' |
| 100 | assert payload['user'] == 'billy bob' |
| 101 | assert payload['metadata']['meta'] == 'data' |
| 102 | |
| 103 | |
| 104 | def test_decode_valid_unverified(token_factory): |
| 105 | payload = jwt.decode(token_factory(), certs=OTHER_CERT_BYTES, verify=False) |
| 106 | assert payload['aud'] == 'audience@example.com' |
| 107 | assert payload['user'] == 'billy bob' |
| 108 | assert payload['metadata']['meta'] == 'data' |
| 109 | |
| 110 | |
| 111 | def test_decode_bad_token_wrong_number_of_segments(): |
| 112 | with pytest.raises(ValueError) as excinfo: |
| 113 | jwt.decode('1.2', PUBLIC_CERT_BYTES) |
| 114 | assert excinfo.match(r'Wrong number of segments') |
| 115 | |
| 116 | |
| 117 | def test_decode_bad_token_not_base64(): |
| 118 | with pytest.raises((ValueError, TypeError)) as excinfo: |
| 119 | jwt.decode('1.2.3', PUBLIC_CERT_BYTES) |
| 120 | assert excinfo.match(r'Incorrect padding') |
| 121 | |
| 122 | |
| 123 | def test_decode_bad_token_not_json(): |
| 124 | token = b'.'.join([base64.urlsafe_b64encode(b'123!')] * 3) |
| 125 | with pytest.raises(ValueError) as excinfo: |
| 126 | jwt.decode(token, PUBLIC_CERT_BYTES) |
| 127 | assert excinfo.match(r'Can\'t parse segment') |
| 128 | |
| 129 | |
| 130 | def test_decode_bad_token_no_iat_or_exp(signer): |
| 131 | token = jwt.encode(signer, {'test': 'value'}) |
| 132 | with pytest.raises(ValueError) as excinfo: |
| 133 | jwt.decode(token, PUBLIC_CERT_BYTES) |
| 134 | assert excinfo.match(r'Token does not contain required claim') |
| 135 | |
| 136 | |
| 137 | def test_decode_bad_token_too_early(token_factory): |
| 138 | token = token_factory(claims={ |
| 139 | 'iat': _helpers.datetime_to_secs( |
| 140 | _helpers.utcnow() + datetime.timedelta(hours=1)) |
| 141 | }) |
| 142 | with pytest.raises(ValueError) as excinfo: |
| 143 | jwt.decode(token, PUBLIC_CERT_BYTES) |
| 144 | assert excinfo.match(r'Token used too early') |
| 145 | |
| 146 | |
| 147 | def test_decode_bad_token_expired(token_factory): |
| 148 | token = token_factory(claims={ |
| 149 | 'exp': _helpers.datetime_to_secs( |
| 150 | _helpers.utcnow() - datetime.timedelta(hours=1)) |
| 151 | }) |
| 152 | with pytest.raises(ValueError) as excinfo: |
| 153 | jwt.decode(token, PUBLIC_CERT_BYTES) |
| 154 | assert excinfo.match(r'Token expired') |
| 155 | |
| 156 | |
| 157 | def test_decode_bad_token_wrong_audience(token_factory): |
| 158 | token = token_factory() |
| 159 | audience = 'audience2@example.com' |
| 160 | with pytest.raises(ValueError) as excinfo: |
| 161 | jwt.decode(token, PUBLIC_CERT_BYTES, audience=audience) |
| 162 | assert excinfo.match(r'Token has wrong audience') |
| 163 | |
| 164 | |
| 165 | def test_decode_wrong_cert(token_factory): |
| 166 | with pytest.raises(ValueError) as excinfo: |
| 167 | jwt.decode(token_factory(), OTHER_CERT_BYTES) |
| 168 | assert excinfo.match(r'Could not verify token signature') |
| 169 | |
| 170 | |
| 171 | def test_decode_multicert_bad_cert(token_factory): |
| 172 | certs = {'1': OTHER_CERT_BYTES, '2': PUBLIC_CERT_BYTES} |
| 173 | with pytest.raises(ValueError) as excinfo: |
| 174 | jwt.decode(token_factory(), certs) |
| 175 | assert excinfo.match(r'Could not verify token signature') |
| 176 | |
| 177 | |
| 178 | def test_decode_no_cert(token_factory): |
| 179 | certs = {'2': PUBLIC_CERT_BYTES} |
| 180 | with pytest.raises(ValueError) as excinfo: |
| 181 | jwt.decode(token_factory(), certs) |
| 182 | assert excinfo.match(r'Certificate for key id 1 not found') |
| 183 | |
| 184 | |
| 185 | def test_decode_no_key_id(token_factory): |
| 186 | token = token_factory(key_id=False) |
| 187 | certs = {'2': PUBLIC_CERT_BYTES} |
| 188 | payload = jwt.decode(token, certs) |
| 189 | assert payload['user'] == 'billy bob' |
| 190 | |
| 191 | |
| 192 | def test_roundtrip_explicit_key_id(token_factory): |
| 193 | token = token_factory(key_id='3') |
| 194 | certs = {'2': OTHER_CERT_BYTES, '3': PUBLIC_CERT_BYTES} |
| 195 | payload = jwt.decode(token, certs) |
| 196 | assert payload['user'] == 'billy bob' |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 197 | |
| 198 | |
| 199 | class TestCredentials: |
| 200 | SERVICE_ACCOUNT_EMAIL = 'service-account@example.com' |
| 201 | SUBJECT = 'subject' |
| 202 | AUDIENCE = 'audience' |
| 203 | ADDITIONAL_CLAIMS = {'meta': 'data'} |
| 204 | credentials = None |
| 205 | |
| 206 | @pytest.fixture(autouse=True) |
| 207 | def credentials_fixture(self, signer): |
| 208 | self.credentials = jwt.Credentials( |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 209 | signer, self.SERVICE_ACCOUNT_EMAIL, self.SERVICE_ACCOUNT_EMAIL, |
| 210 | self.AUDIENCE) |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 211 | |
| 212 | def test_from_service_account_info(self): |
| 213 | with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh: |
| 214 | info = json.load(fh) |
| 215 | |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 216 | credentials = jwt.Credentials.from_service_account_info( |
| 217 | info, audience=self.AUDIENCE) |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 218 | |
| 219 | assert credentials._signer.key_id == info['private_key_id'] |
| 220 | assert credentials._issuer == info['client_email'] |
| 221 | assert credentials._subject == info['client_email'] |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 222 | assert credentials._audience == self.AUDIENCE |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 223 | |
| 224 | def test_from_service_account_info_args(self): |
| 225 | info = SERVICE_ACCOUNT_INFO.copy() |
| 226 | |
| 227 | credentials = jwt.Credentials.from_service_account_info( |
| 228 | info, subject=self.SUBJECT, audience=self.AUDIENCE, |
| 229 | additional_claims=self.ADDITIONAL_CLAIMS) |
| 230 | |
| 231 | assert credentials._signer.key_id == info['private_key_id'] |
| 232 | assert credentials._issuer == info['client_email'] |
| 233 | assert credentials._subject == self.SUBJECT |
| 234 | assert credentials._audience == self.AUDIENCE |
| 235 | assert credentials._additional_claims == self.ADDITIONAL_CLAIMS |
| 236 | |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 237 | def test_from_service_account_file(self): |
| 238 | info = SERVICE_ACCOUNT_INFO.copy() |
| 239 | |
| 240 | credentials = jwt.Credentials.from_service_account_file( |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 241 | SERVICE_ACCOUNT_JSON_FILE, audience=self.AUDIENCE) |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 242 | |
| 243 | assert credentials._signer.key_id == info['private_key_id'] |
| 244 | assert credentials._issuer == info['client_email'] |
| 245 | assert credentials._subject == info['client_email'] |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 246 | assert credentials._audience == self.AUDIENCE |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 247 | |
| 248 | def test_from_service_account_file_args(self): |
| 249 | info = SERVICE_ACCOUNT_INFO.copy() |
| 250 | |
| 251 | credentials = jwt.Credentials.from_service_account_file( |
| 252 | SERVICE_ACCOUNT_JSON_FILE, subject=self.SUBJECT, |
| 253 | audience=self.AUDIENCE, additional_claims=self.ADDITIONAL_CLAIMS) |
| 254 | |
| 255 | assert credentials._signer.key_id == info['private_key_id'] |
| 256 | assert credentials._issuer == info['client_email'] |
| 257 | assert credentials._subject == self.SUBJECT |
| 258 | assert credentials._audience == self.AUDIENCE |
| 259 | assert credentials._additional_claims == self.ADDITIONAL_CLAIMS |
| 260 | |
| 261 | def test_default_state(self): |
| 262 | assert not self.credentials.valid |
| 263 | # Expiration hasn't been set yet |
| 264 | assert not self.credentials.expired |
| 265 | |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 266 | def test_with_claims(self): |
| 267 | new_audience = 'new_audience' |
| 268 | new_credentials = self.credentials.with_claims( |
| 269 | audience=new_audience) |
| 270 | |
| 271 | assert new_credentials._signer == self.credentials._signer |
| 272 | assert new_credentials._issuer == self.credentials._issuer |
| 273 | assert new_credentials._subject == self.credentials._subject |
| 274 | assert new_credentials._audience == new_audience |
| 275 | assert (new_credentials._additional_claims == |
| 276 | self.credentials._additional_claims) |
| 277 | |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 278 | def test_sign_bytes(self): |
| 279 | to_sign = b'123' |
| 280 | signature = self.credentials.sign_bytes(to_sign) |
| 281 | assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES) |
| 282 | |
Jon Wayne Parrott | d722167 | 2017-02-16 09:05:11 -0800 | [diff] [blame] | 283 | def test_signer(self): |
Jon Wayne Parrott | 254befe | 2017-02-22 14:37:31 -0800 | [diff] [blame] | 284 | assert isinstance(self.credentials.signer, crypt.RSASigner) |
Jon Wayne Parrott | d722167 | 2017-02-16 09:05:11 -0800 | [diff] [blame] | 285 | |
Jon Wayne Parrott | 4c883f0 | 2016-12-02 14:26:33 -0800 | [diff] [blame] | 286 | def test_signer_email(self): |
| 287 | assert (self.credentials.signer_email == |
| 288 | SERVICE_ACCOUNT_INFO['client_email']) |
| 289 | |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 290 | def _verify_token(self, token): |
| 291 | payload = jwt.decode(token, PUBLIC_CERT_BYTES) |
| 292 | assert payload['iss'] == self.SERVICE_ACCOUNT_EMAIL |
| 293 | return payload |
| 294 | |
| 295 | def test_refresh(self): |
| 296 | self.credentials.refresh(None) |
| 297 | assert self.credentials.valid |
| 298 | assert not self.credentials.expired |
| 299 | |
| 300 | def test_expired(self): |
| 301 | assert not self.credentials.expired |
| 302 | |
| 303 | self.credentials.refresh(None) |
| 304 | assert not self.credentials.expired |
| 305 | |
| 306 | with mock.patch('google.auth._helpers.utcnow') as now: |
| 307 | one_day = datetime.timedelta(days=1) |
| 308 | now.return_value = self.credentials.expiry + one_day |
| 309 | assert self.credentials.expired |
| 310 | |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 311 | def test_before_request(self): |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 312 | headers = {} |
| 313 | |
| 314 | self.credentials.refresh(None) |
| 315 | self.credentials.before_request( |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 316 | None, 'GET', 'http://example.com?a=1#3', headers) |
| 317 | |
| 318 | header_value = headers['authorization'] |
| 319 | _, token = header_value.split(' ') |
| 320 | |
| 321 | # Since the audience is set, it should use the existing token. |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 322 | assert token.encode('utf-8') == self.credentials.token |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 323 | |
| 324 | payload = self._verify_token(token) |
| 325 | assert payload['aud'] == self.AUDIENCE |
| 326 | |
| 327 | def test_before_request_refreshes(self): |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 328 | assert not self.credentials.valid |
| 329 | self.credentials.before_request( |
Jon Wayne Parrott | abcd3ed | 2016-10-17 11:23:47 -0700 | [diff] [blame] | 330 | None, 'GET', 'http://example.com?a=1#3', {}) |
Jon Wayne Parrott | ab08689 | 2017-02-23 09:20:14 -0800 | [diff] [blame^] | 331 | assert self.credentials.valid |