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é"