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/// Imported secret material (KEK-wrapped). Named `imported_secrets`, **not**
53/// `imported` — the latter was a long-standing test-only typo that operated on
54/// an empty keyspace disjoint from production. Always reference this const.
55pub const IMPORTED_SECRETS: &str = "imported_secrets";
56/// Non-extractable internal signing keys.
57///
58/// Deliberately **not** [`IMPORTED_SECRETS`]: that keyspace wraps its contents
59/// under a KEK derived from the BIP-39 master seed, so anything stored there is
60/// reconstructible by whoever holds the mnemonic. Internal keys exist precisely
61/// to have no such path — their material is generated from the system CSPRNG,
62/// never derived, and lives here instead.
63///
64/// In [`EXCLUDED_FROM_BACKUP`] by design, not by omission. A backup containing
65/// this keyspace would be an export of keys the VTA promises never to export.
66pub const INTERNAL_KEYS: &str = "internal_keys";
67/// Ephemeral cache (resolver/auth caches).
68pub const CACHE: &str = "cache";
69/// Holder credential vault (third-party secrets stored on this VTA).
70pub const VAULT: &str = "vault";
71/// Persistent runtime service-enable state (`operations::protocol::runtime_state`).
72pub const SERVICE_STATE: &str = "service_state";
73/// Sealed-bootstrap anti-replay nonce log.
74pub const SEALED_NONCES: &str = "sealed_nonces";
75/// In-flight backup-bundle control-plane records.
76pub const BACKUP_BUNDLES: &str = "backup_bundles";
77/// WebVH DID records + `did.jsonl` state.
78pub const WEBVH: &str = "webvh";
79/// In-flight passkey-as-verificationMethod enrolment state.
80pub const PASSKEY_VMS: &str = "passkey_vms";
81/// Persisted protocol-management drain set.
82pub const DRAINS: &str = "drains";
83/// Per-kind previous-config snapshots for fail-forward rollback.
84/// (Historically `operations::protocol::snapshot::KEYSPACE_NAME`.)
85pub const SNAPSHOT: &str = "service_prev_config";
86/// KMS-protected, unencrypted boot keyspace (TEE integrity manifest, etc.).
87pub const BOOTSTRAP: &str = "bootstrap";
88/// Inbound-messaging consent: durable grants + TTL'd pending requests
89/// (`vti_common::consent`). The VTA is the first gate for bridged conversations.
90pub const CONSENT: &str = "consent";
91/// Per-(platform, context) approver bindings — who decides consent and how the
92/// prompt routes (`vti_common::consent::ApproverBinding`).
93pub const CONSENT_APPROVERS: &str = "consent_approvers";
94/// VTA-issued credentials (minted by `vta/credentials/issue/0.1`, revoked by
95/// `vta/credentials/revoke/0.1`). One record per credential keyed `cred:<id>`;
96/// revocation is a tombstone (`revokedAt` set in place), not a delete. Distinct
97/// from [`VAULT`] (which stores credentials the holder *holds*).
98pub const ISSUED_CREDENTIALS: &str = "issued_credentials";
99
100/// Per-context key/value store for AI-agent memory (`vta/memory/{put,list,
101/// delete}/0.1`). One record per `(contextId, key)` pair, keyed
102/// `mem:<contextId>:<key>`; `list` is a `mem:<contextId>:` prefix scan. Durable
103/// user data → in [`BACKED_UP`].
104pub const MEMORY: &str = "memory";
105
106/// Versioned, namespaced application state (`vta/app-state/{get,put,list,
107/// delete,get-many,put-many}/1.0`) — the third store, beside [`VAULT`] (secrets
108/// and credentials) and [`MEMORY`] (agent memory), for JSON an application owns
109/// and the VTA does not interpret.
110///
111/// Four record shapes share the keyspace, distinguished by prefix:
112///
113/// - `app:<contextId>:<namespace>:<key>` — the record itself. `list` in
114///   snapshot mode is an `app:<contextId>:<namespace>:` prefix scan.
115/// - `appv:<contextId>:<namespace>:<version:020}>` — version index, mapping a
116///   zero-padded counter value to its record key. Change-feed `list` scans this
117///   so it can return changes in version order and paginate over a stable
118///   storage key; a scan-and-sort over the records could do neither.
119/// - `appc:<contextId>:<namespace>` — the namespace's monotonic write counter.
120/// - `appt:<contextId>:<namespace>` — the oldest version still covered by a
121///   retained tombstone, which is what `sinceVersion` is checked against.
122///
123/// Deliberately **not** [`MEMORY`]: clearing an agent's memory has to stay a
124/// safe thing for a user to ask, which it cannot be if account state lives
125/// there. Durable user data — an account's recoverability depends on it — so it
126/// is in [`BACKED_UP`], and a restore that came back without it would defeat
127/// the point of the feature.
128pub const APP_STATE: &str = "app_state";
129
130/// Rego policy modules for the Policy Decision Point (`policy/{upsert,list,
131/// delete,evaluate}`). One `policy::PolicyModule` per id, keyed `policy:<id>`;
132/// the active set is every enabled row, priority-ordered. Durable operator
133/// security config → in [`BACKED_UP`] (a lost policy set would silently drop
134/// enforcement on restore).
135pub const POLICY: &str = "policy";
136
137/// Task-execution consent for the PDP's `requireConsent` disposition: pending
138/// approvals keyed by payload digest, and granted consents a re-submitted task
139/// consumes. Distinct from [`CONSENT`] (messaging-bridge conversation consent).
140/// One `policy::consent::PendingTaskConsent` per `pending:<digest>` and
141/// `policy::consent::TaskConsentGrant` per `grant:<digest>:<requester>`.
142/// Durable operator-facing security state → [`BACKED_UP`].
143pub const TASK_CONSENT: &str = "task_consent";
144
145/// Durable reliable-messaging outbox backing `vti_common::outbox_store::`
146/// `VtiOutboxStore` for the delivery-layer `MessagingService` (D2 P2a
147/// cut-over). Holds `Guaranteed`-delivery outbox entries; dormant in P2a (all
148/// current sends are `BestEffort`) but wired so the drain/confirmation loops
149/// persist across restarts once P2b adds guaranteed VTA pushes. Runtime state,
150/// not backed up.
151pub const OUTBOX: &str = "outbox";
152
153/// Idempotency records for keyed Trust Tasks — one row per
154/// `(actor, idempotency-key)`, holding the request digest and, for tasks whose
155/// response may be replayed, the original response. Lets a client's retry of a
156/// lost reply converge on the first execution instead of producing a second
157/// durable effect.
158///
159/// Persistent rather than in-memory (unlike the `(actor, envelope-id)` replay
160/// cache it sits beside) because the window that matters is exactly the one a
161/// restart falls inside: the VTA processed the request, the reply was lost, and
162/// the client is still retrying. Swept on TTL by
163/// `vta_sweepers::idempotency_sweeper`. Runtime state, not backed up.
164pub const IDEMPOTENCY: &str = "idempotency";
165
166/// Every production keyspace. Partitioned by [`BACKED_UP`] +
167/// [`EXCLUDED_FROM_BACKUP`]; the [`tests::backup_partition_is_total`] guard
168/// asserts the partition stays exhaustive so a newly-added keyspace can't be
169/// silently omitted from the backup decision.
170pub const ALL: &[&str] = &[
171    INTERNAL_KEYS,
172    KEYS,
173    SESSIONS,
174    ACL,
175    CONTEXTS,
176    DID_TEMPLATES,
177    AUDIT,
178    IMPORTED_SECRETS,
179    CACHE,
180    VAULT,
181    SERVICE_STATE,
182    SEALED_NONCES,
183    BACKUP_BUNDLES,
184    WEBVH,
185    PASSKEY_VMS,
186    DRAINS,
187    SNAPSHOT,
188    BOOTSTRAP,
189    CONSENT,
190    CONSENT_APPROVERS,
191    ISSUED_CREDENTIALS,
192    MEMORY,
193    APP_STATE,
194    POLICY,
195    TASK_CONSENT,
196    OUTBOX,
197    IDEMPOTENCY,
198];
199
200/// Keyspaces whose contents a full `export_backup` captures (as typed
201/// collections — see `operations::backup`).
202pub const BACKED_UP: &[&str] = &[
203    KEYS,
204    ACL,
205    CONTEXTS,
206    AUDIT,
207    IMPORTED_SECRETS,
208    WEBVH,
209    CONSENT,
210    CONSENT_APPROVERS,
211    // Durable agent memory is user data and must survive a restore.
212    MEMORY,
213    // Application state IS the user's account for a consumer built on it —
214    // labels, relationships, contacts, join history. A restore that came back
215    // without it would return a VTA whose applications no longer recognise
216    // their own data, which is the failure the store exists to prevent.
217    APP_STATE,
218    // Operator security policy — must survive a restore, else enforcement
219    // silently reverts to whatever defaults boot-install provides.
220    POLICY,
221    // Task-consent grants are durable authorizations a re-submitted task
222    // consumes; losing them on restore would strand in-flight approvals.
223    TASK_CONSENT,
224];
225
226/// Keyspaces deliberately **not** in a backup.
227///
228/// Most are ephemeral / runtime / re-derivable: [`SESSIONS`], [`CACHE`],
229/// [`SEALED_NONCES`], [`SERVICE_STATE`], [`BACKUP_BUNDLES`], [`PASSKEY_VMS`],
230/// [`DRAINS`], [`SNAPSHOT`], [`BOOTSTRAP`]. [`DID_TEMPLATES`] and [`VAULT`]
231/// hold durable operator/holder state and are **known backup gaps** — a
232/// backup-fidelity follow-up should move them into [`BACKED_UP`], not leave
233/// them silently dropped.
234pub const EXCLUDED_FROM_BACKUP: &[&str] = &[
235    // Non-extractable internal signing keys. Excluding them is the feature:
236    // a backup that carried them would export keys the VTA guarantees never
237    // to export, and restoring one elsewhere would silently clone a signer.
238    INTERNAL_KEYS,
239    SESSIONS,
240    DID_TEMPLATES,
241    CACHE,
242    VAULT,
243    SERVICE_STATE,
244    SEALED_NONCES,
245    BACKUP_BUNDLES,
246    PASSKEY_VMS,
247    DRAINS,
248    SNAPSHOT,
249    BOOTSTRAP,
250    // Durable VTA-issued holder credentials. Like [`VAULT`], a known backup
251    // gap — a backup-fidelity follow-up should move it into [`BACKED_UP`].
252    ISSUED_CREDENTIALS,
253    // Reliable-messaging outbox: runtime delivery state, re-driven from live
254    // sends, not part of a state backup.
255    OUTBOX,
256    // Trust-Task idempotency records. Short-lived by construction (a retry
257    // window, not durable state) and scoped to the VTA that served the original
258    // request — restoring one elsewhere would claim to have already performed
259    // operations that instance never did.
260    IDEMPOTENCY,
261];
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use std::collections::BTreeSet;
267
268    /// The backup partition must be total and disjoint: every production
269    /// keyspace is either backed up or explicitly excluded. Adding a keyspace
270    /// to [`ALL`] without classifying it fails here — that's the point.
271    #[test]
272    fn backup_partition_is_total() {
273        let all: BTreeSet<&str> = ALL.iter().copied().collect();
274        let backed: BTreeSet<&str> = BACKED_UP.iter().copied().collect();
275        let excluded: BTreeSet<&str> = EXCLUDED_FROM_BACKUP.iter().copied().collect();
276
277        assert_eq!(all.len(), ALL.len(), "ALL has a duplicate");
278        assert!(
279            backed.is_disjoint(&excluded),
280            "a keyspace is both backed up and excluded: {:?}",
281            backed.intersection(&excluded).collect::<Vec<_>>()
282        );
283        let union: BTreeSet<&str> = backed.union(&excluded).copied().collect();
284        assert_eq!(
285            union, all,
286            "backup partition is not exhaustive — every keyspace in ALL must be in \
287             exactly one of BACKED_UP / EXCLUDED_FROM_BACKUP"
288        );
289    }
290}
291
292// ---------------------------------------------------------------------------
293// What a DID deletion means for each keyspace
294// ---------------------------------------------------------------------------
295
296/// What happens to a keyspace's DID-keyed contents when that DID is deleted.
297///
298/// Deleting a DID is not one cleanup. It is four different relationships, and
299/// treating them alike gets one of them wrong in a way nobody notices until it
300/// matters:
301///
302/// * things the DID **owns** go with it;
303/// * things that **name it as a subject of authorization** must go with it, or
304///   they become authority for an identity that no longer resolves;
305/// * things that **depend on it to function** must *stop* the deletion, because
306///   cascading would silently break them;
307/// * credentials the VTA **issued** cannot be deleted at all — copies exist
308///   elsewhere — so the only honest action is revocation.
309///
310/// # Why this is an enum and not a list in a function
311///
312/// The failure mode is not getting today's answers wrong. It is a keyspace
313/// added next quarter that nobody classifies, whose rows then quietly outlive
314/// the DID they belong to. [`ALL`] is already pinned by a census test for the
315/// backup partition, for exactly the same reason; this rides the same rail, so
316/// "we forgot" is a red test rather than an orphan found months later in a log.
317///
318/// The classifications below are judgements and several are arguable. That is
319/// fine — the point of the census is to force the question to be asked, not to
320/// claim these answers are the last word.
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322pub enum DidDeleteEffect {
323    /// Rows belonging to the DID are removed with it.
324    Cascade,
325    /// A row referencing the DID **blocks** the deletion: something still in
326    /// use would break. Refused, never forced — the operator is told what to
327    /// unpick first.
328    Blocks,
329    /// Rows cannot be removed, because the VTA is not the only holder. They
330    /// are revoked instead.
331    Revoke,
332    /// Nothing here is keyed to a DID.
333    Unrelated,
334}
335
336/// The effect a DID deletion has on `keyspace`, or `None` if the name is not a
337/// keyspace this build knows.
338///
339/// Every entry in [`ALL`] is classified — see `did_delete_census` in this
340/// module's tests.
341#[must_use]
342pub const fn did_delete_effect(keyspace: &str) -> Option<DidDeleteEffect> {
343    use DidDeleteEffect::*;
344    // `const fn` cannot match on `&str`, so this is a byte-slice match.
345    Some(match keyspace.as_bytes() {
346        // ---- Owned by the DID -------------------------------------------
347        // Key material derived under it, its own log, its advertised name.
348        b"keys" | b"internal_keys" | b"imported_secrets" | b"webvh" => Cascade,
349        // Resolution + protocol caches keyed by DID: stale the moment it goes.
350        b"cache" | b"outbox" => Cascade,
351
352        // ---- Names the DID as a subject of authorization -----------------
353        // An ACL entry outliving its DID is the worst of the orphans: live
354        // authority for an identity that can no longer be resolved or rotated.
355        // The VTC learned this the expensive way (#1194, #1196).
356        b"acl" | b"sessions" | b"passkey_vms" => Cascade,
357        // Consent state and the vault are held *for* a holder; with the holder
358        // gone they are unreachable by anyone.
359        b"consent" | b"task_consent" | b"vault" => Cascade,
360        // Per-DID application state the VTA stores on a holder's behalf.
361        b"app_state" | b"memory" => Cascade,
362
363        // ---- Depends on the DID to function ------------------------------
364        // A context whose `did` is this one, a DID named in an advertised
365        // service entry (or its rollback snapshot), a policy or approver set
366        // that names it. Cascading any of these breaks something that is still
367        // in use; refusing tells the operator what to unpick.
368        b"contexts" | b"service_state" | b"service_prev_config" => Blocks,
369        b"policy" | b"consent_approvers" => Blocks,
370
371        // ---- Cannot be deleted, only revoked -----------------------------
372        // Third parties hold copies. Deleting our record achieves nothing but
373        // losing our ability to revoke it.
374        b"issued_credentials" => Revoke,
375
376        // ---- Not keyed to a DID ------------------------------------------
377        // The audit log is deliberately here: it is append-only, and the record
378        // that a DID was deleted is the one thing that must survive deleting it.
379        b"audit" => Unrelated,
380        b"did_templates" | b"sealed_nonces" | b"backup_bundles" => Unrelated,
381        b"drains" | b"bootstrap" | b"idempotency" => Unrelated,
382
383        _ => return None,
384    })
385}
386
387#[cfg(test)]
388mod did_delete_tests {
389    use super::*;
390
391    /// Every keyspace must have an answer to "what happens to this when a DID
392    /// is deleted".
393    ///
394    /// This is the whole point of the classification. Adding a keyspace is
395    /// easy; remembering that its rows might outlive the DID they belong to is
396    /// not, and nothing about adding one prompts the question. This test asks
397    /// it, once, at the only moment anyone is looking.
398    ///
399    /// A new keyspace fails here until it is classified. `Unrelated` is a
400    /// perfectly good answer — but it has to be a chosen one.
401    #[test]
402    fn every_keyspace_is_classified_for_did_deletion() {
403        let unclassified: Vec<&str> = ALL
404            .iter()
405            .copied()
406            .filter(|ks| did_delete_effect(ks).is_none())
407            .collect();
408        assert!(
409            unclassified.is_empty(),
410            "these keyspaces have no DID-deletion effect declared: {unclassified:?}\n\
411             Add them to `did_delete_effect`. `Unrelated` is a fine answer if \
412             nothing in the keyspace is keyed to a DID — but it must be chosen, \
413             not defaulted."
414        );
415    }
416
417    /// An unknown name is not silently `Unrelated`. The distinction matters:
418    /// `None` means "this build does not know that keyspace", and answering
419    /// `Unrelated` to it would let a typo read as "nothing to clean up".
420    #[test]
421    fn an_unknown_keyspace_has_no_effect_rather_than_a_harmless_one() {
422        assert_eq!(did_delete_effect("not_a_keyspace"), None);
423        assert_eq!(did_delete_effect(""), None);
424    }
425
426    /// The credential keyspace must never be classified `Cascade`.
427    ///
428    /// Pinned explicitly because it is the one that looks most like a cascade
429    /// and is not: the VTA is not the only holder of what it issued, so
430    /// deleting our record destroys the ability to revoke it while leaving
431    /// every copy in the wild valid forever. That is the exact residue an ACL
432    /// revoke left behind on the VTC.
433    #[test]
434    fn issued_credentials_are_revoked_never_deleted() {
435        assert_eq!(
436            did_delete_effect(ISSUED_CREDENTIALS),
437            Some(DidDeleteEffect::Revoke)
438        );
439    }
440
441    /// The audit log must survive the deletion it records.
442    #[test]
443    fn the_audit_log_is_never_cascaded() {
444        assert_eq!(did_delete_effect(AUDIT), Some(DidDeleteEffect::Unrelated));
445    }
446}