Financial Integrity Operations
Admin-only operations surface for reconciliation findings, exceptions, and recovery operations. All endpoints require an admin-role JWT (x-dev-user dev identities are never accepted in production config). Implemented on the Cloudflare worker (be-cloudflare) — the Axum backend has no equivalent surface.
API surface
Summary and exceptions
GET /api/v1/admin/financial-integrity/summary
GET /api/v1/admin/financial-integrity/exceptions[?status=]
GET /api/v1/admin/financial-integrity/exceptions/:id # includes append-only event log
POST /api/v1/admin/financial-integrity/exceptions/:id/transition
{to_status, reason, note?, operation_id?, correlation_id?}2
3
4
5
Exception state machine (enforced by transition_allowed, migration 022):
OPEN → TRIAGED → INVESTIGATING → AWAITING_APPROVAL → REMEDIATING
→ REVERIFYING → RESOLVED | REOPENED
BLOCKED — enter/exit from any non-terminal state
CLOSED_AS_FALSE_POSITIVE — terminal (operator verdict)
REOPENED — engine re-detects fingerprint, or verify fails2
3
4
5
- Every transition requires
reason; transitions append toreconciliation_exception_events(append-only). RESOLVEDis reached only viaREVERIFYING+ the producing check completing without re-observing the fingerprint (engine sync or a verified recovery op).- Fingerprint dedup:
sha256(check_name|entity_type|entity_id|finding_code)— re-observed findings bumpoccurrence_countinstead of creating new rows.
Recovery operations
GET /api/v1/admin/financial-integrity/operations[?status=]
POST /api/v1/admin/financial-integrity/operations
{op_type, target_entity_type, target_entity_id,
expected_state?, reason_code|reason, idempotency_key?}
GET /api/v1/admin/financial-integrity/operations/:id
POST /api/v1/admin/financial-integrity/operations/:id/approve {decision: approve|reject, reason}
POST /api/v1/admin/financial-integrity/operations/:id/execute
POST /api/v1/admin/financial-integrity/operations/:id/verify2
3
4
5
6
7
8
| op_type | target | approval | effect |
|---|---|---|---|
RELEASE_STALE_SETTLEMENT_CLAIM | settlement_run / order | required | release run:* order claims |
REDRIVE_OUTBOX | outbox | required | dead-letter → pending requeue |
REPLAY_INBOX_PROCESSING | inbox_event | required | processing/failed → received (never terminal) |
APPLY_CONFIRMED_REFUND_INTERNAL | refund_attempt | required | internal effects only — no PG call |
RECHECK_PROVIDER_REFUND | refund_attempt | auto-approved | GET-only PG status recheck |
RUN_RECON_VERIFY | reconciliation_exception | auto-approved | re-run recon, drive REVERIFYING |
Rules:
status: DRAFT → PENDING_APPROVAL → APPROVED → EXECUTING → VERIFIED | FAILED | CANCELLED- Money-affecting ops require actor ≠ approver (
403 SELF_APPROVAL_DENIED). Read-only recheck ops auto-approve with asystemapproval record. idempotency_keyis UNIQUE — resubmission replays the stored operation.- Execute/verify are CAS-guarded (no double execution); before/after target snapshots + receipt + verification are stored on the op.
- Internal recovery never performs new external PG capture/cancel calls — GET status reads only.
Settlements admin
POST /api/v1/admin/settlements/sweep # release stale run claims
POST /api/v1/admin/settlements/:id/mark-paid {payout_ref} # payout confirmation2
Evidence
Every op execute/verify emits a chain-sealed recovery.execute / recovery.verify evidence record (see audit-evidence).
Fail-closed behavior — S1 hardening (85f113b / 45ffde5, main after 45e270c)
- Transient D1 errors inside the settlement drive surface as
DriveOutcome::DbError→ HTTP 500; the run stays non-terminal and order claims are retained — retry viaPOST /api/v1/settlementsor the sweep; a transient error never orphans or double-claims. - Recovery-op execute/verify now carry live-run guards — ops do not interleave with a live settlement run target.
committed_krwreads,scalar_i64parses, and missingproj_sellerrows are strict → 500, never silently clean.audit_prevresolution is strict everywhere — the compatibility wrapper was deleted; a chain-write failure fails the request rather than writing an unsealed record.- Public error bodies no longer leak
{e}literals on the fixed sites; a sweep of pre-existing sites is a non-blocking S2 item.
NOUGAT_FI test-injection seam (operators)
NOUGAT_FI is an env-gated fault-injection seam used by tests/failclosed.test.mjs (run-failclosed.sh, 20/20 locally at 45ffde5) to drive deterministic DB-failure legs. It is armed only when DEV_AUTH is enabled and PAYMENT_MODE is non-production — it is inert in a production-configured worker; do not set it outside dev/staging test runs. Probe classes settle.claimed / settle.chk / settle.counter exist — per-class assertions landed in S2 (x-fi-probes request-scoped arming, s2-03 c5cffd7; tests/fault-injection 77 legs). The x-fi-probes header merges with the NOUGAT_FI env list under the same gate — it grants no extra privilege and is also inert under production config.
Suite evidence (local loopback): integrity 22/22, failclosed 20/20, exceptions-ops 38/38 + audit-evidence 47/47 (prior wave, not re-run in S1).
S2 assurance wave (main cabbc7f–940fd75; CI wiring 1b4f139)
Changes affecting this surface — details and full ledger in the S2 wave report:
- Settlement check expansion (s2-02
e6a05cf). Thesettlement_consistencycheck now emits five finding types:settlement_consistency(hard drift),settlement_membership(order_ids_json↔orders.settlement_idbidirectional, dup/broken JSON),post_settlement_refund(refunds on member orders after commit — surfaced, never silently absorbed),settlement_fee_mismatch(fees re-derived from the stored bp snapshot,floor((g×bp+5000)/10000)), andsettlement_run_mismatch(settlement ↔ committingsettlement_runsrow). The false positive where recon summed rawamount_krwagainst the committedΣ(amount−refunded_krw)gross is fixed. reference_integritypayments-orphan (s2-02). Payment rows with no owning order surface as areference_integrityfinding.- Approve CAS-first (s2-10
ca9fca5).POST .../operations/:id/approveperforms the CAS UPDATE first and assertschanges==1(else409 OP_STATE_INVALID, no decision row) — exactly one decision row per op; 24-way raced approve/reject converged to a single decision in test. - Stale
EXECUTINGconvergence (s2-101daf526). An op stuckEXECUTINGwithout a receipt (crashed between the execute CAS and receipt write) converges viaverifyonce stale (>10 min,OP_EXECUTING_STALE_MIN): target-state re-evaluation →VERIFIED(effect observed) orFAILED+ explicit reason. FreshEXECUTINGis left alone — never prematurely failed while execution may be live. - Cron recon lifecycle (s2-10).
scheduled()now reaps stalerunningrecon runs (failed+INCOMPLETEchecks) and resumes a liverunningrun instead of always creating a new one. alert:evidence_gaps(s2-10).scheduled_assurancefolds sealed-without-evidence / burned-sequence residue into a chain-sealed evidence record — console-log loss can no longer hide emit gaps.- v2 evidence coverage (s2-10).
preflight(fail-closed before the live-payments gate) +payment.capture/feedback.donationevidence added to purchase paid, subscription renew, paid feedback,finalize_paid, and feedback-payment creation. - Verify fields (s2-05
637654a).GET /admin/audit/v2/verifyadditionally reportscheckpoint_comparison(every seal vs current chain — reseal cannot launder an older mismatch; latest 200 seals),evidence_coverage(report-only),key_ids,algorithm,truncated,link_breaks,sequence_gaps. - Webhook freshness (s2-10). Signed Toss webhooks with a
tosspayments-webhook-transmission-timeolder than ±600 s are rejected401 WEBHOOK_STALE+stale_transmissionaudit — only whenTOSS_WEBHOOK_SECRETis configured. - Counter self-heal (s2-10).
next_counterseed-then-increment for order/settlement counters — a missing row heals; real DB errors fail closed (500TX).audit_v2_sequencedeliberately stays fail-closed. - Suites (local loopback): recon2 39 · fault-injection 77 · audit2 79 · recovery-security 46 · alerts 28 · assurance-gaps 26 — all wired into the
financial-integrityCI job at1b4f139(first real CI runNOT_VERIFIED).
Related runbooks
- reconciliation-runbook — findings → exceptions flow
- refund-recovery — refund attempt lifecycle
- settlement-recovery — settlement run recovery
- incident-response — incident ordering