Skip to main content

agentmux_srv_core/backend/user_sync/
keys.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A collection's keys on a machine, and how they reach another member (SPEC_USER_DATA_SYNC_LAYER ยง3.1). A collection
5//! has one key for each key epoch it has been in. A key is made on the machine that founds the collection or removes a
6//! member, kept by a [`KeyStore`], and handed to another member sealed to that member's box key (the key its install
7//! offers for sealing, derived from its WAN seed and signed into the membership chain), one sealed key for each epoch,
8//! so a new member can open what was written before it joined. A key is never sent unsealed, and a machine that is not
9//! a current member is given none.
10//!
11//! The Kanban's keys are kept in the shared store beside the board they protect ([`SqlKeys`]). A collection with
12//! secrets of its own (a Vault) supplies a [`KeyStore`] that keeps its keys under its own protection.
13
14use rusqlite::{params, Connection, OptionalExtension};
15use zeroize::Zeroizing;
16
17use agentmux_common::jekt_sign::wan_key_fingerprint;
18
19use super::members::Subject;
20use super::ops::KeyDelivery;
21use super::seal::{self, KeyRing};
22use crate::backend::jekt_seal::{self, Recipient};
23use crate::backend::vault::seal::Key;
24
25pub(crate) const SCHEMA: &str = "
26    CREATE TABLE IF NOT EXISTS db_sync_keys (
27        collection TEXT NOT NULL,
28        epoch      INTEGER NOT NULL,
29        key        BLOB NOT NULL,
30        PRIMARY KEY (collection, epoch)
31    );";
32
33/// Where a machine keeps the keys of the collections it is a member of.
34pub trait KeyStore {
35    fn get(&self, collection: &str, epoch: u32) -> Option<Key>;
36    /// Keeps the key for an epoch. An epoch that already has a key keeps it: false if it could not be kept.
37    fn put(&self, collection: &str, epoch: u32, key: &Key) -> bool;
38    /// The epochs a key is held for, lowest first.
39    fn epochs(&self, collection: &str) -> Vec<u32>;
40    /// Forgets the key of an epoch.
41    fn forget(&self, collection: &str, epoch: u32);
42}
43
44/// Keys kept in the shared store, for collections whose data is in that store anyway.
45pub struct SqlKeys<'a>(pub &'a Connection);
46
47impl KeyStore for SqlKeys<'_> {
48    fn get(&self, collection: &str, epoch: u32) -> Option<Key> {
49        let bytes: Option<Vec<u8>> =
50            self.0.query_row("SELECT key FROM db_sync_keys WHERE collection = ?1 AND epoch = ?2", params![collection, epoch], |r| r.get(0)).optional().ok()?;
51        let array: [u8; 32] = bytes?.try_into().ok()?;
52        Some(Zeroizing::new(array))
53    }
54
55    fn put(&self, collection: &str, epoch: u32, key: &Key) -> bool {
56        self.0
57            .execute("INSERT OR IGNORE INTO db_sync_keys (collection, epoch, key) VALUES (?1, ?2, ?3)", params![collection, epoch, key.as_slice()])
58            .is_ok()
59    }
60
61    fn forget(&self, collection: &str, epoch: u32) {
62        let _ = self.0.execute("DELETE FROM db_sync_keys WHERE collection = ?1 AND epoch = ?2", params![collection, epoch]);
63    }
64
65    fn epochs(&self, collection: &str) -> Vec<u32> {
66        let Ok(mut stmt) = self.0.prepare("SELECT epoch FROM db_sync_keys WHERE collection = ?1 ORDER BY epoch") else { return Vec::new() };
67        let rows = stmt.query_map(params![collection], |r| r.get::<_, u32>(0));
68        rows.map(|rows| rows.filter_map(Result::ok).collect()).unwrap_or_default()
69    }
70}
71
72/// The keys a machine holds for a collection, one per epoch, to seal and open records with.
73pub fn ring(store: &dyn KeyStore, collection: &str) -> KeyRing {
74    let mut ring = KeyRing::new();
75    for epoch in store.epochs(collection) {
76        if let Some(key) = store.get(collection, epoch) {
77            ring.insert(epoch, key);
78        }
79    }
80    ring
81}
82
83/// Makes and keeps the key for an epoch if there is none: false if it could not be made or kept.
84pub fn mint(store: &dyn KeyStore, collection: &str, epoch: u32) -> bool {
85    if store.get(collection, epoch).is_some() {
86        return true;
87    }
88    seal::generate_key().is_some_and(|key| store.put(collection, epoch, &key))
89}
90
91fn unhex32(s: &str) -> Option<[u8; 32]> {
92    super::members::unhex32(s)
93}
94
95fn place(epoch: u32) -> String {
96    format!("epoch-{epoch}")
97}
98
99/// `key` sealed to a member's box key, for this collection and epoch only: it opens nowhere else.
100pub fn seal_to(key: &Key, collection: &str, epoch: u32, to: &Subject) -> Option<String> {
101    let recipient = Recipient { key: unhex32(&to.box_key)?, key_fp: wan_key_fingerprint(&to.public()?) };
102    jekt_seal::wrap(key, &recipient, collection, &place(epoch))
103}
104
105/// The key a sealed one holds, opened with this install's WAN seed; none if it was sealed to another key, for another
106/// collection or epoch, or altered.
107pub fn open_sealed(sealed: &str, wan_public: &[u8; 32], wan_seed: &[u8; 32], collection: &str, epoch: u32) -> Option<Key> {
108    jekt_seal::unwrap(sealed, wan_public, wan_seed, collection, &place(epoch)).ok().map(Zeroizing::new)
109}
110
111/// This install's side of key delivery over a [`KeyStore`]: seals what it holds to a member, makes the key of a new
112/// epoch, and opens keys another member sealed to it.
113pub struct StoreKeys<'a> {
114    pub store: &'a dyn KeyStore,
115    pub wan_public: [u8; 32],
116    pub wan_seed: [u8; 32],
117}
118
119impl KeyDelivery for StoreKeys<'_> {
120    fn keys_for(&self, collection: &str, to: &Subject) -> Vec<(u32, String)> {
121        self.store.epochs(collection).into_iter().filter_map(|e| Some((e, seal_to(&self.store.get(collection, e)?, collection, e, to)?))).collect()
122    }
123
124    fn mint(&self, collection: &str, epoch: u32) -> bool {
125        mint(self.store, collection, epoch)
126    }
127
128    fn discard(&self, collection: &str, epoch: u32) {
129        self.store.forget(collection, epoch);
130    }
131
132    fn held(&self, collection: &str) -> Vec<u32> {
133        self.store.epochs(collection)
134    }
135
136    fn ring(&self, collection: &str) -> KeyRing {
137        ring(self.store, collection)
138    }
139
140    fn take(&self, collection: &str, keys: &[(u32, String)]) -> usize {
141        keys.iter()
142            .filter(|(epoch, sealed)| {
143                open_sealed(sealed, &self.wan_public, &self.wan_seed, collection, *epoch).is_some_and(|key| self.store.put(collection, *epoch, &key))
144            })
145            .count()
146    }
147}