Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /mattyopon_faultray /tests /test_audit_chain.py
| """Tests for append-only audit chain.""" | |
| from __future__ import annotations | |
| import json | |
| from pathlib import Path | |
| import pytest | |
| from faultray.reporter.audit_chain import AuditChain, AuditEntry | |
| # --------------------------------------------------------------------------- | |
| # Fixtures | |
| # --------------------------------------------------------------------------- | |
| def chain(tmp_path: Path) -> AuditChain: | |
| return AuditChain(log_path=tmp_path / "audit.jsonl") | |
| def populated_chain(chain: AuditChain) -> AuditChain: | |
| chain.append("topology_loaded", "user@test.com", "Loaded topology v1", data="topology_yaml") | |
| chain.append("simulation_run", "system", "Ran simulation #42", data='{"result": "ok"}') | |
| chain.append("report_generated", "api_key:abc", "Generated PDF report") | |
| return chain | |
| # --------------------------------------------------------------------------- | |
| # Append | |
| # --------------------------------------------------------------------------- | |
| class TestAuditChainAppend: | |
| """Tests for appending entries to the chain.""" | |
| def test_append_returns_audit_entry(self, chain: AuditChain) -> None: | |
| entry = chain.append("test_action", "actor", "details") | |
| assert isinstance(entry, AuditEntry) | |
| def test_first_entry_sequence_zero(self, chain: AuditChain) -> None: | |
| entry = chain.append("action", "actor", "first entry") | |
| assert entry.sequence == 0 | |
| def test_sequence_increments(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries() | |
| for i, entry in enumerate(entries): | |
| assert entry.sequence == i | |
| def test_first_entry_uses_genesis_hash(self, chain: AuditChain) -> None: | |
| entry = chain.append("action", "actor", "first") | |
| assert entry.previous_hash == AuditChain.GENESIS_HASH | |
| def test_subsequent_entries_chain_hashes(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries() | |
| assert entries[1].previous_hash == entries[0].entry_hash | |
| assert entries[2].previous_hash == entries[1].entry_hash | |
| def test_entry_hash_is_sha256(self, chain: AuditChain) -> None: | |
| entry = chain.append("action", "actor", "details") | |
| assert len(entry.entry_hash) == 64 | |
| assert all(c in "0123456789abcdef" for c in entry.entry_hash) | |
| def test_data_hash_computed(self, chain: AuditChain) -> None: | |
| entry = chain.append("action", "actor", "details", data="some data") | |
| assert len(entry.data_hash) == 64 | |
| # Different data should produce different hash | |
| entry2 = chain.append("action", "actor", "details", data="other data") | |
| assert entry.data_hash != entry2.data_hash | |
| def test_empty_data_hash(self, chain: AuditChain) -> None: | |
| entry = chain.append("action", "actor", "details", data="") | |
| assert len(entry.data_hash) == 64 | |
| def test_length_property(self, populated_chain: AuditChain) -> None: | |
| assert populated_chain.length == 3 | |
| def test_last_hash_property(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries() | |
| assert populated_chain.last_hash == entries[-1].entry_hash | |
| def test_last_hash_empty_chain(self, chain: AuditChain) -> None: | |
| assert chain.last_hash == AuditChain.GENESIS_HASH | |
| # --------------------------------------------------------------------------- | |
| # Integrity Verification | |
| # --------------------------------------------------------------------------- | |
| class TestAuditChainIntegrity: | |
| """Tests for chain integrity verification.""" | |
| def test_empty_chain_valid(self, chain: AuditChain) -> None: | |
| valid, msg = chain.verify_integrity() | |
| assert valid is True | |
| assert "Empty chain" in msg | |
| def test_valid_chain_passes(self, populated_chain: AuditChain) -> None: | |
| valid, msg = populated_chain.verify_integrity() | |
| assert valid is True | |
| assert "3 entries" in msg | |
| def test_tampered_entry_hash_detected(self, populated_chain: AuditChain) -> None: | |
| # Tamper with entry hash | |
| populated_chain._entries[1].entry_hash = "f" * 64 | |
| valid, msg = populated_chain.verify_integrity() | |
| assert valid is False | |
| assert "previous_hash mismatch" in msg or "hash tampered" in msg | |
| def test_tampered_previous_hash_detected(self, populated_chain: AuditChain) -> None: | |
| populated_chain._entries[1].previous_hash = "e" * 64 | |
| valid, msg = populated_chain.verify_integrity() | |
| assert valid is False | |
| assert "mismatch" in msg | |
| def test_tampered_sequence_detected(self, populated_chain: AuditChain) -> None: | |
| populated_chain._entries[1].sequence = 99 | |
| valid, msg = populated_chain.verify_integrity() | |
| assert valid is False | |
| assert "Sequence mismatch" in msg | |
| def test_single_entry_valid(self, chain: AuditChain) -> None: | |
| chain.append("action", "actor", "single entry") | |
| valid, msg = chain.verify_integrity() | |
| assert valid is True | |
| # --------------------------------------------------------------------------- | |
| # Filtering and Retrieval | |
| # --------------------------------------------------------------------------- | |
| class TestAuditChainFiltering: | |
| """Tests for entry retrieval and filtering.""" | |
| def test_get_all_entries(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries() | |
| assert len(entries) == 3 | |
| def test_filter_by_action(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries(action="simulation_run") | |
| assert len(entries) == 1 | |
| assert entries[0].action == "simulation_run" | |
| def test_filter_no_match(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries(action="nonexistent") | |
| assert len(entries) == 0 | |
| def test_limit_entries(self, populated_chain: AuditChain) -> None: | |
| entries = populated_chain.get_entries(limit=2) | |
| assert len(entries) == 2 | |
| # Should return the last 2 entries | |
| assert entries[0].sequence == 1 | |
| assert entries[1].sequence == 2 | |
| # --------------------------------------------------------------------------- | |
| # Persistence | |
| # --------------------------------------------------------------------------- | |
| class TestAuditChainPersistence: | |
| """Tests for loading and persisting the chain.""" | |
| def test_persist_creates_file(self, tmp_path: Path) -> None: | |
| log_path = tmp_path / "audit.jsonl" | |
| chain = AuditChain(log_path=log_path) | |
| chain.append("action", "actor", "details") | |
| assert log_path.exists() | |
| def test_load_from_file(self, tmp_path: Path) -> None: | |
| log_path = tmp_path / "audit.jsonl" | |
| chain1 = AuditChain(log_path=log_path) | |
| chain1.append("action1", "actor1", "first") | |
| chain1.append("action2", "actor2", "second") | |
| chain2 = AuditChain(log_path=log_path) | |
| assert chain2.length == 2 | |
| entries = chain2.get_entries() | |
| assert entries[0].action == "action1" | |
| assert entries[1].action == "action2" | |
| def test_loaded_chain_verifies(self, tmp_path: Path) -> None: | |
| log_path = tmp_path / "audit.jsonl" | |
| chain1 = AuditChain(log_path=log_path) | |
| chain1.append("a", "b", "c") | |
| chain1.append("d", "e", "f") | |
| chain2 = AuditChain(log_path=log_path) | |
| valid, msg = chain2.verify_integrity() | |
| assert valid is True | |
| def test_append_after_reload(self, tmp_path: Path) -> None: | |
| log_path = tmp_path / "audit.jsonl" | |
| chain1 = AuditChain(log_path=log_path) | |
| chain1.append("first", "actor", "initial") | |
| chain2 = AuditChain(log_path=log_path) | |
| chain2.append("second", "actor", "continued") | |
| assert chain2.length == 2 | |
| # Verify the chain is still valid after reload+append | |
| valid, msg = chain2.verify_integrity() | |
| assert valid is True | |
| def test_nonexistent_file_starts_empty(self, tmp_path: Path) -> None: | |
| chain = AuditChain(log_path=tmp_path / "nonexistent.jsonl") | |
| assert chain.length == 0 | |
| def test_creates_parent_directories(self, tmp_path: Path) -> None: | |
| log_path = tmp_path / "deep" / "nested" / "audit.jsonl" | |
| chain = AuditChain(log_path=log_path) | |
| chain.append("action", "actor", "details") | |
| assert log_path.exists() | |
| # --------------------------------------------------------------------------- | |
| # Export for Audit | |
| # --------------------------------------------------------------------------- | |
| class TestAuditChainExport: | |
| """Tests for exporting the chain for auditors.""" | |
| def test_export_creates_json(self, populated_chain: AuditChain, tmp_path: Path) -> None: | |
| output = tmp_path / "export.json" | |
| populated_chain.export_for_audit(output) | |
| assert output.exists() | |
| data = json.loads(output.read_text(encoding="utf-8")) | |
| assert data["chain_length"] == 3 | |
| assert data["integrity_verified"] is True | |
| assert len(data["entries"]) == 3 | |
| def test_export_includes_timestamps(self, populated_chain: AuditChain, tmp_path: Path) -> None: | |
| output = tmp_path / "export.json" | |
| populated_chain.export_for_audit(output) | |
| data = json.loads(output.read_text(encoding="utf-8")) | |
| assert data["first_entry"] is not None | |
| assert data["last_entry"] is not None | |
| def test_export_empty_chain(self, chain: AuditChain, tmp_path: Path) -> None: | |
| output = tmp_path / "export.json" | |
| chain.export_for_audit(output) | |
| data = json.loads(output.read_text(encoding="utf-8")) | |
| assert data["chain_length"] == 0 | |
| assert data["integrity_verified"] is True | |
| assert data["first_entry"] is None | |
| assert data["last_entry"] is None | |
| # --------------------------------------------------------------------------- | |
| # Keyed HMAC tamper-evidence (FAULTRAY_SIGNING_KEY) | |
| # --------------------------------------------------------------------------- | |
| class TestAuditChainSigning: | |
| """The chain is only cryptographically tamper-evident when keyed.""" | |
| def test_unkeyed_chain_is_not_tamper_evident( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| chain = AuditChain(log_path=tmp_path / "a.jsonl") | |
| entry = chain.append("simulation_run", "system", "ran") | |
| assert entry.signed is False | |
| assert chain.tamper_evident is False | |
| valid, msg = chain.verify_integrity() | |
| assert valid is True | |
| assert "not cryptographically signed" in msg | |
| def test_keyed_chain_is_hmac_verified(self, tmp_path: Path) -> None: | |
| chain = AuditChain(log_path=tmp_path / "a.jsonl", signing_key="s3cret") | |
| entry = chain.append("simulation_run", "system", "ran", data="payload") | |
| assert entry.signed is True | |
| assert chain.tamper_evident is True | |
| valid, msg = chain.verify_integrity() | |
| assert valid is True | |
| assert "HMAC-verified" in msg | |
| def test_signing_key_changes_the_link(self, tmp_path: Path) -> None: | |
| a = AuditChain(log_path=tmp_path / "a.jsonl", signing_key="key-a") | |
| b = AuditChain(log_path=tmp_path / "b.jsonl", signing_key="key-b") | |
| ea = a.append("x", "system", "d", data="same") | |
| eb = b.append("x", "system", "d", data="same") | |
| # Same inputs, different keys -> different MACs (forgery needs the key). | |
| assert ea.entry_hash != eb.entry_hash | |
| def test_wrong_key_on_reload_fails_closed(self, tmp_path: Path) -> None: | |
| log = tmp_path / "a.jsonl" | |
| signer = AuditChain(log_path=log, signing_key="real-key") | |
| signer.append("simulation_run", "system", "ran", data="payload") | |
| # Attacker/operator without the real key cannot vouch for the chain. | |
| forger = AuditChain(log_path=log, signing_key="wrong-key") | |
| valid, msg = forger.verify_integrity() | |
| assert valid is False | |
| assert "tampered" in msg | |
| def test_field_boundary_shift_detected(self, tmp_path: Path) -> None: | |
| # A `|` inside a field must not let an attacker re-partition the signed | |
| # fields while keeping the MAC valid. Under the old pipe-joined payload, | |
| # action="deploy"/actor="alice|admin" and action="deploy|alice"/ | |
| # actor="admin" hashed identically (same "deploy|alice|admin" bytes); the | |
| # canonical JSON payload distinguishes them. | |
| log = tmp_path / "a.jsonl" | |
| chain = AuditChain(log_path=log, signing_key="real-key") | |
| chain.append("deploy", "alice|admin", "prod deploy") | |
| assert chain.verify_integrity()[0] is True | |
| # Re-partition the fields across the former delimiter, leaving the | |
| # concatenation between action and actor unchanged. | |
| chain._entries[0].action = "deploy|alice" | |
| chain._entries[0].actor = "admin" | |
| valid, msg = chain.verify_integrity() | |
| assert valid is False | |
| assert "tampered" in msg | |
| def test_legacy_pipe_signed_entry_still_verifies(self, tmp_path: Path) -> None: | |
| # A chain signed by the PREVIOUS release used a pipe-joined HMAC payload. | |
| # After upgrading to the canonical-JSON payload, those entries must still | |
| # verify with the correct key — otherwise loading an existing signed log | |
| # reports "tampered" and the chain becomes non-appendable on upgrade. | |
| import hashlib as _h | |
| import hmac as _hm | |
| log = tmp_path / "a.jsonl" | |
| chain = AuditChain(log_path=log, signing_key="real-key") | |
| e = chain.append("deploy", "alice", "prod deploy", data="d") | |
| # Re-stamp the entry hash the OLD way (pipe-joined payload) in place. | |
| pipe = ( | |
| f"{e.sequence}|{e.timestamp}|{e.action}|{e.actor}" | |
| f"|{e.data_hash}|{e.previous_hash}|{e.details}" | |
| ) | |
| e.entry_hash = _hm.new(b"real-key", pipe.encode(), _h.sha256).hexdigest() | |
| valid, msg = chain.verify_integrity() | |
| assert valid is True, msg | |
| def test_signed_entry_without_key_fails_closed( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| log = tmp_path / "a.jsonl" | |
| AuditChain(log_path=log, signing_key="real-key").append("a", "system", "d") | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| unkeyed = AuditChain(log_path=log) | |
| valid, msg = unkeyed.verify_integrity() | |
| assert valid is False | |
| assert "no signing key" in msg | |
| def test_require_signing_raises_without_key( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| with pytest.raises(RuntimeError, match="signing is required"): | |
| AuditChain(log_path=tmp_path / "a.jsonl", require_signing=True) | |
| def test_export_reports_tamper_evidence(self, tmp_path: Path) -> None: | |
| chain = AuditChain(log_path=tmp_path / "a.jsonl", signing_key="k") | |
| chain.append("a", "system", "d") | |
| out = tmp_path / "export.json" | |
| chain.export_for_audit(out) | |
| data = json.loads(out.read_text(encoding="utf-8")) | |
| assert data["tamper_evident"] is True | |
| assert data["signature_algorithm"] == "hmac-sha256" | |
| def test_append_refuses_signed_onto_unsigned_legacy( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| # Enabling signing on a chain that already has unsigned (legacy) entries | |
| # must NOT silently produce a mixed [unsigned..., signed] chain that | |
| # verify_integrity() would then reject at entry 0. | |
| log = tmp_path / "a.jsonl" | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| AuditChain(log_path=log).append("legacy", "system", "unsigned") | |
| chain = AuditChain(log_path=log, signing_key="k") | |
| with pytest.raises(RuntimeError, match="unsigned"): | |
| chain.append("new", "system", "would be signed") | |
| # Fail-closed: nothing was written; the log still has just the one entry. | |
| assert log.read_text(encoding="utf-8").strip().count("\n") == 0 | |
| # A brand-new signed chain and an already-all-signed chain still append. | |
| fresh = AuditChain(log_path=tmp_path / "b.jsonl", signing_key="k") | |
| fresh.append("a", "system", "d") | |
| fresh.append("b", "system", "d") # all-signed prefix -> allowed | |
| assert fresh.verify_integrity()[0] is True | |
| def test_append_refuses_after_key_rotation( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| # An all-signed chain under key A, reloaded under key B (rotation): the | |
| # old entries no longer verify, so appending a new B-signed entry would | |
| # leave a chain that NEITHER key can verify — refuse. | |
| log = tmp_path / "a.jsonl" | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| AuditChain(log_path=log, signing_key="key-A").append("a", "system", "d") | |
| rotated = AuditChain(log_path=log, signing_key="key-B") | |
| with pytest.raises(RuntimeError, match="rotated"): | |
| rotated.append("b", "system", "d") | |
| # Nothing written: the log still has just the one key-A entry. | |
| assert log.read_text(encoding="utf-8").strip().count("\n") == 0 | |
| def test_append_refuses_signed_log_loaded_without_key( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| # A HMAC-signed chain reloaded with NO key configured (misconfigured | |
| # signed deployment): appending would write an UNSIGNED entry after the | |
| # signed prefix, which verify_integrity() rejects the moment the correct | |
| # key is restored — permanently breaking the chain after one keyless | |
| # event. Detect the signed prefix even without a key and fail closed. | |
| log = tmp_path / "a.jsonl" | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| AuditChain(log_path=log, signing_key="k").append("a", "system", "d") | |
| keyless = AuditChain(log_path=log) # signed prefix loaded, no key | |
| with pytest.raises(RuntimeError, match="no key is configured"): | |
| keyless.append("b", "system", "would be unsigned") | |
| # Fail-closed: nothing written; the log still has just the one entry. | |
| assert log.read_text(encoding="utf-8").strip().count("\n") == 0 | |
| class TestAuditDetailsAndExport: | |
| def test_details_are_covered_by_the_mac(self, tmp_path: Path) -> None: | |
| chain = AuditChain(log_path=tmp_path / "a.jsonl", signing_key="k") | |
| chain.append("act", "system", "original details", data="d") | |
| # Tampering the human-readable details must break verification. | |
| chain._entries[0].details = "tampered details" | |
| ok, _ = chain.verify_integrity() | |
| assert ok is False | |
| def test_unsigned_entries_not_exported_as_tamper_evident( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| log = tmp_path / "a.jsonl" | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| AuditChain(log_path=log).append("a", "system", "d") # unsigned legacy | |
| # Reload with a key now present — must NOT advertise tamper-evidence. | |
| chain = AuditChain(log_path=log, signing_key="k") | |
| out = tmp_path / "e.json" | |
| chain.export_for_audit(out) | |
| data = json.loads(out.read_text(encoding="utf-8")) | |
| assert data["tamper_evident"] is False | |
| assert data["signature_algorithm"] == "sha256-unkeyed" | |
| class TestAuditLegacyAndAppendGuards: | |
| def test_legacy_unsigned_entry_without_details_still_verifies( | |
| self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | |
| ) -> None: | |
| import hashlib | |
| monkeypatch.delenv("FAULTRAY_SIGNING_KEY", raising=False) | |
| chain = AuditChain(log_path=tmp_path / "a.jsonl") | |
| seq, ts, action, actor, details = ( | |
| 0, "2026-01-01T00:00:00+00:00", "act", "system", "legacy details" | |
| ) | |
| data_hash = hashlib.sha256(b"").hexdigest() | |
| prev = AuditChain.GENESIS_HASH | |
| # Pre-upgrade payload omitted `details`. | |
| legacy_payload = f"{seq}|{ts}|{action}|{actor}|{data_hash}|{prev}" | |
| legacy_hash = hashlib.sha256(legacy_payload.encode()).hexdigest() | |
| chain._entries = [AuditEntry(seq, ts, action, actor, details, data_hash, prev, legacy_hash)] | |
| ok, _ = chain.verify_integrity() | |
| assert ok is True | |
| def test_unsigned_append_to_signed_chain_is_rejected(self, tmp_path: Path) -> None: | |
| import hashlib | |
| chain = AuditChain(log_path=tmp_path / "a.jsonl", signing_key="k") | |
| chain.append("a", "system", "d") # legitimate signed entry 0 | |
| e0 = chain._entries[0] | |
| seq, ts, action, actor, details = ( | |
| 1, "2026-01-01T00:00:00+00:00", "evil", "attacker", "forged" | |
| ) | |
| data_hash = hashlib.sha256(b"").hexdigest() | |
| prev = e0.entry_hash | |
| payload = f"{seq}|{ts}|{action}|{actor}|{data_hash}|{prev}|{details}" | |
| forged = hashlib.sha256(payload.encode()).hexdigest() # attacker computes plain sha256 | |
| chain._entries.append( | |
| AuditEntry(seq, ts, action, actor, details, data_hash, prev, forged, signed=False) | |
| ) | |
| ok, msg = chain.verify_integrity() | |
| assert ok is False | |
| assert "unsigned" in msg | |
Xet Storage Details
- Size:
- 21.4 kB
- Xet hash:
- da4ce68e8deb9b711af0248c1b4763f5cd9cc98d5becbc7a7060f0e0f7e17f8d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.