git clone https://garage44.eu/jeroen/midas.git.. /src/botsetup.rs
//! `sudo midas bot setup <node>`: give a node's bots one secret, on the machine.
//!
//! A bot usually needs a credential of its own — the intended one is an access
//! token the owner made for it in the service the bot talks to (`--env
//! CARTO_TOKEN`). It is the machine owner's to give, so it is set here, on the
//! machine, by its owner: read from the terminal with echo off, written as
//! `NAME=value` to `bot.env` in the node's configuration directory — the one
//! `node.env` is in, which the container sees read-only as `/config` — and
//! from there put in the environment of every bot `midas node bot start`
//! starts. **It never goes to the hub**, and nothing logs it: the event log
//! and this command's output name the variable and the file, never the value.
//!
//! The file is 0600 and belongs to the container's `build` user — the user
//! sessions and bots run as — through the node user's subordinate ids, as
//! rootless podman maps them. Nothing else on the machine but root reads it.
//! What this does **not** stop: anything running as `build` in the node (the
//! holder's sessions, the hub's operator key) can read a running bot's
//! environment (DESIGN.md §8, decision 14).
use std::fs;
use std::io::{BufRead, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::PathBuf;
use anyhow::{anyhow, bail, Context, Result};
use crate::setup;
/// The container's `build` user (node/Containerfile).
const BUILD_UID: u32 = 1000;
pub struct Args {
pub node: String,
/// The variable's name; remembered with the node's settings.
pub env: Option<String>,
/// Read the secret from one line of stdin rather than the terminal.
pub stdin: bool,
pub remove: bool,
}
/// The id `inner` inside a rootless container of `user` has on the machine:
/// container ids from 1 take the user's subordinate ranges in the order
/// `/etc/subuid` (or `/etc/subgid`) lists them, as podman maps them.
pub fn mapped_id(subid: &str, user: &str, inner: u32) -> Option<u32> {
let mut left = inner.checked_sub(1)? as u64;
for l in subid.lines() {
let f: Vec<&str> = l.trim().split(':').collect();
if f.first() != Some(&user) {
continue;
}
let (Some(start), Some(count)) = (f.get(1).and_then(|v| v.parse::<u64>().ok()), f.get(2).and_then(|v| v.parse::<u64>().ok())) else {
continue;
};
if left < count {
return u32::try_from(start + left).ok();
}
left -= count;
}
None
}
/// `bot.env` with `name` set to `value` and every other line kept.
pub fn with_value(old: &str, name: &str, value: &str) -> String {
let mut out: Vec<String> = old.lines()
.filter(|l| l.split_once('=').map(|(k, _)| k.trim().trim_start_matches("export ").trim()) != Some(name))
.map(str::to_string).collect();
if out.is_empty() {
out.push("# Written by `midas bot setup`: the environment of this node's bots. Never sent to the hub.".into());
}
out.push(format!("{name}={value}"));
out.join("\n") + "\n"
}
/// One line from the terminal, not echoed.
pub(crate) fn read_hidden(prompt: &str) -> Result<String> {
eprint!("{prompt}");
let _ = std::io::stderr().flush();
// SAFETY: tcgetattr/tcsetattr on stdin, a terminal (checked by the caller),
// with a struct we own; the settings are put back before returning.
let mut t: libc::termios = unsafe { std::mem::zeroed() };
if unsafe { libc::tcgetattr(0, &mut t) } != 0 {
bail!("could not read the terminal's settings: {}", std::io::Error::last_os_error());
}
let saved = t;
t.c_lflag &= !libc::ECHO;
unsafe { libc::tcsetattr(0, libc::TCSANOW, &t) };
let mut line = String::new();
let read = std::io::stdin().lock().read_line(&mut line);
unsafe { libc::tcsetattr(0, libc::TCSANOW, &saved) };
eprintln!();
read.context("reading the secret")?;
Ok(line)
}
pub fn setup(a: Args) -> Result<i32> {
if cfg!(target_os = "macos") {
eprintln!("midas bot setup: not supported on macOS nodes yet");
return Ok(1);
}
// SAFETY: geteuid has no preconditions.
if unsafe { libc::geteuid() } != 0 {
bail!("run it as root: sudo midas bot setup {} …", a.node);
}
let mut c = setup::stored(&a.node)
.ok_or_else(|| anyhow!("no node {} set up on this machine (sudo midas setup {} first)", a.node, a.node))?;
let (_, home) = setup::passwd(&c.user).ok_or_else(|| anyhow!("no user {}", c.user))?;
let dir: PathBuf = home.join(".config/midas").join(&c.node);
let path = dir.join("bot.env");
if !dir.is_dir() {
bail!("{} is missing — run sudo midas setup {} first", dir.display(), c.node);
}
if a.remove {
match fs::remove_file(&path) {
Ok(()) => println!("removed {}: bots on {} start with no secret from now on", path.display(), c.node),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => println!("{} has no bot.env; nothing to remove", c.node),
Err(e) => return Err(e).with_context(|| format!("removing {}", path.display())),
}
return Ok(0);
}
let name = a.env.clone().or_else(|| c.bot_env.clone())
.ok_or_else(|| anyhow!("the first time, say which variable the bot reads it from: --env NAME (e.g. --env CARTO_TOKEN)"))?;
if !crate::bot::env_name_ok(&name) {
bail!("--env is a variable's name (letters, digits and _), not {name:?}");
}
// SAFETY: isatty on a descriptor every process has.
let value = if a.stdin {
let mut line = String::new();
std::io::stdin().lock().read_line(&mut line).context("reading the secret from stdin")?;
line
} else if unsafe { libc::isatty(0) } == 1 {
read_hidden(&format!("{name} for the bots on {} (not shown): ", c.node))?
} else {
bail!("stdin is not a terminal; to read the secret from a pipe, add --stdin");
};
let value = value.trim();
if value.is_empty() {
bail!("nothing entered; nothing stored");
}
if value.contains(['\n', '\r', '\0']) {
bail!("the secret is one line");
}
let (subuid, subgid) = (fs::read_to_string("/etc/subuid").unwrap_or_default(), fs::read_to_string("/etc/subgid").unwrap_or_default());
let (Some(uid), Some(gid)) = (mapped_id(&subuid, &c.user, BUILD_UID), mapped_id(&subgid, &c.user, BUILD_UID)) else {
bail!("{} has no subordinate ids for the container's build user (/etc/subuid) — run sudo midas setup {} again", c.user, c.node);
};
let old = fs::read_to_string(&path).unwrap_or_default();
let tmp = dir.join(".bot.env.tmp");
let _ = fs::remove_file(&tmp);
{
let mut f = fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)
.with_context(|| format!("writing {}", tmp.display()))?;
f.write_all(with_value(&old, &name, value).as_bytes())?;
f.sync_all()?;
}
std::os::unix::fs::chown(&tmp, Some(uid), Some(gid)).context("giving bot.env to the container's build user")?;
fs::rename(&tmp, &path)?;
if c.bot_env.as_deref() != Some(name.as_str()) {
c.bot_env = Some(name.clone());
setup::write(&setup::conf_path(&c.node), &(serde_json::to_string_pretty(&c)? + "\n"), 0o644)?;
}
println!("stored {name} for the bots on {} in {} (mode 0600, the container's build user; /config/bot.env inside).\n\
The next bot started there has it in its environment. Nothing was sent to the hub.",
c.node, path.display());
Ok(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_build_user_maps_through_the_subordinate_ranges() {
let subuid = "deck:100000:65536\nmidas-node:165536:65536\n";
assert_eq!(mapped_id(subuid, "midas-node", 1000), Some(165536 + 999));
assert_eq!(mapped_id(subuid, "midas-node", 0), None, "the container's root is the user itself, not a subordinate id");
assert_eq!(mapped_id(subuid, "nobody", 1000), None);
// Ranges are taken in order: a short first one is used up first.
assert_eq!(mapped_id("u:500000:500\nu:900000:65536\n", "u", 1000), Some(900000 + 499));
}
#[test]
fn storing_a_secret_replaces_its_line_and_keeps_the_rest() {
let first = with_value("", "CARTO_TOKEN", "abc");
assert!(first.starts_with("# Written by `midas bot setup`") && first.ends_with("CARTO_TOKEN=abc\n"));
let again = with_value(&(first + "OTHER=1\n"), "CARTO_TOKEN", "xyz");
assert_eq!(crate::bot::parse_env(&again), vec![("OTHER".into(), "1".into()), ("CARTO_TOKEN".into(), "xyz".into())]);
assert!(!again.contains("abc"), "the old value is gone");
}
}