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::{OpenOptionsExt, PermissionsExt};
6use std::path::{Path, PathBuf};
7use std::process::{Child, Command, Stdio};
8
9use anyhow::{Context, Result};
10use second_brain_core::machine::MachineIdentity;
11
12use crate::session::{Exit, Remote, Transport};
13
14pub fn known_hosts_path_in(config_dir: &Path) -> PathBuf {
15    config_dir.join("known_hosts")
16}
17
18pub fn known_hosts_path() -> Result<PathBuf> {
19    Ok(known_hosts_path_in(&MachineIdentity::config_dir()?))
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct KeyscanLine {
24    pub host: String,
25    pub key_type: String,
26    pub public_key: String,
27}
28
29pub fn parse_keyscan_output(raw: &str) -> Vec<KeyscanLine> {
30    raw.lines()
31        .filter_map(|line| {
32            let line = line.trim();
33            if line.is_empty() || line.starts_with('#') {
34                return None;
35            }
36            let mut parts = line.split_whitespace();
37            let host = parts.next()?;
38            let key_type = parts.next()?;
39            let public_key = parts.next()?;
40            Some(KeyscanLine {
41                host: host.to_string(),
42                key_type: key_type.to_string(),
43                public_key: public_key.to_string(),
44            })
45        })
46        .collect()
47}
48
49pub fn compose_known_host_entry(line: &KeyscanLine) -> String {
50    format!("{} {} {}\n", line.host, line.key_type, line.public_key)
51}
52
53pub fn append_known_host(path: &Path, lines: &[KeyscanLine]) -> Result<()> {
54    if let Some(parent) = path.parent()
55        && !parent.as_os_str().is_empty()
56    {
57        fs::create_dir_all(parent).context("creating known_hosts parent dir")?;
58    }
59
60    let existing = match fs::read_to_string(path) {
61        Ok(s) => s,
62        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
63        Err(e) => return Err(e).context("reading known_hosts"),
64    };
65    let already: HashSet<&str> = existing
66        .lines()
67        .map(str::trim)
68        .filter(|l| !l.is_empty())
69        .collect();
70
71    let mut file = fs::OpenOptions::new()
72        .create(true)
73        .append(true)
74        .mode(0o600)
75        .open(path)
76        .context("opening known_hosts for append")?;
77
78    for line in lines {
79        let entry = compose_known_host_entry(line);
80        if already.contains(entry.trim_end()) {
81            continue;
82        }
83        file.write_all(entry.as_bytes())
84            .context("writing known_hosts entry")?;
85    }
86
87    // because OpenOptions::mode only applies on file creation, tighten unconditionally
88    // so an existing permissive file is corrected on first append.
89    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
90        .context("setting known_hosts mode 0600")?;
91
92    Ok(())
93}
94
95pub fn untrusted_host_hint(host: &str) -> String {
96    format!(
97        "if ssh reported a host-key error, the host is not in ~/.second-brain/known_hosts yet — \
98         run `sb sync trust {host}` to verify and pin its fingerprint."
99    )
100}
101
102pub fn ssh_args(known_hosts: &Path) -> Vec<OsString> {
103    let mut user_kh = OsString::from("UserKnownHostsFile=");
104    user_kh.push(known_hosts);
105
106    vec![
107        OsString::from("-o"),
108        OsString::from("StrictHostKeyChecking=yes"),
109        OsString::from("-o"),
110        user_kh,
111        OsString::from("-o"),
112        OsString::from("GlobalKnownHostsFile=/dev/null"),
113        OsString::from("-o"),
114        OsString::from("ServerAliveInterval=30"),
115    ]
116}
117
118/// Runs the peer's `sb` over ssh, trusting only host keys pinned in this
119/// machine's known_hosts.
120pub struct SshTransport {
121    host: String,
122    sb: String,
123    known_hosts: PathBuf,
124    unattended: bool,
125}
126
127impl SshTransport {
128    pub fn new(host: &str, sb: &str) -> Result<Self> {
129        Ok(Self {
130            host: host.to_string(),
131            sb: sb.to_string(),
132            known_hosts: known_hosts_path()?,
133            unattended: false,
134        })
135    }
136
137    /// For a caller with no terminal: ssh fails instead of prompting, and an
138    /// unreachable host fails within seconds instead of the TCP timeout.
139    pub fn unattended(mut self) -> Self {
140        self.unattended = true;
141        self
142    }
143
144    fn ssh(&self) -> Command {
145        let mut command = Command::new("ssh");
146        command.args(ssh_args(&self.known_hosts));
147        if self.unattended {
148            command.args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=15"]);
149        }
150        command
151    }
152}
153
154impl Transport for SshTransport {
155    fn host(&self) -> &str {
156        &self.host
157    }
158
159    fn whoami(&self) -> Result<String> {
160        let output = self
161            .ssh()
162            .arg(&self.host)
163            .arg(&self.sb)
164            .arg("whoami")
165            .output()
166            .context("spawning ssh to resolve peer machine id")?;
167        if !output.status.success() {
168            anyhow::bail!(
169                "ssh whoami on {} exited with {}: {}",
170                self.host,
171                output.status,
172                String::from_utf8_lossy(&output.stderr).trim()
173            );
174        }
175        let id = String::from_utf8_lossy(&output.stdout).trim().to_string();
176        if id.is_empty() {
177            anyhow::bail!("peer {} returned an empty machine id", self.host);
178        }
179        Ok(id)
180    }
181
182    fn export(&self, after_seq: u64) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
183        let mut child = self
184            .ssh()
185            .arg(&self.host)
186            .arg(&self.sb)
187            .arg("sync-export")
188            .arg("--after-seq")
189            .arg(after_seq.to_string())
190            .stdout(Stdio::piped())
191            .stderr(Stdio::inherit())
192            .spawn()
193            .context("spawning ssh for pull")?;
194        let output = child
195            .stdout
196            .take()
197            .expect("ssh export spawned with piped stdout");
198        Ok((Box::new(output), Box::new(SshRemote(child))))
199    }
200
201    fn import(&self) -> Result<(Box<dyn Write + Send>, Box<dyn Remote>)> {
202        let mut child = self
203            .ssh()
204            .args([
205                "-o",
206                "ServerAliveInterval=60",
207                "-o",
208                "ServerAliveCountMax=60",
209            ])
210            .arg(&self.host)
211            .arg(&self.sb)
212            .arg("sync-import")
213            .stdin(Stdio::piped())
214            .stderr(Stdio::inherit())
215            .spawn()
216            .context("spawning ssh for push")?;
217        let input = child
218            .stdin
219            .take()
220            .expect("ssh import spawned with piped stdin");
221        Ok((Box::new(input), Box::new(SshRemote(child))))
222    }
223}
224
225struct SshRemote(Child);
226
227impl Remote for SshRemote {
228    fn wait(&mut self) -> Result<Exit> {
229        let status = self.0.wait()?;
230        Ok(Exit {
231            success: status.success(),
232            status: status.to_string(),
233        })
234    }
235
236    fn stop(&mut self) -> Result<()> {
237        if let Err(e) = self.0.kill() {
238            tracing::debug!("ssh already exited: {e}");
239        }
240        self.0.wait()?;
241        Ok(())
242    }
243}