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:
2026-10-16 01:48:46 +02:00
co-authored by Claude Opus 5.5
parent e6ceacb63b
commit 3dccafe2b8
22 changed files with 2645 additions and 13 deletions
+164
View File
@@ -0,0 +1,164 @@
use crate::config::TelegramConfig;
use anyhow::{anyhow, bail, Context, Result};
use serde_json::{json, Value};
use std::future::Future;
use std::io::Read;
use std::pin::Pin;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::{Duration, Instant};
/// Approval prompts with Approve/Deny buttons. The bot must be dedicated to
/// the broker: getUpdates has a single consumer, so a shared bot would see
/// (or swallow) the other's callbacks.
pub struct Telegram {
http: reqwest::Client,
/// Contains the token: never print it, and strip it from reqwest errors.
base: String,
chat_id: i64,
offset: AtomicI64,
}
pub enum Verdict {
Approved,
Denied,
Expired,
Cancelled,
}
impl Telegram {
pub fn new(cfg: &TelegramConfig) -> Result<Self> {
let token = std::fs::read_to_string(&cfg.token_file)
.with_context(|| format!("reading {}", cfg.token_file.display()))?;
let chat_id = std::fs::read_to_string(&cfg.chat_id_file)
.with_context(|| format!("reading {}", cfg.chat_id_file.display()))?
.trim()
.parse()
.context("telegram chat id is not a number")?;
Ok(Self {
http: reqwest::Client::builder().timeout(Duration::from_secs(40)).build()?,
base: format!("{}/bot{}", cfg.api_base.trim_end_matches('/'), token.trim()),
chat_id,
offset: AtomicI64::new(0),
})
}
async fn call(&self, method: &str, body: Value) -> Result<Value> {
let resp = self
.http
.post(format!("{}/{method}", self.base))
.json(&body)
.send()
.await
.map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?;
let v: Value = resp
.json()
.await
.map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?;
if v["ok"] != json!(true) {
bail!("telegram {method}: {}", v["description"]);
}
Ok(v["result"].clone())
}
/// Callers must not ask concurrently: each call polls getUpdates itself.
/// `gone` resolving (the client hung up) withdraws the prompt.
pub async fn ask(
&self,
text: &str,
timeout: Duration,
mut gone: Pin<&mut impl Future<Output = ()>>,
) -> Result<Verdict> {
let nonce = nonce()?;
let (yes, no) = (format!("ok:{nonce}"), format!("no:{nonce}"));
let msg = self
.call(
"sendMessage",
json!({
"chat_id": self.chat_id,
"text": text,
"reply_markup": { "inline_keyboard": [[
{ "text": "Approve", "callback_data": yes },
{ "text": "Deny", "callback_data": no },
]]},
}),
)
.await?;
let message_id = msg["message_id"].clone();
let deadline = Instant::now() + timeout;
let verdict = 'poll: loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
break Verdict::Expired;
}
let poll = self.call(
"getUpdates",
json!({
"offset": self.offset.load(Ordering::SeqCst),
"timeout": left.as_secs().min(25),
"allowed_updates": ["callback_query"],
}),
);
let polled = tokio::select! {
r = poll => r,
_ = gone.as_mut() => break 'poll Verdict::Cancelled,
};
let updates = match polled {
Ok(u) => u,
Err(e) => {
eprintln!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
};
for u in updates.as_array().into_iter().flatten() {
if let Some(id) = u["update_id"].as_i64() {
self.offset.fetch_max(id + 1, Ordering::SeqCst);
}
let cq = &u["callback_query"];
let Some(cq_id) = cq["id"].as_str() else { continue };
let data = cq["data"].as_str().unwrap_or("");
let mine = data == yes || data == no;
// The button lives in our chat, but the bot can be added
// elsewhere and a forwarded message keeps its buttons.
let from_owner = cq["from"]["id"].as_i64() == Some(self.chat_id);
let note = match (mine, from_owner) {
(_, false) => "Not yours.",
(false, true) => "Expired.",
(true, true) => "",
};
let _ = self
.call("answerCallbackQuery", json!({ "callback_query_id": cq_id, "text": note }))
.await;
if mine && from_owner {
break 'poll if data == yes { Verdict::Approved } else { Verdict::Denied };
}
}
};
let outcome = match verdict {
Verdict::Approved => "✅ approved",
Verdict::Denied => "❌ denied",
Verdict::Expired => "⌛ expired",
Verdict::Cancelled => "🚫 cancelled: the requester went away",
};
// Without reply_markup this also removes the buttons.
let _ = self
.call(
"editMessageText",
json!({
"chat_id": self.chat_id,
"message_id": message_id,
"text": format!("{text}\n\n{outcome}"),
}),
)
.await;
Ok(verdict)
}
}
fn nonce() -> Result<String> {
let mut buf = [0u8; 16];
std::fs::File::open("/dev/urandom")?.read_exact(&mut buf)?;
Ok(buf.iter().map(|b| format!("{b:02x}")).collect())
}