Skip to content

Commit b2546e4

Browse files
authored
Merge pull request #1 from Beach-Bum/fix/audit-verify-detects-tampering
Make audit verify detect tampering
2 parents 795328f + 6155020 commit b2546e4

3 files changed

Lines changed: 274 additions & 19 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,17 @@ jobs:
2222
- name: Set up Python ${{ matrix.python-version }}
2323
run: uv python install ${{ matrix.python-version }}
2424

25+
# A project environment, not the runner's system Python: Ubuntu marks
26+
# that one as externally managed and refuses installs into it.
2527
- name: Install dependencies
26-
run: uv pip install -e ".[dev]" --system
28+
run: uv sync --extra dev --python ${{ matrix.python-version }}
2729

2830
- name: Run tests
29-
run: uv run pytest -q
31+
run: uv run --extra dev pytest -q
3032

3133
- name: Lint with ruff
32-
run: uv run ruff check .
34+
run: uv run --extra dev ruff check .
3335

3436
- name: Type check with mypy
35-
run: uv run mypy agentix_logos/
37+
run: uv run --extra dev mypy agentix_logos/
3638
continue-on-error: true

‎agentix_logos/audit_chain.py‎

Lines changed: 98 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,23 @@ class ChainVerification:
5151
valid: bool
5252
entries: int
5353
errors: list[str]
54+
sealed: int = 0 # lines covered by the sidecar and checked against it
55+
unsealed: int = 0 # lines written since the chain was last sealed
5456

5557
def to_dict(self) -> dict:
5658
return {
5759
"valid": self.valid,
5860
"entries": self.entries,
5961
"errors": self.errors,
62+
"sealed": self.sealed,
63+
"unsealed": self.unsealed,
6064
}
6165

6266

67+
SIDECAR_NAME = "audit-chain.jsonl"
68+
MAX_REPORTED_ERRORS = 10
69+
70+
6371
def build_chain(audit_path: Path) -> list[ChainEntry]:
6472
"""Build a hash chain from an audit.jsonl file."""
6573
if not audit_path.exists():
@@ -84,39 +92,114 @@ def build_chain(audit_path: Path) -> list[ChainEntry]:
8492
return chain
8593

8694

87-
def verify_chain(audit_path: Path) -> ChainVerification:
88-
"""Verify the integrity of an audit chain.
95+
def load_chain_sidecar(sidecar_path: Path) -> list[dict]:
96+
"""Read the sealed chain. A line that is not JSON is kept as an empty
97+
record so that it fails verification instead of being skipped."""
98+
records: list[dict] = []
99+
for raw in sidecar_path.read_text(encoding="utf-8").splitlines():
100+
if not raw.strip():
101+
continue
102+
try:
103+
record = json.loads(raw)
104+
except json.JSONDecodeError:
105+
record = {}
106+
records.append(record if isinstance(record, dict) else {})
107+
return records
108+
109+
110+
def _check_sidecar(records: list[dict]) -> list[str]:
111+
"""The sealed chain must be consistent with itself before it can vouch
112+
for anything: positions in order, each entry naming the one before it,
113+
and each chain_root recomputable from its own fields."""
114+
problems: list[str] = []
115+
prev_cid: str | None = None
116+
for i, rec in enumerate(records):
117+
cid = rec.get("cid")
118+
if rec.get("sequence_number") != i or not isinstance(cid, str):
119+
problems.append(f"Chain entry {i}: malformed or out of sequence")
120+
prev_cid = cid if isinstance(cid, str) else None
121+
continue
122+
if rec.get("prev_cid") != prev_cid:
123+
problems.append(f"Chain entry {i}: does not link to the entry before it")
124+
if rec.get("chain_root") != compute_chain_root(i, cid, rec.get("prev_cid")):
125+
problems.append(f"Chain entry {i}: chain_root does not match its own fields")
126+
prev_cid = cid
127+
return problems
128+
89129

90-
Recomputes every CID and chain_root from the raw lines and checks
91-
the prev_cid linkage. Any discrepancy = tampering detected.
130+
def verify_chain(audit_path: Path, sidecar_path: Path | None = None) -> ChainVerification:
131+
"""Verify the audit log against its sealed chain.
132+
133+
`agentix-logos audit chain` seals the log: it writes one record per line
134+
(the line's CID, the previous CID, a root binding both to a position) to
135+
the sidecar. This checks the log as it is now against that record.
136+
137+
Detected, and reported by position:
138+
- a sealed line whose content changed
139+
- a sealed line removed, inserted or moved (every line from that point
140+
stops matching the CID recorded for its position)
141+
- the log cut short
142+
- a sidecar edited to agree with a changed log, unless every linked
143+
field was recomputed too
144+
145+
Not detected: lines appended after the last seal. They are counted as
146+
`unsealed`, not treated as errors, because appending is what a log does.
147+
148+
What this cannot do on its own: someone who can rewrite the log can
149+
rewrite the sidecar beside it. The check becomes binding once the sidecar
150+
(or its last chain_root) is held somewhere the writer cannot reach, which
151+
is what publishing it is for.
152+
153+
With no sidecar there is nothing to compare against, so the result only
154+
says whether each line is well-formed, and `sealed` is 0.
92155
"""
93156
if not audit_path.exists():
94157
return ChainVerification(valid=True, entries=0, errors=[])
95158

96159
lines = audit_path.read_text(encoding="utf-8").strip().splitlines()
97160
errors: list[str] = []
98-
prev_cid: str | None = None
99161

100162
for i, line in enumerate(lines):
101-
# Verify the line is valid JSON
102163
try:
103164
json.loads(line)
104165
except json.JSONDecodeError:
105166
errors.append(f"Line {i}: invalid JSON")
106-
continue
107167

108-
cid = compute_cid(line)
109-
compute_chain_root(i, cid, prev_cid)
110-
111-
# The chain is implicit — we're verifying that the lines
112-
# haven't been reordered, removed, or modified by checking
113-
# that the CID sequence is reproducible.
114-
prev_cid = cid
168+
if sidecar_path is None:
169+
sidecar_path = audit_path.parent / SIDECAR_NAME
170+
if not sidecar_path.exists():
171+
return ChainVerification(
172+
valid=not errors, entries=len(lines), errors=errors,
173+
sealed=0, unsealed=len(lines),
174+
)
175+
176+
records = load_chain_sidecar(sidecar_path)
177+
errors.extend(_check_sidecar(records))
178+
179+
mismatched = [
180+
i for i, rec in enumerate(records[: len(lines)])
181+
if compute_cid(lines[i]) != rec.get("cid")
182+
]
183+
for i in mismatched[:MAX_REPORTED_ERRORS]:
184+
errors.append(f"Line {i}: content does not match the CID sealed for this position")
185+
if len(mismatched) > MAX_REPORTED_ERRORS:
186+
errors.append(
187+
f"{len(mismatched) - MAX_REPORTED_ERRORS} more lines do not match "
188+
f"(first divergence at line {mismatched[0]})"
189+
)
190+
191+
if len(lines) < len(records):
192+
errors.append(
193+
f"Log is shorter than its sealed chain: {len(records) - len(lines)} sealed "
194+
f"line(s) missing from the end"
195+
)
115196

116197
return ChainVerification(
117-
valid=len(errors) == 0,
198+
valid=not errors,
118199
entries=len(lines),
119200
errors=errors,
201+
sealed=min(len(lines), len(records)),
202+
unsealed=max(0, len(lines) - len(records)),
120203
)
121204

122205

‎tests/test_audit_tamper.py‎

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
"""The audit log is called tamper-evident. These tests tamper with it.
2+
3+
Each one seals a log, changes it the way someone covering their tracks
4+
would, and requires verification to fail and to say where.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import json
10+
from pathlib import Path
11+
12+
import pytest
13+
14+
from agentix_logos.audit_chain import (
15+
SIDECAR_NAME,
16+
build_chain,
17+
save_chain_sidecar,
18+
verify_chain,
19+
)
20+
21+
EVENTS = [
22+
{"action": "snapshot", "modules": 55},
23+
{"action": "verify", "module": "codex", "passed": True},
24+
{"action": "verify", "module": "waku", "passed": False},
25+
{"action": "auto_rollback", "module": "waku", "to": "a1b2c3"},
26+
{"action": "propose", "module": "waku", "approved_by": "operator"},
27+
{"action": "apply", "module": "waku"},
28+
]
29+
30+
31+
@pytest.fixture
32+
def sealed(tmp_path: Path) -> Path:
33+
"""A six-line audit log with its chain sealed beside it."""
34+
audit_dir = tmp_path / ".agentix"
35+
audit_dir.mkdir()
36+
audit_path = audit_dir / "audit.jsonl"
37+
audit_path.write_text(
38+
"".join(json.dumps(e, sort_keys=True) + "\n" for e in EVENTS), encoding="utf-8"
39+
)
40+
save_chain_sidecar(build_chain(audit_path), audit_dir / SIDECAR_NAME)
41+
return audit_path
42+
43+
44+
def _lines(path: Path) -> list[str]:
45+
return path.read_text(encoding="utf-8").splitlines()
46+
47+
48+
def _rewrite(path: Path, lines: list[str]) -> None:
49+
path.write_text("".join(line + "\n" for line in lines), encoding="utf-8")
50+
51+
52+
def test_an_untouched_log_verifies(sealed: Path) -> None:
53+
result = verify_chain(sealed)
54+
assert result.valid is True
55+
assert result.errors == []
56+
assert (result.entries, result.sealed, result.unsealed) == (6, 6, 0)
57+
58+
59+
def test_rewriting_a_past_event_is_detected(sealed: Path) -> None:
60+
# the failed check becomes a pass; still valid JSON, same length
61+
lines = _lines(sealed)
62+
lines[2] = lines[2].replace("false", "true ")
63+
_rewrite(sealed, lines)
64+
65+
result = verify_chain(sealed)
66+
assert result.valid is False
67+
assert any(e.startswith("Line 2:") for e in result.errors)
68+
assert not any(e.startswith(("Line 0:", "Line 1:", "Line 3:")) for e in result.errors)
69+
70+
71+
@pytest.mark.parametrize("index", range(len(EVENTS)))
72+
def test_a_single_changed_character_on_any_line_is_detected(sealed: Path, index: int) -> None:
73+
lines = _lines(sealed)
74+
lines[index] = lines[index].replace("a", "b", 1)
75+
_rewrite(sealed, lines)
76+
77+
result = verify_chain(sealed)
78+
assert result.valid is False
79+
assert any(e.startswith(f"Line {index}:") for e in result.errors)
80+
81+
82+
def test_deleting_an_event_is_detected(sealed: Path) -> None:
83+
lines = _lines(sealed)
84+
del lines[3] # the rollback never happened
85+
_rewrite(sealed, lines)
86+
87+
result = verify_chain(sealed)
88+
assert result.valid is False
89+
assert any(e.startswith("Line 3:") for e in result.errors) # first divergence
90+
assert any("shorter than its sealed chain" in e for e in result.errors)
91+
92+
93+
def test_inserting_an_event_is_detected(sealed: Path) -> None:
94+
lines = _lines(sealed)
95+
lines.insert(4, json.dumps({"action": "propose", "approved_by": "nobody"}, sort_keys=True))
96+
_rewrite(sealed, lines)
97+
98+
result = verify_chain(sealed)
99+
assert result.valid is False
100+
assert any(e.startswith("Line 4:") for e in result.errors)
101+
102+
103+
def test_reordering_events_is_detected(sealed: Path) -> None:
104+
lines = _lines(sealed)
105+
lines[4], lines[5] = lines[5], lines[4] # applied before it was approved
106+
_rewrite(sealed, lines)
107+
108+
result = verify_chain(sealed)
109+
assert result.valid is False
110+
assert any(e.startswith("Line 4:") for e in result.errors)
111+
assert any(e.startswith("Line 5:") for e in result.errors)
112+
113+
114+
def test_cutting_the_log_short_is_detected(sealed: Path) -> None:
115+
_rewrite(sealed, _lines(sealed)[:4])
116+
117+
result = verify_chain(sealed)
118+
assert result.valid is False
119+
assert any("2 sealed line(s) missing" in e for e in result.errors)
120+
121+
122+
def test_appending_is_what_a_log_does_and_is_reported_not_refused(sealed: Path) -> None:
123+
with sealed.open("a", encoding="utf-8") as f:
124+
f.write(json.dumps({"action": "verify", "module": "codex"}, sort_keys=True) + "\n")
125+
126+
result = verify_chain(sealed)
127+
assert result.valid is True
128+
assert (result.sealed, result.unsealed) == (6, 1)
129+
130+
131+
def test_editing_the_sidecar_to_match_a_changed_line_is_detected(sealed: Path) -> None:
132+
# the careful attacker: change the event, then fix up its recorded CID
133+
from agentix_logos.audit_chain import compute_cid
134+
135+
lines = _lines(sealed)
136+
lines[2] = lines[2].replace("false", "true ")
137+
_rewrite(sealed, lines)
138+
139+
sidecar = sealed.parent / SIDECAR_NAME
140+
records = [json.loads(r) for r in sidecar.read_text(encoding="utf-8").splitlines()]
141+
records[2]["cid"] = compute_cid(lines[2])
142+
sidecar.write_text("".join(json.dumps(r, sort_keys=True) + "\n" for r in records), encoding="utf-8")
143+
144+
result = verify_chain(sealed)
145+
assert result.valid is False
146+
# entry 2's root no longer matches its fields, and entry 3 no longer links to it
147+
assert any(e.startswith("Chain entry 2:") for e in result.errors)
148+
assert any(e.startswith("Chain entry 3:") for e in result.errors)
149+
150+
151+
def test_a_garbled_sidecar_line_fails_instead_of_being_skipped(sealed: Path) -> None:
152+
sidecar = sealed.parent / SIDECAR_NAME
153+
records = sidecar.read_text(encoding="utf-8").splitlines()
154+
records[1] = "not json"
155+
sidecar.write_text("".join(r + "\n" for r in records), encoding="utf-8")
156+
157+
result = verify_chain(sealed)
158+
assert result.valid is False
159+
assert any(e.startswith("Chain entry 1:") for e in result.errors)
160+
161+
162+
def test_without_a_sidecar_nothing_is_claimed(tmp_path: Path) -> None:
163+
audit_dir = tmp_path / ".agentix"
164+
audit_dir.mkdir()
165+
audit_path = audit_dir / "audit.jsonl"
166+
audit_path.write_text(json.dumps({"action": "a"}) + "\n", encoding="utf-8")
167+
168+
result = verify_chain(audit_path)
169+
assert result.valid is True
170+
assert (result.sealed, result.unsealed) == (0, 1)

0 commit comments

Comments
 (0)