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