git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-21T19:38:58Z
feat(hub): a published midas runs as root only as hub.conf's self_update allows
A deploy of midas itself published the binary into
/usr/local/lib/midas/next, and midas-self-update ran that binary's
`hub setup` as root. The hub's user builds and publishes, and the hub
answers untrusted nodes, so whoever was that user was root on the hub
the next time midas deployed — what DESIGN.md's decision 15 ("root
publishes bytes only to the places that file names") did not cover
when the place was root's own executable. Found by the review before
the code went public.
The service now runs `midas hub self-update` with the installed midas,
which decides from `self_update` in hub.conf: `hub` runs the published
build as before; `signed` runs it only with a good signature by the
release key whose public half root holds in /etc/midas/release.pub;
`off` leaves it published for somebody to install by hand. The key is
the owner's, made and used on their own machine (`midas sign keygen`,
`midas sign build out/midas` → out/midas.sig published beside it) and
never on the hub; `sudo midas hub setup --self-update signed
--release-key -` installs the public half. ECDSA P-256, the p256 crate
the push notifications already sign with: no new dependency.
The default stays `hub`: a workspace that has never made a release key
must keep updating itself the day it takes this build, and the owner's
direction for releases (approval on their own device) is where
`signed` leads. A refusal is logged as self_update_refused.DESIGN.md | 12 ++-
docs/development.md | 20 ++++
docs/hub.md | 26 ++++-
src/conf.rs | 8 ++
src/hubsetup.rs | 35 +++++++
src/main.rs | 59 ++++++++++-
src/release.rs | 216 ++++++++++++++++++++++++++++++++++++++++
units/midas-self-update.service | 7 +-
8 files changed, 375 insertions(+), 8 deletions(-)
diff --git a/DESIGN.md b/DESIGN.md
index f79ad26..4973636 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -337,7 +337,17 @@ status is the number of the caller's. **`midas mcp`** offers the same as MCP too
hub's directories. Known limitation: a node is less clean than a fresh CI
container — its warm `target/` outlives its holders — which is acceptable
while every holder is the workspace's own agent, and would call for a build
- directory of the deploy's own if it were not.
+ directory of the deploy's own if it were not. Revised 2026-11-21, before
+ the code went public: "only to the places that file names" did not hold
+ where a place was root's own executable — midas's self-update ran the
+ published binary as root, so the hub's user was root — nor where the
+ place's directory belonged to someone else, who could swap a level of it
+ for a link between root's calls. Root now writes relative to a destination
+ directory opened without following links, and runs a published midas only
+ as hub.conf's `self_update` says: `hub` (as before, the default), `signed`
+ (the owner's key on it, never on the hub: `release.rs`), or `off`. The
+ honest default is still `hub`: a workspace that has never made a release
+ key must keep updating itself the day it takes this build.
16. **Bot secrets kept by the hub** (2026-10-16), revising 14. A bot's token
was set on its machine by root (`sudo midas bot setup`), which meant a sudo
diff --git a/docs/development.md b/docs/development.md
index 350f902..ca07c95 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -136,6 +136,26 @@ home network**:
- **Secrets stay off command lines**: tokens go to `curl` as a config on stdin
(`-K -`), never as arguments.
+And on the hub's machine, where root publishes what the hub's user built:
+
+- **Root trusts no path the hub's user, or an agent's container, can change.**
+ What it reads from them it opens refusing a symbolic link at every level;
+ what it writes, it writes relative to a destination directory opened the
+ same way (`deploy.rs`: `open_nofollow`, `install_in`, `sync_into`). A link
+ swapped into a path between two calls is what this is about.
+- **Root runs a build of midas only as `self_update` in hub.conf allows**
+ (`release.rs`): with `signed`, only one the owner's release key signed; the
+ key never leaves the owner's machine.
+- **A posted event is believed only from whoever may say it**: a kind the hub
+ acts on (`events::drives_state`) is taken from a caller key, or from the
+ node it names; the tunnel may post a log line and nothing more.
+- **A project's hooks run as landed**: `midas hook projects` runs a worktree's
+ `.claude/settings.json` hooks only when that file is the one on the
+ project's main, and never `settings.local.json`. Nobody reviews a branch's
+ hook change before it would run on the runner; landing is the review.
+- **A node's secrets go to the node**: `/v1/bot/secrets/for` answers the node
+ named, from its own address, and logs the read; a caller key reads none.
+
A change that lets the hub, or anything inside a node, reach past that line is
a bug, however convenient. Tested by switching the node's own inner firewall
off: it still reached only the hub, the internet and the hub machine's public
diff --git a/docs/hub.md b/docs/hub.md
index 1b60753..404324c 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -153,10 +153,26 @@ user, `midas-publish` publishes as root. Neither runs until something is queued.
**midas itself** deploys the same way, as a target of its own project, with a
third service: a deploy that publishes into `/usr/local/lib/midas/next` and
writes its `stamp` starts `midas-self-update`, which waits five seconds (for
-the publish to tell the hub it went out) and runs `hub setup` with the
-published binary, as root: it installs itself, updates the services and
-restarts the hub. A `midas-macos-aarch64` published beside it goes to the
-Macs' nodes. Publish it also to the copy an agent container runs (`{"from":
+the publish to tell the hub it went out) and runs `midas hub self-update` with
+the **installed** midas, as root. That decides, from `self_update` in
+hub.conf, what to do with the published build: `"hub"` (the default) runs its
+`hub setup` as it comes — it installs itself, updates the services and
+restarts the hub; `"signed"` does so only when `midas.sig` beside it (and
+`midas-macos-aarch64.sig`, when that is published too) is a good signature by
+the release key in `/etc/midas/release.pub`; `"off"` leaves it there for
+somebody to install by hand. A refusal is logged (`self_update_refused`) and
+shown with the deploy. The point of `signed`: the hub's user, which builds and
+publishes, is assumed compromisable, and with `hub` whoever is that user is
+root on this machine the next time midas deploys. The key is the owner's, on
+their own machine, never on the hub:
+
+```bash
+midas sign keygen # once, on your own machine: ~/.config/midas/release.key, prints the public line
+sudo midas hub setup --self-update signed --release-key 'midas-release-public-v1 …' # on the hub
+midas sign build out/midas # each release: out/midas.sig beside it, published with it
+```
+
+A `midas-macos-aarch64` published beside it goes to the Macs' nodes. Publish it also to the copy an agent container runs (`{"from":
"out/midas", "to": "<that copy, as this machine sees it>"}`): its sessions runner
then installs the new skills and hooks and starts again on it by itself, which
is the rest of what `deploy.sh` does by hand. The nodes take the hub's build as
@@ -1195,6 +1211,8 @@ healthy.
|---|---|
| `/etc/midas/hub.conf` | the settings above |
| `/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 |
| `/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/src/conf.rs b/src/conf.rs
index a0e1465..350a476 100644
--- a/src/conf.rs
+++ b/src/conf.rs
@@ -41,6 +41,13 @@ pub struct HubConf {
/// project's with `midas project`.
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
pub projects: std::collections::BTreeMap<String, Project>,
+ /// What the hub does with a build of midas its own deploy published
+ /// (`midas-self-update`, release.rs): `hub`, run its `hub setup` as root
+ /// as it comes (the default, and how it was until 2026-11-21); `signed`,
+ /// only with a good signature by the release key in
+ /// `/etc/midas/release.pub`; `off`, never — somebody installs it by hand.
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub self_update: String,
}
/// What the shared `finish-branch` skill needs to know about one project. The
@@ -289,6 +296,7 @@ impl Default for HubConf {
deploy: Default::default(),
alerts: None,
projects: Default::default(),
+ self_update: String::new(),
}
}
}
diff --git a/src/hubsetup.rs b/src/hubsetup.rs
index 16f1d27..e6e57a4 100644
--- a/src/hubsetup.rs
+++ b/src/hubsetup.rs
@@ -56,10 +56,21 @@ pub struct Args {
/// `<os>-<arch>=<path>`: this same build of midas for nodes of another
/// platform (deploy.sh builds the Macs' beside the hub's own).
pub node_binaries: Vec<String>,
+ /// `hub`, `signed` or `off`: what the self-update does with a published build (release.rs).
+ pub self_update: Option<String>,
+ /// The release key's public line (`midas sign keygen` prints it), or a
+ /// file holding it, or `-` for stdin: installed as /etc/midas/release.pub.
+ pub release_key: Option<String>,
}
pub fn merge(stored: Option<HubConf>, a: Args) -> Result<HubConf> {
let mut c = stored.unwrap_or_default();
+ if let Some(v) = a.self_update {
+ if !matches!(v.as_str(), "hub" | "signed" | "off") {
+ bail!("--self-update is hub, signed or off, not {v:?}");
+ }
+ c.self_update = if v == "hub" { String::new() } else { v };
+ }
if let Some(v) = a.listen { c.listen = v; }
if let Some(v) = a.forgejo_ssh { c.forgejo_ssh = v; }
if let Some(v) = a.forgejo_api { c.forgejo_api = v; }
@@ -155,7 +166,11 @@ pub fn setup(mut a: Args) -> Result<i32> {
bail!("run it as root: sudo midas hub setup …");
}
let node_binaries = std::mem::take(&mut a.node_binaries);
+ let release_key = a.release_key.take();
let c = merge(conf::read(Path::new(HUB_CONF))?, a)?;
+ if c.self_update == "signed" && release_key.is_none() && !Path::new(crate::release::RELEASE_PUB).exists() {
+ bail!("--self-update signed needs the release key's public half: --release-key <line, file or ->");
+ }
for tool in ["git", "ssh-keygen", "systemctl", "useradd"] {
if run(Command::new("sh").args(["-c", &format!("command -v {tool}")])).is_err() {
bail!("{tool} is not installed");
@@ -184,6 +199,24 @@ pub fn setup(mut a: Args) -> Result<i32> {
chown("/etc/midas", &format!("root:{USER}"))?;
write_if_changed(HUB_CONF, &(serde_json::to_string_pretty(&c)? + "\n"), 0o640)?;
chown(HUB_CONF, &format!("root:{USER}"))?;
+ if let Some(k) = release_key {
+ // The line itself, a file holding it, or stdin: root's, readable by all (it is public).
+ let line = if k == "-" {
+ let mut t = String::new();
+ std::io::stdin().read_line(&mut t)?;
+ t
+ } else if k.starts_with("midas-release-public-") {
+ k
+ } else {
+ fs::read_to_string(&k).with_context(|| format!("reading {k}"))?
+ };
+ let line = line.trim();
+ if !line.starts_with("midas-release-public-v1 ") {
+ bail!("not a release key's public line: {line:?}");
+ }
+ write_if_changed(crate::release::RELEASE_PUB, &format!("{line}\n"), 0o644)?;
+ println!("release key installed at {}", crate::release::RELEASE_PUB);
+ }
// Its two keys.
let mut new_deploy_key = false;
@@ -402,6 +435,8 @@ mod tests {
repos: vec!["owner/project".into()],
agent_keys: vec![],
node_binaries: vec![],
+ self_update: None,
+ release_key: None,
}
}
diff --git a/src/main.rs b/src/main.rs
index d9e8d7d..0d8cee0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -47,6 +47,7 @@ mod nodectl;
mod procs;
mod push;
mod registry;
+mod release;
mod remote;
mod runners;
mod setup;
@@ -636,6 +637,10 @@ enum Cmd {
/// The hub's services.
#[command(subcommand)]
Hub(HubCmd),
+ /// The owner's release key: signs a build of midas, which the hub's
+ /// self-update can insist on (hub.conf `self_update: "signed"`).
+ #[command(subcommand)]
+ Sign(SignCmd),
/// A node on this machine: status, start/stop/restart, logs, a shell.
#[command(subcommand)]
Node(NodeCmd),
@@ -942,6 +947,35 @@ enum NodesCmd {
Rename { id: String, to: String },
}
+#[derive(Subcommand)]
+enum SignCmd {
+ /// A new release key (default ~/.config/midas/release.key, 0600, never over
+ /// an old one); prints its public line for the hub.
+ Keygen {
+ #[arg(long)]
+ key: Option<String>,
+ },
+ /// The public line of a release key.
+ Public {
+ #[arg(long)]
+ key: Option<String>,
+ },
+ /// Sign a build: writes <file>.sig beside it.
+ Build {
+ file: std::path::PathBuf,
+ #[arg(long)]
+ key: Option<String>,
+ },
+ /// Check a build against a public key (default signature: <file>.sig).
+ Verify {
+ file: std::path::PathBuf,
+ #[arg(long)]
+ pubkey: std::path::PathBuf,
+ #[arg(long)]
+ sig: Option<std::path::PathBuf>,
+ },
+}
+
#[derive(Subcommand)]
enum HubCmd {
/// Make this machine the hub (as root): its user, keys, services. Run it
@@ -966,6 +1000,22 @@ enum HubCmd {
/// they take from the hub when free (repeatable; deploy.sh passes it).
#[arg(long = "node-binary")]
node_binaries: Vec<String>,
+ /// What the hub does with a build of midas it published itself: hub
+ /// (run it as root, the default), signed (only with the release key's
+ /// signature on it), off (never).
+ #[arg(long)]
+ self_update: Option<String>,
+ /// The release key's public line (`midas sign keygen` prints it), a
+ /// file holding it, or - for stdin: goes to /etc/midas/release.pub.
+ #[arg(long)]
+ release_key: Option<String>,
+ },
+ /// 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 {
+ /// Where the build waits (default: /usr/local/lib/midas/next).
+ #[arg(long)]
+ next: Option<std::path::PathBuf>,
},
/// Who may change the workspace: one key per caller (as root, on the hub).
#[command(subcommand)]
@@ -1443,8 +1493,13 @@ 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::Setup { listen, forgejo, forgejo_api, repos, agent_keys, node_binaries }) => hubsetup::setup(hubsetup::Args {
- listen, forgejo_ssh: forgejo, forgejo_api, repos, agent_keys, node_binaries,
+ 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)),
+ Cmd::Sign(SignCmd::Build { file, key }) => release::sign(&key.map(std::path::PathBuf::from).unwrap_or_else(release::default_key), &file),
+ Cmd::Sign(SignCmd::Verify { file, pubkey, sig }) => release::verify_cmd(&pubkey, &file, sig.as_deref()),
+ Cmd::Hub(HubCmd::Setup { listen, forgejo, forgejo_api, repos, agent_keys, node_binaries, self_update, release_key }) => hubsetup::setup(hubsetup::Args {
+ listen, forgejo_ssh: forgejo, forgejo_api, repos, agent_keys, node_binaries, self_update, release_key,
}),
Cmd::Hub(HubCmd::Caller(CallerCmd::Add { name, forgejo_token, role })) => hubsetup::caller_add(&name, forgejo_token, role.as_deref()),
Cmd::Hub(HubCmd::Caller(CallerCmd::Role { name, role })) => hubsetup::caller_role(&name, &role),
diff --git a/src/release.rs b/src/release.rs
new file mode 100644
index 0000000..d1833a7
--- /dev/null
+++ b/src/release.rs
@@ -0,0 +1,216 @@
+//! Release signatures: the owner's key on a build of midas, which root on the
+//! hub checks before it runs that build as itself (`midas hub self-update`).
+//!
+//! The hub's machine is assumed compromisable (DESIGN.md §6), and its user
+//! publishes the midas binary that the self-update then runs as root: whoever
+//! is that user is root on the hub, unless root checks something that user
+//! cannot make. That is a signature by a key the hub never holds — the owner's,
+//! on their own machine (`midas sign keygen`, `midas sign build`). The
+//! public half is `/etc/midas/release.pub`, root's; `self_update` in hub.conf
+//! says whether the hub insists on it (`signed`), trusts its own publish
+//! (`hub`: how it was until 2026-11-21, and still the default, since a
+//! workspace with no release key would otherwise stop updating itself the day
+//! it took this build) or never updates itself (`off`).
+//!
+//! ECDSA P-256 over SHA-256 — the `p256` crate the push notifications already
+//! sign with, deterministic (RFC 6979), so no random number is drawn at
+//! signing. The key is its 32 raw bytes, the public key the compressed point,
+//! the signature 64 raw bytes; each file is one line, a label and base64, so a
+//! wrong file is told from a corrupt one.
+
+use std::fs;
+use std::os::unix::fs::OpenOptionsExt;
+use std::path::{Path, PathBuf};
+
+use anyhow::{anyhow, bail, Context, Result};
+use data_encoding::BASE64;
+use p256::ecdsa::signature::{Signer, Verifier};
+use p256::ecdsa::{Signature, SigningKey, VerifyingKey};
+
+/// The release key's public half on the hub's machine, root's.
+pub const RELEASE_PUB: &str = "/etc/midas/release.pub";
+/// Where a published build of midas waits for the self-update (hub.conf's
+/// midas target publishes into it; `units/midas-self-update.path` watches it).
+pub const NEXT: &str = "/usr/local/lib/midas/next";
+
+const KEY_LABEL: &str = "midas-release-key-v1";
+const PUB_LABEL: &str = "midas-release-public-v1";
+const SIG_LABEL: &str = "midas-release-signature-v1";
+
+/// `~/.config/midas/release.key` unless said otherwise.
+pub fn default_key() -> PathBuf {
+ let home = std::env::var("HOME").unwrap_or_default();
+ PathBuf::from(format!("{home}/.config/midas/release.key"))
+}
+
+fn write_line(path: &Path, label: &str, bytes: &[u8], mode: u32) -> Result<()> {
+ if let Some(p) = path.parent() {
+ fs::create_dir_all(p)?;
+ }
+ let mut f = fs::OpenOptions::new().write(true).create_new(true).mode(mode).open(path)
+ .with_context(|| format!("writing {} (it is not overwritten)", path.display()))?;
+ std::io::Write::write_all(&mut f, format!("{label} {}\n", BASE64.encode(bytes)).as_bytes())?;
+ Ok(())
+}
+
+fn read_line(path: &Path, label: &str) -> Result<Vec<u8>> {
+ let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
+ let mut w = text.split_whitespace();
+ match (w.next(), w.next()) {
+ (Some(l), Some(b)) if l == label => BASE64.decode(b.as_bytes()).map_err(|_| anyhow!("{} is not a {label}", path.display())),
+ (Some(l), _) => bail!("{} is a {l}, not a {label}", path.display()),
+ _ => bail!("{} is empty", path.display()),
+ }
+}
+
+fn signing_key(path: &Path) -> Result<SigningKey> {
+ SigningKey::from_slice(&read_line(path, KEY_LABEL)?).map_err(|_| anyhow!("{} holds no P-256 key", path.display()))
+}
+
+fn verifying_key(path: &Path) -> Result<VerifyingKey> {
+ VerifyingKey::from_sec1_bytes(&read_line(path, PUB_LABEL)?).map_err(|_| anyhow!("{} holds no P-256 public key", path.display()))
+}
+
+fn public_line(key: &SigningKey) -> String {
+ format!("{PUB_LABEL} {}", BASE64.encode(VerifyingKey::from(key).to_encoded_point(true).as_bytes()))
+}
+
+/// `midas sign keygen`: a new key at `path` (0600, never over an old one),
+/// and its public line on stdout, for `/etc/midas/release.pub` on the hub.
+pub fn keygen(path: &Path) -> Result<i32> {
+ let mut urandom = fs::File::open("/dev/urandom")?;
+ let key = loop {
+ let mut b = [0u8; 32];
+ std::io::Read::read_exact(&mut urandom, &mut b)?;
+ // Nearly every 32 bytes is a valid scalar; the rest is drawn again.
+ if let Ok(k) = SigningKey::from_slice(&b) {
+ write_line(path, KEY_LABEL, &b, 0o600)?;
+ break k;
+ }
+ };
+ eprintln!("key written to {}. Its public half, for the hub (sudo midas hub setup --release-key -):", path.display());
+ println!("{}", public_line(&key));
+ Ok(0)
+}
+
+/// `midas sign public`: the public line of the key at `path`.
+pub fn public(path: &Path) -> Result<i32> {
+ println!("{}", public_line(&signing_key(path)?));
+ Ok(0)
+}
+
+/// The signature file beside `file`.
+pub fn sig_path(file: &Path) -> PathBuf {
+ let mut s = file.as_os_str().to_owned();
+ s.push(".sig");
+ PathBuf::from(s)
+}
+
+/// `midas sign build <file>`: `<file>.sig` beside it, by the key at `key`.
+pub fn sign(key: &Path, file: &Path) -> Result<i32> {
+ let k = signing_key(key)?;
+ let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
+ let sig: Signature = k.sign(&bytes);
+ let out = sig_path(file);
+ let _ = fs::remove_file(&out);
+ write_line(&out, SIG_LABEL, &sig.to_bytes(), 0o644)?;
+ eprintln!("{} signed: {}", file.display(), out.display());
+ Ok(0)
+}
+
+/// `file` carries a good signature (`sig`, default `<file>.sig`) by the key
+/// whose public half is at `pubkey`; an error says which part is not so.
+pub fn verify(pubkey: &Path, file: &Path, sig: Option<&Path>) -> Result<()> {
+ let vk = verifying_key(pubkey)?;
+ let sig_file = sig.map(Path::to_path_buf).unwrap_or_else(|| sig_path(file));
+ let sig = Signature::from_slice(&read_line(&sig_file, SIG_LABEL)?).map_err(|_| anyhow!("{} holds no signature", sig_file.display()))?;
+ let bytes = fs::read(file).with_context(|| format!("reading {}", file.display()))?;
+ vk.verify(&bytes, &sig).map_err(|_| anyhow!("{} does not match the signature in {} by the key in {}", file.display(), sig_file.display(), pubkey.display()))
+}
+
+/// `midas sign verify <file> --pubkey <path>`: exit 0 when `verify` says so.
+pub fn verify_cmd(pubkey: &Path, file: &Path, sig: Option<&Path>) -> Result<i32> {
+ verify(pubkey, file, sig)?;
+ eprintln!("{} is signed by the key in {}", file.display(), pubkey.display());
+ Ok(0)
+}
+
+/// `midas hub self-update` (root; `units/midas-self-update.service` runs it
+/// with the installed midas, never with the published one): what hub.conf's
+/// `self_update` says about the build waiting in `next`, then that build's
+/// `hub setup`, which installs it, updates the services and restarts the hub.
+pub fn self_update(next: &Path) -> Result<i32> {
+ // SAFETY: geteuid has no preconditions.
+ if unsafe { libc::geteuid() } != 0 {
+ bail!("the self-update is root's: the midas-self-update service runs it");
+ }
+ let c = crate::conf::read(Path::new(crate::conf::HUB_CONF))?.unwrap_or_default();
+ let bin = next.join("midas");
+ if !bin.is_file() {
+ bail!("nothing to install: no {}", bin.display());
+ }
+ let mac = next.join("midas-macos-aarch64");
+ let policy = if c.self_update.is_empty() { "hub" } else { c.self_update.as_str() };
+ let outcome = match policy {
+ "off" => Err(anyhow!("self_update is off in hub.conf: {} stays published, not installed", bin.display())),
+ "signed" => {
+ let pubkey = Path::new(RELEASE_PUB);
+ verify(pubkey, &bin, None)
+ .and_then(|_| if mac.is_file() { verify(pubkey, &mac, None) } else { Ok(()) })
+ .context("the published midas carries no good signature by the release key, so it is not installed")
+ }
+ "hub" => Ok(()),
+ other => Err(anyhow!("hub.conf's self_update is {other:?}, not hub, signed or off: nothing installed")),
+ };
+ if let Err(e) = outcome {
+ crate::deploy::root_emit("self_update_refused", serde_json::json!({"policy": policy, "what": format!("{e:#}")}));
+ return Err(e);
+ }
+ let mut cmd = std::process::Command::new(&bin);
+ cmd.args(["hub", "setup"]);
+ if mac.is_file() {
+ cmd.arg("--node-binary").arg(format!("macos-aarch64={}", mac.display()));
+ }
+ let err = std::os::unix::process::CommandExt::exec(&mut cmd);
+ bail!("running {} hub setup: {err}", bin.display())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn scratch(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("midas-release-{name}-{}", std::process::id()));
+ let _ = fs::remove_dir_all(&d);
+ fs::create_dir_all(&d).unwrap();
+ d
+ }
+
+ #[test]
+ fn a_signature_holds_for_the_bytes_signed_and_for_nothing_else() {
+ let d = scratch("sign");
+ let key = d.join("k/release.key");
+ keygen(&key).unwrap();
+ assert_eq!(fs::metadata(&key).unwrap().permissions().mode() & 0o777, 0o600);
+ assert!(keygen(&key).is_err(), "never over an old key");
+ let pubkey = d.join("release.pub");
+ fs::write(&pubkey, public_line(&signing_key(&key).unwrap()) + "\n").unwrap();
+ let bin = d.join("midas");
+ fs::write(&bin, b"ELF of a build").unwrap();
+ sign(&key, &bin).unwrap();
+ verify(&pubkey, &bin, None).unwrap();
+ fs::write(&bin, b"ELF of another build").unwrap();
+ assert!(verify(&pubkey, &bin, None).unwrap_err().to_string().contains("does not match"));
+ // Another key's signature, a wrong file in a key's place, a corrupt line.
+ let other = d.join("other.key");
+ keygen(&other).unwrap();
+ sign(&other, &bin).unwrap();
+ assert!(verify(&pubkey, &bin, None).is_err());
+ assert!(verify(&key, &bin, None).unwrap_err().to_string().contains("not a midas-release-public-v1"));
+ fs::write(&pubkey, "midas-release-public-v1 ****\n").unwrap();
+ assert!(verify(&pubkey, &bin, None).is_err());
+ let _ = fs::remove_dir_all(&d);
+ }
+
+ use std::os::unix::fs::PermissionsExt;
+}
diff --git a/units/midas-self-update.service b/units/midas-self-update.service
index c14fdf8..0757d71 100644
--- a/units/midas-self-update.service
+++ b/units/midas-self-update.service
@@ -1,6 +1,11 @@
# Root, as `sudo midas hub setup` is: the published build installs itself,
# updates the services and restarts the hub on it, as deploy.sh does by hand.
# A build for the Macs' nodes, published beside it, goes to them too.
+#
+# Run by the midas that is installed, never by the one published: it is that
+# one which decides, from hub.conf's `self_update`, whether the published build
+# is run as root at all (`hub`), only with the owner's signature on it
+# (`signed`: /etc/midas/release.pub, src/release.rs), or never (`off`).
[Unit]
Description=midas: install the published build and restart the hub on it
After=midas-publish.service
@@ -10,5 +15,5 @@ Type=oneshot
# The publish that wrote the stamp still tells the hub the deploy went out:
# that must reach the hub before it restarts, or the landing never reads live.
ExecStartPre=/bin/sleep 5
-ExecStart=/bin/sh -c 'n=/usr/local/lib/midas/next; mac=; [ -f $$n/midas-macos-aarch64 ] && mac="--node-binary macos-aarch64=$$n/midas-macos-aarch64"; exec $$n/midas hub setup $$mac'
+ExecStart=/usr/local/bin/midas hub self-update
TimeoutStartSec=10min