Python oslo_policy.policy.Enforcer() Examples

The following are 30 code examples of oslo_policy.policy.Enforcer(). 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: _engine.py    From neutron-lib with Apache License 2.0 6 votes vote down vote up
def init(conf=cfg.CONF, policy_file=None):
    """Initialize the global enforcer if not already initialized.

    Initialize the global enforcer (and load its rules) if not already
    initialized; otherwise this is a no-op.

    :param conf: The configuration to initialize the global enforcer with.
    Defaults to oslo_config.cfg.CONF.
    :param policy_file: The policy file to initialize the global enforcer
    with.
    :returns: None.
    """

    global _ROLE_ENFORCER
    if not _ROLE_ENFORCER:
        _ROLE_ENFORCER = policy.Enforcer(conf, policy_file=policy_file)
        _ROLE_ENFORCER.register_defaults(_BASE_RULES)
        _ROLE_ENFORCER.load_rules(True) 
Example #2
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 #3
Source File: context.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def __init__(self, roles=None, policy_enforcer=None, project=None,
                 **kwargs):
        # prefer usage of 'project' instead of 'tenant'
        if project:
            kwargs['tenant'] = project
        self.project = project
        self.policy_enforcer = policy_enforcer or policy.Enforcer(CONF)

        # NOTE(edtubill): oslo_context 2.2.0 now has a roles attribute in
        # the RequestContext. This will make sure of backwards compatibility
        # with past oslo_context versions.
        argspec = inspect.getargspec(super(RequestContext, self).__init__)
        if 'roles' in argspec.args:
            kwargs['roles'] = roles
        else:
            self.roles = roles or []

        super(RequestContext, self).__init__(**kwargs) 
Example #4
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_deprecate_check_str_suppress_does_not_log_warning(self):
        deprecated_rule = policy.DeprecatedRule(
            name='foo:create_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'
        )]
        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 #5
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 #6
Source File: policy.py    From manila with Apache License 2.0 6 votes vote down vote up
def init(rules=None, use_conf=True):
    """Init an Enforcer class.

        :param policy_file: Custom policy file to use, if none is specified,
                          `CONF.policy_file` will be used.
        :param rules: Default dictionary / Rules to use. It will be
                    considered just in the first instantiation.
        :param default_rule: Default rule to use, CONF.default_rule will
                           be used if none is specified.
        :param use_conf: Whether to load rules from config file.
    """

    global _ENFORCER
    if not _ENFORCER:
        _ENFORCER = policy.Enforcer(CONF,
                                    rules=rules,
                                    use_conf=use_conf)
        register_rules(_ENFORCER) 
Example #7
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 #8
Source File: test_policy.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def test_suppress_default_change_warnings_flag_not_log_warning(self):
        deprecated_rule = policy.DeprecatedRule(
            name='foo:create_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'
        )]
        enforcer = policy.Enforcer(self.conf)
        enforcer.suppress_default_change_warnings = True
        enforcer.register_defaults(rule_list)
        with mock.patch('warnings.warn') as mock_warn:
            enforcer.load_rules()
            mock_warn.assert_not_called() 
Example #9
Source File: generator.py    From oslo.policy with Apache License 2.0 6 votes vote down vote up
def _get_enforcer(namespace):
    """Find a policy.Enforcer via an entry point with the given namespace.

    :param namespace: a namespace under oslo.policy.enforcer where the desired
                      enforcer object can be found.
    :returns: a policy.Enforcer object
    """
    mgr = stevedore.named.NamedExtensionManager(
        'oslo.policy.enforcer',
        names=[namespace],
        on_load_failure_callback=on_load_failure_callback,
        invoke_on_load=True)
    if namespace not in mgr:
        raise KeyError('Namespace "%s" not found.' % namespace)
    enforcer = mgr[namespace].obj

    return enforcer 
Example #10
Source File: policy.py    From cyborg with Apache License 2.0 6 votes vote down vote up
def authorize(rule, target, creds, do_raise=False, *args, **kwargs):
    """A shortcut for policy.Enforcer.authorize()

    Checks authorization of a rule against the target and credentials, and
    raises an exception if the rule is not defined.
    """
    enforcer = get_enforcer()
    try:
        return enforcer.authorize(rule, target, creds, do_raise=do_raise,
                                  *args, **kwargs)
    except policy.PolicyNotAuthorized:
        raise exception.HTTPForbidden(resource=rule)


# This decorator MUST appear first (the outermost decorator)
# on an API method for it to work correctly 
Example #11
Source File: policy.py    From ironic-inspector with Apache License 2.0 6 votes vote down vote up
def authorize(rule, target, creds, *args, **kwargs):
    """A shortcut for policy.Enforcer.authorize()

    Checks authorization of a rule against the target and credentials, and
    raises an exception if the rule is not defined.
    args and kwargs are passed directly to oslo.policy Enforcer.authorize
    Always returns True if CONF.auth_strategy != keystone.

    :param rule: name of a registered oslo.policy rule
    :param target: dict-like structure to check rule against
    :param creds: dict of policy values from request
    :returns: True if request is authorized against given policy,
              False otherwise
    :raises: oslo_policy.policy.PolicyNotRegistered if supplied policy
             is not registered in oslo_policy
    """
    if CONF.auth_strategy != 'keystone':
        return True
    enforcer = get_enforcer()
    rule = CONF.oslo_policy.policy_default_rule if rule is None else rule
    return enforcer.authorize(rule, target, creds, *args, **kwargs) 
Example #12
Source File: policy.py    From designate with Apache License 2.0 6 votes vote down vote up
def set_rules(data, default_rule=None, overwrite=True):
    default_rule = default_rule or cfg.CONF.policy_default_rule
    if not _ENFORCER:
        LOG.debug("Enforcer not present, recreating at rules stage.")
        init()

    if default_rule:
        _ENFORCER.default_rule = default_rule

    msg = "Loading rules %s, default: %s, overwrite: %s"
    LOG.debug(msg, data, default_rule, overwrite)

    if isinstance(data, dict):
        rules = policy.Rules.from_dict(data, default_rule)
    else:
        rules = policy.Rules.load_json(data, default_rule)

    _ENFORCER.set_rules(rules, overwrite=overwrite) 
Example #13
Source File: config.py    From freezer-api with Apache License 2.0 6 votes vote down vote up
def parse_args(args=[]):
    CONF.register_cli_opts(api_common_opts())
    register_db_drivers_opt()
    # register paste configuration
    paste_grp = cfg.OptGroup('paste_deploy',
                             'Paste Configuration')
    CONF.register_group(paste_grp)
    CONF.register_opts(paste_deploy, group=paste_grp)
    log.register_options(CONF)
    policy.Enforcer(CONF)
    default_config_files = cfg.find_config_files('freezer', 'freezer-api')
    CONF(args=args,
         project='freezer-api',
         default_config_files=default_config_files,
         version=FREEZER_API_VERSION
         ) 
Example #14
Source File: policy.py    From karbor with Apache License 2.0 6 votes vote down vote up
def init(policy_file=None, rules=None, default_rule=None, use_conf=True):
    """Init an Enforcer class.

        :param policy_file: Custom policy file to use, if none is specified,
                          `CONF.policy_file` will be used.
        :param rules: Default dictionary / Rules to use. It will be
                    considered just in the first instantiation.
        :param default_rule: Default rule to use, CONF.default_rule will
                           be used if none is specified.
        :param use_conf: Whether to load rules from config file.
    """

    global _ENFORCER
    if not _ENFORCER:
        _ENFORCER = policy.Enforcer(CONF,
                                    policy_file=policy_file,
                                    rules=rules,
                                    default_rule=default_rule,
                                    use_conf=use_conf)
        register_rules(_ENFORCER)
        _ENFORCER.load_rules() 
Example #15
Source File: policy.py    From ironic-inspector with Apache License 2.0 6 votes vote down vote up
def init_enforcer(policy_file=None, rules=None,
                  default_rule=None, use_conf=True):
    """Synchronously initializes the policy enforcer

       :param policy_file: Custom policy file to use, if none is specified,
                           `CONF.oslo_policy.policy_file` will be used.
       :param rules: Default dictionary / Rules to use. It will be
                     considered just in the first instantiation.
       :param default_rule: Default rule to use,
                            CONF.oslo_policy.policy_default_rule will
                            be used if none is specified.
       :param use_conf: Whether to load rules from config file.
    """
    global _ENFORCER

    if _ENFORCER:
        return
    _ENFORCER = policy.Enforcer(CONF, policy_file=policy_file,
                                rules=rules,
                                default_rule=default_rule,
                                use_conf=use_conf)
    _ENFORCER.register_defaults(list_policies()) 
Example #16
Source File: policy.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.enforcer = policy.Enforcer(cfg.CONF) 
Example #17
Source File: policy.py    From coriolis with GNU Affero General Public License v3.0 5 votes vote down vote up
def init():
    global _ENFORCER
    global saved_file_rules

    if not _ENFORCER:
        _ENFORCER = policy.Enforcer(CONF)
        register_rules(_ENFORCER)
        _ENFORCER.load_rules() 
Example #18
Source File: base.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(PolicyBaseTestCase, self).setUp()
        self.conf = self.useFixture(config.Config()).conf
        self.config_dir = self.useFixture(fixtures.TempDir()).path
        self.conf(args=['--config-dir', self.config_dir])
        self.enforcer = policy.Enforcer(self.conf)
        self.addCleanup(self.enforcer.clear) 
Example #19
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_enforcer_with_default_rule(self):
        rules_json = jsonutils.dumps({
            "deny_stack_user": "not role:stack_user",
            "cloudwatch:PutMetricData": ""
        })
        rules = policy.Rules.load(rules_json)
        default_rule = _checks.TrueCheck()
        enforcer = policy.Enforcer(self.conf, default_rule=default_rule)
        enforcer.set_rules(rules)
        action = 'cloudwatch:PutMetricData'
        creds = {'roles': ''}
        self.assertTrue(enforcer.enforce(action, {}, creds)) 
Example #20
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_enforcer_with_default_policy_file(self):
        enforcer = policy.Enforcer(self.conf)
        self.assertEqual(self.conf.oslo_policy.policy_file,
                         enforcer.policy_file) 
Example #21
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_enforcer_with_policy_file(self):
        enforcer = policy.Enforcer(self.conf, policy_file='non-default.json')
        self.assertEqual('non-default.json', enforcer.policy_file) 
Example #22
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 #23
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_deprecate_a_policy_check_string(self):
        deprecated_rule = policy.DeprecatedRule(
            name='foo:create_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'
        )]
        enforcer = policy.Enforcer(self.conf)
        enforcer.register_defaults(rule_list)
        expected_msg = (
            'Policy "foo:create_bar":"role:fizz" was deprecated in N in favor '
            'of "foo:create_bar":"role:bang". Reason: "role:bang" is a better '
            'default. Either ensure your deployment is ready for the new '
            'default or copy/paste the deprecated policy into your policy '
            'file and maintain it manually.'
        )

        with mock.patch('warnings.warn') as mock_warn:
            enforcer.load_rules()
            mock_warn.assert_called_once_with(expected_msg)

        self.assertTrue(
            enforcer.enforce('foo:create_bar', {}, {'roles': ['bang']})
        )
        self.assertTrue(
            enforcer.enforce('foo:create_bar', {}, {'roles': ['fizz']})
        )
        self.assertFalse(
            enforcer.enforce('foo:create_bar', {}, {'roles': ['baz']})
        ) 
Example #24
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_deprecate_an_empty_policy_check_string(self):
        deprecated_rule = policy.DeprecatedRule(
            name='foo:create_bar',
            check_str=''
        )

        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='because of reasons',
            deprecated_since='N'
        )]
        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()

        enforcer.enforce('foo:create_bar', {}, {'roles': ['bang']},
                         do_raise=True)
        enforcer.enforce('foo:create_bar', {}, {'roles': ['fizz']},
                         do_raise=True) 
Example #25
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_deprecate_replace_with_empty_policy_check_string(self):
        deprecated_rule = policy.DeprecatedRule(
            name='foo:create_bar',
            check_str='role:fizz'
        )

        rule_list = [policy.DocumentedRuleDefault(
            name='foo:create_bar',
            check_str='',
            description='Create a bar.',
            operations=[{'path': '/v1/bars', 'method': 'POST'}],
            deprecated_rule=deprecated_rule,
            deprecated_reason='because of reasons',
            deprecated_since='N'
        )]
        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()

        enforcer.enforce('foo:create_bar', {}, {'roles': ['fizz']},
                         do_raise=True)
        enforcer.enforce('foo:create_bar', {}, {'roles': ['bang']},
                         do_raise=True) 
Example #26
Source File: policy_engine.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def init(policy_file=None, rules=None, default_rule=None, use_conf=True):
    """Init an Enforcer class.

       :param policy_file: Custom policy file to use, if none is specified,
                           `CONF.policy_file` will be used.
       :param rules: Default dictionary / Rules to use. It will be
                     considered just in the first instantiation.
       :param default_rule: Default rule to use, CONF.default_rule will
                            be used if none is specified.
       :param use_conf: Whether to load rules from config file.
    """

    global _ENFORCER
    global saved_file_rules

    if not _ENFORCER:
        _ENFORCER = policy.Enforcer(CONF,
                                    policy_file=policy_file,
                                    rules=rules,
                                    default_rule=default_rule,
                                    use_conf=use_conf
                                    )
        register_rules(_ENFORCER)
        _ENFORCER.load_rules()
    # Only the rules which are loaded from file may be changed
    current_file_rules = _ENFORCER.file_rules
    current_file_rules = _serialize_rules(current_file_rules)

    if saved_file_rules != current_file_rules:
        _warning_for_deprecated_user_based_rules(current_file_rules)
        saved_file_rules = copy.deepcopy(current_file_rules) 
Example #27
Source File: access_control.py    From qinling with Apache License 2.0 5 votes vote down vote up
def _ensure_enforcer_initialization():
    global _ENFORCER
    if not _ENFORCER:
        _ENFORCER = policy.Enforcer(cfg.CONF)
        _ENFORCER.load_rules() 
Example #28
Source File: hooks.py    From aodh with Apache License 2.0 5 votes vote down vote up
def __init__(self, conf):
        self.conf = conf
        self.enforcer = policy.Enforcer(conf, default_rule="default")
        self.enforcer.register_defaults(policies.list_rules()) 
Example #29
Source File: test_policy.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def test_enforce_new_defaults_no_old_check_string(self):
        self.conf.set_override('enforce_new_defaults', True,
                               group='oslo_policy')
        deprecated_rule = policy.DeprecatedRule(
            name='foo:create_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'
        )]
        enforcer = policy.Enforcer(self.conf)
        enforcer.register_defaults(rule_list)

        with mock.patch('warnings.warn') as mock_warn:
            enforcer.load_rules()
            mock_warn.assert_not_called()
        self.assertTrue(
            enforcer.enforce('foo:create_bar', {}, {'roles': ['bang']})
        )
        self.assertFalse(
            enforcer.enforce('foo:create_bar', {}, {'roles': ['fizz']})
        )
        self.assertFalse(
            enforcer.enforce('foo:create_bar', {}, {'roles': ['baz']})
        ) 
Example #30
Source File: test_generator.py    From oslo.policy with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(GenerateSampleJSONTestCase, self).setUp()
        self.enforcer = policy.Enforcer(self.conf, policy_file='policy.json')