blob: 00161537d7f3e270515f6d5e2371b13b40bdffce [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
Joe Gregorio8b4c1732011-12-06 11:28:29 -050038from apiclient.http import HttpMockSequence
39from 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 Gregorio0b723c22013-01-03 15:00:50 -050064 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050065 public_key = datafile('publickey.pem')
66
Joe Gregorio0b723c22013-01-03 15:00:50 -050067 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050068 signature = signer.sign('foo')
69
Joe Gregorio0b723c22013-01-03 15:00:50 -050070 verifier = self.verifier.from_string(public_key, True)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050071
72 self.assertTrue(verifier.verify('foo', signature))
73
74 self.assertFalse(verifier.verify('bar', signature))
75 self.assertFalse(verifier.verify('foo', 'bad signagure'))
76
77 def _check_jwt_failure(self, jwt, expected_error):
78 try:
79 public_key = datafile('publickey.pem')
80 certs = {'foo': public_key}
81 audience = 'https://www.googleapis.com/auth/id?client_id=' + \
82 'external_public_key@testing.gserviceaccount.com'
83 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
84 self.fail('Should have thrown for %s' % jwt)
85 except:
86 e = sys.exc_info()[1]
87 msg = e.args[0]
88 self.assertTrue(expected_error in msg)
89
90 def _create_signed_jwt(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -050091 private_key = datafile('privatekey.%s' % self.format)
92 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050093 audience = 'some_audience_address@testing.gserviceaccount.com'
94 now = long(time.time())
95
96 return crypt.make_signed_jwt(
97 signer,
98 {
99 'aud': audience,
100 'iat': now,
101 'exp': now + 300,
102 'user': 'billy bob',
103 'metadata': {'meta': 'data'},
104 })
105
106 def test_verify_id_token(self):
107 jwt = self._create_signed_jwt()
108 public_key = datafile('publickey.pem')
109 certs = {'foo': public_key }
110 audience = 'some_audience_address@testing.gserviceaccount.com'
111 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500112 self.assertEqual('billy bob', contents['user'])
113 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500114
115 def test_verify_id_token_with_certs_uri(self):
116 jwt = self._create_signed_jwt()
117
118 http = HttpMockSequence([
119 ({'status': '200'}, datafile('certs.json')),
120 ])
121
122 contents = verify_id_token(jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400123 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500124 self.assertEqual('billy bob', contents['user'])
125 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500126
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500127 def test_verify_id_token_with_certs_uri_fails(self):
128 jwt = self._create_signed_jwt()
129
130 http = HttpMockSequence([
131 ({'status': '404'}, datafile('certs.json')),
132 ])
133
134 self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400135 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500136
137 def test_verify_id_token_bad_tokens(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500138 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500139
140 # Wrong number of segments
141 self._check_jwt_failure('foo', 'Wrong number of segments')
142
143 # Not json
144 self._check_jwt_failure('foo.bar.baz',
145 'Can\'t parse token')
146
147 # Bad signature
148 jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
149 self._check_jwt_failure(jwt, 'Invalid token signature')
150
151 # No expiration
Joe Gregorio0b723c22013-01-03 15:00:50 -0500152 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500153 audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
154 'external_public_key@testing.gserviceaccount.com'
155 jwt = crypt.make_signed_jwt(signer, {
156 'aud': 'audience',
157 'iat': time.time(),
158 }
159 )
160 self._check_jwt_failure(jwt, 'No exp field in token')
161
162 # No issued at
163 jwt = crypt.make_signed_jwt(signer, {
164 'aud': 'audience',
165 'exp': time.time() + 400,
166 }
167 )
168 self._check_jwt_failure(jwt, 'No iat field in token')
169
170 # Too early
171 jwt = crypt.make_signed_jwt(signer, {
172 'aud': 'audience',
173 'iat': time.time() + 301,
174 'exp': time.time() + 400,
175 })
176 self._check_jwt_failure(jwt, 'Token used too early')
177
178 # Too late
179 jwt = crypt.make_signed_jwt(signer, {
180 'aud': 'audience',
181 'iat': time.time() - 500,
182 'exp': time.time() - 301,
183 })
184 self._check_jwt_failure(jwt, 'Token used too late')
185
186 # Wrong target
187 jwt = crypt.make_signed_jwt(signer, {
188 'aud': 'somebody else',
189 'iat': time.time(),
190 'exp': time.time() + 300,
191 })
192 self._check_jwt_failure(jwt, 'Wrong recipient')
193
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400194
Joe Gregorio0b723c22013-01-03 15:00:50 -0500195class PEMCryptTestsPyCrypto(CryptTests):
196 def setUp(self):
197 self.format = 'pem'
198 self.signer = crypt.PyCryptoSigner
199 self.verifier = crypt.OpenSSLVerifier
200
201
202class PEMCryptTestsOpenSSL(CryptTests):
203 def setUp(self):
204 self.format = 'pem'
205 self.signer = crypt.OpenSSLSigner
206 self.verifier = crypt.OpenSSLVerifier
207
208
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400209class SignedJwtAssertionCredentialsTests(unittest.TestCase):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500210 def setUp(self):
211 self.format = 'p12'
212 crypt.Signer = crypt.OpenSSLSigner
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400213
214 def test_credentials_good(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500215 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500216 credentials = SignedJwtAssertionCredentials(
217 'some_account@example.com',
218 private_key,
219 scope='read+write',
220 prn='joe@example.org')
221 http = HttpMockSequence([
222 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
223 ({'status': '200'}, 'echo_request_headers'),
224 ])
225 http = credentials.authorize(http)
226 resp, content = http.request('http://example.org')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500227 self.assertEqual('Bearer 1/3w', content['Authorization'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500228
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400229 def test_credentials_to_from_json(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500230 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400231 credentials = SignedJwtAssertionCredentials(
232 'some_account@example.com',
233 private_key,
234 scope='read+write',
235 prn='joe@example.org')
236 json = credentials.to_json()
237 restored = Credentials.new_from_json(json)
238 self.assertEqual(credentials.private_key, restored.private_key)
239 self.assertEqual(credentials.private_key_password,
240 restored.private_key_password)
241 self.assertEqual(credentials.kwargs, restored.kwargs)
242
243 def _credentials_refresh(self, credentials):
244 http = HttpMockSequence([
245 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
246 ({'status': '401'}, ''),
247 ({'status': '200'}, '{"access_token":"3/3w","expires_in":3600}'),
248 ({'status': '200'}, 'echo_request_headers'),
249 ])
250 http = credentials.authorize(http)
251 resp, content = http.request('http://example.org')
252 return content
253
254 def test_credentials_refresh_without_storage(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500255 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400256 credentials = SignedJwtAssertionCredentials(
257 'some_account@example.com',
258 private_key,
259 scope='read+write',
260 prn='joe@example.org')
261
262 content = self._credentials_refresh(credentials)
263
264 self.assertEqual('Bearer 3/3w', content['Authorization'])
265
266 def test_credentials_refresh_with_storage(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500267 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400268 credentials = SignedJwtAssertionCredentials(
269 'some_account@example.com',
270 private_key,
271 scope='read+write',
272 prn='joe@example.org')
273
274 (filehandle, filename) = tempfile.mkstemp()
275 os.close(filehandle)
276 store = Storage(filename)
277 store.put(credentials)
278 credentials.set_store(store)
279
280 content = self._credentials_refresh(credentials)
281
282 self.assertEqual('Bearer 3/3w', content['Authorization'])
283 os.unlink(filename)
284
285
Joe Gregorio0b723c22013-01-03 15:00:50 -0500286class PEMSignedJwtAssertionCredentialsOpenSSLTests(
287 SignedJwtAssertionCredentialsTests):
288 def setUp(self):
289 self.format = 'pem'
290 crypt.Signer = crypt.OpenSSLSigner
291
292
293class PEMSignedJwtAssertionCredentialsPyCryptoTests(
294 SignedJwtAssertionCredentialsTests):
295 def setUp(self):
296 self.format = 'pem'
297 crypt.Signer = crypt.PyCryptoSigner
298
299
300class PKCSSignedJwtAssertionCredentialsPyCryptoTests(unittest.TestCase):
301 def test_for_failure(self):
302 crypt.Signer = crypt.PyCryptoSigner
303 private_key = datafile('privatekey.p12')
304 credentials = SignedJwtAssertionCredentials(
305 'some_account@example.com',
306 private_key,
307 scope='read+write',
308 prn='joe@example.org')
309 try:
310 credentials._generate_assertion()
311 self.fail()
312 except NotImplementedError:
313 pass
314
Joe Gregoriocff6b4d2013-02-12 13:13:04 -0500315class TestHasOpenSSLFlag(unittest.TestCase):
316 def test_true(self):
317 self.assertEqual(True, HAS_OPENSSL)
318 self.assertEqual(True, HAS_CRYPTO)
Joe Gregorio0b723c22013-01-03 15:00:50 -0500319
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500320if __name__ == '__main__':
321 unittest.main()