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