Skip to content

fix(convex): harden audit integrity verifier and cron coverage (#1846) - #2218

Merged
yannickmonney merged 2 commits into
mainfrom
tale/xs76gnecd7jq2ph36pdbjsnsgd89e4ge
Jun 29, 2026
Merged

yannickmonney merged 2 commits into
mainfrom
tale/xs76gnecd7jq2ph36pdbjsnsgd89e4ge

Conversation

@larryro

@larryro larryro commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Summary

Resolves the five coverage gaps and latent chain hazards reported in #1846 for the audit-log integrity verifier (verify_integrity.ts) and its daily cron (integrity_check.ts).

1. Orgs beyond the first 500 were never checked

listAuditedOrganizationIds always took the same first MAX_ORGS_PER_RUN genesis rows. Replaced with selectOrgsForIntegrityRun, which ranks orgs round-robin by staleness (auditIntegrityProgress.updatedAt) and verifies the stalest window each run — so every org is reached across runs, and the cron's "checked on the next run" log line is now true.

2. Rows past the oldest window were never verified

The cron re-walked the oldest rows every run, never reaching the newest segment where live tampering would land. It now pages forward across runs from a persisted per-org cursor (new additive auditIntegrityProgress table), covering the whole chain over successive runs.

3. The documented fromTimestamp resume always reported a false break

On resume, previousExpectedHash started '' and the only seeding site lived inside the skipped isFirstEntry block, so the first resumed row's real previousHash was compared against '' → guaranteed firstBrokenAt. verifyAuditChain now accepts afterId + previousExpectedHash, seeds the linkage from the previous page's hash, and uses an exclusive (timestamp, _id) cursor so same-timestamp siblings of the boundary row are verified rather than skipped. A fromTimestamp-only resume no longer false-breaks (boundary trusted), and a retention-deleted cursor falls back to a seeded re-walk instead of stalling.

4. No write-side timestamp monotonicity clamp (clock regression orphaned a row)

createAuditLog now clamps the chain timestamp to max(now, genesis.lastInsertedAt + 1). A backward wall-clock step (NTP correction, VM snapshot restore) can no longer sort a new row before the head it chains off — eliminating the permanent false tamper alarm. The genesis row is already read+patched for OCC, so the clamp is free.

5. Same-mutation parallel appends could fork the chain

Within one mutation there was no OCC: two createAuditLog calls under Promise.all both read the same head and committed the same previousHash. createAuditLog now serializes appends sharing a MutationCtx (per-ctx promise chain), so each observes the previous insert as its lastEntry. Cross-mutation forks remain guarded by the genesis sentinel + chainSuccessor OCC patch.

Tests

  • New chain_integrity_hardening.test.ts covers all five fixes (intra-mutation fork, clock-skew clamp, paged resume + false-break guard, forward cursor advancement, org selection).
  • All convex/audit_logs/ tests pass (36), plus governance/legal_hold + users suites (29) which exercise the shared audit writer.

Verification

  • bunx tsc --noEmit — clean
  • bunx oxlint --type-aware on touched files — 0 warnings/errors
  • bun run migrations:check — green (new table is data-safe; no migration needed)
  • SAST (Opengrep) pre-commit hook on changed files — 0 findings

No user-visible strings, env vars, or docs changed (internal backend control), so translations/docs are N/A.

Closes #1846

Close five coverage gaps and latent chain hazards in the audit-log
integrity verifier and its daily cron:

1. Org cap — the cron now selects orgs round-robin by staleness and
   persists per-org progress, so every org is reached across runs
   instead of re-checking the same first MAX_ORGS_PER_RUN forever.
2. Unverified tail — the cron pages FORWARD across runs from each org's
   persisted cursor (new auditIntegrityProgress table), so the newest
   rows are covered rather than only the oldest window.
3. Broken resume — verifyAuditChain seeds the linkage from the previous
   page's hash and skips up to/including an exact (timestamp, _id)
   cursor, fixing the guaranteed false break on a resumed page and the
   skipped same-timestamp siblings.
4. Clock skew — createAuditLog clamps the chain timestamp to
   max(now, lastInsertedAt + 1) so a backward wall-clock step can no
   longer orphan a row and raise a false tamper alarm.
5. Intra-mutation fork — createAuditLog serializes appends sharing a
   MutationCtx so parallel same-org writes under Promise.all can no
   longer commit a duplicate previousHash (a silent fork).

Adds chain_integrity_hardening.test.ts covering all five.

Closes #1846
@larryro

larryro commented Jun 27, 2026

Copy link
Copy Markdown
Contributor Author

Desk Review — PR #2218 (fix for #1846)

Verdict: NOT READY — CHANGES REQUIRED. One reproducible correctness defect that makes this control raise false critical "tamper detected" alerts during ordinary retention, plus a coverage hole that re-introduces issue #1846 item 1's starvation under error conditions.

CI & tests (observed)

  • CI: green. gh pr checks — all real checks pass (Type check, Lint, Unit, Build platform/convex, Opengrep, Migrations, Playwright ×16, etc.). The "skipping" entries are fork-PR job variants, expected.
  • Tests run locally (single setup): bunx vitest --run --project server convex/audit_logs/ → 36 passed; … convex/governance/legal_hold convex/users → 29 passed. Matches the PR body's claim.

What is correct

Items 4 (clock clamp), 5 runtime serialization (per-ctx WeakMap tail — verified read-after-write ordering, error propagation, and OCC composition are sound), the round-robin org selection happy path, forward cursor advancement, "never advance past a break", headReached logic, and the same-timestamp _id-keyed cursor are all sound. The cron is correctly registered (crons.ts, daily 02:00 UTC). verifyAuditChainForOrg as an internalQuery is a sound access boundary; no RLS/crypto regression.


BLOCKING 1 — Deleted-afterId resume produces a FALSE firstBrokenAt (false critical tamper alert)

File: services/platform/convex/audit_logs/verify_integrity.ts:359-373 (fallback re-walk) together with :395-400 / :545-548 (needsSeed/seed).

When the persisted cursor row (afterId) has been hard-deleted by retention since the last run, the walk takes the fallback re-walk (:363-373). Because the cron always supplies previousExpectedHash (integrity_check.ts:113-116), needsSeed is false, so the seed at :545-548 is not applied and previousExpectedHash keeps the deleted cursor row's hash. The first surviving row's previousHash is then compared (:550) against that stale hash. The checkpoint re-anchor logic (:508-537) is skipped on any resume (isFirstEntry=false), so a legitimate retention deletion boundary is never re-anchored.

  • If retention deleted the cursor row and one or more rows after it (the realistic case — a daily retention cutoff jumps past the cursor by more than one row; especially right after this fix deploys, when every existing org's fresh cursor sits in the oldest rows near the retention boundary), the first surviving row's previousHash ≠ the stale hash → firstBrokenAt with zero tampering.
  • classifyIntegrityFinding maps any firstBrokenAt to kind:'tampering' → critical in-app + Slack alert (integrity_check.ts:201-204, notifyIntegrityFailure). The cursor never advances past a "break", so it re-fires every daily run until manual intervention.

This directly undermines the control this PR is hardening, and is the same class of false-alarm that started the investigation.

Reproduced with a throwaway convex-test (added, confirmed failing, then removed — working tree unchanged): page 1 verifies oldest 2 rows; delete the cursor row + intervening rows (indices 0–3 of 6) leaving indices 4–5; resume with the full cron cursor →
{"valid":false,"firstBrokenAt":{...},"verifiedCount":0}. The control case (deletion stopping exactly at the cursor row) correctly returns valid:true.

Required fix: in the afterId-not-found fallback (verify_integrity.ts:363-373), do not trust the stale supplied previousExpectedHash for the first surviving row — set needsSeed = true so the first surviving row's own previousHash is adopted (boundary trusted, as the fromTimestamp-only path already does), or re-anchor against the retention checkpoint. Add a regression test for the "retention deleted the cursor row AND rows after it" case.

BLOCKING 2 — Erroring orgs never rotate; re-introduces item-1 starvation under errors

File: services/platform/convex/audit_logs/integrity_check.ts:273-280.

When verifyAuditChainForOrg throws, the handler logs and continues without calling recordIntegrityProgress, so the org's auditIntegrityProgress.updatedAt is never bumped. Selection ranks by updatedAt ascending with sentinel -1 for never-checked orgs (:60-71), so a never-checked org that deterministically throws sorts to the front every run. With more than MAX_ORGS_PER_RUN (500) such orgs they permanently occupy all slots and healthy orgs past the first window are never reached — exactly the "no org permanently outside the control" guarantee item 1 claims to restore, defeated under error conditions. (A detected break returns valid:false, it does not throw, so it is unaffected — this is specifically the throw path.)

Required fix: in the catch at :273-280, still rotate the org to the back — e.g. bump updatedAt (record progress with the unchanged prior cursor, or a dedicated "touch") so an erroring org cannot starve the queue. Add a test for a throwing org.


Non-blocking (should address / note)

  1. Item 5's explicitly-requested guard is missing. Bug: audit integrity verifier/cron coverage gaps and latent chain hazards (org cap, unverified tail, broken resume, clock skew, intra-mutation fork) #1846 item 5 asked for "a lint/test guard against Promise.all-wrapped createAuditLog." Only a behavioral test exists; no oxlint no-restricted-syntax rule. The runtime serializer makes the pattern safe, so this is defense-in-depth, but it is an unmet stated sub-requirement the PR body silently dropped.
  2. Forward clock-drift trap (helpers.ts:266): a large forward clock step pins lastInsertedAt high, ratcheting all future timestamps by +1ms detached from real time and potentially starving retention. Latent/low-probability but undocumented — at least note the tradeoff, ideally cap when lastInsertedAt > now + MAX_SKEW.
  3. verifyAuditChainForOrg lacks a returns validator (integrity_check.ts:97) — the only function in the file without one; AGENTS.md asks for it.
  4. Test gaps: the deleted-afterId fallback (BLOCKING 1), the break-detected-cursor-does-not-advance path, the >MAX_ORGS_PER_RUN truncation/rotation path, and the erroring-org path (BLOCKING 2) are all untested.
  5. headReached is persisted but never read — justify in the comment or drop.
  6. Persistent breaks / config (no-key) gaps re-alert daily with no suppression — confirm this alert cadence is intended.

NOT READY — CHANGES REQUIRED. Address BLOCKING 1 (false tamper alert on retention-deleted cursor) and BLOCKING 2 (erroring-org starvation) with regression tests; the non-blocking items are recommended.

@larryro

larryro commented Jun 27, 2026

Copy link
Copy Markdown
Contributor Author

Desk Review — PR #2218 (fix(convex): harden audit integrity verifier and cron coverage) for issue #1846

Verdict: READY TO MERGE. All five reported items are correctly and robustly fixed, CI is confirmed green, and the project's own tests pass. Findings below are non-blocking quality / robustness / coverage notes for optional follow-up.

CI state

gh pr checks — all required checks PASS (Analyze js/py, Build platform/convex/db/+, Lint, Type check, Format, Knip, Migrations, Opengrep, Unit, UI, Storybook, Smoke, all 16 Playwright platform shards, web/docs). The only non-pass entries are conditional skipping jobs (fork-PR / Trivy / web+docs container tests) that do not apply to this PR. No red, no pending.

Tests run (this review, locally on the branch)

  • bunx vitest --run --project server audit_logs → 39 passed.
  • bunx vitest --run --project server governance/legal_hold users (shared audit writer) → 29 passed.
  • bun run migrations:check → green (new auditIntegrityProgress table classified data-safe; no migration needed). bunx tsc --noEmit → clean.
  • Added two throwaway probe tests (since removed): confirmed a body-tampered row and a linkage-tampered first row on a RESUMED page are both still CAUGHT (firstBrokenAt at the tampered row). The new boundary-trust logic does not mask tampering on the normal cron resume path.

What was verified correct (per item)

  1. Org cap (item 1): selectOrgsForIntegrityRun ranks orgs round-robin by auditIntegrityProgress.updatedAt (never-checked = -1 sort first), so every org is reached across runs. Erroring orgs are rotated to the back via touchIntegrityProgress (bumps updatedAt, not the cursor) so a deterministically-throwing org can't starve the fleet.
  2. Unverified tail (item 2): forward paging from a persisted per-org cursor; traced a 12000-row / 5000-window scenario end to end — coverage converges and the newest rows are reached. headReached is informational only and never gates resume. Truncation is surfaced as a warning, not a failure.
  3. Broken resume (item 3): afterId (_id-keyed, exact) + previousExpectedHash seeding fixes the guaranteed false break; same-timestamp siblings across a page boundary are verified exactly once; the deleted-cursor path re-seeds from the first surviving row instead of false-breaking. Normal resume cross-checks the boundary (not trusted) — empirically confirmed.
  4. Clock skew (item 4): write-side timestamp = max(now, genesis.lastInsertedAt + 1) clamp piggybacks the existing genesis OCC read/patch; backward steps, first-write, concurrent writers, retention and PII-scrub paths all keep head-pick (desc) and verify walk (asc) consistent; per-org timestamps are now strictly unique.
  5. Intra-mutation fork (item 5): per-ctx WeakMap promise-chain serializes appends sharing a MutationCtx; settles on resolve OR reject so a failed sibling can't race the head read; returns the real promise to callers. Verified non-tautological (pre-fix code forks; this doesn't).

Hash parity holds: writer (buildAuditRecordHashInput) and verifier reconstruct the same field set, and post-write fields (chainSuccessor, piiScrubbedAt, lifecycleStatus, statusChangedAt) are in EXCLUDED_FIELDS. Security posture preserved: admin gate on the public query intact, cron query is internal-only, cron cursor is server-controlled (not attacker-supplied), pii_scrub/checkpoint-signature gating unchanged.

Non-blocking findings (recommended follow-up, not required for merge)

  1. selectOrgsForIntegrityRun reads all auditLogChainGenesis + all auditIntegrityProgress rows with no pagination (integrity_check.ts:57-82). This is the inherent cost of round-robin fairness, but at very large org counts it could approach Convex's per-query read limit; that call is outside the per-org try/catch, so if it ever throws the whole sweep no-ops. (Same un-wrapped pattern as the listAuditedOrganizationIds it replaced — not a regression.) Consider an updatedAt-indexed bounded page.
  2. In-band createAuditLog write is the one in-loop await with no try/catch (integrity_check.ts:436-451); the surrounding touchIntegrityProgress/notifyIntegrityFailure are isolated but this isn't. If it throws for one finding org it aborts the rest of that run's sweep. Wrap it like the neighbors.
  3. recordIntegrityProgress failure has no rotation fallback (integrity_check.ts:373-383): on a persistent progress-write fault the org keeps a low updatedAt, re-walks the same window every run and crowds the front of the queue.
  4. Head-anchor / re-anchor checkpoint check runs only on a non-resumed walk (verify_integrity.ts:396-401). Because the cron now always resumes after run 1, the deletion-boundary re-anchor defense is exercised once per org via the cron (admin-triggered full walk still anchors). Consider periodically forcing a non-resumed anchored walk, or re-validating the first surviving row against retention checkpoints on the afterIdDeleted path.
  5. Test coverage gaps (none of the claimed fixes is unguarded, but edge branches are untested): tamper-still-caught on a resumed page (I verified this manually — worth a permanent test); the >MAX_ORGS_PER_RUN (500) round-robin truncated path; a chain longer than MAX_ENTRIES_PER_ORG (5000) truncated multi-run paging; the error-in-one-append sibling-chaining branch; the forward-clock ratchet.
  6. Nits: shipped comments cite review-process artifacts (Round-2 review C.5, PR #2218 review BLOCKING 1/2) which the repo's comment convention discourages — keep the explanatory prose, drop the review-status tags; the inline self-check's "verifyIntegrity has no operational wiring" comment (helpers.ts:295-301) is now stale since this PR adds the cron wiring.

READY TO MERGE.

@yannickmonney
yannickmonney merged commit 169ad3f into main Jun 29, 2026
68 of 69 checks passed
@yannickmonney
yannickmonney deleted the tale/xs76gnecd7jq2ph36pdbjsnsgd89e4ge branch June 29, 2026 17:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: audit integrity verifier/cron coverage gaps and latent chain hazards (org cap, unverified tail, broken resume, clock skew, intra-mutation fork)

2 participants