Debian Codegraph @

keystoneclient/tests/unit/v3/test_oauth1.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 from unittest import mock
15
16 import fixtures
17 from urllib import parse as urlparse
18 import uuid
19
20 from testtools import matchers
21
22 from keystoneclient import session
23 from keystoneclient.tests.unit.v3 import client_fixtures
24 from keystoneclient.tests.unit.v3 import utils
25 from keystoneclient import utils as client_utils
26 from keystoneclient.v3.contrib.oauth1 import access_tokens
27 from keystoneclient.v3.contrib.oauth1 import auth
28 from keystoneclient.v3.contrib.oauth1 import consumers
29 from keystoneclient.v3.contrib.oauth1 import request_tokens
30
31 try:
32 from oauthlib import oauth1
33 except ImportError:
34 oauth1 = None
35
36
37 class ConsumerTests(utils.ClientTestCase, utils.CrudTests):
38 def setUp(self):
39 if oauth1 is None:
40 self.skipTest('oauthlib package not available')
41
42 super(ConsumerTests, self).setUp()
43 self.key = 'consumer'
44 self.collection_key = 'consumers'
45 self.model = consumers.Consumer
46 self.manager = self.client.oauth1.consumers
47 self.path_prefix = 'OS-OAUTH1'
48
49 def new_ref(self, **kwargs):
50 kwargs = super(ConsumerTests, self).new_ref(**kwargs)
51 kwargs.setdefault('description', uuid.uuid4().hex)
52 return kwargs
53
54 def test_description_is_optional(self):
55 consumer_id = uuid.uuid4().hex
56 resp_ref = {'consumer': {'description': None,
57 'id': consumer_id}}
58
59 self.stub_url('POST',
60 [self.path_prefix, self.collection_key],
61 status_code=201, json=resp_ref)
62
63 consumer = self.manager.create()
64 self.assertEqual(consumer_id, consumer.id)
65 self.assertIsNone(consumer.description)
66
67 def test_description_not_included(self):
68 consumer_id = uuid.uuid4().hex
69 resp_ref = {'consumer': {'id': consumer_id}}
70
71 self.stub_url('POST',
72 [self.path_prefix, self.collection_key],
73 status_code=201, json=resp_ref)
74
75 consumer = self.manager.create()
76 self.assertEqual(consumer_id, consumer.id)
77
78
79 class TokenTests(object):
80 def _new_oauth_token(self):
81 key = uuid.uuid4().hex
82 secret = uuid.uuid4().hex
83 params = {'oauth_token': key, 'oauth_token_secret': secret}
84 token = urlparse.urlencode(params)
85 return (key, secret, token)
86
87 def _new_oauth_token_with_expires_at(self):
88 key, secret, token = self._new_oauth_token()
89 expires_at = client_utils.strtime()
90 params = {'oauth_token': key,
91 'oauth_token_secret': secret,
92 'oauth_expires_at': expires_at}
93 token = urlparse.urlencode(params)
94 return (key, secret, expires_at, token)
95
96 def _validate_oauth_headers(self, auth_header, oauth_client):
97 """Validate data in the headers.
98
99 Assert that the data in the headers matches the data
100 that is produced from oauthlib.
101 """
102 self.assertThat(auth_header, matchers.StartsWith('OAuth '))
103 parameters = dict(
104 oauth1.rfc5849.utils.parse_authorization_header(auth_header))
105
106 self.assertEqual('HMAC-SHA1', parameters['oauth_signature_method'])
107 self.assertEqual('1.0', parameters['oauth_version'])
108 self.assertIsInstance(parameters['oauth_nonce'], str)
109 self.assertEqual(oauth_client.client_key,
110 parameters['oauth_consumer_key'])
111 if oauth_client.resource_owner_key:
112 self.assertEqual(oauth_client.resource_owner_key,
113 parameters['oauth_token'],)
114 if oauth_client.verifier:
115 self.assertEqual(oauth_client.verifier,
116 parameters['oauth_verifier'])
117 if oauth_client.callback_uri:
118 self.assertEqual(oauth_client.callback_uri,
119 parameters['oauth_callback'])
120 return parameters
121
122
123 class RequestTokenTests(utils.ClientTestCase, TokenTests):
124 def setUp(self):
125 if oauth1 is None:
126 self.skipTest('oauthlib package not available')
127
128 super(RequestTokenTests, self).setUp()
129 self.model = request_tokens.RequestToken
130 self.manager = self.client.oauth1.request_tokens
131 self.path_prefix = 'OS-OAUTH1'
132
133 def test_authorize_request_token(self):
134 request_key = uuid.uuid4().hex
135 info = {'id': request_key,
136 'key': request_key,
137 'secret': uuid.uuid4().hex}
138 request_token = request_tokens.RequestToken(self.manager, info)
139
140 verifier = uuid.uuid4().hex
141 resp_ref = {'token': {'oauth_verifier': verifier}}
142 self.stub_url('PUT',
143 [self.path_prefix, 'authorize', request_key],
144 status_code=200, json=resp_ref)
145
146 # Assert the manager is returning the expected data
147 role_id = uuid.uuid4().hex
148 token = request_token.authorize([role_id])
149 self.assertEqual(verifier, token.oauth_verifier)
150
151 # Assert that the request was sent in the expected structure
152 exp_body = {'roles': [{'id': role_id}]}
153 self.assertRequestBodyIs(json=exp_body)
154
155 def test_create_request_token(self):
156 project_id = uuid.uuid4().hex
157 consumer_key = uuid.uuid4().hex
158 consumer_secret = uuid.uuid4().hex
159
160 request_key, request_secret, resp_ref = self._new_oauth_token()
161
162 headers = {'Content-Type': 'application/x-www-form-urlencoded'}
163 self.stub_url('POST', [self.path_prefix, 'request_token'],
164 status_code=201, text=resp_ref, headers=headers)
165
166 # Assert the manager is returning request token object
167 request_token = self.manager.create(consumer_key, consumer_secret,
168 project_id)
169 self.assertIsInstance(request_token, self.model)
170 self.assertEqual(request_key, request_token.key)
171 self.assertEqual(request_secret, request_token.secret)
172
173 # Assert that the project id is in the header
174 self.assertRequestHeaderEqual('requested-project-id', project_id)
175 req_headers = self.requests_mock.last_request.headers
176
177 oauth_client = oauth1.Client(consumer_key,
178 client_secret=consumer_secret,
179 signature_method=oauth1.SIGNATURE_HMAC,
180 callback_uri="oob")
181 self._validate_oauth_headers(req_headers['Authorization'],
182 oauth_client)
183
184
185 class AccessTokenTests(utils.ClientTestCase, TokenTests):
186 def setUp(self):
187 if oauth1 is None:
188 self.skipTest('oauthlib package not available')
189
190 super(AccessTokenTests, self).setUp()
191 self.manager = self.client.oauth1.access_tokens
192 self.model = access_tokens.AccessToken
193 self.path_prefix = 'OS-OAUTH1'
194
195 def test_create_access_token_expires_at(self):
196 verifier = uuid.uuid4().hex
197 consumer_key = uuid.uuid4().hex
198 consumer_secret = uuid.uuid4().hex
199 request_key = uuid.uuid4().hex
200 request_secret = uuid.uuid4().hex
201
202 t = self._new_oauth_token_with_expires_at()
203 access_key, access_secret, expires_at, resp_ref = t
204
205 headers = {'Content-Type': 'application/x-www-form-urlencoded'}
206 self.stub_url('POST', [self.path_prefix, 'access_token'],
207 status_code=201, text=resp_ref, headers=headers)
208
209 # Assert that the manager creates an access token object
210 access_token = self.manager.create(consumer_key, consumer_secret,
211 request_key, request_secret,
212 verifier)
213 self.assertIsInstance(access_token, self.model)
214 self.assertEqual(access_key, access_token.key)
215 self.assertEqual(access_secret, access_token.secret)
216 self.assertEqual(expires_at, access_token.expires)
217
218 req_headers = self.requests_mock.last_request.headers
219 oauth_client = oauth1.Client(consumer_key,
220 client_secret=consumer_secret,
221 resource_owner_key=request_key,
222 resource_owner_secret=request_secret,
223 signature_method=oauth1.SIGNATURE_HMAC,
224 verifier=verifier)
225
226 self._validate_oauth_headers(req_headers['Authorization'],
227 oauth_client)
228
229
230 class AuthenticateWithOAuthTests(utils.TestCase, TokenTests):
231 def setUp(self):
232 super(AuthenticateWithOAuthTests, self).setUp()
233 if oauth1 is None:
234 self.skipTest('optional package oauthlib is not installed')
235
236 def test_oauth_authenticate_success(self):
237 consumer_key = uuid.uuid4().hex
238 consumer_secret = uuid.uuid4().hex
239 access_key = uuid.uuid4().hex
240 access_secret = uuid.uuid4().hex
241
242 # Just use an existing project scoped token and change
243 # the methods to oauth1, and add an OS-OAUTH1 section.
244 oauth_token = client_fixtures.project_scoped_token()
245 oauth_token['methods'] = ["oauth1"]
246 oauth_token['OS-OAUTH1'] = {"consumer_id": consumer_key,
247 "access_token_id": access_key}
248 self.stub_auth(json=oauth_token)
249
250 with self.deprecations.expect_deprecations_here():
251 a = auth.OAuth(self.TEST_URL, consumer_key=consumer_key,
252 consumer_secret=consumer_secret,
253 access_key=access_key,
254 access_secret=access_secret)
255 s = session.Session(auth=a)
256 t = s.get_token()
257 self.assertEqual(self.TEST_TOKEN, t)
258
259 OAUTH_REQUEST_BODY = {
260 "auth": {
261 "identity": {
262 "methods": ["oauth1"],
263 "oauth1": {}
264 }
265 }
266 }
267
268 self.assertRequestBodyIs(json=OAUTH_REQUEST_BODY)
269
270 # Assert that the headers have the same oauthlib data
271 req_headers = self.requests_mock.last_request.headers
272 oauth_client = oauth1.Client(consumer_key,
273 client_secret=consumer_secret,
274 resource_owner_key=access_key,
275 resource_owner_secret=access_secret,
276 signature_method=oauth1.SIGNATURE_HMAC)
277 self._validate_oauth_headers(req_headers['Authorization'],
278 oauth_client)
279
280
281 class OauthRequestIdTests(utils.TestRequestId, TokenTests):
282
283 def setUp(self):
284 super(OauthRequestIdTests, self).setUp()
285 self.mgr = consumers.ConsumerManager(self.client)
286
287 def _mock_request_method(self, method=None, body=None):
288 return self.useFixture(fixtures.MockPatchObject(
289 self.client, method, autospec=True,
290 return_value=(self.resp, body))
291 ).mock
292
293 def test_get_consumers(self):
294 body = {"consumer": {"name": "admin"}}
295 get_mock = self._mock_request_method(method='get', body=body)
296
297 response = self.mgr.get("admin")
298 self.assertEqual(response.request_ids[0], self.TEST_REQUEST_ID)
299 get_mock.assert_called_once_with('/OS-OAUTH1/consumers/admin')
300
301 def test_create_consumers(self):
302 body = {"consumer": {"name": "admin"}}
303 post_mock = self._mock_request_method(method='post', body=body)
304
305 response = self.mgr.create(name="admin", description="fake")
306 self.assertEqual(response.request_ids[0], self.TEST_REQUEST_ID)
307 post_mock.assert_called_once_with('/OS-OAUTH1/consumers', body={
308 'consumer': {'name': 'admin', 'description': 'fake'}})
309
310 def test_update_consumers(self):
311 body = {"consumer": {"name": "admin"}}
312 patch_mock = self._mock_request_method(method='patch', body=body)
313 self._mock_request_method(method='post', body=body)
314
315 response = self.mgr.update("admin", "demo")
316 self.assertEqual(response.request_ids[0], self.TEST_REQUEST_ID)
317 patch_mock.assert_called_once_with('/OS-OAUTH1/consumers/admin', body={
318 'consumer': {'description': 'demo'}})
319
320 def test_delete_consumers(self):
321 get_mock = self._mock_request_method(method='delete')
322
323 _, resp = self.mgr.delete("admin")
324 self.assertEqual(resp.request_ids[0], self.TEST_REQUEST_ID)
325 get_mock.assert_called_once_with('/OS-OAUTH1/consumers/admin')
326
327
328 class TestOAuthLibModule(utils.TestCase):
329
330 def test_no_oauthlib_installed(self):
331 with mock.patch.object(auth, 'oauth1', None):
332 self.assertRaises(NotImplementedError,
333 auth.OAuth,
334 self.TEST_URL,
335 consumer_key=uuid.uuid4().hex,
336 consumer_secret=uuid.uuid4().hex,
337 access_key=uuid.uuid4().hex,
338 access_secret=uuid.uuid4().hex)