Skip to content
Merged
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
15 changes: 14 additions & 1 deletion src/metaseed/repositories/filesystem_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,20 @@ def _ensure_dir(self: Self) -> None:
self._dir.mkdir(parents=True, exist_ok=True)

def _get_path(self: Self, name: str) -> Path:
"""Get the file path for a dataset."""
"""Resolve the on-disk path for a dataset, rejecting unsafe names.

The name is interpolated straight into a filename, so a value like
``../../etc/passwd`` or an absolute path would escape the datasets
directory. This is the single choke point shared by save/load/delete/
exists, so validating here protects every operation rather than only
the save path.

Raises:
ValueError: If the name is not a valid dataset name.
"""
error = self.validate_name(name)
if error:
raise ValueError(error)
return self._dir / f"{name}.json"

def list(self: Self) -> list[DatasetInfo]:
Expand Down
40 changes: 40 additions & 0 deletions tests/test_repositories/test_dataset_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,46 @@ def test_delete_nonexistent(self, repo):
"""Should return False for nonexistent."""
assert repo.delete("nonexistent") is False

@pytest.mark.parametrize(
"evil_name",
[
"../secret",
"../../etc/passwd",
"sub/../../escape",
"/etc/passwd",
"..",
],
)
def test_load_rejects_path_traversal(self, repo, tmp_path, evil_name):
"""load() must not read files outside the datasets directory.

The name becomes a filename, so an unvalidated ``../secret`` (or an
absolute path) would escape the datasets dir. Every read/delete path,
not only save, must reject such names.
"""
outside = tmp_path / "secret.json"
outside.write_text('{"name": "secret", "profile": "x", "version": "1"}')

with pytest.raises(ValueError):
repo.load(evil_name)

def test_delete_rejects_path_traversal(self, repo, tmp_path):
"""delete() must not unlink files outside the datasets directory."""
victim = tmp_path / "victim.json"
victim.write_text("{}")

with pytest.raises(ValueError):
repo.delete("../victim")
assert victim.exists() # untouched

def test_exists_rejects_path_traversal(self, repo, tmp_path):
"""exists() must not probe files outside the datasets directory."""
outside = tmp_path / "probe.json"
outside.write_text("{}")

with pytest.raises(ValueError):
repo.exists("../probe")

def test_exists(self, repo):
"""Should check existence correctly."""
assert not repo.exists("test")
Expand Down
Loading