feat(terra): pass-broker prompts say who asked

Prompts and the journal now show "darman via Claude Code" (a `claude`
ancestor) or the terminal holding the tty, plus the caller's command with
store/profile paths cut to program names, and the process chain. It is
a hint, not identity: anything running as darman can fake it.

A client that has already hung up now always loses the race against the
prompt lock and Telegram polling, so it can no longer get a prompt, and
gone clients get no reply (no more EPIPE noise). The ghost-request test
freezes the broker to reproduce the queued-while-restarting case exactly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 02:12:04 +02:00
co-authored by Claude Opus 5.5
parent 3dccafe2b8
commit 8c0c2822c6
3 changed files with 128 additions and 38 deletions
+110 -36
View File
@@ -81,7 +81,7 @@ async fn handle(state: Arc<State>, 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<State>, 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<State>, 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<Requester> {
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<i32> {
/// None when the client has already exited.
fn requester(pid: i32, uid: u32) -> Option<Requester> {
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::<Vec<_>>().join(" ← ");
Some(Requester { who: format!("{} via {via}", user_name(uid)), command, chain })
}
struct Stat {
ppid: i32,
tty: i32,
}
fn stat(pid: i32) -> Option<Stat> {
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");
}
}
+2 -1
View File
@@ -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,