Coverage for audit/hash_chain.py: 100%

35 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Pure tamper-evidence logic for the audit log (development/Problems.md #42). 

2 

3Each row's hash covers its own content plus the previous row's hash, so 

4altering or deleting any historical row breaks every hash after it - the 

5same construction git commits / blockchains use, just for one linear table 

6instead of a DAG. No I/O here on purpose: audit/postgres_worker.py computes 

7each new row's hash at insert time (fetching the current chain tail first), 

8and audit/postgres_audit.py's callers (the CLI's --verify, the API route) 

9re-verify an already-fetched list of rows through verify_chain() below. 

10""" 

11 

12from __future__ import annotations 

13 

14import datetime 

15import hashlib 

16import json 

17from typing import Any 

18 

19# The hash of the very first entry in the chain (no predecessor to link to) - 

20# a fixed, well-known genesis value rather than None/empty-string, so an 

21# empty prev_hash column can never be confused with "chain not yet verified". 

22GENESIS_HASH = "0" * 64 

23 

24 

25def canonical_timestamp(value: datetime | str) -> str: 

26 """The text a row's timestamp is hashed as, and read back as (Problems #339). Postgres stores `created_at` in a TIMESTAMPTZ column and returns a `datetime`, while the hash was taken over 

27 the producer's string, so a chain read back from a real database could not be verified: `verify_chain` raised on the datetime, and would have mismatched on the offset's spelling even if 

28 it had not. A datetime, or an ISO 8601 string that parses, is written in UTC as `YYYY-MM-DDTHH:MM:SSZ` (with microseconds only when there are some); anything else is returned as it is. 

29 `build_audit_event` already writes that form, so rows hashed before this existed verify unchanged.""" 

30 moment = value 

31 if isinstance(value, str): 

32 try: 

33 moment = datetime.datetime.fromisoformat(value.replace("Z", "+00:00") if value.endswith("Z") else value) 

34 except ValueError: 

35 return value 

36 if not isinstance(moment, datetime.datetime): 

37 return str(value) 

38 if moment.tzinfo is None: 

39 moment = moment.replace(tzinfo=datetime.timezone.utc) 

40 moment = moment.astimezone(datetime.timezone.utc) 

41 return moment.strftime("%Y-%m-%dT%H:%M:%S.%fZ") if moment.microsecond else moment.strftime("%Y-%m-%dT%H:%M:%SZ") 

42 

43 

44def compute_entry_hash(prev_hash: str, event_type: str, created_at: str, payload: dict[str, Any]) -> str: 

45 """sha256(prev_hash || event_type || created_at || canonical-JSON payload). 

46 

47 `created_at` must be a string (ISO 8601), not a datetime - callers own 

48 formatting so this stays pure and independent of any particular 

49 Postgres driver's timestamp type. `payload` is serialized with sorted 

50 keys and no extra whitespace so the same logical event always hashes 

51 identically regardless of dict insertion order. 

52 """ 

53 canonical_payload = json.dumps(payload, sort_keys=True, separators=(",", ":")) 

54 digest_input = "|".join([prev_hash, event_type, created_at, canonical_payload]) 

55 return hashlib.sha256(digest_input.encode("utf-8")).hexdigest() 

56 

57 

58def verify_chain(rows: list[dict], expected_tail_hash: str | None = None) -> tuple[bool, int | None]: 

59 """Walks `rows` (each needing prev_hash/hash/event_type/created_at/payload 

60 keys, oldest-first) recomputing every hash and comparing. Returns 

61 (all_valid, first_broken_index) - first_broken_index is None when 

62 all_valid is True, else the 0-based index of the first row whose 

63 prev_hash doesn't match the prior row's hash, or whose own hash doesn't 

64 match its recomputed value. An empty list is trivially valid. 

65 

66 Deleting the newest rows leaves a valid chain: every prefix of a valid chain is valid 

67 (formal/AetherFormal/HashChain.lean, `truncation_undetected`). `expected_tail_hash`, the latest hash recorded 

68 somewhere else, closes that gap: a chain that does not end on it reports index len(rows).""" 

69 expected_prev = GENESIS_HASH 

70 for index, row in enumerate(rows): 

71 if row["prev_hash"] != expected_prev: 

72 return False, index 

73 recomputed = compute_entry_hash(row["prev_hash"], row["event_type"], row["created_at"], row["payload"]) 

74 if recomputed != row["hash"]: 

75 return False, index 

76 expected_prev = row["hash"] 

77 if expected_tail_hash is not None and expected_prev != expected_tail_hash: 

78 return False, len(rows) 

79 return True, None