From 0c87d14f558d78bf0bd436bd74e9e126b20dbe14 Mon Sep 17 00:00:00 2001 From: Lance Bragstad Date: Tue, 16 Feb 2021 20:46:23 +0000 Subject: [PATCH] Make sure we pass context objects directly to policy enforcement The oslo.policy Enforcer understands what to do with oslo.context.RequestContext objects. This makes things easier for us because we don't have to call .to_policy_values() before invoking enforcement. Oslo.policy will do it for us. This commit ensures we do this in cinder.policy.enforce() and it adds some tests to make sure cinder.policy.authorize() doesn't regress. Change-Id: Id7f4f81df47763763b83580b4ff10908da86ed18 --- cinder/policy.py | 2 +- cinder/tests/unit/test_policy.py | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/cinder/policy.py b/cinder/policy.py index 1e848344984..700d77bbfee 100644 --- a/cinder/policy.py +++ b/cinder/policy.py @@ -79,7 +79,7 @@ def enforce(context, action, target): try: return _ENFORCER.enforce(action, target, - context.to_policy_values(), + context, do_raise=True, exc=exception.PolicyNotAuthorized, action=action) diff --git a/cinder/tests/unit/test_policy.py b/cinder/tests/unit/test_policy.py index bac57f8fc61..41b16c66497 100644 --- a/cinder/tests/unit/test_policy.py +++ b/cinder/tests/unit/test_policy.py @@ -13,6 +13,7 @@ # License for the specific language governing permissions and limitations # under the License. import os.path +from unittest import mock from oslo_config import cfg from oslo_config import fixture as config_fixture @@ -156,3 +157,25 @@ class PolicyTestCase(test.TestCase): policy._ENFORCER.register_defaults([rule]) self.assertTrue(policy.enforce(project_context, 'foo', {})) + + def test_enforce_passes_context_objects_to_enforcement(self): + fake_context = context.RequestContext(roles=['foo']) + action = 'foo' + target = {} + with mock.patch.object(policy._ENFORCER, 'enforce') as fake_enforce: + policy.enforce(fake_context, action, target) + fake_enforce.assert_called_once_with( + action, target, fake_context, do_raise=True, + exc=exception.PolicyNotAuthorized, action=action) + + def test_authorize_passes_context_objects_to_enforcement(self): + fake_context = context.RequestContext(project_id='fake-project-id', + user_id='fake-user-id', + roles=['foo']) + action = 'foo' + target = {'project_id': 'fake-project-id', 'user_id': 'fake-user-id'} + with mock.patch.object(policy._ENFORCER, 'authorize') as fake_authz: + fake_context.authorize('foo') + fake_authz.assert_called_once_with( + action, target, fake_context, do_raise=True, + exc=exception.PolicyNotAuthorized, action=action)