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)
-
AAD tuple
(table, column, row_id); canonical bytes defined ONCE incraig-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 forBlindIndexcells (the storedhmacsibling, derived before encryption in the walk, read fromhmac_slot_mutat 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. -
Version byte
pub const FORMAT_VERSION: u8 = 2;FORMAT_VERSION_V1DELETED (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 (SchemeMismatchnamingcargo xtask dev reseed); the same check is the ROLLBACK boundary (an N−1 binary over a v2 DB refuses before any decrypt). -
Keyed
Requiredreads fail closed on ANY non-envelope value in a populated encrypted cell:decrypt_text’s `(Some(), false, Required)arm anddecrypt_jsonb_envelope’s `(Some(), None, Required)arm becomeSearchError::PlaintextInEncryptedCell { column }(→ApiError500 through the exhaustiveimpl 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.Optionalmode 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 keyedRequiredharness must encrypt through the walk — candidates underservices/craig-cases/src/(the battery decides; a keyless /Optionalscratch 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; andkeyed_decrypt_of_legacy_plaintext_passes_through(crates/craig-search/tests/row.rs:341) splits into Optional-passes / Required-refuses. -
Row identity known before every encryption: reports create mints
new_id()in the handler and the store INSERT bindsid; referral-from-report mints inconversion.rsand passes it to the store; persons create hoistsproposed_idaboveencrypt_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 isreceived_request_id+ digest; the handler id is not in the intent projection). -
Table token single-sourced:
pub const TABLEpercraig-cases-fieldsmodule (persons / referrals / reports / cases / investigations — none exists today) feedingDEFAULT_REGISTRY,EffectiveRegistries, verify-seed’s covered set and the seed; unit pins assert key == TABLE for every entity with an encrypted field. -
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_V1unchanged (KCV derivation + canary plaintext only). -
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_specv1 (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. -
Devstack — the wipe-before-start marker class (the
.devstack/field-key.kcvprecedent, #1653 class): a new marker.devstack/envelope-formatholds the FORMAT_VERSION the volumes were seeded under;apply_envelope_format_staleness(besideapply_field_key_staleness) setsVolumeAction::Wipewhen the marker is absent (marker dir present — the same arm shape asapply_field_key_staleness’s `(Some(), None)) or ≠ the linkedcraig_cryptoformat constant (xtask already links craig-crypto; MR-0 bindsFORMAT_VERSION_V1, MR-1 renames it), sodev start/dev refresh/dev reseedwipe 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 (noapply*_stalenessarm runs; the v2 binary refuses withSchemeMismatchnamingdev reseed).SEED_INPUT_DIRSunchanged (the marker, not a source hash, is the durable signal). Seed identity flips throughFORMAT_VERSION;MARKER_PROTOCOL_VERSIONstays 3 (its doc reserves bumps for recipe/DDL-shape changes) — onlyGOLDEN_IDENTITYand the CASES / VARIANTS_CASES byte pins re-bless. -
Residual, stated precisely (ADR text + follow-up issue): a substituted
_hmacsibling 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; everyencrypt*/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_encryptedstays 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, thenctx.aad()?, thenPayload { msg, aad }(aead 0.5Payload). 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.CryptoErrorgains onlyInvalidStorageContext.
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 aBlindIndexspec 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_ciphertextexact-shape.EncryptableRow,impl_encryptable_row!,take_encrypted_fields: unchanged.SearchErrorgainsPlaintextInEncryptedCell { column }(+ theApiErrorarm). -
plan.rs:EffectiveRegistry::row(&self, id) → RowContext; re-exportRowContext+StorageContext. -
fields crate: the
TABLEconsts (decision 5) + the registry pin test.
C. craig-cases
-
Wrappers
api/encryption/report.rs,referral.rs,person.rstake the registry (orRowContextfor the narrowed person slices) and the id; call sites (from the research map, underservices/craig-cases/src/):api/reports/crud.rs:120(+ mint,persist_or_replay(id, ..),store/reports.rsINSERT binds$1 = id),api/reports/conversion.rs:160-168(+ mint;store/referrals.rsdrops its internalnew_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 summaryProjection(ReportSummaryRow.id; decryptsnarrativeonly —api/reports/summary.rsmodule doc), the inbox consumer (Deps.registries+report.id), NCANDS / federal export / IV-E / screening evidence / SSN release. -
boot_verify.rs: bindFORMAT_VERSION; canary viaCANARY_CONTEXT;SchemeMismatchtext names v2/#1007 and the reseed;CanaryUndecryptabledoc mentions a foreign context. Order sentinel → scheme → KCV → canary unchanged.
D. Seed / verify-seed / devstack
-
tools/craig-seed/src/encrypt.rs: walk underRowContext::new(<module>::TABLE, model.id)×3; canary underCANARY_CONTEXT;CryptoLineagebindsFORMAT_VERSION.seed_marker.rs:111bindsFORMAT_VERSION; golden re-pinned.sql_byte_identity.rs: CASES + VARIANTS_CASES re-bless (sentinel row renders2); other families asserted unchanged; a test pins<model as SqlRow>::TABLE == fields::<module>::TABLE×3. -
xtask/src/cmd/verify_seed.rs:fetch_seed_rowsselectsid(+ the_hmacsiblings it already covers); the lineage query readsenvelope_versionand--expect keyedrequiresFORMAT_VERSION; per cellenvelope_version_ofreports a v1 blob as "format stale — reseed" before decrypting under(entity.table, spec.column, id[, sibling]); a populated non-envelope cell under--expect keyedfails. -
xtask/src/devstack_guard.rs: theenvelope-formatmarker +apply_envelope_format_staleness(decision 8), its bless in the success arm,dev statusline, 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), neverDecrypt); proptests P1 round-trip ∀ ctx; P2 contexts differing in exactly one component (table / column / row_id / sibling) never decrypt; P3 independentAes256GcmSivreference with the AAD bytes recovers, and with the AAD version byte flipped fails (header binding at the primitive); P4aad()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; underOptionalthe plaintext passthrough is pinned as deliberate;cell_copied_between_rows|columns|tables_fails_closed;blind_index_sibling_substitution_fails_the_base_decrypt(rewritessn_hmac⇒ decrypt ofssn_last_fourfails) + proptest P5 over ids; bothcipher_fault.rssuites (crypto + search) gain a fixture context. -
craig-cases (keyed harness, devstack-gated): NEW
tests/api/cell_swap_encryption.rs— raw-SQL swaps:narrativebetween two reports ⇒ report detail 500 AND the summary list 500 (it decryptsnarrative), 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); referralsreporter_first_name := reports.reporter_first_namefor a converted pair ⇒ referral detail + referral list 500, report detail and summary list 200; magic-alterednarrative⇒ 500 (never the raw cell); personsssn_hmacsubstituted from another row ⇒ the equality search may match but the person detail 500s (the recorded residual, pinned as such);boot_verify.rsgainscanary_under_foreign_context_refuses_boot
v1_lineage_row_refuses_as_scheme_mismatch; existing encryption suites gain ids/contexts (report_encryption.rshelpers,report_decisions_screening.rsenvelope overwrite,api/encryption/mod.rs,summary.rs,ssn_promotion.rs,report_persons_tests.rs); the decision-3 fixture conversions. -
seed / xtask:
decrypted_envelopesrebuilt as a per-row decrypt; verify-seed tests for a swapped cell, a v1 blob, a plaintext cell under keyed, a lineageenvelope_versionmismatch; 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.
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 startANDdev refreshon a stack still holding v1 volumes must both wipe-then-reseed (the marker class) and come up green withverify-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-cryptoin a quiet worktree (MISSED list reported on the MR). -
Rehearsal: (1) a keyed devstack seeded on the pre-MR-1 images + a
dev refreshon the MR-1 tree ⇒ the guard reports the format marker stale, wipes, reseeds, green (never aSchemeMismatchboot loop); (2) the v2 cases image started by hand against a v1 volume refuses withSchemeMismatchnaming the reseed (the boot test pins it); (3) on the reseeded devstack DB: swap two reports'narrativecells by raw SQL ⇒ both report details and the summary list 500 without leaking either plaintext; overwrite anarrativecell’s magic ⇒ 500, never the raw bytes; substitute one person’sssn_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 |
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;
mainstill carries a fourth — the directPOST /v1/cases/referralscreate (api/referrals.rs, retired by #1746 / #895 MR-D) — and MR-0 hoists its id the same way, so every encrypted write path onmainknows 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 aRowContext(uniformity is cosmetic); and decision 5’sinvestigations::TABLEis"investigations", the registry key onmain— when #895 MR-E’sv_investigationsread view lands, the view wins the read identity (the registry pin covers only encrypted entities, so it stays green either way).