garage44.eu/jeroen/midas

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

.. /src/botsecrets.rs

raw

//! The bots' secrets, kept by the hub (`midas bot token`): one set of
//! `NAME=value` per node, handed to a bot's environment when `midas bot start`
//! starts it — over the ssh session's stdin, so it is on no node's disk, in no
//! command line and in no log.
//!
//! This revises decision 14 (DESIGN.md §8), which kept a bot's credential on
//! its machine (`sudo midas bot setup`, still there). Set from anywhere with a
//! caller key, for one node or a whole group (`gpu`, a machine), with no root
//! on any machine — and a Mac node, whose VM has no configuration directory
//! of the machine's, needs nothing of its own. What it costs: anyone with a
//! caller key can read a secret back, and a compromised hub has them all. Both
//! were already true of a running bot, whose environment the hub's operator key
//! can read on the node.

use std::collections::BTreeMap;
use std::path::PathBuf;

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

use crate::events;
use crate::registry;
use crate::store;

type Secrets = BTreeMap<String, BTreeMap<String, String>>;

fn path() -> PathBuf {
    registry::root().join("bot-secrets.json")
}

fn read() -> Secrets {
    store::read(&path()).unwrap_or_default()
}

/// Change the secrets under their lock: the hub answers on a thread per
/// connection, and two `bot token`s at once must both be kept.
fn update<R>(f: impl FnOnce(&mut Secrets) -> R) -> Result<R> {
    let mut s = store::Store::<Secrets>::open(path())?.private();
    let r = f(&mut s.data);
    s.save()?;
    Ok(r)
}

/// The nodes `target` names: a node, or as for a take — `any`, `gpu`, a machine.
fn nodes_for(target: &str) -> Vec<String> {
    let all = registry::nodes();
    if all.iter().any(|n| n["id"] == target) {
        return vec![target.to_string()];
    }
    all.iter().filter(|n| registry::machine_matches(target, n))
        .filter_map(|n| n["id"].as_str().map(str::to_string)).collect()
}

/// Set (or with `value` none, remove) one secret for every node `target` names.
pub fn set(target: &str, name: &str, value: Option<&str>, by: &str) -> Result<Value> {
    if !crate::bot::env_name_ok(name) {
        bail!("a secret's name is a variable's name (letters, digits and _), not {name:?}");
    }
    if let Some(v) = value {
        if v.is_empty() || v.len() > 4096 || v.contains(['\n', '\r', '\0']) {
            bail!("a secret is one line of at most 4096 bytes");
        }
    }
    let nodes = nodes_for(target);
    if nodes.is_empty() {
        bail!("{target:?} names no node: a node, a machine, gpu or any");
    }
    update(|s| {
        for n in &nodes {
            match value {
                Some(v) => { s.entry(n.clone()).or_default().insert(name.to_string(), v.to_string()); }
                None => {
                    if let Some(m) = s.get_mut(n) {
                        m.remove(name);
                    }
                }
            }
        }
        s.retain(|_, m| !m.is_empty());
    })?;
    // The name and where, never the value.
    events::emit("bot_secret", json!({"nodes": nodes, "name": name, "removed": value.is_none(), "actor": by}));
    Ok(json!({"nodes": nodes, "name": name}))
}

/// What a bot started on `node` gets: names and values.
pub fn for_node(node: &str) -> BTreeMap<String, String> {
    read().remove(node).unwrap_or_default()
}

/// Which names each node has — never a value.
pub fn names() -> Value {
    json!(read().into_iter().map(|(n, m)| (n, m.into_keys().collect::<Vec<_>>())).collect::<BTreeMap<_, _>>())
}

/// A node renamed keeps its secrets; one removed loses them.
pub fn renamed(from: &str, to: Option<&str>) -> Result<()> {
    update(|s| {
        if let Some(m) = s.remove(from) {
            if let Some(to) = to {
                s.insert(to.to_string(), m);
            }
        }
    })
}