diff --git a/CLAUDE.md b/CLAUDE.md index f34277f..6b0d44c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 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 --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 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 # proxy, registry validation, caddy routes, reboot persistence 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 @@ -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 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". +- **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` (`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. diff --git a/flake.nix b/flake.nix index 05a37d1..d2f504d 100644 --- a/flake.nix +++ b/flake.nix @@ -533,6 +533,12 @@ luna-sites = import ./hosts/mars/luna-sites-test.nix { 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. diff --git a/hosts/terra/configuration.nix b/hosts/terra/configuration.nix index eee7395..1841f41 100644 --- a/hosts/terra/configuration.nix +++ b/hosts/terra/configuration.nix @@ -21,6 +21,7 @@ in ../../services/desktop/claude-desktop.nix ../../services/desktop/librechat.nix ../../services/desktop/luna-voice.nix + ../../services/identity/pass-broker.nix ../../services/dev/turtle-beach-re.nix inputs.turtle-beach-swarm-re.nixosModules.release inputs.tbctl.nixosModules.tbctl @@ -105,6 +106,16 @@ in environment.systemPackages = [ unstable.proton-pass-cli ]; + # Proton Pass for scripts/deploy and Claude, one Telegram tap per use. Your + # own pass-cli stays logged out here: the broker's session is the only one. + 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 # while the polkit dialog is still open (slow typing, a vault lookup). # Scoped to run0 so a hung systemctl doesn't also wait 5min. diff --git a/hosts/terra/secrets.nix b/hosts/terra/secrets.nix index f2d1087..3f0b90d 100644 --- a/hosts/terra/secrets.nix +++ b/hosts/terra/secrets.nix @@ -39,6 +39,13 @@ sops.secrets.hermes_api_server_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_iv = { }; sops.secrets.librechat_jwt_secret = { }; diff --git a/pkgs/pass-broker.nix b/pkgs/pass-broker.nix new file mode 100644 index 0000000..ff6c73e --- /dev/null +++ b/pkgs/pass-broker.nix @@ -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; + }; +} diff --git a/pkgs/pass-broker/Cargo.lock b/pkgs/pass-broker/Cargo.lock new file mode 100644 index 0000000..2ef4f98 --- /dev/null +++ b/pkgs/pass-broker/Cargo.lock @@ -0,0 +1,1290 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pass-broker" +version = "0.1.0" +dependencies = [ + "anyhow", + "reqwest", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/pkgs/pass-broker/Cargo.toml b/pkgs/pass-broker/Cargo.toml new file mode 100644 index 0000000..0845cc0 --- /dev/null +++ b/pkgs/pass-broker/Cargo.toml @@ -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 diff --git a/pkgs/pass-broker/src/client.rs b/pkgs/pass-broker/src/client.rs new file mode 100644 index 0000000..7220fa6 --- /dev/null +++ b/pkgs/pass-broker/src/client.rs @@ -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); +} diff --git a/pkgs/pass-broker/src/config.rs b/pkgs/pass-broker/src/config.rs new file mode 100644 index 0000000..3ca10a2 --- /dev/null +++ b/pkgs/pass-broker/src/config.rs @@ -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")); + } +} diff --git a/pkgs/pass-broker/src/daemon.rs b/pkgs/pass-broker/src/daemon.rs new file mode 100644 index 0000000..be9c48f --- /dev/null +++ b/pkgs/pass-broker/src/daemon.rs @@ -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(), + } +} diff --git a/pkgs/pass-broker/src/main.rs b/pkgs/pass-broker/src/main.rs new file mode 100644 index 0000000..72b1bf1 --- /dev/null +++ b/pkgs/pass-broker/src/main.rs @@ -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); + } + } +} diff --git a/pkgs/pass-broker/src/pass.rs b/pkgs/pass-broker/src/pass.rs new file mode 100644 index 0000000..dbfbc97 --- /dev/null +++ b/pkgs/pass-broker/src/pass.rs @@ -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)?) + } +} diff --git a/pkgs/pass-broker/src/proto.rs b/pkgs/pass-broker/src/proto.rs new file mode 100644 index 0000000..2eef93b --- /dev/null +++ b/pkgs/pass-broker/src/proto.rs @@ -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 }, +} diff --git a/pkgs/pass-broker/src/telegram.rs b/pkgs/pass-broker/src/telegram.rs new file mode 100644 index 0000000..e8dce9b --- /dev/null +++ b/pkgs/pass-broker/src/telegram.rs @@ -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()) +} diff --git a/scripts/deploy b/scripts/deploy index 5a868b0..893de9d 100755 --- a/scripts/deploy +++ b/scripts/deploy @@ -18,7 +18,8 @@ # 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 -# <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. set -euo pipefail shopt -s nullglob @@ -386,6 +387,15 @@ require_tracked() { # real on darman@neptun, which had both an Active and a Trashed copy). proton_pass_password() { 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 # Lines look like: - [ITEM_ID]: the title (state=Active) diff --git a/secrets/jupiter.yaml b/secrets/jupiter.yaml index 4bcf8b5..c7379f5 100644 --- a/secrets/jupiter.yaml +++ b/secrets/jupiter.yaml @@ -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] gitea_hermes_webhook_secret: ENC[AES256_GCM,data:Q8e+mj05MJI7CEJwRonpOmQphAZ0CfnZFoGxrDSSiyHoH3BNhqBU5gBmzuu+6NK9OS33kN+JnFvrwCeEzVxooA==,iv:mdsKOMD5B0Jzh1YRmRh71P8Io9RFtI6aqAky5x+WxOQ=,tag:v3LKz5a8ayl7WAzIPbwj6Q==,type:str] couchdb_admin_password: ENC[AES256_GCM,data:QHkCFUwLbQdd5yKETI5qAz4CkEfsPcl2iCU8F9mX3PA=,iv:2dPNKjjoXEgm7wfC6MlhQTMvAXSNDtaXnjWl2ldl4fk=,tag:1ZltqH94Q5/6GbXAnaIgdg==,type:str] +pass_broker_pat: ENC[AES256_GCM,data:4rO5srDthuvDObbhVkHCCm5vblkwbIDtT3c/Eg0KxiVavfoQbmK2RBPOylBLR3v/9wcXEkdQzk8f0N98SkaSr9dB4oe8CbZc91aA9zgCnI8qR7coWCmBJin/wYjcVhX91sxg9Xz81sBWZK3PtrgELFo=,iv:znQrJzdWcsBtK4Rnz/vUIQcU8M3anRm1UGlCJQ/t35U=,tag:fHZLaMm3a3Y/4kf/KEL12A==,type:str] +pass_broker_telegram_token: ENC[AES256_GCM,data:JMm7tGxncQkVS00goTv7zrSrXVUhFmsTeswoTU0deV3YiFDPg6pEuuSZIH2Blg==,iv:PJiA6u0hs20YhD0Ct+I3Bluc2+ugsg2j7QhpwP+lX4I=,tag:Vl53sodg5Ik2yYwMZdozYA==,type:str] +darman_telegram_user_id: ENC[AES256_GCM,data:oocFRYiOWw4=,iv:OGVpIJ4IcgpbyFOEGY9Y90YHJxjy7FrLlQL7qoo+ax4=,tag:p4tuT8QKkUN/lUA9Xt/g9A==,type:str] sops: age: - enc: | @@ -36,7 +39,7 @@ sops: CzjSDQZTcseEXZNwuzZcfB5Mvq0BQvjOj7lGuxzuE4qwWkdJWGfVLQ== -----END AGE ENCRYPTED FILE----- recipient: age1zak7glavmg4026p2389fyqe769vqm4jrryknuqckgqq4merz5f7q44rkkt - lastmodified: "2026-08-25T20:39:37Z" - mac: ENC[AES256_GCM,data:Z59BCw8gETfddXqul4LXrq6V3LBJA1itF7A1VNUERwK4NfaUGwWUhbl9h7YF/srzgtg9yGjbFB/f5kwmT3k/TWTG+C0M/4KOyTVs4y5UvB9gI4g8awYbtnFDPRAcqqcxoMD0sgapgVcNh48KWv76ndF6UGn+QfWn9eF4KBP+ZzQ=,iv:57myu1aTMMSLTz+1ldwxdusnzh8cyPwrLiEIx3rLS9w=,tag:isthpdOydD4ZNoFZyflViw==,type:str] + lastmodified: "2026-10-15T23:31:28Z" + mac: ENC[AES256_GCM,data:vKhvZ2zibAbyswIzoa2eefS9ym4K3OBoG4bIb0a10zU2vPD4McfrhIBYdVl93hfInGPZwT2Sxd76Sd6AXE0lyo1EB4WzqFsCL2y4DHY5j2iQroqoQQS2TRvM5Sjylfij9OPAbtMTLKiome40Q/qZL2XURBTS0eXIopvWnbQGsX0=,iv:VmOd6+6Z2blaHxa+jdARd7ctCCXM6zzHicKVnFdm3P4=,tag:JCu5wXdtqtViIjULCEdlGw==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/mars.yaml b/secrets/mars.yaml index 862c5b0..32620a5 100644 --- a/secrets/mars.yaml +++ b/secrets/mars.yaml @@ -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] 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] +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: age: - enc: | @@ -31,7 +34,7 @@ sops: oyJ7PS3lW+PxH5AZkeeU7gXO/pz2oDku0aDOds7kaD3n0+qSWicQ+Q== -----END AGE ENCRYPTED FILE----- recipient: age1eapjg6tdrr0fuvmgs3q3nlvnjkaxez298qynqqqxt0lpcv0lrsyq7ayxjk - lastmodified: "2026-10-02T18:30:32Z" - mac: ENC[AES256_GCM,data:AHtMRFzzIfZQMHDaA1lV2geJ/O7CWgOJigS8IKk/8Y66H1gFQ4LPVBs86MpSaEmutSx7wzc/lTq+m0MPbVC9zoRidYjbhTzG2wbW0jxKvbPwqoBhE2x+UOTF7eWDPEKU2uttkjzlmHC2HT9G+zldEj7seW+6ElY5IQUG6WZ0Ils=,iv:Xr7iphCHeQd8sD06KQ2yo3ezvuHHDjOaDabisJUb3oc=,tag:vpbJigbu8Sek7m+rXw614A==,type:str] + lastmodified: "2026-10-15T23:30:38Z" + mac: ENC[AES256_GCM,data:cUtgKQ++tv3gupyFbNGaLHBHKCf6926N9a++xFFziTx9msXg5nztyWIalj8Spo4mW7hZiy1dQuyqkwxO2/ChdBnmnu2qF3JRH8k2BEJ6Cg6RmVHfvgoVefaDGv4lV+E2izloJJY0V1oKVnV6szZK+Pjkwsx8i6WqoXx8pMEMy5g=,iv:DqNRr1TOnT2ShNFRoYRwZaUoj5ZPzg0MF/cKxaqHiB4=,tag:AaphOTCdZlQZcQKsE+9fjQ==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/mercury.yaml b/secrets/mercury.yaml index 4ec6587..fb85595 100644 --- a/secrets/mercury.yaml +++ b/secrets/mercury.yaml @@ -1,6 +1,9 @@ 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] tailscale_authkey: ENC[AES256_GCM,data:h3jbN9SrPZwUlYJPEbydvcf9tP/qGQPegnY87AYKOj9AsqAgxeEKfLYwtNeksLgcNBvCoJ1ALk7gqfrMw6sCrW7S7IFlDYhSJDAPfFkR6iczInBDpSfISg==,iv:ML+l4nmPfmSoTGQnNWpdxGZkdaq5HKEHaUxKcblmR8w=,tag:BCAbJ6Iy5ziBNLiOuI/5PA==,type:str] +pass_broker_pat: ENC[AES256_GCM,data:yifofOjuajr7UN045S9WlScnzgK91nmQm9f6qzhZs2eBIntjZW+jr0P/EhESD7rDp1ckN7pL8yMdERRJIcCkjI7yTqFC6Q8w/dBHVG5DmeoZXCdY4OkGvVNKoyFBbSbm1T1Hi38r/rDle4zNDOoJKjA=,iv:WJNhzDrXGI+NnJpsqcFQoEwFI0sEGysk16yPPq9HdTI=,tag:d6JgY0DXjopEgOGRd2KdeA==,type:str] +pass_broker_telegram_token: ENC[AES256_GCM,data:x+mz8QykafDBzFK2+2jOPKTD/2Z5bRZcy8P5mN+/qZVoHHAeSbAGrIqmKBVRrQ==,iv:VI7pADIesa8Dk9BCSAXEoUti37m4ZHIjvI+gGD+5IKI=,tag:jEuP3KJO+hJvIrI1brUP5Q==,type:str] +darman_telegram_user_id: ENC[AES256_GCM,data:NPESqxacvBY=,iv:OoDE6qp4atptRwAe88ORYan8XzSBxoU+dzOtHmUzjrk=,tag:6ecraLo/jUYD61YFYGsOFw==,type:str] sops: age: - enc: | @@ -21,7 +24,7 @@ sops: x6FfYadcRfqvSX60l6+TGdzq6xDpxLIZOJ8q19qZsAvB0in50HW5gg== -----END AGE ENCRYPTED FILE----- recipient: age1cpty7zrgnn6l97upq00w5wa8zcvnkxkdt2jvhlj97jh83exure4slha43t - lastmodified: "2026-09-18T19:44:32Z" - mac: ENC[AES256_GCM,data:PYNiUnDjBTgTAvTOAMk+XQEgcFSXLXgkw/vQCw0GhZsVHfkvd7jzkpk33ER64JqU4aPw+PRWo937mVKVEGDKkYVY2pP6hl2EJeOtfgjOuL9QpTNh+BKxDhYige5KsxPeMTEvtL7Y6dSsgAneaNPBEeLfZ0wiTVq1v2RJNgdNAGU=,iv:WYbyNn3/0QWXR7X8CHBKPPdVf0tYv8E4F4CYLjnuhVo=,tag:7ABexc8r6WZfskABUsquHg==,type:str] + lastmodified: "2026-10-15T23:32:42Z" + mac: ENC[AES256_GCM,data:r8TkYs9SwYpRS6edXqda9bYwUAtFkoM3LyHfDMLsRF5hHO/jtN1Mgjm0JP5t72S9PZPT4cZRvezrrVx7vzv19mTA/O5uL56l4POwtrZxRGMb+Yof/BlcBMkCTPpBSZZAMba5tBojd4ekwFewpp4mS+TyKULOn4B9kROuMNEmVVI=,iv:OanzbUHeE/PFHknpm5XAzBothZK6xkzZ/iJ2Uy7NhoI=,tag:DWMEaYCgM1jMGjuzu6yhug==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 diff --git a/secrets/neptun.yaml b/secrets/neptun.yaml index d5a11ff..d3963e4 100644 --- a/secrets/neptun.yaml +++ b/secrets/neptun.yaml @@ -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] headscale_oidc_client_secret: ENC[AES256_GCM,data:262lZGgtmuXTuk3He1WyqyjcXrdnIiwNyWlXEYCGKYbKkWe0JPbUdWcwGVlZ+wXt71pzKuRDpZjgdibVTWYd71mohD/Ni6CwJm7dhf517DqznnYrxojZaSxRYXg/sCVSkwEvVseJ5z2yf/Led1VLNd3I1PaUIlwkdm2P91ps7mM=,iv:w/hu7siWwNAIw7g14bake5BP8ouA/b1SZdeukZXa/dw=,tag:vAXqWfSHwIdGAjR78gSpRg==,type:str] caddy_acme_email: ENC[AES256_GCM,data:j+iPz4lt0Gqs2SKHTS53,iv:DQNfcpYy2v93sKeCvXzLOoBhAo0PjZrxHgFD1oVqYu8=,tag:1yPH/2cW/IiRi9lT8dELEg==,type:str] +pass_broker_pat: ENC[AES256_GCM,data:SSyRLiGgDV0A/qVvIYjX1OfmqnsAaZ4vfenAluMC00AlB9r6vfmFWk5+LKYuaq0tGDWw4s2pOxkNvju66o8a0JOR2wqXKLuK51BxrpR9Fruuew2tIs4+ydXu0jqhZE6APhOU9+QcDt5IbHQZPXbO/JA=,iv:l1RFTjV1N6q2whj5LKOylkOZ+ZcNzh29ury+XhquKRU=,tag:O9xKHZQ1fgkbmEjsNF66bg==,type:str] +pass_broker_telegram_token: ENC[AES256_GCM,data:VoWGtKaU69MD/KwvQll+PFzfbwTIOyxEF/ktcPY0YnFXbaUYONlYgk3jaNfnvA==,iv:BnS2/MtIXGRysBVT8yE3wuaULV9DbSOlCKVpNQ2fmhQ=,tag:+plI73w1h1bk18RqrbCbQw==,type:str] +darman_telegram_user_id: ENC[AES256_GCM,data:uMmNPR3go2k=,iv:tXEgAFABOrExLsGyRWpkHsp6i3h0BgI+eMmsPK+Gi3s=,tag:P7WeeeA2nC7po5J0H6FAfA==,type:str] sops: age: - enc: | @@ -28,7 +31,7 @@ sops: Wptkf76aP9UpjhgNkxzedRebQPB7ti+UiVqCvLVimtuHcsm/NJPcRg== -----END AGE ENCRYPTED FILE----- recipient: age1hp72xyx2cnd05937e4eww95g5kdtn0wsf9j2nypw330pa69gfdxqn0lpkp - lastmodified: "2026-08-21T23:14:15Z" - mac: ENC[AES256_GCM,data:O1wp0QLbfi7hn7+IoKkk+xqGYLX95y9KgVCsjyDjsv6eqiP+RPz5PmEqXapt926HREEPi4vcDW2FbaBMTqtsojbhWMTG0lYmV6zSQ4aDueL9/GmDqdOJDtQdbXhJH9gpAVhwGQzNoRDQ/5wjknDI8GSBVO077aSaaiGbreuuzBQ=,iv:yecrpLaDNFqt7XxHv/KDTXgjOs+5fk/6UXCSxPMuoJ0=,tag:m7co54lvtnZIYqSMX2c3kQ==,type:str] + lastmodified: "2026-10-15T23:32:01Z" + mac: ENC[AES256_GCM,data:sRD40rFUDkTc+mLJolKqtMXSubK+tMWTKZfyIrxl/mkAl3zHLET3J1aosKDZ1UhX0JWaBFV/lSxpt5yt/JkwwA93CXlllORP8hCwksb4RHbovLHDOrFWObZdHF/NrYmX9ZyWYiU5bgMS4xRPkl8N++CrJSPkvkVcBuD+QWStTgg=,iv:MGL/fEkYzPWja79QkLluOubFQA2KaX0Vfa8pUEKXS48=,tag:jKqdi5cgt6CDX2p9bbB3Pw==,type:str] unencrypted_suffix: _unencrypted - version: 3.13.2 + version: 3.13.3 diff --git a/secrets/terra.yaml b/secrets/terra.yaml index 2a31fbd..25ff3a1 100644 --- a/secrets/terra.yaml +++ b/secrets/terra.yaml @@ -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] hermes_api_server_key: ENC[AES256_GCM,data:NU+6zVmUeM9+m5eZCPdCiMLo76GqbsRxNM7EmVM2TmKTOUL2af7Msg==,iv:EMd7JKhQ3ZkFPi2xMGZ+mHHK05qQVDR+ZCbiYcWdhHU=,tag:JaElU4CyvD5qQbehHbM5qQ==,type:str] elevenlabs_api_key: ENC[AES256_GCM,data:4IBKKMxor1sJ1skh1pgLrQnNX31cgQFiy89O1TZn71QHaq+xY7p+7JLtmGkhbZ10l12m,iv:Ww5RLYuv09xD1deFgM89u0wZ3hZ/0Pndda0kreMx2aQ=,tag:opgIPsDwSc+rLqseqjP6Gg==,type:str] +pass_broker_pat: ENC[AES256_GCM,data:A4NrFBQIL6waKSaVB4EZnxLp4RWkm1hGZcHGBd5qSh+BPv7gvj+g9vjFhkCwXgAinBekxo0GOhf/Ip4zK+KWZwNTzF8MXjAkSARnFQgXiFAncaEVzXGho1TVYvYAN1PRQxEu79bYS0IG5+ZOw0VVpjw=,iv:vLiojJJrl6yC83stsNoXLZX762z8nM0Jx164lx7XVjs=,tag:K8zFZ5bb8QeADmsLf0o6pw==,type:str] +pass_broker_telegram_token: ENC[AES256_GCM,data:iSyl9sm82yfN+EGKGCd4Px3WbkW9/pb026tqKJdHGWVvDIX0g5yRl+KXetMMVg==,iv:w1zukDV9L/gfe0lFmgrebjaenBz8vraCi0GQr+TJTPw=,tag:wKhpWDSQVwNqxILFuLQBIA==,type:str] +darman_telegram_user_id: ENC[AES256_GCM,data:IPPf4Sf99qc=,iv:uJBSGlVwDrhSQUeE5seQGKaPiD1mumORYE8NX+rBWjo=,tag:hFTbzVmekZJZk2je1OWpTQ==,type:str] sops: age: - enc: | @@ -27,7 +30,7 @@ sops: sHjKfw8VrrmAR4pQf1dsY+wcyh4FsZxhP3Q+QIVq3eCIXS9PeJkGAg== -----END AGE ENCRYPTED FILE----- recipient: age1rfcmu6zh40v4260l9hnf8ajs9vly0s06rx3ey76eu78dp9t7getqyhmkut - lastmodified: "2026-09-20T20:02:50Z" - mac: ENC[AES256_GCM,data:fEgOKCOYrpnojw9yl3b7ZgJFCcmAs+DmY7etHgD5KNBtoZ3QgQUiTY5+kXvO5HMoENve+bUfyHymUDNjLlb45lItl9ZkAMKvTxGOe+5t0MR2X8BkB/2tjl/fS7CRBTJ0D4S84mH1hB2V2cfKcnGoKNsQyRJddi6OOey534QeV44=,iv:nQuRLkGklMXwkh8LpMC/Tmz1ewRiv8iKbK6IA88r2fA=,tag:LnzQc1sjrIdZ26AtH1Laxw==,type:str] + lastmodified: "2026-10-15T23:24:57Z" + mac: ENC[AES256_GCM,data:4h3bHgofztrcDz2VN7KhGxL6dlGTB8BUOwF6pdei+ysDV8PmEf6NNKYxwTln7zB+uiQDHdwZm3yxT/Bl9J/JbMV3amBT8JpqlhHTDWMpDdmS8n81wlcYokL75A0Ipp9YmxWhraDuX4bw4r6k0XpTqwaOtvHbT7pThcMuI6Ta+V0=,iv:RnqlhIbcp/vs7aFRwMW/H6eMK3Qxx6CMhDR3Ihy/tVs=,tag:sCcCOA2roUTqnXE+lYCCog==,type:str] unencrypted_suffix: _unencrypted - version: 3.13.2 + version: 3.13.3 diff --git a/services/identity/pass-broker-test.nix b/services/identity/pass-broker-test.nix new file mode 100644 index 0000000..7cba949 --- /dev/null +++ b/services/identity/pass-broker-test.nix @@ -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") + ''; +} diff --git a/services/identity/pass-broker.nix b/services/identity/pass-broker.nix new file mode 100644 index 0000000..43e01c4 --- /dev/null +++ b/services/identity/pass-broker.nix @@ -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"; + }; + }; + }; +}