gabriel / muse public
test_security_path_traversal.py python
672 lines 26.4 KB
Raw
sha256:88ac91129873e6a496e9189515aa690eb893ae25d69c8f72af141a2be5068eb3 docs: docstring sprint contract→find-symbol — idiomatic run… Sonnet 4.6 patch 138 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_mpack / 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 MPackBundle, apply_mpack
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, long_id
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 data["object_id"].startswith("sha256:")
240 assert len(data["object_id"]) == 71
241
242 def test_symlink_to_regular_file_accepted(self, tmp_path: pathlib.Path) -> None:
243 """Symlinks to regular files are followed — consistent with git hash-object."""
244 real = tmp_path / "real.txt"
245 real.write_bytes(b"real content")
246 link = tmp_path / "link.txt"
247 link.symlink_to(real)
248 result = runner.invoke(cli, ["hash-object", str(link)])
249 # By design: hash-object follows symlinks to regular files.
250 assert result.exit_code == 0
251
252 def test_symlink_to_nonexistent_rejected(self, tmp_path: pathlib.Path) -> None:
253 link = tmp_path / "dangling.txt"
254 link.symlink_to(tmp_path / "ghost.txt")
255 result = runner.invoke(cli, ["hash-object", str(link)])
256 assert result.exit_code != 0
257
258 def test_very_long_path_rejected(self, tmp_path: pathlib.Path) -> None:
259 """A 100 000-char path argument must not stack-overflow — it simply won't exist."""
260 long_path = str(tmp_path) + "/" + "a" * 100_000
261 result = runner.invoke(cli, ["hash-object", long_path])
262 # The file doesn't exist so exit code is non-zero — no crash.
263 assert result.exit_code != 0
264 assert "exit_code" not in result.output # no Python traceback leaked
265
266 def test_write_stores_object_in_repo(self, tmp_path: pathlib.Path) -> None:
267 _init_repo(tmp_path)
268 f = tmp_path / "data.bin"
269 f.write_bytes(b"secret content")
270 result = runner.invoke(
271 cli, ["hash-object", "--write", str(f)],
272 env=_env(tmp_path),
273 )
274 assert result.exit_code == 0
275 data = json.loads(result.output)
276 assert data["stored"] is True
277
278 @pytest.mark.skipif(sys.platform == "win32", reason="block devices not on Windows")
279 def test_rejects_char_device(self) -> None:
280 """/dev/null is a char device — must be rejected."""
281 null_dev = pathlib.Path("/dev/null")
282 if not null_dev.exists():
283 pytest.skip("/dev/null not available")
284 result = runner.invoke(cli, ["hash-object", str(null_dev)])
285 assert result.exit_code != 0
286
287
288 # ===========================================================================
289 # 4. ls-files — prefix injection
290 # ===========================================================================
291
292
293 class TestLsFilesPrefix:
294 def test_null_byte_in_prefix_rejected(self, tmp_path: pathlib.Path) -> None:
295 _init_repo(tmp_path)
296 _make_commit(tmp_path)
297 result = runner.invoke(
298 cli, ["ls-files", "--path-prefix", "src/\x00evil"],
299 env=_env(tmp_path),
300 )
301 assert result.exit_code != 0
302
303 def test_glob_star_in_prefix_rejected(self, tmp_path: pathlib.Path) -> None:
304 _init_repo(tmp_path)
305 _make_commit(tmp_path)
306 result = runner.invoke(
307 cli, ["ls-files", "--path-prefix", "src/*.py"],
308 env=_env(tmp_path),
309 )
310 assert result.exit_code != 0
311
312 def test_clean_prefix_accepted(self, tmp_path: pathlib.Path) -> None:
313 _init_repo(tmp_path)
314 _make_commit(tmp_path)
315 result = runner.invoke(
316 cli, ["ls-files", "--path-prefix", "file_"],
317 env=_env(tmp_path),
318 )
319 assert result.exit_code == 0
320
321 def test_empty_prefix_returns_all(self, tmp_path: pathlib.Path) -> None:
322 _init_repo(tmp_path)
323 _make_commit(tmp_path)
324 result = runner.invoke(
325 cli, ["ls-files", "--path-prefix", ""],
326 env=_env(tmp_path),
327 )
328 # Empty prefix is valid and returns all files.
329 assert result.exit_code == 0
330
331
332 # ===========================================================================
333 # 5. check-attr — traversal, null bytes, absolute paths, CRLF stdin
334 # ===========================================================================
335
336
337 class TestCheckAttrSecurity:
338 def _repo_with_attrs(self, root: pathlib.Path) -> pathlib.Path:
339 _init_repo(root)
340 (root / ".museattributes").write_text(
341 '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n'
342 'strategy = "auto"\ncomment = ""\n',
343 encoding="utf-8",
344 )
345 return root
346
347 def test_traversal_path_rejected(self, tmp_path: pathlib.Path) -> None:
348 self._repo_with_attrs(tmp_path)
349 result = runner.invoke(
350 cli, ["check-attr", "../../../etc/passwd"],
351 env=_env(tmp_path),
352 )
353 assert result.exit_code != 0
354 out = result.output
355 assert "traversal" in out.lower() or "invalid" in out.lower()
356
357 def test_null_byte_path_rejected(self, tmp_path: pathlib.Path) -> None:
358 self._repo_with_attrs(tmp_path)
359 result = runner.invoke(
360 cli, ["check-attr", "foo\x00../../etc/passwd"],
361 env=_env(tmp_path),
362 )
363 assert result.exit_code != 0
364
365 def test_absolute_path_rejected(self, tmp_path: pathlib.Path) -> None:
366 self._repo_with_attrs(tmp_path)
367 result = runner.invoke(
368 cli, ["check-attr", "/etc/passwd"],
369 env=_env(tmp_path),
370 )
371 assert result.exit_code != 0
372
373 def test_ansi_escape_in_path_rejected(self, tmp_path: pathlib.Path) -> None:
374 """ESC[31m in a path argument must be rejected before it reaches output."""
375 self._repo_with_attrs(tmp_path)
376 result = runner.invoke(
377 cli, ["check-attr", "\x1b[31mevil\x1b[0m"],
378 env=_env(tmp_path),
379 )
380 assert result.exit_code != 0
381
382 def test_valid_path_accepted(self, tmp_path: pathlib.Path) -> None:
383 self._repo_with_attrs(tmp_path)
384 result = runner.invoke(
385 cli, ["check-attr", "tracks/drums.mid"],
386 env=_env(tmp_path),
387 )
388 assert result.exit_code == 0
389
390 def test_very_long_path_rejected(self, tmp_path: pathlib.Path) -> None:
391 self._repo_with_attrs(tmp_path)
392 long_path = "a/" * 2500 # > 4096 chars
393 result = runner.invoke(
394 cli, ["check-attr", long_path],
395 env=_env(tmp_path),
396 )
397 assert result.exit_code != 0
398
399 def test_crlf_stdin_stripped(self, tmp_path: pathlib.Path) -> None:
400 """CRLF-terminated stdin lines must not embed \\r in path strings."""
401 self._repo_with_attrs(tmp_path)
402 # "tracks/ok.mid\r\n" — the \\r must be stripped before path use.
403 crlf_input = "tracks/ok.mid\r\n"
404 result = runner.invoke(
405 cli, ["check-attr", "--stdin"],
406 input=crlf_input,
407 env=_env(tmp_path),
408 )
409 assert result.exit_code == 0
410 # The path in output must not contain \\r.
411 assert "\r" not in result.output
412
413 def test_10k_paths_stress(self, tmp_path: pathlib.Path) -> None:
414 """10 000 valid paths must be processed without crash or timeout."""
415 self._repo_with_attrs(tmp_path)
416 paths = [f"track_{i:05d}.mid" for i in range(10_000)]
417 stdin_data = "\n".join(paths)
418 result = runner.invoke(
419 cli, ["check-attr", "--stdin"],
420 input=stdin_data,
421 env=_env(tmp_path),
422 )
423 assert result.exit_code == 0
424
425
426 # ===========================================================================
427 # 6. check-ignore — same surface as check-attr
428 # ===========================================================================
429
430
431 class TestCheckIgnoreSecurity:
432 def _repo(self, root: pathlib.Path) -> pathlib.Path:
433 _init_repo(root)
434 # .museignore is TOML format — not a gitignore-style file.
435 (root / ".museignore").write_text(
436 '[global]\npatterns = ["build/", "*.bin"]\n',
437 encoding="utf-8",
438 )
439 return root
440
441 def test_traversal_path_rejected(self, tmp_path: pathlib.Path) -> None:
442 self._repo(tmp_path)
443 result = runner.invoke(
444 cli, ["check-ignore", "../../../etc/passwd"],
445 env=_env(tmp_path),
446 )
447 assert result.exit_code != 0
448
449 def test_null_byte_path_rejected(self, tmp_path: pathlib.Path) -> None:
450 self._repo(tmp_path)
451 result = runner.invoke(
452 cli, ["check-ignore", "build/\x00../../etc/cron.d/evil"],
453 env=_env(tmp_path),
454 )
455 assert result.exit_code != 0
456
457 def test_absolute_path_rejected(self, tmp_path: pathlib.Path) -> None:
458 self._repo(tmp_path)
459 result = runner.invoke(
460 cli, ["check-ignore", "/absolute/path"],
461 env=_env(tmp_path),
462 )
463 assert result.exit_code != 0
464
465 def test_valid_path_accepted(self, tmp_path: pathlib.Path) -> None:
466 self._repo(tmp_path)
467 result = runner.invoke(
468 cli, ["check-ignore", "build/output.bin"],
469 env=_env(tmp_path),
470 )
471 assert result.exit_code == 0
472
473 def test_crlf_stdin_does_not_embed_cr(self, tmp_path: pathlib.Path) -> None:
474 self._repo(tmp_path)
475 crlf = "build/out.bin\r\n"
476 result = runner.invoke(
477 cli, ["check-ignore", "--stdin"],
478 input=crlf,
479 env=_env(tmp_path),
480 )
481 assert result.exit_code == 0
482 assert "\r" not in result.output
483
484 def test_dotdot_in_middle_rejected(self, tmp_path: pathlib.Path) -> None:
485 self._repo(tmp_path)
486 result = runner.invoke(
487 cli, ["check-ignore", "build/../../../etc/shadow"],
488 env=_env(tmp_path),
489 )
490 assert result.exit_code != 0
491
492
493 # ===========================================================================
494 # 7. verify-object --stdin — CRLF line endings
495 # ===========================================================================
496
497
498 class TestVerifyObjectStdinCRLF:
499 def test_crlf_id_rejected_cleanly(self, tmp_path: pathlib.Path) -> None:
500 """A CRLF-terminated object ID must produce a clear error, not a crash."""
501 _init_repo(tmp_path)
502 content = b"test content"
503 import hashlib
504 oid = long_id(hashlib.sha256(content).hexdigest())
505 write_object(tmp_path, oid, content)
506
507 # Pass the ID with a trailing \\r before the newline.
508 crlf_input = oid + "\r\n"
509 result = runner.invoke(
510 cli, ["verify-object", "--stdin"],
511 input=crlf_input,
512 env=_env(tmp_path),
513 )
514 # After the fix: \\r is stripped, so the ID is valid and the object passes.
515 assert result.exit_code == 0
516
517 def test_lf_only_works(self, tmp_path: pathlib.Path) -> None:
518 _init_repo(tmp_path)
519 content = b"lf content"
520 import hashlib
521 oid = long_id(hashlib.sha256(content).hexdigest())
522 write_object(tmp_path, oid, content)
523
524 result = runner.invoke(
525 cli, ["verify-object", "--stdin"],
526 input=oid + "\n",
527 env=_env(tmp_path),
528 )
529 assert result.exit_code == 0
530
531
532 # ===========================================================================
533 # 8. apply_mpack / unpack-objects — zip-slip via manifest keys
534 # ===========================================================================
535
536
537 class TestPackZipSlip:
538 def _minimal_bundle(self, manifest: Manifest) -> MPackBundle:
539 snap_id = compute_snapshot_id(manifest)
540 snap_dict: SnapshotDict = {
541 "snapshot_id": snap_id,
542 "manifest": manifest,
543 "created_at": "2026-01-01T00:00:00+00:00",
544 }
545 return MPackBundle(
546 commits=[],
547 snapshots=[snap_dict],
548 objects=[],
549 tags=[],
550 branch_heads={},
551 )
552
553 def test_traversal_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None:
554 """apply_mpack must reject manifests with ../../ traversal keys."""
555 _init_repo(tmp_path)
556 bundle = self._minimal_bundle({"../../etc/cron.d/evil": "a" * 64})
557 result = apply_mpack(tmp_path, bundle)
558 # The snapshot must be skipped — not written.
559 assert result["snapshots_written"] == 0
560
561 def test_absolute_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None:
562 """Manifest keys starting with / must be rejected."""
563 _init_repo(tmp_path)
564 bundle = self._minimal_bundle({"/etc/passwd": "a" * 64})
565 result = apply_mpack(tmp_path, bundle)
566 assert result["snapshots_written"] == 0
567
568 def test_null_byte_key_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None:
569 _init_repo(tmp_path)
570 bundle = self._minimal_bundle({"tracks/\x00evil": "a" * 64})
571 result = apply_mpack(tmp_path, bundle)
572 assert result["snapshots_written"] == 0
573
574 def test_invalid_object_id_in_manifest_rejected(self, tmp_path: pathlib.Path) -> None:
575 """Manifest values must be valid 64-hex object IDs."""
576 _init_repo(tmp_path)
577 bundle = self._minimal_bundle({"file.py": "not-a-valid-oid"})
578 result = apply_mpack(tmp_path, bundle)
579 assert result["snapshots_written"] == 0
580
581 def test_clean_manifest_written(self, tmp_path: pathlib.Path) -> None:
582 """A manifest with valid keys and IDs must be written successfully."""
583 _init_repo(tmp_path)
584 bundle = self._minimal_bundle({"src/main.py": long_id("b" * 64)})
585 result = apply_mpack(tmp_path, bundle)
586 assert result["snapshots_written"] == 1
587
588 def test_100_malicious_keys_all_skipped(self, tmp_path: pathlib.Path) -> None:
589 """Stress: 100 bundles each with a traversal key — all must be rejected."""
590 _init_repo(tmp_path)
591 skipped = 0
592 for i in range(100):
593 manifest: Manifest = {f"../../evil_{i}": "a" * 64}
594 bundle = self._minimal_bundle(manifest)
595 result = apply_mpack(tmp_path, bundle)
596 skipped += result["snapshots_written"]
597 assert skipped == 0
598
599 def test_malicious_object_id_in_pack_rejected(self, tmp_path: pathlib.Path) -> None:
600 """An object payload with a non-hex 'object_id' must be rejected by write_object."""
601 _init_repo(tmp_path)
602 from muse.core.pack import ObjectPayload
603 bad_obj = ObjectPayload(object_id="../../etc/evil", content=b"payload")
604 bundle = MPackBundle(
605 commits=[], snapshots=[], objects=[bad_obj], tags=[], branch_heads={}
606 )
607 result = apply_mpack(tmp_path, bundle)
608 # The object must be skipped (write_object raises ValueError on bad ID).
609 assert result["objects_written"] == 0
610
611 def test_unpack_objects_core_with_traversal_manifest(
612 self, tmp_path: pathlib.Path
613 ) -> None:
614 """Core apply_mpack rejects traversal manifest keys from any bundle source."""
615 _init_repo(tmp_path)
616 bundle = self._minimal_bundle({"../../evil": "a" * 64})
617 result = apply_mpack(tmp_path, bundle)
618 # The traversal manifest key must cause the snapshot to be skipped.
619 assert result["snapshots_written"] == 0
620
621
622 # ===========================================================================
623 # 9. Integration: full pipeline with adversarial inputs
624 # ===========================================================================
625
626
627 class TestEndToEndAdversarial:
628 def test_hash_object_write_then_ls_files(self, tmp_path: pathlib.Path) -> None:
629 """Write a real object, commit it, list it — no traversal at any step."""
630 _init_repo(tmp_path)
631 f = tmp_path / "song.mid"
632 f.write_bytes(b"\x00" * 128) # synthetic MIDI-like content
633 result = runner.invoke(
634 cli, ["hash-object", "--write", str(f)],
635 env=_env(tmp_path),
636 )
637 assert result.exit_code == 0
638
639 def test_check_attr_stdin_mixed_good_and_bad(self, tmp_path: pathlib.Path) -> None:
640 """Mixed stdin with one traversal path must reject the whole batch cleanly."""
641 _init_repo(tmp_path)
642 (tmp_path / ".museattributes").write_text(
643 '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n'
644 'strategy = "auto"\ncomment = ""\n',
645 encoding="utf-8",
646 )
647 mixed_stdin = "tracks/good.mid\n../../../etc/passwd\ntracks/also_good.mid\n"
648 result = runner.invoke(
649 cli, ["check-attr", "--stdin"],
650 input=mixed_stdin,
651 env=_env(tmp_path),
652 )
653 # The batch must be rejected as soon as the bad path is encountered.
654 assert result.exit_code != 0
655
656 def test_no_sensitive_data_in_error_output(self, tmp_path: pathlib.Path) -> None:
657 """Error messages for traversal attempts must not echo the full attack string."""
658 _init_repo(tmp_path)
659 (tmp_path / ".museattributes").write_text(
660 '[rules]\n[[rules.entries]]\npath_pattern = "*"\ndimension = "*"\n'
661 'strategy = "auto"\ncomment = ""\n',
662 encoding="utf-8",
663 )
664 attack = "../../../etc/passwd"
665 result = runner.invoke(
666 cli, ["check-attr", attack],
667 env=_env(tmp_path),
668 )
669 assert result.exit_code != 0
670 # The error output must not contain raw control sequences or leak
671 # system paths (the path is echoed, but sanitize_display must strip it).
672 assert "\x1b" not in result.output
File History 2 commits
sha256:88ac91129873e6a496e9189515aa690eb893ae25d69c8f72af141a2be5068eb3 docs: docstring sprint contract→find-symbol — idiomatic run… Sonnet 4.6 patch 138 days ago
sha256:a09b1b4f6838754495547f200aa0ce88e2f56ffc5b20b900f6f0cff2c3cdede9 fix(cursorignore): remove git-ism (.git/worktrees) Human minor 141 days ago