use crate::config::{Approval, Config}; use crate::pass::Pass; use crate::proto::{Reply, Request}; use crate::approver::Approver; use crate::telegram::Verdict; use anyhow::{bail, Context, Result}; use std::collections::HashMap; use std::future::Future; use std::os::fd::FromRawFd; use std::pin::Pin; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf}; use tokio::net::{UnixListener, UnixStream}; use tokio::sync::Mutex; struct State { cfg: Config, uids: Vec, pass: Pass, approver: Approver, /// "vault\0item" -> when the last approval stops covering it. grants: Mutex>, /// One prompt per host at a time; direct mode polls getUpdates in ask. asking: Mutex<()>, } pub async fn run() -> Result<()> { let cfg = Config::load()?; let state = Arc::new(State { uids: cfg.allowed_uids()?, pass: Pass::new(&cfg), approver: Approver::new(&cfg.approval, &cfg.host)?, grants: Mutex::new(HashMap::new()), asking: Mutex::new(()), cfg, }); // Not fatal: a stale PAT should show up in the journal, not stop the socket. if let Err(e) = state.pass.ensure_session().await { eprintln!("initial login failed: {e:#}"); } let listener = listener()?; eprintln!("pass-broker ready"); loop { let (stream, _) = listener.accept().await?; let state = state.clone(); tokio::spawn(async move { if let Err(e) = handle(state, stream).await { eprintln!("connection: {e:#}"); } }); } } /// From pass-broker.socket. The socket is 0666; access control is the peer /// uid check in handle(), so a new client needs no re-login for a group. fn listener() -> Result { let ours = std::env::var("LISTEN_PID").ok() == Some(std::process::id().to_string()); if !ours || std::env::var("LISTEN_FDS").ok().as_deref() != Some("1") { bail!("expected exactly one socket from systemd (pass-broker.socket)"); } let l = unsafe { std::os::unix::net::UnixListener::from_raw_fd(3) }; l.set_nonblocking(true)?; Ok(UnixListener::from_std(l)?) } async fn handle(state: Arc, stream: UnixStream) -> Result<()> { let cred = stream.peer_cred()?; let (mut rd, mut wr) = stream.into_split(); // Read before refusing, or the client's write hits a closed socket and // it reports EPIPE instead of the reason. let mut line = String::new(); BufReader::new((&mut rd).take(64 * 1024)).read_line(&mut line).await?; if !state.uids.contains(&cred.uid()) { eprintln!("refused uid {}", cred.uid()); return send(&mut wr, Reply::Error { error: "uid not allowed".into() }).await; } let req: Request = serde_json::from_str(&line).context("bad request")?; 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(|pid| requester(pid, cred.uid())) { Some(who) if !closed(&rd) => who, _ => { eprintln!("dropped {vault}/{}: requester went away", req.item); return Ok(()); } }; eprintln!( "request {vault}/{} ({}) reason={:?} by {}", req.item, req.field, req.reason, who.summary() ); let gone = client_gone(&rd); tokio::pin!(gone); let reply = match decide(&state, &mut wr, gone.as_mut(), &vault, &req, &who).await { Ok(()) if closed(&rd) => Reply::Error { error: "requester went away".into() }, Ok(()) => { let reason = format!("{} (pass-broker on {})", req.reason, state.cfg.host); match state.pass.get(&vault, &req.item, &req.field, &reason).await { Ok(value) => Reply::Ok { value }, Err(e) => Reply::Error { error: format!("{e:#}") }, } } Err(e) => Reply::Error { error: format!("{e:#}") }, }; match &reply { Reply::Ok { .. } => eprintln!("served {vault}/{}", req.item), Reply::Error { error } => eprintln!("refused {vault}/{}: {error}", req.item), Reply::Pending { .. } => {} } if closed(&rd) { return Ok(()); } send(&mut wr, reply).await } async fn decide( state: &State, wr: &mut OwnedWriteHalf, mut gone: Pin<&mut impl Future>, vault: &str, req: &Request, who: &Requester, ) -> Result<()> { let Some(rule) = state.cfg.rule_for(vault, &req.item) else { bail!("no rule allows {vault}/{}", req.item); }; match rule.approval { Approval::Deny => bail!("policy denies {vault}/{}", req.item), Approval::Auto => return Ok(()), Approval::Ask => {} } let key = format!("{vault}\0{}", req.item); let granted = |grants: &HashMap| grants.get(&key).is_some_and(|t| *t > Instant::now()); if granted(&*state.grants.lock().await) { eprintln!("covered by an earlier approval"); return Ok(()); } // 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! { 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) { return Ok(()); } let grant = match rule.grant_minutes { 0 => "Approves this request only.".to_string(), n => format!("Approving covers further requests for {n} min."), }; let body = format!( "{vault} / {item} ({field})\nReason: {reason}\nBy: {by}\nCommand: {command}\nChain: {chain}\n{grant}", item = req.item, field = req.field, reason = req.reason, by = who.who, command = who.command, chain = who.chain, ); let timeout = Duration::from_secs(state.cfg.approval_timeout_secs); match state.approver.ask(&body, timeout, gone).await? { Verdict::Approved => { if rule.grant_minutes > 0 { let until = Instant::now() + Duration::from_secs(rule.grant_minutes * 60); state.grants.lock().await.insert(key, until); } Ok(()) } Verdict::Denied => bail!("denied on Telegram"), Verdict::Expired => bail!("no answer on Telegram within {}s", timeout.as_secs()), Verdict::Cancelled => bail!("requester went away"), } } /// Resolves once the client hangs up. It sends nothing after its request, so /// readable means EOF; stray bytes are discarded. async fn client_gone(rd: &OwnedReadHalf) { while rd.readable().await.is_ok() { if closed(rd) { return; } } } fn closed(rd: &OwnedReadHalf) -> bool { match rd.try_read(&mut [0u8; 64]) { Ok(0) => true, Ok(_) => false, Err(e) => e.kind() != std::io::ErrorKind::WouldBlock, } } async fn send(wr: &mut OwnedWriteHalf, reply: Reply) -> Result<()> { let mut line = serde_json::to_string(&reply)?; line.push('\n'); wr.write_all(line.as_bytes()).await?; Ok(()) } /// 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 { /// "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, } impl Requester { fn summary(&self) -> String { format!("{} [{}] chain: {}", self.who, self.command, self.chain) } } /// 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 ')': // 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 { match s.char_indices().nth(max) { Some((i, _)) => format!("{}…", &s[..i]), 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"); } }