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>
129 lines
4.3 KiB
Rust
129 lines
4.3 KiB
Rust
use crate::config::ApprovalConfig;
|
|
use crate::telegram::{Telegram, Verdict};
|
|
use anyhow::{anyhow, Context, Result};
|
|
use serde_json::{json, Value};
|
|
use std::future::Future;
|
|
use std::pin::Pin;
|
|
use std::time::{Duration, Instant};
|
|
|
|
/// Shows a prompt and waits for its verdict: via this broker's own bot, or
|
|
/// via the gateway that owns the shared one.
|
|
pub enum Approver {
|
|
Direct { tg: Telegram, host: String },
|
|
Gateway(GatewayClient),
|
|
}
|
|
|
|
pub struct GatewayClient {
|
|
http: reqwest::Client,
|
|
url: String,
|
|
token: String,
|
|
}
|
|
|
|
impl Approver {
|
|
pub fn new(cfg: &ApprovalConfig, host: &str) -> Result<Self> {
|
|
Ok(match cfg {
|
|
ApprovalConfig::Telegram(t) => {
|
|
Approver::Direct { tg: Telegram::new(t)?, host: host.to_string() }
|
|
}
|
|
ApprovalConfig::Gateway(g) => Approver::Gateway(GatewayClient {
|
|
http: reqwest::Client::builder().timeout(Duration::from_secs(40)).build()?,
|
|
url: g.url.trim_end_matches('/').to_string(),
|
|
token: std::fs::read_to_string(&g.token_file)
|
|
.with_context(|| format!("reading {}", g.token_file.display()))?
|
|
.trim()
|
|
.to_string(),
|
|
}),
|
|
})
|
|
}
|
|
|
|
/// `body` is the prompt without its "🔑 host:" header; the gateway adds
|
|
/// that itself, from the token.
|
|
pub async fn ask(
|
|
&self,
|
|
body: &str,
|
|
timeout: Duration,
|
|
gone: Pin<&mut impl Future<Output = ()>>,
|
|
) -> Result<Verdict> {
|
|
match self {
|
|
Approver::Direct { tg, host } => tg.ask(&format!("🔑 {host}: {body}"), timeout, gone).await,
|
|
Approver::Gateway(g) => g.ask(body, timeout, gone).await,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl GatewayClient {
|
|
async fn ask(
|
|
&self,
|
|
body: &str,
|
|
timeout: Duration,
|
|
mut gone: Pin<&mut impl Future<Output = ()>>,
|
|
) -> Result<Verdict> {
|
|
let resp: Value = self
|
|
.http
|
|
.post(format!("{}/ask", self.url))
|
|
.bearer_auth(&self.token)
|
|
.json(&json!({ "text": body, "timeout_secs": timeout.as_secs() }))
|
|
.send()
|
|
.await
|
|
.and_then(|r| r.error_for_status())
|
|
.map_err(|e| anyhow!("gateway: {}", e.without_url()))?
|
|
.json()
|
|
.await
|
|
.map_err(|e| anyhow!("gateway: {}", e.without_url()))?;
|
|
let id = resp["id"].as_str().ok_or_else(|| anyhow!("gateway returned no id"))?.to_string();
|
|
|
|
// The gateway expires the prompt itself; this only bounds a gateway
|
|
// that stopped answering.
|
|
let give_up = Instant::now() + timeout + Duration::from_secs(30);
|
|
while Instant::now() < give_up {
|
|
let polled = tokio::select! {
|
|
biased;
|
|
_ = gone.as_mut() => {
|
|
let _ = self
|
|
.http
|
|
.delete(format!("{}/ask/{id}", self.url))
|
|
.bearer_auth(&self.token)
|
|
.send()
|
|
.await;
|
|
return Ok(Verdict::Cancelled);
|
|
}
|
|
r = self.status(&id) => r,
|
|
};
|
|
match polled {
|
|
Ok(Some(v)) => return Ok(v),
|
|
Ok(None) => {}
|
|
Err(e) => {
|
|
eprintln!("{e:#}");
|
|
tokio::time::sleep(Duration::from_secs(2)).await;
|
|
}
|
|
}
|
|
}
|
|
Ok(Verdict::Expired)
|
|
}
|
|
|
|
/// None while pending.
|
|
async fn status(&self, id: &str) -> Result<Option<Verdict>> {
|
|
let resp = self
|
|
.http
|
|
.get(format!("{}/ask/{id}?wait=25", self.url))
|
|
.bearer_auth(&self.token)
|
|
.send()
|
|
.await
|
|
.map_err(|e| anyhow!("gateway: {}", e.without_url()))?;
|
|
// A restarted gateway has forgotten the prompt.
|
|
if resp.status() == reqwest::StatusCode::NOT_FOUND {
|
|
return Ok(Some(Verdict::Expired));
|
|
}
|
|
let v: Value = resp
|
|
.error_for_status()
|
|
.map_err(|e| anyhow!("gateway: {}", e.without_url()))?
|
|
.json()
|
|
.await
|
|
.map_err(|e| anyhow!("gateway: {}", e.without_url()))?;
|
|
match v["status"].as_str() {
|
|
Some("pending") => Ok(None),
|
|
_ => Ok(Some(serde_json::from_value(v["status"].clone())?)),
|
|
}
|
|
}
|
|
}
|