Python oslo_policy.policy.RuleDefault() Examples

The following are 30 code examples of oslo_policy.policy.RuleDefault(). 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_policy.py    From karbor with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(PolicyTestCase, self).setUp()
        rules = [
            oslo_policy.RuleDefault("true", '@'),
            oslo_policy.RuleDefault("test:allowed", '@'),
            oslo_policy.RuleDefault("test:denied", "!"),
            oslo_policy.RuleDefault("test:my_file",
                                    "role:compute_admin or "
                                    "project_id:%(project_id)s"),
            oslo_policy.RuleDefault("test:early_and_fail", "! and @"),
            oslo_policy.RuleDefault("test:early_or_success", "@ or !"),
            oslo_policy.RuleDefault("test:lowercase_admin",
                                    "role:admin"),
            oslo_policy.RuleDefault("test:uppercase_admin",
                                    "role:ADMIN"),
        ]
        policy.reset()
        policy.init()
        # before a policy rule can be used, its default has to be registered.
        policy._ENFORCER.register_defaults(rules)
        self.context = context.RequestContext('fake', 'fake', roles=['member'])
        self.target = {}
        self.addCleanup(policy.reset) 
Example #2
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def _test_scenario_with_opts_registered(self, scenario, *args, **kwargs):
        # This test registers some rules, calls the scenario and then checks
        # the registered rules. The scenario should be a method which loads
        # policy files containing POLICY_*_CONTENTS defined above. They should
        # be loaded on the self.enforcer object.

        # This should be overridden by the policy file
        self.enforcer.register_default(policy.RuleDefault(name='admin',
                                       check_str='is_admin:False'))
        # This is not in the policy file, only registered
        self.enforcer.register_default(policy.RuleDefault(name='owner',
                                       check_str='role:owner'))

        scenario(*args, **kwargs)

        self.assertIn('owner', self.enforcer.rules)
        self.assertEqual('role:owner', str(self.enforcer.rules['owner']))
        self.assertEqual('is_admin:True', str(self.enforcer.rules['admin']))
        self.assertIn('owner', self.enforcer.registered_rules)
        self.assertIn('admin', self.enforcer.registered_rules)
        self.assertNotIn('default', self.enforcer.registered_rules)
        self.assertNotIn('owner', self.enforcer.file_rules)
        self.assertIn('admin', self.enforcer.file_rules)
        self.assertIn('default', self.enforcer.file_rules) 
Example #3
Source File: test_policy.py    From octavia with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=True) as tmp:
            self.conf.load_raw_values(
                group='oslo_policy', policy_file=tmp.name)

            tmp.write('{"example:test": ""}')
            tmp.flush()

            self.context = context.Context('fake', 'fake')

            rule = oslo_policy.RuleDefault('example:test', "")
            policy.get_enforcer().register_defaults([rule])

            action = "example:test"
            policy.get_enforcer().authorize(action, self.target, self.context)

            tmp.seek(0)
            tmp.write('{"example:test": "!"}')
            tmp.flush()
            policy.get_enforcer().load_rules(True)
            self.assertRaises(exceptions.PolicyForbidden,
                              policy.get_enforcer().authorize,
                              action, self.target, self.context) 
Example #4
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_enforcer_raises_invalid_scope_with_system_scope_type(self):
        self.conf.set_override('enforce_scope', True, group='oslo_policy')
        rule = policy.RuleDefault(
            name='fake_rule', check_str='role:test', scope_types=['system']
        )
        self.enforcer.register_default(rule)

        # model a domain-scoped token, which should fail enforcement
        ctx = context.RequestContext(domain_id='fake')
        target_dict = {}
        self.assertRaises(
            policy.InvalidScope, self.enforcer.enforce, 'fake_rule',
            target_dict, ctx
        )

        # model a project-scoped token, which should fail enforcement
        ctx = context.RequestContext(project_id='fake')
        self.assertRaises(
            policy.InvalidScope, self.enforcer.enforce, 'fake_rule',
            target_dict, ctx
        ) 
Example #5
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_enforcer_keep_use_conf_flag_after_reload_opts_registered(self):
        # This test does not use _test_scenario_with_opts_registered because
        # it loads all rules and then dumps them to a policy file and reloads.
        # That breaks the ability to differentiate between registered and file
        # loaded policies.

        # This should be overridden by the policy file
        self.enforcer.register_default(policy.RuleDefault(name='admin',
                                       check_str='is_admin:False'))
        # This is not in the policy file, only registered
        self.enforcer.register_default(policy.RuleDefault(name='owner',
                                       check_str='role:owner'))

        self.test_enforcer_keep_use_conf_flag_after_reload()

        self.assertIn('owner', self.enforcer.rules)
        self.assertEqual('role:owner', str(self.enforcer.rules['owner']))
        self.assertEqual('is_admin:True', str(self.enforcer.rules['admin'])) 
Example #6
Source File: test_policy.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        tmp_file = \
            self.create_tempfiles(files=[('policies', '{}')], ext='.yaml')[0]
        base.BaseTestCase.conf_override(policy_file=tmp_file,
                                        group='oslo_policy')

        policy.reset()
        policy.init()
        action = 'example:test'
        rule = os_policy.RuleDefault(action, '')
        policy._ENFORCER.register_defaults([rule])

        with open(tmp_file, 'w') as policy_file:
            policy_file.write('{"example:test": ""}')
        policy.authorize(self.context, action, self.target)

        with open(tmp_file, 'w') as policy_file:
            policy_file.write('{"example:test": "!"}')
        policy._ENFORCER.load_rules(True)
        self.assertRaises(os_policy.PolicyNotAuthorized, policy.authorize,
                          self.context, action, self.target) 
Example #7
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_enforcer_raises_invalid_scope_with_domain_scope_type(self):
        self.conf.set_override('enforce_scope', True, group='oslo_policy')
        rule = policy.RuleDefault(
            name='fake_rule', check_str='role:test', scope_types=['domain']
        )
        self.enforcer.register_default(rule)

        # model a system-scoped token, which should fail enforcement
        ctx = context.RequestContext(system_scope='all')
        target_dict = {}
        self.assertRaises(
            policy.InvalidScope, self.enforcer.enforce, 'fake_rule',
            target_dict, ctx
        )

        # model a project-scoped token, which should fail enforcement
        ctx = context.RequestContext(project_id='fake')
        self.assertRaises(
            policy.InvalidScope, self.enforcer.enforce, 'fake_rule',
            target_dict, ctx
        ) 
Example #8
Source File: test_policy.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        tmp_file = \
            self.create_tempfiles(files=[('policies', '{}')], ext='.yaml')[0]
        base.BaseTestCase.conf_override(policy_file=tmp_file,
                                        group='oslo_policy')

        policy.reset()
        policy.init()
        action = 'example:test'
        rule = os_policy.RuleDefault(action, '')
        policy._ENFORCER.register_defaults([rule])

        with open(tmp_file, 'w') as policy_file:
            policy_file.write('{"example:test": ""}')
        policy.authorize(self.context, action, self.target)

        with open(tmp_file, 'w') as policy_file:
            policy_file.write('{"example:test": "!"}')
        policy._ENFORCER.load_rules(True)
        self.assertRaises(os_policy.PolicyNotAuthorized, policy.authorize,
                          self.context, action, self.target) 
Example #9
Source File: test_policy.py    From karbor with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        with utils.tempdir() as tmpdir:
            tmpfilename = os.path.join(tmpdir, 'policy')
            self.fixture.config(policy_file=tmpfilename, group='oslo_policy')
            policy.reset()
            policy.init()
            rule = oslo_policy.RuleDefault('example:test', "")
            policy._ENFORCER.register_defaults([rule])

            action = "example:test"
            with open(tmpfilename, "w") as policyfile:
                policyfile.write('{"example:test": ""}')
            policy.authorize(self.context, action, self.target)
            with open(tmpfilename, "w") as policyfile:
                policyfile.write('{"example:test": "!"}')
            policy._ENFORCER.load_rules(True)
            self.assertRaises(exception.PolicyNotAuthorized,
                              policy.authorize,
                              self.context, action, self.target) 
Example #10
Source File: test_policy.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        tmp_file = \
            self.create_tempfiles(files=[('policies', '{}')], ext='.yaml')[0]
        base.BaseTestCase.conf_override(policy_file=tmp_file,
                                        group='oslo_policy')

        policy_engine.reset()
        policy_engine.init()

        action = 'example:test'
        rule = os_policy.RuleDefault(action, '')
        policy_engine._ENFORCER.register_defaults([rule])

        with open(tmp_file, 'w') as policy_file:
            policy_file.write('{"example:test": ""}')
        policy_engine.authorize(self.context, action, self.target)

        with open(tmp_file, 'w') as policy_file:
            policy_file.write('{"example:test": "!"}')
        policy_engine._ENFORCER.load_rules(True)
        self.assertRaises(os_policy.PolicyNotAuthorized,
                          policy_engine.authorize,
                          self.context, action, self.target) 
Example #11
Source File: test_policy.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(PolicyTestCase, self).setUp()
        rules = [
            oslo_policy.RuleDefault("true", '@'),
            oslo_policy.RuleDefault("test:allowed", '@'),
            oslo_policy.RuleDefault("test:denied", "!"),
            oslo_policy.RuleDefault("test:early_and_fail", "! and @"),
            oslo_policy.RuleDefault("test:early_or_success", "@ or !"),
            oslo_policy.RuleDefault("test:lowercase_admin",
                                    "role:admin"),
            oslo_policy.RuleDefault("test:uppercase_admin",
                                    "role:ADMIN"),
        ]
        CONF(args=[], project='cloudkitty', default_config_files=[])
        # before a policy rule can be used, its default has to be registered.
        policy.reset()
        policy.init()
        policy._ENFORCER.register_defaults(rules)
        self.context = context.RequestContext(user_id='fake',
                                              project_id='fake',
                                              roles=['member'])
        self.target = {}
        self.addCleanup(policy.reset) 
Example #12
Source File: test_policy.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        with utils.tempdir() as tmpdir:
            tmpfilename = os.path.join(tmpdir, 'policy')
            self.fixture.config(policy_file=tmpfilename, group='oslo_policy')
            rule = oslo_policy.RuleDefault('example:test', "")
            policy.reset()
            policy.init()
            policy._ENFORCER.register_defaults([rule])

            action = "example:test"
            with open(tmpfilename, "w") as policyfile:
                policyfile.write('{"example:test": ""}')
            policy.authorize(self.context, action, self.target)
            with open(tmpfilename, "w") as policyfile:
                policyfile.write('{"example:test": "!"}')
            policy._ENFORCER.load_rules(True)
            self.assertRaises(policy.PolicyNotAuthorized,
                              policy.authorize,
                              self.context, action, self.target) 
Example #13
Source File: test_policy.py    From masakari with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(PolicyTestCase, self).setUp()
        rules = [
            oslo_policy.RuleDefault("true", '@'),
            oslo_policy.RuleDefault("example:allowed", '@'),
            oslo_policy.RuleDefault("example:denied", "!"),
            oslo_policy.RuleDefault("example:get_http",
                                    "http://www.example.com"),
            oslo_policy.RuleDefault("example:my_file",
                                    "role:compute_admin or "
                                    "project_id:%(project_id)s"),
            oslo_policy.RuleDefault("example:early_and_fail", "! and @"),
            oslo_policy.RuleDefault("example:early_or_success", "@ or !"),
            oslo_policy.RuleDefault("example:lowercase_admin",
                                    "role:admin or role:sysadmin"),
            oslo_policy.RuleDefault("example:uppercase_admin",
                                    "role:ADMIN or role:sysadmin"),
        ]
        policy.reset()
        policy.init()
        # before a policy rule can be used, its default has to be registered.
        policy._ENFORCER.register_defaults(rules)
        self.context = context.RequestContext('fake', 'fake', roles=['member'])
        self.target = {} 
Example #14
Source File: test_policy.py    From masakari with Apache License 2.0 6 votes vote down vote up
def test_modified_policy_reloads(self):
        with utils.tempdir() as tmpdir:
            tmpfilename = os.path.join(tmpdir, 'policy')

            self.flags(policy_file=tmpfilename, group='oslo_policy')

            # NOTE(Dinesh_Bhor): context construction invokes policy check to
            # determine is_admin or not. As a side-effect, policy reset is
            # needed here to flush existing policy cache.
            policy.reset()
            policy.init()
            rule = oslo_policy.RuleDefault('example:test', "")
            policy._ENFORCER.register_defaults([rule])

            action = "example:test"
            with open(tmpfilename, "w") as policyfile:
                policyfile.write('{"example:test": ""}')
            policy.authorize(self.context, action, self.target)
            with open(tmpfilename, "w") as policyfile:
                policyfile.write('{"example:test": "!"}')
            policy._ENFORCER.load_rules(True)
            self.assertRaises(exception.PolicyNotAuthorized, policy.authorize,
                              self.context, action, self.target) 
Example #15
Source File: test_policy.py    From manila with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(PolicyTestCase, self).setUp()
        rules = [
            common_policy.RuleDefault("true", '@'),
            common_policy.RuleDefault("test:allowed", '@'),
            common_policy.RuleDefault("test:denied", "!"),
            common_policy.RuleDefault("test:my_file",
                                      "role:compute_admin or "
                                      "project_id:%(project_id)s"),
            common_policy.RuleDefault("test:early_and_fail", "! and @"),
            common_policy.RuleDefault("test:early_or_success", "@ or !"),
            common_policy.RuleDefault("test:lowercase_admin",
                                      "role:admin"),
            common_policy.RuleDefault("test:uppercase_admin",
                                      "role:ADMIN"),
        ]
        policy.reset()
        policy.init()
        # before a policy rule can be used, its default has to be registered.
        policy._ENFORCER.register_defaults(rules)
        self.context = context.RequestContext('fake', 'fake', roles=['member'])
        self.target = {}
        self.addCleanup(policy.reset) 
Example #16
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_rule_is_parsed(self):
        opt = policy.RuleDefault(name='foo', check_str='rule:foo')
        self.assertIsInstance(opt.check, _checks.BaseCheck)
        self.assertEqual('rule:foo', str(opt.check)) 
Example #17
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_not_equal_name(self):
        opt1 = policy.RuleDefault(name='foo', check_str='rule:foo',
                                  description='foo')
        opt2 = policy.RuleDefault(name='bar', check_str='rule:foo',
                                  description='bar')
        self.assertNotEqual(opt1, opt2) 
Example #18
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_not_equal_class(self):
        class NotRuleDefault(object):
            def __init__(self, name, check_str):
                self.name = name
                self.check = _parser.parse_rule(check_str)

        opt1 = policy.RuleDefault(name='foo', check_str='rule:foo')
        opt2 = NotRuleDefault(name='foo', check_str='rule:foo')
        self.assertNotEqual(opt1, opt2) 
Example #19
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_equality_less_obvious(self):
        opt1 = policy.RuleDefault(name='foo', check_str='',
                                  description='foo')
        opt2 = policy.RuleDefault(name='foo', check_str='@',
                                  description='bar')
        self.assertEqual(opt1, opt2) 
Example #20
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_equality_obvious(self):
        opt1 = policy.RuleDefault(name='foo', check_str='rule:foo',
                                  description='foo')
        opt2 = policy.RuleDefault(name='foo', check_str='rule:foo',
                                  description='bar')
        self.assertEqual(opt1, opt2) 
Example #21
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_str(self):
        opt = policy.RuleDefault(name='foo', check_str='rule:foo')
        self.assertEqual('"foo": "rule:foo"', str(opt)) 
Example #22
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_enforcer_understands_system_scope(self):
        self.conf.set_override('enforce_scope', True, group='oslo_policy')
        rule = policy.RuleDefault(
            name='fake_rule', check_str='role:test', scope_types=['system']
        )
        self.enforcer.register_default(rule)

        ctx = context.RequestContext(system_scope='all')
        target_dict = {}
        self.enforcer.enforce('fake_rule', target_dict, ctx) 
Example #23
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_equal_subclass(self):
        class RuleDefaultSub(policy.RuleDefault):
            pass

        opt1 = policy.RuleDefault(name='foo', check_str='rule:foo')
        opt2 = RuleDefaultSub(name='foo', check_str='rule:foo')
        self.assertEqual(opt1, opt2) 
Example #24
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_not_equal_subclass(self):
        class RuleDefaultSub(policy.RuleDefault):
            pass

        opt1 = policy.RuleDefault(name='foo', check_str='rule:foo')
        opt2 = RuleDefaultSub(name='bar', check_str='rule:foo')
        self.assertNotEqual(opt1, opt2) 
Example #25
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_create_opt_with_scope_types(self):
        scope_types = ['project']
        opt = policy.RuleDefault(
            name='foo',
            check_str='role:bar',
            scope_types=scope_types
        )
        self.assertEqual(opt.scope_types, scope_types) 
Example #26
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_create_opt_with_multiple_scope_types(self):
        opt = policy.RuleDefault(
            name='foo',
            check_str='role:bar',
            scope_types=['project', 'domain', 'system']
        )

        self.assertEqual(opt.scope_types, ['project', 'domain', 'system']) 
Example #27
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_ensure_scope_types_are_unique(self):
        self.assertRaises(
            ValueError,
            policy.RuleDefault,
            name='foo',
            check_str='role:bar',
            scope_types=['project', 'project']
        ) 
Example #28
Source File: test_generator.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_policies_deprecated_for_removal(self):
        rule = policy.RuleDefault(
            name='foo:post_bar',
            check_str='role:fizz',
            description='Create a bar.',
            deprecated_for_removal=True,
            deprecated_reason='This policy is not used anymore',
            deprecated_since='N'
        )
        opts = {'rules': [rule]}

        extensions = []
        for name, opts, in opts.items():
            ext = stevedore.extension.Extension(name=name, entry_point=None,
                                                plugin=None, obj=opts)
            extensions.append(ext)

        test_mgr = stevedore.named.NamedExtensionManager.make_test_instance(
            extensions=extensions, namespace=['rules']
        )

        expected = '''# DEPRECATED
# "foo:post_bar" has been deprecated since N.
# This policy is not used anymore
# Create a bar.
#"foo:post_bar": "role:fizz"

'''
        stdout = self._capture_stdout()
        with mock.patch('stevedore.named.NamedExtensionManager',
                        return_value=test_mgr) as mock_ext_mgr:
            generator._generate_sample(['rules'], output_file=None)
            mock_ext_mgr.assert_called_once_with(
                'oslo.policy.policies', names=['rules'],
                on_load_failure_callback=generator.on_load_failure_callback,
                invoke_on_load=True
            )
        self.assertEqual(expected, stdout.getvalue()) 
Example #29
Source File: test_generator.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def _get_test_enforcer(self):
        test_rules = [policy.RuleDefault('foo', 'foo:bar=baz'),
                      policy.RuleDefault('bar', 'bar:foo=baz')]
        enforcer = policy.Enforcer(self.conf)
        enforcer.register_defaults(test_rules)
        return enforcer 
Example #30
Source File: generator.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def _format_rule_default_json(default):
    """Create a json node from policy.RuleDefault or policy.DocumentedRuleDefault.

    :param default: A policy.RuleDefault or policy.DocumentedRuleDefault object
    :returns: A string containing a json representation of the RuleDefault
    """
    return ('"%(name)s": "%(check_str)s"' %
            {'name': default.name,
             'check_str': default.check_str})