garage44.eu/jeroen/midas

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

.. /src/hubsetup.rs

raw

//! `sudo midas hub setup`: make this machine the workspace's hub, in one command.
//!
//! It creates the `midas` user and its directory (`/srv/midas`), the two keys
//! the hub uses (a read-only deploy key for the git mirror, and the operator
//! key the warmer logs into nodes with), installs this binary as
//! `/usr/local/bin/midas` and the hub's services, and starts them. The settings
//! are `/etc/midas/hub.conf`; running it again re-applies them, and that is
//! also how the hub is updated (a newer midas, then `sudo midas hub setup`).
//!
//! The hub keeps its ssh files itself from the node list (`refresh_ssh`):
//! which node keys may fetch git, the nodes' host keys, and the warmer's ssh
//! config. Nobody edits them.

use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use serde_json::{json, Value};

use crate::conf::{self, HubConf, HUB_CONF};
use crate::hub::callers_file;
use crate::sshcfg::{self, write_if_changed};
use crate::util::run;

pub const HOME: &str = "/srv/midas";
pub const USER: &str = "midas";
pub const BIN: &str = "/usr/local/bin/midas";
/// The midas the hub hands nodes of a platform other than its own
/// (`midas-<os>-<arch>`, and beside it `.build`: the build it is). Root's, so
/// the hub, which only serves them, cannot change them.
pub const NODE_BIN_DIR: &str = "/usr/local/lib/midas/node";
pub const OPERATOR_KEY: &str = "/srv/midas/.ssh/operator_ed25519";

const UNITS: &[(&str, &str)] = &[
    ("midas-hub.service", include_str!("../units/midas-hub.service")),
    ("midas-warm.service", include_str!("../units/midas-warm.service")),
    ("midas-warm.timer", include_str!("../units/midas-warm.timer")),
    ("midas-deploy.path", include_str!("../units/midas-deploy.path")),
    ("midas-deploy.service", include_str!("../units/midas-deploy.service")),
    ("midas-publish.path", include_str!("../units/midas-publish.path")),
    ("midas-publish.service", include_str!("../units/midas-publish.service")),
    ("midas-self-update.path", include_str!("../units/midas-self-update.path")),
    ("midas-self-update.service", include_str!("../units/midas-self-update.service")),
    ("midas-admin.path", include_str!("../units/midas-admin.path")),
    ("midas-admin.service", include_str!("../units/midas-admin.service")),
    ("midas-admin.timer", include_str!("../units/midas-admin.timer")),
];

#[derive(Default)]
pub struct Args {
    pub listen: Option<String>,
    pub forgejo_ssh: Option<String>,
    pub forgejo_api: Option<String>,
    pub repos: Vec<String>,
    pub agent_keys: Vec<String>,
    /// `<os>-<arch>=<path>`: this same build of midas for nodes of another
    /// platform (deploy.sh builds the Macs' beside the hub's own).
    pub node_binaries: Vec<String>,
    /// `hub`, `signed` or `off`: what the self-update does with a published build (release.rs).
    pub self_update: Option<String>,
    /// The release key's public line (`midas sign keygen` prints it), or a
    /// file holding it, or `-` for stdin: installed as /etc/midas/release.pub.
    pub release_key: Option<String>,
}

pub fn merge(stored: Option<HubConf>, a: Args) -> Result<HubConf> {
    let mut c = stored.unwrap_or_default();
    if let Some(v) = a.self_update {
        if !matches!(v.as_str(), "hub" | "signed" | "off") {
            bail!("--self-update is hub, signed or off, not {v:?}");
        }
        c.self_update = if v == "hub" { String::new() } else { v };
    }
    if let Some(v) = a.listen { c.listen = v; }
    if let Some(v) = a.forgejo_ssh { c.forgejo_ssh = v; }
    if let Some(v) = a.forgejo_api { c.forgejo_api = v; }
    if !a.repos.is_empty() { c.repos = a.repos; }
    if !a.agent_keys.is_empty() { c.agent_keys = a.agent_keys; }
    // Forgejo is optional: a hub that hosts its repositories itself has both
    // blank (the self-update runs this with no flags, and refused every build
    // after garage44.eu's forge moved to the hub).
    if c.listen.is_empty() || c.repos.is_empty() {
        bail!("the first time, say where the hub listens and what it serves:\n  \
               sudo midas hub setup --listen ADDRESS:PORT --repo OWNER/NAME --agent-key \"ssh-ed25519 …\"\n  \
               (and --forgejo ssh://git@HOST:PORT --forgejo-api https://HOST/api/v1 to mirror a Forgejo)");
    }
    c.listen.parse::<std::net::SocketAddrV4>().map_err(|_| anyhow!("--listen is ADDRESS:PORT, not {:?}", c.listen))?;
    if !c.forgejo_ssh.is_empty() && !c.forgejo_ssh.starts_with("ssh://") { bail!("--forgejo is ssh://user@host:port"); }
    if !c.forgejo_api.is_empty() && !c.forgejo_api.starts_with("https://") && !c.forgejo_api.starts_with("http://") {
        bail!("--forgejo-api is a URL");
    }
    for r in &c.repos {
        crate::mirror::repo_name(r)?;
    }
    for k in &mut c.agent_keys {
        *k = crate::registry::ed25519_key(k).ok_or_else(|| anyhow!("--agent-key wants an ssh-ed25519 public key"))?;
    }
    Ok(c)
}

fn chown(path: &str, owner: &str) -> Result<()> {
    run(Command::new("chown").arg(owner).arg(path)).map(|_| ())
}

fn user_exists(u: &str) -> bool {
    fs::read_to_string("/etc/passwd").unwrap_or_default().lines().any(|l| l.split(':').next() == Some(u))
}

/// Copy this binary to `BIN`, beside and renamed over, so a running hub keeps
/// the file it started from.
pub fn install_self() -> Result<bool> {
    let me = fs::read("/proc/self/exe")?;
    if fs::read(BIN).is_ok_and(|b| b == me) {
        return Ok(false);
    }
    let tmp = format!("{BIN}.new");
    fs::write(&tmp, &me)?;
    fs::set_permissions(&tmp, fs::Permissions::from_mode(0o755))?;
    fs::rename(&tmp, BIN)?;
    Ok(true)
}

/// Keep the midas for nodes of another platform, marked as this build: the hub
/// hands a node only the one marked as its own build (`hub::node_binary`), so
/// one left from an earlier setup is never offered.
fn install_node_binaries(specs: &[String]) -> Result<Vec<String>> {
    let mut done = Vec::new();
    for spec in specs {
        let (platform, path) = spec.split_once('=').ok_or_else(|| anyhow!("--node-binary is OS-ARCH=PATH, not {spec:?}"))?;
        if !crate::node::is_platform(platform) {
            bail!("--node-binary: {platform:?} is not OS-ARCH (macos-aarch64, linux-x86_64, …)");
        }
        fs::create_dir_all(NODE_BIN_DIR)?;
        fs::set_permissions(NODE_BIN_DIR, fs::Permissions::from_mode(0o755))?;
        let dest = format!("{NODE_BIN_DIR}/midas-{platform}");
        let tmp = format!("{dest}.new");
        fs::copy(path, &tmp).with_context(|| format!("reading {path}"))?;
        fs::set_permissions(&tmp, fs::Permissions::from_mode(0o644))?;
        fs::rename(&tmp, &dest)?;
        write_if_changed(&format!("{dest}.build"), &format!("{}\n", crate::VERSION), 0o644)?;
        done.push(platform.to_string());
    }
    Ok(done)
}

/// The hub's ssh files, from the node list: run by the hub (as `midas`) after
/// a node is added, removed or registers, and by `hub setup`.
pub fn refresh_ssh() -> Result<()> {
    let nodes = crate::registry::nodes();
    let ssh = format!("{HOME}/.ssh");
    let opts = sshcfg::Opts {
        identity: OPERATOR_KEY.into(),
        known_hosts: format!("{ssh}/known_hosts_nodes"),
        flush: false,
        write: None,
    };
    write_if_changed(&format!("{ssh}/config"), &sshcfg::block_for(&nodes, &opts), 0o600)?;
    write_if_changed(&format!("{ssh}/known_hosts_nodes"), &sshcfg::known_hosts(&nodes), 0o644)?;
    // Each node's own key may fetch git and LFS objects, and nothing else.
    let keys: String = nodes.iter().filter_map(|n| {
        Some(format!("restrict,command=\"{BIN} hub git --node {}\" {} midas-node-{}\n",
            n["id"].as_str()?, n["git_key"].as_str()?, n["id"].as_str()?))
    }).collect();
    // And the person's and agents' keys for the repositories the hub hosts.
    let keys = keys + &crate::hosted::authorized_lines(BIN);
    let head = "# Written by the midas hub from its node list and its git keys; nodes register their own.\n";
    write_if_changed(&format!("{ssh}/authorized_keys"), &format!("{head}{keys}"), 0o600)?;
    Ok(())
}

pub fn setup(mut a: Args) -> Result<i32> {
    if unsafe { libc::geteuid() } != 0 {
        bail!("run it as root: sudo midas hub setup …");
    }
    let node_binaries = std::mem::take(&mut a.node_binaries);
    let release_key = a.release_key.take();
    let c = merge(conf::read(Path::new(HUB_CONF))?, a)?;
    if c.self_update == "signed" && release_key.is_none() && !Path::new(crate::release::RELEASE_PUB).exists() {
        bail!("--self-update signed needs the release key's public half: --release-key <line, file or ->");
    }
    for tool in ["git", "ssh-keygen", "systemctl", "useradd"] {
        if run(Command::new("sh").args(["-c", &format!("command -v {tool}")])).is_err() {
            bail!("{tool} is not installed");
        }
    }

    // The user and its directory.
    if !user_exists(USER) {
        run(Command::new("useradd").args(["--system", "--home-dir", HOME, "--create-home", "--shell", "/bin/sh",
            "--comment", "midas hub", USER]))?;
        println!("created user {USER} ({HOME})");
    }
    for d in ["", "/state", "/mirrors", "/lfs", "/tokens", "/.ssh", "/deploy", "/deploy/queue", "/deploy/work", "/deploy/ready", "/admin"] {
        let p = format!("{HOME}{d}");
        fs::create_dir_all(&p)?;
        fs::set_permissions(&p, fs::Permissions::from_mode(if d == "/.ssh" { 0o700 } else { 0o750 }))?;
        chown(&p, &format!("{USER}:{USER}"))?;
    }

    // The settings, readable by the hub and nobody else.
    fs::create_dir_all("/etc/midas")?;
    // Readable by all: a node's settings live here too, and `midas node status`
    // reads them without sudo. What is not public keeps its own mode (hub.conf
    // 640, the mirror's key 600).
    fs::set_permissions("/etc/midas", fs::Permissions::from_mode(0o755))?;
    chown("/etc/midas", &format!("root:{USER}"))?;
    write_if_changed(HUB_CONF, &(serde_json::to_string_pretty(&c)? + "\n"), 0o640)?;
    chown(HUB_CONF, &format!("root:{USER}"))?;
    if let Some(k) = release_key {
        // The line itself, a file holding it, or stdin: root's, readable by all (it is public).
        let line = if k == "-" {
            let mut t = String::new();
            std::io::stdin().read_line(&mut t)?;
            t
        } else if k.starts_with("midas-release-public-") {
            k
        } else {
            fs::read_to_string(&k).with_context(|| format!("reading {k}"))?
        };
        let line = line.trim();
        if !line.starts_with("midas-release-public-v1 ") {
            bail!("not a release key's public line: {line:?}");
        }
        write_if_changed(crate::release::RELEASE_PUB, &format!("{line}\n"), 0o644)?;
        println!("release key installed at {}", crate::release::RELEASE_PUB);
    }

    // Its two keys.
    let mut new_deploy_key = false;
    if !Path::new(crate::mirror::DEPLOY_KEY).exists() {
        run(Command::new("ssh-keygen").args(["-q", "-t", "ed25519", "-N", "", "-C", "midas-hub-mirror", "-f",
            crate::mirror::DEPLOY_KEY]))?;
        new_deploy_key = true;
    }
    chown(crate::mirror::DEPLOY_KEY, &format!("{USER}:{USER}"))?;
    if !Path::new(OPERATOR_KEY).exists() {
        run(Command::new("ssh-keygen").args(["-q", "-t", "ed25519", "-N", "", "-C", "midas-hub-operator", "-f", OPERATOR_KEY]))?;
    }
    for f in [OPERATOR_KEY.to_string(), format!("{OPERATOR_KEY}.pub")] {
        chown(&f, &format!("{USER}:{USER}"))?;
    }
    if !Path::new(&callers_file()).exists() {
        write_if_changed(&callers_file(), "{}\n", 0o600)?;
        chown(&callers_file(), &format!("{USER}:{USER}"))?;
    }
    ensure_publisher_key()?;

    // Leftovers from before the hub kept its own files.
    for old in ["repos", "node-kit.tar"] {
        let _ = fs::remove_file(format!("{HOME}/{old}"));
    }
    std::env::set_var("MIDAS_STATE", format!("{HOME}/state"));
    refresh_ssh()?;
    for f in ["config", "known_hosts_nodes", "authorized_keys"] {
        chown(&format!("{HOME}/.ssh/{f}"), &format!("{USER}:{USER}"))?;
    }
    for d in ["/state"] {
        run(Command::new("chown").arg("-R").arg(format!("{USER}:{USER}")).arg(format!("{HOME}{d}")))?;
    }

    // The binary and the services.
    let updated = install_self()?;
    let platforms = install_node_binaries(&node_binaries)?;
    let mut units_changed = false;
    for (name, body) in UNITS {
        units_changed |= write_if_changed(&format!("/etc/systemd/system/{name}"), body, 0o644)?;
    }
    run(Command::new("systemctl").arg("daemon-reload"))?;
    // The admin window's (admin.rs) do nothing until `midas hub admin-setup` writes its settings.
    run(Command::new("systemctl").args(["enable", "midas-hub.service", "midas-warm.timer", "midas-deploy.path", "midas-publish.path", "midas-self-update.path",
        "midas-admin.path", "midas-admin.timer"]))?;
    run(Command::new("systemctl").args(["start", "midas-warm.timer", "midas-deploy.path", "midas-publish.path", "midas-self-update.path",
        "midas-admin.path", "midas-admin.timer"]))?;
    run(Command::new("systemctl").args(["restart", "midas-hub.service"]))?;
    let url = c.url();
    let mut up = None;
    for _ in 0..20 {
        std::thread::sleep(Duration::from_millis(500));
        if let Ok((200, body)) = crate::hub::request(&url, "GET", "/v1/health", None) {
            up = serde_json::from_str::<Value>(&body).ok();
            break;
        }
    }
    let Some(health) = up else {
        bail!("the hub did not answer at {url} — journalctl -u midas-hub; is {} an address on this machine?", c.ip());
    };

    println!("midas hub {} answering at {url}{}{}", health["version"].as_str().unwrap_or("?"),
        if updated { " (binary updated)" } else { "" }, if units_changed { " (services updated)" } else { "" });
    if !platforms.is_empty() {
        println!("nodes on {} get this build too, when free", platforms.join(", "));
    }
    let deploy_pub = fs::read_to_string(format!("{}.pub", crate::mirror::DEPLOY_KEY)).unwrap_or_default();
    if new_deploy_key {
        println!("\nAdd this as a read-only deploy key on {} in your git server:\n  {}",
            c.repos.join(", "), deploy_pub.trim());
    }
    let callers: Value = serde_json::from_str(&fs::read_to_string(callers_file())?).unwrap_or(json!({}));
    if callers.as_object().is_none_or(|o| o.is_empty()) {
        println!("\nNo callers yet. Give the agents a key to change the workspace with:\n  sudo midas hub caller add agents");
    }
    for (name, c) in callers.as_object().into_iter().flatten() {
        if c["role"].as_str().and_then(crate::accounts::rank).is_none() {
            println!("\nCaller {name} has no role, so it is admin (it may manage accounts and read every setting). \
                      Narrow it:\n  sudo midas hub caller role {name} steer");
        }
    }
    if c.agent_keys.is_empty() {
        println!("\nNo agent keys yet: nodes will only let the hub in. Add the agents' public key with\n  sudo midas hub setup --agent-key \"ssh-ed25519 AAAA…\"");
    }
    if crate::registry::nodes().is_empty() {
        println!("\nNo build nodes yet. Name the first one here, then set it up on its machine (docs/node.md):\n  \
                  midas nodes add box-1 --machine box --address <its WireGuard address>\n  \
                  sudo midas setup box-1 --hub {}      # on that machine, by its owner", c.listen);
    }
    Ok(0)
}

/// Root's own caller key, read by nobody else: what the publisher reports
/// (`deploy::root_emit`) is believed because it comes with this, where a line
/// posted from the tunnel is not.
pub const PUBLISHER_KEY: &str = "/etc/midas/publisher.key";

fn ensure_publisher_key() -> Result<()> {
    let mut all = callers()?;
    let have = fs::read_to_string(PUBLISHER_KEY).ok().map(|s| s.trim().to_string()).filter(|k| !k.is_empty());
    if let Some(k) = &have {
        if all.get("publisher").is_some_and(|c| c["key"] == k.as_str()) {
            return Ok(());
        }
    }
    let key = match have { Some(k) => k, None => crate::mirror::random_hex(32)? };
    all.insert("publisher".into(), json!({"key": key, "role": "operator"}));
    write_callers(&all)?;
    write_if_changed(PUBLISHER_KEY, &format!("{key}\n"), 0o600)?;
    Ok(())
}

fn callers() -> Result<serde_json::Map<String, Value>> {
    let v: Value = serde_json::from_str(&fs::read_to_string(callers_file()).context("no callers file — run sudo midas hub setup first")?)?;
    Ok(v.as_object().cloned().unwrap_or_default())
}

fn write_callers(m: &serde_json::Map<String, Value>) -> Result<()> {
    write_if_changed(&callers_file(), &(serde_json::to_string_pretty(m)? + "\n"), 0o600)?;
    chown(&callers_file(), &format!("{USER}:{USER}"))
}

/// A caller is whoever may change the workspace (take and release nodes, add
/// nodes): one key per trust level, e.g. the agents' container. The Forgejo
/// token, if given, is what `/v1/forgejo` calls are made with for that caller.
pub fn caller_add(name: &str, forgejo_token: Option<String>, role: Option<&str>) -> Result<i32> {
    if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
        bail!("a caller's name is letters, digits, - and _");
    }
    if role.is_some_and(|r| crate::accounts::rank(r).is_none()) {
        bail!("a role is one of {}", crate::accounts::ROLES.join(", "));
    }
    let mut all = callers()?;
    let key = crate::mirror::random_hex(32)?;
    let token = match forgejo_token.as_deref() {
        Some("-") => {
            let mut t = String::new();
            std::io::stdin().read_line(&mut t)?;
            Some(t.trim().to_string())
        }
        other => other.map(str::to_string),
    };
    // Agents' keys are the common case, and they run the sessions (steer); a
    // key with no role at all is admin, and every agent session would hold it.
    let mut entry = json!({"key": key, "role": role.unwrap_or("steer")});
    if let Some(t) = token.filter(|t| !t.is_empty()) {
        entry["token"] = json!(t);
    }
    let replaced = all.insert(name.to_string(), entry).is_some();
    write_callers(&all)?;
    println!("{} caller {name}. On the caller's machine, put this in ~/.config/midas/hub.env:\n\nMIDAS_HUB={}\nMIDAS_HUB_KEY={key}",
        if replaced { "New key for" } else { "Added" }, conf::hub().url());
    Ok(0)
}

pub fn caller_list() -> Result<i32> {
    for (name, c) in callers()? {
        println!("{name}  {}{}{}", c["role"].as_str().unwrap_or("admin (no role set)"),
                 if c.get("starts").is_some() { " · retired starts-only key, refused: remove it" } else { "" },
                 if c["token"].is_string() { " · with a Forgejo token" } else { "" });
    }
    Ok(0)
}

/// What a caller key may do (accounts.rs's roles). A key with none can do
/// everything, as keys always could.
pub fn caller_role(name: &str, role: &str) -> Result<i32> {
    if crate::accounts::rank(role).is_none() {
        bail!("a role is one of {}", crate::accounts::ROLES.join(", "));
    }
    let mut all = callers()?;
    let Some(c) = all.get_mut(name) else { bail!("no caller {name}") };
    c["role"] = json!(role);
    write_callers(&all)?;
    println!("caller {name} is {role}");
    Ok(0)
}

pub fn caller_remove(name: &str) -> Result<i32> {
    let mut all = callers()?;
    if all.remove(name).is_none() {
        bail!("no caller {name}");
    }
    write_callers(&all)?;
    println!("removed caller {name}");
    Ok(0)
}

/// `midas hub backup`: the hub's state as a gzipped tar on stdout, for a
/// machine that is not this one to keep — run over ssh from there, so this
/// machine holds no key into it (`ssh hub sudo midas hub backup > file`).
/// Everything under the hub's home and /etc/midas, but the git mirrors and the
/// LFS cache, which Forgejo holds already. Each state file is replaced whole
/// when written (`store::write_atomic`), so a copy taken while the hub runs
/// has every file as it was at one moment, if not all at the same one.
pub fn backup() -> Result<i32> {
    if unsafe { libc::geteuid() } != 0 {
        bail!("run it as root: sudo midas hub backup > midas-hub.tar.gz");
    }
    if unsafe { libc::isatty(1) } == 1 {
        bail!("the backup is a tarball on stdout: send it to a file, or over ssh to another machine");
    }
    let home = HOME.trim_start_matches('/');
    let st = Command::new("tar").args(["-C", "/", "-czf", "-", "--warning=no-file-changed",
            &format!("--exclude={home}/mirrors"), &format!("--exclude={home}/lfs"), &format!("--exclude={home}/.cache"),
            home, "etc/midas"])
        .status().context("running tar")?;
    // 1: a file changed while it was read (a log being appended to) — the copy is still good.
    match st.code() {
        Some(0 | 1) => Ok(0),
        _ => bail!("tar failed ({st})"),
    }
}

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

    fn first() -> Args {
        Args {
            listen: Some("10.0.0.1:4791".into()),
            forgejo_ssh: Some("ssh://git@git.example:2222".into()),
            forgejo_api: Some("https://git.example/api/v1".into()),
            repos: vec!["owner/project".into()],
            agent_keys: vec![],
            node_binaries: vec![],
            self_update: None,
            release_key: None,
        }
    }

    #[test]
    fn hub_settings_are_asked_for_once_and_kept() {
        assert!(merge(None, Args::default()).is_err(), "nothing about a network is assumed");
        let c = merge(None, first()).unwrap();
        assert!(c.allows("owner/project.git"));
        assert!(!c.allows("owner/other.git"));
        assert!(merge(None, Args { listen: Some("nope".into()), ..first() }).is_err());
        assert!(merge(None, Args { repos: vec!["../x".into()], ..first() }).is_err());
        let k = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIO05aMfpDsKVmX1V1QXPgDp6ZFrMOxoqN7+2w1BL4dzC someone";
        let c = merge(Some(c), Args { agent_keys: vec![k.into()], ..Default::default() }).unwrap();
        assert_eq!(c.agent_keys, vec![k.rsplit_once(' ').unwrap().0.to_string()]);
        assert_eq!(c.repos, vec!["owner/project"], "a re-run keeps what it was not told");
    }

    #[test]
    fn a_hub_that_hosts_its_repositories_needs_no_forgejo() {
        let own = Args { forgejo_ssh: None, forgejo_api: None, ..first() };
        let c = merge(None, own).unwrap();
        assert!(c.forgejo_ssh.is_empty() && c.forgejo_api.is_empty());
        // The self-update re-runs setup with no flags at all.
        assert!(merge(Some(c), Args::default()).is_ok(), "the self-update installs a build on a hub without Forgejo");
        assert!(merge(None, Args { forgejo_ssh: Some("git.example".into()), ..first() }).is_err(), "one given is still checked");
    }
}