blob: 6dc272930b212a03535a5267203cd4dc72913aac [file] [log] [blame]
Joe Gregorioccc79542011-02-19 00:05:26 -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
Joe Gregorio0bc70912011-05-24 15:30:49 -040018"""Oauth2client tests
Joe Gregorioccc79542011-02-19 00:05:26 -050019
Joe Gregorio0bc70912011-05-24 15:30:49 -040020Unit tests for oauth2client.
Joe Gregorioccc79542011-02-19 00:05:26 -050021"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
Joe Gregorio8b4c1732011-12-06 11:28:29 -050025import base64
Joe Gregorio562b7312011-09-15 09:06:38 -040026import datetime
Joe Gregorioe1de4162011-02-23 11:30:29 -050027import httplib2
Joe Gregorio32d852d2012-06-14 09:08:18 -040028import os
Joe Gregorioccc79542011-02-19 00:05:26 -050029import unittest
30import urlparse
Joe Gregorioe1de4162011-02-23 11:30:29 -050031
Joe Gregorio83f2ee62012-12-06 15:25:54 -050032from apiclient.http import HttpMock
Joe Gregorioccc79542011-02-19 00:05:26 -050033from apiclient.http import HttpMockSequence
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080034from oauth2client import GOOGLE_REVOKE_URI
35from oauth2client import GOOGLE_TOKEN_URI
Joe Gregorio549230c2012-01-11 10:38:05 -050036from oauth2client.anyjson import simplejson
Joe Gregorioccc79542011-02-19 00:05:26 -050037from oauth2client.client import AccessTokenCredentials
38from oauth2client.client import AccessTokenCredentialsError
39from oauth2client.client import AccessTokenRefreshError
JacobMoshenko8e905102011-06-20 09:53:10 -040040from oauth2client.client import AssertionCredentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040041from oauth2client.client import Credentials
Joe Gregorioccc79542011-02-19 00:05:26 -050042from oauth2client.client import FlowExchangeError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040043from oauth2client.client import MemoryCache
Joe Gregorio83f2ee62012-12-06 15:25:54 -050044from oauth2client.client import NonAsciiHeaderError
Joe Gregorioccc79542011-02-19 00:05:26 -050045from oauth2client.client import OAuth2Credentials
46from oauth2client.client import OAuth2WebServerFlow
Joe Gregoriof2326c02012-02-09 12:18:44 -050047from oauth2client.client import OOB_CALLBACK_URN
Joe Gregorio0bd8c412013-01-03 17:17:46 -050048from oauth2client.client import REFRESH_STATUS_CODES
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080049from oauth2client.client import Storage
50from oauth2client.client import TokenRevokeError
Joe Gregorio8b4c1732011-12-06 11:28:29 -050051from oauth2client.client import VerifyJwtTokenError
52from oauth2client.client import _extract_id_token
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080053from oauth2client.client import _update_query_params
Joe Gregorio32d852d2012-06-14 09:08:18 -040054from oauth2client.client import credentials_from_clientsecrets_and_code
Joe Gregorio83f2ee62012-12-06 15:25:54 -050055from oauth2client.client import credentials_from_code
Joe Gregorioc29aaa92012-07-16 16:16:31 -040056from oauth2client.client import flow_from_clientsecrets
Joe Gregorio0bd8c412013-01-03 17:17:46 -050057from oauth2client.clientsecrets import _loadfile
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080058from test_discovery import assertUrisEqual
59
Joe Gregorio32d852d2012-06-14 09:08:18 -040060
61DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
62
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040063
Joe Gregorio32d852d2012-06-14 09:08:18 -040064def datafile(filename):
65 return os.path.join(DATA_DIR, filename)
Joe Gregorioccc79542011-02-19 00:05:26 -050066
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040067
Joe Gregorioc29aaa92012-07-16 16:16:31 -040068def load_and_cache(existing_file, fakename, cache_mock):
69 client_type, client_info = _loadfile(datafile(existing_file))
70 cache_mock.cache[fakename] = {client_type: client_info}
71
Joe Gregorio68a8cfe2012-08-03 16:17:40 -040072
Joe Gregorioc29aaa92012-07-16 16:16:31 -040073class CacheMock(object):
74 def __init__(self):
75 self.cache = {}
76
77 def get(self, key, namespace=''):
78 # ignoring namespace for easier testing
79 return self.cache.get(key, None)
80
81 def set(self, key, value, namespace=''):
82 # ignoring namespace for easier testing
83 self.cache[key] = value
84
Joe Gregorioccc79542011-02-19 00:05:26 -050085
Joe Gregorio08cdcb82012-03-14 00:09:33 -040086class CredentialsTests(unittest.TestCase):
87
88 def test_to_from_json(self):
89 credentials = Credentials()
90 json = credentials.to_json()
91 restored = Credentials.new_from_json(json)
92
93
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080094class DummyDeleteStorage(Storage):
95 delete_called = False
96
97 def locked_delete(self):
98 self.delete_called = True
99
100
101def _token_revoke_test_helper(testcase, status, revoke_raise,
102 valid_bool_value, token_attr):
103 current_store = getattr(testcase.credentials, 'store', None)
104
105 dummy_store = DummyDeleteStorage()
106 testcase.credentials.set_store(dummy_store)
107
108 actual_do_revoke = testcase.credentials._do_revoke
109 testcase.token_from_revoke = None
110 def do_revoke_stub(http_request, token):
111 testcase.token_from_revoke = token
112 return actual_do_revoke(http_request, token)
113 testcase.credentials._do_revoke = do_revoke_stub
114
115 http = HttpMock(headers={'status': status})
116 if revoke_raise:
117 testcase.assertRaises(TokenRevokeError, testcase.credentials.revoke, http)
118 else:
119 testcase.credentials.revoke(http)
120
121 testcase.assertEqual(getattr(testcase.credentials, token_attr),
122 testcase.token_from_revoke)
123 testcase.assertEqual(valid_bool_value, testcase.credentials.invalid)
124 testcase.assertEqual(valid_bool_value, dummy_store.delete_called)
125
126 testcase.credentials.set_store(current_store)
127
128
Joe Gregorio83f2ee62012-12-06 15:25:54 -0500129class BasicCredentialsTests(unittest.TestCase):
Joe Gregorioccc79542011-02-19 00:05:26 -0500130
131 def setUp(self):
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800132 access_token = 'foo'
133 client_id = 'some_client_id'
134 client_secret = 'cOuDdkfjxxnv+'
135 refresh_token = '1/0/a.df219fjls0'
Joe Gregorio562b7312011-09-15 09:06:38 -0400136 token_expiry = datetime.datetime.utcnow()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800137 user_agent = 'refresh_checker/1.0'
Joe Gregorioccc79542011-02-19 00:05:26 -0500138 self.credentials = OAuth2Credentials(
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800139 access_token, client_id, client_secret,
140 refresh_token, token_expiry, GOOGLE_TOKEN_URI,
141 user_agent, revoke_uri=GOOGLE_REVOKE_URI)
Joe Gregorioccc79542011-02-19 00:05:26 -0500142
143 def test_token_refresh_success(self):
Joe Gregorio0bd8c412013-01-03 17:17:46 -0500144 for status_code in REFRESH_STATUS_CODES:
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400145 http = HttpMockSequence([
146 ({'status': status_code}, ''),
147 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
148 ({'status': '200'}, 'echo_request_headers'),
149 ])
150 http = self.credentials.authorize(http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800151 resp, content = http.request('http://example.com')
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400152 self.assertEqual('Bearer 1/3w', content['Authorization'])
153 self.assertFalse(self.credentials.access_token_expired)
Joe Gregorioccc79542011-02-19 00:05:26 -0500154
155 def test_token_refresh_failure(self):
Joe Gregorio0bd8c412013-01-03 17:17:46 -0500156 for status_code in REFRESH_STATUS_CODES:
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400157 http = HttpMockSequence([
158 ({'status': status_code}, ''),
159 ({'status': '400'}, '{"error":"access_denied"}'),
160 ])
161 http = self.credentials.authorize(http)
162 try:
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800163 http.request('http://example.com')
164 self.fail('should raise AccessTokenRefreshError exception')
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400165 except AccessTokenRefreshError:
166 pass
167 self.assertTrue(self.credentials.access_token_expired)
Joe Gregorioccc79542011-02-19 00:05:26 -0500168
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800169 def test_token_revoke_success(self):
170 _token_revoke_test_helper(
171 self, '200', revoke_raise=False,
172 valid_bool_value=True, token_attr='refresh_token')
173
174 def test_token_revoke_failure(self):
175 _token_revoke_test_helper(
176 self, '400', revoke_raise=True,
177 valid_bool_value=False, token_attr='refresh_token')
178
Joe Gregorioccc79542011-02-19 00:05:26 -0500179 def test_non_401_error_response(self):
180 http = HttpMockSequence([
181 ({'status': '400'}, ''),
182 ])
183 http = self.credentials.authorize(http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800184 resp, content = http.request('http://example.com')
Joe Gregorioccc79542011-02-19 00:05:26 -0500185 self.assertEqual(400, resp.status)
186
Joe Gregorio562b7312011-09-15 09:06:38 -0400187 def test_to_from_json(self):
188 json = self.credentials.to_json()
189 instance = OAuth2Credentials.from_json(json)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500190 self.assertEqual(OAuth2Credentials, type(instance))
Joe Gregorio1daa71b2011-09-15 18:12:14 -0400191 instance.token_expiry = None
192 self.credentials.token_expiry = None
193
Joe Gregorio654f4a22012-02-09 14:15:44 -0500194 self.assertEqual(instance.__dict__, self.credentials.__dict__)
Joe Gregorio562b7312011-09-15 09:06:38 -0400195
Joe Gregorio83f2ee62012-12-06 15:25:54 -0500196 def test_no_unicode_in_request_params(self):
197 access_token = u'foo'
198 client_id = u'some_client_id'
199 client_secret = u'cOuDdkfjxxnv+'
200 refresh_token = u'1/0/a.df219fjls0'
201 token_expiry = unicode(datetime.datetime.utcnow())
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800202 token_uri = unicode(GOOGLE_TOKEN_URI)
203 revoke_uri = unicode(GOOGLE_REVOKE_URI)
Joe Gregorio83f2ee62012-12-06 15:25:54 -0500204 user_agent = u'refresh_checker/1.0'
205 credentials = OAuth2Credentials(access_token, client_id, client_secret,
206 refresh_token, token_expiry, token_uri,
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800207 user_agent, revoke_uri=revoke_uri)
Joe Gregorio83f2ee62012-12-06 15:25:54 -0500208
209 http = HttpMock(headers={'status': '200'})
210 http = credentials.authorize(http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800211 http.request(u'http://example.com', method=u'GET', headers={u'foo': u'bar'})
Joe Gregorio83f2ee62012-12-06 15:25:54 -0500212 for k, v in http.headers.iteritems():
213 self.assertEqual(str, type(k))
214 self.assertEqual(str, type(v))
215
216 # Test again with unicode strings that can't simple be converted to ASCII.
217 try:
218 http.request(
219 u'http://example.com', method=u'GET', headers={u'foo': u'\N{COMET}'})
220 self.fail('Expected exception to be raised.')
221 except NonAsciiHeaderError:
222 pass
223
Joe Gregorioccc79542011-02-19 00:05:26 -0500224
225class AccessTokenCredentialsTests(unittest.TestCase):
226
227 def setUp(self):
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800228 access_token = 'foo'
229 user_agent = 'refresh_checker/1.0'
230 self.credentials = AccessTokenCredentials(access_token, user_agent,
231 revoke_uri=GOOGLE_REVOKE_URI)
Joe Gregorioccc79542011-02-19 00:05:26 -0500232
233 def test_token_refresh_success(self):
Joe Gregorio0bd8c412013-01-03 17:17:46 -0500234 for status_code in REFRESH_STATUS_CODES:
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400235 http = HttpMockSequence([
236 ({'status': status_code}, ''),
237 ])
238 http = self.credentials.authorize(http)
239 try:
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800240 resp, content = http.request('http://example.com')
241 self.fail('should throw exception if token expires')
Joe Gregorio7c7c6b12012-07-16 16:31:01 -0400242 except AccessTokenCredentialsError:
243 pass
244 except Exception:
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800245 self.fail('should only throw AccessTokenCredentialsError')
246
247 def test_token_revoke_success(self):
248 _token_revoke_test_helper(
249 self, '200', revoke_raise=False,
250 valid_bool_value=True, token_attr='access_token')
251
252 def test_token_revoke_failure(self):
253 _token_revoke_test_helper(
254 self, '400', revoke_raise=True,
255 valid_bool_value=False, token_attr='access_token')
Joe Gregorioccc79542011-02-19 00:05:26 -0500256
257 def test_non_401_error_response(self):
258 http = HttpMockSequence([
259 ({'status': '400'}, ''),
260 ])
261 http = self.credentials.authorize(http)
Joe Gregorio83cd4392011-06-20 10:11:35 -0400262 resp, content = http.request('http://example.com')
Joe Gregorioccc79542011-02-19 00:05:26 -0500263 self.assertEqual(400, resp.status)
264
Joe Gregorio83cd4392011-06-20 10:11:35 -0400265 def test_auth_header_sent(self):
266 http = HttpMockSequence([
267 ({'status': '200'}, 'echo_request_headers'),
268 ])
269 http = self.credentials.authorize(http)
270 resp, content = http.request('http://example.com')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500271 self.assertEqual('Bearer foo', content['Authorization'])
Joe Gregorioccc79542011-02-19 00:05:26 -0500272
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500273
JacobMoshenko8e905102011-06-20 09:53:10 -0400274class TestAssertionCredentials(unittest.TestCase):
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800275 assertion_text = 'This is the assertion'
276 assertion_type = 'http://www.google.com/assertionType'
JacobMoshenko8e905102011-06-20 09:53:10 -0400277
278 class AssertionCredentialsTestImpl(AssertionCredentials):
279
280 def _generate_assertion(self):
281 return TestAssertionCredentials.assertion_text
282
283 def setUp(self):
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800284 user_agent = 'fun/2.0'
JacobMoshenko8e905102011-06-20 09:53:10 -0400285 self.credentials = self.AssertionCredentialsTestImpl(self.assertion_type,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400286 user_agent=user_agent)
JacobMoshenko8e905102011-06-20 09:53:10 -0400287
288 def test_assertion_body(self):
289 body = urlparse.parse_qs(self.credentials._generate_refresh_request_body())
Joe Gregorio654f4a22012-02-09 14:15:44 -0500290 self.assertEqual(self.assertion_text, body['assertion'][0])
291 self.assertEqual(self.assertion_type, body['assertion_type'][0])
JacobMoshenko8e905102011-06-20 09:53:10 -0400292
293 def test_assertion_refresh(self):
294 http = HttpMockSequence([
295 ({'status': '200'}, '{"access_token":"1/3w"}'),
296 ({'status': '200'}, 'echo_request_headers'),
297 ])
298 http = self.credentials.authorize(http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800299 resp, content = http.request('http://example.com')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500300 self.assertEqual('Bearer 1/3w', content['Authorization'])
JacobMoshenko8e905102011-06-20 09:53:10 -0400301
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800302 def test_token_revoke_success(self):
303 _token_revoke_test_helper(
304 self, '200', revoke_raise=False,
305 valid_bool_value=True, token_attr='access_token')
JacobMoshenko8e905102011-06-20 09:53:10 -0400306
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800307 def test_token_revoke_failure(self):
308 _token_revoke_test_helper(
309 self, '400', revoke_raise=True,
310 valid_bool_value=False, token_attr='access_token')
311
312
313class UpdateQueryParamsTest(unittest.TestCase):
314 def test_update_query_params_no_params(self):
315 uri = 'http://www.google.com'
316 updated = _update_query_params(uri, {'a': 'b'})
317 self.assertEqual(updated, uri + '?a=b')
318
319 def test_update_query_params_existing_params(self):
320 uri = 'http://www.google.com?x=y'
321 updated = _update_query_params(uri, {'a': 'b', 'c': 'd&'})
322 hardcoded_update = uri + '&a=b&c=d%26'
323 assertUrisEqual(self, updated, hardcoded_update)
324
325
326class ExtractIdTokenTest(unittest.TestCase):
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500327 """Tests _extract_id_token()."""
328
329 def test_extract_success(self):
330 body = {'foo': 'bar'}
331 payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
332 jwt = 'stuff.' + payload + '.signature'
333
334 extracted = _extract_id_token(jwt)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500335 self.assertEqual(extracted, body)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500336
337 def test_extract_failure(self):
338 body = {'foo': 'bar'}
339 payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
340 jwt = 'stuff.' + payload
341
342 self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
343
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400344
Joe Gregorioccc79542011-02-19 00:05:26 -0500345class OAuth2WebServerFlowTest(unittest.TestCase):
346
347 def setUp(self):
348 self.flow = OAuth2WebServerFlow(
349 client_id='client_id+1',
350 client_secret='secret+1',
351 scope='foo',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400352 redirect_uri=OOB_CALLBACK_URN,
Joe Gregorioccc79542011-02-19 00:05:26 -0500353 user_agent='unittest-sample/1.0',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800354 revoke_uri='dummy_revoke_uri',
Joe Gregorioccc79542011-02-19 00:05:26 -0500355 )
356
357 def test_construct_authorize_url(self):
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400358 authorize_url = self.flow.step1_get_authorize_url()
Joe Gregorioccc79542011-02-19 00:05:26 -0500359
360 parsed = urlparse.urlparse(authorize_url)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800361 q = urlparse.parse_qs(parsed[4])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500362 self.assertEqual('client_id+1', q['client_id'][0])
363 self.assertEqual('code', q['response_type'][0])
364 self.assertEqual('foo', q['scope'][0])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400365 self.assertEqual(OOB_CALLBACK_URN, q['redirect_uri'][0])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500366 self.assertEqual('offline', q['access_type'][0])
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400367
Joe Gregorio32f73192012-10-23 16:13:44 -0400368 def test_override_flow_via_kwargs(self):
369 """Passing kwargs to override defaults."""
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400370 flow = OAuth2WebServerFlow(
371 client_id='client_id+1',
372 client_secret='secret+1',
373 scope='foo',
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400374 redirect_uri=OOB_CALLBACK_URN,
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400375 user_agent='unittest-sample/1.0',
Joe Gregorio32f73192012-10-23 16:13:44 -0400376 access_type='online',
377 response_type='token'
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400378 )
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400379 authorize_url = flow.step1_get_authorize_url()
Joe Gregorio69a0aca2011-11-03 10:47:32 -0400380
381 parsed = urlparse.urlparse(authorize_url)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800382 q = urlparse.parse_qs(parsed[4])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500383 self.assertEqual('client_id+1', q['client_id'][0])
Joe Gregorio32f73192012-10-23 16:13:44 -0400384 self.assertEqual('token', q['response_type'][0])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500385 self.assertEqual('foo', q['scope'][0])
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400386 self.assertEqual(OOB_CALLBACK_URN, q['redirect_uri'][0])
Joe Gregorio654f4a22012-02-09 14:15:44 -0500387 self.assertEqual('online', q['access_type'][0])
Joe Gregorioccc79542011-02-19 00:05:26 -0500388
389 def test_exchange_failure(self):
390 http = HttpMockSequence([
JacobMoshenko8e905102011-06-20 09:53:10 -0400391 ({'status': '400'}, '{"error":"invalid_request"}'),
Joe Gregorioccc79542011-02-19 00:05:26 -0500392 ])
393
394 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400395 credentials = self.flow.step2_exchange('some random code', http=http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800396 self.fail('should raise exception if exchange doesn\'t get 200')
Joe Gregorioccc79542011-02-19 00:05:26 -0500397 except FlowExchangeError:
398 pass
399
Joe Gregorioddb969a2012-07-11 11:04:12 -0400400 def test_urlencoded_exchange_failure(self):
401 http = HttpMockSequence([
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800402 ({'status': '400'}, 'error=invalid_request'),
Joe Gregorioddb969a2012-07-11 11:04:12 -0400403 ])
404
405 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400406 credentials = self.flow.step2_exchange('some random code', http=http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800407 self.fail('should raise exception if exchange doesn\'t get 200')
Joe Gregorioddb969a2012-07-11 11:04:12 -0400408 except FlowExchangeError, e:
409 self.assertEquals('invalid_request', str(e))
410
411 def test_exchange_failure_with_json_error(self):
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800412 # Some providers have 'error' attribute as a JSON object
Joe Gregorioddb969a2012-07-11 11:04:12 -0400413 # in place of regular string.
414 # This test makes sure no strange object-to-string coversion
415 # exceptions are being raised instead of FlowExchangeError.
416 http = HttpMockSequence([
417 ({'status': '400'},
418 """ {"error": {
419 "type": "OAuthException",
420 "message": "Error validating verification code."} }"""),
421 ])
422
423 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400424 credentials = self.flow.step2_exchange('some random code', http=http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800425 self.fail('should raise exception if exchange doesn\'t get 200')
Joe Gregorioddb969a2012-07-11 11:04:12 -0400426 except FlowExchangeError, e:
427 pass
428
Joe Gregorioccc79542011-02-19 00:05:26 -0500429 def test_exchange_success(self):
430 http = HttpMockSequence([
431 ({'status': '200'},
432 """{ "access_token":"SlAV32hkKG",
433 "expires_in":3600,
434 "refresh_token":"8xLOxBtZp8" }"""),
435 ])
436
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400437 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500438 self.assertEqual('SlAV32hkKG', credentials.access_token)
439 self.assertNotEqual(None, credentials.token_expiry)
440 self.assertEqual('8xLOxBtZp8', credentials.refresh_token)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800441 self.assertEqual('dummy_revoke_uri', credentials.revoke_uri)
Joe Gregorioccc79542011-02-19 00:05:26 -0500442
Joe Gregorioddb969a2012-07-11 11:04:12 -0400443 def test_urlencoded_exchange_success(self):
444 http = HttpMockSequence([
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800445 ({'status': '200'}, 'access_token=SlAV32hkKG&expires_in=3600'),
Joe Gregorioddb969a2012-07-11 11:04:12 -0400446 ])
447
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400448 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400449 self.assertEqual('SlAV32hkKG', credentials.access_token)
450 self.assertNotEqual(None, credentials.token_expiry)
451
452 def test_urlencoded_expires_param(self):
453 http = HttpMockSequence([
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800454 # Note the 'expires=3600' where you'd normally
455 # have if named 'expires_in'
456 ({'status': '200'}, 'access_token=SlAV32hkKG&expires=3600'),
Joe Gregorioddb969a2012-07-11 11:04:12 -0400457 ])
458
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400459 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400460 self.assertNotEqual(None, credentials.token_expiry)
461
Joe Gregorioccc79542011-02-19 00:05:26 -0500462 def test_exchange_no_expires_in(self):
463 http = HttpMockSequence([
464 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
465 "refresh_token":"8xLOxBtZp8" }"""),
466 ])
467
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400468 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500469 self.assertEqual(None, credentials.token_expiry)
Joe Gregorioccc79542011-02-19 00:05:26 -0500470
Joe Gregorioddb969a2012-07-11 11:04:12 -0400471 def test_urlencoded_exchange_no_expires_in(self):
472 http = HttpMockSequence([
473 # This might be redundant but just to make sure
474 # urlencoded access_token gets parsed correctly
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800475 ({'status': '200'}, 'access_token=SlAV32hkKG'),
Joe Gregorioddb969a2012-07-11 11:04:12 -0400476 ])
477
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400478 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorioddb969a2012-07-11 11:04:12 -0400479 self.assertEqual(None, credentials.token_expiry)
480
Joe Gregorio4b4002f2012-06-14 15:41:01 -0400481 def test_exchange_fails_if_no_code(self):
482 http = HttpMockSequence([
483 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
484 "refresh_token":"8xLOxBtZp8" }"""),
485 ])
486
487 code = {'error': 'thou shall not pass'}
488 try:
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400489 credentials = self.flow.step2_exchange(code, http=http)
Joe Gregorio4b4002f2012-06-14 15:41:01 -0400490 self.fail('should raise exception if no code in dictionary.')
491 except FlowExchangeError, e:
492 self.assertTrue('shall not pass' in str(e))
493
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500494 def test_exchange_id_token_fail(self):
495 http = HttpMockSequence([
496 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
497 "refresh_token":"8xLOxBtZp8",
498 "id_token": "stuff.payload"}"""),
499 ])
500
501 self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400502 'some random code', http=http)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500503
504 def test_exchange_id_token_fail(self):
505 body = {'foo': 'bar'}
506 payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
Joe Gregoriobd512b52011-12-06 15:39:26 -0500507 jwt = (base64.urlsafe_b64encode('stuff')+ '.' + payload + '.' +
508 base64.urlsafe_b64encode('signature'))
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500509
510 http = HttpMockSequence([
511 ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
512 "refresh_token":"8xLOxBtZp8",
513 "id_token": "%s"}""" % jwt),
514 ])
515
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400516 credentials = self.flow.step2_exchange('some random code', http=http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500517 self.assertEqual(credentials.id_token, body)
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500518
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400519
520class FlowFromCachedClientsecrets(unittest.TestCase):
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400521
522 def test_flow_from_clientsecrets_cached(self):
523 cache_mock = CacheMock()
524 load_and_cache('client_secrets.json', 'some_secrets', cache_mock)
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400525
526 flow = flow_from_clientsecrets(
527 'some_secrets', '', redirect_uri='oob', cache=cache_mock)
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400528 self.assertEquals('foo_client_secret', flow.client_secret)
529
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400530
Joe Gregorio32d852d2012-06-14 09:08:18 -0400531class CredentialsFromCodeTests(unittest.TestCase):
532 def setUp(self):
533 self.client_id = 'client_id_abc'
534 self.client_secret = 'secret_use_code'
535 self.scope = 'foo'
536 self.code = '12345abcde'
537 self.redirect_uri = 'postmessage'
538
539 def test_exchange_code_for_token(self):
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800540 token = 'asdfghjkl'
541 payload =simplejson.dumps({'access_token': token, 'expires_in': 3600})
Joe Gregorio32d852d2012-06-14 09:08:18 -0400542 http = HttpMockSequence([
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800543 ({'status': '200'}, payload),
Joe Gregorio32d852d2012-06-14 09:08:18 -0400544 ])
545 credentials = credentials_from_code(self.client_id, self.client_secret,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400546 self.scope, self.code, redirect_uri=self.redirect_uri,
547 http=http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800548 self.assertEquals(credentials.access_token, token)
Joe Gregorio32d852d2012-06-14 09:08:18 -0400549 self.assertNotEqual(None, credentials.token_expiry)
550
551 def test_exchange_code_for_token_fail(self):
552 http = HttpMockSequence([
553 ({'status': '400'}, '{"error":"invalid_request"}'),
554 ])
555
556 try:
557 credentials = credentials_from_code(self.client_id, self.client_secret,
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400558 self.scope, self.code, redirect_uri=self.redirect_uri,
559 http=http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800560 self.fail('should raise exception if exchange doesn\'t get 200')
Joe Gregorio32d852d2012-06-14 09:08:18 -0400561 except FlowExchangeError:
562 pass
563
Joe Gregorio32d852d2012-06-14 09:08:18 -0400564 def test_exchange_code_and_file_for_token(self):
565 http = HttpMockSequence([
566 ({'status': '200'},
567 """{ "access_token":"asdfghjkl",
568 "expires_in":3600 }"""),
569 ])
570 credentials = credentials_from_clientsecrets_and_code(
571 datafile('client_secrets.json'), self.scope,
572 self.code, http=http)
573 self.assertEquals(credentials.access_token, 'asdfghjkl')
574 self.assertNotEqual(None, credentials.token_expiry)
575
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400576 def test_exchange_code_and_cached_file_for_token(self):
577 http = HttpMockSequence([
578 ({'status': '200'}, '{ "access_token":"asdfghjkl"}'),
579 ])
580 cache_mock = CacheMock()
581 load_and_cache('client_secrets.json', 'some_secrets', cache_mock)
582
583 credentials = credentials_from_clientsecrets_and_code(
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800584 'some_secrets', self.scope,
585 self.code, http=http, cache=cache_mock)
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400586 self.assertEquals(credentials.access_token, 'asdfghjkl')
587
Joe Gregorio32d852d2012-06-14 09:08:18 -0400588 def test_exchange_code_and_file_for_token_fail(self):
589 http = HttpMockSequence([
590 ({'status': '400'}, '{"error":"invalid_request"}'),
591 ])
592
593 try:
594 credentials = credentials_from_clientsecrets_and_code(
595 datafile('client_secrets.json'), self.scope,
596 self.code, http=http)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800597 self.fail('should raise exception if exchange doesn\'t get 200')
Joe Gregorio32d852d2012-06-14 09:08:18 -0400598 except FlowExchangeError:
599 pass
600
601
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400602class MemoryCacheTests(unittest.TestCase):
603
604 def test_get_set_delete(self):
605 m = MemoryCache()
606 self.assertEqual(None, m.get('foo'))
607 self.assertEqual(None, m.delete('foo'))
608 m.set('foo', 'bar')
609 self.assertEqual('bar', m.get('foo'))
610 m.delete('foo')
611 self.assertEqual(None, m.get('foo'))
612
613
Joe Gregorioccc79542011-02-19 00:05:26 -0500614if __name__ == '__main__':
615 unittest.main()