Plan: Field-Ciphertext Storage-Context AAD — Envelope Format v2 (#1007)

Archive record

Merge requests: !1598 (U0 plan page, Relates to #1007) + !1599 (MR-0, Closes #1756) + !1600 (MR-1, Closes #1757) + !1601 (MR-2, Closes #1758 / #1007)

2026-09-10 — every craig-cases field ciphertext is envelope format v2, binding its storage context (table, column, primary-key UUID and, for a blind-index base, the stored HMAC sibling) as AES-256-GCM-SIV associated data: v1 is refused outright, a keyed Required reader refuses any non-envelope cell, every write path mints its row id before the walk, the boot canary lives under CANARY_CONTEXT, and the devstack envelope-format marker class turns the bump into one wipe + keyed reseed per stack. crypto_field_lineage and the migrate gate are untouched; the ADR-048 amendment carries the as-built and the index-only sibling residual is #1759.

Status

Done (2026-09-10) — !1601

Anchors

#1007 (ruled 2026-09-03), ADR-048 (threat model + D3 boot verify-only), ADR-049 (#1025 single-writer scheme truth), ADR-063 (migrate gate), ADR-064 (secrets store / field-key adoption), ADR-020 (#906 envelope), ADR-062 (id-minting precedent), #1399 (post-1.0 rewrite tooling), #1310 (role split — the REVOKE follow-up rides it), #1653 / #1405 (devstack marker classes), epic &92 (children #1756 MR-0, #1757 MR-1, #1758 MR-2), follow-up #1759 (index-only sibling substitution).

Context

craig-crypto’s AES-256-GCM-SIV field envelope (`CGEF || version(1) || nonce || ct+tag, base64; crates/craig-crypto/src/lib.rs:215-228,398-427) binds NO associated data: a valid ciphertext moves between rows, columns and tables under one key, and the header bytes themselves are unauthenticated (lib.rs:389-392). ADR-048 scoped its threat model to passive disclosure and named this the deferred follow-up (its "Threat model" paragraph and the Consequences "no-AAD cell-swap limitation" bullet).

Ruling (2026-09-03, maintainer, on #1007). Do it NOW, pre-1.0, through plan mode — "AAD = table
column + row identity" as ciphertext format v2; a format change today costs one devstack reseed, after 1.0 a production rewrite (#1399). Rulings at the plan gate: the row identity is the primary-key UUID on every table (reports and referral-from-report mint the id client-side before the walk — the ADR-062 create_person precedent). The maintainer’s rev-1 review (2026-09-09) folded four findings: keyed Required reads must REFUSE non-envelope values (the plaintext passthrough was an authentication bypass); the format bump needs the wipe-before-start marker class (dev refresh starts the rebuilt image against the old volume and would abort on SchemeMismatch before its reseed step); the blind-index residual is HMAC-only substitution, not pair copying; the summary list decrypts only narrative.

Facts that shape the design (read-only research, every claim file:line): craig_search::row is the ONE walk every writer and reader funnels through (crates/craig-search/src/row.rs:180-196,322-335) and knows neither table nor id; every read model carries id; NO site legitimately copies ciphertext between rows/columns (convert_report and SSN promotion re-encrypt plaintext); crypto_key_lineage.envelope_version already exists and is checked BEFORE the KCV at boot (services/craig-cases/src/boot_verify.rs:189-198); the seed identity folds FORMAT_VERSION_V1 (tools/craig-seed/src/seed_marker.rs:111); the seed is DB-less; the migrate gate holds no key; the devstack guard’s VolumeAction::Wipe (set by apply_field_key_staleness, xtask/src/devstack_guard.rs:673-692) runs BEFORE rebuild/up; the keyed harness runs EncryptionMode::Required (services/craig-cases/tests/api/keyed_harness.rs).

Scope

In scope: the StorageContext AAD encoding + format v2 in craig-crypto; the context-threaded craig_search::row walk + the keyed-Required refusal of non-envelope cells; TABLE consts in craig-cases-fields; every craig-cases wrapper / call site / read projection / inbox consumer on the new signatures; the id-minting hoists; boot verify (canary under a fixed context, FORMAT_VERSION); seed / verify-seed / the devstack envelope-format marker class; goldens + proptests + the cell-swap suite; CHANGELOG + the ADR-048 amendment + the doc pages named in MR-1. NO migration; no floor bump.

Out of scope (follow-ups filed at U0): #1759 — the index-only blind-index residual — search hits re-derive the sibling from the decrypted base and drop mismatches (decision 9; counts stay index-only and are documented as such); REVOKE of runtime DML on crypto_key_lineage once #1310 splits the roles (today a compromised app could re-stamp envelope_version); production lineage bootstrap onto pre-existing ciphertext (ADR-048 open question 3) and #1399 rewrite tooling stay post-1.0.

Design

Decisions (recorded in the ADR-048 amendment)

  1. AAD tuple (table, column, row_id); canonical bytes defined ONCE in craig-crypto: ENVELOPE_MAGIC(4) || FORMAT_VERSION(1) || len(table):u8 || table || len(column):u8 || column || row_id(16) || len(sibling):u8 || sibling — the last pair present ONLY for BlindIndex cells (the stored hmac sibling, derived before encryption in the walk, read from hmac_slot_mut at decrypt), so the (base, sibling) pair is authenticated as one cell. Length-prefixed ⇒ injective; identifiers [a-z0-9]{1,255}, sibling ≤ 255 bytes (InvalidStorageContext(&'static str)); the header constants ride in the AAD, so magic + version are authenticated. The encoding is versioned BY the envelope byte (a future layout = v3). Golden vectors pin the exact bytes.

  2. Version byte pub const FORMAT_VERSION: u8 = 2; FORMAT_VERSION_V1 DELETED (one name). v1 is REFUSED at decrypt (UnsupportedVersion(1), remedy names the reseed) — fail-open dual-read stays rejected (ADR-048 "Mega-MR / mode-flag dual-read"; ADR-020 #906: reseed, no backfill). A keyed DB holding v1 data refuses boot via the existing scheme check (SchemeMismatch naming cargo xtask dev reseed); the same check is the ROLLBACK boundary (an N−1 binary over a v2 DB refuses before any decrypt).

  3. Keyed Required reads fail closed on ANY non-envelope value in a populated encrypted cell: decrypt_text’s `(Some(), false, Required) arm and decrypt_jsonb_envelope’s `(Some(), None, Required) arm become SearchError::PlaintextInEncryptedCell { column } (→ ApiError 500 through the exhaustive impl From<craig_search::SearchError> for ApiError, crates/craig-common/src/error.rs); the JSONB envelope reader accepts ONLY the exact single-key {"v": <str>} object. Optional mode keeps the passthrough (keyless devstacks / the pre-key posture) and says so in its doc. Consequence: every test fixture that plants plaintext in an encrypted column under a keyed Required harness must encrypt through the walk — candidates under services/craig-cases/src/ (the battery decides; a keyless / Optional scratch fixture keeps the passthrough): inbox/report_converted.rs:300/417/512, ssn_promotion.rs:362/451, matching/mod.rs:1230, store/{report_attachments.rs:98, report_persons.rs:157,screening_decisions.rs:321}, api/case_screening_tests.rs:82; and keyed_decrypt_of_legacy_plaintext_passes_through (crates/craig-search/tests/row.rs:341) splits into Optional-passes / Required-refuses.

  4. Row identity known before every encryption: reports create mints new_id() in the handler and the store INSERT binds id; referral-from-report mints in conversion.rs and passes it to the store; persons create hoists proposed_id above encrypt_person_pii (already outside the #1363 retry closure). Update / SSN promotion / every read site already hold the id. ADR-062 untouched (the reports LIFETIME claim is received_request_id + digest; the handler id is not in the intent projection).

  5. Table token single-sourced: pub const TABLE per craig-cases-fields module (persons / referrals / reports / cases / investigations — none exists today) feeding DEFAULT_REGISTRY, EffectiveRegistries, verify-seed’s covered set and the seed; unit pins assert key == TABLE for every entity with an encrypted field.

  6. Canary exercises AAD: pub const CANARY_CONTEXT = StorageContext::new("crypto_key_lineage", "canary", Uuid::nil()) (no sibling); the seeder encrypts under it, boot decrypts under it; any other context ⇒ CanaryUndecryptable. KCV_SCHEME_V1 unchanged (KCV derivation + canary plaintext only).

  7. Lineage interplay: the format version stays a DATA fact in crypto_key_lineage.envelope_version (written by the ciphertext writer = the seeder, verified at boot; verify-seed becomes a third reader); crypto_field_lineage / canonical_spec v1 (gate-written per-field scheme truth, ADR-049 #1025) UNCHANGED — the AAD is not a per-field scheme and the ADR-063 gate holds no key. NO migration; no floor bump.

  8. Devstack — the wipe-before-start marker class (the .devstack/field-key.kcv precedent, #1653 class): a new marker .devstack/envelope-format holds the FORMAT_VERSION the volumes were seeded under; apply_envelope_format_staleness (beside apply_field_key_staleness) sets VolumeAction::Wipe when the marker is absent (marker dir present — the same arm shape as apply_field_key_staleness’s `(Some(), None)) or ≠ the linked craig_crypto format constant (xtask already links craig-crypto; MR-0 binds FORMAT_VERSION_V1, MR-1 renames it), so dev start / dev refresh / dev reseed wipe volumes BEFORE the rebuilt image starts; the marker is blessed with the others after a verified bring-up. The whole-.devstack/-absent cold start is unchanged (no apply*_staleness arm runs; the v2 binary refuses with SchemeMismatch naming dev reseed). SEED_INPUT_DIRS unchanged (the marker, not a source hash, is the durable signal). Seed identity flips through FORMAT_VERSION; MARKER_PROTOCOL_VERSION stays 3 (its doc reserves bumps for recipe/DDL-shape changes) — only GOLDEN_IDENTITY and the CASES / VARIANTS_CASES byte pins re-bless.

  9. Residual, stated precisely (ADR text + follow-up issue): a substituted _hmac sibling can still make an EQUALITY SEARCH match a row whose plaintext differs; every read that DECRYPTS that row’s base now fails closed (the sibling is in the base’s AAD), so the residual is confined to index-only operations (a hit whose base is never decrypted, a count). Follow-up: search hits re-derive the sibling from the decrypted base and drop mismatches; the other out-of-scope items are listed under Scope.

A. crates/craig-crypto/src/lib.rs

  • pub struct StorageContext<'a> { table: &'a str, column: &'a str, row_id: Uuid, sibling: Option<&'a str> } (Copy; every encrypt* / decrypt* takes it BY VALUE)
    const fn new(table, column, row_id) + const fn with_sibling(self, &'a str)
    fn aad(&self) → Result<Vec<u8>>; pub const CANARY_CONTEXT; pub const FORMAT_VERSION: u8 = 2; pub fn envelope_version_of(&str) → Option<u8> (diagnostic; is_encrypted stays magic-only — the reader’s refusal in decision 3 is what closes the header bypass). uuid = { workspace = true } (lib target uses it).

  • encrypt(&self, plaintext, ctx), encrypt_str, decrypt(&self, blob, ctx), decrypt_str — no context-free variants survive. Fault check first, then ctx.aad()?, then Payload { msg, aad } (aead 0.5 Payload). Parse order unchanged: base64 → MissingMagic → Truncated → version != FORMAT_VERSION ⇒ UnsupportedVersion → BlobTooShort → nonce → AEAD (Decrypt; text gains "or foreign storage context"). Rewrite the "header not bound" paragraph. CryptoError gains only InvalidStorageContext.

B. crates/craig-search + crates/craig-cases-fields

  • row.rs: pub struct RowContext { table: &'static str, row_id: Uuid } (const fn new, fn cell(column, sibling: Option<&str>) → StorageContext<'_>); encrypt_row(row, ctx, fields, enc, mode) / decrypt_row(..); for a BlindIndex spec the walk reads the sibling slot and passes it into the cell context on both sides; the slot / text / jsonb helpers take the per-cell context; decision-3 refusals; jsonb_envelope_ciphertext exact-shape. EncryptableRow, impl_encryptable_row!, take_encrypted_fields: unchanged. SearchError gains PlaintextInEncryptedCell { column } (+ the ApiError arm).

  • plan.rs: EffectiveRegistry::row(&self, id) → RowContext; re-export RowContext + StorageContext.

  • fields crate: the TABLE consts (decision 5) + the registry pin test.

C. craig-cases

  • Wrappers api/encryption/report.rs, referral.rs, person.rs take the registry (or RowContext for the narrowed person slices) and the id; call sites (from the research map, under services/craig-cases/src/): api/reports/crud.rs:120 (+ mint, persist_or_replay(id, ..), store/reports.rs INSERT binds $1 = id), api/reports/conversion.rs:160-168 (+ mint; store/referrals.rs drops its internal new_id(); two test fixtures pass ids), api/persons.rs:216/389 (hoist), ssn_promotion.rs (takes the registry), and the ~20 decrypt sites incl. the summary Projection (ReportSummaryRow.id; decrypts narrative only — api/reports/summary.rs module doc), the inbox consumer (Deps.registries + report.id), NCANDS / federal export / IV-E / screening evidence / SSN release.

  • boot_verify.rs: bind FORMAT_VERSION; canary via CANARY_CONTEXT; SchemeMismatch text names v2/#1007 and the reseed; CanaryUndecryptable doc mentions a foreign context. Order sentinel → scheme → KCV → canary unchanged.

D. Seed / verify-seed / devstack

  • tools/craig-seed/src/encrypt.rs: walk under RowContext::new(<module>::TABLE, model.id) ×3; canary under CANARY_CONTEXT; CryptoLineage binds FORMAT_VERSION. seed_marker.rs:111 binds FORMAT_VERSION; golden re-pinned. sql_byte_identity.rs: CASES + VARIANTS_CASES re-bless (sentinel row renders 2); other families asserted unchanged; a test pins <model as SqlRow>::TABLE == fields::<module>::TABLE ×3.

  • xtask/src/cmd/verify_seed.rs: fetch_seed_rows selects id (+ the _hmac siblings it already covers); the lineage query reads envelope_version and --expect keyed requires FORMAT_VERSION; per cell envelope_version_of reports a v1 blob as "format stale — reseed" before decrypting under (entity.table, spec.column, id[, sibling]); a populated non-envelope cell under --expect keyed fails.

  • xtask/src/devstack_guard.rs: the envelope-format marker + apply_envelope_format_staleness (decision 8), its bless in the success arm, dev status line, unit tests (absent ⇒ Wipe; equal ⇒ none; stale ⇒ Wipe); Local Development marker table row; the Known Issues & Lessons Learned keyed-devstack cold-start note.

E. Tests (J1 by risk)

  • craig-crypto: golden vectors (cell, blind-index cell with sibling, canary — pinned AAD bytes per context plus one pinned blob under a pinned test key that must decrypt to a pinned plaintext under exactly that context; nonces are random, so the blob is pinned, never regenerated); identifier/sibling refusals; decrypt_refuses_v1_envelope_by_version_byte (byte 4 := 1 ⇒ UnsupportedVersion(1), never Decrypt); proptests P1 round-trip ∀ ctx; P2 contexts differing in exactly one component (table / column / row_id / sibling) never decrypt; P3 independent Aes256GcmSiv reference with the AAD bytes recovers, and with the AAD version byte flipped fails (header binding at the primitive); P4 aad() injective over valid tuples.

  • craig-search (the READER proofs the rev-1 review asked for): under keyed Required — altered magic ⇒ PlaintextInEncryptedCell, replaced-by-plaintext ⇒ same, altered version byte ⇒ Crypto(UnsupportedVersion), JSONB envelope with an extra key ⇒ PlaintextInEncryptedCell, JSONB plaintext object ⇒ same; under Optional the plaintext passthrough is pinned as deliberate; cell_copied_between_rows|columns|tables_fails_closed; blind_index_sibling_substitution_fails_the_base_decrypt (rewrite ssn_hmac ⇒ decrypt of ssn_last_four fails) + proptest P5 over ids; both cipher_fault.rs suites (crypto + search) gain a fixture context.

  • craig-cases (keyed harness, devstack-gated): NEW tests/api/cell_swap_encryption.rs — raw-SQL swaps: narrative between two reports ⇒ report detail 500 AND the summary list 500 (it decrypts narrative), no plaintext in either body; reporter_first_name := reporter_last_name ⇒ report detail 500 while the summary list stays 200 (it never reads reporter names); referrals reporter_first_name := reports.reporter_first_name for a converted pair ⇒ referral detail + referral list 500, report detail and summary list 200; magic-altered narrative ⇒ 500 (never the raw cell); persons ssn_hmac substituted from another row ⇒ the equality search may match but the person detail 500s (the recorded residual, pinned as such); boot_verify.rs gains canary_under_foreign_context_refuses_boot
    v1_lineage_row_refuses_as_scheme_mismatch; existing encryption suites gain ids/contexts (report_encryption.rs helpers, report_decisions_screening.rs envelope overwrite, api/encryption/mod.rs, summary.rs, ssn_promotion.rs, report_persons_tests.rs); the decision-3 fixture conversions.

  • seed / xtask: decrypted_envelopes rebuilt as a per-row decrypt; verify-seed tests for a swapped cell, a v1 blob, a plaintext cell under keyed, a lineage envelope_version mismatch; the registry-token pins; the guard marker tests.

Steps

Each MR is independently green, closes its child issue and Relates to #1007; MR-2 also Closes #1007. MR-1 cannot split further without a retained v1 API — one compile graph crypto → search → cases/seed/xtask, and pre-1.0 forbids the scaffold. Process per MR: branch, contextless J1–J8 lens, reseed + battery, MR with the J-record note, merge on green (no tier-1 content — self-merge under the standing authorization).

Unit Delivers Weight Issue link

U0

this page, epic + child issues, follow-up issues, the ADR-048 status pointer

1

Relates to #1007

MR-0

behaviour-neutral prerequisites, green on v1

3

Closes #1756 · Relates to #1007

MR-1

format v2 — §A–§E, fixture conversions, goldens / re-bless, CHANGELOG, the ADR-048 amendment, docs

6

Closes #1757 · Relates to #1007

MR-2

close-out

1

Closes #1758 · Closes #1007

U0 — plan page, epic, issues (weight 1)

This page (Active nav), the epic + child issues, the follow-up issues (index-only sibling substitution; REVOKE on #1310), the ADR-048 status pointer.

MR-0 — behaviour-neutral prerequisites, green on v1 (weight 3; Closes #1756)

TABLE consts + registry / effective / verify-seed / seed pins; the three id-minting hoists + the two store signatures (create_report(id, ..), create_referral_from_report(id, ..)); the devstack envelope-format marker + guard class (binds FORMAT_VERSION_V1 = 1 today, so the MR-1 bump is a clean wipe on every existing stack). Merging the absent arm itself costs one wipe + reseed per existing stack (the #1398 precedent) before MR-1’s second one.

MR-1 — format v2 (weight 6; Closes #1757)

§A + §B (incl. decision 3) + §C + §D + §E, fixture conversions, goldens / re-bless, CHANGELOG Changed (format break, v1 refused, keyed-Required refusal of non-envelope cells, reseed, FieldEncryptor signatures) + Added, ADR-048 == Amendment — #1007 (retire the "Threat model" no-AAD paragraph and the Consequences follow-up bullet; tuple / encoding / version rule incl. the sibling binding; canary context; lineage interplay incl. a one-line ADR-049 note — a BlindIndex base now binds its sibling into the AAD while the Opaque override does not, so "at-rest bytes identical" no longer holds for the #1025 flip; reader refusal; rollback boundary; the index-only residue), ADR-020 status note, Configuration Reference (the CRAIG_FIELD_ENCRYPTION_KEY row), Known Issues & Lessons Learned (the keyed-devstack entry), Data Model: Case Management (the crypto_key_lineage row), Shared Crates — Public API Surface crypto / search entries, Local Development.

MR-2 — close-out (weight 1; Closes #1758, Closes #1007)

Status Done, nav → Archive + archive.adoc row, .claude/CLAUDE.md, plan-lint --done.

Rollout / rollback

Pre-1.0: no production data. Devstack / CI: the first dev start / dev refresh after merge wipes and reseeds through the marker class (keyed reseed, markers blessed incl. envelope-format = 2); raw-compose CI seeds fresh with verify-seed --expect keyed. The whole-.devstack/-absent cold start over a persisted v1 volume (the known-issues entry) is unchanged: the v2 binary refuses with SchemeMismatch naming dev reseed (rehearsal 2); the entry stays.

Rollback boundary (decision 2): an N−1 cases binary over a v2 database refuses at the scheme check (SchemeMismatch) before any decrypt; on the devstack the guard’s ≠ is symmetric, so a tree whose linked craig_crypto format constant differs from the blessed marker wipes + reseeds the same way.

Verification

  • Per MR: fmt, clippy -D warnings --locked, budgets, the 22 lints, axis-coverage, api-docs --check (no API change expected), coverage-matrix-mapping, check-docs, validate-migration-constraints (no migration), plan-lint.

  • Devstack: after MR-1, dev start AND dev refresh on a stack still holding v1 volumes must both wipe-then-reseed (the marker class) and come up green with verify-seed --expect keyed; full craig-cases battery --run-ignored all (boot_verify legs, the encryption suites, the new cell-swap suite); craig-crypto / craig-search / craig-seed / xtask unit + proptests; the pre-push battery; cargo xtask mutants --smoke --package craig-crypto in a quiet worktree (MISSED list reported on the MR).

  • Rehearsal: (1) a keyed devstack seeded on the pre-MR-1 images + a dev refresh on the MR-1 tree ⇒ the guard reports the format marker stale, wipes, reseeds, green (never a SchemeMismatch boot loop); (2) the v2 cases image started by hand against a v1 volume refuses with SchemeMismatch naming the reseed (the boot test pins it); (3) on the reseeded devstack DB: swap two reports' narrative cells by raw SQL ⇒ both report details and the summary list 500 without leaking either plaintext; overwrite a narrative cell’s magic ⇒ 500, never the raw bytes; substitute one person’s ssn_hmac ⇒ the person detail 500s.

Review log

Round Vendor Resolved model Verdict

1

Anthropic — one fresh contextless subagent, the four plan-lifecycle questions, over this page

Claude Fable 5.1

no-ship → 2 blockers folded (the marker’s absent arm has no volume probe and a missing .devstack/ runs no staleness arm — reworded to the apply_field_key_staleness shape with the cold start unchanged; each MR closes its child issue) + the advisories taken (no TABLE const exists today; ADR-049 note; fixture list as candidates; conversion.rs cite; MR-0 binds FORMAT_VERSION_V1; golden = pinned blob + AAD bytes; cipher_fault suites; StorageContext by value)

2

the maintainer (human) — plan-mode gate review of the pre-page draft (4 findings folded into rev 2): keyed-Required readers must refuse non-envelope cells; the wipe-before-start marker class; the blind-index residual is sibling substitution; the summary list decrypts only narrative

—

no-ship → folded; approved 2026-09-09 in plan mode

Errata

  • Erratum (2026-09-09): decision 4 names three write paths; main still carries a fourth — the direct POST /v1/cases/referrals create (api/referrals.rs, retired by #1746 / #895 MR-D) — and MR-0 hoists its id the same way, so every encrypted write path on main knows its row id before the walk.

  • Erratum (2026-09-09): two as-built variances the MR notes recorded — §C’s person READ wrappers take the table token (decrypt_person(s)_pii(fields, table, ..), the id from the model) while the write wrapper takes a RowContext (uniformity is cosmetic); and decision 5’s investigations::TABLE is "investigations", the registry key on main — when #895 MR-E’s v_investigations read view lands, the view wins the read identity (the registry pin covers only encrypted entities, so it stays green either way).

Edit this page · latest