blob: 11162be5d87b137522085cbe4e84aeb1724cd5c4 [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):
56
57 def test_sign_and_verify(self):
58 private_key = datafile('privatekey.p12')
59 public_key = datafile('publickey.pem')
60
61 signer = crypt.Signer.from_string(private_key)
62 signature = signer.sign('foo')
63
64 verifier = crypt.Verifier.from_string(public_key, True)
65
66 self.assertTrue(verifier.verify('foo', signature))
67
68 self.assertFalse(verifier.verify('bar', signature))
69 self.assertFalse(verifier.verify('foo', 'bad signagure'))
70
71 def _check_jwt_failure(self, jwt, expected_error):
72 try:
73 public_key = datafile('publickey.pem')
74 certs = {'foo': public_key}
75 audience = 'https://www.googleapis.com/auth/id?client_id=' + \
76 'external_public_key@testing.gserviceaccount.com'
77 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
78 self.fail('Should have thrown for %s' % jwt)
79 except:
80 e = sys.exc_info()[1]
81 msg = e.args[0]
82 self.assertTrue(expected_error in msg)
83
84 def _create_signed_jwt(self):
85 private_key = datafile('privatekey.p12')
86 signer = crypt.Signer.from_string(private_key)
87 audience = 'some_audience_address@testing.gserviceaccount.com'
88 now = long(time.time())
89
90 return crypt.make_signed_jwt(
91 signer,
92 {
93 'aud': audience,
94 'iat': now,
95 'exp': now + 300,
96 'user': 'billy bob',
97 'metadata': {'meta': 'data'},
98 })
99
100 def test_verify_id_token(self):
101 jwt = self._create_signed_jwt()
102 public_key = datafile('publickey.pem')
103 certs = {'foo': public_key }
104 audience = 'some_audience_address@testing.gserviceaccount.com'
105 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500106 self.assertEqual('billy bob', contents['user'])
107 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500108
109 def test_verify_id_token_with_certs_uri(self):
110 jwt = self._create_signed_jwt()
111
112 http = HttpMockSequence([
113 ({'status': '200'}, datafile('certs.json')),
114 ])
115
116 contents = verify_id_token(jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400117 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500118 self.assertEqual('billy bob', contents['user'])
119 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500120
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500121 def test_verify_id_token_with_certs_uri_fails(self):
122 jwt = self._create_signed_jwt()
123
124 http = HttpMockSequence([
125 ({'status': '404'}, datafile('certs.json')),
126 ])
127
128 self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400129 'some_audience_address@testing.gserviceaccount.com', http=http)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500130
131 def test_verify_id_token_bad_tokens(self):
132 private_key = datafile('privatekey.p12')
133
134 # Wrong number of segments
135 self._check_jwt_failure('foo', 'Wrong number of segments')
136
137 # Not json
138 self._check_jwt_failure('foo.bar.baz',
139 'Can\'t parse token')
140
141 # Bad signature
142 jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
143 self._check_jwt_failure(jwt, 'Invalid token signature')
144
145 # No expiration
146 signer = crypt.Signer.from_string(private_key)
147 audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
148 'external_public_key@testing.gserviceaccount.com'
149 jwt = crypt.make_signed_jwt(signer, {
150 'aud': 'audience',
151 'iat': time.time(),
152 }
153 )
154 self._check_jwt_failure(jwt, 'No exp field in token')
155
156 # No issued at
157 jwt = crypt.make_signed_jwt(signer, {
158 'aud': 'audience',
159 'exp': time.time() + 400,
160 }
161 )
162 self._check_jwt_failure(jwt, 'No iat field in token')
163
164 # Too early
165 jwt = crypt.make_signed_jwt(signer, {
166 'aud': 'audience',
167 'iat': time.time() + 301,
168 'exp': time.time() + 400,
169 })
170 self._check_jwt_failure(jwt, 'Token used too early')
171
172 # Too late
173 jwt = crypt.make_signed_jwt(signer, {
174 'aud': 'audience',
175 'iat': time.time() - 500,
176 'exp': time.time() - 301,
177 })
178 self._check_jwt_failure(jwt, 'Token used too late')
179
180 # Wrong target
181 jwt = crypt.make_signed_jwt(signer, {
182 'aud': 'somebody else',
183 'iat': time.time(),
184 'exp': time.time() + 300,
185 })
186 self._check_jwt_failure(jwt, 'Wrong recipient')
187
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400188
189class SignedJwtAssertionCredentialsTests(unittest.TestCase):
190
191 def test_credentials_good(self):
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500192 private_key = datafile('privatekey.p12')
193 credentials = SignedJwtAssertionCredentials(
194 'some_account@example.com',
195 private_key,
196 scope='read+write',
197 prn='joe@example.org')
198 http = HttpMockSequence([
199 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
200 ({'status': '200'}, 'echo_request_headers'),
201 ])
202 http = credentials.authorize(http)
203 resp, content = http.request('http://example.org')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500204 self.assertEqual('Bearer 1/3w', content['Authorization'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500205
Joe Gregorioa19f3a72012-07-11 15:35:35 -0400206 def test_credentials_to_from_json(self):
207 private_key = datafile('privatekey.p12')
208 credentials = SignedJwtAssertionCredentials(
209 'some_account@example.com',
210 private_key,
211 scope='read+write',
212 prn='joe@example.org')
213 json = credentials.to_json()
214 restored = Credentials.new_from_json(json)
215 self.assertEqual(credentials.private_key, restored.private_key)
216 self.assertEqual(credentials.private_key_password,
217 restored.private_key_password)
218 self.assertEqual(credentials.kwargs, restored.kwargs)
219
220 def _credentials_refresh(self, credentials):
221 http = HttpMockSequence([
222 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
223 ({'status': '401'}, ''),
224 ({'status': '200'}, '{"access_token":"3/3w","expires_in":3600}'),
225 ({'status': '200'}, 'echo_request_headers'),
226 ])
227 http = credentials.authorize(http)
228 resp, content = http.request('http://example.org')
229 return content
230
231 def test_credentials_refresh_without_storage(self):
232 private_key = datafile('privatekey.p12')
233 credentials = SignedJwtAssertionCredentials(
234 'some_account@example.com',
235 private_key,
236 scope='read+write',
237 prn='joe@example.org')
238
239 content = self._credentials_refresh(credentials)
240
241 self.assertEqual('Bearer 3/3w', content['Authorization'])
242
243 def test_credentials_refresh_with_storage(self):
244 private_key = datafile('privatekey.p12')
245 credentials = SignedJwtAssertionCredentials(
246 'some_account@example.com',
247 private_key,
248 scope='read+write',
249 prn='joe@example.org')
250
251 (filehandle, filename) = tempfile.mkstemp()
252 os.close(filehandle)
253 store = Storage(filename)
254 store.put(credentials)
255 credentials.set_store(store)
256
257 content = self._credentials_refresh(credentials)
258
259 self.assertEqual('Bearer 3/3w', content['Authorization'])
260 os.unlink(filename)
261
262
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500263if __name__ == '__main__':
264 unittest.main()