fix(dsh): preserve complete decision audit chain beyond display limit
This commit is contained in:
1 parent
27334fef81
commit
a99f84b25e
3 files changed
+198
-40
No files matched your search
@@ -1,16 +1,20 @@
|
||||
"""Append-only, hash-linked records for automatic DSH decisions."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import deque
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
from threading import RLock
|
||||
|
||||
from .evidence import scrub
|
||||
|
||||
_ID = re.compile(r"^[0-9a-f]{24}$")
|
||||
_MAX = 2000
|
||||
_MAX = 2000 # Presentation limit only; never limits append or verification.
|
||||
_LOCK = RLock()
|
||||
|
||||
|
||||
def _bounded(value, limit=1000):
|
||||
@@ -24,6 +28,18 @@ def _bounded(value, limit=1000):
|
||||
return value
|
||||
|
||||
|
||||
def _record_hash(value):
|
||||
body = {key: item for key, item in value.items() if key != 'record_hash'}
|
||||
payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return sha256(payload.encode('utf8')).hexdigest()
|
||||
|
||||
|
||||
class _CorruptLog(ValueError):
|
||||
def __init__(self, code, checked):
|
||||
super().__init__('decision_log_corrupt: ' + code)
|
||||
self.code, self.checked = code, checked
|
||||
|
||||
|
||||
class DecisionLog:
|
||||
def __init__(self, data_root):
|
||||
self.path = Path(data_root) / "dsh" / "decisions.jsonl"
|
||||
@@ -31,9 +47,27 @@ class DecisionLog:
|
||||
def append(self, record):
|
||||
if not isinstance(record, dict) or not _ID.fullmatch(str(record.get("incident_id", ""))):
|
||||
raise ValueError("incident_id")
|
||||
rows = self.list(limit=_MAX)
|
||||
previous = rows[-1]["record_hash"] if rows else ""
|
||||
value = {"sequence": len(rows) + 1, "at_utc": datetime.now(timezone.utc).isoformat(),
|
||||
# Validate the original bytes all the way to EOF. Display truncation or
|
||||
# redaction must never choose the next sequence or change hashed input.
|
||||
with _LOCK:
|
||||
sequence, previous = 0, ''
|
||||
for row in self._records():
|
||||
sequence, previous = row['sequence'], row['record_hash']
|
||||
value = self._new_record(record, sequence + 1, previous)
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self.path.open('a+b') as stream:
|
||||
if stream.tell():
|
||||
stream.seek(-1, os.SEEK_END)
|
||||
if stream.read(1) != b'\n':
|
||||
stream.write(b'\n')
|
||||
stream.write((json.dumps(value, ensure_ascii=False, sort_keys=True) + '\n').encode('utf8'))
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _new_record(record, sequence, previous):
|
||||
value = {"sequence": sequence, "at_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"previous_hash": previous, "incident_id": record["incident_id"],
|
||||
"trigger": _bounded(record.get("trigger", ""), 160),
|
||||
"evidence_refs": _bounded(record.get("evidence_refs", []), 300),
|
||||
@@ -42,44 +76,52 @@ class DecisionLog:
|
||||
"authorized_scope": _bounded(record.get("authorized_scope", {}), 600),
|
||||
"outcome": _bounded(record.get("outcome", "unknown"), 160),
|
||||
"human_takeover": bool(record.get("human_takeover", False))}
|
||||
payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
value["record_hash"] = sha256(payload.encode("utf8")).hexdigest()
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self.path.open("a", encoding="utf8") as stream:
|
||||
stream.write(json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n")
|
||||
stream.flush()
|
||||
return dict(value)
|
||||
value['record_hash'] = _record_hash(value)
|
||||
return value
|
||||
|
||||
def _records(self, sequence=None):
|
||||
"""Stream the complete raw chain, failing at the first invalid record."""
|
||||
try:
|
||||
stream = self.path.open('rb')
|
||||
except FileNotFoundError:
|
||||
return
|
||||
previous, checked = '', 0
|
||||
with stream:
|
||||
while sequence is None or checked < sequence:
|
||||
line = stream.readline()
|
||||
if not line:
|
||||
break
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except (ValueError, UnicodeError) as error:
|
||||
raise _CorruptLog('invalid_json', checked) from error
|
||||
if not isinstance(value, dict) or not _ID.fullmatch(str(value.get('incident_id', ''))):
|
||||
raise _CorruptLog('invalid_record', checked)
|
||||
if type(value.get('sequence')) is not int or value['sequence'] != checked + 1:
|
||||
raise _CorruptLog('sequence_mismatch', checked)
|
||||
if value.get('previous_hash') != previous or value.get('record_hash') != _record_hash(value):
|
||||
raise _CorruptLog('hash_mismatch', checked)
|
||||
previous, checked = value['record_hash'], checked + 1
|
||||
yield value
|
||||
|
||||
def list(self, limit=20):
|
||||
if not isinstance(limit, int) or limit <= 0:
|
||||
if type(limit) is not int or limit <= 0:
|
||||
return []
|
||||
rows = []
|
||||
try:
|
||||
with self.path.open(encoding="utf8") as stream:
|
||||
for line in stream:
|
||||
if len(rows) >= min(limit, _MAX):
|
||||
break
|
||||
try:
|
||||
value = json.loads(line)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
if isinstance(value, dict) and _ID.fullmatch(str(value.get("incident_id", ""))):
|
||||
rows.append(_bounded(value, 2000))
|
||||
except OSError:
|
||||
return []
|
||||
return rows
|
||||
with _LOCK:
|
||||
rows = deque(self._records(), maxlen=min(limit, _MAX))
|
||||
return [_bounded(row, 2000) for row in rows]
|
||||
|
||||
def verify(self, sequence=None):
|
||||
rows = self.list(limit=_MAX)
|
||||
previous = ""
|
||||
checked = 0
|
||||
for value in rows:
|
||||
if sequence is not None and value.get("sequence") > sequence:
|
||||
break
|
||||
expected = value.get("record_hash")
|
||||
body = {key: item for key, item in value.items() if key != "record_hash"}
|
||||
payload = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
if value.get("previous_hash") != previous or expected != sha256(payload.encode("utf8")).hexdigest():
|
||||
return {"valid": False, "checked": checked, "error": "hash_mismatch"}
|
||||
previous, checked = expected, checked + 1
|
||||
return {"valid": True, "checked": checked, "last_hash": previous}
|
||||
"""Verify every record unless the caller explicitly requests a prefix."""
|
||||
if sequence is not None and (type(sequence) is not int or sequence < 1):
|
||||
raise ValueError('decision_sequence')
|
||||
with _LOCK:
|
||||
previous, checked = '', 0
|
||||
try:
|
||||
for value in self._records(sequence):
|
||||
previous, checked = value['record_hash'], checked + 1
|
||||
except _CorruptLog as error:
|
||||
return {'valid': False, 'checked': error.checked, 'error': error.code}
|
||||
except OSError:
|
||||
return {'valid': False, 'checked': checked, 'error': 'read_unavailable'}
|
||||
return {"valid": True, "checked": checked, "last_hash": previous}
|
||||
Reference in new issue
Block a user