second-brain-sync 0.13.2

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
use std::collections::HashSet;
use std::ffi::OsString;
use std::fs;
use std::io::{Read, Write};
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};

use anyhow::{Context, Result};
use second_brain_core::keys::valid_machine_id;
use second_brain_core::machine::MachineIdentity;

use crate::protocol::Hello;
use crate::session::{Exit, Remote, Transport};
use crate::ssh_identity::EphemeralIdentity;

/// Every read-modify-write of a known_hosts file in this process holds it,
/// so a pin and an unpin from two handlers cannot drop each other's change.
static KNOWN_HOSTS_LOCK: Mutex<()> = Mutex::new(());
static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);

fn known_hosts_guard() -> MutexGuard<'static, ()> {
    KNOWN_HOSTS_LOCK
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
}

pub fn known_hosts_path_in(config_dir: &Path) -> PathBuf {
    config_dir.join("known_hosts")
}

pub fn known_hosts_path() -> Result<PathBuf> {
    Ok(known_hosts_path_in(&MachineIdentity::config_dir()?))
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyscanLine {
    pub host: String,
    pub key_type: String,
    pub public_key: String,
}

pub fn parse_keyscan_output(raw: &str) -> Vec<KeyscanLine> {
    raw.lines()
        .filter_map(|line| {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                return None;
            }
            let mut parts = line.split_whitespace();
            let host = parts.next()?;
            let key_type = parts.next()?;
            let public_key = parts.next()?;
            Some(KeyscanLine {
                host: host.to_string(),
                key_type: key_type.to_string(),
                public_key: public_key.to_string(),
            })
        })
        .collect()
}

pub fn compose_known_host_entry(line: &KeyscanLine) -> String {
    format!("{} {} {}\n", line.host, line.key_type, line.public_key)
}

pub fn append_known_host(path: &Path, lines: &[KeyscanLine]) -> Result<()> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent).context("creating known_hosts parent dir")?;
    }

    let _guard = known_hosts_guard();
    let existing = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e).context("reading known_hosts"),
    };
    let already: HashSet<&str> = existing
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .collect();

    let mut file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .open(path)
        .context("opening known_hosts for append")?;

    for line in lines {
        let entry = compose_known_host_entry(line);
        if already.contains(entry.trim_end()) {
            continue;
        }
        file.write_all(entry.as_bytes())
            .context("writing known_hosts entry")?;
    }

    // because OpenOptions::mode only applies on file creation, tighten unconditionally
    // so an existing permissive file is corrected on first append.
    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
        .context("setting known_hosts mode 0600")?;

    Ok(())
}

const HOST_KEY_FILES: &[&str] = &[
    "ssh_host_ed25519_key.pub",
    "ssh_host_ecdsa_key.pub",
    "ssh_host_rsa_key.pub",
];

/// This machine's sshd host keys from `dir` (`/etc/ssh` on a real host) as
/// `type base64` lines, ed25519 first. Unreadable files are skipped.
pub fn read_host_keys(dir: &Path) -> Vec<String> {
    HOST_KEY_FILES
        .iter()
        .filter_map(|name| fs::read_to_string(dir.join(name)).ok())
        .filter_map(|text| {
            let mut parts = text.split_whitespace();
            let key_type = parts.next()?;
            let key = parts.next()?;
            (key_type.starts_with("ssh-") || key_type.starts_with("ecdsa-"))
                .then(|| format!("{key_type} {key}"))
        })
        .collect()
}

/// How known_hosts names `host` reached on `port`.
pub fn known_host_name(host: &str, port: u16) -> String {
    if port == 22 {
        host.to_string()
    } else {
        format!("[{host}]:{port}")
    }
}

/// A name or address with no known_hosts pattern, marker or separator in
/// it, so a pinned line matches that host alone.
fn is_plain_host(host: &str) -> bool {
    !host.is_empty()
        && host
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':' | b'%'))
}

/// Pins a paired device's host keys under each name it may be dialled by,
/// so sync to it needs no `sb sync trust`. Names that are not a plain host
/// are skipped. Returns the entries written or already present.
pub fn pin_host_keys(
    path: &Path,
    hosts: &[String],
    port: u16,
    host_keys: &[String],
) -> Result<Vec<String>> {
    let mut lines = Vec::new();
    for host in hosts.iter().filter(|host| is_plain_host(host)) {
        let name = known_host_name(host, port);
        for key in host_keys {
            let mut parts = key.split_whitespace();
            let (Some(key_type), Some(public_key)) = (parts.next(), parts.next()) else {
                continue;
            };
            lines.push(KeyscanLine {
                host: name.clone(),
                key_type: key_type.to_string(),
                public_key: public_key.to_string(),
            });
        }
    }
    lines.dedup();
    append_known_host(path, &lines)?;
    Ok(lines
        .iter()
        .map(|line| compose_known_host_entry(line).trim_end().to_string())
        .collect())
}

pub fn device_alias(machine_id: &str) -> String {
    format!("sb-{machine_id}")
}

fn read_known_hosts(path: &Path) -> Result<String> {
    match fs::read_to_string(path) {
        Ok(text) => Ok(text),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
        Err(e) => Err(e).context("reading known_hosts"),
    }
}

/// Pins `host_keys` (`type base64`, a trailing comment is dropped) under
/// `alias`, skipping keys already pinned there; a new key replaces the one of
/// its type pinned before, since a host has one key per type. Returns whether
/// it wrote.
pub fn pin_alias(path: &Path, alias: &str, host_keys: &[String]) -> Result<bool> {
    anyhow::ensure!(
        valid_machine_id(alias),
        "{alias:?} cannot be a known_hosts host name"
    );
    let _guard = known_hosts_guard();
    let existing = read_known_hosts(path)?;
    let pinned: HashSet<(&str, &str)> = existing
        .lines()
        .filter_map(|line| {
            let mut parts = line.split_whitespace();
            (parts.next()? == alias).then_some(())?;
            Some((parts.next()?, parts.next()?))
        })
        .collect();
    let mut fresh: Vec<(&str, &str)> = Vec::new();
    for key in host_keys {
        let mut parts = key.split_whitespace();
        let (Some(key_type), Some(public_key)) = (parts.next(), parts.next()) else {
            continue;
        };
        let pair = (key_type, public_key);
        if !pinned.contains(&pair) && !fresh.contains(&pair) {
            fresh.push(pair);
        }
    }
    if fresh.is_empty() {
        return Ok(false);
    }
    let rotated: HashSet<&str> = fresh.iter().map(|(key_type, _)| *key_type).collect();
    let mut out: String = existing
        .split_inclusive('\n')
        .filter(|line| match pinned_line(line) {
            Some((host, (key_type, _))) => host != alias || !rotated.contains(key_type),
            None => true,
        })
        .collect();
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
    for (key_type, public_key) in fresh {
        out.push_str(&format!("{alias} {key_type} {public_key}\n"));
    }
    write_atomic(path, out.as_bytes(), Some(0o600))?;
    Ok(true)
}

/// A device's pins: its alias and the host key its signed row carries.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DevicePin {
    pub alias: String,
    pub signed_host_key: Option<String>,
}

fn key_pair(key: &str) -> Option<(&str, &str)> {
    let mut parts = key.split_whitespace();
    Some((parts.next()?, parts.next()?))
}

/// The host field and key of a plain known_hosts line; None for comments
/// and marker (`@revoked`, `@cert-authority`) lines.
fn pinned_line(line: &str) -> Option<(&str, (&str, &str))> {
    let mut parts = line.split_whitespace();
    let host = parts
        .next()
        .filter(|h| !h.starts_with('#') && !h.starts_with('@'))?;
    Some((host, (parts.next()?, parts.next()?)))
}

/// Removes the pins of `cut` devices: every line under their aliases, and
/// every line under any other name holding one of their keys (the host
/// names pairing pinned), unless a `kept` device holds that key too.
pub fn unpin_devices(path: &Path, cut: &[DevicePin], kept: &[DevicePin]) -> Result<bool> {
    if cut.is_empty() {
        return Ok(false);
    }
    let _guard = known_hosts_guard();
    let existing = read_known_hosts(path)?;
    let keys_of = |pins: &[DevicePin]| -> HashSet<(String, String)> {
        let aliases: HashSet<&str> = pins.iter().map(|p| p.alias.as_str()).collect();
        let mut keys: HashSet<(String, String)> = existing
            .lines()
            .filter_map(pinned_line)
            .filter(|(host, _)| aliases.contains(host))
            .map(|(_, (t, k))| (t.to_string(), k.to_string()))
            .collect();
        keys.extend(
            pins.iter()
                .filter_map(|p| p.signed_host_key.as_deref().and_then(key_pair))
                .map(|(t, k)| (t.to_string(), k.to_string())),
        );
        keys
    };
    let kept_keys = keys_of(kept);
    let cut_keys: HashSet<(String, String)> =
        keys_of(cut).difference(&kept_keys).cloned().collect();
    let cut_aliases: HashSet<&str> = cut.iter().map(|p| p.alias.as_str()).collect();
    let kept_lines: String = existing
        .split_inclusive('\n')
        .filter(|line| match pinned_line(line) {
            Some((host, (t, k))) => {
                !cut_aliases.contains(host) && !cut_keys.contains(&(t.to_string(), k.to_string()))
            }
            None => true,
        })
        .collect();
    if kept_lines == existing {
        return Ok(false);
    }
    write_atomic(path, kept_lines.as_bytes(), Some(0o600))?;
    Ok(true)
}

/// Replaces `path` (or the target of a symlink at `path`) atomically. A file
/// that exists keeps its mode unless `mode` is given; a new one gets 0600.
pub(crate) fn write_atomic(path: &Path, bytes: &[u8], mode: Option<u32>) -> Result<()> {
    let target = if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
        fs::canonicalize(path).with_context(|| format!("resolving symlink {}", path.display()))?
    } else {
        path.to_path_buf()
    };
    let dir = match target.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
        _ => PathBuf::from("."),
    };
    fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(&dir)
        .with_context(|| format!("creating {}", dir.display()))?;
    let mode = mode.unwrap_or_else(|| {
        fs::metadata(&target)
            .map(|m| m.permissions().mode() & 0o7777)
            .unwrap_or(0o600)
    });
    let name = target
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default();
    let tmp = dir.join(format!(
        ".{name}.sb-{}-{}.tmp",
        std::process::id(),
        TEMP_SEQ.fetch_add(1, Ordering::Relaxed)
    ));
    let written = (|| -> Result<()> {
        let mut file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(&tmp)
            .with_context(|| format!("creating {}", tmp.display()))?;
        file.write_all(bytes)?;
        file.set_permissions(fs::Permissions::from_mode(mode))?;
        file.sync_all()?;
        fs::rename(&tmp, &target).with_context(|| format!("replacing {}", target.display()))?;
        fs::File::open(&dir).and_then(|d| d.sync_all())?;
        Ok(())
    })();
    if written.is_err() {
        let _ = fs::remove_file(&tmp);
    }
    written
}

/// Options the transport adds to every ssh command it runs.
#[derive(Debug, Clone, Default)]
struct ConnectOptions {
    port: Option<u16>,
    host_key_alias: Option<String>,
    identity: Option<PathBuf>,
}

pub fn untrusted_host_hint(host: &str) -> String {
    format!(
        "if ssh reported a host-key error, the host is not in ~/.second-brain/known_hosts yet — \
         run `sb sync trust {host}` to verify and pin its fingerprint."
    )
}

pub fn ssh_args(known_hosts: &Path) -> Vec<OsString> {
    let mut user_kh = OsString::from("UserKnownHostsFile=");
    user_kh.push(known_hosts);

    vec![
        OsString::from("-o"),
        OsString::from("StrictHostKeyChecking=yes"),
        OsString::from("-o"),
        user_kh,
        OsString::from("-o"),
        OsString::from("GlobalKnownHostsFile=/dev/null"),
        OsString::from("-o"),
        OsString::from("ServerAliveInterval=30"),
    ]
}

/// Runs the peer's `sb` over ssh, trusting only host keys pinned in this
/// machine's known_hosts.
pub struct SshTransport {
    host: String,
    sb: String,
    known_hosts: PathBuf,
    unattended: bool,
    options: ConnectOptions,
    ephemeral: Option<EphemeralIdentity>,
}

impl SshTransport {
    pub fn new(host: &str, sb: &str) -> Result<Self> {
        Ok(Self {
            host: host.to_string(),
            sb: sb.to_string(),
            known_hosts: known_hosts_path()?,
            unattended: false,
            options: ConnectOptions::default(),
            ephemeral: None,
        })
    }

    /// For a caller with no terminal: ssh fails instead of prompting, and an
    /// unreachable host fails within seconds instead of the TCP timeout.
    pub fn unattended(mut self) -> Self {
        self.unattended = true;
        self
    }

    pub fn known_hosts(mut self, path: PathBuf) -> Self {
        self.known_hosts = path;
        self
    }

    pub fn port(mut self, port: u16) -> Self {
        self.options.port = Some(port);
        self
    }

    pub fn host_key_alias(mut self, alias: &str) -> Self {
        self.options.host_key_alias = Some(alias.to_string());
        self
    }

    pub fn identity(mut self, key_file: PathBuf) -> Self {
        self.options.identity = Some(key_file);
        self
    }

    /// Signs in with `identity`, whose key file lives as long as the transport.
    pub fn ephemeral_identity(mut self, identity: EphemeralIdentity) -> Self {
        self.options.identity = Some(identity.path().to_path_buf());
        self.ephemeral = Some(identity);
        self
    }

    fn ssh_options(&self) -> Vec<OsString> {
        let mut args = ssh_args(&self.known_hosts);
        if self.unattended {
            args.extend(
                ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15"]
                    .into_iter()
                    .map(OsString::from),
            );
        }
        if let Some(port) = self.options.port {
            args.extend([OsString::from("-p"), OsString::from(port.to_string())]);
        }
        if let Some(alias) = &self.options.host_key_alias {
            args.extend([
                OsString::from("-o"),
                OsString::from(format!("HostKeyAlias={alias}")),
            ]);
        }
        if let Some(identity) = &self.options.identity {
            args.extend([
                OsString::from("-i"),
                identity.clone().into_os_string(),
                OsString::from("-o"),
                OsString::from("IdentitiesOnly=yes"),
            ]);
        }
        args
    }

    fn ssh(&self) -> Command {
        let mut command = Command::new("ssh");
        command.args(self.ssh_options());
        command
    }

    /// `sb <args>` on the host; the `--` keeps a host that starts with `-`
    /// from being read as an ssh option.
    fn remote(&self, options: &[&str], args: &[&str]) -> Command {
        let mut command = self.ssh();
        command
            .args(options)
            .arg("--")
            .arg(&self.host)
            .arg(&self.sb)
            .args(args);
        command
    }
}

impl Transport for SshTransport {
    fn host(&self) -> &str {
        &self.host
    }

    fn whoami(&self) -> Result<String> {
        let output = self
            .remote(&[], &["whoami"])
            .output()
            .context("spawning ssh to resolve peer machine id")?;
        if !output.status.success() {
            anyhow::bail!(
                "ssh whoami on {} exited with {}: {}",
                self.host,
                output.status,
                String::from_utf8_lossy(&output.stderr).trim()
            );
        }
        let id = String::from_utf8_lossy(&output.stdout).trim().to_string();
        if id.is_empty() {
            anyhow::bail!("peer {} returned an empty machine id", self.host);
        }
        Ok(id)
    }

    fn export(
        &self,
        after_seq: u64,
        hello: &Hello,
    ) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
        let mut child = self
            .remote(&[], &["sync-export", "--after-seq", &after_seq.to_string()])
            .arg("--hello")
            .arg(hello.to_arg())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .context("spawning ssh for pull")?;
        let output = child
            .stdout
            .take()
            .expect("ssh export spawned with piped stdout");
        Ok((Box::new(output), Box::new(SshRemote(child))))
    }

    fn import(&self) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
        self.spawn_push("sync-import", &[])
    }

    fn snapshot_export(&self, hello: &Hello) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
        let mut child = self
            .remote(&[], &["sync-snapshot", "--hello"])
            .arg(hello.to_arg())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .context("spawning ssh for snapshot export")?;
        let output = child
            .stdout
            .take()
            .expect("ssh snapshot export spawned with piped stdout");
        Ok((Box::new(output), Box::new(SshRemote(child))))
    }

    fn snapshot_import(
        &self,
    ) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
        self.spawn_push("sync-snapshot", &["--apply"])
    }
}

impl SshTransport {
    fn spawn_push(
        &self,
        command: &str,
        extra: &[&str],
    ) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
        let mut child = self
            .remote(
                &[
                    "-o",
                    "ServerAliveInterval=60",
                    "-o",
                    "ServerAliveCountMax=60",
                ],
                &[command],
            )
            .args(extra)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::inherit())
            .spawn()
            .context("spawning ssh for push")?;
        let input = child
            .stdin
            .take()
            .expect("ssh push spawned with piped stdin");
        let output = child
            .stdout
            .take()
            .expect("ssh push spawned with piped stdout");
        Ok((
            Box::new(input),
            Box::new(output),
            Box::new(SshRemote(child)),
        ))
    }
}

struct SshRemote(Child);

impl Remote for SshRemote {
    fn wait(&mut self) -> Result<Exit> {
        let status = self.0.wait()?;
        Ok(Exit {
            success: status.success(),
            status: status.to_string(),
        })
    }

    fn stop(&mut self) -> Result<()> {
        if let Err(e) = self.0.kill() {
            tracing::debug!("ssh already exited: {e}");
        }
        self.0.wait()?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const KEY_1: &str =
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
    const KEY_2: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC0";

    fn transport() -> SshTransport {
        SshTransport {
            host: "box".to_string(),
            sb: "sb".to_string(),
            known_hosts: PathBuf::from("/tmp/kh"),
            unattended: false,
            options: ConnectOptions::default(),
            ephemeral: None,
        }
    }

    fn args_of(command: &Command) -> Vec<String> {
        command
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect()
    }

    fn has_pair(args: &[String], a: &str, b: &str) -> bool {
        args.windows(2).any(|w| w[0] == a && w[1] == b)
    }

    #[test]
    fn an_ephemeral_identity_reaches_ssh_and_goes_with_the_transport() {
        let base = tempfile::tempdir().unwrap();
        let data_dir = tempfile::tempdir().unwrap();
        let key = ed25519_dalek::SigningKey::from_bytes(&[3; 32]);
        let identity =
            EphemeralIdentity::create_in(base.path(), data_dir.path(), &key, "sb").unwrap();
        let path = identity.path().to_string_lossy().into_owned();
        let t = transport().ephemeral_identity(identity);
        let args = args_of(&t.ssh());
        assert!(has_pair(&args, "-i", &path));
        assert!(has_pair(&args, "-o", "IdentitiesOnly=yes"));
        drop(t);
        assert!(!Path::new(&path).exists());
    }

    #[test]
    fn device_alias_prefixes_machine_id() {
        assert_eq!(device_alias("m-1"), "sb-m-1");
    }

    #[test]
    fn builder_options_reach_the_ssh_command() {
        let t = transport()
            .known_hosts(PathBuf::from("/x/known"))
            .port(2222)
            .host_key_alias("sb-m-1")
            .identity(PathBuf::from("/x/id"))
            .unattended();
        let args = args_of(&t.ssh());
        assert!(has_pair(&args, "-o", "UserKnownHostsFile=/x/known"));
        assert!(has_pair(&args, "-p", "2222"));
        assert!(has_pair(&args, "-o", "HostKeyAlias=sb-m-1"));
        assert!(has_pair(&args, "-i", "/x/id"));
        assert!(has_pair(&args, "-o", "IdentitiesOnly=yes"));
        assert!(has_pair(&args, "-o", "BatchMode=yes"));
    }

    #[test]
    fn the_host_is_never_read_as_an_option() {
        let mut t = transport();
        t.host = "-oProxyCommand=touch /tmp/x".to_string();
        let args = args_of(&t.remote(&["-o", "ServerAliveInterval=60"], &["whoami"]));
        let end = args.len();
        assert_eq!(
            args[end - 4..],
            ["--", "-oProxyCommand=touch /tmp/x", "sb", "whoami"]
        );
        assert!(has_pair(&args, "-o", "ServerAliveInterval=60"));
    }

    #[test]
    fn default_transport_adds_no_extra_options() {
        let args = args_of(&transport().ssh());
        assert!(!args.iter().any(|a| a == "-p" || a == "-i"));
        assert!(!args.iter().any(|a| a.starts_with("HostKeyAlias")));
    }

    #[test]
    fn pin_alias_adds_missing_keys_once() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known_hosts");
        std::fs::write(&path, "other ssh-rsa ZZZ").unwrap();
        let keys = vec![format!("{KEY_1} comment"), KEY_2.to_string()];
        assert!(pin_alias(&path, "sb-m-1", &keys).unwrap());
        let text = std::fs::read_to_string(&path).unwrap();
        assert_eq!(
            text,
            format!("other ssh-rsa ZZZ\nsb-m-1 {KEY_1}\nsb-m-1 {KEY_2}\n")
        );
        assert!(!pin_alias(&path, "sb-m-1", &keys).unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
        assert!(pin_alias(&path, "sb-m-2", &keys[..1]).unwrap());
        assert_eq!(
            std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[test]
    fn unpinning_a_device_drops_its_alias_and_its_keys_under_other_names() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known_hosts");
        let original = format!(
            "# note\nhost {KEY_1}\n[host]:2222 {KEY_2}\nsb-m-1 {KEY_1}\nsb-m-10 {KEY_2}\nsb-m-1 {KEY_2}\n"
        );
        std::fs::write(&path, &original).unwrap();
        let pin = |alias: &str, key: Option<&str>| DevicePin {
            alias: alias.to_string(),
            signed_host_key: key.map(str::to_string),
        };
        assert!(unpin_devices(&path, &[pin("sb-m-1", None)], &[pin("sb-m-10", None)]).unwrap());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            format!("# note\n[host]:2222 {KEY_2}\nsb-m-10 {KEY_2}\n")
        );
        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
        assert!(!unpin_devices(&path, &[pin("sb-m-1", None)], &[pin("sb-m-10", None)]).unwrap());
        assert_eq!(
            std::fs::metadata(&path).unwrap().modified().unwrap(),
            before
        );

        assert!(unpin_devices(&path, &[pin("sb-m-10", Some(KEY_2))], &[]).unwrap());
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "# note\n");
        assert!(!unpin_devices(&dir.path().join("none"), &[pin("sb-m-1", None)], &[]).unwrap());
    }

    #[test]
    fn a_rotated_host_key_replaces_the_old_one_of_its_type() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known_hosts");
        let rotated = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIRotatedHostKeyOfTheDevice";
        pin_alias(&path, "sb-m-1", &[KEY_1.to_string(), KEY_2.to_string()]).unwrap();
        pin_alias(&path, "sb-m-2", &[KEY_1.to_string()]).unwrap();
        assert!(pin_alias(&path, "sb-m-1", &[rotated.to_string()]).unwrap());
        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            format!("sb-m-1 {KEY_2}\nsb-m-2 {KEY_1}\nsb-m-1 {rotated}\n")
        );
    }

    #[test]
    fn an_alias_that_could_add_a_known_hosts_line_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known_hosts");
        let keys = [KEY_1.to_string()];
        for alias in [
            "sb-x\n@cert-authority *",
            "sb-x y",
            "sb-x\0",
            "@revoked",
            "",
        ] {
            assert!(pin_alias(&path, alias, &keys).is_err(), "{alias:?}");
        }
        assert!(!path.exists());
    }

    #[test]
    fn concurrent_pins_of_one_file_all_land() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("known_hosts");
        let threads: Vec<_> = (0..8)
            .map(|t| {
                let path = path.clone();
                std::thread::spawn(move || {
                    for i in 0..25 {
                        pin_alias(&path, &format!("sb-{t}-{i}"), &[KEY_1.to_string()]).unwrap();
                    }
                })
            })
            .collect();
        for thread in threads {
            thread.join().unwrap();
        }
        assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 200);
    }
}