Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(256)

Side by Side Diff: tools/telemetry/third_party/gsutil/third_party/oauth2client/tests/test_jwt.py

Issue 1258583006: Add gsutil 4.13 to telemetry/third_party (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Undo all other changes so this just add gsutil to third_party Created 5 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 #!/usr/bin/python2.4
2 #
3 # Copyright 2014 Google Inc. All rights reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 """Oauth2client tests
19
20 Unit tests for oauth2client.
21 """
22
23 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
25 import os
26 import mock
27 import sys
28 import tempfile
29 import time
30 import unittest
31
32 from .http_mock import HttpMockSequence
33 from oauth2client import client
34 from oauth2client.client import Credentials
35 from oauth2client.client import SignedJwtAssertionCredentials
36 from oauth2client.client import VerifyJwtTokenError
37 from oauth2client.client import verify_id_token
38 from oauth2client.client import HAS_OPENSSL
39 from oauth2client.client import HAS_CRYPTO
40 from oauth2client import crypt
41 from oauth2client.file import Storage
42
43
44 def datafile(filename):
45 f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'rb')
46 data = f.read()
47 f.close()
48 return data
49
50
51 class CryptTests(unittest.TestCase):
52
53 def setUp(self):
54 self.format = 'p12'
55 self.signer = crypt.OpenSSLSigner
56 self.verifier = crypt.OpenSSLVerifier
57
58 def test_sign_and_verify(self):
59 self._check_sign_and_verify('privatekey.%s' % self.format)
60
61 def test_sign_and_verify_from_converted_pkcs12(self):
62 """Tests that following instructions to convert from PKCS12 to PEM works."""
63 if self.format == 'pem':
64 self._check_sign_and_verify('pem_from_pkcs12.pem')
65
66 def _check_sign_and_verify(self, private_key_file):
67 private_key = datafile(private_key_file)
68 public_key = datafile('publickey.pem')
69
70 signer = self.signer.from_string(private_key)
71 signature = signer.sign('foo')
72
73 verifier = self.verifier.from_string(public_key, True)
74 self.assertTrue(verifier.verify(b'foo', signature))
75
76 self.assertFalse(verifier.verify(b'bar', signature))
77 self.assertFalse(verifier.verify(b'foo', 'bad signagure'))
78
79 def _check_jwt_failure(self, jwt, expected_error):
80 public_key = datafile('publickey.pem')
81 certs = {'foo': public_key}
82 audience = ('https://www.googleapis.com/auth/id?client_id='
83 'external_public_key@testing.gserviceaccount.com')
84 try:
85 crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
86 self.fail()
87 except crypt.AppIdentityError as e:
88 self.assertTrue(expected_error in str(e))
89
90 def _create_signed_jwt(self):
91 private_key = datafile('privatekey.%s' % self.format)
92 signer = self.signer.from_string(private_key)
93 audience = 'some_audience_address@testing.gserviceaccount.com'
94 now = int(time.time())
95
96 return crypt.make_signed_jwt(signer, {
97 'aud': audience,
98 'iat': now,
99 'exp': now + 300,
100 'user': 'billy bob',
101 'metadata': {'meta': 'data'},
102 })
103
104 def test_verify_id_token(self):
105 jwt = self._create_signed_jwt()
106 public_key = datafile('publickey.pem')
107 certs = {'foo': public_key}
108 audience = 'some_audience_address@testing.gserviceaccount.com'
109 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
110 self.assertEqual('billy bob', contents['user'])
111 self.assertEqual('data', contents['metadata']['meta'])
112
113 def test_verify_id_token_with_certs_uri(self):
114 jwt = self._create_signed_jwt()
115
116 http = HttpMockSequence([
117 ({'status': '200'}, datafile('certs.json')),
118 ])
119
120 contents = verify_id_token(
121 jwt, 'some_audience_address@testing.gserviceaccount.com', http=http)
122 self.assertEqual('billy bob', contents['user'])
123 self.assertEqual('data', contents['metadata']['meta'])
124
125 def test_verify_id_token_with_certs_uri_fails(self):
126 jwt = self._create_signed_jwt()
127
128 http = HttpMockSequence([
129 ({'status': '404'}, datafile('certs.json')),
130 ])
131
132 self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
133 'some_audience_address@testing.gserviceaccount.com',
134 http=http)
135
136 def test_verify_id_token_bad_tokens(self):
137 private_key = datafile('privatekey.%s' % self.format)
138
139 # Wrong number of segments
140 self._check_jwt_failure('foo', 'Wrong number of segments')
141
142 # Not json
143 self._check_jwt_failure('foo.bar.baz', 'Can\'t parse token')
144
145 # Bad signature
146 jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
147 self._check_jwt_failure(jwt, 'Invalid token signature')
148
149 # No expiration
150 signer = self.signer.from_string(private_key)
151 audience = ('https:#www.googleapis.com/auth/id?client_id='
152 'external_public_key@testing.gserviceaccount.com')
153 jwt = crypt.make_signed_jwt(signer, {
154 'aud': audience,
155 'iat': time.time(),
156 })
157 self._check_jwt_failure(jwt, 'No exp field in token')
158
159 # No issued at
160 jwt = crypt.make_signed_jwt(signer, {
161 'aud': 'audience',
162 'exp': time.time() + 400,
163 })
164 self._check_jwt_failure(jwt, 'No iat field in token')
165
166 # Too early
167 jwt = crypt.make_signed_jwt(signer, {
168 'aud': 'audience',
169 'iat': time.time() + 301,
170 'exp': time.time() + 400,
171 })
172 self._check_jwt_failure(jwt, 'Token used too early')
173
174 # Too late
175 jwt = crypt.make_signed_jwt(signer, {
176 'aud': 'audience',
177 'iat': time.time() - 500,
178 'exp': time.time() - 301,
179 })
180 self._check_jwt_failure(jwt, 'Token used too late')
181
182 # Wrong target
183 jwt = crypt.make_signed_jwt(signer, {
184 'aud': 'somebody else',
185 'iat': time.time(),
186 'exp': time.time() + 300,
187 })
188 self._check_jwt_failure(jwt, 'Wrong recipient')
189
190
191 class PEMCryptTestsPyCrypto(CryptTests):
192 def setUp(self):
193 self.format = 'pem'
194 self.signer = crypt.PyCryptoSigner
195 self.verifier = crypt.PyCryptoVerifier
196
197
198 class PEMCryptTestsOpenSSL(CryptTests):
199 def setUp(self):
200 self.format = 'pem'
201 self.signer = crypt.OpenSSLSigner
202 self.verifier = crypt.OpenSSLVerifier
203
204
205 class SignedJwtAssertionCredentialsTests(unittest.TestCase):
206 def setUp(self):
207 self.format = 'p12'
208 crypt.Signer = crypt.OpenSSLSigner
209
210 def test_credentials_good(self):
211 private_key = datafile('privatekey.%s' % self.format)
212 credentials = SignedJwtAssertionCredentials(
213 'some_account@example.com',
214 private_key,
215 scope='read+write',
216 sub='joe@example.org')
217 http = HttpMockSequence([
218 ({'status': '200'}, b'{"access_token":"1/3w","expires_in":3600}'),
219 ({'status': '200'}, 'echo_request_headers'),
220 ])
221 http = credentials.authorize(http)
222 resp, content = http.request('http://example.org')
223 self.assertEqual(b'Bearer 1/3w', content[b'Authorization'])
224
225 def test_credentials_to_from_json(self):
226 private_key = datafile('privatekey.%s' % self.format)
227 credentials = SignedJwtAssertionCredentials(
228 'some_account@example.com',
229 private_key,
230 scope='read+write',
231 sub='joe@example.org')
232 json = credentials.to_json()
233 restored = Credentials.new_from_json(json)
234 self.assertEqual(credentials.private_key, restored.private_key)
235 self.assertEqual(credentials.private_key_password,
236 restored.private_key_password)
237 self.assertEqual(credentials.kwargs, restored.kwargs)
238
239 def _credentials_refresh(self, credentials):
240 http = HttpMockSequence([
241 ({'status': '200'}, b'{"access_token":"1/3w","expires_in":3600}'),
242 ({'status': '401'}, b''),
243 ({'status': '200'}, b'{"access_token":"3/3w","expires_in":3600}'),
244 ({'status': '200'}, 'echo_request_headers'),
245 ])
246 http = credentials.authorize(http)
247 _, content = http.request('http://example.org')
248 return content
249
250 def test_credentials_refresh_without_storage(self):
251 private_key = datafile('privatekey.%s' % self.format)
252 credentials = SignedJwtAssertionCredentials(
253 'some_account@example.com',
254 private_key,
255 scope='read+write',
256 sub='joe@example.org')
257
258 content = self._credentials_refresh(credentials)
259
260 self.assertEqual(b'Bearer 3/3w', content[b'Authorization'])
261
262 def test_credentials_refresh_with_storage(self):
263 private_key = datafile('privatekey.%s' % self.format)
264 credentials = SignedJwtAssertionCredentials(
265 'some_account@example.com',
266 private_key,
267 scope='read+write',
268 sub='joe@example.org')
269
270 (filehandle, filename) = tempfile.mkstemp()
271 os.close(filehandle)
272 store = Storage(filename)
273 store.put(credentials)
274 credentials.set_store(store)
275
276 content = self._credentials_refresh(credentials)
277
278 self.assertEqual(b'Bearer 3/3w', content[b'Authorization'])
279 os.unlink(filename)
280
281
282 class PEMSignedJwtAssertionCredentialsOpenSSLTests(
283 SignedJwtAssertionCredentialsTests):
284 def setUp(self):
285 self.format = 'pem'
286 crypt.Signer = crypt.OpenSSLSigner
287
288
289 class PEMSignedJwtAssertionCredentialsPyCryptoTests(
290 SignedJwtAssertionCredentialsTests):
291 def setUp(self):
292 self.format = 'pem'
293 crypt.Signer = crypt.PyCryptoSigner
294
295
296 class PKCSSignedJwtAssertionCredentialsPyCryptoTests(unittest.TestCase):
297
298 def test_for_failure(self):
299 crypt.Signer = crypt.PyCryptoSigner
300 private_key = datafile('privatekey.p12')
301 credentials = SignedJwtAssertionCredentials(
302 'some_account@example.com',
303 private_key,
304 scope='read+write',
305 sub='joe@example.org')
306 try:
307 credentials._generate_assertion()
308 self.fail()
309 except NotImplementedError:
310 pass
311
312
313 class TestHasOpenSSLFlag(unittest.TestCase):
314 def test_true(self):
315 self.assertEqual(True, HAS_OPENSSL)
316 self.assertEqual(True, HAS_CRYPTO)
317
318
319 if __name__ == '__main__':
320 unittest.main()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698