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:
2026-10-21 11:34:19 +02:00
co-authored by Claude Opus 5.5
parent 760e353335
commit e95726d69c
24 changed files with 1164 additions and 250 deletions
+154 -1
View File
@@ -14,6 +14,56 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
]
[[package]]
name = "base64"
version = "0.22.1"
@@ -32,6 +82,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -73,10 +132,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"cpufeatures 0.3.1",
"rand_core",
]
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "cpufeatures"
version = "0.3.1"
@@ -86,6 +154,26 @@ dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "displaydoc"
version = "0.2.7"
@@ -155,6 +243,16 @@ dependencies = [
"slab",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.17"
@@ -221,6 +319,12 @@ version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "1.12.0"
@@ -233,6 +337,7 @@ dependencies = [
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
@@ -431,12 +536,24 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mime"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mio"
version = "1.2.4"
@@ -459,9 +576,11 @@ name = "pass-broker"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"reqwest",
"serde",
"serde_json",
"sha2",
"tokio",
]
@@ -740,6 +859,17 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -752,6 +882,17 @@ dependencies = [
"serde",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest",
]
[[package]]
name = "shlex"
version = "2.0.1"
@@ -976,6 +1117,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
@@ -1006,6 +1153,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "want"
version = "0.3.2"
+2
View File
@@ -5,9 +5,11 @@ edition = "2021"
[dependencies]
anyhow = "1"
axum = { version = "0.8", default-features = false, features = ["http1", "json", "query", "tokio"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "process", "io-util"] }
[profile.release]
+128
View File
@@ -0,0 +1,128 @@
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())?)),
}
}
}
+39 -4
View File
@@ -13,11 +13,19 @@ pub struct Config {
pub session_dir: PathBuf,
pub pat_file: PathBuf,
pub approval_timeout_secs: u64,
pub telegram: TelegramConfig,
pub approval: ApprovalConfig,
/// First match wins; no match means deny.
pub rules: Vec<Rule>,
}
/// Who shows the prompt: this broker's own bot, or the shared gateway.
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalConfig {
Telegram(TelegramConfig),
Gateway(GatewayClientConfig),
}
#[derive(Deserialize)]
pub struct TelegramConfig {
pub api_base: String,
@@ -25,6 +33,35 @@ pub struct TelegramConfig {
pub chat_id_file: PathBuf,
}
#[derive(Deserialize)]
pub struct GatewayClientConfig {
pub url: String,
pub token_file: PathBuf,
}
/// Written by services/identity/pass-broker-gateway.nix; path in
/// $PASS_BROKER_GATEWAY_CONFIG.
#[derive(Deserialize)]
pub struct GatewayConfig {
pub listen: String,
pub telegram: TelegramConfig,
/// Hashes only: the gateway host never holds a broker's token.
pub hosts: Vec<GatewayHost>,
pub max_timeout_secs: u64,
}
#[derive(Deserialize)]
pub struct GatewayHost {
pub name: String,
pub token_sha256: String,
}
pub fn load<T: serde::de::DeserializeOwned>(var: &str) -> Result<T> {
let path = std::env::var(var).with_context(|| format!("{var} unset"))?;
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {path}"))?;
serde_json::from_str(&text).with_context(|| format!("parsing {path}"))
}
#[derive(Deserialize)]
pub struct Rule {
pub vault: Option<String>,
@@ -45,9 +82,7 @@ pub enum Approval {
impl Config {
pub fn load() -> Result<Self> {
let path = std::env::var("PASS_BROKER_CONFIG").context("PASS_BROKER_CONFIG unset")?;
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {path}"))?;
serde_json::from_str(&text).with_context(|| format!("parsing {path}"))
load("PASS_BROKER_CONFIG")
}
pub fn rule_for(&self, vault: &str, item: &str) -> Option<&Rule> {
+8 -8
View File
@@ -1,7 +1,8 @@
use crate::config::{Approval, Config};
use crate::pass::Pass;
use crate::proto::{Reply, Request};
use crate::telegram::{Telegram, Verdict};
use crate::approver::Approver;
use crate::telegram::Verdict;
use anyhow::{bail, Context, Result};
use std::collections::HashMap;
use std::future::Future;
@@ -18,10 +19,10 @@ struct State {
cfg: Config,
uids: Vec<u32>,
pass: Pass,
tg: Telegram,
approver: Approver,
/// "vault\0item" -> when the last approval stops covering it.
grants: Mutex<HashMap<String, Instant>>,
/// One prompt at a time; Telegram::ask polls getUpdates itself.
/// One prompt per host at a time; direct mode polls getUpdates in ask.
asking: Mutex<()>,
}
@@ -30,7 +31,7 @@ pub async fn run() -> Result<()> {
let state = Arc::new(State {
uids: cfg.allowed_uids()?,
pass: Pass::new(&cfg),
tg: Telegram::new(&cfg.telegram)?,
approver: Approver::new(&cfg.approval, &cfg.host)?,
grants: Mutex::new(HashMap::new()),
asking: Mutex::new(()),
cfg,
@@ -161,9 +162,8 @@ async fn decide(
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}\nBy: {by}\nCommand: {command}\nChain: {chain}\n{grant}",
host = state.cfg.host,
let body = format!(
"{vault} / {item} ({field})\nReason: {reason}\nBy: {by}\nCommand: {command}\nChain: {chain}\n{grant}",
item = req.item,
field = req.field,
reason = req.reason,
@@ -172,7 +172,7 @@ async fn decide(
chain = who.chain,
);
let timeout = Duration::from_secs(state.cfg.approval_timeout_secs);
match state.tg.ask(&text, timeout, gone).await? {
match state.approver.ask(&body, timeout, gone).await? {
Verdict::Approved => {
if rule.grant_minutes > 0 {
let until = Instant::now() + Duration::from_secs(rule.grant_minutes * 60);
+207
View File
@@ -0,0 +1,207 @@
//! `pass-broker gateway`: the one owner of the approval bot, shared by every
//! host's broker over the tailnet. It sees prompts and verdicts, never items.
use crate::config::{load, GatewayConfig};
use crate::telegram::{nonce, Telegram, Verdict};
use anyhow::{Context, Result};
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::routing::{get, post};
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use tokio::sync::watch;
struct Prompt {
host: String,
text: String,
message_id: i64,
deadline: Instant,
verdict: watch::Sender<Option<Verdict>>,
decided_at: Option<Instant>,
}
struct Gateway {
tg: Telegram,
/// sha256(token) -> host name.
hosts: HashMap<String, String>,
max_timeout: Duration,
prompts: Mutex<HashMap<String, Prompt>>,
}
pub async fn run() -> Result<()> {
let cfg: GatewayConfig = load("PASS_BROKER_GATEWAY_CONFIG")?;
let gw = Arc::new(Gateway {
tg: Telegram::new(&cfg.telegram)?,
hosts: cfg.hosts.into_iter().map(|h| (h.token_sha256.to_lowercase(), h.name)).collect(),
max_timeout: Duration::from_secs(cfg.max_timeout_secs),
prompts: Mutex::new(HashMap::new()),
});
let poller = gw.clone();
tokio::spawn(async move {
loop {
let live = |n: &str| {
poller.prompts.lock().unwrap().get(n).is_some_and(|p| p.decided_at.is_none())
};
match poller.tg.taps(25, live).await {
Ok(taps) => {
for t in taps {
poller.decide(&t.nonce, t.verdict).await;
}
}
Err(e) => {
eprintln!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
}
});
let sweeper = gw.clone();
tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
let now = Instant::now();
let expired: Vec<String> = {
let mut map = sweeper.prompts.lock().unwrap();
// Decided prompts linger so a broker polling late still gets its verdict.
map.retain(|_, p| p.decided_at.is_none_or(|t| now - t < Duration::from_secs(600)));
map.iter()
.filter(|(_, p)| p.decided_at.is_none() && p.deadline <= now)
.map(|(id, _)| id.clone())
.collect()
};
for id in expired {
sweeper.decide(&id, Verdict::Expired).await;
}
}
});
let app = Router::new()
.route("/ask", post(ask))
.route("/ask/{id}", get(status).delete(cancel))
.with_state(gw);
let listener = tokio::net::TcpListener::bind(&cfg.listen)
.await
.with_context(|| format!("binding {}", cfg.listen))?;
eprintln!("pass-broker gateway listening on {}", cfg.listen);
axum::serve(listener, app).await?;
Ok(())
}
impl Gateway {
fn host(&self, headers: &HeaderMap) -> Option<String> {
let token = headers.get("authorization")?.to_str().ok()?.strip_prefix("Bearer ")?;
let hash: String =
Sha256::digest(token.trim().as_bytes()).iter().map(|b| format!("{b:02x}")).collect();
self.hosts.get(&hash).cloned()
}
/// First verdict wins; later ones are no-ops.
async fn decide(&self, id: &str, verdict: Verdict) {
let decided = {
let mut map = self.prompts.lock().unwrap();
match map.get_mut(id) {
Some(p) if p.decided_at.is_none() => {
p.decided_at = Some(Instant::now());
p.verdict.send_replace(Some(verdict));
Some((p.host.clone(), p.message_id, p.text.clone()))
}
_ => None,
}
};
if let Some((host, message_id, text)) = decided {
eprintln!("{host}: {id} {verdict:?}");
self.tg.conclude(message_id, &text, verdict).await;
}
}
/// Another host's prompt looks exactly like a missing one.
fn owns(&self, id: &str, host: &str) -> bool {
self.prompts.lock().unwrap().get(id).is_some_and(|p| p.host == host)
}
}
#[derive(Deserialize)]
struct AskBody {
text: String,
timeout_secs: u64,
}
async fn ask(
State(gw): State<Arc<Gateway>>,
headers: HeaderMap,
Json(body): Json<AskBody>,
) -> Result<Json<Value>, StatusCode> {
let host = gw.host(&headers).ok_or(StatusCode::UNAUTHORIZED)?;
let id = nonce().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Labelled from the token, not the request, so no host can pose as another.
let text = format!("🔑 {host}: {}", body.text);
let message_id = gw.tg.prompt(&text, &id).await.map_err(|e| {
eprintln!("{host}: {e:#}");
StatusCode::BAD_GATEWAY
})?;
let timeout = Duration::from_secs(body.timeout_secs).min(gw.max_timeout);
let (verdict, _) = watch::channel(None);
gw.prompts.lock().unwrap().insert(
id.clone(),
Prompt {
host: host.clone(),
text,
message_id,
deadline: Instant::now() + timeout,
verdict,
decided_at: None,
},
);
eprintln!("{host}: {id} asked");
Ok(Json(json!({ "id": id })))
}
#[derive(Deserialize)]
struct Wait {
wait: Option<u64>,
}
async fn status(
State(gw): State<Arc<Gateway>>,
headers: HeaderMap,
Path(id): Path<String>,
Query(q): Query<Wait>,
) -> Result<Json<Value>, StatusCode> {
let host = gw.host(&headers).ok_or(StatusCode::UNAUTHORIZED)?;
let mut rx = {
let map = gw.prompts.lock().unwrap();
match map.get(&id) {
Some(p) if p.host == host => p.verdict.subscribe(),
_ => return Err(StatusCode::NOT_FOUND),
}
};
let wait = Duration::from_secs(q.wait.unwrap_or(0).min(30));
let verdict = match tokio::time::timeout(wait, rx.wait_for(Option::is_some)).await {
Ok(Ok(v)) => *v,
_ => None,
};
Ok(Json(match verdict {
Some(v) => json!({ "status": v }),
None => json!({ "status": "pending" }),
}))
}
async fn cancel(
State(gw): State<Arc<Gateway>>,
headers: HeaderMap,
Path(id): Path<String>,
) -> StatusCode {
let Some(host) = gw.host(&headers) else { return StatusCode::UNAUTHORIZED };
if !gw.owns(&id, &host) {
return StatusCode::NOT_FOUND;
}
gw.decide(&id, Verdict::Cancelled).await;
StatusCode::NO_CONTENT
}
+7 -2
View File
@@ -3,11 +3,14 @@
//!
//! The daemon runs as its own system user and holds the only pass-cli session
//! (an agent PAT), so nothing running as darman can read it directly. Clients
//! talk to it over a unix socket; see services/identity/pass-broker.nix.
//! talk to it over a unix socket; see services/identity/pass-broker.nix. The
//! prompt comes from its own bot or from the shared gateway (gateway.rs).
mod approver;
mod client;
mod config;
mod daemon;
mod gateway;
mod pass;
mod proto;
mod telegram;
@@ -15,13 +18,15 @@ mod telegram;
use anyhow::Result;
const USAGE: &str = "usage: pass-broker get --item <title> --reason <why> [--vault <name>] [--field <name>]
pass-broker daemon";
pass-broker daemon
pass-broker gateway";
#[tokio::main]
async fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
match args.first().map(String::as_str) {
Some("daemon") => daemon::run().await,
Some("gateway") => gateway::run().await,
Some("get") => client::get(&args[1..]).await,
_ => {
eprintln!("{USAGE}");
+108 -70
View File
@@ -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())