Coverage for audit/status_export.py: 100%

25 statements  

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

1"""Dashboard/monitoring JSON export for the audit log (development/Problems.md 

2#42). Same reason as retraining/status_export.py: main.py never connects to 

3Postgres, only Redis, so monitoring/api_server.py can't query audit_log 

4directly - this module is the sole writer of 

5visualization/grafana/audit_log.json, refreshed by audit/postgres_worker.py 

6after every batch it persists (real-time-ish, not a periodic cron export, 

7since a stale audit trail defeats its own purpose). 

8""" 

9 

10from __future__ import annotations 

11 

12from datetime import date, datetime, timezone 

13from pathlib import Path 

14from typing import Any 

15 

16from json_safety import atomic_write_json 

17 

18from .hash_chain import verify_chain 

19from .postgres_audit import fetch_all_events_ordered, fetch_recent_events 

20 

21ROOT_DIR = Path(__file__).resolve().parent.parent 

22DEFAULT_STATUS_PATH = ROOT_DIR / "visualization" / "grafana" / "audit_log.json" 

23 

24# Dashboard snapshot only ever shows the most recent N entries (unlike 

25# `aq audit-log`'s CLI, which can page further back) - the webui panel is 

26# "what's happened recently," not a full audit browser. 

27_DASHBOARD_ENTRY_LIMIT = 50 

28 

29 

30def _json_safe(value: Any) -> Any: 

31 if isinstance(value, (datetime, date)): 

32 return value.isoformat() 

33 if isinstance(value, dict): 

34 return {key: _json_safe(item) for key, item in value.items()} 

35 if isinstance(value, (list, tuple)): 

36 return [_json_safe(item) for item in value] 

37 return value 

38 

39 

40def build_audit_status_view(conn) -> dict: 

41 """{generated_at, recent_events, chain_valid, total_entries}. Chain 

42 verification runs over the FULL table (fetch_all_events_ordered), not 

43 just the dashboard's recent-N slice - a tampered OLD entry must still 

44 surface as chain_valid=False even if it's scrolled off the recent list.""" 

45 recent = fetch_recent_events(conn, limit=_DASHBOARD_ENTRY_LIMIT) 

46 all_rows = fetch_all_events_ordered(conn) 

47 chain_valid, broken_index = verify_chain(all_rows) 

48 

49 return { 

50 "generated_at": datetime.now(timezone.utc).isoformat(), 

51 "total_entries": len(all_rows), 

52 "chain_valid": chain_valid, 

53 "chain_broken_at_event_id": all_rows[broken_index]["event_id"] if broken_index is not None else None, 

54 "recent_events": [_json_safe(event) for event in recent], 

55 } 

56 

57 

58def write_status_file(status: dict, path: Path = DEFAULT_STATUS_PATH) -> None: 

59 # V5.4.7 (Problems.md #120): atomic + finite-safe - the API reader 

60 # previously raced this write and 500'd on torn JSON. 

61 atomic_write_json(path, status, indent=2) 

62 

63