Skip to main content

second_brain_sync/
ssh.rs

1use std::collections::HashSet;
2use std::ffi::OsString;
3use std::fs;
4use std::io::{Read, Write};
5use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
6use std::path::{Path, PathBuf};
7use std::process::{Child, Command, Stdio};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::{Mutex, MutexGuard, PoisonError};
10
11use anyhow::{Context, Result};
12use second_brain_core::keys::valid_machine_id;
13use second_brain_core::machine::MachineIdentity;
14
15use crate::protocol::Hello;
16use crate::session::{Exit, Remote, Transport};
17use crate::ssh_identity::EphemeralIdentity;
18
19/// Every read-modify-write of a known_hosts file in this process holds it,
20/// so a pin and an unpin from two handlers cannot drop each other's change.
21static KNOWN_HOSTS_LOCK: Mutex<()> = Mutex::new(());
22static TEMP_SEQ: AtomicU64 = AtomicU64::new(0);
23
24fn known_hosts_guard() -> MutexGuard<'static, ()> {
25    KNOWN_HOSTS_LOCK
26        .lock()
27        .unwrap_or_else(PoisonError::into_inner)
28}
29
30pub fn known_hosts_path_in(config_dir: &Path) -> PathBuf {
31    config_dir.join("known_hosts")
32}
33
34pub fn known_hosts_path() -> Result<PathBuf> {
35    Ok(known_hosts_path_in(&MachineIdentity::config_dir()?))
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct KeyscanLine {
40    pub host: String,
41    pub key_type: String,
42    pub public_key: String,
43}
44
45pub fn parse_keyscan_output(raw: &str) -> Vec<KeyscanLine> {
46    raw.lines()
47        .filter_map(|line| {
48            let line = line.trim();
49            if line.is_empty() || line.starts_with('#') {
50                return None;
51            }
52            let mut parts = line.split_whitespace();
53            let host = parts.next()?;
54            let key_type = parts.next()?;
55            let public_key = parts.next()?;
56            Some(KeyscanLine {
57                host: host.to_string(),
58                key_type: key_type.to_string(),
59                public_key: public_key.to_string(),
60            })
61        })
62        .collect()
63}
64
65pub fn compose_known_host_entry(line: &KeyscanLine) -> String {
66    format!("{} {} {}\n", line.host, line.key_type, line.public_key)
67}
68
69pub fn append_known_host(path: &Path, lines: &[KeyscanLine]) -> Result<()> {
70    if let Some(parent) = path.parent()
71        && !parent.as_os_str().is_empty()
72    {
73        fs::create_dir_all(parent).context("creating known_hosts parent dir")?;
74    }
75
76    let _guard = known_hosts_guard();
77    let existing = match fs::read_to_string(path) {
78        Ok(s) => s,
79        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
80        Err(e) => return Err(e).context("reading known_hosts"),
81    };
82    let already: HashSet<&str> = existing
83        .lines()
84        .map(str::trim)
85        .filter(|l| !l.is_empty())
86        .collect();
87
88    let mut file = fs::OpenOptions::new()
89        .create(true)
90        .append(true)
91        .mode(0o600)
92        .open(path)
93        .context("opening known_hosts for append")?;
94
95    for line in lines {
96        let entry = compose_known_host_entry(line);
97        if already.contains(entry.trim_end()) {
98            continue;
99        }
100        file.write_all(entry.as_bytes())
101            .context("writing known_hosts entry")?;
102    }
103
104    // because OpenOptions::mode only applies on file creation, tighten unconditionally
105    // so an existing permissive file is corrected on first append.
106    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
107        .context("setting known_hosts mode 0600")?;
108
109    Ok(())
110}
111
112const HOST_KEY_FILES: &[&str] = &[
113    "ssh_host_ed25519_key.pub",
114    "ssh_host_ecdsa_key.pub",
115    "ssh_host_rsa_key.pub",
116];
117
118/// This machine's sshd host keys from `dir` (`/etc/ssh` on a real host) as
119/// `type base64` lines, ed25519 first. Unreadable files are skipped.
120pub fn read_host_keys(dir: &Path) -> Vec<String> {
121    HOST_KEY_FILES
122        .iter()
123        .filter_map(|name| fs::read_to_string(dir.join(name)).ok())
124        .filter_map(|text| {
125            let mut parts = text.split_whitespace();
126            let key_type = parts.next()?;
127            let key = parts.next()?;
128            (key_type.starts_with("ssh-") || key_type.starts_with("ecdsa-"))
129                .then(|| format!("{key_type} {key}"))
130        })
131        .collect()
132}
133
134/// How known_hosts names `host` reached on `port`.
135pub fn known_host_name(host: &str, port: u16) -> String {
136    if port == 22 {
137        host.to_string()
138    } else {
139        format!("[{host}]:{port}")
140    }
141}
142
143/// A name or address with no known_hosts pattern, marker or separator in
144/// it, so a pinned line matches that host alone.
145fn is_plain_host(host: &str) -> bool {
146    !host.is_empty()
147        && host
148            .bytes()
149            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_' | b':' | b'%'))
150}
151
152/// Pins a paired device's host keys under each name it may be dialled by,
153/// so sync to it needs no `sb sync trust`. Names that are not a plain host
154/// are skipped. Returns the entries written or already present.
155pub fn pin_host_keys(
156    path: &Path,
157    hosts: &[String],
158    port: u16,
159    host_keys: &[String],
160) -> Result<Vec<String>> {
161    let mut lines = Vec::new();
162    for host in hosts.iter().filter(|host| is_plain_host(host)) {
163        let name = known_host_name(host, port);
164        for key in host_keys {
165            let mut parts = key.split_whitespace();
166            let (Some(key_type), Some(public_key)) = (parts.next(), parts.next()) else {
167                continue;
168            };
169            lines.push(KeyscanLine {
170                host: name.clone(),
171                key_type: key_type.to_string(),
172                public_key: public_key.to_string(),
173            });
174        }
175    }
176    lines.dedup();
177    append_known_host(path, &lines)?;
178    Ok(lines
179        .iter()
180        .map(|line| compose_known_host_entry(line).trim_end().to_string())
181        .collect())
182}
183
184pub fn device_alias(machine_id: &str) -> String {
185    format!("sb-{machine_id}")
186}
187
188fn read_known_hosts(path: &Path) -> Result<String> {
189    match fs::read_to_string(path) {
190        Ok(text) => Ok(text),
191        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
192        Err(e) => Err(e).context("reading known_hosts"),
193    }
194}
195
196/// Pins `host_keys` (`type base64`, a trailing comment is dropped) under
197/// `alias`, skipping keys already pinned there; a new key replaces the one of
198/// its type pinned before, since a host has one key per type. Returns whether
199/// it wrote.
200pub fn pin_alias(path: &Path, alias: &str, host_keys: &[String]) -> Result<bool> {
201    anyhow::ensure!(
202        valid_machine_id(alias),
203        "{alias:?} cannot be a known_hosts host name"
204    );
205    let _guard = known_hosts_guard();
206    let existing = read_known_hosts(path)?;
207    let pinned: HashSet<(&str, &str)> = existing
208        .lines()
209        .filter_map(|line| {
210            let mut parts = line.split_whitespace();
211            (parts.next()? == alias).then_some(())?;
212            Some((parts.next()?, parts.next()?))
213        })
214        .collect();
215    let mut fresh: Vec<(&str, &str)> = Vec::new();
216    for key in host_keys {
217        let mut parts = key.split_whitespace();
218        let (Some(key_type), Some(public_key)) = (parts.next(), parts.next()) else {
219            continue;
220        };
221        let pair = (key_type, public_key);
222        if !pinned.contains(&pair) && !fresh.contains(&pair) {
223            fresh.push(pair);
224        }
225    }
226    if fresh.is_empty() {
227        return Ok(false);
228    }
229    let rotated: HashSet<&str> = fresh.iter().map(|(key_type, _)| *key_type).collect();
230    let mut out: String = existing
231        .split_inclusive('\n')
232        .filter(|line| match pinned_line(line) {
233            Some((host, (key_type, _))) => host != alias || !rotated.contains(key_type),
234            None => true,
235        })
236        .collect();
237    if !out.is_empty() && !out.ends_with('\n') {
238        out.push('\n');
239    }
240    for (key_type, public_key) in fresh {
241        out.push_str(&format!("{alias} {key_type} {public_key}\n"));
242    }
243    write_atomic(path, out.as_bytes(), Some(0o600))?;
244    Ok(true)
245}
246
247/// A device's pins: its alias and the host key its signed row carries.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct DevicePin {
250    pub alias: String,
251    pub signed_host_key: Option<String>,
252}
253
254fn key_pair(key: &str) -> Option<(&str, &str)> {
255    let mut parts = key.split_whitespace();
256    Some((parts.next()?, parts.next()?))
257}
258
259/// The host field and key of a plain known_hosts line; None for comments
260/// and marker (`@revoked`, `@cert-authority`) lines.
261fn pinned_line(line: &str) -> Option<(&str, (&str, &str))> {
262    let mut parts = line.split_whitespace();
263    let host = parts
264        .next()
265        .filter(|h| !h.starts_with('#') && !h.starts_with('@'))?;
266    Some((host, (parts.next()?, parts.next()?)))
267}
268
269/// Removes the pins of `cut` devices: every line under their aliases, and
270/// every line under any other name holding one of their keys (the host
271/// names pairing pinned), unless a `kept` device holds that key too.
272pub fn unpin_devices(path: &Path, cut: &[DevicePin], kept: &[DevicePin]) -> Result<bool> {
273    if cut.is_empty() {
274        return Ok(false);
275    }
276    let _guard = known_hosts_guard();
277    let existing = read_known_hosts(path)?;
278    let keys_of = |pins: &[DevicePin]| -> HashSet<(String, String)> {
279        let aliases: HashSet<&str> = pins.iter().map(|p| p.alias.as_str()).collect();
280        let mut keys: HashSet<(String, String)> = existing
281            .lines()
282            .filter_map(pinned_line)
283            .filter(|(host, _)| aliases.contains(host))
284            .map(|(_, (t, k))| (t.to_string(), k.to_string()))
285            .collect();
286        keys.extend(
287            pins.iter()
288                .filter_map(|p| p.signed_host_key.as_deref().and_then(key_pair))
289                .map(|(t, k)| (t.to_string(), k.to_string())),
290        );
291        keys
292    };
293    let kept_keys = keys_of(kept);
294    let cut_keys: HashSet<(String, String)> =
295        keys_of(cut).difference(&kept_keys).cloned().collect();
296    let cut_aliases: HashSet<&str> = cut.iter().map(|p| p.alias.as_str()).collect();
297    let kept_lines: String = existing
298        .split_inclusive('\n')
299        .filter(|line| match pinned_line(line) {
300            Some((host, (t, k))) => {
301                !cut_aliases.contains(host) && !cut_keys.contains(&(t.to_string(), k.to_string()))
302            }
303            None => true,
304        })
305        .collect();
306    if kept_lines == existing {
307        return Ok(false);
308    }
309    write_atomic(path, kept_lines.as_bytes(), Some(0o600))?;
310    Ok(true)
311}
312
313/// Replaces `path` (or the target of a symlink at `path`) atomically. A file
314/// that exists keeps its mode unless `mode` is given; a new one gets 0600.
315pub(crate) fn write_atomic(path: &Path, bytes: &[u8], mode: Option<u32>) -> Result<()> {
316    let target = if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
317        fs::canonicalize(path).with_context(|| format!("resolving symlink {}", path.display()))?
318    } else {
319        path.to_path_buf()
320    };
321    let dir = match target.parent() {
322        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
323        _ => PathBuf::from("."),
324    };
325    fs::DirBuilder::new()
326        .recursive(true)
327        .mode(0o700)
328        .create(&dir)
329        .with_context(|| format!("creating {}", dir.display()))?;
330    let mode = mode.unwrap_or_else(|| {
331        fs::metadata(&target)
332            .map(|m| m.permissions().mode() & 0o7777)
333            .unwrap_or(0o600)
334    });
335    let name = target
336        .file_name()
337        .map(|n| n.to_string_lossy().into_owned())
338        .unwrap_or_default();
339    let tmp = dir.join(format!(
340        ".{name}.sb-{}-{}.tmp",
341        std::process::id(),
342        TEMP_SEQ.fetch_add(1, Ordering::Relaxed)
343    ));
344    let written = (|| -> Result<()> {
345        let mut file = fs::OpenOptions::new()
346            .write(true)
347            .create(true)
348            .truncate(true)
349            .mode(0o600)
350            .open(&tmp)
351            .with_context(|| format!("creating {}", tmp.display()))?;
352        file.write_all(bytes)?;
353        file.set_permissions(fs::Permissions::from_mode(mode))?;
354        file.sync_all()?;
355        fs::rename(&tmp, &target).with_context(|| format!("replacing {}", target.display()))?;
356        fs::File::open(&dir).and_then(|d| d.sync_all())?;
357        Ok(())
358    })();
359    if written.is_err() {
360        let _ = fs::remove_file(&tmp);
361    }
362    written
363}
364
365/// Options the transport adds to every ssh command it runs.
366#[derive(Debug, Clone, Default)]
367struct ConnectOptions {
368    port: Option<u16>,
369    host_key_alias: Option<String>,
370    identity: Option<PathBuf>,
371}
372
373pub fn untrusted_host_hint(host: &str) -> String {
374    format!(
375        "if ssh reported a host-key error, the host is not in ~/.second-brain/known_hosts yet — \
376         run `sb sync trust {host}` to verify and pin its fingerprint."
377    )
378}
379
380pub fn ssh_args(known_hosts: &Path) -> Vec<OsString> {
381    let mut user_kh = OsString::from("UserKnownHostsFile=");
382    user_kh.push(known_hosts);
383
384    vec![
385        OsString::from("-o"),
386        OsString::from("StrictHostKeyChecking=yes"),
387        OsString::from("-o"),
388        user_kh,
389        OsString::from("-o"),
390        OsString::from("GlobalKnownHostsFile=/dev/null"),
391        OsString::from("-o"),
392        OsString::from("ServerAliveInterval=30"),
393    ]
394}
395
396/// Runs the peer's `sb` over ssh, trusting only host keys pinned in this
397/// machine's known_hosts.
398pub struct SshTransport {
399    host: String,
400    sb: String,
401    known_hosts: PathBuf,
402    unattended: bool,
403    options: ConnectOptions,
404    ephemeral: Option<EphemeralIdentity>,
405}
406
407impl SshTransport {
408    pub fn new(host: &str, sb: &str) -> Result<Self> {
409        Ok(Self {
410            host: host.to_string(),
411            sb: sb.to_string(),
412            known_hosts: known_hosts_path()?,
413            unattended: false,
414            options: ConnectOptions::default(),
415            ephemeral: None,
416        })
417    }
418
419    /// For a caller with no terminal: ssh fails instead of prompting, and an
420    /// unreachable host fails within seconds instead of the TCP timeout.
421    pub fn unattended(mut self) -> Self {
422        self.unattended = true;
423        self
424    }
425
426    pub fn known_hosts(mut self, path: PathBuf) -> Self {
427        self.known_hosts = path;
428        self
429    }
430
431    pub fn port(mut self, port: u16) -> Self {
432        self.options.port = Some(port);
433        self
434    }
435
436    pub fn host_key_alias(mut self, alias: &str) -> Self {
437        self.options.host_key_alias = Some(alias.to_string());
438        self
439    }
440
441    pub fn identity(mut self, key_file: PathBuf) -> Self {
442        self.options.identity = Some(key_file);
443        self
444    }
445
446    /// Signs in with `identity`, whose key file lives as long as the transport.
447    pub fn ephemeral_identity(mut self, identity: EphemeralIdentity) -> Self {
448        self.options.identity = Some(identity.path().to_path_buf());
449        self.ephemeral = Some(identity);
450        self
451    }
452
453    fn ssh_options(&self) -> Vec<OsString> {
454        let mut args = ssh_args(&self.known_hosts);
455        if self.unattended {
456            args.extend(
457                ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15"]
458                    .into_iter()
459                    .map(OsString::from),
460            );
461        }
462        if let Some(port) = self.options.port {
463            args.extend([OsString::from("-p"), OsString::from(port.to_string())]);
464        }
465        if let Some(alias) = &self.options.host_key_alias {
466            args.extend([
467                OsString::from("-o"),
468                OsString::from(format!("HostKeyAlias={alias}")),
469            ]);
470        }
471        if let Some(identity) = &self.options.identity {
472            args.extend([
473                OsString::from("-i"),
474                identity.clone().into_os_string(),
475                OsString::from("-o"),
476                OsString::from("IdentitiesOnly=yes"),
477            ]);
478        }
479        args
480    }
481
482    fn ssh(&self) -> Command {
483        let mut command = Command::new("ssh");
484        command.args(self.ssh_options());
485        command
486    }
487
488    /// `sb <args>` on the host; the `--` keeps a host that starts with `-`
489    /// from being read as an ssh option.
490    fn remote(&self, options: &[&str], args: &[&str]) -> Command {
491        let mut command = self.ssh();
492        command
493            .args(options)
494            .arg("--")
495            .arg(&self.host)
496            .arg(&self.sb)
497            .args(args);
498        command
499    }
500}
501
502impl Transport for SshTransport {
503    fn host(&self) -> &str {
504        &self.host
505    }
506
507    fn whoami(&self) -> Result<String> {
508        let output = self
509            .remote(&[], &["whoami"])
510            .output()
511            .context("spawning ssh to resolve peer machine id")?;
512        if !output.status.success() {
513            anyhow::bail!(
514                "ssh whoami on {} exited with {}: {}",
515                self.host,
516                output.status,
517                String::from_utf8_lossy(&output.stderr).trim()
518            );
519        }
520        let id = String::from_utf8_lossy(&output.stdout).trim().to_string();
521        if id.is_empty() {
522            anyhow::bail!("peer {} returned an empty machine id", self.host);
523        }
524        Ok(id)
525    }
526
527    fn export(
528        &self,
529        after_seq: u64,
530        hello: &Hello,
531    ) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
532        let mut child = self
533            .remote(&[], &["sync-export", "--after-seq", &after_seq.to_string()])
534            .arg("--hello")
535            .arg(hello.to_arg())
536            .stdout(Stdio::piped())
537            .stderr(Stdio::inherit())
538            .spawn()
539            .context("spawning ssh for pull")?;
540        let output = child
541            .stdout
542            .take()
543            .expect("ssh export spawned with piped stdout");
544        Ok((Box::new(output), Box::new(SshRemote(child))))
545    }
546
547    fn import(&self) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
548        self.spawn_push("sync-import", &[])
549    }
550
551    fn snapshot_export(&self, hello: &Hello) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
552        let mut child = self
553            .remote(&[], &["sync-snapshot", "--hello"])
554            .arg(hello.to_arg())
555            .stdout(Stdio::piped())
556            .stderr(Stdio::inherit())
557            .spawn()
558            .context("spawning ssh for snapshot export")?;
559        let output = child
560            .stdout
561            .take()
562            .expect("ssh snapshot export spawned with piped stdout");
563        Ok((Box::new(output), Box::new(SshRemote(child))))
564    }
565
566    fn snapshot_import(
567        &self,
568    ) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
569        self.spawn_push("sync-snapshot", &["--apply"])
570    }
571}
572
573impl SshTransport {
574    fn spawn_push(
575        &self,
576        command: &str,
577        extra: &[&str],
578    ) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
579        let mut child = self
580            .remote(
581                &[
582                    "-o",
583                    "ServerAliveInterval=60",
584                    "-o",
585                    "ServerAliveCountMax=60",
586                ],
587                &[command],
588            )
589            .args(extra)
590            .stdin(Stdio::piped())
591            .stdout(Stdio::piped())
592            .stderr(Stdio::inherit())
593            .spawn()
594            .context("spawning ssh for push")?;
595        let input = child
596            .stdin
597            .take()
598            .expect("ssh push spawned with piped stdin");
599        let output = child
600            .stdout
601            .take()
602            .expect("ssh push spawned with piped stdout");
603        Ok((
604            Box::new(input),
605            Box::new(output),
606            Box::new(SshRemote(child)),
607        ))
608    }
609}
610
611struct SshRemote(Child);
612
613impl Remote for SshRemote {
614    fn wait(&mut self) -> Result<Exit> {
615        let status = self.0.wait()?;
616        Ok(Exit {
617            success: status.success(),
618            status: status.to_string(),
619        })
620    }
621
622    fn stop(&mut self) -> Result<()> {
623        if let Err(e) = self.0.kill() {
624            tracing::debug!("ssh already exited: {e}");
625        }
626        self.0.wait()?;
627        Ok(())
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634
635    const KEY_1: &str =
636        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
637    const KEY_2: &str = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC0";
638
639    fn transport() -> SshTransport {
640        SshTransport {
641            host: "box".to_string(),
642            sb: "sb".to_string(),
643            known_hosts: PathBuf::from("/tmp/kh"),
644            unattended: false,
645            options: ConnectOptions::default(),
646            ephemeral: None,
647        }
648    }
649
650    fn args_of(command: &Command) -> Vec<String> {
651        command
652            .get_args()
653            .map(|a| a.to_string_lossy().into_owned())
654            .collect()
655    }
656
657    fn has_pair(args: &[String], a: &str, b: &str) -> bool {
658        args.windows(2).any(|w| w[0] == a && w[1] == b)
659    }
660
661    #[test]
662    fn an_ephemeral_identity_reaches_ssh_and_goes_with_the_transport() {
663        let base = tempfile::tempdir().unwrap();
664        let data_dir = tempfile::tempdir().unwrap();
665        let key = ed25519_dalek::SigningKey::from_bytes(&[3; 32]);
666        let identity =
667            EphemeralIdentity::create_in(base.path(), data_dir.path(), &key, "sb").unwrap();
668        let path = identity.path().to_string_lossy().into_owned();
669        let t = transport().ephemeral_identity(identity);
670        let args = args_of(&t.ssh());
671        assert!(has_pair(&args, "-i", &path));
672        assert!(has_pair(&args, "-o", "IdentitiesOnly=yes"));
673        drop(t);
674        assert!(!Path::new(&path).exists());
675    }
676
677    #[test]
678    fn device_alias_prefixes_machine_id() {
679        assert_eq!(device_alias("m-1"), "sb-m-1");
680    }
681
682    #[test]
683    fn builder_options_reach_the_ssh_command() {
684        let t = transport()
685            .known_hosts(PathBuf::from("/x/known"))
686            .port(2222)
687            .host_key_alias("sb-m-1")
688            .identity(PathBuf::from("/x/id"))
689            .unattended();
690        let args = args_of(&t.ssh());
691        assert!(has_pair(&args, "-o", "UserKnownHostsFile=/x/known"));
692        assert!(has_pair(&args, "-p", "2222"));
693        assert!(has_pair(&args, "-o", "HostKeyAlias=sb-m-1"));
694        assert!(has_pair(&args, "-i", "/x/id"));
695        assert!(has_pair(&args, "-o", "IdentitiesOnly=yes"));
696        assert!(has_pair(&args, "-o", "BatchMode=yes"));
697    }
698
699    #[test]
700    fn the_host_is_never_read_as_an_option() {
701        let mut t = transport();
702        t.host = "-oProxyCommand=touch /tmp/x".to_string();
703        let args = args_of(&t.remote(&["-o", "ServerAliveInterval=60"], &["whoami"]));
704        let end = args.len();
705        assert_eq!(
706            args[end - 4..],
707            ["--", "-oProxyCommand=touch /tmp/x", "sb", "whoami"]
708        );
709        assert!(has_pair(&args, "-o", "ServerAliveInterval=60"));
710    }
711
712    #[test]
713    fn default_transport_adds_no_extra_options() {
714        let args = args_of(&transport().ssh());
715        assert!(!args.iter().any(|a| a == "-p" || a == "-i"));
716        assert!(!args.iter().any(|a| a.starts_with("HostKeyAlias")));
717    }
718
719    #[test]
720    fn pin_alias_adds_missing_keys_once() {
721        let dir = tempfile::tempdir().unwrap();
722        let path = dir.path().join("known_hosts");
723        std::fs::write(&path, "other ssh-rsa ZZZ").unwrap();
724        let keys = vec![format!("{KEY_1} comment"), KEY_2.to_string()];
725        assert!(pin_alias(&path, "sb-m-1", &keys).unwrap());
726        let text = std::fs::read_to_string(&path).unwrap();
727        assert_eq!(
728            text,
729            format!("other ssh-rsa ZZZ\nsb-m-1 {KEY_1}\nsb-m-1 {KEY_2}\n")
730        );
731        assert!(!pin_alias(&path, "sb-m-1", &keys).unwrap());
732        assert_eq!(std::fs::read_to_string(&path).unwrap(), text);
733        assert!(pin_alias(&path, "sb-m-2", &keys[..1]).unwrap());
734        assert_eq!(
735            std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
736            0o600
737        );
738    }
739
740    #[test]
741    fn unpinning_a_device_drops_its_alias_and_its_keys_under_other_names() {
742        let dir = tempfile::tempdir().unwrap();
743        let path = dir.path().join("known_hosts");
744        let original = format!(
745            "# 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"
746        );
747        std::fs::write(&path, &original).unwrap();
748        let pin = |alias: &str, key: Option<&str>| DevicePin {
749            alias: alias.to_string(),
750            signed_host_key: key.map(str::to_string),
751        };
752        assert!(unpin_devices(&path, &[pin("sb-m-1", None)], &[pin("sb-m-10", None)]).unwrap());
753        assert_eq!(
754            std::fs::read_to_string(&path).unwrap(),
755            format!("# note\n[host]:2222 {KEY_2}\nsb-m-10 {KEY_2}\n")
756        );
757        let before = std::fs::metadata(&path).unwrap().modified().unwrap();
758        assert!(!unpin_devices(&path, &[pin("sb-m-1", None)], &[pin("sb-m-10", None)]).unwrap());
759        assert_eq!(
760            std::fs::metadata(&path).unwrap().modified().unwrap(),
761            before
762        );
763
764        assert!(unpin_devices(&path, &[pin("sb-m-10", Some(KEY_2))], &[]).unwrap());
765        assert_eq!(std::fs::read_to_string(&path).unwrap(), "# note\n");
766        assert!(!unpin_devices(&dir.path().join("none"), &[pin("sb-m-1", None)], &[]).unwrap());
767    }
768
769    #[test]
770    fn a_rotated_host_key_replaces_the_old_one_of_its_type() {
771        let dir = tempfile::tempdir().unwrap();
772        let path = dir.path().join("known_hosts");
773        let rotated = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIRotatedHostKeyOfTheDevice";
774        pin_alias(&path, "sb-m-1", &[KEY_1.to_string(), KEY_2.to_string()]).unwrap();
775        pin_alias(&path, "sb-m-2", &[KEY_1.to_string()]).unwrap();
776        assert!(pin_alias(&path, "sb-m-1", &[rotated.to_string()]).unwrap());
777        assert_eq!(
778            std::fs::read_to_string(&path).unwrap(),
779            format!("sb-m-1 {KEY_2}\nsb-m-2 {KEY_1}\nsb-m-1 {rotated}\n")
780        );
781    }
782
783    #[test]
784    fn an_alias_that_could_add_a_known_hosts_line_is_refused() {
785        let dir = tempfile::tempdir().unwrap();
786        let path = dir.path().join("known_hosts");
787        let keys = [KEY_1.to_string()];
788        for alias in [
789            "sb-x\n@cert-authority *",
790            "sb-x y",
791            "sb-x\0",
792            "@revoked",
793            "",
794        ] {
795            assert!(pin_alias(&path, alias, &keys).is_err(), "{alias:?}");
796        }
797        assert!(!path.exists());
798    }
799
800    #[test]
801    fn concurrent_pins_of_one_file_all_land() {
802        let dir = tempfile::tempdir().unwrap();
803        let path = dir.path().join("known_hosts");
804        let threads: Vec<_> = (0..8)
805            .map(|t| {
806                let path = path.clone();
807                std::thread::spawn(move || {
808                    for i in 0..25 {
809                        pin_alias(&path, &format!("sb-{t}-{i}"), &[KEY_1.to_string()]).unwrap();
810                    }
811                })
812            })
813            .collect();
814        for thread in threads {
815            thread.join().unwrap();
816        }
817        assert_eq!(std::fs::read_to_string(&path).unwrap().lines().count(), 200);
818    }
819}