git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-21T19:38:57Z
fix(bot): a node's secrets go to the node itself, not to any caller key POST /v1/bot/secrets/for answered any operator key with any node's bot secrets and any named bot's password and OpenAI key, in clear: `midas bot start` fetched them in the agent's process and piped them to the node. Every session in the agents' container holds that key, so every session could read every node's. Found by the review before the code went public. The node asks for them now, as the bot starts (`midas node bot start --bot <name>`), and the hub answers only the node named, from its own address, as it takes its heartbeat; each read is logged with the names and the node's holder, never the values. What a secret reaches is then the node that runs the bot, and the session holding it, which could read them there anyway. The route moved out of the keyed section (the commit before this added the node's; this removes the old one). A `bot start` from before this still works against a new node, without the hub's secrets, until its midas follows the hub's.
docs/usage.md | 6 +++++-
src/bot.rs | 59 ++++++++++++++++++++++++++++++++++-------------------------
src/hub.rs | 14 ++++----------
src/main.rs | 7 +++++--
4 files changed, 48 insertions(+), 38 deletions(-)
diff --git a/docs/usage.md b/docs/usage.md
index 2aae017..c1fe380 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -90,7 +90,11 @@ midas bot stop # stop it and give the node back (midas release does
- **Its credential**: `midas bot token gpu` (asks for it with echo off; `--env`
names the variable, default `CARTO_TOKEN`) gives every GPU node's bots one, kept
by the hub and handed to the bot when it starts — a node, a machine or `any`
- work too, and `--list` names what is set. A machine's owner can instead set one
+ work too, and `--list` names what is set. The node itself asks the hub for
+ them as the bot starts, and the hub answers only the node named, from its
+ own address: a secret reaches the node that runs the bot and the session
+ holding it, no other session, and each read is logged (`bot_secrets_read`,
+ names only). A machine's owner can instead set one
on the machine (`sudo midas bot setup`, [node.md](node.md#bot-credentials)),
which never passes through the hub; where both set a name, the hub's wins.
- **A named bot's sign-in and voice**: Settings ▸ Bots on the page keeps, per
diff --git a/src/bot.rs b/src/bot.rs
index b6d6d7d..098a7ae 100644
--- a/src/bot.rs
+++ b/src/bot.rs
@@ -115,9 +115,9 @@ pub fn sh_quote(s: &str) -> String {
}
/// The command `midas bot start` runs on the node, every argument quoted.
-pub fn remote_command(relay: &str, timeout: u64, command: &[String], env_stdin: bool) -> String {
+pub fn remote_command(relay: &str, timeout: u64, command: &[String], bot: Option<&str>) -> String {
let mut s = format!("midas node bot start --timeout {timeout} --mcp {}{} --", sh_quote(relay),
- if env_stdin { " --env-stdin" } else { "" });
+ bot.map(|b| format!(" --bot {}", sh_quote(b))).unwrap_or_default());
for w in command {
s.push(' ');
s.push_str(&sh_quote(w));
@@ -151,26 +151,17 @@ pub fn start(s: &Start) -> Result<i32> {
};
// The hub's secrets for this node (`midas bot token`), and the bot's own
// sign-in and voice key when the page configures one by this name
- // (Settings ▸ Bots, `botconfig`), handed over on the session's stdin: on
- // no disk, in no command line, in no log.
+ // (Settings ▸ Bots, `botconfig`), are asked for by the node itself
+ // (`node_start`), which the hub answers from the node's address and no
+ // other: they never pass through this process, and until 2026-11-21 any
+ // caller key could ask for any node's.
let bot = s.agent.as_ref().map(|a| a.name.clone());
- let secrets: Vec<(String, String)> = client::post("/v1/bot/secrets/for", &json!({"node": id, "bot": bot})).ok()
- .and_then(|v| v["env"].as_object().cloned())
- .map(|m| m.into_iter().filter_map(|(k, v)| v.as_str().map(|v| (k, v.to_string()))).collect())
- .unwrap_or_default();
// The flush runs before this ssh, as before any: the bot is built from
// exactly the tree this worktree has.
- let mut child = Command::new("ssh").args(["-o", "BatchMode=yes", &id])
- .arg(remote_command(&s.mcp, s.timeout, &s.command, !secrets.is_empty()))
- .stdin(if secrets.is_empty() { Stdio::null() } else { Stdio::piped() })
- .stdout(to_stderr()).spawn().context("running ssh")?;
- if let Some(mut input) = child.stdin.take() {
- for (k, v) in &secrets {
- writeln!(input, "{k}={v}")?;
- }
- // Dropped here: EOF is how the node knows the list is done.
- }
- let st = child.wait()?;
+ let st = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id])
+ .arg(remote_command(&s.mcp, s.timeout, &s.command, bot.as_deref()))
+ .stdin(Stdio::null())
+ .stdout(to_stderr()).status().context("running ssh")?;
if !st.success() {
if before.as_deref() == Some(id.as_str()) {
eprintln!("midas: no bot on {id}; this worktree held it before, and still does");
@@ -217,7 +208,7 @@ pub fn mcp(owner: &str) -> Result<i32> {
// MIDAS_FLUSHING: the bot was built when it started, and a relay
// has nothing to send; nor need it be run from the holding
// worktree (a host's agent runs it from a directory of its own).
- let err = Command::new("ssh").args(["-o", "BatchMode=yes", &id, "midas node bot mcp"])
+ let err = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id, "midas node bot mcp"])
.env("MIDAS_FLUSHING", "1").exec();
bail!("could not run ssh: {err}")
}
@@ -237,7 +228,7 @@ pub fn mcp(owner: &str) -> Result<i32> {
pub fn stop_remote(node: &str) -> bool {
// MIDAS_FLUSHING: no flush and no holder check for this one — stopping
// needs no worktree, and a release should not first send one.
- let ok = Command::new("ssh").args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", node, "midas node bot stop"])
+ let ok = Command::new("ssh").args(["-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "--", node, "midas node bot stop"])
.env("MIDAS_FLUSHING", "1").stdin(Stdio::null()).stdout(to_stderr()).status()
.is_ok_and(|s| s.success());
if !ok {
@@ -291,7 +282,7 @@ pub fn status(owner: &str, name: Option<&str>) -> Result<i32> {
return Ok(1);
};
println!("{id}, held in {} mode", mode.as_str());
- let st = Command::new("ssh").args(["-o", "BatchMode=yes", &id, "midas node bot status"])
+ let st = Command::new("ssh").args(["-o", "BatchMode=yes", "--", &id, "midas node bot status"])
.env("MIDAS_FLUSHING", "1").stdin(Stdio::null()).status().context("running ssh")?;
Ok(st.code().unwrap_or(1))
}
@@ -563,7 +554,7 @@ pub fn handshake(relay: &str, cwd: &Path, wait: Duration) -> Result<()> {
}
/// `midas node bot start`: start the bot detached, and return when it answers.
-pub fn node_start(relay: &str, timeout: u64, command: &[String], env_stdin: bool) -> Result<i32> {
+pub fn node_start(relay: &str, timeout: u64, command: &[String], env_stdin: bool, bot: Option<&str>) -> Result<i32> {
// A relay that ends before taking the request must cost the request, not
// this process: with SIGPIPE at its default a write to it would end us.
// SAFETY: setting a signal's disposition.
@@ -593,6 +584,23 @@ pub fn node_start(relay: &str, timeout: u64, command: &[String], env_stdin: bool
}
let _ = fs::remove_file(state_path());
let mut env = bot_env()?;
+ // The hub's secrets for this node, and the bot's own (Settings ▸ Bots), after
+ // the machine's: a name set in both takes the hub's. Asked for by this node,
+ // which the hub answers from its address only; they go into the bot's
+ // environment and nowhere else.
+ match crate::hub::request(&cfg.hub, "POST", "/v1/bot/secrets/for", Some(&json!({"node": cfg.node, "bot": bot}).to_string())) {
+ Ok((200, body)) => {
+ let given = serde_json::from_str::<Value>(&body).ok().and_then(|v| v["env"].as_object().cloned()).unwrap_or_default();
+ for (k, v) in given {
+ if let Some(v) = v.as_str() {
+ env.retain(|(name, _)| *name != k);
+ env.push((k, v.to_string()));
+ }
+ }
+ }
+ Ok((code, body)) => eprintln!("midas: the hub gave {} no secrets (HTTP {code}): {}", cfg.node, body.trim()),
+ Err(e) => eprintln!("midas: the hub gave {} no secrets: {e:#}", cfg.node),
+ }
if env_stdin {
// The hub's, after the machine's: a name set in both takes the hub's.
let mut text = String::new();
@@ -776,8 +784,9 @@ mod tests {
assert_eq!(sh_quote(""), "''");
assert_eq!(sh_quote("it's $HOME; rm -rf ~"), r"'it'\''s $HOME; rm -rf ~'");
let cmd: Vec<String> = ["cargo", "run", "-q", "--", "--name", "a b", "$X", "it's"].map(String::from).to_vec();
- let remote = remote_command("socat - UNIX:/tmp/s", 60, &cmd, false);
- assert!(remote_command("r", 60, &cmd, true).contains(" --env-stdin --"), "the secrets' flag, before the command");
+ let remote = remote_command("socat - UNIX:/tmp/s", 60, &cmd, None);
+ assert!(remote_command("r", 60, &cmd, Some("scout")).contains(" --bot scout --"), "the bot's name, before the command");
+ assert!(remote_command("r", 60, &cmd, Some("a b")).contains(" --bot 'a b' --"));
assert!(!remote.contains("--env-stdin"));
// What the node's `bash -lc` makes of it is exactly the argument list.
let out = Command::new("bash").arg("-c").arg(format!("printf '%s\\n' {}", remote.trim_start_matches("midas ")))
diff --git a/src/hub.rs b/src/hub.rs
index ebb9ca5..0414c1f 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -18,7 +18,10 @@
//! * from nodes, accepted only from the node's own WireGuard address:
//! `POST /v1/renew/<node>`, `/v1/readings/<node>` (the heartbeat),
//! `/v1/nodes/<node>/register` (its git and host keys), `GET /v1/nodes/<node>/midas`
-//! and `/v1/nodes/<node>/midas/<os-arch>` (the midas it should run); and `/v1/events`;
+//! and `/v1/nodes/<node>/midas/<os-arch>` (the midas it should run), `/v1/bot/secrets/for`
+//! (the secrets a bot there starts with), and its `ssh_session` lines to `/v1/events` — which
+//! is otherwise open for a plain log line, but acts on a kind in `events::drives_state` only
+//! from a caller key;
//! and from a machine's address, `POST /v1/power` (what it draws: power.rs, read
//! back with the open `GET /v1/power?since=&step=`), and `POST /v1/sleep` (which
//! of its VMs to keep running: sleep.rs);
@@ -1291,15 +1294,6 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
let value = if body["remove"] == true { None } else { Some(s("value").unwrap_or_default()) };
(200, crate::botsecrets::set(&s("target").unwrap_or_default(), &s("name").unwrap_or_default(), value.as_deref(), &by)?)
}
- // The node's secrets, and with `bot`, that bot's configuration on top
- // (Settings ▸ Bots): the more particular wins.
- ("POST", "bot/secrets/for") => {
- let mut env = crate::botsecrets::for_node(&s("node").unwrap_or_default());
- if let Some(bot) = s("bot").filter(|b| !b.is_empty()) {
- env.extend(crate::botconfig::env_for(&bot));
- }
- (200, json!({"env": env}))
- }
("GET", "bot/secrets") => (200, crate::botsecrets::names()),
("POST", "land/targets") => {
let picked: Vec<String> = body["targets"].as_array().into_iter().flatten()
diff --git a/src/main.rs b/src/main.rs
index b28b5a1..d9e8d7d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -889,9 +889,12 @@ enum NodeBotCmd {
timeout: u64,
#[arg(last = true, required = true)]
command: Vec<String>,
- /// Read more NAME=value lines from stdin, to EOF (the hub's secrets, from `bot start`).
+ /// Read more NAME=value lines from stdin, to EOF (a `bot start` from before 2026-11-21).
#[arg(long, hide = true)]
env_stdin: bool,
+ /// The bot's name at the hub (Settings ▸ Bots), whose own secrets it starts with.
+ #[arg(long)]
+ bot: Option<String>,
},
/// Become the relay to the running bot: MCP on stdin and stdout.
Mcp,
@@ -1561,7 +1564,7 @@ fn run(cmd: Cmd, owner: Option<String>) -> anyhow::Result<i32> {
Cmd::Node(NodeCmd::Forward { vm, pairs }) => forward::forward(&vm, &pairs),
Cmd::Node(NodeCmd::Power { hub }) => power::report(&hub),
Cmd::Node(NodeCmd::Apply) => flush::apply(),
- Cmd::Node(NodeCmd::Bot(NodeBotCmd::Start { mcp, timeout, command, env_stdin })) => bot::node_start(&mcp, timeout, &command, env_stdin),
+ Cmd::Node(NodeCmd::Bot(NodeBotCmd::Start { mcp, timeout, command, env_stdin, bot })) => bot::node_start(&mcp, timeout, &command, env_stdin, bot.as_deref()),
Cmd::Node(NodeCmd::Bot(NodeBotCmd::Mcp)) => bot::node_mcp(),
Cmd::Node(NodeCmd::Bot(NodeBotCmd::Stop)) => bot::node_stop(),
Cmd::Node(NodeCmd::Bot(NodeBotCmd::Status)) => bot::node_status(),