示例#1
0
 def evaluate(self, expression_source: str) -> PolicyResult:
     """Parse and evaluate expression. Policy is expected to return a truthy object.
     Messages can be added using 'do ak_message()'."""
     try:
         result = super().evaluate(expression_source)
     except PolicyException as exc:
         # PolicyExceptions should be propagated back to the process,
         # which handles recording and returning a correct result
         raise exc
     except Exception as exc:  # pylint: disable=broad-except
         LOGGER.warning("Expression error", exc=exc)
         return PolicyResult(False, str(exc))
     else:
         policy_result = PolicyResult(False, *self._messages)
         if result is None:
             LOGGER.warning(
                 "Expression policy returned None",
                 src=expression_source,
                 req=self._context,
             )
             policy_result.passing = False
         if result:
             policy_result.passing = bool(result)
         return policy_result
示例#2
0
 def execute(self) -> PolicyResult:
     """Run actual policy, returns result"""
     LOGGER.debug(
         "P_ENG(proc): Running policy",
         policy=self.binding.policy,
         user=self.request.user,
         process="PolicyProcess",
     )
     try:
         policy_result = self.binding.passes(self.request)
         if self.binding.policy and not self.request.debug:
             if self.binding.policy.execution_logging:
                 self.create_event(
                     EventAction.POLICY_EXECUTION,
                     message="Policy Execution",
                     result=policy_result,
                 )
     except PolicyException as exc:
         # Either use passed original exception or whatever we have
         src_exc = exc.src_exc if exc.src_exc else exc
         error_string = (TRACEBACK_HEADER +
                         "".join(format_tb(src_exc.__traceback__)) +
                         str(src_exc))
         # Create policy exception event, only when we're not debugging
         if not self.request.debug:
             self.create_event(EventAction.POLICY_EXCEPTION,
                               message=error_string)
         LOGGER.debug("P_ENG(proc): error", exc=src_exc)
         policy_result = PolicyResult(False, str(src_exc))
     policy_result.source_binding = self.binding
     # Invert result if policy.negate is set
     if self.binding.negate:
         policy_result.passing = not policy_result.passing
     if not self.request.debug:
         key = cache_key(self.binding, self.request)
         cache.set(key, policy_result)
     LOGGER.debug(
         "P_ENG(proc): finished and cached ",
         policy=self.binding.policy,
         result=policy_result,
         process="PolicyProcess",
         passing=policy_result.passing,
         user=self.request.user,
     )
     return policy_result