The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): add regression tests for #20441 - <script> tags in messages (#20573)
Varun Chawlae587370f671a
diff --git a/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.py b/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.pyindex 324a58acfa9..af366b082a0 100644--- a/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.py+++ b/tests/test_litellm/proxy/common_utils/test_http_parsing_utils.py@@ -697,3 +697,67 @@ def test_populate_request_with_path_params_does_not_overwrite_existing_values():assert result["organization_id"] == "org-existing" # Should keep original, not "org-query-param"# Verify other data is preservedassert result["messages"] == [{"role": "user", "content": "Hello"}]+++async def test_request_body_with_html_script_tags():+ """+ Test that JSON request bodies containing HTML tags like <script> are+ parsed correctly without being blocked or modified.++ Regression test for GitHub issue #20441:+ https://github.com/BerriAI/litellm/issues/20441++ LLM message content frequently contains HTML/code snippets.+ The HTTP parsing layer must not interfere with such content.+ """+ test_messages = [+ {+ "role": "user",+ "content": "<script>alert('hello')</script>",+ },+ {+ "role": "user",+ "content": "<script> test </script>",+ },+ {+ "role": "user",+ "content": "Can you explain what <script> tags do in HTML?",+ },+ {+ "role": "user",+ "content": "Here is code: <div><script src='app.js'></script></div>",+ },+ {+ "role": "user",+ "content": "<img onerror='alert(1)' src='x'>",+ },+ {+ "role": "user",+ "content": "<iframe src='https://example.com'></iframe>",+ },+ ]++ for msg in test_messages:+ test_payload = {+ "model": "gpt-4o",+ "messages": [+ {"role": "user", "content": "hi"},+ {"role": "assistant", "content": "Hello! How can I help?"},+ msg,+ ],+ }++ mock_request = MagicMock()+ mock_request.body = AsyncMock(return_value=orjson.dumps(test_payload))+ mock_request.headers = {"content-type": "application/json"}+ mock_request.scope = {}++ result = await _read_request_body(mock_request)++ assert result["model"] == "gpt-4o"+ assert len(result["messages"]) == 3+ assert result["messages"][2]["content"] == msg["content"], (+ f"Message content with HTML was modified during parsing: "+ f"expected={msg['content']!r}, got={result['messages'][2]['content']!r}"+ )diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.pyindex d886a4da76b..a0d92a0fa6f 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/content_filter/test_content_filter.py@@ -986,3 +986,146 @@ class TestContentFilterGuardrail:assert detail.get("category") == "harm_toxic_abuse"else:assert "harm_toxic_abuse" in str(detail)+ async def test_html_tags_in_messages_not_blocked(self):+ """+ Test that HTML tags like <script> in LLM message content are NOT blocked+ by the content filter guardrail.++ Regression test for GitHub issue #20441:+ https://github.com/BerriAI/litellm/issues/20441++ LLM message content is not rendered as HTML, so HTML tags should be+ treated as plain text and should pass through without being blocked.+ """+ # Set up a guardrail with all prebuilt patterns enabled as BLOCK+ patterns = [+ ContentFilterPattern(+ pattern_type="prebuilt",+ pattern_name="us_ssn",+ action=ContentFilterAction.BLOCK,+ ),+ ContentFilterPattern(+ pattern_type="prebuilt",+ pattern_name="email",+ action=ContentFilterAction.BLOCK,+ ),+ ContentFilterPattern(+ pattern_type="prebuilt",+ pattern_name="credit_card",+ action=ContentFilterAction.BLOCK,+ ),+ ]++ guardrail = ContentFilterGuardrail(+ guardrail_name="test-html-tags",+ patterns=patterns,+ )++ # Messages containing <script> and other HTML tags should NOT be blocked+ html_messages = [+ "<script>alert('hello')</script>",+ "<script> test </script>",+ "Can you explain what <script> tags do in HTML?",+ "Here is some code: <div><script src='app.js'></script></div>",+ "<img onerror='alert(1)' src='x'>",+ "<iframe src='https://example.com'></iframe>",+ "The <style> and <script> elements are important in HTML",+ "<a href='javascript:void(0)'>click me</a>",+ ]++ for message in html_messages:+ # Should NOT raise HTTPException+ result = await guardrail.apply_guardrail(+ inputs={"texts": [message]},+ request_data={},+ input_type="request",+ )+ processed_texts = result.get("texts", [])+ assert len(processed_texts) == 1+ # Content should pass through unchanged (no HTML tags are patterns)+ assert processed_texts[0] == message, (+ f"Message containing HTML was unexpectedly modified: "+ f"input={message!r}, output={processed_texts[0]!r}"+ )++ @pytest.mark.asyncio+ async def test_script_tag_not_blocked_with_blocked_words(self):+ """+ Test that <script> tags are not accidentally caught by blocked words+ unless explicitly configured.++ Regression test for GitHub issue #20441.+ """+ blocked_words = [+ BlockedWord(+ keyword="confidential",+ action=ContentFilterAction.BLOCK,+ ),+ BlockedWord(+ keyword="secret_project",+ action=ContentFilterAction.BLOCK,+ ),+ ]++ guardrail = ContentFilterGuardrail(+ guardrail_name="test-script-not-blocked",+ blocked_words=blocked_words,+ )++ # <script> should not be caught by unrelated blocked words+ script_messages = [+ "<script>alert('test')</script>",+ "How do I use <script> tags in HTML?",+ "<script src='app.js'></script>",+ ]++ for message in script_messages:+ result = await guardrail.apply_guardrail(+ inputs={"texts": [message]},+ request_data={},+ input_type="request",+ )+ processed_texts = result.get("texts", [])+ assert len(processed_texts) == 1+ assert processed_texts[0] == message++ def test_no_builtin_pattern_matches_script_tag(self):+ """+ Test that NONE of the prebuilt patterns in patterns.json match+ the string '<script>' or common HTML tags.++ This is a safeguard to ensure that future pattern additions+ do not accidentally block legitimate LLM content containing+ HTML/code snippets.++ Regression test for GitHub issue #20441.+ """+ from litellm.proxy.guardrails.guardrail_hooks.litellm_content_filter.patterns import (+ PREBUILT_PATTERNS,+ get_compiled_pattern,+ )++ html_test_strings = [+ "<script>alert('xss')</script>",+ "<script> test </script>",+ "<script src='app.js'></script>",+ "<img onerror='alert(1)' src='x'>",+ "<iframe src='https://example.com'></iframe>",+ "<style>body { color: red; }</style>",+ "<div onclick='alert(1)'>click</div>",+ ]++ for pattern_name in PREBUILT_PATTERNS:+ compiled = get_compiled_pattern(pattern_name)+ for test_string in html_test_strings:+ match = compiled.search(test_string)+ if match:+ # Some patterns may legitimately match substrings+ # (e.g., URL pattern matching src='https://...')+ # but they should not match the script/HTML tag itself+ matched_text = match.group()+ assert "<script" not in matched_text.lower(), (+ f"Pattern '{pattern_name}' matched '<script>' in "+ f"test string: {test_string!r}. "+ f"LLM message content should not be blocked for HTML tags."+ )