blob: 960a55aa8c850d9c020d6c2c74d7ba6014c92695 [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 Gregorioa19f3a72012-07-11 15:35:35 -040045from oauth2client.file import Storage
Joe Gregorio8b4c1732011-12-06 11:28:29 -050046
47
48def datafile(filename):
49 f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'r')
50 data = f.read()
51 f.close()
52 return data
53
54
55class CryptTests(unittest.TestCase):
Joe Gregorio0b723c22013-01-03 15:00:50 -050056 def setUp(self):
57 self.format = 'p12'
58 self.signer = crypt.OpenSSLSigner
59 self.verifier = crypt.OpenSSLVerifier
Joe Gregorio8b4c1732011-12-06 11:28:29 -050060
61 def test_sign_and_verify(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -050062 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050063 public_key = datafile('publickey.pem')
64
Joe Gregorio0b723c22013-01-03 15:00:50 -050065 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050066 signature = signer.sign('foo')
67
Joe Gregorio0b723c22013-01-03 15:00:50 -050068 verifier = self.verifier.from_string(public_key, True)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050069
70 self.assertTrue(verifier.verify('foo', signature))
71
72 self.assertFalse(verifier.verify('bar', signature))
73 self.assertFalse(verifier.verify('foo', 'bad signagure'))
74
75 def _check_jwt_failure(self, jwt, expected_error):
76 try:
77 public_key = datafile('publickey.pem')
78 certs = {'foo': public_key}
79 audience = 'https://www.googleapis.com/auth/id?client_id=' + \
80 'external_public_key@testing.gserviceaccount.com'
81 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
82 self.fail('Should have thrown for %s' % jwt)
83 except:
84 e = sys.exc_info()[1]
85 msg = e.args[0]
86 self.assertTrue(expected_error in msg)
87
88 def _create_signed_jwt(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -050089 private_key = datafile('privatekey.%s' % self.format)
90 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -050091 audience = 'some_audience_address@testing.gserviceaccount.com'
92 now = long(time.time())
93
94 return crypt.make_signed_jwt(
95 signer,
96 {
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)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500110 self.assertEqual('billy bob', contents['user'])
111 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500112
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(jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400121 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500122 self.assertEqual('billy bob', contents['user'])
123 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500124
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500125 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,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400133 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500134
135 def test_verify_id_token_bad_tokens(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500136 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500137
138 # Wrong number of segments
139 self._check_jwt_failure('foo', 'Wrong number of segments')
140
141 # Not json
142 self._check_jwt_failure('foo.bar.baz',
143 '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
Joe Gregorio0b723c22013-01-03 15:00:50 -0500150 signer = self.signer.from_string(private_key)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500151 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 )
158 self._check_jwt_failure(jwt, 'No exp field in token')
159
160 # No issued at
161 jwt = crypt.make_signed_jwt(signer, {
162 'aud': 'audience',
163 'exp': time.time() + 400,
164 }
165 )
166 self._check_jwt_failure(jwt, 'No iat field in token')
167
168 # Too early
169 jwt = crypt.make_signed_jwt(signer, {
170 'aud': 'audience',
171 'iat': time.time() + 301,
172 'exp': time.time() + 400,
173 })
174 self._check_jwt_failure(jwt, 'Token used too early')
175
176 # Too late
177 jwt = crypt.make_signed_jwt(signer, {
178 'aud': 'audience',
179 'iat': time.time() - 500,
180 'exp': time.time() - 301,
181 })
182 self._check_jwt_failure(jwt, 'Token used too late')
183
184 # Wrong target
185 jwt = crypt.make_signed_jwt(signer, {
186 'aud': 'somebody else',
187 'iat': time.time(),
188 'exp': time.time() + 300,
189 })
190 self._check_jwt_failure(jwt, 'Wrong recipient')
191
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400192
Joe Gregorio0b723c22013-01-03 15:00:50 -0500193class PEMCryptTestsPyCrypto(CryptTests):
194 def setUp(self):
195 self.format = 'pem'
196 self.signer = crypt.PyCryptoSigner
197 self.verifier = crypt.OpenSSLVerifier
198
199
200class PEMCryptTestsOpenSSL(CryptTests):
201 def setUp(self):
202 self.format = 'pem'
203 self.signer = crypt.OpenSSLSigner
204 self.verifier = crypt.OpenSSLVerifier
205
206
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400207class SignedJwtAssertionCredentialsTests(unittest.TestCase):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500208 def setUp(self):
209 self.format = 'p12'
210 crypt.Signer = crypt.OpenSSLSigner
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400211
212 def test_credentials_good(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500213 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500214 credentials = SignedJwtAssertionCredentials(
215 'some_account@example.com',
216 private_key,
217 scope='read+write',
218 prn='joe@example.org')
219 http = HttpMockSequence([
220 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
221 ({'status': '200'}, 'echo_request_headers'),
222 ])
223 http = credentials.authorize(http)
224 resp, content = http.request('http://example.org')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500225 self.assertEqual('Bearer 1/3w', content['Authorization'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500226
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400227 def test_credentials_to_from_json(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500228 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400229 credentials = SignedJwtAssertionCredentials(
230 'some_account@example.com',
231 private_key,
232 scope='read+write',
233 prn='joe@example.org')
234 json = credentials.to_json()
235 restored = Credentials.new_from_json(json)
236 self.assertEqual(credentials.private_key, restored.private_key)
237 self.assertEqual(credentials.private_key_password,
238 restored.private_key_password)
239 self.assertEqual(credentials.kwargs, restored.kwargs)
240
241 def _credentials_refresh(self, credentials):
242 http = HttpMockSequence([
243 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
244 ({'status': '401'}, ''),
245 ({'status': '200'}, '{"access_token":"3/3w","expires_in":3600}'),
246 ({'status': '200'}, 'echo_request_headers'),
247 ])
248 http = credentials.authorize(http)
249 resp, content = http.request('http://example.org')
250 return content
251
252 def test_credentials_refresh_without_storage(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500253 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400254 credentials = SignedJwtAssertionCredentials(
255 'some_account@example.com',
256 private_key,
257 scope='read+write',
258 prn='joe@example.org')
259
260 content = self._credentials_refresh(credentials)
261
262 self.assertEqual('Bearer 3/3w', content['Authorization'])
263
264 def test_credentials_refresh_with_storage(self):
Joe Gregorio0b723c22013-01-03 15:00:50 -0500265 private_key = datafile('privatekey.%s' % self.format)
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400266 credentials = SignedJwtAssertionCredentials(
267 'some_account@example.com',
268 private_key,
269 scope='read+write',
270 prn='joe@example.org')
271
272 (filehandle, filename) = tempfile.mkstemp()
273 os.close(filehandle)
274 store = Storage(filename)
275 store.put(credentials)
276 credentials.set_store(store)
277
278 content = self._credentials_refresh(credentials)
279
280 self.assertEqual('Bearer 3/3w', content['Authorization'])
281 os.unlink(filename)
282
283
Joe Gregorio0b723c22013-01-03 15:00:50 -0500284class PEMSignedJwtAssertionCredentialsOpenSSLTests(
285 SignedJwtAssertionCredentialsTests):
286 def setUp(self):
287 self.format = 'pem'
288 crypt.Signer = crypt.OpenSSLSigner
289
290
291class PEMSignedJwtAssertionCredentialsPyCryptoTests(
292 SignedJwtAssertionCredentialsTests):
293 def setUp(self):
294 self.format = 'pem'
295 crypt.Signer = crypt.PyCryptoSigner
296
297
298class PKCSSignedJwtAssertionCredentialsPyCryptoTests(unittest.TestCase):
299 def test_for_failure(self):
300 crypt.Signer = crypt.PyCryptoSigner
301 private_key = datafile('privatekey.p12')
302 credentials = SignedJwtAssertionCredentials(
303 'some_account@example.com',
304 private_key,
305 scope='read+write',
306 prn='joe@example.org')
307 try:
308 credentials._generate_assertion()
309 self.fail()
310 except NotImplementedError:
311 pass
312
313
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500314if __name__ == '__main__':
315 unittest.main()