blob: 680cea2df1f6909c18cdda7f7ff6399464b4589a [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 Gregoriod84d6b82012-02-28 14:53:00 -050028import time
Joe Gregorio432f17e2011-05-22 23:18:00 -040029import unittest
30import urlparse
31
32try:
33 from urlparse import parse_qs
34except ImportError:
35 from cgi import parse_qs
36
Joe Gregorio8b4c1732011-12-06 11:28:29 -050037import dev_appserver
38dev_appserver.fix_sys_path()
Joe Gregorio17774972012-03-01 11:11:59 -050039import webapp2
Joe Gregorio8b4c1732011-12-06 11:28:29 -050040
JacobMoshenko8e905102011-06-20 09:53:10 -040041from apiclient.http import HttpMockSequence
42from google.appengine.api import apiproxy_stub
43from google.appengine.api import apiproxy_stub_map
Joe Gregoriod84d6b82012-02-28 14:53:00 -050044from google.appengine.api import app_identity
JacobMoshenko8e905102011-06-20 09:53:10 -040045from google.appengine.api import users
Joe Gregorioe84c9442012-03-12 08:45:57 -040046from google.appengine.api import memcache
Joe Gregoriod84d6b82012-02-28 14:53:00 -050047from google.appengine.api.memcache import memcache_stub
Joe Gregorioe84c9442012-03-12 08:45:57 -040048from google.appengine.ext import db
JacobMoshenko8e905102011-06-20 09:53:10 -040049from google.appengine.ext import testbed
Joe Gregoriod84d6b82012-02-28 14:53:00 -050050from google.appengine.runtime import apiproxy_errors
Joe Gregorio549230c2012-01-11 10:38:05 -050051from oauth2client.anyjson import simplejson
JacobMoshenko8e905102011-06-20 09:53:10 -040052from oauth2client.appengine import AppAssertionCredentials
Joe Gregorioe84c9442012-03-12 08:45:57 -040053from oauth2client.appengine import CredentialsModel
Joe Gregorio432f17e2011-05-22 23:18:00 -040054from oauth2client.appengine import OAuth2Decorator
Joe Gregorio432f17e2011-05-22 23:18:00 -040055from oauth2client.appengine import OAuth2Handler
Joe Gregorioe84c9442012-03-12 08:45:57 -040056from oauth2client.appengine import StorageByKeyName
Joe Gregorio549230c2012-01-11 10:38:05 -050057from oauth2client.client import AccessTokenRefreshError
58from oauth2client.client import FlowExchangeError
Joe Gregorioe84c9442012-03-12 08:45:57 -040059from oauth2client.client import OAuth2Credentials
JacobMoshenko8e905102011-06-20 09:53:10 -040060from webtest import TestApp
Joe Gregorio432f17e2011-05-22 23:18:00 -040061
Joe Gregorio432f17e2011-05-22 23:18:00 -040062class UserMock(object):
63 """Mock the app engine user service"""
JacobMoshenko8e905102011-06-20 09:53:10 -040064
Joe Gregorio432f17e2011-05-22 23:18:00 -040065 def user_id(self):
66 return 'foo_user'
67
68
69class Http2Mock(object):
70 """Mock httplib2.Http"""
71 status = 200
72 content = {
73 'access_token': 'foo_access_token',
74 'refresh_token': 'foo_refresh_token',
JacobMoshenko8e905102011-06-20 09:53:10 -040075 'expires_in': 3600,
Joe Gregorio432f17e2011-05-22 23:18:00 -040076 }
77
78 def request(self, token_uri, method, body, headers, *args, **kwargs):
79 self.body = body
80 self.headers = headers
81 return (self, simplejson.dumps(self.content))
82
83
JacobMoshenko8e905102011-06-20 09:53:10 -040084class TestAppAssertionCredentials(unittest.TestCase):
85 account_name = "service_account_name@appspot.com"
86 signature = "signature"
87
Joe Gregoriod84d6b82012-02-28 14:53:00 -050088
JacobMoshenko8e905102011-06-20 09:53:10 -040089 class AppIdentityStubImpl(apiproxy_stub.APIProxyStub):
90
91 def __init__(self):
92 super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__(
93 'app_identity_service')
94
Joe Gregoriod84d6b82012-02-28 14:53:00 -050095 def _Dynamic_GetAccessToken(self, request, response):
96 response.set_access_token('a_token_123')
97 response.set_expiration_time(time.time() + 1800)
JacobMoshenko8e905102011-06-20 09:53:10 -040098
JacobMoshenko8e905102011-06-20 09:53:10 -040099
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500100 class ErroringAppIdentityStubImpl(apiproxy_stub.APIProxyStub):
101
102 def __init__(self):
103 super(TestAppAssertionCredentials.ErroringAppIdentityStubImpl, self).__init__(
104 'app_identity_service')
105
106 def _Dynamic_GetAccessToken(self, request, response):
107 raise app_identity.BackendDeadlineExceeded()
108
109 def test_raise_correct_type_of_exception(self):
110 app_identity_stub = self.ErroringAppIdentityStubImpl()
111 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
JacobMoshenko8e905102011-06-20 09:53:10 -0400112 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
113 app_identity_stub)
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500114 apiproxy_stub_map.apiproxy.RegisterStub(
115 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400116
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500117 scope = "http://www.googleapis.com/scope"
118 try:
119 credentials = AppAssertionCredentials(scope)
120 http = httplib2.Http()
121 credentials.refresh(http)
122 self.fail('Should have raised an AccessTokenRefreshError')
123 except AccessTokenRefreshError:
124 pass
JacobMoshenko8e905102011-06-20 09:53:10 -0400125
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500126 def test_get_access_token_on_refresh(self):
127 app_identity_stub = self.AppIdentityStubImpl()
128 apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
129 apiproxy_stub_map.apiproxy.RegisterStub("app_identity_service",
130 app_identity_stub)
131 apiproxy_stub_map.apiproxy.RegisterStub(
132 'memcache', memcache_stub.MemcacheServiceStub())
JacobMoshenko8e905102011-06-20 09:53:10 -0400133
Joe Gregoriod84d6b82012-02-28 14:53:00 -0500134 scope = "http://www.googleapis.com/scope"
135 credentials = AppAssertionCredentials(scope)
136 http = httplib2.Http()
137 credentials.refresh(http)
138 self.assertEqual('a_token_123', credentials.access_token)
JacobMoshenko8e905102011-06-20 09:53:10 -0400139
140
Joe Gregorioe84c9442012-03-12 08:45:57 -0400141def _http_request(*args, **kwargs):
142 resp = httplib2.Response({'status': '200'})
143 content = simplejson.dumps({'access_token': 'bar'})
144
145 return resp, content
146
147
148class StorageByKeyNameTest(unittest.TestCase):
149
150 def setUp(self):
151 self.testbed = testbed.Testbed()
152 self.testbed.activate()
153 self.testbed.init_datastore_v3_stub()
154 self.testbed.init_memcache_stub()
155 self.testbed.init_user_stub()
156
157 access_token = "foo"
158 client_id = "some_client_id"
159 client_secret = "cOuDdkfjxxnv+"
160 refresh_token = "1/0/a.df219fjls0"
161 token_expiry = datetime.datetime.utcnow()
162 token_uri = "https://www.google.com/accounts/o8/oauth2/token"
163 user_agent = "refresh_checker/1.0"
164 self.credentials = OAuth2Credentials(
165 access_token, client_id, client_secret,
166 refresh_token, token_expiry, token_uri,
167 user_agent)
168
169 def tearDown(self):
170 self.testbed.deactivate()
171
172 def test_get_and_put_simple(self):
173 storage = StorageByKeyName(
174 CredentialsModel, 'foo', 'credentials')
175
176 self.assertEqual(None, storage.get())
177 self.credentials.set_store(storage)
178
179 self.credentials._refresh(_http_request)
180 credmodel = CredentialsModel.get_by_key_name('foo')
181 self.assertEqual('bar', credmodel.credentials.access_token)
182
183 def test_get_and_put_cached(self):
184 storage = StorageByKeyName(
185 CredentialsModel, 'foo', 'credentials', cache=memcache)
186
187 self.assertEqual(None, storage.get())
188 self.credentials.set_store(storage)
189
190 self.credentials._refresh(_http_request)
191 credmodel = CredentialsModel.get_by_key_name('foo')
192 self.assertEqual('bar', credmodel.credentials.access_token)
193
194 # Now remove the item from the cache.
195 memcache.delete('foo')
196
197 # Check that getting refreshes the cache.
198 credentials = storage.get()
199 self.assertEqual('bar', credentials.access_token)
200 self.assertNotEqual(None, memcache.get('foo'))
201
202 # Deleting should clear the cache.
203 storage.delete()
204 credentials = storage.get()
205 self.assertEqual(None, credentials)
206 self.assertEqual(None, memcache.get('foo'))
207
208
209
Joe Gregorio432f17e2011-05-22 23:18:00 -0400210class DecoratorTests(unittest.TestCase):
211
212 def setUp(self):
213 self.testbed = testbed.Testbed()
214 self.testbed.activate()
215 self.testbed.init_datastore_v3_stub()
216 self.testbed.init_memcache_stub()
217 self.testbed.init_user_stub()
218
219 decorator = OAuth2Decorator(client_id='foo_client_id',
220 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100221 scope=['foo_scope', 'bar_scope'],
222 user_agent='foo')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400223 self.decorator = decorator
224
Joe Gregorio17774972012-03-01 11:11:59 -0500225 class TestRequiredHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400226
Joe Gregorio432f17e2011-05-22 23:18:00 -0400227 @decorator.oauth_required
228 def get(self):
229 pass
230
Joe Gregorio17774972012-03-01 11:11:59 -0500231 class TestAwareHandler(webapp2.RequestHandler):
JacobMoshenko8e905102011-06-20 09:53:10 -0400232
Joe Gregorio432f17e2011-05-22 23:18:00 -0400233 @decorator.oauth_aware
Joe Gregorio17774972012-03-01 11:11:59 -0500234 def get(self, *args, **kwargs):
Joe Gregorio432f17e2011-05-22 23:18:00 -0400235 self.response.out.write('Hello World!')
Joe Gregorio17774972012-03-01 11:11:59 -0500236 assert(kwargs['year'] == '2012')
237 assert(kwargs['month'] == '01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400238
239
Joe Gregorio17774972012-03-01 11:11:59 -0500240 application = webapp2.WSGIApplication([
241 ('/oauth2callback', OAuth2Handler),
242 ('/foo_path', TestRequiredHandler),
243 webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>',
244 handler=TestAwareHandler, name='bar')],
245 debug=True)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400246 self.app = TestApp(application)
247 users.get_current_user = UserMock
Joe Gregorio922b78c2011-05-26 21:36:34 -0400248 self.httplib2_orig = httplib2.Http
Joe Gregorio432f17e2011-05-22 23:18:00 -0400249 httplib2.Http = Http2Mock
250
251 def tearDown(self):
252 self.testbed.deactivate()
Joe Gregorio922b78c2011-05-26 21:36:34 -0400253 httplib2.Http = self.httplib2_orig
Joe Gregorio432f17e2011-05-22 23:18:00 -0400254
255 def test_required(self):
256 # An initial request to an oauth_required decorated path should be a
257 # redirect to start the OAuth dance.
258 response = self.app.get('/foo_path')
259 self.assertTrue(response.status.startswith('302'))
260 q = parse_qs(response.headers['Location'].split('?', 1)[1])
261 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
262 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400263 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400264 self.assertEqual('http://localhost/foo_path', q['state'][0])
265 self.assertEqual('code', q['response_type'][0])
266 self.assertEqual(False, self.decorator.has_credentials())
267
Joe Gregorio562b7312011-09-15 09:06:38 -0400268 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400269 response = self.app.get('/oauth2callback', {
270 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400271 'state': 'foo_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400272 })
273 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
274 self.assertEqual(None, self.decorator.credentials)
275
Joe Gregorio562b7312011-09-15 09:06:38 -0400276 # Now requesting the decorated path should work.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400277 response = self.app.get('/foo_path')
278 self.assertEqual('200 OK', response.status)
279 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400280 self.assertEqual('foo_refresh_token',
281 self.decorator.credentials.refresh_token)
282 self.assertEqual('foo_access_token',
283 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400284
Joe Gregorio562b7312011-09-15 09:06:38 -0400285 # Invalidate the stored Credentials.
Joe Gregorio9da2ad82011-09-11 14:04:44 -0400286 self.decorator.credentials.invalid = True
287 self.decorator.credentials.store.put(self.decorator.credentials)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400288
Joe Gregorio562b7312011-09-15 09:06:38 -0400289 # Invalid Credentials should start the OAuth dance again.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400290 response = self.app.get('/foo_path')
291 self.assertTrue(response.status.startswith('302'))
292 q = parse_qs(response.headers['Location'].split('?', 1)[1])
293 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
294
Joe Gregorioec75dc12012-02-06 13:40:42 -0500295 def test_storage_delete(self):
296 # An initial request to an oauth_required decorated path should be a
297 # redirect to start the OAuth dance.
298 response = self.app.get('/foo_path')
299 self.assertTrue(response.status.startswith('302'))
300
301 # Now simulate the callback to /oauth2callback.
302 response = self.app.get('/oauth2callback', {
303 'code': 'foo_access_code',
304 'state': 'foo_path',
305 })
306 self.assertEqual('http://localhost/foo_path', response.headers['Location'])
307 self.assertEqual(None, self.decorator.credentials)
308
309 # Now requesting the decorated path should work.
310 response = self.app.get('/foo_path')
311
312 # Invalidate the stored Credentials.
313 self.decorator.credentials.store.delete()
314
315 # Invalid Credentials should start the OAuth dance again.
316 response = self.app.get('/foo_path')
317 self.assertTrue(response.status.startswith('302'))
318
Joe Gregorio432f17e2011-05-22 23:18:00 -0400319 def test_aware(self):
Joe Gregorio562b7312011-09-15 09:06:38 -0400320 # An initial request to an oauth_aware decorated path should not redirect.
Joe Gregorio17774972012-03-01 11:11:59 -0500321 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400322 self.assertEqual('Hello World!', response.body)
323 self.assertEqual('200 OK', response.status)
324 self.assertEqual(False, self.decorator.has_credentials())
325 url = self.decorator.authorize_url()
326 q = parse_qs(url.split('?', 1)[1])
327 self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0])
328 self.assertEqual('foo_client_id', q['client_id'][0])
Joe Gregoriof2f8a5a2011-10-14 15:11:29 -0400329 self.assertEqual('foo_scope bar_scope', q['scope'][0])
Joe Gregorio17774972012-03-01 11:11:59 -0500330 self.assertEqual('http://localhost/bar_path/2012/01', q['state'][0])
Joe Gregorio432f17e2011-05-22 23:18:00 -0400331 self.assertEqual('code', q['response_type'][0])
332
Joe Gregorio562b7312011-09-15 09:06:38 -0400333 # Now simulate the callback to /oauth2callback.
Joe Gregorio432f17e2011-05-22 23:18:00 -0400334 url = self.decorator.authorize_url()
335 response = self.app.get('/oauth2callback', {
336 'code': 'foo_access_code',
JacobMoshenko8e905102011-06-20 09:53:10 -0400337 'state': 'bar_path',
Joe Gregorio432f17e2011-05-22 23:18:00 -0400338 })
339 self.assertEqual('http://localhost/bar_path', response.headers['Location'])
340 self.assertEqual(False, self.decorator.has_credentials())
341
Joe Gregorio562b7312011-09-15 09:06:38 -0400342 # Now requesting the decorated path will have credentials.
Joe Gregorio17774972012-03-01 11:11:59 -0500343 response = self.app.get('/bar_path/2012/01')
Joe Gregorio432f17e2011-05-22 23:18:00 -0400344 self.assertEqual('200 OK', response.status)
345 self.assertEqual('Hello World!', response.body)
346 self.assertEqual(True, self.decorator.has_credentials())
JacobMoshenko8e905102011-06-20 09:53:10 -0400347 self.assertEqual('foo_refresh_token',
348 self.decorator.credentials.refresh_token)
349 self.assertEqual('foo_access_token',
350 self.decorator.credentials.access_token)
Joe Gregorio432f17e2011-05-22 23:18:00 -0400351
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500352
353 def test_kwargs_are_passed_to_underlying_flow(self):
354 decorator = OAuth2Decorator(client_id='foo_client_id',
355 client_secret='foo_client_secret',
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100356 user_agent='foo_user_agent',
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500357 scope=['foo_scope', 'bar_scope'],
358 access_type='offline',
359 approval_prompt='force')
360 self.assertEqual('offline', decorator.flow.params['access_type'])
361 self.assertEqual('force', decorator.flow.params['approval_prompt'])
Johan Euphrosineacf517f2012-02-13 21:08:33 +0100362 self.assertEqual('foo_user_agent', decorator.flow.user_agent)
363 self.assertEqual(None, decorator.flow.params.get('user_agent', None))
Joe Gregorio1adde1a2012-01-06 12:30:35 -0500364
365
Joe Gregorio432f17e2011-05-22 23:18:00 -0400366if __name__ == '__main__':
367 unittest.main()