diff --git a/pkgs/pass-broker/src/daemon.rs b/pkgs/pass-broker/src/daemon.rs index be9c48f..dba356e 100644 --- a/pkgs/pass-broker/src/daemon.rs +++ b/pkgs/pass-broker/src/daemon.rs @@ -81,7 +81,7 @@ async fn handle(state: Arc, stream: UnixStream) -> Result<()> { let vault = req.vault.clone().unwrap_or_else(|| state.cfg.default_vault.clone()); // A client killed while queued (the broker restarting) leaves its request // in the socket; nobody would see the answer or know who asked. - let who = match cred.pid().and_then(requester) { + let who = match cred.pid().and_then(|pid| requester(pid, cred.uid())) { Some(who) if !closed(&rd) => who, _ => { eprintln!("dropped {vault}/{}: requester went away", req.item); @@ -89,8 +89,11 @@ async fn handle(state: Arc, stream: UnixStream) -> Result<()> { } }; eprintln!( - "request {vault}/{} ({}) uid={} reason={:?} from {}", - req.item, req.field, cred.uid(), req.reason, who.from + "request {vault}/{} ({}) reason={:?} by {}", + req.item, + req.field, + req.reason, + who.summary() ); let gone = client_gone(&rd); @@ -111,6 +114,9 @@ async fn handle(state: Arc, stream: UnixStream) -> Result<()> { Reply::Error { error } => eprintln!("refused {vault}/{}: {error}", req.item), Reply::Pending { .. } => {} } + if closed(&rd) { + return Ok(()); + } send(&mut wr, reply).await } @@ -139,9 +145,12 @@ async fn decide( } // Before the lock, so a client queued behind another prompt hears from us. let _ = send(wr, Reply::Pending { message: "waiting for approval on Telegram".into() }).await; + // Biased: a client that already hung up must lose even to a free lock, + // or it would get a prompt. let _asking = tokio::select! { - guard = state.asking.lock() => guard, + biased; _ = gone.as_mut() => bail!("requester went away"), + guard = state.asking.lock() => guard, }; // A concurrent request for the same item may have been approved meanwhile. if granted(&*state.grants.lock().await) { @@ -153,12 +162,13 @@ async fn decide( n => format!("Approving covers further requests for {n} min."), }; let text = format!( - "🔑 {host}: {vault} / {item} ({field})\nReason: {reason}\nFrom: {from}\nChain: {chain}\n{grant}", + "🔑 {host}: {vault} / {item} ({field})\nReason: {reason}\nBy: {by}\nCommand: {command}\nChain: {chain}\n{grant}", host = state.cfg.host, item = req.item, field = req.field, reason = req.reason, - from = who.from, + by = who.who, + command = who.command, chain = who.chain, ); let timeout = Duration::from_secs(state.cfg.approval_timeout_secs); @@ -201,44 +211,94 @@ async fn send(wr: &mut OwnedWriteHalf, reply: Reply) -> Result<()> { Ok(()) } -/// Who is asking, for the prompt. Informational only: any process of the -/// same uid can make itself look like anything. +/// Who is asking, for the prompt and the journal. A hint, not identity: any +/// process of the same uid can make itself look like anything. struct Requester { - from: String, + /// "darman via Claude Code", "darman via foot", … + who: String, + /// The client's parent, i.e. the caller (the client is `pass-broker get`). + command: String, chain: String, } -/// The client itself is just `pass-broker get …`; its parent is the caller. -/// None when the client has already exited. -fn requester(pid: i32) -> Option { - let parent = ppid(pid)?; - let from = std::fs::read(format!("/proc/{parent}/cmdline")) - .map(|b| { - let s = String::from_utf8_lossy(&b).replace('\0', " "); - truncate(s.trim(), 200) - }) - .unwrap_or_default(); - let mut names = vec![]; - let mut p = parent; - for _ in 0..8 { - if p <= 1 { - break; - } - if let Ok(c) = std::fs::read_to_string(format!("/proc/{p}/comm")) { - names.push(c.trim().to_string()); - } - match ppid(p) { - Some(pp) => p = pp, - None => break, - } +impl Requester { + fn summary(&self) -> String { + format!("{} [{}] chain: {}", self.who, self.command, self.chain) } - Some(Requester { from, chain: names.join(" ← ") }) } -fn ppid(pid: i32) -> Option { +/// None when the client has already exited. +fn requester(pid: i32, uid: u32) -> Option { + let client = stat(pid)?; + let command = std::fs::read(format!("/proc/{}/cmdline", client.ppid)) + .map(|b| { + let s = String::from_utf8_lossy(&b); + let args: Vec<&str> = s.split('\0').filter(|a| !a.is_empty()).map(short_path).collect(); + truncate(&args.join(" "), 200) + }) + .unwrap_or_default(); + + let mut ancestors = vec![]; + let mut p = client.ppid; + while p > 1 && ancestors.len() < 12 { + let Some(s) = stat(p) else { break }; + let comm = std::fs::read_to_string(format!("/proc/{p}/comm")).unwrap_or_default(); + ancestors.push((comm.trim().to_string(), s.tty)); + p = s.ppid; + } + + // Claude Code's own process is `claude`. Otherwise the origin is whatever + // holds the terminal: the first ancestor without a tty (foot, sshd-session, + // the desktop app's terminal panel). + let via = if ancestors.iter().any(|(c, _)| c == "claude") { + "Claude Code".to_string() + } else if client.tty == 0 { + "no terminal".to_string() + } else { + match ancestors.iter().find(|(_, tty)| *tty == 0).map(|(c, _)| c.as_str()) { + Some("claude-desktop") => "Claude desktop's terminal".to_string(), + Some(c) => c.to_string(), + None => "unknown".to_string(), + } + }; + + let chain = ancestors.iter().take(8).map(|(c, _)| c.as_str()).collect::>().join(" ← "); + Some(Requester { who: format!("{} via {via}", user_name(uid)), command, chain }) +} + +struct Stat { + ppid: i32, + tty: i32, +} + +fn stat(pid: i32) -> Option { let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; - // comm may contain spaces and parens; fields resume after the last ')'. - stat.rsplit_once(')')?.1.split_whitespace().nth(1)?.parse().ok() + // comm may contain spaces and parens; fields resume after the last ')': + // state ppid pgrp session tty_nr … + let f: Vec<&str> = stat.rsplit_once(')')?.1.split_whitespace().collect(); + Some(Stat { ppid: f.get(1)?.parse().ok()?, tty: f.get(4)?.parse().ok()? }) +} + +fn user_name(uid: u32) -> String { + std::fs::read_to_string("/etc/passwd") + .ok() + .and_then(|p| { + p.lines().find_map(|l| { + let f: Vec<&str> = l.split(':').collect(); + (f.len() > 2 && f[2] == uid.to_string()).then(|| f[0].to_string()) + }) + }) + .unwrap_or_else(|| format!("uid {uid}")) +} + +/// `/nix/store/…-bash-5.3/bin/bash` and profile paths down to `bash`. +fn short_path(arg: &str) -> &str { + const PREFIXES: [&str; 4] = ["/nix/store/", "/run/current-system/", "/run/wrappers/", "/etc/profiles/"]; + if PREFIXES.iter().any(|p| arg.starts_with(p)) && arg.contains("/bin/") { + arg.rsplit('/').next().unwrap_or(arg) + } else { + arg + } } fn truncate(s: &str, max: usize) -> String { @@ -247,3 +307,17 @@ fn truncate(s: &str, max: usize) -> String { None => s.to_string(), } } + +#[cfg(test)] +mod tests { + use super::short_path; + + #[test] + fn short_paths() { + assert_eq!(short_path("/nix/store/abc-bash-interactive-5.3p9/bin/bash"), "bash"); + assert_eq!(short_path("/run/current-system/sw/bin/try-get"), "try-get"); + assert_eq!(short_path("/run/wrappers/bin/sudo"), "sudo"); + assert_eq!(short_path("/nix/store/abc-config.json"), "/nix/store/abc-config.json"); + assert_eq!(short_path("./scripts/deploy"), "./scripts/deploy"); + } +} diff --git a/pkgs/pass-broker/src/telegram.rs b/pkgs/pass-broker/src/telegram.rs index e8dce9b..1aa17e5 100644 --- a/pkgs/pass-broker/src/telegram.rs +++ b/pkgs/pass-broker/src/telegram.rs @@ -100,8 +100,9 @@ impl Telegram { }), ); let polled = tokio::select! { - r = poll => r, + biased; _ = gone.as_mut() => break 'poll Verdict::Cancelled, + r = poll => r, }; let updates = match polled { Ok(u) => u, diff --git a/services/identity/pass-broker-test.nix b/services/identity/pass-broker-test.nix index 7cba949..4c71751 100644 --- a/services/identity/pass-broker-test.nix +++ b/services/identity/pass-broker-test.nix @@ -110,6 +110,11 @@ let # ghost: send a request and hang up before the broker reads it, like a # client killed while queued. silent: a socket that never answers, like a # crash-looping broker behind its socket unit. + # Stand-in for Claude Code, whose process name is `claude`. + fakeClaude = pkgs.writeShellScriptBin "claude" '' + pass-broker get --item auto-item --reason "from claude" + ''; + sockProbe = pkgs.writers.writePython3Bin "sock-probe" { flakeIgnore = [ "E501" ]; } '' import json import socket @@ -136,7 +141,7 @@ pkgs.testers.runNixOSTest { users.users.darman.isNormalUser = true; users.users.eve.isNormalUser = true; - environment.systemPackages = [ pkgs.curl pkgs.jq tryGet sockProbe ]; + environment.systemPackages = [ pkgs.curl pkgs.jq tryGet sockProbe fakeClaude ]; systemd.tmpfiles.rules = [ "d /tmp/r 1777 root root -" ]; environment.etc = { @@ -201,6 +206,8 @@ pkgs.testers.runNixOSTest { start("a", "darman@jupiter") msg = wait_messages(1) assert "darman@jupiter" in msg["text"] and "vm test" in msg["text"], msg + assert "\nBy: darman via " in msg["text"], msg + assert "\nCommand: bash try-get a darman@jupiter\n" in msg["text"], msg assert msg["chat_id"] == 4242, msg press(button(msg, 0), sender=999) machine.sleep(2) @@ -275,7 +282,11 @@ pkgs.testers.runNixOSTest { with subtest("a request whose client already hung up is dropped without a prompt"): before = views() + # Frozen broker = the crash-loop case: the request waits in the socket + # while its client exits, and only then gets read. + machine.succeed("systemctl kill --signal=SIGSTOP pass-broker.service") machine.succeed("sock-probe ghost") + machine.succeed("systemctl kill --signal=SIGCONT pass-broker.service") journal_has("dropped HomeLab/root@jupiter: requester went away") machine.sleep(2) assert len(tg()["messages"]) == 6 @@ -290,6 +301,10 @@ pkgs.testers.runNixOSTest { ) assert "no answer within 30s" in err, err + with subtest("a request from under Claude Code is labelled as such"): + assert machine.succeed("su darman -c claude").strip() == "autopw" + journal_has('reason="from claude" by darman via Claude Code [bash claude]') + with subtest("other users are refused, and darman cannot read the session"): err = machine.fail("su eve -c 'pass-broker get --item auto-item --reason x' 2>&1") assert "uid not allowed" in err, err