"""Phase 2.1 — Path traversal security tests. Covers every attack vector identified in the muse-powered security recon: 1. validate_workspace_path / validate_path_prefix — unit tests for the new validation primitives that gate all workspace-relative path inputs. 2. hash-object — special-file guard (named pipes, sockets), null-byte injection, symlink following (documented behaviour), very long paths. 3. ls-files --path-prefix — null-byte and glob metacharacter injection. 4. check-attr — traversal sequences, null bytes, absolute paths, control characters, CRLF-poisoned stdin, very long paths. 5. check-ignore — same surface as check-attr. 6. verify-object --stdin — CRLF line endings must not embed \\r in IDs. 7. apply_mpack / unpack-objects — zip-slip attack via malicious manifest keys; malicious object IDs in pack bundles. Design principles ----------------- - Every test is hermetic: uses tmp_path, writes only what it needs. - No datetime.now() — pinned UTC timestamps wherever commits are needed. - No synthetic IDs — compute_commit_id / compute_snapshot_id used throughout. - Stress: 10 000-path batch, 100 000-char path, 100-entry malicious manifest. """ from __future__ import annotations import datetime import json import os import pathlib import sys import pytest from tests.cli_test_helper import CliRunner from muse.core.errors import ExitCode from muse.core.object_store import write_object from muse.core.mpack import MPack, SnapshotDeltaDict, apply_mpack from muse.core.ids import hash_commit as compute_commit_id, hash_snapshot as compute_snapshot_id from muse.core.commits import ( CommitRecord, write_commit, ) from muse.core.snapshots import ( SnapshotRecord, write_snapshot, ) from muse.core.validation import ( validate_path_prefix, validate_workspace_path, ) from muse.core.types import Manifest, blob_id, fake_id, long_id from muse.core.paths import heads_dir, muse_dir cli = None # argparse migration — CliRunner ignores this runner = CliRunner() _REPO_ID = "security-test" _BASE_DT = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) # --------------------------------------------------------------------------- # Repo helpers # --------------------------------------------------------------------------- def _init_repo(root: pathlib.Path) -> pathlib.Path: dot_muse = muse_dir(root) for d in ("commits", "snapshots", "objects", "refs/heads"): (dot_muse / d).mkdir(parents=True, exist_ok=True) (dot_muse / "HEAD").write_text("ref: refs/heads/main", encoding="utf-8") (dot_muse / "repo.json").write_text( json.dumps({"repo_id": _REPO_ID, "domain": "generic"}), encoding="utf-8" ) return root def _make_commit(root: pathlib.Path, idx: int = 0, parent_id: str | None = None) -> str: manifest: Manifest = {f"file_{idx}.py": "a" * 64} snap_id = compute_snapshot_id(manifest) write_snapshot(root, SnapshotRecord(snapshot_id=snap_id, manifest=manifest)) dt = _BASE_DT + datetime.timedelta(hours=idx) parent_ids = [parent_id] if parent_id else [] commit_id = compute_commit_id( parent_ids=parent_ids, snapshot_id=snap_id, message=f"commit {idx}", committed_at_iso=dt.isoformat(), ) write_commit(root, CommitRecord( commit_id=commit_id, branch="main", snapshot_id=snap_id, message=f"commit {idx}", committed_at=dt, parent_commit_id=parent_id, )) (heads_dir(root) / "main").write_text(commit_id, encoding="utf-8") return commit_id def _env(root: pathlib.Path) -> Manifest: return {"MUSE_REPO_ROOT": str(root)} # =========================================================================== # 1. validate_workspace_path — unit tests # =========================================================================== class TestValidateWorkspacePath: def test_valid_simple_path(self) -> None: assert validate_workspace_path("tracks/drums.mid") == "tracks/drums.mid" def test_valid_filename_only(self) -> None: assert validate_workspace_path("README.md") == "README.md" def test_valid_with_dots_in_name(self) -> None: assert validate_workspace_path("src/my.module.py") == "src/my.module.py" def test_valid_with_tab(self) -> None: # Tab is the only non-printable char we allow. assert validate_workspace_path("path\twith\ttabs") == "path\twith\ttabs" def test_rejects_empty(self) -> None: with pytest.raises(ValueError, match="empty"): validate_workspace_path("") def test_rejects_null_byte(self) -> None: with pytest.raises(ValueError, match="null byte"): validate_workspace_path("foo\x00bar") def test_rejects_null_byte_prefix_injection(self) -> None: """Classic null-byte injection: foo\\x00../../etc/passwd.""" with pytest.raises(ValueError, match="null byte"): validate_workspace_path("tracks/song.mid\x00../../etc/passwd") def test_rejects_dotdot_relative(self) -> None: with pytest.raises(ValueError, match="traversal"): validate_workspace_path("../../../etc/passwd") def test_rejects_dotdot_in_middle(self) -> None: with pytest.raises(ValueError, match="traversal"): validate_workspace_path("tracks/../../../etc/passwd") def test_rejects_dotdot_alone(self) -> None: with pytest.raises(ValueError, match="traversal"): validate_workspace_path("..") def test_rejects_absolute_posix(self) -> None: with pytest.raises(ValueError, match="absolute"): validate_workspace_path("/etc/passwd") def test_rejects_absolute_windows_backslash(self) -> None: with pytest.raises(ValueError, match="absolute"): validate_workspace_path("\\windows\\path") def test_rejects_windows_drive_letter(self) -> None: with pytest.raises(ValueError, match="absolute"): validate_workspace_path("C:\\Users\\malicious") def test_rejects_control_character_cr(self) -> None: with pytest.raises(ValueError, match="control character"): validate_workspace_path("foo\rbar") def test_rejects_control_character_lf(self) -> None: with pytest.raises(ValueError, match="control character"): validate_workspace_path("foo\nbar") def test_rejects_control_character_esc(self) -> None: with pytest.raises(ValueError, match="control character"): validate_workspace_path("foo\x1bbar") def test_rejects_ansi_escape_sequence(self) -> None: """ESC[31m — terminal colour injection.""" with pytest.raises(ValueError, match="control character"): validate_workspace_path("\x1b[31mmalicious\x1b[0m") def test_rejects_very_long_path(self) -> None: with pytest.raises(ValueError, match="too long"): validate_workspace_path("a/" * 2500) # > 4096 chars def test_accepts_path_at_max_length(self) -> None: # 4096 chars exactly — must pass. p = "a" * 4096 assert validate_workspace_path(p) == p def test_rejects_path_one_over_max(self) -> None: with pytest.raises(ValueError, match="too long"): validate_workspace_path("a" * 4097) # =========================================================================== # 2. validate_path_prefix — unit tests # =========================================================================== class TestValidatePathPrefix: def test_valid_prefix(self) -> None: assert validate_path_prefix("src/") == "src/" def test_valid_empty_prefix(self) -> None: # Empty prefix matches everything — it's a valid no-op filter. assert validate_path_prefix("") == "" def test_rejects_null_byte(self) -> None: with pytest.raises(ValueError, match="null byte"): validate_path_prefix("src/\x00malicious") def test_rejects_glob_star(self) -> None: with pytest.raises(ValueError, match="glob metacharacters"): validate_path_prefix("src/*.py") def test_rejects_glob_question(self) -> None: with pytest.raises(ValueError, match="glob metacharacters"): validate_path_prefix("src/?") def test_rejects_glob_bracket(self) -> None: with pytest.raises(ValueError, match="glob metacharacters"): validate_path_prefix("src/[ab]") def test_rejects_control_character(self) -> None: with pytest.raises(ValueError, match="control character"): validate_path_prefix("src/\x1b[malicious") # =========================================================================== # 3. hash-object — special-file guard, null bytes, symlinks, long paths # =========================================================================== class TestHashObjectSecurity: def test_rejects_named_pipe(self, tmp_path: pathlib.Path) -> None: """A named pipe (FIFO) must be rejected — opening it would block forever.""" fifo = tmp_path / "malicious.fifo" os.mkfifo(fifo) result = runner.invoke(cli, ["hash-object", str(fifo)]) assert result.exit_code != 0 assert "not a regular file" in result.stderr.lower() or "regular" in result.stderr.lower() def test_rejects_directory(self, tmp_path: pathlib.Path) -> None: result = runner.invoke(cli, ["hash-object", str(tmp_path)]) assert result.exit_code != 0 def test_rejects_nonexistent_path(self, tmp_path: pathlib.Path) -> None: result = runner.invoke(cli, ["hash-object", str(tmp_path / "ghost.txt")]) assert result.exit_code != 0 def test_regular_file_accepted(self, tmp_path: pathlib.Path) -> None: f = tmp_path / "hello.txt" f.write_bytes(b"hello muse") result = runner.invoke(cli, ["hash-object", "--json", str(f)]) assert result.exit_code == 0 data = json.loads(result.output) assert data["object_id"].startswith("sha256:") assert len(data["object_id"]) == 71 def test_symlink_to_regular_file_accepted(self, tmp_path: pathlib.Path) -> None: """Symlinks to regular files are followed — consistent with git hash-object.""" real = tmp_path / "real.txt" real.write_bytes(b"real content") link = tmp_path / "link.txt" link.symlink_to(real) result = runner.invoke(cli, ["hash-object", str(link)]) # By design: hash-object follows symlinks to regular files. assert result.exit_code == 0 def test_symlink_to_nonexistent_rejected(self, tmp_path: pathlib.Path) -> None: link = tmp_path / "dangling.txt" link.symlink_to(tmp_path / "ghost.txt") result = runner.invoke(cli, ["hash-object", str(link)]) assert result.exit_code != 0 def test_very_long_path_rejected(self, tmp_path: pathlib.Path) -> None: """A 100 000-char path argument must not stack-overflow — it simply won't exist.""" long_path = f"{tmp_path}/{'a' * 100_000}" result = runner.invoke(cli, ["hash-object", long_path]) # The file doesn't exist so exit code is non-zero — no crash. assert result.exit_code != 0 assert "exit_code" not in result.output # no Python traceback leaked def test_write_stores_object_in_repo(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) f = tmp_path / "data.bin" f.write_bytes(b"secret content") result = runner.invoke( cli, ["hash-object", "--write", "--json", str(f)], env=_env(tmp_path), ) assert result.exit_code == 0 data = json.loads(result.output) assert data["stored"] is True @pytest.mark.skipif(sys.platform == "win32", reason="block devices not on Windows") def test_rejects_char_device(self) -> None: """/dev/null is a char device — must be rejected.""" null_dev = pathlib.Path("/dev/null") if not null_dev.exists(): pytest.skip("/dev/null not available") result = runner.invoke(cli, ["hash-object", str(null_dev)]) assert result.exit_code != 0 # =========================================================================== # 4. ls-files — prefix injection # =========================================================================== class TestLsFilesPrefix: def test_null_byte_in_prefix_rejected(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) _make_commit(tmp_path) result = runner.invoke( cli, ["ls-files", "--path-prefix", "src/\x00malicious"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_glob_star_in_prefix_rejected(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) _make_commit(tmp_path) result = runner.invoke( cli, ["ls-files", "--path-prefix", "src/*.py"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_clean_prefix_accepted(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) _make_commit(tmp_path) result = runner.invoke( cli, ["ls-files", "--path-prefix", "file_"], env=_env(tmp_path), ) assert result.exit_code == 0 def test_empty_prefix_returns_all(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) _make_commit(tmp_path) result = runner.invoke( cli, ["ls-files", "--path-prefix", ""], env=_env(tmp_path), ) # Empty prefix is valid and returns all files. assert result.exit_code == 0 # =========================================================================== # 5. check-attr — traversal, null bytes, absolute paths, CRLF stdin # =========================================================================== class TestCheckAttrSecurity: def _repo_with_attrs(self, root: pathlib.Path) -> pathlib.Path: _init_repo(root) (root / ".museattributes").write_text( '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n' 'strategy = "auto"\ncomment = ""\n', encoding="utf-8", ) return root def test_traversal_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo_with_attrs(tmp_path) result = runner.invoke( cli, ["check-attr", "../../../etc/passwd"], env=_env(tmp_path), ) assert result.exit_code != 0 out = result.stderr assert "traversal" in out.lower() or "invalid" in out.lower() def test_null_byte_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo_with_attrs(tmp_path) result = runner.invoke( cli, ["check-attr", "foo\x00../../etc/passwd"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_absolute_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo_with_attrs(tmp_path) result = runner.invoke( cli, ["check-attr", "/etc/passwd"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_ansi_escape_in_path_rejected(self, tmp_path: pathlib.Path) -> None: """ESC[31m in a path argument must be rejected before it reaches output.""" self._repo_with_attrs(tmp_path) result = runner.invoke( cli, ["check-attr", "\x1b[31mmalicious\x1b[0m"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_valid_path_accepted(self, tmp_path: pathlib.Path) -> None: self._repo_with_attrs(tmp_path) result = runner.invoke( cli, ["check-attr", "tracks/drums.mid"], env=_env(tmp_path), ) assert result.exit_code == 0 def test_very_long_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo_with_attrs(tmp_path) long_path = "a/" * 2500 # > 4096 chars result = runner.invoke( cli, ["check-attr", long_path], env=_env(tmp_path), ) assert result.exit_code != 0 def test_crlf_stdin_stripped(self, tmp_path: pathlib.Path) -> None: """CRLF-terminated stdin lines must not embed \\r in path strings.""" self._repo_with_attrs(tmp_path) # "tracks/ok.mid\r\n" — the \\r must be stripped before path use. crlf_input = "tracks/ok.mid\r\n" result = runner.invoke( cli, ["check-attr", "--stdin"], input=crlf_input, env=_env(tmp_path), ) assert result.exit_code == 0 # The path in output must not contain \\r. assert "\r" not in result.output def test_10k_paths_stress(self, tmp_path: pathlib.Path) -> None: """10 000 valid paths must be processed without crash or timeout.""" self._repo_with_attrs(tmp_path) paths = [f"track_{i:05d}.mid" for i in range(10_000)] stdin_data = "\n".join(paths) result = runner.invoke( cli, ["check-attr", "--stdin"], input=stdin_data, env=_env(tmp_path), ) assert result.exit_code == 0 # =========================================================================== # 6. check-ignore — same surface as check-attr # =========================================================================== class TestCheckIgnoreSecurity: def _repo(self, root: pathlib.Path) -> pathlib.Path: _init_repo(root) # .museignore is TOML format — not a gitignore-style file. (root / ".museignore").write_text( '[global]\npatterns = ["build/", "*.bin"]\n', encoding="utf-8", ) return root def test_traversal_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo(tmp_path) result = runner.invoke( cli, ["check-ignore", "../../../etc/passwd"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_null_byte_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo(tmp_path) result = runner.invoke( cli, ["check-ignore", "build/\x00../../etc/cron.d/malicious"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_absolute_path_rejected(self, tmp_path: pathlib.Path) -> None: self._repo(tmp_path) result = runner.invoke( cli, ["check-ignore", "/absolute/path"], env=_env(tmp_path), ) assert result.exit_code != 0 def test_valid_path_accepted(self, tmp_path: pathlib.Path) -> None: self._repo(tmp_path) result = runner.invoke( cli, ["check-ignore", "build/output.bin"], env=_env(tmp_path), ) assert result.exit_code == 0 def test_crlf_stdin_does_not_embed_cr(self, tmp_path: pathlib.Path) -> None: self._repo(tmp_path) crlf = "build/out.bin\r\n" result = runner.invoke( cli, ["check-ignore", "--stdin"], input=crlf, env=_env(tmp_path), ) assert result.exit_code == 0 assert "\r" not in result.output def test_dotdot_in_middle_rejected(self, tmp_path: pathlib.Path) -> None: self._repo(tmp_path) result = runner.invoke( cli, ["check-ignore", "build/../../../etc/shadow"], env=_env(tmp_path), ) assert result.exit_code != 0 # =========================================================================== # 7. verify-object --stdin — CRLF line endings # =========================================================================== class TestVerifyObjectStdinCRLF: def test_crlf_id_rejected_cleanly(self, tmp_path: pathlib.Path) -> None: """A CRLF-terminated object ID must produce a clear error, not a crash.""" _init_repo(tmp_path) content = b"test content" oid = blob_id(content) write_object(tmp_path, oid, content) # Pass the ID with a trailing \\r before the newline. crlf_input = f"{oid}\r\n" result = runner.invoke( cli, ["verify-object", "--stdin"], input=crlf_input, env=_env(tmp_path), ) # After the fix: \\r is stripped, so the ID is valid and the object passes. assert result.exit_code == 0 def test_lf_only_works(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) content = b"lf content" oid = blob_id(content) write_object(tmp_path, oid, content) result = runner.invoke( cli, ["verify-object", "--stdin"], input=f"{oid}\n", env=_env(tmp_path), ) assert result.exit_code == 0 # =========================================================================== # 8. apply_mpack / unpack-objects — zip-slip via manifest keys # =========================================================================== class TestPackZipSlip: def _minimal_bundle(self, manifest: Manifest) -> MPack: snap_id = compute_snapshot_id(manifest) snap_dict = SnapshotDeltaDict( snapshot_id=snap_id, parent_snapshot_id=None, delta_upsert=dict(manifest), delta_remove=[], ) return MPack( commits=[], snapshots=[snap_dict], blobs=[], tags=[], branch_heads={}, ) def test_traversal_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: """apply_mpack must reject manifests with ../../ traversal keys.""" _init_repo(tmp_path) mpack = self._minimal_bundle({"../../etc/cron.d/malicious": "a" * 64}) result = apply_mpack(tmp_path, mpack) # The snapshot must be skipped — not written. assert result["snapshots_written"] == 0 def test_absolute_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: """Manifest keys starting with / must be rejected.""" _init_repo(tmp_path) mpack = self._minimal_bundle({"/etc/passwd": "a" * 64}) result = apply_mpack(tmp_path, mpack) assert result["snapshots_written"] == 0 def test_null_byte_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: _init_repo(tmp_path) mpack = self._minimal_bundle({"tracks/\x00malicious": "a" * 64}) result = apply_mpack(tmp_path, mpack) assert result["snapshots_written"] == 0 def test_invalid_object_id_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: """Manifest values must be valid 64-hex object IDs.""" _init_repo(tmp_path) # Craft mpack manually — compute_snapshot_id rejects invalid OIDs. # _apply_snapshot_deltas will also raise when it calls compute_snapshot_id # on the reconstructed manifest, so snapshots_written stays 0. snap_dict = SnapshotDeltaDict( snapshot_id=fake_id("invalid-snap"), parent_snapshot_id=None, delta_upsert={"file.py": "not-a-valid-oid"}, # type: ignore[typeddict-item] delta_remove=[], ) mpack = MPack( commits=[], snapshots=[snap_dict], blobs=[], tags=[], branch_heads={}, ) result = apply_mpack(tmp_path, mpack) assert result["snapshots_written"] == 0 def test_clean_manifest_written(self, tmp_path: pathlib.Path) -> None: """A manifest with valid keys and IDs must be written successfully.""" _init_repo(tmp_path) mpack = self._minimal_bundle({"src/main.py": long_id("b" * 64)}) result = apply_mpack(tmp_path, mpack) assert result["snapshots_written"] == 1 def test_100_malicious_keys_all_skipped(self, tmp_path: pathlib.Path) -> None: """Stress: 100 bundles each with a traversal key — all must be rejected.""" _init_repo(tmp_path) skipped = 0 for i in range(100): manifest: Manifest = {f"../../malicious_{i}": "a" * 64} mpack = self._minimal_bundle(manifest) result = apply_mpack(tmp_path, mpack) skipped += result["snapshots_written"] assert skipped == 0 def test_malicious_object_id_in_pack_rejected(self, tmp_path: pathlib.Path) -> None: """An object payload with a non-hex 'object_id' must be rejected by write_object.""" _init_repo(tmp_path) from muse.core.mpack import BlobPayload bad_obj = BlobPayload(object_id="../../etc/malicious", content=b"payload") mpack = MPack( commits=[], snapshots=[], blobs=[bad_obj], tags=[], branch_heads={} ) result = apply_mpack(tmp_path, mpack) # The blob must be skipped (write_object raises ValueError on bad ID). assert result["blobs_written"] == 0 def test_unpack_objects_core_with_traversal_manifest( self, tmp_path: pathlib.Path ) -> None: """Core apply_mpack rejects traversal manifest keys from any mpack source.""" _init_repo(tmp_path) mpack = self._minimal_bundle({"../../malicious": "a" * 64}) result = apply_mpack(tmp_path, mpack) # The traversal manifest key must cause the snapshot to be skipped. assert result["snapshots_written"] == 0 # =========================================================================== # 9. Integration: full pipeline with adversarial inputs # =========================================================================== class TestEndToEndAdversarial: def test_hash_object_write_then_ls_files(self, tmp_path: pathlib.Path) -> None: """Write a real object, commit it, list it — no traversal at any step.""" _init_repo(tmp_path) f = tmp_path / "song.mid" f.write_bytes(b"\x00" * 128) # synthetic MIDI-like content result = runner.invoke( cli, ["hash-object", "--write", str(f)], env=_env(tmp_path), ) assert result.exit_code == 0 def test_check_attr_stdin_mixed_good_and_bad(self, tmp_path: pathlib.Path) -> None: """Mixed stdin with one traversal path must reject the whole batch cleanly.""" _init_repo(tmp_path) (tmp_path / ".museattributes").write_text( '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n' 'strategy = "auto"\ncomment = ""\n', encoding="utf-8", ) mixed_stdin = "tracks/good.mid\n../../../etc/passwd\ntracks/also_good.mid\n" result = runner.invoke( cli, ["check-attr", "--stdin"], input=mixed_stdin, env=_env(tmp_path), ) # The batch must be rejected as soon as the bad path is encountered. assert result.exit_code != 0 def test_no_sensitive_data_in_error_output(self, tmp_path: pathlib.Path) -> None: """Error messages for traversal attempts must not echo the full attack string.""" _init_repo(tmp_path) (tmp_path / ".museattributes").write_text( '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n' 'strategy = "auto"\ncomment = ""\n', encoding="utf-8", ) attack = "../../../etc/passwd" result = runner.invoke( cli, ["check-attr", attack], env=_env(tmp_path), ) assert result.exit_code != 0 # The error output must not contain raw control sequences or leak # system paths (the path is echoed, but sanitize_display must strip it). assert "\x1b" not in result.output