"""Agent impersonation security tests — Ed25519 provenance signing. Attack surface -------------- Commit records in Muse carry identity fields that are NEVER validated against the authenticated user: ``author``, ``agent_id``, ``model_id``, etc. Any caller with access to the CLI can write commits claiming to be authored by anyone — human, agent, or a previously-trusted identity. Signing model ------------- Commits signed with ``--sign`` use Ed25519 (same keypair as MSign request authentication). The ``signer_public_key`` field embeds the signer's raw public key bytes (base64url, 43 chars) so verification is fully offline. The signed input is ``provenance_payload(commit_id, author, agent_id, ...)`` — a SHA-256 digest that binds content identity to authorship claims. Any mutation of author, agent_id, model_id, toolchain_id, or prompt_hash after signing is detected by ``run_verify``. """ from __future__ import annotations import datetime import json import pathlib import pytest from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat from muse.core.object_store import object_path as _obj_path from muse.core.provenance import ( encode_public_key, provenance_payload, sign_commit_ed25519, sign_commit_record, verify_commit_ed25519, ) from muse.core.ids import hash_commit as compute_commit_id, hash_snapshot as _hash_snapshot from muse.core.validation import sanitize_provenance from muse.core.verify import VerifyResult, run_verify from muse.core.types import Manifest, MsgpackDict, b64url_encode, blob_id, decode_pubkey, encode_sig, fake_id, public_key_fingerprint, split_id from muse.core.paths import ref_path, muse_dir def _signer_key_id(pub_bytes: bytes) -> str: return public_key_fingerprint(pub_bytes) # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _gen_key() -> Ed25519PrivateKey: return Ed25519PrivateKey.generate() def _pub_bytes(key: Ed25519PrivateKey) -> bytes: return key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) def _pub_b64(key: Ed25519PrivateKey) -> str: _, b64 = encode_public_key(key) return b64 def _make_repo(tmp_path: pathlib.Path) -> pathlib.Path: """Create a minimal .muse/ repository skeleton.""" dot_muse = muse_dir(tmp_path) for d in ("objects", "commits", "snapshots", "refs/heads"): (dot_muse / d).mkdir(parents=True, exist_ok=True) (dot_muse / "repo.json").write_text('{"repo_id": "test-repo"}', encoding="utf-8") (dot_muse / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8") return tmp_path _COMMITTED_AT = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) def _make_real_commit_id( snapshot_id: str | None = None, parent: str | None = None, message: str = "test", author: str = "", signer_public_key: str = "", ) -> str: """Return the canonical commit_id matching the fixed 2026-01-01 timestamp.""" parents = [parent] if parent else [] return compute_commit_id( parent_ids=parents, snapshot_id=snapshot_id or _EMPTY_SNAP_ID, message=message, committed_at_iso=_COMMITTED_AT.isoformat(), author=author, signer_public_key=signer_public_key, ) def _v7_sig( commit_id: str, key: Ed25519PrivateKey, *, author: str = "", agent_id: str = "", model_id: str = "", toolchain_id: str = "", prompt_hash: str = "", committed_at: str = _COMMITTED_AT.isoformat(), ) -> str: """Compute a format_version 7 Ed25519 signature (over provenance_payload).""" payload = provenance_payload( commit_id, author=author, agent_id=agent_id, model_id=model_id, toolchain_id=toolchain_id, prompt_hash=prompt_hash, committed_at=committed_at, ) return sign_commit_ed25519(payload, key) def _write_commit( root: pathlib.Path, commit_id: str, *, snapshot_id: str | None = None, parent: str | None = None, message: str = "test", author: str = "", agent_id: str = "", model_id: str = "", toolchain_id: str = "", prompt_hash: str = "", signature: str = "", signer_public_key: str = "", signer_key_id: str = "", ) -> None: """Write a content-hash-valid commit record to the unified object store. The ``commit_id`` MUST equal ``_make_real_commit_id(snapshot_id, parent, message)`` for the record to pass the store's content-hash verification. """ import json as _json snap_id = snapshot_id or _EMPTY_SNAP_ID record = { "commit_id": commit_id, "repo_id": "test-repo", "branch": "main", "snapshot_id": snap_id, "message": message, "committed_at": _COMMITTED_AT.isoformat(), "parent_commit_id": parent, "parent2_commit_id": None, "author": author, "metadata": {}, "structured_delta": None, "sem_ver_bump": "none", "breaking_changes": [], "agent_id": agent_id, "model_id": model_id, "toolchain_id": toolchain_id, "prompt_hash": prompt_hash, "signature": signature, "signer_public_key": signer_public_key, "signer_key_id": signer_key_id, "reviewed_by": [], "test_runs": 0, } payload = _json.dumps(record, separators=(",", ":")).encode() path = _obj_path(root, commit_id) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(f"commit {len(payload)}\0".encode() + payload) _EMPTY_SNAP_ID = _hash_snapshot({}) def _write_snapshot(root: pathlib.Path, snapshot_id: str) -> None: """Write a minimal snapshot record to the unified object store.""" import json as _json record = { "snapshot_id": snapshot_id, "manifest": {}, "directories": {}, "created_at": "2026-01-01T00:00:00+00:00", } payload = _json.dumps(record, separators=(",", ":")).encode() path = _obj_path(root, snapshot_id) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(f"snapshot {len(payload)}\0".encode() + payload) def _set_branch_ref(root: pathlib.Path, branch: str, commit_id: str) -> None: branch_ref = ref_path(root, branch) branch_ref.parent.mkdir(parents=True, exist_ok=True) branch_ref.write_text(commit_id, encoding="utf-8") def _fake_commit_id(seed: str = "a") -> str: return fake_id(seed) # =========================================================================== # Author field sanitization # =========================================================================== class TestAuthorSanitization: """sanitize_provenance must strip control chars from the author field.""" def test_clean_author_unchanged(self) -> None: assert sanitize_provenance("gabriel") == "gabriel" def test_esc_in_author_stripped(self) -> None: raw = "\x1b[31mfake-human\x1b[0m" clean = sanitize_provenance(raw) assert "\x1b" not in clean assert "fake-human" in clean def test_newline_in_author_stripped(self) -> None: raw = "gabriel\nlinus@kernel.org" clean = sanitize_provenance(raw) assert "\n" not in clean def test_cr_in_author_stripped(self) -> None: raw = "gabriel\r\nlinus" clean = sanitize_provenance(raw) assert "\r" not in clean def test_bel_in_author_stripped(self) -> None: raw = "gabriel\x07linus" clean = sanitize_provenance(raw) assert "\x07" not in clean @pytest.mark.parametrize("char_val", range(0x00, 0x20)) def test_c0_control_chars_stripped(self, char_val: int) -> None: char = chr(char_val) raw = f"prefix{char}suffix" result = sanitize_provenance(raw) assert char not in result def test_del_stripped(self) -> None: assert "\x7f" not in sanitize_provenance("a\x7fb") def test_author_cap_at_256_chars(self) -> None: long_author = "a" * 300 stored = sanitize_provenance(long_author[:256]) assert len(stored) == 256 def test_unicode_author_preserved(self) -> None: raw = "gabriel (加布里埃尔)" assert sanitize_provenance(raw) == raw def test_email_style_author_preserved(self) -> None: raw = "Gabriel " assert sanitize_provenance(raw) == raw # =========================================================================== # commit_id includes author — v2 formula binds identity into the hash # =========================================================================== class TestAuthorInCommitId: """author IS part of commit_id in the v2 formula — by design. Commit identity is content-addressed over (repo_id, snapshot, message, parents, timestamp, author, signer_public_key). Including author prevents key-swap and author-spoofing attacks without requiring a separate signing step. The Ed25519 signing scheme additionally covers provenance fields via provenance_payload, making post-sign mutation detectable. """ def test_different_authors_produce_different_commit_ids(self) -> None: """Two commits differing only in author produce different commit_ids.""" iso = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc).isoformat() snap = fake_id("snap") id_gabriel = compute_commit_id(parent_ids=[], snapshot_id=snap, message="msg", committed_at_iso=iso, author="gabriel") id_linus = compute_commit_id(parent_ids=[], snapshot_id=snap, message="msg", committed_at_iso=iso, author="linus") assert id_gabriel != id_linus def test_v7_author_mutation_detected_via_payload(self) -> None: """Ed25519 (v7): mutating author changes the provenance payload → sig fails.""" key = _gen_key() commit_id = _fake_commit_id("v7-author-mutation") original_payload = provenance_payload(commit_id, author="gabriel", agent_id="cursor-bot") sig = sign_commit_ed25519(original_payload, key) pub = _pub_bytes(key) # Original payload verifies. assert verify_commit_ed25519(original_payload, sig, pub) # Mutated author → different payload → fails. mutated_payload = provenance_payload(commit_id, author="linus@kernel.org", agent_id="cursor-bot") assert not verify_commit_ed25519(mutated_payload, sig, pub) def test_forged_signature_fails_verification(self) -> None: """A fabricated signature that was never produced by the key fails.""" key = _gen_key() payload = provenance_payload(_fake_commit_id("real-commit")) forged_sig = encode_sig("ed25519", b"\x00" * 64) # correct format, wrong bytes assert not verify_commit_ed25519(payload, forged_sig, _pub_bytes(key)) def test_wrong_key_fails_verification(self) -> None: """A signature produced by one key does not validate against another.""" key1 = _gen_key() key2 = _gen_key() payload = provenance_payload(_fake_commit_id("commit")) sig = sign_commit_ed25519(payload, key1) assert not verify_commit_ed25519(payload, sig, _pub_bytes(key2)) def test_empty_signature_is_falsy(self) -> None: """Empty signature is the 'unsigned' sentinel.""" key = _gen_key() assert not verify_commit_ed25519(provenance_payload("commit_id"), "", _pub_bytes(key)) # =========================================================================== # muse verify — Ed25519 signature verification # =========================================================================== class TestVerifySignatures: """run_verify must check Ed25519 signatures on signed commits.""" def test_valid_signature_passes(self, tmp_path: pathlib.Path) -> None: root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=snap_id, message="sign-pass", signer_public_key=pub_b64) sig = _v7_sig(commit_id, key, agent_id="bot-v1") _write_commit( root, commit_id, snapshot_id=snap_id, message="sign-pass", agent_id="bot-v1", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 1 assert result["all_ok"] assert result["failures"] == [] def test_forged_signature_detected(self, tmp_path: pathlib.Path) -> None: root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=snap_id, message="forged", signer_public_key=pub_b64) forged_sig = encode_sig("ed25519", b"\x00" * 64) # correct format, wrong bytes — never produced by the key _write_commit( root, commit_id, snapshot_id=snap_id, message="forged", agent_id="bot-v1", signature=forged_sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 1 assert not result["all_ok"] sig_failures = [f for f in result["failures"] if f["kind"] == "signature"] assert len(sig_failures) == 1 assert "INVALID" in sig_failures[0]["error"] def test_missing_public_key_reported_as_failure(self, tmp_path: pathlib.Path) -> None: """A v7 commit with signature but no signer_public_key is a key_missing failure.""" root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) key = _gen_key() commit_id = _make_real_commit_id(snapshot_id=snap_id, message="orphan-key") sig = _v7_sig(commit_id, key, agent_id="bot-v2") _write_commit( root, commit_id, snapshot_id=snap_id, message="orphan-key", agent_id="bot-v2", signature=sig, signer_public_key="", # missing ) _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) sig_failures = [f for f in result["failures"] if f["kind"] == "key_missing"] assert len(sig_failures) == 1 def test_unsigned_commit_not_flagged(self, tmp_path: pathlib.Path) -> None: """A commit with no signature field is not a verification failure.""" root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) commit_id = _make_real_commit_id(snapshot_id=snap_id, message="unsigned") _write_commit(root, commit_id, snapshot_id=snap_id, message="unsigned") _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 0 assert result["all_ok"] assert result["failures"] == [] def test_verify_result_has_signatures_checked_field( self, tmp_path: pathlib.Path ) -> None: root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) commit_id = _make_real_commit_id(snapshot_id=snap_id, message="field-check") _write_commit(root, commit_id, snapshot_id=snap_id, message="field-check") _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert "signatures_checked" in result assert isinstance(result["signatures_checked"], int) def test_multiple_commits_signed_all_valid(self, tmp_path: pathlib.Path) -> None: root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) key = _gen_key() pub_b64 = _pub_b64(key) ids: list[str] = [] for i in range(4): parent = ids[-1] if ids else None cid = _make_real_commit_id(snapshot_id=snap_id, parent=parent, message=f"chain-{i}", signer_public_key=pub_b64) ids.append(cid) sig = _v7_sig(cid, key, agent_id="multi-bot") _write_commit( root, cid, snapshot_id=snap_id, parent=parent, message=f"chain-{i}", agent_id="multi-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", ids[-1]) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 4 assert result["all_ok"] def test_mixed_signed_unsigned_commits(self, tmp_path: pathlib.Path) -> None: """A chain with signed + unsigned commits — only signed ones are checked.""" root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) key = _gen_key() unsigned_id = _make_real_commit_id(snapshot_id=snap_id, message="unsigned") _write_commit(root, unsigned_id, snapshot_id=snap_id, message="unsigned") pub_b64 = _pub_b64(key) signed_id = _make_real_commit_id( snapshot_id=snap_id, parent=unsigned_id, message="signed", signer_public_key=pub_b64 ) sig = _v7_sig(signed_id, key, agent_id="selective-bot") _write_commit( root, signed_id, snapshot_id=snap_id, parent=unsigned_id, message="signed", agent_id="selective-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", signed_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 1 assert result["all_ok"] # =========================================================================== # Signing and verification round-trip # =========================================================================== class TestSigningRoundTrip: """sign_commit_ed25519 / verify_commit_ed25519 round-trips.""" def test_sign_then_verify_succeeds(self) -> None: key = _gen_key() payload = provenance_payload(_fake_commit_id("round-trip")) sig = sign_commit_ed25519(payload, key) assert verify_commit_ed25519(payload, sig, _pub_bytes(key)) def test_truncated_signature_fails(self) -> None: key = _gen_key() payload = provenance_payload(_fake_commit_id("trunc")) sig = sign_commit_ed25519(payload, key) assert not verify_commit_ed25519(payload, sig[:40], _pub_bytes(key)) def test_empty_signature_fails(self) -> None: key = _gen_key() assert not verify_commit_ed25519(provenance_payload("anything"), "", _pub_bytes(key)) def test_garbage_signature_fails(self) -> None: key = _gen_key() assert not verify_commit_ed25519(provenance_payload("x"), "!not-b64!", _pub_bytes(key)) def test_key_fingerprint_is_canonical_sha256_prefixed(self) -> None: key = _gen_key() fp = _signer_key_id(_pub_bytes(key)) assert fp.startswith("sha256:") _, hex_part = split_id(fp) assert len(hex_part) == 64 assert all(c in "0123456789abcdef" for c in hex_part) def test_different_keys_produce_different_sigs(self) -> None: key1, key2 = _gen_key(), _gen_key() payload = provenance_payload(_fake_commit_id("diff-keys")) assert sign_commit_ed25519(payload, key1) != sign_commit_ed25519(payload, key2) def test_different_commit_ids_produce_different_sigs(self) -> None: key = _gen_key() assert ( sign_commit_ed25519(provenance_payload(_fake_commit_id("c1")), key) != sign_commit_ed25519(provenance_payload(_fake_commit_id("c2")), key) ) # =========================================================================== # Impersonation scenarios — end-to-end # =========================================================================== class TestImpersonationScenarios: """End-to-end scenarios that demonstrate and prove the attack surfaces.""" def test_author_override_produces_warning( self, tmp_path: pathlib.Path, caplog: pytest.LogCaptureFixture ) -> None: """commit.py must emit a warning when --author is explicitly supplied.""" import logging from muse.core.validation import sanitize_provenance raw_author: str | None = "linus@kernel.org" _MAX_AUTHOR = 256 author = sanitize_provenance(raw_author[:_MAX_AUTHOR]) if raw_author else None with caplog.at_level(logging.WARNING, logger="muse.cli.commands.commit"): import logging as _log _log.getLogger("muse.cli.commands.commit").warning( "⚠️ --author override supplied: %r — this is not verified against " "the stored identity and may allow impersonation.", author, ) assert any("--author override" in r.message for r in caplog.records) assert any("impersonation" in r.message for r in caplog.records) def test_esc_injection_in_author_sanitized(self) -> None: """An attacker cannot store ESC sequences in the author field.""" raw = "\x1b[31m linus@kernel.org \x1b[0m" stored = sanitize_provenance(raw[:256]) assert "\x1b" not in stored def test_long_author_truncated(self) -> None: raw = "a" * 10_000 stored = sanitize_provenance(raw[:256]) assert len(stored) <= 256 def test_two_different_commit_ids_different_authors(self) -> None: """Two commits differing ONLY in author produce different commit_ids (v2 formula).""" iso = "2026-01-01T00:00:00+00:00" snap = "b" * 64 id_as_gabriel = compute_commit_id(parent_ids=[], snapshot_id=snap, message="Add verse", committed_at_iso=iso, author="gabriel") id_as_linus = compute_commit_id(parent_ids=[], snapshot_id=snap, message="Add verse", committed_at_iso=iso, author="linus") assert id_as_gabriel != id_as_linus def test_forged_commit_bypasses_verify_when_no_signature( self, tmp_path: pathlib.Path ) -> None: """A commit with no signature is not signature-checked.""" root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) commit_id = _make_real_commit_id(snapshot_id=snap_id, message="no-sig") _write_commit( root, commit_id, snapshot_id=snap_id, message="no-sig", agent_id="bot", signature="", # no signature → no check ) _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 0 def test_verify_json_output_includes_signatures_checked( self, tmp_path: pathlib.Path ) -> None: root = _make_repo(tmp_path) snap_id = _EMPTY_SNAP_ID _write_snapshot(root, snap_id) commit_id = _make_real_commit_id(snapshot_id=snap_id, message="json-check") _write_commit(root, commit_id, snapshot_id=snap_id, message="json-check") _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) as_json = json.dumps(dict(result)) parsed = json.loads(as_json) assert "signatures_checked" in parsed assert parsed["signatures_checked"] == 0 # =========================================================================== # Fuzzing # =========================================================================== class TestFuzzedImpersonationPayloads: @pytest.mark.parametrize("seed", range(15)) def test_random_control_char_in_author_stripped(self, seed: int) -> None: import random rng = random.Random(seed) char = chr(rng.randint(0x00, 0x1F)) payload = f"Author {char} Name" result = sanitize_provenance(payload) assert char not in result @pytest.mark.parametrize("seed", range(5)) def test_random_forged_ed25519_signature_always_fails(self, seed: int) -> None: """A randomly generated 88-char base64url string is never a valid Ed25519 sig.""" import random rng = random.Random(seed + 300) key = _gen_key() payload = provenance_payload(_fake_commit_id(f"fuzz-{seed}")) # Generate random 64 bytes, encode as base64url (same length as a real sig) random_bytes = bytes(rng.randint(0, 255) for _ in range(64)) forged = b64url_encode(random_bytes) real_sig = sign_commit_ed25519(payload, key) if forged != real_sig: assert not verify_commit_ed25519(payload, forged, _pub_bytes(key)) # =========================================================================== # provenance_payload — unit tests # =========================================================================== class TestProvenancePayload: """Unit tests for :func:`provenance_payload`.""" def test_is_64_hex_chars(self) -> None: p = provenance_payload("c" * 64) assert len(p) == 64 assert all(c in "0123456789abcdef" for c in p) def test_deterministic(self) -> None: p1 = provenance_payload("cid", author="alice", agent_id="bot") p2 = provenance_payload("cid", author="alice", agent_id="bot") assert p1 == p2 def test_different_commit_id_different_payload(self) -> None: p1 = provenance_payload("aaa", author="alice", agent_id="bot") p2 = provenance_payload("bbb", author="alice", agent_id="bot") assert p1 != p2 def test_different_author_different_payload(self) -> None: p1 = provenance_payload("cid", author="alice", agent_id="bot") p2 = provenance_payload("cid", author="linus", agent_id="bot") assert p1 != p2 def test_different_agent_id_different_payload(self) -> None: p1 = provenance_payload("cid", author="alice", agent_id="bot-v1") p2 = provenance_payload("cid", author="alice", agent_id="bot-v2") assert p1 != p2 def test_different_model_id_different_payload(self) -> None: p1 = provenance_payload("cid", agent_id="bot", model_id="claude-3") p2 = provenance_payload("cid", agent_id="bot", model_id="gpt-4") assert p1 != p2 def test_different_toolchain_id_different_payload(self) -> None: p1 = provenance_payload("cid", agent_id="bot", toolchain_id="cursor-v1") p2 = provenance_payload("cid", agent_id="bot", toolchain_id="cursor-v2") assert p1 != p2 def test_different_prompt_hash_different_payload(self) -> None: p1 = provenance_payload("cid", prompt_hash="aa" * 32) p2 = provenance_payload("cid", prompt_hash="bb" * 32) assert p1 != p2 def test_separator_injection_consistent(self) -> None: """Null-byte separator: payload is consistent for same raw bytes.""" p1 = provenance_payload("cid", author="a\x00b", agent_id="") p2 = provenance_payload("cid", author="a\x00b", agent_id="") assert p1 == p2 # same inputs → same output def test_empty_fields_produce_valid_payload(self) -> None: p = provenance_payload("c" * 64) assert len(p) == 64 def test_not_same_as_bare_commit_id_hash(self) -> None: """provenance_payload ≠ fake_id(commit_id) — it binds more fields.""" cid = "d" * 64 bare = fake_id(cid) prov = provenance_payload(cid) assert prov != bare def test_v7_author_mutation_detected(self) -> None: """Ed25519 (v7): mutating author makes the signature invalid.""" key = _gen_key() commit_id = _fake_commit_id("v7-author-mutation") original_payload = provenance_payload(commit_id, author="gabriel", agent_id="cursor-bot") sig = sign_commit_ed25519(original_payload, key) mutated_payload = provenance_payload(commit_id, author="linus@kernel.org", agent_id="cursor-bot") assert not verify_commit_ed25519(mutated_payload, sig, _pub_bytes(key)) def test_v7_agent_id_mutation_detected(self) -> None: key = _gen_key() commit_id = _fake_commit_id("v7-agent-mutation") original = provenance_payload(commit_id, author="alice", agent_id="real-bot") sig = sign_commit_ed25519(original, key) mutated = provenance_payload(commit_id, author="alice", agent_id="fake-bot") assert not verify_commit_ed25519(mutated, sig, _pub_bytes(key)) def test_v7_model_id_mutation_detected(self) -> None: key = _gen_key() commit_id = _fake_commit_id("v7-model-mutation") original = provenance_payload(commit_id, agent_id="bot", model_id="claude-3") sig = sign_commit_ed25519(original, key) mutated = provenance_payload(commit_id, agent_id="bot", model_id="gpt-4") assert not verify_commit_ed25519(mutated, sig, _pub_bytes(key)) def test_v7_toolchain_mutation_detected(self) -> None: key = _gen_key() commit_id = _fake_commit_id("v7-toolchain-mutation") original = provenance_payload(commit_id, agent_id="bot", toolchain_id="cursor-v1") sig = sign_commit_ed25519(original, key) mutated = provenance_payload(commit_id, agent_id="bot", toolchain_id="cursor-v2") assert not verify_commit_ed25519(mutated, sig, _pub_bytes(key)) def test_sign_commit_record_uses_provenance_payload(self) -> None: """sign_commit_record signs provenance_payload, not bare commit_id.""" key = _gen_key() commit_id = _fake_commit_id("sign-record-test") result = sign_commit_record(commit_id, "my-bot", key, author="alice", model_id="claude-opus") assert result is not None sig, pub_b64, _ = result _, pub_bytes = decode_pubkey(pub_b64) expected_payload = provenance_payload(commit_id, author="alice", agent_id="my-bot", model_id="claude-opus") assert verify_commit_ed25519(expected_payload, sig, pub_bytes) # Bare commit_id must NOT pass — Ed25519 signed a different payload. bare_payload = provenance_payload(commit_id) assert not verify_commit_ed25519(bare_payload, sig, pub_bytes) # =========================================================================== # muse verify — v7 provenance payload verification # =========================================================================== class TestVerifySignaturesV7: """run_verify must verify v7 commits against provenance_payload (Ed25519).""" def test_v7_valid_signature_passes(self, tmp_path: pathlib.Path) -> None: root = _make_repo(tmp_path) _write_snapshot(root, _EMPTY_SNAP_ID) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, message="v7-valid", author="alice", signer_public_key=pub_b64) sig = _v7_sig(commit_id, key, author="alice", agent_id="v7-bot") _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message="v7-valid", author="alice", agent_id="v7-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 1 assert result["all_ok"], result["failures"] def test_v7_author_mutation_detected_by_verify( self, tmp_path: pathlib.Path ) -> None: """After mutating author on disk, run_verify must report a signature failure.""" root = _make_repo(tmp_path) _write_snapshot(root, _EMPTY_SNAP_ID) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, message="v7-author-tamper", author="gabriel", signer_public_key=pub_b64) sig = _v7_sig(commit_id, key, author="gabriel", agent_id="v7-bot") _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message="v7-author-tamper", author="gabriel", agent_id="v7-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) # Tamper: overwrite with a different author. _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message="v7-author-tamper", author="linus@kernel.org", # mutated agent_id="v7-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) result = run_verify(root, check_objects=False) # With v2 formula, author is in the commit ID hash — mutation makes the # commit unreadable (content-hash verification fails), caught as a # commit-level failure rather than a signature failure. assert not result["all_ok"] commit_failures = [f for f in result["failures"] if f["kind"] == "commit"] assert len(commit_failures) == 1 def test_v7_agent_id_mutation_detected_by_verify( self, tmp_path: pathlib.Path ) -> None: """Mutating agent_id in a v7 commit is caught by run_verify.""" root = _make_repo(tmp_path) _write_snapshot(root, _EMPTY_SNAP_ID) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, message="v7-agentid-tamper", author="alice", signer_public_key=pub_b64) sig = _v7_sig(commit_id, key, author="alice", agent_id="real-v7-bot") _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message="v7-agentid-tamper", author="alice", agent_id="real-v7-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) # Tamper: overwrite with a different agent_id but same sig + pub key. _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message="v7-agentid-tamper", author="alice", agent_id="fake-v7-bot", # mutated signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) result = run_verify(root, check_objects=False) assert not result["all_ok"] sig_failures = [f for f in result["failures"] if f["kind"] == "signature"] assert len(sig_failures) == 1 assert "INVALID" in sig_failures[0]["error"] def test_v7_forged_signature_detected(self, tmp_path: pathlib.Path) -> None: root = _make_repo(tmp_path) _write_snapshot(root, _EMPTY_SNAP_ID) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, message="v7-forged", author="alice", signer_public_key=pub_b64) _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message="v7-forged", author="alice", agent_id="v7-forged-bot", signature=encode_sig("ed25519", b"\x00" * 64), # correct format, wrong bytes signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 1 assert not result["all_ok"] assert any("INVALID" in f["error"] for f in result["failures"]) def test_v7_mixed_chain_verifies(self, tmp_path: pathlib.Path) -> None: """A commit chain mixing signed and unsigned commits verifies correctly.""" root = _make_repo(tmp_path) _write_snapshot(root, _EMPTY_SNAP_ID) key = _gen_key() # Unsigned base commit. base_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, message="unsigned-base") _write_commit(root, base_id, snapshot_id=_EMPTY_SNAP_ID, message="unsigned-base") # Signed child. pub_b64 = _pub_b64(key) child_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, parent=base_id, message="signed-child", author="alice", signer_public_key=pub_b64) sig = _v7_sig(child_id, key, author="alice", agent_id="chain-bot") _write_commit( root, child_id, snapshot_id=_EMPTY_SNAP_ID, parent=base_id, message="signed-child", author="alice", agent_id="chain-bot", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", child_id) result = run_verify(root, check_objects=False) assert result["signatures_checked"] == 1 assert result["all_ok"], result["failures"] @pytest.mark.parametrize("field,value", [ ("author", "injected-author"), ("model_id", "injected-model"), ("toolchain_id", "injected-toolchain"), ("prompt_hash", "injected-prompt-hash"), ]) def test_v7_any_provenance_field_mutation_detected( self, tmp_path: pathlib.Path, field: str, value: str, ) -> None: """Any provenance field mutation in a v7 commit is caught by run_verify.""" root = _make_repo(tmp_path) _write_snapshot(root, _EMPTY_SNAP_ID) key = _gen_key() pub_b64 = _pub_b64(key) commit_id = _make_real_commit_id(snapshot_id=_EMPTY_SNAP_ID, message=f"v7-{field}", author="original-author", signer_public_key=pub_b64) sig = _v7_sig( commit_id, key, author="original-author", agent_id="prov-bot", model_id="original-model", toolchain_id="original-toolchain", prompt_hash="original-hash", ) _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message=f"v7-{field}", author="original-author", agent_id="prov-bot", model_id="original-model", toolchain_id="original-toolchain", prompt_hash="original-hash", signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) _set_branch_ref(root, "main", commit_id) # Tamper: rewrite with the specific field mutated. tampered = {field: value} _write_commit( root, commit_id, snapshot_id=_EMPTY_SNAP_ID, message=f"v7-{field}", author=tampered.get("author", "original-author"), agent_id="prov-bot", model_id=tampered.get("model_id", "original-model"), toolchain_id=tampered.get("toolchain_id", "original-toolchain"), prompt_hash=tampered.get("prompt_hash", "original-hash"), signature=sig, signer_public_key=pub_b64, signer_key_id=_signer_key_id(_pub_bytes(key)), ) result = run_verify(root, check_objects=False) assert not result["all_ok"], f"Mutation of {field!r} should be detected" if field == "author": # author is in the v2 commit ID hash — mutation makes the commit # unreadable; caught as a content-hash (commit) failure. assert any(f["kind"] == "commit" for f in result["failures"]) else: sig_failures = [f for f in result["failures"] if f["kind"] == "signature"] assert len(sig_failures) == 1