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:
@@ -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")
|
||||
'';
|
||||
}
|
||||
@@ -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";
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user