Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(audit): detect deletion of the newest audit rows (#1250)

antigravitysoham-enga32b3866ed51
diff --git a/services/api/app/api/v1/endpoints/health.py b/services/api/app/api/v1/endpoints/health.py
index 7cac5050f..e7d97d800 100644
--- a/services/api/app/api/v1/endpoints/health.py
+++ b/services/api/app/api/v1/endpoints/health.py
@@ -86,7 +86,7 @@ from app.core.config import settings
from app.db.rls import TenantDBSession
from app.models.alert import Alert
from app.models.connector import Connector
-from app.services.audit_hash import verify_chain_breaks
+from app.services.audit_hash import verify_chain_breaks, verify_chain_tail
from app.services.connector_freshness import compute_freshness
from app.services.dlq_replay_gateway import DlqReplayRequest, DlqReplayResponse, run_replay
from app.services.fleet_health import assess_fleet
@@ -689,6 +689,19 @@ async def get_audit_chain_health(
.one()
)
+ # The head is read before the rows so a concurrent append cannot look
+ # like truncation (see verify_chain_tail).
+ head = (
+ (
+ await db.execute(
+ text("SELECT head_hash, next_index, updated_at FROM audit_chain_head WHERE tenant_id = :tid"),
+ {"tid": user.tenant_id},
+ )
+ )
+ .mappings()
+ .one_or_none()
+ )
+
# Ordered by `chain_index` first, which is the order the serialized
# appender actually chained in. `(created_at, id)` is the fallback for
# epoch-1 rows, which have no index — and is precisely the ambiguity
@@ -716,22 +729,12 @@ async def get_audit_chain_health(
)
replay = [dict(r) for r in reversed(rows)]
breaks = verify_chain_breaks(replay)
- intact = not breaks
+ tail_break = verify_chain_tail(replay, dict(head) if head else None)
+ intact = not breaks and tail_break is None
bad_index = int(breaks[0]["index"]) if breaks else None
- reason = str(breaks[0]["reason"]) if breaks else None
+ reason = str(breaks[0]["reason"]) if breaks else (tail_break["reason"] if tail_break else None)
epoch2_breaks = [b for b in breaks if (b.get("chain_epoch") or 1) >= 2]
- head = (
- (
- await db.execute(
- text("SELECT head_hash, next_index, updated_at FROM audit_chain_head WHERE tenant_id = :tid"),
- {"tid": user.tenant_id},
- )
- )
- .mappings()
- .one_or_none()
- )
-
unchained = int(counts["unchained"] or 0)
return {
# Two facts, reported separately, because they have different causes
@@ -750,6 +753,11 @@ async def get_audit_chain_health(
"oldest_unchained_at": counts["oldest_unchained"].isoformat() if counts["oldest_unchained"] else None,
"newest_unchained_at": counts["newest_unchained"].isoformat() if counts["newest_unchained"] else None,
"replay_window": len(replay),
+ # Deleting the newest rows leaves every remaining link valid; only the
+ # stored head shows the chain used to be longer.
+ "tail_intact": tail_break is None,
+ "tail_reason": tail_break["reason"] if tail_break else None,
+ "tail_missing_rows": tail_break["missing"] if tail_break else 0,
# `replay_intact` covers the whole window including history. It can be
# false forever on a deployment that forked before migration 074, and
# that is the honest answer — those rows were not re-chained, because
diff --git a/services/api/app/services/audit_hash.py b/services/api/app/services/audit_hash.py
index a2e4e6854..d7c50819f 100644
--- a/services/api/app/services/audit_hash.py
+++ b/services/api/app/services/audit_hash.py
@@ -201,6 +201,45 @@ def verify_chain_breaks(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
return breaks
+def verify_chain_tail(rows: list[dict[str, Any]], head: dict[str, Any] | None) -> dict[str, Any] | None:
+ """Compare the newest chained row with the stored chain head.
+
+ :func:`verify_chain_breaks` checks the links *between* rows, so deleting
+ the newest rows leaves a chain that replays cleanly: every surviving link
+ is still valid. ``audit_chain_head`` remembers where the chain ended
+ (``next_index``, ``head_hash``), which is what makes truncation visible.
+
+ Read the head **before** the rows. An append that lands between the two
+ reads only makes the newest row newer than the head, which is not a
+ break; a deleted tail leaves the newest row short of it, which is.
+
+ Returns ``None`` when the tail matches, else a break dict with ``reason``
+ and ``missing`` (rows the head says exist and the table does not have).
+ """
+ if not head or head.get("next_index") is None:
+ return None
+ head_next = int(head["next_index"])
+ indexed = [r for r in rows if r.get("chain_index") is not None and r.get("entry_hash")]
+ newest = max(indexed, key=lambda r: int(r["chain_index"])) if indexed else None
+ newest_next = int(newest["chain_index"]) + 1 if newest else 0
+ if newest_next >= head_next:
+ if newest_next == head_next and newest is not None and head.get("head_hash") not in (None, newest.get("entry_hash")):
+ return {
+ "reason": "chain head hash does not match the newest row",
+ "missing": 0,
+ "chain_index": newest_next - 1,
+ }
+ return None
+ return {
+ "reason": (
+ f"chain head expects next_index {head_next} but the newest row is "
+ f"chain_index {newest_next - 1}: {head_next - newest_next} row(s) missing from the tail"
+ ),
+ "missing": head_next - newest_next,
+ "chain_index": newest_next - 1,
+ }
+
+
def verify_chain(rows: list[dict[str, Any]]) -> tuple[bool, int | None, str | None]:
"""Replay ``rows`` (oldest → newest, same tenant) and verify the chain.
diff --git a/services/api/tests/test_audit_chain_tail.py b/services/api/tests/test_audit_chain_tail.py
new file mode 100644
index 000000000..454a433d2
--- /dev/null
+++ b/services/api/tests/test_audit_chain_tail.py
@@ -0,0 +1,44 @@
+"""verify_chain_tail: truncation of the newest audit rows must be visible."""
+
+from app.services.audit_hash import verify_chain_tail
+
+
+def _rows(n):
+ return [{"chain_index": i, "entry_hash": f"h{i}"} for i in range(n)]
+
+
+def test_intact_tail_is_not_a_break():
+ assert verify_chain_tail(_rows(3), {"next_index": 3, "head_hash": "h2"}) is None
+
+
+def test_deleting_the_newest_row_is_a_break():
+ # Observed on v17.1: rows 0..2 written, row 2 deleted with the immutability
+ # trigger disabled, /health/audit-chain still reported replay_intact=true.
+ brk = verify_chain_tail(_rows(2), {"next_index": 3, "head_hash": "h2"})
+ assert brk is not None and brk["missing"] == 1
+
+
+def test_deleting_every_row_is_a_break():
+ brk = verify_chain_tail([], {"next_index": 3, "head_hash": "h2"})
+ assert brk is not None and brk["missing"] == 3
+
+
+def test_append_after_the_head_was_read_is_not_a_break():
+ assert verify_chain_tail(_rows(4), {"next_index": 3, "head_hash": "h2"}) is None
+
+
+def test_replaced_newest_row_is_a_break():
+ rows = _rows(3)
+ rows[-1]["entry_hash"] = "forged"
+ brk = verify_chain_tail(rows, {"next_index": 3, "head_hash": "h2"})
+ assert brk is not None and brk["missing"] == 0
+
+
+def test_no_head_yet_is_not_a_break():
+ assert verify_chain_tail([], None) is None
+ assert verify_chain_tail([], {"next_index": 0, "head_hash": None}) is None
+
+
+def test_legacy_unindexed_rows_are_ignored():
+ rows = [{"chain_index": None, "entry_hash": "x"}, *_rows(2)]
+ assert verify_chain_tail(rows, {"next_index": 2, "head_hash": "h1"}) is None