From 56787fb29c9bec377d3482f3d5157a05a92735bd Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Thu, 21 Oct 2021 17:50:52 +0200 Subject: [PATCH 1/3] utils/evaluate: allow some calls in expressions (#58055) --- src/authentic2/utils/evaluate.py | 16 +++++++++++++++- tests/test_utils_evaluate.py | 4 ++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/authentic2/utils/evaluate.py b/src/authentic2/utils/evaluate.py index cc03acfd..065667aa 100644 --- a/src/authentic2/utils/evaluate.py +++ b/src/authentic2/utils/evaluate.py @@ -146,6 +146,7 @@ class ConditionValidator(BaseExpressionValidator): - if expressions (x if y else z), - compare expressions with all operators. - subscript of direct variable reference. + - calls to simple names with simple literal or variable values Are implicitely forbidden: - binary expressions (so no "'aaa' * 99999999999" or 233333333333333233**2232323233232323 bombs), @@ -154,7 +155,7 @@ class ConditionValidator(BaseExpressionValidator): - comprehensions (list, dict and set), - generators, - yield, - - call, + - others calls, - Repr node (i dunno what it is), - attribute access, """ @@ -172,6 +173,7 @@ class ConditionValidator(BaseExpressionValidator): ast.boolop, ast.cmpop, ast.Compare, + ast.Call, ] def __init__(self, authorized_nodes=None, forbidden_nodes=None): @@ -182,6 +184,18 @@ class ConditionValidator(BaseExpressionValidator): if node.id.startswith('_'): raise ExpressionError(_('name must not start with a _'), code='invalid-variable', node=node) + def check_Call(self, node): + if isinstance(node.func, ast.Name) and all(self.validate_call_arg(arg) for arg in node.args): + return + raise ExpressionError(_('call is invalid'), code='invalid-call', node=node) + + def validate_call_arg(self, node): + # check node is constant or string + return self.is_constant(node) or isinstance(node, ast.Name) + + def is_constant(self, node): + return isinstance(node, CONSTANT_CLASSES) + def check_Subscript(self, node): # check subscript are constant number or strings ok = True diff --git a/tests/test_utils_evaluate.py b/tests/test_utils_evaluate.py index e6b9e1bc..a79068df 100644 --- a/tests/test_utils_evaluate.py +++ b/tests/test_utils_evaluate.py @@ -72,6 +72,10 @@ def test_condition_validator(): with pytest.raises(ExpressionError, match='MUST be a constant'): v('headers[headers]') + assert v('func(a, b, 1, \'x\')') + with pytest.raises(ExpressionError): + assert v('func(a[0], b(c), 1, \'x\')') + def test_evaluate_condition(rf): assert evaluate_condition('False') is False -- 2.33.0