Data Model: Security & Compliance

Overview

The security service is CRAIG’s compliance, audit, and platform-integrity backbone (port 8007, database craig_security). Its tables back the audit trail (45 CFR § 95.621), the security-review and NIST SP 800-53 control registries, data archiving/retention (2 CFR § 200.334), the administrative-unit registry, breach detection (rules + alerts), partner + worker identity (ADR-017 / ADR-018 / ADR-026), and the outbox/inbox/dead-letter durability + idempotency machinery (ADR-022), the legacy OIDC issuer record (ADR-085 D7) and the internal token issuer’s signing-key registry (ADR-085 D8). The migrations create 28 tables (source of truth: services/craig-security/migrations/; the orphaned idempotency_responses was dropped by &77 BF). This page catalogs 26 of them; the other two, the per-service background-job ledger background_jobs + background_job_attempts, are specified by ADR-068 § Amendment — #1571. The schema carries eight foreign keys — review_evidence.review_id → security_reviews.id, security_alerts.rule_id → detection_rules.id, partner_api_keys.partner_id → partners.id, partner_signer_keys.partner_id → partners.id, worker_admin_units.admin_unit_id → admin_unit_registry.id, background_job_attempts.job_id → background_jobs.id (ON DELETE CASCADE), and identity_legacy_issuer_retirements.issuer_id → identity_legacy_issuers.id, and identity_key_revocations.kid → identity_signing_keys.kid; the durability tables' cross-table links are logical, by envelope_id.

The endpoint catalog for this service is API: Security & Compliance; its state machines are in State Machines; its events are in ADR-003: RabbitMQ Topology (the wildcard # audit subscriber).

Recorders name the acting worker (#2250). No craig-security recorder (a who-acted column or an event’s actor key) names the request token’s own sub / preferred_username: under a BFF-lifted token that token is craig-web’s service principal, so a staff act names claims.acting_worker() (ADR-028, ADR-062), the lifted worker, or the token’s own subject when nothing is lifted. That covers partners.created_by, partner_api_keys.created_by (issue and rotation), partner_signer_keys.created_by / approved_by / revoked_by, security_alerts.acknowledged_by, archive_records.purged_by, nist_controls.assessed_by_name (named only when the assessor is the acting worker, #2320) and major_changes.reported_by / reported_by_name (#2276), plus the actor key of every event those acts stage. The ADR-026 identity cache (worker_identities) records the acting worker too (#2472). Since #2522 the Claims fields are private and crates/craig-test-lib/tests/acting_identity_census.rs pins it: the token’s own identity is read only through a bearer_*() accessor, each such read under services/craig-security/src is pinned with its reason, with no exception (the identity cache reads none since #2472), and a recorded worker is claims.worker_subject(), which reads the claims.acting_worker() view, never the bare claims (#2740 removed parse_sub / parse_actor_sub).

Tables

Table Purpose

audit_log

Append-only audit trail of all data access + mutation (45 CFR § 95.621); the wildcard # subscriber writes here, plus actor (on-behalf-of) columns.

security_reviews

Biennial / incident / ad-hoc security reviews (45 CFR § 95.621(f)) — findings + remediation plans; soft-deletable.

nist_controls

NIST SP 800-53 control mapping + implementation-status tracking; soft-deletable, partial-unique on control_id while active.

archive_records

Data-archiving + purge tracking (2 CFR § 200.334) — retention windows + purge eligibility per source service/table.

admin_unit_registry

Registry of administrative units (states / counties / districts) with jurisdiction + FIPS mappings; partial-unique on (name, jurisdiction) while active. version BIGINT is the ADR-062 §G3 If-Match CAS counter (the update SET clause overwrites every field). Since #1899 (ADR-077 D2) a row with a LIVE worker_admin_units binding is frozen: PUT / DELETE /v1/security/admin/units/{id} (any field — fips_code / state_fips included) and the craig-manage seed-admin-units UPSERT refuse it (409 ADMIN_UNIT_BOUND; revoke the bindings first), taken lock-first (FOR NO KEY UPDATE, then the guarded NOT EXISTS (live binding) UPDATE under a fresh snapshot).

detection_rules

Breach-detection rule registry (four rule types over audit_log); soft-deletable (active = false), scanned by the 60 s scheduler + POST /v1/security/detection/run. version BIGINT is the ADR-062 §G3 If-Match CAS counter (a stale replay cannot re-enable a disabled rule).

security_alerts

Alerts fired by breached detection rules — FK to detection_rules; at most ONE unacknowledged alert per rule (uq_security_alerts_standing_rule, #1172).

detection_scan_watermark

One row: the snapshot of the last committed detection scan, which the next scan locks and counts from (#2771).

dead_letter_audit

Forensic capture of RabbitMQ DLX-dead-lettered messages for causal-chain reconstruction
threshold alerting (ADR-022 Step 4).

event_outbox

Transactional outbox for this service’s own staged events (ADR-022), published-only 30-day retention (ADR-058).

event_inbox

Idempotent inbox for subscription handlers — the ADR-062 single-transaction attempt machine (claim + effects + stamp atomic; supersedes ADR-022 §D3.2’s three-statement shape), 31-day retention (ADR-058).

request_claims

ADR-062 §B convert-class idempotency claims (claim-first inside the domain transaction); pruned hourly on the fleet-wide CRAIGREQUEST_CLAIMSWINDOW_DAYS horizon. The actor is the ADR-085 D3 column pair (#2740): created_by_sub holds a worker’s UUID and created_by_sub_service a service’s service:<name> encoding, with a CHECK that exactly one is set.

schema_compat_floor

ADR-063 rollback floor singleton — the minimum binary version the schema still serves; destructive contract migrations bump it in the same file. Written only by the migration gate; the verify-only boot SELECTs it.

event_inbox_collisions

Identity-collision ledger (ADR-062 §A-4): reused envelope ids with divergent (source, type, payload_hash) triples, recorded without touching the canonical claim.

partners

Partner organization registry (hospital / school / LE / other) for edge identity (ADR-017); active → suspended → deleted soft-delete; per-partner rate limit. version BIGINT is the ADR-062 §G3 body-version CAS counter (suspension cycles are ABA-vulnerable).

partner_api_keys

SHA-256-hashed partner API credentials (FK → partners) — prefix display, revocation, 1-year expires_at rotation (F-009); hot-path /partners/verify lookup by hash.

partner_signer_keys

Per-PERSON ES256 signer keys for mandated-reporter detached JWS (ADR-018; FK → partners); pending → approved → revoked, globally-unique JWS kid lookup.

partner_client_certificates

The client certificates a partner calls CRAIG with (ADR-091; FK → partners): fingerprint, subject and validity as read from the certificate; pending → approved → revoked; one live row per fingerprint.

worker_identities

IdP-neutral worker identity cache (ADR-026) — lazy-populated from the acting worker’s claims by the auth-after middleware (#2472: the worker a verified X-Craig-Actor names, else the worker’s own token; a bare service call caches nothing); trigram autocomplete for BFF reassignment; since #1857 the service-only contact projection (POST /v1/security/worker-identities/contacts, ≤ 50 subs → display_name + contact_phone, craig-placement’s scoped contact row, no-store; a relayed (X-Craig-Actor) call is refused 403 before the engine, #2339; it replaced the #1850 display-name projection, retired by #2525) and the admin-only work-line write (PUT /v1/security/admin/workers/{sub}/contact) — a worker this service has never seen has no row and is simply omitted. #2505: display_name falls back to the username when a token carries no name; both responses return display_name: null for a name equal to the cached preferred_username, so a username never reaches the portal, which shows its generic label.

worker_admin_units

ADR-077 D1 (#1899): the worker→administrative-unit binding LEDGER — one row per (worker_sub, county) binding with the unit NAME / type / jurisdiction FROZEN at assign (D2: the name is the scope token consumers match; only an active county registry row binds), soft-revoked through the revoked_at / revoked_by pair, ONE live binding per pair (partial-unique worker_admin_units_live_pair), version the ADR-062 §G3 If-Match CAS counter for the revoke. No FK to worker_identities (a never-seen subject may be bound); FK → admin_unit_registry ON DELETE RESTRICT. Written by POST /v1/security/admin/workers/{sub}/admin-units (ADR-062 claim security.assign_worker_admin_unit) and DELETE …/admin-units/{id} — and by the devstack seed’s direct rows; audited as security.worker_admin_unit.assigned / .revoked (resource_type = worker_admin_unit, resource_id = binding_id). The devstack seed binds rita.regional to Harris and Travis (texas).

worker_admin_units_meta

Single-row generation counter (the keyring_meta shape, #892) bumped inside every assign / revoke transaction — and once by the seed — the ADR-077 D4 snapshot’s monotonicity witness (a consumer installs a snapshot only when its generation exceeds the one held). A rolled-back assign leaves it untouched by construction.

review_evidence

Uploaded evidence objects attached to security reviews (FK → security_reviews) — object-store pointers, never file bytes. No route writes it yet, so the OpenAPI document carries no evidence schema; deleting a review soft-deletes it and leaves its evidence rows in place (#2907).

major_changes

CCWIS major-change monitoring (staffing / org / system / policy) with ACF-reporting flags; soft-deletable.

identity_legacy_issuers

#2739 (ADR-085 D7): one row per distinct OIDC_ISSUER craig-security booted with — the issuer every persisted iss matched, which the switch’s adoption rule needs. Owner-owned, INSERT-only; the app login holds no privilege on it and writes it only through identity_record_legacy_issuer (§ Identity records).

identity_legacy_issuer_retirements

#2739: at most one retirement per recorded issuer (operator, reason, time), written only by the owner-only identity_retire_legacy_issuer; the row is the retirement log. Owner-owned, INSERT-only; the app login holds no privilege on it.

identity_signing_keys

#2741 (ADR-085 D8): one row per public key an issuer replica published (the private half never leaves the replica’s memory). Inserted by the issuer login on five columns; the times are stamped by an owner trigger; at most 64 unrevoked rows inside their publish window. Owner-owned, INSERT-only (§ Signing-key registry).

identity_key_revocations

#2741: one revocation per key, written only through the owner-only identity_revoke_key (the D8 compromise response; the security-admin path arrives with plan U10). Owner-owned, INSERT-only.

identity_key_cap_guard

#2741: the one row the stamping trigger locks to serialize the 64-key count. Owner-held; no other role holds any privilege on it.

Key columns

Source of truth: services/craig-security/migrations/. Every PK is id UUID DEFAULT uuidv7() unless noted (ADR-002).

audit_log

audit_log is range-partitioned by UTC calendar month on timestamp (#3173, migration 20261127230000_audit_log_month_partitions): one partition a month, audit_log_pYYYYMM, bounds at the 1st 00:00 UTC, no default partition, so a row whose month has no partition is refused (23514). Its key is PRIMARY KEY (timestamp, id), since a partitioned table’s unique key must hold the partition key; id alone is no longer unique by constraint, and no writer relies on it (ids come from the uuidv7() default). Every index is declared on the parent and copied to each partition under the parent index’s name plus _pYYYYMM: idx_audit_log_user, idx_audit_log_resource, idx_audit_log_service, idx_audit_log_actor_service, idx_audit_log_actor_user_sub, idx_audit_log_action, the three detection partials, the two trigram indexes and idx_audit_log_xact_id. The key serves the time ranges idx_audit_log_timestamp served before. A query bounded by timestamp reads only its months' partitions; the detection scan’s span statement, bound by xact_id alone, plans against every partition, which is why the unit is a month and not a day.

The owner’s functions, the app login’s only way to make or drop a partition (it executes these three and no helper; the issuer login executes none):

Function Contract

audit_log_ensure_partitions(from_month date, to_month date) RETURNS integer, SECURITY DEFINER

Makes each missing month from from_month through to_month, each truncated to its month, at most 36 a call (22023 beyond); idempotent; returns how many it made. A partition is created standalone with a CHECK equal to its bounds, then attached, which takes SHARE UPDATE EXCLUSIVE on the parent and so never waits on an insert. craig-security’s partition-maintenance worker calls it for the current month through the month holding the date 30 days ahead, at start and hourly.

audit_log_partition_months() RETURNS SETOF date, SECURITY DEFINER

The first day of each partition, oldest first, read from the catalog by the naming rule.

audit_log_drop_partition(month date, expected bigint) RETURNS bigint, SECURITY DEFINER

The retention archiver’s drop (ADR-058). Refuses a date that is not a month’s first day, a month that is not wholly before the current UTC month (22023) and a month with no partition (42P01). Under a 2 s lock_timeout it locks the partition SHARE (writers wait, readers do not), counts it, and drops it only when the count equals expected; it returns the count either way. The drop takes ACCESS EXCLUSIVE on the parent, so inserts queue behind it for at most the lock timeout, after which it gives up until the next pass (55P03).

The three share owner-only helpers, range_partition_ensure, range_partition_starts and range_partition_drop, which take the parent and the unit (day or month).

Column Type Notes

id

UUID

NOT NULL, DEFAULT uuidv7(); the primary key with timestamp (#3173)

timestamp

TIMESTAMPTZ

the partition key; NOT NULL, DEFAULT now(); the event-audit insert writes clock_timestamp(), the insert’s own time, so rows a batched audit transaction writes keep distinct times (#2765, plan audit-batched-claims D8)

user_id / user_role

TEXT

acting worker identity (display); for a service-acted event, the service’s ADR-085 D3 encoding service:<name> (#2740), with actor_user_sub NULL

service

TEXT

originating service

action

TEXT

e.g. read / create / update / delete

resource_type

TEXT

domain resource class: one of the closed craig_mq::AuditResource tokens, which hold every craig-authz ResourceType token (#2515) and the batch and record tokens with no authz type; unknown for a header token this build cannot read; for a headerless event, see below; forward-only, so older rows keep the token they were written with

resource_id

UUID

nullable

details

JSONB

nullable structured context

ip_address

TEXT

nullable

success

BOOLEAN

NOT NULL, DEFAULT true

actor_service

TEXT

NOT NULL, DEFAULT 'unknown' — on-behalf-of service (ADR-028)

actor_user_sub

UUID

nullable — on-behalf-of subject

xact_id

BIGINT

NOT NULL, DEFAULT the inserting top-level transaction’s id (pg_current_xact_id()); 0 on the rows that existed before migration 20261126180000_detection_exact_windows, and 0 means "committed before any scan counts it". The detection scan finds the rows committed since its last run by it (#2771); idx_audit_log_xact_id. Archived rows carry it; the partitioning migration copied each row’s value across

Where the event-audit columns come from (#2314). handle_inbound_event writes one row per envelope, and services/craig-security/src/audit_columns.rs derives its columns one of two ways:

  • The envelope carries an audit header (EventEnvelope.audit, a craig_mq::AuditMeta the publisher stated where it staged the event). The header supplies the columns and the payload is not read:

    Column From the header

    action

    the action token (AuditAction, a closed set of 43)

    resource_type

    the resource token (AuditResource, a closed set of 85)

    resource_id

    the header’s record id; NULL when it names none

    user_id

    the actor: a worker’s UUID in hyphenated lower case, system, or a named actor’s text (service:<name>, system:retention, …) verbatim

    actor_user_sub

    the worker’s UUID; NULL for the system and for a named actor

    user_role

    the header’s roles joined by a comma; unknown when it states none

    success

    false when the header’s outcome is refused, else true

    service, actor_service and details are the envelope’s source_service and payload, as before. A UUID actor written in another spelling (upper case, no hyphens) is stored in the canonical spelling on this path.

    Who the actor is (#3116). A publisher states the worker whose act, or whose run, caused the event, whenever the staging site holds that worker; a worker a calling service asserts as data is stated only where the endpoint admits that one service and nothing else (the SSN release, whose row names the requesting caseworker while details keeps the service as requestor). Where a service principal called and no worker is known, the actor is that service in its ADR-085 encoding, service:<name>, the text an authorization denial of the same service carries. system is left for an event no request causes: a scheduler tick, a reconciler, an inbox consumer acting on another service’s event, or a cache signal.

  • The envelope carries no header. The row still lands, degraded, and the payload is not read:

    Event type action resource_type success

    authz.access_denied

    deny

    authz_decision

    false

    any other security.*

    system

    security

    true

    anything else

    the text after the first dot of the event type

    the text before it (unknown, with the whole type as the action, when it has no dot)

    true

    In all three, user_id is system, user_role is unknown, and resource_id and actor_user_sub are NULL. No actor, record, role or resource type is taken from the payload, which is still stored whole in details. A denial stays a denial, so a query for success = false still finds it. The split halves are publisher-controlled text and pass through the same escaping and capping as every other column.

What an operator sees for a headerless event. Every publisher in the workspace states a header: staging refuses an envelope without one (Unpublishable::MissingAuditHeader). A headerless delivery is therefore an outbox row written by a build that stated none, an admin replay of such a row, or a message from a publisher outside the workspace. Each one increments the label-free counter audit_headerless_events_total (served on /metrics) and logs one WARN with the stable message audit event carries no header, carrying the envelope id and the capped, escaped source_service and event_type. The counter should stay at zero. A headerless row is counted by a detection rule only when the text after the first dot of its event type is exactly a token that rule counts (placement.portal_read by bulk_access, reporting.afcars_export_generated by data_export); a headerless authz.access_denied is filed as a refused deny and counted by privilege_escalation. Its actor and record are recoverable only from details.

A degraded header still lands its row. The header is decoded field by field, and a field that cannot be read is replaced on its own: an unknown or missing action or resource_type is stored as unknown; an unreadable resource_id is NULL; an unreadable actor is system; an unreadable outcome is a refusal when the action is deny and a success otherwise; an unreadable role list is empty. Such a delivery increments the label-free counter audit_degraded_headers_total (served on /metrics) and logs one WARN, audit header degraded. An audit value that is not a JSON object is no header at all, and the row takes the headerless path above.

Hostile values are degraded, never dropped (#2864). The event-audit insert (handle_inbound_event) records every envelope it receives. The columns are derived from the raw header or event type, and the stored forms are applied to the derived values only, whichever path produced them (services/craig-security/src/audit_text.rs):

  • Displayed identifier columns (user_id, user_role, service, actor_service, action, resource_type): each NUL and each Unicode format character (Cf: bidirectional overrides and isolates, zero-width joiners, tag characters) is written as the literal text \u{XXXX}, the code point in upper-case hex with at least four digits (\u{202E}, \u{E0020}; craig_validation::escape_display). The five indexed columns (all but user_role) are then capped at 1024 bytes, cut on a whole character or escape and suffixed …[truncated N bytes], N being the escaped value’s length minus the kept prefix (craig_validation::cap_bytes). The truncated original is kept nowhere in audit_log (a value the payload also carries is still whole in details; the uncapped inbox copy of source_service / event_type expires with the 31-day event_inbox retention).

  • details: every NUL in a string leaf or an object key is written as \u{0000}; nothing else changes, so format characters with legitimate uses (ZWNJ in Persian, the soft hyphen, emoji ZWJ sequences, LRM/RLM) stay verbatim. An escaped key that collides with an existing one takes the first free name among e, e#1, e#2, … after every key that needed no escape.

  • The escape is not injective: a value already holding the literal text \u{202E} reads the same as an escaped U+202E. Other control and separator characters (newline, CR, ESC, U+0085, U+2028 / U+2029) are out of scope and stored as they are.

A clean value (no NUL, no Cf character, an indexed value of at most 1024 bytes) is stored exactly as derived, so the detection rules (action equality, success) match clean rows as before. One hostile value can take three stored forms: NUL-escaped in craig-mq’s event_inbox bookkeeping copy (source_service / event_type, otherwise verbatim); escaped and capped for display here; NUL-escaped with a capped event_type in dead_letter_audit.

security_reviews

Column Type Notes

review_type

TEXT

NOT NULL — the closed ReviewType vocabulary (biennial / incident / ad_hoc / access_review), API-enforced at create with the typed 400 INVALID_ENUM_VALUE (#1288)

scheduled_date

DATE

NOT NULL

completed_date

DATE

nullable

reviewer

TEXT

NOT NULL

findings / remediation_plan

JSONB

nullable

status

TEXT

NOT NULL, DEFAULT 'scheduled'

active / deleted_at

BOOLEAN / TIMESTAMPTZ

soft-delete (active partial index)

The row names no actor of a change: each update and soft delete stages a security.review.* act naming the acting worker (#3001, ADR-003).

nist_controls

Column Type Notes

control_id

TEXT

NOT NULL, partial-UNIQUE while active

control_family / control_name

TEXT

NOT NULL

implementation_status

TEXT

NOT NULL, DEFAULT 'planned'

implementation_notes

TEXT

nullable

evidence_key

TEXT

nullable (object-store pointer)

last_assessed

DATE

nullable

assessed_by / assessed_by_name

TEXT

nullable (the assessor as submitted + its display name: an API write stores the acting worker’s username when assessed_by is the acting worker’s own sub, else NULL. An update naming a new assessor replaces or clears the name; #2320, the #1366 rule). Not the actor of the write: each create, update and delete stages a security.nist_control.* act naming the acting worker (#2496, ADR-003)

active / deleted_at

BOOLEAN / TIMESTAMPTZ

soft-delete

archive_records

#1129 (ADR-058): the durable LOCAL LEDGER of the archive-then-prune engine — one row per archive batch, written inside the batch’s prune transaction (D8). Also holds craig-rules' fleet BOOKKEEPING copies (validated from rules.evaluations_archived, D16) — those are outside security’s purge authority (rules' own archive_ledger drives their lifecycle).

Column Type Notes

source_service / source_table

TEXT

NOT NULL — what was archived

record_count

INTEGER

NOT NULL

archived_at

TIMESTAMPTZ

NOT NULL, DEFAULT now(); the ledger insert writes clock_timestamp(), the insert’s own time, on both the D16 event path and the retention archiver’s prune (#2765, D8)

retention_until

DATE

NULLABLE since #1129: NULL = awaiting the DFCS records-retention schedule (⁂ #1073); purge refuses NULL/future/held at EVERY destructive statement (D14)

purge_eligible

BOOLEAN

NOT NULL, DEFAULT false — purge-time audit fact ONLY (set true at purge; the D14 predicate is the purge authority). #1145 retired the list filter, the web badge, and the idx_archive_purge partial index built on it

purged_at / purged_by

TIMESTAMPTZ / TEXT

the D15-attributed purge stamp; the acting operator, #2250 (partial index WHERE purged_at IS NULL)

archived_by / archived_by_name

TEXT

actor sub or system:retention; display name stays NULL at engine inserts

legal_hold

BOOLEAN

NOT NULL, DEFAULT false — never purged while true (D14)

data_key / manifest_key

TEXT

full object keys (NULL only on pre-engine legacy rows)

data_sha256

TEXT

sha256 of the data object’s exact bytes

store_endpoint / store_bucket

TEXT

the D9 store identity at archive time

first_record_id / last_record_id

UUID

the batch’s [min, max] row-id range (D17 candidate lookup; min/max never inverts)

first_record_at / last_record_at

TIMESTAMPTZ

oldest/newest archived row by the age column

hot_window_days

INTEGER

the window in force when the batch was cut

admin_unit_registry

Column Type Notes

name

TEXT

NOT NULL

unit_type

TEXT

NOT NULL (state / county / district)

fips_code

TEXT

nullable

state_fips

TEXT

NOT NULL

jurisdiction

TEXT

NOT NULL — partial-UNIQUE (name, jurisdiction) while active

active

BOOLEAN

NOT NULL, DEFAULT true

created_at

TIMESTAMPTZ

NOT NULL, DEFAULT now()

The row names no actor: each create, update and deactivation stages a security.admin_unit.* act naming the acting worker (#3001, ADR-003).

detection_rules

Column Type Notes

rule_name

TEXT

NOT NULL, UNIQUE

description

TEXT

NOT NULL

rule_type

TEXT

NOT NULL, CHECK — bulk_access / after_hours_access / privilege_escalation / data_export (see the predicates below)

threshold / window_minutes

INTEGER

NOT NULL, CHECK threshold >= 0 and window_minutes >= 1 (#3163; create and update refuse anything else with the 422 naming the field, since a shorter window counts no row). A set of at least threshold matching rows whose timestamps lie within one half-open window of window_minutes fires at the first scan that sees all of them, unless an unacknowledged alert for the rule stands then, however the scans fall and however late a row’s transaction commits (#2771). Threshold 0 fires on every scan the rule is not suppressed in

severity

TEXT

NOT NULL, CHECK (info / warning / critical)

enabled

BOOLEAN

NOT NULL, DEFAULT true — scan-participation switch

notify_webhook

TEXT

nullable — critical-severity push target

active

BOOLEAN

NOT NULL, DEFAULT true — soft-delete flag

The row names no actor: each create, update and soft delete stages a security.detection_rule.* act naming the acting worker (#3001, ADR-003).

Each rule type counts the audit_log rows of its window that satisfy one predicate (#3114). The action lists are AuditAction variants in services/craig-security/src/detection_sql.rs, compared by exact equality:

rule_type Predicate on audit_log

bulk_access

action IN ('read', 'portal_read'): a caregiver’s portal read and a read a publisher audits (the placement AFCARS release). A worker’s ordinary record read stages no event and is counted by no rule.

data_export

action IN ('export', 'afcars_export_generated', 'afcars_export_failed', 'ncands_export_generated', 'ncands_export_failed', 'reveal'). A failed export releases nothing and is counted as export activity.

privilege_escalation

action = 'deny' AND success = false: every authorization denial, system-wide, whoever was denied. The rule’s threshold and window_minutes are its only tuning; there is no per-actor count.

after_hours_access

Every row stamped outside the rule’s business_start_hour–business_end_hour band in the jurisdiction’s business timezone, whatever its action.

How a scan counts (#2771). A scan is one transaction. It locks the detection_scan_watermark row, so scans run one at a time and a scan that waits past the statement timeout fails (the route’s 504 db-timeout). It takes its own snapshot, and a row is new to it when its transaction completed after the watermark’s snapshot and by its own. For each enabled rule it finds the span in which a new matching row can share a window (by idx_audit_log_xact_id), then the most matching rows any window [a, a + window_minutes) anchored at a matching row holds with at least one new row among them. The alerts, their events and the watermark’s move to the scan’s snapshot commit together, so a failed scan leaves every row new for the next one. Two consequences follow:

  • After an alert is acknowledged, the rule fires again only on a window holding a row no scan had evaluated yet: one committed after the last scan before the acknowledgement. An acknowledged burst does not fire again.

  • A rule created or re-enabled is first evaluated at the next scan, over the windows holding a row committed since the scan before it; a burst that committed wholly before that earlier scan is not reported by it.

The first three are each also served by a partial index on audit_log (timestamp) with the same predicate (idx_audit_log_det_bulk_access, idx_audit_log_det_export, idx_audit_log_det_privilege), which the largest-window count reads over the span. No rule type detects a failed login or an account lockout: those happen at the identity provider, which sends CRAIG no events, so audit_log holds no row for them. The failed_auth and account_lockout types are refused on create, and migration 20261117120000_detection_closed_tokens (schema_compat_floor bumped) deleted the rules of those types, keeping their alerts with rule_id NULL.

security_alerts

rule_id → detection_rules.id is one of the schema’s four foreign keys (see Overview). #1172: uq_security_alerts_standing_rule (partial UNIQUE on rule_id WHERE NOT acknowledged) DB-enforces the #1156 one-standing-alert-per-rule invariant — the scan’s insert uses it as an explicit ON CONFLICT arbiter, so overlapping scans produce exactly one alert. Legacy NULL-rule_id rows are outside the constraint (partial-index NULLs are distinct).

Column Type Notes

rule_id

UUID

FK → detection_rules.id; nullable (legacy rows, and alerts whose rule migration 20261117120000 deleted — the store requires it since #1172)

rule_name / severity / description

TEXT

NOT NULL (severity CHECK: info / warning / critical)

details

JSONB

nullable — window count context

acknowledged

BOOLEAN

NOT NULL, DEFAULT false — partial-unique key domain

acknowledged_by

TEXT

nullable — the acting operator’s sub (#2250), or the attributed migration:standing-alert-dedupe (#1172) maintenance actor

acknowledged_at

TIMESTAMPTZ

nullable

created_at

TIMESTAMPTZ

NOT NULL, DEFAULT now()

detection_scan_watermark

Column Type Notes

singleton

BOOLEAN

PRIMARY KEY, DEFAULT true, CHECK (singleton) — the table holds one row

snapshot_xmax

BIGINT

NOT NULL — the last committed scan’s snapshot: one past the highest transaction id that had completed (not xmax, a system column name)

in_progress

BIGINT[]

NOT NULL — the transactions below snapshot_xmax still running then

scanned_at

TIMESTAMPTZ

NOT NULL — when that scan moved the row

Migration 20261126180000_detection_exact_windows seeds the row with its own snapshot. A scan with no row refuses (a 500 naming the table), rather than treating every audit row as new.

Operator notes. Audit rows restored into this database from another PostgreSQL cluster (a logical dump and restore) keep that cluster’s transaction ids; set their xact_id to 0 after the restore, so no scan takes them for new rows. A deployment whose scans stopped for long enough that the rows since cannot be counted inside the statement timeout can move the watermark to now, giving up that backlog on purpose:

UPDATE detection_scan_watermark
   SET snapshot_xmax = (pg_snapshot_xmax(s)::text)::bigint,
       in_progress = ARRAY(SELECT (x::text)::bigint FROM pg_snapshot_xip(s) AS x),
       scanned_at = now()
  FROM pg_current_snapshot() AS s;

dead_letter_audit

Column Type Notes

envelope_id

UUID

NOT NULL — correlates to event_outbox.id / event_inbox.envelope_id

source_service / event_type

TEXT

NOT NULL

original_queue

TEXT

NOT NULL

envelope

JSONB

NOT NULL — the full dead-lettered message

dlq_received_at

TIMESTAMPTZ

NOT NULL, DEFAULT now()

occurrence_token

TEXT

NULLABLE (#1181): per-occurrence idempotency token (dlxcap:/xdeath: grammar); PARTIAL UNIQUE WHERE occurrence_token IS NOT NULL is the redelivery-dedup arbiter — NULL = tokenless/historical, recorded undeduped

occurred_at

TIMESTAMPTZ

NULLABLE (#1181): when the occurrence happened (when derivable); the #1156 threshold window keys on LEAST(COALESCE(occurred_at, dlq_received_at), dlq_received_at) — clamped occurrence time, never receipt alone

Stored forms (#2864). A capture is recorded whatever it carries: every NUL in envelope (string leaves and keys), source_service and original_queue is written as the literal text \u{0000}, and event_type is NUL-escaped and capped at 1024 bytes plus …[truncated N bytes] (it backs idx_dead_letter_event_type_occurred); format characters are kept. The values are derived once per capture, and the inserts, the per-event_type crossing lock, the window count, the security.dlq.threshold_exceeded payload and the R7 phantom comparison all read them, so a redelivered phantom of a NUL or over-cap capture is absorbed. A capture with no NUL and an event_type of at most 1024 bytes is stored byte-identical to the pre-#2864 form; the one residual is a redelivery straddling the deploy whose event_type is over 1024 bytes (stored whole before), which is quarantined as divergent rather than absorbed. The escape is not injective and a truncated original is kept nowhere. This table is forensic only, never a replay source: the ADR-022 §D4 admin replay (crates/craig-api/src/admin_replay.rs) re-stages from the producer’s event_outbox, so an escaped envelope is never re-published.

event_inbox

PK is envelope_id UUID (the dedup key from the envelope), not a generated id.

Column Type Notes

envelope_id

UUID

PK — dedup key

source_service / event_type

TEXT

NOT NULL

received_at

TIMESTAMPTZ

NOT NULL, DEFAULT now()

processed_at

TIMESTAMPTZ

nullable — set when the handler returns Ok

error_count

INT

NOT NULL, DEFAULT 0

last_error

TEXT

nullable

failed_at

TIMESTAMPTZ

nullable — permanently failed (DLX-surfaced only after a CONFIRMED surface, ADR-062)

attempt_started_at

TIMESTAMPTZ

nullable — in-flight marker

payload_hash

TEXT

NOT NULL (#1273, post-horizon ratchet) — hex SHA-256 of the payload, the third leg of the ADR-062 identity triple (#1053); bound at claim by every writer

source_service and event_type (and event_inbox_collisions’ `observed_source / observed_type) are stored NUL-escaped (#2864, craig_validation::escape_nul), otherwise verbatim, by every claim, comparison and collision write; see the craig-mq inbox module docs for the identity consequences.

event_inbox_collisions

Present in ALL 8 stateful services (like event_inbox; documented here per the transport-table catalog convention). A reused envelope id whose (source_service, event_type, payload_hash) triple diverges from the canonical event_inbox claim is recorded here and nacked without requeue (ADR-062 §A-4, #1053); the canonical row is never mutated. Any row is an alert — the report-only inbox_identity_collisions_present watchdog fires on presence.

Column Type Notes

envelope_id

UUID

part of the composite PK — the reused id

observed_source / observed_type

TEXT

NOT NULL — the collider’s identity

observed_payload_hash

TEXT

NOT NULL — part of the composite PK with the two above

first_seen

TIMESTAMPTZ

NOT NULL, DEFAULT now() — the deterministic occurred_at of the collision’s DLX surface

occurrences

INT

NOT NULL, DEFAULT 1 — repeat observations of the same collider bump this

partners

Column Type Notes

name

TEXT

NOT NULL

kind

TEXT

NOT NULL, CHECK (hospital / school / le / other)

status

TEXT

NOT NULL, DEFAULT 'active', CHECK (active / suspended / deleted) — suspended blocks /partners/verify but preserves the row for audit/reinstatement

contact_email / contact_phone

TEXT

nullable

rate_limit_rpm

INTEGER

NOT NULL, DEFAULT 60, CHECK > 0 — mirrors intake’s per-partner default

created_by

UUID

NOT NULL — the acting worker (#2250); the creator only: each update and soft delete stages a security.partner.* act naming its worker (#3001, ADR-003)

partner_api_keys

Plaintext keys are never stored — the raw key is returned exactly once at issue time. SHA-256 (not argon2/bcrypt) is deliberate: keys are 256-bit high-entropy random tokens, not passwords, and the hash must support the indexed hot-path /partners/verify lookup (partial index on unrevoked key_hash).

Column Type Notes

partner_id

UUID

FK → partners.id, ON DELETE RESTRICT

key_hash

TEXT

NOT NULL, UNIQUE — SHA-256 hex of the raw key

key_prefix

TEXT

NOT NULL — first 8 chars, safe to display for revocation UX

label

TEXT

nullable

expires_at

TIMESTAMPTZ

NOT NULL, DEFAULT now() + 1 year (F-009 rotation) — expired keys fail verify even if unrevoked

revoked_at / last_used_at

TIMESTAMPTZ

nullable

created_by

UUID

NOT NULL — the acting worker (#2250)

partner_signer_keys

ADR-018: one partner carries many signer keys, ONE PER PERSON — mandatory-reporting statute identifies the individual as the accountable reporting party. Scoped to the partner (not the api-key) so credential rotation never orphans signer keys.

Column Type Notes

partner_id

UUID

FK → partners.id, ON DELETE RESTRICT

user_identifier

TEXT

NOT NULL — the person (email, employee id, …)

display_name

TEXT

NOT NULL

public_key_jwk

JSONB

NOT NULL (RFC 7517)

algorithm

TEXT

NOT NULL, DEFAULT + CHECK 'ES256'

key_id

TEXT

NOT NULL, UNIQUE — the JWS header kid; intake’s verify path looks up by kid (partial index WHERE approved AND unrevoked)

status

TEXT

NOT NULL, DEFAULT 'pending', CHECK (pending / approved / revoked) — admin review gates approval

approved_by / approved_at

UUID / TIMESTAMPTZ

nullable approval stamp — the acting worker (#2250)

revoked_by / revoked_at

UUID / TIMESTAMPTZ

nullable revocation stamp — the acting worker (#2250)

expires_at / last_used_at

TIMESTAMPTZ

nullable

created_by

UUID

NOT NULL — the acting worker (#2250)

partner_client_certificates

ADR-091: a partner that calls CRAIG is known by its client certificate. An administrator registers the certificate against the partner and, as a separate act, approves it. The certificate itself is not kept: it is public, and the row holds what was read from it at registration.

Column Type Notes

partner_id

UUID

FK → partners.id, ON DELETE RESTRICT

fingerprint_sha256

TEXT

NOT NULL, CHECK 64 lowercase hex digits: the SHA-256 of the certificate’s DER encoding. A caller is looked up by it. Partial UNIQUE index WHERE status is not revoked: one fingerprint is live at most once, across every partner

subject

TEXT

NOT NULL, at most 500 characters: the certificate’s subject as text, control characters removed

label

TEXT

NOT NULL, 1 to 100 characters: the administrator’s label, control characters removed

not_before / not_after

TIMESTAMPTZ

NOT NULL, CHECK not_before ⇐ not_after: the certificate’s validity

status

TEXT

NOT NULL, DEFAULT 'pending', CHECK (pending / approved / revoked). A CHECK ties each status to its stamps: pending has neither, approved has its approval and no revocation, revoked has its revocation

approved_by / approved_at

UUID / TIMESTAMPTZ

nullable, set together: the approving administrator

revoked_by / revoked_at

UUID / TIMESTAMPTZ

nullable, set together: the revoking administrator

created_by

UUID

NOT NULL: the registering administrator

The lookup (GET /v1/security/client-certificates/by-fingerprint/{sha256}) answers a row only while it is approved, its partner is active and the database’s clock is inside the certificate’s validity, so an approval, a revocation and a suspension each take effect with the statement that makes them.

worker_identities

PK is sub UUID (the IdP subject), not a generated id. Lazy-upserted from the acting worker’s claims by the auth-after middleware (ADR-026), at most once per worker per debounce window (#1155). Since #2472 the acting worker is the worker a verified X-Craig-Actor names on a service bearer, else the bearer when it is a worker’s own token; a bare service call, a portal channel and a lifted service or portal identity cache nothing. A worker’s own token is authoritative for display_name and email; a relay keeps a cached value unless it carries a new one.

Column Type Notes

sub

UUID

PK — IdP subject

preferred_username

TEXT

NOT NULL — deliberately non-unique (sub is the identity key; username uniqueness is the IdP’s contract, not CRAIG’s invariant); trigram-indexed

display_name

TEXT

NOT NULL — trigram-indexed for GET /v1/security/workers?search=; since #1850 the acting worker’s IdP name claim when it carries one (the OIDC profile full-name mapper), else the username — released to a service only on the contact projection, beside contact_phone. #2472: a relay (the actor JWT craig-web mints) overwrites it only when it carries a non-blank name; a first relayed sighting without a name seeds the username

email

TEXT

nullable — the acting worker’s email claim; #2472: a relay overwrites it only when it carries one, a worker’s own token without one clears it

contact_phone

TEXT

nullable, CHECK E.164 (^\+[1-9][0-9]{1,14}$; craig_validation::is_valid_e164 is the boundary twin) — #1857: the caseworker’s agency work line, admin-set through PUT /v1/security/admin/workers/{sub}/contact (each change stages security.worker_identity.contact_changed carrying the new value), never from a token; the auth-after upsert never names it, so a sign-in never clears it. Read back on the service-only contact projection and in the admin write’s own response, both under Cache-Control: no-store, and in the audit trail (the event’s value lands in the audit row’s details, read through the /v1/security/audit routes, which set no Cache-Control); never in the GET /v1/security/workers autocomplete and never in a tracing field. Agency work line, admin-set; not client PII; not field-encrypted (ADR-020/048 cover cases/reporting client PII)

attrs

JSONB

NOT NULL, DEFAULT '{}' — reserved JSONB, NOT an authz input since ADR-077 (#1086): worker units live in worker_admin_units; the one write path that touches it (the auth-after upsert; the admin contact write sets contact_phone only) rewrites it {} on every touch

first_seen_at / last_seen_at

TIMESTAMPTZ

NOT NULL, DEFAULT now()

worker_admin_units

PK id UUID (UUIDv7, handler-minted so the ADR-062 claim binds it before the insert; the DB default serves the seed). Never deleted — revocation is the pair below.

Column Type Notes

worker_sub

UUID

NOT NULL — the bound worker’s IdP subject (claims.sub); no FK

admin_unit_id

UUID

NOT NULL, FK → admin_unit_registry.id ON DELETE RESTRICT

unit_name / unit_type / jurisdiction

TEXT

NOT NULL — copied from the registry row AT ASSIGN (D2, frozen); unit_type is always county today

assigned_by

UUID

NOT NULL — the acting admin (the assign event’s created_by and its audit header’s actor)

assigned_at

TIMESTAMPTZ

NOT NULL, DEFAULT now()

revoked_at / revoked_by

TIMESTAMPTZ / UUID

nullable, both-or-neither (CHECK worker_admin_units_revoked_pair); NULL while live

version

BIGINT

NOT NULL, DEFAULT 1 — ADR-062 §G3 CAS counter (the revoke requires If-Match = version and bumps it; a replay against an already-revoked row is 200, no bump)

Indexes: UNIQUE worker_admin_units_live_pair (worker_sub, admin_unit_id) WHERE revoked_at IS NULL (the 23505 discriminator behind 409 ADMIN_UNIT_ALREADY_BOUND), worker_admin_units_live_worker_idx (worker_sub) WHERE revoked_at IS NULL (the per-worker list + the D4 projection), worker_admin_units_live_unit_idx (admin_unit_id) WHERE revoked_at IS NULL (the registry’s bound-row guard).

The D4 snapshot read (#1900, GET /v1/security/worker-identities/admin-units?jurisdiction=) selects worker_sub, unit_name from the LIVE rows of ONE frozen jurisdiction with unit_type = 'county' (a directly inserted row of any other type is absent) — never a registry join — AFTER reading worker_admin_units_meta.generation in the same transaction, so the rows it answers are never older than the generation it carries. Service-only: a worker bearer, direct or relayed through X-Craig-Actor, is the 403 before the engine (#2339).

worker_admin_units_meta

Column Type Notes

singleton

BOOLEAN

PK, DEFAULT TRUE, CHECK (singleton) — a second row is unrepresentable

generation

BIGINT

NOT NULL, DEFAULT 0 — +1 per committed assign / revoke (and once per seed load), never on a replay; the D4 snapshot reads it FIRST, then the rows (#1900)

review_evidence

Column Type Notes

review_id

UUID

NOT NULL, FK → security_reviews.id

file_name / content_type

TEXT

NOT NULL

object_key

TEXT

NOT NULL — object-store pointer (bytes live in the store, never here)

uploaded_by

TEXT

NOT NULL

major_changes

Column Type Notes

change_type

TEXT

NOT NULL, CHECK (worker_assignment / supervisor_change / org_restructure / system_upgrade / policy_change)

description / affected_scope

TEXT

NOT NULL

effective_date

DATE

NOT NULL

reported_to_acf

BOOLEAN

NOT NULL, DEFAULT false

reported_date

DATE

nullable

reported_by / reported_by_name

TEXT

NOT NULL / nullable — the sub and username of the worker who recorded the change (the create’s claims.acting_worker(): under a BFF-lifted token the worker the service acts for, never the service principal; #2276). The update that marks the change reported to ACF does not rewrite them: each update and soft delete stages a security.major_change.* act naming its worker (#3001, ADR-003).

active / deleted_at

BOOLEAN / TIMESTAMPTZ

soft-delete

identity_legacy_issuers

PK id UUID (UUIDv7, supplied by identity_record_legacy_issuer through uuidv7(); no column default). Never updated, deleted or truncated (§ Identity records).

Column Type Notes

issuer

TEXT

NOT NULL, UNIQUE — the configured OIDC_ISSUER, exact bytes; CHECK 1–2048 octets (inside the btree entry limit) with no control character (U+0001–U+001F, U+007F–U+009F; the value reaches the server log)

first_recorded_at

TIMESTAMPTZ

NOT NULL, DEFAULT clock_timestamp() — the boot that first recorded it

identity_legacy_issuer_retirements

PK id UUID (UUIDv7, supplied by identity_retire_legacy_issuer). Never updated, deleted or truncated.

Column Type Notes

issuer_id

UUID

NOT NULL, UNIQUE (one retirement per issuer), FK → identity_legacy_issuers.id ON DELETE RESTRICT

operator

TEXT

NOT NULL — who retired it; CHECK not blank, at most 256 characters, no control character (it is logged)

reason

TEXT

NOT NULL — CHECK not blank, at most 2048 characters

retired_at

TIMESTAMPTZ

NOT NULL, DEFAULT clock_timestamp()

identity_signing_keys

PK kid TEXT (the key’s RFC 7638 thumbprint; an ADR-085 D2 exception to the UUIDv7 rule). Never updated, deleted or truncated. The issuer supplies the first five columns; the stamping trigger sets the rest from clock_timestamp(), overwriting any value a caller (the owner) supplied.

Column Type Notes

kid

TEXT

PK — CHECK canonical unpadded base64url of 32 bytes, and equal to the SHA-256 thumbprint of {"crv":"P-256","kty":"EC","x":…,"y":…} (craig_crypto::jwk::thumbprint)

x, y

TEXT

NOT NULL — the P-256 point, each CHECK canonical unpadded base64url of 32 bytes

replica_id

UUID

NOT NULL — the publishing replica, a UUIDv7 minted at its boot

requested_sign_seconds

INTEGER

NOT NULL — CHECK 600–21600 (a replica’s first key 600, every later key 21600)

created_at

TIMESTAMPTZ

NOT NULL — stamped

sign_from

TIMESTAMPTZ

NOT NULL — stamped; CHECK created_at + 60 s (the staged lead)

sign_until

TIMESTAMPTZ

NOT NULL — stamped; CHECK sign_from + requested_sign_seconds

publish_until

TIMESTAMPTZ

NOT NULL — stamped; CHECK sign_until + 720 s; indexed (the cap count and the JWKS read filter on it)

identity_key_revocations

PK kid TEXT, FK → identity_signing_keys.kid ON DELETE RESTRICT. Never updated, deleted or truncated; a key is revoked once.

Column Type Notes

revoked_at

TIMESTAMPTZ

NOT NULL — clock_timestamp() in identity_revoke_key

operator

TEXT

NOT NULL — who revoked it; CHECK not blank, at most 256 characters, no control character (it is logged)

reason

TEXT

NOT NULL — CHECK not blank, at most 2048 characters

revoked_by

TEXT

NOT NULL — the session’s login (session_user), never caller text

identity_key_cap_guard

PK id INTEGER CHECK id = 1 (the guard’s one row, an ADR-085 D2 exception), and generation BIGINT, which every key insert increments.

identity_jti

PK (client_id TEXT, jti TEXT) (the client picks the jti; an ADR-085 D2 exception to the UUIDv7 rule). A spent client-assertion jti (#2743). Never updated or truncated; rows leave only through identity_purge_client_assertions. The issuer’s issuance-log writer inserts the rows, in the same transaction as the batch’s log rows, with a bare ON CONFLICT DO NOTHING, so its INSERT-only login learns a replay from the rows affected (#3151).

Column Type Notes

client_id

TEXT

NOT NULL — CHECK ^[a-z0-9][a-z0-9-]{0,63}$

jti

TEXT

NOT NULL — CHECK 1–256 visible ASCII characters

expires_at

TIMESTAMPTZ

NOT NULL — the assertion’s exp; CHECK at most 120 s after created_at; indexed (the sweep)

created_at

TIMESTAMPTZ

NOT NULL, DEFAULT clock_timestamp() (the issuer cannot name it)

identity_client_status

PK id UUID (UUIDv7, supplied by the writer). Runtime client disablement (#2743): INSERT-only, the latest row per client (recorded_at, then id) winning. Never updated, deleted or truncated.

Column Type Notes

client_id

TEXT

NOT NULL — CHECK as identity_jti

enabled

BOOLEAN

NOT NULL

operator, reason

TEXT

NOT NULL — as identity_key_revocations

recorded_at

TIMESTAMPTZ

NOT NULL, DEFAULT clock_timestamp()

recorded_by

TEXT

NOT NULL, DEFAULT session_user

identity_issuance_log

Every mint and refusal (#2743). Never updated or truncated; archived a closed UTC day at a time, each day’s partition then dropped (ADR-058).

The log is range-partitioned by UTC day on recorded_at (#3173, migration 20261128010000_identity_issuance_log_day_partitions): one partition a day, identity_issuance_log_pYYYYMMDD, bounds at 00:00 UTC, no default partition, so a row whose day has no partition is refused (23514) and its mint answers 503. Its key is PRIMARY KEY (recorded_at, id), which replaced both PRIMARY KEY (id) and identity_issuance_log_recorded_at_idx: a partitioned table’s unique key must hold the partition key. id alone is no longer unique by constraint, and no writer relies on it (ids are the issuer’s UUIDv7s). Each partition’s key index is named identity_issuance_log_pkey_pYYYYMMDD. The app login reads the log through the parent; it holds no privilege on a partition, and nor does any runtime login.

Column Type Notes

id

UUID

NOT NULL — UUIDv7, supplied by the issuer; the primary key with recorded_at

recorded_at

TIMESTAMPTZ

NOT NULL, DEFAULT clock_timestamp() — the partition key. The issuer holds no INSERT on it, so its rows take the default; the partitioning migration copied each row’s value across

row_digest

TEXT

NOT NULL — stamped: hex SHA-256 of the row’s other columns in order, the stored recorded_at included, NULL as empty, separated by U+001F

replica_id

UUID

NOT NULL — the issuer replica

outcome

TEXT

NOT NULL — CHECK minted or refused

grant_type, client_id, audience, subject, scope

TEXT

the grant, the authenticated client, the audience URN, the subject and the scopes; bounded by CHECKs

token_jti, kid, expires_at

TEXT, TEXT, TIMESTAMPTZ

the released token’s id, signing key and expiry; NOT NULL for a mint, NULL for a refusal (CHECK)

refusal

TEXT

the refusal code, CHECK ^[a-z_]{1,64}$; NOT NULL exactly for a refusal

act_chain

TEXT[]

a worker token’s hops (later units)

Identity records (ADR-085 D2 / D7, #2739)

The identity_ objects follow ADR-085 D2’s rules, set by these first ones for every later identity_ function: owned by craig_security_owner, SECURITY DEFINER, SET search_path = pg_catalog, public, pg_temp (this database’s schema is public), and REVOKE ALL … FROM PUBLIC before any grant. The migration (20261026120000_identity_legacy_issuers.sql) names the roles in unconditional statements, so it fails when craig_security_owner or craig_security_app is absent: craig-security’s role names are required (ADR-085 § Amendment — #2739; deployment guide § Per-service DB roles).

  • INSERT-only. One statement-level trigger function, refuse_legacy_issuer_mutation(), refuses every UPDATE, DELETE and TRUNCATE on both tables, the owner’s included, with SQLSTATE 23000 (a statement trigger also fires on an empty table and on TRUNCATE, which a row trigger does not).

  • identity_record_legacy_issuer(p_issuer text) → boolean inserts the issuer when absent (ON CONFLICT (issuer) DO NOTHING) and returns whether this call inserted it. Re-recording a retired issuer returns false and leaves it retired. It refuses an issuer outside 1–2048 bytes or holding a control character with 22023.

  • identity_retire_legacy_issuer(p_issuer text, p_operator text, p_reason text) → uuid, owner-only, inserts the retirement row of a recorded issuer that never validated a token and returns its id; it logs the retirement (RAISE LOG and RAISE NOTICE, naming the issuer and the operator). Refusals: 22023 a blank or over-long operator or reason, P0002 an issuer not recorded, 23505 one already retired.

The privilege matrix for these objects. The migration first revokes everything on them from every grantee but the owner, PUBLIC included, read from their ACLs, so a role holding the owner’s default privileges under any name keeps nothing, then makes the one grant. The blocking invariant identity_execute_matrix compares every grantee’s rights on every identity_ object (from the ACLs) and PUBLIC’s and the app login’s effective rights with the matrix, and flags any grant option a grantee but the owner holds (the matrix grants none); later units extend both:

Object craig_security_app PUBLIC

identity_legacy_issuers, identity_legacy_issuer_retirements

none

none

identity_record_legacy_issuer(text)

EXECUTE, until the switch’s migration revokes it (ADR-085 U17)

none

identity_retire_legacy_issuer(text, text, text)

none (owner only)

none

The boot step (services/craig-security/src/identity.rs, in run() after the verify-only boot, before serving):

  1. The boot check (identity/app_probe.rs) reads the app pool’s session in one statement and refuses to boot, naming each unmet requirement and the remedy, unless session_user and current_user are craig_security_app; every identity_ object it names exists (a missing one is a refusal, never "no privilege"); no role the login belongs to (itself and PUBLIC included) holds a privilege on either table or on identity_key_cap_guard, anything beyond SELECT on identity_signing_keys or identity_key_revocations (#2741), EXECUTE on identity_retire_legacy_issuer or identity_revoke_key, or a grant option on any identity_ object; and the login owns, directly or through a membership (pg_database_owner included), neither the database, the public schema nor an identity_ object. It names the objects with schema-qualified names and argument types, and every catalog function, type and operator pg_catalog-qualified, so an object created in a schema the login searches cannot hide a privilege. A pass logs INFO identity privilege check passed.

  2. The record. With EXECUTE on identity_record_legacy_issuer held, craig-security records its OIDC_ISSUER (identity/legacy_issuer.rs) and logs INFO legacy issuer recorded or legacy issuer already recorded, naming the issuer. Without the grant it logs a WARN and records nothing; a failed call logs a WARN naming the error and its SQLSTATE. Neither stops the boot, so a prior release redeployed during the soak, after the switch revokes the grant, still boots (D7).

Signing-key registry (ADR-085 D2 / D8, #2741)

The internal token issuer (plan Internal Token Issuer U4) runs as craig-security’s issuer process mode on its own login, craig_security_issuer, and publishes each replica’s in-memory ES256 public keys here. Nothing trusts the keys until the switch (ADR-085 D15). The migration (20261105120000_identity_signing_keys.sql) follows the rules above and fails when craig_security_owner, craig_security_app or craig_security_issuer is absent.

  • Stamping and the cap. identity_signing_keys_stamp(), an owner SECURITY DEFINER BEFORE INSERT row trigger, stamps created_at from clock_timestamp() and derives the three windows (staged created_at–sign_from, primary sign_from–sign_until − 5 s, retiring until publish_until). It then increments the guard row, so concurrent inserters queue, and counts the unrevoked rows whose publish_until is ahead: at 64 it refuses with 54000 (program_limit_exceeded). A revoked row frees its slot. The CHECKs repeat the arithmetic and the thumbprint, so they hold with the triggers bypassed.

  • INSERT-only. identity_registry_immutable(), a statement trigger, refuses every UPDATE, DELETE and TRUNCATE on both tables, the owner’s included, with 23514.

  • identity_revoke_key(p_kid text, p_operator text, p_reason text) → timestamptz, owner-only, inserts the key’s revocation (with revoked_by = session_user), logs it (RAISE LOG) and returns its time. Refusals: 22023 a blank or over-long operator or reason, P0002 an unknown kid, 23505 a key already revoked. A revoked key leaves the published set; its row stays.

  • TEMPORARY. The migration revokes TEMPORARY on craig_security from PUBLIC (no craig-security code uses temporary tables) and TEMPORARY and CREATE from the issuer, and CREATE on public; a closing audit fails it when the issuer still holds either by any path, which happens when the migrator does not own the database (the REVOKE then only warns).

The matrix for the issuer and the app login on the identity objects (ADR-085 D2); PUBLIC holds nothing. No runtime login holds UPDATE, DELETE or TRUNCATE, or EXECUTE on a function created here:

Object craig_security_issuer craig_security_app

identity_signing_keys

SELECT; INSERT on kid, x, y, replica_id, requested_sign_seconds

SELECT

identity_key_revocations

SELECT

SELECT

identity_key_cap_guard

none (the owner trigger takes it)

none

identity_legacy_issuers, identity_legacy_issuer_retirements

SELECT

none

_sqlx_migrations, schema_compat_floor (the schema check)

SELECT

as before

identity_revoke_key, identity_signing_keys_stamp, identity_registry_immutable

none

none

identity_execute_matrix now holds the issuer login to this matrix as well (its effective rights, memberships and PUBLIC included).

The issuer probe (services/craig-security/src/identity/issuer/probe.rs) runs at the issuer’s boot, after the pool and before the schema check, and refuses to serve, naming each unmet requirement, unless session_user and current_user are craig_security_issuer; neither it nor a role it belongs to holds SUPERUSER, CREATEROLE, CREATEDB, REPLICATION or BYPASSRLS; every object it names exists; it holds the matrix above (SELECT on each table, INSERT on each of the five columns) and nothing beyond it, directly, through PUBLIC or through a membership; it executes no identity_ function (found by catalog scan); it holds no grant option; it owns neither the database, the public schema nor a checked object; and it holds neither TEMPORARY nor CREATE on the database nor CREATE on public. A craig_security_app pool is refused by name.

Key rotation (identity/keys/): each replica holds its keys in memory only. Its first key after boot requests 600 s and every later one 21600 s; the next is inserted 120 s before the current sign_until; a key signs from its sign_from to 5 s before its sign_until, both mapped once onto the monotonic clock from the database’s own times; a failed insert retries after 1 s, doubling to 30 s, and one whose outcome is unknown reads back its own kid first; when the database clock and monotonic time diverge by more than 5 s (a suspend, a VM pause, a clock step), the replica drops its keys and publishes a fresh one. A cap refusal is a WARN and counts in identity_key_cap_refusals_total and the issuer’s /readyz.

Issuance stores (ADR-085 D2 / D11 / D13 / D16, #2743)

The token endpoint (plan Internal Token Issuer U6) adds three tables, migration 20261107120000_identity_issuance_stores.sql, which follows the rules above.

  • INSERT-only. identity_issuance_stores_immutable() refuses UPDATE and TRUNCATE on all three tables, and DELETE on identity_client_status, the owner’s included, with 23514. On the partitioned log (#3173) it runs as a row-level BEFORE UPDATE trigger on the parent, which every partition inherits, and as a BEFORE TRUNCATE statement trigger on the parent and on each partition, since a statement trigger is not inherited.

  • identity_issuance_log_stamp(), a BEFORE INSERT row trigger, stamps row_digest over the row’s stored values, overwriting anything supplied. Since #3173 it no longer assigns recorded_at, which comes from the column default (a BEFORE INSERT trigger may not move a row to another partition); an inserter that may name recorded_at, the owner, gets a digest over the time it named.

  • identity_purge_client_assertions(p_limit integer) → integer, owner SECURITY DEFINER, deletes at most p_limit (1–1000, else 22023) jti rows whose expires_at is over 60 s past, oldest first, FOR UPDATE SKIP LOCKED, and returns the count. The issuer sweeps with it.

  • The partition functions (#3173), the app login’s only way to make or drop a partition, over the owner-only range_partition_* helpers that audit_log shares (audit_log). Like audit_log’s, they are owned by the migrating role, `craig_security_owner in a deployment, because they create tables in public:

    • identity_issuance_log_ensure_partitions(from_day date, to_day date) → integer, SECURITY DEFINER: makes each missing day from from_day through to_day, at most 400 a call (22023 beyond); idempotent; returns how many it made. A partition is created standalone with a CHECK equal to its bounds, then attached, so it never waits on an insert. Each new partition then has every privilege revoked from every grantee but the owner, read from its ACL (a name-free sweep, as each identity_ migration makes), and from PUBLIC, craig_security_app and craig_security_issuer by name: the owner’s default privileges would otherwise give the app login, or a role under any name, DML on it. It also gets the truncate guard. craig-security’s partition-maintenance worker calls it for yesterday through 30 days ahead, at start and hourly.

    • identity_issuance_log_partition_days() → SETOF date, SECURITY DEFINER: the day of each partition, oldest first.

    • identity_issuance_log_drop_partition(day date, expected bigint) → bigint, SECURITY DEFINER: the retention archiver’s drop (ADR-058). Refuses a day that is not before the current UTC date (22023) and a day with no partition (42P01). Under a 2 s lock_timeout it locks the partition SHARE (writers wait, readers do not), counts it, and drops it only when the count equals expected; it returns the count either way. The drop takes ACCESS EXCLUSIVE on the parent, so the issuer’s inserts queue behind it for at most the lock timeout, after which it gives up until the next pass (55P03).

  • identity_prune_issuance_log(p_ids uuid[]) was the archive engine’s row prune; the partitioning migration dropped it, and the count-checked partition drop replaces it.

Object craig_security_issuer craig_security_app

identity_jti

INSERT on client_id, jti, expires_at (no read)

none

identity_client_status

SELECT

SELECT

identity_issuance_log

INSERT on every column but recorded_at and row_digest (no read)

SELECT

identity_issuance_log_pYYYYMMDD (each partition, #3173)

none

none

identity_purge_client_assertions

EXECUTE

none

identity_issuance_log_ensure_partitions, identity_issuance_log_partition_days, identity_issuance_log_drop_partition (#3173)

none

EXECUTE

The issuer probe requires exactly these grants beside U4’s and refuses any read of the two append-only tables; the app probe refuses the app login anything on identity_jti or EXECUTE on the purge; identity_execute_matrix lists them all.

  • API: Security & Compliance — the endpoint catalog.

  • ADR-022 — the outbox/inbox/DLQ durability model event_inbox + dead_letter_audit implement.

  • ADR-028 — the on-behalf-of identity the actor_* audit columns capture.

  • ADR-085 — the internal token issuer whose D7 adoption rule reads the legacy issuer record.

Edit this page · latest