blob: 2a4795acc5bdc06600596e325b2c6e549398ce78 [file] [log] [blame]
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -07001# 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
15import base64
16import datetime
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -070017import json
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070018import os
19
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -070020import mock
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070021import pytest
22
23from google.auth import _helpers
24from google.auth import crypt
25from google.auth import jwt
26
27
28DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
29
30with open(os.path.join(DATA_DIR, 'privatekey.pem'), 'rb') as fh:
31 PRIVATE_KEY_BYTES = fh.read()
32
33with open(os.path.join(DATA_DIR, 'public_cert.pem'), 'rb') as fh:
34 PUBLIC_CERT_BYTES = fh.read()
35
36with open(os.path.join(DATA_DIR, 'other_cert.pem'), 'rb') as fh:
37 OTHER_CERT_BYTES = fh.read()
38
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -070039SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, 'service_account.json')
40
41with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh:
42 SERVICE_ACCOUNT_INFO = json.load(fh)
43
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070044
45@pytest.fixture
46def signer():
47 return crypt.Signer.from_string(PRIVATE_KEY_BYTES, '1')
48
49
50def 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
58def 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
66def 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:
81 signer.key_id = None
82 key_id = None
83
84 return jwt.encode(signer, payload, key_id=key_id)
85 return factory
86
87
88def 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
95def 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
104def 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
111def 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
117def 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
123def 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
130def 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
137def 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
147def 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
157def 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
165def 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
171def 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
178def 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
185def 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
192def 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 Parrottabcd3ed2016-10-17 11:23:47 -0700197
198
199class 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(
209 signer, self.SERVICE_ACCOUNT_EMAIL)
210
211 def test_from_service_account_info(self):
212 with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh:
213 info = json.load(fh)
214
215 credentials = jwt.Credentials.from_service_account_info(info)
216
217 assert credentials._signer.key_id == info['private_key_id']
218 assert credentials._issuer == info['client_email']
219 assert credentials._subject == info['client_email']
220
221 def test_from_service_account_info_args(self):
222 info = SERVICE_ACCOUNT_INFO.copy()
223
224 credentials = jwt.Credentials.from_service_account_info(
225 info, subject=self.SUBJECT, audience=self.AUDIENCE,
226 additional_claims=self.ADDITIONAL_CLAIMS)
227
228 assert credentials._signer.key_id == info['private_key_id']
229 assert credentials._issuer == info['client_email']
230 assert credentials._subject == self.SUBJECT
231 assert credentials._audience == self.AUDIENCE
232 assert credentials._additional_claims == self.ADDITIONAL_CLAIMS
233
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700234 def test_from_service_account_file(self):
235 info = SERVICE_ACCOUNT_INFO.copy()
236
237 credentials = jwt.Credentials.from_service_account_file(
238 SERVICE_ACCOUNT_JSON_FILE)
239
240 assert credentials._signer.key_id == info['private_key_id']
241 assert credentials._issuer == info['client_email']
242 assert credentials._subject == info['client_email']
243
244 def test_from_service_account_file_args(self):
245 info = SERVICE_ACCOUNT_INFO.copy()
246
247 credentials = jwt.Credentials.from_service_account_file(
248 SERVICE_ACCOUNT_JSON_FILE, subject=self.SUBJECT,
249 audience=self.AUDIENCE, additional_claims=self.ADDITIONAL_CLAIMS)
250
251 assert credentials._signer.key_id == info['private_key_id']
252 assert credentials._issuer == info['client_email']
253 assert credentials._subject == self.SUBJECT
254 assert credentials._audience == self.AUDIENCE
255 assert credentials._additional_claims == self.ADDITIONAL_CLAIMS
256
257 def test_default_state(self):
258 assert not self.credentials.valid
259 # Expiration hasn't been set yet
260 assert not self.credentials.expired
261
262 def test_sign_bytes(self):
263 to_sign = b'123'
264 signature = self.credentials.sign_bytes(to_sign)
265 assert crypt.verify_signature(to_sign, signature, PUBLIC_CERT_BYTES)
266
267 def _verify_token(self, token):
268 payload = jwt.decode(token, PUBLIC_CERT_BYTES)
269 assert payload['iss'] == self.SERVICE_ACCOUNT_EMAIL
270 return payload
271
272 def test_refresh(self):
273 self.credentials.refresh(None)
274 assert self.credentials.valid
275 assert not self.credentials.expired
276
277 def test_expired(self):
278 assert not self.credentials.expired
279
280 self.credentials.refresh(None)
281 assert not self.credentials.expired
282
283 with mock.patch('google.auth._helpers.utcnow') as now:
284 one_day = datetime.timedelta(days=1)
285 now.return_value = self.credentials.expiry + one_day
286 assert self.credentials.expired
287
288 def test_before_request_one_time_token(self):
289 headers = {}
290
291 self.credentials.refresh(None)
292 self.credentials.before_request(
293 mock.Mock(), 'GET', 'http://example.com?a=1#3', headers)
294
295 header_value = headers['authorization']
296 _, token = header_value.split(' ')
297
298 # This should be a one-off token, so it shouldn't be the same as the
299 # credentials' stored token.
300 assert token != self.credentials.token
301
302 payload = self._verify_token(token)
303 assert payload['aud'] == 'http://example.com'
304
305 def test_before_request_with_preset_audience(self):
306 headers = {}
307
308 credentials = self.credentials.with_claims(audience=self.AUDIENCE)
309 credentials.refresh(None)
310 credentials.before_request(
311 None, 'GET', 'http://example.com?a=1#3', headers)
312
313 header_value = headers['authorization']
314 _, token = header_value.split(' ')
315
316 # Since the audience is set, it should use the existing token.
317 assert token.encode('utf-8') == credentials.token
318
319 payload = self._verify_token(token)
320 assert payload['aud'] == self.AUDIENCE
321
322 def test_before_request_refreshes(self):
323 credentials = self.credentials.with_claims(audience=self.AUDIENCE)
324 assert not credentials.valid
325 credentials.before_request(
326 None, 'GET', 'http://example.com?a=1#3', {})
327 assert credentials.valid