1use ring::hmac;
18use rusqlite::{params, Connection, OptionalExtension};
19use zeroize::Zeroizing;
20
21use super::seal::{self, Key};
22use super::sync_capture_kinds as kinds;
23use super::sync_links;
24use super::sync_record::{stays_here, EntryBody, Profiles};
25use super::sync_store::links_of;
26use crate::backend::storage::store::Store;
27use crate::backend::storage::vault::VaultRow;
28use crate::backend::user_sync::log::{self, Signer};
29use crate::backend::user_sync::seal::KeyRing;
30
31pub const KIND: &str = "vault";
33
34const SCHEMA: &str = "
37 CREATE TABLE IF NOT EXISTS db_sync_vault_seen (
38 entry_id TEXT PRIMARY KEY,
39 vault TEXT NOT NULL,
40 record TEXT NOT NULL,
41 hash TEXT NOT NULL
42 );
43 -- Records the log holds that the store could not take (an error, or a kind this version does not know yet): taken again
44 -- from the log by `Taker::retake`, because a record the log holds is never sent again.
45 CREATE TABLE IF NOT EXISTS db_sync_vault_retake (
46 vault TEXT NOT NULL,
47 record TEXT NOT NULL,
48 -- Why the other side of a conflict was kept, when the record won one: the retake keeps it the same way.
49 kept TEXT,
50 PRIMARY KEY (vault, record)
51 );
52 -- Records this machine no longer writes an entry under (it follows another machine's, see `sync_take`): ended with a
53 -- tombstone by the next capture.
54 CREATE TABLE IF NOT EXISTS db_sync_vault_ended (
55 vault TEXT NOT NULL,
56 record TEXT NOT NULL,
57 PRIMARY KEY (vault, record)
58 );";
59
60pub fn init(conn: &Connection) -> rusqlite::Result<()> {
62 log::init(conn)?;
63 conn.execute_batch(SCHEMA)?;
64 conn.execute_batch(kinds::SCHEMA)
65}
66
67#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
69pub struct Captured {
70 pub written: usize,
72 pub tombstoned: usize,
74 pub lines: usize,
76 pub grants: usize,
78}
79
80pub use crate::backend::user_sync::seal::sealer;
84
85fn digest(key: &Key, body: &[u8]) -> String {
89 let mut ctx = hmac::Context::with_key(&hmac::Key::new(hmac::HMAC_SHA256, &key[..]));
90 ctx.update(b"agentmux-vault-sync-seen-v1\0");
91 ctx.update(body);
92 ctx.sign().as_ref().iter().map(|b| format!("{b:02x}")).collect()
93}
94
95pub(super) fn body_of(store: &Store, row: &VaultRow, key: &Key, profiles: &dyn Profiles) -> Result<Zeroizing<Vec<u8>>, String> {
98 let parts = seal::open(key, &row.id, &row.sealed)?;
99 let body = EntryBody::of_row(row, &parts, profiles).with_link_ids(links_of(store, &row.id)?.ids());
100 Ok(Zeroizing::new(serde_json::to_vec(&body).map_err(|e| e.to_string())?))
101}
102
103pub(super) fn mark_seen(store: &Store, row: &VaultRow, record: &str, key: &Key, profiles: &dyn Profiles) -> Result<(), String> {
107 let hash = digest(key, &body_of(store, row, key, profiles)?);
108 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
109 conn.execute("INSERT OR REPLACE INTO db_sync_vault_seen (entry_id, vault, record, hash) VALUES (?1, ?2, ?3, ?4)", params![row.id, row.vault_id, record, hash]).map_err(|e| e.to_string())?;
110 Ok(())
111}
112
113pub(super) fn retake_mark(store: &Store, vault: &str, record: &str, kept: Option<&str>) -> Result<(), String> {
116 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
117 conn.execute("INSERT OR IGNORE INTO db_sync_vault_retake (vault, record, kept) VALUES (?1, ?2, ?3)", params![vault, record, kept]).map_err(|e| e.to_string())?;
118 Ok(())
119}
120
121pub(super) fn retake_clear(store: &Store, vault: &str, record: &str) -> Result<(), String> {
123 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
124 conn.execute("DELETE FROM db_sync_vault_retake WHERE vault = ?1 AND record = ?2", params![vault, record]).map_err(|e| e.to_string())?;
125 Ok(())
126}
127
128pub(super) fn retake_pending(store: &Store, vault: &str) -> Result<Vec<(String, Option<String>)>, String> {
130 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
131 let mut stmt = conn.prepare("SELECT record, kept FROM db_sync_vault_retake WHERE vault = ?1 ORDER BY rowid").map_err(|e| e.to_string())?;
132 let rows = stmt.query_map(params![vault], |r| Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?))).map_err(|e| e.to_string())?;
133 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
134}
135
136fn records_written(store: &Store) -> Result<std::collections::HashMap<String, String>, String> {
138 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
139 let mut stmt = conn.prepare("SELECT entry_id, record FROM db_sync_vault_seen").map_err(|e| e.to_string())?;
140 let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(|e| e.to_string())?;
141 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())
142}
143
144pub(super) fn identity_of(store: &Store, entry_id: &str) -> Result<Option<(String, String)>, String> {
147 {
148 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
149 if let Some(s) = seen_of(&conn, entry_id).map_err(|e| e.to_string())? {
150 return Ok(Some((s.vault, s.record)));
151 }
152 }
153 Ok(store.vault_link_primary(entry_id).map_err(|e| e.to_string())?.map(|p| (String::new(), p)))
154}
155
156pub(super) fn end_record(store: &Store, vault: &str, record: &str) -> Result<(), String> {
158 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
159 conn.execute("INSERT OR IGNORE INTO db_sync_vault_ended (vault, record) VALUES (?1, ?2)", params![vault, record]).map_err(|e| e.to_string())?;
160 Ok(())
161}
162
163pub(super) fn forget(store: &Store, entry_id: &str) -> Result<(), String> {
165 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
166 conn.execute("DELETE FROM db_sync_vault_seen WHERE entry_id = ?1", params![entry_id]).map_err(|e| e.to_string())?;
167 Ok(())
168}
169
170struct Seen {
171 vault: String,
172 record: String,
173 hash: String,
174}
175
176fn seen_of(conn: &Connection, entry_id: &str) -> rusqlite::Result<Option<Seen>> {
177 conn.query_row("SELECT vault, record, hash FROM db_sync_vault_seen WHERE entry_id = ?1", params![entry_id], |r| {
178 Ok(Seen { vault: r.get(0)?, record: r.get(1)?, hash: r.get(2)? })
179 })
180 .optional()
181}
182
183pub(super) fn tombstone(conn: &Connection, signer: &mut Signer, collection: &str, record: &str, now_ms: i64) -> Result<bool, String> {
185 match log::current(conn, collection, record).map_err(|e| e.to_string())? {
186 Some(cur) if !cur.header.tombstone => {
187 log::append_local(conn, signer, collection, record, Vec::new(), true, now_ms).map_err(|e| format!("{e:?}"))?;
188 Ok(true)
189 }
190 _ => Ok(false),
191 }
192}
193
194struct Pending {
196 entry_id: String,
197 record: String,
198 body: Zeroizing<Vec<u8>>,
200 hash: String,
201}
202
203pub fn capture(store: &Store, signer: &mut Signer, vault_id: &str, ring: &KeyRing, key: &Key, profiles: &dyn Profiles, now_ms: i64) -> Result<Captured, String> {
206 let more = kinds::read(store, vault_id)?;
209 let all: Vec<_> = store.vault_list().map_err(|e| e.to_string())?.into_iter().filter(|r| r.vault_id == vault_id).collect();
210 let here: std::collections::HashSet<&str> = all.iter().map(|r| r.id.as_str()).collect();
211 let rows: Vec<_> = all.iter().filter(|r| !stays_here(r, profiles)).cloned().collect();
212 let ids: Vec<&str> = rows.iter().map(|r| r.id.as_str()).collect();
213 let link_of = super::link_ids(store, &ids)?;
214 let written_as = records_written(store)?;
215 let mut pending = Vec::new();
216 for row in &rows {
217 let Some(record) = written_as.get(&row.id).or_else(|| link_of.get(&row.id)) else { continue };
220 if !sync_links::is_link_id(record) {
221 continue;
222 }
223 let body = body_of(store, row, key, profiles)?;
224 let hash = digest(key, &body);
225 pending.push(Pending { entry_id: row.id.clone(), record: record.clone(), body, hash });
226 }
227 let now_here: std::collections::HashSet<&str> = rows.iter().map(|r| r.id.as_str()).collect();
228
229 let conn = store.conn().lock().unwrap_or_else(|e| e.into_inner());
230 let mut out = Captured::default();
231 log::ensure_collection(&conn, vault_id, KIND, now_ms).map_err(|e| e.to_string())?;
232 let mut ended = conn.prepare("SELECT record FROM db_sync_vault_ended WHERE vault = ?1").map_err(|e| e.to_string())?;
234 let ended: Vec<String> = ended.query_map(params![vault_id], |r| r.get(0)).map_err(|e| e.to_string())?.collect::<Result<_, _>>().map_err(|e| e.to_string())?;
235 for record in ended {
236 if tombstone(&conn, signer, vault_id, &record, now_ms)? {
237 out.tombstoned += 1;
238 }
239 conn.execute("DELETE FROM db_sync_vault_ended WHERE vault = ?1 AND record = ?2", params![vault_id, record]).map_err(|e| e.to_string())?;
240 }
241 for p in &pending {
242 let seen = seen_of(&conn, &p.entry_id).map_err(|e| e.to_string())?;
243 if seen.as_ref().is_some_and(|s| s.vault == vault_id && s.record == p.record && s.hash == p.hash) {
244 continue;
245 }
246 log::append_local_with(&conn, signer, vault_id, &p.record, false, now_ms, sealer(ring, &p.body)).map_err(|e| format!("{e:?}"))?;
247 out.written += 1;
248 if let Some(old) = seen.filter(|s| s.vault != vault_id) {
250 if tombstone(&conn, signer, &old.vault, &old.record, now_ms)? {
251 out.tombstoned += 1;
252 }
253 }
254 conn.execute(
255 "INSERT OR REPLACE INTO db_sync_vault_seen (entry_id, vault, record, hash) VALUES (?1, ?2, ?3, ?4)",
256 params![p.entry_id, vault_id, p.record, p.hash],
257 )
258 .map_err(|e| e.to_string())?;
259 }
260 let records: std::collections::HashMap<String, String> = pending.iter().map(|p| (p.entry_id.clone(), p.record.clone())).collect();
261 let wrote = kinds::write(&conn, signer, vault_id, ring, &more, &rows, &records, &here, now_ms)?;
262 out.lines = wrote.lines;
263 out.grants = wrote.grants;
264 out.tombstoned += wrote.tombstoned;
265 let mut stmt = conn.prepare("SELECT entry_id, record FROM db_sync_vault_seen WHERE vault = ?1").map_err(|e| e.to_string())?;
269 let was: Vec<(String, String)> = stmt.query_map(params![vault_id], |r| Ok((r.get(0)?, r.get(1)?))).map_err(|e| e.to_string())?.collect::<Result<_, _>>().map_err(|e| e.to_string())?;
270 drop(stmt);
271 for (entry_id, record) in was.into_iter().filter(|(e, _)| !now_here.contains(e.as_str())) {
272 let exists = conn.query_row("SELECT 1 FROM db_vault_entries WHERE id = ?1", params![entry_id], |_| Ok(())).optional().map_err(|e| e.to_string())?.is_some();
273 if exists {
274 continue;
275 }
276 if tombstone(&conn, signer, vault_id, &record, now_ms)? {
277 out.tombstoned += 1;
278 }
279 conn.execute("DELETE FROM db_sync_vault_seen WHERE entry_id = ?1", params![entry_id]).map_err(|e| e.to_string())?;
280 }
281 Ok(out)
282}
283
284#[cfg(test)]
285#[path = "sync_capture_tests.rs"]
286mod tests;