Python oslo_policy.policy.PolicyNotAuthorized() Examples
The following are 18
code examples of oslo_policy.policy.PolicyNotAuthorized().
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: policy.py From cyborg with Apache License 2.0 | 6 votes |
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 #2
Source File: policy.py From tacker with Apache License 2.0 | 6 votes |
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
Example #3
Source File: test_policy.py From monasca-log-api with Apache License 2.0 | 6 votes |
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 #4
Source File: test_policy.py From monasca-api with Apache License 2.0 | 6 votes |
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 #5
Source File: test_policy.py From monasca-api with Apache License 2.0 | 6 votes |
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 #6
Source File: test_policy.py From monasca-api with Apache License 2.0 | 5 votes |
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)
Example #7
Source File: test_policy.py From oslo.policy with Apache License 2.0 | 5 votes |
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)
Example #8
Source File: test_policy.py From monasca-log-api with Apache License 2.0 | 5 votes |
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, {})
Example #9
Source File: test_policy.py From monasca-api with Apache License 2.0 | 5 votes |
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, {})
Example #10
Source File: test_policy.py From monasca-api with Apache License 2.0 | 5 votes |
def test_early_AND_authorization(self): action = "example:early_and_fail" self.assertRaises(os_policy.PolicyNotAuthorized, policy_engine.authorize, self.context, action, self.target)
Example #11
Source File: test_policy.py From monasca-api with Apache License 2.0 | 5 votes |
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)
Example #12
Source File: __init__.py From sgx-kms with Apache License 2.0 | 5 votes |
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
Example #13
Source File: test_policy.py From monasca-api with Apache License 2.0 | 5 votes |
def test_authorize_bad_action_throws(self): action = 'example:denied' self.assertRaises(os_policy.PolicyNotAuthorized, policy_engine.authorize, self.context, action, self.target)
Example #14
Source File: __init__.py From barbican with Apache License 2.0 | 5 votes |
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
Example #15
Source File: __init__.py From barbican with Apache License 2.0 | 5 votes |
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
Example #16
Source File: test_api_common.py From tacker with Apache License 2.0 | 5 votes |
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)
Example #17
Source File: policy.py From tacker with Apache License 2.0 | 5 votes |
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
Example #18
Source File: api_common.py From tacker with Apache License 2.0 | 5 votes |
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)