blob: 2d95f08f75f610c9f8a81a5569b9460b6a8a2c0e [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
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -080055from oauth2client import GOOGLE_TOKEN_URI
Joe Gregorio549230c2012-01-11 10:38:05 -050056from oauth2client.anyjson import simplejson
Joe Gregorioc29aaa92012-07-16 16:16:31 -040057from oauth2client.clientsecrets import _loadfile
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040058from oauth2client.clientsecrets import InvalidClientSecretsError
JacobMoshenko8e905102011-06-20 09:53:10 -040059from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040060from oauth2client.appengine import CredentialsModel
dhermes@google.com47154822012-11-26 10:44:09 -080061from oauth2client.appengine import CredentialsNDBModel
62from oauth2client.appengine import FlowNDBProperty
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040063from oauth2client.appengine import FlowProperty
Joe Gregorio432f17e2011-05-22 23:18:00 -040064from oauth2client.appengine import OAuth2Decorator
Joe Gregorioe84c9442012-03-12 08:45:57 -040065from oauth2client.appengine import StorageByKeyName
Joe Gregorio08cdcb82012-03-14 00:09:33 -040066from oauth2client.appengine import oauth2decorator_from_clientsecrets
Joe Gregorio549230c2012-01-11 10:38:05 -050067from oauth2client.client import AccessTokenRefreshError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040068from oauth2client.client import Credentials
Joe Gregorio549230c2012-01-11 10:38:05 -050069from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040070from oauth2client.client import OAuth2Credentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040071from oauth2client.client import flow_from_clientsecrets
JacobMoshenko8e905102011-06-20 09:53:10 -040072from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040073
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040074
Joe Gregorio08cdcb82012-03-14 00:09:33 -040075DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
76
77
78def datafile(filename):
79 return os.path.join(DATA_DIR, filename)
80
81
Joe Gregorioc29aaa92012-07-16 16:16:31 -040082def load_and_cache(existing_file, fakename, cache_mock):
83 client_type, client_info = _loadfile(datafile(existing_file))
84 cache_mock.cache[fakename] = {client_type: client_info}
85
86
87class CacheMock(object):
88 def __init__(self):
89 self.cache = {}
90
91 def get(self, key, namespace=''):
92 # ignoring namespace for easier testing
93 return self.cache.get(key, None)
94
95 def set(self, key, value, namespace=''):
96 # ignoring namespace for easier testing
97 self.cache[key] = value
98
99
Joe Gregorio432f17e2011-05-22 23:18:00 -0400100class UserMock(object):
101 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -0400102
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400103 def __call__(self):
104 return self
105
Joe Gregorio432f17e2011-05-22 23:18:00 -0400106 def user_id(self):
107 return 'foo_user'
108
109
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400110class UserNotLoggedInMock(object):
111 """Mock the app engine user service"""
112
113 def __call__(self):
114 return None
115
116
Joe Gregorio432f17e2011-05-22 23:18:00 -0400117class Http2Mock(object):
118 """Mock httplib2.Http"""
119 status = 200
120 content = {
121 'access_token': 'foo_access_token',
122 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -0400123 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -0400124 }
125
126 def request(self, token_uri, method, body, headers, *args, **kwargs):
127 self.body = body
128 self.headers = headers
129 return (self, simplejson.dumps(self.content))
130
131
JacobMoshenko8e905102011-06-20 09:53:10 -0400132class TestAppAssertionCredentials(unittest.TestCase):
133 account_name = "service_account_name@appspot.com"
134 signature = "signature"
135
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500136
JacobMoshenko8e905102011-06-20 09:53:10 -0400137 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
138
139 def __init__(self):
140 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
141 'app_identity_service')
142
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500143 def _Dynamic_GetAccessToken(self, request, response):
144 response.set_access_token('a_token_123')
145 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400146
JacobMoshenko8e905102011-06-20 09:53:10 -0400147
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500148 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
149
150 def __init__(self):
151 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
152 'app_identity_service')
153
154 def _Dynamic_GetAccessToken(self, request, response):
155 raise app_identity.BackendDeadlineExceeded()
156
157 def test_raise_correct_type_of_exception(self):
158 app_identity_stub = self.ErroringAppIdentityStubImpl()
159 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800160 apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service',
JacobMoshenko8e905102011-06-20 09:53:10 -0400161 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500162 apiproxy_stub_map.apiproxy.RegisterStub(
163 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400164
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800165 scope = 'http://www.googleapis.com/scope'
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500166 try:
167 credentials = AppAssertionCredentials(scope)
168 http = httplib2.Http()
169 credentials.refresh(http)
170 self.fail('Should have raised an AccessTokenRefreshError')
171 except AccessTokenRefreshError:
172 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400173
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500174 def test_get_access_token_on_refresh(self):
175 app_identity_stub = self.AppIdentityStubImpl()
176 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
177 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
178 app_identity_stub)
179 apiproxy_stub_map.apiproxy.RegisterStub(
180 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400181
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500182 scope = [
183 "http://www.googleapis.com/scope",
184 "http://www.googleapis.com/scope2"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500185 credentials = AppAssertionCredentials(scope)
186 http = httplib2.Http()
187 credentials.refresh(http)
188 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400189
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400190 json = credentials.to_json()
191 credentials = Credentials.new_from_json(json)
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500192 self.assertEqual(
193 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
194 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400195
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500196 scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
197 credentials = AppAssertionCredentials(scope)
198 http = httplib2.Http()
199 credentials.refresh(http)
200 self.assertEqual('a_token_123', credentials.access_token)
201 self.assertEqual(
202 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
203 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400204
dhermes@google.com47154822012-11-26 10:44:09 -0800205
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400206class TestFlowModel(db.Model):
207 flow = FlowProperty()
208
209
210class FlowPropertyTest(unittest.TestCase):
211
212 def setUp(self):
213 self.testbed = testbed.Testbed()
214 self.testbed.activate()
215 self.testbed.init_datastore_v3_stub()
216
217 def tearDown(self):
218 self.testbed.deactivate()
219
220 def test_flow_get_put(self):
221 instance = TestFlowModel(
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400222 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
223 redirect_uri='oob'),
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400224 key_name='foo'
225 )
226 instance.put()
227 retrieved = TestFlowModel.get_by_key_name('foo')
228
229 self.assertEqual('foo_client_id', retrieved.flow.client_id)
230
JacobMoshenko8e905102011-06-20 09:53:10 -0400231
dhermes@google.com47154822012-11-26 10:44:09 -0800232class TestFlowNDBModel(ndb.Model):
233 flow = FlowNDBProperty()
234
235
236class FlowNDBPropertyTest(unittest.TestCase):
237
238 def setUp(self):
239 self.testbed = testbed.Testbed()
240 self.testbed.activate()
241 self.testbed.init_datastore_v3_stub()
242 self.testbed.init_memcache_stub()
243
244 def tearDown(self):
245 self.testbed.deactivate()
246
247 def test_flow_get_put(self):
248 instance = TestFlowNDBModel(
249 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
250 redirect_uri='oob'),
251 id='foo'
252 )
253 instance.put()
254 retrieved = TestFlowNDBModel.get_by_id('foo')
255
256 self.assertEqual('foo_client_id', retrieved.flow.client_id)
257
258
Joe Gregorioe84c9442012-03-12 08:45:57 -0400259def _http_request(*args, **kwargs):
260 resp = httplib2.Response({'status': '200'})
261 content = simplejson.dumps({'access_token': 'bar'})
262
263 return resp, content
264
265
266class StorageByKeyNameTest(unittest.TestCase):
267
268 def setUp(self):
269 self.testbed = testbed.Testbed()
270 self.testbed.activate()
271 self.testbed.init_datastore_v3_stub()
272 self.testbed.init_memcache_stub()
273 self.testbed.init_user_stub()
274
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800275 access_token = 'foo'
276 client_id = 'some_client_id'
277 client_secret = 'cOuDdkfjxxnv+'
278 refresh_token = '1/0/a.df219fjls0'
Joe Gregorioe84c9442012-03-12 08:45:57 -0400279 token_expiry = datetime.datetime.utcnow()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800280 user_agent = 'refresh_checker/1.0'
Joe Gregorioe84c9442012-03-12 08:45:57 -0400281 self.credentials = OAuth2Credentials(
282 access_token, client_id, client_secret,
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800283 refresh_token, token_expiry, GOOGLE_TOKEN_URI,
Joe Gregorioe84c9442012-03-12 08:45:57 -0400284 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()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800492 m.StubOutWithMock(appengine, '_parse_state_value')
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400493 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()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800534 m.StubOutWithMock(appengine, '_parse_state_value')
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400535 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()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800576 m.StubOutWithMock(appengine, '_parse_state_value')
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400577 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',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800619 approval_prompt='force',
620 revoke_uri='dummy_revoke_uri')
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400621 request_handler = MockRequestHandler()
622 decorator._create_flow(request_handler)
623
624 self.assertEqual('https://example.org/oauth2callback',
625 decorator.flow.redirect_uri)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500626 self.assertEqual('offline', decorator.flow.params['access_type'])
627 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100628 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800629 self.assertEqual('dummy_revoke_uri', decorator.flow.revoke_uri)
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100630 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500631
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400632 def test_decorator_from_client_secrets(self):
633 decorator = oauth2decorator_from_clientsecrets(
634 datafile('client_secrets.json'),
635 scope=['foo_scope', 'bar_scope'])
636 self._finish_setup(decorator, user_mock=UserMock)
637
638 self.assertFalse(decorator._in_error)
639 self.decorator = decorator
640 self.test_required()
641 http = self.decorator.http()
642 self.assertEquals('foo_access_token', http.request.credentials.access_token)
643
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800644 # revoke_uri is not required
645 self.assertEqual(self.decorator._revoke_uri,
646 'https://accounts.google.com/o/oauth2/revoke')
647 self.assertEqual(self.decorator._revoke_uri,
648 self.decorator.credentials.revoke_uri)
649
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400650 def test_decorator_from_cached_client_secrets(self):
651 cache_mock = CacheMock()
652 load_and_cache('client_secrets.json', 'secret', cache_mock)
653 decorator = oauth2decorator_from_clientsecrets(
654 # filename, scope, message=None, cache=None
655 'secret', '', cache=cache_mock)
656 self.assertFalse(decorator._in_error)
657
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400658 def test_decorator_from_client_secrets_not_logged_in_required(self):
659 decorator = oauth2decorator_from_clientsecrets(
660 datafile('client_secrets.json'),
661 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
662 self.decorator = decorator
663 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
664
665 self.assertFalse(decorator._in_error)
666
667 # An initial request to an oauth_required decorated path should be a
668 # redirect to login.
669 response = self.app.get('/foo_path')
670 self.assertTrue(response.status.startswith('302'))
671 self.assertTrue('Login' in str(response))
672
673 def test_decorator_from_client_secrets_not_logged_in_aware(self):
674 decorator = oauth2decorator_from_clientsecrets(
675 datafile('client_secrets.json'),
676 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
677 self.decorator = decorator
678 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
679
680 # An initial request to an oauth_aware decorated path should be a
681 # redirect to login.
682 response = self.app.get('/bar_path/2012/03')
683 self.assertTrue(response.status.startswith('302'))
684 self.assertTrue('Login' in str(response))
685
686 def test_decorator_from_unfilled_client_secrets_required(self):
687 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400688 try:
689 decorator = oauth2decorator_from_clientsecrets(
690 datafile('unfilled_client_secrets.json'),
691 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
692 except InvalidClientSecretsError:
693 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400694
695 def test_decorator_from_unfilled_client_secrets_aware(self):
696 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400697 try:
698 decorator = oauth2decorator_from_clientsecrets(
699 datafile('unfilled_client_secrets.json'),
700 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
701 except InvalidClientSecretsError:
702 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400703
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400704
705class DecoratorXsrfSecretTests(unittest.TestCase):
706 """Test xsrf_secret_key."""
707
708 def setUp(self):
709 self.testbed = testbed.Testbed()
710 self.testbed.activate()
711 self.testbed.init_datastore_v3_stub()
712 self.testbed.init_memcache_stub()
713
714 def tearDown(self):
715 self.testbed.deactivate()
716
717 def test_build_and_parse_state(self):
718 secret = appengine.xsrf_secret_key()
719
720 # Secret shouldn't change from call to call.
721 secret2 = appengine.xsrf_secret_key()
722 self.assertEqual(secret, secret2)
723
724 # Secret shouldn't change if memcache goes away.
725 memcache.delete(appengine.XSRF_MEMCACHE_ID,
dhermes@google.com47154822012-11-26 10:44:09 -0800726 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400727 secret3 = appengine.xsrf_secret_key()
728 self.assertEqual(secret2, secret3)
729
730 # Secret should change if both memcache and the model goes away.
731 memcache.delete(appengine.XSRF_MEMCACHE_ID,
dhermes@google.com47154822012-11-26 10:44:09 -0800732 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400733 model = appengine.SiteXsrfSecretKey.get_or_insert('site')
734 model.delete()
735
736 secret4 = appengine.xsrf_secret_key()
737 self.assertNotEqual(secret3, secret4)
738
dhermes@google.com47154822012-11-26 10:44:09 -0800739 def test_ndb_insert_db_get(self):
740 secret = appengine._generate_new_xsrf_secret_key()
741 appengine.SiteXsrfSecretKeyNDB(id='site', secret=secret).put()
742
743 site_key = appengine.SiteXsrfSecretKey.get_by_key_name('site')
744 self.assertEqual(site_key.secret, secret)
745
746 def test_db_insert_ndb_get(self):
747 secret = appengine._generate_new_xsrf_secret_key()
748 appengine.SiteXsrfSecretKey(key_name='site', secret=secret).put()
749
750 site_key = appengine.SiteXsrfSecretKeyNDB.get_by_id('site')
751 self.assertEqual(site_key.secret, secret)
752
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400753
754class DecoratorXsrfProtectionTests(unittest.TestCase):
755 """Test _build_state_value and _parse_state_value."""
756
757 def setUp(self):
758 self.testbed = testbed.Testbed()
759 self.testbed.activate()
760 self.testbed.init_datastore_v3_stub()
761 self.testbed.init_memcache_stub()
762
763 def tearDown(self):
764 self.testbed.deactivate()
765
766 def test_build_and_parse_state(self):
767 state = appengine._build_state_value(MockRequestHandler(), UserMock())
768 self.assertEqual(
769 'https://example.org',
770 appengine._parse_state_value(state, UserMock()))
771 self.assertRaises(appengine.InvalidXsrfTokenError,
772 appengine._parse_state_value, state[1:], UserMock())
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400773
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500774
Joe Gregorio432f17e2011-05-22 23:18:00 -0400775if __name__ == '__main__':
776 unittest.main()