use crate::config::Config; use anyhow::{anyhow, bail, Context, Result}; use std::path::PathBuf; use std::process::Stdio; use tokio::process::Command; use tokio::sync::Mutex; /// The broker's own pass-cli session. pass-cli calls are serialised: they /// share one session dir and a re-login mid-lookup would race. pub struct Pass { bin: String, session_dir: PathBuf, pat_file: PathBuf, lock: Mutex<()>, } impl Pass { pub fn new(cfg: &Config) -> Self { Self { bin: cfg.pass_cli.clone(), session_dir: cfg.session_dir.clone(), pat_file: cfg.pat_file.clone(), lock: Mutex::new(()), } } pub async fn ensure_session(&self) -> Result<()> { let _g = self.lock.lock().await; self.ensure_session_locked().await } async fn ensure_session_locked(&self) -> Result<()> { if self.run(&["info"], &[]).await.is_ok() { return Ok(()); } eprintln!("no pass-cli session, logging in with the PAT"); let pat = std::fs::read_to_string(&self.pat_file) .with_context(|| format!("reading {}", self.pat_file.display()))?; let _ = self.run(&["logout", "--force"], &[]).await; // Via env, not `--pat`: argv is world-readable in /proc. self.run(&["login"], &[("PROTON_PASS_PERSONAL_ACCESS_TOKEN", pat.trim())]) .await .context("pass-cli login")?; Ok(()) } pub async fn get(&self, vault: &str, title: &str, field: &str, reason: &str) -> Result { let _g = self.lock.lock().await; self.ensure_session_locked().await?; // `item view --item-title` has no state filter and can return a // trashed duplicate, so resolve the id among active items first. let list = self .run( &["item", "list", "--vault-name", vault, "--filter-state", "active", "--output", "human"], &[], ) .await?; let id = list .lines() .find_map(|l| { // - [ITEM_ID]: the title (state=Active) let rest = l.strip_prefix("- [")?; let (id, rest) = rest.split_once("]: ")?; let t = match rest.rfind(" (state=") { Some(i) if rest.ends_with(')') => &rest[..i], _ => rest, }; (t == title).then(|| id.to_string()) }) .ok_or_else(|| anyhow!("no active item {title:?} in vault {vault:?}"))?; let out = self .run( &["item", "view", "--vault-name", vault, "--item-id", &id, "--field", field, "--output", "human"], &[("PROTON_PASS_AGENT_REASON", reason)], ) .await?; let value = out.lines().next().unwrap_or("").to_string(); if value.is_empty() { bail!("{title:?} has an empty {field} field"); } Ok(value) } async fn run(&self, args: &[&str], env: &[(&str, &str)]) -> Result { let out = Command::new(&self.bin) .args(args) .envs(env.iter().copied()) .env("PROTON_PASS_SESSION_DIR", &self.session_dir) .stdin(Stdio::null()) .kill_on_drop(true) .output() .await .with_context(|| format!("running {}", self.bin))?; if !out.status.success() { let err = String::from_utf8_lossy(&out.stderr); bail!("pass-cli {} failed ({}): {}", args[0], out.status, err.trim()); } Ok(String::from_utf8(out.stdout)?) } }