test_verify_commit_attest.py
file-level
1
files
1
commits
0
hotspots
0
π§ dead
0
π₯ blast risk
| 1 | """Tests for verify_attestation + ``muse verify-commit --attest`` β Phase 7.5. |
| 2 | |
| 3 | Rule #0 tier coverage: |
| 4 | |
| 5 | * unit β tier output mapping, four-tier glyph rendering, exit codes. |
| 6 | * integration β full round-trip commit β attest β verify, all four tiers. |
| 7 | * security β forged HMAC β tier 2 (signed) not tier 3; missing anchor β |
| 8 | explicit ICP_NOT_ANCHORED; network-unreachable canister β |
| 9 | explicit ICP_UNREACHABLE (not silent degrade); partial |
| 10 | verifications surface clearly. |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import argparse |
| 16 | import json |
| 17 | import os |
| 18 | import pathlib |
| 19 | from dataclasses import dataclass, field |
| 20 | from typing import Any |
| 21 | from unittest.mock import patch |
| 22 | |
| 23 | import pytest |
| 24 | |
| 25 | from muse.cli.commands import verify_commit as verify_commit_cmd |
| 26 | from muse.core.attestation import ( |
| 27 | AttestationVerifyError, |
| 28 | register_attestation_provider, |
| 29 | unregister_attestation_provider, |
| 30 | ) |
| 31 | from muse.core.errors import ExitCode |
| 32 | from muse.core.verify import ( |
| 33 | AttestationVerifyResult, |
| 34 | TIER_HMAC_ATTESTED, |
| 35 | TIER_ICP_ANCHORED, |
| 36 | TIER_SIGNED_ONLY, |
| 37 | TIER_UNSIGNED, |
| 38 | verify_attestation, |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | # --------------------------------------------------------------------------- |
| 43 | # Fake commit + provider scaffolding |
| 44 | # --------------------------------------------------------------------------- |
| 45 | |
| 46 | |
| 47 | @dataclass |
| 48 | class _FakeCommit: |
| 49 | """Minimal CommitRecord shape used by the verify engine.""" |
| 50 | |
| 51 | commit_id: str = "c" * 64 |
| 52 | signature: str = "" |
| 53 | signer_public_key: str = "" |
| 54 | format_version: int = 7 |
| 55 | author: str = "" |
| 56 | agent_id: str = "" |
| 57 | model_id: str = "" |
| 58 | toolchain_id: str = "" |
| 59 | prompt_hash: str = "" |
| 60 | |
| 61 | @property |
| 62 | def committed_at(self) -> Any: |
| 63 | import datetime |
| 64 | return datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) |
| 65 | |
| 66 | metadata: dict[str, str] = field(default_factory=dict) |
| 67 | |
| 68 | |
| 69 | def _make_signed_commit(metadata: dict[str, str] | None = None) -> _FakeCommit: |
| 70 | """Forge a real Ed25519 signature so the engine treats the commit as signed.""" |
| 71 | from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey |
| 72 | from muse.core.provenance import ( |
| 73 | encode_public_key, |
| 74 | provenance_payload, |
| 75 | sign_commit_ed25519, |
| 76 | ) |
| 77 | pk = Ed25519PrivateKey.generate() |
| 78 | commit = _FakeCommit(metadata=dict(metadata or {})) |
| 79 | payload = provenance_payload( |
| 80 | commit.commit_id, |
| 81 | author=commit.author, agent_id=commit.agent_id, |
| 82 | model_id=commit.model_id, toolchain_id=commit.toolchain_id, |
| 83 | prompt_hash=commit.prompt_hash, |
| 84 | committed_at=commit.committed_at.isoformat(), |
| 85 | ) |
| 86 | sig = sign_commit_ed25519(payload, pk) |
| 87 | _, pub_b64 = encode_public_key(pk) |
| 88 | commit.signature = sig |
| 89 | commit.signer_public_key = pub_b64 |
| 90 | return commit |
| 91 | |
| 92 | |
| 93 | class _AlwaysValidProvider: |
| 94 | """Stub provider whose verify always returns valid=True.""" |
| 95 | |
| 96 | def compute_attestation(self, snapshot_id: str, commit_meta: dict[str, object]) -> Any: |
| 97 | return {} |
| 98 | |
| 99 | def anchor(self, record: Any) -> Any: |
| 100 | return {} |
| 101 | |
| 102 | def verify(self, record: Any, receipt: Any) -> Any: |
| 103 | return {"valid": True, "reason": "", "depth": 0, "provider_id": "knowtation"} |
| 104 | |
| 105 | |
| 106 | class _AlwaysInvalidProvider(_AlwaysValidProvider): |
| 107 | """Stub provider whose verify returns valid=False (provably bad).""" |
| 108 | |
| 109 | def verify(self, record: Any, receipt: Any) -> Any: |
| 110 | return { |
| 111 | "valid": False, "reason": "HMAC signature mismatch (forged)", |
| 112 | "depth": 0, "provider_id": "knowtation", |
| 113 | } |
| 114 | |
| 115 | |
| 116 | class _RaisingProvider(_AlwaysValidProvider): |
| 117 | """Stub provider whose verify raises (partial verification).""" |
| 118 | |
| 119 | def verify(self, record: Any, receipt: Any) -> Any: |
| 120 | raise AttestationVerifyError("simulated key missing", code="KEY_MISSING") |
| 121 | |
| 122 | |
| 123 | @pytest.fixture(autouse=True) |
| 124 | def _registry_cleanup() -> None: |
| 125 | """Ensure each test starts/ends with no provider registered.""" |
| 126 | unregister_attestation_provider("knowtation") |
| 127 | yield |
| 128 | unregister_attestation_provider("knowtation") |
| 129 | |
| 130 | |
| 131 | # =========================================================================== |
| 132 | # UNIT TIER β tier mapping |
| 133 | # =========================================================================== |
| 134 | |
| 135 | |
| 136 | class TestTierLabels: |
| 137 | """Tier label map exposes stable strings for JSON consumers.""" |
| 138 | |
| 139 | def test_all_tiers_have_labels(self) -> None: |
| 140 | """Every defined tier has a non-empty label.""" |
| 141 | labels = verify_commit_cmd.TIER_LABELS |
| 142 | assert labels[TIER_UNSIGNED] == "unsigned" |
| 143 | assert labels[TIER_SIGNED_ONLY] == "signed" |
| 144 | assert labels[TIER_HMAC_ATTESTED] == "hmac-attested" |
| 145 | assert labels[TIER_ICP_ANCHORED] == "icp-anchored" |
| 146 | |
| 147 | |
| 148 | # =========================================================================== |
| 149 | # INTEGRATION TIER β verify_attestation engine |
| 150 | # =========================================================================== |
| 151 | |
| 152 | |
| 153 | class TestEngineTier0: |
| 154 | """Unsigned commit β tier 0.""" |
| 155 | |
| 156 | def test_unsigned_returns_tier_0(self) -> None: |
| 157 | """No signature β tier 0, valid=False, reason populated.""" |
| 158 | commit = _FakeCommit() |
| 159 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 160 | assert result["tier"] == TIER_UNSIGNED |
| 161 | assert result["valid"] is False |
| 162 | assert result["reason"] |
| 163 | |
| 164 | |
| 165 | class TestEngineTier1: |
| 166 | """Signed commit, no attestation β tier 1.""" |
| 167 | |
| 168 | def test_signed_only_returns_tier_1(self) -> None: |
| 169 | """Real signature, no metadata β tier 1, valid=True.""" |
| 170 | commit = _make_signed_commit() |
| 171 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 172 | assert result["tier"] == TIER_SIGNED_ONLY |
| 173 | assert result["valid"] is True |
| 174 | assert result["partial"] is False |
| 175 | |
| 176 | |
| 177 | class TestEngineTier2: |
| 178 | """Signed + HMAC attestation valid β tier 2.""" |
| 179 | |
| 180 | def test_hmac_valid_no_icp_check_returns_tier_2(self) -> None: |
| 181 | """HMAC OK, ICP check disabled β tier 2.""" |
| 182 | register_attestation_provider("knowtation", _AlwaysValidProvider()) |
| 183 | commit = _make_signed_commit({ |
| 184 | "attestation": json.dumps({ |
| 185 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 186 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 187 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 188 | "provider_id": "knowtation", |
| 189 | }), |
| 190 | }) |
| 191 | result = verify_attestation( |
| 192 | commit, pathlib.Path("/tmp/fake"), {"check_icp": False} |
| 193 | ) |
| 194 | assert result["tier"] == TIER_HMAC_ATTESTED |
| 195 | assert result["hmac_valid"] is True |
| 196 | assert result["valid"] is True |
| 197 | |
| 198 | |
| 199 | class TestEngineTier3: |
| 200 | """Signed + HMAC + ICP anchored β tier 3.""" |
| 201 | |
| 202 | def test_icp_anchored_returns_tier_3(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 203 | """Mock anchor fetch returning matching record β tier 3.""" |
| 204 | register_attestation_provider("knowtation", _AlwaysValidProvider()) |
| 205 | attestation = { |
| 206 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 207 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 208 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 209 | "provider_id": "knowtation", |
| 210 | } |
| 211 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 212 | |
| 213 | def _fake_fetch(canister_id: str, rid: str, *, timeout: float = 5.0) -> Any: |
| 214 | return {**attestation, "seq": 42} |
| 215 | |
| 216 | monkeypatch.setattr( |
| 217 | "muse.plugins.knowtation.icp_push_hook.fetch_attestation_via_http", |
| 218 | _fake_fetch, |
| 219 | ) |
| 220 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 221 | assert result["tier"] == TIER_ICP_ANCHORED |
| 222 | assert result["icp_anchored"] is True |
| 223 | assert "icp-seq-42" in result["anchor_tx_id"] |
| 224 | |
| 225 | |
| 226 | # =========================================================================== |
| 227 | # SECURITY TIER (mandatory) |
| 228 | # =========================================================================== |
| 229 | |
| 230 | |
| 231 | class TestSecurity: |
| 232 | """Phase 7.5 security contracts β partial verifications must surface.""" |
| 233 | |
| 234 | def test_forged_hmac_returns_valid_false_at_tier_above_signed( |
| 235 | self, |
| 236 | ) -> None: |
| 237 | """Provably-bad HMAC β valid=False, partial=False, NOT tier 1 fallthrough.""" |
| 238 | register_attestation_provider("knowtation", _AlwaysInvalidProvider()) |
| 239 | attestation = { |
| 240 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 241 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 242 | "sig": "forged-sig", "algorithm": "hmac-sha256", |
| 243 | "provider_id": "knowtation", |
| 244 | } |
| 245 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 246 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 247 | # Critical: HMAC_INVALID surfaces explicitly, not silent tier-1. |
| 248 | assert "HMAC_INVALID" in result["reason"] |
| 249 | assert result["valid"] is False |
| 250 | assert result["partial"] is False |
| 251 | |
| 252 | def test_icp_unreachable_surfaces_partial_not_silent_degrade( |
| 253 | self, monkeypatch: pytest.MonkeyPatch |
| 254 | ) -> None: |
| 255 | """Network failure β partial=True, ICP_UNREACHABLE in reason.""" |
| 256 | register_attestation_provider("knowtation", _AlwaysValidProvider()) |
| 257 | attestation = { |
| 258 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 259 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 260 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 261 | "provider_id": "knowtation", |
| 262 | } |
| 263 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 264 | |
| 265 | def _fail(canister_id: str, rid: str, *, timeout: float = 5.0) -> Any: |
| 266 | raise OSError("connection refused") |
| 267 | |
| 268 | monkeypatch.setattr( |
| 269 | "muse.plugins.knowtation.icp_push_hook.fetch_attestation_via_http", |
| 270 | _fail, |
| 271 | ) |
| 272 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 273 | assert result["partial"] is True |
| 274 | assert "ICP_UNREACHABLE" in result["reason"] |
| 275 | # The HMAC was still valid β tier capped at HMAC_ATTESTED. |
| 276 | assert result["tier"] == TIER_HMAC_ATTESTED |
| 277 | assert result["icp_anchored"] is False |
| 278 | |
| 279 | def test_icp_404_returns_explicit_not_anchored( |
| 280 | self, monkeypatch: pytest.MonkeyPatch |
| 281 | ) -> None: |
| 282 | """Canister returns 404 β ICP_NOT_ANCHORED, partial=False.""" |
| 283 | register_attestation_provider("knowtation", _AlwaysValidProvider()) |
| 284 | attestation = { |
| 285 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 286 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 287 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 288 | "provider_id": "knowtation", |
| 289 | } |
| 290 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 291 | monkeypatch.setattr( |
| 292 | "muse.plugins.knowtation.icp_push_hook.fetch_attestation_via_http", |
| 293 | lambda *a, **kw: None, |
| 294 | ) |
| 295 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 296 | assert "ICP_NOT_ANCHORED" in result["reason"] |
| 297 | assert result["icp_anchored"] is False |
| 298 | # NOT partial β verifier completed the check and got a definitive 404. |
| 299 | assert result["partial"] is False |
| 300 | |
| 301 | def test_icp_content_hash_mismatch_caught( |
| 302 | self, monkeypatch: pytest.MonkeyPatch |
| 303 | ) -> None: |
| 304 | """Anchored copy has different content_hash β ICP_NOT_ANCHORED.""" |
| 305 | register_attestation_provider("knowtation", _AlwaysValidProvider()) |
| 306 | attestation = { |
| 307 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 308 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 309 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 310 | "provider_id": "knowtation", |
| 311 | } |
| 312 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 313 | |
| 314 | def _fake_mismatch(canister_id: str, rid: str, *, timeout: float = 5.0) -> Any: |
| 315 | return {**attestation, "content_hash": "TAMPERED", "seq": 1} |
| 316 | |
| 317 | monkeypatch.setattr( |
| 318 | "muse.plugins.knowtation.icp_push_hook.fetch_attestation_via_http", |
| 319 | _fake_mismatch, |
| 320 | ) |
| 321 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 322 | assert "content_hash" in result["reason"] |
| 323 | assert result["icp_anchored"] is False |
| 324 | |
| 325 | def test_provider_raise_is_partial_not_invalid(self) -> None: |
| 326 | """Provider raises β partial=True (verifier could not complete).""" |
| 327 | register_attestation_provider("knowtation", _RaisingProvider()) |
| 328 | attestation = { |
| 329 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 330 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 331 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 332 | "provider_id": "knowtation", |
| 333 | } |
| 334 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 335 | result = verify_attestation( |
| 336 | commit, pathlib.Path("/tmp/fake"), {"check_icp": False} |
| 337 | ) |
| 338 | assert result["partial"] is True |
| 339 | assert "KEY_MISSING" in result["reason"] |
| 340 | |
| 341 | def test_no_provider_registered_is_partial(self) -> None: |
| 342 | """No provider for the record's domain β partial=True, NO_PROVIDER.""" |
| 343 | attestation = { |
| 344 | "id": "a" * 64, "action": "write", "path": "x.md", |
| 345 | "content_hash": "abc", "timestamp": "2026-01-01T00:00:00Z", |
| 346 | "sig": "real-sig", "algorithm": "hmac-sha256", |
| 347 | "provider_id": "nonexistent-domain", |
| 348 | } |
| 349 | commit = _make_signed_commit({"attestation": json.dumps(attestation)}) |
| 350 | result = verify_attestation(commit, pathlib.Path("/tmp/fake")) |
| 351 | assert result["partial"] is True |
| 352 | assert "NO_PROVIDER" in result["reason"] |
| 353 | |
| 354 | |
| 355 | # =========================================================================== |
| 356 | # CLI tier β argparse / exit codes |
| 357 | # =========================================================================== |
| 358 | |
| 359 | |
| 360 | class TestCLI: |
| 361 | """muse verify-commit subcommand exits cleanly per tier.""" |
| 362 | |
| 363 | def _init_repo_with_commit(self, tmp_path: pathlib.Path) -> str: |
| 364 | """Init a knowtation repo, commit one note, return the commit ID.""" |
| 365 | os.chdir(tmp_path) |
| 366 | from muse.cli.commands.init import run as init_run |
| 367 | init_args = argparse.Namespace( |
| 368 | bare=False, template=None, default_branch="main", |
| 369 | force=False, domain="knowtation", as_json=False, |
| 370 | ) |
| 371 | init_run(init_args) |
| 372 | (tmp_path / "notes").mkdir() |
| 373 | (tmp_path / "notes" / "seed.md").write_text("seed\n", encoding="utf-8") |
| 374 | from muse.cli.commands import commit as commit_cmd |
| 375 | captured: list[str] = [] |
| 376 | import builtins |
| 377 | real_print = builtins.print |
| 378 | try: |
| 379 | builtins.print = lambda *a, **kw: captured.append(" ".join(str(x) for x in a)) # type: ignore[assignment] |
| 380 | commit_args = argparse.Namespace( |
| 381 | message="seed", allow_empty=False, dry_run=False, |
| 382 | section=None, track=None, emotion=None, author=None, |
| 383 | agent_id=None, model_id=None, toolchain_id=None, |
| 384 | event_type=None, meta=None, sign=False, attest=False, |
| 385 | attest_config=None, fmt="json", |
| 386 | ) |
| 387 | commit_cmd.run(commit_args) |
| 388 | finally: |
| 389 | builtins.print = real_print |
| 390 | payload = json.loads([c for c in captured if c.startswith("{")][0]) |
| 391 | return str(payload["commit_id"]) |
| 392 | |
| 393 | def test_unsigned_commit_exits_user_error(self, tmp_path: pathlib.Path) -> None: |
| 394 | """Real unsigned commit β CLI exits USER_ERROR for tier 0.""" |
| 395 | commit_id = self._init_repo_with_commit(tmp_path) |
| 396 | args = argparse.Namespace( |
| 397 | commit_id=commit_id, attest=False, no_icp=True, |
| 398 | icp_canister=None, icp_timeout=5.0, json_out=True, |
| 399 | ) |
| 400 | with pytest.raises(SystemExit) as exc: |
| 401 | verify_commit_cmd.run(args) |
| 402 | assert exc.value.code == ExitCode.USER_ERROR |
| 403 | |
| 404 | def test_unknown_commit_exits_not_found(self, tmp_path: pathlib.Path) -> None: |
| 405 | """Bogus commit ID β exits NOT_FOUND.""" |
| 406 | self._init_repo_with_commit(tmp_path) |
| 407 | args = argparse.Namespace( |
| 408 | commit_id="0" * 64, attest=False, no_icp=True, |
| 409 | icp_canister=None, icp_timeout=5.0, json_out=True, |
| 410 | ) |
| 411 | with pytest.raises(SystemExit) as exc: |
| 412 | verify_commit_cmd.run(args) |
| 413 | assert exc.value.code == ExitCode.NOT_FOUND |