Skip to main content

second_brain_sync/
dial.rs

1use std::collections::HashMap;
2use std::path::Path;
3
4use anyhow::Result;
5use second_brain_core::keys::{
6    DeviceRecord, DeviceRoute, LegacyRoute, valid_login, valid_machine_id,
7};
8use second_brain_core::sqlite_store::SqliteStore;
9
10use crate::mdns::{self, Found};
11use crate::peers::{self, Peer};
12
13const SSH_PORT: u16 = 22;
14
15/// One way to reach a peer.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Route {
18    /// The peer's forced-command line for this device, entered with this
19    /// device's own ssh key and the peer's host keys pinned by machine id.
20    Device {
21        machine_id: String,
22        login: String,
23        address: String,
24        port: u16,
25    },
26    /// A `sync-peers` line, through the user's own ssh setup.
27    Line(Peer),
28}
29
30impl Route {
31    pub fn describe(&self) -> String {
32        match self {
33            Route::Device {
34                login,
35                address,
36                port,
37                ..
38            } if *port != SSH_PORT => format!("{login}@{address}:{port}"),
39            Route::Device { login, address, .. } => format!("{login}@{address}"),
40            Route::Line(peer) => peer.host.clone(),
41        }
42    }
43}
44
45/// A peer the sync loop dials, with its routes in the order they are tried.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct Dial {
48    /// Unique per peer: its machine id, or a `sync-peers` host not yet
49    /// matched to a device.
50    pub key: String,
51    /// The device name, or the host, for health and logs.
52    pub label: String,
53    /// The id a device route must answer with; None for an unmatched line.
54    pub machine_id: Option<String>,
55    pub routes: Vec<Route>,
56}
57
58/// `device_dials`, then `line_dials`.
59pub fn dials(store: &SqliteStore, data_dir: &Path) -> Result<Vec<Dial>> {
60    let mut out = device_dials(store)?;
61    out.extend(line_dials(store, data_dir)?);
62    Ok(out)
63}
64
65/// Every active device of this store's identity that can be reached, by its
66/// device routes and the `sync-peers` lines matched to it. Revoked devices
67/// are never dialled, by either kind of route.
68pub fn device_dials(store: &SqliteStore) -> Result<Vec<Dial>> {
69    let routes: HashMap<String, _> = store
70        .device_routes()?
71        .into_iter()
72        .map(|route| (route.machine_id.clone(), route))
73        .collect();
74    let legacy: Vec<(String, LegacyRoute)> = store.legacy_routes()?;
75
76    let mut out = Vec::new();
77    for record in &peer_records(store)? {
78        let route = routes.get(&record.machine_id);
79        let login = login_for(record, route, None);
80        let port = port_for(record, route, None);
81        let mut tried = Vec::new();
82        if let (Some(login), Some(route)) = (login, route) {
83            tried.extend(route.addresses.iter().map(|address| Route::Device {
84                machine_id: record.machine_id.clone(),
85                login: login.clone(),
86                address: address.clone(),
87                port,
88            }));
89        }
90        tried.extend(
91            legacy
92                .iter()
93                .filter(|(id, _)| *id == record.machine_id)
94                .map(|(_, line)| {
95                    Route::Line(Peer {
96                        host: line.host.clone(),
97                        sb: line.sb.clone(),
98                    })
99                }),
100        );
101        if tried.is_empty() {
102            continue;
103        }
104        out.push(Dial {
105            key: record.machine_id.clone(),
106            label: label(record),
107            machine_id: Some(record.machine_id.clone()),
108            routes: tried,
109        });
110    }
111
112    let labels: Vec<String> = out.iter().map(|dial| dial.label.clone()).collect();
113    for dial in &mut out {
114        if labels.iter().filter(|label| **label == dial.label).count() > 1 {
115            dial.label = format!("{} ({})", dial.label, dial.key);
116        }
117    }
118    Ok(out)
119}
120
121/// Dials for the active devices of this store's identity that an mDNS
122/// lookup found, at the addresses their answers came from. A responder
123/// counts only under a machine id the device list holds as active, so an
124/// unknown, revoked or own id is ignored.
125pub fn found_dials(store: &SqliteStore, found: &[Found]) -> Result<Vec<Dial>> {
126    let routes: HashMap<String, DeviceRoute> = store
127        .device_routes()?
128        .into_iter()
129        .map(|route| (route.machine_id.clone(), route))
130        .collect();
131    let mut out = Vec::new();
132    for record in peer_records(store)? {
133        let route = routes.get(&record.machine_id);
134        let mut tried: Vec<Route> = Vec::new();
135        for answer in found
136            .iter()
137            .filter(|answer| answer.get(mdns::TXT_ID) == Some(record.machine_id.as_str()))
138        {
139            let Some(login) = login_for(&record, route, Some(answer)) else {
140                continue;
141            };
142            let port = port_for(&record, route, Some(answer));
143            let found_route = Route::Device {
144                machine_id: record.machine_id.clone(),
145                login,
146                address: answer.address.to_string(),
147                port,
148            };
149            if !tried.contains(&found_route) {
150                tried.push(found_route);
151            }
152        }
153        if !tried.is_empty() {
154            out.push(Dial {
155                key: record.machine_id.clone(),
156                label: label(&record),
157                machine_id: Some(record.machine_id.clone()),
158                routes: tried,
159            });
160        }
161    }
162    Ok(out)
163}
164
165/// True when an active device of this identity has no dial in `dials`,
166/// which an mDNS lookup may find.
167pub fn undialled(store: &SqliteStore, dials: &[Dial]) -> Result<bool> {
168    Ok(peer_records(store)?
169        .iter()
170        .any(|record| !dials.iter().any(|dial| dial.key == record.machine_id)))
171}
172
173/// Records a device route that answered as its device: its address goes
174/// ahead of those held, with the login and port that reached it. An
175/// address already held changes nothing. True when something was recorded.
176pub fn record_answered(store: &SqliteStore, route: &Route) -> Result<bool> {
177    let Route::Device {
178        machine_id,
179        login,
180        address,
181        port,
182    } = route
183    else {
184        return Ok(false);
185    };
186    let held = store.device_route(machine_id)?.unwrap_or_default();
187    if held.addresses.contains(address) {
188        return Ok(false);
189    }
190    let mut addresses = vec![address.clone()];
191    addresses.extend(held.addresses);
192    store.set_device_route(DeviceRoute {
193        machine_id: machine_id.clone(),
194        addresses,
195        ssh_login: Some(login.clone()),
196        ssh_port: Some(*port),
197    })?;
198    Ok(true)
199}
200
201/// The active devices of this store's identity besides this one, with
202/// machine ids safe to dial.
203fn peer_records(store: &SqliteStore) -> Result<Vec<DeviceRecord>> {
204    let own = store.machine_id().to_string();
205    let rows = store.device_records()?;
206    let identity = rows
207        .iter()
208        .find(|row| row.current.record.machine_id == own)
209        .map(|row| row.current.record.identity_tag.clone());
210    Ok(rows
211        .into_iter()
212        .filter(|row| {
213            let record = &row.current.record;
214            !row.revoked
215                && valid_machine_id(&record.machine_id)
216                && record.machine_id != own
217                && Some(&record.identity_tag) == identity.as_ref()
218        })
219        .map(|row| row.current.record)
220        .collect())
221}
222
223/// The device's signed login, then the one held from pairing or a
224/// handshake, then its mDNS advert's, which nothing authenticates.
225fn login_for(
226    record: &DeviceRecord,
227    route: Option<&DeviceRoute>,
228    answer: Option<&Found>,
229) -> Option<String> {
230    record
231        .ssh_login
232        .clone()
233        .filter(|login| valid_login(login))
234        .or_else(|| route.and_then(|r| r.ssh_login.clone()))
235        .or_else(|| {
236            answer
237                .and_then(|a| a.get(mdns::TXT_LOGIN))
238                .filter(|login| valid_login(login))
239                .map(str::to_string)
240        })
241}
242
243/// The sshd port, in the order `login_for` takes the login.
244fn port_for(record: &DeviceRecord, route: Option<&DeviceRoute>, answer: Option<&Found>) -> u16 {
245    record
246        .ssh_port
247        .filter(|port| *port != 0)
248        .or_else(|| route.and_then(|r| r.ssh_port))
249        .or_else(|| answer.map(|a| a.port).filter(|port| *port != 0))
250        .unwrap_or(SSH_PORT)
251}
252
253fn label(record: &DeviceRecord) -> String {
254    if record.name.is_empty() {
255        record.machine_id.clone()
256    } else {
257        record.name.clone()
258    }
259}
260
261/// Every `sync-peers` line not yet matched to a device; once every line is
262/// matched the file is no longer read.
263pub fn line_dials(store: &SqliteStore, data_dir: &Path) -> Result<Vec<Dial>> {
264    if store.sync_peers_migrated()? {
265        return Ok(Vec::new());
266    }
267    let lines = unmatched_lines(data_dir, &store.legacy_routes()?)?;
268    if lines.is_empty() {
269        store.mark_sync_peers_migrated()?;
270    }
271    Ok(lines
272        .into_iter()
273        .map(|peer| Dial {
274            key: peer.host.clone(),
275            label: peer.host.clone(),
276            machine_id: None,
277            routes: vec![Route::Line(peer)],
278        })
279        .collect())
280}
281
282/// The active devices of this store's identity besides this one, whether or
283/// not this device can dial them, plus the `sync-peers` lines not yet matched
284/// to one. Reads only.
285pub fn sync_partners(store: &SqliteStore, data_dir: &Path) -> Result<usize> {
286    let devices = peer_records(store)?.len();
287    let lines = if store.sync_peers_migrated()? {
288        0
289    } else {
290        unmatched_lines(data_dir, &store.legacy_routes()?)?.len()
291    };
292    Ok(devices + lines)
293}
294
295/// The first line per host wins, as `sb sync` reads the file.
296fn unmatched_lines(data_dir: &Path, legacy: &[(String, LegacyRoute)]) -> Result<Vec<Peer>> {
297    let mut seen = Vec::new();
298    let mut lines = Vec::new();
299    for line in peers::configured_peers(data_dir)?.unwrap_or_default() {
300        let peer = Peer::parse(&line);
301        if seen.contains(&peer.host) {
302            continue;
303        }
304        seen.push(peer.host.clone());
305        if !legacy.iter().any(|(_, route)| route.host == peer.host) {
306            lines.push(peer);
307        }
308    }
309    Ok(lines)
310}
311
312/// What a `sync-peers` line's host answered: once it names a device this
313/// store holds a row for, the line becomes that device's route.
314pub fn line_answered(store: &SqliteStore, peer: &Peer, machine_id: &str) -> Result<()> {
315    if store.device_record(machine_id)?.is_none() {
316        return Ok(());
317    }
318    store.set_legacy_route(
319        machine_id,
320        &LegacyRoute {
321            host: peer.host.clone(),
322            sb: peer.sb.clone(),
323        },
324    )
325}
326
327/// A route that answered with another machine id than the device it was
328/// dialled for: an address now held by another machine, or a `sync-peers`
329/// host that is a revoked device.
330pub fn refuse_answer(store: &SqliteStore, dial: &Dial, answered: &str) -> Result<()> {
331    if let Some(expected) = &dial.machine_id
332        && expected != answered
333    {
334        anyhow::bail!(
335            "{} answered as {answered}, not as {expected}; skipping that route",
336            dial.label
337        );
338    }
339    if store
340        .device_record(answered)?
341        .is_some_and(|row| row.revoked)
342    {
343        anyhow::bail!(
344            "{} answered as {answered}, a revoked device; it is not synced with",
345            dial.label
346        );
347    }
348    Ok(())
349}
350
351#[cfg(test)]
352mod tests {
353    use std::collections::BTreeSet;
354
355    use second_brain_core::keys::{
356        DeviceKeys, DeviceRecord, DeviceRoute, admit_device, ensure_device_keys, found_identity,
357        load_device_keys,
358    };
359
360    use super::*;
361    use crate::keyring::Keyring;
362
363    struct Fixture {
364        store: SqliteStore,
365        dir: tempfile::TempDir,
366    }
367
368    impl Fixture {
369        fn new(others: &[(&str, Option<&str>)]) -> Self {
370            let named: Vec<(&str, String, Option<&str>)> = others
371                .iter()
372                .map(|(id, login)| (*id, format!("{id}-name"), *login))
373                .collect();
374            Self::named(&named)
375        }
376
377        fn named(others: &[(&str, String, Option<&str>)]) -> Self {
378            let dir = tempfile::tempdir().unwrap();
379            let store = SqliteStore::in_memory("self".to_string()).unwrap();
380            ensure_device_keys(&store, dir.path()).unwrap();
381            let device = load_device_keys(dir.path()).unwrap().unwrap();
382            let founded = found_identity(&store, &device, "self", &[], 1).unwrap();
383            for (id, name, login) in others {
384                let keys = DeviceKeys::generate().unwrap();
385                let record = DeviceRecord {
386                    machine_id: id.to_string(),
387                    identity_tag: founded.tag.as_str().to_string(),
388                    version: 1,
389                    name: name.clone(),
390                    age_recipient: keys.age_recipient().to_string(),
391                    ssh_public_key: keys.ssh_public_key(),
392                    signing_public_key: keys.verifying_key().to_bytes(),
393                    recovery_fingerprints: Vec::new(),
394                    ssh_login: login.map(str::to_string),
395                    ssh_port: login.map(|_| 2222),
396                    ssh_host_key: None,
397                };
398                admit_device(&store, &device, record).unwrap();
399            }
400            Self { store, dir }
401        }
402
403        fn route(&self, id: &str, addresses: &[&str]) {
404            self.store
405                .set_device_route(DeviceRoute {
406                    machine_id: id.to_string(),
407                    addresses: addresses.iter().map(|a| a.to_string()).collect(),
408                    ssh_login: None,
409                    ssh_port: None,
410                })
411                .unwrap();
412        }
413
414        fn lines(&self, text: &str) {
415            std::fs::write(self.dir.path().join(peers::PEERS_FILE), text).unwrap();
416        }
417
418        fn dials(&self) -> Vec<Dial> {
419            dials(&self.store, self.dir.path()).unwrap()
420        }
421
422        fn revoke(&self, id: &str) {
423            Keyring::load(&self.store, self.dir.path())
424                .unwrap()
425                .remove_device(id, &BTreeSet::new(), 10)
426                .unwrap();
427        }
428    }
429
430    fn line(host: &str) -> Route {
431        Route::Line(Peer {
432            host: host.to_string(),
433            sb: "sb".to_string(),
434        })
435    }
436
437    #[test]
438    fn an_active_device_is_dialled_at_each_known_address_through_its_signed_login() {
439        let f = Fixture::new(&[("a", Some("me")), ("b", None)]);
440        f.route("a", &["192.0.2.1", "a.local"]);
441        f.route("b", &["192.0.2.2"]);
442        let dials = f.dials();
443        assert_eq!(dials.len(), 1, "b has no sshd login and no line: {dials:?}");
444        assert_eq!(dials[0].key, "a");
445        assert_eq!(dials[0].label, "a-name");
446        assert_eq!(
447            dials[0]
448                .routes
449                .iter()
450                .map(Route::describe)
451                .collect::<Vec<_>>(),
452            vec!["me@192.0.2.1:2222", "me@a.local:2222"]
453        );
454    }
455
456    #[test]
457    fn a_signed_login_that_ssh_could_misread_is_never_dialled() {
458        let f = Fixture::new(&[("a", Some("-oProxyCommand=x")), ("b", Some("me"))]);
459        f.route("a", &["192.0.2.1"]);
460        f.store
461            .set_device_route(DeviceRoute {
462                machine_id: "b".to_string(),
463                addresses: vec!["192.0.2.2".to_string()],
464                ssh_login: Some("-oProxyCommand=y".to_string()),
465                ssh_port: None,
466            })
467            .unwrap();
468        let dials = f.dials();
469        assert_eq!(
470            dials.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
471            vec!["b"],
472            "{dials:?}"
473        );
474        assert_eq!(dials[0].routes[0].describe(), "me@192.0.2.2:2222");
475    }
476
477    #[test]
478    fn devices_with_one_name_get_labels_that_tell_them_apart() {
479        let f = Fixture::named(&[
480            ("a", "laptop".to_string(), Some("me")),
481            ("b", "laptop".to_string(), Some("me")),
482            ("c", "pi".to_string(), Some("me")),
483        ]);
484        for id in ["a", "b", "c"] {
485            f.route(id, &["192.0.2.1"]);
486        }
487        assert_eq!(
488            f.dials()
489                .iter()
490                .map(|d| d.label.as_str())
491                .collect::<Vec<_>>(),
492            vec!["laptop (a)", "laptop (b)", "pi"]
493        );
494    }
495
496    #[test]
497    fn partners_count_every_active_device_and_unmatched_line_without_marking() {
498        let f = Fixture::new(&[("a", Some("me")), ("b", None), ("c", None)]);
499        f.revoke("c");
500        f.lines("me@pi\n");
501        assert_eq!(sync_partners(&f.store, f.dir.path()).unwrap(), 3);
502        f.lines("");
503        assert_eq!(sync_partners(&f.store, f.dir.path()).unwrap(), 2);
504        assert!(!f.store.sync_peers_migrated().unwrap());
505    }
506
507    #[test]
508    fn a_signed_row_with_an_unsafe_machine_id_is_neither_dialled_nor_counted() {
509        let f = Fixture::new(&[("a", Some("me"))]);
510        f.route("a", &["192.0.2.1"]);
511        let device = load_device_keys(f.dir.path()).unwrap().unwrap();
512        let tag = f
513            .store
514            .device_record("self")
515            .unwrap()
516            .unwrap()
517            .current
518            .record
519            .identity_tag;
520        let keys = DeviceKeys::generate().unwrap();
521        for id in ["x\n@cert-authority *", "x\0"] {
522            let record = DeviceRecord {
523                machine_id: id.to_string(),
524                identity_tag: tag.clone(),
525                version: 1,
526                name: "planted".to_string(),
527                age_recipient: keys.age_recipient().to_string(),
528                ssh_public_key: keys.ssh_public_key(),
529                signing_public_key: keys.verifying_key().to_bytes(),
530                recovery_fingerprints: Vec::new(),
531                ssh_login: Some("me".to_string()),
532                ssh_port: None,
533                ssh_host_key: None,
534            };
535            f.store
536                .insert_first_device_record(
537                    &record.sign("self", device.signing_key()),
538                    "self",
539                    &device.verifying_key(),
540                )
541                .unwrap();
542            f.route(id, &["192.0.2.9"]);
543        }
544        assert_eq!(
545            f.dials().iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
546            vec!["a"]
547        );
548        assert_eq!(sync_partners(&f.store, f.dir.path()).unwrap(), 1);
549    }
550
551    #[test]
552    fn an_unreadable_sync_peers_leaves_devices_dialled() {
553        let f = Fixture::new(&[("a", Some("me"))]);
554        f.route("a", &["192.0.2.1"]);
555        std::fs::create_dir(f.dir.path().join(peers::PEERS_FILE)).unwrap();
556        assert!(dials(&f.store, f.dir.path()).is_err());
557        assert!(line_dials(&f.store, f.dir.path()).is_err());
558        assert_eq!(
559            device_dials(&f.store)
560                .unwrap()
561                .iter()
562                .map(|d| d.key.as_str())
563                .collect::<Vec<_>>(),
564            vec!["a"]
565        );
566    }
567
568    #[test]
569    fn a_revoked_device_is_not_dialled_by_any_route() {
570        let f = Fixture::new(&[("a", Some("me")), ("b", Some("me"))]);
571        f.route("a", &["192.0.2.1"]);
572        f.route("b", &["192.0.2.2"]);
573        f.lines("me@pi\n");
574        line_answered(&f.store, &Peer::parse("me@pi"), "b").unwrap();
575        f.revoke("b");
576        let dials = f.dials();
577        assert_eq!(
578            dials.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
579            vec!["a"]
580        );
581    }
582
583    #[test]
584    fn sync_peers_lines_are_dialled_until_each_names_a_device_then_never_read_again() {
585        let f = Fixture::new(&[("a", None)]);
586        f.lines("me@pi /opt/sb\nme@mac\nme@pi\n");
587        let before = f.dials();
588        assert_eq!(
589            before.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
590            vec!["me@pi", "me@mac"]
591        );
592        assert_eq!(before[0].machine_id, None);
593
594        line_answered(&f.store, &Peer::parse("me@pi /opt/sb"), "a").unwrap();
595        line_answered(&f.store, &Peer::parse("me@mac"), "unknown").unwrap();
596        let after = f.dials();
597        assert_eq!(after[0].key, "a");
598        assert_eq!(
599            after[0].routes,
600            vec![Route::Line(Peer::parse("me@pi /opt/sb"))]
601        );
602        assert_eq!(after[1].routes, vec![line("me@mac")]);
603        assert!(!f.store.sync_peers_migrated().unwrap());
604
605        f.lines("me@pi\n");
606        f.dials();
607        assert!(f.store.sync_peers_migrated().unwrap());
608        f.lines("me@new\n");
609        assert_eq!(
610            f.dials().iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
611            vec!["a"]
612        );
613    }
614
615    #[test]
616    fn an_answer_from_another_or_a_revoked_device_is_refused() {
617        let f = Fixture::new(&[("a", Some("me")), ("b", Some("me"))]);
618        f.route("a", &["192.0.2.1"]);
619        let dial = f.dials().remove(0);
620        assert!(refuse_answer(&f.store, &dial, "a").is_ok());
621        assert!(refuse_answer(&f.store, &dial, "b").is_err());
622
623        f.revoke("b");
624        let unmatched = Dial {
625            key: "me@old".to_string(),
626            label: "me@old".to_string(),
627            machine_id: None,
628            routes: vec![line("me@old")],
629        };
630        assert!(refuse_answer(&f.store, &unmatched, "b").is_err());
631        assert!(refuse_answer(&f.store, &unmatched, "x").is_ok());
632    }
633
634    fn answer(id: &str, address: &str, login: Option<&str>, port: u16) -> Found {
635        let mut txt = std::collections::BTreeMap::new();
636        txt.insert(mdns::TXT_ID.to_string(), id.to_string());
637        if let Some(login) = login {
638            txt.insert(mdns::TXT_LOGIN.to_string(), login.to_string());
639        }
640        Found {
641            instance: id.to_string(),
642            address: address.parse().unwrap(),
643            port,
644            txt,
645        }
646    }
647
648    fn described(dials: &[Dial]) -> Vec<(String, Vec<String>)> {
649        dials
650            .iter()
651            .map(|d| {
652                (
653                    d.key.clone(),
654                    d.routes.iter().map(Route::describe).collect(),
655                )
656            })
657            .collect()
658    }
659
660    #[test]
661    fn a_lookup_dials_only_active_devices_of_this_identity_by_their_pinned_id() {
662        let f = Fixture::new(&[("a", None), ("b", Some("signed")), ("c", None)]);
663        f.revoke("c");
664        let found = [
665            answer("a", "192.0.2.1", Some("me"), 22),
666            answer("a", "192.0.2.1", Some("me"), 22),
667            answer("b", "192.0.2.2", Some("advertised"), 2200),
668            answer("c", "192.0.2.3", Some("me"), 22),
669            answer("stranger", "192.0.2.4", Some("me"), 22),
670            answer("self", "192.0.2.5", Some("me"), 22),
671            answer("a", "192.0.2.6", None, 22),
672            answer("a", "192.0.2.7", Some("-oProxyCommand=x"), 22),
673            answer("a", "192.0.2.8", Some("me"), 0),
674        ];
675        assert_eq!(
676            described(&found_dials(&f.store, &found).unwrap()),
677            vec![
678                (
679                    "a".to_string(),
680                    vec!["me@192.0.2.1".to_string(), "me@192.0.2.8".to_string()]
681                ),
682                ("b".to_string(), vec!["signed@192.0.2.2:2222".to_string()]),
683            ]
684        );
685    }
686
687    #[test]
688    fn a_held_login_and_port_win_over_the_adverts() {
689        let f = Fixture::new(&[("a", None)]);
690        f.store
691            .set_device_route(DeviceRoute {
692                machine_id: "a".to_string(),
693                addresses: vec!["192.0.2.1".to_string()],
694                ssh_login: Some("held".to_string()),
695                ssh_port: Some(2022),
696            })
697            .unwrap();
698        assert_eq!(
699            described(
700                &found_dials(
701                    &f.store,
702                    &[answer("a", "192.0.2.9", Some("advertised"), 2200)]
703                )
704                .unwrap()
705            ),
706            vec![("a".to_string(), vec!["held@192.0.2.9:2022".to_string()])]
707        );
708    }
709
710    #[test]
711    fn an_address_that_answered_goes_first_once() {
712        let f = Fixture::new(&[("a", None)]);
713        f.route("a", &["192.0.2.1"]);
714        let found = Route::Device {
715            machine_id: "a".to_string(),
716            login: "me".to_string(),
717            address: "192.0.2.9".to_string(),
718            port: 2200,
719        };
720        assert!(record_answered(&f.store, &found).unwrap());
721        assert_eq!(
722            f.store.device_route("a").unwrap().unwrap(),
723            DeviceRoute {
724                machine_id: "a".to_string(),
725                addresses: vec!["192.0.2.9".to_string(), "192.0.2.1".to_string()],
726                ssh_login: Some("me".to_string()),
727                ssh_port: Some(2200),
728            }
729        );
730        assert!(!record_answered(&f.store, &found).unwrap());
731        assert!(!record_answered(&f.store, &line("me@pi")).unwrap());
732        assert_eq!(
733            described(&device_dials(&f.store).unwrap()),
734            vec![(
735                "a".to_string(),
736                vec![
737                    "me@192.0.2.9:2200".to_string(),
738                    "me@192.0.2.1:2200".to_string()
739                ]
740            )]
741        );
742    }
743
744    #[test]
745    fn an_active_device_without_a_dial_is_undialled() {
746        let f = Fixture::new(&[("a", Some("me")), ("b", None), ("c", None)]);
747        f.revoke("c");
748        f.route("a", &["192.0.2.1"]);
749        let dials = device_dials(&f.store).unwrap();
750        assert!(undialled(&f.store, &dials).unwrap(), "b has no route");
751        f.route("b", &["192.0.2.2"]);
752        record_answered(
753            &f.store,
754            &Route::Device {
755                machine_id: "b".to_string(),
756                login: "me".to_string(),
757                address: "192.0.2.3".to_string(),
758                port: 22,
759            },
760        )
761        .unwrap();
762        let dials = device_dials(&f.store).unwrap();
763        assert!(!undialled(&f.store, &dials).unwrap(), "{dials:?}");
764    }
765}