Files
homelab/services/identity/pass-broker-test.nix
darmanandClaude Opus 5.5 e95726d69c 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>
2026-10-21 11:34:19 +02:00

222 lines
8.9 KiB
Nix

# 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 (pass-broker-fakes.nix).
{ pkgs }:
let
fakes = import ./pass-broker-fakes.nix { inherit pkgs; };
inherit (fakes) tryGet;
fakePassCli = fakes.passCli;
fakeTelegram = fakes.telegram;
# 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
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 fakeClaude ];
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 "\nBy: darman via " in msg["text"], msg
assert "\nCommand: bash try-get a darman@jupiter\n" 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()
# Frozen broker = the crash-loop case: the request waits in the socket
# while its client exits, and only then gets read.
machine.succeed("systemctl kill --signal=SIGSTOP pass-broker.service")
machine.succeed("sock-probe ghost")
machine.succeed("systemctl kill --signal=SIGCONT pass-broker.service")
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("a request from under Claude Code is labelled as such"):
assert machine.succeed("su darman -c claude").strip() == "autopw"
journal_has('reason="from claude" by darman via Claude Code [bash claude]')
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")
'';
}