Python oslo_policy.policy.json() Examples

The following are 30 code examples of oslo_policy.policy.json(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module oslo_policy.policy , or try the search function .
Example #1
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def test_should_raise_decrypt_secret_for_with_project_access_nolist(self):
        """Should raise authz error as secret is marked private.

        As secret is private so project users should not be able to access
        the secret.  This test passes user_ids as empty list, which is a
        valid and common case. Admin project user can still access it.
        """
        self.acl_list.pop()  # remove read acl from default setup
        acl_read = models.SecretACL(secret_id=self.secret_id, operation='read',
                                    project_access=False,
                                    user_ids=[])
        self.acl_list.append(acl_read)
        self._assert_fail_rbac(['observer', 'creator', 'audit'],
                               self._invoke_on_get,
                               accept='notjsonaccepttype',
                               content_type='application/json',
                               user_id=self.user_id,
                               project_id=self.external_project_id) 
Example #2
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_deprecate_name_suppress_does_not_log_warning(self):
        deprecated_rule = policy.DeprecatedRule(
            name='foo:bar',
            check_str='role:baz'
        )

        rule_list = [policy.DocumentedRuleDefault(
            name='foo:create_bar',
            check_str='role:baz',
            description='Create a bar.',
            operations=[{'path': '/v1/bars/', 'method': 'POST'}],
            deprecated_rule=deprecated_rule,
            deprecated_reason='"foo:bar" is not granular enough.',
            deprecated_since='N'
        )]

        rules = jsonutils.dumps({'foo:bar': 'role:bang'})
        self.create_config_file('policy.json', rules)
        enforcer = policy.Enforcer(self.conf)
        enforcer.suppress_deprecation_warnings = True
        enforcer.register_defaults(rule_list)

        with mock.patch('warnings.warn') as mock_warn:
            enforcer.load_rules()
            mock_warn.assert_not_called() 
Example #3
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_deprecate_for_removal_suppress_does_not_log_warning(self):
        rule_list = [policy.DocumentedRuleDefault(
            name='foo:bar',
            check_str='role:baz',
            description='Create a foo.',
            operations=[{'path': '/v1/foos/', 'method': 'POST'}],
            deprecated_for_removal=True,
            deprecated_reason=(
                '"foo:bar" is no longer a policy used by the service'
            ),
            deprecated_since='N'
        )]
        rules = jsonutils.dumps({'foo:bar': 'role:bang'})
        self.create_config_file('policy.json', rules)
        enforcer = policy.Enforcer(self.conf)
        enforcer.suppress_deprecation_warnings = True
        enforcer.register_defaults(rule_list)

        with mock.patch('warnings.warn') as mock_warn:
            enforcer.load_rules()
            mock_warn.assert_not_called() 
Example #4
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_deprecate_a_policy_for_removal_logs_warning_when_overridden(self):
        rule_list = [policy.DocumentedRuleDefault(
            name='foo:bar',
            check_str='role:baz',
            description='Create a foo.',
            operations=[{'path': '/v1/foos/', 'method': 'POST'}],
            deprecated_for_removal=True,
            deprecated_reason=(
                '"foo:bar" is no longer a policy used by the service'
            ),
            deprecated_since='N'
        )]
        expected_msg = (
            'Policy "foo:bar":"role:baz" was deprecated for removal in N. '
            'Reason: "foo:bar" is no longer a policy used by the service. Its '
            'value may be silently ignored in the future.'
        )
        rules = jsonutils.dumps({'foo:bar': 'role:bang'})
        self.create_config_file('policy.json', rules)
        enforcer = policy.Enforcer(self.conf)
        enforcer.register_defaults(rule_list)

        with mock.patch('warnings.warn') as mock_warn:
            enforcer.load_rules()
            mock_warn.assert_called_once_with(expected_msg) 
Example #5
Source File: policy.py    From tacker with Apache License 2.0 6 votes vote down vote up
def get_enforcer():
    # NOTE(amotoki): This was borrowed from nova/policy.py.
    # This method is for use by oslo.policy CLI scripts. Those scripts need the
    # 'output-file' and 'namespace' options, but having those in sys.argv means
    # loading the tacker config options will fail as those are not expected to
    # be present. So we pass in an arg list with those stripped out.
    conf_args = []
    # Start at 1 because cfg.CONF expects the equivalent of sys.argv[1:]
    i = 1
    while i < len(sys.argv):
        if sys.argv[i].strip('-') in ['namespace', 'output-file']:
            i += 2
            continue
        conf_args.append(sys.argv[i])
        i += 1

    # 'project' must be 'tacker' so that get_enforcer looks at
    # /etc/tacker/policy.json by default.
    cfg.CONF(conf_args, project='tacker')
    init()
    return _ENFORCER 
Example #6
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def test_fail_decrypt_secret_for_creator_user_with_different_project(self):
        """Check for creator user rule for secret decrypt/get call.

        If token's user is creator of secret but its scoped to different
        project, then he/she is not allowed access to secret when project
        is marked private.
        """
        self.acl_list.pop()  # remove read acl from default setup
        acl_read = models.SecretACL(secret_id=self.secret_id,
                                    operation='write',
                                    project_access=True,
                                    user_ids=['anyRandomUserX', 'aclUser1'])
        self.acl_list.append(acl_read)
        self.resource.controller.secret.creator_id = 'creatorUserX'
        # token user is creator but scoped to project different from secret
        # project so don't allow decrypt secret call to creator of that secret
        self._assert_fail_rbac(['admin', 'observer', 'creator', 'audit',
                                'bogusRole'],
                               self._invoke_on_get,
                               accept='notjsonaccepttype',
                               content_type='application/json',
                               user_id='creatorUserX',
                               project_id='different_project_id') 
Example #7
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def test_should_pass_decrypt_secret_private_enabled_with_read_acl(self):
        """Should pass authz as user has read acl for private secret.

        Even though secret is private, user with read acl should be able to
        access the secret.
        """
        self.acl_list.pop()  # remove read acl from default setup
        acl_read = models.SecretACL(secret_id=self.secret_id, operation='read',
                                    project_access=False,
                                    user_ids=['anyRandomUserX', 'aclUser1'])
        self.acl_list.append(acl_read)
        self._assert_pass_rbac(['admin', 'observer', 'creator', 'audit',
                                'bogusRole'],
                               self._invoke_on_get,
                               accept='notjsonaccepttype',
                               content_type='application/json',
                               user_id='aclUser1',
                               project_id=self.external_project_id) 
Example #8
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def test_pass_decrypt_secret_for_admin_user_project_access_disabled(self):
        """Should pass authz for admin role user as secret is marked private.

        Even when secret is private, admin user should still have access to
        the secret.
        """
        self.acl_list.pop()  # remove read acl from default setup
        acl_read = models.SecretACL(secret_id=self.secret_id, operation='read',
                                    project_access=False,
                                    user_ids=['anyRandomUserX', 'aclUser1'])
        self.acl_list.append(acl_read)
        self._assert_pass_rbac(['admin'],
                               self._invoke_on_get,
                               accept='notjsonaccepttype',
                               content_type='application/json',
                               user_id=self.user_id,
                               project_id=self.external_project_id) 
Example #9
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def test_should_raise_decrypt_secret_with_project_access_disabled(self):
        """Should raise authz error as secret is marked private.

        As secret is private so project users should not be able to access
        the secret. Admin project user can still access it.
        """
        self.acl_list.pop()  # remove read acl from default setup
        acl_read = models.SecretACL(secret_id=self.secret_id, operation='read',
                                    project_access=False,
                                    user_ids=['anyRandomUserX', 'aclUser1'])
        self.acl_list.append(acl_read)
        self._assert_fail_rbac(['observer', 'creator', 'audit'],
                               self._invoke_on_get,
                               accept='notjsonaccepttype',
                               content_type='application/json',
                               user_id=self.user_id,
                               project_id=self.external_project_id) 
Example #10
Source File: property_utils.py    From searchlight with Apache License 2.0 6 votes vote down vote up
def _add_policy_rules(self, property_exp, action, rule):
        """Add policy rules to the policy enforcer.

        For example, if the file listed as property_protection_file has:
        [prop_a]
        create = searchlight_creator
        then the corresponding policy rule would be:
        "prop_a:create": "rule:searchlight_creator"
        where searchlight_creator is defined in policy.json or policy.yaml.
        For example:
        "searchlight_creator": "role:admin or role:searchlight_create_user"
        """
        rule = "rule:%s" % rule
        rule_name = "%s:%s" % (property_exp, action)
        rule_dict = policy.Rules.from_dict({
            rule_name: rule
        })
        self.policy_enforcer.add_rules(rule_dict) 
Example #11
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_load_directory_caching_with_files_same(self, overwrite=True):
        self.enforcer.overwrite = overwrite

        self.create_config_file(
            os.path.join('policy.d', 'a.conf'), POLICY_A_CONTENTS)

        self.enforcer.load_rules(False)
        self.assertIsNotNone(self.enforcer.rules)

        old = six.next(six.itervalues(
            self.enforcer._policy_dir_mtimes))
        self.assertEqual(1, len(self.enforcer._policy_dir_mtimes))

        self.enforcer.load_rules(False)
        self.assertEqual(1, len(self.enforcer._policy_dir_mtimes))
        self.assertEqual(old, six.next(six.itervalues(
            self.enforcer._policy_dir_mtimes)))

        loaded_rules = jsonutils.loads(str(self.enforcer.rules))
        self.assertEqual('is_admin:True', loaded_rules['admin'])
        self.check_loaded_files([
            'policy.json',
            os.path.join('policy.d', 'a.conf'),
        ]) 
Example #12
Source File: _engine.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def get_enforcer():
    # NOTE(amotoki): This was borrowed from nova/policy.py.
    # This method is for use by oslo.policy CLI scripts. Those scripts need the
    # 'output-file' and 'namespace' options, but having those in sys.argv means
    # loading the neutron config options will fail as those are not expected to
    # be present. So we pass in an arg list with those stripped out.
    conf_args = []
    # Start at 1 because cfg.CONF expects the equivalent of sys.argv[1:]
    i = 1
    while i < len(sys.argv):
        if sys.argv[i].strip('-') in ['namespace', 'output-file']:
            i += 2
            continue
        conf_args.append(sys.argv[i])
        i += 1

    # 'project' must be 'neutron' so that get_enforcer looks at
    # /etc/neutron/policy.json by default.
    cfg.CONF(conf_args, project='neutron')
    init()
    return _ROLE_ENFORCER 
Example #13
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_get_policy_path_raises_exc(self):
        enforcer = policy.Enforcer(self.conf, policy_file='raise_error.json')
        e = self.assertRaises(cfg.ConfigFilesNotFoundError,
                              enforcer._get_policy_path, enforcer.policy_file)
        self.assertEqual(('raise_error.json', ), e.config_files) 
Example #14
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(CheckFunctionTestCase, self).setUp()
        self.create_config_file('policy.json', POLICY_JSON_CONTENTS) 
Example #15
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_non_reversible_check(self):
        self.create_config_file('policy.json',
                                jsonutils.dumps(
                                    {'shared': 'field:networks:shared=True'}))
        # load_rules succeeding without error is the focus of this test
        self.enforcer.load_rules(True)
        self.assertIsNotNone(self.enforcer.rules)
        loaded_rules = jsonutils.loads(str(self.enforcer.rules))
        self.assertNotEqual('field:networks:shared=True',
                            loaded_rules['shared']) 
Example #16
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_check_rule_not_exist_not_empty_policy_file(self):
        # If the rule doesn't exist, then enforce() fails rather than KeyError.

        # This test needs a non-empty file otherwise the code short-circuits.
        self.create_config_file('policy.json', jsonutils.dumps({"a_rule": []}))
        self.enforcer.default_rule = None
        self.enforcer.load_rules()
        creds = {}
        result = self.enforcer.enforce('rule', 'target', creds)
        self.assertFalse(result) 
Example #17
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_load_directory_caching_with_files_updated(self):
        self.create_config_file(
            os.path.join('policy.d', 'a.conf'), POLICY_A_CONTENTS)

        self.enforcer.load_rules(False)
        self.assertIsNotNone(self.enforcer.rules)

        old = six.next(six.itervalues(
            self.enforcer._policy_dir_mtimes))
        self.assertEqual(1, len(self.enforcer._policy_dir_mtimes))

        # Touch the file
        conf_path = os.path.join(self.config_dir, os.path.join(
            'policy.d', 'a.conf'))
        stinfo = os.stat(conf_path)
        os.utime(conf_path, (stinfo.st_atime + 10, stinfo.st_mtime + 10))

        self.enforcer.load_rules(False)
        self.assertEqual(1, len(self.enforcer._policy_dir_mtimes))
        self.assertEqual(old, six.next(six.itervalues(
            self.enforcer._policy_dir_mtimes)))

        loaded_rules = jsonutils.loads(str(self.enforcer.rules))
        self.assertEqual('is_admin:True', loaded_rules['admin'])
        self.check_loaded_files([
            'policy.json',
            os.path.join('policy.d', 'a.conf'),
            os.path.join('policy.d', 'a.conf'),
        ]) 
Example #18
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_override_deprecated_policy_with_new_name(self):
        # Simulate an operator overriding a policy using the new policy name
        rules = jsonutils.dumps({'foo:create_bar': 'role:bazz'})
        self.create_config_file('policy.json', rules)

        # Deprecate the policy name and check string in favor of something
        # better.
        deprecated_rule = policy.DeprecatedRule(
            name='foo:bar',
            check_str='role:fizz'
        )
        rule_list = [policy.DocumentedRuleDefault(
            name='foo:create_bar',
            check_str='role:bang',
            description='Create a bar.',
            operations=[{'path': '/v1/bars', 'method': 'POST'}],
            deprecated_rule=deprecated_rule,
            deprecated_reason='"role:bang" is a better default',
            deprecated_since='N'
        )]
        self.enforcer.register_defaults(rule_list)

        # Make sure the override supplied by the operator is being used in
        # place of either default value.
        self.assertFalse(
            self.enforcer.enforce('foo:create_bar', {}, {'roles': ['fizz']})
        )
        self.assertFalse(
            self.enforcer.enforce('foo:create_bar', {}, {'roles': ['bang']})
        )
        self.assertTrue(
            self.enforcer.enforce('foo:create_bar', {}, {'roles': ['bazz']})
        ) 
Example #19
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_override_deprecated_policy_with_new_rule(self):
        # Simulate an operator overriding a deprecated policy with a reference
        # to the new policy, as done by the sample policy generator.
        rules = jsonutils.dumps({'old_rule': 'rule:new_rule'})
        self.create_config_file('policy.json', rules)

        # Deprecate the policy name in favor of something better.
        deprecated_rule = policy.DeprecatedRule(
            name='old_rule',
            check_str='role:bang'
        )
        rule_list = [policy.DocumentedRuleDefault(
            name='new_rule',
            check_str='role:bang',
            description='Replacement for old_rule.',
            operations=[{'path': '/v1/bars', 'method': 'POST'}],
            deprecated_rule=deprecated_rule,
            deprecated_reason='"old_rule" is a bad name',
            deprecated_since='N'
        )]
        self.enforcer.register_defaults(rule_list)

        # Make sure the override supplied by the operator using the old policy
        # name is used in favor of the old or new default.
        self.assertFalse(
            self.enforcer.enforce('new_rule', {}, {'roles': ['fizz']})
        )
        self.assertTrue(
            self.enforcer.enforce('new_rule', {}, {'roles': ['bang']})
        )
        # Verify that we didn't overwrite the new rule.
        self.assertEqual('bang', self.enforcer.rules['new_rule'].match) 
Example #20
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_no_violations(self):
        self.create_config_file('policy.json', POLICY_JSON_CONTENTS)
        self.enforcer.load_rules(True)
        self.assertTrue(self.enforcer.check_rules(raise_on_violation=True)) 
Example #21
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_undefined_rule(self, mock_log):
        rules = jsonutils.dumps({'foo': 'rule:bar'})
        self.create_config_file('policy.json', rules)
        self.enforcer.load_rules(True)

        self.assertFalse(self.enforcer.check_rules())
        mock_log.warning.assert_called() 
Example #22
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_cyclical_rules(self, mock_log):
        rules = jsonutils.dumps({'foo': 'rule:bar', 'bar': 'rule:foo'})
        self.create_config_file('policy.json', rules)
        self.enforcer.load_rules(True)

        self.assertFalse(self.enforcer.check_rules())
        mock_log.warning.assert_called() 
Example #23
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_cyclical_rules_raises(self, mock_log):
        rules = jsonutils.dumps({'foo': 'rule:bar', 'bar': 'rule:foo'})
        self.create_config_file('policy.json', rules)
        self.enforcer.load_rules(True)

        self.assertRaises(policy.InvalidDefinitionError,
                          self.enforcer.check_rules, raise_on_violation=True)
        mock_log.warning.assert_called() 
Example #24
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_complex_cyclical_rules_false(self, mock_log):
        rules = jsonutils.dumps({'foo': 'rule:bar',
                                 'bar': 'rule:baz and role:admin',
                                 'baz': 'rule:foo or role:user'})
        self.create_config_file('policy.json', rules)
        self.enforcer.load_rules(True)

        self.assertFalse(self.enforcer.check_rules())
        mock_log.warning.assert_called() 
Example #25
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_complex_cyclical_rules_true(self):
        rules = jsonutils.dumps({'foo': 'rule:bar or rule:baz',
                                 'bar': 'role:admin',
                                 'baz': 'rule:bar or role:user'})
        self.create_config_file('policy.json', rules)
        self.enforcer.load_rules(True)

        self.assertTrue(self.enforcer.check_rules()) 
Example #26
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def test_should_raise_create_consumer(self):
        self._assert_fail_rbac([None, 'audit', 'observer', 'creator', 'bogus'],
                               self._invoke_on_post,
                               content_type='application/json') 
Example #27
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def test_should_pass_create_secret(self):
        self._assert_pass_rbac(['admin', 'creator'], self._invoke_on_post,
                               content_type='application/json') 
Example #28
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def test_should_raise_create_secret(self):
        self._assert_fail_rbac([None, 'audit', 'observer', 'bogus'],
                               self._invoke_on_post,
                               content_type='application/json') 
Example #29
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def test_should_pass_get_secrets(self):
        self._assert_pass_rbac(['admin', 'observer', 'creator'],
                               self._invoke_on_get,
                               content_type='application/json') 
Example #30
Source File: test_resources_policy.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def test_should_raise_get_secrets(self):
        self._assert_fail_rbac([None, 'audit', 'bogus'],
                               self._invoke_on_get,
                               content_type='application/json')