feat(mars): pass-broker approval gateway for every host
A Telegram bot has a single getUpdates consumer, so a broker per host would split approval taps between them. mars now runs the gateway: the bot's only poller, relaying prompts and taps for terra's and titan's brokers over the tailnet (:8097) without ever seeing an item. Each broker authenticates with its own pass_broker_gateway_token; mars holds only the sha256, and the prompt is labelled with the host that token belongs to. The bot token and chat id move to mars and are dropped from the other hosts' sops files (terra.yaml also loses its leftover LibreChat keys and gains protonvpn_wg_private_key, which a later commit uses). Covered by checks.pass-broker-gateway (two nodes: labels, cancel, expiry, per-host token isolation, gateway down); the fakes are shared with checks.pass-broker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
use crate::config::TelegramConfig;
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::future::Future;
|
||||
use std::io::Read;
|
||||
@@ -7,9 +8,9 @@ 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.
|
||||
/// Approval prompts with Approve/Deny buttons. A bot has one getUpdates
|
||||
/// consumer, so exactly one process may own it: a host's broker in direct
|
||||
/// mode, or the gateway (gateway.rs) for every host.
|
||||
pub struct Telegram {
|
||||
http: reqwest::Client,
|
||||
/// Contains the token: never print it, and strip it from reqwest errors.
|
||||
@@ -18,6 +19,8 @@ pub struct Telegram {
|
||||
offset: AtomicI64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Verdict {
|
||||
Approved,
|
||||
Denied,
|
||||
@@ -25,6 +28,23 @@ pub enum Verdict {
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl Verdict {
|
||||
fn outcome(self) -> &'static str {
|
||||
match self {
|
||||
Verdict::Approved => "✅ approved",
|
||||
Verdict::Denied => "❌ denied",
|
||||
Verdict::Expired => "⌛ expired",
|
||||
Verdict::Cancelled => "🚫 cancelled: the requester went away",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An owner's tap on a live prompt's button.
|
||||
pub struct Tap {
|
||||
pub nonce: String,
|
||||
pub verdict: Verdict,
|
||||
}
|
||||
|
||||
impl Telegram {
|
||||
pub fn new(cfg: &TelegramConfig) -> Result<Self> {
|
||||
let token = std::fs::read_to_string(&cfg.token_file)
|
||||
@@ -60,16 +80,8 @@ impl Telegram {
|
||||
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}"));
|
||||
/// Sends the prompt; returns its message id.
|
||||
pub async fn prompt(&self, text: &str, nonce: &str) -> Result<i64> {
|
||||
let msg = self
|
||||
.call(
|
||||
"sendMessage",
|
||||
@@ -77,13 +89,84 @@ impl Telegram {
|
||||
"chat_id": self.chat_id,
|
||||
"text": text,
|
||||
"reply_markup": { "inline_keyboard": [[
|
||||
{ "text": "Approve", "callback_data": yes },
|
||||
{ "text": "Deny", "callback_data": no },
|
||||
{ "text": "Approve", "callback_data": format!("ok:{nonce}") },
|
||||
{ "text": "Deny", "callback_data": format!("no:{nonce}") },
|
||||
]]},
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let message_id = msg["message_id"].clone();
|
||||
msg["message_id"].as_i64().ok_or_else(|| anyhow!("sendMessage returned no message_id"))
|
||||
}
|
||||
|
||||
/// One long poll. Every tap is answered; the owner's taps on prompts
|
||||
/// `live` still knows are returned.
|
||||
pub async fn taps(&self, timeout_secs: u64, live: impl Fn(&str) -> bool) -> Result<Vec<Tap>> {
|
||||
let updates = self
|
||||
.call(
|
||||
"getUpdates",
|
||||
json!({
|
||||
"offset": self.offset.load(Ordering::SeqCst),
|
||||
"timeout": timeout_secs,
|
||||
"allowed_updates": ["callback_query"],
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let mut taps = vec![];
|
||||
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 tap = match data.split_once(':') {
|
||||
Some(("ok", n)) => Some((n, Verdict::Approved)),
|
||||
Some(("no", n)) => Some((n, Verdict::Denied)),
|
||||
_ => None,
|
||||
}
|
||||
.filter(|(n, _)| live(n));
|
||||
// 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 (&tap, from_owner) {
|
||||
(_, false) => "Not yours.",
|
||||
(None, true) => "Expired.",
|
||||
(Some(_), true) => "",
|
||||
};
|
||||
let _ = self
|
||||
.call("answerCallbackQuery", json!({ "callback_query_id": cq_id, "text": note }))
|
||||
.await;
|
||||
if let (Some((n, verdict)), true) = (tap, from_owner) {
|
||||
taps.push(Tap { nonce: n.to_string(), verdict });
|
||||
}
|
||||
}
|
||||
Ok(taps)
|
||||
}
|
||||
|
||||
/// Appends the outcome; without reply_markup this also drops the buttons.
|
||||
pub async fn conclude(&self, message_id: i64, text: &str, verdict: Verdict) {
|
||||
let _ = self
|
||||
.call(
|
||||
"editMessageText",
|
||||
json!({
|
||||
"chat_id": self.chat_id,
|
||||
"message_id": message_id,
|
||||
"text": format!("{text}\n\n{}", verdict.outcome()),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
/// Direct mode: prompt and poll in one call. Callers must not ask
|
||||
/// concurrently. `gone` resolving (the client hung up) withdraws it.
|
||||
pub async fn ask(
|
||||
&self,
|
||||
text: &str,
|
||||
timeout: Duration,
|
||||
mut gone: Pin<&mut impl Future<Output = ()>>,
|
||||
) -> Result<Verdict> {
|
||||
let nonce = nonce()?;
|
||||
let message_id = self.prompt(text, &nonce).await?;
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
let verdict = 'poll: loop {
|
||||
@@ -91,74 +174,29 @@ impl Telegram {
|
||||
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! {
|
||||
biased;
|
||||
_ = gone.as_mut() => break 'poll Verdict::Cancelled,
|
||||
r = poll => r,
|
||||
r = self.taps(left.as_secs().min(25), |n| n == nonce) => r,
|
||||
};
|
||||
let updates = match polled {
|
||||
Ok(u) => u,
|
||||
match polled {
|
||||
Ok(taps) => {
|
||||
if let Some(t) = taps.first() {
|
||||
break t.verdict;
|
||||
}
|
||||
}
|
||||
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;
|
||||
self.conclude(message_id, text, verdict).await;
|
||||
Ok(verdict)
|
||||
}
|
||||
}
|
||||
|
||||
fn nonce() -> Result<String> {
|
||||
pub 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())
|
||||
|
||||
Reference in New Issue
Block a user