blob: dfcbf72b68472926f2bf3829b7763c68ece082a6 [file] [log] [blame]
Joe Gregorioccc79542011-02-19 00:05:26 -05001#!/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 Gregorio0bc70912011-05-24 15:30:49 -040018"""Oauth2client tests
Joe Gregorioccc79542011-02-19 00:05:26 -050019
Joe Gregorio0bc70912011-05-24 15:30:49 -040020Unit tests for oauth2client.
Joe Gregorioccc79542011-02-19 00:05:26 -050021"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
Joe Gregorio8b4c1732011-12-06 11:28:29 -050025import base64
Joe Gregorio562b7312011-09-15 09:06:38 -040026import datetime
Joe Gregorioe1de4162011-02-23 11:30:29 -050027import httplib2
Joe Gregorioccc79542011-02-19 00:05:26 -050028import unittest
29import urlparse
Joe Gregorioe1de4162011-02-23 11:30:29 -050030
Joe Gregorioccc79542011-02-19 00:05:26 -050031try:
32 from urlparse import parse_qs
33except ImportError:
34 from cgi import parse_qs
35
36from apiclient.http import HttpMockSequence
Joe Gregorio549230c2012-01-11 10:38:05 -050037from oauth2client.anyjson import simplejson
Joe Gregorioccc79542011-02-19 00:05:26 -050038from oauth2client.client import AccessTokenCredentials
39from oauth2client.client import AccessTokenCredentialsError
40from oauth2client.client import AccessTokenRefreshError
JacobMoshenko8e905102011-06-20 09:53:10 -040041from oauth2client.client import AssertionCredentials
Joe Gregorioccc79542011-02-19 00:05:26 -050042from oauth2client.client import FlowExchangeError
43from oauth2client.client import OAuth2Credentials
44from oauth2client.client import OAuth2WebServerFlow
Joe Gregorio8b4c1732011-12-06 11:28:29 -050045from oauth2client.client import VerifyJwtTokenError
46from oauth2client.client import _extract_id_token
Joe Gregorioccc79542011-02-19 00:05:26 -050047
48
49class 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 Gregorio562b7312011-09-15 09:06:38 -040056 token_expiry = datetime.datetime.utcnow()
Joe Gregorioccc79542011-02-19 00:05:26 -050057 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 Gregorio562b7312011-09-15 09:06:38 -040094 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 Gregorio1daa71b2011-09-15 18:12:14 -040098 instance.token_expiry = None
99 self.credentials.token_expiry = None
100
Joe Gregorio562b7312011-09-15 09:06:38 -0400101 self.assertEquals(self.credentials.__dict__, instance.__dict__)
102
Joe Gregorioccc79542011-02-19 00:05:26 -0500103
104class 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 Gregorio83cd4392011-06-20 10:11:35 -0400129 resp, content = http.request('http://example.com')
Joe Gregorioccc79542011-02-19 00:05:26 -0500130 self.assertEqual(400, resp.status)
131
Joe Gregorio83cd4392011-06-20 10:11:35 -0400132 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 Gregorioccc79542011-02-19 00:05:26 -0500139
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500140
JacobMoshenko8e905102011-06-20 09:53:10 -0400141class 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 Gregorio8b4c1732011-12-06 11:28:29 -0500170class 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 Gregorioccc79542011-02-19 00:05:26 -0500188class 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 Gregorio69a0aca2011-11-03 10:47:32 -0400207 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 Gregorioccc79542011-02-19 00:05:26 -0500227
228 def test_exchange_failure(self):
229 http = HttpMockSequence([
JacobMoshenko8e905102011-06-20 09:53:10 -0400230 ({'status': '400'}, '{"error":"invalid_request"}'),
Joe Gregorioccc79542011-02-19 00:05:26 -0500231 ])
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 Gregorioccc79542011-02-19 00:05:26 -0500252 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 Gregorio8b4c1732011-12-06 11:28:29 -0500261 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 Gregoriobd512b52011-12-06 15:39:26 -0500274 jwt = (base64.urlsafe_b64encode('stuff')+ '.' + payload + '.' +
275 base64.urlsafe_b64encode('signature'))
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500276
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 Gregorioccc79542011-02-19 00:05:26 -0500286
287if __name__ == '__main__':
288 unittest.main()