diff --git a/ddtrace/appsec/_iast/_taint_tracking/aspects.py b/ddtrace/appsec/_iast/_taint_tracking/aspects.py index 8b52878f275..fa2f512f81a 100644 --- a/ddtrace/appsec/_iast/_taint_tracking/aspects.py +++ b/ddtrace/appsec/_iast/_taint_tracking/aspects.py @@ -449,8 +449,8 @@ def format_value_aspect( return format(new_text, format_spec) return format(new_text) - try: - if format_spec: + if format_spec: + try: # Apply formatting text_ranges = get_tainted_ranges(new_text) if text_ranges: @@ -466,11 +466,11 @@ def format_value_aspect( return ("{:%s}" % format_spec).format(new_text) else: return ("{:%s}" % format_spec).format(new_text) - else: - return format(new_text) - except Exception as e: - iast_propagation_error_log(f"format_value_aspect. {e}") - return new_text + except Exception as e: + iast_propagation_error_log(f"format_value_aspect. {e}") + return ("{:%s}" % format_spec).format(new_text) + + return format(new_text) def incremental_translation(self, incr_coder, funcode, empty): diff --git a/releasenotes/notes/iast-fstring-exception-d460a37b6e44f972.yaml b/releasenotes/notes/iast-fstring-exception-d460a37b6e44f972.yaml new file mode 100644 index 00000000000..a22008a34ca --- /dev/null +++ b/releasenotes/notes/iast-fstring-exception-d460a37b6e44f972.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + IAST: Fixes a bug where invalid f-strings didn’t raise the expected "Unknown format code" error when IAST was enabled. diff --git a/tests/appsec/iast/aspects/test_str_py3.py b/tests/appsec/iast/aspects/test_str_py3.py index ba468c34286..b4a4291ea8d 100644 --- a/tests/appsec/iast/aspects/test_str_py3.py +++ b/tests/appsec/iast/aspects/test_str_py3.py @@ -1,3 +1,5 @@ +from hypothesis import given +from hypothesis.strategies import text import pytest from ddtrace.appsec._iast._taint_tracking import as_formatted_evidence @@ -10,6 +12,17 @@ mod_py3 = _iast_patched_module("benchmarks.bm.iast_fixtures.str_methods_py3") +@given(text()) +def test_int_fstring_zero_padding_text(text): + with pytest.raises(ValueError) as excinfo: + f"{text:05d}" + assert str(excinfo.value) == "Unknown format code 'd' for object of type 'str'" + + with pytest.raises(ValueError) as excinfo: + mod_py3.do_zero_padding_fstring(text) + assert str(excinfo.value) == "Unknown format code 'd' for object of type 'str'" + + class TestOperatorsReplacement(BaseReplacement): @staticmethod def test_taint(): # type: () -> None