diff --git a/CLAUDE.md b/CLAUDE.md index 8349222..5677b2e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -54,10 +54,14 @@ empty password, so the script resolves the title among `--filter-state active` i first; a plain `pass-cli item view --item-title` silently returns the trashed copy and you get an interactive prompt with no explanation. -On terra the values come from **pass-broker** (`services/identity/pass-broker.nix`), not -from anyone's own pass-cli session: it runs as its own user with an agent PAT scoped to -the HomeLab vaults and releases an item only after a tap on its Telegram bot. When the -socket exists, deploy uses it exclusively; a refused tap falls back to the interactive prompt. +On terra/titan the values come from **pass-broker** (`services/identity/pass-broker.nix`), +not from anyone's own pass-cli session: it runs as its own user with an agent PAT scoped to +the HomeLab vaults and releases an item only after a Telegram tap. Prompts go through the +**gateway on mars** (`hosts/mars/pass-broker-gateway.nix`, tailnet :8097), the bot's only +`getUpdates` consumer: a second poller would split the taps. A new host gets its own +`pass_broker_gateway_token` in its sops file and that token's sha256 in the gateway's +`hosts`. When the socket exists, deploy uses it exclusively; a refused tap falls back to the +interactive prompt. **Claude: fetch Proton Pass items only via `pass-broker get --item --reason <why>`**, never `pass-cli login` yourself, and never print a value you fetched. Values go into variables or pipes, as `scripts/deploy` does. @@ -91,6 +95,9 @@ nix build .#checks.x86_64-linux.luna-sites -L # VM test of pass-broker with fake pass-cli + Telegram: approve/deny/expiry, # grants, policy, uid check nix build .#checks.x86_64-linux.pass-broker -L +# two-node VM test of the gateway on mars with a broker using it: labels, +# cancel, expiry, per-host token isolation, gateway down +nix build .#checks.x86_64-linux.pass-broker-gateway -L ``` `checks.kexec-local` is the only way to exercise `kexec-local` at all: it jumps the diff --git a/flake.nix b/flake.nix index d9bc8eb..b2b4d01 100644 --- a/flake.nix +++ b/flake.nix @@ -553,6 +553,12 @@ pass-broker = import ./services/identity/pass-broker-test.nix { pkgs = nixpkgs.legacyPackages.${system}; }; + + # Two-node test of the approval gateway (mars) with a broker using it: + # nix build .#checks.x86_64-linux.pass-broker-gateway -L + pass-broker-gateway = import ./services/identity/pass-broker-gateway-test.nix { + pkgs = nixpkgs.legacyPackages.${system}; + }; }; # `nix develop` — hot-reload loop for dotfiles/quickshell. diff --git a/hosts/mars/configuration.nix b/hosts/mars/configuration.nix index 2bd414c..a05b43f 100644 --- a/hosts/mars/configuration.nix +++ b/hosts/mars/configuration.nix @@ -13,6 +13,7 @@ ./honcho-console.nix # web console for it, tailnet-only on :8095 ./livesync-bridge.nix ./luna-sites.nix # luna's LAN web apps: http://mars.sol/<name>/ + ./pass-broker-gateway.nix # Telegram approvals for every host's pass-broker, tailnet :8097 ../../common.nix # shared base: user / ssh / nix / firewall ../../services/containers.nix ../../services/vpn/tailscale.nix diff --git a/hosts/mars/pass-broker-gateway.nix b/hosts/mars/pass-broker-gateway.nix new file mode 100644 index 0000000..6c7aea2 --- /dev/null +++ b/hosts/mars/pass-broker-gateway.nix @@ -0,0 +1,25 @@ +{ config, ... }: + +# Approval gateway for every host's pass-broker +# (services/identity/pass-broker-gateway.nix): one Telegram bot and one chat. +# Not Hermes' bot: a bot has one getUpdates consumer. +{ + imports = [ ../../services/identity/pass-broker-gateway.nix ]; + + homelab.passBrokerGateway = { + enable = true; + telegram.tokenFile = config.sops.secrets.pass_broker_telegram_token.path; + telegram.chatIdFile = config.sops.secrets.darman_telegram_user_id.path; + # sha256 of each host's pass_broker_gateway_token (secrets/<host>.yaml). + hosts = { + terra.tokenSha256 = "fac335a1c842eba95782df7f7e46c3bcae85eef286958d6abc10d93979a4356e"; + titan.tokenSha256 = "23555315de23011627cbfc0cb43199de85fce9c47f63933664763638453dd15b"; + }; + }; + + sops.secrets.pass_broker_telegram_token = { + owner = "pass-broker-gateway"; + restartUnits = [ "pass-broker-gateway.service" ]; + }; + sops.secrets.darman_telegram_user_id.owner = "pass-broker-gateway"; +} diff --git a/hosts/titan/secrets.nix b/hosts/titan/secrets.nix index 60806cf..dff2125 100644 --- a/hosts/titan/secrets.nix +++ b/hosts/titan/secrets.nix @@ -3,8 +3,6 @@ # sops-nix wiring for titan (laptop). Encrypted values in ../../secrets/titan.yaml, # decrypted with titan's own SSH host key (recipient in ../../.sops.yaml). # samba + pass-broker secrets are declared in profiles/workstation.nix. -# pass_broker_telegram_token must be titan's OWN bot: getUpdates has one -# consumer, so sharing terra's would split approval taps between the two. { sops.defaultSopsFile = ../../secrets/titan.yaml; sops.age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ]; diff --git a/pkgs/pass-broker/Cargo.lock b/pkgs/pass-broker/Cargo.lock index 2ef4f98..170379b 100644 --- a/pkgs/pass-broker/Cargo.lock +++ b/pkgs/pass-broker/Cargo.lock @@ -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" diff --git a/pkgs/pass-broker/Cargo.toml b/pkgs/pass-broker/Cargo.toml index 0845cc0..9532ab7 100644 --- a/pkgs/pass-broker/Cargo.toml +++ b/pkgs/pass-broker/Cargo.toml @@ -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] diff --git a/pkgs/pass-broker/src/approver.rs b/pkgs/pass-broker/src/approver.rs new file mode 100644 index 0000000..a51cfaa --- /dev/null +++ b/pkgs/pass-broker/src/approver.rs @@ -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())?)), + } + } +} diff --git a/pkgs/pass-broker/src/config.rs b/pkgs/pass-broker/src/config.rs index 3ca10a2..f04a6e7 100644 --- a/pkgs/pass-broker/src/config.rs +++ b/pkgs/pass-broker/src/config.rs @@ -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> { diff --git a/pkgs/pass-broker/src/daemon.rs b/pkgs/pass-broker/src/daemon.rs index dba356e..4915ad0 100644 --- a/pkgs/pass-broker/src/daemon.rs +++ b/pkgs/pass-broker/src/daemon.rs @@ -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); diff --git a/pkgs/pass-broker/src/gateway.rs b/pkgs/pass-broker/src/gateway.rs new file mode 100644 index 0000000..062a210 --- /dev/null +++ b/pkgs/pass-broker/src/gateway.rs @@ -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 +} diff --git a/pkgs/pass-broker/src/main.rs b/pkgs/pass-broker/src/main.rs index 72b1bf1..17878d6 100644 --- a/pkgs/pass-broker/src/main.rs +++ b/pkgs/pass-broker/src/main.rs @@ -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}"); diff --git a/pkgs/pass-broker/src/telegram.rs b/pkgs/pass-broker/src/telegram.rs index 1aa17e5..f2e63f1 100644 --- a/pkgs/pass-broker/src/telegram.rs +++ b/pkgs/pass-broker/src/telegram.rs @@ -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()) diff --git a/profiles/workstation.nix b/profiles/workstation.nix index 61825ae..daa8c49 100644 --- a/profiles/workstation.nix +++ b/profiles/workstation.nix @@ -45,22 +45,20 @@ in environment.systemPackages = [ unstable.proton-pass-cli ]; - # Proton Pass for scripts/deploy and Claude, one Telegram tap per use. Your - # own pass-cli stays logged out here: the broker's session is the only one. + # Proton Pass for scripts/deploy and Claude, one Telegram tap per use via + # the gateway on mars. Your own pass-cli stays logged out here: the + # broker's session is the only one. homelab.passBroker = { enable = true; passCli = unstable.proton-pass-cli; patFile = config.sops.secrets.pass_broker_pat.path; - telegram.tokenFile = config.sops.secrets.pass_broker_telegram_token.path; - telegram.chatIdFile = config.sops.secrets.darman_telegram_user_id.path; + gateway.tokenFile = config.sops.secrets.pass_broker_gateway_token.path; }; - # pass-broker (services/identity/pass-broker.nix): the agent PAT and its - # dedicated Telegram bot. Owner pass-broker, so darman cannot read them. + # Owner pass-broker, so darman cannot read them. The token's sha256 is in + # hosts/mars/pass-broker-gateway.nix. sops.secrets.pass_broker_pat.owner = "pass-broker"; - sops.secrets.pass_broker_telegram_token.owner = "pass-broker"; - # Not broker-specific; a second reader needs a sops.templates copy, not a new owner. - sops.secrets.darman_telegram_user_id.owner = "pass-broker"; + sops.secrets.pass_broker_gateway_token.owner = "pass-broker"; # run0 waits on systemd over D-Bus, whose 25s default call timeout runs out # while the polkit dialog is still open (slow typing, a vault lookup). diff --git a/secrets/jupiter.yaml b/secrets/jupiter.yaml index c7379f5..66561eb 100644 --- a/secrets/jupiter.yaml +++ b/secrets/jupiter.yaml @@ -17,8 +17,6 @@ sabnzbd_eweka_password: ENC[AES256_GCM,data:Mt3ZHAe2wzacCQq3x9Uy8WxjrVNad1SmU6sl gitea_hermes_webhook_secret: ENC[AES256_GCM,data:Q8e+mj05MJI7CEJwRonpOmQphAZ0CfnZFoGxrDSSiyHoH3BNhqBU5gBmzuu+6NK9OS33kN+JnFvrwCeEzVxooA==,iv:mdsKOMD5B0Jzh1YRmRh71P8Io9RFtI6aqAky5x+WxOQ=,tag:v3LKz5a8ayl7WAzIPbwj6Q==,type:str] couchdb_admin_password: ENC[AES256_GCM,data:QHkCFUwLbQdd5yKETI5qAz4CkEfsPcl2iCU8F9mX3PA=,iv:2dPNKjjoXEgm7wfC6MlhQTMvAXSNDtaXnjWl2ldl4fk=,tag:1ZltqH94Q5/6GbXAnaIgdg==,type:str] pass_broker_pat: ENC[AES256_GCM,data:4rO5srDthuvDObbhVkHCCm5vblkwbIDtT3c/Eg0KxiVavfoQbmK2RBPOylBLR3v/9wcXEkdQzk8f0N98SkaSr9dB4oe8CbZc91aA9zgCnI8qR7coWCmBJin/wYjcVhX91sxg9Xz81sBWZK3PtrgELFo=,iv:znQrJzdWcsBtK4Rnz/vUIQcU8M3anRm1UGlCJQ/t35U=,tag:fHZLaMm3a3Y/4kf/KEL12A==,type:str] -pass_broker_telegram_token: ENC[AES256_GCM,data:JMm7tGxncQkVS00goTv7zrSrXVUhFmsTeswoTU0deV3YiFDPg6pEuuSZIH2Blg==,iv:PJiA6u0hs20YhD0Ct+I3Bluc2+ugsg2j7QhpwP+lX4I=,tag:Vl53sodg5Ik2yYwMZdozYA==,type:str] -darman_telegram_user_id: ENC[AES256_GCM,data:oocFRYiOWw4=,iv:OGVpIJ4IcgpbyFOEGY9Y90YHJxjy7FrLlQL7qoo+ax4=,tag:p4tuT8QKkUN/lUA9Xt/g9A==,type:str] sops: age: - enc: | @@ -39,7 +37,7 @@ sops: CzjSDQZTcseEXZNwuzZcfB5Mvq0BQvjOj7lGuxzuE4qwWkdJWGfVLQ== -----END AGE ENCRYPTED FILE----- recipient: age1zak7glavmg4026p2389fyqe769vqm4jrryknuqckgqq4merz5f7q44rkkt - lastmodified: "2026-10-15T23:31:28Z" - mac: ENC[AES256_GCM,data:vKhvZ2zibAbyswIzoa2eefS9ym4K3OBoG4bIb0a10zU2vPD4McfrhIBYdVl93hfInGPZwT2Sxd76Sd6AXE0lyo1EB4WzqFsCL2y4DHY5j2iQroqoQQS2TRvM5Sjylfij9OPAbtMTLKiome40Q/qZL2XURBTS0eXIopvWnbQGsX0=,iv:VmOd6+6Z2blaHxa+jdARd7ctCCXM6zzHicKVnFdm3P4=,tag:JCu5wXdtqtViIjULCEdlGw==,type:str] + lastmodified: "2026-10-18T14:38:08Z" + mac: ENC[AES256_GCM,data:nMh+Wk3KR5tz152aELRpA4yBhY2xIGf5EOMIn7Zakg7en3Uk3LIUyK88uz4MqBhGBU1gRjPcM1OqbTnotFK+kDf9ZL6FtJJY2NX0A8B/X60R+I1Afx/KXeDF/wGUqmVkMC0aVaUhyp2FdN5MT9YoHe256ZT/Bjurrvylf54nxNY=,iv:Pu7SUboIGGcpVluF3qSc8JUIv2Y8XwDJZh5mEfw24/w=,tag:I/uoYTHal1YYPwco6mBqZQ==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/mercury.yaml b/secrets/mercury.yaml index fb85595..2617501 100644 --- a/secrets/mercury.yaml +++ b/secrets/mercury.yaml @@ -2,8 +2,6 @@ darman_password: ENC[AES256_GCM,data:iZQERcXtyH+91yUc3r7U6jnFYrGQPFeCPk/9ZDfxOhP pihole_webpassword: ENC[AES256_GCM,data:5iOTqD0CcbOCnM1b4+RbajMTyAU=,iv:2ZRW7dshnPzWkuudrn6n92y4Z2n/6fdnBB7BO5/ypS4=,tag:8UZSqJM6dVECQgrF6v5Fuw==,type:str] tailscale_authkey: ENC[AES256_GCM,data:h3jbN9SrPZwUlYJPEbydvcf9tP/qGQPegnY87AYKOj9AsqAgxeEKfLYwtNeksLgcNBvCoJ1ALk7gqfrMw6sCrW7S7IFlDYhSJDAPfFkR6iczInBDpSfISg==,iv:ML+l4nmPfmSoTGQnNWpdxGZkdaq5HKEHaUxKcblmR8w=,tag:BCAbJ6Iy5ziBNLiOuI/5PA==,type:str] pass_broker_pat: ENC[AES256_GCM,data:yifofOjuajr7UN045S9WlScnzgK91nmQm9f6qzhZs2eBIntjZW+jr0P/EhESD7rDp1ckN7pL8yMdERRJIcCkjI7yTqFC6Q8w/dBHVG5DmeoZXCdY4OkGvVNKoyFBbSbm1T1Hi38r/rDle4zNDOoJKjA=,iv:WJNhzDrXGI+NnJpsqcFQoEwFI0sEGysk16yPPq9HdTI=,tag:d6JgY0DXjopEgOGRd2KdeA==,type:str] -pass_broker_telegram_token: ENC[AES256_GCM,data:x+mz8QykafDBzFK2+2jOPKTD/2Z5bRZcy8P5mN+/qZVoHHAeSbAGrIqmKBVRrQ==,iv:VI7pADIesa8Dk9BCSAXEoUti37m4ZHIjvI+gGD+5IKI=,tag:jEuP3KJO+hJvIrI1brUP5Q==,type:str] -darman_telegram_user_id: ENC[AES256_GCM,data:NPESqxacvBY=,iv:OoDE6qp4atptRwAe88ORYan8XzSBxoU+dzOtHmUzjrk=,tag:6ecraLo/jUYD61YFYGsOFw==,type:str] sops: age: - enc: | @@ -24,7 +22,7 @@ sops: x6FfYadcRfqvSX60l6+TGdzq6xDpxLIZOJ8q19qZsAvB0in50HW5gg== -----END AGE ENCRYPTED FILE----- recipient: age1cpty7zrgnn6l97upq00w5wa8zcvnkxkdt2jvhlj97jh83exure4slha43t - lastmodified: "2026-10-15T23:32:42Z" - mac: ENC[AES256_GCM,data:r8TkYs9SwYpRS6edXqda9bYwUAtFkoM3LyHfDMLsRF5hHO/jtN1Mgjm0JP5t72S9PZPT4cZRvezrrVx7vzv19mTA/O5uL56l4POwtrZxRGMb+Yof/BlcBMkCTPpBSZZAMba5tBojd4ekwFewpp4mS+TyKULOn4B9kROuMNEmVVI=,iv:OanzbUHeE/PFHknpm5XAzBothZK6xkzZ/iJ2Uy7NhoI=,tag:DWMEaYCgM1jMGjuzu6yhug==,type:str] + lastmodified: "2026-10-18T14:38:08Z" + mac: ENC[AES256_GCM,data:yFKYiu36FaLoL6VCOwIGB0MEYbTSk130w/8ExgZdD9CCHqKKz+jn7qHtaj5HyWpn+hgujIX+7GucDI1sPKPwszp4Ede+88XvLKXfSfn95ejYah513llNCz1UUPEIda67rh3bCwV199v1/kdE7JVeZ0n4lE8vGzRv3j3IFb7WbHA=,iv:3mGDuvi9kjEpAU4CYQGpT1oB6yR4LI0qVp3rh1x9B/M=,tag:UQ+KI1roqur4Fd1HcU1nJA==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/neptun.yaml b/secrets/neptun.yaml index d3963e4..1275288 100644 --- a/secrets/neptun.yaml +++ b/secrets/neptun.yaml @@ -9,8 +9,6 @@ headplane_headscale_api_key: ENC[AES256_GCM,data:KcwcprV100wfAkn+YM4+1oTfXkmyeAM headscale_oidc_client_secret: ENC[AES256_GCM,data:262lZGgtmuXTuk3He1WyqyjcXrdnIiwNyWlXEYCGKYbKkWe0JPbUdWcwGVlZ+wXt71pzKuRDpZjgdibVTWYd71mohD/Ni6CwJm7dhf517DqznnYrxojZaSxRYXg/sCVSkwEvVseJ5z2yf/Led1VLNd3I1PaUIlwkdm2P91ps7mM=,iv:w/hu7siWwNAIw7g14bake5BP8ouA/b1SZdeukZXa/dw=,tag:vAXqWfSHwIdGAjR78gSpRg==,type:str] caddy_acme_email: ENC[AES256_GCM,data:j+iPz4lt0Gqs2SKHTS53,iv:DQNfcpYy2v93sKeCvXzLOoBhAo0PjZrxHgFD1oVqYu8=,tag:1yPH/2cW/IiRi9lT8dELEg==,type:str] pass_broker_pat: ENC[AES256_GCM,data:SSyRLiGgDV0A/qVvIYjX1OfmqnsAaZ4vfenAluMC00AlB9r6vfmFWk5+LKYuaq0tGDWw4s2pOxkNvju66o8a0JOR2wqXKLuK51BxrpR9Fruuew2tIs4+ydXu0jqhZE6APhOU9+QcDt5IbHQZPXbO/JA=,iv:l1RFTjV1N6q2whj5LKOylkOZ+ZcNzh29ury+XhquKRU=,tag:O9xKHZQ1fgkbmEjsNF66bg==,type:str] -pass_broker_telegram_token: ENC[AES256_GCM,data:VoWGtKaU69MD/KwvQll+PFzfbwTIOyxEF/ktcPY0YnFXbaUYONlYgk3jaNfnvA==,iv:BnS2/MtIXGRysBVT8yE3wuaULV9DbSOlCKVpNQ2fmhQ=,tag:+plI73w1h1bk18RqrbCbQw==,type:str] -darman_telegram_user_id: ENC[AES256_GCM,data:uMmNPR3go2k=,iv:tXEgAFABOrExLsGyRWpkHsp6i3h0BgI+eMmsPK+Gi3s=,tag:P7WeeeA2nC7po5J0H6FAfA==,type:str] sops: age: - enc: | @@ -31,7 +29,7 @@ sops: Wptkf76aP9UpjhgNkxzedRebQPB7ti+UiVqCvLVimtuHcsm/NJPcRg== -----END AGE ENCRYPTED FILE----- recipient: age1hp72xyx2cnd05937e4eww95g5kdtn0wsf9j2nypw330pa69gfdxqn0lpkp - lastmodified: "2026-10-15T23:32:01Z" - mac: ENC[AES256_GCM,data:sRD40rFUDkTc+mLJolKqtMXSubK+tMWTKZfyIrxl/mkAl3zHLET3J1aosKDZ1UhX0JWaBFV/lSxpt5yt/JkwwA93CXlllORP8hCwksb4RHbovLHDOrFWObZdHF/NrYmX9ZyWYiU5bgMS4xRPkl8N++CrJSPkvkVcBuD+QWStTgg=,iv:MGL/fEkYzPWja79QkLluOubFQA2KaX0Vfa8pUEKXS48=,tag:jKqdi5cgt6CDX2p9bbB3Pw==,type:str] + lastmodified: "2026-10-18T14:38:08Z" + mac: ENC[AES256_GCM,data:Glw0Yv31UElvb7JIvzCL1TMMYd0QYUHFkwHdFtJVead9SXaEmxZQWP+hIEbo8e/HNTWRv3LvVUBUlNS5LzccbgVK+oN2ZPrEgex/dIEcqVVj/X1Y6H+89gvf0n/DCgqGVoXQdiAxZcgoigT0Kiau7zrr3dbH7OQZP6TplO+dFAk=,iv:2SXBwEuTpp/vySo1V85mwNduGbMBv5af755Ebbx+dd0=,tag:HarYC6Blbmo9yM7V0cdLkw==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/terra.yaml b/secrets/terra.yaml index 25ff3a1..d997613 100644 --- a/secrets/terra.yaml +++ b/secrets/terra.yaml @@ -1,15 +1,11 @@ tailscale_authkey: ENC[AES256_GCM,data:B2J+PbFv6o3Dt4em0nCV/9a77VxZ2TFnRFj1QDaaUutDjbKtbO+WXID/kE2kVQhnD5xBmhU5inytytbiP8LYKIcNlklqO5c8hJCzAvFx8xpBfpjxcQrojQ==,iv:aPGqQG14LnUabgan1QYUL0Lf6cIJfMDOQS/XBekoxaM=,tag:A0oKUfwvHZvf5e/NDIWSZQ==,type:str] darman_password: ENC[AES256_GCM,data:G3ZM+NMxvKq5twblcBvyC+MiUX+X7nz+s1GqBHBkJQy1YgW4KN6rpbdj10F9jWxHph5dJ9j9fG6L7UlEg5W5zUYeLFdEx2xJGE1fxksch+6BB9FT6LKkhJ7MmbJmhNHYwJOZO3LM1f/oRw==,iv:abQTRe9kRyYj+TL0rtoxM6JFBaIBmxu7y77qt1h4eME=,tag:OgKrB3SUgSNJjmtJyrmh/Q==,type:str] samba_password: ENC[AES256_GCM,data:UkJLUa2hW1iZ++sfJAcg6G1RJMM=,iv:/HbZ9F+GxCydUP50PNBtJknPlmDWh1DAE26N9FJUyb0=,tag:z1cbwUaVdyfwEIU8LINEcw==,type:str] -librechat_creds_key: ENC[AES256_GCM,data:e2Ptf41yHu0KxfzjW4DP04CSJfbtdsJ8bwrgJyv9up4/JSCbBzjPFmOi7jsHUL4jT0AGVuHG5w3y+YOil9EeNA==,iv:zneozNSkXsb4Vy/sq21b8HWCKpDkXVTxyLY2Zh0bwP0=,tag:6CxR5sIspbfzHlfdx+45Iw==,type:str] -librechat_creds_iv: ENC[AES256_GCM,data:iuW1Rxfu7Ei8zHVG7wsBTYYznbtErj7DC9B71OiiWGA=,iv:Ngs88C44gcSzxQZU1lMiy5kn9mM/ckuWKRRGOFJeeoQ=,tag:Q9B8vM4YMkIP3RyYVWSQqg==,type:str] -librechat_jwt_secret: ENC[AES256_GCM,data:f/gljrQPZIXeLHXtqKCCYGEu2pXgbZd69CjyEhSVJ+AMuaVj7DWVclD5IMsEVERBHw5a7OndBSfLvgXRaKN6Gg==,iv:DG5CwCbQLCTv1++APCdFzAiWGKiEJl+9MhKIM2ykJQM=,tag:wdpY6l+5h4UtsluIncsyhA==,type:str] -librechat_jwt_refresh_secret: ENC[AES256_GCM,data:N/yAPtaodJX4t2C2A0bZ/LQaVc8SBMgg3KYJrWRyXCM6HAmgHtSQ9nWJO2fl+7A966mMtYvpATYcBIPj/K5nig==,iv:k5ZYi2OKjL9Z+lhVgdNsmGVQm+iCqmF15H3TUTbofWk=,tag:NVTdvlL1lpwVhjo2c2phpg==,type:str] hermes_api_server_key: ENC[AES256_GCM,data:NU+6zVmUeM9+m5eZCPdCiMLo76GqbsRxNM7EmVM2TmKTOUL2af7Msg==,iv:EMd7JKhQ3ZkFPi2xMGZ+mHHK05qQVDR+ZCbiYcWdhHU=,tag:JaElU4CyvD5qQbehHbM5qQ==,type:str] elevenlabs_api_key: ENC[AES256_GCM,data:4IBKKMxor1sJ1skh1pgLrQnNX31cgQFiy89O1TZn71QHaq+xY7p+7JLtmGkhbZ10l12m,iv:Ww5RLYuv09xD1deFgM89u0wZ3hZ/0Pndda0kreMx2aQ=,tag:opgIPsDwSc+rLqseqjP6Gg==,type:str] pass_broker_pat: ENC[AES256_GCM,data:A4NrFBQIL6waKSaVB4EZnxLp4RWkm1hGZcHGBd5qSh+BPv7gvj+g9vjFhkCwXgAinBekxo0GOhf/Ip4zK+KWZwNTzF8MXjAkSARnFQgXiFAncaEVzXGho1TVYvYAN1PRQxEu79bYS0IG5+ZOw0VVpjw=,iv:vLiojJJrl6yC83stsNoXLZX762z8nM0Jx164lx7XVjs=,tag:K8zFZ5bb8QeADmsLf0o6pw==,type:str] -pass_broker_telegram_token: ENC[AES256_GCM,data:iSyl9sm82yfN+EGKGCd4Px3WbkW9/pb026tqKJdHGWVvDIX0g5yRl+KXetMMVg==,iv:w1zukDV9L/gfe0lFmgrebjaenBz8vraCi0GQr+TJTPw=,tag:wKhpWDSQVwNqxILFuLQBIA==,type:str] -darman_telegram_user_id: ENC[AES256_GCM,data:IPPf4Sf99qc=,iv:uJBSGlVwDrhSQUeE5seQGKaPiD1mumORYE8NX+rBWjo=,tag:hFTbzVmekZJZk2je1OWpTQ==,type:str] +pass_broker_gateway_token: ENC[AES256_GCM,data:OSM2iCIi+GymGzIS3T2vN06H0q8GvSuQ2RWkatSfIyIrQpVKaeU/GUEkD6S4okedKBtXXYN9cnc2Ro3H7d+S0g==,iv:9hgYqlTonbDlAu8WpjUUTqhqbpfAxb1ZAuQUUac2QC4=,tag:skIctluEWh4hMnmR4Y7g6w==,type:str] +protonvpn_wg_private_key: ENC[AES256_GCM,data:aTfP7xyStfy/kmLuJA8L32J8uJ5Y0eA5c8XySiiozFLau+PxU7t8sSremQ8=,iv:pbkMKmPhRmTat5swTsjf29ZOEHSTjWvUXMsdbFgF3PY=,tag:OAyEkFthYwv6lkr6M/EWkA==,type:str] sops: age: - enc: | @@ -30,7 +26,7 @@ sops: sHjKfw8VrrmAR4pQf1dsY+wcyh4FsZxhP3Q+QIVq3eCIXS9PeJkGAg== -----END AGE ENCRYPTED FILE----- recipient: age1rfcmu6zh40v4260l9hnf8ajs9vly0s06rx3ey76eu78dp9t7getqyhmkut - lastmodified: "2026-10-15T23:24:57Z" - mac: ENC[AES256_GCM,data:4h3bHgofztrcDz2VN7KhGxL6dlGTB8BUOwF6pdei+ysDV8PmEf6NNKYxwTln7zB+uiQDHdwZm3yxT/Bl9J/JbMV3amBT8JpqlhHTDWMpDdmS8n81wlcYokL75A0Ipp9YmxWhraDuX4bw4r6k0XpTqwaOtvHbT7pThcMuI6Ta+V0=,iv:RnqlhIbcp/vs7aFRwMW/H6eMK3Qxx6CMhDR3Ihy/tVs=,tag:sCcCOA2roUTqnXE+lYCCog==,type:str] + lastmodified: "2026-10-21T08:28:58Z" + mac: ENC[AES256_GCM,data:8p2f7x4YqO7C1p7fDmiAaiQdSdAsqL8nYUshYC1e6pj7YyZnh2mUZU2e1ZcGQbs+t0OvssRD9dyY0Np1D9GTjVfiPDYp1PIZGwoZCeH7knc2d66dUYWn92P73pOPajgYzaQqzBUMCXntt9y6eeflHcn5XjV75baRAbInuU/Y7Bc=,iv:8MfH8rQqgFl2acS0Fjs+XjNwNJHv+Kuc8uUQRbwiiF8=,tag:HcccDy0k0jTiMgmUV4M6iw==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/titan.yaml b/secrets/titan.yaml index b6c5500..de94547 100644 --- a/secrets/titan.yaml +++ b/secrets/titan.yaml @@ -1,9 +1,8 @@ tailscale_authkey: ENC[AES256_GCM,data:IMPUuTAo1T/suiEKm9FhNTPaJF1FjdIH5dZw6vzjjzH/eqoKbJ0LyWZ5psGLhJb+5b1T6y9p+OgLVD5g4KaSiW05tIgiMXE7DKF+eHZq3r32guKOymTB9g==,iv:YLODeA1yD+/xyXNygwrvDOG9C+QpO6yTD/JyOsVV64g=,tag:94XPWgNuHeLE3vaN2IvinQ==,type:str] darman_password: ENC[AES256_GCM,data:GI2aBID+NUkKsmWY6+4igchMVKy5U3CK5kxST15aoE9yd7z01Xf2TZwA73MZnH/PY2nqmPQdBexdPRusGXrU3YgRF4tqkngblMA+NVqiZvYzeETtza7aSI034Y1AfBJboVvOX+fOq1TF+Q==,iv:EFne3Dl49lAp8Wufurv3pjoT99tRcSaVrJmA85i6qSU=,tag:S4CevQN/zmpGJ3SOVB4ahw==,type:str] samba_password: ENC[AES256_GCM,data:UEi/qgYVlBM2xelRvAw42WvAvk4=,iv:Ho9td+rD96VpX/l4RmuQrtUCSQj8YG5zXMKITwcDXC8=,tag:CVRbasHUBZO257P9YSdSXg==,type:str] -darman_telegram_user_id: ENC[AES256_GCM,data:x37bHgV9yCU=,iv:QYaR/yz8c5cHVD01ZbhkRYz9t9uyMekbIUQvnWj4kAQ=,tag:Yg3aoxeZja9RecDS0PntLQ==,type:str] pass_broker_pat: ENC[AES256_GCM,data:askNNSjnr0aaFQ==,iv:9JSmZt0t5A/IFUXDPJ49abbboVZMzy7+u5OkoZkYbuk=,tag:yjTDxqcwd4O6m8d5g6hM3g==,type:str] -pass_broker_telegram_token: ENC[AES256_GCM,data:2C9ySGfLwBVFHg==,iv:jQLLuRwvW81tHaM4NEHDbT1YnrVenJ8tD6dphQShu5k=,tag:llsNm6Vmxe0wqF3Sh28tBw==,type:str] +pass_broker_gateway_token: ENC[AES256_GCM,data:JyWNufgUi80n1CiclM/ZPQT5llgo3u78sYfuzgQeDosuvBOH29s3ga5sSUl2Mz+r5sDIvAkmvwf1SY9aMT8YBQ==,iv:aBYR5F3Mnfs23B3QrCxe8nWm4lE7La6JwFsAkDdVDhs=,tag:ccpx2i9GMog+FbKNouGisQ==,type:str] sops: age: - enc: | @@ -24,7 +23,7 @@ sops: xxQw11N8OGw4tA1nPY8ahD2LAQRcZo72mOrdAe2DR1OT1BSLEwoh3A== -----END AGE ENCRYPTED FILE----- recipient: age1qm6ne4mrgwkj7eea5j3vn0qmtw4p5h4eu78vvahhfnd4pk04qausn3qgv2 - lastmodified: "2026-10-16T15:54:09Z" - mac: ENC[AES256_GCM,data:1MVKmhALGhpf0gdb0iuJ8kKE26YkFzB/ipfrZGyr7VYJyA2+Sv54n/sPw/WhJ8cz1iDtPgRATdIa8DEX0dumZqaePdm+j359VYrIcF9VYc3HMoR1NMpDOp9K8jtO4Kt7iJvzQWEDqFtiMn+blXVMMcBsJ9aC8MmDg+nivl6VQT0=,iv:AFRQUpE311b3ZNrhIcf8LGuosrBy2ob6f0Yr/EYWpHs=,tag:+ba7aNv91qWXo0cexD8LBg==,type:str] + lastmodified: "2026-10-18T14:38:08Z" + mac: ENC[AES256_GCM,data:MSLE2u3ebHFIBmcCfORk/QxP33VD1idHsyfWPkIMiEzAOROMFe8ldwAqNfZL04dhI41r8CbpwV4awHnDTHoI0tyldvaHsCqzbiwSySzc97YC5XQDMZzk7NGqsUWmtQ0q6e3tB7QCeW3BClQLEPiXN+fgQgmNDN7KM7Bkh/Mq4GU=,iv:yYRv75odGFVZGToTatkjdsWf9CnMJq/RUOnSAX2kF0I=,tag:LIwXHxK47nciemETsOFsWA==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/services/identity/pass-broker-fakes.nix b/services/identity/pass-broker-fakes.nix new file mode 100644 index 0000000..e0d2ffc --- /dev/null +++ b/services/identity/pass-broker-fakes.nix @@ -0,0 +1,106 @@ +# Fakes shared by pass-broker-test.nix and pass-broker-gateway-test.nix: a +# pass-cli that only logs in with the expected PAT (and refuses one on its +# command line), and a Telegram API on 127.0.0.1:8081 whose button presses +# the test script injects via /test/press. +{ pkgs }: +{ + passCli = pkgs.writeShellScriptBin "pass-cli" '' + set -eu + case "$*" in *pst_*) echo "PAT on the command line" >&2; exit 99 ;; esac + s="$PROTON_PASS_SESSION_DIR"; mkdir -p "$s" + case "$1" in + info) [ -f "$s/ok" ] ;; + logout) rm -f "$s/ok" ;; + login) [ "''${PROTON_PASS_PERSONAL_ACCESS_TOKEN:-}" = "pst_test::key" ] && touch "$s/ok" ;; + item) + [ -f "$s/ok" ] || { echo "not logged in" >&2; exit 1; } + case "$2" in + list) printf '%s\n' \ + '- [id1]: darman@jupiter (state=Active)' \ + '- [id2]: root@jupiter (state=Active)' \ + '- [id4]: secret-note (state=Active)' \ + '- [id5]: auto-item (state=Active)' ;; + view) + [ -n "''${PROTON_PASS_AGENT_REASON:-}" ] || { echo "reason required" >&2; exit 1; } + echo "$PROTON_PASS_AGENT_REASON" >> "$HOME/reasons" + case "$*" in + *"--item-id id1 "*) echo hunter2 ;; + *"--item-id id2 "*) echo rootpw ;; + *"--item-id id5 "*) echo autopw ;; + *) exit 1 ;; + esac ;; + esac ;; + *) exit 1 ;; + esac + ''; + + telegram = pkgs.writers.writePython3Bin "fake-telegram" { flakeIgnore = [ "E501" "E701" "E704" ]; } '' + import json + import threading + import time + from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + from urllib.parse import urlparse, parse_qs + + PREFIX = "/bot123:test/" + cv = threading.Condition() + state = {"messages": [], "edits": [], "answers": []} + updates = [] + + + class H(BaseHTTPRequestHandler): + def reply(self, obj, code=200): + b = json.dumps(obj).encode() + self.send_response(code) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + + def do_GET(self): + with cv: self.reply(state) + + def do_POST(self): + n = int(self.headers.get("Content-Length", 0)) + body = json.loads(self.rfile.read(n) or b"{}") + u = urlparse(self.path) + if u.path == "/test/press": + q = parse_qs(u.query) + with cv: + uid = len(updates) + 1 + updates.append({"update_id": uid, "callback_query": { + "id": "cq%d" % uid, "from": {"id": int(q["from"][0])}, "data": q["data"][0]}}) + cv.notify_all() + return self.reply({"ok": True}) + if not u.path.startswith(PREFIX): + return self.reply({"ok": False, "description": "Unauthorized"}, 401) + method = u.path[len(PREFIX):] + with cv: + if method == "sendMessage": + body["message_id"] = len(state["messages"]) + 1 + state["messages"].append(body) + return self.reply({"ok": True, "result": {"message_id": body["message_id"]}}) + if method in ("editMessageText", "answerCallbackQuery"): + state["edits" if method == "editMessageText" else "answers"].append(body) + return self.reply({"ok": True, "result": True}) + if method == "getUpdates": + deadline = time.time() + min(body.get("timeout", 0), 5) + while True: + pending = [x for x in updates if x["update_id"] >= body.get("offset", 0)] + if pending or time.time() >= deadline: + return self.reply({"ok": True, "result": pending}) + cv.wait(deadline - time.time()) + self.reply({"ok": False, "description": "unknown method"}, 404) + + def log_message(self, *a): pass + + + ThreadingHTTPServer(("127.0.0.1", 8081), H).serve_forever() + ''; + + # try-get <tag> <item>: result lands in /tmp/r/<tag>.{out,err,rc}. The tag + # is in the reason so pkill can pick out one client. + tryGet = pkgs.writeShellScriptBin "try-get" '' + pass-broker get --item "$2" --reason "vm test $1" >/tmp/r/$1.out 2>/tmp/r/$1.err + echo $? >/tmp/r/$1.rc + ''; +} diff --git a/services/identity/pass-broker-gateway-test.nix b/services/identity/pass-broker-gateway-test.nix new file mode 100644 index 0000000..810f52a --- /dev/null +++ b/services/identity/pass-broker-gateway-test.nix @@ -0,0 +1,168 @@ +# VM test for pass-broker-gateway.nix with a broker in gateway mode. Run: +# nix build .#checks.x86_64-linux.pass-broker-gateway -L +# +# Two nodes: mars runs the gateway and the fake Telegram API, terra a broker +# whose prompts go through mars. A third token, titan's, is used only via +# curl, to check that hosts can't see or cancel each other's prompts. +{ pkgs }: +let + fakes = import ./pass-broker-fakes.nix { inherit pkgs; }; + sha256 = builtins.hashString "sha256"; +in +pkgs.testers.runNixOSTest { + name = "pass-broker-gateway"; + + nodes.mars = { + imports = [ ./pass-broker-gateway.nix ]; + + environment.systemPackages = [ pkgs.curl pkgs.jq ]; + networking.firewall.allowedTCPPorts = [ 8097 ]; + + environment.etc = { + "pb/token" = { text = "123:test\n"; mode = "0400"; user = "pass-broker-gateway"; }; + "pb/chat" = { text = "4242\n"; mode = "0400"; user = "pass-broker-gateway"; }; + }; + + homelab.passBrokerGateway = { + enable = true; + telegram = { + apiBase = "http://127.0.0.1:8081"; + tokenFile = "/etc/pb/token"; + chatIdFile = "/etc/pb/chat"; + }; + hosts = { + terra.tokenSha256 = sha256 "terra-token"; + titan.tokenSha256 = sha256 "titan-token"; + }; + }; + + systemd.services.fake-telegram = { + wantedBy = [ "multi-user.target" ]; + before = [ "pass-broker-gateway.service" ]; + serviceConfig.ExecStart = "${fakes.telegram}/bin/fake-telegram"; + }; + }; + + nodes.terra = { + imports = [ ./pass-broker.nix ]; + + users.users.darman.isNormalUser = true; + environment.systemPackages = [ pkgs.curl pkgs.jq fakes.tryGet ]; + systemd.tmpfiles.rules = [ "d /tmp/r 1777 root root -" ]; + + environment.etc = { + "pb/pat" = { text = "pst_test::key\n"; mode = "0400"; user = "pass-broker"; }; + "pb/gateway" = { text = "terra-token\n"; mode = "0400"; user = "pass-broker"; }; + }; + + homelab.passBroker = { + enable = true; + passCli = fakes.passCli; + patFile = "/etc/pb/pat"; + approvalTimeout = 6; + gateway = { + url = "http://mars:8097"; + tokenFile = "/etc/pb/gateway"; + }; + rules = [ + { item = "darman@*"; } + { item = "root@*"; grantMinutes = 0; } + ]; + }; + }; + + testScript = /* python */ '' + import json + + def tg(): + return json.loads(mars.succeed("curl -s http://127.0.0.1:8081/")) + + def wait_messages(n): + mars.wait_until_succeeds(f"curl -s http://127.0.0.1:8081/ | jq -e '.messages | length == {n}'") + return tg()["messages"][-1] + + def button(msg, i): + return msg["reply_markup"]["inline_keyboard"][0][i]["callback_data"] + + def press(data): + mars.succeed(f"curl -s -X POST 'http://127.0.0.1:8081/test/press?data={data}&from=4242'") + + def start(tag, item): + terra.succeed(f"su darman -c 'try-get {tag} {item}' >/dev/null 2>&1 &") + + def result(tag): + terra.wait_for_file(f"/tmp/r/{tag}.rc", timeout=60) + rc = int(terra.succeed(f"cat /tmp/r/{tag}.rc")) + return rc, terra.succeed(f"cat /tmp/r/{tag}.out").strip(), terra.succeed(f"cat /tmp/r/{tag}.err") + + def api(method, path, token, body=None): + data = f"-H 'Content-Type: application/json' -d '{json.dumps(body)}'" if body else "" + out = terra.succeed( + f"curl -s -o /tmp/api.out -w '%{{http_code}}' -X {method} {data} " + f"-H 'Authorization: Bearer {token}' http://mars:8097{path}" + ) + return int(out), terra.succeed("cat /tmp/api.out") + + start_all() + mars.wait_for_unit("pass-broker-gateway.service") + mars.wait_for_open_port(8097) + terra.wait_for_unit("pass-broker.socket") + + with subtest("a broker's prompt arrives through the gateway, labelled by its token"): + start("a", "darman@jupiter") + msg = wait_messages(1) + assert msg["text"].startswith("🔑 terra: HomeLab / darman@jupiter (password)"), msg + assert "vm test a" in msg["text"], msg + press(button(msg, 0)) + assert result("a")[:2] == (0, "hunter2"), result("a") + assert tg()["edits"][-1]["text"].endswith("approved") + + with subtest("deny refuses"): + start("b", "root@jupiter") + press(button(wait_messages(2), 1)) + rc, out, err = result("b") + assert rc == 1 and "denied" in err, (rc, out, err) + + with subtest("a client that hangs up withdraws its prompt on the gateway"): + start("c", "root@jupiter") + wait_messages(3) + terra.wait_until_succeeds("grep -q 'waiting for approval' /tmp/r/c.err") + terra.succeed("pkill -f 'vm test c'") + mars.wait_until_succeeds( + "curl -s http://127.0.0.1:8081/ | jq -e '.edits[-1].text | endswith(\"went away\")'" + ) + + with subtest("no answer expires on the gateway's clock"): + start("d", "root@jupiter") + wait_messages(4) + rc, out, err = result("d") + assert rc == 1 and "no answer" in err, (rc, out, err) + assert tg()["edits"][-1]["text"].endswith("expired") + + with subtest("tokens: unknown is refused, hosts can't see or cancel each other's prompts"): + code, _ = api("POST", "/ask", "wrong-token", {"text": "x", "timeout_secs": 30}) + assert code == 401, code + code, out = api("POST", "/ask", "titan-token", {"text": "terra: trust me", "timeout_secs": 300}) + assert code == 200, (code, out) + titan_id = json.loads(out)["id"] + assert wait_messages(5)["text"] == "🔑 titan: terra: trust me" + assert api("GET", f"/ask/{titan_id}", "terra-token")[0] == 404 + assert api("DELETE", f"/ask/{titan_id}", "terra-token")[0] == 404 + assert json.loads(api("GET", f"/ask/{titan_id}", "titan-token")[1]) == {"status": "pending"} + + with subtest("a tap resolves only its own prompt"): + start("e", "root@jupiter") + terra_msg = wait_messages(6) + press(button(terra_msg, 0)) + assert result("e")[:2] == (0, "rootpw") + assert json.loads(api("GET", f"/ask/{titan_id}", "titan-token")[1]) == {"status": "pending"} + assert api("DELETE", f"/ask/{titan_id}", "titan-token")[0] == 204 + assert json.loads(api("GET", f"/ask/{titan_id}", "titan-token")[1]) == {"status": "cancelled"} + + with subtest("gateway down refuses instead of hanging"): + mars.succeed("systemctl stop pass-broker-gateway.service") + start("f", "root@jupiter") + rc, out, err = result("f") + assert rc == 1 and "gateway" in err, (rc, out, err) + ''; +} diff --git a/services/identity/pass-broker-gateway.nix b/services/identity/pass-broker-gateway.nix new file mode 100644 index 0000000..c7bbedb --- /dev/null +++ b/services/identity/pass-broker-gateway.nix @@ -0,0 +1,108 @@ +{ config, pkgs, lib, ... }: + +# The approval gateway: sole owner of the pass-broker Telegram bot, so every +# host's broker (pass-broker.nix with `gateway`) prompts in the same chat. It +# relays prompts and taps and never sees an item. Tailnet-only: tailscale0 is +# a trusted interface (services/vpn/tailscale.nix) and nothing opens the port +# elsewhere. +# +# Brokers authenticate with a per-host token; only its sha256 is here, so this +# host holds no broker's credential. The prompt is labelled with the host the +# token belongs to, not what the request claims. + +let + cfg = config.homelab.passBrokerGateway; + pass-broker = pkgs.callPackage ../../pkgs/pass-broker.nix { }; + + configFile = pkgs.writeText "pass-broker-gateway.json" (builtins.toJSON { + listen = "0.0.0.0:${toString cfg.port}"; + telegram = { + api_base = cfg.telegram.apiBase; + token_file = cfg.telegram.tokenFile; + chat_id_file = cfg.telegram.chatIdFile; + }; + hosts = lib.mapAttrsToList (name: h: { inherit name; token_sha256 = h.tokenSha256; }) cfg.hosts; + max_timeout_secs = cfg.maxTimeout; + }); +in +{ + options.homelab.passBrokerGateway = { + enable = lib.mkEnableOption "pass-broker approval gateway"; + + port = lib.mkOption { + type = lib.types.port; + default = 8097; + }; + + telegram = { + apiBase = lib.mkOption { + type = lib.types.str; + default = "https://api.telegram.org"; + }; + tokenFile = lib.mkOption { + type = lib.types.path; + description = "Bot token of a bot nothing else polls."; + }; + chatIdFile = lib.mkOption { + type = lib.types.path; + description = "Your Telegram user id; only its taps count."; + }; + }; + + hosts = lib.mkOption { + description = "Brokers allowed to prompt, by the name shown in the prompt."; + type = lib.types.attrsOf (lib.types.submodule { + options.tokenSha256 = lib.mkOption { + type = lib.types.strMatching "[0-9a-f]{64}"; + description = "sha256 of that host's gateway token, hex."; + }; + }); + }; + + maxTimeout = lib.mkOption { + type = lib.types.int; + default = 600; + description = "Cap on how long a broker may keep a prompt open, in seconds."; + }; + }; + + config = lib.mkIf cfg.enable { + users.users.pass-broker-gateway = { + isSystemUser = true; + group = "pass-broker-gateway"; + }; + users.groups.pass-broker-gateway = { }; + + systemd.services.pass-broker-gateway = { + description = "pass-broker approval gateway (Telegram)"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network-online.target" ]; + environment.PASS_BROKER_GATEWAY_CONFIG = configFile; + + serviceConfig = { + ExecStart = "${pass-broker}/bin/pass-broker gateway"; + User = "pass-broker-gateway"; + Group = "pass-broker-gateway"; + Restart = "on-failure"; + RestartSec = 5; + + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectProc = "invisible"; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ]; + RestrictNamespaces = true; + LockPersonality = true; + MemoryDenyWriteExecute = true; + SystemCallArchitectures = "native"; + UMask = "0077"; + }; + }; + }; +} diff --git a/services/identity/pass-broker-test.nix b/services/identity/pass-broker-test.nix index 4c71751..d2639c6 100644 --- a/services/identity/pass-broker-test.nix +++ b/services/identity/pass-broker-test.nix @@ -2,119 +2,22 @@ # nix build .#checks.x86_64-linux.pass-broker -L # # Real pass-cli and Telegram need network and real secrets, so both are -# faked: a pass-cli that only logs in with the expected PAT (and refuses one -# on its command line), and a Telegram API whose button presses the test -# script injects. +# faked (pass-broker-fakes.nix). { pkgs }: let - fakePassCli = pkgs.writeShellScriptBin "pass-cli" '' - set -eu - case "$*" in *pst_*) echo "PAT on the command line" >&2; exit 99 ;; esac - s="$PROTON_PASS_SESSION_DIR"; mkdir -p "$s" - case "$1" in - info) [ -f "$s/ok" ] ;; - logout) rm -f "$s/ok" ;; - login) [ "''${PROTON_PASS_PERSONAL_ACCESS_TOKEN:-}" = "pst_test::key" ] && touch "$s/ok" ;; - item) - [ -f "$s/ok" ] || { echo "not logged in" >&2; exit 1; } - case "$2" in - list) printf '%s\n' \ - '- [id1]: darman@jupiter (state=Active)' \ - '- [id2]: root@jupiter (state=Active)' \ - '- [id4]: secret-note (state=Active)' \ - '- [id5]: auto-item (state=Active)' ;; - view) - [ -n "''${PROTON_PASS_AGENT_REASON:-}" ] || { echo "reason required" >&2; exit 1; } - echo "$PROTON_PASS_AGENT_REASON" >> "$HOME/reasons" - case "$*" in - *"--item-id id1 "*) echo hunter2 ;; - *"--item-id id2 "*) echo rootpw ;; - *"--item-id id5 "*) echo autopw ;; - *) exit 1 ;; - esac ;; - esac ;; - *) exit 1 ;; - esac - ''; + fakes = import ./pass-broker-fakes.nix { inherit pkgs; }; + inherit (fakes) tryGet; + fakePassCli = fakes.passCli; + fakeTelegram = fakes.telegram; - fakeTelegram = pkgs.writers.writePython3Bin "fake-telegram" { flakeIgnore = [ "E501" "E701" "E704" ]; } '' - import json - import threading - import time - from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler - from urllib.parse import urlparse, parse_qs - - PREFIX = "/bot123:test/" - cv = threading.Condition() - state = {"messages": [], "edits": [], "answers": []} - updates = [] - - - class H(BaseHTTPRequestHandler): - def reply(self, obj, code=200): - b = json.dumps(obj).encode() - self.send_response(code) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(b))) - self.end_headers() - self.wfile.write(b) - - def do_GET(self): - with cv: self.reply(state) - - def do_POST(self): - n = int(self.headers.get("Content-Length", 0)) - body = json.loads(self.rfile.read(n) or b"{}") - u = urlparse(self.path) - if u.path == "/test/press": - q = parse_qs(u.query) - with cv: - uid = len(updates) + 1 - updates.append({"update_id": uid, "callback_query": { - "id": "cq%d" % uid, "from": {"id": int(q["from"][0])}, "data": q["data"][0]}}) - cv.notify_all() - return self.reply({"ok": True}) - if not u.path.startswith(PREFIX): - return self.reply({"ok": False, "description": "Unauthorized"}, 401) - method = u.path[len(PREFIX):] - with cv: - if method == "sendMessage": - body["message_id"] = len(state["messages"]) + 1 - state["messages"].append(body) - return self.reply({"ok": True, "result": {"message_id": body["message_id"]}}) - if method in ("editMessageText", "answerCallbackQuery"): - state["edits" if method == "editMessageText" else "answers"].append(body) - return self.reply({"ok": True, "result": True}) - if method == "getUpdates": - deadline = time.time() + min(body.get("timeout", 0), 5) - while True: - pending = [x for x in updates if x["update_id"] >= body.get("offset", 0)] - if pending or time.time() >= deadline: - return self.reply({"ok": True, "result": pending}) - cv.wait(deadline - time.time()) - self.reply({"ok": False, "description": "unknown method"}, 404) - - def log_message(self, *a): pass - - - ThreadingHTTPServer(("127.0.0.1", 8081), H).serve_forever() - ''; - - # try-get <tag> <item>: result lands in /tmp/r/<tag>.{out,err,rc}. The tag - # is in the reason so pkill can pick out one client. - tryGet = pkgs.writeShellScriptBin "try-get" '' - pass-broker get --item "$2" --reason "vm test $1" >/tmp/r/$1.out 2>/tmp/r/$1.err - echo $? >/tmp/r/$1.rc - ''; - - # ghost: send a request and hang up before the broker reads it, like a - # client killed while queued. silent: a socket that never answers, like a - # crash-looping broker behind its socket unit. # Stand-in for Claude Code, whose process name is `claude`. fakeClaude = pkgs.writeShellScriptBin "claude" '' pass-broker get --item auto-item --reason "from claude" ''; + # ghost: send a request and hang up before the broker reads it, like a + # client killed while queued. silent: a socket that never answers, like a + # crash-looping broker behind its socket unit. sockProbe = pkgs.writers.writePython3Bin "sock-probe" { flakeIgnore = [ "E501" ]; } '' import json import socket diff --git a/services/identity/pass-broker.nix b/services/identity/pass-broker.nix index 43e01c4..28ce426 100644 --- a/services/identity/pass-broker.nix +++ b/services/identity/pass-broker.nix @@ -7,9 +7,10 @@ # `pass-broker get --item <title> --reason <why>`; scripts/deploy uses it. # # Telegram, not a desktop dialog: any process of darman's can fake Wayland -# input and click its own approval. The bot must be dedicated to this: a bot -# has one getUpdates consumer, so sharing it (e.g. with Hermes) would let the -# other side see or swallow the approvals. +# input and click its own approval. A bot has one getUpdates consumer, so +# either this broker owns a dedicated bot (`telegram`) or it asks the shared +# gateway on mars (`gateway`, pass-broker-gateway.nix), which owns the one +# bot for every host. let cfg = config.homelab.passBroker; @@ -24,11 +25,16 @@ let session_dir = "${stateDir}/session"; pat_file = cfg.patFile; approval_timeout_secs = cfg.approvalTimeout; - telegram = { - api_base = cfg.telegram.apiBase; - token_file = cfg.telegram.tokenFile; - chat_id_file = cfg.telegram.chatIdFile; - }; + approval = + if cfg.gateway != null then { + gateway = { inherit (cfg.gateway) url; token_file = cfg.gateway.tokenFile; }; + } else { + telegram = { + api_base = cfg.telegram.apiBase; + token_file = cfg.telegram.tokenFile; + chat_id_file = cfg.telegram.chatIdFile; + }; + }; rules = map (r: { inherit (r) vault item approval; grant_minutes = r.grantMinutes; @@ -69,19 +75,45 @@ in description = "Seconds to wait for a tap before refusing."; }; - telegram = { - apiBase = lib.mkOption { - type = lib.types.str; - default = "https://api.telegram.org"; - }; - tokenFile = lib.mkOption { - type = lib.types.path; - description = "Bot token of a bot used for nothing else."; - }; - chatIdFile = lib.mkOption { - type = lib.types.path; - description = "Your Telegram user id; only its taps count."; - }; + telegram = lib.mkOption { + default = null; + description = "Prompt via this broker's own bot. Exactly one of telegram/gateway."; + type = lib.types.nullOr (lib.types.submodule { + options = { + apiBase = lib.mkOption { + type = lib.types.str; + default = "https://api.telegram.org"; + }; + tokenFile = lib.mkOption { + type = lib.types.path; + description = "Bot token of a bot nothing else polls."; + }; + chatIdFile = lib.mkOption { + type = lib.types.path; + description = "Your Telegram user id; only its taps count."; + }; + }; + }); + }; + + gateway = lib.mkOption { + default = null; + description = "Prompt via the shared gateway. Exactly one of telegram/gateway."; + type = lib.types.nullOr (lib.types.submodule { + options = { + url = lib.mkOption { + type = lib.types.str; + default = "http://mars.orbit.sol:8097"; + }; + tokenFile = lib.mkOption { + type = lib.types.path; + description = '' + This host's gateway token; its sha256 goes in the gateway's + homelab.passBrokerGateway.hosts.<host>.tokenSha256. + ''; + }; + }; + }); }; rules = lib.mkOption { @@ -116,6 +148,11 @@ in }; config = lib.mkIf cfg.enable { + assertions = [{ + assertion = (cfg.telegram == null) != (cfg.gateway == null); + message = "homelab.passBroker: set exactly one of telegram or gateway."; + }]; + environment.systemPackages = [ pass-broker ]; users.users.pass-broker = {