garage44.eu/jeroen/midas

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

.. /src/admin.rs

raw

//! Admin on the hub's machine for a while, granted by the person with a passkey
//! (DESIGN.md §8, decision 30).
//!
//! The agents reach the hub's machine as a user of their own (`admin.json`'s
//! `user`), which may do nothing as root. A session that needs root asks
//! (`midas admin "<why>" --for 30m`); the person's phone shows it, and their
//! Allow is a passkey assertion over that grant — who, for how long, why, and
//! when it was asked. Root (`midas hub admin-apply`, run by
//! `midas-admin.path` when the hub spools one and by `midas-admin.timer` every
//! minute) checks the assertion against a key the person installed themselves
//! (`sudo midas hub admin-enroll`), and only then writes the sudoers file that
//! lets the user be root, until the window's time is up, the session ends or
//! it says it is done. Closing it kills what still runs as root from the
//! user's logins.
//!
//! The hub's machine is assumed compromisable (§6): the hub only carries the
//! request and the signature, as it carries a release for the self-update
//! (release.rs). Whoever is the hub's user can ask, and show the person any
//! words on the page, but cannot sign; and what root accepts is capped
//! (`max_minutes`, one grant newer than the last, asked minutes ago), so a
//! tap the person was tricked into gives one window, not a standing grant.
//!
//! A window is consent and a record, not a cage: what a session does as root
//! while it is open — a package installed, a service started — outlasts it.
//! Every grant, with its signature, goes to `/var/log/midas-admin/grants.log`;
//! classic sudo records what was typed under it (`log_output`) beside it, while
//! sudo-rs, the hub's machine's, only logs each command to the journal.

use std::fs;
use std::io::Read;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

use anyhow::{anyhow, bail, Context, Result};
use data_encoding::BASE64URL_NOPAD;
use p256::ecdsa::signature::Verifier;
use p256::ecdsa::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::{Digest, Sha256};

use crate::events;
use crate::registry::now;

/// Root's settings: the user the agents are, the passkeys that may grant, the page's address.
pub const CONF: &str = "/etc/midas/admin.json";
/// The window as root keeps it: open or not, and the newest grant it took.
pub const WINDOW: &str = "/etc/midas/admin-window.json";
/// What lets the user be root while a window is open; nothing else writes it.
pub const SUDOERS: &str = "/etc/sudoers.d/midas-admin";
/// Root's answers for the hub to read: the window, and how each grant went.
pub const STATUS: &str = "/run/midas-admin/status.json";
/// Every grant, with its signature, and every window closing.
pub const LOG_DIR: &str = "/var/log/midas-admin";

/// The longest window when `admin.json` says none.
pub const MAX_MINUTES: u32 = 60;
/// How long a grant may wait between the person's tap and root reading it.
const FRESH_S: i64 = 600;
/// A request the person has not answered in this long is dropped.
const ASKED_S: i64 = 86400;

const KEY_LABEL: &str = "midas-admin-key-v1";
const GRANT_LABEL: &str = "midas-admin-grant-v1";

/// The DER head of a P-256 public key as `getPublicKey()` gives it (SubjectPublicKeyInfo): 65 bytes follow.
const SPKI_P256: [u8; 26] = [0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08,
    0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00];

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Conf {
    /// The user on this machine the agents log in as.
    pub user: String,
    /// The passkeys' relying party: the page's host (`garage44.eu`).
    pub rp_id: String,
    /// The page's origins a signature may come from (`https://garage44.eu`).
    pub origins: Vec<String>,
    #[serde(default)]
    pub max_minutes: u32,
    #[serde(default)]
    pub keys: Vec<Key>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Key {
    /// The credential's id, base64url.
    pub id: String,
    /// Its public key, SEC1, base64url.
    pub public: String,
    #[serde(default)]
    pub label: String,
    #[serde(default)]
    pub added: i64,
}

impl Conf {
    pub fn max(&self) -> u32 {
        if self.max_minutes == 0 { MAX_MINUTES } else { self.max_minutes }
    }
}

pub fn read_conf() -> Option<Conf> {
    serde_json::from_str(&fs::read_to_string(CONF).ok()?).ok()
}

/// What the person grants, as signed: every field is in the message.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Grant {
    pub id: String,
    pub user: String,
    pub minutes: u32,
    pub issued_at: i64,
    pub session: String,
    pub reason: String,
}

impl Grant {
    /// The words signed, one field a line, so no field can pass for another.
    pub fn message(&self) -> String {
        let line = |s: &str| s.replace(['\n', '\r'], " ");
        format!("{GRANT_LABEL}\nid {}\nuser {}\nminutes {}\nissued {}\nsession {}\nreason {}",
            line(&self.id), line(&self.user), self.minutes, self.issued_at, line(&self.session), line(&self.reason))
    }

    /// The WebAuthn challenge the page asks the passkey to sign: the message's hash, base64url.
    pub fn challenge(&self) -> String {
        BASE64URL_NOPAD.encode(&Sha256::digest(self.message().as_bytes()))
    }
}

/// A passkey's answer (`navigator.credentials.get`), each part base64url.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Assertion {
    pub credential_id: String,
    pub authenticator_data: String,
    pub client_data_json: String,
    pub signature: String,
}

fn b64url(s: &str, what: &str) -> Result<Vec<u8>> {
    BASE64URL_NOPAD.decode(s.trim_end_matches('=').as_bytes()).map_err(|e| anyhow!("{what} is not base64url: {e}"))
}

/// A public key from the page (SPKI DER, what `getPublicKey()` gives) or already SEC1.
pub fn public_key(bytes: &[u8]) -> Result<VerifyingKey> {
    let sec1 = if bytes.len() == 91 && bytes[..26] == SPKI_P256 { &bytes[26..] } else { bytes };
    VerifyingKey::from_sec1_bytes(sec1).map_err(|_| anyhow!("not a P-256 public key"))
}

/// Whether `a` is the person's signature over `g`, from the page, by one of `c`'s keys,
/// and `g` a grant root may take now: fresh, newer than `last_issued`, within the cap.
pub fn verify(c: &Conf, g: &Grant, a: &Assertion, now: i64, last_issued: i64) -> Result<()> {
    if g.user != c.user {
        bail!("the grant is for {}, the agents are {}", g.user, c.user);
    }
    if g.minutes == 0 || g.minutes > c.max() {
        bail!("{} minutes: a window is 1 to {} minutes", g.minutes, c.max());
    }
    if g.issued_at <= last_issued {
        bail!("not newer than the last grant taken: a grant is used once");
    }
    if now - g.issued_at > FRESH_S || g.issued_at > now + 60 {
        bail!("signed at {}, it is {now}: a grant is taken within {} minutes", g.issued_at, FRESH_S / 60);
    }
    let Some(key) = c.keys.iter().find(|k| k.id.trim_end_matches('=') == a.credential_id.trim_end_matches('=')) else {
        bail!("signed by a passkey this machine does not know");
    };
    let key = public_key(&b64url(&key.public, "the key")?)?;
    let cd = b64url(&a.client_data_json, "clientDataJSON")?;
    let client: Value = serde_json::from_slice(&cd).context("clientDataJSON is not JSON")?;
    if client["type"] != "webauthn.get" {
        bail!("not a sign-in assertion ({})", client["type"]);
    }
    if client["challenge"].as_str().map(|c| c.trim_end_matches('=')) != Some(g.challenge().as_str()) {
        bail!("the signature is over another grant than this one");
    }
    let origin = client["origin"].as_str().unwrap_or("");
    if !c.origins.iter().any(|o| o == origin) {
        bail!("signed on {origin:?}, not on the page");
    }
    let ad = b64url(&a.authenticator_data, "authenticatorData")?;
    if ad.len() < 37 {
        bail!("authenticatorData too short");
    }
    if ad[..32] != Sha256::digest(c.rp_id.as_bytes())[..] {
        bail!("signed for another site than {}", c.rp_id);
    }
    // User present and verified: a tap, and the fingerprint or PIN behind it.
    if ad[32] & 0x05 != 0x05 {
        bail!("the passkey did not verify the person (no fingerprint or PIN)");
    }
    let sig = Signature::from_der(&b64url(&a.signature, "the signature")?).map_err(|_| anyhow!("the signature is not DER"))?;
    let mut signed = ad.clone();
    signed.extend_from_slice(&Sha256::digest(&cd));
    key.verify(&signed, &sig).map_err(|_| anyhow!("the signature does not verify"))
}

/// A key line from the page: `midas-admin-key-v1 <id> <public> [label…]`.
pub fn parse_key_line(line: &str) -> Result<Key> {
    let mut w = line.split_whitespace();
    if w.next() != Some(KEY_LABEL) {
        bail!("not an admin key line (it starts {KEY_LABEL}): {line:?}");
    }
    let (Some(id), Some(public)) = (w.next(), w.next()) else { bail!("a key line is: {KEY_LABEL} <id> <public key> [label]") };
    b64url(id, "the credential id")?;
    let key = public_key(&b64url(public, "the public key")?)?;
    let sec1 = key.to_encoded_point(true);
    Ok(Key { id: id.trim_end_matches('=').into(), public: BASE64URL_NOPAD.encode(sec1.as_bytes()),
        label: w.collect::<Vec<_>>().join(" "), added: now() })
}

// --- root's side ---------------------------------------------------------------------------------

/// The window as root keeps it.
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Window {
    pub open: Option<Open>,
    #[serde(default)]
    pub last_issued: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Open {
    pub id: String,
    pub session: String,
    pub reason: String,
    pub opened: i64,
    pub until: i64,
}

/// What the hub spools for root (`<spool>/<name>.json`): a signed grant, or a close.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Spooled {
    Grant { grant: Grant, assertion: Assertion },
    Close { by: String, why: String },
}

/// Where the hub leaves them: in its own directory, which root only reads.
pub fn spool() -> PathBuf {
    PathBuf::from(crate::hubsetup::HOME).join("admin")
}

fn require_root(what: &str) -> Result<()> {
    if unsafe { libc::geteuid() } != 0 {
        bail!("{what} is root's: sudo midas hub {what}");
    }
    Ok(())
}

/// `sudo midas hub admin-setup`: the user the agents are, the page passkeys sign on, the cap.
pub fn setup(user: &str, rp_id: &str, origins: &[String], max_minutes: Option<u32>) -> Result<i32> {
    require_root("admin-setup")?;
    if user.is_empty() || user == "root" || !user.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
        bail!("--user: a plain user name, not root");
    }
    let mut c = read_conf().unwrap_or_default();
    c.user = user.into();
    c.rp_id = rp_id.into();
    c.origins = if origins.is_empty() { vec![format!("https://{rp_id}")] } else { origins.to_vec() };
    if let Some(m) = max_minutes {
        c.max_minutes = m;
    }
    let exists = fs::read_to_string("/etc/passwd").unwrap_or_default().lines().any(|l| l.split(':').next() == Some(user));
    if !exists {
        // Logs to read without root: the journal's group and adm's (/var/log).
        crate::util::run(std::process::Command::new("useradd").args(["--create-home", "--shell", "/bin/bash",
            "--groups", "systemd-journal,adm", "--comment", "midas agents (root only in a granted window)", user]))?;
        println!("created user {user}: put the agents' key in ~{user}/.ssh/authorized_keys");
    }
    write_root(CONF, &(serde_json::to_string_pretty(&c)? + "\n"))?;
    let sp = spool();
    fs::create_dir_all(&sp)?;
    crate::util::run(std::process::Command::new("chown").arg(format!("{}:{}", crate::hubsetup::USER, crate::hubsetup::USER)).arg(&sp))?;
    fs::set_permissions(&sp, std::os::unix::fs::PermissionsExt::from_mode(0o750))?;
    println!("{CONF}: agents are {user}; passkeys sign on {} ({}); windows up to {} min; {} key(s)",
        c.rp_id, c.origins.join(", "), c.max(), c.keys.len());
    if c.keys.is_empty() {
        println!("next: make the passkey on the page (Settings ▸ Admin passkey) and run the command it shows");
    }
    Ok(0)
}

/// `sudo midas hub admin-enroll '<line>'` (or `--remove <id>`): a passkey that may grant, or one no longer.
pub fn enroll(line: Option<&str>, remove: Option<&str>) -> Result<i32> {
    require_root("admin-enroll")?;
    let mut c = read_conf().ok_or_else(|| anyhow!("no {CONF}: sudo midas hub admin-setup first"))?;
    if let Some(id) = remove {
        let before = c.keys.len();
        c.keys.retain(|k| k.id != id.trim_end_matches('='));
        if c.keys.len() == before {
            bail!("no key {id}");
        }
        println!("removed key {id}");
    } else {
        let k = parse_key_line(line.unwrap_or_default())?;
        c.keys.retain(|o| o.id != k.id);
        println!("added key {}{}", k.id, if k.label.is_empty() { String::new() } else { format!(" ({})", k.label) });
        c.keys.push(k);
    }
    write_root(CONF, &(serde_json::to_string_pretty(&c)? + "\n"))?;
    log_line(&json!({"at": now(), "event": "keys", "keys": c.keys.iter().map(|k| &k.id).collect::<Vec<_>>()}));
    Ok(0)
}

/// Root's file, written whole and renamed into place.
fn write_root(path: &str, body: &str) -> Result<()> {
    crate::store::write_atomic(Path::new(path), body.as_bytes(), 0o644)
}

fn log_line(v: &Value) {
    let _ = fs::create_dir_all(LOG_DIR);
    let line = format!("{v}\n");
    let f = fs::OpenOptions::new().create(true).append(true).mode(0o600).open(format!("{LOG_DIR}/grants.log"));
    if let Ok(mut f) = f {
        use std::io::Write;
        let _ = f.write_all(line.as_bytes());
    }
    println!("{line}");
}

/// The sudoers lines of an open window: root for `user`, everything typed recorded.
/// `record`: sudo's own recording of what is typed, which sudo-rs (Ubuntu's sudo since 25.10)
/// does not have; it logs each command it runs to the journal instead (`journalctl _COMM=sudo`).
pub fn sudoers(user: &str, o: &Open, record: bool) -> String {
    let record = if record { format!("Defaults:{user} log_output, iolog_dir={LOG_DIR}/io\n") } else { String::new() };
    format!("# midas admin window {} for {}, until {} (unix): written by `midas hub admin-apply`, removed when it closes.\n\
             {record}{user} ALL=(ALL:ALL) NOPASSWD: ALL\n", o.id, o.session.replace('\n', " "), o.until)
}

/// Whether visudo takes `body` as a sudoers file.
fn visudo_ok(tmp: &str, body: &str) -> Result<()> {
    fs::write(tmp, body)?;
    fs::set_permissions(tmp, std::os::unix::fs::PermissionsExt::from_mode(0o440))?;
    crate::util::run(std::process::Command::new("visudo").args(["-c", "-q", "-f", tmp])).map(|_| ())
}

/// A spooled file, read by root out of the hub's directory: no link followed, nothing large.
fn read_spooled(p: &Path) -> Result<Spooled> {
    let f = fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(p)?;
    if !f.metadata()?.is_file() {
        bail!("not a file");
    }
    let mut text = String::new();
    f.take(64 * 1024).read_to_string(&mut text)?;
    Ok(serde_json::from_str(&text)?)
}

/// `midas hub admin-apply` (root; `midas-admin.service`): close what is over, then take what the hub spooled.
pub fn apply() -> Result<i32> {
    require_root("admin-apply")?;
    let _lock = crate::store::lock(Path::new("/etc/midas/.admin.lock"))?;
    let Some(c) = read_conf() else {
        // Not set up: nothing may open, and what is spooled is answered as refused.
        let mut results = Vec::new();
        for (name, _) in spooled() {
            results.push(json!({"id": name, "ok": false, "why": "admin is not set up on this machine", "at": now()}));
        }
        write_status(&Window::default(), &results);
        return Ok(0);
    };
    let mut w: Window = fs::read_to_string(WINDOW).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default();
    let t = now();
    let mut results = previous_results();
    if w.open.as_ref().is_some_and(|o| t >= o.until) {
        close_window(&c, &mut w, "its time was up");
    }
    // Root's word is the window file: a sudoers file with no window open is a leftover, and goes.
    if w.open.is_none() && Path::new(SUDOERS).exists() {
        let _ = fs::remove_file(SUDOERS);
    }
    for (name, item) in spooled() {
        let r = match item {
            Ok(Spooled::Grant { grant, assertion }) => match verify(&c, &grant, &assertion, t, w.last_issued).and_then(|()| open(&c, &mut w, &grant, &assertion, t)) {
                Ok(()) => json!({"id": grant.id, "ok": true, "until": w.open.as_ref().map(|o| o.until), "at": t}),
                Err(e) => {
                    log_line(&json!({"at": t, "event": "refused", "grant": grant, "why": format!("{e:#}")}));
                    json!({"id": grant.id, "ok": false, "why": format!("{e:#}"), "at": t})
                }
            },
            Ok(Spooled::Close { by, why }) => {
                if w.open.is_some() {
                    close_window(&c, &mut w, &format!("{why} ({by})"));
                }
                json!({"id": name, "ok": true, "closed": true, "at": t})
            }
            Err(e) => json!({"id": name, "ok": false, "why": format!("unreadable: {e:#}"), "at": t}),
        };
        results.push(r);
    }
    write_root(WINDOW, &(serde_json::to_string_pretty(&w)? + "\n"))?;
    results.retain(|r| t - r["at"].as_i64().unwrap_or(0) < 86400);
    let skip = results.len().saturating_sub(50);
    write_status(&w, &results[skip..]);
    Ok(0)
}

/// What waits in the spool, oldest first; each file taken out as it is read.
fn spooled() -> Vec<(String, Result<Spooled>)> {
    // The hub's user owns the directory above it, so it could put a link to another directory
    // in its place, whose .json files root would then read and remove: only the real one counts.
    let real = fs::symlink_metadata(spool()).is_ok_and(|m| {
        use std::os::unix::fs::MetadataExt;
        m.is_dir() && uid_of(crate::hubsetup::USER) == Some(m.uid())
    });
    if !real {
        return Vec::new();
    }
    let mut names: Vec<PathBuf> = fs::read_dir(spool()).into_iter().flatten().flatten().map(|e| e.path())
        .filter(|p| p.extension().is_some_and(|x| x == "json")).collect();
    names.sort();
    names.into_iter().map(|p| {
        let item = read_spooled(&p);
        let _ = fs::remove_file(&p);
        (p.file_stem().unwrap_or_default().to_string_lossy().into_owned(), item)
    }).collect()
}

fn open(c: &Conf, w: &mut Window, g: &Grant, a: &Assertion, t: i64) -> Result<()> {
    let o = Open { id: g.id.clone(), session: g.session.clone(), reason: g.reason.clone(), opened: t, until: t + i64::from(g.minutes) * 60 };
    // Checked by visudo before it is in place: a broken sudoers file breaks sudo for everyone.
    // A name with a dot is one sudo's includedir skips. Recorded if this sudo can, else not:
    // sudo-rs refuses `log_output` (found on the hub's machine, 2026-11-28).
    let tmp = format!("/etc/sudoers.d/.midas-admin.{}", std::process::id());
    fs::create_dir_all(format!("{LOG_DIR}/io"))?;
    let mut recorded = true;
    if visudo_ok(&tmp, &sudoers(&c.user, &o, true)).is_err() {
        recorded = false;
        if let Err(e) = visudo_ok(&tmp, &sudoers(&c.user, &o, false)) {
            let _ = fs::remove_file(&tmp);
            bail!("visudo refused the window's sudoers: {e:#}");
        }
    }
    fs::rename(&tmp, SUDOERS)?;
    w.last_issued = g.issued_at;
    // Root's own log only: a log file of the hub's that root created would be root's, and the
    // hub could not write it any more. The hub logs the window from root's answers (`tick`).
    log_line(&json!({"at": t, "event": "opened", "grant": g, "assertion": a, "until": o.until,
        "typed": if recorded { "recorded in io/" } else { "not recorded: sudo logs each command to the journal" }}));
    w.open = Some(o);
    Ok(())
}

fn close_window(c: &Conf, w: &mut Window, why: &str) {
    let _ = fs::remove_file(SUDOERS);
    let killed = kill_root_of(&c.user);
    if let Some(o) = w.open.take() {
        log_line(&json!({"at": now(), "event": "closed", "id": o.id, "session": o.session, "why": why, "killed": killed}));
    }
}

/// Stop what runs as root from `user`'s logins (its audit login id, which sudo
/// keeps): a root shell left open would otherwise outlast the window. What it
/// had systemd start is not theirs any more, and stays.
fn kill_root_of(user: &str) -> Vec<i32> {
    let Some(uid) = uid_of(user) else { return Vec::new() };
    let mut killed = Vec::new();
    for e in fs::read_dir("/proc").into_iter().flatten().flatten() {
        let Ok(pid) = e.file_name().to_string_lossy().parse::<i32>() else { continue };
        let login = fs::read_to_string(format!("/proc/{pid}/loginuid")).ok().and_then(|t| t.trim().parse::<u32>().ok());
        if login != Some(uid) {
            continue;
        }
        let status = fs::read_to_string(format!("/proc/{pid}/status")).unwrap_or_default();
        let euid = status.lines().find_map(|l| l.strip_prefix("Uid:")).and_then(|l| l.split_whitespace().nth(1)).and_then(|u| u.parse::<u32>().ok());
        if euid == Some(0) && unsafe { libc::kill(pid, libc::SIGKILL) } == 0 {
            killed.push(pid);
        }
    }
    killed
}

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

fn previous_results() -> Vec<Value> {
    read_status()["results"].as_array().cloned().unwrap_or_default()
}

fn write_status(w: &Window, results: &[Value]) {
    let dir = Path::new(STATUS).parent().unwrap_or(Path::new("/run"));
    let _ = fs::create_dir_all(dir);
    let _ = fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o755));
    let body = json!({"open": w.open, "results": results, "at": now()});
    if let Err(e) = crate::store::write_atomic(Path::new(STATUS), body.to_string().as_bytes(), 0o644) {
        eprintln!("midas admin: writing {STATUS}: {e:#}");
    }
}

/// Root's answers, as the hub reads them: `{open, results}`.
pub fn read_status() -> Value {
    fs::read_to_string(STATUS).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(json!({}))
}

// --- the hub's side ------------------------------------------------------------------------------

fn requests_path() -> PathBuf {
    crate::registry::root().join("admin.json")
}

/// A session asks for a window: one asked at a time per session, the newer kept.
pub fn request(session: &str, reason: &str, minutes: u32) -> Result<String> {
    let reason: String = reason.trim().replace(['\n', '\r'], " ").chars().take(300).collect();
    if reason.is_empty() {
        bail!("say what root is for: midas admin \"restart caddy\"");
    }
    if session.is_empty() {
        bail!("a window is a session's: run it from one");
    }
    let Some(c) = read_conf() else { bail!("admin is not set up on the hub's machine (sudo midas hub admin-setup)") };
    if c.keys.is_empty() {
        bail!("no passkey can grant yet: the person makes one on the page (Settings ▸ Admin passkey)");
    }
    if minutes == 0 || minutes > c.max() {
        bail!("{minutes} minutes: a window is 1 to {} minutes", c.max());
    }
    let id = crate::store::update(requests_path(), |d: &mut Value| {
        let n = d["seq"].as_u64().unwrap_or(0) + 1;
        d["seq"] = json!(n);
        let id = format!("a{n}");
        crate::store::objects(d, &["requests"]);
        let reqs = d["requests"].as_object_mut().expect("an object");
        for r in reqs.values_mut() {
            if r["session"] == session && r["state"] == "asked" {
                r["state"] = json!("replaced");
            }
        }
        reqs.insert(id.clone(), json!({"session": session, "reason": reason, "minutes": minutes, "at": now(), "state": "asked"}));
        Ok(id)
    })?;
    events::emit("admin_asked", json!({"actor": session, "id": id, "minutes": minutes, "reason": reason}));
    Ok(id)
}

/// The grant the page is to sign for request `id`: what root will check, field by field.
pub fn to_sign(id: &str) -> Result<Value> {
    let c = read_conf().ok_or_else(|| anyhow!("admin is not set up"))?;
    let r = request_of(id)?;
    if r["state"] != "asked" {
        bail!("{id} is {}, not waiting for you", r["state"].as_str().unwrap_or("?"));
    }
    let g = grant_of(&c, id, &r, now());
    Ok(json!({"grant": g, "challenge": g.challenge(), "rp_id": c.rp_id, "keys": c.keys.iter().map(|k| &k.id).collect::<Vec<_>>()}))
}

fn grant_of(c: &Conf, id: &str, r: &Value, issued_at: i64) -> Grant {
    Grant { id: id.into(), user: c.user.clone(), minutes: r["minutes"].as_u64().unwrap_or(0) as u32, issued_at,
        session: r["session"].as_str().unwrap_or("").into(), reason: r["reason"].as_str().unwrap_or("").into() }
}

fn request_of(id: &str) -> Result<Value> {
    let d: Value = fs::read_to_string(requests_path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(json!({}));
    d["requests"].get(id).cloned().ok_or_else(|| anyhow!("no admin request {id}"))
}

fn set_state(id: &str, state: &str, why: Option<&str>) -> Result<Value> {
    crate::store::update(requests_path(), |d: &mut Value| {
        let r = d["requests"].get_mut(id).ok_or_else(|| anyhow!("no admin request {id}"))?;
        r["state"] = json!(state);
        r["changed"] = json!(now());
        if let Some(w) = why {
            r["why"] = json!(w);
        }
        Ok(r.clone())
    })
}

/// The person's Allow: the signed grant, checked here for a plain answer and spooled for root,
/// whose check is the one that counts.
pub fn grant(id: &str, issued_at: i64, a: Assertion, by: &str) -> Result<Value> {
    let c = read_conf().ok_or_else(|| anyhow!("admin is not set up"))?;
    let r = request_of(id)?;
    if r["state"] != "asked" {
        bail!("{id} is {}, not waiting for you", r["state"].as_str().unwrap_or("?"));
    }
    let g = grant_of(&c, id, &r, issued_at);
    let last = fs::read_to_string(WINDOW).ok().and_then(|t| serde_json::from_str::<Window>(&t).ok()).map(|w| w.last_issued).unwrap_or(0);
    verify(&c, &g, &a, now(), last)?;
    spool_write(&format!("{}-{id}", now()), &Spooled::Grant { grant: g, assertion: a })?;
    events::emit("admin_signed", json!({"actor": by, "id": id, "session": r["session"]}));
    set_state(id, "signed", None)
}

/// The person's No, or the hub dropping a request: told to the session.
pub fn decline(id: &str, by: &str) -> Result<Value> {
    let r = set_state(id, "declined", None)?;
    let s = r["session"].as_str().unwrap_or("");
    let _ = crate::collab::say("hub", s, &format!("admin {id} declined by the person: no root for “{}”. Do without it, or ask them why.",
        r["reason"].as_str().unwrap_or("")), "admin");
    events::emit("admin_declined", json!({"actor": by, "id": id, "session": s}));
    Ok(r)
}

/// Close the window: the session that has it says it is done, the person, or the session ended.
pub fn close(by: &str, why: &str) -> Result<()> {
    spool_write(&format!("{}-close", now()), &Spooled::Close { by: by.into(), why: why.into() })
}

fn spool_write(name: &str, item: &Spooled) -> Result<()> {
    let p = spool().join(format!("{name}.json"));
    crate::store::write_atomic(&p, serde_json::to_string(item)?.as_bytes(), 0o640)
        .with_context(|| format!("spooling {} for root", p.display()))
}

/// What the page and `midas admin` show: the setup (no keys' public halves), requests, the window.
pub fn status() -> Value {
    let d: Value = fs::read_to_string(requests_path()).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or(json!({}));
    let t = now();
    let mut reqs: Vec<Value> = d["requests"].as_object().into_iter().flatten()
        .filter(|(_, r)| r["state"] == "asked" || r["state"] == "signed" || r["state"] == "open"
            || t - r["changed"].as_i64().or(r["at"].as_i64()).unwrap_or(0) < 86400)
        .map(|(id, r)| { let mut r = r.clone(); r["id"] = json!(id); r }).collect();
    reqs.sort_by_key(|r| r["at"].as_i64().unwrap_or(0));
    let conf = read_conf().map(|c| json!({"user": c.user, "rp_id": c.rp_id, "max_minutes": c.max(),
        "keys": c.keys.iter().map(|k| json!({"id": k.id, "label": k.label, "added": k.added})).collect::<Vec<_>>()}));
    json!({"setup": conf, "requests": reqs, "window": read_status()["open"]})
}

/// Every half minute on the hub: root's answers told to the sessions, windows that closed, requests gone stale.
pub fn tick() {
    let st = read_status();
    let open_id = st["open"]["id"].as_str().map(str::to_string);
    let results = st["results"].as_array().cloned().unwrap_or_default();
    let mut tell: Vec<(String, String)> = Vec::new();
    let r = crate::store::update(requests_path(), |d: &mut Value| {
        let Some(reqs) = d["requests"].as_object_mut() else { return Ok(()) };
        let t = now();
        for (id, r) in reqs.iter_mut() {
            let session = r["session"].as_str().unwrap_or("").to_string();
            match r["state"].as_str().unwrap_or("") {
                "signed" => {
                    let Some(res) = results.iter().rev().find(|x| x["id"] == id.as_str()) else { continue };
                    if res["ok"] == true {
                        r["state"] = json!("open");
                        r["until"] = res["until"].clone();
                        events::emit("admin_opened", json!({"actor": session, "id": id, "minutes": r["minutes"], "reason": r["reason"], "until": r["until"]}));
                        tell.push((session, format!("admin {id} is open: `ssh host sudo …` works until {} UTC, for “{}”. \
                            Say `midas admin --done` when you are through; it closes by itself then, and when this session ends.",
                            hhmm_utc(res["until"].as_i64().unwrap_or(t)), r["reason"].as_str().unwrap_or(""))));
                    } else {
                        r["state"] = json!("refused");
                        r["why"] = res["why"].clone();
                        tell.push((session, format!("admin {id} was refused by the machine: {}", res["why"].as_str().unwrap_or("?"))));
                    }
                    r["changed"] = json!(t);
                }
                "open" if open_id.as_deref() != Some(id.as_str()) => {
                    r["state"] = json!("closed");
                    r["changed"] = json!(t);
                    events::emit("admin_closed", json!({"actor": session, "id": id}));
                    tell.push((session, format!("admin {id} is closed: no root on the hub's machine any more.")));
                }
                "asked" if t - r["at"].as_i64().unwrap_or(t) > ASKED_S => {
                    r["state"] = json!("expired");
                    r["changed"] = json!(t);
                }
                _ => {}
            }
        }
        // A day's history is enough: the log on the machine is the record.
        reqs.retain(|_, r| matches!(r["state"].as_str(), Some("asked" | "signed" | "open"))
            || t - r["changed"].as_i64().or(r["at"].as_i64()).unwrap_or(t) < 7 * 86400);
        Ok(())
    });
    if let Err(e) = r {
        events::emit("error", json!({"actor": "hub", "what": format!("admin requests: {e:#}")}));
    }
    for (s, text) in tell {
        let _ = crate::collab::say("hub", &s, &text, "admin");
    }
}

/// A session ended: its window closes, and what it asked for is dropped.
pub fn session_ended(owner: &str) {
    let st = read_status();
    if st["open"]["session"].as_str() == Some(owner) {
        let _ = close(owner, "the session ended");
    }
    let _ = crate::store::update(requests_path(), |d: &mut Value| {
        for r in d["requests"].as_object_mut().into_iter().flat_map(|m| m.values_mut()) {
            if r["session"] == owner && r["state"] == "asked" {
                r["state"] = json!("dropped");
                r["changed"] = json!(now());
            }
        }
        Ok(())
    });
}

/// `--for 30m`, `1h`, `45`: minutes.
pub fn minutes_of(s: &str) -> Result<u32> {
    let s = s.trim();
    let (n, unit) = s.find(|c: char| !c.is_ascii_digit()).map_or((s, ""), |i| s.split_at(i));
    let n: u32 = n.parse().map_err(|_| anyhow!("--for: minutes, as 30m or 1h"))?;
    match unit {
        "" | "m" | "min" => Ok(n),
        "h" => Ok(n * 60),
        _ => bail!("--for: minutes, as 30m or 1h"),
    }
}

/// `14:05`, in UTC: the agent says it to the person with its offset.
fn hhmm_utc(ts: i64) -> String {
    chrono::DateTime::from_timestamp(ts, 0).map(|t| t.format("%H:%M").to_string()).unwrap_or_else(|| "?".into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use p256::ecdsa::signature::Signer;
    use p256::ecdsa::SigningKey;

    fn key() -> SigningKey {
        SigningKey::from_slice(&[7u8; 32]).unwrap()
    }

    fn conf() -> Conf {
        let pk = key().verifying_key().to_encoded_point(true);
        Conf { user: "agent".into(), rp_id: "garage44.eu".into(), origins: vec!["https://garage44.eu".into()], max_minutes: 60,
            keys: vec![Key { id: "Y3JlZA".into(), public: BASE64URL_NOPAD.encode(pk.as_bytes()), label: "phone".into(), added: 0 }] }
    }

    fn grant(t: i64) -> Grant {
        Grant { id: "a1".into(), user: "agent".into(), minutes: 30, issued_at: t, session: "session-s902".into(), reason: "restart caddy".into() }
    }

    /// What a phone's passkey answers for `challenge`, signed by `k`.
    fn assert_with(k: &SigningKey, challenge: &str, origin: &str, rp: &str, flags: u8) -> Assertion {
        let cd = json!({"type": "webauthn.get", "challenge": challenge, "origin": origin, "crossOrigin": false}).to_string();
        let mut ad = Sha256::digest(rp.as_bytes()).to_vec();
        ad.push(flags);
        ad.extend_from_slice(&[0, 0, 0, 0]);
        let mut signed = ad.clone();
        signed.extend_from_slice(&Sha256::digest(cd.as_bytes()));
        let sig: Signature = k.sign(&signed);
        Assertion { credential_id: "Y3JlZA".into(), authenticator_data: BASE64URL_NOPAD.encode(&ad),
            client_data_json: BASE64URL_NOPAD.encode(cd.as_bytes()), signature: BASE64URL_NOPAD.encode(sig.to_der().as_bytes()) }
    }

    fn good(g: &Grant) -> Assertion {
        assert_with(&key(), &g.challenge(), "https://garage44.eu", "garage44.eu", 0x05)
    }

    #[test]
    fn a_signed_grant_verifies() {
        let g = grant(1000);
        verify(&conf(), &g, &good(&g), 1010, 0).unwrap();
    }

    #[test]
    fn a_grant_changed_after_signing_does_not() {
        let g = grant(1000);
        let a = good(&g);
        for changed in [Grant { minutes: 60, ..g.clone() }, Grant { session: "session-s1".into(), ..g.clone() },
                        Grant { reason: "anything".into(), ..g.clone() }, Grant { id: "a2".into(), ..g.clone() }] {
            let e = verify(&conf(), &changed, &a, 1010, 0).unwrap_err().to_string();
            assert!(e.contains("another grant"), "{e}");
        }
    }

    #[test]
    fn root_refuses_what_the_hub_could_make() {
        let g = grant(1000);
        let c = conf();
        // Another key, as the hub's user could make one.
        let other = SigningKey::from_slice(&[9u8; 32]).unwrap();
        assert!(verify(&c, &g, &assert_with(&other, &g.challenge(), "https://garage44.eu", "garage44.eu", 5), 1010, 0).is_err());
        // Signed for another site, or on another page.
        assert!(verify(&c, &g, &assert_with(&key(), &g.challenge(), "https://evil.example", "garage44.eu", 5), 1010, 0).is_err());
        assert!(verify(&c, &g, &assert_with(&key(), &g.challenge(), "https://garage44.eu", "evil.example", 5), 1010, 0).is_err());
        // A tap without the fingerprint behind it.
        assert!(verify(&c, &g, &assert_with(&key(), &g.challenge(), "https://garage44.eu", "garage44.eu", 0x01), 1010, 0).is_err());
        // For root, or longer than the cap.
        let root = Grant { user: "root".into(), ..g.clone() };
        assert!(verify(&c, &root, &good(&root), 1010, 0).is_err());
        let long = Grant { minutes: 61, ..g.clone() };
        assert!(verify(&c, &long, &good(&long), 1010, 0).unwrap_err().to_string().contains("1 to 60"));
    }

    #[test]
    fn a_grant_is_taken_once_and_soon() {
        let g = grant(1000);
        let a = good(&g);
        assert!(verify(&conf(), &g, &a, 1010, 1000).unwrap_err().to_string().contains("used once"));
        assert!(verify(&conf(), &g, &a, 1000 + FRESH_S + 1, 0).unwrap_err().to_string().contains("within"));
        assert!(verify(&conf(), &g, &a, 900, 0).is_err(), "signed in the future");
    }

    #[test]
    fn the_message_keeps_fields_apart() {
        let a = Grant { reason: "x\nsession session-s1".into(), ..grant(1) };
        assert_eq!(a.message().lines().count(), 7);
        assert!(a.message().ends_with("reason x session session-s1"));
    }

    #[test]
    fn a_key_line_round_trips_from_the_page() {
        let vk = *key().verifying_key();
        let mut spki = SPKI_P256.to_vec();
        spki.extend_from_slice(vk.to_encoded_point(false).as_bytes());
        // As web/src/lib/passkey.ts `makeKey` writes it: the id, the SPKI public key, a label.
        let line = format!("midas-admin-key-v1 Y3JlZA {} Pixel", BASE64URL_NOPAD.encode(&spki));
        let k = parse_key_line(&line).unwrap();
        assert_eq!((k.id.as_str(), k.label.as_str()), ("Y3JlZA", "Pixel"));
        assert_eq!(k.public, conf().keys[0].public);
        assert!(parse_key_line("midas-release-public-v1 abc").is_err());
    }

    /// What Chrome 154's passkey (its virtual authenticator, over CDP) made and signed through
    /// web/src/lib/passkey.ts on http://localhost:43733, 2026-11-28: the browser's own encodings.
    #[test]
    fn a_browsers_passkey_verifies() {
        let k = parse_key_line("midas-admin-key-v1 Ijh2-lbRWEuPCIH097_lmu_S-Ak6vofDiull9pNJuyk MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEDiwasYy_wD_mT7RqrDxjA1bTysFuYubbRngKSWPCLnXNDgSVvc2Hfvpl7eFeROMlhClM5ss_HB-63n3Zlbumlw virtual").unwrap();
        let c = Conf { user: "agent".into(), rp_id: "localhost".into(), origins: vec!["http://localhost:43733".into()], max_minutes: 60, keys: vec![k] };
        let g = Grant { id: "a7".into(), user: "agent".into(), minutes: 30, issued_at: 1795896000, session: "session-s902".into(), reason: "restart caddy".into() };
        assert_eq!(g.challenge(), "3itBLyWMsKWqAnT7EyRseqjWwM4N-fAtPooAnGTPKzY");
        let a = Assertion {
            credential_id: "Ijh2-lbRWEuPCIH097_lmu_S-Ak6vofDiull9pNJuyk".into(),
            authenticator_data: "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAAAg".into(),
            client_data_json: "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiM2l0Qkx5V01zS1dxQW5UN0V5UnNlcWpXd000Ti1mQXRQb29BbkdUUEt6WSIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDM3MzMiLCJjcm9zc09yaWdpbiI6ZmFsc2V9".into(),
            signature: "MEYCIQD6zfNMRf-DSHD8QYvWV24Sfvp2Vw4fvFmaoeHQUQbl0AIhAKjoPmJqvqIlfo4Fhh-FUcm0b_HQ-EHCL4MI7VQ6Omuu".into(),
        };
        verify(&c, &g, &a, 1795896010, 0).unwrap();
        // The same signature for a longer window is not one.
        assert!(verify(&c, &Grant { minutes: 60, ..g }, &a, 1795896010, 0).is_err());
    }

    #[test]
    fn minutes_read_as_people_write_them() {
        assert_eq!(minutes_of("30m").unwrap(), 30);
        assert_eq!(minutes_of("1h").unwrap(), 60);
        assert_eq!(minutes_of("45").unwrap(), 45);
        assert!(minutes_of("soon").is_err());
    }

    #[test]
    fn the_sudoers_file_records_what_is_typed() {
        let o = Open { id: "a1".into(), session: "s".into(), reason: "r".into(), opened: 0, until: 1800 };
        let s = sudoers("agent", &o, true);
        assert!(!sudoers("agent", &o, false).contains("log_output"), "sudo-rs has no log_output");
        assert!(s.contains("Defaults:agent log_output"));
        assert!(s.contains("agent ALL=(ALL:ALL) NOPASSWD: ALL"));
    }
}