policies/expression: Return False if Policy returns Undefined and log warning

This commit is contained in:
Jens Langhammer 2020-02-19 16:19:02 +01:00
parent ac273aab75
commit 995615d0a0
1 changed files with 10 additions and 0 deletions

View File

@ -3,6 +3,7 @@ import re
from typing import TYPE_CHECKING, Any, Dict from typing import TYPE_CHECKING, Any, Dict
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from jinja2 import Undefined
from jinja2.exceptions import TemplateSyntaxError, UndefinedError from jinja2.exceptions import TemplateSyntaxError, UndefinedError
from jinja2.nativetypes import NativeEnvironment from jinja2.nativetypes import NativeEnvironment
from structlog import get_logger from structlog import get_logger
@ -13,6 +14,8 @@ from passbook.policies.struct import PolicyRequest, PolicyResult
if TYPE_CHECKING: if TYPE_CHECKING:
from passbook.core.models import User from passbook.core.models import User
LOGGER = get_logger()
class Evaluator: class Evaluator:
"""Validate and evaulate jinja2-based expressions""" """Validate and evaulate jinja2-based expressions"""
@ -67,6 +70,13 @@ class Evaluator:
result = expression.render( result = expression.render(
request=request, **self._get_expression_context(request) request=request, **self._get_expression_context(request)
) )
if isinstance(result, Undefined):
LOGGER.warning(
"Expression policy returned undefined",
src=expression_source,
req=request,
)
return PolicyRequest(False)
if isinstance(result, list) and len(result) == 2: if isinstance(result, list) and len(result) == 2:
return PolicyResult(*result) return PolicyResult(*result)
if result: if result: