test_security_path_traversal.py
python
sha256:660fcac1df3ab28f61862e961890bd2ca8b754fa0242079d93ca1e25037ec8a6
chore(tests): add docstring to tests/__init__.py so rc14 tr…
Human
26 days ago
| 1 | """Phase 2.1 — Path traversal security tests. |
| 2 | |
| 3 | Covers every attack vector identified in the muse-powered security recon: |
| 4 | |
| 5 | 1. validate_workspace_path / validate_path_prefix — unit tests for the new |
| 6 | validation primitives that gate all workspace-relative path inputs. |
| 7 | 2. hash-object — special-file guard (named pipes, sockets), null-byte |
| 8 | injection, symlink following (documented behaviour), very long paths. |
| 9 | 3. ls-files --path-prefix — null-byte and glob metacharacter injection. |
| 10 | 4. check-attr — traversal sequences, null bytes, absolute paths, control |
| 11 | characters, CRLF-poisoned stdin, very long paths. |
| 12 | 5. check-ignore — same surface as check-attr. |
| 13 | 6. verify-object --stdin — CRLF line endings must not embed \\r in IDs. |
| 14 | 7. apply_pack / unpack-objects — zip-slip attack via malicious manifest keys; |
| 15 | malicious object IDs in pack bundles. |
| 16 | |
| 17 | Design principles |
| 18 | ----------------- |
| 19 | - Every test is hermetic: uses tmp_path, writes only what it needs. |
| 20 | - No datetime.now() — pinned UTC timestamps wherever commits are needed. |
| 21 | - No synthetic IDs — compute_commit_id / compute_snapshot_id used throughout. |
| 22 | - Stress: 10 000-path batch, 100 000-char path, 100-entry malicious manifest. |
| 23 | """ |
| 24 | |
| 25 | from __future__ import annotations |
| 26 | |
| 27 | import datetime |
| 28 | import json |
| 29 | import os |
| 30 | import pathlib |
| 31 | import sys |
| 32 | |
| 33 | import pytest |
| 34 | |
| 35 | from tests.cli_test_helper import CliRunner |
| 36 | from muse.core.errors import ExitCode |
| 37 | from muse.core.object_store import write_object |
| 38 | from muse.core.pack import PackBundle, apply_pack |
| 39 | from muse.core.snapshot import compute_commit_id, compute_snapshot_id |
| 40 | from muse.core.store import CommitRecord, SnapshotDict, SnapshotRecord, write_commit, write_snapshot |
| 41 | from muse.core.validation import ( |
| 42 | validate_path_prefix, |
| 43 | validate_workspace_path, |
| 44 | ) |
| 45 | from muse.core._types import Manifest |
| 46 | |
| 47 | cli = None # argparse migration — CliRunner ignores this |
| 48 | runner = CliRunner() |
| 49 | |
| 50 | _REPO_ID = "security-test" |
| 51 | _BASE_DT = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) |
| 52 | |
| 53 | |
| 54 | # --------------------------------------------------------------------------- |
| 55 | # Repo helpers |
| 56 | # --------------------------------------------------------------------------- |
| 57 | |
| 58 | |
| 59 | def _init_repo(root: pathlib.Path) -> pathlib.Path: |
| 60 | muse = root / ".muse" |
| 61 | for d in ("commits", "snapshots", "objects", "refs/heads"): |
| 62 | (muse / d).mkdir(parents=True, exist_ok=True) |
| 63 | (muse / "HEAD").write_text("ref: refs/heads/main", encoding="utf-8") |
| 64 | (muse / "repo.json").write_text( |
| 65 | json.dumps({"repo_id": _REPO_ID, "domain": "generic"}), encoding="utf-8" |
| 66 | ) |
| 67 | return root |
| 68 | |
| 69 | |
| 70 | def _make_commit(root: pathlib.Path, idx: int = 0, parent_id: str | None = None) -> str: |
| 71 | manifest: Manifest = {f"file_{idx}.py": "a" * 64} |
| 72 | snap_id = compute_snapshot_id(manifest) |
| 73 | write_snapshot(root, SnapshotRecord(snapshot_id=snap_id, manifest=manifest)) |
| 74 | dt = _BASE_DT + datetime.timedelta(hours=idx) |
| 75 | parent_ids = [parent_id] if parent_id else [] |
| 76 | commit_id = compute_commit_id(parent_ids, snap_id, f"commit {idx}", dt.isoformat()) |
| 77 | write_commit(root, CommitRecord( |
| 78 | commit_id=commit_id, repo_id=_REPO_ID, branch="main", |
| 79 | snapshot_id=snap_id, message=f"commit {idx}", committed_at=dt, |
| 80 | parent_commit_id=parent_id, |
| 81 | )) |
| 82 | (root / ".muse" / "refs" / "heads" / "main").write_text(commit_id, encoding="utf-8") |
| 83 | return commit_id |
| 84 | |
| 85 | |
| 86 | def _env(root: pathlib.Path) -> Manifest: |
| 87 | return {"MUSE_REPO_ROOT": str(root)} |
| 88 | |
| 89 | |
| 90 | # =========================================================================== |
| 91 | # 1. validate_workspace_path — unit tests |
| 92 | # =========================================================================== |
| 93 | |
| 94 | |
| 95 | class TestValidateWorkspacePath: |
| 96 | def test_valid_simple_path(self) -> None: |
| 97 | assert validate_workspace_path("tracks/drums.mid") == "tracks/drums.mid" |
| 98 | |
| 99 | def test_valid_filename_only(self) -> None: |
| 100 | assert validate_workspace_path("README.md") == "README.md" |
| 101 | |
| 102 | def test_valid_with_dots_in_name(self) -> None: |
| 103 | assert validate_workspace_path("src/my.module.py") == "src/my.module.py" |
| 104 | |
| 105 | def test_valid_with_tab(self) -> None: |
| 106 | # Tab is the only non-printable char we allow. |
| 107 | assert validate_workspace_path("path\twith\ttabs") == "path\twith\ttabs" |
| 108 | |
| 109 | def test_rejects_empty(self) -> None: |
| 110 | with pytest.raises(ValueError, match="empty"): |
| 111 | validate_workspace_path("") |
| 112 | |
| 113 | def test_rejects_null_byte(self) -> None: |
| 114 | with pytest.raises(ValueError, match="null byte"): |
| 115 | validate_workspace_path("foo\x00bar") |
| 116 | |
| 117 | def test_rejects_null_byte_prefix_injection(self) -> None: |
| 118 | """Classic null-byte injection: foo\\x00../../etc/passwd.""" |
| 119 | with pytest.raises(ValueError, match="null byte"): |
| 120 | validate_workspace_path("tracks/song.mid\x00../../etc/passwd") |
| 121 | |
| 122 | def test_rejects_dotdot_relative(self) -> None: |
| 123 | with pytest.raises(ValueError, match="traversal"): |
| 124 | validate_workspace_path("../../../etc/passwd") |
| 125 | |
| 126 | def test_rejects_dotdot_in_middle(self) -> None: |
| 127 | with pytest.raises(ValueError, match="traversal"): |
| 128 | validate_workspace_path("tracks/../../../etc/passwd") |
| 129 | |
| 130 | def test_rejects_dotdot_alone(self) -> None: |
| 131 | with pytest.raises(ValueError, match="traversal"): |
| 132 | validate_workspace_path("..") |
| 133 | |
| 134 | def test_rejects_absolute_posix(self) -> None: |
| 135 | with pytest.raises(ValueError, match="absolute"): |
| 136 | validate_workspace_path("/etc/passwd") |
| 137 | |
| 138 | def test_rejects_absolute_windows_backslash(self) -> None: |
| 139 | with pytest.raises(ValueError, match="absolute"): |
| 140 | validate_workspace_path("\\windows\\path") |
| 141 | |
| 142 | def test_rejects_windows_drive_letter(self) -> None: |
| 143 | with pytest.raises(ValueError, match="absolute"): |
| 144 | validate_workspace_path("C:\\Users\\evil") |
| 145 | |
| 146 | def test_rejects_control_character_cr(self) -> None: |
| 147 | with pytest.raises(ValueError, match="control character"): |
| 148 | validate_workspace_path("foo\rbar") |
| 149 | |
| 150 | def test_rejects_control_character_lf(self) -> None: |
| 151 | with pytest.raises(ValueError, match="control character"): |
| 152 | validate_workspace_path("foo\nbar") |
| 153 | |
| 154 | def test_rejects_control_character_esc(self) -> None: |
| 155 | with pytest.raises(ValueError, match="control character"): |
| 156 | validate_workspace_path("foo\x1bbar") |
| 157 | |
| 158 | def test_rejects_ansi_escape_sequence(self) -> None: |
| 159 | """ESC[31m — terminal colour injection.""" |
| 160 | with pytest.raises(ValueError, match="control character"): |
| 161 | validate_workspace_path("\x1b[31mevil\x1b[0m") |
| 162 | |
| 163 | def test_rejects_very_long_path(self) -> None: |
| 164 | with pytest.raises(ValueError, match="too long"): |
| 165 | validate_workspace_path("a/" * 2500) # > 4096 chars |
| 166 | |
| 167 | def test_accepts_path_at_max_length(self) -> None: |
| 168 | # 4096 chars exactly — must pass. |
| 169 | p = "a" * 4096 |
| 170 | assert validate_workspace_path(p) == p |
| 171 | |
| 172 | def test_rejects_path_one_over_max(self) -> None: |
| 173 | with pytest.raises(ValueError, match="too long"): |
| 174 | validate_workspace_path("a" * 4097) |
| 175 | |
| 176 | |
| 177 | # =========================================================================== |
| 178 | # 2. validate_path_prefix — unit tests |
| 179 | # =========================================================================== |
| 180 | |
| 181 | |
| 182 | class TestValidatePathPrefix: |
| 183 | def test_valid_prefix(self) -> None: |
| 184 | assert validate_path_prefix("src/") == "src/" |
| 185 | |
| 186 | def test_valid_empty_prefix(self) -> None: |
| 187 | # Empty prefix matches everything — it's a valid no-op filter. |
| 188 | assert validate_path_prefix("") == "" |
| 189 | |
| 190 | def test_rejects_null_byte(self) -> None: |
| 191 | with pytest.raises(ValueError, match="null byte"): |
| 192 | validate_path_prefix("src/\x00evil") |
| 193 | |
| 194 | def test_rejects_glob_star(self) -> None: |
| 195 | with pytest.raises(ValueError, match="glob metacharacters"): |
| 196 | validate_path_prefix("src/*.py") |
| 197 | |
| 198 | def test_rejects_glob_question(self) -> None: |
| 199 | with pytest.raises(ValueError, match="glob metacharacters"): |
| 200 | validate_path_prefix("src/?") |
| 201 | |
| 202 | def test_rejects_glob_bracket(self) -> None: |
| 203 | with pytest.raises(ValueError, match="glob metacharacters"): |
| 204 | validate_path_prefix("src/[ab]") |
| 205 | |
| 206 | def test_rejects_control_character(self) -> None: |
| 207 | with pytest.raises(ValueError, match="control character"): |
| 208 | validate_path_prefix("src/\x1b[evil") |
| 209 | |
| 210 | |
| 211 | # =========================================================================== |
| 212 | # 3. hash-object — special-file guard, null bytes, symlinks, long paths |
| 213 | # =========================================================================== |
| 214 | |
| 215 | |
| 216 | class TestHashObjectSecurity: |
| 217 | def test_rejects_named_pipe(self, tmp_path: pathlib.Path) -> None: |
| 218 | """A named pipe (FIFO) must be rejected — opening it would block forever.""" |
| 219 | fifo = tmp_path / "evil.fifo" |
| 220 | os.mkfifo(fifo) |
| 221 | result = runner.invoke(cli, ["hash-object", str(fifo)]) |
| 222 | assert result.exit_code != 0 |
| 223 | assert "not a regular file" in result.output.lower() or "regular" in result.output.lower() |
| 224 | |
| 225 | def test_rejects_directory(self, tmp_path: pathlib.Path) -> None: |
| 226 | result = runner.invoke(cli, ["hash-object", str(tmp_path)]) |
| 227 | assert result.exit_code != 0 |
| 228 | |
| 229 | def test_rejects_nonexistent_path(self, tmp_path: pathlib.Path) -> None: |
| 230 | result = runner.invoke(cli, ["hash-object", str(tmp_path / "ghost.txt")]) |
| 231 | assert result.exit_code != 0 |
| 232 | |
| 233 | def test_regular_file_accepted(self, tmp_path: pathlib.Path) -> None: |
| 234 | f = tmp_path / "hello.txt" |
| 235 | f.write_bytes(b"hello muse") |
| 236 | result = runner.invoke(cli, ["hash-object", str(f)]) |
| 237 | assert result.exit_code == 0 |
| 238 | data = json.loads(result.output) |
| 239 | assert len(data["object_id"]) == 64 |
| 240 | |
| 241 | def test_symlink_to_regular_file_accepted(self, tmp_path: pathlib.Path) -> None: |
| 242 | """Symlinks to regular files are followed — consistent with git hash-object.""" |
| 243 | real = tmp_path / "real.txt" |
| 244 | real.write_bytes(b"real content") |
| 245 | link = tmp_path / "link.txt" |
| 246 | link.symlink_to(real) |
| 247 | result = runner.invoke(cli, ["hash-object", str(link)]) |
| 248 | # By design: hash-object follows symlinks to regular files. |
| 249 | assert result.exit_code == 0 |
| 250 | |
| 251 | def test_symlink_to_nonexistent_rejected(self, tmp_path: pathlib.Path) -> None: |
| 252 | link = tmp_path / "dangling.txt" |
| 253 | link.symlink_to(tmp_path / "ghost.txt") |
| 254 | result = runner.invoke(cli, ["hash-object", str(link)]) |
| 255 | assert result.exit_code != 0 |
| 256 | |
| 257 | def test_very_long_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 258 | """A 100 000-char path argument must not stack-overflow — it simply won't exist.""" |
| 259 | long_path = str(tmp_path) + "/" + "a" * 100_000 |
| 260 | result = runner.invoke(cli, ["hash-object", long_path]) |
| 261 | # The file doesn't exist so exit code is non-zero — no crash. |
| 262 | assert result.exit_code != 0 |
| 263 | assert "exit_code" not in result.output # no Python traceback leaked |
| 264 | |
| 265 | def test_write_stores_object_in_repo(self, tmp_path: pathlib.Path) -> None: |
| 266 | _init_repo(tmp_path) |
| 267 | f = tmp_path / "data.bin" |
| 268 | f.write_bytes(b"secret content") |
| 269 | result = runner.invoke( |
| 270 | cli, ["hash-object", "--write", str(f)], |
| 271 | env=_env(tmp_path), |
| 272 | ) |
| 273 | assert result.exit_code == 0 |
| 274 | data = json.loads(result.output) |
| 275 | assert data["stored"] is True |
| 276 | |
| 277 | @pytest.mark.skipif(sys.platform == "win32", reason="block devices not on Windows") |
| 278 | def test_rejects_char_device(self) -> None: |
| 279 | """/dev/null is a char device — must be rejected.""" |
| 280 | null_dev = pathlib.Path("/dev/null") |
| 281 | if not null_dev.exists(): |
| 282 | pytest.skip("/dev/null not available") |
| 283 | result = runner.invoke(cli, ["hash-object", str(null_dev)]) |
| 284 | assert result.exit_code != 0 |
| 285 | |
| 286 | |
| 287 | # =========================================================================== |
| 288 | # 4. ls-files — prefix injection |
| 289 | # =========================================================================== |
| 290 | |
| 291 | |
| 292 | class TestLsFilesPrefix: |
| 293 | def test_null_byte_in_prefix_rejected(self, tmp_path: pathlib.Path) -> None: |
| 294 | _init_repo(tmp_path) |
| 295 | _make_commit(tmp_path) |
| 296 | result = runner.invoke( |
| 297 | cli, ["ls-files", "--path-prefix", "src/\x00evil"], |
| 298 | env=_env(tmp_path), |
| 299 | ) |
| 300 | assert result.exit_code != 0 |
| 301 | |
| 302 | def test_glob_star_in_prefix_rejected(self, tmp_path: pathlib.Path) -> None: |
| 303 | _init_repo(tmp_path) |
| 304 | _make_commit(tmp_path) |
| 305 | result = runner.invoke( |
| 306 | cli, ["ls-files", "--path-prefix", "src/*.py"], |
| 307 | env=_env(tmp_path), |
| 308 | ) |
| 309 | assert result.exit_code != 0 |
| 310 | |
| 311 | def test_clean_prefix_accepted(self, tmp_path: pathlib.Path) -> None: |
| 312 | _init_repo(tmp_path) |
| 313 | _make_commit(tmp_path) |
| 314 | result = runner.invoke( |
| 315 | cli, ["ls-files", "--path-prefix", "file_"], |
| 316 | env=_env(tmp_path), |
| 317 | ) |
| 318 | assert result.exit_code == 0 |
| 319 | |
| 320 | def test_empty_prefix_returns_all(self, tmp_path: pathlib.Path) -> None: |
| 321 | _init_repo(tmp_path) |
| 322 | _make_commit(tmp_path) |
| 323 | result = runner.invoke( |
| 324 | cli, ["ls-files", "--path-prefix", ""], |
| 325 | env=_env(tmp_path), |
| 326 | ) |
| 327 | # Empty prefix is valid and returns all files. |
| 328 | assert result.exit_code == 0 |
| 329 | |
| 330 | |
| 331 | # =========================================================================== |
| 332 | # 5. check-attr — traversal, null bytes, absolute paths, CRLF stdin |
| 333 | # =========================================================================== |
| 334 | |
| 335 | |
| 336 | class TestCheckAttrSecurity: |
| 337 | def _repo_with_attrs(self, root: pathlib.Path) -> pathlib.Path: |
| 338 | _init_repo(root) |
| 339 | (root / ".museattributes").write_text( |
| 340 | '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n' |
| 341 | 'strategy = "auto"\ncomment = ""\n', |
| 342 | encoding="utf-8", |
| 343 | ) |
| 344 | return root |
| 345 | |
| 346 | def test_traversal_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 347 | self._repo_with_attrs(tmp_path) |
| 348 | result = runner.invoke( |
| 349 | cli, ["check-attr", "../../../etc/passwd"], |
| 350 | env=_env(tmp_path), |
| 351 | ) |
| 352 | assert result.exit_code != 0 |
| 353 | out = result.output |
| 354 | assert "traversal" in out.lower() or "invalid" in out.lower() |
| 355 | |
| 356 | def test_null_byte_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 357 | self._repo_with_attrs(tmp_path) |
| 358 | result = runner.invoke( |
| 359 | cli, ["check-attr", "foo\x00../../etc/passwd"], |
| 360 | env=_env(tmp_path), |
| 361 | ) |
| 362 | assert result.exit_code != 0 |
| 363 | |
| 364 | def test_absolute_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 365 | self._repo_with_attrs(tmp_path) |
| 366 | result = runner.invoke( |
| 367 | cli, ["check-attr", "/etc/passwd"], |
| 368 | env=_env(tmp_path), |
| 369 | ) |
| 370 | assert result.exit_code != 0 |
| 371 | |
| 372 | def test_ansi_escape_in_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 373 | """ESC[31m in a path argument must be rejected before it reaches output.""" |
| 374 | self._repo_with_attrs(tmp_path) |
| 375 | result = runner.invoke( |
| 376 | cli, ["check-attr", "\x1b[31mevil\x1b[0m"], |
| 377 | env=_env(tmp_path), |
| 378 | ) |
| 379 | assert result.exit_code != 0 |
| 380 | |
| 381 | def test_valid_path_accepted(self, tmp_path: pathlib.Path) -> None: |
| 382 | self._repo_with_attrs(tmp_path) |
| 383 | result = runner.invoke( |
| 384 | cli, ["check-attr", "tracks/drums.mid"], |
| 385 | env=_env(tmp_path), |
| 386 | ) |
| 387 | assert result.exit_code == 0 |
| 388 | |
| 389 | def test_very_long_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 390 | self._repo_with_attrs(tmp_path) |
| 391 | long_path = "a/" * 2500 # > 4096 chars |
| 392 | result = runner.invoke( |
| 393 | cli, ["check-attr", long_path], |
| 394 | env=_env(tmp_path), |
| 395 | ) |
| 396 | assert result.exit_code != 0 |
| 397 | |
| 398 | def test_crlf_stdin_stripped(self, tmp_path: pathlib.Path) -> None: |
| 399 | """CRLF-terminated stdin lines must not embed \\r in path strings.""" |
| 400 | self._repo_with_attrs(tmp_path) |
| 401 | # "tracks/ok.mid\r\n" — the \\r must be stripped before path use. |
| 402 | crlf_input = "tracks/ok.mid\r\n" |
| 403 | result = runner.invoke( |
| 404 | cli, ["check-attr", "--stdin"], |
| 405 | input=crlf_input, |
| 406 | env=_env(tmp_path), |
| 407 | ) |
| 408 | assert result.exit_code == 0 |
| 409 | # The path in output must not contain \\r. |
| 410 | assert "\r" not in result.output |
| 411 | |
| 412 | def test_10k_paths_stress(self, tmp_path: pathlib.Path) -> None: |
| 413 | """10 000 valid paths must be processed without crash or timeout.""" |
| 414 | self._repo_with_attrs(tmp_path) |
| 415 | paths = [f"track_{i:05d}.mid" for i in range(10_000)] |
| 416 | stdin_data = "\n".join(paths) |
| 417 | result = runner.invoke( |
| 418 | cli, ["check-attr", "--stdin"], |
| 419 | input=stdin_data, |
| 420 | env=_env(tmp_path), |
| 421 | ) |
| 422 | assert result.exit_code == 0 |
| 423 | |
| 424 | |
| 425 | # =========================================================================== |
| 426 | # 6. check-ignore — same surface as check-attr |
| 427 | # =========================================================================== |
| 428 | |
| 429 | |
| 430 | class TestCheckIgnoreSecurity: |
| 431 | def _repo(self, root: pathlib.Path) -> pathlib.Path: |
| 432 | _init_repo(root) |
| 433 | # .museignore is TOML format — not a gitignore-style file. |
| 434 | (root / ".museignore").write_text( |
| 435 | '[global]\npatterns = ["build/", "*.bin"]\n', |
| 436 | encoding="utf-8", |
| 437 | ) |
| 438 | return root |
| 439 | |
| 440 | def test_traversal_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 441 | self._repo(tmp_path) |
| 442 | result = runner.invoke( |
| 443 | cli, ["check-ignore", "../../../etc/passwd"], |
| 444 | env=_env(tmp_path), |
| 445 | ) |
| 446 | assert result.exit_code != 0 |
| 447 | |
| 448 | def test_null_byte_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 449 | self._repo(tmp_path) |
| 450 | result = runner.invoke( |
| 451 | cli, ["check-ignore", "build/\x00../../etc/cron.d/evil"], |
| 452 | env=_env(tmp_path), |
| 453 | ) |
| 454 | assert result.exit_code != 0 |
| 455 | |
| 456 | def test_absolute_path_rejected(self, tmp_path: pathlib.Path) -> None: |
| 457 | self._repo(tmp_path) |
| 458 | result = runner.invoke( |
| 459 | cli, ["check-ignore", "/absolute/path"], |
| 460 | env=_env(tmp_path), |
| 461 | ) |
| 462 | assert result.exit_code != 0 |
| 463 | |
| 464 | def test_valid_path_accepted(self, tmp_path: pathlib.Path) -> None: |
| 465 | self._repo(tmp_path) |
| 466 | result = runner.invoke( |
| 467 | cli, ["check-ignore", "build/output.bin"], |
| 468 | env=_env(tmp_path), |
| 469 | ) |
| 470 | assert result.exit_code == 0 |
| 471 | |
| 472 | def test_crlf_stdin_does_not_embed_cr(self, tmp_path: pathlib.Path) -> None: |
| 473 | self._repo(tmp_path) |
| 474 | crlf = "build/out.bin\r\n" |
| 475 | result = runner.invoke( |
| 476 | cli, ["check-ignore", "--stdin"], |
| 477 | input=crlf, |
| 478 | env=_env(tmp_path), |
| 479 | ) |
| 480 | assert result.exit_code == 0 |
| 481 | assert "\r" not in result.output |
| 482 | |
| 483 | def test_dotdot_in_middle_rejected(self, tmp_path: pathlib.Path) -> None: |
| 484 | self._repo(tmp_path) |
| 485 | result = runner.invoke( |
| 486 | cli, ["check-ignore", "build/../../../etc/shadow"], |
| 487 | env=_env(tmp_path), |
| 488 | ) |
| 489 | assert result.exit_code != 0 |
| 490 | |
| 491 | |
| 492 | # =========================================================================== |
| 493 | # 7. verify-object --stdin — CRLF line endings |
| 494 | # =========================================================================== |
| 495 | |
| 496 | |
| 497 | class TestVerifyObjectStdinCRLF: |
| 498 | def test_crlf_id_rejected_cleanly(self, tmp_path: pathlib.Path) -> None: |
| 499 | """A CRLF-terminated object ID must produce a clear error, not a crash.""" |
| 500 | _init_repo(tmp_path) |
| 501 | content = b"test content" |
| 502 | import hashlib |
| 503 | oid = hashlib.sha256(content).hexdigest() |
| 504 | write_object(tmp_path, oid, content) |
| 505 | |
| 506 | # Pass the ID with a trailing \\r before the newline. |
| 507 | crlf_input = oid + "\r\n" |
| 508 | result = runner.invoke( |
| 509 | cli, ["verify-object", "--stdin"], |
| 510 | input=crlf_input, |
| 511 | env=_env(tmp_path), |
| 512 | ) |
| 513 | # After the fix: \\r is stripped, so the ID is valid and the object passes. |
| 514 | assert result.exit_code == 0 |
| 515 | |
| 516 | def test_lf_only_works(self, tmp_path: pathlib.Path) -> None: |
| 517 | _init_repo(tmp_path) |
| 518 | content = b"lf content" |
| 519 | import hashlib |
| 520 | oid = hashlib.sha256(content).hexdigest() |
| 521 | write_object(tmp_path, oid, content) |
| 522 | |
| 523 | result = runner.invoke( |
| 524 | cli, ["verify-object", "--stdin"], |
| 525 | input=oid + "\n", |
| 526 | env=_env(tmp_path), |
| 527 | ) |
| 528 | assert result.exit_code == 0 |
| 529 | |
| 530 | |
| 531 | # =========================================================================== |
| 532 | # 8. apply_pack / unpack-objects — zip-slip via manifest keys |
| 533 | # =========================================================================== |
| 534 | |
| 535 | |
| 536 | class TestPackZipSlip: |
| 537 | def _minimal_bundle(self, manifest: Manifest) -> PackBundle: |
| 538 | snap_id = compute_snapshot_id(manifest) |
| 539 | snap_dict: SnapshotDict = { |
| 540 | "snapshot_id": snap_id, |
| 541 | "manifest": manifest, |
| 542 | "created_at": "2026-01-01T00:00:00+00:00", |
| 543 | } |
| 544 | return PackBundle( |
| 545 | commits=[], |
| 546 | snapshots=[snap_dict], |
| 547 | objects=[], |
| 548 | tags=[], |
| 549 | branch_heads={}, |
| 550 | ) |
| 551 | |
| 552 | def test_traversal_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: |
| 553 | """apply_pack must reject manifests with ../../ traversal keys.""" |
| 554 | _init_repo(tmp_path) |
| 555 | bundle = self._minimal_bundle({"../../etc/cron.d/evil": "a" * 64}) |
| 556 | result = apply_pack(tmp_path, bundle) |
| 557 | # The snapshot must be skipped — not written. |
| 558 | assert result["snapshots_written"] == 0 |
| 559 | |
| 560 | def test_absolute_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: |
| 561 | """Manifest keys starting with / must be rejected.""" |
| 562 | _init_repo(tmp_path) |
| 563 | bundle = self._minimal_bundle({"/etc/passwd": "a" * 64}) |
| 564 | result = apply_pack(tmp_path, bundle) |
| 565 | assert result["snapshots_written"] == 0 |
| 566 | |
| 567 | def test_null_byte_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: |
| 568 | _init_repo(tmp_path) |
| 569 | bundle = self._minimal_bundle({"tracks/\x00evil": "a" * 64}) |
| 570 | result = apply_pack(tmp_path, bundle) |
| 571 | assert result["snapshots_written"] == 0 |
| 572 | |
| 573 | def test_invalid_object_id_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None: |
| 574 | """Manifest values must be valid 64-hex object IDs.""" |
| 575 | _init_repo(tmp_path) |
| 576 | bundle = self._minimal_bundle({"file.py": "not-a-valid-oid"}) |
| 577 | result = apply_pack(tmp_path, bundle) |
| 578 | assert result["snapshots_written"] == 0 |
| 579 | |
| 580 | def test_clean_manifest_written(self, tmp_path: pathlib.Path) -> None: |
| 581 | """A manifest with valid keys and IDs must be written successfully.""" |
| 582 | _init_repo(tmp_path) |
| 583 | bundle = self._minimal_bundle({"src/main.py": "b" * 64}) |
| 584 | result = apply_pack(tmp_path, bundle) |
| 585 | assert result["snapshots_written"] == 1 |
| 586 | |
| 587 | def test_100_malicious_keys_all_skipped(self, tmp_path: pathlib.Path) -> None: |
| 588 | """Stress: 100 bundles each with a traversal key — all must be rejected.""" |
| 589 | _init_repo(tmp_path) |
| 590 | skipped = 0 |
| 591 | for i in range(100): |
| 592 | manifest: Manifest = {f"../../evil_{i}": "a" * 64} |
| 593 | bundle = self._minimal_bundle(manifest) |
| 594 | result = apply_pack(tmp_path, bundle) |
| 595 | skipped += result["snapshots_written"] |
| 596 | assert skipped == 0 |
| 597 | |
| 598 | def test_malicious_object_id_in_pack_rejected(self, tmp_path: pathlib.Path) -> None: |
| 599 | """An object payload with a non-hex 'object_id' must be rejected by write_object.""" |
| 600 | _init_repo(tmp_path) |
| 601 | from muse.core.pack import ObjectPayload |
| 602 | bad_obj = ObjectPayload(object_id="../../etc/evil", content=b"payload") |
| 603 | bundle = PackBundle( |
| 604 | commits=[], snapshots=[], objects=[bad_obj], tags=[], branch_heads={} |
| 605 | ) |
| 606 | result = apply_pack(tmp_path, bundle) |
| 607 | # The object must be skipped (write_object raises ValueError on bad ID). |
| 608 | assert result["objects_written"] == 0 |
| 609 | |
| 610 | def test_unpack_objects_core_with_traversal_manifest( |
| 611 | self, tmp_path: pathlib.Path |
| 612 | ) -> None: |
| 613 | """Core apply_pack rejects traversal manifest keys from any bundle source.""" |
| 614 | _init_repo(tmp_path) |
| 615 | bundle = self._minimal_bundle({"../../evil": "a" * 64}) |
| 616 | result = apply_pack(tmp_path, bundle) |
| 617 | # The traversal manifest key must cause the snapshot to be skipped. |
| 618 | assert result["snapshots_written"] == 0 |
| 619 | |
| 620 | |
| 621 | # =========================================================================== |
| 622 | # 9. Integration: full plumbing pipeline with adversarial inputs |
| 623 | # =========================================================================== |
| 624 | |
| 625 | |
| 626 | class TestEndToEndAdversarial: |
| 627 | def test_hash_object_write_then_ls_files(self, tmp_path: pathlib.Path) -> None: |
| 628 | """Write a real object, commit it, list it — no traversal at any step.""" |
| 629 | _init_repo(tmp_path) |
| 630 | f = tmp_path / "song.mid" |
| 631 | f.write_bytes(b"\x00" * 128) # synthetic MIDI-like content |
| 632 | result = runner.invoke( |
| 633 | cli, ["hash-object", "--write", str(f)], |
| 634 | env=_env(tmp_path), |
| 635 | ) |
| 636 | assert result.exit_code == 0 |
| 637 | |
| 638 | def test_check_attr_stdin_mixed_good_and_bad(self, tmp_path: pathlib.Path) -> None: |
| 639 | """Mixed stdin with one traversal path must reject the whole batch cleanly.""" |
| 640 | _init_repo(tmp_path) |
| 641 | (tmp_path / ".museattributes").write_text( |
| 642 | '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n' |
| 643 | 'strategy = "auto"\ncomment = ""\n', |
| 644 | encoding="utf-8", |
| 645 | ) |
| 646 | mixed_stdin = "tracks/good.mid\n../../../etc/passwd\ntracks/also_good.mid\n" |
| 647 | result = runner.invoke( |
| 648 | cli, ["check-attr", "--stdin"], |
| 649 | input=mixed_stdin, |
| 650 | env=_env(tmp_path), |
| 651 | ) |
| 652 | # The batch must be rejected as soon as the bad path is encountered. |
| 653 | assert result.exit_code != 0 |
| 654 | |
| 655 | def test_no_sensitive_data_in_error_output(self, tmp_path: pathlib.Path) -> None: |
| 656 | """Error messages for traversal attempts must not echo the full attack string.""" |
| 657 | _init_repo(tmp_path) |
| 658 | (tmp_path / ".museattributes").write_text( |
| 659 | '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n' |
| 660 | 'strategy = "auto"\ncomment = ""\n', |
| 661 | encoding="utf-8", |
| 662 | ) |
| 663 | attack = "../../../etc/passwd" |
| 664 | result = runner.invoke( |
| 665 | cli, ["check-attr", attack], |
| 666 | env=_env(tmp_path), |
| 667 | ) |
| 668 | assert result.exit_code != 0 |
| 669 | # The error output must not contain raw control sequences or leak |
| 670 | # system paths (the path is echoed, but sanitize_display must strip it). |
| 671 | assert "\x1b" not in result.output |
File History
5 commits
sha256:660fcac1df3ab28f61862e961890bd2ca8b754fa0242079d93ca1e25037ec8a6
chore(tests): add docstring to tests/__init__.py so rc14 tr…
Human
26 days ago
sha256:d8316ffae901be06347e16ab55be11868eb519dd16ade3e8aa16a99e662f7e62
baseline: rc14 re-baseline after rc3 store corruption recovery
Human
patch
26 days ago
sha256:50d413a635f57761c3fce1f70251b957b6423821525bf330747ef4007339222e
Merge branch 'dev' into main
Human
29 days ago
sha256:fb67fed5a4d3e40de84bdd163de94ef1386570bef1dd1a020a732c8a038962ce
Merge branch 'dev' into main
Human
48 days ago
sha256:1c4b3e3a9a1f300774c3ee662b572a698d5fd405bf765a71e6011a2e9c3eaaaa
feat: Muse — version control for the agent era
Human
100 days ago