openvtc-core 0.6.0

OpenVTC Core Library
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! The account model as app-state records, and back.
//!
//! [`project`] turns the synced parts of the config into one JSON value per
//! record key; [`apply`] writes one record's value (or its deletion) back into
//! the config. Everything in between — diffing, merging, versioning — happens
//! on that JSON, so the engine never needs to know what a membership is.
//!
//! **One key per record, never one blob (D8a).** A blob grows without bound
//! against the VTA's per-record cap, and last-write-wins on a blob loses
//! unrelated edits. Keys hash their identifiers so a DID or a credential id
//! can never produce an over-long or ambiguous key; the value carries the
//! identifier itself.

use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use serde_json::{Value, json};
use sha2::{Digest, Sha256};

use crate::agent_name::CachedAgentName;
use crate::config::account::{Account, CommunityRecord, PersonaRecord};
use crate::config::protected_config::{Contact, ProtectedConfig};
use crate::config::secured_config::{KeyInfoConfig, KeySourceMaterial};
use crate::relationships::Relationship;
use crate::vetting::VettingBook;
use crate::vrc::Vrcs;

/// What a record holds. The key prefix names it, so a record from a newer
/// build with a kind this one does not know is recognisable as such.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum RecordKind {
    /// An account persona ([`PersonaRecord`]).
    Persona,
    /// A community membership ([`CommunityRecord`]), with its flags.
    Membership,
    /// A DIDComm pairwise relationship.
    Relationship,
    /// A contact.
    Contact,
    /// A verified agent name. Only positive lookups are synced: a negative is
    /// a note about this run's network, and is pruned at every launch anyway.
    AgentName,
    /// One row of the durable TSP relationship store.
    Tsp,
    /// A relationship credential we issued.
    VrcIssued,
    /// A relationship credential we received.
    VrcReceived,
    /// A reference to a VTA-managed key. Only the VTA key id travels — a key
    /// whose material is held locally is never synced.
    Key,
    /// Vetting state, minus the hidden-vetting engine, which carries secrets.
    Vetting,
}

impl RecordKind {
    /// Every kind, for iteration.
    pub const ALL: [RecordKind; 10] = [
        RecordKind::Persona,
        RecordKind::Membership,
        RecordKind::Relationship,
        RecordKind::Contact,
        RecordKind::AgentName,
        RecordKind::Tsp,
        RecordKind::VrcIssued,
        RecordKind::VrcReceived,
        RecordKind::Key,
        RecordKind::Vetting,
    ];

    fn prefix(self) -> &'static str {
        match self {
            RecordKind::Persona => "v1/persona/",
            RecordKind::Membership => "v1/membership/",
            RecordKind::Relationship => "v1/relationship/",
            RecordKind::Contact => "v1/contact/",
            RecordKind::AgentName => "v1/agent-name/",
            RecordKind::Tsp => "v1/tsp/",
            RecordKind::VrcIssued => "v1/vrc-issued/",
            RecordKind::VrcReceived => "v1/vrc-received/",
            RecordKind::Key => "v1/key/",
            RecordKind::Vetting => "v1/vetting",
        }
    }

    /// The kind a record key names, or `None` for a kind this build does not
    /// know (a newer build's record, which is left alone).
    #[must_use]
    pub fn of_key(key: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|k| key.starts_with(k.prefix()))
    }

    /// Whether a change of this kind can be applied to a running session.
    ///
    /// The rest are hydrated at load — a persona needs its keys fetched and a
    /// messaging profile registered, a relationship needs its profile, the TSP
    /// store is owned by the live messaging layer, and vetting holds in-flight
    /// protocol state beside what it persists. Changing those under a running
    /// session would leave the config describing something the runtime does
    /// not have, so they wait for the next launch.
    #[must_use]
    pub fn applies_live(self) -> bool {
        matches!(
            self,
            RecordKind::Membership
                | RecordKind::Contact
                | RecordKind::AgentName
                | RecordKind::VrcIssued
                | RecordKind::VrcReceived
        )
    }

    /// A short human name, for the activity log.
    #[must_use]
    pub fn noun(self) -> &'static str {
        match self {
            RecordKind::Persona => "persona",
            RecordKind::Membership => "community membership",
            RecordKind::Relationship => "relationship",
            RecordKind::Contact => "contact",
            RecordKind::AgentName => "agent name",
            RecordKind::Tsp => "TSP relationship",
            RecordKind::VrcIssued | RecordKind::VrcReceived => "relationship credential",
            RecordKind::Key => "key reference",
            RecordKind::Vetting => "vetting state",
        }
    }
}

/// A stable, fixed-length key segment for an identifier.
fn h(id: &str) -> String {
    hex::encode(&Sha256::digest(id.as_bytes())[..16])
}

fn persona_key(p: &PersonaRecord) -> String {
    format!("{}{}", RecordKind::Persona.prefix(), p.persona_id)
}

fn membership_key(c: &CommunityRecord) -> String {
    format!(
        "{}{}/{}",
        RecordKind::Membership.prefix(),
        h(&c.vtc_did),
        c.persona_ref
    )
}

fn simple_key(kind: RecordKind, id: &str) -> String {
    format!("{}{}", kind.prefix(), h(id))
}

fn vrc_key(kind: RecordKind, remote: &str, id: &str) -> String {
    format!("{}{}/{}", kind.prefix(), h(remote), h(id))
}

/// The synced parts of a config, borrowed.
///
/// `account` is separate from `private` because at runtime the live account is
/// [`crate::config::Config::account`], and the copy in the protected tier is
/// only refreshed on save.
pub struct SyncView<'a> {
    /// The live account.
    pub account: &'a Account,
    /// The protected tier.
    pub private: &'a ProtectedConfig,
    /// Key references (the secured tier's `key_info`).
    pub key_info: &'a HashMap<String, KeyInfoConfig>,
}

/// The synced parts of a config, mutably — what [`apply`] writes into.
pub struct SyncParts<'a> {
    /// The live account.
    pub account: &'a mut Account,
    /// The protected tier.
    pub private: &'a mut ProtectedConfig,
    /// Key references (the secured tier's `key_info`).
    pub key_info: &'a mut HashMap<String, KeyInfoConfig>,
}

impl SyncParts<'_> {
    /// A read-only view of the same parts.
    #[must_use]
    pub fn view(&self) -> SyncView<'_> {
        SyncView {
            account: self.account,
            private: self.private,
            key_info: self.key_info,
        }
    }
}

/// Serialize, or `None` if a value will not serialize (which none of these
/// types fail at; an `Option` keeps a surprise from taking the sync down).
fn to_json<T: serde::Serialize>(v: &T) -> Option<Value> {
    serde_json::to_value(v).ok()
}

/// The vetting book as synced: everything it persists except the hidden
/// vetter engine, whose snapshots carry the key every tag derives from. App
/// state is not for secrets.
fn vetting_json(book: &VettingBook) -> Option<Value> {
    let mut v = to_json(book)?;
    if let Value::Object(map) = &mut v {
        map.remove("hidden_vetter");
        if map.is_empty() {
            return None;
        }
    }
    Some(v)
}

fn vrc_records(kind: RecordKind, vrcs: &Vrcs, out: &mut BTreeMap<String, Value>) {
    for (remote, by_id) in vrcs.keys().zip(vrcs.values()) {
        for (id, vrc) in by_id {
            if let Some(credential) = to_json(vrc.as_ref()) {
                out.insert(
                    vrc_key(kind, remote, id),
                    json!({ "remote": remote.as_str(), "id": id.as_str(), "credential": credential }),
                );
            }
        }
    }
}

/// Every synced record of `view`, keyed by record key.
#[must_use]
pub fn project(view: &SyncView<'_>) -> BTreeMap<String, Value> {
    let mut out = BTreeMap::new();

    for p in view.account.personas.values() {
        if let Some(v) = to_json(p) {
            out.insert(persona_key(p), v);
        }
    }
    for c in view.account.memberships() {
        if let Some(v) = to_json(c) {
            out.insert(membership_key(c), v);
        }
    }
    for (p_did, r) in &view.private.relationships.relationships {
        if let Some(r) = to_json(r) {
            out.insert(
                simple_key(RecordKind::Relationship, p_did),
                json!({ "pDid": p_did.as_str(), "relationship": r }),
            );
        }
    }
    for c in view.private.contacts.contacts.values() {
        if let Some(v) = to_json(c.as_ref()) {
            out.insert(simple_key(RecordKind::Contact, &c.did), v);
        }
    }
    for (did, entry) in &view.private.agent_names {
        if entry.name.is_some()
            && let Some(e) = to_json(entry)
        {
            out.insert(
                simple_key(RecordKind::AgentName, did),
                json!({ "did": did, "entry": e }),
            );
        }
    }
    for (k, v) in view.private.tsp_relationships.entries() {
        out.insert(
            simple_key(RecordKind::Tsp, k),
            json!({ "key": k, "value": v }),
        );
    }
    vrc_records(RecordKind::VrcIssued, &view.private.vrcs_issued, &mut out);
    vrc_records(
        RecordKind::VrcReceived,
        &view.private.vrcs_received,
        &mut out,
    );
    for (name, info) in view.key_info {
        if matches!(info.path, KeySourceMaterial::VtaManaged { .. })
            && let Some(i) = to_json(info)
        {
            out.insert(
                simple_key(RecordKind::Key, name),
                json!({ "name": name, "info": i }),
            );
        }
    }
    if let Some(v) = vetting_json(&view.private.vetting) {
        out.insert(RecordKind::Vetting.prefix().to_string(), v);
    }
    out
}

fn str_field<'v>(v: &'v Value, field: &str) -> Result<&'v str, String> {
    v.get(field)
        .and_then(Value::as_str)
        .ok_or_else(|| format!("missing `{field}`"))
}

fn decode<T: serde::de::DeserializeOwned>(v: &Value) -> Result<T, String> {
    serde_json::from_value(v.clone()).map_err(|e| e.to_string())
}

/// Write one record into `parts`: `Some` inserts or replaces it, `None`
/// removes whatever local item the key names.
///
/// # Errors
///
/// A value that does not decode as its kind. Nothing is changed in that case.
pub fn apply(parts: &mut SyncParts<'_>, key: &str, value: Option<&Value>) -> Result<(), String> {
    let Some(kind) = RecordKind::of_key(key) else {
        return Err("unknown record kind".to_string());
    };
    match kind {
        RecordKind::Persona => match value {
            Some(v) => {
                let p: PersonaRecord = decode(v)?;
                if persona_key(&p) != key {
                    return Err("persona id does not match its key".to_string());
                }
                parts.account.personas.insert(p.persona_id, p);
            }
            None => parts.account.personas.retain(|_, p| persona_key(p) != key),
        },
        RecordKind::Membership => {
            let incoming: Option<CommunityRecord> = value.map(decode).transpose()?;
            if let Some(c) = &incoming
                && membership_key(c) != key
            {
                return Err("membership does not match its key".to_string());
            }
            for list in parts.account.communities.values_mut() {
                list.retain(|c| membership_key(c) != key);
            }
            if let Some(c) = incoming {
                parts
                    .account
                    .communities
                    .entry(c.vtc_did.clone())
                    .or_default()
                    .push(c);
            }
            parts.account.communities.retain(|_, list| !list.is_empty());
        }
        RecordKind::Relationship => match value {
            Some(v) => {
                let p_did = str_field(v, "pDid")?;
                if simple_key(kind, p_did) != key {
                    return Err("relationship does not match its key".to_string());
                }
                let r: Relationship = decode(v.get("relationship").unwrap_or(&Value::Null))?;
                parts
                    .private
                    .relationships
                    .relationships
                    .insert(Arc::new(p_did.to_string()), r);
            }
            None => parts
                .private
                .relationships
                .relationships
                .retain(|p_did, _| simple_key(kind, p_did) != key),
        },
        RecordKind::Contact => {
            let incoming: Option<Contact> = value.map(decode).transpose()?;
            if let Some(c) = &incoming
                && simple_key(kind, &c.did) != key
            {
                return Err("contact does not match its key".to_string());
            }
            let contacts = &mut parts.private.contacts;
            contacts
                .contacts
                .retain(|did, _| simple_key(kind, did) != key);
            if let Some(c) = incoming {
                contacts.contacts.insert(c.did.clone(), Arc::new(c));
            }
            contacts.aliases = contacts
                .contacts
                .values()
                .filter_map(|c| c.alias.clone().map(|a| (a, c.clone())))
                .collect();
        }
        RecordKind::AgentName => match value {
            Some(v) => {
                let did = str_field(v, "did")?;
                if simple_key(kind, did) != key {
                    return Err("agent name does not match its key".to_string());
                }
                let entry: CachedAgentName = decode(v.get("entry").unwrap_or(&Value::Null))?;
                parts.private.agent_names.insert(did.to_string(), entry);
            }
            None => parts
                .private
                .agent_names
                .retain(|did, e| e.name.is_none() || simple_key(kind, did) != key),
        },
        RecordKind::Tsp => match value {
            Some(v) => {
                let k = str_field(v, "key")?;
                if simple_key(kind, k) != key {
                    return Err("TSP row does not match its key".to_string());
                }
                let row = str_field(v, "value")?;
                parts
                    .private
                    .tsp_relationships
                    .entries_mut()
                    .insert(k.to_string(), row.to_string());
            }
            None => parts
                .private
                .tsp_relationships
                .entries_mut()
                .retain(|k, _| simple_key(kind, k) != key),
        },
        RecordKind::VrcIssued | RecordKind::VrcReceived => {
            let vrcs = if kind == RecordKind::VrcIssued {
                &mut parts.private.vrcs_issued
            } else {
                &mut parts.private.vrcs_received
            };
            apply_vrc(vrcs, kind, key, value)?;
        }
        RecordKind::Key => match value {
            Some(v) => {
                let name = str_field(v, "name")?;
                if simple_key(kind, name) != key {
                    return Err("key reference does not match its key".to_string());
                }
                let info: KeyInfoConfig = decode(v.get("info").unwrap_or(&Value::Null))?;
                // Only a reference ever arrives this way. A record claiming to
                // carry key material is refused, never stored as a secret.
                if !matches!(info.path, KeySourceMaterial::VtaManaged { .. }) {
                    return Err("a synced key must be VTA-managed".to_string());
                }
                parts.key_info.insert(name.to_string(), info);
            }
            None => parts.key_info.retain(|name, info| {
                !matches!(info.path, KeySourceMaterial::VtaManaged { .. })
                    || simple_key(kind, name) != key
            }),
        },
        RecordKind::Vetting => {
            // The hidden vetter is never synced; keep this install's.
            let hidden = std::mem::take(&mut parts.private.vetting.hidden_vetter);
            let mut book: VettingBook = match value {
                Some(v) => decode(v)?,
                None => VettingBook::default(),
            };
            book.hidden_vetter = hidden;
            parts.private.vetting = book;
        }
    }
    Ok(())
}

/// Insert or remove one VRC. `Vrcs` keeps its map private and re-checks
/// conformance on decode, so the change goes through its JSON form — which is
/// also what keeps a non-conformant credential from slipping in this way.
fn apply_vrc(
    vrcs: &mut Vrcs,
    kind: RecordKind,
    key: &str,
    value: Option<&Value>,
) -> Result<(), String> {
    let mut whole = to_json(vrcs).ok_or("credentials will not serialize")?;
    let map = whole
        .as_object_mut()
        .and_then(|o| o.entry("vrcs").or_insert_with(|| json!({})).as_object_mut())
        .ok_or("unexpected credential store shape")?;
    for (remote, by_id) in map.iter_mut() {
        if let Some(by_id) = by_id.as_object_mut() {
            by_id.retain(|id, _| vrc_key(kind, remote, id) != key);
        }
    }
    if let Some(v) = value {
        let remote = str_field(v, "remote")?;
        let id = str_field(v, "id")?;
        if vrc_key(kind, remote, id) != key {
            return Err("credential does not match its key".to_string());
        }
        let credential = v.get("credential").cloned().unwrap_or(Value::Null);
        map.entry(remote.to_string())
            .or_insert_with(|| json!({}))
            .as_object_mut()
            .ok_or("unexpected credential store shape")?
            .insert(id.to_string(), credential);
    }
    map.retain(|_, by_id| by_id.as_object().is_none_or(|o| !o.is_empty()));
    *vrcs = decode(&whole)?;
    Ok(())
}