garage44.eu/jeroen/midas

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

.. /src/setup_macos.rs

raw

//! `sudo midas setup <node>` on a Mac: the node is a macOS virtual machine.
//!
//! macOS has no container that can run Xcode safely (docs/macos-nodes.md), so
//! a node here is a Tart VM, and the boundary the owner sets is the same idea
//! as on Linux:
//!
//! 1. a user of its own (`midas-node`, hidden, no login) runs the VM;
//! 2. a firewall on the Mac (a pf anchor, loaded at boot) lets the VMs' network
//!    reach the hub's two forwarded ports and DNS on this machine, and nothing
//!    private — not the LAN, not the Mac itself — while the internet is
//!    allowed; from the tunnel only the node's ssh port gets in;
//! 3. the VM is built once from an image with Xcode (Packer + Tart), then
//!    started at boot by launchd. Everything from this machine reaches it on a
//!    read-only shared folder: the owner's midas, the node's settings and the
//!    login keys, installed by the VM at every start.
//!
//! `midas node forward` (launchd, as the node's user) carries the TCP: the
//! tunnel to the VM's sshd, and the VM to the hub, so the hub sees the node's
//! requests come from this machine's WireGuard address.

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_json::Value;

use crate::setup::{conf_path, run, which, write, FromHub, NodeConf};

const PACKER: &str = include_str!("../node/macos/node.pkr.hcl");
const GUEST: &[(&str, &str)] = &[
    ("provision.sh", include_str!("../node/macos/guest/provision.sh")),
    ("start.sh", include_str!("../node/macos/guest/start.sh")),
    ("sshd.conf", include_str!("../node/macos/guest/sshd.conf")),
    ("eu.midas.node.plist", include_str!("../node/macos/guest/eu.midas.node.plist")),
];

/// The VM's recipe, for `setup::recipe`.
pub(crate) fn recipe_parts() -> impl Iterator<Item = (&'static str, &'static str)> {
    [("node.pkr.hcl", PACKER)].into_iter().chain(GUEST.iter().copied())
}
/// Cirrus Labs' macOS with Xcode: inside the node, which is untrusted anyway.
pub const DEFAULT_IMAGE: &str = "ghcr.io/cirruslabs/macos-tahoe-xcode:latest";
const DEFAULT_DISK_GB: u32 = 200;
/// The ports the VM reaches the hub on, at its gateway (this Mac).
const HUB_API_PORT: u16 = 4791;
const HUB_GIT_PORT: u16 = 4792;

pub(crate) fn label(kind: &str, node: &str) -> String {
    format!("eu.midas.{kind}.{node}")
}

fn plist_path(kind: &str, node: &str) -> String {
    format!("/Library/LaunchDaemons/{}.plist", label(kind, node))
}

fn anchor(node: &str) -> String {
    format!("com.apple/250.midas.{node}")
}

/// What closes the tunnel, for every node on this Mac at once. It cannot live
/// in a node's anchor: a Mac with two nodes has them on one tunnel, and pf
/// evaluates `com.apple/*` in name order, so mac-1's "block the rest of the
/// tunnel" dropped mac-2's ssh before mac-2's anchor could pass it (seen on the
/// first Mac with two nodes, 2026-10-16). Named to sort after every node's.
const TUNNEL_ANCHOR: &str = "com.apple/259.midas.tunnel";
const TUNNEL_RULES: &str = "/etc/midas/pf-tunnel.conf";

/// The shared anchor's rules: nothing in on the tunnel but what a node's anchor passed.
pub fn tunnel_firewall(tunnel_if: &str) -> String {
    format!("# Written by `midas setup` — the tunnel, for every node on this Mac. Each node's anchor\n\
             # ({}) passes its own ssh port; this one, evaluated after them all, drops the rest.\n\
             block drop in quick on {tunnel_if} all\n", anchor("<node>"))
}

/// `ifconfig` → (interface, IPv4 address).
pub fn parse_ifconfig(text: &str) -> Vec<(String, String)> {
    let mut out = Vec::new();
    let mut iface = String::new();
    for l in text.lines() {
        if !l.starts_with(['\t', ' ']) {
            iface = l.split(':').next().unwrap_or("").to_string();
        } else if let Some(rest) = l.trim().strip_prefix("inet ") {
            if let Some(ip) = rest.split_whitespace().next() {
                out.push((iface.clone(), ip.to_string()));
            }
        }
    }
    out
}

/// The VMs' shared network: macOS's vmnet gateway and its /24.
fn vmnet() -> (String, String) {
    let gw = Command::new("defaults")
        .args(["read", "/Library/Preferences/SystemConfiguration/com.apple.vmnet", "Shared_Net_Address"])
        .output().ok().filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .filter(|a| a.parse::<std::net::Ipv4Addr>().is_ok())
        .unwrap_or_else(|| "192.168.64.1".into());
    let net = gw.rsplit_once('.').map(|(a, _)| format!("{a}.0/24")).unwrap_or_default();
    (gw, net)
}

/// The pf rules: the boundary on this Mac.
pub fn firewall(node: &str, h: &FromHub, gw: &str, net: &str, tunnel_if: &str, vm_if: Option<&str>) -> String {
    let mut r = format!(
        "# Written by `midas setup {node}` — run it again rather than editing this.\n\
         # Keeps node {node}'s VM off this Mac's network (anchor {a}).\n\
         # The VMs may reach this Mac only on the hub's forwarded ports, DNS and DHCP…\n\
         pass in quick proto tcp from {net} to {gw} port {{ {HUB_API_PORT}, {HUB_GIT_PORT} }}\n\
         pass in quick proto {{ tcp, udp }} from {net} to {gw} port 53\n\
         pass in quick proto udp from {net} to any port {{ 67, 68 }}\n\
         # …and nothing private at all: not the LAN, not this Mac, not the tunnel.\n\
         block drop in quick from {net} to {{ 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, \
         172.16.0.0/12, 192.0.0.0/24, 192.168.0.0/16, 198.18.0.0/15, 224.0.0.0/4, 240.0.0.0/4 }}\n",
        a = anchor(node),
    );
    if let Some(i) = vm_if {
        r += &format!("# No IPv6 from the VMs: a LAN with IPv6 gives its devices public addresses.\nblock drop in quick on {i} inet6 all\n");
    }
    r += &format!(
        "# The tunnel: this Mac's own connections to the hub, and the node's ssh port. The rest\n\
         # of the tunnel is dropped in {TUNNEL_ANCHOR}, after every node's anchor.\n\
         pass out quick on {tunnel_if} keep state\n\
         pass in quick on {tunnel_if} proto tcp to {addr} port {port} keep state\n",
        addr = h.address, port = h.port,
    );
    r
}

fn plist(label: &str, user: Option<&str>, env: &[(&str, String)], args: &[String], log: &str) -> String {
    let esc = |s: &str| s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
    let mut p = format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
         <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n\
         <plist version=\"1.0\">\n<dict>\n    <key>Label</key><string>{}</string>\n",
        esc(label)
    );
    if let Some(u) = user {
        p += &format!("    <key>UserName</key><string>{}</string>\n", esc(u));
    }
    if !env.is_empty() {
        p += "    <key>EnvironmentVariables</key>\n    <dict>\n";
        for (k, v) in env {
            p += &format!("        <key>{}</key><string>{}</string>\n", esc(k), esc(v));
        }
        p += "    </dict>\n";
    }
    p += "    <key>ProgramArguments</key>\n    <array>\n";
    for a in args {
        p += &format!("        <string>{}</string>\n", esc(a));
    }
    p += &format!(
        "    </array>\n    <key>RunAtLoad</key><true/>\n    <key>KeepAlive</key><true/>\n\
         \x20   <key>StandardOutPath</key><string>{l}</string>\n    <key>StandardErrorPath</key><string>{l}</string>\n\
         </dict>\n</plist>\n", l = esc(log)
    );
    p
}

/// The VM's job. launchd starts it again only after an unsuccessful exit, so
/// a guest shut down on purpose (sleep.rs) stays down.
fn vm_plist(label: &str, user: &str, home: &Path, tart: &Path, vm: &str, share: &Path, node: &str) -> String {
    plist(label, Some(user), &[("TART_HOME", format!("{}/.tart", home.display()))],
        &[tart.display().to_string(), "run".into(), vm.into(), "--no-graphics".into(),
          format!("--dir=midas:{}:ro", share.display())],
        &format!("{}/vm-{node}.log", home.display()))
        .replace("<key>KeepAlive</key><true/>", "<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>")
}

fn dscl(args: &[&str]) -> Result<String> {
    run(Command::new("dscl").arg(".").args(args))
}

/// The node's user: hidden, no login shell, its own group.
fn ensure_user(user: &str) -> Result<(u32, PathBuf)> {
    let home = PathBuf::from(format!("/Users/{user}"));
    if dscl(&["-read", &format!("/Users/{user}"), "UniqueID"]).is_err() {
        let used: Vec<u32> = dscl(&["-list", "/Users", "UniqueID"])?.lines()
            .chain(dscl(&["-list", "/Groups", "PrimaryGroupID"])?.lines().collect::<Vec<_>>())
            .filter_map(|l| l.split_whitespace().last()?.parse().ok()).collect();
        let id = (400..500).find(|n| !used.contains(n)).ok_or_else(|| anyhow!("no free id below 500 for {user}"))?;
        let (g, u) = (format!("/Groups/{user}"), format!("/Users/{user}"));
        dscl(&["-create", &g])?;
        dscl(&["-create", &g, "PrimaryGroupID", &id.to_string()])?;
        dscl(&["-create", &u])?;
        for (k, v) in [("UserShell", "/usr/bin/false".to_string()), ("RealName", "midas build node".into()),
                       ("UniqueID", id.to_string()), ("PrimaryGroupID", id.to_string()),
                       ("NFSHomeDirectory", home.display().to_string()), ("IsHidden", "1".into()), ("Password", "*".into())] {
            dscl(&["-create", &u, k, &v])?;
        }
        fs::create_dir_all(&home)?;
        run(Command::new("chown").arg(format!("{user}:{user}")).arg(&home))?;
        fs::set_permissions(&home, fs::Permissions::from_mode(0o750))?;
        println!("created user {user}");
    }
    let uid = dscl(&["-read", &format!("/Users/{user}"), "UniqueID"])?
        .split_whitespace().last().and_then(|v| v.parse().ok()).ok_or_else(|| anyhow!("no uid for {user}"))?;
    Ok((uid, home))
}

/// A command as the node's user, with its own Tart and Packer state.
pub(crate) fn as_user(user: &str, home: &Path, prog: &Path) -> Command {
    let mut c = Command::new("sudo");
    c.args(["-u", user, "-H", "env"])
        .arg(format!("TART_HOME={}/.tart", home.display()))
        .arg(format!("PACKER_PLUGIN_PATH={}/.packer.d/plugins", home.display()))
        .arg(format!("PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"))
        .arg(prog)
        .current_dir(home);
    c
}

/// (Re)start a job. `bootout` returns before launchd has let go of the job —
/// its process may still be stopping — and a `bootstrap` then fails ("5:
/// Input/output error"): on the first re-run of setup on a Mac that left
/// mac-1 with no forwarder and the run stopped before mac-2. So wait for the
/// job to be gone, and give the bootstrap a few tries.
fn launchctl_load(kind: &str, node: &str) -> Result<()> {
    let target = format!("system/{}", label(kind, node));
    let _ = run(Command::new("launchctl").args(["bootout", &target]));
    for _ in 0..30 {
        if !Command::new("launchctl").args(["print", &target]).output().is_ok_and(|o| o.status.success()) {
            break;
        }
        std::thread::sleep(Duration::from_millis(500));
    }
    let mut last = None;
    for _ in 0..5 {
        match run(Command::new("launchctl").args(["bootstrap", "system", &plist_path(kind, node)])) {
            Ok(_) => return Ok(()),
            Err(e) => last = Some(e),
        }
        std::thread::sleep(Duration::from_secs(2));
    }
    Err(last.unwrap()).with_context(|| format!("starting {}", label(kind, node)))
}

fn launchctl_unload(kind: &str, node: &str) {
    let _ = run(Command::new("launchctl").args(["bootout", &format!("system/{}", label(kind, node))]));
}

pub fn remove(c: &NodeConf) -> Result<i32> {
    stop(c);
    println!("node {} stopped and its firewall removed. Kept: user {u}, the VM {vm} and its disk.\n\
              To delete those: sudo -u {u} tart delete {vm}; sudo dscl . -delete /Users/{u}", c.node, u = c.user, vm = c.storage());
    Ok(0)
}

/// Take a node's launchd jobs, firewall and settings away; its VM stays.
fn stop(c: &NodeConf) {
    let node = &c.node;
    for kind in ["vm", "forward", "firewall"] {
        launchctl_unload(kind, node);
        let _ = fs::remove_file(plist_path(kind, node));
    }
    if let Some(pfctl) = which("pfctl") {
        let _ = run(Command::new(pfctl).args(["-a", &anchor(node), "-F", "all"]));
    }
    for f in [conf_path(node), format!("/etc/midas/pf-{node}.conf")] {
        let _ = fs::remove_file(f);
    }
    if crate::setup::all_stored().is_empty() {
        if let Some(pfctl) = which("pfctl") {
            let _ = run(Command::new(pfctl).args(["-a", TUNNEL_ANCHOR, "-F", "all"]));
        }
        let _ = fs::remove_file(TUNNEL_RULES);
        launchctl_unload(POWER.0, POWER.1);
        let _ = fs::remove_file(plist_path(POWER.0, POWER.1));
    }
}

/// `old`: the node the hub renamed to this one, whose VM this node takes over.
pub fn setup(c: &NodeConf, h: &FromHub, old: Option<&NodeConf>, rebuild: bool) -> Result<i32> {
    let node = &c.node;
    let vm = c.storage();
    let tart = which("tart").ok_or_else(|| anyhow!("tart is not installed: brew install cirruslabs/cli/tart"))?;
    let pfctl = which("pfctl").ok_or_else(|| anyhow!("no pfctl"))?;
    let addrs = parse_ifconfig(&run(&mut Command::new("ifconfig"))?);
    let tunnel = addrs.iter().find(|(_, ip)| *ip == h.address).map(|(i, _)| i.clone())
        .ok_or_else(|| anyhow!("{} (the hub's address for {node}) is not on this Mac — is its WireGuard up?", h.address))?;
    let hub_ip = c.hub.rsplit_once(':').map(|(ip, _)| ip.to_string()).unwrap_or_default();
    let (gw, net) = vmnet();
    let me = std::env::current_exe().context("finding this midas")?;

    // 1. The user, and the settings.
    let (uid, home) = ensure_user(&c.user)?;
    if let Some(p) = old {
        // Its jobs and firewall go, which shuts its VM down; the VM stays, now this node's.
        stop(p);
        let _ = fs::remove_dir_all(home.join(format!("share-{}", p.node)));
    }
    fs::create_dir_all("/etc/midas")?;
    write(&conf_path(node), &(serde_json::to_string_pretty(c)? + "\n"), 0o644)?;

    // 2. The firewall, in force before the VM starts and at every boot.
    let rules = format!("/etc/midas/pf-{node}.conf");
    let vm_if = || addrs.iter().find(|(_, ip)| *ip == gw).map(|(i, _)| i.clone());
    write(&rules, &firewall(node, h, &gw, &net, &tunnel, vm_if().as_deref()), 0o644)?;
    run(Command::new(&pfctl).args(["-n", "-f", &rules])).context("the firewall rules did not check")?;
    write(TUNNEL_RULES, &tunnel_firewall(&tunnel), 0o644)?;
    run(Command::new(&pfctl).args(["-n", "-f", TUNNEL_RULES])).context("the tunnel's rules did not check")?;
    // Every node's job loads the shared anchor too, so it is in force at boot
    // whichever nodes this Mac has.
    let p = pfctl.display();
    write(&plist_path("firewall", node), &plist(&label("firewall", node), None, &[],
        &["/bin/sh".into(), "-c".into(),
          format!("{p} -E -a {a} -f {rules} && {p} -a {TUNNEL_ANCHOR} -f {TUNNEL_RULES}", a = anchor(node))],
        "/var/log/midas-firewall.log").replace("<key>KeepAlive</key><true/>", "<key>KeepAlive</key><false/>"), 0o644)?;
    launchctl_load("firewall", node)?;
    std::thread::sleep(Duration::from_secs(1));
    run(Command::new(&pfctl).args(["-a", &anchor(node), "-s", "rules"])).context("the firewall is not loaded")?;
    run(Command::new(&pfctl).args(["-a", TUNNEL_ANCHOR, "-s", "rules"])).context("the tunnel's firewall is not loaded")?;
    println!("firewall: in force ({rules}); from the tunnel only the node's ssh");

    // 3. What the VM reads at every start: the owner's midas, settings, keys.
    let share = home.join(format!("share-{node}"));
    fs::create_dir_all(&share)?;
    fs::set_permissions(&share, fs::Permissions::from_mode(0o755))?;
    fs::copy(&me, share.join("midas"))?;
    fs::set_permissions(share.join("midas"), fs::Permissions::from_mode(0o755))?;
    // The VM's start job, which replaces itself with this one when they differ.
    let start = GUEST.iter().find(|(n, _)| *n == "start.sh").map(|(_, b)| *b).unwrap_or_default();
    write(&share.join("start.sh").display().to_string(), start, 0o755)?;
    write(&share.join("node.env").display().to_string(), &format!(
        "MIDAS_NODE={node}\nMIDAS_HUB=http://{gw}:{HUB_API_PORT}\nMIDAS_GIT_HOST={gw}\nMIDAS_GIT_PORT={HUB_GIT_PORT}\n\
         MIDAS_REPO={}\nMIDAS_GUARD_WARN=80\nMIDAS_GUARD_STOP=92\nMIDAS_RECIPE={}\n", h.repo, crate::setup::recipe()), 0o644)?;
    write(&share.join("authorized_keys").display().to_string(), &(h.agent_keys.join("\n") + "\n"), 0o644)?;
    write(&share.join("operator_keys").display().to_string(), &(h.operator_keys.join("\n") + "\n"), 0o644)?;

    // 4. The VM: built once (it holds the warm build directory), sized every time.
    launchctl_unload("vm", node);
    let exists = as_user(&c.user, &home, &tart).args(["get", &vm]).output().is_ok_and(|o| o.status.success());
    if exists && rebuild {
        run(as_user(&c.user, &home, &tart).args(["delete", &vm]))?;
    }
    if !exists || rebuild {
        build_image(c, &home, &vm)?;
    }
    let mem_mb = parse_gb(&c.memory)? * 1024;
    run(as_user(&c.user, &home, &tart).args(["set", &vm, "--cpu", &c.cpus, "--memory", &mem_mb.to_string()]))?;
    // Started again only when it failed: a VM shut down on purpose while nobody
    // uses it (sleep.rs) stays down until the power job starts it.
    write(&plist_path("vm", node), &vm_plist(&label("vm", node), &c.user, &home, &tart, &vm, &share, node), 0o644)?;
    launchctl_load("vm", node)?;

    // 5. The forwarder: tunnel ⇄ VM, VM ⇄ hub.
    write(&plist_path("forward", node), &plist(&label("forward", node), Some(&c.user),
        &[("TART_HOME", format!("{}/.tart", home.display()))],
        &[me.display().to_string(), "node".into(), "forward".into(), "--vm".into(), vm.clone(),
          "--pair".into(), format!("{}:{}=vm:22", h.address, h.port),
          "--pair".into(), format!("{gw}:{HUB_API_PORT}={}", c.hub),
          "--pair".into(), format!("{gw}:{HUB_GIT_PORT}={hub_ip}:22")],
        &format!("{}/forward-{node}.log", home.display())), 0o644)?;
    launchctl_load("forward", node)?;

    // The VM's bridge exists now: add its IPv6 rule.
    std::thread::sleep(Duration::from_secs(20));
    let addrs = parse_ifconfig(&run(&mut Command::new("ifconfig"))?);
    if let Some(i) = addrs.iter().find(|(_, ip)| *ip == gw).map(|(i, _)| i.clone()) {
        write(&rules, &firewall(node, h, &gw, &net, &tunnel, Some(&i)), 0o644)?;
        run(Command::new(&pfctl).args(["-a", &anchor(node), "-f", &rules]))?;
    }

    // 6. The node registers with the hub as it starts: wait to see it.
    let mut registered = false;
    for _ in 0..90 {
        let fresh = crate::hub::request(&format!("http://{}", c.hub), "GET", "/v1/state", None).ok()
            .and_then(|(_, b)| serde_json::from_str::<Value>(&b).ok())
            .and_then(|st| st["nodes"].as_array()?.iter().find(|n| n["id"] == node.as_str()).cloned())
            .is_some_and(|n| n["host_key"].is_string() && n["reading"]["at"].as_i64()
                .is_some_and(|at| crate::registry::now() - at < 120));
        if fresh {
            registered = true;
            break;
        }
        std::thread::sleep(Duration::from_secs(5));
    }
    println!("\nmidas node {node}: VM {vm} running as {} (uid {uid}), {}.", c.user,
        if registered { "registered with the hub and reporting" } else { "not reporting to the hub yet — see the logs in ~midas-node" });
    power_job(&c.hub);
    Ok(0)
}

/// The Mac's power, to the hub (power.rs): one job per machine, as root, for
/// powermetrics. Not the node's business, so a failure here is a note.
const POWER: (&str, &str) = ("power", "machine");

fn power_job(hub: &str) {
    let r = (|| -> Result<()> {
        crate::power::place_binary()?;
        write(&plist_path(POWER.0, POWER.1), &plist(&label(POWER.0, POWER.1), None, &[],
            &[crate::power::BIN.into(), "node".into(), "power".into(), "--hub".into(), hub.into()],
            "/var/log/midas-power.log"), 0o644)?;
        launchctl_load(POWER.0, POWER.1)
    })();
    match r {
        Ok(()) => println!("power: reported to the hub once a minute ({}, log /var/log/midas-power.log)", label(POWER.0, POWER.1)),
        Err(e) => println!("note: the power job did not start: {e:#}"),
    }
}

fn parse_gb(m: &str) -> Result<u64> {
    let n = m.trim_end_matches(['g', 'G']);
    n.parse().map_err(|_| anyhow!("--memory on a Mac is in GB, like 24g, not {m:?}"))
}

/// The node's VM, from the image: Packer with Cirrus Labs' tart plugin, as
/// the node's user. Takes a while: the base image is tens of GB.
fn build_image(c: &NodeConf, home: &Path, vm: &str) -> Result<()> {
    let packer = which("packer").ok_or_else(|| anyhow!("packer is not installed: brew install hashicorp/tap/packer"))?;
    let dir = home.join(format!("image-{}", c.node));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(dir.join("guest"))?;
    fs::write(dir.join("node.pkr.hcl"), PACKER)?;
    for (name, body) in GUEST {
        fs::write(dir.join("guest").join(name), body)?;
    }
    run(Command::new("chown").arg("-R").arg(format!("{u}:{u}", u = c.user)).arg(&dir))?;
    println!("building the VM {vm} from {} — this downloads the image the first time, and takes a while",
        c.image.as_deref().unwrap_or(DEFAULT_IMAGE));
    run(as_user(&c.user, home, &packer).args(["init", "node.pkr.hcl"]).current_dir(&dir))?;
    let st = as_user(&c.user, home, &packer).arg("build")
        .arg(format!("-var=base={}", c.image.as_deref().unwrap_or(DEFAULT_IMAGE)))
        .arg(format!("-var=name={vm}"))
        .arg(format!("-var=cpus={}", c.cpus))
        .arg(format!("-var=memory_gb={}", parse_gb(&c.memory)?))
        .arg(format!("-var=disk_gb={}", c.disk_gb.unwrap_or(DEFAULT_DISK_GB)))
        .arg("node.pkr.hcl").current_dir(&dir).status()?;
    if !st.success() {
        bail!("building the VM failed (above)");
    }
    Ok(())
}

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

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

    #[test]
    fn ifconfig_is_read_per_interface() {
        let a = parse_ifconfig("lo0: flags=8049<UP>\n\tinet 127.0.0.1 netmask 0xff000000\n\
            en0: flags=8863<UP>\n\tinet 192.168.1.30 netmask 0xffffff00 broadcast 192.168.1.255\n\
            utun4: flags=8051<UP>\n\tinet 10.44.0.4 --> 10.44.0.4 netmask 0xffffffff\n\
            bridge100: flags=8a63<UP>\n\tinet 192.168.64.1 netmask 0xffffff00\n");
        assert!(a.contains(&("utun4".into(), "10.44.0.4".into())));
        assert!(a.contains(&("bridge100".into(), "192.168.64.1".into())));
    }

    #[test]
    fn the_mac_firewall_keeps_the_vm_off_everything_private_and_limits_the_tunnel() {
        let f = firewall("mac-1", &hub(), "192.168.64.1", "192.168.64.0/24", "utun4", Some("bridge100"));
        assert!(f.contains("pass in quick proto tcp from 192.168.64.0/24 to 192.168.64.1 port { 4791, 4792 }"));
        assert!(f.contains("block drop in quick from 192.168.64.0/24 to { 0.0.0.0/8, 10.0.0.0/8"));
        assert!(f.contains("192.168.0.0/16"));
        assert!(f.contains("block drop in quick on bridge100 inet6 all"));
        assert!(f.contains("pass in quick on utun4 proto tcp to 10.44.0.4 port 2226 keep state"));
        assert!(!f.contains("block drop in quick on utun4 all"), "that would drop another node's port too");
        assert!(tunnel_firewall("utun4").contains("block drop in quick on utun4 all"));
        // Allowing comes first: pf's `quick` takes the first match.
        assert!(f.find("port { 4791, 4792 }").unwrap() < f.find("block drop in quick from").unwrap());
    }

    #[test]
    fn the_tunnel_is_closed_after_every_nodes_anchor_has_passed_its_port() {
        // pf evaluates com.apple/* in name order, whatever the node is called.
        for node in ["mac-1", "mac-2", "zz-9", "0", "a"] {
            assert!(anchor(node).as_str() < TUNNEL_ANCHOR, "{node}");
        }
    }

    #[test]
    fn launchd_jobs_say_what_runs_as_whom() {
        let p = plist("eu.midas.vm.mac-1", Some("midas-node"), &[("TART_HOME", "/Users/midas-node/.tart".into())],
            &["tart".into(), "run".into(), "midas-mac-1".into(), "--dir=midas:/Users/midas-node/share-mac-1:ro".into()], "/tmp/x.log");
        assert!(p.contains("<key>UserName</key><string>midas-node</string>"));
        assert!(p.contains("<string>--dir=midas:/Users/midas-node/share-mac-1:ro</string>"));
        assert!(p.contains("<key>TART_HOME</key>"));
    }

    #[test]
    fn a_vm_shut_down_on_purpose_is_not_started_again_by_launchd() {
        let p = vm_plist("eu.midas.vm.mac-1", "midas-node", Path::new("/Users/midas-node"), Path::new("/opt/homebrew/bin/tart"),
            "midas-mac-1", Path::new("/Users/midas-node/share-mac-1"), "mac-1");
        assert!(p.contains("<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>"), "{p}");
        assert!(!p.contains("<key>KeepAlive</key><true/>"));
        assert!(p.contains("<string>--no-graphics</string>") && !p.contains("--no-audio"));
    }
}