2020-02-19 08:49:38 +00:00
|
|
|
"""passbook expression policy evaluator"""
|
|
|
|
import re
|
2020-06-01 17:07:10 +00:00
|
|
|
from typing import Any, Dict, List, Optional
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
from django.core.exceptions import ValidationError
|
2020-06-01 13:25:38 +00:00
|
|
|
from django.http import HttpRequest
|
2020-02-19 15:19:02 +00:00
|
|
|
from jinja2 import Undefined
|
2020-05-28 19:45:54 +00:00
|
|
|
from jinja2.exceptions import TemplateSyntaxError
|
2020-02-19 08:49:38 +00:00
|
|
|
from jinja2.nativetypes import NativeEnvironment
|
2020-05-15 10:02:41 +00:00
|
|
|
from requests import Session
|
2020-02-19 08:49:38 +00:00
|
|
|
from structlog import get_logger
|
|
|
|
|
2020-06-01 17:07:10 +00:00
|
|
|
from passbook.core.models import User
|
2020-05-08 14:10:27 +00:00
|
|
|
from passbook.flows.planner import PLAN_CONTEXT_SSO
|
2020-05-13 16:44:36 +00:00
|
|
|
from passbook.flows.views import SESSION_KEY_PLAN
|
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
|
|
|
|
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
|
|
|
|
|
2020-06-01 13:25:38 +00:00
|
|
|
_context: Dict[str, Any]
|
|
|
|
_messages: List[str]
|
|
|
|
|
2020-02-19 08:49:38 +00:00
|
|
|
def __init__(self):
|
2020-06-01 13:25:38 +00:00
|
|
|
self._env = NativeEnvironment(
|
2020-06-02 13:20:02 +00:00
|
|
|
extensions=["jinja2.ext.do"],
|
2020-06-01 13:25:38 +00:00
|
|
|
trim_blocks=True,
|
|
|
|
lstrip_blocks=True,
|
|
|
|
line_statement_prefix=">",
|
|
|
|
)
|
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-06-01 13:25:38 +00:00
|
|
|
self._env.globals["pb_message"] = self.jinja2_func_message
|
|
|
|
self._context = {
|
|
|
|
"pb_is_group_member": Evaluator.jinja2_func_is_group_member,
|
2020-06-01 17:07:10 +00:00
|
|
|
"pb_user_by": Evaluator.jinja2_func_user_by,
|
2020-06-01 13:25:38 +00:00
|
|
|
"pb_logger": get_logger(),
|
|
|
|
"requests": Session(),
|
|
|
|
}
|
|
|
|
self._messages = []
|
|
|
|
|
|
|
|
@property
|
|
|
|
def env(self) -> NativeEnvironment:
|
|
|
|
"""Access to our custom NativeEnvironment"""
|
|
|
|
return self._env
|
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
|
2020-06-01 17:07:10 +00:00
|
|
|
def jinja2_func_user_by(**filters) -> Optional[User]:
|
|
|
|
"""Get user by filters"""
|
|
|
|
users = User.objects.filter(**filters)
|
|
|
|
if users:
|
|
|
|
return users.first()
|
|
|
|
return None
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def jinja2_func_is_group_member(user: User, group_name: str) -> bool:
|
2020-02-19 09:22:28 +00:00
|
|
|
"""Check if `user` is member of group with name `group_name`"""
|
|
|
|
return user.groups.filter(name=group_name).exists()
|
|
|
|
|
2020-06-01 13:25:38 +00:00
|
|
|
def jinja2_func_message(self, message: str):
|
|
|
|
"""Wrapper to append to messages list, which is returned with PolicyResult"""
|
|
|
|
self._messages.append(message)
|
|
|
|
|
|
|
|
def set_policy_request(self, request: PolicyRequest):
|
|
|
|
"""Update context based on policy request (if http request is given, update that too)"""
|
2020-02-19 09:22:28 +00:00
|
|
|
# update passbook/policies/expression/templates/policy/expression/form.html
|
|
|
|
# update docs/policies/expression/index.md
|
2020-06-01 13:25:38 +00:00
|
|
|
self._context["pb_is_sso_flow"] = request.context.get(PLAN_CONTEXT_SSO, False)
|
|
|
|
self._context["request"] = request
|
2020-02-23 14:54:26 +00:00
|
|
|
if request.http_request:
|
2020-06-01 13:25:38 +00:00
|
|
|
self.set_http_request(request.http_request)
|
|
|
|
|
|
|
|
def set_http_request(self, request: HttpRequest):
|
|
|
|
"""Update context based on http request"""
|
|
|
|
# update passbook/policies/expression/templates/policy/expression/form.html
|
|
|
|
# update docs/policies/expression/index.md
|
|
|
|
self._context["pb_client_ip"] = (
|
|
|
|
get_client_ip(request.http_request) or "255.255.255.255"
|
|
|
|
)
|
|
|
|
self._context["request"] = request
|
|
|
|
if SESSION_KEY_PLAN in request.http_request.session:
|
|
|
|
self._context["pb_flow_plan"] = request.http_request.session[
|
|
|
|
SESSION_KEY_PLAN
|
|
|
|
]
|
|
|
|
|
|
|
|
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 pb_message()'."""
|
2020-02-19 08:49:38 +00:00
|
|
|
try:
|
2020-06-01 13:25:38 +00:00
|
|
|
expression = self._env.from_string(expression_source.lstrip().rstrip())
|
2020-02-19 08:49:38 +00:00
|
|
|
except TemplateSyntaxError as exc:
|
|
|
|
return PolicyResult(False, str(exc))
|
|
|
|
try:
|
2020-06-01 13:25:38 +00:00
|
|
|
result: Optional[Any] = expression.render(self._context)
|
|
|
|
except Exception as exc: # pylint: disable=broad-except
|
|
|
|
LOGGER.warning("Expression error", exc=exc)
|
|
|
|
return PolicyResult(False, str(exc))
|
|
|
|
else:
|
|
|
|
policy_result = PolicyResult(False)
|
|
|
|
policy_result.messages = tuple(self._messages)
|
2020-02-19 15:19:02 +00:00
|
|
|
if isinstance(result, Undefined):
|
|
|
|
LOGGER.warning(
|
|
|
|
"Expression policy returned undefined",
|
|
|
|
src=expression_source,
|
2020-06-01 13:25:38 +00:00
|
|
|
req=self._context,
|
2020-02-19 15:19:02 +00:00
|
|
|
)
|
2020-06-01 13:25:38 +00:00
|
|
|
policy_result.passing = False
|
2020-02-19 08:49:38 +00:00
|
|
|
if result:
|
2020-06-01 13:25:38 +00:00
|
|
|
policy_result.passing = bool(result)
|
|
|
|
return policy_result
|
2020-02-19 08:49:38 +00:00
|
|
|
|
|
|
|
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:
|
2020-06-01 17:07:10 +00:00
|
|
|
raise ValidationError(f"Expression Syntax Error: {str(exc)}") from exc
|