blob: f8cf00b72ec3f9745a194a291b1fa465cef8e4c3 [file] [log] [blame]
Joe Gregorio8b4c1732011-12-06 11:28:29 -05001#!/usr/bin/python2.4
2#
3# Copyright 2010 Google Inc.
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
20Unit tests for oauth2client.
21"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
25import httplib2
26import os
27import sys
Joe Gregorioa19f3a72012-07-11 15:35:35 -040028import tempfile
Joe Gregorio8b4c1732011-12-06 11:28:29 -050029import time
30import unittest
31import urlparse
32
33try:
34 from urlparse import parse_qs
35except ImportError:
36 from cgi import parse_qs
37
John Asmuth864311d2014-04-24 15:46:08 -040038from googleapiclient.http import HttpMockSequence
Joe Gregorio8b4c1732011-12-06 11:28:29 -050039from oauth2client import crypt
Joe Gregorio549230c2012-01-11 10:38:05 -050040from oauth2client.anyjson import simplejson
Joe Gregorioa19f3a72012-07-11 15:35:35 -040041from oauth2client.client import Credentials
Joe Gregorio8b4c1732011-12-06 11:28:29 -050042from oauth2client.client import SignedJwtAssertionCredentials
Joe Gregorio8b4c1732011-12-06 11:28:29 -050043from oauth2client.client import VerifyJwtTokenError
Joe Gregorio549230c2012-01-11 10:38:05 -050044from oauth2client.client import verify_id_token
Joe Gregoriocff6b4d2013-02-12 13:13:04 -050045from oauth2client.client import HAS_OPENSSL
46from oauth2client.client import HAS_CRYPTO
Joe Gregorioa19f3a72012-07-11 15:35:35 -040047from oauth2client.file import Storage
Joe Gregorio8b4c1732011-12-06 11:28:29 -050048
49
50def datafile(filename):
51 f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'r')
52 data = f.read()
53 f.close()
54 return data
55
56
57class CryptTests(unittest.TestCase):
Joe Gregorio0b723c22013-01-03 15:00:50 -050058 def setUp(self):
59 self.format = 'p12'
60 self.signer = crypt.OpenSSLSigner
61 self.verifier = crypt.OpenSSLVerifier
Joe Gregorio8b4c1732011-12-06 11:28:29 -050062
63 def test_sign_and_verify(self):
Joe Gregorio89d832a2013-10-29 16:02:32 -040064 self._check_sign_and_verify('privatekey.%s' % self.format)
65
66 def test_sign_and_verify_from_converted_pkcs12(self):
67 """Tests that following instructions to convert from PKCS12 to PEM works."""
68 if self.format == 'pem':
69 self._check_sign_and_verify('pem_from_pkcs12.pem')
70
71 def _check_sign_and_verify(self, private_key_file):
72 private_key = datafile(private_key_file)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050073 public_key = datafile('publickey.pem')
74
Joe Gregorio0b723c22013-01-03 15:00:50 -050075 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050076 signature = signer.sign('foo')
77
Joe Gregorio0b723c22013-01-03 15:00:50 -050078 verifier = self.verifier.from_string(public_key, True)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050079
80 self.assertTrue(verifier.verify('foo', signature))
81
82 self.assertFalse(verifier.verify('bar', signature))
83 self.assertFalse(verifier.verify('foo', 'bad signagure'))
84
85 def _check_jwt_failure(self, jwt, expected_error):
86 try:
87 public_key = datafile('publickey.pem')
88 certs = {'foo': public_key}
89 audience = 'https://www.googleapis.com/auth/id?client_id=' + \
90 'external_public_key@testing.gserviceaccount.com'
91 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
92 self.fail('Should have thrown for %s' % jwt)
93 except:
94 e = sys.exc_info()[1]
95 msg = e.args[0]
96 self.assertTrue(expected_error in msg)
97
98 def _create_signed_jwt(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -050099 private_key = datafile('privatekey.%s' % self.format)
100 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500101 audience = 'some_audience_address@testing.gserviceaccount.com'
102 now = long(time.time())
103
104 return crypt.make_signed_jwt(
105 signer,
106 {
107 'aud': audience,
108 'iat': now,
109 'exp': now + 300,
110 'user': 'billy bob',
111 'metadata': {'meta': 'data'},
112 })
113
114 def test_verify_id_token(self):
115 jwt = self._create_signed_jwt()
116 public_key = datafile('publickey.pem')
117 certs = {'foo': public_key }
118 audience = 'some_audience_address@testing.gserviceaccount.com'
119 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500120 self.assertEqual('billy bob', contents['user'])
121 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500122
123 def test_verify_id_token_with_certs_uri(self):
124 jwt = self._create_signed_jwt()
125
126 http = HttpMockSequence([
127 ({'status': '200'}, datafile('certs.json')),
128 ])
129
130 contents = verify_id_token(jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400131 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500132 self.assertEqual('billy bob', contents['user'])
133 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500134
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500135 def test_verify_id_token_with_certs_uri_fails(self):
136 jwt = self._create_signed_jwt()
137
138 http = HttpMockSequence([
139 ({'status': '404'}, datafile('certs.json')),
140 ])
141
142 self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400143 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500144
145 def test_verify_id_token_bad_tokens(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500146 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500147
148 # Wrong number of segments
149 self._check_jwt_failure('foo', 'Wrong number of segments')
150
151 # Not json
152 self._check_jwt_failure('foo.bar.baz',
153 'Can\'t parse token')
154
155 # Bad signature
156 jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
157 self._check_jwt_failure(jwt, 'Invalid token signature')
158
159 # No expiration
Joe Gregorio0b723c22013-01-03 15:00:50 -0500160 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500161 audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
162 'external_public_key@testing.gserviceaccount.com'
163 jwt = crypt.make_signed_jwt(signer, {
164 'aud': 'audience',
165 'iat': time.time(),
166 }
167 )
168 self._check_jwt_failure(jwt, 'No exp field in token')
169
170 # No issued at
171 jwt = crypt.make_signed_jwt(signer, {
172 'aud': 'audience',
173 'exp': time.time() + 400,
174 }
175 )
176 self._check_jwt_failure(jwt, 'No iat field in token')
177
178 # Too early
179 jwt = crypt.make_signed_jwt(signer, {
180 'aud': 'audience',
181 'iat': time.time() + 301,
182 'exp': time.time() + 400,
183 })
184 self._check_jwt_failure(jwt, 'Token used too early')
185
186 # Too late
187 jwt = crypt.make_signed_jwt(signer, {
188 'aud': 'audience',
189 'iat': time.time() - 500,
190 'exp': time.time() - 301,
191 })
192 self._check_jwt_failure(jwt, 'Token used too late')
193
194 # Wrong target
195 jwt = crypt.make_signed_jwt(signer, {
196 'aud': 'somebody else',
197 'iat': time.time(),
198 'exp': time.time() + 300,
199 })
200 self._check_jwt_failure(jwt, 'Wrong recipient')
201
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400202
Joe Gregorio0b723c22013-01-03 15:00:50 -0500203class PEMCryptTestsPyCrypto(CryptTests):
204 def setUp(self):
205 self.format = 'pem'
206 self.signer = crypt.PyCryptoSigner
207 self.verifier = crypt.OpenSSLVerifier
208
209
210class PEMCryptTestsOpenSSL(CryptTests):
211 def setUp(self):
212 self.format = 'pem'
213 self.signer = crypt.OpenSSLSigner
214 self.verifier = crypt.OpenSSLVerifier
215
216
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400217class SignedJwtAssertionCredentialsTests(unittest.TestCase):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500218 def setUp(self):
219 self.format = 'p12'
220 crypt.Signer = crypt.OpenSSLSigner
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400221
222 def test_credentials_good(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500223 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500224 credentials = SignedJwtAssertionCredentials(
225 'some_account@example.com',
226 private_key,
227 scope='read+write',
Daniel Hermes482ab762013-03-13 13:37:27 -0700228 sub='joe@example.org')
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500229 http = HttpMockSequence([
230 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
231 ({'status': '200'}, 'echo_request_headers'),
232 ])
233 http = credentials.authorize(http)
234 resp, content = http.request('http://example.org')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500235 self.assertEqual('Bearer 1/3w', content['Authorization'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500236
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400237 def test_credentials_to_from_json(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500238 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400239 credentials = SignedJwtAssertionCredentials(
240 'some_account@example.com',
241 private_key,
242 scope='read+write',
Daniel Hermes482ab762013-03-13 13:37:27 -0700243 sub='joe@example.org')
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400244 json = credentials.to_json()
245 restored = Credentials.new_from_json(json)
246 self.assertEqual(credentials.private_key, restored.private_key)
247 self.assertEqual(credentials.private_key_password,
248 restored.private_key_password)
249 self.assertEqual(credentials.kwargs, restored.kwargs)
250
251 def _credentials_refresh(self, credentials):
252 http = HttpMockSequence([
253 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
254 ({'status': '401'}, ''),
255 ({'status': '200'}, '{"access_token":"3/3w","expires_in":3600}'),
256 ({'status': '200'}, 'echo_request_headers'),
257 ])
258 http = credentials.authorize(http)
259 resp, content = http.request('http://example.org')
260 return content
261
262 def test_credentials_refresh_without_storage(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500263 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400264 credentials = SignedJwtAssertionCredentials(
265 'some_account@example.com',
266 private_key,
267 scope='read+write',
Daniel Hermes482ab762013-03-13 13:37:27 -0700268 sub='joe@example.org')
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400269
270 content = self._credentials_refresh(credentials)
271
272 self.assertEqual('Bearer 3/3w', content['Authorization'])
273
274 def test_credentials_refresh_with_storage(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500275 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400276 credentials = SignedJwtAssertionCredentials(
277 'some_account@example.com',
278 private_key,
279 scope='read+write',
Daniel Hermes482ab762013-03-13 13:37:27 -0700280 sub='joe@example.org')
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400281
282 (filehandle, filename) = tempfile.mkstemp()
283 os.close(filehandle)
284 store = Storage(filename)
285 store.put(credentials)
286 credentials.set_store(store)
287
288 content = self._credentials_refresh(credentials)
289
290 self.assertEqual('Bearer 3/3w', content['Authorization'])
291 os.unlink(filename)
292
293
Joe Gregorio0b723c22013-01-03 15:00:50 -0500294class PEMSignedJwtAssertionCredentialsOpenSSLTests(
295 SignedJwtAssertionCredentialsTests):
296 def setUp(self):
297 self.format = 'pem'
298 crypt.Signer = crypt.OpenSSLSigner
299
300
301class PEMSignedJwtAssertionCredentialsPyCryptoTests(
302 SignedJwtAssertionCredentialsTests):
303 def setUp(self):
304 self.format = 'pem'
305 crypt.Signer = crypt.PyCryptoSigner
306
307
308class PKCSSignedJwtAssertionCredentialsPyCryptoTests(unittest.TestCase):
309 def test_for_failure(self):
310 crypt.Signer = crypt.PyCryptoSigner
311 private_key = datafile('privatekey.p12')
312 credentials = SignedJwtAssertionCredentials(
313 'some_account@example.com',
314 private_key,
315 scope='read+write',
Daniel Hermes482ab762013-03-13 13:37:27 -0700316 sub='joe@example.org')
Joe Gregorio0b723c22013-01-03 15:00:50 -0500317 try:
318 credentials._generate_assertion()
319 self.fail()
320 except NotImplementedError:
321 pass
322
Joe Gregoriocff6b4d2013-02-12 13:13:04 -0500323class TestHasOpenSSLFlag(unittest.TestCase):
324 def test_true(self):
325 self.assertEqual(True, HAS_OPENSSL)
326 self.assertEqual(True, HAS_CRYPTO)
Joe Gregorio0b723c22013-01-03 15:00:50 -0500327
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500328if __name__ == '__main__':
329 unittest.main()