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
24 changes: 20 additions & 4 deletions servers/prompt/src/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ def _prompt_text(message: Any) -> str:

# Create a sandboxed Jinja2 environment for security
_sandboxed_env = SandboxedEnvironment(autoescape=True)
_PROMPTS_DIR = (Path(__file__).resolve().parents[3] / "prompt").resolve()
_ALLOWED_TEMPLATE_SUFFIXES = {".jinja", ".jinja2", ".j2"}


def _validate_template_path(template_path: Union[str, Path]) -> Path:
"""Validate template path to prevent path traversal.
"""Validate template path to prevent path traversal and restrict to prompt/.

Args:
template_path: Path to template file
Expand All @@ -38,20 +40,34 @@ def _validate_template_path(template_path: Union[str, Path]) -> Path:
Validated Path object

Raises:
ValueError: If path is invalid or contains traversal attempts
ValueError: If path is invalid, outside prompt/, or contains traversal attempts
"""
path = Path(template_path)

# Check for path traversal
if ".." in str(path):
if ".." in path.parts or ".." in str(path):
raise ValueError(f"Path traversal detected in template path: {template_path}")

if not path.is_absolute():
parts = path.parts
if parts and parts[0] == "prompt":
candidate = _PROMPTS_DIR.joinpath(*parts[1:])
else:
candidate = _PROMPTS_DIR / path
else:
candidate = path

# Resolve to absolute path
try:
resolved = path.resolve()
resolved = candidate.resolve()
except (OSError, RuntimeError) as e:
raise ValueError(f"Invalid template path: {template_path}") from e

if not resolved.is_relative_to(_PROMPTS_DIR) or resolved.suffix not in _ALLOWED_TEMPLATE_SUFFIXES:
raise ValueError(
f"Template path must be a Jinja template inside {_PROMPTS_DIR}: {template_path}"
)

return resolved


Expand Down
79 changes: 79 additions & 0 deletions tests/servers/prompt/test_prompt_path_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Ensure prompt server template loading is restricted to the workspace prompt/ directory."""

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

import pytest

from ultrarag.server import local_server_mode

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


@pytest.fixture(scope="module")
def prompt_server() -> ModuleType:
spec = importlib.util.spec_from_file_location(
"prompt_path_validation_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


@pytest.mark.parametrize(
"valid_path",
[
"prompt/qa_boxed.jinja",
"qa_boxed.jinja",
PROMPTS_DIR / "qa_boxed.jinja",
str(PROMPTS_DIR / "qa_boxed.jinja"),
],
)
def test_validate_template_path_accepts_workspace_prompts(
prompt_server: ModuleType, valid_path: str | Path
) -> None:
resolved = prompt_server._validate_template_path(valid_path)
assert resolved == PROMPTS_DIR / "qa_boxed.jinja"
template = prompt_server.load_prompt_template(valid_path)
assert template is not None


@pytest.mark.parametrize(
"invalid_path",
[
"/etc/passwd",
"/etc/hosts",
"../pyproject.toml",
"prompt/../pyproject.toml",
str(ROOT / "pyproject.toml"),
str(ROOT / "README.md"),
],
)
def test_validate_template_path_rejects_outside_or_non_jinja_paths(
prompt_server: ModuleType, invalid_path: str
) -> None:
with pytest.raises(ValueError):
prompt_server._validate_template_path(invalid_path)
with pytest.raises(ValueError):
prompt_server.load_prompt_template(invalid_path)


def test_validate_template_path_rejects_symlinks_escaping_prompt_dir(
prompt_server: ModuleType, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_prompts = tmp_path / "prompt"
fake_prompts.mkdir()
outside = tmp_path / "outside.jinja"
outside.write_text("secret", encoding="utf-8")
symlink = fake_prompts / "escape.jinja"
symlink.symlink_to(outside)

monkeypatch.setattr(prompt_server, "_PROMPTS_DIR", fake_prompts.resolve())
with pytest.raises(ValueError):
prompt_server._validate_template_path("prompt/escape.jinja")
with pytest.raises(ValueError):
prompt_server._validate_template_path(symlink)