Skip to main content

vta_keyspaces/
lib.rs

1//! Central registry of the VTA's keyspace names.
2//!
3//! Every `store.keyspace(..)` call in the VTA (`vta-service` server, offline
4//! CLIs, backup, tests) names its keyspace through a `const` here rather than a
5//! bare string literal. This is the single source of truth that killed the
6//! `"imported"` / `"imported_secrets"` test-vs-production divergence (a test
7//! opened a *different*, empty keyspace than the one production writes). The
8//! `no_bare_keyspace_literals` guard in `vta-service` keeps it that way by
9//! scanning that crate's source for bare `.keyspace("…")` literals.
10//!
11//! Keyspace *names* live here; per-keyspace *key formats* (the `key:`, `seed:`,
12//! `path_counter:` … record families inside a keyspace) are a separate concern
13//! and are not yet centralised.
14//!
15//! A near-leaf crate: it holds the shared keyspace vocabulary (the name
16//! constants) plus the [`Keyspaces`] handle bundle, so that every VTA subsystem
17//! crate can name and pass keyspaces without depending on `vta-service`. Its
18//! only dependency is `vti-common` (for `KeyspaceHandle`).
19
20use vti_common::store::KeyspaceHandle;
21
22/// Shared bundle of borrowed keyspace handles passed to operations that need
23/// several keyspaces at once.
24///
25/// The struct is a pure field bundle — the constructors that borrow it from a
26/// concrete `AppState` / `VtaState` live in `vta-service` (they know those
27/// types), so this stays free of any `vta-service` dependency.
28pub struct Keyspaces<'a> {
29    pub keys: &'a KeyspaceHandle,
30    pub acl: &'a KeyspaceHandle,
31    pub contexts: &'a KeyspaceHandle,
32    pub did_templates: &'a KeyspaceHandle,
33    pub audit: &'a KeyspaceHandle,
34    pub imported: &'a KeyspaceHandle,
35    /// Per-context agent memory ([`MEMORY`]). Here so a context deletion can
36    /// take the context's entries with it.
37    pub memory: &'a KeyspaceHandle,
38    /// Per-context application state ([`APP_STATE`]). Here so a context
39    /// deletion can take the context's records with it — left behind, they
40    /// reappear in any new context created under the same id.
41    pub app_state: &'a KeyspaceHandle,
42    /// Non-extractable internal key material ([`INTERNAL_KEYS`]), so a context
43    /// deletion takes the material of the context's internal keys with their
44    /// records.
45    pub internal: &'a KeyspaceHandle,
46    /// The holder's credential vault ([`VAULT`]): credentials and vault entries
47    /// in a context's custody go with the context.
48    pub vault: &'a KeyspaceHandle,
49    /// Inbound-messaging consent ([`CONSENT`]): grants and pending requests
50    /// decided in a context go with it.
51    pub consent: &'a KeyspaceHandle,
52    /// Per-(platform, context) approver bindings ([`CONSENT_APPROVERS`]).
53    pub consent_approvers: &'a KeyspaceHandle,
54    /// The persona store ([`PERSONA`]): its context-scoped half goes with the
55    /// context.
56    pub persona: &'a KeyspaceHandle,
57    /// Hidden-vetting and voting engine state ([`PCS_ENGINE`]), each record
58    /// naming the context its key is derived under.
59    pub pcs_engine: &'a KeyspaceHandle,
60    /// Notifications held for the principal ([`NOTIFICATIONS`]), per context.
61    pub notifications: &'a KeyspaceHandle,
62    /// External accounts ([`EXTERNAL_ACCOUNTS`]), keyed by context.
63    pub external_accounts: &'a KeyspaceHandle,
64    /// The wrapped secrets of external accounts ([`EXTERNAL_SECRETS`]).
65    pub external_secrets: &'a KeyspaceHandle,
66    /// Collection claims, conflicts and settings ([`COLLECTION`]). Here so a
67    /// context deletion ends every claim for its identifiers (VTI-NTF-090) and
68    /// drops its setting, so a context created again under the id starts
69    /// enabled (VTI-NTF-094).
70    pub collection: &'a KeyspaceHandle,
71    #[cfg(feature = "webvh")]
72    pub webvh: &'a KeyspaceHandle,
73}
74
75/// Master seed + key records (`key:`, `seed:`, `path_counter:`,
76/// `active_seed_id`, `imported_kek_salt`, …) and the backup import sentinel.
77pub const KEYS: &str = "keys";
78/// Auth sessions + challenges.
79pub const SESSIONS: &str = "sessions";
80/// ACL entries + the seal record + the integrity-anchor root.
81pub const ACL: &str = "acl";
82/// Trust contexts (the BIP-32 key hierarchy roots).
83pub const CONTEXTS: &str = "contexts";
84/// Stored DID templates (global + context-scoped).
85pub const DID_TEMPLATES: &str = "did_templates";
86/// Audit log.
87pub const AUDIT: &str = "audit";
88/// The keyed-hash keys the audit log commits actor and target identifiers
89/// under, and their history.
90///
91/// Separate from [`AUDIT`] because the two have opposite lifetimes: entries
92/// are erased when their retention expires, and a key must outlive every entry
93/// that references it or those entries stop being checkable against a
94/// candidate identifier.
95pub const AUDIT_KEY: &str = "audit_key";
96/// Imported secret material (KEK-wrapped). Named `imported_secrets`, **not**
97/// `imported` — the latter was a long-standing test-only typo that operated on
98/// an empty keyspace disjoint from production. Always reference this const.
99pub const IMPORTED_SECRETS: &str = "imported_secrets";
100/// Non-extractable internal signing keys.
101///
102/// Deliberately **not** [`IMPORTED_SECRETS`]: that keyspace wraps its contents
103/// under a KEK derived from the BIP-39 master seed, so anything stored there is
104/// reconstructible by whoever holds the mnemonic. Internal keys exist precisely
105/// to have no such path — their material is generated from the system CSPRNG,
106/// never derived, and lives here instead.
107///
108/// In [`EXCLUDED_FROM_BACKUP`] by design, not by omission. A backup containing
109/// this keyspace would be an export of keys the VTA promises never to export.
110pub const INTERNAL_KEYS: &str = "internal_keys";
111/// Holder credential vault (third-party secrets stored on this VTA).
112pub const VAULT: &str = "vault";
113/// Persistent runtime service-enable state (`operations::protocol::runtime_state`).
114pub const SERVICE_STATE: &str = "service_state";
115/// Sealed-bootstrap anti-replay nonce log.
116pub const SEALED_NONCES: &str = "sealed_nonces";
117/// In-flight backup-bundle control-plane records.
118pub const BACKUP_BUNDLES: &str = "backup_bundles";
119/// WebVH DID records + `did.jsonl` state.
120pub const WEBVH: &str = "webvh";
121/// In-flight passkey-as-verificationMethod enrolment state.
122pub const PASSKEY_VMS: &str = "passkey_vms";
123/// Persisted protocol-management drain set.
124pub const DRAINS: &str = "drains";
125/// Per-kind previous-config snapshots for fail-forward rollback.
126/// (Historically `operations::protocol::snapshot::KEYSPACE_NAME`.)
127pub const SNAPSHOT: &str = "service_prev_config";
128/// KMS-protected, unencrypted boot keyspace (TEE integrity manifest, etc.).
129pub const BOOTSTRAP: &str = "bootstrap";
130/// Inbound-messaging consent: durable grants + TTL'd pending requests
131/// (`vti_common::consent`). The VTA is the first gate for bridged conversations.
132pub const CONSENT: &str = "consent";
133/// Per-(platform, context) approver bindings — who decides consent and how the
134/// prompt routes (`vti_common::consent::ApproverBinding`).
135pub const CONSENT_APPROVERS: &str = "consent_approvers";
136/// VTA-issued credentials (minted by `vta/credentials/issue/0.1`, revoked by
137/// `vta/credentials/revoke/0.1`). One record per credential keyed `cred:<id>`;
138/// revocation is a tombstone (`revokedAt` set in place), not a delete. Distinct
139/// from [`VAULT`] (which stores credentials the holder *holds*).
140pub const ISSUED_CREDENTIALS: &str = "issued_credentials";
141
142/// Per-context key/value store for AI-agent memory (`vta/memory/{put,list,
143/// delete}/0.1`). One record per `(contextId, key)` pair, keyed
144/// `mem:<contextId>:<key>`; `list` is a `mem:<contextId>:` prefix scan. Durable
145/// user data → in [`BACKED_UP`].
146pub const MEMORY: &str = "memory";
147
148/// A member's MLS group state for each data room they belong to
149/// (`rooms/keys/{welcome,commit,open}`), keyed **per member**:
150/// `room-group/<roomId>/<persona>`, beside the member's pending KeyPackage
151/// (`room-kp/…`), pending epoch advance (`room-advance/…`), root memory
152/// (`room-roots/…`), the epoch a commit removed the member at
153/// (`room-removed/…`) and an owner's last applied admission, Welcome included, kept
154/// for at most 24 hours so a repeated request can be answered
155/// (`room-admitted/…`, `rooms/owner/group/add/0.3` item 8) under the same
156/// `<roomId>/<persona>`. One VTA may hold several
157/// members of one room — several principals, or several personas of one — and
158/// each is a different leaf with different secrets. Rows a per-room build wrote
159/// (`room-group:<roomId>`, …) are moved under their member on first touch.
160///
161/// **This holds group secrets.** Whoever reads a row can decrypt every record
162/// the group could, up to its epoch — the same class of material as [`KEYS`],
163/// and it inherits the same protection: the KMS storage key in a TEE
164/// deployment, and a trusted data directory outside one.
165///
166/// In [`BACKED_UP`], and that is a decision rather than a default. A member who
167/// restores a VTA without their room groups has lost the ability to read every
168/// sealed room they belong to, with no way to recover it — the group cannot be
169/// re-derived, and rejoining means a fresh invitation from every owner. The
170/// backup already carries the credential vault and the master seed; group state
171/// belongs with them.
172pub const ROOM_GROUPS: &str = "room_groups";
173
174/// Invitation credentials this VTA has consumed by joining a room
175/// (`rooms/keys/welcome`), keyed `room-vic:<credentialId>`.
176///
177/// Separate from [`ROOM_GROUPS`] because it outlives them: a member who leaves a
178/// room discards the group, and the consumed-invitation record must survive that
179/// or the same invitation would let them be re-added without a fresh one. Single
180/// use means single use.
181pub const ROOM_INVITATIONS: &str = "room_invitations";
182
183/// The holder's identity attributes, profiles, bindings and contacts
184/// (`persona/*`) — the fourth store, beside [`VAULT`] (secrets and
185/// credentials), [`MEMORY`] (agent memory) and [`APP_STATE`] (uninterpreted
186/// application JSON).
187///
188/// It is a distinct store because disclosure control is its point, and a
189/// maintainer that cannot read a record cannot decide which of its members may
190/// leave, cannot audit which ones did, and cannot answer "what have I shared
191/// with whom". [`APP_STATE`] promises never to interpret its records, so it
192/// cannot host this; and a namespace there is collision avoidance rather than a
193/// trust boundary, so a compromised application sharing a context could remove
194/// the holder's identity data.
195///
196/// **Two scopes share the keyspace, and the split is a security control rather
197/// than a filing decision.** The pool and profiles are *agent-scoped* — above
198/// every context — so that the correlation index can see the risk it most needs
199/// to report: the same value presented by two personas in two different
200/// contexts, which a per-context index cannot see by construction. Bindings,
201/// contacts and disclosure records are context-scoped, because a persona lives
202/// in a context and so do its counterparties.
203///
204/// Nothing inside a context may read the agent-scoped prefixes. The holder
205/// pushes a materialised projection down; a context never pulls. That is
206/// enforced at dispatch, not here, but the prefix split is what makes the
207/// enforcement expressible.
208///
209/// Agent-scoped:
210///
211/// - `pa:<attributeId>` — one attribute of the pool.
212/// - `pp:<profileId>` — one profile.
213/// - `pxi:<hmac>` — correlation index, keyed by a keyed hash of the value so
214///   exact-match lookup works with no plaintext index over personal data.
215/// - `pxr:<attributeId>:<profileId>` — attribute → profile reverse index, so a
216///   delete can name its referring profiles without scanning every profile.
217///
218/// Context-scoped:
219///
220/// - `pb:<contextId>:<personaDid>` — binding of a profile to a persona DID.
221/// - `pc:<contextId>:<contactId>` — a contact's current revision.
222/// - `pcr:<contextId>:<contactId>:<rev>` — superseded contact revisions,
223///   reference-counted rather than reaped on a flat TTL: a revision behind a
224///   disclosure record is evidence the holder can still be asked to account for.
225/// - `pd:<contextId>:<seq:020>` — append-only disclosure record.
226/// - `plp:<contextId>:<profileId>` — context-local profile (inline entries
227///   only). A *separate prefix*, not a flag on `pp:`, so a context-scoped list
228///   scans a space that structurally cannot contain a pool profile — a filter
229///   bug there would be the same one-line leak the authorization rule exists to
230///   remove.
231/// - `plb:<contextId>:<personaDid>` — binding of a local profile.
232///
233/// The holder's identity is the account → in [`BACKED_UP`]. A restored agent
234/// that came back without it would be an agent that no longer knows who its
235/// holder is.
236pub const PERSONA: &str = "persona";
237
238/// Versioned, namespaced application state (`vta/app-state/{get,put,list,
239/// delete,get-many,put-many}/1.0`) — the third store, beside [`VAULT`] (secrets
240/// and credentials) and [`MEMORY`] (agent memory), for JSON an application owns
241/// and the VTA does not interpret.
242///
243/// Four record shapes share the keyspace, distinguished by prefix:
244///
245/// - `app:<contextId>:<namespace>:<key>` — the record itself. `list` in
246///   snapshot mode is an `app:<contextId>:<namespace>:` prefix scan.
247/// - `appv:<contextId>:<namespace>:<version:020}>` — version index, mapping a
248///   zero-padded counter value to its record key. Change-feed `list` scans this
249///   so it can return changes in version order and paginate over a stable
250///   storage key; a scan-and-sort over the records could do neither.
251/// - `appc:<contextId>:<namespace>` — the namespace's monotonic write counter.
252/// - `appt:<contextId>:<namespace>` — the oldest version still covered by a
253///   retained tombstone, which is what `sinceVersion` is checked against.
254///
255/// Deliberately **not** [`MEMORY`]: clearing an agent's memory has to stay a
256/// safe thing for a user to ask, which it cannot be if account state lives
257/// there. Durable user data — an account's recoverability depends on it — so it
258/// is in [`BACKED_UP`], and a restore that came back without it would defeat
259/// the point of the feature.
260pub const APP_STATE: &str = "app_state";
261
262/// Rego policy modules for the Policy Decision Point (`policy/{upsert,list,
263/// delete,evaluate}`). One `policy::PolicyModule` per id, keyed `policy:<id>`;
264/// the active set is every enabled row, priority-ordered. Durable operator
265/// security config → in [`BACKED_UP`] (a lost policy set would silently drop
266/// enforcement on restore).
267pub const POLICY: &str = "policy";
268
269/// Task-execution consent for the PDP's `requireConsent` disposition: pending
270/// approvals keyed by payload digest, and granted consents a re-submitted task
271/// consumes. Distinct from [`CONSENT`] (messaging-bridge conversation consent).
272/// One `vti_common::task_consent::PendingTaskConsent` per `pending:<digest>` and
273/// `vti_common::task_consent::TaskConsentGrant` per `grant:<digest>:<requester>`.
274/// Durable operator-facing security state → [`BACKED_UP`].
275pub const TASK_CONSENT: &str = "task_consent";
276
277/// Durable reliable-messaging outbox backing `vti_common::outbox_store::`
278/// `VtiOutboxStore` for the delivery-layer `MessagingService` (D2 P2a
279/// cut-over). Holds `Guaranteed`-delivery outbox entries; dormant in P2a (all
280/// current sends are `BestEffort`) but wired so the drain/confirmation loops
281/// persist across restarts once P2b adds guaranteed VTA pushes. Runtime state,
282/// not backed up.
283pub const OUTBOX: &str = "outbox";
284
285/// Trust Task pushes in flight or recently finished — one record per push,
286/// holding the signed document, the transport plan and the outcome
287/// (`vti_common::trust_task_push`). Encrypted at rest; runtime delivery state
288/// like [`OUTBOX`], not backed up.
289pub const TRUST_TASK_PUSHES: &str = "trust_task_pushes";
290
291/// Idempotency records for keyed Trust Tasks — one row per
292/// `(actor, idempotency-key)`, holding the request digest and, for tasks whose
293/// response may be replayed, the original response. Lets a client's retry of a
294/// lost reply converge on the first execution instead of producing a second
295/// durable effect.
296///
297/// Persistent rather than in-memory (unlike the `(actor, envelope-id)` replay
298/// cache it sits beside) because the window that matters is exactly the one a
299/// restart falls inside: the VTA processed the request, the reply was lost, and
300/// the client is still retrying. Swept on TTL by
301/// `vta_sweepers::idempotency_sweeper`. Runtime state, not backed up.
302pub const IDEMPOTENCY: &str = "idempotency";
303
304/// The record of accepted Trust Task document identifiers (VTI-OPS-025 … 027,
305/// SPEC §7.2 item 11): one row per document `id` accepted for execution,
306/// `accepted:<id>`, holding the digest of the document accepted under it, the
307/// instant the row may be dropped (the end of that document's acceptance
308/// window) and, for a task whose response may be replayed, that response.
309///
310/// Persistent rather than in-memory because the acceptance window outlives a
311/// restart: a document accepted a minute before one is still acceptable after
312/// it, and must still be refused. Shared by every binding (VTI-OPS-027).
313/// Swept on its deadline (`vti_trust_task_server::accepted_store::sweep_expired`).
314/// Runtime state, not backed up.
315pub const ACCEPTED_IDS: &str = "accepted_ids";
316
317/// Durable TSP relationship state, backing the SDK's `RelationshipStore` for the
318/// TSP transport. One record per facet per `(our_vid, their_vid)` pair — the
319/// relationship FSM state, thread digests, reply path and learned capability.
320///
321/// Persistent because Rev 3 §7.2.2 has an endpoint silently drop application
322/// traffic from a VID it holds no relationship with: an in-memory store wiped on
323/// restart makes every established peer's messages vanish until each
324/// re-handshakes. Persisting the state turns a restart transparent (design note
325/// `docs/05-design-notes/tsp-relationship-recovery.md`, D1). Runtime state, not
326/// backed up — a relationship is re-establishable (D2/D3), and like [`SESSIONS`]
327/// it is scoped to this VTA's DIDs, so a restore re-drives it rather than
328/// carrying it.
329pub const RELATIONSHIPS: &str = "relationships";
330
331/// External accounts a VTA holds at clouds and third-party providers
332/// (`external/accounts/*`), keyed `acct:<context>:<accountId>`, plus a
333/// `retired:<context>:<accountId>` tombstone per deleted id so an id is never
334/// reused while a provider-side trust policy may still name it.
335///
336/// Settings, bindings, state and the approvals that changed them — never a
337/// secret or a private key. In [`BACKED_UP`]: a restore that came back without
338/// them would strand every integration bound to an account, while the
339/// provider-side setup they describe still exists.
340pub const EXTERNAL_ACCOUNTS: &str = "external_accounts";
341
342/// The secret halves of external accounts whose model holds one
343/// (`s3-static-presign`, `static-secret`), set by
344/// `external/accounts/secret/set/0.1` and wrapped under the seed-derived KEK the
345/// way imported keys are. Keyed `secret:<context>:<accountId>`.
346///
347/// In [`EXCLUDED_FROM_BACKUP`], and that is the point: a VTA backup is portable
348/// and password-protected, so a super-admin holding a backup and its password
349/// could otherwise take a provider secret away. A restored account reports
350/// `providerSetupRequired` until its secret is set again.
351pub const EXTERNAL_SECRETS: &str = "external_secrets";
352
353/// The VTA's hidden-vetting **PCS engine** state (`vta/pcs/*`): one vetter
354/// engine per (context, community), keyed `vetter:<digest(context, community)>`,
355/// one applicant engine per application, keyed `app:<applicationId>`, and the
356/// voter and trustee engines (`voter:<digest>`, `trustee:<digest>`). The keys
357/// are digests, so finding a context's records means reading each record's
358/// `contextId`; the wrapped state sits beside each under `secret:<key>`.
359///
360/// Never a `usk`: each member key is re-derived from its context's base on
361/// every use (VTI-KEY-030). The rest of an engine — class credentials, unspent
362/// tokens, draws and enrolments in flight, attestations held — is secret, and
363/// is stored wrapped under the seed-derived KEK the way imported keys are.
364///
365/// In [`BACKED_UP`]: an applicant's attestations cannot be replaced without
366/// its vetters sitting again, and the KEK is a function of the seed the
367/// restore brings back.
368pub const PCS_ENGINE: &str = "pcs_engine";
369
370/// The VTA's records of **witnessed sessions** in flight (`vta/witness/*`): one per
371/// session, keyed `session:<sessionId>`, from `vta/witness/open` until the record
372/// expires — minutes, near the witness's own session lifetime — with an accepted
373/// session reduced to its stub (`vta/_shared/0.6/CONVENTIONS.md` §3).
374///
375/// Holds the session document as signed, the relationship and member DIDs, the
376/// credential handles and their digests. Never a presentation or a challenge.
377///
378/// In [`EXCLUDED_FROM_BACKUP`]: transient by construction. A restored record would
379/// name a session the witness has long since expired, and the VWC a completed
380/// session produced is in the credential vault, which is backed up.
381pub const WITNESS_SESSIONS: &str = "witness_sessions";
382
383/// The **notifications** this VTA holds for its principal (`notifications/notify`,
384/// `notifications/relay`, `vta/notifications/*`, VTI-NTF-050): one record per
385/// (originator, `notificationId`) a DID it holds keys of was sent, keyed
386/// `held:<contextId>\0<recordId>` with the dedup index `dedup:<digest of addressee,
387/// originator and notificationId>` beside it. Each record keeps the delivering document exactly
388/// as received, so a client can verify every proof itself.
389///
390/// In [`BACKED_UP`]: a held notification cannot be fetched again — an originator
391/// delivers each revision once, and a relayer re-sends only later revisions — so a
392/// restore without it would lose what the principal was told they may take part
393/// in, a member-party election among it (VTI-NTF-063).
394pub const NOTIFICATIONS: &str = "notifications";
395
396/// **Collection** of the principal's identifiers (`vta/collection/*`,
397/// VTI-NTF-080 – 098): the collection claims — `claim:<contextId>\0<did>`, a
398/// client's lease on being a persona DID's one collector at its mediator — the
399/// identifiers the VTA stopped collecting for after another connection kept
400/// closing its own (`conflict:<contextId>\0<did>`), the identities provisioned
401/// for another party, which their holders collect for (`provisioned:<did>`),
402/// each context's collection-by-default setting once changed
403/// (`context-setting:<contextId>`, VTI-NTF-094), the operator's suspension as
404/// last applied at boot (`suspension`, VTI-NTF-098), and the record that the
405/// upgrade backfill of `provisioned:` has run (`backfill:provisioned`).
406///
407/// In [`BACKED_UP`]: a claim names a client that is connected for the
408/// identifier until the claim ends. A restore without it would make the
409/// restored VTA the second connection to every claimed persona, which is the
410/// eviction fight the claim exists to prevent (VTI-NTF-081).
411pub const COLLECTION: &str = "collection";
412
413/// The watches this VTA holds for its principal's clients (`rooms/keys/watch/0.1`): one
414/// record per armed watch, keyed by a digest of (caller, member, host, room), holding
415/// exactly what Recipient item 6 lets it keep — the caller, the member, the room, the
416/// host, the address it armed with and that address's key material, and when the watch
417/// lapses. Never a watermark, a signalled version or the time a signal arrived. A record
418/// is deleted when its watch fires, is cancelled or lapses (30 days at most), when the
419/// caller's standing to act as the member is withdrawn, or when the member's credentials
420/// for the room are gone.
421///
422/// In [`EXCLUDED_FROM_BACKUP`]: a backup is a durable copy, and the specification asks the
423/// VTA not to keep an address, or a history of watches, once it has forgotten the watch.
424/// A restored VTA holds no watches; a client re-arms after its next read, or polls.
425pub const ROOM_KEY_WATCHES: &str = "room_key_watches";
426
427/// Every production keyspace. Partitioned by [`BACKED_UP`] +
428/// [`EXCLUDED_FROM_BACKUP`]; the [`tests::backup_partition_is_total`] guard
429/// asserts the partition stays exhaustive so a newly-added keyspace can't be
430/// silently omitted from the backup decision.
431pub const ALL: &[&str] = &[
432    INTERNAL_KEYS,
433    KEYS,
434    SESSIONS,
435    ACL,
436    CONTEXTS,
437    DID_TEMPLATES,
438    AUDIT,
439    AUDIT_KEY,
440    IMPORTED_SECRETS,
441    VAULT,
442    SERVICE_STATE,
443    SEALED_NONCES,
444    BACKUP_BUNDLES,
445    WEBVH,
446    PASSKEY_VMS,
447    DRAINS,
448    SNAPSHOT,
449    BOOTSTRAP,
450    CONSENT,
451    CONSENT_APPROVERS,
452    ISSUED_CREDENTIALS,
453    MEMORY,
454    ROOM_GROUPS,
455    ROOM_INVITATIONS,
456    APP_STATE,
457    PERSONA,
458    POLICY,
459    TASK_CONSENT,
460    OUTBOX,
461    TRUST_TASK_PUSHES,
462    IDEMPOTENCY,
463    ACCEPTED_IDS,
464    RELATIONSHIPS,
465    EXTERNAL_ACCOUNTS,
466    EXTERNAL_SECRETS,
467    PCS_ENGINE,
468    WITNESS_SESSIONS,
469    NOTIFICATIONS,
470    COLLECTION,
471    ROOM_KEY_WATCHES,
472];
473
474/// Keyspaces a backup carries, **every row of each**, as a raw dump.
475///
476/// A backup exists to bring an agent back, so the rule is inclusion: a
477/// keyspace is here unless there is a reason on [`EXCLUDED_FROM_BACKUP`] for
478/// leaving it out. Within a carried keyspace the only rows left behind are the
479/// few that belong to one *deployment* rather than to the agent — see
480/// [`is_environment_bound`] — and the restore re-creates those for the target.
481///
482/// Every name here is exported by `vta_backup::ops::export_backup` without a
483/// per-keyspace code path: it walks this list. `every_backed_up_keyspace_
484/// survives_a_round_trip` in `vta-backup` writes a row into each and asserts
485/// it comes back, so a keyspace cannot be listed here and silently skipped —
486/// which is exactly what happened to ten of them while export was a set of
487/// hand-written collectors.
488pub const BACKED_UP: &[&str] = &[
489    KEYS,
490    ACL,
491    CONTEXTS,
492    DID_TEMPLATES,
493    AUDIT,
494    // Without the keys, a restored audit log still verifies as a chain and
495    // still says what happened, but no entry can be checked against a
496    // candidate identifier again — the commitments become opaque. The key is
497    // generated rather than derived, so nothing else reproduces it.
498    AUDIT_KEY,
499    IMPORTED_SECRETS,
500    // The holder's secrets and credentials. The reason a person keeps a VTA.
501    VAULT,
502    WEBVH,
503    // Which transports this VTA serves. The DID log restored beside it
504    // advertises them, and a document naming a transport the node does not
505    // serve fails at the peer as a parse error, not as "not served".
506    SERVICE_STATE,
507    SNAPSHOT,
508    DRAINS,
509    // Anti-replay for sealed bootstrap requests. Restoring it only ever makes
510    // the restored agent stricter; leaving it behind reopens every request
511    // still inside its validity window.
512    SEALED_NONCES,
513    CONSENT,
514    CONSENT_APPROVERS,
515    // Credentials this VTA issued. Losing the records loses the ability to
516    // revoke them, while every copy in the wild stays valid.
517    ISSUED_CREDENTIALS,
518    // Durable agent memory is user data and must survive a restore.
519    MEMORY,
520    ROOM_GROUPS,
521    ROOM_INVITATIONS,
522    // Application state IS the user's account for a consumer built on it —
523    // labels, relationships, contacts, join history. A restore that came back
524    // without it would return a VTA whose applications no longer recognise
525    // their own data, which is the failure the store exists to prevent.
526    APP_STATE,
527    // The holder's own identity — attributes, profiles, bindings, contacts.
528    // A restore that came back without it would return an agent that no longer
529    // knows who its holder is, which is most of what the restore was for.
530    PERSONA,
531    // Operator security policy — must survive a restore, else enforcement
532    // silently reverts to whatever defaults boot-install provides.
533    POLICY,
534    // Task-consent grants are durable authorizations a re-submitted task
535    // consumes; losing them on restore would strand in-flight approvals.
536    TASK_CONSENT,
537    // The external accounts a community's integrations are bound to. Their
538    // secrets are not here; see EXTERNAL_SECRETS.
539    EXTERNAL_ACCOUNTS,
540    // Hidden-vetting engine state, wrapped. An applicant's attestations are not
541    // replaceable without its vetters sitting again.
542    PCS_ENGINE,
543    // What the principal was told they may take part in. An originator sends each
544    // revision once, so a lost record is not fetched again (VTI-NTF-050).
545    NOTIFICATIONS,
546    // Who collects for each persona. A restored VTA without the claims would be
547    // the second connection to every claimed persona (VTI-NTF-081).
548    COLLECTION,
549];
550
551/// Keyspaces deliberately **not** in a backup, each for a stated reason.
552pub const EXCLUDED_FROM_BACKUP: &[&str] = &[
553    // Non-extractable internal signing keys. Excluding them is the feature:
554    // a backup that carried them would export keys the VTA guarantees never
555    // to export, and restoring one elsewhere would silently clone a signer.
556    // Their *records* live in KEYS and are carried; the restore reports every
557    // one whose material stayed behind.
558    INTERNAL_KEYS,
559    // Live sessions are bound to the JWT key and the node that issued them.
560    SESSIONS,
561    // The control plane of the transfer carrying this very backup.
562    BACKUP_BUNDLES,
563    // TTL'd, in-flight passkey enrolment ceremonies.
564    PASSKEY_VMS,
565    // The deployment's own boot material: KMS ciphertexts, the integrity
566    // manifest, the staged restore itself. A restore writes the target's.
567    BOOTSTRAP,
568    // Reliable-messaging outbox: runtime delivery state, re-driven from live
569    // sends, not part of a state backup.
570    OUTBOX,
571    // Trust Task push records: the same runtime delivery state as the outbox
572    // they drive, bounded by their retention sweep.
573    TRUST_TASK_PUSHES,
574    // Trust-Task idempotency records. Short-lived by construction (a retry
575    // window, not durable state) and scoped to the VTA that served the original
576    // request — restoring one elsewhere would claim to have already performed
577    // operations that instance never did.
578    IDEMPOTENCY,
579    // The accepted-document-id record. Its horizon is the acceptance window —
580    // minutes — so a restored row is all but certainly expired, and an expired
581    // row refuses nothing. It is execution bookkeeping of the VTA that did the
582    // executing, and it holds recorded task responses, which a backup's scope
583    // (the agent's durable state) does not take.
584    ACCEPTED_IDS,
585    // TSP relationship state: durable across a restart, but re-establishable by
586    // a re-handshake (design note D2/D3) and scoped to this VTA's DIDs — so a
587    // restore re-drives it, like [`SESSIONS`], rather than carrying it.
588    RELATIONSHIPS,
589    // Provider secrets of external accounts. A portable, password-protected
590    // backup must not be a way to take one away; a restored account asks for
591    // its secret again (`providerSetupRequired`).
592    EXTERNAL_SECRETS,
593    // Witnessed sessions in flight: minutes long, and useless once the witness
594    // has expired its own side. A completed session's VWC and evidence are in
595    // the credential vault, which is carried.
596    WITNESS_SESSIONS,
597    // Watches armed for the principal's clients (`rooms/keys/watch/0.1`): each lapses
598    // within 30 days, holds a per-watch address's key material, and the specification
599    // asks that no copy of an address outlive its watch (Recipient item 6).
600    ROOM_KEY_WATCHES,
601];
602
603/// Rows inside a [`BACKED_UP`] keyspace that belong to the **deployment**, not
604/// to the agent, as `(keyspace, key prefix)`.
605///
606/// A backup moves between a plain VTA, a hardened one and a Nitro enclave in
607/// any direction. These rows only mean something in the environment that wrote
608/// them, or are derived from that environment's storage key, so copying one
609/// would be wrong on the target: the restore leaves them out and re-creates
610/// what the target needs.
611pub const ENVIRONMENT_BOUND_ROWS: &[(&str, &str)] = &[
612    // TEE identity mirror, did.jsonl copy, Mode-B carve-out sentinel and the
613    // legacy admin credential. The restore writes the target's own.
614    (KEYS, "tee:"),
615    // The hardened deployment's JWT key row. The key itself travels as the
616    // payload's `jwt_signing_key` and lands wherever the target keeps it.
617    (KEYS, "hardened:"),
618    // Restore / import bookkeeping of the source.
619    (KEYS, "backup:"),
620    (KEYS, "restore:"),
621    // Blinded persona indexes are keyed by an HMAC whose key is derived from
622    // the storage key, so they are meaningless under any other one. The
623    // restore rebuilds them from the rows they index.
624    (PERSONA, "pxi:"),
625    (PERSONA, "pxf:"),
626    (PERSONA, "pxfv"),
627];
628
629/// Whether `key` in `keyspace` is an [`ENVIRONMENT_BOUND_ROWS`] row.
630#[must_use]
631pub fn is_environment_bound(keyspace: &str, key: &[u8]) -> bool {
632    ENVIRONMENT_BOUND_ROWS
633        .iter()
634        .any(|(ks, prefix)| *ks == keyspace && key.starts_with(prefix.as_bytes()))
635}
636
637#[cfg(test)]
638mod tests {
639    use super::*;
640    use std::collections::BTreeSet;
641
642    /// The backup partition must be total and disjoint: every production
643    /// keyspace is either backed up or explicitly excluded. Adding a keyspace
644    /// to [`ALL`] without classifying it fails here — that's the point.
645    #[test]
646    fn backup_partition_is_total() {
647        let all: BTreeSet<&str> = ALL.iter().copied().collect();
648        let backed: BTreeSet<&str> = BACKED_UP.iter().copied().collect();
649        let excluded: BTreeSet<&str> = EXCLUDED_FROM_BACKUP.iter().copied().collect();
650
651        assert_eq!(all.len(), ALL.len(), "ALL has a duplicate");
652        assert!(
653            backed.is_disjoint(&excluded),
654            "a keyspace is both backed up and excluded: {:?}",
655            backed.intersection(&excluded).collect::<Vec<_>>()
656        );
657        let union: BTreeSet<&str> = backed.union(&excluded).copied().collect();
658        assert_eq!(
659            union, all,
660            "backup partition is not exhaustive — every keyspace in ALL must be in \
661             exactly one of BACKED_UP / EXCLUDED_FROM_BACKUP"
662        );
663    }
664
665    /// An environment-bound rule for a keyspace a backup never carries would be
666    /// dead, and one naming an unknown keyspace would be a typo that silently
667    /// lets a deployment row travel.
668    #[test]
669    fn environment_bound_rows_name_backed_up_keyspaces() {
670        for (ks, prefix) in ENVIRONMENT_BOUND_ROWS {
671            assert!(
672                BACKED_UP.contains(ks),
673                "environment-bound rule ({ks}, {prefix}) names a keyspace that is not backed up"
674            );
675            assert!(
676                !prefix.is_empty(),
677                "an empty prefix would drop the whole keyspace"
678            );
679        }
680    }
681
682    #[test]
683    fn environment_bound_rows_are_matched_by_prefix_within_their_keyspace() {
684        assert!(is_environment_bound(KEYS, b"tee:vta_did"));
685        assert!(is_environment_bound(KEYS, b"hardened:jwt_key"));
686        assert!(is_environment_bound(PERSONA, b"pxi:abcd"));
687        // Same prefix, different keyspace: carried.
688        assert!(!is_environment_bound(ACL, b"tee:mode-b"));
689        // The agent's own rows are carried.
690        assert!(!is_environment_bound(KEYS, b"key:abc"));
691        assert!(!is_environment_bound(PERSONA, b"pa:01H"));
692        assert!(!is_environment_bound(WEBVH, b"server:srv1"));
693    }
694}
695
696// ---------------------------------------------------------------------------
697// What a DID deletion means for each keyspace
698// ---------------------------------------------------------------------------
699
700/// What happens to a keyspace's DID-keyed contents when that DID is deleted.
701///
702/// Deleting a DID is not one cleanup. It is four different relationships, and
703/// treating them alike gets one of them wrong in a way nobody notices until it
704/// matters:
705///
706/// * things the DID **owns** go with it;
707/// * things that **name it as a subject of authorization** must go with it, or
708///   they become authority for an identity that no longer resolves;
709/// * things that **depend on it to function** must *stop* the deletion, because
710///   cascading would silently break them;
711/// * credentials the VTA **issued** cannot be deleted at all — copies exist
712///   elsewhere — so the only honest action is revocation.
713///
714/// # Why this is an enum and not a list in a function
715///
716/// The failure mode is not getting today's answers wrong. It is a keyspace
717/// added next quarter that nobody classifies, whose rows then quietly outlive
718/// the DID they belong to. [`ALL`] is already pinned by a census test for the
719/// backup partition, for exactly the same reason; this rides the same rail, so
720/// "we forgot" is a red test rather than an orphan found months later in a log.
721///
722/// The classifications below are judgements and several are arguable. That is
723/// fine — the point of the census is to force the question to be asked, not to
724/// claim these answers are the last word.
725///
726/// # A label is a claim about the code
727///
728/// `Cascade`, `Blocks` and `Revoke` say what a DID deletion *does*, and
729/// `vta-service`'s `did_delete_labels_match_the_cascade` test holds them to the
730/// cascade's own list of what it reaches. A keyspace whose rows should go with
731/// the DID (or should stop the deletion) but which the cascade does not reach
732/// yet is [`Orphaned`](DidDeleteEffect::Orphaned), with the effect it should
733/// have written beside it — labelling it `Cascade` would be the comfortable
734/// version of the orphan this census exists to catch.
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736#[non_exhaustive]
737pub enum DidDeleteEffect {
738    /// Rows belonging to the DID are removed with it.
739    Cascade,
740    /// A row referencing the DID **blocks** the deletion: something still in
741    /// use would break. Refused, never forced — the operator is told what to
742    /// unpick first.
743    Blocks,
744    /// Rows cannot be removed, because the VTA is not the only holder. They
745    /// are revoked instead.
746    Revoke,
747    /// Nothing here is keyed to a DID.
748    Unrelated,
749    /// Rows here can name the DID, and a DID deletion leaves them in place
750    /// today. The comment beside each says what the deletion should do with
751    /// them. A known gap, stated rather than labelled away.
752    Orphaned,
753}
754
755/// The effect a DID deletion has on `keyspace`, or `None` if the name is not a
756/// keyspace this build knows.
757///
758/// Every entry in [`ALL`] is classified — see `did_delete_census` in this
759/// module's tests.
760#[must_use]
761pub const fn did_delete_effect(keyspace: &str) -> Option<DidDeleteEffect> {
762    use DidDeleteEffect::*;
763    // `const fn` cannot match on `&str`, so this is a byte-slice match.
764    Some(match keyspace.as_bytes() {
765        // ---- Removed with the DID ----------------------------------------
766        // Its key records (`<did>#key-N`, `#pre-rotation-N`) and its own log.
767        b"keys" | b"webvh" => Cascade,
768        // An ACL entry outliving its DID is the worst of the orphans: live
769        // authority for an identity that can no longer be resolved or rotated.
770        // The VTC learned this the expensive way (#1194, #1196). Sessions are
771        // authority already issued, and go the same way.
772        b"acl" | b"sessions" => Cascade,
773
774        // ---- Depends on the DID to function ------------------------------
775        // A context whose `did` is this one: deleting the DID would strand it,
776        // so the operator is told to reassign it first.
777        b"contexts" => Blocks,
778
779        // ---- Cannot be deleted, only revoked -----------------------------
780        // Third parties hold copies. Deleting our record achieves nothing but
781        // losing our ability to revoke it.
782        b"issued_credentials" => Revoke,
783
784        // ---- Should go with the DID; the cascade does not reach them -----
785        // Material of the DID's imported / internal keys. The cascade removes
786        // the key *records* only. (A context deletion takes both.)
787        b"internal_keys" | b"imported_secrets" => Orphaned,
788        // Delivery and protocol state keyed by DID: stale the moment it goes.
789        // TSP relationships name this VTA's DID as one half of each
790        // `(our_vid, their_vid)` pair; with that VID gone the relationship can
791        // neither send nor be sent to.
792        b"outbox" | b"trust_task_pushes" | b"relationships" => Orphaned,
793        // In-flight passkey enrolment for the DID (TTL'd).
794        b"passkey_vms" => Orphaned,
795        // Consent state and the vault are held *for* a holder; with the holder
796        // gone they are unreachable by anyone.
797        b"consent" | b"task_consent" | b"vault" => Orphaned,
798        // Per-holder application state and memory. Keyed by context, not DID,
799        // and purged by a context deletion; a lone DID deletion leaves them.
800        b"app_state" | b"memory" => Orphaned,
801        // A member's room groups, and the invitations they were joined under.
802        // Held for the holder in the same sense the vault is: the group state
803        // decrypts a room *that member* belongs to, and with the member gone
804        // nobody can use it or ever will again.
805        //
806        // The consumed-invitation records should go with them and not before:
807        // while the member exists, a consumed invitation MUST outlive the group
808        // it let them join, or leaving a room would make the same invitation
809        // work twice.
810        b"room_groups" | b"room_invitations" => Orphaned,
811        // Hidden-vetting engines: a vetter's names the member DID it draws
812        // tokens as, an applicant's the DID it joins as. Purged with their
813        // context; a lone DID deletion leaves them.
814        b"pcs_engine" => Orphaned,
815        // A witnessed session in flight is the relationship DID's (minutes long).
816        b"witness_sessions" => Orphaned,
817        // A held notification was addressed to the DID.
818        b"notifications" => Orphaned,
819        // A collection claim, conflict or provisioned marker names the DID. Not
820        // reached by the cascade; the collector's sweep drops claims and
821        // conflicts on an identifier that is no longer collectable within one
822        // pass, and such a claim is not in force meanwhile (VTI-NTF-090). A
823        // context's setting, the suspension and the backfill record name no
824        // DID as their subject.
825        b"collection" => Orphaned,
826        // A watch names its member and its caller. Not reached by the cascade; the
827        // watch sweep forgets a watch whose caller may no longer act as the member
828        // (`rooms/keys/watch/0.1` Recipient item 7) within one pass, and every watch
829        // lapses within 30 days.
830        b"room_key_watches" => Orphaned,
831        // Persona is two scopes in one keyspace and only one half is DID-keyed:
832        // a binding is keyed by the persona DID, and a contact records the
833        // persona that knows it. Those should cascade (a context deletion takes
834        // them); the agent-scoped rows — the attribute pool, the profiles, and
835        // their indexes — are keyed to no DID and must survive, because a
836        // profile may be bound to several personas.
837        b"persona" => Orphaned,
838        // These should *block*: a DID named in an advertised service entry (or
839        // its rollback snapshot), a policy or approver set that names it, an
840        // external account binding whose consumer it is. Cascading breaks
841        // something still in use; but nothing checks them yet.
842        b"service_state" | b"service_prev_config" => Orphaned,
843        b"policy" | b"consent_approvers" | b"external_accounts" => Orphaned,
844
845        // ---- Not keyed to a DID ------------------------------------------
846        // The audit log is deliberately here: it is append-only, and the record
847        // that a DID was deleted is the one thing that must survive deleting it.
848        b"audit" | b"audit_key" => Unrelated,
849        b"did_templates" | b"sealed_nonces" | b"backup_bundles" => Unrelated,
850        b"drains" | b"bootstrap" | b"idempotency" => Unrelated,
851        // Keyed by Trust Task document `id`, and gone within the document's
852        // acceptance window. Cascading would hand a deleted DID's accepted ids
853        // back while their documents can still arrive — the replay the record
854        // exists to refuse.
855        b"accepted_ids" => Unrelated,
856        // Keyed by account, never by DID; the account row carries the bindings.
857        b"external_secrets" => Unrelated,
858
859        _ => return None,
860    })
861}
862
863#[cfg(test)]
864mod did_delete_tests {
865    use super::*;
866
867    /// Every keyspace must have an answer to "what happens to this when a DID
868    /// is deleted".
869    ///
870    /// This is the whole point of the classification. Adding a keyspace is
871    /// easy; remembering that its rows might outlive the DID they belong to is
872    /// not, and nothing about adding one prompts the question. This test asks
873    /// it, once, at the only moment anyone is looking.
874    ///
875    /// A new keyspace fails here until it is classified. `Unrelated` is a
876    /// perfectly good answer — but it has to be a chosen one.
877    #[test]
878    fn every_keyspace_is_classified_for_did_deletion() {
879        let unclassified: Vec<&str> = ALL
880            .iter()
881            .copied()
882            .filter(|ks| did_delete_effect(ks).is_none())
883            .collect();
884        assert!(
885            unclassified.is_empty(),
886            "these keyspaces have no DID-deletion effect declared: {unclassified:?}\n\
887             Add them to `did_delete_effect`. `Unrelated` is a fine answer if \
888             nothing in the keyspace is keyed to a DID — but it must be chosen, \
889             not defaulted."
890        );
891    }
892
893    /// An unknown name is not silently `Unrelated`. The distinction matters:
894    /// `None` means "this build does not know that keyspace", and answering
895    /// `Unrelated` to it would let a typo read as "nothing to clean up".
896    #[test]
897    fn an_unknown_keyspace_has_no_effect_rather_than_a_harmless_one() {
898        assert_eq!(did_delete_effect("not_a_keyspace"), None);
899        assert_eq!(did_delete_effect(""), None);
900    }
901
902    /// The credential keyspace must never be classified `Cascade`.
903    ///
904    /// Pinned explicitly because it is the one that looks most like a cascade
905    /// and is not: the VTA is not the only holder of what it issued, so
906    /// deleting our record destroys the ability to revoke it while leaving
907    /// every copy in the wild valid forever. That is the exact residue an ACL
908    /// revoke left behind on the VTC.
909    #[test]
910    fn issued_credentials_are_revoked_never_deleted() {
911        assert_eq!(
912            did_delete_effect(ISSUED_CREDENTIALS),
913            Some(DidDeleteEffect::Revoke)
914        );
915    }
916
917    /// The audit log must survive the deletion it records.
918    #[test]
919    fn the_audit_log_is_never_cascaded() {
920        assert_eq!(did_delete_effect(AUDIT), Some(DidDeleteEffect::Unrelated));
921    }
922}
923
924// ---------------------------------------------------------------------------
925// What a context deletion means for each keyspace
926// ---------------------------------------------------------------------------
927
928/// What happens to a keyspace's context-scoped contents when that context is
929/// deleted (`vta/contexts/delete`).
930///
931/// The question that matters is narrower than "is this tidy": a context can be
932/// created again **under the same id**, and anything keyed by (or carrying) the
933/// old id that survives the deletion is inherited by the new one. That has
934/// happened twice — application state syncing a deleted profile's personas back
935/// (#2415), and a vetter engine record pinning the old member DID so the new
936/// context's `vta/pcs/root-request` failed with `memberMismatch`.
937///
938/// Same rail as [`DidDeleteEffect`]: every keyspace in [`ALL`] must be
939/// classified, and `vta-service`'s `context_delete_labels_match_the_cascade`
940/// test holds the [`Purged`](ContextDeleteEffect::Purged) set to the list the
941/// cascade itself declares, so a label cannot claim a purge the code does not do.
942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
943#[non_exhaustive]
944pub enum ContextDeleteEffect {
945    /// The context's rows are removed with it.
946    Purged,
947    /// Context-scoped rows are deliberately kept; the reason is beside each.
948    Retained,
949    /// Context-scoped rows are not removed, but each expires on its own within
950    /// a bounded time, and none is found again through a recreated context.
951    Lapses,
952    /// Nothing here is scoped to a context.
953    Unrelated,
954}
955
956/// The effect a context deletion has on `keyspace`, or `None` if the name is
957/// not a keyspace this build knows.
958#[must_use]
959pub const fn context_delete_effect(keyspace: &str) -> Option<ContextDeleteEffect> {
960    use ContextDeleteEffect::*;
961    Some(match keyspace.as_bytes() {
962        // ---- Removed with the context -----------------------------------
963        // The context record and its daily quota counters; its key records and
964        // the material of its imported / internal keys; its DIDs (through the
965        // full DID deletion); its ACL scope; its DID templates.
966        b"contexts" | b"keys" | b"imported_secrets" | b"internal_keys" => Purged,
967        b"webvh" | b"acl" | b"did_templates" => Purged,
968        // Data held for the principal in the context.
969        b"app_state" | b"memory" | b"persona" | b"vault" => Purged,
970        b"consent" | b"consent_approvers" | b"notifications" => Purged,
971        // Engine records name the context their key is derived under; left
972        // behind, a recreated context inherits a vetter pinned to the old
973        // member DID and an old derivation path.
974        b"pcs_engine" => Purged,
975        // Live accounts are deleted the way `external/accounts/delete` deletes
976        // one: secret gone, id retired. The `retired:` tombstones are kept —
977        // see `Retained` below for why that is not a resurrection.
978        b"external_accounts" | b"external_secrets" => Purged,
979        // Collection claims and conflicts on the context's identifiers end with
980        // it (VTI-NTF-090), and so does its setting, so a context created again
981        // under the id starts enabled (VTI-NTF-094).
982        b"collection" => Purged,
983
984        // ---- Kept on purpose --------------------------------------------
985        // Append-only; the record that a context was deleted must survive it.
986        b"audit" | b"audit_key" => Retained,
987        // Credentials the VTA issued: third parties hold copies, so the record
988        // is what revokes them. The context's DIDs are deleted through the DID
989        // cascade, which revokes what was issued to them.
990        b"issued_credentials" => Retained,
991        // Operator policy. An approval rule naming a context id is the
992        // operator's statement about that id, not data the context owned.
993        b"policy" => Retained,
994        // Keyed by member persona DID and by credential id, never by context. A
995        // recreated context's personas are new DIDs and cannot reach them; a
996        // consumed invitation must stay consumed (single use).
997        b"room_groups" | b"room_invitations" => Retained,
998
999        // ---- Expire on their own ----------------------------------------
1000        // Live sessions keep the context in their access token's `contexts`
1001        // claim until it expires; a refresh re-reads the ACL, which the
1002        // deletion already narrowed. TTL'd consent, enrolment, idempotency and
1003        // witness records likewise.
1004        b"sessions" | b"task_consent" | b"passkey_vms" => Lapses,
1005        b"idempotency" | b"accepted_ids" | b"witness_sessions" => Lapses,
1006        // A watch whose caller loses standing in the context is forgotten by the
1007        // watch sweep's next pass, and every watch lapses within 30 days. Its member
1008        // is a persona DID, which a recreated context never holds again.
1009        b"room_key_watches" => Lapses,
1010
1011        // ---- Not scoped to a context ------------------------------------
1012        b"service_state" | b"service_prev_config" | b"sealed_nonces" => Unrelated,
1013        b"backup_bundles" | b"drains" | b"bootstrap" => Unrelated,
1014        b"outbox" | b"trust_task_pushes" | b"relationships" => Unrelated,
1015
1016        _ => return None,
1017    })
1018}
1019
1020#[cfg(test)]
1021mod context_delete_tests {
1022    use super::*;
1023
1024    /// Every keyspace must answer "what happens to this context's rows here
1025    /// when the context is deleted" — a keyspace added without an answer is
1026    /// the next one whose rows a recreated context inherits.
1027    #[test]
1028    fn every_keyspace_is_classified_for_context_deletion() {
1029        let unclassified: Vec<&str> = ALL
1030            .iter()
1031            .copied()
1032            .filter(|ks| context_delete_effect(ks).is_none())
1033            .collect();
1034        assert!(
1035            unclassified.is_empty(),
1036            "these keyspaces have no context-deletion effect declared: {unclassified:?}\n\
1037             Add them to `context_delete_effect`, and if their rows are scoped to a \
1038             context, purge them in `vta-service`'s `delete_context`."
1039        );
1040        assert_eq!(context_delete_effect("not_a_keyspace"), None);
1041    }
1042
1043    /// The audit log survives the deletion it records.
1044    #[test]
1045    fn the_audit_log_is_never_purged() {
1046        assert_eq!(
1047            context_delete_effect(AUDIT),
1048            Some(ContextDeleteEffect::Retained)
1049        );
1050    }
1051}