Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 1 | #!/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 | |
| 20 | Unit tests for objects created from discovery documents. |
| 21 | """ |
| 22 | |
| 23 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 24 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 25 | import base64 |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 26 | import datetime |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 27 | import httplib2 |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 28 | import mox |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 29 | import os |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 30 | import time |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 31 | import unittest |
Joe Gregorio | cda8752 | 2013-02-22 16:22:48 -0500 | [diff] [blame] | 32 | import urllib |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 33 | |
| 34 | try: |
Daniel Hermes | b7c5a40 | 2013-04-05 09:32:45 -0700 | [diff] [blame] | 35 | from urlparse import parse_qs |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 36 | except ImportError: |
Daniel Hermes | b7c5a40 | 2013-04-05 09:32:45 -0700 | [diff] [blame] | 37 | from cgi import parse_qs |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 38 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 39 | import dev_appserver |
| 40 | dev_appserver.fix_sys_path() |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 41 | import webapp2 |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 42 | |
John Asmuth | 864311d | 2014-04-24 15:46:08 -0400 | [diff] [blame^] | 43 | from googleapiclient.http import HttpMockSequence |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 44 | from google.appengine.api import apiproxy_stub |
| 45 | from google.appengine.api import apiproxy_stub_map |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 46 | from google.appengine.api import app_identity |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 47 | from google.appengine.api import memcache |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 48 | from google.appengine.api import users |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 49 | from google.appengine.api.memcache import memcache_stub |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 50 | from google.appengine.ext import db |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 51 | from google.appengine.ext import ndb |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 52 | from google.appengine.ext import testbed |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 53 | from google.appengine.runtime import apiproxy_errors |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 54 | from oauth2client import appengine |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 55 | from oauth2client import GOOGLE_TOKEN_URI |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 56 | from oauth2client.anyjson import simplejson |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 57 | from oauth2client.clientsecrets import _loadfile |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 58 | from oauth2client.clientsecrets import InvalidClientSecretsError |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 59 | from oauth2client.appengine import AppAssertionCredentials |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 60 | from oauth2client.appengine import CredentialsModel |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 61 | from oauth2client.appengine import CredentialsNDBModel |
| 62 | from oauth2client.appengine import FlowNDBProperty |
Joe Gregorio | 4fbde1c | 2012-07-11 14:47:39 -0400 | [diff] [blame] | 63 | from oauth2client.appengine import FlowProperty |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 64 | from oauth2client.appengine import OAuth2Decorator |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 65 | from oauth2client.appengine import StorageByKeyName |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 66 | from oauth2client.appengine import oauth2decorator_from_clientsecrets |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 67 | from oauth2client.client import AccessTokenRefreshError |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 68 | from oauth2client.client import Credentials |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 69 | from oauth2client.client import FlowExchangeError |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 70 | from oauth2client.client import OAuth2Credentials |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 71 | from oauth2client.client import flow_from_clientsecrets |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 72 | from webtest import TestApp |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 73 | |
Joe Gregorio | 4fbde1c | 2012-07-11 14:47:39 -0400 | [diff] [blame] | 74 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 75 | DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') |
| 76 | |
| 77 | |
| 78 | def datafile(filename): |
| 79 | return os.path.join(DATA_DIR, filename) |
| 80 | |
| 81 | |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 82 | def 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 | |
| 87 | class CacheMock(object): |
Daniel Hermes | b7c5a40 | 2013-04-05 09:32:45 -0700 | [diff] [blame] | 88 | def __init__(self): |
| 89 | self.cache = {} |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 90 | |
Daniel Hermes | b7c5a40 | 2013-04-05 09:32:45 -0700 | [diff] [blame] | 91 | def get(self, key, namespace=''): |
| 92 | # ignoring namespace for easier testing |
| 93 | return self.cache.get(key, None) |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 94 | |
Daniel Hermes | b7c5a40 | 2013-04-05 09:32:45 -0700 | [diff] [blame] | 95 | def set(self, key, value, namespace=''): |
| 96 | # ignoring namespace for easier testing |
| 97 | self.cache[key] = value |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 98 | |
| 99 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 100 | class UserMock(object): |
| 101 | """Mock the app engine user service""" |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 102 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 103 | def __call__(self): |
| 104 | return self |
| 105 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 106 | def user_id(self): |
| 107 | return 'foo_user' |
| 108 | |
| 109 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 110 | class UserNotLoggedInMock(object): |
| 111 | """Mock the app engine user service""" |
| 112 | |
| 113 | def __call__(self): |
| 114 | return None |
| 115 | |
| 116 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 117 | class Http2Mock(object): |
| 118 | """Mock httplib2.Http""" |
| 119 | status = 200 |
| 120 | content = { |
| 121 | 'access_token': 'foo_access_token', |
| 122 | 'refresh_token': 'foo_refresh_token', |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 123 | 'expires_in': 3600, |
Joe Gregorio | cda8752 | 2013-02-22 16:22:48 -0500 | [diff] [blame] | 124 | 'extra': 'value', |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 125 | } |
| 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 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 133 | class TestAppAssertionCredentials(unittest.TestCase): |
| 134 | account_name = "service_account_name@appspot.com" |
| 135 | signature = "signature" |
| 136 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 137 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 138 | class AppIdentityStubImpl(apiproxy_stub.APIProxyStub): |
| 139 | |
| 140 | def __init__(self): |
| 141 | super(TestAppAssertionCredentials.AppIdentityStubImpl, self).__init__( |
| 142 | 'app_identity_service') |
| 143 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 144 | def _Dynamic_GetAccessToken(self, request, response): |
| 145 | response.set_access_token('a_token_123') |
| 146 | response.set_expiration_time(time.time() + 1800) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 147 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 148 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 149 | 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.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 161 | apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 162 | app_identity_stub) |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 163 | apiproxy_stub_map.apiproxy.RegisterStub( |
| 164 | 'memcache', memcache_stub.MemcacheServiceStub()) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 165 | |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 166 | scope = 'http://www.googleapis.com/scope' |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 167 | 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 |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 174 | |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 175 | 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()) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 182 | |
Joe Gregorio | 5cf5d12 | 2012-11-16 16:36:12 -0500 | [diff] [blame] | 183 | scope = [ |
| 184 | "http://www.googleapis.com/scope", |
| 185 | "http://www.googleapis.com/scope2"] |
Joe Gregorio | d84d6b8 | 2012-02-28 14:53:00 -0500 | [diff] [blame] | 186 | credentials = AppAssertionCredentials(scope) |
| 187 | http = httplib2.Http() |
| 188 | credentials.refresh(http) |
| 189 | self.assertEqual('a_token_123', credentials.access_token) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 190 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 191 | json = credentials.to_json() |
| 192 | credentials = Credentials.new_from_json(json) |
Joe Gregorio | 5cf5d12 | 2012-11-16 16:36:12 -0500 | [diff] [blame] | 193 | self.assertEqual( |
| 194 | 'http://www.googleapis.com/scope http://www.googleapis.com/scope2', |
| 195 | credentials.scope) |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 196 | |
Joe Gregorio | 5cf5d12 | 2012-11-16 16:36:12 -0500 | [diff] [blame] | 197 | 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 Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 205 | |
Joe Gregorio | 956c120 | 2014-02-05 14:24:11 -0500 | [diff] [blame] | 206 | def test_custom_service_account(self): |
| 207 | scope = "http://www.googleapis.com/scope" |
| 208 | account_id = "service_account_name_2@appspot.com" |
| 209 | m = mox.Mox() |
| 210 | m.StubOutWithMock(app_identity, 'get_access_token') |
| 211 | app_identity.get_access_token( |
| 212 | [scope], service_account_id=account_id).AndReturn(('a_token_456', None)) |
| 213 | m.ReplayAll() |
| 214 | |
| 215 | credentials = AppAssertionCredentials(scope, service_account_id=account_id) |
| 216 | http = httplib2.Http() |
| 217 | credentials.refresh(http) |
| 218 | m.VerifyAll() |
| 219 | m.UnsetStubs() |
| 220 | self.assertEqual('a_token_456', credentials.access_token) |
| 221 | self.assertEqual(scope, credentials.scope) |
| 222 | |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 223 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 224 | class TestFlowModel(db.Model): |
| 225 | flow = FlowProperty() |
| 226 | |
| 227 | |
| 228 | class FlowPropertyTest(unittest.TestCase): |
| 229 | |
| 230 | def setUp(self): |
| 231 | self.testbed = testbed.Testbed() |
| 232 | self.testbed.activate() |
| 233 | self.testbed.init_datastore_v3_stub() |
| 234 | |
| 235 | def tearDown(self): |
| 236 | self.testbed.deactivate() |
| 237 | |
| 238 | def test_flow_get_put(self): |
| 239 | instance = TestFlowModel( |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 240 | flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo', |
| 241 | redirect_uri='oob'), |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 242 | key_name='foo' |
| 243 | ) |
| 244 | instance.put() |
| 245 | retrieved = TestFlowModel.get_by_key_name('foo') |
| 246 | |
| 247 | self.assertEqual('foo_client_id', retrieved.flow.client_id) |
| 248 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 249 | |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 250 | class TestFlowNDBModel(ndb.Model): |
| 251 | flow = FlowNDBProperty() |
| 252 | |
| 253 | |
| 254 | class FlowNDBPropertyTest(unittest.TestCase): |
| 255 | |
| 256 | def setUp(self): |
| 257 | self.testbed = testbed.Testbed() |
| 258 | self.testbed.activate() |
| 259 | self.testbed.init_datastore_v3_stub() |
| 260 | self.testbed.init_memcache_stub() |
| 261 | |
| 262 | def tearDown(self): |
| 263 | self.testbed.deactivate() |
| 264 | |
| 265 | def test_flow_get_put(self): |
| 266 | instance = TestFlowNDBModel( |
| 267 | flow=flow_from_clientsecrets(datafile('client_secrets.json'), 'foo', |
| 268 | redirect_uri='oob'), |
| 269 | id='foo' |
| 270 | ) |
| 271 | instance.put() |
| 272 | retrieved = TestFlowNDBModel.get_by_id('foo') |
| 273 | |
| 274 | self.assertEqual('foo_client_id', retrieved.flow.client_id) |
| 275 | |
| 276 | |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 277 | def _http_request(*args, **kwargs): |
| 278 | resp = httplib2.Response({'status': '200'}) |
| 279 | content = simplejson.dumps({'access_token': 'bar'}) |
| 280 | |
| 281 | return resp, content |
| 282 | |
| 283 | |
| 284 | class StorageByKeyNameTest(unittest.TestCase): |
| 285 | |
| 286 | def setUp(self): |
| 287 | self.testbed = testbed.Testbed() |
| 288 | self.testbed.activate() |
| 289 | self.testbed.init_datastore_v3_stub() |
| 290 | self.testbed.init_memcache_stub() |
| 291 | self.testbed.init_user_stub() |
| 292 | |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 293 | access_token = 'foo' |
| 294 | client_id = 'some_client_id' |
| 295 | client_secret = 'cOuDdkfjxxnv+' |
| 296 | refresh_token = '1/0/a.df219fjls0' |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 297 | token_expiry = datetime.datetime.utcnow() |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 298 | user_agent = 'refresh_checker/1.0' |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 299 | self.credentials = OAuth2Credentials( |
| 300 | access_token, client_id, client_secret, |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 301 | refresh_token, token_expiry, GOOGLE_TOKEN_URI, |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 302 | user_agent) |
| 303 | |
| 304 | def tearDown(self): |
| 305 | self.testbed.deactivate() |
| 306 | |
| 307 | def test_get_and_put_simple(self): |
| 308 | storage = StorageByKeyName( |
| 309 | CredentialsModel, 'foo', 'credentials') |
| 310 | |
| 311 | self.assertEqual(None, storage.get()) |
| 312 | self.credentials.set_store(storage) |
| 313 | |
| 314 | self.credentials._refresh(_http_request) |
| 315 | credmodel = CredentialsModel.get_by_key_name('foo') |
| 316 | self.assertEqual('bar', credmodel.credentials.access_token) |
| 317 | |
| 318 | def test_get_and_put_cached(self): |
| 319 | storage = StorageByKeyName( |
| 320 | CredentialsModel, 'foo', 'credentials', cache=memcache) |
| 321 | |
| 322 | self.assertEqual(None, storage.get()) |
| 323 | self.credentials.set_store(storage) |
| 324 | |
| 325 | self.credentials._refresh(_http_request) |
| 326 | credmodel = CredentialsModel.get_by_key_name('foo') |
| 327 | self.assertEqual('bar', credmodel.credentials.access_token) |
| 328 | |
| 329 | # Now remove the item from the cache. |
| 330 | memcache.delete('foo') |
| 331 | |
| 332 | # Check that getting refreshes the cache. |
| 333 | credentials = storage.get() |
| 334 | self.assertEqual('bar', credentials.access_token) |
| 335 | self.assertNotEqual(None, memcache.get('foo')) |
| 336 | |
| 337 | # Deleting should clear the cache. |
| 338 | storage.delete() |
| 339 | credentials = storage.get() |
| 340 | self.assertEqual(None, credentials) |
| 341 | self.assertEqual(None, memcache.get('foo')) |
| 342 | |
Joe Gregorio | e912d18 | 2013-08-06 11:30:44 -0400 | [diff] [blame] | 343 | def test_get_and_put_set_store_on_cache_retrieval(self): |
| 344 | storage = StorageByKeyName( |
| 345 | CredentialsModel, 'foo', 'credentials', cache=memcache) |
| 346 | |
| 347 | self.assertEqual(None, storage.get()) |
| 348 | self.credentials.set_store(storage) |
| 349 | storage.put(self.credentials) |
| 350 | # Pre-bug 292 old_creds wouldn't have storage, and the _refresh wouldn't |
| 351 | # be able to store the updated cred back into the storage. |
| 352 | old_creds = storage.get() |
| 353 | self.assertEqual(old_creds.access_token, 'foo') |
| 354 | old_creds.invalid = True |
| 355 | old_creds._refresh(_http_request) |
| 356 | new_creds = storage.get() |
| 357 | self.assertEqual(new_creds.access_token, 'bar') |
| 358 | |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 359 | def test_get_and_put_ndb(self): |
| 360 | # Start empty |
| 361 | storage = StorageByKeyName( |
| 362 | CredentialsNDBModel, 'foo', 'credentials') |
| 363 | self.assertEqual(None, storage.get()) |
| 364 | |
| 365 | # Refresh storage and retrieve without using storage |
| 366 | self.credentials.set_store(storage) |
| 367 | self.credentials._refresh(_http_request) |
| 368 | credmodel = CredentialsNDBModel.get_by_id('foo') |
| 369 | self.assertEqual('bar', credmodel.credentials.access_token) |
| 370 | self.assertEqual(credmodel.credentials.to_json(), |
| 371 | self.credentials.to_json()) |
| 372 | |
| 373 | def test_delete_ndb(self): |
| 374 | # Start empty |
| 375 | storage = StorageByKeyName( |
| 376 | CredentialsNDBModel, 'foo', 'credentials') |
| 377 | self.assertEqual(None, storage.get()) |
| 378 | |
| 379 | # Add credentials to model with storage, and check equivalent w/o storage |
| 380 | storage.put(self.credentials) |
| 381 | credmodel = CredentialsNDBModel.get_by_id('foo') |
| 382 | self.assertEqual(credmodel.credentials.to_json(), |
| 383 | self.credentials.to_json()) |
| 384 | |
| 385 | # Delete and make sure empty |
| 386 | storage.delete() |
| 387 | self.assertEqual(None, storage.get()) |
| 388 | |
| 389 | def test_get_and_put_mixed_ndb_storage_db_get(self): |
| 390 | # Start empty |
| 391 | storage = StorageByKeyName( |
| 392 | CredentialsNDBModel, 'foo', 'credentials') |
| 393 | self.assertEqual(None, storage.get()) |
| 394 | |
| 395 | # Set NDB store and refresh to add to storage |
| 396 | self.credentials.set_store(storage) |
| 397 | self.credentials._refresh(_http_request) |
| 398 | |
| 399 | # Retrieve same key from DB model to confirm mixing works |
| 400 | credmodel = CredentialsModel.get_by_key_name('foo') |
| 401 | self.assertEqual('bar', credmodel.credentials.access_token) |
| 402 | self.assertEqual(self.credentials.to_json(), |
| 403 | credmodel.credentials.to_json()) |
| 404 | |
| 405 | def test_get_and_put_mixed_db_storage_ndb_get(self): |
| 406 | # Start empty |
| 407 | storage = StorageByKeyName( |
| 408 | CredentialsModel, 'foo', 'credentials') |
| 409 | self.assertEqual(None, storage.get()) |
| 410 | |
| 411 | # Set DB store and refresh to add to storage |
| 412 | self.credentials.set_store(storage) |
| 413 | self.credentials._refresh(_http_request) |
| 414 | |
| 415 | # Retrieve same key from NDB model to confirm mixing works |
| 416 | credmodel = CredentialsNDBModel.get_by_id('foo') |
| 417 | self.assertEqual('bar', credmodel.credentials.access_token) |
| 418 | self.assertEqual(self.credentials.to_json(), |
| 419 | credmodel.credentials.to_json()) |
| 420 | |
| 421 | def test_delete_db_ndb_mixed(self): |
| 422 | # Start empty |
| 423 | storage_ndb = StorageByKeyName( |
| 424 | CredentialsNDBModel, 'foo', 'credentials') |
| 425 | storage = StorageByKeyName( |
| 426 | CredentialsModel, 'foo', 'credentials') |
| 427 | |
| 428 | # First DB, then NDB |
| 429 | self.assertEqual(None, storage.get()) |
| 430 | storage.put(self.credentials) |
| 431 | self.assertNotEqual(None, storage.get()) |
| 432 | |
| 433 | storage_ndb.delete() |
| 434 | self.assertEqual(None, storage.get()) |
| 435 | |
| 436 | # First NDB, then DB |
| 437 | self.assertEqual(None, storage_ndb.get()) |
| 438 | storage_ndb.put(self.credentials) |
| 439 | |
| 440 | storage.delete() |
| 441 | self.assertNotEqual(None, storage_ndb.get()) |
| 442 | # NDB uses memcache and an instance cache (Context) |
| 443 | ndb.get_context().clear_cache() |
| 444 | memcache.flush_all() |
| 445 | self.assertEqual(None, storage_ndb.get()) |
| 446 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 447 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 448 | class MockRequest(object): |
| 449 | url = 'https://example.org' |
| 450 | |
| 451 | def relative_url(self, rel): |
| 452 | return self.url + rel |
| 453 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 454 | |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 455 | class MockRequestHandler(object): |
| 456 | request = MockRequest() |
Joe Gregorio | e84c944 | 2012-03-12 08:45:57 -0400 | [diff] [blame] | 457 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 458 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 459 | class DecoratorTests(unittest.TestCase): |
| 460 | |
| 461 | def setUp(self): |
| 462 | self.testbed = testbed.Testbed() |
| 463 | self.testbed.activate() |
| 464 | self.testbed.init_datastore_v3_stub() |
| 465 | self.testbed.init_memcache_stub() |
| 466 | self.testbed.init_user_stub() |
| 467 | |
| 468 | decorator = OAuth2Decorator(client_id='foo_client_id', |
| 469 | client_secret='foo_client_secret', |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 470 | scope=['foo_scope', 'bar_scope'], |
| 471 | user_agent='foo') |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 472 | |
| 473 | self._finish_setup(decorator, user_mock=UserMock) |
| 474 | |
| 475 | def _finish_setup(self, decorator, user_mock): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 476 | self.decorator = decorator |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 477 | self.had_credentials = False |
| 478 | self.found_credentials = None |
| 479 | self.should_raise = False |
| 480 | parent = self |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 481 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 482 | class TestRequiredHandler(webapp2.RequestHandler): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 483 | @decorator.oauth_required |
| 484 | def get(self): |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 485 | if decorator.has_credentials(): |
| 486 | parent.had_credentials = True |
| 487 | parent.found_credentials = decorator.credentials |
| 488 | if parent.should_raise: |
| 489 | raise Exception('') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 490 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 491 | class TestAwareHandler(webapp2.RequestHandler): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 492 | @decorator.oauth_aware |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 493 | def get(self, *args, **kwargs): |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 494 | self.response.out.write('Hello World!') |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 495 | assert(kwargs['year'] == '2012') |
| 496 | assert(kwargs['month'] == '01') |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 497 | if decorator.has_credentials(): |
| 498 | parent.had_credentials = True |
| 499 | parent.found_credentials = decorator.credentials |
| 500 | if parent.should_raise: |
| 501 | raise Exception('') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 502 | |
| 503 | |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 504 | application = webapp2.WSGIApplication([ |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 505 | ('/oauth2callback', self.decorator.callback_handler()), |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 506 | ('/foo_path', TestRequiredHandler), |
| 507 | webapp2.Route(r'/bar_path/<year:\d{4}>/<month:\d{2}>', |
| 508 | handler=TestAwareHandler, name='bar')], |
| 509 | debug=True) |
Joe Gregorio | 77254c1 | 2012-08-27 14:13:22 -0400 | [diff] [blame] | 510 | self.app = TestApp(application, extra_environ={ |
| 511 | 'wsgi.url_scheme': 'http', |
| 512 | 'HTTP_HOST': 'localhost', |
| 513 | }) |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 514 | users.get_current_user = user_mock() |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 515 | self.httplib2_orig = httplib2.Http |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 516 | httplib2.Http = Http2Mock |
| 517 | |
| 518 | def tearDown(self): |
| 519 | self.testbed.deactivate() |
Joe Gregorio | 922b78c | 2011-05-26 21:36:34 -0400 | [diff] [blame] | 520 | httplib2.Http = self.httplib2_orig |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 521 | |
| 522 | def test_required(self): |
| 523 | # An initial request to an oauth_required decorated path should be a |
| 524 | # redirect to start the OAuth dance. |
Joe Gregorio | c211bec | 2013-08-06 12:06:54 -0400 | [diff] [blame] | 525 | self.assertEqual(self.decorator.flow, None) |
| 526 | self.assertEqual(self.decorator.credentials, None) |
Joe Gregorio | 77254c1 | 2012-08-27 14:13:22 -0400 | [diff] [blame] | 527 | response = self.app.get('http://localhost/foo_path') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 528 | self.assertTrue(response.status.startswith('302')) |
| 529 | q = parse_qs(response.headers['Location'].split('?', 1)[1]) |
| 530 | self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0]) |
| 531 | self.assertEqual('foo_client_id', q['client_id'][0]) |
Joe Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 532 | self.assertEqual('foo_scope bar_scope', q['scope'][0]) |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 533 | self.assertEqual('http://localhost/foo_path', |
| 534 | q['state'][0].rsplit(':', 1)[0]) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 535 | self.assertEqual('code', q['response_type'][0]) |
| 536 | self.assertEqual(False, self.decorator.has_credentials()) |
| 537 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 538 | m = mox.Mox() |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 539 | m.StubOutWithMock(appengine, '_parse_state_value') |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 540 | appengine._parse_state_value('foo_path:xsrfkey123', |
| 541 | mox.IgnoreArg()).AndReturn('foo_path') |
| 542 | m.ReplayAll() |
| 543 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 544 | # Now simulate the callback to /oauth2callback. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 545 | response = self.app.get('/oauth2callback', { |
| 546 | 'code': 'foo_access_code', |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 547 | 'state': 'foo_path:xsrfkey123', |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 548 | }) |
Joe Gregorio | cda8752 | 2013-02-22 16:22:48 -0500 | [diff] [blame] | 549 | parts = response.headers['Location'].split('?', 1) |
| 550 | self.assertEqual('http://localhost/foo_path', parts[0]) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 551 | self.assertEqual(None, self.decorator.credentials) |
Joe Gregorio | cda8752 | 2013-02-22 16:22:48 -0500 | [diff] [blame] | 552 | if self.decorator._token_response_param: |
Daniel Hermes | f7b648f | 2013-03-06 09:38:53 -0800 | [diff] [blame] | 553 | response = parse_qs(parts[1])[self.decorator._token_response_param][0] |
| 554 | self.assertEqual(Http2Mock.content, |
| 555 | simplejson.loads(urllib.unquote(response))) |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 556 | self.assertEqual(self.decorator.flow, self.decorator._tls.flow) |
| 557 | self.assertEqual(self.decorator.credentials, |
| 558 | self.decorator._tls.credentials) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 559 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 560 | m.UnsetStubs() |
| 561 | m.VerifyAll() |
| 562 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 563 | # Now requesting the decorated path should work. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 564 | response = self.app.get('/foo_path') |
| 565 | self.assertEqual('200 OK', response.status) |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 566 | self.assertEqual(True, self.had_credentials) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 567 | self.assertEqual('foo_refresh_token', |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 568 | self.found_credentials.refresh_token) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 569 | self.assertEqual('foo_access_token', |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 570 | self.found_credentials.access_token) |
| 571 | self.assertEqual(None, self.decorator.credentials) |
| 572 | |
| 573 | # Raising an exception still clears the Credentials. |
| 574 | self.should_raise = True |
| 575 | try: |
| 576 | response = self.app.get('/foo_path') |
| 577 | self.fail('Should have raised an exception.') |
| 578 | except Exception: |
| 579 | pass |
| 580 | self.assertEqual(None, self.decorator.credentials) |
| 581 | self.should_raise = False |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 582 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 583 | # Invalidate the stored Credentials. |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 584 | self.found_credentials.invalid = True |
| 585 | self.found_credentials.store.put(self.found_credentials) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 586 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 587 | # Invalid Credentials should start the OAuth dance again. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 588 | response = self.app.get('/foo_path') |
| 589 | self.assertTrue(response.status.startswith('302')) |
| 590 | q = parse_qs(response.headers['Location'].split('?', 1)[1]) |
| 591 | self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0]) |
| 592 | |
Joe Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 593 | def test_storage_delete(self): |
| 594 | # An initial request to an oauth_required decorated path should be a |
| 595 | # redirect to start the OAuth dance. |
| 596 | response = self.app.get('/foo_path') |
| 597 | self.assertTrue(response.status.startswith('302')) |
| 598 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 599 | m = mox.Mox() |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 600 | m.StubOutWithMock(appengine, '_parse_state_value') |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 601 | appengine._parse_state_value('foo_path:xsrfkey123', |
| 602 | mox.IgnoreArg()).AndReturn('foo_path') |
| 603 | m.ReplayAll() |
| 604 | |
Joe Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 605 | # Now simulate the callback to /oauth2callback. |
| 606 | response = self.app.get('/oauth2callback', { |
| 607 | 'code': 'foo_access_code', |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 608 | 'state': 'foo_path:xsrfkey123', |
Joe Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 609 | }) |
| 610 | self.assertEqual('http://localhost/foo_path', response.headers['Location']) |
| 611 | self.assertEqual(None, self.decorator.credentials) |
| 612 | |
| 613 | # Now requesting the decorated path should work. |
| 614 | response = self.app.get('/foo_path') |
| 615 | |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 616 | self.assertTrue(self.had_credentials) |
| 617 | |
| 618 | # Credentials should be cleared after each call. |
| 619 | self.assertEqual(None, self.decorator.credentials) |
| 620 | |
Joe Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 621 | # Invalidate the stored Credentials. |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 622 | self.found_credentials.store.delete() |
Joe Gregorio | ec75dc1 | 2012-02-06 13:40:42 -0500 | [diff] [blame] | 623 | |
| 624 | # Invalid Credentials should start the OAuth dance again. |
| 625 | response = self.app.get('/foo_path') |
| 626 | self.assertTrue(response.status.startswith('302')) |
| 627 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 628 | m.UnsetStubs() |
| 629 | m.VerifyAll() |
| 630 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 631 | def test_aware(self): |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 632 | # An initial request to an oauth_aware decorated path should not redirect. |
Joe Gregorio | 77254c1 | 2012-08-27 14:13:22 -0400 | [diff] [blame] | 633 | response = self.app.get('http://localhost/bar_path/2012/01') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 634 | self.assertEqual('Hello World!', response.body) |
| 635 | self.assertEqual('200 OK', response.status) |
| 636 | self.assertEqual(False, self.decorator.has_credentials()) |
| 637 | url = self.decorator.authorize_url() |
| 638 | q = parse_qs(url.split('?', 1)[1]) |
| 639 | self.assertEqual('http://localhost/oauth2callback', q['redirect_uri'][0]) |
| 640 | self.assertEqual('foo_client_id', q['client_id'][0]) |
Joe Gregorio | f2f8a5a | 2011-10-14 15:11:29 -0400 | [diff] [blame] | 641 | self.assertEqual('foo_scope bar_scope', q['scope'][0]) |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 642 | self.assertEqual('http://localhost/bar_path/2012/01', |
| 643 | q['state'][0].rsplit(':', 1)[0]) |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 644 | self.assertEqual('code', q['response_type'][0]) |
| 645 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 646 | m = mox.Mox() |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 647 | m.StubOutWithMock(appengine, '_parse_state_value') |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 648 | appengine._parse_state_value('bar_path:xsrfkey456', |
| 649 | mox.IgnoreArg()).AndReturn('bar_path') |
| 650 | m.ReplayAll() |
| 651 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 652 | # Now simulate the callback to /oauth2callback. |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 653 | url = self.decorator.authorize_url() |
| 654 | response = self.app.get('/oauth2callback', { |
| 655 | 'code': 'foo_access_code', |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 656 | 'state': 'bar_path:xsrfkey456', |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 657 | }) |
| 658 | self.assertEqual('http://localhost/bar_path', response.headers['Location']) |
| 659 | self.assertEqual(False, self.decorator.has_credentials()) |
| 660 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 661 | m.UnsetStubs() |
| 662 | m.VerifyAll() |
| 663 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 664 | # Now requesting the decorated path will have credentials. |
Joe Gregorio | 1777497 | 2012-03-01 11:11:59 -0500 | [diff] [blame] | 665 | response = self.app.get('/bar_path/2012/01') |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 666 | self.assertEqual('200 OK', response.status) |
| 667 | self.assertEqual('Hello World!', response.body) |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 668 | self.assertEqual(True, self.had_credentials) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 669 | self.assertEqual('foo_refresh_token', |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 670 | self.found_credentials.refresh_token) |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 671 | self.assertEqual('foo_access_token', |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 672 | self.found_credentials.access_token) |
| 673 | |
| 674 | # Credentials should be cleared after each call. |
| 675 | self.assertEqual(None, self.decorator.credentials) |
| 676 | |
| 677 | # Raising an exception still clears the Credentials. |
| 678 | self.should_raise = True |
| 679 | try: |
| 680 | response = self.app.get('/bar_path/2012/01') |
| 681 | self.fail('Should have raised an exception.') |
| 682 | except Exception: |
| 683 | pass |
| 684 | self.assertEqual(None, self.decorator.credentials) |
| 685 | self.should_raise = False |
| 686 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 687 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 688 | def test_error_in_step2(self): |
| 689 | # An initial request to an oauth_aware decorated path should not redirect. |
| 690 | response = self.app.get('/bar_path/2012/01') |
| 691 | url = self.decorator.authorize_url() |
| 692 | response = self.app.get('/oauth2callback', { |
Joe Gregorio | 77254c1 | 2012-08-27 14:13:22 -0400 | [diff] [blame] | 693 | 'error': 'Bad<Stuff>Happened\'' |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 694 | }) |
| 695 | self.assertEqual('200 OK', response.status) |
Joe Gregorio | 77254c1 | 2012-08-27 14:13:22 -0400 | [diff] [blame] | 696 | self.assertTrue('Bad<Stuff>Happened'' in response.body) |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 697 | |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 698 | def test_kwargs_are_passed_to_underlying_flow(self): |
| 699 | decorator = OAuth2Decorator(client_id='foo_client_id', |
| 700 | client_secret='foo_client_secret', |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 701 | user_agent='foo_user_agent', |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 702 | scope=['foo_scope', 'bar_scope'], |
| 703 | access_type='offline', |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 704 | approval_prompt='force', |
| 705 | revoke_uri='dummy_revoke_uri') |
Joe Gregorio | 68a8cfe | 2012-08-03 16:17:40 -0400 | [diff] [blame] | 706 | request_handler = MockRequestHandler() |
| 707 | decorator._create_flow(request_handler) |
| 708 | |
| 709 | self.assertEqual('https://example.org/oauth2callback', |
| 710 | decorator.flow.redirect_uri) |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 711 | self.assertEqual('offline', decorator.flow.params['access_type']) |
| 712 | self.assertEqual('force', decorator.flow.params['approval_prompt']) |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 713 | self.assertEqual('foo_user_agent', decorator.flow.user_agent) |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 714 | self.assertEqual('dummy_revoke_uri', decorator.flow.revoke_uri) |
Johan Euphrosine | acf517f | 2012-02-13 21:08:33 +0100 | [diff] [blame] | 715 | self.assertEqual(None, decorator.flow.params.get('user_agent', None)) |
Joe Gregorio | b8b6fea | 2013-05-16 15:52:57 -0400 | [diff] [blame] | 716 | self.assertEqual(decorator.flow, decorator._tls.flow) |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 717 | |
Joe Gregorio | cda8752 | 2013-02-22 16:22:48 -0500 | [diff] [blame] | 718 | def test_token_response_param(self): |
| 719 | self.decorator._token_response_param = 'foobar' |
| 720 | self.test_required() |
| 721 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 722 | def test_decorator_from_client_secrets(self): |
| 723 | decorator = oauth2decorator_from_clientsecrets( |
| 724 | datafile('client_secrets.json'), |
| 725 | scope=['foo_scope', 'bar_scope']) |
| 726 | self._finish_setup(decorator, user_mock=UserMock) |
| 727 | |
| 728 | self.assertFalse(decorator._in_error) |
| 729 | self.decorator = decorator |
| 730 | self.test_required() |
| 731 | http = self.decorator.http() |
| 732 | self.assertEquals('foo_access_token', http.request.credentials.access_token) |
| 733 | |
dhermes@google.com | a9eb0bb | 2013-02-06 09:19:01 -0800 | [diff] [blame] | 734 | # revoke_uri is not required |
| 735 | self.assertEqual(self.decorator._revoke_uri, |
| 736 | 'https://accounts.google.com/o/oauth2/revoke') |
| 737 | self.assertEqual(self.decorator._revoke_uri, |
| 738 | self.decorator.credentials.revoke_uri) |
| 739 | |
Joe Gregorio | c29aaa9 | 2012-07-16 16:16:31 -0400 | [diff] [blame] | 740 | def test_decorator_from_cached_client_secrets(self): |
| 741 | cache_mock = CacheMock() |
| 742 | load_and_cache('client_secrets.json', 'secret', cache_mock) |
| 743 | decorator = oauth2decorator_from_clientsecrets( |
| 744 | # filename, scope, message=None, cache=None |
| 745 | 'secret', '', cache=cache_mock) |
| 746 | self.assertFalse(decorator._in_error) |
| 747 | |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 748 | def test_decorator_from_client_secrets_not_logged_in_required(self): |
| 749 | decorator = oauth2decorator_from_clientsecrets( |
| 750 | datafile('client_secrets.json'), |
| 751 | scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') |
| 752 | self.decorator = decorator |
| 753 | self._finish_setup(decorator, user_mock=UserNotLoggedInMock) |
| 754 | |
| 755 | self.assertFalse(decorator._in_error) |
| 756 | |
| 757 | # An initial request to an oauth_required decorated path should be a |
| 758 | # redirect to login. |
| 759 | response = self.app.get('/foo_path') |
| 760 | self.assertTrue(response.status.startswith('302')) |
| 761 | self.assertTrue('Login' in str(response)) |
| 762 | |
| 763 | def test_decorator_from_client_secrets_not_logged_in_aware(self): |
| 764 | decorator = oauth2decorator_from_clientsecrets( |
| 765 | datafile('client_secrets.json'), |
| 766 | scope=['foo_scope', 'bar_scope'], message='NotLoggedInMessage') |
| 767 | self.decorator = decorator |
| 768 | self._finish_setup(decorator, user_mock=UserNotLoggedInMock) |
| 769 | |
| 770 | # An initial request to an oauth_aware decorated path should be a |
| 771 | # redirect to login. |
| 772 | response = self.app.get('/bar_path/2012/03') |
| 773 | self.assertTrue(response.status.startswith('302')) |
| 774 | self.assertTrue('Login' in str(response)) |
| 775 | |
| 776 | def test_decorator_from_unfilled_client_secrets_required(self): |
| 777 | MESSAGE = 'File is missing' |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 778 | try: |
| 779 | decorator = oauth2decorator_from_clientsecrets( |
| 780 | datafile('unfilled_client_secrets.json'), |
| 781 | scope=['foo_scope', 'bar_scope'], message=MESSAGE) |
| 782 | except InvalidClientSecretsError: |
| 783 | pass |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 784 | |
| 785 | def test_decorator_from_unfilled_client_secrets_aware(self): |
| 786 | MESSAGE = 'File is missing' |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 787 | try: |
| 788 | decorator = oauth2decorator_from_clientsecrets( |
| 789 | datafile('unfilled_client_secrets.json'), |
| 790 | scope=['foo_scope', 'bar_scope'], message=MESSAGE) |
| 791 | except InvalidClientSecretsError: |
| 792 | pass |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 793 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 794 | |
| 795 | class DecoratorXsrfSecretTests(unittest.TestCase): |
| 796 | """Test xsrf_secret_key.""" |
| 797 | |
| 798 | def setUp(self): |
| 799 | self.testbed = testbed.Testbed() |
| 800 | self.testbed.activate() |
| 801 | self.testbed.init_datastore_v3_stub() |
| 802 | self.testbed.init_memcache_stub() |
| 803 | |
| 804 | def tearDown(self): |
| 805 | self.testbed.deactivate() |
| 806 | |
| 807 | def test_build_and_parse_state(self): |
| 808 | secret = appengine.xsrf_secret_key() |
| 809 | |
| 810 | # Secret shouldn't change from call to call. |
| 811 | secret2 = appengine.xsrf_secret_key() |
| 812 | self.assertEqual(secret, secret2) |
| 813 | |
| 814 | # Secret shouldn't change if memcache goes away. |
| 815 | memcache.delete(appengine.XSRF_MEMCACHE_ID, |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 816 | namespace=appengine.OAUTH2CLIENT_NAMESPACE) |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 817 | secret3 = appengine.xsrf_secret_key() |
| 818 | self.assertEqual(secret2, secret3) |
| 819 | |
| 820 | # Secret should change if both memcache and the model goes away. |
| 821 | memcache.delete(appengine.XSRF_MEMCACHE_ID, |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 822 | namespace=appengine.OAUTH2CLIENT_NAMESPACE) |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 823 | model = appengine.SiteXsrfSecretKey.get_or_insert('site') |
| 824 | model.delete() |
| 825 | |
| 826 | secret4 = appengine.xsrf_secret_key() |
| 827 | self.assertNotEqual(secret3, secret4) |
| 828 | |
dhermes@google.com | 4715482 | 2012-11-26 10:44:09 -0800 | [diff] [blame] | 829 | def test_ndb_insert_db_get(self): |
| 830 | secret = appengine._generate_new_xsrf_secret_key() |
| 831 | appengine.SiteXsrfSecretKeyNDB(id='site', secret=secret).put() |
| 832 | |
| 833 | site_key = appengine.SiteXsrfSecretKey.get_by_key_name('site') |
| 834 | self.assertEqual(site_key.secret, secret) |
| 835 | |
| 836 | def test_db_insert_ndb_get(self): |
| 837 | secret = appengine._generate_new_xsrf_secret_key() |
| 838 | appengine.SiteXsrfSecretKey(key_name='site', secret=secret).put() |
| 839 | |
| 840 | site_key = appengine.SiteXsrfSecretKeyNDB.get_by_id('site') |
| 841 | self.assertEqual(site_key.secret, secret) |
| 842 | |
Joe Gregorio | 6ceea2d | 2012-08-24 11:57:58 -0400 | [diff] [blame] | 843 | |
| 844 | class DecoratorXsrfProtectionTests(unittest.TestCase): |
| 845 | """Test _build_state_value and _parse_state_value.""" |
| 846 | |
| 847 | def setUp(self): |
| 848 | self.testbed = testbed.Testbed() |
| 849 | self.testbed.activate() |
| 850 | self.testbed.init_datastore_v3_stub() |
| 851 | self.testbed.init_memcache_stub() |
| 852 | |
| 853 | def tearDown(self): |
| 854 | self.testbed.deactivate() |
| 855 | |
| 856 | def test_build_and_parse_state(self): |
| 857 | state = appengine._build_state_value(MockRequestHandler(), UserMock()) |
| 858 | self.assertEqual( |
| 859 | 'https://example.org', |
| 860 | appengine._parse_state_value(state, UserMock())) |
| 861 | self.assertRaises(appengine.InvalidXsrfTokenError, |
| 862 | appengine._parse_state_value, state[1:], UserMock()) |
Joe Gregorio | 08cdcb8 | 2012-03-14 00:09:33 -0400 | [diff] [blame] | 863 | |
Joe Gregorio | 1adde1a | 2012-01-06 12:30:35 -0500 | [diff] [blame] | 864 | |
Joe Gregorio | 432f17e | 2011-05-22 23:18:00 -0400 | [diff] [blame] | 865 | if __name__ == '__main__': |
| 866 | unittest.main() |