Personal AI, On Personal Devices
Python
fix(security): serialize audit chain writes (#932)
Haotian Zheng94c191ee3077
diff --git a/src/openjarvis/security/audit.py b/src/openjarvis/security/audit.pyindex 888fe160..40df1c90 100644--- a/src/openjarvis/security/audit.py+++ b/src/openjarvis/security/audit.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport hashlibimport jsonimport sqlite3+import threading+from functools import wrapsfrom pathlib import Pathfrom typing import List, Optional, Tuple, Union@@ -18,6 +20,17 @@ from openjarvis.security.types import ()+def _db_locked(func):+ """Serialize access to an audit connection shared by worker threads."""++ @wraps(func)+ def wrapped(self, *args, **kwargs):+ with self._db_lock:+ return func(self, *args, **kwargs)++ return wrapped++class AuditLogger:"""Append-only SQLite audit log for security events.@@ -39,6 +52,7 @@ class AuditLogger:from openjarvis.security.file_utils import secure_createsecure_create(self._db_path)+ self._db_lock = threading.RLock()self._conn = sqlite3.connect(str(self._db_path), check_same_thread=False)self._conn.execute("""@@ -62,6 +76,7 @@ class AuditLogger:bus.subscribe(EventType.SECURITY_ALERT, self._on_event)bus.subscribe(EventType.SECURITY_BLOCK, self._on_event)+ @_db_lockeddef _migrate_schema(self) -> None:"""Add row_hash/prev_hash columns if missing (schema migration)."""columns = {@@ -82,6 +97,7 @@ class AuditLogger:# -- public API ----------------------------------------------------------+ @_db_lockeddef log(self, event: SecurityEvent) -> None:"""Insert a security event into the audit log with Merkle hash chain."""findings_json = json.dumps(@@ -98,33 +114,41 @@ class AuditLogger:])- # Compute hash chain- prev_hash = self.tail_hash()- hash_input = (- f"{prev_hash}|{event.timestamp}|{event.event_type.value}"- f"|{findings_json}|{event.content_preview}|{event.action_taken}"- )- row_hash = hashlib.sha256(hash_input.encode()).hexdigest()+ # Serialize writers across both threads and independent connections.+ # A deferred transaction would let two writers read the same tail+ # before either insert commits, breaking the Merkle chain.+ self._conn.execute("BEGIN IMMEDIATE")+ try:+ prev_hash = self.tail_hash()+ hash_input = (+ f"{prev_hash}|{event.timestamp}|{event.event_type.value}"+ f"|{findings_json}|{event.content_preview}|{event.action_taken}"+ )+ row_hash = hashlib.sha256(hash_input.encode()).hexdigest()- self._conn.execute(- """- INSERT INTO security_events- (timestamp, event_type, findings_json, content_preview,- action_taken, row_hash, prev_hash)- VALUES (?, ?, ?, ?, ?, ?, ?)- """,- (- event.timestamp,- event.event_type.value,- findings_json,- event.content_preview,- event.action_taken,- row_hash,- prev_hash,- ),- )- self._conn.commit()+ self._conn.execute(+ """+ INSERT INTO security_events+ (timestamp, event_type, findings_json, content_preview,+ action_taken, row_hash, prev_hash)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ """,+ (+ event.timestamp,+ event.event_type.value,+ findings_json,+ event.content_preview,+ event.action_taken,+ row_hash,+ prev_hash,+ ),+ )+ self._conn.commit()+ except Exception:+ self._conn.rollback()+ raise+ @_db_lockeddef query(self,*,@@ -177,6 +201,7 @@ class AuditLogger:)return events+ @_db_lockeddef tail_hash(self) -> str:"""Return the hash of the last row in the chain, or empty string."""row = self._conn.execute(@@ -184,6 +209,7 @@ class AuditLogger:).fetchone()return row[0] if row and row[0] else ""+ @_db_lockeddef verify_chain(self) -> Tuple[bool, Optional[int]]:"""Verify the Merkle hash chain integrity.@@ -217,11 +243,13 @@ class AuditLogger:return True, None+ @_db_lockeddef count(self) -> int:"""Return the total number of logged security events."""row = self._conn.execute("SELECT COUNT(*) FROM security_events").fetchone()return row[0] if row else 0+ @_db_lockeddef close(self) -> None:"""Close the SQLite connection."""self._conn.close()diff --git a/tests/security/test_merkle_audit.py b/tests/security/test_merkle_audit.pyindex bd6f25b4..361267e8 100644--- a/tests/security/test_merkle_audit.py+++ b/tests/security/test_merkle_audit.py@@ -2,6 +2,7 @@from __future__ import annotations+import threadingimport timefrom openjarvis.security.audit import AuditLogger@@ -94,6 +95,51 @@ class TestMerkleAudit:assert logger.count() == 2logger.close()+ def test_concurrent_loggers_preserve_chain(self, tmp_path):+ """Concurrent writers must link each event to the committed predecessor."""+ db_path = tmp_path / "audit.db"+ first_tail_read = threading.Event()+ release_first_tail_read = threading.Event()++ class ControlledAuditLogger(AuditLogger):+ def tail_hash(self):+ if not first_tail_read.is_set():+ first_tail_read.set()+ assert release_first_tail_read.wait(timeout=5)+ return super().tail_hash()++ loggers = [+ ControlledAuditLogger(db_path=db_path),+ ControlledAuditLogger(db_path=db_path),+ ]+ errors = []++ def write(logger, content):+ try:+ logger.log(_make_event(content=content))+ except Exception as exc: # noqa: BLE001 - capture race symptoms+ errors.append(exc)++ first = threading.Thread(target=write, args=(loggers[0], "first"))+ second = threading.Thread(target=write, args=(loggers[1], "second"))+ first.start()+ assert first_tail_read.wait(timeout=5)+ second.start()+ release_first_tail_read.set()+ first.join(timeout=5)+ second.join(timeout=5)++ assert errors == []+ assert not first.is_alive()+ assert not second.is_alive()+ for logger in loggers:+ logger.close()++ verifier = AuditLogger(db_path=db_path)+ assert verifier.count() == 2+ assert verifier.verify_chain() == (True, None)+ verifier.close()+def test_query_returns_events(self, tmp_path):db_path = tmp_path / "audit.db"logger = AuditLogger(db_path=db_path)