Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ if __name__ == "__main__":

- Uses `SandboxedEnvironment` from Jinja2 for safer rendering.
- Validates template paths to reduce traversal risk.
- Escapes string inputs before template rendering.
- Renders values as plain text, without HTML escaping; prompts go to the model, not a browser.

---

Expand Down
30 changes: 6 additions & 24 deletions servers/prompt/src/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

from jinja2 import Template
from jinja2.sandbox import SandboxedEnvironment
from markupsafe import escape

from typing import Any as PromptMessage
from ultrarag.server import UltraRAG_MCP_Server
Expand All @@ -24,8 +23,10 @@ def _prompt_text(message: Any) -> str:
text = content.get("text") if isinstance(content, dict) else content.text
return str(text)

# Create a sandboxed Jinja2 environment for security
_sandboxed_env = SandboxedEnvironment(autoescape=True)
# Prompts are plain text for the model, so values are not HTML-escaped: an
# escaped "What's" reaches the model as "What's". The sandbox guards the
# template source; values passed to render() are never parsed as templates.
_sandboxed_env = SandboxedEnvironment(autoescape=False)


def _validate_template_path(template_path: Union[str, Path]) -> Path:
Expand Down Expand Up @@ -83,27 +84,8 @@ def load_prompt_template(template_path: Union[str, Path]) -> Template:


def _safe_render(template: Template, **kwargs: Any) -> str:
"""Safely render a template with escaped user inputs.

Args:
template: Jinja2 Template object
**kwargs: Template variables (will be escaped if strings)

Returns:
Rendered template string
"""
# Escape all string inputs to prevent XSS and injection
safe_kwargs = {}
for key, value in kwargs.items():
if isinstance(value, str):
safe_kwargs[key] = escape(value)
elif isinstance(value, list):
# Escape string items in lists
safe_kwargs[key] = [escape(str(item)) if isinstance(item, str) else item for item in value]
else:
safe_kwargs[key] = value

return template.render(**safe_kwargs)
"""Render a sandboxed template with the values passed through unchanged."""
return template.render(**kwargs)


@app.prompt(output="q_ls,template->prompt_ls")
Expand Down
85 changes: 85 additions & 0 deletions tests/servers/prompt/test_prompt_rendering.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""Prompt values reach the model as plain text, not HTML."""

import importlib.util
from pathlib import Path
from types import ModuleType

import pytest
from jinja2.exceptions import SecurityError

from ultrarag.server import local_server_mode

ROOT = Path(__file__).resolve().parents[3]
TEMPLATES = ROOT / "prompt"

QUESTION = 'What does the "R&D" team\'s report say about x < y?'
PASSAGES = [
'The R&D team\'s report says x < y holds in "strict" mode.',
"Budgets > $5k need sign-off.",
]


@pytest.fixture(scope="module")
def prompt_server() -> ModuleType:
spec = importlib.util.spec_from_file_location(
"prompt_rendering_test", ROOT / "servers/prompt/src/prompt.py"
)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
with local_server_mode():
spec.loader.exec_module(module)
return module


def test_question_and_passages_are_rendered_verbatim(
prompt_server: ModuleType,
) -> None:
[prompt] = prompt_server.qa_rag_boxed(
[QUESTION], [PASSAGES], TEMPLATES / "qa_rag_boxed.jinja"
)
assert f"Question: {QUESTION}" in prompt
assert "\n".join(PASSAGES) in prompt


@pytest.mark.parametrize(
("tool", "init_template", "append_template", "answer"),
[
(
"search_r1_gen",
"search_r1_init.jinja",
"search_r1_append.jinja",
"<think>I need the report.</think>\n<search> R&D team's report on x < y",
),
(
"r1_searcher_gen",
"r1_searcher_init.jinja",
"r1_searcher_append.jinja",
"I need the report. <|begin_of_query|> R&D team's report on x < y",
),
],
ids=["search_r1", "r1_searcher"],
)
def test_each_turn_extends_the_history_unchanged(
prompt_server: ModuleType,
tool: str,
init_template: str,
append_template: str,
answer: str,
) -> None:
[history] = prompt_server.qa_boxed([QUESTION], TEMPLATES / init_template)
for _ in range(3):
[prompt] = getattr(prompt_server, tool)(
[history], [answer], [PASSAGES], TEMPLATES / append_template
)
assert prompt.startswith(history)
assert answer in prompt
history = prompt


def test_template_source_still_renders_in_the_sandbox(
prompt_server: ModuleType, tmp_path: Path
) -> None:
template = tmp_path / "unsafe.jinja"
template.write_text("{{ question.__class__.__mro__ }}", encoding="utf-8")
with pytest.raises(SecurityError):
prompt_server.qa_boxed(["q"], template)