Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion asteval/astutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,38 @@ def safe_lshift(arg1, arg2):
return arg1 << arg2


# printf-style conversion specifier, used to bound %-formatting field sizes
_PERCENT_CONV = re.compile(r'%(?:\((?P<key>[^)]*)\))?'
r'(?P<flags>[#0\- +]*)'
r'(?P<width>\*|\d+)?'
r'(?:\.(?P<prec>\*|\d+))?'
r'[hlL]?'
r'(?P<type>[diouxXeEfFgGcrsa%])')


def safe_mod(arg1, arg2):
"""safe version of %, capping string %-formatting field sizes"""
if isinstance(arg1, str):
args = arg2 if isinstance(arg2, tuple) else (arg2,)
pos = 0
for match in _PERCENT_CONV.finditer(arg1):
if match.group('type') == '%':
continue
for field in (match.group('width'), match.group('prec')):
if field == '*':
value = args[pos] if pos < len(args) else None
pos += 1
elif field is not None:
value = int(field)
else:
value = None
if isinstance(value, int) and value > MAX_STR_LEN:
raise RuntimeError(f"String length exceeded, max string length is {MAX_STR_LEN}")
if match.group('key') is None:
pos += 1
return arg1 % arg2


OPERATORS = {ast.Is: lambda a, b: a is b,
ast.IsNot: lambda a, b: a is not b,
ast.In: lambda a, b: a in b,
Expand All @@ -265,7 +297,7 @@ def safe_lshift(arg1, arg2):
ast.Pow: safe_pow,
ast.MatMult: lambda a, b: a @ b,
ast.Sub: lambda a, b: a - b,
ast.Mod: lambda a, b: a % b,
ast.Mod: safe_mod,
ast.And: lambda a, b: a and b,
ast.Or: lambda a, b: a or b,
ast.Eq: lambda a, b: a == b,
Expand Down
8 changes: 8 additions & 0 deletions tests/test_asteval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1234,6 +1234,14 @@ def test_safe_funcs(nested):
check_error(interp, None)
interp("1<<1001")
check_error(interp, 'RuntimeError')
interp("'%5d' % 3")
check_error(interp, None)
interp("'%2000000d' % 0")
check_error(interp, 'RuntimeError')
interp("'%.2000000f' % 0.0")
check_error(interp, 'RuntimeError')
interp("'%*d' % (2000000, 0)")
check_error(interp, 'RuntimeError')

@pytest.mark.parametrize("nested", [False, True])
def test_safe__numpyfuncs(nested):
Expand Down