blob: 6039a0d3fdf10128386443551be4ce6a48d2eca4 [file] [log] [blame]
Joe Gregorio432f17e2011-05-22 23:18:00 -04001#!/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"""Discovery document tests
19
20Unit tests for objects created from discovery documents.
21"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
JacobMoshenko8e905102011-06-20 09:53:10 -040025import base64
Joe Gregorioe84c9442012-03-12 08:45:57 -040026import datetime
Joe Gregorio432f17e2011-05-22 23:18:00 -040027import httplib2
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040028import mox
Joe Gregorio08cdcb82012-03-14 00:09:33 -040029import os
Joe Gregoriod84d6b82012-02-28 14:53:00 -050030import time
Joe Gregorio432f17e2011-05-22 23:18:00 -040031import unittest
32import urlparse
33
34try:
35 from urlparse import parse_qs
36except ImportError:
37 from cgi import parse_qs
38
Joe Gregorio8b4c1732011-12-06 11:28:29 -050039import dev_appserver
40dev_appserver.fix_sys_path()
Joe Gregorio17774972012-03-01 11:11:59 -050041import webapp2
Joe Gregorio8b4c1732011-12-06 11:28:29 -050042
JacobMoshenko8e905102011-06-20 09:53:10 -040043from apiclient.http import HttpMockSequence
44from google.appengine.api import apiproxy_stub
45from google.appengine.api import apiproxy_stub_map
Joe Gregoriod84d6b82012-02-28 14:53:00 -050046from google.appengine.api import app_identity
Joe Gregorioe84c9442012-03-12 08:45:57 -040047from google.appengine.api import memcache
Joe Gregorio08cdcb82012-03-14 00:09:33 -040048from google.appengine.api import users
Joe Gregoriod84d6b82012-02-28 14:53:00 -050049from google.appengine.api.memcache import memcache_stub
Joe Gregorioe84c9442012-03-12 08:45:57 -040050from google.appengine.ext import db
JacobMoshenko8e905102011-06-20 09:53:10 -040051from google.appengine.ext import testbed
Joe Gregoriod84d6b82012-02-28 14:53:00 -050052from google.appengine.runtime import apiproxy_errors
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040053from oauth2client import appengine
Joe Gregorio549230c2012-01-11 10:38:05 -050054from oauth2client.anyjson import simplejson
Joe Gregorioc29aaa92012-07-16 16:16:31 -040055from oauth2client.clientsecrets import _loadfile
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040056from oauth2client.clientsecrets import InvalidClientSecretsError
JacobMoshenko8e905102011-06-20 09:53:10 -040057from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040058from oauth2client.appengine import CredentialsModel
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040059from oauth2client.appengine import FlowProperty
Joe Gregorio432f17e2011-05-22 23:18:00 -040060from oauth2client.appengine import OAuth2Decorator
Joe Gregorioe84c9442012-03-12 08:45:57 -040061from oauth2client.appengine import StorageByKeyName
Joe Gregorio08cdcb82012-03-14 00:09:33 -040062from oauth2client.appengine import oauth2decorator_from_clientsecrets
Joe Gregorio549230c2012-01-11 10:38:05 -050063from oauth2client.client import AccessTokenRefreshError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040064from oauth2client.client import Credentials
Joe Gregorio549230c2012-01-11 10:38:05 -050065from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040066from oauth2client.client import OAuth2Credentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040067from oauth2client.client import flow_from_clientsecrets
JacobMoshenko8e905102011-06-20 09:53:10 -040068from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040069
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040070
Joe Gregorio08cdcb82012-03-14 00:09:33 -040071DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
72
73
74def datafile(filename):
75 return os.path.join(DATA_DIR, filename)
76
77
Joe Gregorioc29aaa92012-07-16 16:16:31 -040078def load_and_cache(existing_file, fakename, cache_mock):
79 client_type, client_info = _loadfile(datafile(existing_file))
80 cache_mock.cache[fakename] = {client_type: client_info}
81
82
83class CacheMock(object):
84 def __init__(self):
85 self.cache = {}
86
87 def get(self, key, namespace=''):
88 # ignoring namespace for easier testing
89 return self.cache.get(key, None)
90
91 def set(self, key, value, namespace=''):
92 # ignoring namespace for easier testing
93 self.cache[key] = value
94
95
Joe Gregorio432f17e2011-05-22 23:18:00 -040096class UserMock(object):
97 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040098
Joe Gregorio08cdcb82012-03-14 00:09:33 -040099 def __call__(self):
100 return self
101
Joe Gregorio432f17e2011-05-22 23:18:00 -0400102 def user_id(self):
103 return 'foo_user'
104
105
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400106class UserNotLoggedInMock(object):
107 """Mock the app engine user service"""
108
109 def __call__(self):
110 return None
111
112
Joe Gregorio432f17e2011-05-22 23:18:00 -0400113class Http2Mock(object):
114 """Mock httplib2.Http"""
115 status = 200
116 content = {
117 'access_token': 'foo_access_token',
118 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -0400119 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -0400120 }
121
122 def request(self, token_uri, method, body, headers, *args, **kwargs):
123 self.body = body
124 self.headers = headers
125 return (self, simplejson.dumps(self.content))
126
127
JacobMoshenko8e905102011-06-20 09:53:10 -0400128class TestAppAssertionCredentials(unittest.TestCase):
129 account_name = "service_account_name@appspot.com"
130 signature = "signature"
131
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500132
JacobMoshenko8e905102011-06-20 09:53:10 -0400133 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
134
135 def __init__(self):
136 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
137 'app_identity_service')
138
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500139 def _Dynamic_GetAccessToken(self, request, response):
140 response.set_access_token('a_token_123')
141 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400142
JacobMoshenko8e905102011-06-20 09:53:10 -0400143
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500144 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
145
146 def __init__(self):
147 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
148 'app_identity_service')
149
150 def _Dynamic_GetAccessToken(self, request, response):
151 raise app_identity.BackendDeadlineExceeded()
152
153 def test_raise_correct_type_of_exception(self):
154 app_identity_stub = self.ErroringAppIdentityStubImpl()
155 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400156 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
157 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500158 apiproxy_stub_map.apiproxy.RegisterStub(
159 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400160
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500161 scope = "http://www.googleapis.com/scope"
162 try:
163 credentials = AppAssertionCredentials(scope)
164 http = httplib2.Http()
165 credentials.refresh(http)
166 self.fail('Should have raised an AccessTokenRefreshError')
167 except AccessTokenRefreshError:
168 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400169
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500170 def test_get_access_token_on_refresh(self):
171 app_identity_stub = self.AppIdentityStubImpl()
172 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
173 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
174 app_identity_stub)
175 apiproxy_stub_map.apiproxy.RegisterStub(
176 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400177
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400178 scope = ["http://www.googleapis.com/scope"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500179 credentials = AppAssertionCredentials(scope)
180 http = httplib2.Http()
181 credentials.refresh(http)
182 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400183
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400184 json = credentials.to_json()
185 credentials = Credentials.new_from_json(json)
186 self.assertEqual(scope[0], credentials.scope)
187
188
189class TestFlowModel(db.Model):
190 flow = FlowProperty()
191
192
193class FlowPropertyTest(unittest.TestCase):
194
195 def setUp(self):
196 self.testbed = testbed.Testbed()
197 self.testbed.activate()
198 self.testbed.init_datastore_v3_stub()
199
200 def tearDown(self):
201 self.testbed.deactivate()
202
203 def test_flow_get_put(self):
204 instance = TestFlowModel(
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400205 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
206 redirect_uri='oob'),
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400207 key_name='foo'
208 )
209 instance.put()
210 retrieved = TestFlowModel.get_by_key_name('foo')
211
212 self.assertEqual('foo_client_id', retrieved.flow.client_id)
213
JacobMoshenko8e905102011-06-20 09:53:10 -0400214
Joe Gregorioe84c9442012-03-12 08:45:57 -0400215def _http_request(*args, **kwargs):
216 resp = httplib2.Response({'status': '200'})
217 content = simplejson.dumps({'access_token': 'bar'})
218
219 return resp, content
220
221
222class StorageByKeyNameTest(unittest.TestCase):
223
224 def setUp(self):
225 self.testbed = testbed.Testbed()
226 self.testbed.activate()
227 self.testbed.init_datastore_v3_stub()
228 self.testbed.init_memcache_stub()
229 self.testbed.init_user_stub()
230
231 access_token = "foo"
232 client_id = "some_client_id"
233 client_secret = "cOuDdkfjxxnv+"
234 refresh_token = "1/0/a.df219fjls0"
235 token_expiry = datetime.datetime.utcnow()
236 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
237 user_agent = "refresh_checker/1.0"
238 self.credentials = OAuth2Credentials(
239 access_token, client_id, client_secret,
240 refresh_token, token_expiry, token_uri,
241 user_agent)
242
243 def tearDown(self):
244 self.testbed.deactivate()
245
246 def test_get_and_put_simple(self):
247 storage = StorageByKeyName(
248 CredentialsModel, 'foo', 'credentials')
249
250 self.assertEqual(None, storage.get())
251 self.credentials.set_store(storage)
252
253 self.credentials._refresh(_http_request)
254 credmodel = CredentialsModel.get_by_key_name('foo')
255 self.assertEqual('bar', credmodel.credentials.access_token)
256
257 def test_get_and_put_cached(self):
258 storage = StorageByKeyName(
259 CredentialsModel, 'foo', 'credentials', cache=memcache)
260
261 self.assertEqual(None, storage.get())
262 self.credentials.set_store(storage)
263
264 self.credentials._refresh(_http_request)
265 credmodel = CredentialsModel.get_by_key_name('foo')
266 self.assertEqual('bar', credmodel.credentials.access_token)
267
268 # Now remove the item from the cache.
269 memcache.delete('foo')
270
271 # Check that getting refreshes the cache.
272 credentials = storage.get()
273 self.assertEqual('bar', credentials.access_token)
274 self.assertNotEqual(None, memcache.get('foo'))
275
276 # Deleting should clear the cache.
277 storage.delete()
278 credentials = storage.get()
279 self.assertEqual(None, credentials)
280 self.assertEqual(None, memcache.get('foo'))
281
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400282
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400283class MockRequest(object):
284 url = 'https://example.org'
285
286 def relative_url(self, rel):
287 return self.url + rel
288
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400289
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400290class MockRequestHandler(object):
291 request = MockRequest()
Joe Gregorioe84c9442012-03-12 08:45:57 -0400292
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400293
Joe Gregorio432f17e2011-05-22 23:18:00 -0400294class DecoratorTests(unittest.TestCase):
295
296 def setUp(self):
297 self.testbed = testbed.Testbed()
298 self.testbed.activate()
299 self.testbed.init_datastore_v3_stub()
300 self.testbed.init_memcache_stub()
301 self.testbed.init_user_stub()
302
303 decorator = OAuth2Decorator(client_id='foo_client_id',
304 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100305 scope=['foo_scope', 'bar_scope'],
306 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400307
308 self._finish_setup(decorator, user_mock=UserMock)
309
310 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400311 self.decorator = decorator
312
Joe Gregorio17774972012-03-01 11:11:59 -0500313 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400314
Joe Gregorio432f17e2011-05-22 23:18:00 -0400315 @decorator.oauth_required
316 def get(self):
317 pass
318
Joe Gregorio17774972012-03-01 11:11:59 -0500319 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400320
Joe Gregorio432f17e2011-05-22 23:18:00 -0400321 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500322 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400323 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500324 assert(kwargs['year'] == '2012')
325 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400326
327
Joe Gregorio17774972012-03-01 11:11:59 -0500328 application = webapp2.WSGIApplication([
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400329 ('/oauth2callback', self.decorator.callback_handler()),
Joe Gregorio17774972012-03-01 11:11:59 -0500330 ('/foo_path', TestRequiredHandler),
331 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
332 handler=TestAwareHandler, name='bar')],
333 debug=True)
Joe Gregorio77254c12012-08-27 14:13:22 -0400334 self.app = TestApp(application, extra_environ={
335 'wsgi.url_scheme': 'http',
336 'HTTP_HOST': 'localhost',
337 })
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400338 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400339 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400340 httplib2.Http = Http2Mock
341
342 def tearDown(self):
343 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400344 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400345
346 def test_required(self):
347 # An initial request to an oauth_required decorated path should be a
348 # redirect to start the OAuth dance.
Joe Gregorio77254c12012-08-27 14:13:22 -0400349 response = self.app.get('http://localhost/foo_path')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400350 self.assertTrue(response.status.startswith('302'))
351 q = parse_qs(response.headers['Location'].split('?', 1)[1])
352 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
353 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400354 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400355 self.assertEqual('http://localhost/foo_path',
356 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400357 self.assertEqual('code', q['response_type'][0])
358 self.assertEqual(False, self.decorator.has_credentials())
359
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400360 m = mox.Mox()
361 m.StubOutWithMock(appengine, "_parse_state_value")
362 appengine._parse_state_value('foo_path:xsrfkey123',
363 mox.IgnoreArg()).AndReturn('foo_path')
364 m.ReplayAll()
365
Joe Gregorio562b7312011-09-15 09:06:38 -0400366 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400367 response = self.app.get('/oauth2callback', {
368 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400369 'state': 'foo_path:xsrfkey123',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400370 })
371 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
372 self.assertEqual(None, self.decorator.credentials)
373
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400374 m.UnsetStubs()
375 m.VerifyAll()
376
Joe Gregorio562b7312011-09-15 09:06:38 -0400377 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400378 response = self.app.get('/foo_path')
379 self.assertEqual('200 OK', response.status)
380 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400381 self.assertEqual('foo_refresh_token',
382 self.decorator.credentials.refresh_token)
383 self.assertEqual('foo_access_token',
384 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400385
Joe Gregorio562b7312011-09-15 09:06:38 -0400386 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400387 self.decorator.credentials.invalid = True
388 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400389
Joe Gregorio562b7312011-09-15 09:06:38 -0400390 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400391 response = self.app.get('/foo_path')
392 self.assertTrue(response.status.startswith('302'))
393 q = parse_qs(response.headers['Location'].split('?', 1)[1])
394 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
395
Joe Gregorioec75dc12012-02-06 13:40:42 -0500396 def test_storage_delete(self):
397 # An initial request to an oauth_required decorated path should be a
398 # redirect to start the OAuth dance.
399 response = self.app.get('/foo_path')
400 self.assertTrue(response.status.startswith('302'))
401
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400402 m = mox.Mox()
403 m.StubOutWithMock(appengine, "_parse_state_value")
404 appengine._parse_state_value('foo_path:xsrfkey123',
405 mox.IgnoreArg()).AndReturn('foo_path')
406 m.ReplayAll()
407
Joe Gregorioec75dc12012-02-06 13:40:42 -0500408 # Now simulate the callback to /oauth2callback.
409 response = self.app.get('/oauth2callback', {
410 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400411 'state': 'foo_path:xsrfkey123',
Joe Gregorioec75dc12012-02-06 13:40:42 -0500412 })
413 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
414 self.assertEqual(None, self.decorator.credentials)
415
416 # Now requesting the decorated path should work.
417 response = self.app.get('/foo_path')
418
419 # Invalidate the stored Credentials.
420 self.decorator.credentials.store.delete()
421
422 # Invalid Credentials should start the OAuth dance again.
423 response = self.app.get('/foo_path')
424 self.assertTrue(response.status.startswith('302'))
425
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400426 m.UnsetStubs()
427 m.VerifyAll()
428
Joe Gregorio432f17e2011-05-22 23:18:00 -0400429 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400430 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio77254c12012-08-27 14:13:22 -0400431 response = self.app.get('http://localhost/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400432 self.assertEqual('Hello World!', response.body)
433 self.assertEqual('200 OK', response.status)
434 self.assertEqual(False, self.decorator.has_credentials())
435 url = self.decorator.authorize_url()
436 q = parse_qs(url.split('?', 1)[1])
437 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
438 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400439 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400440 self.assertEqual('http://localhost/bar_path/2012/01',
441 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400442 self.assertEqual('code', q['response_type'][0])
443
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400444 m = mox.Mox()
445 m.StubOutWithMock(appengine, "_parse_state_value")
446 appengine._parse_state_value('bar_path:xsrfkey456',
447 mox.IgnoreArg()).AndReturn('bar_path')
448 m.ReplayAll()
449
Joe Gregorio562b7312011-09-15 09:06:38 -0400450 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400451 url = self.decorator.authorize_url()
452 response = self.app.get('/oauth2callback', {
453 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400454 'state': 'bar_path:xsrfkey456',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400455 })
456 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
457 self.assertEqual(False, self.decorator.has_credentials())
458
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400459 m.UnsetStubs()
460 m.VerifyAll()
461
Joe Gregorio562b7312011-09-15 09:06:38 -0400462 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500463 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400464 self.assertEqual('200 OK', response.status)
465 self.assertEqual('Hello World!', response.body)
466 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400467 self.assertEqual('foo_refresh_token',
468 self.decorator.credentials.refresh_token)
469 self.assertEqual('foo_access_token',
470 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400471
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400472 def test_error_in_step2(self):
473 # An initial request to an oauth_aware decorated path should not redirect.
474 response = self.app.get('/bar_path/2012/01')
475 url = self.decorator.authorize_url()
476 response = self.app.get('/oauth2callback', {
Joe Gregorio77254c12012-08-27 14:13:22 -0400477 'error': 'Bad<Stuff>Happened\''
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400478 })
479 self.assertEqual('200 OK', response.status)
Joe Gregorio77254c12012-08-27 14:13:22 -0400480 self.assertTrue('Bad&lt;Stuff&gt;Happened&#39;' in response.body)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400481
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500482 def test_kwargs_are_passed_to_underlying_flow(self):
483 decorator = OAuth2Decorator(client_id='foo_client_id',
484 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100485 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500486 scope=['foo_scope', 'bar_scope'],
487 access_type='offline',
488 approval_prompt='force')
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400489 request_handler = MockRequestHandler()
490 decorator._create_flow(request_handler)
491
492 self.assertEqual('https://example.org/oauth2callback',
493 decorator.flow.redirect_uri)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500494 self.assertEqual('offline', decorator.flow.params['access_type'])
495 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100496 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
497 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500498
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400499 def test_decorator_from_client_secrets(self):
500 decorator = oauth2decorator_from_clientsecrets(
501 datafile('client_secrets.json'),
502 scope=['foo_scope', 'bar_scope'])
503 self._finish_setup(decorator, user_mock=UserMock)
504
505 self.assertFalse(decorator._in_error)
506 self.decorator = decorator
507 self.test_required()
508 http = self.decorator.http()
509 self.assertEquals('foo_access_token', http.request.credentials.access_token)
510
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400511 def test_decorator_from_cached_client_secrets(self):
512 cache_mock = CacheMock()
513 load_and_cache('client_secrets.json', 'secret', cache_mock)
514 decorator = oauth2decorator_from_clientsecrets(
515 # filename, scope, message=None, cache=None
516 'secret', '', cache=cache_mock)
517 self.assertFalse(decorator._in_error)
518
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400519 def test_decorator_from_client_secrets_not_logged_in_required(self):
520 decorator = oauth2decorator_from_clientsecrets(
521 datafile('client_secrets.json'),
522 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
523 self.decorator = decorator
524 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
525
526 self.assertFalse(decorator._in_error)
527
528 # An initial request to an oauth_required decorated path should be a
529 # redirect to login.
530 response = self.app.get('/foo_path')
531 self.assertTrue(response.status.startswith('302'))
532 self.assertTrue('Login' in str(response))
533
534 def test_decorator_from_client_secrets_not_logged_in_aware(self):
535 decorator = oauth2decorator_from_clientsecrets(
536 datafile('client_secrets.json'),
537 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
538 self.decorator = decorator
539 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
540
541 # An initial request to an oauth_aware decorated path should be a
542 # redirect to login.
543 response = self.app.get('/bar_path/2012/03')
544 self.assertTrue(response.status.startswith('302'))
545 self.assertTrue('Login' in str(response))
546
547 def test_decorator_from_unfilled_client_secrets_required(self):
548 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400549 try:
550 decorator = oauth2decorator_from_clientsecrets(
551 datafile('unfilled_client_secrets.json'),
552 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
553 except InvalidClientSecretsError:
554 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400555
556 def test_decorator_from_unfilled_client_secrets_aware(self):
557 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400558 try:
559 decorator = oauth2decorator_from_clientsecrets(
560 datafile('unfilled_client_secrets.json'),
561 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
562 except InvalidClientSecretsError:
563 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400564
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400565
566class DecoratorXsrfSecretTests(unittest.TestCase):
567 """Test xsrf_secret_key."""
568
569 def setUp(self):
570 self.testbed = testbed.Testbed()
571 self.testbed.activate()
572 self.testbed.init_datastore_v3_stub()
573 self.testbed.init_memcache_stub()
574
575 def tearDown(self):
576 self.testbed.deactivate()
577
578 def test_build_and_parse_state(self):
579 secret = appengine.xsrf_secret_key()
580
581 # Secret shouldn't change from call to call.
582 secret2 = appengine.xsrf_secret_key()
583 self.assertEqual(secret, secret2)
584
585 # Secret shouldn't change if memcache goes away.
586 memcache.delete(appengine.XSRF_MEMCACHE_ID,
587 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
588 secret3 = appengine.xsrf_secret_key()
589 self.assertEqual(secret2, secret3)
590
591 # Secret should change if both memcache and the model goes away.
592 memcache.delete(appengine.XSRF_MEMCACHE_ID,
593 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
594 model = appengine.SiteXsrfSecretKey.get_or_insert('site')
595 model.delete()
596
597 secret4 = appengine.xsrf_secret_key()
598 self.assertNotEqual(secret3, secret4)
599
600
601class DecoratorXsrfProtectionTests(unittest.TestCase):
602 """Test _build_state_value and _parse_state_value."""
603
604 def setUp(self):
605 self.testbed = testbed.Testbed()
606 self.testbed.activate()
607 self.testbed.init_datastore_v3_stub()
608 self.testbed.init_memcache_stub()
609
610 def tearDown(self):
611 self.testbed.deactivate()
612
613 def test_build_and_parse_state(self):
614 state = appengine._build_state_value(MockRequestHandler(), UserMock())
615 self.assertEqual(
616 'https://example.org',
617 appengine._parse_state_value(state, UserMock()))
618 self.assertRaises(appengine.InvalidXsrfTokenError,
619 appengine._parse_state_value, state[1:], UserMock())
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400620
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500621
Joe Gregorio432f17e2011-05-22 23:18:00 -0400622if __name__ == '__main__':
623 unittest.main()