blob: 827a31fa9560bf5cd7406a3e33afaaf3ddf407df [file] [log] [blame]
Joe Gregorio432f17e2011-05-22 23:18:00 -04001#!/usr/bin/python2.4
2#
3# Copyright 2010 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17
18"""Discovery document tests
19
20Unit tests for objects created from discovery documents.
21"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
JacobMoshenko8e905102011-06-20 09:53:10 -040025import base64
Joe Gregorioe84c9442012-03-12 08:45:57 -040026import datetime
Joe Gregorio432f17e2011-05-22 23:18:00 -040027import httplib2
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040028import mox
Joe Gregorio08cdcb82012-03-14 00:09:33 -040029import os
Joe Gregoriod84d6b82012-02-28 14:53:00 -050030import time
Joe Gregorio432f17e2011-05-22 23:18:00 -040031import unittest
32import urlparse
33
34try:
35 from urlparse import parse_qs
36except ImportError:
37 from cgi import parse_qs
38
Joe Gregorio8b4c1732011-12-06 11:28:29 -050039import dev_appserver
40dev_appserver.fix_sys_path()
Joe Gregorio17774972012-03-01 11:11:59 -050041import webapp2
Joe Gregorio8b4c1732011-12-06 11:28:29 -050042
JacobMoshenko8e905102011-06-20 09:53:10 -040043from apiclient.http import HttpMockSequence
44from google.appengine.api import apiproxy_stub
45from google.appengine.api import apiproxy_stub_map
Joe Gregoriod84d6b82012-02-28 14:53:00 -050046from google.appengine.api import app_identity
Joe Gregorioe84c9442012-03-12 08:45:57 -040047from google.appengine.api import memcache
Joe Gregorio08cdcb82012-03-14 00:09:33 -040048from google.appengine.api import users
Joe Gregoriod84d6b82012-02-28 14:53:00 -050049from google.appengine.api.memcache import memcache_stub
Joe Gregorioe84c9442012-03-12 08:45:57 -040050from google.appengine.ext import db
JacobMoshenko8e905102011-06-20 09:53:10 -040051from google.appengine.ext import testbed
Joe Gregoriod84d6b82012-02-28 14:53:00 -050052from google.appengine.runtime import apiproxy_errors
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040053from oauth2client import appengine
Joe Gregorio549230c2012-01-11 10:38:05 -050054from oauth2client.anyjson import simplejson
Joe Gregorioc29aaa92012-07-16 16:16:31 -040055from oauth2client.clientsecrets import _loadfile
Joe Gregorio6ceea2d2012-08-24 11:57:58 -040056from oauth2client.clientsecrets import InvalidClientSecretsError
JacobMoshenko8e905102011-06-20 09:53:10 -040057from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040058from oauth2client.appengine import CredentialsModel
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040059from oauth2client.appengine import FlowProperty
Joe Gregorio432f17e2011-05-22 23:18:00 -040060from oauth2client.appengine import OAuth2Decorator
Joe Gregorioe84c9442012-03-12 08:45:57 -040061from oauth2client.appengine import StorageByKeyName
Joe Gregorio08cdcb82012-03-14 00:09:33 -040062from oauth2client.appengine import oauth2decorator_from_clientsecrets
Joe Gregorio549230c2012-01-11 10:38:05 -050063from oauth2client.client import AccessTokenRefreshError
Joe Gregorio08cdcb82012-03-14 00:09:33 -040064from oauth2client.client import Credentials
Joe Gregorio549230c2012-01-11 10:38:05 -050065from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040066from oauth2client.client import OAuth2Credentials
Joe Gregorio08cdcb82012-03-14 00:09:33 -040067from oauth2client.client import flow_from_clientsecrets
JacobMoshenko8e905102011-06-20 09:53:10 -040068from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040069
Joe Gregorio4fbde1c2012-07-11 14:47:39 -040070
Joe Gregorio08cdcb82012-03-14 00:09:33 -040071DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
72
73
74def datafile(filename):
75 return os.path.join(DATA_DIR, filename)
76
77
Joe Gregorioc29aaa92012-07-16 16:16:31 -040078def load_and_cache(existing_file, fakename, cache_mock):
79 client_type, client_info = _loadfile(datafile(existing_file))
80 cache_mock.cache[fakename] = {client_type: client_info}
81
82
83class CacheMock(object):
84 def __init__(self):
85 self.cache = {}
86
87 def get(self, key, namespace=''):
88 # ignoring namespace for easier testing
89 return self.cache.get(key, None)
90
91 def set(self, key, value, namespace=''):
92 # ignoring namespace for easier testing
93 self.cache[key] = value
94
95
Joe Gregorio432f17e2011-05-22 23:18:00 -040096class UserMock(object):
97 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040098
Joe Gregorio08cdcb82012-03-14 00:09:33 -040099 def __call__(self):
100 return self
101
Joe Gregorio432f17e2011-05-22 23:18:00 -0400102 def user_id(self):
103 return 'foo_user'
104
105
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400106class UserNotLoggedInMock(object):
107 """Mock the app engine user service"""
108
109 def __call__(self):
110 return None
111
112
Joe Gregorio432f17e2011-05-22 23:18:00 -0400113class Http2Mock(object):
114 """Mock httplib2.Http"""
115 status = 200
116 content = {
117 'access_token': 'foo_access_token',
118 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -0400119 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -0400120 }
121
122 def request(self, token_uri, method, body, headers, *args, **kwargs):
123 self.body = body
124 self.headers = headers
125 return (self, simplejson.dumps(self.content))
126
127
JacobMoshenko8e905102011-06-20 09:53:10 -0400128class TestAppAssertionCredentials(unittest.TestCase):
129 account_name = "service_account_name@appspot.com"
130 signature = "signature"
131
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500132
JacobMoshenko8e905102011-06-20 09:53:10 -0400133 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
134
135 def __init__(self):
136 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
137 'app_identity_service')
138
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500139 def _Dynamic_GetAccessToken(self, request, response):
140 response.set_access_token('a_token_123')
141 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -0400142
JacobMoshenko8e905102011-06-20 09:53:10 -0400143
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500144 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
145
146 def __init__(self):
147 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
148 'app_identity_service')
149
150 def _Dynamic_GetAccessToken(self, request, response):
151 raise app_identity.BackendDeadlineExceeded()
152
153 def test_raise_correct_type_of_exception(self):
154 app_identity_stub = self.ErroringAppIdentityStubImpl()
155 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400156 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
157 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500158 apiproxy_stub_map.apiproxy.RegisterStub(
159 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400160
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500161 scope = "http://www.googleapis.com/scope"
162 try:
163 credentials = AppAssertionCredentials(scope)
164 http = httplib2.Http()
165 credentials.refresh(http)
166 self.fail('Should have raised an AccessTokenRefreshError')
167 except AccessTokenRefreshError:
168 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400169
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500170 def test_get_access_token_on_refresh(self):
171 app_identity_stub = self.AppIdentityStubImpl()
172 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
173 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
174 app_identity_stub)
175 apiproxy_stub_map.apiproxy.RegisterStub(
176 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400177
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500178 scope = [
179 "http://www.googleapis.com/scope",
180 "http://www.googleapis.com/scope2"]
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500181 credentials = AppAssertionCredentials(scope)
182 http = httplib2.Http()
183 credentials.refresh(http)
184 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400185
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400186 json = credentials.to_json()
187 credentials = Credentials.new_from_json(json)
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500188 self.assertEqual(
189 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
190 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400191
Joe Gregorio5cf5d122012-11-16 16:36:12 -0500192 scope = "http://www.googleapis.com/scope http://www.googleapis.com/scope2"
193 credentials = AppAssertionCredentials(scope)
194 http = httplib2.Http()
195 credentials.refresh(http)
196 self.assertEqual('a_token_123', credentials.access_token)
197 self.assertEqual(
198 'http://www.googleapis.com/scope http://www.googleapis.com/scope2',
199 credentials.scope)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400200
201class TestFlowModel(db.Model):
202 flow = FlowProperty()
203
204
205class FlowPropertyTest(unittest.TestCase):
206
207 def setUp(self):
208 self.testbed = testbed.Testbed()
209 self.testbed.activate()
210 self.testbed.init_datastore_v3_stub()
211
212 def tearDown(self):
213 self.testbed.deactivate()
214
215 def test_flow_get_put(self):
216 instance = TestFlowModel(
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400217 flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo',
218 redirect_uri='oob'),
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400219 key_name='foo'
220 )
221 instance.put()
222 retrieved = TestFlowModel.get_by_key_name('foo')
223
224 self.assertEqual('foo_client_id', retrieved.flow.client_id)
225
JacobMoshenko8e905102011-06-20 09:53:10 -0400226
Joe Gregorioe84c9442012-03-12 08:45:57 -0400227def _http_request(*args, **kwargs):
228 resp = httplib2.Response({'status': '200'})
229 content = simplejson.dumps({'access_token': 'bar'})
230
231 return resp, content
232
233
234class StorageByKeyNameTest(unittest.TestCase):
235
236 def setUp(self):
237 self.testbed = testbed.Testbed()
238 self.testbed.activate()
239 self.testbed.init_datastore_v3_stub()
240 self.testbed.init_memcache_stub()
241 self.testbed.init_user_stub()
242
243 access_token = "foo"
244 client_id = "some_client_id"
245 client_secret = "cOuDdkfjxxnv+"
246 refresh_token = "1/0/a.df219fjls0"
247 token_expiry = datetime.datetime.utcnow()
248 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
249 user_agent = "refresh_checker/1.0"
250 self.credentials = OAuth2Credentials(
251 access_token, client_id, client_secret,
252 refresh_token, token_expiry, token_uri,
253 user_agent)
254
255 def tearDown(self):
256 self.testbed.deactivate()
257
258 def test_get_and_put_simple(self):
259 storage = StorageByKeyName(
260 CredentialsModel, 'foo', 'credentials')
261
262 self.assertEqual(None, storage.get())
263 self.credentials.set_store(storage)
264
265 self.credentials._refresh(_http_request)
266 credmodel = CredentialsModel.get_by_key_name('foo')
267 self.assertEqual('bar', credmodel.credentials.access_token)
268
269 def test_get_and_put_cached(self):
270 storage = StorageByKeyName(
271 CredentialsModel, 'foo', 'credentials', cache=memcache)
272
273 self.assertEqual(None, storage.get())
274 self.credentials.set_store(storage)
275
276 self.credentials._refresh(_http_request)
277 credmodel = CredentialsModel.get_by_key_name('foo')
278 self.assertEqual('bar', credmodel.credentials.access_token)
279
280 # Now remove the item from the cache.
281 memcache.delete('foo')
282
283 # Check that getting refreshes the cache.
284 credentials = storage.get()
285 self.assertEqual('bar', credentials.access_token)
286 self.assertNotEqual(None, memcache.get('foo'))
287
288 # Deleting should clear the cache.
289 storage.delete()
290 credentials = storage.get()
291 self.assertEqual(None, credentials)
292 self.assertEqual(None, memcache.get('foo'))
293
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400294
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400295class MockRequest(object):
296 url = 'https://example.org'
297
298 def relative_url(self, rel):
299 return self.url + rel
300
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400301
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400302class MockRequestHandler(object):
303 request = MockRequest()
Joe Gregorioe84c9442012-03-12 08:45:57 -0400304
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400305
Joe Gregorio432f17e2011-05-22 23:18:00 -0400306class DecoratorTests(unittest.TestCase):
307
308 def setUp(self):
309 self.testbed = testbed.Testbed()
310 self.testbed.activate()
311 self.testbed.init_datastore_v3_stub()
312 self.testbed.init_memcache_stub()
313 self.testbed.init_user_stub()
314
315 decorator = OAuth2Decorator(client_id='foo_client_id',
316 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100317 scope=['foo_scope', 'bar_scope'],
318 user_agent='foo')
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400319
320 self._finish_setup(decorator, user_mock=UserMock)
321
322 def _finish_setup(self, decorator, user_mock):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400323 self.decorator = decorator
324
Joe Gregorio17774972012-03-01 11:11:59 -0500325 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400326
Joe Gregorio432f17e2011-05-22 23:18:00 -0400327 @decorator.oauth_required
328 def get(self):
329 pass
330
Joe Gregorio17774972012-03-01 11:11:59 -0500331 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400332
Joe Gregorio432f17e2011-05-22 23:18:00 -0400333 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500334 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400335 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500336 assert(kwargs['year'] == '2012')
337 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400338
339
Joe Gregorio17774972012-03-01 11:11:59 -0500340 application = webapp2.WSGIApplication([
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400341 ('/oauth2callback', self.decorator.callback_handler()),
Joe Gregorio17774972012-03-01 11:11:59 -0500342 ('/foo_path', TestRequiredHandler),
343 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
344 handler=TestAwareHandler, name='bar')],
345 debug=True)
Joe Gregorio77254c12012-08-27 14:13:22 -0400346 self.app = TestApp(application, extra_environ={
347 'wsgi.url_scheme': 'http',
348 'HTTP_HOST': 'localhost',
349 })
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400350 users.get_current_user = user_mock()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400351 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400352 httplib2.Http = Http2Mock
353
354 def tearDown(self):
355 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400356 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400357
358 def test_required(self):
359 # An initial request to an oauth_required decorated path should be a
360 # redirect to start the OAuth dance.
Joe Gregorio77254c12012-08-27 14:13:22 -0400361 response = self.app.get('http://localhost/foo_path')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400362 self.assertTrue(response.status.startswith('302'))
363 q = parse_qs(response.headers['Location'].split('?', 1)[1])
364 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
365 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400366 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400367 self.assertEqual('http://localhost/foo_path',
368 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400369 self.assertEqual('code', q['response_type'][0])
370 self.assertEqual(False, self.decorator.has_credentials())
371
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400372 m = mox.Mox()
373 m.StubOutWithMock(appengine, "_parse_state_value")
374 appengine._parse_state_value('foo_path:xsrfkey123',
375 mox.IgnoreArg()).AndReturn('foo_path')
376 m.ReplayAll()
377
Joe Gregorio562b7312011-09-15 09:06:38 -0400378 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400379 response = self.app.get('/oauth2callback', {
380 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400381 'state': 'foo_path:xsrfkey123',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400382 })
383 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
384 self.assertEqual(None, self.decorator.credentials)
385
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400386 m.UnsetStubs()
387 m.VerifyAll()
388
Joe Gregorio562b7312011-09-15 09:06:38 -0400389 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400390 response = self.app.get('/foo_path')
391 self.assertEqual('200 OK', response.status)
392 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400393 self.assertEqual('foo_refresh_token',
394 self.decorator.credentials.refresh_token)
395 self.assertEqual('foo_access_token',
396 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400397
Joe Gregorio562b7312011-09-15 09:06:38 -0400398 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400399 self.decorator.credentials.invalid = True
400 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400401
Joe Gregorio562b7312011-09-15 09:06:38 -0400402 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400403 response = self.app.get('/foo_path')
404 self.assertTrue(response.status.startswith('302'))
405 q = parse_qs(response.headers['Location'].split('?', 1)[1])
406 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
407
Joe Gregorioec75dc12012-02-06 13:40:42 -0500408 def test_storage_delete(self):
409 # An initial request to an oauth_required decorated path should be a
410 # redirect to start the OAuth dance.
411 response = self.app.get('/foo_path')
412 self.assertTrue(response.status.startswith('302'))
413
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400414 m = mox.Mox()
415 m.StubOutWithMock(appengine, "_parse_state_value")
416 appengine._parse_state_value('foo_path:xsrfkey123',
417 mox.IgnoreArg()).AndReturn('foo_path')
418 m.ReplayAll()
419
Joe Gregorioec75dc12012-02-06 13:40:42 -0500420 # Now simulate the callback to /oauth2callback.
421 response = self.app.get('/oauth2callback', {
422 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400423 'state': 'foo_path:xsrfkey123',
Joe Gregorioec75dc12012-02-06 13:40:42 -0500424 })
425 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
426 self.assertEqual(None, self.decorator.credentials)
427
428 # Now requesting the decorated path should work.
429 response = self.app.get('/foo_path')
430
431 # Invalidate the stored Credentials.
432 self.decorator.credentials.store.delete()
433
434 # Invalid Credentials should start the OAuth dance again.
435 response = self.app.get('/foo_path')
436 self.assertTrue(response.status.startswith('302'))
437
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400438 m.UnsetStubs()
439 m.VerifyAll()
440
Joe Gregorio432f17e2011-05-22 23:18:00 -0400441 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400442 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio77254c12012-08-27 14:13:22 -0400443 response = self.app.get('http://localhost/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400444 self.assertEqual('Hello World!', response.body)
445 self.assertEqual('200 OK', response.status)
446 self.assertEqual(False, self.decorator.has_credentials())
447 url = self.decorator.authorize_url()
448 q = parse_qs(url.split('?', 1)[1])
449 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
450 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400451 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400452 self.assertEqual('http://localhost/bar_path/2012/01',
453 q['state'][0].rsplit(':', 1)[0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400454 self.assertEqual('code', q['response_type'][0])
455
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400456 m = mox.Mox()
457 m.StubOutWithMock(appengine, "_parse_state_value")
458 appengine._parse_state_value('bar_path:xsrfkey456',
459 mox.IgnoreArg()).AndReturn('bar_path')
460 m.ReplayAll()
461
Joe Gregorio562b7312011-09-15 09:06:38 -0400462 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400463 url = self.decorator.authorize_url()
464 response = self.app.get('/oauth2callback', {
465 'code': 'foo_access_code',
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400466 'state': 'bar_path:xsrfkey456',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400467 })
468 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
469 self.assertEqual(False, self.decorator.has_credentials())
470
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400471 m.UnsetStubs()
472 m.VerifyAll()
473
Joe Gregorio562b7312011-09-15 09:06:38 -0400474 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500475 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400476 self.assertEqual('200 OK', response.status)
477 self.assertEqual('Hello World!', response.body)
478 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400479 self.assertEqual('foo_refresh_token',
480 self.decorator.credentials.refresh_token)
481 self.assertEqual('foo_access_token',
482 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400483
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400484 def test_error_in_step2(self):
485 # An initial request to an oauth_aware decorated path should not redirect.
486 response = self.app.get('/bar_path/2012/01')
487 url = self.decorator.authorize_url()
488 response = self.app.get('/oauth2callback', {
Joe Gregorio77254c12012-08-27 14:13:22 -0400489 'error': 'Bad<Stuff>Happened\''
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400490 })
491 self.assertEqual('200 OK', response.status)
Joe Gregorio77254c12012-08-27 14:13:22 -0400492 self.assertTrue('Bad&lt;Stuff&gt;Happened&#39;' in response.body)
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400493
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500494 def test_kwargs_are_passed_to_underlying_flow(self):
495 decorator = OAuth2Decorator(client_id='foo_client_id',
496 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100497 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500498 scope=['foo_scope', 'bar_scope'],
499 access_type='offline',
500 approval_prompt='force')
Joe Gregorio68a8cfe2012-08-03 16:17:40 -0400501 request_handler = MockRequestHandler()
502 decorator._create_flow(request_handler)
503
504 self.assertEqual('https://example.org/oauth2callback',
505 decorator.flow.redirect_uri)
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500506 self.assertEqual('offline', decorator.flow.params['access_type'])
507 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100508 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
509 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500510
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400511 def test_decorator_from_client_secrets(self):
512 decorator = oauth2decorator_from_clientsecrets(
513 datafile('client_secrets.json'),
514 scope=['foo_scope', 'bar_scope'])
515 self._finish_setup(decorator, user_mock=UserMock)
516
517 self.assertFalse(decorator._in_error)
518 self.decorator = decorator
519 self.test_required()
520 http = self.decorator.http()
521 self.assertEquals('foo_access_token', http.request.credentials.access_token)
522
Joe Gregorioc29aaa92012-07-16 16:16:31 -0400523 def test_decorator_from_cached_client_secrets(self):
524 cache_mock = CacheMock()
525 load_and_cache('client_secrets.json', 'secret', cache_mock)
526 decorator = oauth2decorator_from_clientsecrets(
527 # filename, scope, message=None, cache=None
528 'secret', '', cache=cache_mock)
529 self.assertFalse(decorator._in_error)
530
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400531 def test_decorator_from_client_secrets_not_logged_in_required(self):
532 decorator = oauth2decorator_from_clientsecrets(
533 datafile('client_secrets.json'),
534 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
535 self.decorator = decorator
536 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
537
538 self.assertFalse(decorator._in_error)
539
540 # An initial request to an oauth_required decorated path should be a
541 # redirect to login.
542 response = self.app.get('/foo_path')
543 self.assertTrue(response.status.startswith('302'))
544 self.assertTrue('Login' in str(response))
545
546 def test_decorator_from_client_secrets_not_logged_in_aware(self):
547 decorator = oauth2decorator_from_clientsecrets(
548 datafile('client_secrets.json'),
549 scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage')
550 self.decorator = decorator
551 self._finish_setup(decorator, user_mock=UserNotLoggedInMock)
552
553 # An initial request to an oauth_aware decorated path should be a
554 # redirect to login.
555 response = self.app.get('/bar_path/2012/03')
556 self.assertTrue(response.status.startswith('302'))
557 self.assertTrue('Login' in str(response))
558
559 def test_decorator_from_unfilled_client_secrets_required(self):
560 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400561 try:
562 decorator = oauth2decorator_from_clientsecrets(
563 datafile('unfilled_client_secrets.json'),
564 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
565 except InvalidClientSecretsError:
566 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400567
568 def test_decorator_from_unfilled_client_secrets_aware(self):
569 MESSAGE = 'File is missing'
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400570 try:
571 decorator = oauth2decorator_from_clientsecrets(
572 datafile('unfilled_client_secrets.json'),
573 scope=['foo_scope', 'bar_scope'], message=MESSAGE)
574 except InvalidClientSecretsError:
575 pass
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400576
Joe Gregorio6ceea2d2012-08-24 11:57:58 -0400577
578class DecoratorXsrfSecretTests(unittest.TestCase):
579 """Test xsrf_secret_key."""
580
581 def setUp(self):
582 self.testbed = testbed.Testbed()
583 self.testbed.activate()
584 self.testbed.init_datastore_v3_stub()
585 self.testbed.init_memcache_stub()
586
587 def tearDown(self):
588 self.testbed.deactivate()
589
590 def test_build_and_parse_state(self):
591 secret = appengine.xsrf_secret_key()
592
593 # Secret shouldn't change from call to call.
594 secret2 = appengine.xsrf_secret_key()
595 self.assertEqual(secret, secret2)
596
597 # Secret shouldn't change if memcache goes away.
598 memcache.delete(appengine.XSRF_MEMCACHE_ID,
599 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
600 secret3 = appengine.xsrf_secret_key()
601 self.assertEqual(secret2, secret3)
602
603 # Secret should change if both memcache and the model goes away.
604 memcache.delete(appengine.XSRF_MEMCACHE_ID,
605 namespace=appengine.OAUTH2CLIENT_NAMESPACE)
606 model = appengine.SiteXsrfSecretKey.get_or_insert('site')
607 model.delete()
608
609 secret4 = appengine.xsrf_secret_key()
610 self.assertNotEqual(secret3, secret4)
611
612
613class DecoratorXsrfProtectionTests(unittest.TestCase):
614 """Test _build_state_value and _parse_state_value."""
615
616 def setUp(self):
617 self.testbed = testbed.Testbed()
618 self.testbed.activate()
619 self.testbed.init_datastore_v3_stub()
620 self.testbed.init_memcache_stub()
621
622 def tearDown(self):
623 self.testbed.deactivate()
624
625 def test_build_and_parse_state(self):
626 state = appengine._build_state_value(MockRequestHandler(), UserMock())
627 self.assertEqual(
628 'https://example.org',
629 appengine._parse_state_value(state, UserMock()))
630 self.assertRaises(appengine.InvalidXsrfTokenError,
631 appengine._parse_state_value, state[1:], UserMock())
Joe Gregorio08cdcb82012-03-14 00:09:33 -0400632
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500633
Joe Gregorio432f17e2011-05-22 23:18:00 -0400634if __name__ == '__main__':
635 unittest.main()