garage44.eu/jeroen/midas

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

.. /src/setup.rs

raw

//! `sudo midas setup <node>`: make this machine a build node, in one command.
//!
//! Run by the machine's owner, as root, with a midas they built themselves. It
//! is the only root step and nothing of it stays running as root:
//!
//! 1. a user of its own for the node (never the owner's account), with
//!    subordinate ids and lingering, its home on the big partition;
//! 2. a firewall **on the machine**, keyed on that user, so whatever runs in the
//!    node cannot reach the machine's network: the hub and the internet (IPv4)
//!    yes; private addresses, the machine's own addresses (but its public web
//!    ports) and IPv6 no. Traffic arriving over the tunnel may reach the node's
//!    ssh port and nothing else on the machine;
//! 3. the node itself, installed as that user from the recipe compiled into
//!    this binary (`node/`): nothing is downloaded from the hub and run here.
//!
//! What the node is — its address, port and the public keys that may log in —
//! comes from the hub (`GET /v1/nodes/<node>/config`), where an agent added it.
//! Trusting the hub for that is safe: it decides only what happens *inside*
//! the container, which is untrusted anyway. The machine's own protection —
//! the user and the firewall — is decided here and nothing inside can change it.
//!
//! The bots' secret is set apart from all this, by `midas bot setup`
//! (`botsetup`), into the same configuration directory.
//!
//! The local settings (limits, GPU, mounts) are kept in
//! `/etc/midas/node-<node>.conf`, so `sudo midas setup <node>` again re-applies
//! them: after building a newer midas, or to repair.

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;

const KIT: &[(&str, &str)] = &[
    ("Containerfile", include_str!("../node/Containerfile")),
    ("sshd_config", include_str!("../node/sshd_config")),
    ("entrypoint.sh", include_str!("../node/entrypoint.sh")),
    ("install.sh", include_str!("../node/install.sh")),
];

/// Bump when a change to the machine side of setup — this file or
/// setup_macos.rs: the node's user, the firewall, the units, the VM — must
/// reach machines that are already set up. The node recipes (`node/`) count
/// by themselves.
const MACHINE_SETUP_EPOCH: &str = "1";

/// What `sudo midas setup` puts on a machine, as eight hex digits: the node's
/// recipe (container or VM) and the machine side's epoch. A node reports the
/// one it was set up from; a different one from the hub's is what still needs
/// its owner's sudo. A newer midas alone does not: the node takes that from
/// the hub (`midas node update`).
pub fn recipe() -> String {
    // FNV-1a: stable across builds and Rust versions, which DefaultHasher is not.
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    let parts = [("epoch", MACHINE_SETUP_EPOCH)].into_iter().chain(KIT.iter().copied())
        .chain(crate::setup_macos::recipe_parts());
    for (name, body) in parts {
        for b in name.bytes().chain([0]).chain(body.bytes()).chain([0]) {
            h ^= u64::from(b);
            h = h.wrapping_mul(0x0100_0000_01b3);
        }
    }
    format!("{:08x}", h >> 32)
}

/// This machine's settings for one node. Everything else comes from the hub.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct NodeConf {
    pub node: String,
    /// The hub, ADDRESS:PORT on the tunnel.
    pub hub: String,
    pub user: String,
    pub memory: String,
    pub cpus: String,
    /// The GPU render node, or `none`.
    pub render_node: String,
    #[serde(default)]
    pub mounts: Vec<String>,
    /// macOS: the VM image a node is built from (default: Cirrus Labs' macOS with Xcode).
    #[serde(default)]
    pub image: Option<String>,
    /// macOS: the VM's disk, in GB.
    #[serde(default)]
    pub disk_gb: Option<u32>,
    /// The variable `midas bot setup` stores the bots' secret as.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bot_env: Option<String>,
    /// The node's identity at the hub, which outlives its name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// What holds the node's data — the podman volume mounted at /work, or on
    /// a Mac the Tart VM. Named once, when the node is first set up, and never
    /// again from the node's name, so a rename moves nothing. Absent in a file
    /// from before this was recorded: see [`NodeConf::storage`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub storage: Option<String>,
}

impl NodeConf {
    /// The volume (Linux) or VM (macOS) with the node's data in it.
    pub fn storage(&self) -> String {
        self.storage.clone().unwrap_or_else(|| storage_by_name(&self.node))
    }
}

/// Where a node set up before storage was named kept its data: under its name.
pub(crate) fn storage_by_name(node: &str) -> String {
    if cfg!(target_os = "macos") { format!("midas-{node}") } else { format!("midas-node-{node}-work") }
}

/// Where a new node keeps its data: under its uuid.
pub(crate) fn storage_by_uuid(uuid: &str) -> String {
    if cfg!(target_os = "macos") { format!("midas-{uuid}") } else { format!("midas-work-{uuid}") }
}

/// The storage a node is set up with. Once named it stays named. A node that
/// was already here (under this name, or under the one it was renamed from)
/// before storage was recorded has its data under that name; a new one gets
/// its uuid's, or its name's from a hub too old to give a uuid.
pub(crate) fn storage_for(recorded: Option<&str>, here_as: Option<&str>, uuid: Option<&str>, node: &str) -> String {
    match (recorded, here_as, uuid) {
        (Some(s), _, _) => s.to_string(),
        (None, Some(name), _) => storage_by_name(name),
        (None, None, Some(u)) => storage_by_uuid(u),
        (None, None, None) => storage_by_name(node),
    }
}

/// Among this machine's nodes, the one the hub has renamed to the node being
/// set up: the same uuid, or failing that (a node set up before uuids) a name
/// the hub says it used to have.
pub(crate) fn pick_predecessor<'a>(here: &'a [NodeConf], uuid: Option<&str>, former: &[String]) -> Option<&'a NodeConf> {
    uuid.and_then(|u| here.iter().find(|c| c.uuid.as_deref() == Some(u)))
        .or_else(|| here.iter().find(|c| c.uuid.is_none() && former.contains(&c.node)))
}

#[derive(Default)]
pub struct Args {
    pub node: String,
    pub hub: Option<String>,
    pub memory: Option<String>,
    pub cpus: Option<String>,
    pub render_node: Option<String>,
    pub mounts: Vec<String>,
    pub user: Option<String>,
    pub remove: bool,
    pub image: Option<String>,
    pub disk_gb: Option<u32>,
    /// macOS: build the VM image again, losing the node's disk (its warm build).
    pub rebuild: bool,
}

fn name_ok(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

pub fn merge(stored: Option<NodeConf>, a: Args) -> Result<NodeConf> {
    if !name_ok(&a.node) {
        bail!("the node's name is lowercase letters, digits and dashes");
    }
    let mut c = stored.unwrap_or(NodeConf {
        node: a.node.clone(),
        hub: String::new(),
        user: "midas-node".into(),
        // A macOS node is a whole VM with Xcode in it; two fit on a 64 GB machine.
        memory: if cfg!(target_os = "macos") { "24g".into() } else { "10g".into() },
        cpus: "6".into(),
        render_node: "/dev/dri/renderD128".into(),
        mounts: vec![],
        image: None,
        disk_gb: None,
        bot_env: None,
        uuid: None,
        storage: None,
    });
    c.node = a.node;
    if let Some(v) = a.hub { c.hub = v.trim_start_matches("http://").to_string(); }
    if let Some(v) = a.user { c.user = v; }
    if let Some(v) = a.memory { c.memory = v; }
    if let Some(v) = a.cpus { c.cpus = v; }
    if let Some(v) = a.render_node { c.render_node = v; }
    if !a.mounts.is_empty() { c.mounts = a.mounts; }
    if a.image.is_some() { c.image = a.image; }
    if a.disk_gb.is_some() { c.disk_gb = a.disk_gb; }
    if c.hub.is_empty() {
        bail!("the first time, say where the hub is: sudo midas setup {} --hub ADDRESS:PORT", c.node);
    }
    c.hub.parse::<std::net::SocketAddrV4>().map_err(|_| anyhow!("--hub is ADDRESS:PORT, not {:?}", c.hub))?;
    if !name_ok(&c.user) {
        bail!("--user is lowercase letters, digits and dashes");
    }
    if !c.memory.trim_end_matches(['k', 'm', 'g']).parse::<u64>().is_ok_and(|n| n > 0) {
        bail!("--memory is like 10g");
    }
    if !c.cpus.parse::<f64>().is_ok_and(|n| n > 0.0) {
        bail!("--cpus is a number");
    }
    for m in &c.mounts {
        if !m.contains(":/") || m.contains(['\n', ' ']) {
            bail!("--mount is HOST_DIR:/CONTAINER_DIR, not {m:?}");
        }
    }
    Ok(c)
}

pub(crate) fn conf_path(node: &str) -> String {
    format!("/etc/midas/node-{node}.conf")
}

pub(crate) fn table(node: &str) -> String {
    format!("midas_{}", node.replace('-', "_"))
}

pub(crate) fn firewall_unit(node: &str) -> String {
    format!("midas-firewall-{node}.service")
}

/// What the hub says about the node: `GET /v1/nodes/<node>/config`.
#[derive(Debug, Clone)]
pub struct FromHub {
    pub address: String,
    pub port: u16,
    pub repo: String,
    pub agent_keys: Vec<String>,
    pub operator_keys: Vec<String>,
    /// None from a hub older than uuids.
    pub uuid: Option<String>,
}

/// What to look at when the hub does not answer. Each clause is a way this
/// has actually failed: the tunnel down after the machine's public address
/// changed, a tunnel up whose route NetworkManager never added (so the
/// traffic left over the LAN), and the machine's own address given as the hub's.
pub(crate) fn hub_unreachable(hub: &str) -> String {
    let ip = hub.rsplit_once(':').map(|(ip, _)| ip).unwrap_or(hub);
    format!("is WireGuard up? `sudo wg show` should show a handshake under two minutes old, \
             `ip route get {ip}` should name the tunnel and not the LAN, and {ip} must be the hub's \
             address, not this machine's (docs/node.md, \"Check the tunnel\")")
}

fn hub_config(hub: &str, node: &str) -> Result<(u16, Value)> {
    let url = format!("http://{hub}");
    let (code, body) = crate::hub::request(&url, "GET", &format!("/v1/nodes/{node}/config"), None)
        .with_context(|| format!("asking the hub at {url} — {}", hub_unreachable(hub)))?;
    Ok((code, serde_json::from_str(&body).unwrap_or_else(|_| serde_json::json!({"error": body}))))
}

pub(crate) fn from_hub(c: &NodeConf) -> Result<FromHub> {
    let (code, v) = hub_config(&c.hub, &c.node)?;
    if code != 200 {
        bail!("the hub: {}", v["error"].as_str().unwrap_or("no answer"));
    }
    let keys = |k: &str| -> Vec<String> {
        v[k].as_array().into_iter().flatten().filter_map(|x| x.as_str()).filter_map(crate::registry::ed25519_key).collect()
    };
    let out = FromHub {
        address: v["address"].as_str().unwrap_or_default().to_string(),
        port: v["port"].as_u64().and_then(|p| u16::try_from(p).ok()).ok_or_else(|| anyhow!("the hub gave no port"))?,
        repo: v["repo"].as_str().unwrap_or_default().to_string(),
        agent_keys: keys("agent_keys"),
        operator_keys: keys("operator_keys"),
        uuid: v["uuid"].as_str().filter(|u| crate::registry::is_uuid(u)).map(str::to_string),
    };
    out.address.parse::<std::net::Ipv4Addr>().map_err(|_| anyhow!("the hub gave no address"))?;
    crate::mirror::repo_name(&out.repo)?;
    if out.agent_keys.is_empty() && out.operator_keys.is_empty() {
        bail!("the hub has no keys for anyone to log in with (sudo midas hub setup --agent-key …)");
    }
    Ok(out)
}

/// A machine's addresses, as `ip` reports them.
#[derive(Debug, Clone)]
pub struct Addr {
    pub ifname: String,
    pub ip: std::net::IpAddr,
}

pub fn parse_addrs(ip_o_addr: &str) -> Vec<Addr> {
    // `2: wg0    inet 10.44.0.1/24 scope global wg0 ...`
    ip_o_addr.lines().filter_map(|l| {
        let w: Vec<&str> = l.split_whitespace().collect();
        let fam = w.iter().position(|x| *x == "inet" || *x == "inet6")?;
        let (ip, _) = w.get(fam + 1)?.split_once('/')?;
        Some(Addr {
            ifname: w.get(1)?.trim_end_matches(':').split('@').next()?.to_string(),
            ip: ip.parse().ok()?,
        })
    }).collect()
}

fn is_private(ip: &std::net::IpAddr) -> bool {
    match ip {
        std::net::IpAddr::V4(a) => {
            let o = a.octets();
            a.is_private() || a.is_loopback() || a.is_link_local() || a.is_unspecified()
                || (o[0] == 100 && (64..128).contains(&o[1]))
        }
        std::net::IpAddr::V6(_) => true,
    }
}

/// The resolvers this machine uses: systemd-resolved's upstreams (`resolvectl
/// dns`), else `/etc/resolv.conf`'s. A loopback stub (127.0.0.53) is nobody
/// the node can reach and is left out.
pub fn resolvers() -> Vec<std::net::IpAddr> {
    let resolvectl = Command::new("resolvectl").arg("dns").output().ok()
        .filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();
    let resolv_conf = fs::read_to_string("/etc/resolv.conf").unwrap_or_default();
    parse_resolvers(&resolvectl, &resolv_conf)
}

fn parse_resolvers(resolvectl: &str, resolv_conf: &str) -> Vec<std::net::IpAddr> {
    let addr = |w: &str| w.split('%').next().unwrap_or("").split('#').next().unwrap_or("").parse::<std::net::IpAddr>().ok();
    let mut found: Vec<std::net::IpAddr> = resolvectl.lines()
        .filter_map(|l| l.split_once(':').map(|(_, rest)| rest))
        .flat_map(|rest| rest.split_whitespace().filter_map(addr).collect::<Vec<_>>())
        .collect();
    if found.is_empty() {
        found = resolv_conf.lines().filter_map(|l| {
            let mut w = l.split_whitespace();
            (w.next() == Some("nameserver")).then(|| w.next()).flatten().and_then(addr)
        }).collect();
    }
    found.retain(|a| !a.is_loopback() && !a.is_unspecified());
    found.sort();
    found.dedup();
    found
}

/// The firewall, as an nft file. `tunnel_if` is the interface the node's
/// address is on, when this machine is not the hub (on the hub that interface
/// also carries every other node's traffic to the hub, so it is left alone).
pub fn firewall(uid: u32, c: &NodeConf, h: &FromHub, addrs: &[Addr], tunnel_if: Option<&str>, resolvers: &[std::net::IpAddr]) -> String {
    let (hub_ip, hub_port) = c.hub.rsplit_once(':').unwrap_or((&c.hub, "4791"));
    let own4: Vec<String> = addrs.iter().filter(|a| a.ip.is_ipv4() && !is_private(&a.ip)).map(|a| a.ip.to_string()).collect();
    let set = |v: &[String]| format!("{{ {} }}", v.join(", "));
    let t = table(&c.node);
    // Name lookups go to the machine's own resolvers and nowhere else: a rule
    // that let port 53 through to any host, v4 or v6, let a node reach every
    // LAN host on it (2026-11-21). Only when none can be found at all does the
    // old rule stand, said so in the file.
    let dns4: Vec<String> = resolvers.iter().filter(|a| a.is_ipv4()).map(|a| a.to_string()).collect();
    let dns6: Vec<String> = resolvers.iter().filter(|a| a.is_ipv6()).map(|a| a.to_string()).collect();
    let dns = if dns4.is_empty() && dns6.is_empty() {
        "        # Name lookups: no resolver was found at setup, so to any host — run `midas setup` again once one is.\n\
         \x20       meta l4proto { udp, tcp } th dport 53 accept\n".to_string()
    } else {
        let mut s = "        # Name lookups, to the resolvers this machine used at setup and no other host.\n".to_string();
        if !dns4.is_empty() {
            s += &format!("        ip daddr {} meta l4proto {{ udp, tcp }} th dport 53 accept\n", set(&dns4));
        }
        if !dns6.is_empty() {
            s += &format!("        ip6 daddr {} meta l4proto {{ udp, tcp }} th dport 53 accept\n", set(&dns6));
        }
        s
    };

    let mut out = format!(
        "# Written by `midas setup {node}` — run it again rather than editing this.\n\
         # Keeps node {node} (user {user}, uid {uid}) off this machine's network.\n\
         table inet {t} {{}}\n\
         delete table inet {t}\n\
         table inet {t} {{\n\
         \x20   set private4 {{\n\
         \x20       type ipv4_addr; flags interval\n\
         \x20       elements = {{ 0.0.0.0/8, 10.0.0.0/8, 100.64.0.0/10, 127.0.0.0/8, 169.254.0.0/16,\n\
         \x20                    172.16.0.0/12, 192.0.0.0/24, 192.168.0.0/16, 198.18.0.0/15,\n\
         \x20                    224.0.0.0/4, 240.0.0.0/4 }}\n\
         \x20   }}\n\
         \x20   chain output {{\n\
         \x20       type filter hook output priority 0; policy accept;\n\
         \x20       meta skuid != {uid} accept\n\
         \x20       ct state established,related accept\n\
         \x20       # The hub: its API, and git (ssh) from its mirror.\n\
         \x20       ip daddr {hub_ip} tcp dport {{ {hub_port}, 22 }} accept\n\
         {dns}",
        node = c.node, user = c.user,
    );
    // The machine's own public addresses: what the internet sees of it (its web
    // ports — on the VPS, the map data a capture fetches), and nothing else.
    // Matched on the address as it was dialled: Docker (on the VPS) rewrites a
    // connection to the machine's own address:443 to its container's private
    // address before this hook, which then read as "private" and was dropped.
    if !own4.is_empty() {
        out += &format!("        ct original ip daddr {} ct original proto-dst {{ 80, 443 }} accept\n", set(&own4));
        out += &format!("        ip daddr {} drop\n", set(&own4));
    }
    // No IPv6 beyond name lookups. A network with IPv6 gives every device on it
    // a public address, so "block private ranges" would not cover the LAN; and
    // a laptop or handheld moves between networks, so a prefix measured now
    // would be stale on the next one. Rejected, not dropped, so programs fall
    // back to IPv4 at once instead of waiting out a timeout.
    out += "        ip daddr @private4 drop\n        meta nfproto ipv6 reject\n    }\n";
    if let Some(ifname) = tunnel_if {
        out += &format!(
            "    # From the hub's end of the tunnel: the node's ssh, and nothing else on this machine.\n\
             \x20   chain input {{\n\
             \x20       type filter hook input priority 0; policy accept;\n\
             \x20       iifname \"{ifname}\" ct state established,related accept\n\
             \x20       iifname \"{ifname}\" ip daddr {} tcp dport {} accept\n\
             \x20       iifname \"{ifname}\" drop\n\
             \x20   }}\n\
             \x20   chain forward {{\n\
             \x20       type filter hook forward priority 0; policy accept;\n\
             \x20       iifname \"{ifname}\" drop\n\
             \x20   }}\n", h.address, h.port
        );
    }
    out += "}\n";
    out
}

pub(crate) use crate::util::run;

pub(crate) fn which(name: &str) -> Option<PathBuf> {
    ["/usr/sbin", "/usr/bin", "/sbin", "/bin", "/opt/homebrew/bin", "/usr/local/bin"].iter()
        .map(|d| Path::new(d).join(name)).find(|p| p.exists())
}

pub(crate) fn write(path: &str, body: &str, mode: u32) -> Result<bool> {
    crate::sshcfg::write_if_changed(path, body, mode)
}

pub(crate) fn passwd(user: &str) -> Option<(u32, PathBuf)> {
    let pw = fs::read_to_string("/etc/passwd").ok()?;
    pw.lines().find_map(|l| {
        let f: Vec<&str> = l.split(':').collect();
        (f.first() == Some(&user)).then(|| Some((f.get(2)?.parse().ok()?, PathBuf::from(f.get(5)?))))?
    })
}

fn user_by_uid(uid: u32) -> String {
    fs::read_to_string("/etc/passwd").unwrap_or_default().lines()
        .find(|l| l.split(':').nth(2) == Some(&uid.to_string()))
        .and_then(|l| l.split(':').next().map(str::to_string)).unwrap_or(uid.to_string())
}

/// The first free range of 65536 subordinate ids after every range in use.
fn next_subid(file: &str) -> u64 {
    fs::read_to_string(file).unwrap_or_default().lines().filter_map(|l| {
        let f: Vec<&str> = l.split(':').collect();
        Some(f.get(1)?.parse::<u64>().ok()? + f.get(2)?.parse::<u64>().ok()?)
    }).max().unwrap_or(100_000).max(100_000)
}

fn ensure_user(user: &str) -> Result<(u32, PathBuf)> {
    if passwd(user).is_none() {
        // /home, not /var: on SteamOS /var is a small partition, and the node's
        // images and build directory are tens of gigabytes.
        let nologin = which("nologin").ok_or_else(|| anyhow!("no nologin shell found"))?;
        run(Command::new("useradd").args(["--system", "--create-home", "--home-dir"])
            .arg(format!("/home/{user}")).arg("--shell").arg(&nologin).args(["--comment", "midas build node"]).arg(user))?;
        println!("created user {user}");
    }
    for (file, flag) in [("/etc/subuid", "--add-subuids"), ("/etc/subgid", "--add-subgids")] {
        let has = fs::read_to_string(file).unwrap_or_default().lines().any(|l| l.split(':').next() == Some(user));
        if !has {
            let start = next_subid(file);
            run(Command::new("usermod").arg(flag).arg(format!("{start}-{}", start + 65535)).arg(user))?;
        }
    }
    run(Command::new("loginctl").args(["enable-linger", user]))?;
    let (uid, home) = passwd(user).ok_or_else(|| anyhow!("user {user} did not appear"))?;
    // Lingering starts the user's manager; the install below talks to it.
    for _ in 0..30 {
        if Path::new(&format!("/run/user/{uid}/bus")).exists() {
            break;
        }
        std::thread::sleep(Duration::from_secs(1));
    }
    Ok((uid, home))
}

/// The uid listening on `ip:port`, if anything is.
fn listener_uid(ip: &str, port: u16) -> Option<u32> {
    let out = Command::new("ss").args(["-Htlnp"]).arg(format!("src {ip} and sport = :{port}")).output().ok()?;
    let text = String::from_utf8_lossy(&out.stdout);
    let pid: u32 = text.split("pid=").nth(1)?.split(|c: char| !c.is_ascii_digit()).next()?.parse().ok()?;
    let status = fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
    status.lines().find(|l| l.starts_with("Uid:"))?.split_whitespace().nth(1)?.parse().ok()
}

/// A command as the node's user, with its systemd and podman reachable.
pub(crate) fn as_user(user: &str, uid: u32, home: &Path) -> Command {
    let mut c = Command::new("runuser");
    c.args(["-u", user, "--", "env"])
        .arg(format!("HOME={}", home.display()))
        .arg(format!("USER={user}"))
        .arg(format!("XDG_RUNTIME_DIR=/run/user/{uid}"))
        .arg(format!("DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/{uid}/bus"))
        .current_dir(home);
    c
}

/// The settings for `node`, from its own file.
pub(crate) fn stored(node: &str) -> Option<NodeConf> {
    serde_json::from_str(&fs::read_to_string(conf_path(node)).ok()?).ok()
}

/// Every node set up on this machine, from its settings file.
pub(crate) fn all_stored() -> Vec<NodeConf> {
    let mut v: Vec<NodeConf> = fs::read_dir("/etc/midas").into_iter().flatten().flatten()
        .filter_map(|e| {
            let n = e.file_name().to_string_lossy().to_string();
            n.strip_prefix("node-").and_then(|r| r.strip_suffix(".conf")).and_then(stored)
        })
        .collect();
    v.sort_by(|a, b| a.node.cmp(&b.node));
    v
}

/// The node on this machine that the hub has renamed to `node`, if one is.
/// The hub is asked at `--hub`, or at the hub each node here was set up with.
/// It must have let go of the old name: a hub that knows both is describing
/// two nodes, and taking one's data for the other is not a rename.
fn predecessor(node: &str, hub: Option<&str>) -> Result<Option<NodeConf>> {
    let here: Vec<NodeConf> = all_stored().into_iter().filter(|c| c.node != node).collect();
    if here.is_empty() {
        return Ok(None);
    }
    let mut hubs: Vec<String> = match hub {
        Some(h) => vec![h.trim_start_matches("http://").to_string()],
        None => here.iter().map(|c| c.hub.clone()).collect(),
    };
    hubs.sort();
    hubs.dedup();
    for h in hubs {
        let Ok((200, v)) = hub_config(&h, node) else { continue };
        let former: Vec<String> = v["former_names"].as_array().into_iter().flatten()
            .filter_map(|x| x.as_str().map(str::to_string)).collect();
        let Some(p) = pick_predecessor(&here, v["uuid"].as_str(), &former) else { continue };
        match hub_config(&h, &p.node) {
            Ok((404, _)) => {}
            Ok((200, _)) => bail!("the hub knows both {} and {node}, so {node} is a new node, not {} renamed; \
                                   set it up under another name, or remove {} at the hub first", p.node, p.node, p.node),
            _ => bail!("could not ask the hub whether {} is gone", p.node),
        }
        println!("{node} is {} renamed: taking over its settings and its data ({})", p.node, p.storage());
        return Ok(Some(p.clone()));
    }
    Ok(None)
}

/// Where docs/node.md installs midas: root-owned, and writable on SteamOS,
/// whose /usr is read-only.
pub(crate) const INSTALLED: &str = "/var/lib/midas/bin/midas";
const INSTALLED_DIR: &str = "/var/lib/midas/bin";

/// The PATH line for login shells, in POSIX sh so bash and zsh both read it.
/// Sourcing it twice must not put the directory in twice.
fn profile_snippet() -> String {
    format!("# Written by `midas setup`: midas as a command.\n\
             case \":$PATH:\" in\n    *:{d}:*) ;;\n    *) PATH=\"{d}:$PATH\"; export PATH ;;\nesac\n", d = INSTALLED_DIR)
}

/// The binary this runs as, at /var/lib/midas/bin/midas: a setup run from a
/// build directory (`sudo target/release/midas setup …`) installs itself, so
/// the owner never copies it by hand. Byte-equal already: nothing to do.
fn install_self() -> Result<()> {
    let me = std::env::current_exe()?;
    if me == Path::new(INSTALLED) {
        return Ok(());
    }
    let bytes = fs::read(&me)?;
    if fs::read(INSTALLED).is_ok_and(|b| b == bytes) {
        return Ok(());
    }
    fs::create_dir_all(INSTALLED_DIR)?;
    let tmp = format!("{INSTALLED}.new");
    fs::write(&tmp, &bytes)?;
    fs::set_permissions(&tmp, fs::Permissions::from_mode(0o755))?;
    fs::rename(&tmp, INSTALLED)?;
    println!("installed {INSTALLED}");
    Ok(())
}

/// Make `midas` a command for the machine's owner: in every login shell's PATH
/// and, where /usr/local is writable, for sudo too, whose secure_path never
/// holds /var/lib/midas/bin. A real file at /usr/local/bin/midas (the hub's
/// own) is left alone.
fn put_on_path() {
    if let Err(e) = install_self() {
        println!("note: could not install {INSTALLED} ({e:#}); midas stays where you built it");
        return;
    }
    let macos = cfg!(target_os = "macos");
    let profile = if macos { "/etc/paths.d/midas" } else { "/etc/profile.d/midas.sh" };
    let body = if macos { format!("{INSTALLED_DIR}\n") } else { profile_snippet() };
    match write(profile, &body, 0o644) {
        Ok(_) if macos => println!("midas is a command in new terminals ({profile})"),
        Ok(_) => println!("midas is a command in new login shells ({profile}; in this one: . {profile})"),
        Err(e) => println!("note: could not write {profile} ({e:#}); add {INSTALLED_DIR} to your PATH yourself"),
    }
    let link = Path::new("/usr/local/bin/midas");
    let sudo = match fs::symlink_metadata(link) {
        Ok(m) if m.file_type().is_symlink() => fs::read_link(link).ok().as_deref() == Some(Path::new(INSTALLED)),
        Ok(_) => true, // a midas of its own is already there
        Err(_) => fs::create_dir_all("/usr/local/bin").and_then(|_| std::os::unix::fs::symlink(INSTALLED, link)).is_ok(),
    };
    if !sudo {
        println!("note: /usr/local/bin/midas could not be linked here, so with sudo give the full path: sudo {INSTALLED} …");
    }
}

pub fn setup(a: Args) -> Result<i32> {
    if unsafe { libc::geteuid() } != 0 {
        bail!("run it as root: sudo midas setup <node> …");
    }
    let (remove, rebuild) = (a.remove, a.rebuild);
    let node = a.node.clone();
    let mine = stored(&node);
    if remove {
        let c = merge(mine, a)?;
        return if cfg!(target_os = "macos") { crate::setup_macos::remove(&c) } else { remove_node(&c) };
    }
    // A node the hub renamed runs here under its old name: carry it over.
    let old = if mine.is_none() { predecessor(&node, a.hub.as_deref())? } else { None };
    let here_as = old.as_ref().map(|p| p.node.clone()).or_else(|| mine.is_some().then(|| node.clone()));
    let mut c = merge(mine.or_else(|| old.clone()), a)?;
    put_on_path();
    let h = from_hub(&c)?;
    c.storage = Some(storage_for(c.storage.as_deref(), here_as.as_deref(), h.uuid.as_deref(), &node));
    if h.uuid.is_some() {
        c.uuid = h.uuid.clone();
    }
    if cfg!(target_os = "macos") {
        return crate::setup_macos::setup(&c, &h, old.as_ref(), rebuild);
    }
    let nft = which("nft").ok_or_else(|| anyhow!("nft (nftables) is not installed; the firewall needs it"))?;
    for tool in ["podman", "ip", "ss", "runuser", "loginctl", "useradd"] {
        which(tool).ok_or_else(|| anyhow!("{tool} is not installed"))?;
    }
    let addrs = parse_addrs(&run(Command::new("ip").args(["-o", "addr", "show"]))?);
    let tunnel = addrs.iter().find(|x| x.ip.to_string() == h.address)
        .ok_or_else(|| anyhow!("{} (the hub's address for {node}) is not on this machine — is its WireGuard up?", h.address))?
        .ifname.clone();
    let hub_ip = c.hub.rsplit_once(':').map(|(ip, _)| ip).unwrap_or(&c.hub);
    let is_hub = addrs.iter().any(|x| x.ip.to_string() == hub_ip);

    // 1. The user.
    let (uid, home) = ensure_user(&c.user)?;
    if let Some(p) = &old {
        // Its container, unit and firewall go; its volume stays, now this node's.
        stop_node(p);
        // The bots' secret lives in the node's configuration directory.
        let cfg = home.join(".config/midas");
        if cfg.join(&p.node).is_dir() && !cfg.join(&node).exists() {
            fs::rename(cfg.join(&p.node), cfg.join(&node)).context("moving the node's configuration")?;
        }
        // Its image is built again under the new name; the old one is only space.
        for tag in ["latest", "previous"] {
            let _ = as_user(&c.user, uid, &home)
                .args(["podman", "image", "rm", &format!("localhost/midas-node-{}:{tag}", p.node)]).output();
        }
    }
    if let Some(other) = listener_uid(&h.address, h.port).filter(|u| *u != uid) {
        let name = user_by_uid(other);
        bail!("{}:{} is already served by user {name} — an older node. Stop it first, as {name}:\n  \
               systemctl --user disable --now midas-node-{node}\n(its image and volume are kept; remove them later with podman)",
              h.address, h.port);
    }
    fs::create_dir_all("/etc/midas")?;
    write(&conf_path(&node), &(serde_json::to_string_pretty(&c)? + "\n"), 0o644)?;

    // 2. The firewall, loaded now and at every boot, before the network.
    let rules_path = format!("/etc/midas/firewall-{node}.nft");
    let dns = resolvers();
    if dns.is_empty() {
        eprintln!("midas: no resolver found (resolvectl dns, /etc/resolv.conf): the node may look names up at any host");
    }
    write(&rules_path, &firewall(uid, &c, &h, &addrs, (!is_hub).then_some(tunnel.as_str()), &dns), 0o644)?;
    run(Command::new(&nft).arg("-c").arg("-f").arg(&rules_path)).context("the firewall rules did not check")?;
    let unit = firewall_unit(&node);
    write(&format!("/etc/systemd/system/{unit}"), &format!(
        "# Written by `midas setup {node}`.\n[Unit]\nDescription=midas: keep node {node} off this machine's network\n\
         DefaultDependencies=no\nBefore=network-pre.target\nWants=network-pre.target\n\n\
         [Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart={n} -f {rules_path}\nExecStop={n} delete table inet {t}\n\n\
         [Install]\nWantedBy=sysinit.target\n", n = nft.display(), t = table(&node)), 0o644)?;
    run(Command::new("systemctl").arg("daemon-reload"))?;
    run(Command::new("systemctl").args(["enable", &unit]))?;
    run(Command::new("systemctl").args(["restart", &unit]))?;
    run(Command::new(&nft).args(["list", "table", "inet", &table(&node)])).context("the firewall is not loaded")?;
    println!("firewall: in force ({rules_path}){}", if is_hub { "" } else { "; from the tunnel only the node's ssh" });

    // 3. The node, as its user, from the recipe in this binary.
    let kit = home.join(".local/share/midas/kit");
    let _ = fs::remove_dir_all(&kit);
    fs::create_dir_all(&kit)?;
    for (name, body) in KIT {
        fs::write(kit.join(name), body)?;
    }
    fs::copy("/proc/self/exe", kit.join("midas")).context("copying this midas into the image")?;
    for name in ["install.sh", "entrypoint.sh", "midas"] {
        fs::set_permissions(kit.join(name), fs::Permissions::from_mode(0o755))?;
    }
    // Only what was just written: ~/.local also holds the node's container
    // storage, whose files belong to the user's subordinate ids — a recursive
    // chown over it would break every image and volume.
    let owner = format!("{}:", c.user);
    for d in [home.join(".local"), home.join(".local/share"), home.join(".local/share/midas"), kit.clone()] {
        run(Command::new("chown").arg(&owner).arg(&d))?;
    }
    for (name, _) in KIT.iter().chain(&[("midas", "")]) {
        run(Command::new("chown").arg(&owner).arg(kit.join(name)))?;
    }
    let mut install = as_user(&c.user, uid, &home);
    install.arg("bash").arg(kit.join("install.sh"))
        .args(["--node", &node, "--listen", &format!("{}:{}", h.address, h.port), "--hub", &format!("http://{}", c.hub),
               "--repo", &h.repo, "--recipe", &recipe(), "--authorized-key", &h.agent_keys.join("\n"),
               "--memory", &c.memory, "--cpus", &c.cpus, "--render-node", &c.render_node,
               "--volume", &c.storage()]);
    for k in &h.operator_keys {
        install.args(["--operator-key", k]);
    }
    for m in &c.mounts {
        install.args(["--mount", m]);
    }
    if !install.status().context("running the node installer")?.success() {
        bail!("the node installer failed (above)");
    }

    // 4. The node registers its keys with the hub as it starts: wait to see it.
    let container = format!("midas-node-{node}");
    let mine = || -> Option<String> {
        let out = as_user(&c.user, uid, &home)
            .args(["podman", "exec", &container, "cat", "/work/.ssh-host/ssh_host_ed25519_key.pub"]).output().ok()?;
        out.status.success().then(|| String::from_utf8_lossy(&out.stdout).to_string())
            .and_then(|k| crate::registry::ed25519_key(&k))
    };
    let hubs = || -> Option<String> {
        let (_, body) = crate::hub::request(&format!("http://{}", c.hub), "GET", "/v1/state", None).ok()?;
        let st: Value = serde_json::from_str(&body).ok()?;
        st["nodes"].as_array()?.iter().find(|s| s["id"] == node.as_str())?["host_key"].as_str().map(str::to_string)
    };
    let mut registered = false;
    for _ in 0..30 {
        if let (Some(m), Some(h)) = (mine(), hubs()) {
            if m == h {
                registered = true;
                break;
            }
        }
        std::thread::sleep(Duration::from_secs(2));
    }
    println!("\nmidas node {node}: running as {} (uid {uid}), {}.", c.user,
        if registered { "registered with the hub" } else { "not registered with the hub yet — it keeps trying; check the hub" });
    power_service(&c.hub);
    Ok(0)
}

/// 5. The machine's power, to the hub (power.rs): one service per machine,
/// whichever nodes it has. Not the node's business, so a failure here is a note.
fn power_service(hub: &str) {
    let r = (|| -> Result<()> {
        crate::power::place_binary()?;
        write(&format!("/etc/systemd/system/{}", crate::power::UNIT), &crate::power::unit(hub), 0o644)?;
        run(Command::new("systemctl").arg("daemon-reload"))?;
        run(Command::new("systemctl").args(["enable", crate::power::UNIT]))?;
        run(Command::new("systemctl").args(["restart", crate::power::UNIT]))?;
        Ok(())
    })();
    match r {
        Ok(()) => println!("power: reported to the hub once a minute ({}; it ends at once on a machine with no sensor)", crate::power::UNIT),
        Err(e) => println!("note: the power service did not start: {e:#}"),
    }
}

fn remove_node(c: &NodeConf) -> Result<i32> {
    stop_node(c);
    println!("node {} stopped and its firewall removed. Kept: user {u} and the node's data (volume {}).\n\
              To delete those too: sudo userdel -r {u}   (after removing any other node it runs)", c.node, c.storage(), u = c.user);
    Ok(0)
}

/// Take a node's container, unit, firewall and settings away; its data stays.
fn stop_node(c: &NodeConf) {
    let node = &c.node;
    if let Some((uid, home)) = passwd(&c.user) {
        let _ = as_user(&c.user, uid, &home)
            .args(["systemctl", "--user", "disable", "--now", &format!("midas-node-{node}.service")]).status();
        let _ = fs::remove_file(home.join(format!(".config/containers/systemd/midas-node-{node}.container")));
    }
    let unit = firewall_unit(node);
    let _ = run(Command::new("systemctl").args(["disable", "--now", &unit]));
    let _ = fs::remove_file(format!("/etc/systemd/system/{unit}"));
    let _ = run(Command::new("systemctl").arg("daemon-reload"));
    for f in [conf_path(node), format!("/etc/midas/firewall-{node}.nft")] {
        let _ = fs::remove_file(f);
    }
    // The machine's power service goes with its last node.
    if all_stored().is_empty() {
        let _ = run(Command::new("systemctl").args(["disable", "--now", crate::power::UNIT]));
        let _ = fs::remove_file(format!("/etc/systemd/system/{}", crate::power::UNIT));
        let _ = run(Command::new("systemctl").arg("daemon-reload"));
    }
}

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

    fn conf() -> NodeConf {
        merge(None, Args { node: "gpu-1".into(), hub: Some("10.44.0.1:4791".into()), ..Default::default() }).unwrap()
    }

    fn hub() -> FromHub {
        FromHub { address: "10.44.0.2".into(), port: 2223, repo: "owner/project".into(), agent_keys: vec![], operator_keys: vec![], uuid: None }
    }

    #[test]
    fn storage_is_named_once_and_never_again_from_the_name() {
        let u = "0b0e6c1e-6f8a-4c47-9d0a-5f3c2e1d0a9b";
        let (by_name, by_uuid) = (storage_by_name("deck-2"), storage_by_uuid(u));
        assert_eq!(storage_for(Some("midas-work-x"), Some("deck-2"), Some(u), "deck-1"), "midas-work-x", "recorded wins");
        assert_eq!(storage_for(None, Some("deck-2"), Some(u), "deck-1"), by_name, "a node from before keeps its data");
        assert_eq!(storage_for(None, None, Some(u), "deck-1"), by_uuid, "a new node gets its uuid's");
        assert_eq!(storage_for(None, None, None, "deck-1"), storage_by_name("deck-1"), "an old hub, no uuid");
        if cfg!(target_os = "macos") {
            assert_eq!((by_name.as_str(), by_uuid.as_str()), ("midas-deck-2", "midas-0b0e6c1e-6f8a-4c47-9d0a-5f3c2e1d0a9b"));
        } else {
            assert_eq!((by_name.as_str(), by_uuid.as_str()), ("midas-node-deck-2-work", "midas-work-0b0e6c1e-6f8a-4c47-9d0a-5f3c2e1d0a9b"));
        }
        let mut c = conf();
        assert_eq!(c.storage(), storage_by_name("gpu-1"), "a settings file without it");
        c.storage = Some("midas-work-x".into());
        c.node = "renamed".into();
        assert_eq!(c.storage(), "midas-work-x", "a name change does not move it");
    }

    #[test]
    fn a_renamed_node_is_found_by_its_uuid_or_failing_that_a_former_name() {
        let u = "0b0e6c1e-6f8a-4c47-9d0a-5f3c2e1d0a9b";
        let mut a = conf();
        a.node = "deck-2".into();
        let mut b = conf();
        b.node = "mac-1".into();
        b.uuid = Some(u.into());
        let here = [a, b];
        let none: [String; 0] = [];
        assert_eq!(pick_predecessor(&here, Some(u), &none).map(|c| c.node.as_str()), Some("mac-1"));
        assert_eq!(pick_predecessor(&here, Some("ffffffff-ffff-4fff-bfff-ffffffffffff"), &["deck-2".into()])
                   .map(|c| c.node.as_str()), Some("deck-2"), "set up before uuids: by the name the hub says it had");
        assert!(pick_predecessor(&here, None, &["mac-1".into()]).is_none(),
                "a node with a uuid is matched by it, never by name");
        assert!(pick_predecessor(&here, Some("ffffffff-ffff-4fff-bfff-ffffffffffff"), &none).is_none());
    }

    #[test]
    fn the_profile_snippet_puts_midas_on_the_path_once() {
        let f = tempfile::NamedTempFile::new().unwrap();
        fs::write(f.path(), profile_snippet()).unwrap();
        let p = f.path().display();
        let out = Command::new("sh").arg("-c").arg(format!(". {p}; . {p}; echo \"$PATH\""))
            .env("PATH", "/usr/bin:/bin").output().unwrap();
        assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), format!("{INSTALLED_DIR}:/usr/bin:/bin"));
    }

    // The Linux node's setup, with its render node in /dev/dri: Linux only, so a landing gated on a Mac node passes without it.
    #[cfg(target_os = "linux")]
    #[test]
    fn settings_need_only_a_name_and_keep_what_a_rerun_does_not_say() {
        let c = conf();
        assert_eq!((c.user.as_str(), c.hub.as_str(), c.memory.as_str()), ("midas-node", "10.44.0.1:4791", "10g"));
        let again = merge(Some(c), Args { node: "gpu-1".into(), memory: Some("8g".into()), ..Default::default() }).unwrap();
        assert_eq!(again.memory, "8g");
        assert_eq!(again.render_node, "/dev/dri/renderD128");
        assert!(merge(None, Args { node: "gpu-1".into(), ..Default::default() }).is_err(), "the hub is asked for once");
        assert!(merge(None, Args { node: "x;y".into(), hub: Some("10.0.0.1:1".into()), ..Default::default() }).is_err());
        assert!(merge(None, Args { node: "a".into(), hub: Some("10.0.0.1:1".into()), memory: Some("lots".into()), ..Default::default() }).is_err());
        assert!(merge(None, Args { node: "a".into(), hub: Some("10.0.0.1:1".into()), mounts: vec!["relative".into()], ..Default::default() }).is_err());
    }

    #[test]
    fn firewall_blocks_the_lan_and_ipv6_and_limits_the_tunnel() {
        let addrs = parse_addrs(
            "1: lo    inet 127.0.0.1/8 scope host lo\n\
             3: wlan0    inet 192.168.1.20/24 brd 192.168.1.255 scope global wlan0\n\
             3: wlan0    inet6 2a02:a46:1234:5600:1:2:3:4/64 scope global dynamic\n\
             7: wg0    inet 10.44.0.2/24 scope global wg0\n");
        let dns = ["192.168.1.1".parse().unwrap(), "2001:db8::53".parse().unwrap()];
        let f = firewall(991, &conf(), &hub(), &addrs, Some("wg0"), &dns);
        assert!(f.contains("table inet midas_gpu_1 {"));
        assert!(f.contains("meta skuid != 991 accept"));
        assert!(f.contains("ip daddr 10.44.0.1 tcp dport { 4791, 22 } accept"));
        assert!(f.contains("meta nfproto ipv6 reject"));
        assert!(f.contains("ip daddr @private4 drop"));
        assert!(f.contains("iifname \"wg0\" ip daddr 10.44.0.2 tcp dport 2223 accept"));
        assert!(f.contains("iifname \"wg0\" drop"));
        assert!(!f.contains("192.168.1.20") && !f.contains("2a02:"));
        // Name lookups: the machine's resolvers, before the private ranges are dropped, and no other host.
        let (r4, r6, drop) = (f.find("ip daddr { 192.168.1.1 } meta l4proto { udp, tcp } th dport 53 accept").unwrap(),
                              f.find("ip6 daddr { 2001:db8::53 } meta l4proto { udp, tcp } th dport 53 accept").unwrap(),
                              f.find("ip daddr @private4 drop").unwrap());
        assert!(r4 < drop && r6 < drop);
        assert!(!f.contains("        meta l4proto { udp, tcp } th dport 53 accept"), "no port 53 to any host");
        let open = firewall(991, &conf(), &hub(), &addrs, Some("wg0"), &[]);
        assert!(open.contains("no resolver was found") && open.contains("meta l4proto { udp, tcp } th dport 53 accept"));
    }

    #[test]
    fn resolvers_come_from_resolved_else_resolv_conf_and_never_a_loopback_stub() {
        let resolved = "Global:\nLink 2 (ens3): 1.1.1.1 2606:4700:4700::1111\nLink 5 (wg0):\nLink 3 (wlan0): 192.168.1.1%wlan0 fe80::1%wlan0\n";
        let conf = "# generated\nnameserver 127.0.0.53\nnameserver 192.168.1.1\noptions edns0\n";
        let got: Vec<String> = parse_resolvers(resolved, conf).iter().map(|a| a.to_string()).collect();
        assert_eq!(got, ["1.1.1.1", "192.168.1.1", "2606:4700:4700::1111", "fe80::1"]);
        let got: Vec<String> = parse_resolvers("", conf).iter().map(|a| a.to_string()).collect();
        assert_eq!(got, ["192.168.1.1"], "the stub is nobody the node can reach");
        assert!(parse_resolvers("Global:\n", "nameserver 127.0.0.11\n").is_empty());
    }

    #[test]
    fn on_the_hub_the_tunnel_is_left_alone_and_the_public_web_stays_reachable() {
        let addrs = parse_addrs(
            "2: ens3    inet 203.0.113.17/32 scope global ens3\n\
             5: wg0    inet 10.44.0.1/24 scope global wg0\n");
        let f = firewall(990, &conf(), &hub(), &addrs, None, &["203.0.113.53".parse().unwrap()]);
        assert!(!f.contains("chain input"));
        assert!(f.contains("ct original ip daddr { 203.0.113.17 } ct original proto-dst { 80, 443 } accept"));
        assert!(f.contains("ip daddr { 203.0.113.17 } drop"));
    }
}