Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [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 | |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 18 | """Oauth2client tests |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 19 | |
Joe Gregorio | 0bc7091 | 2011-05-24 15:30:49 -0400 | [diff] [blame] | 20 | Unit tests for oauth2client. |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 21 | """ |
| 22 | |
| 23 | __author__ = 'jcgregorio@google.com (Joe Gregorio)' |
| 24 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 25 | import base64 |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 26 | import datetime |
Joe Gregorio | e1de416 | 2011-02-23 11:30:29 -0500 | [diff] [blame] | 27 | import httplib2 |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 28 | import unittest |
| 29 | import urlparse |
Joe Gregorio | e1de416 | 2011-02-23 11:30:29 -0500 | [diff] [blame] | 30 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 31 | try: |
| 32 | from urlparse import parse_qs |
| 33 | except ImportError: |
| 34 | from cgi import parse_qs |
| 35 | |
| 36 | from apiclient.http import HttpMockSequence |
Joe Gregorio | 549230c | 2012-01-11 10:38:05 -0500 | [diff] [blame] | 37 | from oauth2client.anyjson import simplejson |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 38 | from oauth2client.client import AccessTokenCredentials |
| 39 | from oauth2client.client import AccessTokenCredentialsError |
| 40 | from oauth2client.client import AccessTokenRefreshError |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 41 | from oauth2client.client import AssertionCredentials |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 42 | from oauth2client.client import FlowExchangeError |
| 43 | from oauth2client.client import OAuth2Credentials |
| 44 | from oauth2client.client import OAuth2WebServerFlow |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 45 | from oauth2client.client import VerifyJwtTokenError |
| 46 | from oauth2client.client import _extract_id_token |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 47 | |
| 48 | |
| 49 | class OAuth2CredentialsTests(unittest.TestCase): |
| 50 | |
| 51 | def setUp(self): |
| 52 | access_token = "foo" |
| 53 | client_id = "some_client_id" |
| 54 | client_secret = "cOuDdkfjxxnv+" |
| 55 | refresh_token = "1/0/a.df219fjls0" |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 56 | token_expiry = datetime.datetime.utcnow() |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 57 | token_uri = "https://www.google.com/accounts/o8/oauth2/token" |
| 58 | user_agent = "refresh_checker/1.0" |
| 59 | self.credentials = OAuth2Credentials( |
| 60 | access_token, client_id, client_secret, |
| 61 | refresh_token, token_expiry, token_uri, |
| 62 | user_agent) |
| 63 | |
| 64 | def test_token_refresh_success(self): |
| 65 | http = HttpMockSequence([ |
| 66 | ({'status': '401'}, ''), |
| 67 | ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'), |
| 68 | ({'status': '200'}, 'echo_request_headers'), |
| 69 | ]) |
| 70 | http = self.credentials.authorize(http) |
| 71 | resp, content = http.request("http://example.com") |
| 72 | self.assertEqual(content['authorization'], 'OAuth 1/3w') |
| 73 | |
| 74 | def test_token_refresh_failure(self): |
| 75 | http = HttpMockSequence([ |
| 76 | ({'status': '401'}, ''), |
| 77 | ({'status': '400'}, '{"error":"access_denied"}'), |
| 78 | ]) |
| 79 | http = self.credentials.authorize(http) |
| 80 | try: |
| 81 | http.request("http://example.com") |
| 82 | self.fail("should raise AccessTokenRefreshError exception") |
| 83 | except AccessTokenRefreshError: |
| 84 | pass |
| 85 | |
| 86 | def test_non_401_error_response(self): |
| 87 | http = HttpMockSequence([ |
| 88 | ({'status': '400'}, ''), |
| 89 | ]) |
| 90 | http = self.credentials.authorize(http) |
| 91 | resp, content = http.request("http://example.com") |
| 92 | self.assertEqual(400, resp.status) |
| 93 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 94 | def test_to_from_json(self): |
| 95 | json = self.credentials.to_json() |
| 96 | instance = OAuth2Credentials.from_json(json) |
| 97 | self.assertEquals(type(instance), OAuth2Credentials) |
Joe Gregorio | 1daa71b | 2011-09-15 18:12:14 -0400 | [diff] [blame] | 98 | instance.token_expiry = None |
| 99 | self.credentials.token_expiry = None |
| 100 | |
Joe Gregorio | 562b731 | 2011-09-15 09:06:38 -0400 | [diff] [blame] | 101 | self.assertEquals(self.credentials.__dict__, instance.__dict__) |
| 102 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 103 | |
| 104 | class AccessTokenCredentialsTests(unittest.TestCase): |
| 105 | |
| 106 | def setUp(self): |
| 107 | access_token = "foo" |
| 108 | user_agent = "refresh_checker/1.0" |
| 109 | self.credentials = AccessTokenCredentials(access_token, user_agent) |
| 110 | |
| 111 | def test_token_refresh_success(self): |
| 112 | http = HttpMockSequence([ |
| 113 | ({'status': '401'}, ''), |
| 114 | ]) |
| 115 | http = self.credentials.authorize(http) |
| 116 | try: |
| 117 | resp, content = http.request("http://example.com") |
| 118 | self.fail("should throw exception if token expires") |
| 119 | except AccessTokenCredentialsError: |
| 120 | pass |
| 121 | except Exception: |
| 122 | self.fail("should only throw AccessTokenCredentialsError") |
| 123 | |
| 124 | def test_non_401_error_response(self): |
| 125 | http = HttpMockSequence([ |
| 126 | ({'status': '400'}, ''), |
| 127 | ]) |
| 128 | http = self.credentials.authorize(http) |
Joe Gregorio | 83cd439 | 2011-06-20 10:11:35 -0400 | [diff] [blame] | 129 | resp, content = http.request('http://example.com') |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 130 | self.assertEqual(400, resp.status) |
| 131 | |
Joe Gregorio | 83cd439 | 2011-06-20 10:11:35 -0400 | [diff] [blame] | 132 | def test_auth_header_sent(self): |
| 133 | http = HttpMockSequence([ |
| 134 | ({'status': '200'}, 'echo_request_headers'), |
| 135 | ]) |
| 136 | http = self.credentials.authorize(http) |
| 137 | resp, content = http.request('http://example.com') |
| 138 | self.assertEqual(content['authorization'], 'OAuth foo') |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 139 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 140 | |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 141 | class TestAssertionCredentials(unittest.TestCase): |
| 142 | assertion_text = "This is the assertion" |
| 143 | assertion_type = "http://www.google.com/assertionType" |
| 144 | |
| 145 | class AssertionCredentialsTestImpl(AssertionCredentials): |
| 146 | |
| 147 | def _generate_assertion(self): |
| 148 | return TestAssertionCredentials.assertion_text |
| 149 | |
| 150 | def setUp(self): |
| 151 | user_agent = "fun/2.0" |
| 152 | self.credentials = self.AssertionCredentialsTestImpl(self.assertion_type, |
| 153 | user_agent) |
| 154 | |
| 155 | def test_assertion_body(self): |
| 156 | body = urlparse.parse_qs(self.credentials._generate_refresh_request_body()) |
| 157 | self.assertEqual(body['assertion'][0], self.assertion_text) |
| 158 | self.assertEqual(body['assertion_type'][0], self.assertion_type) |
| 159 | |
| 160 | def test_assertion_refresh(self): |
| 161 | http = HttpMockSequence([ |
| 162 | ({'status': '200'}, '{"access_token":"1/3w"}'), |
| 163 | ({'status': '200'}, 'echo_request_headers'), |
| 164 | ]) |
| 165 | http = self.credentials.authorize(http) |
| 166 | resp, content = http.request("http://example.com") |
| 167 | self.assertEqual(content['authorization'], 'OAuth 1/3w') |
| 168 | |
| 169 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 170 | class ExtractIdTokenText(unittest.TestCase): |
| 171 | """Tests _extract_id_token().""" |
| 172 | |
| 173 | def test_extract_success(self): |
| 174 | body = {'foo': 'bar'} |
| 175 | payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=') |
| 176 | jwt = 'stuff.' + payload + '.signature' |
| 177 | |
| 178 | extracted = _extract_id_token(jwt) |
| 179 | self.assertEqual(body, extracted) |
| 180 | |
| 181 | def test_extract_failure(self): |
| 182 | body = {'foo': 'bar'} |
| 183 | payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=') |
| 184 | jwt = 'stuff.' + payload |
| 185 | |
| 186 | self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt) |
| 187 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 188 | class OAuth2WebServerFlowTest(unittest.TestCase): |
| 189 | |
| 190 | def setUp(self): |
| 191 | self.flow = OAuth2WebServerFlow( |
| 192 | client_id='client_id+1', |
| 193 | client_secret='secret+1', |
| 194 | scope='foo', |
| 195 | user_agent='unittest-sample/1.0', |
| 196 | ) |
| 197 | |
| 198 | def test_construct_authorize_url(self): |
| 199 | authorize_url = self.flow.step1_get_authorize_url('oob') |
| 200 | |
| 201 | parsed = urlparse.urlparse(authorize_url) |
| 202 | q = parse_qs(parsed[4]) |
| 203 | self.assertEqual(q['client_id'][0], 'client_id+1') |
| 204 | self.assertEqual(q['response_type'][0], 'code') |
| 205 | self.assertEqual(q['scope'][0], 'foo') |
| 206 | self.assertEqual(q['redirect_uri'][0], 'oob') |
Joe Gregorio | 69a0aca | 2011-11-03 10:47:32 -0400 | [diff] [blame] | 207 | self.assertEqual(q['access_type'][0], 'offline') |
| 208 | |
| 209 | def test_override_flow_access_type(self): |
| 210 | """Passing access_type overrides the default.""" |
| 211 | flow = OAuth2WebServerFlow( |
| 212 | client_id='client_id+1', |
| 213 | client_secret='secret+1', |
| 214 | scope='foo', |
| 215 | user_agent='unittest-sample/1.0', |
| 216 | access_type='online' |
| 217 | ) |
| 218 | authorize_url = flow.step1_get_authorize_url('oob') |
| 219 | |
| 220 | parsed = urlparse.urlparse(authorize_url) |
| 221 | q = parse_qs(parsed[4]) |
| 222 | self.assertEqual(q['client_id'][0], 'client_id+1') |
| 223 | self.assertEqual(q['response_type'][0], 'code') |
| 224 | self.assertEqual(q['scope'][0], 'foo') |
| 225 | self.assertEqual(q['redirect_uri'][0], 'oob') |
| 226 | self.assertEqual(q['access_type'][0], 'online') |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 227 | |
| 228 | def test_exchange_failure(self): |
| 229 | http = HttpMockSequence([ |
JacobMoshenko | 8e90510 | 2011-06-20 09:53:10 -0400 | [diff] [blame] | 230 | ({'status': '400'}, '{"error":"invalid_request"}'), |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 231 | ]) |
| 232 | |
| 233 | try: |
| 234 | credentials = self.flow.step2_exchange('some random code', http) |
| 235 | self.fail("should raise exception if exchange doesn't get 200") |
| 236 | except FlowExchangeError: |
| 237 | pass |
| 238 | |
| 239 | def test_exchange_success(self): |
| 240 | http = HttpMockSequence([ |
| 241 | ({'status': '200'}, |
| 242 | """{ "access_token":"SlAV32hkKG", |
| 243 | "expires_in":3600, |
| 244 | "refresh_token":"8xLOxBtZp8" }"""), |
| 245 | ]) |
| 246 | |
| 247 | credentials = self.flow.step2_exchange('some random code', http) |
| 248 | self.assertEqual(credentials.access_token, 'SlAV32hkKG') |
| 249 | self.assertNotEqual(credentials.token_expiry, None) |
| 250 | self.assertEqual(credentials.refresh_token, '8xLOxBtZp8') |
| 251 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 252 | def test_exchange_no_expires_in(self): |
| 253 | http = HttpMockSequence([ |
| 254 | ({'status': '200'}, """{ "access_token":"SlAV32hkKG", |
| 255 | "refresh_token":"8xLOxBtZp8" }"""), |
| 256 | ]) |
| 257 | |
| 258 | credentials = self.flow.step2_exchange('some random code', http) |
| 259 | self.assertEqual(credentials.token_expiry, None) |
| 260 | |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 261 | def test_exchange_id_token_fail(self): |
| 262 | http = HttpMockSequence([ |
| 263 | ({'status': '200'}, """{ "access_token":"SlAV32hkKG", |
| 264 | "refresh_token":"8xLOxBtZp8", |
| 265 | "id_token": "stuff.payload"}"""), |
| 266 | ]) |
| 267 | |
| 268 | self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange, |
| 269 | 'some random code', http) |
| 270 | |
| 271 | def test_exchange_id_token_fail(self): |
| 272 | body = {'foo': 'bar'} |
| 273 | payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=') |
Joe Gregorio | bd512b5 | 2011-12-06 15:39:26 -0500 | [diff] [blame] | 274 | jwt = (base64.urlsafe_b64encode('stuff')+ '.' + payload + '.' + |
| 275 | base64.urlsafe_b64encode('signature')) |
Joe Gregorio | 8b4c173 | 2011-12-06 11:28:29 -0500 | [diff] [blame] | 276 | |
| 277 | http = HttpMockSequence([ |
| 278 | ({'status': '200'}, """{ "access_token":"SlAV32hkKG", |
| 279 | "refresh_token":"8xLOxBtZp8", |
| 280 | "id_token": "%s"}""" % jwt), |
| 281 | ]) |
| 282 | |
| 283 | credentials = self.flow.step2_exchange('some random code', http) |
| 284 | self.assertEquals(body, credentials.id_token) |
| 285 | |
Joe Gregorio | ccc7954 | 2011-02-19 00:05:26 -0500 | [diff] [blame] | 286 | |
| 287 | if __name__ == '__main__': |
| 288 | unittest.main() |