Skip to main content

second_brain_core/keys/
wiring.rs

1use std::collections::BTreeSet;
2
3use anyhow::Result;
4use rusqlite::params;
5
6use super::identity::{Envelope, Epoch, IdentityTag};
7use crate::sqlite_store::SqliteStore;
8
9impl SqliteStore {
10    /// Commits the epochs and envelopes with the WAL synced to disk, so the
11    /// caller may delete the only other copy of a key once this returns.
12    /// Rows already stored are kept as they are.
13    pub fn put_keys_durably(
14        &self,
15        tag: &IdentityTag,
16        epochs: &[Epoch],
17        envelopes: &[Envelope],
18        created_at: i64,
19    ) -> Result<()> {
20        self.with_durable_txn(|tx| {
21            for epoch in epochs {
22                tx.execute(
23                    "INSERT OR IGNORE INTO key_epochs (identity_tag, epoch, key_id, cause, created_at) \
24                     VALUES (?1, ?2, ?3, NULL, ?4)",
25                    params![tag.as_str(), epoch.number, epoch.key_id.to_string(), created_at],
26                )?;
27            }
28            for envelope in envelopes {
29                tx.execute(
30                    "INSERT OR IGNORE INTO key_envelopes \
31                     (identity_tag, epoch, key_id, recipient, machine_id, envelope) \
32                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
33                    params![
34                        envelope.identity_tag.as_str(),
35                        envelope.epoch.number,
36                        envelope.epoch.key_id.to_string(),
37                        envelope.recipient,
38                        envelope.machine_id,
39                        envelope.ciphertext,
40                    ],
41                )?;
42            }
43            Ok(())
44        })
45    }
46
47    /// This device's identity, named by its own device record, and the
48    /// envelopes of that identity wrapped to `recipient`. None until the
49    /// store holds the record.
50    pub fn own_identity_envelopes(
51        &self,
52        recipient: &str,
53    ) -> Result<Option<(IdentityTag, Vec<Envelope>)>> {
54        let own = self.machine_id();
55        let Some(row) = self.device_record(own)? else {
56            return Ok(None);
57        };
58        let tag = IdentityTag::from(row.current.record.identity_tag);
59        let envelopes = self
60            .envelopes_for_machine(own)?
61            .into_iter()
62            .filter(|e| e.identity_tag == tag && e.recipient == recipient)
63            .collect();
64        Ok(Some((tag, envelopes)))
65    }
66
67    /// Returns false when no envelope was stored for that epoch and
68    /// recipient.
69    pub fn delete_envelope(
70        &self,
71        tag: &IdentityTag,
72        epoch: &Epoch,
73        recipient: &str,
74    ) -> Result<bool> {
75        let deleted = self.conn().execute(
76            "DELETE FROM key_envelopes \
77             WHERE identity_tag = ?1 AND epoch = ?2 AND key_id = ?3 AND recipient = ?4",
78            params![
79                tag.as_str(),
80                epoch.number,
81                epoch.key_id.to_string(),
82                recipient
83            ],
84        )?;
85        Ok(deleted > 0)
86    }
87
88    /// Every other machine this store has synced with or holds records
89    /// from: sync cursor keys (with any `push:` prefix removed) and the
90    /// origins in the sync log.
91    pub fn known_peer_ids(&self) -> Result<BTreeSet<String>> {
92        let conn = self.reader();
93        let mut ids = BTreeSet::new();
94        let mut cursors = conn.prepare("SELECT peer_id FROM sync_state")?;
95        for peer in cursors.query_map([], |r| r.get::<_, String>(0))? {
96            let peer = peer?;
97            ids.insert(peer.strip_prefix("push:").unwrap_or(&peer).to_string());
98        }
99        let mut origins = conn.prepare("SELECT DISTINCT origin_machine_id FROM sync_log")?;
100        for origin in origins.query_map([], |r| r.get::<_, String>(0))? {
101            ids.insert(origin?);
102        }
103        ids.remove(self.machine_id());
104        Ok(ids)
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use chrono::Utc;
111
112    use crate::keys::{DeviceKeys, IdentityKey, wrap};
113    use crate::schema::SyncState;
114    use crate::sqlite_store::SqliteStore;
115    use crate::store::StoreAdmin;
116
117    use super::*;
118
119    #[test]
120    fn durable_keys_are_stored_once_and_the_writer_returns_to_normal_sync() {
121        let store = SqliteStore::in_memory("local".to_string()).unwrap();
122        let device = DeviceKeys::generate().unwrap();
123        let key = IdentityKey::generate().unwrap();
124        let tag = IdentityTag::migrated(&key.key_id());
125        let envelope = wrap(&key, 0, &tag, &device.age_recipient(), Some("local".into())).unwrap();
126        for _ in 0..2 {
127            store
128                .put_keys_durably(&tag, &[envelope.epoch], std::slice::from_ref(&envelope), 7)
129                .unwrap();
130        }
131        assert_eq!(store.key_epochs(&tag).unwrap().len(), 1);
132        assert_eq!(
133            store.envelopes_for_machine("local").unwrap(),
134            vec![envelope]
135        );
136        let mode: i64 = store
137            .conn()
138            .query_row("PRAGMA synchronous", [], |r| r.get(0))
139            .unwrap();
140        assert_eq!(mode, 1, "synchronous must be back to NORMAL");
141    }
142
143    #[test]
144    fn an_envelope_is_deleted_for_its_recipient_alone() {
145        let store = SqliteStore::in_memory("local".to_string()).unwrap();
146        let key = IdentityKey::generate().unwrap();
147        let tag = IdentityTag::migrated(&key.key_id());
148        let mine = DeviceKeys::generate().unwrap().age_recipient();
149        let peer = DeviceKeys::generate().unwrap().age_recipient();
150        let own = wrap(&key, 0, &tag, &mine, Some("local".into())).unwrap();
151        let theirs = wrap(&key, 0, &tag, &peer, Some("peer".into())).unwrap();
152        store.put_envelope(&own).unwrap();
153        store.put_envelope(&theirs).unwrap();
154        assert!(
155            store
156                .delete_envelope(&tag, &theirs.epoch, &peer.to_string())
157                .unwrap()
158        );
159        assert!(
160            !store
161                .delete_envelope(&tag, &theirs.epoch, &peer.to_string())
162                .unwrap()
163        );
164        assert_eq!(store.envelopes_for_machine("local").unwrap(), vec![own]);
165        assert!(store.envelopes_for_machine("peer").unwrap().is_empty());
166    }
167
168    #[test]
169    fn known_peers_come_from_cursors_and_log_origins_but_never_this_machine() {
170        let store = SqliteStore::in_memory("local".to_string()).unwrap();
171        for peer in ["pi", "push:mac", "local"] {
172            store
173                .set_sync_state(&SyncState {
174                    peer_id: peer.to_string(),
175                    last_seq: 1,
176                    last_sync_at: Utc::now(),
177                })
178                .unwrap();
179        }
180        store
181            .conn()
182            .execute(
183                "INSERT INTO sync_log (id, local_seq, origin_machine_id, origin_seq, op, node_type, \
184                 node_id, timestamp) VALUES ('l1', 1, 'laptop', 1, 'create', 'memory', 'n', \
185                 '2026-01-01T00:00:00Z')",
186                [],
187            )
188            .unwrap();
189        let ids: Vec<String> = store.known_peer_ids().unwrap().into_iter().collect();
190        assert_eq!(ids, vec!["laptop", "mac", "pi"]);
191    }
192}