feat(mars): pass-broker approval gateway for every host

A Telegram bot has a single getUpdates consumer, so a broker per host
would split approval taps between them. mars now runs the gateway: the
bot's only poller, relaying prompts and taps for terra's and titan's
brokers over the tailnet (:8097) without ever seeing an item. Each broker
authenticates with its own pass_broker_gateway_token; mars holds only the
sha256, and the prompt is labelled with the host that token belongs to.

The bot token and chat id move to mars and are dropped from the other
hosts' sops files (terra.yaml also loses its leftover LibreChat keys and
gains protonvpn_wg_private_key, which a later commit uses). Covered by
checks.pass-broker-gateway (two nodes: labels, cancel, expiry, per-host
token isolation, gateway down); the fakes are shared with checks.pass-broker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 11:34:19 +02:00
co-authored by Claude Opus 5.5
parent 760e353335
commit e95726d69c
24 changed files with 1164 additions and 250 deletions
+106
View File
@@ -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
'';
}
@@ -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)
'';
}
+108
View File
@@ -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";
};
};
};
}
+8 -105
View File
@@ -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
+58 -21
View File
@@ -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 = {