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
9 changes: 8 additions & 1 deletion src/spark_character/chip_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,11 +350,18 @@ def load_chip(path: str | Path) -> PersonalityChip:


def _safe_chip_id(value: str) -> str:
"""Reject chip ids that could escape the chip lab directory tree."""
chip_id = str(value or "").strip()
if not chip_id:
raise ValueError("Personality chip id is required.")
if "/" in chip_id or "\\" in chip_id:
raise ValueError(f"Personality chip id must not contain path separators: {chip_id!r}")
raise ValueError(
f"Personality chip id must not contain path separators: {chip_id!r}"
)
if ".." in chip_id:
raise ValueError(
f"Personality chip id must not contain path traversal sequences: {chip_id!r}"
)
return chip_id


Expand Down
41 changes: 41 additions & 0 deletions tests/test_chip_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,44 @@ def broken_loader(_path: Path) -> chip_loader.PersonalityChip:

with pytest.raises(RuntimeError, match="unexpected loader bug"):
chip_loader.load_chip_by_id("founder-operator", search_paths=[tmp_path])


# --- Path-traversal guard tests ---------------------------------------------


def test_safe_chip_id_rejects_forward_slash() -> None:
with pytest.raises(ValueError, match="path separators"):
chip_loader._safe_chip_id("../../etc/passwd")


def test_safe_chip_id_rejects_backslash() -> None:
with pytest.raises(ValueError, match="path separators"):
chip_loader._safe_chip_id("..\\..\\windows\\system32")


def test_safe_chip_id_rejects_dotdot() -> None:
with pytest.raises(ValueError, match="path traversal"):
chip_loader._safe_chip_id("foo..bar")


def test_safe_chip_id_rejects_empty() -> None:
with pytest.raises(ValueError, match="required"):
chip_loader._safe_chip_id("")


def test_safe_chip_id_rejects_whitespace_only() -> None:
with pytest.raises(ValueError, match="required"):
chip_loader._safe_chip_id(" ")


def test_safe_chip_id_accepts_valid_id() -> None:
assert chip_loader._safe_chip_id("founder-operator") == "founder-operator"


def test_safe_chip_id_strips_whitespace() -> None:
assert chip_loader._safe_chip_id(" founder-operator ") == "founder-operator"


def test_load_chip_by_id_rejects_traversal_id(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="path"):
chip_loader.load_chip_by_id("../../etc/passwd", search_paths=[tmp_path])
Loading