Debian Codegraph @

osc_lib/tests/test_clientmanager.py

raw
1 # Copyright 2012-2013 OpenStack Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import copy
16 import json as jsonutils
17 from unittest import mock
18
19 from keystoneauth1.access import service_catalog
20 from keystoneauth1 import exceptions as ksa_exceptions
21 from keystoneauth1 import fixture as ksa_fixture
22 from keystoneauth1.identity import generic as generic_plugin
23 from keystoneauth1.identity.v3 import k2k
24 from keystoneauth1 import loading
25 from keystoneauth1 import noauth
26 from keystoneauth1 import token_endpoint
27 from openstack.config import cloud_config
28 from openstack.config import cloud_region
29 from openstack.config import defaults
30 from openstack import connection
31 from requests_mock.contrib import fixture as requests_mock_fixture
32
33 from osc_lib.api import auth
34 from osc_lib import clientmanager
35 from osc_lib import exceptions as exc
36 from osc_lib.test import base
37 from osc_lib.test import fakes
38
39 SERVICE_PROVIDER_ID = "bob"
40
41 TEST_RESPONSE_DICT = ksa_fixture.V2Token(
42 token_id=fakes.TOKEN, user_name=fakes.USERNAME
43 )
44 _s = TEST_RESPONSE_DICT.add_service('identity', name='keystone')
45 _s.add_endpoint(fakes.AUTH_URL + ':5000/v2.0')
46 _s = TEST_RESPONSE_DICT.add_service('network', name='neutron')
47 _s.add_endpoint(fakes.AUTH_URL + ':9696')
48 _s = TEST_RESPONSE_DICT.add_service('compute', name='nova')
49 _s.add_endpoint(fakes.AUTH_URL + ':8774/v2')
50 _s = TEST_RESPONSE_DICT.add_service('image', name='glance')
51 _s.add_endpoint(fakes.AUTH_URL + ':9292')
52 _s = TEST_RESPONSE_DICT.add_service('object', name='swift')
53 _s.add_endpoint(fakes.AUTH_URL + ':8080/v1')
54
55 TEST_RESPONSE_DICT_V3 = ksa_fixture.V3Token(user_name=fakes.USERNAME)
56 TEST_RESPONSE_DICT_V3.set_project_scope()
57
58 TEST_VERSIONS = ksa_fixture.DiscoveryList(href=fakes.AUTH_URL)
59
60 AUTH_REF = {'version': 'v2.0'}
61 AUTH_REF.update(TEST_RESPONSE_DICT['access'])
62 SERVICE_CATALOG = service_catalog.ServiceCatalogV2(AUTH_REF)
63
64 AUTH_DICT = {
65 'auth_url': fakes.AUTH_URL,
66 'username': fakes.USERNAME,
67 'password': fakes.PASSWORD,
68 'project_name': fakes.PROJECT_NAME,
69 }
70
71
72 # This is deferred in api.auth but we need it here...
73 auth.get_options_list()
74
75
76 class Container:
77 attr = clientmanager.ClientCache(lambda x: object())
78 buggy_attr = clientmanager.ClientCache(lambda x: x.foo)
79
80 def __init__(self):
81 pass
82
83
84 class TestClientCache(base.TestCase):
85 def test_singleton(self):
86 # NOTE(dtroyer): Verify that the ClientCache descriptor only invokes
87 # the factory one time and always returns the same value after that.
88 c = Container()
89 self.assertEqual(c.attr, c.attr)
90
91 def test_attribute_error_propagates(self):
92 c = Container()
93 err = self.assertRaises(
94 exc.PluginAttributeError, getattr, c, 'buggy_attr'
95 )
96 self.assertNotIsInstance(err, AttributeError)
97 self.assertEqual("'Container' object has no attribute 'foo'", str(err))
98
99
100 class BaseTestClientManager(base.TestCase):
101 """ClientManager class test framework"""
102
103 default_password_auth = {
104 'auth_url': fakes.AUTH_URL,
105 'username': fakes.USERNAME,
106 'password': fakes.PASSWORD,
107 'project_name': fakes.PROJECT_NAME,
108 }
109 default_token_auth = {
110 'auth_url': fakes.AUTH_URL,
111 'token': fakes.TOKEN,
112 }
113
114 def setUp(self):
115 super().setUp()
116 self.mock = mock.Mock()
117 self.requests = self.useFixture(requests_mock_fixture.Fixture())
118 # fake v2password token retrieval
119 self.stub_auth(json=TEST_RESPONSE_DICT)
120 # fake token and token_endpoint retrieval
121 self.stub_auth(
122 json=TEST_RESPONSE_DICT,
123 url='/'.join([fakes.AUTH_URL, 'v2.0/tokens']),
124 )
125 # fake v3password token retrieval
126 self.stub_auth(
127 json=TEST_RESPONSE_DICT_V3,
128 url='/'.join([fakes.AUTH_URL, 'v3/auth/tokens']),
129 )
130 # fake password token retrieval
131 self.stub_auth(
132 json=TEST_RESPONSE_DICT_V3,
133 url='/'.join([fakes.AUTH_URL, 'auth/tokens']),
134 )
135 # fake password version endpoint discovery
136 self.stub_auth(json=TEST_VERSIONS, url=fakes.AUTH_URL, verb='GET')
137
138 # Mock the auth plugin
139 self.auth_mock = mock.Mock()
140
141 def stub_auth(self, json=None, url=None, verb=None, **kwargs):
142 subject_token = fakes.TOKEN
143 base_url = fakes.AUTH_URL
144 if json:
145 text = jsonutils.dumps(json)
146 headers = {
147 'X-Subject-Token': subject_token,
148 'Content-Type': 'application/json',
149 }
150 if not url:
151 url = '/'.join([base_url, 'tokens'])
152 url = url.replace("/?", "?")
153 if not verb:
154 verb = 'POST'
155 self.requests.register_uri(
156 verb,
157 url,
158 headers=headers,
159 text=text,
160 )
161
162 def _clientmanager_class(self):
163 """Allow subclasses to override the ClientManager class"""
164 return clientmanager.ClientManager
165
166 def _make_clientmanager(
167 self,
168 auth_args=None,
169 config_args=None,
170 identity_api_version=None,
171 auth_plugin_name=None,
172 auth_required=None,
173 ):
174 if identity_api_version is None:
175 identity_api_version = '2.0'
176 if auth_plugin_name is None:
177 auth_plugin_name = 'password'
178
179 if auth_plugin_name.endswith('password'):
180 auth_dict = copy.deepcopy(self.default_password_auth)
181 elif auth_plugin_name.endswith('token'):
182 auth_dict = copy.deepcopy(self.default_token_auth)
183 else:
184 auth_dict = {}
185
186 if auth_args is not None:
187 auth_dict = auth_args
188
189 cli_options = defaults.get_defaults()
190 cli_options.update(
191 {
192 'auth_type': auth_plugin_name,
193 'auth': auth_dict,
194 'interface': fakes.INTERFACE,
195 'region_name': fakes.REGION_NAME,
196 }
197 )
198 if config_args is not None:
199 cli_options.update(config_args)
200
201 loader = loading.get_plugin_loader(auth_plugin_name)
202 auth_plugin = loader.load_from_options(**auth_dict)
203 client_manager = self._clientmanager_class()(
204 cli_options=cloud_region.CloudRegion(
205 name='t1',
206 region_name='1',
207 config=cli_options,
208 auth_plugin=auth_plugin,
209 ),
210 api_version={
211 'identity': identity_api_version,
212 },
213 )
214 client_manager._auth_required = auth_required is True
215 client_manager.setup_auth()
216 client_manager.auth_ref
217
218 self.assertEqual(
219 auth_plugin_name,
220 client_manager.auth_plugin_name,
221 )
222 return client_manager
223
224
225 class TestClientManager(BaseTestClientManager):
226 def test_client_manager_none(self):
227 none_auth = {
228 'endpoint': fakes.AUTH_URL,
229 }
230 client_manager = self._make_clientmanager(
231 auth_args=none_auth,
232 auth_plugin_name='none',
233 )
234
235 self.assertEqual(
236 fakes.AUTH_URL,
237 client_manager._cli_options.config['auth']['endpoint'],
238 )
239 self.assertIsInstance(
240 client_manager.auth,
241 noauth.NoAuth,
242 )
243 # Check that the endpoint option works as the override
244 self.assertEqual(
245 fakes.AUTH_URL,
246 client_manager.get_endpoint_for_service_type('baremetal'),
247 )
248
249 def test_client_manager_admin_token(self):
250 token_auth = {
251 'endpoint': fakes.AUTH_URL,
252 'token': fakes.TOKEN,
253 }
254 client_manager = self._make_clientmanager(
255 auth_args=token_auth,
256 auth_plugin_name='admin_token',
257 )
258
259 self.assertEqual(
260 fakes.AUTH_URL,
261 client_manager._cli_options.config['auth']['endpoint'],
262 )
263 self.assertEqual(
264 fakes.TOKEN,
265 client_manager.auth.get_token(None),
266 )
267 self.assertIsInstance(
268 client_manager.auth,
269 token_endpoint.Token,
270 )
271 # NOTE(dtroyer): This is intentionally not assertFalse() as the return
272 # value from is_service_available() may be == None
273 self.assertNotEqual(
274 False,
275 client_manager.is_service_available('network'),
276 )
277
278 def test_client_manager_password(self):
279 client_manager = self._make_clientmanager(
280 auth_required=True,
281 )
282
283 self.assertEqual(
284 fakes.AUTH_URL,
285 client_manager._cli_options.config['auth']['auth_url'],
286 )
287 self.assertEqual(
288 fakes.USERNAME,
289 client_manager._cli_options.config['auth']['username'],
290 )
291 self.assertEqual(
292 fakes.PASSWORD,
293 client_manager._cli_options.config['auth']['password'],
294 )
295 self.assertIsInstance(
296 client_manager.auth,
297 generic_plugin.Password,
298 )
299 self.assertTrue(client_manager.verify)
300 self.assertIsNone(client_manager.cert)
301
302 # These need to stick around until the old-style clients are gone
303 self.assertEqual(
304 AUTH_REF.pop('version'),
305 client_manager.auth_ref.version,
306 )
307 self.assertEqual(
308 AUTH_REF,
309 client_manager.auth_ref._data['access'],
310 )
311 self.assertEqual(
312 dir(SERVICE_CATALOG),
313 dir(client_manager.auth_ref.service_catalog),
314 )
315 self.assertTrue(client_manager.is_service_available('network'))
316
317 def test_client_manager_password_verify(self):
318 client_manager = self._make_clientmanager(
319 auth_required=True,
320 )
321
322 self.assertTrue(client_manager.verify)
323 self.assertIsNone(client_manager.cacert)
324 self.assertTrue(client_manager.is_service_available('network'))
325
326 def test_client_manager_password_verify_ca(self):
327 config_args = {
328 'cacert': 'cafile',
329 }
330 client_manager = self._make_clientmanager(
331 config_args=config_args,
332 auth_required=True,
333 )
334
335 # Test that client_manager.verify is Requests-compatible,
336 # i.e. it contains the value of cafile here
337 self.assertTrue(client_manager.verify)
338 self.assertEqual('cafile', client_manager.verify)
339 self.assertEqual('cafile', client_manager.cacert)
340 self.assertTrue(client_manager.is_service_available('network'))
341
342 def test_client_manager_password_verify_false(self):
343 config_args = {
344 'verify': False,
345 }
346 client_manager = self._make_clientmanager(
347 config_args=config_args,
348 auth_required=True,
349 )
350
351 self.assertFalse(client_manager.verify)
352 self.assertIsNone(client_manager.cacert)
353 self.assertTrue(client_manager.is_service_available('network'))
354
355 def test_client_manager_password_verify_insecure(self):
356 config_args = {
357 'insecure': True,
358 }
359 client_manager = self._make_clientmanager(
360 config_args=config_args,
361 auth_required=True,
362 )
363
364 self.assertFalse(client_manager.verify)
365 self.assertIsNone(client_manager.cacert)
366 self.assertTrue(client_manager.is_service_available('network'))
367
368 def test_client_manager_password_verify_insecure_ca(self):
369 config_args = {
370 'insecure': True,
371 'cacert': 'cafile',
372 }
373 client_manager = self._make_clientmanager(
374 config_args=config_args,
375 auth_required=True,
376 )
377
378 # insecure overrides cacert
379 self.assertFalse(client_manager.verify)
380 self.assertIsNone(client_manager.cacert)
381 self.assertTrue(client_manager.is_service_available('network'))
382
383 def test_client_manager_password_client_cert(self):
384 config_args = {
385 'cert': 'cert',
386 }
387 client_manager = self._make_clientmanager(
388 config_args=config_args,
389 )
390
391 self.assertEqual('cert', client_manager.cert)
392
393 def test_client_manager_password_client_key(self):
394 config_args = {
395 'cert': 'cert',
396 'key': 'key',
397 }
398 client_manager = self._make_clientmanager(
399 config_args=config_args,
400 )
401
402 self.assertEqual(('cert', 'key'), client_manager.cert)
403
404 def test_client_manager_select_auth_plugin_password(self):
405 # test password auth
406 auth_args = {
407 'auth_url': fakes.AUTH_URL,
408 'username': fakes.USERNAME,
409 'password': fakes.PASSWORD,
410 'tenant_name': fakes.PROJECT_NAME,
411 }
412 self._make_clientmanager(
413 auth_args=auth_args,
414 identity_api_version='2.0',
415 auth_plugin_name='v2password',
416 )
417
418 auth_args = copy.deepcopy(self.default_password_auth)
419 auth_args.update(
420 {
421 'user_domain_name': 'default',
422 'project_domain_name': 'default',
423 }
424 )
425 self._make_clientmanager(
426 auth_args=auth_args,
427 identity_api_version='3',
428 auth_plugin_name='v3password',
429 )
430
431 # Use v2.0 auth args
432 auth_args = {
433 'auth_url': fakes.AUTH_URL,
434 'username': fakes.USERNAME,
435 'password': fakes.PASSWORD,
436 'tenant_name': fakes.PROJECT_NAME,
437 }
438 self._make_clientmanager(
439 auth_args=auth_args,
440 identity_api_version='2.0',
441 )
442
443 # Use v3 auth args
444 auth_args = copy.deepcopy(self.default_password_auth)
445 auth_args.update(
446 {
447 'user_domain_name': 'default',
448 'project_domain_name': 'default',
449 }
450 )
451 self._make_clientmanager(
452 auth_args=auth_args,
453 identity_api_version='3',
454 )
455
456 auth_args = copy.deepcopy(self.default_password_auth)
457 auth_args.pop('username')
458 auth_args.update({'user_id': fakes.USER_ID})
459 self._make_clientmanager(
460 auth_args=auth_args,
461 identity_api_version='3',
462 )
463
464 def test_client_manager_select_auth_plugin_token(self):
465 # test token auth
466 self._make_clientmanager(
467 # auth_args=auth_args,
468 identity_api_version='2.0',
469 auth_plugin_name='v2token',
470 )
471 self._make_clientmanager(
472 # auth_args=auth_args,
473 identity_api_version='3',
474 auth_plugin_name='v3token',
475 )
476 self._make_clientmanager(
477 # auth_args=auth_args,
478 identity_api_version='x',
479 auth_plugin_name='token',
480 )
481
482 def test_client_manager_select_auth_plugin_failure(self):
483 self.assertRaises(
484 ksa_exceptions.NoMatchingPlugin,
485 self._make_clientmanager,
486 identity_api_version='3',
487 auth_plugin_name='bad_plugin',
488 )
489
490 @mock.patch('osc_lib.api.auth.check_valid_authentication_options')
491 def test_client_manager_auth_setup_once(self, check_authn_options_func):
492 loader = loading.get_plugin_loader('password')
493 auth_plugin = loader.load_from_options(**AUTH_DICT)
494 cli_options = defaults.get_defaults()
495 cli_options.update(
496 {
497 'auth_type': 'password',
498 'auth': AUTH_DICT,
499 'interface': fakes.INTERFACE,
500 'region_name': fakes.REGION_NAME,
501 }
502 )
503 client_manager = self._clientmanager_class()(
504 cli_options=cloud_config.CloudConfig(
505 name='t1',
506 region='1',
507 config=cli_options,
508 auth_plugin=auth_plugin,
509 ),
510 api_version={
511 'identity': '2.0',
512 },
513 )
514 self.assertFalse(client_manager._auth_setup_completed)
515 client_manager.setup_auth()
516 self.assertTrue(check_authn_options_func.called)
517 self.assertTrue(client_manager._auth_setup_completed)
518
519 # now make sure we don't do auth setup the second time around
520 # by checking whether check_valid_auth_options() gets called again
521 check_authn_options_func.reset_mock()
522 client_manager.auth_ref
523 check_authn_options_func.assert_not_called()
524
525 def test_client_manager_endpoint_disabled(self):
526 auth_args = copy.deepcopy(self.default_password_auth)
527 auth_args.update(
528 {
529 'user_domain_name': 'default',
530 'project_domain_name': 'default',
531 }
532 )
533 # v3 fake doesn't have network endpoint
534 client_manager = self._make_clientmanager(
535 auth_args=auth_args,
536 identity_api_version='3',
537 auth_plugin_name='v3password',
538 )
539
540 self.assertFalse(client_manager.is_service_available('network'))
541
542 def test_client_manager_k2k_auth_setup(self):
543 loader = loading.get_plugin_loader('password')
544 auth_plugin = loader.load_from_options(**AUTH_DICT)
545 cli_options = defaults.get_defaults()
546 cli_options.update(
547 {
548 'auth_type': 'password',
549 'auth': AUTH_DICT,
550 'interface': fakes.INTERFACE,
551 'region_name': fakes.REGION_NAME,
552 'service_provider': SERVICE_PROVIDER_ID,
553 'remote_project_id': fakes.PROJECT_ID,
554 }
555 )
556 client_manager = self._clientmanager_class()(
557 cli_options=cloud_config.CloudConfig(
558 name='t1',
559 region='1',
560 config=cli_options,
561 auth_plugin=auth_plugin,
562 ),
563 api_version={
564 'identity': '3',
565 },
566 )
567
568 self.assertFalse(client_manager._auth_setup_completed)
569 client_manager.setup_auth()
570 # Note(knikolla): Make sure that the auth object is of the correct
571 # type and that the service_provider is correctly set.
572 self.assertIsInstance(client_manager.auth, k2k.Keystone2Keystone)
573 self.assertEqual(client_manager.auth._sp_id, SERVICE_PROVIDER_ID)
574 self.assertEqual(client_manager.auth.project_id, fakes.PROJECT_ID)
575 self.assertTrue(client_manager._auth_setup_completed)
576
577 def test_client_manager_none_auth(self):
578 # test token auth
579 client_manager = self._make_clientmanager(
580 auth_args={},
581 auth_plugin_name='none',
582 )
583 self.assertIsNone(
584 client_manager.get_endpoint_for_service_type('compute')
585 )
586
587 def test_client_manager_endpoint_override(self):
588 # test token auth
589 client_manager = self._make_clientmanager(
590 auth_args={},
591 config_args={
592 'compute_endpoint_override': 'http://example.com',
593 'foo_bar_endpoint_override': 'http://example2.com',
594 },
595 auth_plugin_name='none',
596 )
597 self.assertEqual(
598 'http://example.com',
599 client_manager.get_endpoint_for_service_type('compute'),
600 )
601 self.assertEqual(
602 'http://example2.com',
603 client_manager.get_endpoint_for_service_type('foo-bar'),
604 )
605 self.assertTrue(client_manager.is_service_available('compute'))
606
607 def test_client_manager_connection(self):
608 client_manager = self._make_clientmanager(
609 auth_required=True,
610 )
611
612 self.assertIsInstance(
613 client_manager.sdk_connection,
614 connection.Connection,
615 )