blob: 870b5a8e5ab27158475b6e4a54a9770003817a2a [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
dhermes@google.com47154822012-11-26 10:44:09 -080051from google.appengine.ext import ndb
JacobMoshenko8e905102011-06-20 09:53:10 -040052from google.appengine.ext import testbed
Joe Gregoriod84d6b82012-02-28 14:53:00 -050053from google.appengine.runtime import apiproxy_errors
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040054from oauth2client import appengine
Joe Gregorio549230c2012-01-11 10:38:05 -050055from oauth2client.anyjson import simplejson
Joe Gregorioc29aaa92012-07-16 16:16:31 -040056from oauth2client.clientsecrets import _loadfile
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040057from oauth2client.clientsecrets import InvalidClientSecretsError
JacobMoshenko8e905102011-06-20 09:53:10 -040058from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040059from oauth2client.appengine import CredentialsModel
dhermes@google.com47154822012-11-26 10:44:09 -080060from oauth2client.appengine import CredentialsNDBModel
61from oauth2client.appengine import FlowNDBProperty
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040062from oauth2client.appengine import FlowProperty
Joe Gregorio432f17e2011-05-22 23:18:00 -040063from oauth2client.appengine import OAuth2Decorator
Joe Gregorioe84c9442012-03-12 08:45:57 -040064from oauth2client.appengine import StorageByKeyName
Joe Gregorio08cdcb82012-03-14 00:09:33 -040065from oauth2client.appengine import oauth2decorator_from_clientsecrets
Joe Gregorio549230c2012-01-11 10:38:05 -050066from oauth2client.client import AccessTokenRefreshError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040067from oauth2client.client import Credentials
Joe Gregorio549230c2012-01-11 10:38:05 -050068from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040069from oauth2client.client import OAuth2Credentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040070from oauth2client.client import flow_from_clientsecrets
JacobMoshenko8e905102011-06-20 09:53:10 -040071from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040072
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040073
Joe Gregorio08cdcb82012-03-14 00:09:33 -040074DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
75
76
77def datafile(filename):
78 return os.path.join(DATA_DIR, filename)
79
80
Joe Gregorioc29aaa92012-07-16 16:16:31 -040081def load_and_cache(existing_file, fakename, cache_mock):
82 client_type, client_info = _loadfile(datafile(existing_file))
83 cache_mock.cache[fakename] = {client_type: client_info}
84
85
86class CacheMock(object):
87 def __init__(self):
88 self.cache = {}
89
90 def get(self, key, namespace=''):
91 # ignoring namespace for easier testing
92 return self.cache.get(key, None)
93
94 def set(self, key, value, namespace=''):
95 # ignoring namespace for easier testing
96 self.cache[key] = value
97
98
Joe Gregorio432f17e2011-05-22 23:18:00 -040099class UserMock(object):
100 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -0400101
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400102 def __call__(self):
103 return self
104
Joe Gregorio432f17e2011-05-22 23:18:00 -0400105 def user_id(self):
106 return 'foo_user'
107
108
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400109class UserNotLoggedInMock(object):
110 """Mock the app engine user service"""
111
112 def __call__(self):
113 return None
114
115
Joe Gregorio432f17e2011-05-22 23:18:00 -0400116class Http2Mock(object):
117 """Mock httplib2.Http"""
118 status = 200
119 content = {
120 'access_token': 'foo_access_token',
121 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -0400122 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -0400123 }
124
125 def request(self, token_uri, method, body, headers, *args, **kwargs):
126 self.body = body
127 self.headers = headers
128 return (self, simplejson.dumps(self.content))
129
130
JacobMoshenko8e905102011-06-20 09:53:10 -0400131class TestAppAssertionCredentials(unittest.TestCase):
132 account_name = "service_account_name@appspot.com"
133 signature = "signature"
134
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500135
JacobMoshenko8e905102011-06-20 09:53:10 -0400136 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
137
138 def __init__(self):
139 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
140 'app_identity_service')
141
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500142 def _Dynamic_GetAccessToken(self, request, response):
143 response.set_access_token('a_token_123')
144 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400145
JacobMoshenko8e905102011-06-20 09:53:10 -0400146
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500147 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
148
149 def __init__(self):
150 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
151 'app_identity_service')
152
153 def _Dynamic_GetAccessToken(self, request, response):
154 raise app_identity.BackendDeadlineExceeded()
155
156 def test_raise_correct_type_of_exception(self):
157 app_identity_stub = self.ErroringAppIdentityStubImpl()
158 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400159 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
160 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500161 apiproxy_stub_map.apiproxy.RegisterStub(
162 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400163
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500164 scope = "http://www.googleapis.com/scope"
165 try:
166 credentials = AppAssertionCredentials(scope)
167 http = httplib2.Http()
168 credentials.refresh(http)
169 self.fail('Should have raised an AccessTokenRefreshError')
170 except AccessTokenRefreshError:
171 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400172
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500173 def test_get_access_token_on_refresh(self):
174 app_identity_stub = self.AppIdentityStubImpl()
175 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
176 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
177 app_identity_stub)
178 apiproxy_stub_map.apiproxy.RegisterStub(
179 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400180
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500181 scope = [
182 "http://www.googleapis.com/scope",
183 "http://www.googleapis.com/scope2"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500184 credentials = AppAssertionCredentials(scope)
185 http = httplib2.Http()
186 credentials.refresh(http)
187 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400188
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400189 json = credentials.to_json()
190 credentials = Credentials.new_from_json(json)
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500191 self.assertEqual(
192 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
193 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400194
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500195 scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
196 credentials = AppAssertionCredentials(scope)
197 http = httplib2.Http()
198 credentials.refresh(http)
199 self.assertEqual('a_token_123', credentials.access_token)
200 self.assertEqual(
201 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
202 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400203
dhermes@google.com47154822012-11-26 10:44:09 -0800204
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400205class TestFlowModel(db.Model):
206 flow = FlowProperty()
207
208
209class FlowPropertyTest(unittest.TestCase):
210
211 def setUp(self):
212 self.testbed = testbed.Testbed()
213 self.testbed.activate()
214 self.testbed.init_datastore_v3_stub()
215
216 def tearDown(self):
217 self.testbed.deactivate()
218
219 def test_flow_get_put(self):
220 instance = TestFlowModel(
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400221 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
222 redirect_uri='oob'),
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400223 key_name='foo'
224 )
225 instance.put()
226 retrieved = TestFlowModel.get_by_key_name('foo')
227
228 self.assertEqual('foo_client_id', retrieved.flow.client_id)
229
JacobMoshenko8e905102011-06-20 09:53:10 -0400230
dhermes@google.com47154822012-11-26 10:44:09 -0800231class TestFlowNDBModel(ndb.Model):
232 flow = FlowNDBProperty()
233
234
235class FlowNDBPropertyTest(unittest.TestCase):
236
237 def setUp(self):
238 self.testbed = testbed.Testbed()
239 self.testbed.activate()
240 self.testbed.init_datastore_v3_stub()
241 self.testbed.init_memcache_stub()
242
243 def tearDown(self):
244 self.testbed.deactivate()
245
246 def test_flow_get_put(self):
247 instance = TestFlowNDBModel(
248 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
249 redirect_uri='oob'),
250 id='foo'
251 )
252 instance.put()
253 retrieved = TestFlowNDBModel.get_by_id('foo')
254
255 self.assertEqual('foo_client_id', retrieved.flow.client_id)
256
257
Joe Gregorioe84c9442012-03-12 08:45:57 -0400258def _http_request(*args, **kwargs):
259 resp = httplib2.Response({'status': '200'})
260 content = simplejson.dumps({'access_token': 'bar'})
261
262 return resp, content
263
264
265class StorageByKeyNameTest(unittest.TestCase):
266
267 def setUp(self):
268 self.testbed = testbed.Testbed()
269 self.testbed.activate()
270 self.testbed.init_datastore_v3_stub()
271 self.testbed.init_memcache_stub()
272 self.testbed.init_user_stub()
273
274 access_token = "foo"
275 client_id = "some_client_id"
276 client_secret = "cOuDdkfjxxnv+"
277 refresh_token = "1/0/a.df219fjls0"
278 token_expiry = datetime.datetime.utcnow()
279 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
280 user_agent = "refresh_checker/1.0"
281 self.credentials = OAuth2Credentials(
282 access_token, client_id, client_secret,
283 refresh_token, token_expiry, token_uri,
284 user_agent)
285
286 def tearDown(self):
287 self.testbed.deactivate()
288
289 def test_get_and_put_simple(self):
290 storage = StorageByKeyName(
291 CredentialsModel, 'foo', 'credentials')
292
293 self.assertEqual(None, storage.get())
294 self.credentials.set_store(storage)
295
296 self.credentials._refresh(_http_request)
297 credmodel = CredentialsModel.get_by_key_name('foo')
298 self.assertEqual('bar', credmodel.credentials.access_token)
299
300 def test_get_and_put_cached(self):
301 storage = StorageByKeyName(
302 CredentialsModel, 'foo', 'credentials', cache=memcache)
303
304 self.assertEqual(None, storage.get())
305 self.credentials.set_store(storage)
306
307 self.credentials._refresh(_http_request)
308 credmodel = CredentialsModel.get_by_key_name('foo')
309 self.assertEqual('bar', credmodel.credentials.access_token)
310
311 # Now remove the item from the cache.
312 memcache.delete('foo')
313
314 # Check that getting refreshes the cache.
315 credentials = storage.get()
316 self.assertEqual('bar', credentials.access_token)
317 self.assertNotEqual(None, memcache.get('foo'))
318
319 # Deleting should clear the cache.
320 storage.delete()
321 credentials = storage.get()
322 self.assertEqual(None, credentials)
323 self.assertEqual(None, memcache.get('foo'))
324
dhermes@google.com47154822012-11-26 10:44:09 -0800325 def test_get_and_put_ndb(self):
326 # Start empty
327 storage = StorageByKeyName(
328 CredentialsNDBModel, 'foo', 'credentials')
329 self.assertEqual(None, storage.get())
330
331 # Refresh storage and retrieve without using storage
332 self.credentials.set_store(storage)
333 self.credentials._refresh(_http_request)
334 credmodel = CredentialsNDBModel.get_by_id('foo')
335 self.assertEqual('bar', credmodel.credentials.access_token)
336 self.assertEqual(credmodel.credentials.to_json(),
337 self.credentials.to_json())
338
339 def test_delete_ndb(self):
340 # Start empty
341 storage = StorageByKeyName(
342 CredentialsNDBModel, 'foo', 'credentials')
343 self.assertEqual(None, storage.get())
344
345 # Add credentials to model with storage, and check equivalent w/o storage
346 storage.put(self.credentials)
347 credmodel = CredentialsNDBModel.get_by_id('foo')
348 self.assertEqual(credmodel.credentials.to_json(),
349 self.credentials.to_json())
350
351 # Delete and make sure empty
352 storage.delete()
353 self.assertEqual(None, storage.get())
354
355 def test_get_and_put_mixed_ndb_storage_db_get(self):
356 # Start empty
357 storage = StorageByKeyName(
358 CredentialsNDBModel, 'foo', 'credentials')
359 self.assertEqual(None, storage.get())
360
361 # Set NDB store and refresh to add to storage
362 self.credentials.set_store(storage)
363 self.credentials._refresh(_http_request)
364
365 # Retrieve same key from DB model to confirm mixing works
366 credmodel = CredentialsModel.get_by_key_name('foo')
367 self.assertEqual('bar', credmodel.credentials.access_token)
368 self.assertEqual(self.credentials.to_json(),
369 credmodel.credentials.to_json())
370
371 def test_get_and_put_mixed_db_storage_ndb_get(self):
372 # Start empty
373 storage = StorageByKeyName(
374 CredentialsModel, 'foo', 'credentials')
375 self.assertEqual(None, storage.get())
376
377 # Set DB store and refresh to add to storage
378 self.credentials.set_store(storage)
379 self.credentials._refresh(_http_request)
380
381 # Retrieve same key from NDB model to confirm mixing works
382 credmodel = CredentialsNDBModel.get_by_id('foo')
383 self.assertEqual('bar', credmodel.credentials.access_token)
384 self.assertEqual(self.credentials.to_json(),
385 credmodel.credentials.to_json())
386
387 def test_delete_db_ndb_mixed(self):
388 # Start empty
389 storage_ndb = StorageByKeyName(
390 CredentialsNDBModel, 'foo', 'credentials')
391 storage = StorageByKeyName(
392 CredentialsModel, 'foo', 'credentials')
393
394 # First DB, then NDB
395 self.assertEqual(None, storage.get())
396 storage.put(self.credentials)
397 self.assertNotEqual(None, storage.get())
398
399 storage_ndb.delete()
400 self.assertEqual(None, storage.get())
401
402 # First NDB, then DB
403 self.assertEqual(None, storage_ndb.get())
404 storage_ndb.put(self.credentials)
405
406 storage.delete()
407 self.assertNotEqual(None, storage_ndb.get())
408 # NDB uses memcache and an instance cache (Context)
409 ndb.get_context().clear_cache()
410 memcache.flush_all()
411 self.assertEqual(None, storage_ndb.get())
412
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400413
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400414class MockRequest(object):
415 url = 'https://example.org'
416
417 def relative_url(self, rel):
418 return self.url + rel
419
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400420
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400421class MockRequestHandler(object):
422 request = MockRequest()
Joe Gregorioe84c9442012-03-12 08:45:57 -0400423
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400424
Joe Gregorio432f17e2011-05-22 23:18:00 -0400425class DecoratorTests(unittest.TestCase):
426
427 def setUp(self):
428 self.testbed = testbed.Testbed()
429 self.testbed.activate()
430 self.testbed.init_datastore_v3_stub()
431 self.testbed.init_memcache_stub()
432 self.testbed.init_user_stub()
433
434 decorator = OAuth2Decorator(client_id='foo_client_id',
435 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100436 scope=['foo_scope', 'bar_scope'],
437 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400438
439 self._finish_setup(decorator, user_mock=UserMock)
440
441 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400442 self.decorator = decorator
443
Joe Gregorio17774972012-03-01 11:11:59 -0500444 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400445
Joe Gregorio432f17e2011-05-22 23:18:00 -0400446 @decorator.oauth_required
447 def get(self):
448 pass
449
Joe Gregorio17774972012-03-01 11:11:59 -0500450 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400451
Joe Gregorio432f17e2011-05-22 23:18:00 -0400452 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500453 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400454 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500455 assert(kwargs['year'] == '2012')
456 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400457
458
Joe Gregorio17774972012-03-01 11:11:59 -0500459 application = webapp2.WSGIApplication([
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400460 ('/oauth2callback', self.decorator.callback_handler()),
Joe Gregorio17774972012-03-01 11:11:59 -0500461 ('/foo_path', TestRequiredHandler),
462 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
463 handler=TestAwareHandler, name='bar')],
464 debug=True)
Joe Gregorio77254c12012-08-27 14:13:22 -0400465 self.app = TestApp(application, extra_environ={
466 'wsgi.url_scheme': 'http',
467 'HTTP_HOST': 'localhost',
468 })
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400469 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400470 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400471 httplib2.Http = Http2Mock
472
473 def tearDown(self):
474 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400475 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400476
477 def test_required(self):
478 # An initial request to an oauth_required decorated path should be a
479 # redirect to start the OAuth dance.
Joe Gregorio77254c12012-08-27 14:13:22 -0400480 response = self.app.get('http://localhost/foo_path')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400481 self.assertTrue(response.status.startswith('302'))
482 q = parse_qs(response.headers['Location'].split('?', 1)[1])
483 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
484 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400485 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400486 self.assertEqual('http://localhost/foo_path',
487 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400488 self.assertEqual('code', q['response_type'][0])
489 self.assertEqual(False, self.decorator.has_credentials())
490
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400491 m = mox.Mox()
492 m.StubOutWithMock(appengine, "_parse_state_value")
493 appengine._parse_state_value('foo_path:xsrfkey123',
494 mox.IgnoreArg()).AndReturn('foo_path')
495 m.ReplayAll()
496
Joe Gregorio562b7312011-09-15 09:06:38 -0400497 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400498 response = self.app.get('/oauth2callback', {
499 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400500 'state': 'foo_path:xsrfkey123',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400501 })
502 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
503 self.assertEqual(None, self.decorator.credentials)
504
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400505 m.UnsetStubs()
506 m.VerifyAll()
507
Joe Gregorio562b7312011-09-15 09:06:38 -0400508 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400509 response = self.app.get('/foo_path')
510 self.assertEqual('200 OK', response.status)
511 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400512 self.assertEqual('foo_refresh_token',
513 self.decorator.credentials.refresh_token)
514 self.assertEqual('foo_access_token',
515 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400516
Joe Gregorio562b7312011-09-15 09:06:38 -0400517 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400518 self.decorator.credentials.invalid = True
519 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400520
Joe Gregorio562b7312011-09-15 09:06:38 -0400521 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400522 response = self.app.get('/foo_path')
523 self.assertTrue(response.status.startswith('302'))
524 q = parse_qs(response.headers['Location'].split('?', 1)[1])
525 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
526
Joe Gregorioec75dc12012-02-06 13:40:42 -0500527 def test_storage_delete(self):
528 # An initial request to an oauth_required decorated path should be a
529 # redirect to start the OAuth dance.
530 response = self.app.get('/foo_path')
531 self.assertTrue(response.status.startswith('302'))
532
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400533 m = mox.Mox()
534 m.StubOutWithMock(appengine, "_parse_state_value")
535 appengine._parse_state_value('foo_path:xsrfkey123',
536 mox.IgnoreArg()).AndReturn('foo_path')
537 m.ReplayAll()
538
Joe Gregorioec75dc12012-02-06 13:40:42 -0500539 # Now simulate the callback to /oauth2callback.
540 response = self.app.get('/oauth2callback', {
541 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400542 'state': 'foo_path:xsrfkey123',
Joe Gregorioec75dc12012-02-06 13:40:42 -0500543 })
544 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
545 self.assertEqual(None, self.decorator.credentials)
546
547 # Now requesting the decorated path should work.
548 response = self.app.get('/foo_path')
549
550 # Invalidate the stored Credentials.
551 self.decorator.credentials.store.delete()
552
553 # Invalid Credentials should start the OAuth dance again.
554 response = self.app.get('/foo_path')
555 self.assertTrue(response.status.startswith('302'))
556
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400557 m.UnsetStubs()
558 m.VerifyAll()
559
Joe Gregorio432f17e2011-05-22 23:18:00 -0400560 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400561 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio77254c12012-08-27 14:13:22 -0400562 response = self.app.get('http://localhost/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400563 self.assertEqual('Hello World!', response.body)
564 self.assertEqual('200 OK', response.status)
565 self.assertEqual(False, self.decorator.has_credentials())
566 url = self.decorator.authorize_url()
567 q = parse_qs(url.split('?', 1)[1])
568 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
569 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400570 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400571 self.assertEqual('http://localhost/bar_path/2012/01',
572 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400573 self.assertEqual('code', q['response_type'][0])
574
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400575 m = mox.Mox()
576 m.StubOutWithMock(appengine, "_parse_state_value")
577 appengine._parse_state_value('bar_path:xsrfkey456',
578 mox.IgnoreArg()).AndReturn('bar_path')
579 m.ReplayAll()
580
Joe Gregorio562b7312011-09-15 09:06:38 -0400581 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400582 url = self.decorator.authorize_url()
583 response = self.app.get('/oauth2callback', {
584 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400585 'state': 'bar_path:xsrfkey456',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400586 })
587 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
588 self.assertEqual(False, self.decorator.has_credentials())
589
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400590 m.UnsetStubs()
591 m.VerifyAll()
592
Joe Gregorio562b7312011-09-15 09:06:38 -0400593 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500594 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400595 self.assertEqual('200 OK', response.status)
596 self.assertEqual('Hello World!', response.body)
597 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400598 self.assertEqual('foo_refresh_token',
599 self.decorator.credentials.refresh_token)
600 self.assertEqual('foo_access_token',
601 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400602
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400603 def test_error_in_step2(self):
604 # An initial request to an oauth_aware decorated path should not redirect.
605 response = self.app.get('/bar_path/2012/01')
606 url = self.decorator.authorize_url()
607 response = self.app.get('/oauth2callback', {
Joe Gregorio77254c12012-08-27 14:13:22 -0400608 'error': 'Bad<Stuff>Happened\''
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400609 })
610 self.assertEqual('200 OK', response.status)
Joe Gregorio77254c12012-08-27 14:13:22 -0400611 self.assertTrue('Bad&lt;Stuff&gt;Happened&#39;' in response.body)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400612
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500613 def test_kwargs_are_passed_to_underlying_flow(self):
614 decorator = OAuth2Decorator(client_id='foo_client_id',
615 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100616 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500617 scope=['foo_scope', 'bar_scope'],
618 access_type='offline',
619 approval_prompt='force')
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400620 request_handler = MockRequestHandler()
621 decorator._create_flow(request_handler)
622
623 self.assertEqual('https://example.org/oauth2callback',
624 decorator.flow.redirect_uri)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500625 self.assertEqual('offline', decorator.flow.params['access_type'])
626 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100627 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
628 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500629
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400630 def test_decorator_from_client_secrets(self):
631 decorator = oauth2decorator_from_clientsecrets(
632 datafile('client_secrets.json'),
633 scope=['foo_scope', 'bar_scope'])
634 self._finish_setup(decorator, user_mock=UserMock)
635
636 self.assertFalse(decorator._in_error)
637 self.decorator = decorator
638 self.test_required()
639 http = self.decorator.http()
640 self.assertEquals('foo_access_token', http.request.credentials.access_token)
641
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400642 def test_decorator_from_cached_client_secrets(self):
643 cache_mock = CacheMock()
644 load_and_cache('client_secrets.json', 'secret', cache_mock)
645 decorator = oauth2decorator_from_clientsecrets(
646 # filename, scope, message=None, cache=None
647 'secret', '', cache=cache_mock)
648 self.assertFalse(decorator._in_error)
649
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400650 def test_decorator_from_client_secrets_not_logged_in_required(self):
651 decorator = oauth2decorator_from_clientsecrets(
652 datafile('client_secrets.json'),
653 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
654 self.decorator = decorator
655 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
656
657 self.assertFalse(decorator._in_error)
658
659 # An initial request to an oauth_required decorated path should be a
660 # redirect to login.
661 response = self.app.get('/foo_path')
662 self.assertTrue(response.status.startswith('302'))
663 self.assertTrue('Login' in str(response))
664
665 def test_decorator_from_client_secrets_not_logged_in_aware(self):
666 decorator = oauth2decorator_from_clientsecrets(
667 datafile('client_secrets.json'),
668 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
669 self.decorator = decorator
670 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
671
672 # An initial request to an oauth_aware decorated path should be a
673 # redirect to login.
674 response = self.app.get('/bar_path/2012/03')
675 self.assertTrue(response.status.startswith('302'))
676 self.assertTrue('Login' in str(response))
677
678 def test_decorator_from_unfilled_client_secrets_required(self):
679 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400680 try:
681 decorator = oauth2decorator_from_clientsecrets(
682 datafile('unfilled_client_secrets.json'),
683 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
684 except InvalidClientSecretsError:
685 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400686
687 def test_decorator_from_unfilled_client_secrets_aware(self):
688 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400689 try:
690 decorator = oauth2decorator_from_clientsecrets(
691 datafile('unfilled_client_secrets.json'),
692 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
693 except InvalidClientSecretsError:
694 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400695
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400696
697class DecoratorXsrfSecretTests(unittest.TestCase):
698 """Test xsrf_secret_key."""
699
700 def setUp(self):
701 self.testbed = testbed.Testbed()
702 self.testbed.activate()
703 self.testbed.init_datastore_v3_stub()
704 self.testbed.init_memcache_stub()
705
706 def tearDown(self):
707 self.testbed.deactivate()
708
709 def test_build_and_parse_state(self):
710 secret = appengine.xsrf_secret_key()
711
712 # Secret shouldn't change from call to call.
713 secret2 = appengine.xsrf_secret_key()
714 self.assertEqual(secret, secret2)
715
716 # Secret shouldn't change if memcache goes away.
717 memcache.delete(appengine.XSRF_MEMCACHE_ID,
dhermes@google.com47154822012-11-26 10:44:09 -0800718 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400719 secret3 = appengine.xsrf_secret_key()
720 self.assertEqual(secret2, secret3)
721
722 # Secret should change if both memcache and the model goes away.
723 memcache.delete(appengine.XSRF_MEMCACHE_ID,
dhermes@google.com47154822012-11-26 10:44:09 -0800724 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400725 model = appengine.SiteXsrfSecretKey.get_or_insert('site')
726 model.delete()
727
728 secret4 = appengine.xsrf_secret_key()
729 self.assertNotEqual(secret3, secret4)
730
dhermes@google.com47154822012-11-26 10:44:09 -0800731 def test_ndb_insert_db_get(self):
732 secret = appengine._generate_new_xsrf_secret_key()
733 appengine.SiteXsrfSecretKeyNDB(id='site', secret=secret).put()
734
735 site_key = appengine.SiteXsrfSecretKey.get_by_key_name('site')
736 self.assertEqual(site_key.secret, secret)
737
738 def test_db_insert_ndb_get(self):
739 secret = appengine._generate_new_xsrf_secret_key()
740 appengine.SiteXsrfSecretKey(key_name='site', secret=secret).put()
741
742 site_key = appengine.SiteXsrfSecretKeyNDB.get_by_id('site')
743 self.assertEqual(site_key.secret, secret)
744
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400745
746class DecoratorXsrfProtectionTests(unittest.TestCase):
747 """Test _build_state_value and _parse_state_value."""
748
749 def setUp(self):
750 self.testbed = testbed.Testbed()
751 self.testbed.activate()
752 self.testbed.init_datastore_v3_stub()
753 self.testbed.init_memcache_stub()
754
755 def tearDown(self):
756 self.testbed.deactivate()
757
758 def test_build_and_parse_state(self):
759 state = appengine._build_state_value(MockRequestHandler(), UserMock())
760 self.assertEqual(
761 'https://example.org',
762 appengine._parse_state_value(state, UserMock()))
763 self.assertRaises(appengine.InvalidXsrfTokenError,
764 appengine._parse_state_value, state[1:], UserMock())
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400765
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500766
Joe Gregorio432f17e2011-05-22 23:18:00 -0400767if __name__ == '__main__':
768 unittest.main()