Skip to main content

second_brain_core/keys/
routes.rs

1use anyhow::{Result, bail};
2use rusqlite::{OptionalExtension, params};
3use serde::{Deserialize, Serialize};
4
5use crate::sqlite_store::SqliteStore;
6
7const ROUTE_PREFIX: &str = "device_route:";
8const LEGACY_PREFIX: &str = "legacy_route:";
9const PEERS_MIGRATED: &str = "sync_peers_migrated";
10const MAX_ADDRESSES: usize = 8;
11
12/// How to reach a device over ssh. Unsigned: a wrong address only fails
13/// the dial, since host keys are pinned per machine id.
14#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
15pub struct DeviceRoute {
16    pub machine_id: String,
17    #[serde(default)]
18    pub addresses: Vec<String>,
19    #[serde(default)]
20    pub ssh_login: Option<String>,
21    #[serde(default)]
22    pub ssh_port: Option<u16>,
23}
24
25/// A `sync-peers` line whose host answered with this device's id.
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct LegacyRoute {
28    pub host: String,
29    pub sb: String,
30}
31
32/// Names ssh is given as a host or login can't start with `-`, so none is
33/// ever read as an option.
34pub fn valid_address(address: &str) -> bool {
35    !address.is_empty()
36        && address.len() <= 253
37        && !address.starts_with('-')
38        && address
39            .chars()
40            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | ':' | '-' | '_' | '%'))
41}
42
43/// What a machine id must be before it goes into an ssh alias, an
44/// authorized_keys command or a thread name: 1 to 128 of A-Z a-z 0-9 . _ -.
45pub fn valid_machine_id(id: &str) -> bool {
46    (1..=128).contains(&id.len())
47        && id
48            .bytes()
49            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
50}
51
52pub fn valid_login(login: &str) -> bool {
53    !login.is_empty()
54        && login.len() <= 64
55        && !login.starts_with('-')
56        && login
57            .chars()
58            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
59}
60
61impl DeviceRoute {
62    /// Drops what could not be dialled safely and keeps the first few
63    /// addresses, in order, once each.
64    pub fn sanitized(mut self) -> Self {
65        let mut kept: Vec<String> = Vec::new();
66        for address in self.addresses {
67            if valid_address(&address) && !kept.contains(&address) {
68                kept.push(address);
69            }
70        }
71        kept.truncate(MAX_ADDRESSES);
72        self.addresses = kept;
73        self.ssh_login = self.ssh_login.filter(|login| valid_login(login));
74        self.ssh_port = self.ssh_port.filter(|port| *port != 0);
75        self
76    }
77
78    /// `other`'s addresses after this route's own, for a route a third
79    /// device relayed.
80    fn filled_from(mut self, other: DeviceRoute) -> Self {
81        self.addresses.extend(other.addresses);
82        self.ssh_login = self.ssh_login.or(other.ssh_login);
83        self.ssh_port = self.ssh_port.or(other.ssh_port);
84        self.sanitized()
85    }
86}
87
88impl SqliteStore {
89    pub fn device_route(&self, machine_id: &str) -> Result<Option<DeviceRoute>> {
90        let value: Option<String> = self
91            .reader()
92            .query_row(
93                "SELECT value FROM index_meta WHERE key = ?1",
94                params![format!("{ROUTE_PREFIX}{machine_id}")],
95                |r| r.get(0),
96            )
97            .optional()?;
98        Ok(value.and_then(|text| serde_json::from_str(&text).ok()))
99    }
100
101    pub fn device_routes(&self) -> Result<Vec<DeviceRoute>> {
102        let conn = self.reader();
103        let mut stmt =
104            conn.prepare("SELECT value FROM index_meta WHERE key >= ?1 AND key < ?2 ORDER BY key")?;
105        let rows = stmt.query_map(params![ROUTE_PREFIX, prefix_end(ROUTE_PREFIX)], |r| {
106            r.get::<_, String>(0)
107        })?;
108        let mut routes = Vec::new();
109        for row in rows {
110            if let Ok(route) = serde_json::from_str::<DeviceRoute>(&row?) {
111                routes.push(route);
112            }
113        }
114        Ok(routes)
115    }
116
117    /// Replaces what this store knows about reaching `route.machine_id`.
118    pub fn set_device_route(&self, route: DeviceRoute) -> Result<()> {
119        let route = route.sanitized();
120        if route.machine_id.is_empty() {
121            bail!("a device route needs a machine id");
122        }
123        self.conn().execute(
124            "INSERT OR REPLACE INTO index_meta (key, value) VALUES (?1, ?2)",
125            params![
126                format!("{ROUTE_PREFIX}{}", route.machine_id),
127                serde_json::to_string(&route)?
128            ],
129        )?;
130        Ok(())
131    }
132
133    /// Takes the routes a peer sent in its handshake: its own addresses go
134    /// first, ahead of those this store already knew for it, and one it
135    /// relays for a third device only adds to what this store already knows.
136    /// Routes to this device and to machines with no active row here are
137    /// ignored. True when anything changed.
138    pub fn merge_device_routes(&self, sender: &str, routes: &[DeviceRoute]) -> Result<bool> {
139        let own = self.machine_id();
140        let mut changed = false;
141        for route in routes {
142            let id = route.machine_id.as_str();
143            if id.is_empty()
144                || id == own
145                || !self.device_record(id)?.is_some_and(|row| !row.revoked)
146            {
147                continue;
148            }
149            let held = self.device_route(id)?;
150            let incoming = route.clone().sanitized();
151            let merged = match held.clone() {
152                Some(held) if id == sender => incoming.filled_from(held),
153                None if id == sender => incoming,
154                Some(held) => held.filled_from(incoming),
155                None => incoming,
156            };
157            if held.as_ref() != Some(&merged) {
158                self.set_device_route(merged)?;
159                changed = true;
160            }
161        }
162        Ok(changed)
163    }
164
165    pub fn legacy_routes(&self) -> Result<Vec<(String, LegacyRoute)>> {
166        let conn = self.reader();
167        let mut stmt = conn.prepare(
168            "SELECT key, value FROM index_meta WHERE key >= ?1 AND key < ?2 ORDER BY key",
169        )?;
170        let rows = stmt.query_map(params![LEGACY_PREFIX, prefix_end(LEGACY_PREFIX)], |r| {
171            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
172        })?;
173        let mut routes = Vec::new();
174        for row in rows {
175            let (key, value) = row?;
176            if let (Some(id), Ok(route)) = (
177                key.strip_prefix(LEGACY_PREFIX),
178                serde_json::from_str::<LegacyRoute>(&value),
179            ) {
180                routes.push((id.to_string(), route));
181            }
182        }
183        Ok(routes)
184    }
185
186    pub fn set_legacy_route(&self, machine_id: &str, route: &LegacyRoute) -> Result<()> {
187        self.conn().execute(
188            "INSERT OR REPLACE INTO index_meta (key, value) VALUES (?1, ?2)",
189            params![
190                format!("{LEGACY_PREFIX}{machine_id}"),
191                serde_json::to_string(route)?
192            ],
193        )?;
194        Ok(())
195    }
196
197    /// Set once every `sync-peers` line has been matched to a device, after
198    /// which the file is no longer read.
199    pub fn sync_peers_migrated(&self) -> Result<bool> {
200        let value: Option<String> = self
201            .reader()
202            .query_row(
203                "SELECT value FROM index_meta WHERE key = ?1",
204                params![PEERS_MIGRATED],
205                |r| r.get(0),
206            )
207            .optional()?;
208        Ok(value.is_some())
209    }
210
211    pub fn mark_sync_peers_migrated(&self) -> Result<()> {
212        self.conn().execute(
213            "INSERT OR REPLACE INTO index_meta (key, value) VALUES (?1, 'done')",
214            params![PEERS_MIGRATED],
215        )?;
216        Ok(())
217    }
218}
219
220fn prefix_end(prefix: &str) -> String {
221    format!("{};", prefix.trim_end_matches(':'))
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use crate::keys::{DeviceRecord, ensure_device_keys, found_identity};
228
229    fn store_with(rows: &[&str]) -> (SqliteStore, tempfile::TempDir) {
230        let dir = tempfile::tempdir().unwrap();
231        let store = SqliteStore::in_memory("self".to_string()).unwrap();
232        ensure_device_keys(&store, dir.path()).unwrap();
233        let device = crate::keys::load_device_keys(dir.path()).unwrap().unwrap();
234        let founded = found_identity(&store, &device, "self", &[], 1).unwrap();
235        for id in rows {
236            let other = crate::keys::DeviceKeys::generate().unwrap();
237            let record = DeviceRecord {
238                machine_id: id.to_string(),
239                identity_tag: founded.tag.as_str().to_string(),
240                version: 1,
241                name: id.to_string(),
242                age_recipient: other.age_recipient().to_string(),
243                ssh_public_key: other.ssh_public_key(),
244                signing_public_key: other.verifying_key().to_bytes(),
245                recovery_fingerprints: Vec::new(),
246                ssh_login: None,
247                ssh_port: None,
248                ssh_host_key: None,
249            };
250            crate::keys::admit_device(&store, &device, record).unwrap();
251        }
252        (store, dir)
253    }
254
255    fn route(id: &str, addresses: &[&str]) -> DeviceRoute {
256        DeviceRoute {
257            machine_id: id.to_string(),
258            addresses: addresses.iter().map(|a| a.to_string()).collect(),
259            ssh_login: Some("me".to_string()),
260            ssh_port: Some(22),
261        }
262    }
263
264    #[test]
265    fn a_senders_own_addresses_go_first_and_a_relayed_route_only_adds() {
266        let (store, _dir) = store_with(&["a", "b"]);
267        assert!(
268            store
269                .merge_device_routes(
270                    "a",
271                    &[route("a", &["192.0.2.1"]), route("b", &["192.0.2.2"])]
272                )
273                .unwrap()
274        );
275        store
276            .merge_device_routes(
277                "a",
278                &[route("a", &["192.0.2.9"]), route("b", &["192.0.2.8"])],
279            )
280            .unwrap();
281        assert_eq!(
282            store.device_route("a").unwrap().unwrap().addresses,
283            vec!["192.0.2.9", "192.0.2.1"]
284        );
285        assert_eq!(
286            store.device_route("b").unwrap().unwrap().addresses,
287            vec!["192.0.2.2", "192.0.2.8"]
288        );
289        assert!(
290            !store
291                .merge_device_routes("a", &[route("a", &["192.0.2.9", "192.0.2.1"])])
292                .unwrap()
293        );
294    }
295
296    #[test]
297    fn routes_to_this_device_or_to_unknown_machines_are_ignored() {
298        let (store, _dir) = store_with(&["a"]);
299        store
300            .merge_device_routes(
301                "a",
302                &[route("self", &["192.0.2.1"]), route("x", &["192.0.2.2"])],
303            )
304            .unwrap();
305        assert!(store.device_route("self").unwrap().is_none());
306        assert!(store.device_route("x").unwrap().is_none());
307    }
308
309    #[test]
310    fn option_like_or_malformed_names_are_never_kept() {
311        let (store, _dir) = store_with(&["a"]);
312        let mut sent = route(
313            "a",
314            &["-oProxyCommand=touch", "ok.local", "a b", "ok.local"],
315        );
316        sent.ssh_login = Some("-l".to_string());
317        store.merge_device_routes("a", &[sent]).unwrap();
318        let held = store.device_route("a").unwrap().unwrap();
319        assert_eq!(held.addresses, vec!["ok.local"]);
320        assert_eq!(held.ssh_login, None);
321    }
322
323    #[test]
324    fn legacy_routes_and_the_migration_mark_round_trip() {
325        let (store, _dir) = store_with(&["a"]);
326        assert!(!store.sync_peers_migrated().unwrap());
327        let legacy = LegacyRoute {
328            host: "me@pi".to_string(),
329            sb: "sb".to_string(),
330        };
331        store.set_legacy_route("a", &legacy).unwrap();
332        store.set_device_route(route("a", &["192.0.2.1"])).unwrap();
333        assert_eq!(
334            store.legacy_routes().unwrap(),
335            vec![("a".to_string(), legacy)]
336        );
337        assert_eq!(store.device_routes().unwrap().len(), 1);
338        store.mark_sync_peers_migrated().unwrap();
339        assert!(store.sync_peers_migrated().unwrap());
340    }
341}