Skip to content

Commit 2c28c23

Browse files
fix(terraform): Fix keeping range a range (#7073)
* Test quick fix * Add range exception * Negative only * Update checkov/terraform/graph_builder/variable_rendering/safe_eval_functions.py Co-authored-by: Ofek Shimko <[email protected]> * fix indent --------- Co-authored-by: Ofek Shimko <[email protected]>
1 parent 56d5f51 commit 2c28c23

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

checkov/terraform/graph_builder/variable_rendering/safe_eval_functions.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from checkov.terraform.parser_functions import tonumber, FUNCTION_FAILED, create_map, tobool, tostring
1212

1313
TIME_DELTA_PATTERN = re.compile(r"(\d*\.*\d+)")
14+
RANGE_PATTERN = re.compile(r'^\d+-\d+$')
1415

1516
"""
1617
This file contains a custom implementation of the builtin `eval` function.
@@ -369,7 +370,11 @@ def evaluate(input_str: str) -> Any:
369370

370371
# Don't use str.replace to make sure we replace just the first occurrence
371372
input_str = f"{TRY_STR_REPLACEMENT}{input_str[3:]}"
372-
evaluated = eval(input_str, {"__builtins__": None}, SAFE_EVAL_DICT) # nosec
373+
if RANGE_PATTERN.match(input_str):
374+
temp_eval = eval(input_str, {"__builtins__": None}, SAFE_EVAL_DICT) # nosec
375+
evaluated = input_str if temp_eval < 0 else temp_eval
376+
else:
377+
evaluated = eval(input_str, {"__builtins__": None}, SAFE_EVAL_DICT) # nosec
373378
return evaluated if not isinstance(evaluated, str) else remove_unicode_null(evaluated)
374379

375380

tests/terraform/graph/variable_rendering/test_string_evaluation.py

+12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from checkov.terraform.graph_builder.variable_rendering.evaluate_terraform import evaluate_terraform, \
88
replace_string_value, \
99
remove_interpolation, _find_new_value_for_interpolation
10+
from checkov.terraform.graph_builder.variable_rendering.safe_eval_functions import evaluate
1011

1112

1213
class TestTerraformEvaluation(TestCase):
@@ -530,3 +531,14 @@ def test_try_then_merge_block(self):
530531
def test_find_new_value_for_interpolation(origin_str: str, str_to_replace: str, new_value: str, expected: str):
531532
actual = _find_new_value_for_interpolation(origin_str, str_to_replace, new_value)
532533
assert actual == expected
534+
535+
536+
def test_evaluate_range_pattern() -> None:
537+
538+
# Test range pattern
539+
assert evaluate("1-10") == "1-10"
540+
assert evaluate("5-25") == "5-25"
541+
assert evaluate("10-5") == 5
542+
543+
# Test non-range pattern for comparison
544+
assert evaluate("1+1") == 2

0 commit comments

Comments
 (0)