garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/sshcfg.rs

raw

//! `midas ssh-config`: the `Host` blocks for every node, from the registry, so
//! adding a node is a registry entry rather than a hand-edited ssh config on
//! every machine that talks to it.
//!
//! Two kinds of caller:
//!
//! * **an agent's container** (`--flush`): its key, connection sharing, and the
//!   `Match … !exec "midas holds %n"` barrier (refuse, or flush) that makes a node follow the
//!   worktree (DESIGN.md §7);
//! * **the hub's machine** (no `--flush`): its operator key, for the warmer and
//!   the reachability check.
//!
//! `--write FILE` replaces the block between the markers (or appends it), after
//! a backup beside the file; without it the block goes to stdout.

use std::fs;
use std::path::Path;

use anyhow::{Context, Result};


const BEGIN: &str = "# >>> midas nodes (generated by `midas ssh-config`; change the registry, not this)";
const END: &str = "# <<< midas nodes";

pub struct Opts {
    pub identity: String,
    pub known_hosts: String,
    pub flush: bool,
    pub write: Option<String>,
}

impl Opts {
    /// An agent's: its key and known-hosts file from the arguments, else from
    /// `hub.env` (`MIDAS_SSH_KEY`), else the usual places.
    pub fn agent(identity: Option<String>, known_hosts: Option<String>, flush: bool, write: Option<String>) -> Opts {
        Opts {
            identity: identity.or_else(|| crate::client::setting("MIDAS_SSH_KEY")).unwrap_or_else(|| "~/.ssh/id_ed25519".into()),
            known_hosts: known_hosts.unwrap_or_else(|| "~/.config/midas/known_hosts".into()),
            flush,
            write,
        }
    }
}

/// The generated block for this machine.
pub fn block(o: &Opts) -> String {
    block_for(&crate::client::nodes().unwrap_or_default(), o)
}

/// `known_hosts` lines for every node that has told the hub its host key.
pub fn known_hosts(nodes: &[serde_json::Value]) -> String {
    nodes.iter().filter_map(|n| {
        Some(format!("[{}]:{} {}\n", n["address"].as_str()?, n["ssh_port"].as_u64()?, n["host_key"].as_str()?))
    }).collect()
}

pub fn block_for(nodes: &[serde_json::Value], o: &Opts) -> String {
    let mut b = vec![BEGIN.to_string()];
    let me = crate::util::exe().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|_| "midas".into());
    // ~/.local/bin/midas rather than the path the exe resolves to, when that
    // link is how this machine reaches it: a container recreate keeps the
    // link's name while the volume path behind it may change.
    let link = std::env::var("HOME").map(|h| format!("{h}/.local/bin/midas")).unwrap_or_default();
    let same = |a: &str, b: &str| fs::canonicalize(a).ok().is_some_and(|x| fs::canonicalize(b).ok() == Some(x));
    let me = if !link.is_empty() && same(&link, &me) { link } else { me };
    let aliases: Vec<&str> = nodes.iter().filter_map(|n| n["id"].as_str()).collect();
    if o.flush {
        // First, so its settings win (ssh keeps the first value it reads): a
        // worktree that does not hold the node gets no connection — and no shared
        // master connection either, which would otherwise carry it straight into
        // the holder's session.
        // The same command brings a node this worktree holds up to date with
        // it before every ssh/scp/rsync/git (the flush): one hub question for
        // both. Its block applies only on a refusal.
        b.push("# A worktree that does not hold the node is refused here, with the reason;".into());
        b.push("# one that holds it brings it up to date with the worktree first.".into());
        b.push(format!("Match originalhost {} !exec \"{me} holds %n\"", aliases.join(",")));
        b.push("    ProxyCommand /bin/false".into());
        b.push("    ControlMaster no".into());
        b.push("    ControlPath none".into());
    }
    for n in nodes {
        let (Some(alias), Some(addr)) = (n["id"].as_str(), n["address"].as_str()) else { continue };
        b.push(format!("Host {alias}"));
        b.push(format!("    HostName {addr}"));
        b.push(format!("    Port {}", n["ssh_port"].as_u64().unwrap_or(22)));
        b.push("    User build".into());
        b.push(format!("    IdentityFile {}", o.identity));
        b.push("    IdentitiesOnly yes".into());
        b.push(format!("    UserKnownHostsFile {}", o.known_hosts));
        // The node's host key comes from the hub (the node registers it), so a
        // node set up again is recognised without anybody editing known_hosts.
        b.push(format!("    StrictHostKeyChecking {}", if n["host_key"].is_string() { "yes" } else { "accept-new" }));
        b.push("    ServerAliveInterval 30".into());
        // A node that is off (a Mac asleep) otherwise costs TCP's own two minutes, twice (the
        // flush, then the command): longer than an agent's command may run.
        b.push("    ConnectTimeout 15".into());
        if o.flush {
            // One connection for the flush and the command after it, kept
            // for the commands after that: a new one costs ~1 s more (1.7 s
            // against 0.6 s to a Mac's node), and an agent often reads and
            // edits for longer than a few minutes between two builds. An idle
            // one is no session to the node (procs::ssh_sessions).
            b.push("    ControlMaster auto".into());
            b.push("    ControlPath ~/.ssh/cm-%C".into());
            b.push("    ControlPersist 30m".into());
        }
    }
    // Back to "every host" so whatever follows this block in the file means what
    // it meant before the block was there.
    b.push("Match all".into());
    b.push(END.into());
    b.join("\n") + "\n"
}

/// The generated block currently in `path`, if there is one.
pub fn installed(path: &str) -> Option<String> {
    let text = fs::read_to_string(path).ok()?;
    let (s, e) = (text.find(BEGIN)?, text.find(END)?);
    if e < s {
        return None;
    }
    Some(text[s..e + END.len()].to_string() + "\n")
}

fn expand(p: &str) -> String {
    match p.strip_prefix("~/") {
        Some(rest) => format!("{}/{rest}", std::env::var("HOME").unwrap_or_default()),
        None => p.to_string(),
    }
}

/// Replace a whole file, atomically, if it changed.
pub fn write_if_changed(path: &str, body: &str, mode: u32) -> Result<bool> {
    if fs::read_to_string(path).is_ok_and(|old| old == body) {
        return Ok(false);
    }
    if let Some(d) = Path::new(path).parent() {
        fs::create_dir_all(d)?;
    }
    let tmp = format!("{path}.midas-tmp");
    fs::write(&tmp, body)?;
    fs::set_permissions(&tmp, std::os::unix::fs::PermissionsExt::from_mode(mode))?;
    fs::rename(&tmp, path)?;
    Ok(true)
}

pub fn ssh_config(o: &Opts) -> Result<i32> {
    let all = crate::client::nodes()?;
    let block = block_for(&all, o);
    let nodes = all.len();
    if o.write.is_some() {
        write_if_changed(&expand(&o.known_hosts), &known_hosts(&all), 0o644)?;
    }
    let Some(path) = &o.write else {
        print!("{block}");
        return Ok(0);
    };
    let old = fs::read_to_string(path).unwrap_or_default();
    let new = match (old.find(BEGIN), old.find(END)) {
        (Some(s), Some(e)) if e > s => {
            let tail = &old[e + END.len()..];
            format!("{}{}{}", &old[..s], block.trim_end_matches('\n'), tail)
        }
        _ => format!("{}{}{block}", old, if old.is_empty() || old.ends_with("\n\n") { "" } else if old.ends_with('\n') { "\n" } else { "\n\n" }),
    };
    if new == old {
        eprintln!("{path}: already current");
        return Ok(0);
    }
    if !old.is_empty() {
        fs::write(format!("{path}.bak-midas"), &old).context("writing the backup")?;
    }
    let tmp = format!("{path}.midas-tmp");
    fs::write(&tmp, &new)?;
    fs::set_permissions(&tmp, std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
    fs::rename(&tmp, path)?;
    eprintln!("{path}: {nodes} node(s) written (previous copy in {path}.bak-midas)");
    Ok(0)
}