blob: 4b2c41462dc6f6b7a5d5299072a4848901eb1816 [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
Joe Gregoriocda87522013-02-22 16:22:48 -050032import urllib
Joe Gregorio432f17e2011-05-22 23:18:00 -040033
34try:
Daniel Hermesb7c5a402013-04-05 09:32:45 -070035 from urlparse import parse_qs
Joe Gregorio432f17e2011-05-22 23:18:00 -040036except ImportError:
Daniel Hermesb7c5a402013-04-05 09:32:45 -070037 from cgi import parse_qs
Joe Gregorio432f17e2011-05-22 23:18:00 -040038
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):
Daniel Hermesb7c5a402013-04-05 09:32:45 -070088 def __init__(self):
89 self.cache = {}
Joe Gregorioc29aaa92012-07-16 16:16:31 -040090
Daniel Hermesb7c5a402013-04-05 09:32:45 -070091 def get(self, key, namespace=''):
92 # ignoring namespace for easier testing
93 return self.cache.get(key, None)
Joe Gregorioc29aaa92012-07-16 16:16:31 -040094
Daniel Hermesb7c5a402013-04-05 09:32:45 -070095 def set(self, key, value, namespace=''):
96 # ignoring namespace for easier testing
97 self.cache[key] = value
Joe Gregorioc29aaa92012-07-16 16:16:31 -040098
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 Gregoriocda87522013-02-22 16:22:48 -0500124 'extra': 'value',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400125 }
126
127 def request(self, token_uri, method, body, headers, *args, **kwargs):
128 self.body = body
129 self.headers = headers
130 return (self, simplejson.dumps(self.content))
131
132
JacobMoshenko8e905102011-06-20 09:53:10 -0400133class TestAppAssertionCredentials(unittest.TestCase):
134 account_name = "service_account_name@appspot.com"
135 signature = "signature"
136
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500137
JacobMoshenko8e905102011-06-20 09:53:10 -0400138 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
139
140 def __init__(self):
141 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
142 'app_identity_service')
143
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500144 def _Dynamic_GetAccessToken(self, request, response):
145 response.set_access_token('a_token_123')
146 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400147
JacobMoshenko8e905102011-06-20 09:53:10 -0400148
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500149 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
150
151 def __init__(self):
152 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
153 'app_identity_service')
154
155 def _Dynamic_GetAccessToken(self, request, response):
156 raise app_identity.BackendDeadlineExceeded()
157
158 def test_raise_correct_type_of_exception(self):
159 app_identity_stub = self.ErroringAppIdentityStubImpl()
160 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800161 apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service',
JacobMoshenko8e905102011-06-20 09:53:10 -0400162 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500163 apiproxy_stub_map.apiproxy.RegisterStub(
164 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400165
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800166 scope = 'http://www.googleapis.com/scope'
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500167 try:
168 credentials = AppAssertionCredentials(scope)
169 http = httplib2.Http()
170 credentials.refresh(http)
171 self.fail('Should have raised an AccessTokenRefreshError')
172 except AccessTokenRefreshError:
173 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400174
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500175 def test_get_access_token_on_refresh(self):
176 app_identity_stub = self.AppIdentityStubImpl()
177 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
178 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
179 app_identity_stub)
180 apiproxy_stub_map.apiproxy.RegisterStub(
181 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400182
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500183 scope = [
184 "http://www.googleapis.com/scope",
185 "http://www.googleapis.com/scope2"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500186 credentials = AppAssertionCredentials(scope)
187 http = httplib2.Http()
188 credentials.refresh(http)
189 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400190
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400191 json = credentials.to_json()
192 credentials = Credentials.new_from_json(json)
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500193 self.assertEqual(
194 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
195 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400196
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500197 scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
198 credentials = AppAssertionCredentials(scope)
199 http = httplib2.Http()
200 credentials.refresh(http)
201 self.assertEqual('a_token_123', credentials.access_token)
202 self.assertEqual(
203 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
204 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400205
dhermes@google.com47154822012-11-26 10:44:09 -0800206
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400207class TestFlowModel(db.Model):
208 flow = FlowProperty()
209
210
211class FlowPropertyTest(unittest.TestCase):
212
213 def setUp(self):
214 self.testbed = testbed.Testbed()
215 self.testbed.activate()
216 self.testbed.init_datastore_v3_stub()
217
218 def tearDown(self):
219 self.testbed.deactivate()
220
221 def test_flow_get_put(self):
222 instance = TestFlowModel(
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400223 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
224 redirect_uri='oob'),
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400225 key_name='foo'
226 )
227 instance.put()
228 retrieved = TestFlowModel.get_by_key_name('foo')
229
230 self.assertEqual('foo_client_id', retrieved.flow.client_id)
231
JacobMoshenko8e905102011-06-20 09:53:10 -0400232
dhermes@google.com47154822012-11-26 10:44:09 -0800233class TestFlowNDBModel(ndb.Model):
234 flow = FlowNDBProperty()
235
236
237class FlowNDBPropertyTest(unittest.TestCase):
238
239 def setUp(self):
240 self.testbed = testbed.Testbed()
241 self.testbed.activate()
242 self.testbed.init_datastore_v3_stub()
243 self.testbed.init_memcache_stub()
244
245 def tearDown(self):
246 self.testbed.deactivate()
247
248 def test_flow_get_put(self):
249 instance = TestFlowNDBModel(
250 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
251 redirect_uri='oob'),
252 id='foo'
253 )
254 instance.put()
255 retrieved = TestFlowNDBModel.get_by_id('foo')
256
257 self.assertEqual('foo_client_id', retrieved.flow.client_id)
258
259
Joe Gregorioe84c9442012-03-12 08:45:57 -0400260def _http_request(*args, **kwargs):
261 resp = httplib2.Response({'status': '200'})
262 content = simplejson.dumps({'access_token': 'bar'})
263
264 return resp, content
265
266
267class StorageByKeyNameTest(unittest.TestCase):
268
269 def setUp(self):
270 self.testbed = testbed.Testbed()
271 self.testbed.activate()
272 self.testbed.init_datastore_v3_stub()
273 self.testbed.init_memcache_stub()
274 self.testbed.init_user_stub()
275
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800276 access_token = 'foo'
277 client_id = 'some_client_id'
278 client_secret = 'cOuDdkfjxxnv+'
279 refresh_token = '1/0/a.df219fjls0'
Joe Gregorioe84c9442012-03-12 08:45:57 -0400280 token_expiry = datetime.datetime.utcnow()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800281 user_agent = 'refresh_checker/1.0'
Joe Gregorioe84c9442012-03-12 08:45:57 -0400282 self.credentials = OAuth2Credentials(
283 access_token, client_id, client_secret,
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800284 refresh_token, token_expiry, GOOGLE_TOKEN_URI,
Joe Gregorioe84c9442012-03-12 08:45:57 -0400285 user_agent)
286
287 def tearDown(self):
288 self.testbed.deactivate()
289
290 def test_get_and_put_simple(self):
291 storage = StorageByKeyName(
292 CredentialsModel, 'foo', 'credentials')
293
294 self.assertEqual(None, storage.get())
295 self.credentials.set_store(storage)
296
297 self.credentials._refresh(_http_request)
298 credmodel = CredentialsModel.get_by_key_name('foo')
299 self.assertEqual('bar', credmodel.credentials.access_token)
300
301 def test_get_and_put_cached(self):
302 storage = StorageByKeyName(
303 CredentialsModel, 'foo', 'credentials', cache=memcache)
304
305 self.assertEqual(None, storage.get())
306 self.credentials.set_store(storage)
307
308 self.credentials._refresh(_http_request)
309 credmodel = CredentialsModel.get_by_key_name('foo')
310 self.assertEqual('bar', credmodel.credentials.access_token)
311
312 # Now remove the item from the cache.
313 memcache.delete('foo')
314
315 # Check that getting refreshes the cache.
316 credentials = storage.get()
317 self.assertEqual('bar', credentials.access_token)
318 self.assertNotEqual(None, memcache.get('foo'))
319
320 # Deleting should clear the cache.
321 storage.delete()
322 credentials = storage.get()
323 self.assertEqual(None, credentials)
324 self.assertEqual(None, memcache.get('foo'))
325
Joe Gregorioe912d182013-08-06 11:30:44 -0400326 def test_get_and_put_set_store_on_cache_retrieval(self):
327 storage = StorageByKeyName(
328 CredentialsModel, 'foo', 'credentials', cache=memcache)
329
330 self.assertEqual(None, storage.get())
331 self.credentials.set_store(storage)
332 storage.put(self.credentials)
333 # Pre-bug 292 old_creds wouldn't have storage, and the _refresh wouldn't
334 # be able to store the updated cred back into the storage.
335 old_creds = storage.get()
336 self.assertEqual(old_creds.access_token, 'foo')
337 old_creds.invalid = True
338 old_creds._refresh(_http_request)
339 new_creds = storage.get()
340 self.assertEqual(new_creds.access_token, 'bar')
341
dhermes@google.com47154822012-11-26 10:44:09 -0800342 def test_get_and_put_ndb(self):
343 # Start empty
344 storage = StorageByKeyName(
345 CredentialsNDBModel, 'foo', 'credentials')
346 self.assertEqual(None, storage.get())
347
348 # Refresh storage and retrieve without using storage
349 self.credentials.set_store(storage)
350 self.credentials._refresh(_http_request)
351 credmodel = CredentialsNDBModel.get_by_id('foo')
352 self.assertEqual('bar', credmodel.credentials.access_token)
353 self.assertEqual(credmodel.credentials.to_json(),
354 self.credentials.to_json())
355
356 def test_delete_ndb(self):
357 # Start empty
358 storage = StorageByKeyName(
359 CredentialsNDBModel, 'foo', 'credentials')
360 self.assertEqual(None, storage.get())
361
362 # Add credentials to model with storage, and check equivalent w/o storage
363 storage.put(self.credentials)
364 credmodel = CredentialsNDBModel.get_by_id('foo')
365 self.assertEqual(credmodel.credentials.to_json(),
366 self.credentials.to_json())
367
368 # Delete and make sure empty
369 storage.delete()
370 self.assertEqual(None, storage.get())
371
372 def test_get_and_put_mixed_ndb_storage_db_get(self):
373 # Start empty
374 storage = StorageByKeyName(
375 CredentialsNDBModel, 'foo', 'credentials')
376 self.assertEqual(None, storage.get())
377
378 # Set NDB store and refresh to add to storage
379 self.credentials.set_store(storage)
380 self.credentials._refresh(_http_request)
381
382 # Retrieve same key from DB model to confirm mixing works
383 credmodel = CredentialsModel.get_by_key_name('foo')
384 self.assertEqual('bar', credmodel.credentials.access_token)
385 self.assertEqual(self.credentials.to_json(),
386 credmodel.credentials.to_json())
387
388 def test_get_and_put_mixed_db_storage_ndb_get(self):
389 # Start empty
390 storage = StorageByKeyName(
391 CredentialsModel, 'foo', 'credentials')
392 self.assertEqual(None, storage.get())
393
394 # Set DB store and refresh to add to storage
395 self.credentials.set_store(storage)
396 self.credentials._refresh(_http_request)
397
398 # Retrieve same key from NDB model to confirm mixing works
399 credmodel = CredentialsNDBModel.get_by_id('foo')
400 self.assertEqual('bar', credmodel.credentials.access_token)
401 self.assertEqual(self.credentials.to_json(),
402 credmodel.credentials.to_json())
403
404 def test_delete_db_ndb_mixed(self):
405 # Start empty
406 storage_ndb = StorageByKeyName(
407 CredentialsNDBModel, 'foo', 'credentials')
408 storage = StorageByKeyName(
409 CredentialsModel, 'foo', 'credentials')
410
411 # First DB, then NDB
412 self.assertEqual(None, storage.get())
413 storage.put(self.credentials)
414 self.assertNotEqual(None, storage.get())
415
416 storage_ndb.delete()
417 self.assertEqual(None, storage.get())
418
419 # First NDB, then DB
420 self.assertEqual(None, storage_ndb.get())
421 storage_ndb.put(self.credentials)
422
423 storage.delete()
424 self.assertNotEqual(None, storage_ndb.get())
425 # NDB uses memcache and an instance cache (Context)
426 ndb.get_context().clear_cache()
427 memcache.flush_all()
428 self.assertEqual(None, storage_ndb.get())
429
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400430
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400431class MockRequest(object):
432 url = 'https://example.org'
433
434 def relative_url(self, rel):
435 return self.url + rel
436
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400437
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400438class MockRequestHandler(object):
439 request = MockRequest()
Joe Gregorioe84c9442012-03-12 08:45:57 -0400440
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400441
Joe Gregorio432f17e2011-05-22 23:18:00 -0400442class DecoratorTests(unittest.TestCase):
443
444 def setUp(self):
445 self.testbed = testbed.Testbed()
446 self.testbed.activate()
447 self.testbed.init_datastore_v3_stub()
448 self.testbed.init_memcache_stub()
449 self.testbed.init_user_stub()
450
451 decorator = OAuth2Decorator(client_id='foo_client_id',
452 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100453 scope=['foo_scope', 'bar_scope'],
454 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400455
456 self._finish_setup(decorator, user_mock=UserMock)
457
458 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400459 self.decorator = decorator
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400460 self.had_credentials = False
461 self.found_credentials = None
462 self.should_raise = False
463 parent = self
Joe Gregorio432f17e2011-05-22 23:18:00 -0400464
Joe Gregorio17774972012-03-01 11:11:59 -0500465 class TestRequiredHandler(webapp2.RequestHandler):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400466 @decorator.oauth_required
467 def get(self):
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400468 if decorator.has_credentials():
469 parent.had_credentials = True
470 parent.found_credentials = decorator.credentials
471 if parent.should_raise:
472 raise Exception('')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400473
Joe Gregorio17774972012-03-01 11:11:59 -0500474 class TestAwareHandler(webapp2.RequestHandler):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400475 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500476 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400477 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500478 assert(kwargs['year'] == '2012')
479 assert(kwargs['month'] == '01')
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400480 if decorator.has_credentials():
481 parent.had_credentials = True
482 parent.found_credentials = decorator.credentials
483 if parent.should_raise:
484 raise Exception('')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400485
486
Joe Gregorio17774972012-03-01 11:11:59 -0500487 application = webapp2.WSGIApplication([
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400488 ('/oauth2callback', self.decorator.callback_handler()),
Joe Gregorio17774972012-03-01 11:11:59 -0500489 ('/foo_path', TestRequiredHandler),
490 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
491 handler=TestAwareHandler, name='bar')],
492 debug=True)
Joe Gregorio77254c12012-08-27 14:13:22 -0400493 self.app = TestApp(application, extra_environ={
494 'wsgi.url_scheme': 'http',
495 'HTTP_HOST': 'localhost',
496 })
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400497 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400498 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400499 httplib2.Http = Http2Mock
500
501 def tearDown(self):
502 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400503 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400504
505 def test_required(self):
506 # An initial request to an oauth_required decorated path should be a
507 # redirect to start the OAuth dance.
Joe Gregorioc211bec2013-08-06 12:06:54 -0400508 self.assertEqual(self.decorator.flow, None)
509 self.assertEqual(self.decorator.credentials, None)
Joe Gregorio77254c12012-08-27 14:13:22 -0400510 response = self.app.get('http://localhost/foo_path')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400511 self.assertTrue(response.status.startswith('302'))
512 q = parse_qs(response.headers['Location'].split('?', 1)[1])
513 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
514 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400515 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400516 self.assertEqual('http://localhost/foo_path',
517 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400518 self.assertEqual('code', q['response_type'][0])
519 self.assertEqual(False, self.decorator.has_credentials())
520
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400521 m = mox.Mox()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800522 m.StubOutWithMock(appengine, '_parse_state_value')
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400523 appengine._parse_state_value('foo_path:xsrfkey123',
524 mox.IgnoreArg()).AndReturn('foo_path')
525 m.ReplayAll()
526
Joe Gregorio562b7312011-09-15 09:06:38 -0400527 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400528 response = self.app.get('/oauth2callback', {
529 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400530 'state': 'foo_path:xsrfkey123',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400531 })
Joe Gregoriocda87522013-02-22 16:22:48 -0500532 parts = response.headers['Location'].split('?', 1)
533 self.assertEqual('http://localhost/foo_path', parts[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400534 self.assertEqual(None, self.decorator.credentials)
Joe Gregoriocda87522013-02-22 16:22:48 -0500535 if self.decorator._token_response_param:
Daniel Hermesf7b648f2013-03-06 09:38:53 -0800536 response = parse_qs(parts[1])[self.decorator._token_response_param][0]
537 self.assertEqual(Http2Mock.content,
538 simplejson.loads(urllib.unquote(response)))
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400539 self.assertEqual(self.decorator.flow, self.decorator._tls.flow)
540 self.assertEqual(self.decorator.credentials,
541 self.decorator._tls.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400542
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400543 m.UnsetStubs()
544 m.VerifyAll()
545
Joe Gregorio562b7312011-09-15 09:06:38 -0400546 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400547 response = self.app.get('/foo_path')
548 self.assertEqual('200 OK', response.status)
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400549 self.assertEqual(True, self.had_credentials)
JacobMoshenko8e905102011-06-20 09:53:10 -0400550 self.assertEqual('foo_refresh_token',
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400551 self.found_credentials.refresh_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400552 self.assertEqual('foo_access_token',
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400553 self.found_credentials.access_token)
554 self.assertEqual(None, self.decorator.credentials)
555
556 # Raising an exception still clears the Credentials.
557 self.should_raise = True
558 try:
559 response = self.app.get('/foo_path')
560 self.fail('Should have raised an exception.')
561 except Exception:
562 pass
563 self.assertEqual(None, self.decorator.credentials)
564 self.should_raise = False
Joe Gregorio432f17e2011-05-22 23:18:00 -0400565
Joe Gregorio562b7312011-09-15 09:06:38 -0400566 # Invalidate the stored Credentials.
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400567 self.found_credentials.invalid = True
568 self.found_credentials.store.put(self.found_credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400569
Joe Gregorio562b7312011-09-15 09:06:38 -0400570 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400571 response = self.app.get('/foo_path')
572 self.assertTrue(response.status.startswith('302'))
573 q = parse_qs(response.headers['Location'].split('?', 1)[1])
574 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
575
Joe Gregorioec75dc12012-02-06 13:40:42 -0500576 def test_storage_delete(self):
577 # An initial request to an oauth_required decorated path should be a
578 # redirect to start the OAuth dance.
579 response = self.app.get('/foo_path')
580 self.assertTrue(response.status.startswith('302'))
581
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400582 m = mox.Mox()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800583 m.StubOutWithMock(appengine, '_parse_state_value')
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400584 appengine._parse_state_value('foo_path:xsrfkey123',
585 mox.IgnoreArg()).AndReturn('foo_path')
586 m.ReplayAll()
587
Joe Gregorioec75dc12012-02-06 13:40:42 -0500588 # Now simulate the callback to /oauth2callback.
589 response = self.app.get('/oauth2callback', {
590 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400591 'state': 'foo_path:xsrfkey123',
Joe Gregorioec75dc12012-02-06 13:40:42 -0500592 })
593 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
594 self.assertEqual(None, self.decorator.credentials)
595
596 # Now requesting the decorated path should work.
597 response = self.app.get('/foo_path')
598
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400599 self.assertTrue(self.had_credentials)
600
601 # Credentials should be cleared after each call.
602 self.assertEqual(None, self.decorator.credentials)
603
Joe Gregorioec75dc12012-02-06 13:40:42 -0500604 # Invalidate the stored Credentials.
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400605 self.found_credentials.store.delete()
Joe Gregorioec75dc12012-02-06 13:40:42 -0500606
607 # Invalid Credentials should start the OAuth dance again.
608 response = self.app.get('/foo_path')
609 self.assertTrue(response.status.startswith('302'))
610
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400611 m.UnsetStubs()
612 m.VerifyAll()
613
Joe Gregorio432f17e2011-05-22 23:18:00 -0400614 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400615 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio77254c12012-08-27 14:13:22 -0400616 response = self.app.get('http://localhost/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400617 self.assertEqual('Hello World!', response.body)
618 self.assertEqual('200 OK', response.status)
619 self.assertEqual(False, self.decorator.has_credentials())
620 url = self.decorator.authorize_url()
621 q = parse_qs(url.split('?', 1)[1])
622 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
623 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400624 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400625 self.assertEqual('http://localhost/bar_path/2012/01',
626 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400627 self.assertEqual('code', q['response_type'][0])
628
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400629 m = mox.Mox()
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800630 m.StubOutWithMock(appengine, '_parse_state_value')
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400631 appengine._parse_state_value('bar_path:xsrfkey456',
632 mox.IgnoreArg()).AndReturn('bar_path')
633 m.ReplayAll()
634
Joe Gregorio562b7312011-09-15 09:06:38 -0400635 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400636 url = self.decorator.authorize_url()
637 response = self.app.get('/oauth2callback', {
638 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400639 'state': 'bar_path:xsrfkey456',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400640 })
641 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
642 self.assertEqual(False, self.decorator.has_credentials())
643
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400644 m.UnsetStubs()
645 m.VerifyAll()
646
Joe Gregorio562b7312011-09-15 09:06:38 -0400647 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500648 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400649 self.assertEqual('200 OK', response.status)
650 self.assertEqual('Hello World!', response.body)
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400651 self.assertEqual(True, self.had_credentials)
JacobMoshenko8e905102011-06-20 09:53:10 -0400652 self.assertEqual('foo_refresh_token',
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400653 self.found_credentials.refresh_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400654 self.assertEqual('foo_access_token',
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400655 self.found_credentials.access_token)
656
657 # Credentials should be cleared after each call.
658 self.assertEqual(None, self.decorator.credentials)
659
660 # Raising an exception still clears the Credentials.
661 self.should_raise = True
662 try:
663 response = self.app.get('/bar_path/2012/01')
664 self.fail('Should have raised an exception.')
665 except Exception:
666 pass
667 self.assertEqual(None, self.decorator.credentials)
668 self.should_raise = False
669
Joe Gregorio432f17e2011-05-22 23:18:00 -0400670
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400671 def test_error_in_step2(self):
672 # An initial request to an oauth_aware decorated path should not redirect.
673 response = self.app.get('/bar_path/2012/01')
674 url = self.decorator.authorize_url()
675 response = self.app.get('/oauth2callback', {
Joe Gregorio77254c12012-08-27 14:13:22 -0400676 'error': 'Bad<Stuff>Happened\''
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400677 })
678 self.assertEqual('200 OK', response.status)
Joe Gregorio77254c12012-08-27 14:13:22 -0400679 self.assertTrue('Bad&lt;Stuff&gt;Happened&#39;' in response.body)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400680
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500681 def test_kwargs_are_passed_to_underlying_flow(self):
682 decorator = OAuth2Decorator(client_id='foo_client_id',
683 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100684 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500685 scope=['foo_scope', 'bar_scope'],
686 access_type='offline',
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800687 approval_prompt='force',
688 revoke_uri='dummy_revoke_uri')
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400689 request_handler = MockRequestHandler()
690 decorator._create_flow(request_handler)
691
692 self.assertEqual('https://example.org/oauth2callback',
693 decorator.flow.redirect_uri)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500694 self.assertEqual('offline', decorator.flow.params['access_type'])
695 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100696 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800697 self.assertEqual('dummy_revoke_uri', decorator.flow.revoke_uri)
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100698 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregoriob8b6fea2013-05-16 15:52:57 -0400699 self.assertEqual(decorator.flow, decorator._tls.flow)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500700
Joe Gregoriocda87522013-02-22 16:22:48 -0500701 def test_token_response_param(self):
702 self.decorator._token_response_param = 'foobar'
703 self.test_required()
704
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400705 def test_decorator_from_client_secrets(self):
706 decorator = oauth2decorator_from_clientsecrets(
707 datafile('client_secrets.json'),
708 scope=['foo_scope', 'bar_scope'])
709 self._finish_setup(decorator, user_mock=UserMock)
710
711 self.assertFalse(decorator._in_error)
712 self.decorator = decorator
713 self.test_required()
714 http = self.decorator.http()
715 self.assertEquals('foo_access_token', http.request.credentials.access_token)
716
dhermes@google.coma9eb0bb2013-02-06 09:19:01 -0800717 # revoke_uri is not required
718 self.assertEqual(self.decorator._revoke_uri,
719 'https://accounts.google.com/o/oauth2/revoke')
720 self.assertEqual(self.decorator._revoke_uri,
721 self.decorator.credentials.revoke_uri)
722
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400723 def test_decorator_from_cached_client_secrets(self):
724 cache_mock = CacheMock()
725 load_and_cache('client_secrets.json', 'secret', cache_mock)
726 decorator = oauth2decorator_from_clientsecrets(
727 # filename, scope, message=None, cache=None
728 'secret', '', cache=cache_mock)
729 self.assertFalse(decorator._in_error)
730
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400731 def test_decorator_from_client_secrets_not_logged_in_required(self):
732 decorator = oauth2decorator_from_clientsecrets(
733 datafile('client_secrets.json'),
734 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
735 self.decorator = decorator
736 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
737
738 self.assertFalse(decorator._in_error)
739
740 # An initial request to an oauth_required decorated path should be a
741 # redirect to login.
742 response = self.app.get('/foo_path')
743 self.assertTrue(response.status.startswith('302'))
744 self.assertTrue('Login' in str(response))
745
746 def test_decorator_from_client_secrets_not_logged_in_aware(self):
747 decorator = oauth2decorator_from_clientsecrets(
748 datafile('client_secrets.json'),
749 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
750 self.decorator = decorator
751 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
752
753 # An initial request to an oauth_aware decorated path should be a
754 # redirect to login.
755 response = self.app.get('/bar_path/2012/03')
756 self.assertTrue(response.status.startswith('302'))
757 self.assertTrue('Login' in str(response))
758
759 def test_decorator_from_unfilled_client_secrets_required(self):
760 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400761 try:
762 decorator = oauth2decorator_from_clientsecrets(
763 datafile('unfilled_client_secrets.json'),
764 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
765 except InvalidClientSecretsError:
766 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400767
768 def test_decorator_from_unfilled_client_secrets_aware(self):
769 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400770 try:
771 decorator = oauth2decorator_from_clientsecrets(
772 datafile('unfilled_client_secrets.json'),
773 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
774 except InvalidClientSecretsError:
775 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400776
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400777
778class DecoratorXsrfSecretTests(unittest.TestCase):
779 """Test xsrf_secret_key."""
780
781 def setUp(self):
782 self.testbed = testbed.Testbed()
783 self.testbed.activate()
784 self.testbed.init_datastore_v3_stub()
785 self.testbed.init_memcache_stub()
786
787 def tearDown(self):
788 self.testbed.deactivate()
789
790 def test_build_and_parse_state(self):
791 secret = appengine.xsrf_secret_key()
792
793 # Secret shouldn't change from call to call.
794 secret2 = appengine.xsrf_secret_key()
795 self.assertEqual(secret, secret2)
796
797 # Secret shouldn't change if memcache goes away.
798 memcache.delete(appengine.XSRF_MEMCACHE_ID,
dhermes@google.com47154822012-11-26 10:44:09 -0800799 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400800 secret3 = appengine.xsrf_secret_key()
801 self.assertEqual(secret2, secret3)
802
803 # Secret should change if both memcache and the model goes away.
804 memcache.delete(appengine.XSRF_MEMCACHE_ID,
dhermes@google.com47154822012-11-26 10:44:09 -0800805 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400806 model = appengine.SiteXsrfSecretKey.get_or_insert('site')
807 model.delete()
808
809 secret4 = appengine.xsrf_secret_key()
810 self.assertNotEqual(secret3, secret4)
811
dhermes@google.com47154822012-11-26 10:44:09 -0800812 def test_ndb_insert_db_get(self):
813 secret = appengine._generate_new_xsrf_secret_key()
814 appengine.SiteXsrfSecretKeyNDB(id='site', secret=secret).put()
815
816 site_key = appengine.SiteXsrfSecretKey.get_by_key_name('site')
817 self.assertEqual(site_key.secret, secret)
818
819 def test_db_insert_ndb_get(self):
820 secret = appengine._generate_new_xsrf_secret_key()
821 appengine.SiteXsrfSecretKey(key_name='site', secret=secret).put()
822
823 site_key = appengine.SiteXsrfSecretKeyNDB.get_by_id('site')
824 self.assertEqual(site_key.secret, secret)
825
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400826
827class DecoratorXsrfProtectionTests(unittest.TestCase):
828 """Test _build_state_value and _parse_state_value."""
829
830 def setUp(self):
831 self.testbed = testbed.Testbed()
832 self.testbed.activate()
833 self.testbed.init_datastore_v3_stub()
834 self.testbed.init_memcache_stub()
835
836 def tearDown(self):
837 self.testbed.deactivate()
838
839 def test_build_and_parse_state(self):
840 state = appengine._build_state_value(MockRequestHandler(), UserMock())
841 self.assertEqual(
842 'https://example.org',
843 appengine._parse_state_value(state, UserMock()))
844 self.assertRaises(appengine.InvalidXsrfTokenError,
845 appengine._parse_state_value, state[1:], UserMock())
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400846
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500847
Joe Gregorio432f17e2011-05-22 23:18:00 -0400848if __name__ == '__main__':
849 unittest.main()