当前位置: 首页>>代码示例>>Python>>正文


Python policy.PolicyNotAuthorized方法代码示例

本文整理汇总了Python中oslo_policy.policy.PolicyNotAuthorized方法的典型用法代码示例。如果您正苦于以下问题:Python policy.PolicyNotAuthorized方法的具体用法?Python policy.PolicyNotAuthorized怎么用?Python policy.PolicyNotAuthorized使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在oslo_policy.policy的用法示例。


在下文中一共展示了policy.PolicyNotAuthorized方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: authorize

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def authorize(context, action, target, do_raise=True, exc=None):

    init()
    credentials = context.to_policy_values()
    if not exc:
        exc = exceptions.PolicyNotAuthorized
    try:
        result = _ENFORCER.authorize(action, target, credentials,
                                     do_raise=do_raise, exc=exc, action=action)
    except policy.PolicyNotRegistered:
        with excutils.save_and_reraise_exception():
            LOG.debug('Policy not registered')
    except Exception:
        with excutils.save_and_reraise_exception():
            LOG.debug('Policy check for %(action)s failed with credentials '
                      '%(credentials)s',
                      {'action': action, 'credentials': credentials})

    return result 
开发者ID:openstack,项目名称:tacker,代码行数:21,代码来源:policy.py

示例2: test_modified_policy_reloads

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
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) 
开发者ID:openstack,项目名称:monasca-api,代码行数:25,代码来源:test_policy.py

示例3: test_modified_policy_reloads

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
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) 
开发者ID:openstack,项目名称:monasca-api,代码行数:23,代码来源:test_policy.py

示例4: authorize

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
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 
开发者ID:openstack,项目名称:cyborg,代码行数:18,代码来源:policy.py

示例5: generate_safe_exception_message

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def generate_safe_exception_message(operation_name, excep):
    """Generates an exception message that is 'safe' for clients to consume.

    A 'safe' message is one that doesn't contain sensitive information that
    could be used for (say) cryptographic attacks on Barbican. That generally
    means that em.CryptoXxxx should be captured here and with a simple
    message created on behalf of them.

    :param operation_name: Name of attempted operation, with a 'Verb noun'
                           format (e.g. 'Create Secret).
    :param excep: The Exception instance that halted the operation.
    :return: (status, message) where 'status' is one of the webob.exc.HTTP_xxx
                               codes, and 'message' is the sanitized message
                               associated with the error.
    """
    message = None
    reason = None
    status = 500

    try:
        raise excep
    except policy.PolicyNotAuthorized:
        message = u._(
            '{operation} attempt not allowed - '
            'please review your '
            'user/project privileges').format(operation=operation_name)
        status = 403

    except exception.BarbicanHTTPException as http_exception:
        reason = http_exception.client_message
        status = http_exception.status_code
    except Exception:
        message = u._('{operation} failure seen - please contact site '
                      'administrator.').format(operation=operation_name)

    if reason:
        message = u._('{operation} issue seen - {reason}.').format(
            operation=operation_name, reason=reason)

    return status, message 
开发者ID:cloud-security-research,项目名称:sgx-kms,代码行数:42,代码来源:__init__.py

示例6: convert_exception_to_http_exc

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def convert_exception_to_http_exc(e, faults, language):
    serializer = wsgi.JSONDictSerializer()
    e = translate(e, language)
    body = serializer.serialize(
        {'TackerError': get_exception_data(e)})
    kwargs = {'body': body, 'content_type': 'application/json'}
    if isinstance(e, exc.HTTPException):
        # already an HTTP error, just update with content type and body
        e.body = body
        e.content_type = kwargs['content_type']
        return e
    if isinstance(e, (exceptions.TackerException, netaddr.AddrFormatError,
                      oslo_policy.PolicyNotAuthorized)):
        for fault in faults:
            if isinstance(e, fault):
                mapped_exc = faults[fault]
                break
        else:
            mapped_exc = exc.HTTPInternalServerError
        return mapped_exc(**kwargs)
    if isinstance(e, NotImplementedError):
        # NOTE(armando-migliaccio): from a client standpoint
        # it makes sense to receive these errors, because
        # extensions may or may not be implemented by
        # the underlying plugin. So if something goes south,
        # because a plugin does not implement a feature,
        # returning 500 is definitely confusing.
        kwargs['body'] = serializer.serialize(
            {'NotImplementedError': get_exception_data(e)})
        return exc.HTTPNotImplemented(**kwargs)
    # NOTE(jkoelker) Everything else is 500
    # Do not expose details of 500 error to clients.
    msg = _('Request Failed: internal server error while '
            'processing your request.')
    msg = translate(msg, language)
    kwargs['body'] = serializer.serialize(
        {'TackerError': get_exception_data(exc.HTTPInternalServerError(msg))})
    return exc.HTTPInternalServerError(**kwargs) 
开发者ID:openstack,项目名称:tacker,代码行数:40,代码来源:api_common.py

示例7: enforce

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def enforce(context, action, target, plugin=None, pluralized=None):
    """Verifies that the action is valid on the target in this context.

    :param context: tacker context
    :param action: string representing the action to be checked
        this should be colon separated for clarity.
    :param target: dictionary representing the object of the action
        for object creation this should be a dictionary representing the
        location of the object e.g. ``{'project_id': context.project_id}``
    :param plugin: currently unused and deprecated.
        Kept for backward compatibility.
    :param pluralized: pluralized case of resource
        e.g. firewall_policy -> pluralized = "firewall_policies"

    :raises oslo_policy.policy.PolicyNotAuthorized:
            if verification fails.
    """
    # If we already know the context has admin rights do not perform an
    # additional check and authorize the operation
    if context.is_admin:
        return True
    rule, target, credentials = _prepare_check(context,
                                               action,
                                               target,
                                               pluralized)
    try:
        result = _ENFORCER.enforce(rule, target, credentials, action=action,
                                   do_raise=True)
    except policy.PolicyNotAuthorized:
        with excutils.save_and_reraise_exception():
            log_rule_list(rule)
            LOG.debug("Failed policy check for '%s'", action)
    return result 
开发者ID:openstack,项目名称:tacker,代码行数:35,代码来源:policy.py

示例8: test_policy_not_authorized_exception

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_policy_not_authorized_exception(self):
        req = wsgi_resource.Request({})
        language = req.best_match_language()
        e = oslo_policy.PolicyNotAuthorized(None, None, None)
        result = common.convert_exception_to_http_exc(e, {}, language)

        except_res = {'message': 'None is disallowed by policy',
                      'type': 'PolicyNotAuthorized',
                      'detail': ''}

        self.assertEqual(
            except_res, jsonutils.loads(result.body)["TackerError"])
        self.assertEqual(500, result.code) 
开发者ID:openstack,项目名称:tacker,代码行数:15,代码来源:test_api_common.py

示例9: handle_exceptions

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def handle_exceptions(operation_name=u._('System')):
    """Decorator handling generic exceptions from REST methods."""

    def exceptions_decorator(fn):

        def handler(inst, *args, **kwargs):
            try:
                return fn(inst, *args, **kwargs)
            except exc.HTTPError:
                LOG.exception('Webob error seen')
                raise  # Already converted to Webob exception, just reraise
            # In case PolicyNotAuthorized, we do not want to expose payload by
            # logging exception, so just LOG.error
            except policy.PolicyNotAuthorized as pna:
                status, message = api.generate_safe_exception_message(
                    operation_name, pna)
                LOG.error(message)
                pecan.abort(status, message)
            except Exception as e:
                # In case intervening modules have disabled logging.
                LOG.logger.disabled = False

                status, message = api.generate_safe_exception_message(
                    operation_name, e)
                LOG.exception(message)
                pecan.abort(status, message)

        return handler

    return exceptions_decorator 
开发者ID:openstack,项目名称:barbican,代码行数:32,代码来源:__init__.py

示例10: test_authorize_bad_action_throws

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_authorize_bad_action_throws(self):
        action = 'example:denied'
        self.assertRaises(os_policy.PolicyNotAuthorized, policy_engine.authorize,
                          self.context, action, self.target) 
开发者ID:openstack,项目名称:monasca-api,代码行数:6,代码来源:test_policy.py

示例11: test_authorize_http_false

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_authorize_http_false(self, req_mock):
        req_mock.post('http://www.example.com/',
                      text='False')
        action = "example:get_http"
        target = {}
        self.assertRaises(os_policy.PolicyNotAuthorized, policy_engine.authorize,
                          self.context, action, target) 
开发者ID:openstack,项目名称:monasca-api,代码行数:9,代码来源:test_policy.py

示例12: test_templatized_authorization

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_templatized_authorization(self):
        target_mine = {'project_id': 'fake'}
        target_not_mine = {'project_id': 'another'}
        action = "example:my_file"
        policy_engine.authorize(self.context, action, target_mine)
        self.assertRaises(os_policy.PolicyNotAuthorized, policy_engine.authorize,
                          self.context, action, target_not_mine) 
开发者ID:openstack,项目名称:monasca-api,代码行数:9,代码来源:test_policy.py

示例13: test_early_AND_authorization

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_early_AND_authorization(self):
        action = "example:early_and_fail"
        self.assertRaises(os_policy.PolicyNotAuthorized, policy_engine.authorize,
                          self.context, action, self.target) 
开发者ID:openstack,项目名称:monasca-api,代码行数:6,代码来源:test_policy.py

示例14: test_authorize_bad_action_throws

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_authorize_bad_action_throws(self):
        action = "example:denied"
        ctx = request.Request(
            testing.create_environ(
                path="/",
                headers={
                    "X_USER_ID": "fake",
                    "X_PROJECT_ID": "fake",
                    "X_ROLES": "member"
                }
            )
        )
        self.assertRaises(os_policy.PolicyNotAuthorized, policy.authorize,
                          ctx.context, action, {}) 
开发者ID:openstack,项目名称:monasca-api,代码行数:16,代码来源:test_policy.py

示例15: test_check_raise_default

# 需要导入模块: from oslo_policy import policy [as 别名]
# 或者: from oslo_policy.policy import PolicyNotAuthorized [as 别名]
def test_check_raise_default(self):
        # When do_raise=True and exc is not used then PolicyNotAuthorized is
        # raised.
        self.enforcer.set_rules(dict(default=_checks.FalseCheck()))

        creds = {}
        self.assertRaisesRegex(policy.PolicyNotAuthorized,
                               " is disallowed by policy",
                               self.enforcer.enforce,
                               'rule', 'target', creds, True) 
开发者ID:openstack,项目名称:oslo.policy,代码行数:12,代码来源:test_policy.py


注:本文中的oslo_policy.policy.PolicyNotAuthorized方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。