2020-02-19 08:49:38 +00:00
|
|
|
"""passbook expression policy evaluator"""
|
|
|
|
import re
|
2020-05-06 22:32:03 +00:00
|
|
|
from typing import TYPE_CHECKING, Any, Dict, Optional
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
from django.core.exceptions import ValidationError
|
2020-02-19 15:19:02 +00:00
|
|
|
from jinja2 import Undefined
|
2020-02-19 08:49:38 +00:00
|
|
|
from jinja2.exceptions import TemplateSyntaxError, UndefinedError
|
|
|
|
from jinja2.nativetypes import NativeEnvironment
|
|
|
|
from structlog import get_logger
|
|
|
|
|
2020-05-07 19:30:52 +00:00
|
|
|
from passbook.flows.view import AuthenticationView
|
2020-02-22 18:26:16 +00:00
|
|
|
from passbook.lib.utils.http import get_client_ip
|
2020-02-20 12:52:05 +00:00
|
|
|
from passbook.policies.types import PolicyRequest, PolicyResult
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
if TYPE_CHECKING:
|
2020-02-19 09:22:28 +00:00
|
|
|
from passbook.core.models import User
|
2020-02-19 08:49:38 +00:00
|
|
|
|
2020-02-19 15:19:02 +00:00
|
|
|
LOGGER = get_logger()
|
|
|
|
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
class Evaluator:
|
2020-02-23 14:54:26 +00:00
|
|
|
"""Validate and evaluate jinja2-based expressions"""
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
_env: NativeEnvironment
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._env = NativeEnvironment()
|
2020-02-19 09:22:28 +00:00
|
|
|
# update passbook/policies/expression/templates/policy/expression/form.html
|
|
|
|
# update docs/policies/expression/index.md
|
|
|
|
self._env.filters["regex_match"] = Evaluator.jinja2_filter_regex_match
|
|
|
|
self._env.filters["regex_replace"] = Evaluator.jinja2_filter_regex_replace
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2020-02-19 09:22:28 +00:00
|
|
|
def jinja2_filter_regex_match(value: Any, regex: str) -> bool:
|
2020-02-19 08:49:38 +00:00
|
|
|
"""Jinja2 Filter to run re.search"""
|
|
|
|
return re.search(regex, value) is None
|
|
|
|
|
|
|
|
@staticmethod
|
2020-02-19 09:22:28 +00:00
|
|
|
def jinja2_filter_regex_replace(value: Any, regex: str, repl: str) -> str:
|
2020-02-19 08:49:38 +00:00
|
|
|
"""Jinja2 Filter to run re.sub"""
|
|
|
|
return re.sub(regex, repl, value)
|
|
|
|
|
2020-02-19 09:22:28 +00:00
|
|
|
@staticmethod
|
|
|
|
def jinja2_func_is_group_member(user: "User", group_name: str) -> bool:
|
|
|
|
"""Check if `user` is member of group with name `group_name`"""
|
|
|
|
return user.groups.filter(name=group_name).exists()
|
|
|
|
|
2020-02-19 08:49:38 +00:00
|
|
|
def _get_expression_context(
|
|
|
|
self, request: PolicyRequest, **kwargs
|
|
|
|
) -> Dict[str, Any]:
|
|
|
|
"""Return dictionary with additional global variables passed to expression"""
|
2020-02-19 09:22:28 +00:00
|
|
|
# update passbook/policies/expression/templates/policy/expression/form.html
|
|
|
|
# update docs/policies/expression/index.md
|
|
|
|
kwargs["pb_is_group_member"] = Evaluator.jinja2_func_is_group_member
|
2020-02-19 08:49:38 +00:00
|
|
|
kwargs["pb_logger"] = get_logger()
|
2020-02-23 14:54:26 +00:00
|
|
|
if request.http_request:
|
|
|
|
kwargs["pb_is_sso_flow"] = request.http_request.session.get(
|
|
|
|
AuthenticationView.SESSION_IS_SSO_LOGIN, False
|
|
|
|
)
|
|
|
|
kwargs["pb_client_ip"] = (
|
|
|
|
get_client_ip(request.http_request) or "255.255.255.255"
|
|
|
|
)
|
2020-02-19 08:49:38 +00:00
|
|
|
return kwargs
|
|
|
|
|
|
|
|
def evaluate(self, expression_source: str, request: PolicyRequest) -> PolicyResult:
|
|
|
|
"""Parse and evaluate expression.
|
|
|
|
If the Expression evaluates to a list with 2 items, the first is used as passing bool and
|
|
|
|
the second as messages.
|
|
|
|
If the Expression evaluates to a truthy-object, it is used as passing bool."""
|
|
|
|
try:
|
|
|
|
expression = self._env.from_string(expression_source)
|
|
|
|
except TemplateSyntaxError as exc:
|
|
|
|
return PolicyResult(False, str(exc))
|
|
|
|
try:
|
2020-05-06 22:32:03 +00:00
|
|
|
result: Optional[Any] = expression.render(
|
2020-02-19 08:49:38 +00:00
|
|
|
request=request, **self._get_expression_context(request)
|
|
|
|
)
|
2020-02-19 15:19:02 +00:00
|
|
|
if isinstance(result, Undefined):
|
|
|
|
LOGGER.warning(
|
|
|
|
"Expression policy returned undefined",
|
|
|
|
src=expression_source,
|
|
|
|
req=request,
|
|
|
|
)
|
2020-02-20 12:51:41 +00:00
|
|
|
return PolicyResult(False)
|
2020-02-23 14:54:26 +00:00
|
|
|
if isinstance(result, (list, tuple)) and len(result) == 2:
|
2020-02-19 08:49:38 +00:00
|
|
|
return PolicyResult(*result)
|
|
|
|
if result:
|
|
|
|
return PolicyResult(result)
|
|
|
|
return PolicyResult(False)
|
|
|
|
except UndefinedError as exc:
|
|
|
|
return PolicyResult(False, str(exc))
|
|
|
|
|
|
|
|
def validate(self, expression: str):
|
|
|
|
"""Validate expression's syntax, raise ValidationError if Syntax is invalid"""
|
|
|
|
try:
|
|
|
|
self._env.from_string(expression)
|
|
|
|
return True
|
|
|
|
except TemplateSyntaxError as exc:
|
|
|
|
raise ValidationError("Expression Syntax Error") from exc
|