git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T20:08:05Z
feat(admin): root on the hub's machine only in a window the person's passkey signs The agents reached the hub's machine as an account with passwordless sudo and the docker group, at all times and in every session. Now they can log in as a user of their own that is root only while a window is open: - a session asks: `midas admin "restart caddy" --for 30m` - the person's phone shows it under Needs you (and as a push); Allow signs the grant (id, user, minutes, when, session, reason) with a passkey made once in Settings > Admin - the hub spools the signed grant; root (`midas hub admin-apply`, run by midas-admin.path and every minute by midas-admin.timer) checks it against a key the person installed themselves (`admin-enroll`), its freshness, the cap and that it is newer than the last, and only then writes /etc/sudoers.d/midas-admin (checked by visudo first) - the window closes on time, on `midas admin --done`, when the session ends, or from the page; closing kills what runs as root from the user's logins (by login uid), and the session hears each step The hub cannot forge a grant: it carries the signature but never holds the key. Every grant and its signature go to /var/log/midas-admin/grants.log. sudo-rs (Ubuntu's sudo, on the hub's machine) has no `log_output`, so typing in a root shell is not recorded there; each sudo command is in the journal. Tried on the hub's machine with a throwaway key: a signed grant opened it (sudo as root), a replay of it was refused, closing removed the sudoers file and killed a `sudo sleep` left running.
DESIGN.md | 21 +
docs/hub.md | 37 ++
docs/usage.md | 17 +
src/admin.rs | 848 ++++++++++++++++++++++++++++++++++++++++
src/collab.rs | 4 +-
src/hub.rs | 50 +++
src/hubsetup.rs | 12 +-
src/main.rs | 69 ++++
src/push.rs | 10 +
units/midas-admin.path | 11 +
units/midas-admin.service | 16 +
units/midas-admin.timer | 12 +
web/src/app.css | 10 +
web/src/components/admin.tsx | 135 +++++++
web/src/components/home.tsx | 2 +-
web/src/components/needs.tsx | 9 +-
web/src/components/settings.tsx | 3 +
web/src/lib/api.ts | 9 +-
web/src/lib/needs.test.ts | 12 +-
web/src/lib/needs.ts | 16 +-
web/src/lib/passkey.ts | 79 ++++
web/src/lib/store.ts | 8 +-
web/src/lib/types.ts | 20 +
23 files changed, 1390 insertions(+), 20 deletions(-)
diff --git a/DESIGN.md b/DESIGN.md
index 3dc8def..5347f68 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -646,6 +646,26 @@ status is the number of the caller's. **`midas mcp`** offers the same as MCP too
is not seen (the person's choices). This is the first step of the
proposal; incidents, rollback and agents put on them build on its
`watch_changed` events.
+30. **Root on the hub's machine only in a window the person signs**
+ (2026-11-28, `admin.rs`). The agents reached the hub's machine as an
+ account with passwordless sudo and the docker group, held by every
+ session at all times: any wrong command, any instruction hidden in a page
+ a session read, and the autopilot answering for the person all ran with
+ root over the git server, the certificates and the deployed services. Now
+ they log in as a user of their own, root only while a window is open: a
+ session asks (`midas admin`), the person's passkey signs the grant (who,
+ how long, why, when), and root checks that signature against a key the
+ person installed from their own login before it writes the sudoers file.
+ The hub carries the request and the signature and cannot make either,
+ as with a release (decision 23's deferred updater asked the same). Root
+ caps what it takes — one user, at most an hour, a grant used once and
+ signed minutes ago — because the page asking for the tap is the hub's,
+ and a person tricked into one should give one window, not a standing
+ grant. Rejected: root trusting the hub's word that the person allowed it
+ (the hub's sign-in would guard root); the window checked by the agents'
+ own tools (an agent could skip them). A window is consent and a record,
+ not a cage: closing it kills root processes from the user's logins, but
+ what root started through systemd, or installed, outlasts it.
## 9. What went wrong, and what midas does about it
@@ -661,5 +681,6 @@ status is the number of the caller's. **`midas mcp`** offers the same as MCP too
| Unpushed commits never reached a node | bundled from `HEAD` |
| A session ran in another's checkout | `midas holds` refuses the connection |
| A node shared its owner's home and network | its own user and a firewall on the machine (§6) |
+| Every session had root on the hub's machine, always | a user of the agents' own, root only in a window the person's passkey signs (decision 30) |
| Every incident diagnosed from transcripts | one structured log (§7) |
| Green gates rerun because another landing pushed while they waited | the landing queue (decision 17) |
diff --git a/docs/hub.md b/docs/hub.md
index 9428a0d..110ab01 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -82,6 +82,39 @@ The Forgejo token, if given, is what the agents' git-server calls through the
hub are made with, so its permissions are theirs. `caller list` and
`caller remove <name>` manage the rest.
+### Root on the hub's machine, only while you allow it
+
+When the agents run on the hub's machine and sometimes need root there
+(restart a service, install a package), give them a user of their own that is
+root only in a window you grant with a passkey (DESIGN.md decision 30):
+
+```bash
+sudo midas hub admin-setup --user agent --rp-id garage44.eu # the page's host
+```
+
+It creates the user (in `systemd-journal` and `adm`, to read logs) if it is
+missing and writes `/etc/midas/admin.json`. Put the agents' ssh key in
+`~agent/.ssh/authorized_keys` and take it out of any account that has sudo or is
+in the `docker` group, which is root as well. Then, on the page, **Settings ▸
+Admin ▸ Make a passkey on this device** (on your phone, on the page's own
+host), and run the command it shows from your own login:
+`sudo midas hub admin-enroll 'midas-admin-key-v1 …'`. Until a passkey is
+installed, no window can open.
+
+A session then asks `midas admin "restart caddy" --for 30m`. Your phone shows
+it under **Needs you**; **Allow with passkey** signs who, how long and why, and
+root (`midas-admin.service`) opens the window only for that signature: sudo
+works for the agents' user until the time is up (60 minutes at most,
+`--max-minutes`), the session says `midas admin --done`, or it ends. The
+session hears each step as a note. Closing kills what still runs as root from
+the user's logins; what root started through systemd stays. Every grant and
+its signature is in `/var/log/midas-admin/grants.log`. Classic sudo also
+records what was typed under it in `/var/log/midas-admin/io` (`sudoreplay -d
+/var/log/midas-admin/io -l`); sudo-rs, Ubuntu's sudo since 25.10, cannot, and
+logs only each command it runs (`journalctl _COMM=sudo`), so what is typed in a
+root shell (`sudo -i`) goes unrecorded.
+`sudo midas hub admin-enroll --remove <id>` takes a passkey away.
+
## 4. Say what "warm" means
The hub keeps free nodes built at the tip of a branch, so taking one costs only
@@ -1446,6 +1479,10 @@ healthy.
| `/etc/midas/mirror_ed25519` | the deploy key |
| `/etc/midas/publisher.key` | root's own caller key, which the publisher reports deploys with |
| `/etc/midas/release.pub` | the owner's release key, public half: what `self_update: "signed"` checks a published midas against |
+| `/etc/midas/admin.json` | admin windows: the agents' user, the page passkeys sign on, the passkeys that may grant (root's) |
+| `/etc/midas/admin-window.json`, `/etc/sudoers.d/midas-admin` | the window root keeps, and the sudoers file only while it is open |
+| `/srv/midas/admin/` | grants and closes the hub spools for root |
+| `/var/log/midas-admin/` | every grant with its signature (`grants.log`), and with classic sudo what was typed under it (`io/`) |
| `/srv/midas/callers.json` | caller keys (and their git tokens) |
| `/srv/midas/openai.key` | the OpenAI key for talking sessions over by voice (optional) |
| `/srv/midas/remote-mcp.json` | remote MCP servers and the tokens the hub calls them with (`midas remote set`) |
diff --git a/docs/usage.md b/docs/usage.md
index 33b5776..5732830 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -278,6 +278,23 @@ session. With `--secret` the box has a field whose value goes to the hub —
yet), `bot:<node or group>:<NAME>` a bot secret — and the session hears that it
is set, never what it is.
+### Root on the hub's machine
+
+```bash
+midas admin "restart caddy, which holds a stale certificate" --for 30m
+midas admin # how it stands
+midas admin --done # through with it
+```
+
+Where the hub's machine is set up for it (`docs/hub.md`, step 3), the agents'
+user there has no root, until the person allows a window with their passkey:
+the request is under **Needs you** on their phone, and a note tells the session
+when `sudo` works and until when (UTC), or that they declined. End the turn
+rather than wait. The window closes on time (the machine's cap is an hour),
+on `--done`, or when the session ends, and with it every root shell from the
+agents' logins. Say in the reason what root is for: it is what the person
+signs, and what the machine's log keeps.
+
## Working beside other sessions
Sessions share the workspace, and the hub carries notes between them; no agent sits
diff --git a/src/admin.rs b/src/admin.rs
new file mode 100644
index 0000000..817d764
--- /dev/null
+++ b/src/admin.rs
@@ -0,0 +1,848 @@
+//! 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"));
+ }
+}
diff --git a/src/collab.rs b/src/collab.rs
index 509d28b..625ab80 100644
--- a/src/collab.rs
+++ b/src/collab.rs
@@ -192,7 +192,7 @@ fn say_about(from: &str, to: &str, text: &str, kind: &str, about: Value) -> Resu
/// news but work left to it: s857 sat idle 19 hours on one, until the person
/// asked.
pub(crate) fn wakes(from: &str, kind: &str) -> bool {
- from != "hub" || matches!(kind, "decision" | "stalled")
+ from != "hub" || matches!(kind, "decision" | "stalled" | "admin")
}
/// A note into `to`'s mailbox, waking nobody: its id.
@@ -703,6 +703,8 @@ pub fn session_ended(owner: &str, reason: Option<&str>) {
events::emit("error", json!({"actor": "hub", "what": format!("dropping {owner}'s notes: {e:#}")}));
}
forget_work(&owner);
+ // Root it was granted goes with it.
+ crate::admin::session_ended(&owner);
}
/// A session's work, gone: it ended. What it was told about overlaps stays for
diff --git a/src/hub.rs b/src/hub.rs
index c0dd5d2..6171ed7 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -632,6 +632,12 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
("GET", "reservations") => return Ok((200, crate::collab::reservations())),
("GET", "todos") => return Ok((200, crate::collab::todos())),
("GET", "decisions") => return Ok((200, crate::collab::decisions())),
+ // Admin windows (admin.rs): how they stand, and the grant the page is to sign for one.
+ ("GET", "admin") => return Ok((200, crate::admin::status())),
+ ("GET", "admin/sign") => return Ok(match crate::admin::to_sign(&q("id").unwrap_or_default()) {
+ Ok(v) => (200, v),
+ Err(e) => (409, json!({"error": format!("{e:#}")})),
+ }),
// The person's decision load, limits, rules and the autopilot's answers for them (focus.rs):
// the logged-in person's, else the one who decided last. The page says its clock's offset.
("GET", "focus") => {
@@ -1274,6 +1280,48 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
let id = crate::collab::decision_add(&owner, &question, &options, &with)?;
(200, json!({"id": id}))
}
+ // Root for a while (admin.rs). A session asks with its key; only the person, logged in on
+ // the page as an admin, answers — and root believes only their passkey's signature.
+ ("POST", "admin/request") => {
+ if p.account.is_some() {
+ return Ok((403, json!({"error": "a session asks for root, with its key"})));
+ }
+ let minutes = body["minutes"].as_u64().unwrap_or(30) as u32;
+ match crate::admin::request(&owner, &s("reason").unwrap_or_default(), minutes) {
+ Ok(id) => (200, json!({"id": id})),
+ Err(e) => (409, json!({"error": format!("{e:#}")})),
+ }
+ }
+ ("POST", "admin/grant" | "admin/decline") => {
+ if !(p.account.is_some() && crate::accounts::at_least(&p.role, "admin")) {
+ return Ok((403, json!({"error": "root is granted by a person with the admin role, on the page"})));
+ }
+ let id = s("id").unwrap_or_default();
+ let r = if path == "admin/decline" {
+ crate::admin::decline(&id, &by)
+ } else {
+ serde_json::from_value::<crate::admin::Assertion>(body["assertion"].clone())
+ .map_err(|e| anyhow::anyhow!("the passkey's answer: {e}"))
+ .and_then(|a| crate::admin::grant(&id, body["issued_at"].as_i64().unwrap_or(0), a, &by))
+ };
+ match r {
+ Ok(v) => (200, v),
+ Err(e) => (409, json!({"error": format!("{e:#}")})),
+ }
+ }
+ ("POST", "admin/close") => {
+ // The session that has the window, or the person; closing takes nothing from anyone else.
+ let st = crate::admin::read_status();
+ if st["open"].is_null() {
+ return Ok(ok);
+ }
+ let person = p.account.is_some() && crate::accounts::at_least(&p.role, "admin");
+ if !person && st["open"]["session"].as_str() != Some(owner.as_str()) {
+ return Ok((403, json!({"error": "the window is another session's; the person can close it on the page"})));
+ }
+ crate::admin::close(&by, if person { "closed on the page" } else { "the session was done" })?;
+ ok
+ }
("POST", "decisions/answer") => {
let d = crate::collab::decision_answer(&s("id").unwrap_or_default(), &s("choice").unwrap_or_default(),
&format!("{caller}:{owner}"), s("note").as_deref())?;
@@ -1508,6 +1556,8 @@ fn watch_heartbeats() {
if tick % 20 == 15 {
crate::collab::expire_notes();
}
+ // Every time, root's answers on admin windows, told to the sessions that asked (admin.rs).
+ crate::admin::tick();
// Every time, what has landed and waits for a deploy (ship.rs), and the sessions to finish once theirs is live.
crate::ship::tick();
crate::sessions::finish_sweep();
diff --git a/src/hubsetup.rs b/src/hubsetup.rs
index be61e55..a277503 100644
--- a/src/hubsetup.rs
+++ b/src/hubsetup.rs
@@ -44,6 +44,9 @@ const UNITS: &[(&str, &str)] = &[
("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)]
@@ -190,7 +193,7 @@ pub fn setup(mut a: Args) -> Result<i32> {
"--comment", "midas hub", USER]))?;
println!("created user {USER} ({HOME})");
}
- for d in ["", "/state", "/mirrors", "/lfs", "/tokens", "/.ssh", "/deploy", "/deploy/queue", "/deploy/work", "/deploy/ready"] {
+ 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 }))?;
@@ -266,8 +269,11 @@ pub fn setup(mut a: Args) -> Result<i32> {
units_changed |= write_if_changed(&format!("/etc/systemd/system/{name}"), body, 0o644)?;
}
run(Command::new("systemctl").arg("daemon-reload"))?;
- run(Command::new("systemctl").args(["enable", "midas-hub.service", "midas-warm.timer", "midas-deploy.path", "midas-publish.path", "midas-self-update.path"]))?;
- run(Command::new("systemctl").args(["start", "midas-warm.timer", "midas-deploy.path", "midas-publish.path", "midas-self-update.path"]))?;
+ // 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;
diff --git a/src/main.rs b/src/main.rs
index 9e9c2c9..55c1605 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,6 +5,7 @@
//! node inside each build machine's container.
mod accounts;
+mod admin;
mod agents;
mod acp;
mod ask;
@@ -258,6 +259,19 @@ enum Cmd {
/// Open decisions, and those made this week (`decide` with no answer).
#[command(hide = true)]
Decisions,
+ /// Root on the hub's machine for a while, if the person allows it with
+ /// their passkey: `midas admin "restart caddy" --for 30m`. A note says when
+ /// it is open; `--done` closes it. Without words, how it stands.
+ Admin {
+ #[arg(trailing_var_arg = true)]
+ reason: Vec<String>,
+ /// How long: 30m (the default), 1h; the machine caps it.
+ #[arg(long = "for", default_value = "30m")]
+ minutes: String,
+ /// Through with it: close the window now.
+ #[arg(long, conflicts_with = "reason")]
+ done: bool,
+ },
/// Agent sessions midas runs, which the page starts, follows and steers:
/// `run` (in the agent container) runs them; `list`, `start "<prompt>"`.
#[command(subcommand)]
@@ -1040,6 +1054,30 @@ enum HubCmd {
#[arg(long)]
release_key: Option<String>,
},
+ /// Root's side of admin windows (admin.rs): the user the agents are, the
+ /// page their passkey signs on, the longest window (as root).
+ AdminSetup {
+ #[arg(long)]
+ user: String,
+ /// The page's host: the passkeys' relying party.
+ #[arg(long)]
+ rp_id: String,
+ /// The page's origin (repeat); `https://<rp-id>` when none.
+ #[arg(long = "origin")]
+ origins: Vec<String>,
+ #[arg(long)]
+ max_minutes: Option<u32>,
+ },
+ /// A passkey that may grant windows: the line the page shows after making
+ /// one; `--remove <id>` takes one away (as root).
+ AdminEnroll {
+ line: Vec<String>,
+ #[arg(long, conflicts_with = "line")]
+ remove: Option<String>,
+ },
+ /// Close an admin window whose time is up, and open one the person signed
+ /// (midas-admin.service runs it, as root).
+ AdminApply,
/// Install the build a deploy of midas published, as hub.conf's self_update
/// says (the midas-self-update service runs it, as root).
SelfUpdate {
@@ -1439,6 +1477,33 @@ fn setup_link(v: &Value) -> String {
format!("{}/setup/{}", base.trim_end_matches('/'), v["token"].as_str().unwrap_or("?"))
}
+/// `midas admin`: ask for a window, close it, or say how it stands (admin.rs).
+fn admin_cmd(owner: &str, reason: &str, minutes: &str, done: bool) -> anyhow::Result<i32> {
+ if done {
+ client::post("/v1/admin/close", &json!({"owner": owner}))?;
+ eprintln!("closing: root goes within a minute (sudo stops working, root shells from your logins end)");
+ return Ok(0);
+ }
+ if reason.trim().is_empty() {
+ let s = client::get("/v1/admin")?;
+ match s["window"]["id"].as_str() {
+ Some(id) => println!("open: {id} for {}, until {} — {}", s["window"]["session"].as_str().unwrap_or("?"),
+ s["window"]["until"], s["window"]["reason"].as_str().unwrap_or("")),
+ None => println!("no window open"),
+ }
+ for r in s["requests"].as_array().into_iter().flatten().filter(|r| r["session"] == owner) {
+ println!("{}: {} — {}", r["id"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"), r["reason"].as_str().unwrap_or(""));
+ }
+ return Ok(0);
+ }
+ let v = client::post("/v1/admin/request", &json!({"owner": owner, "reason": reason, "minutes": admin::minutes_of(minutes)?}))?;
+ let id = v["id"].as_str().unwrap_or("?");
+ eprintln!("asked as {id}: the person's phone shows it, and their passkey opens it. A note tells you when root works \
+ (or that they declined); end your turn rather than wait, and do what does not need root meanwhile.");
+ println!("{id}");
+ Ok(0)
+}
+
/// `decide` with no answer: the open decisions, and those made this week.
fn decisions() -> anyhow::Result<i32> {
for d in client::get("/v1/decisions")?.as_array().into_iter().flatten() {
@@ -1521,6 +1586,7 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
println!("{id}");
Ok(0)
}
+ Cmd::Admin { reason, minutes, done } => admin_cmd(&who(), &reason.join(" "), &minutes, done),
Cmd::Decide { id: None, .. } | Cmd::Decisions => decisions(),
Cmd::Decide { id: Some(id), choice, note } => {
if choice.is_empty() {
@@ -1660,6 +1726,9 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
Cmd::Flush { node } => flush::flush(&node),
Cmd::Mcp => mcp::serve(),
Cmd::Hub(HubCmd::Serve { listen }) => hub::serve(listen.as_deref()),
+ Cmd::Hub(HubCmd::AdminSetup { user, rp_id, origins, max_minutes }) => admin::setup(&user, &rp_id, &origins, max_minutes),
+ Cmd::Hub(HubCmd::AdminEnroll { line, remove }) => admin::enroll(Some(line.join(" ").as_str()).filter(|l| !l.is_empty()), remove.as_deref()),
+ Cmd::Hub(HubCmd::AdminApply) => admin::apply(),
Cmd::Hub(HubCmd::SelfUpdate { next }) => release::self_update(next.as_deref().unwrap_or(std::path::Path::new(release::NEXT))),
Cmd::Sign(SignCmd::Keygen { key }) => release::keygen(&key.map(std::path::PathBuf::from).unwrap_or_else(release::default_key)),
Cmd::Sign(SignCmd::Public { key }) => release::public(&key.map(std::path::PathBuf::from).unwrap_or_else(release::default_key)),
diff --git a/src/push.rs b/src/push.rs
index a33b3ae..7e50b9d 100644
--- a/src/push.rs
+++ b/src/push.rs
@@ -297,6 +297,16 @@ pub fn needs() -> Vec<Value> {
}
out.extend(news(&sessions));
let names = crate::collab::names();
+ // A session asking for root (admin.rs) waits on the person's passkey for its work.
+ for r in crate::admin::status()["requests"].as_array().into_iter().flatten().filter(|r| r["state"] == "asked") {
+ let by = r["session"].as_str().unwrap_or("a session");
+ let who = names[by]["label"].as_str().unwrap_or(by);
+ out.push(json!({
+ "key": format!("admin:{}", r["id"].as_str().unwrap_or("")),
+ "title": format!("{} asks for root", crate::util::short(who, 60)),
+ "body": format!("{} min: {}", r["minutes"], r["reason"].as_str().unwrap_or("")), "url": "/", "urgent": true,
+ }));
+ }
for d in crate::collab::decisions().as_array().into_iter().flatten().filter(|d| d["answer"].is_null()) {
let by = d["by"].as_str().unwrap_or("a session");
let who = names[by.strip_prefix("gate-").unwrap_or(by)]["label"].as_str().unwrap_or(by);
diff --git a/units/midas-admin.path b/units/midas-admin.path
new file mode 100644
index 0000000..8747642
--- /dev/null
+++ b/units/midas-admin.path
@@ -0,0 +1,11 @@
+[Unit]
+Description=midas: take a grant or a close the hub spooled for an admin window
+
+# The hub writes the person's signed grant, or a close, into its own directory;
+# root reads it from there and checks it (src/admin.rs).
+[Path]
+PathExistsGlob=/srv/midas/admin/*.json
+Unit=midas-admin.service
+
+[Install]
+WantedBy=multi-user.target
diff --git a/units/midas-admin.service b/units/midas-admin.service
new file mode 100644
index 0000000..04b6547
--- /dev/null
+++ b/units/midas-admin.service
@@ -0,0 +1,16 @@
+# Root, because it writes /etc/sudoers.d/midas-admin: opens an admin window
+# only for a grant signed by a passkey in /etc/midas/admin.json, which the hub
+# never holds, and closes one whose time is up (src/admin.rs). Nothing set up,
+# it does nothing.
+[Unit]
+Description=midas: open or close the agents' admin window
+
+[Service]
+Type=oneshot
+ExecStart=/usr/local/bin/midas hub admin-apply
+TimeoutStartSec=1min
+PrivateTmp=yes
+ProtectHome=read-only
+ProtectKernelTunables=yes
+ProtectKernelModules=yes
+ProtectControlGroups=yes
diff --git a/units/midas-admin.timer b/units/midas-admin.timer
new file mode 100644
index 0000000..fd18838
--- /dev/null
+++ b/units/midas-admin.timer
@@ -0,0 +1,12 @@
+[Unit]
+Description=midas: close an admin window whose time is up
+
+# Every minute, and soon after boot: a window left open across a restart
+# closes as soon as the machine is up again.
+[Timer]
+OnBootSec=20s
+OnUnitActiveSec=1min
+AccuracySec=5s
+
+[Install]
+WantedBy=timers.target
diff --git a/web/src/app.css b/web/src/app.css
index c4ac995..c35c5bf 100644
--- a/web/src/app.css
+++ b/web/src/app.css
@@ -3004,6 +3004,16 @@ code {
flex: 1 1 12rem;
}
+/* The command that installs an admin passkey: long, copied whole, so it wraps anywhere. */
+.admin__cmd {
+ white-space: pre-wrap;
+ word-break: break-all;
+ font-size: var(--m-font-size-sm);
+ padding: var(--m-space-2);
+ border: 1px solid var(--m-border);
+ border-radius: var(--m-radius-sm, 4px);
+}
+
/* The page's header, one row: the title, then the open session's state, its ⓘ and full screen. */
.frame__title {
flex: 1 1 auto;
diff --git a/web/src/components/admin.tsx b/web/src/components/admin.tsx
new file mode 100644
index 0000000..821ab9f
--- /dev/null
+++ b/web/src/components/admin.tsx
@@ -0,0 +1,135 @@
+import m, {MithrilComponent} from '@garage44/mithril'
+import {Badge, Button, Card, FieldText} from '@garage44/mithril/components'
+
+import {who} from '@/components/who'
+import {act} from '@/lib/actions'
+import {api} from '@/lib/api'
+import {age, when} from '@/lib/format'
+import {makeKey, passkeyHere, signGrant} from '@/lib/passkey'
+import {bind, local} from '@/lib/reactive'
+import {$s} from '@/lib/store'
+import type {AdminRequest} from '@/lib/types'
+
+/**
+ * Admin windows (src/admin.rs): a session asks for root on the hub's machine,
+ * and the person's passkey signs the grant — who, for how long, why — which
+ * root checks before sudo works. The hub only carries the signature.
+ */
+
+const rpId = () => $s.admin?.setup?.rp_id ?? location.hostname
+
+async function allow(r: AdminRequest) {
+ // Hub's time in the grant: root checks it against its own clock.
+ const s = await api.adminToSign(r.id)
+ const assertion = await signGrant(s.challenge, s.rp_id, s.keys)
+ await api.adminGrant(r.id, s.grant.issued_at, assertion)
+}
+
+/** One request, under Needs you: what for, how long, and Allow (the passkey) or No. */
+export function adminRequestRow(r: AdminRequest): m.Children {
+ const blocked = $s.role !== 'admin' ? 'an admin grants root' : passkeyHere(rpId())
+ return (
+ <div class="decision" id={`admin-${r.id}`}>
+ <div>
+ <Badge tone="danger">root</Badge> <b>{r.reason}</b>
+ </div>
+ <div class="hint">
+ {who(r.session, {max: 40})} asks for root on the hub's machine for {r.minutes} min · {age(r.at)} ago. Root then can change anything
+ there; the machine closes it on time, or when the session ends.
+ </div>
+ <div class="decision__choices">
+ <Button variant="primary" disabled={!!blocked} onclick={() => act(`root for ${r.minutes} min allowed`, () => allow(r))}>
+ Allow with passkey
+ </Button>
+ <Button variant="secondary" disabled={$s.role !== 'admin'} onclick={() => act(`${r.id} declined`, () => api.adminDecline(r.id))}>
+ No
+ </Button>
+ </div>
+ {blocked ? <p class="hint">{blocked}</p> : null}
+ </div>
+ )
+}
+
+/** The window while it is open: whose, until when, and Close. */
+export function adminOpenRow(): m.Children {
+ const w = $s.admin?.window
+ if (!w) return null
+ return (
+ <div class="needs__row needs__row--admin">
+ <span>
+ <Badge tone="danger">root open</Badge> {who(w.session, {max: 40})} until {when(w.until)}: {w.reason}
+ </span>
+ <Button size="sm" variant="secondary" disabled={$s.role !== 'admin'} onclick={() => act('closing root', () => api.adminClose())}>
+ Close now
+ </Button>
+ </div>
+ )
+}
+
+/** Settings ▸ Admin: the machine's setup, the passkeys that may grant, making one. */
+export class AdminPasskey extends MithrilComponent {
+ s = local({label: '', line: '', error: ''})
+
+ async make() {
+ const setup = $s.admin?.setup
+ if (!setup) return
+ try {
+ this.s.line = await makeKey(setup.rp_id, this.s.label, setup.keys.map((k) => k.id))
+ this.s.error = ''
+ } catch (e) {
+ this.s.error = (e as Error).message
+ }
+ }
+
+ view() {
+ const setup = $s.admin?.setup
+ if (!setup)
+ return (
+ <Card title="Admin passkey" subtitle="not set up on the hub's machine">
+ <p class="hint">
+ As root there, once: <code>sudo midas hub admin-setup --user agent --rp-id {location.hostname}</code>. The agents then log in as that user, which
+ is root only in a window you allow.
+ </p>
+ </Card>
+ )
+ const blocked = passkeyHere(setup.rp_id)
+ const cmd = this.s.line ? `sudo midas hub admin-enroll '${this.s.line}'` : ''
+ return (
+ <Card
+ title="Admin passkey"
+ subtitle={`sessions log in as ${setup.user}; root for up to ${setup.max_minutes} min, only when your passkey signs it`}
+ footer={[
+ <Button variant="primary" disabled={!!blocked} onclick={() => void this.make()}>
+ Make a passkey on this device
+ </Button>,
+ ]}
+ >
+ {setup.keys.length ? (
+ <ul class="pairs">
+ {setup.keys.map((k) => (
+ <li>
+ <b>{k.label || 'passkey'}</b> <span class="hint">· added {when(k.added)} · {k.id.slice(0, 10)}…</span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p class="hint">No passkey yet: until there is one, no session can be given root.</p>
+ )}
+ <FieldText model={bind(this.s, 'label')} placeholder="what this device is (phone, laptop)" />
+ {blocked ? <p class="hint">{blocked}</p> : null}
+ {this.s.error ? <p class="hint error">{this.s.error}</p> : null}
+ {cmd ? (
+ <div>
+ <p class="hint">
+ Made. The machine trusts it only once you install it yourself, as root, from your own login (not a session's): run this there.
+ </p>
+ <pre class="admin__cmd">{cmd}</pre>
+ <Button size="sm" variant="ghost" onclick={() => void navigator.clipboard.writeText(cmd)}>
+ Copy
+ </Button>
+ </div>
+ ) : null}
+ </Card>
+ )
+ }
+}
diff --git a/web/src/components/home.tsx b/web/src/components/home.tsx
index 1fc2148..01d3314 100644
--- a/web/src/components/home.tsx
+++ b/web/src/components/home.tsx
@@ -413,7 +413,7 @@ export class Home extends MithrilComponent {
{projectFilter((repo) => all.filter((c) => c.stage !== 'landed' && repoOf(c, byOwner.get(c.session)).includes(repo)).length)}
{!live.loaded ? (
<p class="hint">Connecting to the hub…</p>
- ) : waiting ? (
+ ) : waiting || $s.admin?.window ? (
NeedsYou()
) : (
<div class="home__calm">
diff --git a/web/src/components/needs.tsx b/web/src/components/needs.tsx
index 51ecb0a..192ddfb 100644
--- a/web/src/components/needs.tsx
+++ b/web/src/components/needs.tsx
@@ -1,6 +1,7 @@
import m from '@garage44/mithril'
import {Button} from '@garage44/mithril/components'
+import {adminOpenRow, adminRequestRow} from '@/components/admin'
import {openDecision} from '@/components/decisions'
import {icon} from '@/components/icons'
import {age, now, span} from '@/lib/format'
@@ -11,11 +12,12 @@ import {go} from '@/lib/route'
import {hosted} from '@/lib/stream'
/** Everything that waits for the person now: the tab's title and the nav count this. */
-export const waitingForYou = (): Need[] => needs($s.decisions, hosted(), now())
+export const waitingForYou = (): Need[] => needs($s.decisions, hosted(), now(), $s.admin?.requests ?? [])
const open = (id: string) => go(`sessions/${id}`)
function row(n: Need): m.Children {
+ if (n.kind === 'admin') return adminRequestRow(n.request)
if (n.kind === 'decision') return openDecision(n.decision)
const s = n.session
if (n.kind === 'awaits')
@@ -55,12 +57,15 @@ function row(n: Need): m.Children {
*/
export function NeedsYou(): m.Children {
const list = waitingForYou()
- if (!list.length) return null
+ // Root open on the hub's machine is shown while it lasts, though it asks nothing of them.
+ const open = adminOpenRow()
+ if (!list.length && !open) return null
return (
<section class="needs" aria-label="Needs you">
<header class="needs__head">
<b>Needs you</b> <span class="board__count">{list.length}</span>
</header>
+ {open}
{list.map(row)}
</section>
)
diff --git a/web/src/components/settings.tsx b/web/src/components/settings.tsx
index 7bc9b39..7348230 100644
--- a/web/src/components/settings.tsx
+++ b/web/src/components/settings.tsx
@@ -2,6 +2,7 @@ import m, {MithrilComponent} from '@garage44/mithril'
import {Button, Card, FieldSelect, FieldSwitch, FieldText} from '@garage44/mithril/components'
import {Accounts} from '@/components/accounts'
+import {AdminPasskey} from '@/components/admin'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
import type {AgentEntry, BotOverview, Device, DeviceCode,DiscussOverview, DiscussSettings} from '@/lib/api'
@@ -18,6 +19,7 @@ const choices = (offered: string[], current: string) => [...new Set([current, ..
const SECTIONS = [
{id: 'device', title: 'This device', lead: 'This browser on this device, for whoever is logged in here.'},
{id: 'people', title: 'People', lead: 'Who logs in to this page, and what each may do.'},
+ {id: 'admin', title: 'Admin', lead: "Root on the hub's machine: only in a window you allow with your passkey."},
{id: 'voice', title: 'Voice', lead: 'Talking sessions over by voice: Discuss, in the header.'},
{id: 'agents', title: 'Agents', lead: 'What a session runs: Claude Code, or another agent you add here.'},
{id: 'bots', title: 'Bots', lead: 'Cartopolis accounts an AI agent speaks for.'},
@@ -226,6 +228,7 @@ export class Settings extends MithrilComponent {
{jump()}
{section('device', device())}
{section('people', <Accounts />)}
+ {section('admin', <AdminPasskey />)}
{section(
'voice',
<Card
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 3ca76b3..b30c349 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -1,4 +1,5 @@
-import type {Build, Decision, Deploys, FilesReport, WorkspaceEvent, WorkspaceState, Landing, PoolSample, Reservations, Session, SessionName, Take, Tally, Todo} from '@/lib/types'
+import type {Assertion} from '@/lib/passkey'
+import type {AdminState, Build, Decision, Deploys, FilesReport, WorkspaceEvent, WorkspaceState, Landing, PoolSample, Reservations, Session, SessionName, Take, Tally, Todo} from '@/lib/types'
import type {LogItem, SearchHit} from '@/lib/stream'
import type {HubNote} from '@/lib/memory'
@@ -775,4 +776,10 @@ export const api = {
/** Put a card away (or back): any session's, on the board. */
archiveCard: (session: string, on: boolean) => post('/v1/archive', {session, on}),
decide: (id: string, choice: string, note?: string) => post('/v1/decisions/answer', {id, choice, note}),
+ /** Admin windows (admin.rs): how they stand; the grant to sign for one; the signed Allow; No; closing the open one. */
+ admin: () => get<AdminState>('/v1/admin'),
+ adminToSign: (id: string) => get<{grant: {issued_at: number}; challenge: string; rp_id: string; keys: string[]}>(`/v1/admin/sign?id=${encodeURIComponent(id)}`),
+ adminGrant: (id: string, issued_at: number, assertion: Assertion) => post('/v1/admin/grant', {id, issued_at, assertion}),
+ adminDecline: (id: string) => post('/v1/admin/decline', {id}),
+ adminClose: () => post('/v1/admin/close', {}),
}
diff --git a/web/src/lib/needs.test.ts b/web/src/lib/needs.test.ts
index 8f17af6..6fa68e9 100644
--- a/web/src/lib/needs.test.ts
+++ b/web/src/lib/needs.test.ts
@@ -2,7 +2,7 @@ import {expect, test} from 'bun:test'
import {needs} from '@/lib/needs'
import type {Hosted} from '@/lib/stream'
-import type {Decision} from '@/lib/types'
+import type {AdminRequest, Decision} from '@/lib/types'
const hosted = (id: string, status: Hosted['status'], updated: number, archived = false): Hosted =>
({kind: 'hosted', id, title: id, status, branch: '', owner: `session-${id}`, by: '', created: updated, updated, base: 'main', archived}) as Hosted
@@ -15,7 +15,7 @@ test('open questions first, oldest first; then permissions; then sessions stuck
[hosted('s1', 'needs_permission', 9000), hosted('s2', 'starting', now - 400), hosted('s3', 'starting', now - 60), hosted('s4', 'working', 0)],
now,
)
- expect(got.map((n) => (n.kind === 'decision' ? n.decision.id : n.session.id))).toEqual(['d1', 'd2', 's1', 's2'])
+ expect(got.map((n) => (n.kind === 'decision' ? n.decision.id : n.kind === 'admin' ? n.request.id : n.session.id))).toEqual(['d1', 'd2', 's1', 's2'])
expect(got[3]).toMatchObject({kind: 'stuck', for_s: 400})
})
@@ -34,9 +34,15 @@ test('what only the person can do comes after permissions, oldest first; put off
],
now,
)
- expect(got.map((n) => (n.kind === 'decision' ? '' : `${n.kind}:${n.session.id}`))).toEqual(['permission:s3', 'awaits:s2', 'awaits:s1'])
+ expect(got.map((n) => (n.kind === 'decision' || n.kind === 'admin' ? '' : `${n.kind}:${n.session.id}`))).toEqual(['permission:s3', 'awaits:s2', 'awaits:s1'])
})
test('an archived session asks nothing of the person', () => {
expect(needs([], [hosted('s1', 'needs_permission', 0, true)], 1)).toEqual([])
})
+
+test('a session asking for root comes first; answered, it asks nothing', () => {
+ const req = (id: string, state: string): AdminRequest => ({id, session: 'session-s9', reason: 'restart caddy', minutes: 30, at: 1, state})
+ const got = needs([decision('d1', 100)], [], 1000, [req('a2', 'asked'), req('a1', 'open'), req('a0', 'declined')])
+ expect(got.map((n) => (n.kind === 'admin' ? n.request.id : n.kind === 'decision' ? n.decision.id : ''))).toEqual(['a2', 'd1'])
+})
diff --git a/web/src/lib/needs.ts b/web/src/lib/needs.ts
index e8d6b4a..785c3ea 100644
--- a/web/src/lib/needs.ts
+++ b/web/src/lib/needs.ts
@@ -1,23 +1,25 @@
import {asksPerson, awaitsPerson} from '@/lib/status'
import type {Hosted} from '@/lib/stream'
-import type {Decision} from '@/lib/types'
+import type {AdminRequest, Decision} from '@/lib/types'
/** A session still starting after this long is stuck: something on its machine went wrong. */
export const STUCK_AFTER_S = 5 * 60
/** One thing that waits for the person: a question to answer, a permission to give, a session that will not start. */
export type Need =
+ | {kind: 'admin'; request: AdminRequest}
| {kind: 'decision'; decision: Decision}
| {kind: 'permission'; session: Hosted}
| {kind: 'awaits'; session: Hosted}
| {kind: 'stuck'; session: Hosted; for_s: number}
-/** What waits for the person: the oldest question first, then permissions, then what only they can do (the oldest first), then stuck sessions. */
-export function needs(decisions: Decision[], sessions: readonly Hosted[], now: number): Need[] {
- const out: Need[] = decisions
- .filter((d) => d.answer == null)
- .sort((a, b) => a.at - b.at)
- .map((decision) => ({kind: 'decision', decision}))
+/**
+ * What waits for the person: a session asking for root first (its work stops on it), then the
+ * oldest question, then permissions, then what only they can do (the oldest first), then stuck sessions.
+ */
+export function needs(decisions: Decision[], sessions: readonly Hosted[], now: number, admin: readonly AdminRequest[] = []): Need[] {
+ const out: Need[] = admin.filter((r) => r.state === 'asked').map((request) => ({kind: 'admin', request}))
+ for (const decision of decisions.filter((d) => d.answer == null).sort((a, b) => a.at - b.at)) out.push({kind: 'decision', decision})
const live = sessions.filter((s) => !s.archived)
for (const s of live) if (asksPerson(s)) out.push({kind: 'permission', session: s})
const busy = (s: Hosted) => s.status === 'working' || s.status === 'starting' || s.status === 'queued'
diff --git a/web/src/lib/passkey.ts b/web/src/lib/passkey.ts
new file mode 100644
index 0000000..80bcdf6
--- /dev/null
+++ b/web/src/lib/passkey.ts
@@ -0,0 +1,79 @@
+/**
+ * The admin passkey (src/admin.rs): made once on the person's phone, its public
+ * half installed by them as root; afterwards each admin window is a grant this
+ * passkey signs. The hub only carries the signature; root checks it.
+ */
+
+const KEY_LABEL = 'midas-admin-key-v1'
+
+export const b64url = (b: ArrayBuffer | Uint8Array): string => {
+ const bytes = b instanceof Uint8Array ? b : new Uint8Array(b)
+ let s = ''
+ for (const x of bytes) s += String.fromCharCode(x)
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
+}
+
+export const fromB64url = (s: string): Uint8Array<ArrayBuffer> => {
+ const t = atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4))
+ const out = new Uint8Array(new ArrayBuffer(t.length))
+ for (let i = 0; i < t.length; i++) out[i] = t.charCodeAt(i)
+ return out
+}
+
+/** Whether this browser can use a passkey here: WebAuthn, on the page's own host. */
+export function passkeyHere(rpId: string): string | null {
+ if (!window.PublicKeyCredential || !navigator.credentials) return 'this browser has no passkeys'
+ if (location.hostname !== rpId && !location.hostname.endsWith(`.${rpId}`)) return `open the page on https://${rpId} for its passkey`
+ return null
+}
+
+/** Make the passkey: its line, for `sudo midas hub admin-enroll '<line>'`. */
+export async function makeKey(rpId: string, label: string, existing: string[]): Promise<string> {
+ const cred = (await navigator.credentials.create({
+ publicKey: {
+ rp: {id: rpId, name: 'midas admin'},
+ user: {id: crypto.getRandomValues(new Uint8Array(16)), name: 'midas admin', displayName: 'midas admin'},
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
+ // ES256 only: what root checks (P-256).
+ pubKeyCredParams: [{type: 'public-key', alg: -7}],
+ authenticatorSelection: {userVerification: 'required', residentKey: 'preferred'},
+ excludeCredentials: existing.map((id) => ({type: 'public-key' as const, id: fromB64url(id)})),
+ attestation: 'none',
+ },
+ })) as PublicKeyCredential | null
+ if (!cred) throw new Error('no passkey was made')
+ const r = cred.response as AuthenticatorAttestationResponse
+ if (r.getPublicKeyAlgorithm() !== -7) throw new Error('this passkey is not P-256 (ES256), which the machine checks')
+ const spki = r.getPublicKey()
+ if (!spki) throw new Error('the browser did not give the public key')
+ const name = label.trim().replace(/\s+/g, ' ') || 'phone'
+ return `${KEY_LABEL} ${b64url(cred.rawId)} ${b64url(spki)} ${name}`
+}
+
+export interface Assertion {
+ credential_id: string
+ authenticator_data: string
+ client_data_json: string
+ signature: string
+}
+
+/** Sign a grant's challenge with the passkey: the fingerprint or PIN is asked for. */
+export async function signGrant(challenge: string, rpId: string, keys: string[]): Promise<Assertion> {
+ const cred = (await navigator.credentials.get({
+ publicKey: {
+ rpId,
+ challenge: fromB64url(challenge),
+ allowCredentials: keys.map((id) => ({type: 'public-key' as const, id: fromB64url(id)})),
+ userVerification: 'required',
+ timeout: 120000,
+ },
+ })) as PublicKeyCredential | null
+ if (!cred) throw new Error('nothing was signed')
+ const r = cred.response as AuthenticatorAssertionResponse
+ return {
+ credential_id: b64url(cred.rawId),
+ authenticator_data: b64url(r.authenticatorData),
+ client_data_json: b64url(r.clientDataJSON),
+ signature: b64url(r.signature),
+ }
+}
diff --git a/web/src/lib/store.ts b/web/src/lib/store.ts
index 460ceff..0e750cd 100644
--- a/web/src/lib/store.ts
+++ b/web/src/lib/store.ts
@@ -4,7 +4,7 @@ import type {Runners} from '@/lib/api'
/** The page's destinations: Home, Sessions and Workspace, and what More holds. */
export type Page = 'home' | 'sessions' | 'workspace' | 'activity' | 'memory' | 'settings' | 'more' | 'design' | 'autopilot' | 'focus' | 'research'
-import type {Build, Decision, Deploys, WorkspaceEvent, WorkspaceState, Landing, PoolSample, Reservations, Session, SessionName, Take, Tally, Todo} from '@/lib/types'
+import type {AdminState, Build, Decision, Deploys, WorkspaceEvent, WorkspaceState, Landing, PoolSample, Reservations, Session, SessionName, Take, Tally, Todo} from '@/lib/types'
/**
* The page's one store. The live part (`workspace`, `deploys`) is polled while the
@@ -21,6 +21,8 @@ export const $s = local({
reservations: {} as Reservations,
todos: [] as Todo[],
decisions: [] as Decision[],
+ /** Admin windows (`/v1/admin`): null from a hub without them. */
+ admin: null as AdminState | null,
error: '',
/** Seconds since the last good poll, for "updated 4s ago". */
polledAt: 0,
@@ -58,7 +60,7 @@ export async function checkCaller() {
export async function poll() {
try {
- const [workspace, deploys, health, names, reservations, todos, decisions] = await Promise.all([
+ const [workspace, deploys, health, names, reservations, todos, decisions, admin] = await Promise.all([
api.state(),
api.deploys(),
api.health(),
@@ -67,6 +69,7 @@ export async function poll() {
api.todos(),
// A hub from before decisions has none to show.
api.decisions().catch(() => [] as Decision[]),
+ api.admin().catch(() => null),
])
// Only what changed: each answer is a new object, and setting it redrew every view
// that reads it (the session page reads the decisions) every ten seconds for nothing.
@@ -77,6 +80,7 @@ export async function poll() {
if (changed($s.reservations, reservations)) $s.reservations = reservations
if (changed($s.todos, todos)) $s.todos = todos
if (changed($s.decisions, decisions)) $s.decisions = decisions
+ if (changed($s.admin, admin)) $s.admin = admin
$s.hubVersion = health.version
$s.hubRecipe = health.recipe ?? ''
$s.error = ''
diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts
index 2de6507..902abc8 100644
--- a/web/src/lib/types.ts
+++ b/web/src/lib/types.ts
@@ -226,6 +226,26 @@ export interface Decision {
note?: string | null
}
+/** A session asking for root on the hub's machine (`/v1/admin`, admin.rs). */
+export interface AdminRequest {
+ id: string
+ session: string
+ reason: string
+ minutes: number
+ at: number
+ /** asked, signed (root is checking), open, refused, declined, closed, expired, replaced, dropped. */
+ state: string
+ why?: string
+ until?: number
+}
+
+/** Admin windows as they stand: the machine's setup (null before `admin-setup`), requests, the open one. */
+export interface AdminState {
+ setup: {user: string; rp_id: string; max_minutes: number; keys: {id: string; label: string; added: number}[]} | null
+ requests: AdminRequest[]
+ window: {id: string; session: string; reason: string; opened: number; until: number} | null
+}
+
/** Work left for the next session on a machine (`/v1/todos`). */
export interface Todo {
id: string