fix(http_spec): escape all JSON control characters in <<PROMPT>> 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.
This commit is contained in:
Aftabbs committed 2026-11-12 07:16:01 +05:30
1 parent 3ae108879e
commit dac5570397
2 files changed
+28 -10

No files matched your search

+4 -10
View File
@@ -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]
+24
View File
@@ -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é"