From dac5570397a982b51033dc0567c89f73c273acee Mon Sep 17 00:00:00 2001 From: Aftabbs Date: Thu, 12 Nov 2026 07:16:01 +0530 Subject: [PATCH] fix(http_spec): escape all JSON control characters in <> substitution escape_special_chars_for_json only escaped backslash, quote, \n, \r and \t. Other control characters below U+0020 (backspace, form feed, ESC, NUL...) were inserted raw into the JSON request body, producing invalid JSON that targets reject, so attack prompts containing them were never evaluated. Delegate to json.dumps, which escapes every character JSON requires. --- agentic_security/http_spec.py | 14 ++++---------- tests/unit/test_spec.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/agentic_security/http_spec.py b/agentic_security/http_spec.py index d22147d..36bcb1e 100644 --- a/agentic_security/http_spec.py +++ b/agentic_security/http_spec.py @@ -258,13 +258,7 @@ def escape_special_chars_for_json(prompt: str) -> str: Returns: str: The escaped string. """ - # Escape backslashes first to avoid double escaping - escaped_prompt = prompt.replace("\\", "\\\\") - - # Escape other special characters - escaped_prompt = escaped_prompt.replace('"', '\\"') - escaped_prompt = escaped_prompt.replace("\n", "\\n") - escaped_prompt = escaped_prompt.replace("\r", "\\r") - escaped_prompt = escaped_prompt.replace("\t", "\\t") - - return escaped_prompt + # json.dumps escapes backslashes, quotes and every control character below + # U+0020 (backspace, form feed, ESC, NUL, ...), all of which JSON forbids + # unescaped. ensure_ascii=False keeps non-ASCII text readable in the body. + return json.dumps(prompt, ensure_ascii=False)[1:-1] diff --git a/tests/unit/test_spec.py b/tests/unit/test_spec.py index 7abca04..bc921c5 100644 --- a/tests/unit/test_spec.py +++ b/tests/unit/test_spec.py @@ -1,8 +1,11 @@ +import json + import pytest from agentic_security.http_spec import ( InvalidHTTPSpecError, LLMSpec, + escape_special_chars_for_json, parse_http_spec, ) @@ -87,3 +90,24 @@ class TestLLMSpec: ) with pytest.raises(ValueError, match="An image is required for this request."): spec.validate(prompt="", encoded_image="", encoded_audio="", files={}) + + +class TestEscapeSpecialCharsForJson: + @pytest.mark.parametrize( + "prompt", + [ + 'say "hi"', + "back\slash", + "line1\nline2\r\n\ttabbed", + "backspace\x08 formfeed\x0c", + "ansi \x1b[31mred\x1b[0m", + "nul\x00byte and unit separator\x1f", + "unicode café 日本語 \U0001f600", + ], + ) + def test_escaped_prompt_round_trips_through_json(self, prompt): + body = '{"prompt": "%s"}' % escape_special_chars_for_json(prompt) + assert json.loads(body)["prompt"] == prompt + + def test_keeps_non_ascii_text_unescaped(self): + assert escape_special_chars_for_json("café") == "café"