agentmux_srv_core/backend/user_sync/
keys.rs1use 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
33pub trait KeyStore {
35 fn get(&self, collection: &str, epoch: u32) -> Option<Key>;
36 fn put(&self, collection: &str, epoch: u32, key: &Key) -> bool;
38 fn epochs(&self, collection: &str) -> Vec<u32>;
40 fn forget(&self, collection: &str, epoch: u32);
42}
43
44pub 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
72pub 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
83pub 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
99pub 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
105pub 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
111pub 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}