def test_create_trusts_auth_plugin_with_correct_user_domain_id(self): importutils.import_module('keystonemiddleware.auth_token') cfg.CONF.set_override('auth_uri', 'http://abc/v2.0', group='keystone_authtoken', enforce_type=True) cfg.CONF.set_override('admin_user', 'heat', group='keystone_authtoken', enforce_type=True) cfg.CONF.set_override('admin_password', 'password', group='keystone_authtoken', enforce_type=True) policy_check = 'heat.common.policy.Enforcer.check_is_admin' with mock.patch(policy_check) as pc: pc.return_value = False ctx = context.RequestContext(auth_url=None, user_domain_id='non-default', username='******') with mock.patch('keystoneauth1.identity.generic.Password') as ps: ctx.trusts_auth_plugin ps.assert_called_once_with(username='******', password='******', user_domain_id='default', auth_url='http://abc/v3', trust_id=None)
def test_policy_cfn_default(self): enforcer = policy.Enforcer(scope='cloudformation') ctx = context.RequestContext(roles=[]) for action in self.cfn_actions: # Everything should be allowed enforcer.enforce(ctx, action, {})
def test_keystone_v3_endpoint_in_clients_keystone_config(self): """Ensure that the [clients_keystone] section is the preferred source. Ensure that the [clients_keystone] section of the configuration is the preferred source when the context does not have the auth_uri. """ cfg.CONF.set_override('auth_uri', 'http://xyz', group='clients_keystone') importutils.import_module('keystonemiddleware.auth_token') cfg.CONF.set_override('auth_uri', 'http://abc/v2.0', group='keystone_authtoken') policy_check = 'heat.common.policy.Enforcer.check_is_admin' with mock.patch(policy_check) as pc: pc.return_value = False with mock.patch('keystoneclient.discover.Discover') as discover: class MockDiscover(object): def url_for(self, endpoint): return 'http://xyz/v3' discover.return_value = MockDiscover() ctx = context.RequestContext(auth_url=None) self.assertEqual(ctx.keystone_v3_endpoint, 'http://xyz/v3')
def test_policy_enforce_tenant_mismatch_is_admin(self, mock_enforce): self.req.context = context.RequestContext(tenant='foo', is_admin=True) mock_enforce.return_value = True self.assertEqual('woot', self.controller.an_action(self.req, 'foo')) self.assertEqual('woot', self.controller.an_action(self.req, 'bar'))
def __call__(self, env, start_response): """Authenticate incoming request.""" username = env.get('HTTP_X_AUTH_USER') password = env.get('HTTP_X_AUTH_KEY') # Determine tenant id from path. tenant = env.get('PATH_INFO').split('/')[1] auth_url = env.get('HTTP_X_AUTH_URL') user_domain_id = env.get('HTTP_X_USER_DOMAIN_ID') if not tenant: return self._reject_request(env, start_response, auth_url) try: ctx = context.RequestContext(username=username, password=password, tenant=tenant, auth_url=auth_url, user_domain_id=user_domain_id, is_admin=False) auth_ref = ctx.auth_plugin.get_access(self.session) except (keystone_exceptions.Unauthorized, keystone_exceptions.Forbidden, keystone_exceptions.NotFound, keystone_exceptions.AuthorizationFailure): return self._reject_request(env, start_response, auth_url) env.update(self._build_user_headers(auth_ref)) return self.app(env, start_response)
def test_keystone_v3_endpoint_not_set_in_config(self): """Ensure an exception is raised when the auth_uri cannot be obtained from any source. """ policy_check = 'heat.common.policy.Enforcer.check_is_admin' with mock.patch(policy_check) as pc: pc.return_value = False ctx = context.RequestContext(auth_url=None) self.assertRaises(exception.AuthorizationFailure, getattr, ctx, 'keystone_v3_endpoint')
def test_keystone_v3_endpoint_in_context(self): """Ensure that the context is the preferred source for the auth_uri.""" cfg.CONF.set_override('auth_uri', 'http://xyz', group='clients_keystone', enforce_type=True) policy_check = 'heat.common.policy.Enforcer.check_is_admin' with mock.patch(policy_check) as pc: pc.return_value = False ctx = context.RequestContext( auth_url='http://example.com:5000/v2.0') self.assertEqual(ctx.keystone_v3_endpoint, 'http://example.com:5000/v3')
def test_request_context_init(self): ctx = context.RequestContext(auth_token=self.ctx.get('auth_token'), username=self.ctx.get('username'), password=self.ctx.get('password'), aws_creds=self.ctx.get('aws_creds'), tenant=self.ctx.get('tenant'), tenant_id=self.ctx.get('tenant_id'), auth_url=self.ctx.get('auth_url'), roles=self.ctx.get('roles'), is_admin=self.ctx.get('is_admin')) ctx_dict = ctx.to_dict() self.assertEqual(ctx_dict, self.ctx)
def setUp(self): super(TestPolicyEnforce, self).setUp() self.req = wsgi.Request({}) self.req.context = context.RequestContext(tenant='foo', is_admin=False) class DummyController(object): REQUEST_SCOPE = 'test' @util.registered_policy_enforce def an_action(self, req): return 'woot' self.controller = DummyController()
def test_policy_cfn_allow_non_stack_user(self): pf = policy_path + 'deny_stack_user.json' self.m.StubOutWithMock(policy.Enforcer, '_find_policy_file') policy.Enforcer._find_policy_file().MultipleTimes().AndReturn(pf) self.m.ReplayAll() enforcer = policy.Enforcer(scope='cloudformation') ctx = context.RequestContext(roles=['not_a_stack_user']) for action in self.cfn_actions: # Everything should be allowed enforcer.enforce(ctx, action, {}) self.m.VerifyAll()
def test_policy_cfn_notallowed(self): pf = policy_path + 'notallowed.json' self.m.StubOutWithMock(policy.Enforcer, '_find_policy_file') policy.Enforcer._find_policy_file().MultipleTimes().AndReturn(pf) self.m.ReplayAll() enforcer = policy.Enforcer(scope='cloudformation') ctx = context.RequestContext(roles=[]) for action in self.cfn_actions: # Everything should raise the default exception.Forbidden self.assertRaises(exception.Forbidden, enforcer.enforce, ctx, action, {}) self.m.VerifyAll()
def test_request_context_to_dict_unicode(self): ctx_origin = { 'username': '******', 'trustor_user_id': None, 'auth_token': '123', 'auth_token_info': { '123info': 'woop' }, 'is_admin': False, 'user': '******', 'password': '******', 'trust_id': None, 'global_request_id': None, 'show_deleted': False, 'roles': ['arole', 'notadmin'], 'tenant_id': '456tenant', 'project_id': '456tenant', 'user_id': u'Gāo', 'tenant': u'\u5218\u80dc', 'project_name': u'\u5218\u80dc', 'auth_url': 'http://xyz', 'aws_creds': 'blah', 'region_name': 'RegionOne', 'user_identity': u'Gāo 456tenant', 'user_domain': None, 'project_domain': None } ctx = context.RequestContext( auth_token=ctx_origin.get('auth_token'), username=ctx_origin.get('username'), password=ctx_origin.get('password'), aws_creds=ctx_origin.get('aws_creds'), project_name=ctx_origin.get('tenant'), tenant=ctx_origin.get('tenant_id'), user=ctx_origin.get('user_id'), auth_url=ctx_origin.get('auth_url'), roles=ctx_origin.get('roles'), show_deleted=ctx_origin.get('show_deleted'), is_admin=ctx_origin.get('is_admin'), auth_token_info=ctx_origin.get('auth_token_info'), trustor_user_id=ctx_origin.get('trustor_user_id'), trust_id=ctx_origin.get('trust_id'), region_name=ctx_origin.get('region_name'), user_domain_id=ctx_origin.get('user_domain'), project_domain_id=ctx_origin.get('project_domain')) ctx_dict = ctx.to_dict() del (ctx_dict['request_id']) self.assertEqual(ctx_origin, ctx_dict)
def test_keystone_v3_endpoint_in_keystone_authtoken_config(self): """Ensure that the [keystone_authtoken] section of the configuration is used when the auth_uri is not defined in the context or the [clients_keystone] section. """ importutils.import_module('keystonemiddleware.auth_token') cfg.CONF.set_override('auth_uri', 'http://abc/v2.0', group='keystone_authtoken') policy_check = 'heat.common.policy.Enforcer.check_is_admin' with mock.patch(policy_check) as pc: pc.return_value = False ctx = context.RequestContext(auth_url=None) self.assertEqual(ctx.keystone_v3_endpoint, 'http://abc/v3')
def test_policy_cfn_deny_stack_user(self): pf = policy_path + 'deny_stack_user.json' self.m.StubOutWithMock(policy.Enforcer, '_find_policy_file') policy.Enforcer._find_policy_file().MultipleTimes().AndReturn(pf) self.m.ReplayAll() enforcer = policy.Enforcer(scope='cloudformation') ctx = context.RequestContext(roles=['heat_stack_user']) for action in self.cfn_actions: # Everything apart from DescribeStackResource should be Forbidden if action == "DescribeStackResource": enforcer.enforce(ctx, action, {}) else: self.assertRaises(exception.Forbidden, enforcer.enforce, ctx, action, {}) self.m.VerifyAll()
def test_request_context_init(self): ctx = context.RequestContext( auth_token=self.ctx.get('auth_token'), username=self.ctx.get('username'), password=self.ctx.get('password'), aws_creds=self.ctx.get('aws_creds'), tenant=self.ctx.get('tenant'), tenant_id=self.ctx.get('tenant_id'), user_id=self.ctx.get('user_id'), auth_url=self.ctx.get('auth_url'), roles=self.ctx.get('roles'), show_deleted=self.ctx.get('show_deleted'), is_admin=self.ctx.get('is_admin'), auth_token_info=self.ctx.get('auth_token_info'), trustor_user_id=self.ctx.get('trustor_user_id'), trust_id=self.ctx.get('trust_id'), user=self.ctx.get('user'), region_name=self.ctx.get('region_name')) ctx_dict = ctx.to_dict() del (ctx_dict['request_id']) self.assertEqual(self.ctx, ctx_dict)
def __call__(self, env, start_response): """Authenticate incoming request.""" username = env.get('HTTP_X_AUTH_USER') password = env.get('HTTP_X_AUTH_KEY') # Determine tenant id from path. tenant = env.get('PATH_INFO').split('/')[1] auth_url = env.get('HTTP_X_AUTH_URL') if not tenant: return self._reject_request(env, start_response, auth_url) try: ctx = context.RequestContext(username=username, password=password, tenant_id=tenant, auth_url=auth_url, is_admin=False) hc = heat_keystoneclient.KeystoneClient(ctx) client = hc.client except (keystone_exceptions.Unauthorized, keystone_exceptions.Forbidden, keystone_exceptions.NotFound, keystone_exceptions.AuthorizationFailure): return self._reject_request(env, start_response, auth_url) env.update(self._build_user_headers(client.auth_ref)) return self.app(env, start_response)
def _test_engine_api(self, method, rpc_method, **kwargs): ctxt = context.RequestContext('fake_user', 'fake_project') if 'rpcapi_class' in kwargs: rpcapi_class = kwargs['rpcapi_class'] del kwargs['rpcapi_class'] else: rpcapi_class = rpc_client.EngineClient rpcapi = rpcapi_class() expected_retval = 'foo' if method == 'call' else None expected_version = kwargs.pop('version', rpcapi.BASE_RPC_API_VERSION) expected_msg = rpcapi.make_msg(method, **kwargs) expected_msg['version'] = expected_version expected_topic = rpc_api.ENGINE_TOPIC cast_and_call = ['delete_stack'] if rpc_method == 'call' and method in cast_and_call: kwargs['cast'] = False self.fake_args = None self.fake_kwargs = None def _fake_rpc_method(*args, **kwargs): self.fake_args = args self.fake_kwargs = kwargs if expected_retval: return expected_retval self.stubs.Set(rpc, rpc_method, _fake_rpc_method) retval = getattr(rpcapi, method)(ctxt, **kwargs) self.assertEqual(retval, expected_retval) expected_args = [ctxt, expected_topic, expected_msg] for arg, expected_arg in zip(self.fake_args, expected_args): self.assertEqual(arg, expected_arg)
def create_trust_context(self): return context.RequestContext(username=self.username, password=self.password, is_admin=False, trust_id='atrust', trustor_user_id='auser123')
def test_admin_context_policy_true(self): policy_check = 'heat.common.policy.Enforcer.check_is_admin' with mock.patch(policy_check) as pc: pc.return_value = True ctx = context.RequestContext(roles=['admin']) self.assertTrue(ctx.is_admin)
# Connecting to heat db using interpreter and run commands from heat.common import import context from oslo_config import cfg cfg.CONF.set_override('connection','mysql+pymysql://root:[email protected]/heat?charset=utf8', group='database') # this api is api.py in devstack-help. Add this to PYTHONPATH # IMPORTANT: Make sure you have correct admin url in api.py from api import keystone as me ctx=context.RequestContext(auth_token=me.auth_token, user=me.username, tenant_id=me.tenant_id, request_id=me.request,user_domain_id=me.user_domain_id,project_domain_id=me.project_domain_id, is_admin=False) from heat.db.sqlalchemy import import api as db_api db_api.resource_get_all(ctx)
def setUp(self): super(TestTenantLocal, self).setUp() self.req = Request({}) self.req.context = context.RequestContext(tenant_id='foo')