Plan: Postgres-Backed craig-intake-keyring

Archive record

Merge requests: !1521 (relay of !1510; Closes #1592–#1596)

2026-08-29 (flat-file store → Postgres for horizontal scale-out: ADR-063 gate wiring, store/api rewrite with the two live-found bugs fixed, multi-instance replay-dedup race proof, flat-file remnants removed; ADR-042 §D8 amendment carries the as-built)

Status

Step Description Status

1

craig_intake_keyring database + roles + signer_keys/replay_records migrations

Done (2026-08-27) — also required registering craig-intake-keyring in xtask/src/registry.rs’s `STATEFUL_SERVICES (a gap this plan didn’t originally scope; missing it would have repeated the exact #1308 bug that registry exists to prevent)

2

ADR-063 migration-gate wiring (KeyringSettings.database_url, main.rs migrate dispatch + verify-only serve boot, compose gate service)

Done (2026-08-27) — verified live: docker compose up craig-intake-keyring-migrate applies cleanly against a real devstack Postgres, tracked in _sqlx_migrations

3

Postgres-backed store.rs rewrite (register/approve/revoke/lookup_active/list_all/replay_check as SQL) + api.rs async wiring

Done (2026-08-27) — also required converting tests/keyring.rs (a pre-existing 24-test HTTP suite this plan’s first draft missed) to the same Postgres design. Live-testing found and fixed two real bugs: register’s INSERT omitted the `expires_at column entirely (silently dropping every caller-supplied expiry); replay_verdict_mutates_nothing’s deliberately-far-future timestamp (chosen to isolate its cutoff from other tests') made its OWN bounded prune indiscriminately delete other concurrently-running tests' fresh rows on the shared table — fixed by isolating that test onto its own scratch database. A post-push independent review pass then found two more: `store.rs’s devstack-backed unit tests were missing `#[ignore = "requires devstack"] (would have hard-failed the no-devstack cargo xtask validate --skip-devstack/CI job, since it runs --lib --bins and those tests live inline in the lib target — tests/*.rs integration files were correctly unmarked, since that job never selects them at all); and register’s new transaction checked capacity BEFORE duplicate-kid, reversed from the original flat-file precedence, silently changing the HTTP status (409→429) for the edge case of re-registering an existing `kid while the store is exactly at capacity — both fixed, with a new test (duplicate_kid_at_capacity_is_still_duplicate_not_at_capacity) pinning the restored precedence

4

Remove flat-file store code, keyring-data volume, store_path config

Done (2026-08-27) — grep sweep clean; Dockerfile’s `/data dir setup also removed (a gap beyond the plan’s original file list)

5

Multi-instance correctness proof (2 replicas against one DB; concurrent-race tests)

Done (2026-08-27) — tests/multi_instance.rs, all 4 tests passing live against real devstack Postgres, stable across repeated runs, including the security-critical two_instances_racing_same_jti_exactly_one_first_seen

6

Docs (services.adoc, .claude/CLAUDE.md, craig-intake-keyring.adoc, CHANGELOG) + ADR-042 amendment

Done (2026-08-27), except .claude/CLAUDE.md — the harness blocks direct edits to that file; the one-line service-table diff was handed to the user instead

Epic: &84 (closed)
Issues: #1592, #1593, #1594, #1595, #1596 (closed), #1597 (bookkeeping)
MR: !1521 (relay of !1510 — force-push denied in the agent environment; identical commits, original authorship preserved), merged 2026-08-29

All 46 tests in craig-intake-keyring (unit + the tests/keyring.rs HTTP suite + tests/multi_instance.rs) pass against a real devstack Postgres, stable across 3 repeated cargo nextest run invocations; the relay branch’s full pre-push battery ran 7039/7039 green. Done (2026-08-29) — merged to main; residual on #1597: the .claude/CLAUDE.md port-table row stays a user-applied one-line diff (harness block).

Context

craig-intake-keyring (ADR-042 §D8) is the stateless-edge companion sidecar that holds the two pieces of state ADR-017’s stateless intake edge cannot: the standalone-SHINES signer public-key registry (kid → JWK, lifecycle pending/approved/revoked) and the JWS replay-dedup table (jti → iat). It was deliberately built as "a minimal companion service" with an unencrypted flat JSON file as its store (ADR-042 §D8) — the file holds only public keys and replay records (all publishable; encryption there would be obscurity, not security, per Kerckhoffs). Concurrency safety today comes entirely from one in-process parking_lot::RwLock serializing every mutation before an atomic local write (temp file → fsync → rename → parent-dir fsync, #980). That design assumes exactly one running instance: state lives on one container’s local disk, so there is no way to run N replicas of the service today.

This plan changes that assumption on request: the deployment wants craig-intake-keyring to run as multiple horizontally-scaled instances. Two S3-based designs were evaluated and rejected before this plan was written (see the ADR-042 amendment this plan pairs with, and ADR-049's own conditional-write caveat for the same backend):

  • Per-operation objects on S3, no locks — fails outright for replay_check: two instances can each observe "not yet seen" and both admit the same jti during the reconciliation window. That is a live anti-replay regression, not a cosmetic race — replay_check is the sole defense against a captured signed JWS being replayed into a mandated report a second time.

  • Per-key S3 objects + conditional writes (If-None-Match/If-Match) for compare-and-swap — crates/craig-store/tests/garage_put_create.rs already pins, against the real devstack Garage backend (v2.2.0), that Garage permanently ignores If-None-Match: * (a CRDT-architecture limitation, confirmed upstream as a design limitation, not a bug). Any design relying on S3 conditional writes for mutual exclusion is unverifiable in this project’s own devstack and would silently lose its safety property there while appearing to work against real AWS S3 in production — the opposite of this repo’s contested-environment testing posture (ADR-067). A lock-file-in-bucket variant was also considered and rejected on the same grounds: a lock file’s "create only if absent" requirement is the identical primitive Garage does not honor.

Postgres gives the needed correctness for free via ordinary row transactions and constraints — the same pattern craig-security’s own `partner_signer_keys table already uses for an almost identical shape of data (a signer-key registry with a pending/approved/revoked lifecycle; craig-intake-keyring’s current store.rs docstrings already say approve/revoke "mirrors craig-security’s `status = 'pending'-gated update" — this plan makes that literal instead of just structural). This also lets the service adopt the fleet’s standard ADR-063 migration-gate posture (same-image migrate subcommand, verify-only serve boot) instead of being the one service outside that discipline.

Scope

In scope:

  • A new craig_intake_keyring Postgres database (devstack: devstack/postgres/init.sql) with owner/app roles per the #1310 migration-owner-vs-runtime-role convention every other stateful service already follows.

  • signer_keys and replay_records tables + migrations under services/craig-intake-keyring/migrations/.

  • ADR-063 migration-gate wiring: <binary> migrate dispatch, verify-only serve boot, a craig-intake-keyring-migrate compose service gating the app service via service_completed_successfully.

  • A full rewrite of store.rs’s five operations (`register, approve, revoke, lookup_active, list_all, replay_check) as SQL against the shared pool — atomic and safe under N concurrent instances, in particular replay_check via a single upsert-with-conditional-overwrite statement (Design section below).

  • Removal of the flat-file store: tempfile/parking_lot deps, the local KeyringSettings::store_path field + keyring-data compose volume, the #[cfg(test)] PersistFault local-disk fault scaffold.

  • A concurrency test that actually runs 2+ store instances against one shared Postgres database and proves the same race guarantees the current single-process tests assert (exactly-one-wins duplicate-kid, exactly-one-wins same-jti replay) — not just unit tests against a single in-process pool, since the whole point of this change is cross-instance safety.

  • Doc updates: services.adoc port/DB table row, .claude/CLAUDE.md service port table + a status bullet, docs/modules/ROOT/pages/craig-intake-keyring.adoc, CHANGELOG.adoc, and an ADR-042 amendment recording the reversal of §D8’s "no DB, flat-file" decision with the rationale above.

Out of scope:

  • Actually running N replicas in devstack/production compose by default (this plan makes it safe to; deployment topology / replica-count knobs are an operational follow-up, filed separately).

  • Any change to craig-intake’s `SignerAuthClient/JwsReplayClient or its wire contract, or to the keyring’s HTTP wire shapes/routes. api.rs’s internals do change (see Design § `api.rs changes below — the store becomes async, so the four spawn_blocking wrappers and the now-dead ApiError::Join variant go away) but every outcome (Created/DuplicateKid/ AtCapacity/Ok/NotFound/FirstSeen/Replay, HTTP status codes, response JSON shapes) keeps its exact current semantics.

  • Encrypting the stored keys/replay records — unchanged from ADR-042 §D8’s Kerckhoffs rationale (public keys + replay metadata, not secrets).

  • Bringing craig-intake-keyring onto the full craig-api::bootstrap_verified/ServiceSettings framework (OIDC, RabbitMQ, AppState). That framework is a package deal — adopting it to get the migration gate would also drag in OIDC/MQ config the keyring has no use for (it has no worker identity concept; auth is a single shared bearer admin token, not OIDC claims). This plan calls the same underlying primitives (craig_api::run_migrate_mode_if_requested, craig_db::DbPool::verify_schema) directly instead, keeping KeyringSettings bespoke as it is today (see Design).

Design

Schema

New database craig_intake_keyring, migration services/craig-intake-keyring/migrations/<ts>_signer_keys_and_replay.sql:

CREATE TABLE signer_keys (
    id               UUID PRIMARY KEY DEFAULT uuidv7(),
    kid              TEXT NOT NULL UNIQUE,
    user_identifier  TEXT NOT NULL,
    display_name     TEXT NOT NULL,
    public_key_jwk   JSONB NOT NULL,
    algorithm        TEXT NOT NULL CHECK (algorithm = 'ES256'),
    status           TEXT NOT NULL DEFAULT 'pending'
                       CHECK (status IN ('pending', 'approved', 'revoked')),
    created_at       TIMESTAMPTZ NOT NULL DEFAULT now(),
    approved_at      TIMESTAMPTZ,
    revoked_at       TIMESTAMPTZ,
    expires_at       TIMESTAMPTZ
);

-- #714 list_all order + the hot lookup_active path.
CREATE INDEX idx_signer_keys_created_at_kid ON signer_keys (created_at, kid);
CREATE INDEX idx_signer_keys_kid_approved ON signer_keys (kid) WHERE status = 'approved';

CREATE TABLE replay_records (
    jti  UUID PRIMARY KEY,
    iat  BIGINT NOT NULL
);

CREATE INDEX idx_replay_records_iat ON replay_records (iat);

algorithm carries both DEFAULT 'ES256' and the CHECK — craig-security’s own partner_signer_keys migration (services/craig-security/migrations/20260424100000_partner_signer_keys.sql:19-20) keeps both, this plan’s earlier draft incorrectly claimed craig-security omits the default; fixed to match exactly. SignerKeyStatus (crates/craig-reference/src/enums.rs) already derives sqlx::Type with #[sqlx(type_name = "text", rename_all = "snake_case")], so Rust code binds/reads it directly against the TEXT column — no new type needed.

Query style: runtime-checked sqlx::query_as::<_, KeyRecord>(…​)/sqlx::query(…​) with .bind(…​), matching every existing store in this codebase (services/craig-composition/src/db.rs, services/craig-security/src/store/signer_keys.rs) — not the compile-time-checked sqlx::query_as!/query! macros. Those macros need a live DATABASE_URL or a committed .sqlx/ offline cache at build time; neither exists anywhere in this workspace today (verified: zero hits for query_as!/query!, no .sqlx/ directory anywhere in the repo), and introducing that build-time DB dependency for one crate would be inconsistent with the rest of the fleet, not a genuine correctness need here.

Devstack role/DB provisioning in devstack/postgres/init.sql, exactly the #1310 pattern already used for every other service (see the craig_composition block for the literal template):

CREATE DATABASE craig_intake_keyring;
...
CREATE ROLE craig_intake_keyring_owner LOGIN PASSWORD 'craig_intake_keyring_owner';
CREATE ROLE craig_intake_keyring_app LOGIN PASSWORD 'craig_intake_keyring_app';
ALTER DATABASE craig_intake_keyring OWNER TO craig_intake_keyring_owner;
GRANT CONNECT ON DATABASE craig_intake_keyring TO craig_intake_keyring_app;

\connect craig_intake_keyring
GRANT USAGE ON SCHEMA public TO craig_intake_keyring_app;
ALTER DEFAULT PRIVILEGES FOR ROLE craig_intake_keyring_owner IN SCHEMA public
    GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO craig_intake_keyring_app;

Atomicity per operation (the part that has to survive N instances)

replay_check — the security-critical one. A single upsert with a conditional overwrite, using Postgres row-level locking during the INSERT …​ ON CONFLICT to make the whole first-seen-or-replay decision one atomic statement regardless of how many instances race it, run inside a transaction alongside a bounded maintenance prune (both statements below, one transaction):

-- statement 1: the atomic first-seen-or-replay decision
INSERT INTO replay_records (jti, iat) VALUES ($1, $2)
ON CONFLICT (jti) DO UPDATE
    SET iat = EXCLUDED.iat
    WHERE replay_records.iat < $3   -- $3 = cutoff = now - retention_secs
RETURNING jti

-- statement 2 (only when statement 1 returned a row, i.e. FirstSeen): a bounded
-- maintenance prune, capped so no single request pays for an unbounded scan
DELETE FROM replay_records
WHERE jti IN (
    SELECT jti FROM replay_records WHERE iat < $3 LIMIT 100
)

A returned row from statement 1 means "accepted" (ReplayOutcome::FirstSeen) — either truly new, or a jti whose prior record fell outside the retention window and was legitimately overwritten. No returned row means the existing record is still within the window: ReplayOutcome::Replay. This is one statement, so two instances racing the same jti cannot both see "first seen" — Postgres serializes the conflicting writers at the row level; the Replay path runs statement 1 only, so it mutates nothing, preserving the current replay_verdict_mutates_nothing invariant.

Statement 2 is not optional and is a correction to this plan’s first draft, which claimed pruning was "piggybacked on the next write, same as today" — that is false. Today’s single-process commit closure (store.rs:343, pre-rewrite) runs retain() over the entire in-memory table on every first-seen write, sweeping every stale record regardless of which jti triggered the write. The single-row ON CONFLICT upsert in statement 1 only ever touches the one row being written — a jti submitted once and never resubmitted would sit in replay_records forever with no statement 1 alone ever reaching it, which is unbounded growth the current design does not have (most legitimate JWS submissions are exactly this "once, never repeated" shape, so this is not an edge case). Statement 2 closes that gap with a capped batch delete piggybacked on every accepted (FirstSeen) write — bounded per-request cost (LIMIT 100), no new background worker/Supervisor registration needed (this service currently documents "zero long-lived workers" in main.rs, and staying there avoids reopening the /readyz worker-gating surface for one maintenance task). Concurrent instances running statement 2 simultaneously on overlapping rows is safe — a DELETE racing an already-deleted row is a no-op, not an error.

register — duplicate-kid rejection is exact; capacity is now exact too, via a transaction-scoped advisory lock. Uniqueness is enforced by the kid UNIQUE constraint itself, so DuplicateKid detection was already exact under any number of racing instances regardless of isolation level — but a naive separate SELECT count(*) capacity pre-check would NOT be exact under concurrent registration at the max_keys boundary (a classic read-then-write race), which would silently weaken the existing concurrent_distinct_kid_registration_respects_capacity test’s "no over-admission past the cap, ever" guarantee. Rather than accept that regression (or weaken the test to match it, which testing-discipline rules out for anything short of a genuinely-wrong test), register wraps its capacity check + insert in one transaction serialized fleet-wide by a transaction-scoped advisory lock (pg_advisory_xact_lock — auto-released on commit/rollback, unlike the session-scoped AdvisoryLease crates/craig-retention/src/lease.rs uses for skip-if-busy batch passes; this is a different primitive for a different shape of problem — a short blocking critical section on an interactive request path, not a periodic pass an instance should skip rather than wait for):

BEGIN;
SELECT pg_advisory_xact_lock(hashtext('craig_intake_keyring_register'));
SELECT count(*) FROM signer_keys;
-- (application code: if count >= max_keys, ROLLBACK and return AtCapacity)
INSERT INTO signer_keys (id, kid, user_identifier, display_name, public_key_jwk, algorithm, status, created_at)
VALUES ($1, $2, $3, $4, $5, $6, 'pending', now())
ON CONFLICT (kid) DO NOTHING
RETURNING id;
COMMIT;

No returned row from the INSERT (having passed the capacity gate) ⇒ DuplicateKid. The advisory lock only ever guards register — approve/revoke are single-row UPDATE …​ WHERE statements with no cross-row invariant to protect, and lookup_active/replay_check are unaffected (the lock’s name/hash is specific to register, so it never contends with the hot lookup_active read path). register is a low-volume administrative operation (signer onboarding, not per-report traffic), so serializing it fleet-wide costs nothing that matters.

approve / revoke — literally craig-security’s pattern, kid-keyed instead of id-keyed (the sidecar’s HTTP API takes kid as the path param, not the server-assigned UUID):

-- approve
UPDATE signer_keys SET status = 'approved', approved_at = $2
WHERE kid = $1 AND status = 'pending'
RETURNING *

-- revoke
UPDATE signer_keys SET status = 'revoked', revoked_at = $2
WHERE kid = $1 AND status <> 'revoked'
RETURNING *

An ordinary UPDATE …​ WHERE is already atomic per-row under Postgres MVCC — no additional locking needed. Zero rows updated ⇒ LifecycleOutcome::NotFound (unknown kid, or not in a transitionable state), exactly today’s semantics.

lookup_active / list_all are plain reads, no concurrency concerns:

-- lookup_active
SELECT * FROM signer_keys
WHERE kid = $1 AND status = 'approved' AND (expires_at IS NULL OR expires_at > $2)

-- list_all (#714 deterministic order)
SELECT * FROM signer_keys ORDER BY created_at, kid

store.rs shape

KeyringState becomes a thin wrapper around sqlx::PgPool (no more RwLock<Inner>, no more KeyringFile/Inner on-disk-vs-in-memory split — every operation is a direct query, matching how every other DB-backed CRAIG service’s store layer works, e.g. services/craig-composition/src/db.rs which takes &PgPool throughout). The five outcome enums (RegisterOutcome, LifecycleOutcome, ReplayOutcome) and the KeyRecord struct are unchanged — only their construction moves from in-memory HashMap mutation to sqlx::query_as! / query! calls. api.rs needs no changes: it already calls store.register(rec) etc. and matches on the outcome enums, not on store internals. load_or_init’s local-file bootstrap is replaced by `KeyringState::new(pool: PgPool) → Self — a plain constructor, no disk I/O, no Result (connecting already happened in main.rs).

The #[cfg(test)] PersistFault one-shot fault-injection scaffold (local-disk temp-write/fsync/ rename/dir-fsync boundaries) is retired outright — those boundaries no longer exist. New tests against the real devstack Postgres should use this project’s existing DB-fault-injection conventions from the contested-environment testing program (ADR-067; PgFaultArmer / pg_terminate_backend-style native faults) rather than reinventing a bespoke scaffold, but building out that fault coverage is Step 5/6 scope, not blocking Steps 1-4’s correctness.

api.rs changes (not a no-op — corrected from this plan’s first draft)

store.rs’s methods become `async fn`s returning `Result<_, KeyringError> (including lookup_active/list_all, which are infallible today — a parking_lot::RwLock read can’t fail, a Postgres query can). Concretely, in api.rs:

  • The four tokio::task::spawn_blocking(move || store.<op>(…​)).await?? call sites (register api.rs:296, replay_check api.rs:375, approve api.rs:394, revoke api.rs:413) become plain st.store.<op>(…​).await? — the #808 comments justifying spawn_blocking ("takes the write lock and does blocking fs I/O") describe a boundary that no longer exists and are replaced with a one-line note that the store call is natively async against the shared pool.

  • lookup_by_kid (api.rs:309-326) and list_keys (api.rs:349-364) start .await-ing a fallible call (st.store.lookup_active(&kid, Utc::now()).await?.ok_or(ApiError::NotFound)?; list_keys becomes Result<Json<Vec<SignerKeyListEntry>>, ApiError> instead of an infallible Json<…​>).

  • ApiError::Join (api.rs:109-113) becomes dead code once no call site produces a tokio::task::JoinError — removed, along with its status_code() and into_response() match arms (api.rs:125, 136).

  • No route, request/response DTO, status-code mapping, or wire contract changes — every outcome enum still maps to the same HTTP status it does today.

  • The four now-unused let store = Arc::clone(&st.store); lines immediately preceding each spawn_blocking call (api.rs:295,373,392,411) are removed along with their call sites — calling st.store.<op>(…​) directly needs no clone. AppState’s `store field doc comment (api.rs:82, "The flat-file key + replay store.") is updated too.

Config + boot wiring

config.rs: drop store_path: String; add database_url: String (no serde default — required, matching every other DB-backed service’s DATABASE_URL-style field and validate()’s existing "never silently default" posture). Keep `port, log_level, admin_token, replay_retention_secs, max_keys, enable_key_list unchanged.

main.rs — the ADR-063 dispatch, called directly (not via craig_api::bootstrap_verified, which would pull in ServiceSettings/OIDC/MQ — see Scope):

let migrator = sqlx::migrate!();
// "CRAIG_INTAKE_KEYRING__DATABASE_URL" is hardcoded here (NOT auto-derived —
// see note below) but happens to be exactly what KeyringSettings's existing
// "CRAIG_INTAKE_KEYRING" env prefix already implies.
if craig_api::run_migrate_mode_if_requested(
    "CRAIG_INTAKE_KEYRING__DATABASE_URL",
    "craig-intake-keyring",
    &migrator,
)
.await?
{
    return Ok(());
}

let settings = KeyringSettings::load()...;
settings.validate()...;
let pool = craig_db::DbPool::connect(&settings.database_url).await?;
pool.verify_schema(&migrator, craig_db::FloorCheck::Enforce, Some("docker compose up craig-intake-keyring-migrate")).await?;
let state = Arc::new(KeyringState::new(pool.inner().clone(), settings.max_keys, retention_secs));

run_migrate_mode_if_requested is pub use-re-exported at the craig_api crate root (crates/craig-api/src/lib.rs:144-146) from migrate_mode.rs:115 — migrate_mode itself is a private module (mod migrate_mode;, lib.rs:112), so the call site is craig_api::run_migrate_mode_if_requested, NOT craig_api::migrate_mode::run_migrate_mode_if_requested (an early draft of this plan got that path wrong; caught by cargo check during implementation). It’s the OpenAPI-doc-free variant of the dispatcher — the keyring has no utoipa::OpenApi today and this plan doesn’t add one just to satisfy the wrapper that wants it (run_process_modes_if_requested, migrate_mode.rs:295, the one every other current DB-backed service actually calls). Calling the bare form is a deliberate, first-of-its-kind deviation in this fleet: unlike run_process_modes_if_requested, which auto-derives the env var name from the service string via database_url_env_var (migrate_mode.rs:332-339), the bare run_migrate_mode_if_requested takes the env var name as an explicit caller-supplied argument — there is no auto-derivation to lean on here, so the string above must be hand-verified to match what database_url_env_var("craig-intake-keyring") would have produced (CRAIG_INTAKE_KEYRING__DATABASE_URL) and kept in sync by hand if the service is ever renamed.

Compose (docker-compose.yml), mirroring craig-composition/craig-composition-migrate exactly:

craig-intake-keyring-migrate:
  <<: *craig-intake-keyring-image
  command: ["migrate"]
  restart: "no"
  environment:
    CRAIG_INTAKE_KEYRING__DATABASE_URL: postgres://craig_intake_keyring_owner:craig_intake_keyring_owner@postgres:5432/craig_intake_keyring
  depends_on:
    postgres:
      condition: service_healthy

craig-intake-keyring:
  <<: *craig-intake-keyring-image
  environment:
    CRAIG_INTAKE_KEYRING__DATABASE_URL: postgres://craig_intake_keyring_app:craig_intake_keyring_app@postgres:5432/craig_intake_keyring
    # admin_token / max_keys / replay_retention_secs / enable_key_list unchanged
  depends_on:
    craig-intake-keyring-migrate:
      condition: service_completed_successfully
  # keyring-data volume + STORE_PATH env var removed

(A x-craig-intake-keyring-image anchor needs to be introduced the same way x-craig-composition-image is — the service currently has no anchor since it’s a single service block with no migrate sibling.)

Steps

Step 1: Schema + devstack provisioning

Files: services/craig-intake-keyring/migrations/<ts>_signer_keys_and_replay.sql (NEW), devstack/postgres/init.sql

Add the craig_intake_keyring database + owner/app roles (Design § Schema) to init.sql in the same block/ordering as the other per-service entries. Add the migration file with the two CREATE TABLE statements + indexes from Design § Schema. Check existing migration timestamp conventions in sibling services to pick a non-colliding filename timestamp.

Step 2: ADR-063 migration-gate wiring

Files: services/craig-intake-keyring/src/config.rs, services/craig-intake-keyring/src/main.rs, services/craig-intake-keyring/Cargo.toml, docker-compose.yml

config.rs: replace store_path with database_url per Design § Config. Update/add validate()/defaults_populate_…​ tests accordingly (store_path assertions become database_url ones).

main.rs: wire the migrate dispatch + verify-only serve boot per Design § Config + boot wiring. Drop the Path/local-file-open imports; add craig_db, craig_api::migrate_mode.

Cargo.toml: add sqlx = { workspace = true }, craig-db = { workspace = true }, craig-api = { workspace = true }; remove tempfile, parking_lot.

docker-compose.yml: introduce the x-craig-intake-keyring-image anchor (mirroring x-craig-composition-image), add the craig-intake-keyring-migrate service, update the craig-intake-keyring service’s environment/depends_on per Design, remove the keyring-data volume mount + its top-level volumes: entry if nothing else references it.

Step 3: Postgres-backed store.rs + api.rs async wiring

Files: services/craig-intake-keyring/src/store.rs, services/craig-intake-keyring/src/api.rs, services/craig-intake-keyring/tests/keyring.rs, crates/craig-test-lib/src/template_db.rs (register the new craig_intake_keyring_captest WarmableBase)

Full rewrite per Design § store.rs shape + § Atomicity per operation. Keep KeyRecord, RegisterOutcome, LifecycleOutcome, ReplayOutcome byte-identical (public API api.rs depends on, after its own changes in Design § api.rs changes). Replace the module doc comment (currently describes the flat-file copy-on-write design) with one describing the Postgres design and its atomicity guarantees per operation.

Disposition of every existing #[cfg(test)] test in store.rs (verified exhaustive against the current file):

  • Port to a real devstack Postgres connection (sqlx::PgPool::connect, same pattern as services/craig-composition/src/db.rs’s test module), asserting the same outcomes, now `async: register_approve_lookup_roundtrip, list_all_is_sorted_by_created_at_then_kid, duplicate_kid_is_rejected, capacity_cap_is_enforced, approve_requires_pending, revoke_is_terminal, expired_key_is_not_active, replay_dedups_by_jti_alone, replay_prunes_old_jti_by_window, concurrent_writers_leave_valid_json (still meaningful: N concurrent tokio tasks against ONE pool all succeed and produce N rows — now proving Postgres’s own concurrency handling instead of the retired RwLock), concurrent_same_kid_register_exactly_one_wins, concurrent_distinct_kid_registration_respects_capacity (this one now also proves the transaction-scoped advisory lock from Design § Atomicity keeps capacity enforcement exact — do not weaken its assertions to accommodate a race; the advisory lock exists specifically so this test’s current guarantee still holds).

  • Port with a rewritten mechanism, same intent: replay_verdict_mutates_nothing currently asserts s.inner.read() HashMap equality (an internal field gone after the rewrite) — port as a behavioral assertion instead: after an expired jti E is superseded by a fresh jti L becoming Replay, SELECT iat FROM replay_records WHERE jti = E is unchanged from its stale value (a Replay verdict must not touch E’s row), and a later replay_check(E, …​) past the cutoff still succeeds as FirstSeen.

  • Retire outright (the boundary being tested no longer exists — do not force-fit): atomic_write_leaves_no_temp_residue, reload_from_disk_is_equivalent, the four persist_failure PersistFault tests (register_persist_failure_rolls_back, approve_persist_failure_stays_inactive, revoke_persist_failure_rolls_back, replay_persist_failure_is_retryable), dir_fsync_failure_rolls_back_and_retry_reconverges (all local-disk temp-write/fsync/rename mechanics), and keyring_file_serde_roundtrip (the KeyringFile/ReplayRec on-disk JSON types it fuzzes are deleted with the flat-file store — this is not a coverage loss of hand-rolled parsing code the testing-discipline proptest mandate would otherwise require keeping, since there is no longer any hand-rolled (de)serializer here at all: column binding is `sqlx’s responsibility, already exercised upstream).

Apply the api.rs changes from Design § api.rs changes in the same step (they’re a direct consequence of `store.rs’s methods becoming async/fallible, not a separable unit of work).

Correction found during implementation, not by either plan-review pass: tests/keyring.rs (a 24-test in-process HTTP-contract suite driving the router via tower::ServiceExt::oneshot) also builds its store from TempDir + KeyringState::load_or_init and needs the same conversion. Unlike store.rs’s own unit tests, MANY of these tests reuse the same literal `kid/jti values (e.g. "k1") across different test functions, so — unlike store.rs’s tests, which can share the plain `postgres_test_db_url database because they use randomly-suffixed identifiers — every test in this file needs its own fully isolated scratch database (the same scratch_db("craig_intake_keyring_captest", …​) mechanism Step 3/5 already introduces), not just isolated data within a shared one. Add services/craig-intake-keyring/tests/keyring.rs to this step’s Files.

Step 4: Remove flat-file remnants

Files: services/craig-intake-keyring/src/lib.rs, services/craig-intake-keyring/src/main.rs (doc comments only — `main.rs’s code changes are Step 2’s)

Confirm no remaining reference to store_path, KeyringFile, Inner, parking_lot, or tempfile anywhere in the crate (grep -rn sweep). Update the crate-level doc comment in lib.rs if it describes the flat-file trust boundary (ADR-042 §D8 reference stays; the storage-mechanism description changes). main.rs’s module doc comment ("the keyring spawns zero long-lived workers…​ store writes run as per-request `spawn_blocking calls") stays true in substance (no worker is introduced — see Design § Atomicity’s bounded-prune choice specifically to avoid that) but its spawn_blocking justification is now stale wording and gets a one-line update.

Step 5: Multi-instance correctness proof

Files: services/craig-intake-keyring/tests/multi_instance.rs (NEW)

The whole point of this plan is cross-instance safety, so prove it directly rather than trusting that per-instance unit tests generalize: construct two independent KeyringState`s, each with its own `PgPool connected to the same devstack craig_intake_keyring database, and race them against each other the same way the current single-process tests race threads within one store:

  • Two KeyringState`s racing `register with the same kid — exactly one Created, the other DuplicateKid (mirrors concurrent_same_kid_register_exactly_one_wins, now across two pools/ connections instead of two threads on one RwLock).

  • Two KeyringState`s racing `replay_check with the same jti — exactly one FirstSeen, the other Replay (the security property this whole plan exists to fix).

  • Two KeyringState`s racing `approve on the same kid — exactly one Ok, the other NotFound.

  • Two KeyringState`s racing `register with distinct kid`s against a store pre-filled to `max_keys - 1 — exactly one Created, the other AtCapacity, proving the transaction-scoped advisory lock (Design § Atomicity per operation) serializes capacity enforcement across instances, not just within one pool (mirrors concurrent_distinct_kid_registration_respects_capacity, across two pools).

Step 6: Docs + ADR amendment

Files: docs/modules/ROOT/pages/services.adoc, .claude/CLAUDE.md, docs/modules/ROOT/pages/craig-intake-keyring.adoc, CHANGELOG.adoc, docs/modules/ROOT/pages/adrs/adr-042-standalone-intake-backend-plugin.adoc

  • services.adoc line 19: change 8010 / — (flat-file registry, ADR-042 §D8) to 8010 / craig_intake_keyring (Postgres, ADR-042 §D8 amendment); the none — flat-file JSON cell in the same row updates to point at the new migration.

  • .claude/CLAUDE.md: the service-port table’s craig-intake-keyring row description column changes from "flat-file registry" to its DB; no epic-status bullet needed unless this plan gets an epic (see Epic/Issues below).

  • craig-intake-keyring.adoc: update the storage description.

  • CHANGELOG.adoc: == Unreleased entry — this is a pre-1.0 breaking operational change (deployments must run docker compose up craig-intake-keyring-migrate / the k8s equivalent before the service can boot; the old keyring-data volume + STORE_PATH env var are gone).

  • ADR-042: add === Amendment {date} — Postgres-backed keyring for horizontal scale-out (#{issue}) under the existing == Amendments section, recording: the multi-instance requirement, the two rejected S3 designs and why (the Garage conditional-write limitation, cited to garage_put_create.rs), and the decision to adopt Postgres + the fleet’s ADR-063 migration-gate pattern instead of the flat-file design §D8 originally chose.

Files Touched

File Change

services/craig-intake-keyring/migrations/<ts>_signer_keys_and_replay.sql

NEW: signer_keys + replay_records tables

devstack/postgres/init.sql

NEW: craig_intake_keyring database + owner/app roles

services/craig-intake-keyring/src/config.rs

store_path → database_url

services/craig-intake-keyring/src/main.rs

ADR-063 migrate dispatch + verify-only boot; drop local-file load_or_init call

services/craig-intake-keyring/src/store.rs

Full rewrite: RwLock<Inner> + flat-file → PgPool-backed async queries

services/craig-intake-keyring/src/api.rs

Remove 4 spawn_blocking wrappers + #808 comments; lookup_by_kid/list_keys become fallible/.await-ing; remove dead ApiError::Join

services/craig-intake-keyring/src/lib.rs

Doc-comment update (storage mechanism description)

services/craig-intake-keyring/Cargo.toml

+sqlx, craig-db, craig-api; -tempfile, parking_lot

services/craig-intake-keyring/tests/multi_instance.rs

NEW: two-pool cross-instance race tests

docker-compose.yml

x-craig-intake-keyring-image anchor, craig-intake-keyring-migrate service, updated craig-intake-keyring env/depends_on, remove keyring-data volume

docs/modules/ROOT/pages/services.adoc

Port/DB table row

.claude/CLAUDE.md

Service port table row

docs/modules/ROOT/pages/craig-intake-keyring.adoc

Storage description

CHANGELOG.adoc

== Unreleased entry (pre-1.0 breaking: migrate gate required, volume/env var removed)

docs/modules/ROOT/pages/adrs/adr-042-standalone-intake-backend-plugin.adoc

New === Amendment section

Verification

  1. cargo nextest run -p craig-intake-keyring --lib — unit tests pass against devstack Postgres

  2. cargo xtask dev reload (schema change — use restart, not reload, per the template’s own caveat for migrations)

  3. docker compose up craig-intake-keyring-migrate succeeds standalone, then docker compose up craig-intake-keyring boots and passes its /readyz healthcheck

  4. cargo nextest run -p craig-intake-keyring — integration tests incl. tests/multi_instance.rs

  5. cargo nextest run --workspace — no regression in craig-intake’s standalone-SHINES tests that exercise `SignerAuthClient/JwsReplayClient against the keyring

  6. cargo xtask e2e — the existing standalone-SHINES signed-report e2e still passes end-to-end through the (now Postgres-backed) keyring

  7. Manual: start 2 instances of craig-intake-keyring against the same devstack DB (docker compose up --scale craig-intake-keyring=2), register a key via instance A, approve via instance B, verify lookup_active on instance A sees the approval

Documentation Updates

Edit this page · latest