feat(terra): pass-broker for Telegram-approved Proton Pass access
A Rust daemon running as its own system user holds terra's only pass-cli session, an agent PAT scoped to the HomeLab vaults. `pass-broker get` asks it for an item; per-item rules decide auto/ask/deny, and "ask" sends a Telegram prompt that only darman's account can approve (10-min grant for darman@*/root@*). Requests whose client is gone are dropped or withdrawn, and the client gives up after 30s without an answer. scripts/deploy uses the broker exclusively when its socket exists. Covered by checks.pass-broker (fake pass-cli + Telegram). Secrets added for all hosts; only terra runs the broker so far. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
use crate::config::{Approval, Config};
|
||||
use crate::pass::Pass;
|
||||
use crate::proto::{Reply, Request};
|
||||
use crate::telegram::{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<u32>,
|
||||
pass: Pass,
|
||||
tg: Telegram,
|
||||
/// "vault\0item" -> when the last approval stops covering it.
|
||||
grants: Mutex<HashMap<String, Instant>>,
|
||||
/// One prompt at a time; Telegram::ask polls getUpdates itself.
|
||||
asking: Mutex<()>,
|
||||
}
|
||||
|
||||
pub async fn run() -> Result<()> {
|
||||
let cfg = Config::load()?;
|
||||
let state = Arc::new(State {
|
||||
uids: cfg.allowed_uids()?,
|
||||
pass: Pass::new(&cfg),
|
||||
tg: Telegram::new(&cfg.telegram)?,
|
||||
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<UnixListener> {
|
||||
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<State>, 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(requester) {
|
||||
Some(who) if !closed(&rd) => who,
|
||||
_ => {
|
||||
eprintln!("dropped {vault}/{}: requester went away", req.item);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
eprintln!(
|
||||
"request {vault}/{} ({}) uid={} reason={:?} from {}",
|
||||
req.item, req.field, cred.uid(), req.reason, who.from
|
||||
);
|
||||
|
||||
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 { .. } => {}
|
||||
}
|
||||
send(&mut wr, reply).await
|
||||
}
|
||||
|
||||
async fn decide(
|
||||
state: &State,
|
||||
wr: &mut OwnedWriteHalf,
|
||||
mut gone: Pin<&mut impl Future<Output = ()>>,
|
||||
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<String, Instant>| 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;
|
||||
let _asking = tokio::select! {
|
||||
guard = state.asking.lock() => guard,
|
||||
_ = gone.as_mut() => bail!("requester went away"),
|
||||
};
|
||||
// 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 text = format!(
|
||||
"🔑 {host}: {vault} / {item} ({field})\nReason: {reason}\nFrom: {from}\nChain: {chain}\n{grant}",
|
||||
host = state.cfg.host,
|
||||
item = req.item,
|
||||
field = req.field,
|
||||
reason = req.reason,
|
||||
from = who.from,
|
||||
chain = who.chain,
|
||||
);
|
||||
let timeout = Duration::from_secs(state.cfg.approval_timeout_secs);
|
||||
match state.tg.ask(&text, 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. Informational only: any process of the
|
||||
/// same uid can make itself look like anything.
|
||||
struct Requester {
|
||||
from: 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,
|
||||
}
|
||||
}
|
||||
Some(Requester { from, chain: names.join(" ← ") })
|
||||
}
|
||||
|
||||
fn ppid(pid: i32) -> Option<i32> {
|
||||
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()
|
||||
}
|
||||
|
||||
fn truncate(s: &str, max: usize) -> String {
|
||||
match s.char_indices().nth(max) {
|
||||
Some((i, _)) => format!("{}…", &s[..i]),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user