feat(terra): pass-broker for Telegram-approved Proton Pass access

A Rust daemon running as its own system user holds terra's only pass-cli
session, an agent PAT scoped to the HomeLab vaults. `pass-broker get` asks
it for an item; per-item rules decide auto/ask/deny, and "ask" sends a
Telegram prompt that only darman's account can approve (10-min grant for
darman@*/root@*). Requests whose client is gone are dropped or withdrawn,
and the client gives up after 30s without an answer.

scripts/deploy uses the broker exclusively when its socket exists. Covered
by checks.pass-broker (fake pass-cli + Telegram). Secrets added for all
hosts; only terra runs the broker so far.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-16 01:48:46 +02:00
co-authored by Claude Opus 5.5
parent e6ceacb63b
commit 3dccafe2b8
22 changed files with 2645 additions and 13 deletions
+15
View File
@@ -51,6 +51,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 first; a plain `pass-cli item view --item-title` silently returns the trashed copy and
you get an interactive prompt with no explanation. 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.
**Claude: fetch Proton Pass items only via `pass-broker get --item <title> --reason <why>`**,
never `pass-cli login` yourself, and never print a value you fetched. Values go into
variables or pipes, as `scripts/deploy` does.
`HOMELAB_KEXEC_TARBALL` (+ `_CPIO` / `_GZIP`) makes `kexec`/`kexec-local` reuse a `HOMELAB_KEXEC_TARBALL` (+ `_CPIO` / `_GZIP`) makes `kexec`/`kexec-local` reuse a
prebuilt installer instead of rebuilding ~500MB. The VM test below uses this. prebuilt installer instead of rebuilding ~500MB. The VM test below uses this.
@@ -77,6 +85,9 @@ nix build .#checks.x86_64-linux.kexec-local -L
# VM test of luna's app hosting on mars (hosts/mars/luna-sites.nix): podman socket # VM test of luna's app hosting on mars (hosts/mars/luna-sites.nix): podman socket
# proxy, registry validation, caddy routes, reboot persistence # proxy, registry validation, caddy routes, reboot persistence
nix build .#checks.x86_64-linux.luna-sites -L 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
``` ```
`checks.kexec-local` is the only way to exercise `kexec-local` at all: it jumps the `checks.kexec-local` is the only way to exercise `kexec-local` at all: it jumps the
@@ -210,6 +221,10 @@ kept its ssh host key. Run it after ANY change to the kexec paths.
- **`kexec-local` stages on `/var/tmp`, not `/tmp`**: `kexec-run.sh` appends a fresh cpio - **`kexec-local` stages on `/var/tmp`, not `/tmp`**: `kexec-run.sh` appends a fresh cpio
to `kexec/initrd` in place and execs binaries from that dir, so a size-capped or to `kexec/initrd` in place and execs binaries from that dir, so a size-capped or
`noexec` tmpfs gives a half-written initrd or a bare "Permission denied". `noexec` tmpfs gives a half-written initrd or a bare "Permission denied".
- **sops-nix values must be STRINGS.** `sops --set '["id"] 123'` stores `type:int`; the
build-time check only sees key names and passes, then activation's sops-install-secrets
fails with "is not a string" and installs NONE of the new secrets. The old generation
stays, so it looks like only the new keys are missing. Quote it: `'["id"] "123"'`.
- **A sops secret a USER service reads needs `owner`, not a mode.** `luna-voiced` - **A sops secret a USER service reads needs `owner`, not a mode.** `luna-voiced`
(`services/desktop/luna-voice.nix`) runs as darman's user unit, and a user manager (`services/desktop/luna-voice.nix`) runs as darman's user unit, and a user manager
cannot read root:root 0400 — `LoadCredential` does not bridge that gap either. cannot read root:root 0400 — `LoadCredential` does not bridge that gap either.
+6
View File
@@ -533,6 +533,12 @@
luna-sites = import ./hosts/mars/luna-sites-test.nix { luna-sites = import ./hosts/mars/luna-sites-test.nix {
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
}; };
# VM test for services/identity/pass-broker.nix, with fake pass-cli
# and Telegram: nix build .#checks.x86_64-linux.pass-broker -L
pass-broker = import ./services/identity/pass-broker-test.nix {
pkgs = nixpkgs.legacyPackages.${system};
};
}; };
# `nix develop` — hot-reload loop for dotfiles/quickshell. # `nix develop` — hot-reload loop for dotfiles/quickshell.
+11
View File
@@ -21,6 +21,7 @@ in
../../services/desktop/claude-desktop.nix ../../services/desktop/claude-desktop.nix
../../services/desktop/librechat.nix ../../services/desktop/librechat.nix
../../services/desktop/luna-voice.nix ../../services/desktop/luna-voice.nix
../../services/identity/pass-broker.nix
../../services/dev/turtle-beach-re.nix ../../services/dev/turtle-beach-re.nix
inputs.turtle-beach-swarm-re.nixosModules.release inputs.turtle-beach-swarm-re.nixosModules.release
inputs.tbctl.nixosModules.tbctl inputs.tbctl.nixosModules.tbctl
@@ -105,6 +106,16 @@ in
environment.systemPackages = [ unstable.proton-pass-cli ]; 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.
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;
};
# run0 waits on systemd over D-Bus, whose 25s default call timeout runs out # 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). # while the polkit dialog is still open (slow typing, a vault lookup).
# Scoped to run0 so a hung systemctl doesn't also wait 5min. # Scoped to run0 so a hung systemctl doesn't also wait 5min.
+7
View File
@@ -39,6 +39,13 @@
sops.secrets.hermes_api_server_key.owner = "darman"; sops.secrets.hermes_api_server_key.owner = "darman";
sops.secrets.elevenlabs_api_key.owner = "darman"; sops.secrets.elevenlabs_api_key.owner = "darman";
# pass-broker (services/identity/pass-broker.nix): the agent PAT and its
# dedicated Telegram bot. Owner pass-broker, so darman cannot read them.
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.librechat_creds_key = { }; sops.secrets.librechat_creds_key = { };
sops.secrets.librechat_creds_iv = { }; sops.secrets.librechat_creds_iv = { };
sops.secrets.librechat_jwt_secret = { }; sops.secrets.librechat_jwt_secret = { };
+16
View File
@@ -0,0 +1,16 @@
{ lib, rustPlatform }:
# Wiring (user, socket, policy, secrets) lives in services/identity/pass-broker.nix.
rustPlatform.buildRustPackage {
pname = "pass-broker";
version = "0.1.0";
src = ./pass-broker;
cargoLock.lockFile = ./pass-broker/Cargo.lock;
meta = {
description = "Telegram-approved access to a Proton Pass agent session";
mainProgram = "pass-broker";
platforms = lib.platforms.linux;
};
}
+1290
View File
File diff suppressed because it is too large Load Diff
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "pass-broker"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1"
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "process", "io-util"] }
[profile.release]
opt-level = 2
+88
View File
@@ -0,0 +1,88 @@
use crate::proto::{Reply, Request, DEFAULT_SOCKET};
use anyhow::Result;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixStream;
const FIRST_REPLY: Duration = Duration::from_secs(30);
/// Prints the value on stdout. Exit 1 = refused/failed, 2 = usage or no broker.
pub async fn get(args: &[String]) -> Result<()> {
let mut req = Request {
vault: None,
item: String::new(),
field: "password".into(),
reason: String::new(),
};
let mut it = args.iter();
while let Some(flag) = it.next() {
let Some(val) = it.next() else { usage() };
match flag.as_str() {
"--vault" => req.vault = Some(val.clone()),
"--item" => req.item = val.clone(),
"--field" => req.field = val.clone(),
"--reason" => req.reason = val.clone(),
_ => usage(),
}
}
if req.item.is_empty() || req.reason.trim().is_empty() {
usage();
}
let path = std::env::var("PASS_BROKER_SOCKET").unwrap_or_else(|_| DEFAULT_SOCKET.into());
let stream = match UnixStream::connect(&path).await {
Ok(s) => s,
Err(e) => {
eprintln!("pass-broker: cannot reach {path}: {e}");
std::process::exit(2);
}
};
let (rd, mut wr) = stream.into_split();
let mut line = serde_json::to_string(&req)?;
line.push('\n');
wr.write_all(line.as_bytes()).await?;
let mut lines = BufReader::new(rd).lines();
// Bounds only the first reply: after Pending the daemon times the prompt
// out itself. A crash-looping broker still accepts via the socket unit,
// so without this the client would wait forever.
let mut pending = false;
loop {
let next = if pending {
lines.next_line().await?
} else {
match tokio::time::timeout(FIRST_REPLY, lines.next_line()).await {
Ok(r) => r?,
Err(_) => {
eprintln!(
"pass-broker: no answer within {}s; see journalctl -u pass-broker",
FIRST_REPLY.as_secs()
);
std::process::exit(1);
}
}
};
let Some(line) = next else { break };
match serde_json::from_str::<Reply>(&line)? {
Reply::Pending { message } => {
pending = true;
eprintln!(">> pass-broker: {message}");
}
Reply::Ok { value } => {
println!("{value}");
return Ok(());
}
Reply::Error { error } => {
eprintln!("pass-broker: {error}");
std::process::exit(1);
}
}
}
eprintln!("pass-broker: daemon closed the connection without an answer");
std::process::exit(1);
}
fn usage() -> ! {
eprintln!("{}", crate::USAGE);
std::process::exit(2);
}
+112
View File
@@ -0,0 +1,112 @@
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::path::PathBuf;
/// Written by services/identity/pass-broker.nix; path in $PASS_BROKER_CONFIG.
#[derive(Deserialize)]
pub struct Config {
pub host: String,
pub default_vault: String,
/// Peer uids are checked against these; root is always allowed.
pub allowed_users: Vec<String>,
pub pass_cli: String,
pub session_dir: PathBuf,
pub pat_file: PathBuf,
pub approval_timeout_secs: u64,
pub telegram: TelegramConfig,
/// First match wins; no match means deny.
pub rules: Vec<Rule>,
}
#[derive(Deserialize)]
pub struct TelegramConfig {
pub api_base: String,
pub token_file: PathBuf,
pub chat_id_file: PathBuf,
}
#[derive(Deserialize)]
pub struct Rule {
pub vault: Option<String>,
/// Item title; `*` matches any run of characters.
pub item: String,
pub approval: Approval,
/// After an approval, further requests for the item skip the prompt for this long.
pub grant_minutes: u64,
}
#[derive(Deserialize, Clone, Copy, PartialEq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Approval {
Auto,
Ask,
Deny,
}
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}"))
}
pub fn rule_for(&self, vault: &str, item: &str) -> Option<&Rule> {
self.rules.iter().find(|r| {
r.vault.as_deref().unwrap_or(&self.default_vault) == vault && glob(&r.item, item)
})
}
/// Resolved once at startup: a user added later needs a broker restart.
pub fn allowed_uids(&self) -> Result<Vec<u32>> {
let passwd = std::fs::read_to_string("/etc/passwd")?;
let mut uids = vec![0];
for name in &self.allowed_users {
let uid = passwd
.lines()
.map(|l| l.split(':').collect::<Vec<_>>())
.find(|f| f.len() > 2 && f[0] == name)
.and_then(|f| f[2].parse().ok());
match uid {
Some(uid) => uids.push(uid),
None => bail!("allowed user {name:?} not in /etc/passwd"),
}
}
Ok(uids)
}
}
fn glob(pat: &str, s: &str) -> bool {
let parts: Vec<&str> = pat.split('*').collect();
if parts.len() == 1 {
return pat == s;
}
let (first, last) = (parts[0], parts[parts.len() - 1]);
if !s.starts_with(first) || s.len() < first.len() + last.len() || !s.ends_with(last) {
return false;
}
let mut rest = &s[first.len()..s.len() - last.len()];
for mid in &parts[1..parts.len() - 1] {
match rest.find(mid) {
Some(i) => rest = &rest[i + mid.len()..],
None => return false,
}
}
true
}
#[cfg(test)]
mod tests {
use super::glob;
#[test]
fn globs() {
assert!(glob("root@*", "root@jupiter"));
assert!(!glob("root@*", "darman@jupiter"));
assert!(glob("*", ""));
assert!(glob("a*b*c", "aXbYc"));
assert!(!glob("a*b*c", "acb"));
assert!(!glob("ab*ba", "aba"));
assert!(glob("exact", "exact"));
assert!(!glob("exact", "exact2"));
}
}
+249
View File
@@ -0,0 +1,249 @@
use crate::config::{Approval, Config};
use crate::pass::Pass;
use crate::proto::{Reply, Request};
use crate::telegram::{Telegram, Verdict};
use anyhow::{bail, Context, Result};
use std::collections::HashMap;
use std::future::Future;
use std::os::fd::FromRawFd;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::{UnixListener, UnixStream};
use tokio::sync::Mutex;
struct State {
cfg: Config,
uids: Vec<u32>,
pass: Pass,
tg: Telegram,
/// "vault\0item" -> when the last approval stops covering it.
grants: Mutex<HashMap<String, Instant>>,
/// One prompt at a time; Telegram::ask polls getUpdates itself.
asking: Mutex<()>,
}
pub async fn run() -> Result<()> {
let cfg = Config::load()?;
let state = Arc::new(State {
uids: cfg.allowed_uids()?,
pass: Pass::new(&cfg),
tg: Telegram::new(&cfg.telegram)?,
grants: Mutex::new(HashMap::new()),
asking: Mutex::new(()),
cfg,
});
// Not fatal: a stale PAT should show up in the journal, not stop the socket.
if let Err(e) = state.pass.ensure_session().await {
eprintln!("initial login failed: {e:#}");
}
let listener = listener()?;
eprintln!("pass-broker ready");
loop {
let (stream, _) = listener.accept().await?;
let state = state.clone();
tokio::spawn(async move {
if let Err(e) = handle(state, stream).await {
eprintln!("connection: {e:#}");
}
});
}
}
/// From pass-broker.socket. The socket is 0666; access control is the peer
/// uid check in handle(), so a new client needs no re-login for a group.
fn listener() -> Result<UnixListener> {
let ours = std::env::var("LISTEN_PID").ok() == Some(std::process::id().to_string());
if !ours || std::env::var("LISTEN_FDS").ok().as_deref() != Some("1") {
bail!("expected exactly one socket from systemd (pass-broker.socket)");
}
let l = unsafe { std::os::unix::net::UnixListener::from_raw_fd(3) };
l.set_nonblocking(true)?;
Ok(UnixListener::from_std(l)?)
}
async fn handle(state: Arc<State>, stream: UnixStream) -> Result<()> {
let cred = stream.peer_cred()?;
let (mut rd, mut wr) = stream.into_split();
// Read before refusing, or the client's write hits a closed socket and
// it reports EPIPE instead of the reason.
let mut line = String::new();
BufReader::new((&mut rd).take(64 * 1024)).read_line(&mut line).await?;
if !state.uids.contains(&cred.uid()) {
eprintln!("refused uid {}", cred.uid());
return send(&mut wr, Reply::Error { error: "uid not allowed".into() }).await;
}
let req: Request = serde_json::from_str(&line).context("bad request")?;
let vault = req.vault.clone().unwrap_or_else(|| state.cfg.default_vault.clone());
// A client killed while queued (the broker restarting) leaves its request
// in the socket; nobody would see the answer or know who asked.
let who = match cred.pid().and_then(requester) {
Some(who) if !closed(&rd) => who,
_ => {
eprintln!("dropped {vault}/{}: requester went away", req.item);
return Ok(());
}
};
eprintln!(
"request {vault}/{} ({}) uid={} reason={:?} from {}",
req.item, req.field, cred.uid(), req.reason, who.from
);
let gone = client_gone(&rd);
tokio::pin!(gone);
let reply = match decide(&state, &mut wr, gone.as_mut(), &vault, &req, &who).await {
Ok(()) if closed(&rd) => Reply::Error { error: "requester went away".into() },
Ok(()) => {
let reason = format!("{} (pass-broker on {})", req.reason, state.cfg.host);
match state.pass.get(&vault, &req.item, &req.field, &reason).await {
Ok(value) => Reply::Ok { value },
Err(e) => Reply::Error { error: format!("{e:#}") },
}
}
Err(e) => Reply::Error { error: format!("{e:#}") },
};
match &reply {
Reply::Ok { .. } => eprintln!("served {vault}/{}", req.item),
Reply::Error { error } => eprintln!("refused {vault}/{}: {error}", req.item),
Reply::Pending { .. } => {}
}
send(&mut wr, reply).await
}
async fn decide(
state: &State,
wr: &mut OwnedWriteHalf,
mut gone: Pin<&mut impl Future<Output = ()>>,
vault: &str,
req: &Request,
who: &Requester,
) -> Result<()> {
let Some(rule) = state.cfg.rule_for(vault, &req.item) else {
bail!("no rule allows {vault}/{}", req.item);
};
match rule.approval {
Approval::Deny => bail!("policy denies {vault}/{}", req.item),
Approval::Auto => return Ok(()),
Approval::Ask => {}
}
let key = format!("{vault}\0{}", req.item);
let granted = |grants: &HashMap<String, Instant>| grants.get(&key).is_some_and(|t| *t > Instant::now());
if granted(&*state.grants.lock().await) {
eprintln!("covered by an earlier approval");
return Ok(());
}
// Before the lock, so a client queued behind another prompt hears from us.
let _ = send(wr, Reply::Pending { message: "waiting for approval on Telegram".into() }).await;
let _asking = tokio::select! {
guard = state.asking.lock() => guard,
_ = gone.as_mut() => bail!("requester went away"),
};
// A concurrent request for the same item may have been approved meanwhile.
if granted(&*state.grants.lock().await) {
return Ok(());
}
let grant = match rule.grant_minutes {
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}\nFrom: {from}\nChain: {chain}\n{grant}",
host = state.cfg.host,
item = req.item,
field = req.field,
reason = req.reason,
from = who.from,
chain = who.chain,
);
let timeout = Duration::from_secs(state.cfg.approval_timeout_secs);
match state.tg.ask(&text, timeout, gone).await? {
Verdict::Approved => {
if rule.grant_minutes > 0 {
let until = Instant::now() + Duration::from_secs(rule.grant_minutes * 60);
state.grants.lock().await.insert(key, until);
}
Ok(())
}
Verdict::Denied => bail!("denied on Telegram"),
Verdict::Expired => bail!("no answer on Telegram within {}s", timeout.as_secs()),
Verdict::Cancelled => bail!("requester went away"),
}
}
/// Resolves once the client hangs up. It sends nothing after its request, so
/// readable means EOF; stray bytes are discarded.
async fn client_gone(rd: &OwnedReadHalf) {
while rd.readable().await.is_ok() {
if closed(rd) {
return;
}
}
}
fn closed(rd: &OwnedReadHalf) -> bool {
match rd.try_read(&mut [0u8; 64]) {
Ok(0) => true,
Ok(_) => false,
Err(e) => e.kind() != std::io::ErrorKind::WouldBlock,
}
}
async fn send(wr: &mut OwnedWriteHalf, reply: Reply) -> Result<()> {
let mut line = serde_json::to_string(&reply)?;
line.push('\n');
wr.write_all(line.as_bytes()).await?;
Ok(())
}
/// Who is asking, for the prompt. Informational only: any process of the
/// same uid can make itself look like anything.
struct Requester {
from: String,
chain: String,
}
/// The client itself is just `pass-broker get …`; its parent is the caller.
/// None when the client has already exited.
fn requester(pid: i32) -> Option<Requester> {
let parent = ppid(pid)?;
let from = std::fs::read(format!("/proc/{parent}/cmdline"))
.map(|b| {
let s = String::from_utf8_lossy(&b).replace('\0', " ");
truncate(s.trim(), 200)
})
.unwrap_or_default();
let mut names = vec![];
let mut p = parent;
for _ in 0..8 {
if p <= 1 {
break;
}
if let Ok(c) = std::fs::read_to_string(format!("/proc/{p}/comm")) {
names.push(c.trim().to_string());
}
match ppid(p) {
Some(pp) => p = pp,
None => break,
}
}
Some(Requester { from, chain: names.join(" ← ") })
}
fn ppid(pid: i32) -> Option<i32> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
// comm may contain spaces and parens; fields resume after the last ')'.
stat.rsplit_once(')')?.1.split_whitespace().nth(1)?.parse().ok()
}
fn truncate(s: &str, max: usize) -> String {
match s.char_indices().nth(max) {
Some((i, _)) => format!("{}…", &s[..i]),
None => s.to_string(),
}
}
+31
View File
@@ -0,0 +1,31 @@
//! pass-broker — hands Proton Pass items to darman's processes (Claude
//! included) only after a Telegram approval.
//!
//! 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.
mod client;
mod config;
mod daemon;
mod pass;
mod proto;
mod telegram;
use anyhow::Result;
const USAGE: &str = "usage: pass-broker get --item <title> --reason <why> [--vault <name>] [--field <name>]
pass-broker daemon";
#[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("get") => client::get(&args[1..]).await,
_ => {
eprintln!("{USAGE}");
std::process::exit(2);
}
}
}
+102
View File
@@ -0,0 +1,102 @@
use crate::config::Config;
use anyhow::{anyhow, bail, Context, Result};
use std::path::PathBuf;
use std::process::Stdio;
use tokio::process::Command;
use tokio::sync::Mutex;
/// The broker's own pass-cli session. pass-cli calls are serialised: they
/// share one session dir and a re-login mid-lookup would race.
pub struct Pass {
bin: String,
session_dir: PathBuf,
pat_file: PathBuf,
lock: Mutex<()>,
}
impl Pass {
pub fn new(cfg: &Config) -> Self {
Self {
bin: cfg.pass_cli.clone(),
session_dir: cfg.session_dir.clone(),
pat_file: cfg.pat_file.clone(),
lock: Mutex::new(()),
}
}
pub async fn ensure_session(&self) -> Result<()> {
let _g = self.lock.lock().await;
self.ensure_session_locked().await
}
async fn ensure_session_locked(&self) -> Result<()> {
if self.run(&["info"], &[]).await.is_ok() {
return Ok(());
}
eprintln!("no pass-cli session, logging in with the PAT");
let pat = std::fs::read_to_string(&self.pat_file)
.with_context(|| format!("reading {}", self.pat_file.display()))?;
let _ = self.run(&["logout", "--force"], &[]).await;
// Via env, not `--pat`: argv is world-readable in /proc.
self.run(&["login"], &[("PROTON_PASS_PERSONAL_ACCESS_TOKEN", pat.trim())])
.await
.context("pass-cli login")?;
Ok(())
}
pub async fn get(&self, vault: &str, title: &str, field: &str, reason: &str) -> Result<String> {
let _g = self.lock.lock().await;
self.ensure_session_locked().await?;
// `item view --item-title` has no state filter and can return a
// trashed duplicate, so resolve the id among active items first.
let list = self
.run(
&["item", "list", "--vault-name", vault, "--filter-state", "active", "--output", "human"],
&[],
)
.await?;
let id = list
.lines()
.find_map(|l| {
// - [ITEM_ID]: the title (state=Active)
let rest = l.strip_prefix("- [")?;
let (id, rest) = rest.split_once("]: ")?;
let t = match rest.rfind(" (state=") {
Some(i) if rest.ends_with(')') => &rest[..i],
_ => rest,
};
(t == title).then(|| id.to_string())
})
.ok_or_else(|| anyhow!("no active item {title:?} in vault {vault:?}"))?;
let out = self
.run(
&["item", "view", "--vault-name", vault, "--item-id", &id, "--field", field, "--output", "human"],
&[("PROTON_PASS_AGENT_REASON", reason)],
)
.await?;
let value = out.lines().next().unwrap_or("").to_string();
if value.is_empty() {
bail!("{title:?} has an empty {field} field");
}
Ok(value)
}
async fn run(&self, args: &[&str], env: &[(&str, &str)]) -> Result<String> {
let out = Command::new(&self.bin)
.args(args)
.envs(env.iter().copied())
.env("PROTON_PASS_SESSION_DIR", &self.session_dir)
.stdin(Stdio::null())
.kill_on_drop(true)
.output()
.await
.with_context(|| format!("running {}", self.bin))?;
if !out.status.success() {
let err = String::from_utf8_lossy(&out.stderr);
bail!("pass-cli {} failed ({}): {}", args[0], out.status, err.trim());
}
Ok(String::from_utf8(out.stdout)?)
}
}
+21
View File
@@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};
pub const DEFAULT_SOCKET: &str = "/run/pass-broker.sock";
/// One JSON line from the client.
#[derive(Serialize, Deserialize)]
pub struct Request {
pub vault: Option<String>,
pub item: String,
pub field: String,
pub reason: String,
}
/// JSON lines from the daemon: any number of `Pending`, then one final reply.
#[derive(Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum Reply {
Pending { message: String },
Ok { value: String },
Error { error: String },
}
+164
View File
@@ -0,0 +1,164 @@
use crate::config::TelegramConfig;
use anyhow::{anyhow, bail, Context, Result};
use serde_json::{json, Value};
use std::future::Future;
use std::io::Read;
use std::pin::Pin;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::{Duration, Instant};
/// Approval prompts with Approve/Deny buttons. The bot must be dedicated to
/// the broker: getUpdates has a single consumer, so a shared bot would see
/// (or swallow) the other's callbacks.
pub struct Telegram {
http: reqwest::Client,
/// Contains the token: never print it, and strip it from reqwest errors.
base: String,
chat_id: i64,
offset: AtomicI64,
}
pub enum Verdict {
Approved,
Denied,
Expired,
Cancelled,
}
impl Telegram {
pub fn new(cfg: &TelegramConfig) -> Result<Self> {
let token = std::fs::read_to_string(&cfg.token_file)
.with_context(|| format!("reading {}", cfg.token_file.display()))?;
let chat_id = std::fs::read_to_string(&cfg.chat_id_file)
.with_context(|| format!("reading {}", cfg.chat_id_file.display()))?
.trim()
.parse()
.context("telegram chat id is not a number")?;
Ok(Self {
http: reqwest::Client::builder().timeout(Duration::from_secs(40)).build()?,
base: format!("{}/bot{}", cfg.api_base.trim_end_matches('/'), token.trim()),
chat_id,
offset: AtomicI64::new(0),
})
}
async fn call(&self, method: &str, body: Value) -> Result<Value> {
let resp = self
.http
.post(format!("{}/{method}", self.base))
.json(&body)
.send()
.await
.map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?;
let v: Value = resp
.json()
.await
.map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?;
if v["ok"] != json!(true) {
bail!("telegram {method}: {}", v["description"]);
}
Ok(v["result"].clone())
}
/// Callers must not ask concurrently: each call polls getUpdates itself.
/// `gone` resolving (the client hung up) withdraws the prompt.
pub async fn ask(
&self,
text: &str,
timeout: Duration,
mut gone: Pin<&mut impl Future<Output = ()>>,
) -> Result<Verdict> {
let nonce = nonce()?;
let (yes, no) = (format!("ok:{nonce}"), format!("no:{nonce}"));
let msg = self
.call(
"sendMessage",
json!({
"chat_id": self.chat_id,
"text": text,
"reply_markup": { "inline_keyboard": [[
{ "text": "Approve", "callback_data": yes },
{ "text": "Deny", "callback_data": no },
]]},
}),
)
.await?;
let message_id = msg["message_id"].clone();
let deadline = Instant::now() + timeout;
let verdict = 'poll: loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
break Verdict::Expired;
}
let poll = self.call(
"getUpdates",
json!({
"offset": self.offset.load(Ordering::SeqCst),
"timeout": left.as_secs().min(25),
"allowed_updates": ["callback_query"],
}),
);
let polled = tokio::select! {
r = poll => r,
_ = gone.as_mut() => break 'poll Verdict::Cancelled,
};
let updates = match polled {
Ok(u) => u,
Err(e) => {
eprintln!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
};
for u in updates.as_array().into_iter().flatten() {
if let Some(id) = u["update_id"].as_i64() {
self.offset.fetch_max(id + 1, Ordering::SeqCst);
}
let cq = &u["callback_query"];
let Some(cq_id) = cq["id"].as_str() else { continue };
let data = cq["data"].as_str().unwrap_or("");
let mine = data == yes || data == no;
// The button lives in our chat, but the bot can be added
// elsewhere and a forwarded message keeps its buttons.
let from_owner = cq["from"]["id"].as_i64() == Some(self.chat_id);
let note = match (mine, from_owner) {
(_, false) => "Not yours.",
(false, true) => "Expired.",
(true, true) => "",
};
let _ = self
.call("answerCallbackQuery", json!({ "callback_query_id": cq_id, "text": note }))
.await;
if mine && from_owner {
break 'poll if data == yes { Verdict::Approved } else { Verdict::Denied };
}
}
};
let outcome = match verdict {
Verdict::Approved => "✅ approved",
Verdict::Denied => "❌ denied",
Verdict::Expired => "⌛ expired",
Verdict::Cancelled => "🚫 cancelled: the requester went away",
};
// Without reply_markup this also removes the buttons.
let _ = self
.call(
"editMessageText",
json!({
"chat_id": self.chat_id,
"message_id": message_id,
"text": format!("{text}\n\n{outcome}"),
}),
)
.await;
Ok(verdict)
}
}
fn nonce() -> Result<String> {
let mut buf = [0u8; 16];
std::fs::File::open("/dev/urandom")?.read_exact(&mut buf)?;
Ok(buf.iter().map(|b| format!("{b:02x}")).collect())
}
+11 -1
View File
@@ -18,7 +18,8 @@
# at ~/.config/homelab/<config>/ssh_host_ed25519_key. Runs from a non-NixOS host too. # at ~/.config/homelab/<config>/ssh_host_ed25519_key. Runs from a non-NixOS host too.
# #
# Password prompts auto-fill from the "HomeLab" Proton Pass vault, keyed by # Password prompts auto-fill from the "HomeLab" Proton Pass vault, keyed by
# <config> not <host> (darman@<config> for sudo, root@<config> for ssh). # <config> not <host> (darman@<config> for sudo, root@<config> for ssh), via
# pass-broker (Telegram-approved) where it runs, else your own pass-cli session.
# Override with HOMELAB_PASS_ITEM / HOMELAB_PASS_ROOT_ITEM / HOMELAB_PASS_VAULT. # Override with HOMELAB_PASS_ITEM / HOMELAB_PASS_ROOT_ITEM / HOMELAB_PASS_VAULT.
set -euo pipefail set -euo pipefail
shopt -s nullglob shopt -s nullglob
@@ -386,6 +387,15 @@ require_tracked() {
# real on darman@neptun, which had both an Active and a Trashed copy). # real on darman@neptun, which had both an Active and a Trashed copy).
proton_pass_password() { proton_pass_password() {
local title="$1" vault="${HOMELAB_PASS_VAULT:-HomeLab}" id pw local title="$1" vault="${HOMELAB_PASS_VAULT:-HomeLab}" id pw
# Where pass-broker runs (services/identity/pass-broker.nix), it is the only
# source: a refused tap must not fall through to someone's own session.
if [ -S /run/pass-broker.sock ] && command -v pass-broker >/dev/null 2>&1; then
pass-broker get --vault "$vault" --item "$title" \
--reason "scripts/deploy ${SCRIPT_ARGS[*]}" || true
return 0
fi
command -v pass-cli >/dev/null 2>&1 || return 0 command -v pass-cli >/dev/null 2>&1 || return 0
# Lines look like: - [ITEM_ID]: the title (state=Active) # Lines look like: - [ITEM_ID]: the title (state=Active)
+5 -2
View File
@@ -16,6 +16,9 @@ sabnzbd_eweka_username: ENC[AES256_GCM,data:eLsTZoM8T8fAlGaXWlDaoQ==,iv:eawyGhN7
sabnzbd_eweka_password: ENC[AES256_GCM,data:Mt3ZHAe2wzacCQq3x9Uy8WxjrVNad1SmU6sl8ZgrkMLymfq2eP4JzO/uPdD33A==,iv:PnFT95Zxqz4QBpPF5PRloKpoa15AU7Ef/Owwy+iDotw=,tag:/uRX00RzHLJN3gws5Qz8SA==,type:str] sabnzbd_eweka_password: ENC[AES256_GCM,data:Mt3ZHAe2wzacCQq3x9Uy8WxjrVNad1SmU6sl8ZgrkMLymfq2eP4JzO/uPdD33A==,iv:PnFT95Zxqz4QBpPF5PRloKpoa15AU7Ef/Owwy+iDotw=,tag:/uRX00RzHLJN3gws5Qz8SA==,type:str]
gitea_hermes_webhook_secret: ENC[AES256_GCM,data:Q8e+mj05MJI7CEJwRonpOmQphAZ0CfnZFoGxrDSSiyHoH3BNhqBU5gBmzuu+6NK9OS33kN+JnFvrwCeEzVxooA==,iv:mdsKOMD5B0Jzh1YRmRh71P8Io9RFtI6aqAky5x+WxOQ=,tag:v3LKz5a8ayl7WAzIPbwj6Q==,type:str] 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] 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: sops:
age: age:
- enc: | - enc: |
@@ -36,7 +39,7 @@ sops:
CzjSDQZTcseEXZNwuzZcfB5Mvq0BQvjOj7lGuxzuE4qwWkdJWGfVLQ== CzjSDQZTcseEXZNwuzZcfB5Mvq0BQvjOj7lGuxzuE4qwWkdJWGfVLQ==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1zak7glavmg4026p2389fyqe769vqm4jrryknuqckgqq4merz5f7q44rkkt recipient: age1zak7glavmg4026p2389fyqe769vqm4jrryknuqckgqq4merz5f7q44rkkt
lastmodified: "2026-08-25T20:39:37Z" lastmodified: "2026-10-15T23:31:28Z"
mac: ENC[AES256_GCM,data:Z59BCw8gETfddXqul4LXrq6V3LBJA1itF7A1VNUERwK4NfaUGwWUhbl9h7YF/srzgtg9yGjbFB/f5kwmT3k/TWTG+C0M/4KOyTVs4y5UvB9gI4g8awYbtnFDPRAcqqcxoMD0sgapgVcNh48KWv76ndF6UGn+QfWn9eF4KBP+ZzQ=,iv:57myu1aTMMSLTz+1ldwxdusnzh8cyPwrLiEIx3rLS9w=,tag:isthpdOydD4ZNoFZyflViw==,type:str] mac: ENC[AES256_GCM,data:vKhvZ2zibAbyswIzoa2eefS9ym4K3OBoG4bIb0a10zU2vPD4McfrhIBYdVl93hfInGPZwT2Sxd76Sd6AXE0lyo1EB4WzqFsCL2y4DHY5j2iQroqoQQS2TRvM5Sjylfij9OPAbtMTLKiome40Q/qZL2XURBTS0eXIopvWnbQGsX0=,iv:VmOd6+6Z2blaHxa+jdARd7ctCCXM6zzHicKVnFdm3P4=,tag:JCu5wXdtqtViIjULCEdlGw==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+5 -2
View File
@@ -11,6 +11,9 @@ obsidian_luna_passphrase: ENC[AES256_GCM,data:fqHtP3g4J40ddYL9lzCixrisdC/DEJJerm
elevenlabs_api_key: ENC[AES256_GCM,data:2oJeClO4/SFsbLwRgMe3bFXrmuDX7YOc57VfSjElV5A3vaIQqfN9eHzo/cm0vISxYgUv,iv:eIeKQJ6odDnmGLjHSLV3HbErVnLr7tatOtV83TvB2QA=,tag:XPkXRfDJ2ZK98TYXKeK/CA==,type:str] elevenlabs_api_key: ENC[AES256_GCM,data:2oJeClO4/SFsbLwRgMe3bFXrmuDX7YOc57VfSjElV5A3vaIQqfN9eHzo/cm0vISxYgUv,iv:eIeKQJ6odDnmGLjHSLV3HbErVnLr7tatOtV83TvB2QA=,tag:XPkXRfDJ2ZK98TYXKeK/CA==,type:str]
hermes_api_server_key: ENC[AES256_GCM,data:Au80iziwdryFTCLnggC9DdjjZPrGPKpmRFgkXe/l9RQ7on9nXb1dvQ==,iv:hWvv4fLkhRgVTT2btI+TvpNBHfMOg9y4BQKn+ht7XDo=,tag:2dEZEys8vsTwc7w0ZiBK1w==,type:str] hermes_api_server_key: ENC[AES256_GCM,data:Au80iziwdryFTCLnggC9DdjjZPrGPKpmRFgkXe/l9RQ7on9nXb1dvQ==,iv:hWvv4fLkhRgVTT2btI+TvpNBHfMOg9y4BQKn+ht7XDo=,tag:2dEZEys8vsTwc7w0ZiBK1w==,type:str]
openrouter_api_key: ENC[AES256_GCM,data:klv/11iORtM8nbUv7RB79AyVM996V8vCU6hrTqgREnTkRW3b5PcOWXl0XdW2fr5JW4lvm6V4qYUsP62cJuVyCL3d6qA2dZCdJQ==,iv:bKMYMpbP0xsipt79sMCKuJoh5T+9GiUKwDVNZe3Sa7Q=,tag:iNOy3X0cygMlkllyWTwphg==,type:str] openrouter_api_key: ENC[AES256_GCM,data:klv/11iORtM8nbUv7RB79AyVM996V8vCU6hrTqgREnTkRW3b5PcOWXl0XdW2fr5JW4lvm6V4qYUsP62cJuVyCL3d6qA2dZCdJQ==,iv:bKMYMpbP0xsipt79sMCKuJoh5T+9GiUKwDVNZe3Sa7Q=,tag:iNOy3X0cygMlkllyWTwphg==,type:str]
pass_broker_pat: ENC[AES256_GCM,data:9fg2TG4RvmcAbd4xI1lPIRURVTNUrakTYsjfssa/v7se6RJvmX0Op6FPzufPHo8J412Fr62emGQcbPc1DFk2tEEUIJIuAGEGXp/2MADIo5XA8eM71DczzI5BTfyk67B32MfGr1hvW7AWCQWA719mg1c=,iv:1i3nA+t/Jh1vE4gHu47fAd1hsC70HB1yWywHITRLlE8=,tag:S/nIlHP4UbrQnbL+4SVqTQ==,type:str]
pass_broker_telegram_token: ENC[AES256_GCM,data:l50+HIyGDQ5V9S9sD/r0z5lP2krPRV1BhrWHSAK5kQoFceQLV9GRkx5JMICTww==,iv:zuL7nXGFjYmZFVqo1rjkSNFQqE1JOlybNmCBr1rirc0=,tag:ogpFMy8txSyuGfys86k9QA==,type:str]
darman_telegram_user_id: ENC[AES256_GCM,data:jdi/eFS8ZoQ=,iv:1aFs4vJjdXA2eXKxLJymcRUQtBRFyMVBNXGaTrcToo8=,tag:zpAqSpYdgs02J3WOzJwwNg==,type:str]
sops: sops:
age: age:
- enc: | - enc: |
@@ -31,7 +34,7 @@ sops:
oyJ7PS3lW+PxH5AZkeeU7gXO/pz2oDku0aDOds7kaD3n0+qSWicQ+Q== oyJ7PS3lW+PxH5AZkeeU7gXO/pz2oDku0aDOds7kaD3n0+qSWicQ+Q==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1eapjg6tdrr0fuvmgs3q3nlvnjkaxez298qynqqqxt0lpcv0lrsyq7ayxjk recipient: age1eapjg6tdrr0fuvmgs3q3nlvnjkaxez298qynqqqxt0lpcv0lrsyq7ayxjk
lastmodified: "2026-10-02T18:30:32Z" lastmodified: "2026-10-15T23:30:38Z"
mac: ENC[AES256_GCM,data:AHtMRFzzIfZQMHDaA1lV2geJ/O7CWgOJigS8IKk/8Y66H1gFQ4LPVBs86MpSaEmutSx7wzc/lTq+m0MPbVC9zoRidYjbhTzG2wbW0jxKvbPwqoBhE2x+UOTF7eWDPEKU2uttkjzlmHC2HT9G+zldEj7seW+6ElY5IQUG6WZ0Ils=,iv:Xr7iphCHeQd8sD06KQ2yo3ezvuHHDjOaDabisJUb3oc=,tag:vpbJigbu8Sek7m+rXw614A==,type:str] mac: ENC[AES256_GCM,data:cUtgKQ++tv3gupyFbNGaLHBHKCf6926N9a++xFFziTx9msXg5nztyWIalj8Spo4mW7hZiy1dQuyqkwxO2/ChdBnmnu2qF3JRH8k2BEJ6Cg6RmVHfvgoVefaDGv4lV+E2izloJJY0V1oKVnV6szZK+Pjkwsx8i6WqoXx8pMEMy5g=,iv:DqNRr1TOnT2ShNFRoYRwZaUoj5ZPzg0MF/cKxaqHiB4=,tag:AaphOTCdZlQZcQKsE+9fjQ==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+5 -2
View File
@@ -1,6 +1,9 @@
darman_password: ENC[AES256_GCM,data:iZQERcXtyH+91yUc3r7U6jnFYrGQPFeCPk/9ZDfxOhPLlGMX3/iEZ+SzZ7a7rDKUeUAaQUsrqANLDLclRYm4Ngo09EkbDxBx5x2GpQwlqSAS45LHnTen9LTzisWghdy79Xnilq322eaB3g==,iv:ozx/BPLR8nZTKHZroKrrh2z6ZlVCuLydQ3aNY4XvcIg=,tag:CSrq5ZipYxtXTT8RintuHQ==,type:str] darman_password: ENC[AES256_GCM,data:iZQERcXtyH+91yUc3r7U6jnFYrGQPFeCPk/9ZDfxOhPLlGMX3/iEZ+SzZ7a7rDKUeUAaQUsrqANLDLclRYm4Ngo09EkbDxBx5x2GpQwlqSAS45LHnTen9LTzisWghdy79Xnilq322eaB3g==,iv:ozx/BPLR8nZTKHZroKrrh2z6ZlVCuLydQ3aNY4XvcIg=,tag:CSrq5ZipYxtXTT8RintuHQ==,type:str]
pihole_webpassword: ENC[AES256_GCM,data:5iOTqD0CcbOCnM1b4+RbajMTyAU=,iv:2ZRW7dshnPzWkuudrn6n92y4Z2n/6fdnBB7BO5/ypS4=,tag:8UZSqJM6dVECQgrF6v5Fuw==,type:str] 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] 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: sops:
age: age:
- enc: | - enc: |
@@ -21,7 +24,7 @@ sops:
x6FfYadcRfqvSX60l6+TGdzq6xDpxLIZOJ8q19qZsAvB0in50HW5gg== x6FfYadcRfqvSX60l6+TGdzq6xDpxLIZOJ8q19qZsAvB0in50HW5gg==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1cpty7zrgnn6l97upq00w5wa8zcvnkxkdt2jvhlj97jh83exure4slha43t recipient: age1cpty7zrgnn6l97upq00w5wa8zcvnkxkdt2jvhlj97jh83exure4slha43t
lastmodified: "2026-09-18T19:44:32Z" lastmodified: "2026-10-15T23:32:42Z"
mac: ENC[AES256_GCM,data:PYNiUnDjBTgTAvTOAMk+XQEgcFSXLXgkw/vQCw0GhZsVHfkvd7jzkpk33ER64JqU4aPw+PRWo937mVKVEGDKkYVY2pP6hl2EJeOtfgjOuL9QpTNh+BKxDhYige5KsxPeMTEvtL7Y6dSsgAneaNPBEeLfZ0wiTVq1v2RJNgdNAGU=,iv:WYbyNn3/0QWXR7X8CHBKPPdVf0tYv8E4F4CYLjnuhVo=,tag:7ABexc8r6WZfskABUsquHg==,type:str] mac: ENC[AES256_GCM,data:r8TkYs9SwYpRS6edXqda9bYwUAtFkoM3LyHfDMLsRF5hHO/jtN1Mgjm0JP5t72S9PZPT4cZRvezrrVx7vzv19mTA/O5uL56l4POwtrZxRGMb+Yof/BlcBMkCTPpBSZZAMba5tBojd4ekwFewpp4mS+TyKULOn4B9kROuMNEmVVI=,iv:OanzbUHeE/PFHknpm5XAzBothZK6xkzZ/iJ2Uy7NhoI=,tag:DWMEaYCgM1jMGjuzu6yhug==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.3 version: 3.13.3
+6 -3
View File
@@ -8,6 +8,9 @@ headplane_oidc_client_secret: ENC[AES256_GCM,data:RiEESz1WHYH/smlJKmKFpPoF5HRYp8
headplane_headscale_api_key: ENC[AES256_GCM,data:KcwcprV100wfAkn+YM4+1oTfXkmyeAMAbXNpQKf2iIq0VxwqVep+fORrKmHiwDViciDoyxdMiT4scGlmd4vQRsWEHdDpkuH7MRHYu0hQepE3rSSQAMbK,iv:NEhmi2hiOE+uSIRZ4uXOK1UGpN+FQx/NpooWzTgwik8=,tag:KcPsD4gp51ERaFwgfA0BrQ==,type:str] headplane_headscale_api_key: ENC[AES256_GCM,data:KcwcprV100wfAkn+YM4+1oTfXkmyeAMAbXNpQKf2iIq0VxwqVep+fORrKmHiwDViciDoyxdMiT4scGlmd4vQRsWEHdDpkuH7MRHYu0hQepE3rSSQAMbK,iv:NEhmi2hiOE+uSIRZ4uXOK1UGpN+FQx/NpooWzTgwik8=,tag:KcPsD4gp51ERaFwgfA0BrQ==,type:str]
headscale_oidc_client_secret: ENC[AES256_GCM,data:262lZGgtmuXTuk3He1WyqyjcXrdnIiwNyWlXEYCGKYbKkWe0JPbUdWcwGVlZ+wXt71pzKuRDpZjgdibVTWYd71mohD/Ni6CwJm7dhf517DqznnYrxojZaSxRYXg/sCVSkwEvVseJ5z2yf/Led1VLNd3I1PaUIlwkdm2P91ps7mM=,iv:w/hu7siWwNAIw7g14bake5BP8ouA/b1SZdeukZXa/dw=,tag:vAXqWfSHwIdGAjR78gSpRg==,type:str] 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] 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: sops:
age: age:
- enc: | - enc: |
@@ -28,7 +31,7 @@ sops:
Wptkf76aP9UpjhgNkxzedRebQPB7ti+UiVqCvLVimtuHcsm/NJPcRg== Wptkf76aP9UpjhgNkxzedRebQPB7ti+UiVqCvLVimtuHcsm/NJPcRg==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1hp72xyx2cnd05937e4eww95g5kdtn0wsf9j2nypw330pa69gfdxqn0lpkp recipient: age1hp72xyx2cnd05937e4eww95g5kdtn0wsf9j2nypw330pa69gfdxqn0lpkp
lastmodified: "2026-08-21T23:14:15Z" lastmodified: "2026-10-15T23:32:01Z"
mac: ENC[AES256_GCM,data:O1wp0QLbfi7hn7+IoKkk+xqGYLX95y9KgVCsjyDjsv6eqiP+RPz5PmEqXapt926HREEPi4vcDW2FbaBMTqtsojbhWMTG0lYmV6zSQ4aDueL9/GmDqdOJDtQdbXhJH9gpAVhwGQzNoRDQ/5wjknDI8GSBVO077aSaaiGbreuuzBQ=,iv:yecrpLaDNFqt7XxHv/KDTXgjOs+5fk/6UXCSxPMuoJ0=,tag:m7co54lvtnZIYqSMX2c3kQ==,type:str] mac: ENC[AES256_GCM,data:sRD40rFUDkTc+mLJolKqtMXSubK+tMWTKZfyIrxl/mkAl3zHLET3J1aosKDZ1UhX0JWaBFV/lSxpt5yt/JkwwA93CXlllORP8hCwksb4RHbovLHDOrFWObZdHF/NrYmX9ZyWYiU5bgMS4xRPkl8N++CrJSPkvkVcBuD+QWStTgg=,iv:MGL/fEkYzPWja79QkLluOubFQA2KaX0Vfa8pUEKXS48=,tag:jKqdi5cgt6CDX2p9bbB3Pw==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.2 version: 3.13.3
+6 -3
View File
@@ -7,6 +7,9 @@ librechat_jwt_secret: ENC[AES256_GCM,data:f/gljrQPZIXeLHXtqKCCYGEu2pXgbZd69CjyEh
librechat_jwt_refresh_secret: ENC[AES256_GCM,data:N/yAPtaodJX4t2C2A0bZ/LQaVc8SBMgg3KYJrWRyXCM6HAmgHtSQ9nWJO2fl+7A966mMtYvpATYcBIPj/K5nig==,iv:k5ZYi2OKjL9Z+lhVgdNsmGVQm+iCqmF15H3TUTbofWk=,tag:NVTdvlL1lpwVhjo2c2phpg==,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] 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] 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]
sops: sops:
age: age:
- enc: | - enc: |
@@ -27,7 +30,7 @@ sops:
sHjKfw8VrrmAR4pQf1dsY+wcyh4FsZxhP3Q+QIVq3eCIXS9PeJkGAg== sHjKfw8VrrmAR4pQf1dsY+wcyh4FsZxhP3Q+QIVq3eCIXS9PeJkGAg==
-----END AGE ENCRYPTED FILE----- -----END AGE ENCRYPTED FILE-----
recipient: age1rfcmu6zh40v4260l9hnf8ajs9vly0s06rx3ey76eu78dp9t7getqyhmkut recipient: age1rfcmu6zh40v4260l9hnf8ajs9vly0s06rx3ey76eu78dp9t7getqyhmkut
lastmodified: "2026-09-20T20:02:50Z" lastmodified: "2026-10-15T23:24:57Z"
mac: ENC[AES256_GCM,data:fEgOKCOYrpnojw9yl3b7ZgJFCcmAs+DmY7etHgD5KNBtoZ3QgQUiTY5+kXvO5HMoENve+bUfyHymUDNjLlb45lItl9ZkAMKvTxGOe+5t0MR2X8BkB/2tjl/fS7CRBTJ0D4S84mH1hB2V2cfKcnGoKNsQyRJddi6OOey534QeV44=,iv:nQuRLkGklMXwkh8LpMC/Tmz1ewRiv8iKbK6IA88r2fA=,tag:LnzQc1sjrIdZ26AtH1Laxw==,type:str] mac: ENC[AES256_GCM,data:4h3bHgofztrcDz2VN7KhGxL6dlGTB8BUOwF6pdei+ysDV8PmEf6NNKYxwTln7zB+uiQDHdwZm3yxT/Bl9J/JbMV3amBT8JpqlhHTDWMpDdmS8n81wlcYokL75A0Ipp9YmxWhraDuX4bw4r6k0XpTqwaOtvHbT7pThcMuI6Ta+V0=,iv:RnqlhIbcp/vs7aFRwMW/H6eMK3Qxx6CMhDR3Ihy/tVs=,tag:sCcCOA2roUTqnXE+lYCCog==,type:str]
unencrypted_suffix: _unencrypted unencrypted_suffix: _unencrypted
version: 3.13.2 version: 3.13.3
+303
View File
@@ -0,0 +1,303 @@
# VM test for pass-broker.nix. Run:
# 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.
{ 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
'';
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.
sockProbe = pkgs.writers.writePython3Bin "sock-probe" { flakeIgnore = [ "E501" ]; } ''
import json
import socket
import sys
import time
s = socket.socket(socket.AF_UNIX)
if sys.argv[1] == "ghost":
s.connect("/run/pass-broker.sock")
req = {"vault": None, "item": "root@jupiter", "field": "password", "reason": "ghost"}
s.sendall(json.dumps(req).encode() + b"\n")
s.close()
else:
s.bind("/tmp/silent.sock")
s.listen(8)
time.sleep(3600)
'';
in
pkgs.testers.runNixOSTest {
name = "pass-broker";
nodes.machine = {
imports = [ ./pass-broker.nix ];
users.users.darman.isNormalUser = true;
users.users.eve.isNormalUser = true;
environment.systemPackages = [ pkgs.curl pkgs.jq tryGet sockProbe ];
systemd.tmpfiles.rules = [ "d /tmp/r 1777 root root -" ];
environment.etc = {
"pb/pat" = { text = "pst_test::key\n"; mode = "0400"; user = "pass-broker"; };
"pb/token" = { text = "123:test\n"; mode = "0400"; user = "pass-broker"; };
"pb/chat" = { text = "4242\n"; mode = "0400"; user = "pass-broker"; };
};
homelab.passBroker = {
enable = true;
passCli = fakePassCli;
patFile = "/etc/pb/pat";
approvalTimeout = 8;
telegram = {
apiBase = "http://127.0.0.1:8081";
tokenFile = "/etc/pb/token";
chatIdFile = "/etc/pb/chat";
};
rules = [
{ item = "darman@*"; }
{ item = "root@*"; grantMinutes = 0; }
{ item = "secret-*"; approval = "deny"; }
{ item = "auto-*"; approval = "auto"; }
];
};
systemd.services.fake-telegram = {
wantedBy = [ "multi-user.target" ];
serviceConfig.ExecStart = "${fakeTelegram}/bin/fake-telegram";
};
};
testScript = /* python */ ''
import json
import shlex
def tg():
return json.loads(machine.succeed("curl -s http://127.0.0.1:8081/"))
def wait_messages(n):
machine.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, sender=4242):
machine.succeed(f"curl -s -X POST 'http://127.0.0.1:8081/test/press?data={data}&from={sender}'")
def start(tag, item, user="darman"):
machine.succeed(f"su {user} -c 'try-get {tag} {item}' >/dev/null 2>&1 &")
def result(tag):
machine.wait_for_file(f"/tmp/r/{tag}.rc", timeout=30)
rc = int(machine.succeed(f"cat /tmp/r/{tag}.rc"))
return rc, machine.succeed(f"cat /tmp/r/{tag}.out").strip(), machine.succeed(f"cat /tmp/r/{tag}.err")
machine.wait_for_unit("pass-broker.socket")
machine.wait_for_open_port(8081)
with subtest("approval on Telegram serves the item, only the owner's tap counts"):
start("a", "darman@jupiter")
msg = wait_messages(1)
assert "darman@jupiter" in msg["text"] and "vm test" in msg["text"], msg
assert msg["chat_id"] == 4242, msg
press(button(msg, 0), sender=999)
machine.sleep(2)
machine.fail("test -e /tmp/r/a.rc")
assert any(a["text"] == "Not yours." for a in tg()["answers"])
press(button(msg, 0))
assert result("a")[:2] == (0, "hunter2"), result("a")
assert tg()["edits"][-1]["text"].endswith("approved")
with subtest("the grant covers the next request without asking"):
out = machine.succeed("su darman -c 'pass-broker get --item darman@jupiter --reason again'")
assert out.strip() == "hunter2"
assert len(tg()["messages"]) == 1
with subtest("deny refuses"):
start("c", "root@jupiter")
press(button(wait_messages(2), 1))
rc, out, err = result("c")
assert rc == 1 and out == "" and "denied" in err, (rc, out, err)
with subtest("grantMinutes = 0 asks every time; no answer expires; stale buttons are ignored"):
start("d", "root@jupiter")
press(button(wait_messages(3), 0))
assert result("d")[:2] == (0, "rootpw")
start("e", "root@jupiter")
wait_messages(4)
press(button(tg()["messages"][0], 0))
rc, out, err = result("e")
assert rc == 1 and "no answer" in err, (rc, out, err)
assert any(a["text"] == "Expired." for a in tg()["answers"])
assert tg()["edits"][-1]["text"].endswith("expired")
with subtest("policy: deny, unmatched and auto need no tap"):
err = machine.fail("su darman -c 'pass-broker get --item secret-note --reason x' 2>&1")
assert "policy denies" in err, err
err = machine.fail("su darman -c 'pass-broker get --item unlisted --reason x' 2>&1")
assert "no rule allows" in err, err
out = machine.succeed("su darman -c 'pass-broker get --item auto-item --reason x'")
assert out.strip() == "autopw"
assert len(tg()["messages"]) == 4
def views():
return int(machine.succeed("wc -l < /var/lib/pass-broker/reasons"))
def journal_has(text):
machine.wait_until_succeeds(f"journalctl -u pass-broker | grep -qF {shlex.quote(text)}")
with subtest("a client that hangs up mid-prompt withdraws it, and nothing is fetched"):
before = views()
start("f", "root@jupiter")
wait_messages(5)
machine.succeed("pkill -f 'vm test f'")
machine.wait_until_succeeds(
"curl -s http://127.0.0.1:8081/ | jq -e '.edits[-1].text | endswith(\"went away\")'"
)
journal_has("refused HomeLab/root@jupiter: requester went away")
assert views() == before
with subtest("a client queued behind another prompt can hang up without ever being asked"):
start("g", "root@jupiter")
msg = wait_messages(6)
start("h", "root@jupiter")
journal_has('reason="vm test h"')
machine.wait_until_succeeds("grep -q 'waiting for approval' /tmp/r/h.err")
machine.succeed("pkill -f 'vm test h'")
machine.wait_until_succeeds(
"test $(journalctl -u pass-broker | grep -c 'refused HomeLab/root@jupiter: requester went away') = 2"
)
press(button(msg, 0))
assert result("g")[:2] == (0, "rootpw")
assert len(tg()["messages"]) == 6
with subtest("a request whose client already hung up is dropped without a prompt"):
before = views()
machine.succeed("sock-probe ghost")
journal_has("dropped HomeLab/root@jupiter: requester went away")
machine.sleep(2)
assert len(tg()["messages"]) == 6
assert views() == before
with subtest("the client gives up on a broker that never answers"):
machine.succeed("sock-probe silent >/dev/null 2>&1 &")
machine.wait_for_file("/tmp/silent.sock")
machine.succeed("chmod 666 /tmp/silent.sock")
err = machine.fail(
"su darman -c 'PASS_BROKER_SOCKET=/tmp/silent.sock pass-broker get --item x --reason y' 2>&1"
)
assert "no answer within 30s" in err, err
with subtest("other users are refused, and darman cannot read the session"):
err = machine.fail("su eve -c 'pass-broker get --item auto-item --reason x' 2>&1")
assert "uid not allowed" in err, err
machine.fail("su darman -c 'ls /var/lib/pass-broker'")
machine.fail("su darman -c 'cat /etc/pb/pat'")
machine.succeed("systemctl show -p User pass-broker | grep -qx User=pass-broker")
with subtest("pass-cli gets the reason, tagged with the host"):
machine.succeed("grep -qx 'vm test a (pass-broker on machine)' /var/lib/pass-broker/reasons")
'';
}
+178
View File
@@ -0,0 +1,178 @@
{ config, pkgs, lib, ... }:
# pass-broker: Proton Pass items for darman's processes (Claude included),
# each gated by a tap on Telegram. The daemon runs as its own user and holds
# the host's only pass-cli session, an agent PAT scoped to the homelab vaults,
# so nothing running as darman can read the session itself. Client:
# `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.
let
cfg = config.homelab.passBroker;
pass-broker = pkgs.callPackage ../../pkgs/pass-broker.nix { };
stateDir = "/var/lib/pass-broker";
configFile = pkgs.writeText "pass-broker.json" (builtins.toJSON {
host = config.networking.hostName;
default_vault = cfg.vault;
allowed_users = cfg.users;
pass_cli = "${cfg.passCli}/bin/pass-cli";
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;
};
rules = map (r: {
inherit (r) vault item approval;
grant_minutes = r.grantMinutes;
}) cfg.rules;
});
in
{
options.homelab.passBroker = {
enable = lib.mkEnableOption "Telegram-approved Proton Pass broker";
passCli = lib.mkOption {
type = lib.types.package;
default = pkgs.proton-pass-cli;
defaultText = lib.literalExpression "pkgs.proton-pass-cli";
description = "Package providing bin/pass-cli.";
};
patFile = lib.mkOption {
type = lib.types.path;
description = "Agent personal access token (pst_…::…), readable by pass-broker.";
};
vault = lib.mkOption {
type = lib.types.str;
default = "HomeLab";
description = "Vault used when a request names none.";
};
users = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ "darman" ];
description = "Users allowed on the socket, besides root.";
};
approvalTimeout = lib.mkOption {
type = lib.types.int;
default = 120;
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.";
};
};
rules = lib.mkOption {
description = "First match wins; an item no rule matches is refused.";
default = [
{ item = "darman@*"; }
{ item = "root@*"; }
];
type = lib.types.listOf (lib.types.submodule {
options = {
vault = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "null = the default vault.";
};
item = lib.mkOption {
type = lib.types.str;
description = "Item title; `*` matches anything.";
};
approval = lib.mkOption {
type = lib.types.enum [ "auto" "ask" "deny" ];
default = "ask";
};
grantMinutes = lib.mkOption {
type = lib.types.int;
default = 10;
description = "How long one approval covers the item; 0 = this request only.";
};
};
});
};
};
config = lib.mkIf cfg.enable {
environment.systemPackages = [ pass-broker ];
users.users.pass-broker = {
isSystemUser = true;
group = "pass-broker";
home = stateDir;
};
users.groups.pass-broker = { };
# World-writable on purpose: the daemon checks the peer uid, so adding a
# client needs no group membership and no re-login.
systemd.sockets.pass-broker = {
wantedBy = [ "sockets.target" ];
socketConfig = {
ListenStream = "/run/pass-broker.sock";
SocketMode = "0666";
};
};
systemd.services.pass-broker = {
description = "Proton Pass broker (Telegram-approved)";
requires = [ "pass-broker.socket" ];
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
environment = {
PASS_BROKER_CONFIG = configFile;
HOME = stateDir;
# No keyring for a system user; the session key sits in the 0700 state dir.
PROTON_PASS_KEY_PROVIDER = "fs";
PROTON_PASS_DISABLE_TELEMETRY = "1";
PROTON_PASS_NO_UPDATE_CHECK = "1";
};
serviceConfig = {
ExecStart = "${pass-broker}/bin/pass-broker daemon";
User = "pass-broker";
Group = "pass-broker";
StateDirectory = "pass-broker";
StateDirectoryMode = "0700";
UMask = "0077";
Restart = "on-failure";
RestartSec = 5;
NoNewPrivileges = true;
ProtectSystem = "strict";
ProtectHome = true;
PrivateTmp = true;
PrivateDevices = true;
ProtectKernelTunables = true;
ProtectKernelModules = true;
ProtectControlGroups = true;
RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
RestrictNamespaces = true;
LockPersonality = true;
SystemCallArchitectures = "native";
};
};
};
}