commit 67b11b0c617f178afe0706c9781f9421e1ad7212 Author: Jack O'Sullivan Date: Sun Nov 22 21:55:31 2026 +0000 broker: Add approval broker for coding agents `slop-broker` runs privileged operations for coding agents under named policies (auto, ask or deny per operation), which requesters can share, with approvals from `slop-approve` or Home Assistant notifications and optional leases. The broker and the `slop` client talk over vsock, so a VM needs no network path to it. Messages are typed enums shared by both, CBOR-encoded and framed with `LengthDelimitedCodec`; decoding validates every value, and requests carry a protocol version. The first operation is `slop ssh`. The `services.slop-broker` NixOS module runs the broker as a hardened service from generated TOML, and a VM test exercises it over vsock loopback. devenv provides the development environment. Co-Authored-By: Claude Opus 5.5 diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..baea1fa --- /dev/null +++ b/.envrc @@ -0,0 +1,4 @@ +# devenv from this flake's nixpkgs, so it needn't be installed +PATH_add "$(nix build --no-link --print-out-paths --inputs-from . nixpkgs#devenv)/bin" +eval "$(devenv direnvrc)" +use devenv diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed9f4d5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +/result* +/.direnv +/.devenv* +/devenv.local.nix +/devenv.local.yaml diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..0ea19c1 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1548 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +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 = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "clap" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[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" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[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-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "humantime" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +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 = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.31.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[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 = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[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 = "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 = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[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.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[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 = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[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.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[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_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + +[[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 3.0.10", +] + +[[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_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[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 = "slop-broker" +version = "0.1.0" +dependencies = [ + "anyhow", + "bytes", + "ciborium", + "clap", + "futures-util", + "hex", + "humantime", + "nix", + "rand", + "rustls", + "serde", + "serde_bytes", + "serde_json", + "tempfile", + "tokio", + "tokio-tungstenite", + "tokio-util", + "tokio-vsock", + "toml", + "url", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[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 = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[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 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "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 3.0.10", +] + +[[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 = "tokio-tungstenite" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "489a59b6730eda1b0171fcfda8b121f4bee2b35cba8645ca35c5f7ba3eb736c1" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-vsock" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "676ade3d183052ca2703288b48f63a2e82633a24836ca279eb6724ab2a97b05d" +dependencies = [ + "bytes", + "futures", + "libc", + "tokio", + "vsock", +] + +[[package]] +name = "toml" +version = "0.9.12+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow 0.7.15", +] + +[[package]] +name = "toml_datetime" +version = "0.7.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + +[[package]] +name = "tungstenite" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadc29d668c91fcc564941132e17b28a7ceb2f3ebf0b9dae3e03fd7a6748eb0d" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[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 = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vsock" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7d4dba01e366e2ffbdf0700b1876f747c548db72dced534de41c54945c0148" +dependencies = [ + "libc", + "nix", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +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 = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +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 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[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.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..54770d2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "slop-broker" +version = "0.1.0" +edition = "2024" +description = "Approval broker that runs privileged operations for coding agents" +license = "MIT" + +[dependencies] +anyhow = "1" +bytes = "1" +ciborium = "0.2" +clap = { version = "4", features = ["derive", "env"] } +futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } +hex = "0.4" +humantime = "2" +# Already a dependency of `tokio-vsock` +nix = { version = "0.31", default-features = false, features = ["signal", "user"] } +rand = "0.9" +rustls = { version = "0.23", default-features = false, features = ["ring", "std"] } +serde = { version = "1", features = ["derive"] } +serde_bytes = "0.11" +serde_json = "1" +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = { version = "0.27", features = ["rustls-tls-webpki-roots"] } +tokio-util = { version = "0.7", features = ["codec"] } +tokio-vsock = "0.7" +toml = { version = "0.9", default-features = false, features = ["parse", "serde", "std"] } +url = "2" + +[dev-dependencies] +tempfile = "3" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..63b7bdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Jack O'Sullivan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/devenv.lock b/devenv.lock new file mode 100644 index 0000000..e85a896 --- /dev/null +++ b/devenv.lock @@ -0,0 +1,45 @@ +{ + "nodes": { + "devenv": { + "locked": { + "dir": "src/modules", + "lastModified": 1795229503, + "narHash": "sha256-FTGzSZYleBgDbPCyeYAnhL5tltIMqxGDxvyEfkw+uXU=", + "owner": "cachix", + "repo": "devenv", + "rev": "ba35fb7169f0a768075e91efab82dce0db31b536", + "type": "github" + }, + "original": { + "dir": "src/modules", + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1795234589, + "narHash": "sha256-f/VVvxf5RsQgWVhUtefoca5ktVg0DA2bnkMOcmSnozo=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} \ No newline at end of file diff --git a/devenv.nix b/devenv.nix new file mode 100644 index 0000000..b7bac77 --- /dev/null +++ b/devenv.nix @@ -0,0 +1,21 @@ +# The development environment: `devenv shell`, or direnv with `.envrc`. The package, modules and +# checks are in `flake.nix`. +{ pkgs, ... }: +{ + languages.rust.enable = true; + + packages = with pkgs; [ nixpkgs-fmt ]; + + scripts = { + vm-test = { + description = "Run the NixOS VM test of the broker module (needs KVM)"; + exec = ''nix build -L --no-link "$DEVENV_ROOT#checks.x86_64-linux.vm" "$@"''; + }; + }; + + # `devenv test` + enterTest = '' + cargo clippy --all-targets -- -D warnings + cargo test + ''; +} diff --git a/devenv.yaml b/devenv.yaml new file mode 100644 index 0000000..63df8b7 --- /dev/null +++ b/devenv.yaml @@ -0,0 +1,4 @@ +# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json +inputs: + nixpkgs: + url: github:NixOS/nixpkgs/nixos-unstable diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..1b51811 --- /dev/null +++ b/flake.lock @@ -0,0 +1,27 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1795234589, + "narHash": "sha256-f/VVvxf5RsQgWVhUtefoca5ktVg0DA2bnkMOcmSnozo=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "2786a2a72088ecf32aea5b3ec52099e6a7cff78f", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..2008611 --- /dev/null +++ b/flake.nix @@ -0,0 +1,55 @@ +{ + description = "Approval broker that runs privileged operations for coding agents"; + + inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + + outputs = { self, nixpkgs }: + let + inherit (nixpkgs) lib; + + systems = [ "x86_64-linux" "aarch64-linux" ]; + forSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system}); + + # Each module defaults its `package` to this flake's build for the system it's used on + withPackage = path: option: { lib, pkgs, ... }: { + imports = [ path ]; + config = lib.setAttrByPath (option ++ [ "package" ]) + (lib.mkDefault self.packages.${pkgs.stdenv.hostPlatform.system}.default); + }; + in + { + packages = forSystems (pkgs: rec { + slop-broker = pkgs.callPackage ./nix/package.nix { }; + default = slop-broker; + }); + + overlays.default = final: _prev: { + slop-broker = final.callPackage ./nix/package.nix { }; + }; + + nixosModules = { + slop-broker = withPackage ./nix/modules/nixos/broker.nix [ "services" "slop-broker" ]; + default = { + imports = with self.nixosModules; [ slop-broker ]; + }; + }; + + # The VM test needs KVM + checks = forSystems (pkgs: { + package = self.packages.${pkgs.stdenv.hostPlatform.system}.default; + vm = pkgs.callPackage ./nix/vm-test.nix { slop-broker = self.packages.${pkgs.stdenv.hostPlatform.system}.default; }; + }); + + # A plain alternative to the devenv shell, for `nix develop`: the toolchain and the build's + # inputs, without devenv's scripts or the demo + devShells = forSystems (pkgs: { + default = pkgs.mkShell { + inputsFrom = [ self.packages.${pkgs.stdenv.hostPlatform.system}.default ]; + packages = with pkgs; [ clippy rustfmt rust-analyzer git nixpkgs-fmt ]; + RUST_SRC_PATH = pkgs.rustPlatform.rustLibSrc; + }; + }); + + formatter = forSystems (pkgs: pkgs.nixpkgs-fmt); + }; +} diff --git a/nix/modules/nixos/broker.nix b/nix/modules/nixos/broker.nix new file mode 100644 index 0000000..2414977 --- /dev/null +++ b/nix/modules/nixos/broker.nix @@ -0,0 +1,196 @@ +# The broker daemon (`services.slop-broker`): writes its TOML configuration and runs it hardened +# as its own user. +{ lib, pkgs, config, ... }: +let + inherit (builtins) any attrNames attrValues isAttrs isList; + inherit (lib) mkIf mkOption mapAttrs filterAttrs optional optionals hasPrefix concatStringsSep; + + mkOpt' = type: default: description: mkOption { inherit type default description; }; + mkBoolOpt' = default: description: mkOpt' lib.types.bool default description; + + cfg = config.services.slop-broker; + ha = cfg.homeAssistant; + + isRuntimePath = p: hasPrefix "/" p && !(hasPrefix "/nix/store/" p); + hasLocalRequesters = any (r: r.uid != null) (attrValues cfg.requesters); + hasVsockRequesters = any (r: r.vsockCid != null) (attrValues cfg.requesters); + missingPolicies = attrNames (filterAttrs (_: r: !(cfg.policies ? ${r.policy})) cfg.requesters); + + # TOML has no null; leave those keys out + dropNulls = v: + if isAttrs v then mapAttrs (_: dropNulls) (filterAttrs (_: x: x != null) v) + else if isList v then map dropNulls v + else v; + + duration = lib.types.strMatching "[1-9][0-9]*[smhd]"; + + opOpts = with lib.types; { + options = { + action = mkOpt' (enum [ "auto" "ask" "deny" ]) "ask" "What happens to a request."; + leases = mkOpt' (listOf duration) [ ] "Lease lengths approvers are offered, like `5m` or `1h`."; + rules = mkOpt' (listOf (submodule { + options = { + match = mkOpt' (attrsOf str) { } "Scope fields and the globs they must match."; + action = mkOpt' (enum [ "auto" "ask" "deny" ]) null "Action for matching requests."; + leases = mkOpt' (nullOr (listOf duration)) null "Leases for matching requests (null keeps the default)."; + }; + })) [ ] "Rules checked in order; the first match wins."; + }; + }; + + policyOpts = with lib.types; { + options = { + maxPending = mkOpt' ints.positive 4 "Requests that may wait for approval at once, for each requester."; + autoPerMinute = mkOpt' ints.positive 60 "Requests per minute that policy approves by itself, for each requester."; + ops = mkOpt' (attrsOf (submodule opOpts)) { } "Policy per operation; unlisted operations are denied."; + }; + }; + + requesterOpts = with lib.types; { + options = { + vsockCid = mkOpt' (nullOr ints.unsigned) null "CID of a VM that connects over vsock."; + uid = mkOpt' (nullOr ints.unsigned) null "UID of a local requester."; + policy = mkOpt' str null "Name of the requester's policy in `policies`."; + }; + }; + + brokerConfig = (pkgs.formats.toml { }).generate "slop-broker.toml" (dropNulls { + requesters = mapAttrs (_: r: { + vsock_cid = r.vsockCid; + inherit (r) uid policy; + }) cfg.requesters; + + policies = mapAttrs (_: p: { + max_pending = p.maxPending; + auto_per_minute = p.autoPerMinute; + inherit (p) ops; + }) cfg.policies; + + inherit (cfg) timeout; + vsock_port = if hasVsockRequesters then cfg.vsockPort else null; + request_socket = if hasLocalRequesters then "/run/slop-broker/request.sock" else null; + approve_socket = "/run/slop-broker/approve.sock"; + approver_group = "slop-broker-approve"; + audit_log = "/var/lib/slop-broker/audit.jsonl"; + + ssh = if cfg.ssh.enable then { + ssh = "${pkgs.openssh}/bin/ssh"; + key = "ssh-key"; + known_hosts = "/var/lib/slop-broker/known_hosts"; + targets = mapAttrs (_: t: { inherit (t) hostname user; ssh_opts = t.sshOpts; }) cfg.ssh.targets; + } else null; + home_assistant = if ha.enable then { + inherit (ha) url; + notify_service = ha.notifyService; + device_id = ha.deviceId; + token = "ha-token"; + } else null; + }); +in +{ + options.services.slop-broker = with lib.types; { + enable = mkBoolOpt' false "Whether to run the approval broker for coding agents."; + package = lib.mkOption { + type = package; + default = pkgs.slop-broker; + defaultText = lib.literalExpression "pkgs.slop-broker"; + description = "slop-broker package; the flake's modules default to its own."; + }; + + vsockPort = mkOpt' ints.unsigned 6262 "vsock port to listen on for VM requesters."; + timeout = mkOpt' duration "5m" "How long a request waits for an approver."; + approvers = mkOpt' (listOf str) [ ] "Users allowed to answer requests with `slop-approve`."; + policies = mkOpt' (attrsOf (submodule policyOpts)) { } "Named policies; several requesters can share one."; + requesters = mkOpt' (attrsOf (submodule requesterOpts)) { } "Who may send requests, and which policy applies."; + + ssh = { + enable = mkBoolOpt' false "Whether to run approved SSH commands."; + keyFile = mkOpt' str "" "Runtime path to the SSH private key; never a Nix store path."; + targets = mkOpt' (attrsOf (submodule { + options = { + hostname = mkOpt' str null "Host to connect to."; + user = mkOpt' str null "Remote user."; + sshOpts = mkOpt' (listOf str) [ ] "Extra SSH arguments (trusted)."; + }; + })) { } "Named SSH targets (nodes), which `slop ssh`, the box queries and deploys address by name."; + }; + + homeAssistant = { + enable = mkBoolOpt' false "Whether to send Companion approval notifications."; + url = mkOpt' str "" "Home Assistant WebSocket endpoint, preferably wss://host/api/websocket."; + notifyService = mkOpt' str "" "Companion notification service name, without the notify. prefix."; + deviceId = mkOpt' str "" + "The Companion app's own ID (the `device_id` in its notification answers, not the device registry's); the broker logs it when it ignores an answer."; + tokenFile = mkOpt' str "" "Runtime path to a Home Assistant token; never a Nix store path."; + }; + }; + + config = mkIf cfg.enable { + assertions = [ + { + assertion = cfg.ssh.enable -> isRuntimePath cfg.ssh.keyFile; + message = "slop-broker SSH needs a runtime key file."; + } + { + assertion = missingPolicies == [ ]; + message = "slop-broker requesters with an unknown policy: ${concatStringsSep ", " missingPolicies}."; + } + { + assertion = ha.enable -> (ha.url != "" && ha.notifyService != "" && ha.deviceId != "" && isRuntimePath ha.tokenFile); + message = "slop-broker Home Assistant needs a URL, service, device ID and runtime token file."; + } + ]; + + users = { + groups = { + slop-broker = { }; + slop-broker-approve.members = cfg.approvers; + }; + users.slop-broker = { + isSystemUser = true; + group = "slop-broker"; + }; + }; + + environment.systemPackages = [ cfg.package ]; + boot.kernelModules = optional hasVsockRequesters "vhost_vsock"; + + systemd.services.slop-broker = { + description = "Approval broker for coding agents"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + serviceConfig = { + ExecStart = "${cfg.package}/bin/slop-broker serve --config ${brokerConfig}"; + LoadCredential = + optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++ + optional ha.enable "ha-token:${ha.tokenFile}"; + + User = "slop-broker"; + Group = "slop-broker"; + SupplementaryGroups = [ "slop-broker-approve" ]; + RuntimeDirectory = "slop-broker"; + RuntimeDirectoryMode = "0755"; + StateDirectory = "slop-broker"; + StateDirectoryMode = "0700"; + Restart = "on-failure"; + + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + PrivateDevices = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + RestrictNamespaces = true; + LockPersonality = true; + RestrictAddressFamilies = [ "AF_UNIX" ] + ++ optional hasVsockRequesters "AF_VSOCK" + ++ optionals (cfg.ssh.enable || ha.enable) [ "AF_INET" "AF_INET6" ]; + CapabilityBoundingSet = ""; + UMask = "0077"; + }; + }; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..93783c6 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,26 @@ +{ lib, rustPlatform, callPackage }: +let + inherit (lib.fileset) toSource unions; +in +rustPlatform.buildRustPackage { + pname = "slop-broker"; + version = "0.1.0"; + + src = toSource { + root = ../.; + fileset = unions [ ../Cargo.toml ../Cargo.lock ../src ../tests ../slop-tools.md ]; + }; + cargoLock.lockFile = ../Cargo.lock; + + postInstall = '' + ln -s slop-broker $out/bin/slop-approve + install -Dm644 slop-tools.md $out/share/slop-broker/slop-tools.md + ''; + + meta = { + description = "Approval broker that runs privileged operations for coding agents"; + license = lib.licenses.mit; + mainProgram = "slop"; + platforms = lib.platforms.linux; + }; +} diff --git a/nix/vm-test.nix b/nix/vm-test.nix new file mode 100644 index 0000000..d365e3a --- /dev/null +++ b/nix/vm-test.nix @@ -0,0 +1,99 @@ +# Runs the broker through the `services.slop-broker` module, with its real service hardening, over +# vsock loopback, against a local sshd. Build it as `checks.x86_64-linux.vm` (see `README.md`). +{ pkgs, slop-broker }: +let + inherit (pkgs) lib; + + key = pkgs.runCommand "test-key" { nativeBuildInputs = [ pkgs.openssh ]; } '' + mkdir $out && ssh-keygen -q -t ed25519 -N "" -f $out/key + ''; +in +pkgs.testers.runNixOSTest { + name = "slop-broker"; + nodes.machine = { ... }: { + imports = [ ./modules/nixos/broker.nix ]; + + config = { + boot.kernelModules = [ "vsock_loopback" ]; + services.openssh.enable = true; + users.users.deploy = { isNormalUser = true; openssh.authorizedKeys.keyFiles = [ "${key}/key.pub" ]; }; + users.users.reviewer.isNormalUser = true; + users.users.agent.isNormalUser = true; + environment.systemPackages = [ pkgs.util-linux ]; + # Not a store path, as the module requires + environment.etc."slop-broker-test/key".source = "${key}/key"; + + services.slop-broker = { + enable = true; + package = slop-broker; + approvers = [ "reviewer" ]; + policies.agent.ops.ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; }; + requesters.agent = { + vsockCid = 1; + policy = "agent"; + }; + ssh = { + enable = true; + keyFile = "/etc/slop-broker-test/key"; + targets = lib.genAttrs [ "local" "other" "denied" ] (_: { hostname = "localhost"; user = "deploy"; }); + }; + }; + }; + }; + testScript = '' + machine.wait_for_unit("sshd.service") + machine.wait_for_unit("slop-broker.service") + machine.wait_for_file("/run/slop-broker/approve.sock") + env = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'" + + # Denied by policy, without asking + status, out = machine.execute(f"su agent -c \"{env} slop ssh denied -- true\" 2>&1") + assert status == 125 and "denied by policy" in out, (status, out) + + # Ask, approve from a terminal, and see the real ssh run + machine.execute(f"su agent -c \"{env} slop ssh local -- 'echo hi from \\$(whoami)'\" > /tmp/out 2>&1 &") + machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh local'") + listing = machine.succeed("su reviewer -c 'slop-approve list'") + print(listing) + assert "vm test" in listing + request = listing.split()[0][:4] + status, out = machine.execute("su agent -c 'slop-approve " + request + " once' 2>&1") + assert status != 0, out + machine.succeed(f"su reviewer -c 'slop-approve {request} 5m'") + machine.wait_until_succeeds("grep -q 'hi from deploy' /tmp/out") + out = machine.succeed("cat /tmp/out") + print(out) + assert "Permanently added" not in out, out + + # Covered by the lease now; stdin is forwarded + out = machine.succeed(f"echo piped | su agent -c \"{env} slop ssh local -- cat\"") + assert "piped" in out, out + out = machine.succeed(f"su agent -c \"{env} slop requests\"") + assert "ssh" in out and "lease" in out, out + + # Unknown nodes are named plainly; usage errors exit 125 like other refusals + status, out = machine.execute(f"su agent -c \"{env} slop ssh nope -- true\" 2>&1") + assert status == 125 and "unknown node nope;" in out, (status, out) + status, out = machine.execute(f"su agent -c \"{env} slop ssh\" 2>&1") + assert status == 125, (status, out) + + # Interactive answering on a terminal + machine.execute(f"su agent -c \"{env} slop ssh other -- echo interactive\" > /tmp/out2 2>&1 &") + machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'") + out = machine.succeed("(sleep 1; echo x; sleep 1; echo o) | timeout 5 su reviewer -c \"script -qec slop-approve /dev/null\" || true") + print(out) + assert "Not an option" in out and "Recorded: once" in out, out + machine.wait_until_succeeds("grep -q interactive /tmp/out2") + + # The only pending request can be answered without its ID + machine.execute(f"su agent -c \"{env} slop ssh other -- true; echo \\$?\" > /tmp/out3 2>&1 &") + machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'") + machine.succeed("su reviewer -c 'slop-approve deny'") + machine.wait_until_succeeds("grep -q 'denied by approver' /tmp/out3") + machine.wait_until_succeeds("grep -qx 125 /tmp/out3", timeout=30) + + audit = machine.succeed("su reviewer -c 'slop-approve log'") + print(audit) + assert "agent asks: ssh local" in audit and "answered 5m by reviewer" in audit, audit + ''; +} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..c775577 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,2 @@ +max_width = 120 +use_small_heuristics = "Max" diff --git a/slop-tools.md b/slop-tools.md new file mode 100644 index 0000000..64473f4 --- /dev/null +++ b/slop-tools.md @@ -0,0 +1,49 @@ +# Privileged operations through `slop` + +You don't have credentials for other boxes or services. Instead, the `slop` command asks a broker +outside this environment to carry out privileged operations for you. The broker holds the keys, +applies a policy, and asks a human to approve most requests. + +## How requests behave + +- A request that needs approval blocks for up to **five minutes** while a human answers. Run + `slop` with a tool timeout of at least six minutes, or in the background. Don't retry a request + that is waiting, denied or expired in a loop; tell the user instead. +- Exit status **125** means the broker did not run the operation: it was denied, expired, invalid + or failed. Any other status is the operation's own. +- Approvers see who sent a request and can see `--label` (or `SLOP_LABEL`). Use it to say briefly + why you need it, e.g. `--label "checking nginx after config change"`. +- Approvers may grant a lease, so repeats of the same request (same target) may run without + waiting. `slop requests` shows your pending requests and leases. +- Anything a command prints ends up in your context and transcript. Avoid printing secrets. + +## Commands + +| Command | What it does | +|---|---| +| `slop ssh -- …` | Run a command over SSH on a deploy node, as the node's configured user. | +| `slop ssh --host @ [-p ] -- …` | The same for a host outside the deploy nodes. | +| `slop requests` | Your pending requests and active leases. | + +- `--json` prints structured results (such as `slop requests`) as JSON. + +- The remote command is joined with spaces and run by the remote login shell, as with `ssh`. Boxes + usually use `fish`, so pipe multi-statement scripts through `bash`: + `slop ssh -- bash -s < script.sh`. +- There is no TTY. Interactive programs won't work; use non-interactive flags (`--no-pager`, + `-y`). +- stdin is forwarded once the request is approved. + +## Don't + +- Don't try to find, read or copy the broker's credentials, or use deploy tools or keys directly. + They won't work from here, and trying is a policy violation. +- Don't ask for broader access than the task needs. + +## Suggest new operations + +`slop` grows one operation at a time. If you find yourself working around a missing operation, or +making the same `slop ssh` request (and waiting for approval) again and again for something that +could be a fixed, checkable operation, tell the user. Say what the operation would do, which +arguments it would take, and whether it could run without approval. Don't build the workaround +into a habit instead. diff --git a/src/approve.rs b/src/approve.rs new file mode 100644 index 0000000..49a9d51 --- /dev/null +++ b/src/approve.rs @@ -0,0 +1,298 @@ +//! The approver socket and the `slop-approve` client, using the same framing and encoding as +//! requesters ([`ApproveRequest`] in, [`ApproveResponse`] out). +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Result, anyhow, bail}; +use tokio::net::{UnixListener, UnixStream}; + +use crate::audit::{Event, short}; +use crate::config::user_name; +use crate::ops::printable; +use crate::proto::{ApproveRequest, ApproveResponse, MAX_LOG_RECORDS, receive, send, transport}; +use crate::queue::{Decision, PendingInfo}; +use crate::server::Broker; + +/// Socket permissions admit approvers; requesters are refused even if misconfigured into the group. +pub async fn listen(broker: Arc, listener: UnixListener) -> Result<()> { + loop { + let (stream, _) = listener.accept().await?; + let broker = broker.clone(); + tokio::spawn(async move { + let _ = serve(broker, stream).await; + }); + } +} + +async fn serve(broker: Arc, stream: UnixStream) -> Result<()> { + let uid = stream.peer_cred()?.uid(); + let mut transport = transport(stream); + let request = tokio::time::timeout(Duration::from_secs(10), receive::<_, ApproveRequest>(&mut transport)).await; + let response = match request { + Ok(Ok(Some(request))) => { + answer(&broker, uid, request).unwrap_or_else(|e| ApproveResponse::Error(format!("{e:#}"))) + } + Ok(Err(error)) => ApproveResponse::Error(format!("{error:#}")), + _ => return Ok(()), + }; + send(&mut transport, &response).await +} + +fn answer(broker: &Broker, uid: u32, request: ApproveRequest) -> Result { + if broker.config.requester_by_uid(uid).is_some() { + bail!("requesters cannot approve"); + } + match request { + ApproveRequest::List => Ok(ApproveResponse::Pending(broker.queue.list())), + ApproveRequest::Decide { id, decision } => { + approve(broker, &id, decision, &user_name(uid))?; + Ok(ApproveResponse::Recorded) + } + ApproveRequest::Log { count } => Ok(ApproveResponse::Log(broker.audit.tail(count.min(MAX_LOG_RECORDS))?)), + } +} + +/// Records a decision from any approver (terminal or phone). +pub fn approve(broker: &Broker, id: &str, decision: Decision, approver: &str) -> Result<()> { + let info = broker.queue.decide(id, decision, approver)?; + broker.audit.log(Event::Decision { + id: id.to_owned(), + requester: info.requester, + summary: info.summary, + decision: decision.name(), + approver: approver.to_owned(), + }); + Ok(()) +} + +async fn call(socket: &Path, request: ApproveRequest) -> Result { + let stream = UnixStream::connect(socket).await.map_err(|e| anyhow!("connecting to {}: {e}", socket.display()))?; + let mut transport = transport(stream); + send(&mut transport, &request).await?; + match receive(&mut transport).await? { + Some(ApproveResponse::Error(error)) => bail!("{error}"), + Some(response) => Ok(response), + None => bail!("the broker closed the connection"), + } +} + +async fn list(socket: &Path) -> Result> { + match call(socket, ApproveRequest::List).await? { + ApproveResponse::Pending(entries) => Ok(entries), + _ => bail!("unexpected response from the broker"), + } +} + +pub fn format(entry: &PendingInfo, full: bool) -> String { + let marker = if entry.sensitive { " [SENSITIVE]" } else { "" }; + let mut text = + format!("{} {} {}{marker} (expires in {}s)\n", entry.id, entry.requester, entry.summary, entry.expires_in); + + let lines: Vec<_> = entry.detail.lines().collect(); + let shown = if full { lines.len() } else { lines.len().min(6) }; + for line in &lines[..shown] { + text += &format!(" {line}\n"); + } + + if shown < lines.len() { + text += &format!(" … {} more lines; slop-approve show {}\n", lines.len() - shown, short(&entry.id)); + } + if let Some(label) = &entry.label { + text += &format!(" Label (agent-supplied): {label}\n"); + } + text +} + +fn offers(entry: &PendingInfo) -> String { + entry.offers.iter().map(Decision::name).collect::>().join("|") +} + +/// Finds the pending request whose ID starts with `prefix`. +fn resolve<'a>(entries: &'a [PendingInfo], prefix: &str) -> Result<&'a PendingInfo> { + let mut matches = entries.iter().filter(|e| !prefix.is_empty() && e.id.starts_with(prefix)); + match (matches.next(), matches.next()) { + (Some(entry), None) => Ok(entry), + (None, _) => bail!("no pending request matches {prefix:?}"), + (Some(_), Some(_)) => bail!("{prefix:?} matches more than one request; give more of the ID"), + } +} + +const USAGE: &str = "usage: slop-approve answer requests one by one, waiting for new ones + (lists them instead when not on a terminal or piped) + slop-approve list list pending requests + slop-approve show show a request in full + slop-approve answer a request: once, deny or an offered lease (e.g. 5m) + slop-approve answer the only pending request + slop-approve log [-n 50] [--json] + recent requests, decisions and results +IDs can be shortened to any unique prefix."; + +pub async fn main(socket: &Path, args: &[String]) -> Result<()> { + use std::io::IsTerminal; + match args { + [] if std::io::stdin().is_terminal() && std::io::stdout().is_terminal() => interactive(socket).await?, + [] => print_list(socket).await?, + [list] if list == "list" => print_list(socket).await?, + [help] if help == "help" || help == "--help" || help == "-h" => println!("{USAGE}"), + [log, options @ ..] if log == "log" => print_log(socket, options).await?, + [show, id] if show == "show" => { + let entries = list(socket).await?; + print!("{}", printable(&format(resolve(&entries, id)?, true))); + } + [decision] => { + let decision = Decision::parse(decision).map_err(|_| anyhow!("{USAGE}"))?; + let entries = list(socket).await?; + let [entry] = entries.as_slice() else { + bail!("{} requests are pending; give an ID", entries.len()); + }; + decide(socket, &entry.id, decision).await?; + } + [id, decision] => { + let decision = Decision::parse(decision)?; + let entries = list(socket).await?; + decide(socket, &resolve(&entries, id)?.id, decision).await?; + } + _ => bail!("{USAGE}"), + } + Ok(()) +} + +async fn print_list(socket: &Path) -> Result<()> { + let entries = list(socket).await?; + if entries.is_empty() { + println!("No pending requests."); + } + for entry in entries { + print!("{}", printable(&format(&entry, false))); + println!(" Answer: slop-approve {} {}", short(&entry.id), offers(&entry)); + } + Ok(()) +} + +async fn print_log(socket: &Path, options: &[String]) -> Result<()> { + let (mut count, mut json) = (50, false); + let mut options = options.iter(); + while let Some(option) = options.next() { + match option.as_str() { + "--json" => json = true, + "-n" => { + count = options + .next() + .and_then(|n| n.parse().ok()) + .filter(|n| (1..=MAX_LOG_RECORDS).contains(n)) + .ok_or_else(|| anyhow!("-n needs a number from 1 to {MAX_LOG_RECORDS}"))? + } + _ => bail!("{USAGE}"), + } + } + let ApproveResponse::Log(records) = call(socket, ApproveRequest::Log { count }).await? else { + bail!("unexpected response from the broker"); + }; + + for record in records { + if json { + println!("{}", serde_json::to_string(&record)?); + } else { + print!("{}", printable(&record.describe())); + } + } + Ok(()) +} + +async fn decide(socket: &Path, id: &str, decision: Decision) -> Result<()> { + call(socket, ApproveRequest::Decide { id: id.to_owned(), decision }).await?; + println!("Recorded: {} for {}.", decision.name(), short(id)); + Ok(()) +} + +/// Shows pending requests one at a time and asks for an answer, then waits for more. +async fn interactive(socket: &Path) -> Result<()> { + use tokio::io::{AsyncBufReadExt, BufReader}; + let mut input = BufReader::new(tokio::io::stdin()).lines(); + let mut skipped = std::collections::HashSet::new(); + let mut waiting = false; + + loop { + let entries = list(socket).await?; + skipped.retain(|id| entries.iter().any(|e| &e.id == id)); + let Some(entry) = entries.iter().find(|e| !skipped.contains(&e.id)) else { + if !waiting { + println!("Waiting for requests (Ctrl-C to quit)…"); + waiting = true; + } + tokio::time::sleep(Duration::from_secs(1)).await; + continue; + }; + + waiting = false; + + // Bell, so a new request is noticed in another window. + print!("\x07\n{}", printable(&format(entry, true))); + + let leases: Vec = + entry.offers.iter().filter(|d| matches!(d, Decision::Lease(_))).map(Decision::name).collect(); + let mut choices = vec!["[o]nce".to_owned()]; + choices.extend(leases); + choices.extend(["[d]eny".into(), "[s]kip".into(), "[q]uit".into()]); + + loop { + print!("Answer {}: ", choices.join(", ")); + std::io::Write::flush(&mut std::io::stdout())?; + let Some(line) = input.next_line().await? else { return Ok(()) }; + + let decision = match line.trim() { + "q" | "quit" => return Ok(()), + "s" | "skip" => { + skipped.insert(entry.id.clone()); + break; + } + "o" => Decision::Once, + "d" => Decision::Deny, + "" => continue, + other => match Decision::parse(other) { + Ok(decision) if entry.offers.contains(&decision) => decision, + _ => { + println!("Not an option."); + continue; + } + }, + }; + + // The request may have expired or been answered elsewhere while waiting. + if let Err(error) = decide(socket, &entry.id, decision).await { + println!("{error:#}"); + } + break; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(id: &str) -> PendingInfo { + PendingInfo { + id: id.into(), + requester: "r".into(), + op: "ssh".into(), + summary: "ssh river".into(), + detail: String::new(), + label: None, + sensitive: false, + offers: vec![Decision::Once, Decision::Deny], + expires_in: 60, + } + } + + #[test] + fn resolves_unique_prefixes() { + let entries = [entry("abc123"), entry("abd456")]; + assert_eq!(resolve(&entries, "abc").unwrap().id, "abc123"); + assert_eq!(resolve(&entries, "abd456").unwrap().id, "abd456"); + assert!(resolve(&entries, "ab").is_err()); + assert!(resolve(&entries, "x").is_err()); + assert!(resolve(&entries, "").is_err()); + } +} diff --git a/src/audit.rs b/src/audit.rs new file mode 100644 index 0000000..615795e --- /dev/null +++ b/src/audit.rs @@ -0,0 +1,235 @@ +//! Audit trail of every request, decision and result. Each event goes to the journal as a line of +//! text and, if configured, to a file as a line of JSON. `slop-approve log` reads the file back. +use std::fmt; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::SystemTime; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +use crate::proto::ApprovedBy; + +/// One line of the audit file. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Record { + /// UTC, RFC 3339. + pub time: String, + #[serde(flatten)] + pub event: Event, +} + +/// `id` is the request's ID, the same one approvers and `slop requests` show. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "event", rename_all = "kebab-case")] +pub enum Event { + /// A connection from a peer that isn't a configured requester. + Unknown { + peer: String, + }, + /// A request that couldn't be read or doesn't fit the configuration. + Invalid { + id: String, + requester: String, + error: String, + }, + Request { + id: String, + requester: String, + op: String, + summary: String, + detail: String, + /// Agent-supplied. + label: Option, + }, + Approved { + id: String, + by: ApprovedBy, + /// Who answered, when an approver did. + #[serde(default, skip_serializing_if = "Option::is_none")] + approver: Option, + }, + /// An approver's answer. + Decision { + id: String, + requester: String, + summary: String, + decision: String, + approver: String, + }, + Denied { + id: String, + reason: String, + }, + Expired { + id: String, + }, + Disconnected { + id: String, + }, + Finished { + id: String, + exit: i32, + seconds: f64, + }, + Failed { + id: String, + error: String, + }, +} + +impl Event { + /// Whether the journal should show it as a warning. + fn is_warning(&self) -> bool { + matches!(self, Event::Unknown { .. } | Event::Invalid { .. } | Event::Failed { .. }) + } +} + +/// Request IDs are long; approvers type a prefix, and logs show the same. +pub fn short(id: &str) -> &str { + &id[..id.len().min(6)] +} + +impl fmt::Display for Event { + /// One line, for the journal. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Event::Unknown { peer } => write!(f, "refused connection from {peer}: not a configured requester"), + Event::Invalid { id, requester, error } => { + write!(f, "{} invalid request from {requester}: {error}", short(id)) + } + Event::Request { id, requester, summary, detail, label, .. } => { + write!(f, "{} {requester} asks: {summary}", short(id))?; + if let Some(line) = detail.lines().next() { + write!(f, "; {line}")?; + } + if let Some(label) = label { + write!(f, " (label: {label})")?; + } + Ok(()) + } + Event::Approved { id, by, approver } => { + let by = match (by, approver) { + (ApprovedBy::Policy, _) => "policy", + (ApprovedBy::Lease, _) => "a lease", + (ApprovedBy::Approver, Some(approver)) => approver, + (ApprovedBy::Approver, None) => "an approver", + }; + write!(f, "{} approved by {by}", short(id)) + } + Event::Decision { id, decision, approver, .. } => { + write!(f, "{} answered {decision} by {approver}", short(id)) + } + Event::Denied { id, reason } => write!(f, "{} {reason}", short(id)), + Event::Expired { id } => write!(f, "{} expired without an answer", short(id)), + Event::Disconnected { id } => write!(f, "{} cancelled: the requester disconnected", short(id)), + Event::Finished { id, exit, seconds } => { + write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id)) + } + Event::Failed { id, error } => write!(f, "{} failed: {error}", short(id)), + } + } +} + +impl Record { + /// For reviewing: the journal's line, with the time and the rest of a request's detail. + pub fn describe(&self) -> String { + let time = self.time.replace('T', " ").trim_end_matches('Z').to_owned(); + let mut text = format!("{time} {}\n", self.event); + if let Event::Request { detail, .. } = &self.event { + for line in detail.lines().skip(1) { + text += &format!("{:21}{line}\n", ""); + } + } + text + } +} + +pub struct Audit { + file: Option<(PathBuf, Mutex)>, +} + +impl Audit { + pub fn new(path: Option<&Path>) -> Result { + let file = match path { + Some(path) => { + let file = OpenOptions::new().create(true).append(true).open(path)?; + Some((path.to_owned(), Mutex::new(file))) + } + None => None, + }; + Ok(Audit { file }) + } + + pub fn log(&self, event: Event) { + // systemd reads the `` prefix as the line's priority. + eprintln!("{}{event}", if event.is_warning() { "<4>" } else { "<6>" }); + + if let Some((_, file)) = &self.file { + let record = Record { time: humantime::format_rfc3339_seconds(SystemTime::now()).to_string(), event }; + if let Ok(line) = serde_json::to_string(&record) { + let _ = writeln!(file.lock().unwrap(), "{line}"); + } + } + } + + /// The last `count` records of the file, oldest first. + pub fn tail(&self, count: usize) -> Result> { + const WINDOW: u64 = 4 << 20; + let Some((path, _)) = &self.file else { anyhow::bail!("the broker has no audit file") }; + + let mut file = File::open(path)?; + let length = file.metadata()?.len(); + let start = length.saturating_sub(WINDOW); + file.seek(SeekFrom::Start(start))?; + let mut text = String::new(); + file.take(WINDOW).read_to_string(&mut text)?; + + // A window that starts mid-file starts mid-line. + let text = if start > 0 { text.split_once('\n').map_or("", |(_, rest)| rest) } else { &text }; + + let lines: Vec<&str> = text.lines().collect(); + let skip = lines.len().saturating_sub(count); + Ok(lines[skip..].iter().filter_map(|line| serde_json::from_str(line).ok()).collect()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn writes_and_reads_back_records() { + let directory = tempfile::tempdir().unwrap(); + let audit = Audit::new(Some(&directory.path().join("audit.jsonl"))).unwrap(); + for exit in 0..5 { + audit.log(Event::Finished { id: "0123456789abcdef".into(), exit, seconds: 1.5 }); + } + let records = audit.tail(2).unwrap(); + assert_eq!(records.len(), 2); + assert_eq!(records[1].event, Event::Finished { id: "0123456789abcdef".into(), exit: 4, seconds: 1.5 }); + assert!(records[1].describe().ends_with("012345 finished with exit status 4 after 1.5s\n")); + } + + #[test] + fn describes_requests_in_full() { + let record = Record { + time: "2026-11-19T10:02:13Z".into(), + event: Event::Request { + id: "0123456789abcdef".into(), + requester: "slop-cannon".into(), + op: "ssh".into(), + summary: "ssh river".into(), + detail: "Command: a\nmore".into(), + label: Some("why".into()), + }, + }; + assert_eq!( + record.describe(), + "2026-11-19 10:02:13 012345 slop-cannon asks: ssh river; Command: a (label: why)\n\ + \x20 more\n" + ); + } +} diff --git a/src/bin/slop-broker.rs b/src/bin/slop-broker.rs new file mode 100644 index 0000000..4ac5c82 --- /dev/null +++ b/src/bin/slop-broker.rs @@ -0,0 +1,109 @@ +//! The broker daemon, and `slop-approve` (the same binary, by name) for approvers. +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::Parser; +use nix::sys::signal::{SigHandler, Signal, signal}; + +use slop_broker::config::{Config, credential, group_id}; +use slop_broker::server::{self, Broker}; +use slop_broker::{approve, ha}; + +#[derive(Parser)] +#[command(about = "Approval broker for coding agents")] +enum Command { + /// Run the broker. + Serve { + #[arg(long)] + config: PathBuf, + }, + /// Answer requests (also available as `slop-approve`). + Approve { + #[arg(long, default_value = DEFAULT_APPROVE_SOCKET)] + socket: PathBuf, + args: Vec, + }, +} + +const DEFAULT_APPROVE_SOCKET: &str = "/run/slop-broker/approve.sock"; + +#[tokio::main] +async fn main() { + let mut args: Vec = std::env::args().collect(); + let name = args.first().and_then(|a| a.rsplit('/').next()).unwrap_or_default().to_owned(); + + let result = if name == "slop-approve" { + let socket = + std::env::var_os("SLOP_APPROVE_SOCKET").map(PathBuf::from).unwrap_or(DEFAULT_APPROVE_SOCKET.into()); + approve_cli(); + approve::main(&socket, &args.split_off(1)).await + } else { + match Command::parse() { + Command::Serve { config } => serve(&config).await, + Command::Approve { socket, args } => { + approve_cli(); + approve::main(&socket, &args).await + } + } + }; + + if let Err(error) = result { + eprintln!("{error:#}"); + std::process::exit(1); + } +} + +/// Lets `slop-approve … | head` end quietly, like other command-line tools. Not for the daemon, +/// which must survive peers closing sockets. +fn approve_cli() { + let _ = unsafe { signal(Signal::SIGPIPE, SigHandler::SigDfl) }; +} + +async fn serve(path: &Path) -> Result<()> { + let config = Config::load(path)?; + let _ = rustls::crypto::ring::default_provider().install_default(); + + let home_assistant = match &config.home_assistant { + Some(settings) => { + ha::validate(settings)?; + let token = std::fs::read_to_string(credential(&settings.token)).context("reading Home Assistant token")?; + let token = token.trim().to_owned(); + anyhow::ensure!(!token.is_empty(), "Home Assistant token is empty"); + Some((settings.clone(), token)) + } + None => None, + }; + + server::check_runtime_dir(&config.approve_socket)?; + let approve_listener = server::bind_unix(&config.approve_socket, 0o660, Some(group_id(&config.approver_group)?))?; + let request_listener = match &config.request_socket { + Some(path) => { + server::check_runtime_dir(path)?; + Some(server::bind_unix(path, 0o666, None)?) + } + None => None, + }; + + let broker = Arc::new(Broker::new(config)?); + let mut tasks = tokio::task::JoinSet::new(); + tasks.spawn(approve::listen(broker.clone(), approve_listener)); + if let Some(listener) = request_listener { + tasks.spawn(server::listen_unix(broker.clone(), listener)); + } + if let Some(port) = broker.config.vsock_port { + tasks.spawn(server::listen_vsock(broker.clone(), port)); + } + if let Some((settings, token)) = home_assistant { + let broker = broker.clone(); + tasks.spawn(async move { + ha::run(broker, settings, token).await; + Ok(()) + }); + } + + eprintln!("<6>slop-broker ready"); + // Any listener failing is fatal; systemd restarts the broker. + tasks.join_next().await.context("no listeners")???; + anyhow::bail!("a listener stopped") +} diff --git a/src/bin/slop.rs b/src/bin/slop.rs new file mode 100644 index 0000000..b92dbd2 --- /dev/null +++ b/src/bin/slop.rs @@ -0,0 +1,249 @@ +//! `slop`: the agents' client for the broker. +use std::num::NonZeroU16; +use std::process::exit; + +use anyhow::{Context, Result, bail}; +use clap::{Args, Parser, Subcommand}; +use futures_util::{SinkExt, StreamExt}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::mpsc; + +use slop_broker::proto::{ + ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, HOST_CID, OpResult, Operation, PROTOCOL_VERSION, + Request, ServerMessage, decode, encode, transport, +}; +use slop_broker::types::{Arg, HostName, NodeName, UserName}; + +/// Exit status when the broker didn't run the operation (denied, expired, invalid or failed). +const NOT_RUN: i32 = 125; + +const GUIDE: &str = include_str!("../../slop-tools.md"); + +#[derive(Parser)] +#[command( + about = "Ask the slop broker to run privileged operations", + after_help = "Requests wait up to five minutes for an approver; don't retry them in a loop.\n\ + Exit status 125 means the broker did not run the operation.\n\ + SLOP_BROKER selects the broker: vsock:: or unix:." +)] +struct Cli { + /// Who is asking and why; shown to the approver as agent-supplied. + #[arg(long, env = "SLOP_LABEL", global = true)] + label: Option, + /// Print structured results as JSON. + #[arg(long, global = true)] + json: bool, + #[command(subcommand)] + command: Command, +} + +#[derive(Args)] +struct Target { + /// Deploy node, or user@host with --host. + target: String, + /// Treat TARGET as user@host instead of a deploy node. + #[arg(long)] + host: bool, + /// SSH port, with --host. + #[arg(short, long)] + port: Option, +} + +impl Target { + fn destination(&self) -> Result { + if !self.host { + if self.port.is_some() { + bail!("--port needs --host; deploy nodes use their configured port"); + } + return Ok(Destination::Node(parse::(&self.target)?)); + } + + let (user, host) = self.target.rsplit_once('@').context("--host needs user@host")?; + let port = self.port.unwrap_or(NonZeroU16::new(22).unwrap()); + Ok(Destination::Host { user: parse::(user)?, host: parse::(host)?, port }) + } +} + +fn parse>(value: &str) -> Result { + value.parse().map_err(anyhow::Error::msg) +} + +#[derive(Subcommand)] +enum Command { + /// Run a command over SSH on a deploy node, or on any host with --host. + Ssh { + #[command(flatten)] + target: Target, + /// Remote command, after `--`; joined with spaces and run by the remote shell, as ssh does. + #[arg(last = true)] + command: Vec, + }, + /// Show your pending requests and active leases. + Requests, + /// Print the guide for agents. + Guide, +} + +fn operation(command: Command) -> Result { + Ok(match command { + Command::Ssh { target, command } => Operation::Ssh { destination: target.destination()?, command }, + Command::Requests => Operation::Requests, + Command::Guide => unreachable!(), + }) +} + +/// The working directory's name, so approvers can tell agents apart. +fn default_label() -> Option { + let directory = std::env::current_dir().ok()?; + Some(format!("in {}", directory.file_name()?.to_string_lossy())) +} + +trait Stream: AsyncRead + AsyncWrite + Send + Unpin {} +impl Stream for T {} + +async fn connect() -> Result> { + let target = std::env::var("SLOP_BROKER").unwrap_or_else(|_| format!("vsock:{HOST_CID}:{DEFAULT_VSOCK_PORT}")); + let failed = || format!("connecting to the broker at {target}"); + if let Some(path) = target.strip_prefix("unix:") { + return Ok(Box::new(tokio::net::UnixStream::connect(path).await.with_context(failed)?)); + } + if let Some((cid, port)) = target.strip_prefix("vsock:").and_then(|a| a.split_once(':')) { + let address = tokio_vsock::VsockAddr::new(cid.parse()?, port.parse()?); + return Ok(Box::new(tokio_vsock::VsockStream::connect(address).await.with_context(failed)?)); + } + bail!("SLOP_BROKER must be vsock:: or unix:") +} + +#[tokio::main] +async fn main() { + // Usage errors also mean nothing ran; help and version are not errors. + let cli = Cli::try_parse().unwrap_or_else(|error| { + let _ = error.print(); + exit(if error.use_stderr() { NOT_RUN } else { 0 }) + }); + + let status = match run(cli).await { + Ok(status) => status, + Err(error) => { + eprintln!("slop: {error:#}"); + NOT_RUN + } + }; + + // Don't wait for a blocked read of our stdin. + exit(status); +} + +async fn run(cli: Cli) -> Result { + if let Command::Guide = cli.command { + print!("{GUIDE}"); + return Ok(0); + } + + let request = Request { + version: PROTOCOL_VERSION, + label: cli.label.or_else(default_label), + operation: operation(cli.command)?, + }; + + let (mut sink, mut source) = transport(connect().await?).split(); + + // One writer for the request and any stdin. + let (tx, mut rx) = mpsc::channel::(16); + tokio::spawn(async move { + while let Some(message) = rx.recv().await { + let Ok(data) = encode(&message) else { break }; + if sink.send(data).await.is_err() { + break; + } + } + }); + tx.send(ClientMessage::Request(request)).await?; + + let (mut stdout, mut stderr) = (tokio::io::stdout(), tokio::io::stderr()); + loop { + let frame = source.next().await.context("the broker closed the connection")??; + match decode::(&frame)? { + ServerMessage::Pending { id, summary } => { + eprintln!("slop: waiting for approval of `{summary}` (request {id})…") + } + ServerMessage::Approved { by, stdin } => { + match by { + ApprovedBy::Lease => eprintln!("slop: approved (lease)"), + ApprovedBy::Approver => eprintln!("slop: approved"), + ApprovedBy::Policy => {} + } + if stdin { + tokio::spawn(forward_stdin(tx.clone())); + } + } + ServerMessage::Info(message) => eprintln!("slop: {message}"), + ServerMessage::Stdout(data) => { + stdout.write_all(&data).await?; + stdout.flush().await?; + } + ServerMessage::Stderr(data) => { + stderr.write_all(&data).await?; + stderr.flush().await?; + } + ServerMessage::Finished { exit, result } => { + if let Some(result) = result { + show(&result, cli.json)?; + } + return Ok(exit); + } + ServerMessage::Denied(reason) => { + eprintln!("slop: {reason}"); + return Ok(NOT_RUN); + } + ServerMessage::Expired => { + eprintln!("slop: no answer from an approver in time"); + return Ok(NOT_RUN); + } + ServerMessage::Error(message) => { + eprintln!("slop: {message}"); + return Ok(NOT_RUN); + } + } + } +} + +fn show(result: &OpResult, json: bool) -> Result<()> { + if json { + println!("{}", serde_json::to_string_pretty(result)?); + return Ok(()); + } + + match result { + OpResult::Requests { pending, leases } => { + if pending.is_empty() && leases.is_empty() { + println!("No pending requests or leases."); + } + for entry in pending { + println!("pending {} {} (expires in {}s)", entry.id, entry.summary, entry.expires_in); + } + for lease in leases { + println!("lease {} ({}s left)", lease.scope, lease.remaining); + } + } + } + Ok(()) +} + +async fn forward_stdin(tx: mpsc::Sender) { + let mut stdin = tokio::io::stdin(); + let mut buffer = vec![0; 64 * 1024]; + loop { + match stdin.read(&mut buffer).await { + Ok(0) | Err(_) => { + let _ = tx.send(ClientMessage::StdinEnd).await; + return; + } + Ok(n) => { + if tx.send(ClientMessage::Stdin(buffer[..n].to_vec())).await.is_err() { + return; + } + } + } + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..d3acba6 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,243 @@ +//! Broker configuration: TOML, generated by the `my.slop-broker` NixOS module. Durations are +//! written like `"5m"` or `"1h"` (plain numbers are seconds). +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use anyhow::Context; +use nix::unistd::{Group, Uid, User}; +use serde::{Deserialize, Deserializer}; + +use crate::policy::OpPolicy; +use crate::queue::parse_duration; + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Config { + pub requesters: BTreeMap, + /// Named policies; several requesters can share one. + #[serde(default)] + pub policies: BTreeMap, + /// Seconds a request waits for an approver. + #[serde(default = "default_timeout", deserialize_with = "duration")] + pub timeout: u64, + /// Pending requests across all requesters. + #[serde(default = "default_max_pending")] + pub max_pending: usize, + #[serde(default)] + pub vsock_port: Option, + /// Unix socket for local requesters, identified by UID. + #[serde(default)] + pub request_socket: Option, + pub approve_socket: PathBuf, + /// Group whose members may answer requests. + pub approver_group: String, + #[serde(default)] + pub audit_log: Option, + #[serde(default)] + pub ssh: Option, + #[serde(default)] + pub home_assistant: Option, +} + +fn default_timeout() -> u64 { + 300 +} + +fn default_max_pending() -> usize { + 64 +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Requester { + #[serde(default)] + pub vsock_cid: Option, + #[serde(default)] + pub uid: Option, + /// The name of its entry in `policies`. + pub policy: String, +} + +/// What a requester may do. Limits are counted for each requester on its own, as are leases. +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Policy { + #[serde(default = "default_requester_pending")] + pub max_pending: usize, + /// Requests per minute that policy approves automatically. + #[serde(default = "default_auto_per_minute")] + pub auto_per_minute: usize, + /// Operations that may be used; anything missing is denied. + #[serde(default)] + pub ops: BTreeMap, +} + +fn default_requester_pending() -> usize { + 4 +} + +fn default_auto_per_minute() -> usize { + 60 +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SshConfig { + pub ssh: PathBuf, + /// Private key; relative paths are resolved in `$CREDENTIALS_DIRECTORY`. + pub key: PathBuf, + pub known_hosts: PathBuf, + /// Named targets (deploy-rs nodes). + pub targets: BTreeMap, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SshTarget { + pub hostname: String, + pub user: String, + #[serde(default)] + pub ssh_opts: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HomeAssistantConfig { + pub url: String, + /// Companion notification service, without the `notify.` prefix. + pub notify_service: String, + pub device_id: String, + /// Long-lived access token; relative paths are resolved in `$CREDENTIALS_DIRECTORY`. + pub token: PathBuf, +} + +/// A duration in seconds, written as `"5m"` or as a number of seconds. +pub fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Seconds(u64), + Text(String), + } + + match Raw::deserialize(deserializer)? { + Raw::Seconds(0) => Err(serde::de::Error::custom("duration must be positive")), + Raw::Seconds(seconds) => Ok(seconds), + Raw::Text(text) => parse_duration(&text) + .ok_or_else(|| serde::de::Error::custom(format!("invalid duration {text:?}; use e.g. 30s, 5m, 1h or 1d"))), + } +} + +pub fn durations<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + #[derive(Deserialize)] + struct Item(#[serde(deserialize_with = "duration")] u64); + Ok(Vec::::deserialize(deserializer)?.into_iter().map(|i| i.0).collect()) +} + +pub fn optional_durations<'de, D: Deserializer<'de>>(deserializer: D) -> Result>, D::Error> { + durations(deserializer).map(Some) +} + +/// Resolves a credential path the way systemd's `LoadCredential` exposes it. +pub fn credential(path: &std::path::Path) -> PathBuf { + if path.is_absolute() { + return path.to_owned(); + } + let directory = std::env::var_os("CREDENTIALS_DIRECTORY").unwrap_or_default(); + PathBuf::from(directory).join(path) +} + +/// Looks up a group's GID by name. +pub fn group_id(name: &str) -> anyhow::Result { + let group = Group::from_name(name)?.with_context(|| format!("unknown group {name:?}"))?; + Ok(group.gid.as_raw()) +} + +/// A user's name, for showing who answered a request. +pub fn user_name(uid: u32) -> String { + match User::from_uid(Uid::from_raw(uid)) { + Ok(Some(user)) => user.name, + _ => format!("uid {uid}"), + } +} + +impl Config { + pub fn load(path: &Path) -> anyhow::Result { + let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + toml::from_str(&text).with_context(|| format!("parsing {}", path.display())) + } + + /// Checks what the types can't: every requester's policy exists. + pub fn validate(&self) -> anyhow::Result<()> { + for (name, requester) in &self.requesters { + anyhow::ensure!( + self.policies.contains_key(&requester.policy), + "requester {name:?} has policy {:?}, which isn't configured", + requester.policy + ); + } + Ok(()) + } + + pub fn policy(&self, requester: &str) -> Option<&Policy> { + self.policies.get(&self.requesters.get(requester)?.policy) + } + + pub fn requester_by_cid(&self, cid: u32) -> Option<&str> { + self.requesters.iter().find(|(_, r)| r.vsock_cid == Some(cid)).map(|(n, _)| n.as_str()) + } + + pub fn requester_by_uid(&self, uid: u32) -> Option<&str> { + self.requesters.iter().find(|(_, r)| r.uid == Some(uid)).map(|(n, _)| n.as_str()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The layout the NixOS module writes. + #[test] + fn parses_generated_config() { + let config: Config = toml::from_str( + r#" + approve_socket = "/run/slop-broker/approve.sock" + approver_group = "slop-broker-approve" + timeout = "5m" + + [requesters.slop-cannon] + vsock_cid = 3 + policy = "agent" + + [policies.agent.ops.query] + action = "auto" + + [policies.agent.ops.ssh] + action = "ask" + leases = ["5m", "1h"] + + [[policies.agent.ops.ssh.rules]] + action = "deny" + leases = [600] + match = { target = "river" } + "#, + ) + .unwrap(); + + config.validate().unwrap(); + assert_eq!(config.timeout, 300); + + let ssh = &config.policy("slop-cannon").unwrap().ops["ssh"]; + assert_eq!(ssh.leases, [300, 3600]); + assert_eq!(ssh.rules[0].leases, Some(vec![600])); + + assert!( + toml::from_str::("approve_socket = \"/a\"\napprover_group = \"g\"\ntimeout = \"5\"\n").is_err() + ); + assert!(toml::from_str::("approve_socket = \"/a\"\napprover_group = \"g\"\nunknown = 1\n").is_err()); + + let mut missing = config.clone(); + missing.policies.clear(); + assert!(missing.validate().is_err()); + } +} diff --git a/src/exec.rs b/src/exec.rs new file mode 100644 index 0000000..f12d3cb --- /dev/null +++ b/src/exec.rs @@ -0,0 +1,136 @@ +//! Runs processes for approved requests, wired to the requester's stdin, stdout and stderr +//! (carried as messages). +use std::process::{ExitStatus, Stdio}; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use nix::errno::Errno; +use nix::sys::signal::{Signal, killpg}; +use nix::unistd::Pid; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; +use tokio::process::Command; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +use crate::proto::ServerMessage; + +/// Messages on their way back to the requester. +#[derive(Clone)] +pub struct Output(pub mpsc::Sender); + +impl Output { + pub async fn send(&self, message: ServerMessage) { + let _ = self.0.send(message).await; + } + + pub async fn info(&self, message: impl Into) { + self.send(ServerMessage::Info(message.into())).await; + } +} + +/// The requester's side of an approved operation. +pub struct Io { + /// Chunks of the requester's stdin; closed at EOF. + pub stdin: mpsc::Receiver>, + pub out: Output, + /// Cancelled when the requester disconnects. + pub cancel: CancellationToken, +} + +pub fn exit_code(status: ExitStatus) -> i32 { + use std::os::unix::process::ExitStatusExt; + status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0)) +} + +/// Runs `command` in its own process group with the requester's stdio. If the requester goes +/// away, the whole group is terminated. +pub async fn run(mut command: Command, io: &mut Io, with_stdin: bool) -> Result { + command + .stdin(if with_stdin { Stdio::piped() } else { Stdio::null() }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .process_group(0) + .kill_on_drop(true); + + let mut child = spawn(&mut command).await?; + let pid = child.id().context("process exited immediately")? as i32; + + let stdout = tokio::spawn(pump(child.stdout.take().unwrap(), io.out.clone(), ServerMessage::Stdout)); + let stderr = tokio::spawn(pump(child.stderr.take().unwrap(), io.out.clone(), ServerMessage::Stderr)); + + let mut child_stdin = child.stdin.take(); + let stdin_rx = &mut io.stdin; + let feed = async move { + if let Some(pipe) = child_stdin.as_mut() { + while let Some(chunk) = stdin_rx.recv().await { + if chunk.is_empty() || pipe.write_all(&chunk).await.is_err() { + break; + } + } + } + drop(child_stdin); + std::future::pending::<()>().await + }; + tokio::pin!(feed); + + let status = tokio::select! { + status = child.wait() => status?, + _ = &mut feed => unreachable!(), + _ = io.cancel.cancelled() => { + terminate(pid, &mut child).await; + bail!("requester disconnected"); + } + }; + + // Output still buffered in the pipes belongs before the exit status. + let _ = tokio::time::timeout(Duration::from_secs(5), async { + let _ = stdout.await; + let _ = stderr.await; + }) + .await; + Ok(exit_code(status)) +} + +/// Runs `command` without the requester's stdio and returns its stdout. +pub async fn capture(mut command: Command, cancel: &CancellationToken) -> Result<(i32, Vec, Vec)> { + command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true); + let child = spawn(&mut command).await?; + tokio::select! { + output = child.wait_with_output() => { + let output = output?; + Ok((exit_code(output.status), output.stdout, output.stderr)) + } + _ = cancel.cancelled() => bail!("requester disconnected"), + } +} + +/// Spawns, retrying briefly if the executable is still open for writing in a forked child. +async fn spawn(command: &mut Command) -> Result { + for _ in 0..20 { + match command.spawn() { + Err(error) if error.raw_os_error() == Some(Errno::ETXTBSY as i32) => { + tokio::time::sleep(Duration::from_millis(50)).await; + } + result => return result.context("failed to start process"), + } + } + command.spawn().context("failed to start process") +} + +async fn terminate(pid: i32, child: &mut tokio::process::Child) { + let _ = killpg(Pid::from_raw(pid), Signal::SIGTERM); + if tokio::time::timeout(Duration::from_secs(5), child.wait()).await.is_err() { + let _ = killpg(Pid::from_raw(pid), Signal::SIGKILL); + let _ = child.wait().await; + } +} + +async fn pump(mut reader: impl AsyncRead + Unpin, out: Output, wrap: fn(Vec) -> ServerMessage) { + let mut buffer = vec![0; 64 * 1024]; + loop { + match reader.read(&mut buffer).await { + Ok(0) | Err(_) => break, + Ok(n) => out.send(wrap(buffer[..n].to_vec())).await, + } + } +} diff --git a/src/ha.rs b/src/ha.rs new file mode 100644 index 0000000..2d73545 --- /dev/null +++ b/src/ha.rs @@ -0,0 +1,236 @@ +//! Home Assistant Companion notifications for pending requests. The broker connects out to Home +//! Assistant's WebSocket API; nothing listens for approvals over HTTP. +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{Value, json}; +use tokio_tungstenite::tungstenite::Message; +use url::Url; + +use crate::approve; +use crate::config::HomeAssistantConfig; +use crate::ops::truncate; +use crate::queue::{Decision, PendingInfo}; +use crate::server::Broker; + +pub fn validate(config: &HomeAssistantConfig) -> Result<()> { + let url = Url::parse(&config.url)?; + if !matches!(url.scheme(), "ws" | "wss") || url.host_str().is_none() || url.path() != "/api/websocket" { + bail!("Home Assistant URL must be ws(s)://host/api/websocket"); + } + if !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some() { + bail!("Home Assistant URL must not contain credentials, a query or a fragment"); + } + + let service = config.notify_service.strip_prefix("mobile_app_").unwrap_or(""); + if service.is_empty() || !service.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_') { + bail!("notification service must be mobile_app_"); + } + + if config.device_id.is_empty() { + bail!("Home Assistant device_id is required"); + } + Ok(()) +} + +pub async fn run(broker: Arc, config: HomeAssistantConfig, token: String) { + loop { + // The token is only ever sent, and the URL can't hold credentials, so errors are safe to log. + if let Err(error) = session(&broker, &config, &token).await { + eprintln!("<4>Home Assistant connection unavailable ({error:#}); retrying in 5 seconds"); + } + tokio::time::sleep(Duration::from_secs(5)).await; + } +} + +/// Notification state for one connection; action IDs are never reused across connections. +struct Notifier<'a> { + broker: &'a Broker, + config: &'a HomeAssistantConfig, + sequence: u64, + /// Random action ID → (request ID, decision). + actions: HashMap, + sent: HashSet, +} + +async fn session(broker: &Broker, config: &HomeAssistantConfig, token: &str) -> Result<()> { + let (mut socket, _) = + tokio::time::timeout(Duration::from_secs(10), tokio_tungstenite::connect_async(&config.url)).await??; + + if read_message(&mut socket).await?["type"] != "auth_required" { + bail!("expected authentication challenge"); + } + send(&mut socket, json!({ "type": "auth", "access_token": token })).await?; + if read_message(&mut socket).await?["type"] != "auth_ok" { + bail!("authentication failed"); + } + + let mut notifier = Notifier { broker, config, sequence: 0, actions: HashMap::new(), sent: HashSet::new() }; + let subscription = notifier.next_id(); + send( + &mut socket, + json!({ "id": subscription, "type": "subscribe_events", "event_type": "mobile_app_notification_action" }), + ) + .await?; + let response = read_message(&mut socket).await?; + if response["id"] != subscription || response["type"] != "result" || response["success"] != true { + bail!("subscribing to notification actions failed: {}", response["error"]["message"]); + } + + let mut changes = broker.queue.subscribe(); + let mut tick = tokio::time::interval(Duration::from_secs(5)); + loop { + notifier.sync(&mut socket).await?; + tokio::select! { + message = read_message(&mut socket) => { + let message = message?; + if message["type"] == "result" && message["success"] == false { + bail!("service call failed"); + } + notifier.handle_event(&message); + } + _ = changes.changed() => {} + _ = tick.tick() => {} + } + } +} + +type Socket = tokio_tungstenite::WebSocketStream>; + +async fn read_message(socket: &mut Socket) -> Result { + loop { + match socket.next().await.context("connection closed")?? { + Message::Text(text) => return Ok(serde_json::from_str(&text)?), + Message::Close(_) => bail!("connection closed"), + _ => continue, + } + } +} + +async fn send(socket: &mut Socket, message: Value) -> Result<()> { + socket.send(Message::text(message.to_string())).await?; + Ok(()) +} + +impl Notifier<'_> { + fn next_id(&mut self) -> u64 { + self.sequence += 1; + self.sequence + } + + async fn notify(&mut self, socket: &mut Socket, data: Value) -> Result<()> { + let id = self.next_id(); + let message = json!({ + "id": id, "type": "call_service", "domain": "notify", "service": self.config.notify_service, "service_data": data, + }); + send(socket, message).await + } + + async fn sync(&mut self, socket: &mut Socket) -> Result<()> { + let pending: HashMap = + self.broker.queue.list().into_iter().map(|e| (e.id.clone(), e)).collect(); + self.actions.retain(|_, (id, _)| pending.contains_key(id)); + + let gone: Vec = self.sent.iter().filter(|id| !pending.contains_key(*id)).cloned().collect(); + for id in gone { + self.notify(socket, json!({ "message": "clear_notification", "data": { "tag": format!("slop-{id}") } })) + .await?; + self.sent.remove(&id); + } + + for (id, entry) in pending { + if !self.sent.contains(&id) { + let data = self.notification(&entry); + self.notify(socket, data).await?; + self.sent.insert(id); + } + } + Ok(()) + } + + fn notification(&mut self, entry: &PendingInfo) -> Value { + // Android shows at most three actions: once, the shortest lease and deny. + let mut decisions = vec![Decision::Once]; + if let Some(&lease) = entry.offers.iter().find(|d| matches!(d, Decision::Lease(_))) { + decisions.push(lease); + } + decisions.push(Decision::Deny); + + let buttons: Vec = decisions + .into_iter() + .map(|decision| { + // Independent of request IDs, which requesters can see. + let action = format!("SLOP_{}", hex::encode(rand::random::<[u8; 32]>())); + self.actions.insert(action.clone(), (entry.id.clone(), decision)); + json!({ "action": action, "title": decision.title(), "authenticationRequired": true }) + }) + .collect(); + + let mut message = format!("{}\n{}", entry.summary, truncate(&entry.detail, 400)); + if let Some(label) = &entry.label { + message += &format!("\nAgent says: {}", truncate(label, 120)); + } + message += &format!("\nFrom {}", entry.requester); + + let title = if entry.sensitive { "Agent approval (sensitive)" } else { "Agent approval" }; + // Sticky, so tapping it doesn't remove it, and persistent, which stops swiping it away on + // Android before 14; the broker clears it by tag once it's answered or expired. + let data = json!({ + "tag": format!("slop-{}", entry.id), + "actions": buttons, + "persistent": true, + "sticky": "true", + }); + json!({ "title": title, "message": message, "data": data }) + } + + fn handle_event(&mut self, message: &Value) { + let event = &message["event"]; + if message["type"] != "event" || event["event_type"] != "mobile_app_notification_action" { + return; + } + + // Other automations' actions aren't ours to mention. + let data = &event["data"]; + let Some(action) = data["action"].as_str().filter(|a| a.starts_with("SLOP_")) else { return }; + let device = data["device_id"].as_str(); + if device != Some(self.config.device_id.as_str()) { + eprintln!("<4>ignored a notification answer from device {device:?}; only the configured device may answer"); + return; + } + + let Some((id, decision)) = self.actions.get(action).cloned() else { + eprintln!("<4>ignored a notification answer for a request that's no longer pending"); + return; + }; + // Fails harmlessly if it expired, was answered in a terminal, or arrived twice. + let _ = approve::approve(self.broker, &id, decision, "home-assistant"); + self.actions.retain(|_, (other, _)| *other != id); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(url: &str, service: &str) -> HomeAssistantConfig { + HomeAssistantConfig { + url: url.into(), + notify_service: service.into(), + device_id: "d".into(), + token: "t".into(), + } + } + + #[test] + fn validates_config() { + assert!(validate(&config("wss://hass.example.org/api/websocket", "mobile_app_pixel")).is_ok()); + assert!(validate(&config("https://hass.example.org/api/websocket", "mobile_app_pixel")).is_err()); + assert!(validate(&config("wss://u:p@hass.example.org/api/websocket", "mobile_app_pixel")).is_err()); + assert!(validate(&config("wss://hass.example.org/api/websocket?x", "mobile_app_pixel")).is_err()); + assert!(validate(&config("wss://hass.example.org/api/websocket", "persistent_notification")).is_err()); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..b9ba1f1 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,13 @@ +//! Broker that runs privileged operations for coding agents, under a policy and with human +//! approval. See `docs/design.md` and `docs/architecture.md`. +pub mod approve; +pub mod audit; +pub mod config; +pub mod exec; +pub mod ha; +pub mod ops; +pub mod policy; +pub mod proto; +pub mod queue; +pub mod server; +pub mod types; diff --git a/src/ops/mod.rs b/src/ops/mod.rs new file mode 100644 index 0000000..15634cb --- /dev/null +++ b/src/ops/mod.rs @@ -0,0 +1,154 @@ +//! Operations the broker carries out. [`plan`] checks a request against the broker's +//! configuration and works out its scope and what approvers are shown; [`execute`] runs it. +use anyhow::{Context, Result}; +use serde_json::{Map, Value}; + +use crate::exec::Io; +use crate::policy::Limits; +use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary}; +use crate::server::Broker; + +pub mod ssh; + +pub struct Parsed { + pub op: &'static str, + /// What an approval covers; also what policy rules match against. + pub scope: Map, + pub summary: String, + pub detail: String, + pub limits: Limits, + /// Reveals a secret or changes who can read one. + pub sensitive: bool, + /// Whether the operation reads the requester's stdin. + pub stdin: bool, + /// Needs no policy or approval. + pub builtin: bool, + pub operation: Operation, +} + +impl Parsed { + pub fn lease_key(&self) -> String { + format!("{} {}", self.op, Value::Object(self.scope.clone())) + } +} + +/// What an operation produced: its exit status and any structured result. +pub struct Outcome { + pub exit: i32, + pub result: Option, +} + +impl From for Outcome { + fn from(exit: i32) -> Outcome { + Outcome { exit, result: None } + } +} + +pub fn plan(broker: &Broker, operation: Operation) -> Result { + match &operation { + Operation::Ssh { destination, command } => { + let config = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?; + ssh::check(config, destination)?; + let shown = + if command.is_empty() { "(no command)".to_owned() } else { truncate(&shell_quote(command), 1000) }; + + Ok(Parsed { + op: "ssh", + scope: ssh::scope(destination), + summary: format!("ssh {}", ssh::describe(destination)), + detail: format!("Command: {shown}"), + limits: Limits::default(), + sensitive: false, + stdin: true, + builtin: false, + operation, + }) + } + Operation::Requests => Ok(Parsed { + op: "requests", + scope: Map::new(), + summary: "list requests".into(), + detail: String::new(), + limits: Limits::default(), + sensitive: false, + stdin: false, + builtin: true, + operation, + }), + } +} + +pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut Io) -> Result { + match parsed.operation { + Operation::Ssh { destination, command } => { + ssh::execute(broker, &destination, &command, io).await.map(Into::into) + } + Operation::Requests => { + let pending = broker + .queue + .list() + .into_iter() + .filter(|e| e.requester == requester) + .map(|e| PendingSummary { id: e.id, summary: e.summary, expires_in: e.expires_in }) + .collect(); + let leases = broker + .queue + .leases(requester) + .into_iter() + .map(|(scope, remaining)| LeaseSummary { scope, remaining }) + .collect(); + Ok(Outcome { exit: 0, result: Some(OpResult::Requests { pending, leases }) }) + } + } +} + +/// Quotes words for a POSIX shell, for showing commands and for remote commands built here. +pub fn shell_quote>(words: &[S]) -> String { + words + .iter() + .map(|w| { + let w = w.as_ref(); + if !w.is_empty() && w.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-./=:@%+,".contains(&c)) { + w.to_owned() + } else { + format!("'{}'", w.replace('\'', r"'\''")) + } + }) + .collect::>() + .join(" ") +} + +/// Text that can't control a terminal, for showing approvers what agents wrote (commit messages, +/// labels, diffs): control characters other than newlines and tabs, and bidirectional overrides, +/// which could hide or reorder what's shown, become `�`. +pub fn printable(text: &str) -> String { + text.chars() + .map(|c| { + let control = c.is_control() && c != '\n' && c != '\t'; + let bidi = matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}' | '\u{200e}' | '\u{200f}'); + if control || bidi { '\u{fffd}' } else { c } + }) + .collect() +} + +pub fn truncate(text: &str, limit: usize) -> String { + match text.char_indices().nth(limit) { + Some((index, _)) => format!("{}…", &text[..index]), + None => text.to_owned(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn makes_text_printable() { + assert_eq!(printable("a\x1b[2Kb\rc\u{202e}d\n\te"), "a\u{fffd}[2Kb\u{fffd}c\u{fffd}d\n\te"); + } + + #[test] + fn quotes_for_the_shell() { + assert_eq!(shell_quote(&["systemctl", "status", "a b", "it's", ""]), r"systemctl status 'a b' 'it'\''s' ''"); + } +} diff --git a/src/ops/ssh.rs b/src/ops/ssh.rs new file mode 100644 index 0000000..9f613ed --- /dev/null +++ b/src/ops/ssh.rs @@ -0,0 +1,111 @@ +//! Commands over SSH with the broker's key, to configured targets or explicit `user@host`s. +use anyhow::{Result, bail}; +use serde_json::{Map, Value, json}; +use tokio::process::Command; + +use crate::config::{SshConfig, credential}; +use crate::exec::{self, Io}; +use crate::proto::Destination; +use crate::server::Broker; +use crate::types::Arg; + +/// Fails if `destination` names a target the broker doesn't know. +pub fn check(config: &SshConfig, destination: &Destination) -> Result<()> { + if let Destination::Node(node) = destination + && !config.targets.contains_key(&**node) + { + bail!("unknown node {node}; use --host for other boxes"); + } + Ok(()) +} + +pub fn scope(destination: &Destination) -> Map { + let value = match destination { + Destination::Node(node) => json!({ "target": node }), + Destination::Host { user, host, port } => json!({ "host": format!("{user}@{host}"), "port": port.get() }), + }; + value.as_object().unwrap().clone() +} + +pub fn describe(destination: &Destination) -> String { + match destination { + Destination::Node(node) => node.to_string(), + Destination::Host { user, host, port } => format!("{user}@{host} port {port} (host)"), + } +} + +/// The `ssh` invocation; every option comes from here or trusted target config. +pub fn command>(config: &SshConfig, destination: &Destination, remote: &[S]) -> Command { + let mut command = Command::new(&config.ssh); + command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty"); + command.args(["-F", "none", "-T", "-i"]).arg(credential(&config.key)); + for option in [ + "IdentitiesOnly=yes", + "IdentityAgent=none", + "BatchMode=yes", + "StrictHostKeyChecking=accept-new", + "UpdateHostKeys=no", + "ForwardAgent=no", + "ForwardX11=no", + "ClearAllForwardings=yes", + "PermitLocalCommand=no", + "ConnectTimeout=15", + // Keeps notices like "Permanently added … to the list of known hosts" out of the output + "LogLevel=ERROR", + ] { + command.args(["-o", option]); + } + command.arg("-o").arg(format!("UserKnownHostsFile={}", config.known_hosts.display())); + match destination { + Destination::Node(node) => { + let target = &config.targets[&**node]; + command.args(&target.ssh_opts).args(["-l", &target.user, "--", &target.hostname]); + } + Destination::Host { user, host, port } => { + command.args(["-p", &port.to_string(), "-l", user, "--", host]); + } + } + + command.args(remote.iter().map(AsRef::as_ref)); + command +} + +pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], io: &mut Io) -> Result { + let config = broker.config.ssh.as_ref().unwrap(); + exec::run(command(config, destination, remote), io, true).await +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::config::SshTarget; + use std::collections::BTreeMap; + + pub fn config() -> SshConfig { + let mut targets = BTreeMap::new(); + targets.insert( + "river".into(), + SshTarget { + hostname: "river.example.org".into(), + user: "deploy".into(), + ssh_opts: vec!["-p".into(), "2222".into()], + }, + ); + SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets } + } + + #[test] + fn unknown_nodes_are_refused() { + assert!(check(&config(), &Destination::Node("river".parse().unwrap())).is_ok()); + assert!(check(&config(), &Destination::Node("sfh".parse().unwrap())).is_err()); + } + + #[test] + fn trusted_options_come_before_the_destination() { + let command = command(&config(), &Destination::Node("river".parse().unwrap()), &["-oProxyCommand=x"]); + let args: Vec<_> = command.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect(); + let separator = args.iter().position(|a| a == "--").unwrap(); + assert_eq!(&args[separator - 3..], ["2222", "-l", "deploy", "--", "river.example.org", "-oProxyCommand=x"]); + assert!(args.contains(&"IdentityAgent=none".to_owned())); + } +} diff --git a/src/policy.rs b/src/policy.rs new file mode 100644 index 0000000..673996a --- /dev/null +++ b/src/policy.rs @@ -0,0 +1,168 @@ +//! Per-requester, per-operation policy: `auto`, `ask` or `deny`, with the lease lengths an +//! approver may grant. Rules match fields of a request's scope with simple globs. +use std::collections::BTreeMap; + +use serde::Deserialize; +use serde_json::{Map, Value}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Action { + Auto, + Ask, + Deny, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OpPolicy { + pub action: Action, + /// Lease lengths in seconds that approvers are offered. + #[serde(default, deserialize_with = "crate::config::durations")] + pub leases: Vec, + /// First matching rule wins; otherwise `action` and `leases` apply. + #[serde(default)] + pub rules: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Rule { + #[serde(rename = "match")] + pub matches: BTreeMap, + pub action: Action, + #[serde(default, deserialize_with = "crate::config::optional_durations")] + pub leases: Option>, +} + +/// What policy decided for one request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Verdict { + pub action: Action, + pub leases: Vec, +} + +/// Limits an operation puts on its own requests, whatever the policy says. +#[derive(Debug, Clone, Copy, Default)] +pub struct Limits { + /// Never approved by policy alone. + pub never_auto: bool, + /// Never covered by a lease. + pub never_lease: bool, +} + +pub fn evaluate(policy: Option<&OpPolicy>, scope: &Map, limits: Limits) -> Verdict { + let Some(policy) = policy else { + return Verdict { action: Action::Deny, leases: vec![] }; + }; + + let (mut action, mut leases) = (policy.action, policy.leases.clone()); + if let Some(rule) = policy.rules.iter().find(|r| matches(&r.matches, scope)) { + action = rule.action; + if let Some(rule_leases) = &rule.leases { + leases = rule_leases.clone(); + } + } + + if limits.never_auto && action == Action::Auto { + action = Action::Ask; + } + if limits.never_lease { + leases.clear(); + } + Verdict { action, leases } +} + +fn matches(patterns: &BTreeMap, scope: &Map) -> bool { + patterns.iter().all(|(field, pattern)| { + let value = match scope.get(field) { + Some(Value::String(s)) => s.clone(), + Some(Value::Null) | None => return false, + Some(other) => other.to_string(), + }; + glob(pattern.as_bytes(), value.as_bytes()) + }) +} + +/// `*` matches any run of characters, `?` one character; everything else is literal. +pub fn glob(pattern: &[u8], text: &[u8]) -> bool { + let (mut p, mut t) = (0, 0); + let mut backtrack = None; + while t < text.len() { + match pattern.get(p) { + Some(b'*') => { + backtrack = Some((p, t)); + p += 1; + } + Some(&c) if c == b'?' || c == text[t] => { + p += 1; + t += 1; + } + _ => match backtrack { + Some((bp, bt)) => { + p = bp + 1; + t = bt + 1; + backtrack = Some((bp, bt + 1)); + } + None => return false, + }, + } + } + pattern[p..].iter().all(|&c| c == b'*') +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn scope(value: Value) -> Map { + value.as_object().unwrap().clone() + } + + #[test] + fn globs() { + assert!(glob(b"*", b"")); + assert!(glob(b"river", b"river")); + assert!(!glob(b"river", b"rivers")); + assert!(glob(b"r*r", b"river")); + assert!(glob(b"*.example.org", b"a.b.example.org")); + assert!(!glob(b"*.example.org", b"example.org")); + assert!(glob(b"?iver", b"river")); + assert!(glob(b"a*b*c", b"aXbYbZc")); + } + + #[test] + fn missing_policy_denies() { + let verdict = evaluate(None, &Map::new(), Limits::default()); + assert_eq!(verdict.action, Action::Deny); + } + + #[test] + fn first_matching_rule_wins() { + let policy: OpPolicy = serde_json::from_value(json!({ + "action": "ask", + "leases": [300, 3600], + "rules": [ + {"match": {"target": "river"}, "action": "deny"}, + {"match": {"target": "r*"}, "action": "auto", "leases": []}, + ], + })) + .unwrap(); + + let verdict = |s| evaluate(Some(&policy), &scope(s), Limits::default()); + assert_eq!(verdict(json!({"target": "river"})).action, Action::Deny); + assert_eq!(verdict(json!({"target": "rain"})), Verdict { action: Action::Auto, leases: vec![] }); + assert_eq!(verdict(json!({"target": "sfh"})), Verdict { action: Action::Ask, leases: vec![300, 3600] }); + assert_eq!(verdict(json!({"host": "river"})).action, Action::Ask); + assert_eq!(verdict(json!({"target": 5})).action, Action::Ask); + } + + #[test] + fn limits_override_policy() { + let policy: OpPolicy = serde_json::from_value(json!({"action": "auto", "leases": [300]})).unwrap(); + let limits = Limits { never_auto: true, never_lease: true }; + let verdict = evaluate(Some(&policy), &Map::new(), limits); + assert_eq!(verdict, Verdict { action: Action::Ask, leases: vec![] }); + } +} diff --git a/src/proto.rs b/src/proto.rs new file mode 100644 index 0000000..2217b18 --- /dev/null +++ b/src/proto.rs @@ -0,0 +1,244 @@ +//! Messages between `slop` and the broker, and between `slop-approve` and the broker. +//! +//! Each message is CBOR, framed with a 4-byte big-endian length (`LengthDelimitedCodec`). A +//! requester sends one [`ClientMessage::Request`], then (only after an `Approved` that asks for +//! it) stdin. The broker answers with [`ServerMessage`]s and closes after a terminal one. +use std::num::NonZeroU16; + +use anyhow::{Context, Result, bail}; +use bytes::Bytes; +use futures_util::{SinkExt, StreamExt}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio_util::codec::{Framed, LengthDelimitedCodec}; + +use crate::audit::Record; +use crate::queue::{Decision, PendingInfo}; +use crate::types::{Arg, HostName, NodeName, UserName}; + +/// Bumped on any incompatible change; the broker refuses other versions. +pub const PROTOCOL_VERSION: u32 = 1; +pub const MAX_MESSAGE: usize = 1 << 20; +pub const DEFAULT_VSOCK_PORT: u32 = 6262; +/// The host's CID, as seen from a guest. +pub const HOST_CID: u32 = 2; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum ClientMessage { + Request(Request), + Stdin(#[serde(with = "serde_bytes")] Vec), + StdinEnd, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Request { + pub version: u32, + /// Free text from the agent (who it is, why); shown to approvers as agent-supplied. + pub label: Option, + pub operation: Operation, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum Operation { + /// A command over SSH, joined with spaces and run by the remote shell (as `ssh` does). + Ssh { destination: Destination, command: Vec }, + /// This requester's pending requests and leases. + Requests, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum Destination { + /// A configured target (normally a deploy-rs node), with its configured user and options. + Node(NodeName), + Host { + user: UserName, + host: HostName, + port: NonZeroU16, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum ServerMessage { + /// Waiting for an approver. + Pending { + id: String, + summary: String, + }, + /// Output follows. The client sends its stdin only if `stdin` is set. + Approved { + by: ApprovedBy, + stdin: bool, + }, + /// Progress from the broker itself. + Info(String), + Stdout(#[serde(with = "serde_bytes")] Vec), + Stderr(#[serde(with = "serde_bytes")] Vec), + /// The operation ran; `exit` is its status and `result` any structured output. + Finished { + exit: i32, + result: Option, + }, + Denied(String), + Expired, + Error(String), +} + +impl ServerMessage { + pub fn is_terminal(&self) -> bool { + matches!(self, Self::Finished { .. } | Self::Denied(_) | Self::Expired | Self::Error(_)) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ApprovedBy { + Policy, + Lease, + Approver, +} + +/// Structured results of operations that produce data rather than a stream. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum OpResult { + Requests { pending: Vec, leases: Vec }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PendingSummary { + pub id: String, + pub summary: String, + pub expires_in: u64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LeaseSummary { + pub scope: String, + pub remaining: u64, +} + +/// Approver socket requests. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum ApproveRequest { + List, + Decide { + id: String, + decision: Decision, + }, + /// The last `count` audit records, at most [`MAX_LOG_RECORDS`]. + Log { + count: usize, + }, +} + +/// Keeps a `Log` response well within [`MAX_MESSAGE`]. +pub const MAX_LOG_RECORDS: usize = 200; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case", deny_unknown_fields)] +pub enum ApproveResponse { + Pending(Vec), + Recorded, + Log(Vec), + Error(String), +} + +pub type Transport = Framed; + +pub fn transport(stream: S) -> Transport { + Framed::new(stream, LengthDelimitedCodec::builder().max_frame_length(MAX_MESSAGE).new_codec()) +} + +pub fn encode(message: &T) -> Result { + let mut buffer = Vec::new(); + ciborium::into_writer(message, &mut buffer)?; + if buffer.len() > MAX_MESSAGE { + bail!("message too large"); + } + Ok(buffer.into()) +} + +pub fn decode(data: &[u8]) -> Result { + ciborium::from_reader(data).context("invalid message") +} + +pub async fn send(transport: &mut S, message: &T) -> Result<()> +where + S: futures_util::Sink + Unpin, + T: Serialize, +{ + transport.send(encode(message)?).await?; + Ok(()) +} + +/// The next message, or `None` at a clean end of stream. +pub async fn receive(transport: &mut S) -> Result> +where + S: futures_util::Stream> + Unpin, + T: DeserializeOwned, +{ + match transport.next().await { + None => Ok(None), + Some(frame) => Ok(Some(decode(&frame?)?)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn messages_round_trip() { + let (a, b) = tokio::io::duplex(1024); + let (mut a, mut b) = (transport(a), transport(b)); + let request = ClientMessage::Request(Request { + version: PROTOCOL_VERSION, + label: Some("test".into()), + operation: Operation::Ssh { + destination: Destination::Node("river".parse().unwrap()), + command: vec!["uptime".parse().unwrap()], + }, + }); + + send(&mut a, &request).await.unwrap(); + send(&mut a, &ClientMessage::Stdin(b"\0\xffbytes".to_vec())).await.unwrap(); + drop(a); + + assert_eq!(receive::<_, ClientMessage>(&mut b).await.unwrap(), Some(request)); + assert_eq!( + receive::<_, ClientMessage>(&mut b).await.unwrap(), + Some(ClientMessage::Stdin(b"\0\xffbytes".to_vec())) + ); + assert_eq!(receive::<_, ClientMessage>(&mut b).await.unwrap(), None); + } + + #[test] + fn invalid_values_fail_to_decode() { + #[derive(Serialize)] + #[serde(rename_all = "kebab-case")] + enum Loose { + Node(String), + } + let data = encode(&Loose::Node("-oProxyCommand=x".into())).unwrap(); + assert!(decode::(&data).is_err()); + let data = encode(&Loose::Node("river".into())).unwrap(); + assert!(decode::(&data).is_ok()); + } + + #[tokio::test] + async fn oversized_frames_are_rejected() { + use tokio::io::AsyncWriteExt; + let (mut a, b) = tokio::io::duplex(64); + a.write_all(&u32::MAX.to_be_bytes()).await.unwrap(); + assert!(receive::<_, ClientMessage>(&mut transport(b)).await.is_err()); + } +} diff --git a/src/queue.rs b/src/queue.rs new file mode 100644 index 0000000..6793375 --- /dev/null +++ b/src/queue.rs @@ -0,0 +1,381 @@ +//! Pending approvals, leases and rate limits. Everything is in memory: a restart drops pending +//! requests and leases. +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use anyhow::{Result, anyhow, bail}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{oneshot, watch}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Decision { + Once, + Lease(u64), + Deny, +} + +impl Decision { + pub fn parse(text: &str) -> Result { + match text { + "once" => Ok(Decision::Once), + "deny" => Ok(Decision::Deny), + _ => parse_duration(text) + .map(Decision::Lease) + .ok_or_else(|| anyhow!("decision must be once, deny or a duration like 5m")), + } + } + + pub fn name(&self) -> String { + match self { + Decision::Once => "once".into(), + Decision::Deny => "deny".into(), + Decision::Lease(seconds) => format_duration(*seconds), + } + } + + pub fn title(&self) -> String { + match self { + Decision::Once => "Once".into(), + Decision::Deny => "Deny".into(), + Decision::Lease(seconds) => format_duration(*seconds), + } + } +} + +/// A new request ID. +pub fn new_id() -> String { + hex::encode(rand::random::<[u8; 8]>()) +} + +pub fn parse_duration(text: &str) -> Option { + let split = text.find(|c: char| !c.is_ascii_digit())?; + let (number, unit) = text.split_at(split); + let number: u64 = number.parse().ok()?; + let scale = match unit { + "s" => 1, + "m" | "min" => 60, + "h" => 3600, + "d" => 86400, + _ => return None, + }; + number.checked_mul(scale).filter(|&s| s > 0) +} + +pub fn format_duration(seconds: u64) -> String { + match seconds { + s if s % 86400 == 0 => format!("{}d", s / 86400), + s if s % 3600 == 0 => format!("{}h", s / 3600), + s if s % 60 == 0 => format!("{}m", s / 60), + s => format!("{s}s"), + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + Approved { + decision: Decision, + /// Who answered, as the audit log names them. + approver: String, + }, + Denied, + Expired, +} + +/// What approvers see of a pending request. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PendingInfo { + pub id: String, + pub requester: String, + pub op: String, + pub summary: String, + pub detail: String, + /// Agent-supplied; never trusted. + pub label: Option, + /// Marks requests that reveal a secret or change who can read one. + pub sensitive: bool, + pub offers: Vec, + pub expires_in: u64, +} + +pub struct NewRequest { + pub requester: String, + pub op: String, + pub lease_key: String, + pub summary: String, + pub detail: String, + pub label: Option, + pub sensitive: bool, + pub leases: Vec, +} + +struct Entry { + request: NewRequest, + deadline: Instant, + reply: Option>, +} + +#[derive(Default)] +struct State { + sequence: u64, + pending: BTreeMap, + leases: HashMap<(String, String), Instant>, + auto: HashMap>, +} + +pub struct Queue { + state: Mutex, + timeout: Duration, + max_pending: usize, + changed: watch::Sender, +} + +impl Queue { + pub fn new(timeout: Duration, max_pending: usize) -> Queue { + Queue { state: Mutex::default(), timeout, max_pending, changed: watch::channel(0).0 } + } + + pub fn timeout(&self) -> Duration { + self.timeout + } + + /// Fires whenever the pending set changes. + pub fn subscribe(&self) -> watch::Receiver { + self.changed.subscribe() + } + + fn bump(&self, state: &mut State) { + state.sequence += 1; + self.changed.send_replace(state.sequence); + } + + pub fn leased(&self, requester: &str, key: &str) -> bool { + let mut state = self.state.lock().unwrap(); + let now = Instant::now(); + state.leases.retain(|_, until| *until > now); + state.leases.contains_key(&(requester.to_owned(), key.to_owned())) + } + + /// Counts a request that policy approves by itself. + pub fn take_auto(&self, requester: &str, per_minute: usize) -> Result<()> { + let mut state = self.state.lock().unwrap(); + let now = Instant::now(); + + let window = state.auto.entry(requester.to_owned()).or_default(); + while window.front().is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(60)) { + window.pop_front(); + } + + if window.len() >= per_minute { + bail!("rate limit reached; try again in a minute"); + } + + window.push_back(now); + Ok(()) + } + + pub fn submit( + &self, + id: &str, + request: NewRequest, + max_for_requester: usize, + ) -> Result> { + let mut state = self.state.lock().unwrap(); + + if state.pending.len() >= self.max_pending { + bail!("approval queue is full"); + } + if state.pending.values().filter(|e| e.request.requester == request.requester).count() >= max_for_requester { + bail!("too many pending requests"); + } + + let (reply, receiver) = oneshot::channel(); + state + .pending + .insert(id.to_owned(), Entry { request, deadline: Instant::now() + self.timeout, reply: Some(reply) }); + + self.bump(&mut state); + Ok(receiver) + } + + /// Drops a request whose client went away or timed out. + pub fn cancel(&self, id: &str) { + let mut state = self.state.lock().unwrap(); + if state.pending.remove(id).is_some() { + self.bump(&mut state); + } + } + + pub fn decide(&self, id: &str, decision: Decision, approver: &str) -> Result { + let mut state = self.state.lock().unwrap(); + let entry = state.pending.get(id).ok_or_else(|| anyhow!("unknown or expired request"))?; + + if let Decision::Lease(seconds) = decision + && !entry.request.leases.contains(&seconds) + { + bail!("lease not offered for this request"); + } + + let info = info(id, entry, Instant::now()); + let mut entry = state.pending.remove(id).unwrap(); + if Instant::now() >= entry.deadline { + self.bump(&mut state); + bail!("request expired"); + } + + if let Decision::Lease(seconds) = decision { + let key = (entry.request.requester.clone(), entry.request.lease_key.clone()); + state.leases.insert(key, Instant::now() + Duration::from_secs(seconds)); + } + + let outcome = match decision { + Decision::Deny => Outcome::Denied, + decision => Outcome::Approved { decision, approver: approver.to_owned() }, + }; + if let Some(reply) = entry.reply.take() { + let _ = reply.send(outcome); + } + + self.bump(&mut state); + Ok(info) + } + + pub fn list(&self) -> Vec { + let state = self.state.lock().unwrap(); + let now = Instant::now(); + state.pending.iter().filter(|(_, e)| e.deadline > now).map(|(id, e)| info(id, e, now)).collect() + } + + /// Active leases for one requester, as (scope key, seconds left). + pub fn leases(&self, requester: &str) -> Vec<(String, u64)> { + let state = self.state.lock().unwrap(); + let now = Instant::now(); + + let mut leases: Vec<_> = state + .leases + .iter() + .filter(|((r, _), until)| r == requester && **until > now) + .map(|((_, key), until)| (key.clone(), until.duration_since(now).as_secs())) + .collect(); + + leases.sort(); + leases + } +} + +fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo { + let r = &entry.request; + + let mut offers = vec![Decision::Once]; + offers.extend(r.leases.iter().map(|&s| Decision::Lease(s))); + offers.push(Decision::Deny); + + PendingInfo { + id: id.to_owned(), + requester: r.requester.clone(), + op: r.op.clone(), + summary: r.summary.clone(), + detail: r.detail.clone(), + label: r.label.clone(), + sensitive: r.sensitive, + offers, + expires_in: entry.deadline.saturating_duration_since(now).as_secs(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(requester: &str, key: &str) -> NewRequest { + NewRequest { + requester: requester.into(), + op: "ssh".into(), + lease_key: key.into(), + summary: "ssh river".into(), + detail: String::new(), + label: None, + sensitive: false, + leases: vec![300], + } + } + + fn submit(queue: &Queue, requester: &str, max: usize) -> Result<(String, oneshot::Receiver)> { + let id = new_id(); + queue.submit(&id, request(requester, "k"), max).map(|reply| (id, reply)) + } + + #[test] + fn decisions_parse() { + assert_eq!(Decision::parse("once").unwrap(), Decision::Once); + assert_eq!(Decision::parse("5m").unwrap(), Decision::Lease(300)); + assert_eq!(Decision::parse("1h").unwrap(), Decision::Lease(3600)); + assert!(Decision::parse("0m").is_err()); + assert!(Decision::parse("5").is_err()); + assert!(Decision::parse("5x").is_err()); + assert_eq!(Decision::Lease(300).name(), "5m"); + } + + #[tokio::test] + async fn lease_covers_the_same_scope_only() { + let queue = Queue::new(Duration::from_secs(60), 64); + let (id, reply) = submit(&queue, "a", 4).unwrap(); + queue.decide(&id, Decision::Lease(300), "dev").unwrap(); + assert_eq!(reply.await.unwrap(), Outcome::Approved { decision: Decision::Lease(300), approver: "dev".into() }); + assert!(queue.leased("a", "k")); + assert!(!queue.leased("a", "other")); + assert!(!queue.leased("b", "k")); + } + + #[tokio::test] + async fn once_and_deny_leave_no_lease() { + let queue = Queue::new(Duration::from_secs(60), 64); + let (id, reply) = submit(&queue, "a", 4).unwrap(); + queue.decide(&id, Decision::Once, "dev").unwrap(); + assert_eq!(reply.await.unwrap(), Outcome::Approved { decision: Decision::Once, approver: "dev".into() }); + let (id, reply) = submit(&queue, "a", 4).unwrap(); + queue.decide(&id, Decision::Deny, "dev").unwrap(); + assert_eq!(reply.await.unwrap(), Outcome::Denied); + assert!(!queue.leased("a", "k")); + assert!(queue.decide(&id, Decision::Once, "dev").is_err()); + } + + #[test] + fn unoffered_leases_are_refused() { + let queue = Queue::new(Duration::from_secs(60), 64); + let (id, _reply) = submit(&queue, "a", 4).unwrap(); + assert!(queue.decide(&id, Decision::Lease(3600), "dev").is_err()); + assert_eq!(queue.list().len(), 1); + } + + #[test] + fn limits_pending_requests() { + let queue = Queue::new(Duration::from_secs(60), 3); + let _held: Vec<_> = (0..2).map(|_| submit(&queue, "a", 2).unwrap()).collect(); + assert!(submit(&queue, "a", 2).is_err()); + let _b = submit(&queue, "b", 2).unwrap(); + assert!(submit(&queue, "c", 2).is_err()); + } + + #[test] + fn rate_limits_auto_requests() { + let queue = Queue::new(Duration::from_secs(60), 64); + assert!(queue.take_auto("a", 2).is_ok()); + assert!(queue.take_auto("a", 2).is_ok()); + assert!(queue.take_auto("a", 2).is_err()); + assert!(queue.take_auto("b", 2).is_ok()); + } + + #[test] + fn cancel_removes_and_notifies() { + let queue = Queue::new(Duration::from_secs(60), 64); + let mut changes = queue.subscribe(); + let (id, _reply) = submit(&queue, "a", 4).unwrap(); + assert!(changes.has_changed().unwrap()); + changes.mark_unchanged(); + queue.cancel(&id); + assert!(changes.has_changed().unwrap()); + assert!(queue.list().is_empty()); + } +} diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..53407a7 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,325 @@ +//! Requester connections: identify the requester, apply policy, wait for approval and run the +//! operation. +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, anyhow, bail}; +use futures_util::StreamExt; +use nix::unistd::geteuid; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio::net::UnixListener; +use tokio::sync::{Semaphore, mpsc}; +use tokio_util::sync::CancellationToken; +use tokio_vsock::{VMADDR_CID_ANY, VsockAddr, VsockListener}; + +use crate::audit::{Audit, Event}; +use crate::config::Config; +use crate::exec::{Io, Output}; +use crate::ops; +use crate::policy::{self, Action}; +use crate::proto::{ApprovedBy, ClientMessage, PROTOCOL_VERSION, Request, ServerMessage, decode, encode, transport}; +use crate::queue::{NewRequest, Outcome, Queue, new_id}; + +pub struct Broker { + pub config: Config, + pub queue: Queue, + pub audit: Audit, +} + +impl Broker { + pub fn new(config: Config) -> Result { + config.validate()?; + let queue = Queue::new(Duration::from_secs(config.timeout), config.max_pending); + let audit = Audit::new(config.audit_log.as_deref())?; + Ok(Broker { config, queue, audit }) + } +} + +const MAX_CONNECTIONS: usize = 128; + +pub async fn listen_vsock(broker: Arc, port: u32) -> Result<()> { + let listener = VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, port)).context("binding vsock")?; + let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); + + loop { + let (stream, address) = listener.accept().await?; + let Some(requester) = broker.config.requester_by_cid(address.cid()).map(str::to_owned) else { + broker.audit.log(Event::Unknown { peer: format!("vsock CID {}", address.cid()) }); + continue; + }; + + let Ok(slot) = slots.clone().try_acquire_owned() else { continue }; + let broker = broker.clone(); + tokio::spawn(async move { + handle(broker, stream, requester).await; + drop(slot); + }); + } +} + +pub fn bind_unix(path: &Path, mode: u32, gid: Option) -> Result { + let _ = std::fs::remove_file(path); + let listener = UnixListener::bind(path).with_context(|| format!("binding {}", path.display()))?; + if let Some(gid) = gid { + std::os::unix::fs::chown(path, None, Some(gid))?; + } + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))?; + Ok(listener) +} + +/// Local requesters, identified by the UID the kernel reports for the peer. +pub async fn listen_unix(broker: Arc, listener: UnixListener) -> Result<()> { + let slots = Arc::new(Semaphore::new(MAX_CONNECTIONS)); + + loop { + let (stream, _) = listener.accept().await?; + let uid = stream.peer_cred()?.uid(); + let Some(requester) = broker.config.requester_by_uid(uid).map(str::to_owned) else { + broker.audit.log(Event::Unknown { peer: format!("local UID {uid}") }); + continue; + }; + + let Ok(slot) = slots.clone().try_acquire_owned() else { continue }; + let broker = broker.clone(); + tokio::spawn(async move { + handle(broker, stream, requester).await; + drop(slot); + }); + } +} + +/// Serves one request from `requester` on `stream`. +pub async fn handle(broker: Arc, stream: S, requester: String) { + let (mut sink, mut source) = transport(stream).split(); + let (tx, mut rx) = mpsc::channel::(64); + let writer = tokio::spawn(async move { + use futures_util::SinkExt; + while let Some(message) = rx.recv().await { + let terminal = message.is_terminal(); + let Ok(data) = encode(&message) else { break }; + if sink.send(data).await.is_err() || terminal { + break; + } + } + let _ = sink.close().await; + }); + + let out = Output(tx); + + let first = tokio::time::timeout(Duration::from_secs(10), source.next()).await; + let request = match first { + Ok(Some(Ok(frame))) => match decode::(&frame) { + Ok(ClientMessage::Request(request)) => Ok(request), + Ok(_) => Err(anyhow!("expected a request")), + Err(error) => Err(error), + }, + Ok(Some(Err(error))) => Err(error.into()), + _ => Err(anyhow!("expected a request")), + }; + + // After the request, the requester only sends stdin; anything else, or the connection + // closing, means it's gone. + let cancel = CancellationToken::new(); + let (stdin_tx, stdin_rx) = mpsc::channel(16); + let reader = { + let cancel = cancel.clone(); + tokio::spawn(async move { + let mut stdin_tx = Some(stdin_tx); + while let Some(Ok(frame)) = source.next().await { + match decode::(&frame) { + Ok(ClientMessage::Stdin(data)) => { + if let Some(tx) = &stdin_tx { + let _ = tx.send(data).await; + } + } + Ok(ClientMessage::StdinEnd) => stdin_tx = None, + _ => break, + } + } + cancel.cancel(); + }) + }; + + let mut io = Io { stdin: stdin_rx, out: out.clone(), cancel }; + + let message = match request { + Ok(request) => process(&broker, &requester, request, &mut io).await, + Err(error) => Some(ServerMessage::Error(format!("{error:#}"))), + }; + if let Some(message) = message { + out.send(message).await; + } + + drop(io); + drop(out); + let _ = writer.await; + reader.abort(); +} + +/// Returns the final message, or `None` if the requester went away. +async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io) -> Option { + if request.version != PROTOCOL_VERSION { + return Some(ServerMessage::Error(format!( + "protocol version {} is not supported (the broker uses {PROTOCOL_VERSION}); update slop", + request.version + ))); + } + + let id = new_id(); + let label = request.label.as_deref().map(|l| ops::truncate(l.trim(), 200)).filter(|l| !l.is_empty()); + let parsed = match ops::plan(broker, request.operation) { + Ok(parsed) => parsed, + Err(error) => { + let error = format!("{error:#}"); + broker.audit.log(Event::Invalid { id, requester: requester.to_owned(), error: error.clone() }); + return Some(ServerMessage::Error(error)); + } + }; + + // Built-in operations only read the broker's own state, so they aren't logged. + let log = |event| { + if !parsed.builtin { + broker.audit.log(event) + } + }; + + log(Event::Request { + id: id.clone(), + requester: requester.to_owned(), + op: parsed.op.to_owned(), + summary: parsed.summary.clone(), + detail: parsed.detail.clone(), + label: label.clone(), + }); + + let (approved_by, approver) = match authorize(broker, &id, requester, &parsed, label, io).await { + Ok(Some(approval)) => approval, + Ok(None) => { + log(Event::Disconnected { id }); + return None; + } + Err(message) => { + log(match &message { + ServerMessage::Expired => Event::Expired { id }, + ServerMessage::Denied(reason) | ServerMessage::Error(reason) => { + Event::Denied { id, reason: reason.clone() } + } + other => Event::Denied { id, reason: format!("{other:?}") }, + }); + return Some(message); + } + }; + + log(Event::Approved { id: id.clone(), by: approved_by, approver }); + io.out.send(ServerMessage::Approved { by: approved_by, stdin: parsed.stdin }).await; + + let (start, builtin) = (std::time::Instant::now(), parsed.builtin); + let result = ops::execute(broker, requester, parsed, io).await; + + let log = |event| { + if !builtin { + broker.audit.log(event) + } + }; + + if io.cancel.is_cancelled() { + log(Event::Disconnected { id }); + return None; + } + + match result { + Ok(outcome) => { + log(Event::Finished { id, exit: outcome.exit, seconds: start.elapsed().as_secs_f64() }); + Some(ServerMessage::Finished { exit: outcome.exit, result: outcome.result }) + } + Err(error) => { + let error = format!("{error:#}"); + log(Event::Failed { id, error: error.clone() }); + Some(ServerMessage::Error(error)) + } + } +} + +/// Applies policy and waits for an approver if needed, returning who approved it (and the +/// approver's name). `Ok(None)` means the requester left. +async fn authorize( + broker: &Broker, + id: &str, + requester: &str, + parsed: &ops::Parsed, + label: Option, + io: &mut Io, +) -> Result)>, ServerMessage> { + if parsed.builtin { + return Ok(Some((ApprovedBy::Policy, None))); + } + + let settings = broker.config.policy(requester).ok_or_else(|| denied("unknown requester"))?; + let verdict = policy::evaluate(settings.ops.get(parsed.op), &parsed.scope, parsed.limits); + match verdict.action { + Action::Deny => Err(denied("denied by policy")), + Action::Auto => { + broker + .queue + .take_auto(requester, settings.auto_per_minute) + .map_err(|e| ServerMessage::Error(e.to_string()))?; + Ok(Some((ApprovedBy::Policy, None))) + } + Action::Ask => { + let key = parsed.lease_key(); + if !verdict.leases.is_empty() && broker.queue.leased(requester, &key) { + return Ok(Some((ApprovedBy::Lease, None))); + } + + let pending = NewRequest { + requester: requester.to_owned(), + op: parsed.op.to_owned(), + lease_key: key, + summary: parsed.summary.clone(), + detail: parsed.detail.clone(), + label, + sensitive: parsed.sensitive, + leases: verdict.leases, + }; + + let reply = broker + .queue + .submit(id, pending, settings.max_pending) + .map_err(|e| ServerMessage::Error(e.to_string()))?; + io.out.send(ServerMessage::Pending { id: id.to_owned(), summary: parsed.summary.clone() }).await; + + let outcome = tokio::select! { + outcome = reply => outcome.unwrap_or(Outcome::Expired), + _ = tokio::time::sleep(broker.queue.timeout()) => Outcome::Expired, + _ = io.cancel.cancelled() => { + broker.queue.cancel(id); + return Ok(None); + } + }; + + broker.queue.cancel(id); + match outcome { + Outcome::Approved { approver, .. } => Ok(Some((ApprovedBy::Approver, Some(approver)))), + Outcome::Denied => Err(denied("denied by approver")), + Outcome::Expired => Err(ServerMessage::Expired), + } + } + } +} + +fn denied(reason: &str) -> ServerMessage { + ServerMessage::Denied(reason.into()) +} + +/// Makes sure configured sockets' parent directories aren't writable by requesters. +pub fn check_runtime_dir(path: &Path) -> Result<()> { + use std::os::unix::fs::MetadataExt; + let parent = path.parent().context("socket path has no parent")?; + let metadata = std::fs::metadata(parent)?; + if metadata.uid() != geteuid().as_raw() || metadata.mode() & 0o022 != 0 { + bail!("{} must be owned by the broker and not group or world writable", parent.display()); + } + Ok(()) +} diff --git a/src/types.rs b/src/types.rs new file mode 100644 index 0000000..cd668c3 --- /dev/null +++ b/src/types.rs @@ -0,0 +1,130 @@ +//! Validated values used in requests. Each type can only be constructed (including by +//! deserializing) from a value that passed its check, so the rest of the broker can rely on it. +use std::fmt; +use std::ops::Deref; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +macro_rules! validated_string { + ($(#[$doc:meta])* $name:ident, $what:literal, $check:expr) => { + $(#[$doc])* + #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] + #[serde(try_from = "String", into = "String")] + pub struct $name(String); + + impl TryFrom for $name { + type Error = String; + fn try_from(value: String) -> Result { + let check: fn(&str) -> bool = $check; + if check(&value) { Ok(Self(value)) } else { Err(format!("invalid {}: {:?}", $what, value)) } + } + } + + impl FromStr for $name { + type Err = String; + fn from_str(value: &str) -> Result { + Self::try_from(value.to_owned()) + } + } + + impl From<$name> for String { + fn from(value: $name) -> String { + value.0 + } + } + + impl Deref for $name { + type Target = str; + fn deref(&self) -> &str { + &self.0 + } + } + + impl AsRef for $name { + fn as_ref(&self) -> &str { + &self.0 + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(&self.0) + } + } + }; +} + +validated_string!( + /// A deploy node or other configured name. + NodeName, + "name", + |s| { + let b = s.as_bytes(); + !b.is_empty() + && b.len() <= 128 + && b[0].is_ascii_alphanumeric() + && b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_.-".contains(&c)) + } +); + +validated_string!( + /// A remote login name. + UserName, + "user name", + |s| { + let b = s.as_bytes(); + !b.is_empty() + && b.len() <= 32 + && (b[0].is_ascii_lowercase() || b[0] == b'_') + && b.iter().all(|&c| c.is_ascii_lowercase() || c.is_ascii_digit() || b"_.-".contains(&c)) + } +); + +validated_string!( + /// A DNS name or IP address; never something `ssh` could read as an option. + HostName, + "host name", + |s| { + if s.parse::().is_ok() { + return true; + } + let b = s.as_bytes(); + !b.is_empty() && b.len() <= 253 && b[0].is_ascii_alphanumeric() && b.iter().all(|&c| c.is_ascii_alphanumeric() || b".-".contains(&c)) + } +); + +validated_string!( + /// One word of a command; anything but NUL. + Arg, + "argument", + |s| !s.contains('\0') +); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names() { + assert!("river".parse::().is_ok()); + assert!("container-hass.x_1".parse::().is_ok()); + assert!("-oProxyCommand=x".parse::().is_err()); + assert!("".parse::().is_err()); + assert!("root".parse::().is_ok()); + assert!("Root".parse::().is_err()); + assert!("-l".parse::().is_err()); + assert!("fergal.example.org".parse::().is_ok()); + assert!("2a0e:97c0:4d2:10::2".parse::().is_ok()); + assert!("-oProxyCommand=x".parse::().is_err()); + assert!("a b".parse::().is_err()); + } + + #[test] + fn deserializing_validates() { + let ok: Result = serde_json::from_str("\"river\""); + assert!(ok.is_ok()); + let bad: Result = serde_json::from_str("\"-x\""); + assert!(bad.is_err()); + } +} diff --git a/tests/broker.rs b/tests/broker.rs new file mode 100644 index 0000000..e2696d1 --- /dev/null +++ b/tests/broker.rs @@ -0,0 +1,294 @@ +//! End-to-end tests of the request handler with a fake `ssh`. +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use nix::sys::signal::kill; +use nix::unistd::Pid; +use serde_json::json; +use tokio::io::DuplexStream; + +use slop_broker::config::Config; +use slop_broker::proto::{ + ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Request, ServerMessage, Transport, + decode, encode, transport, +}; +use slop_broker::queue::Decision; +use slop_broker::server::{Broker, handle}; +use slop_broker::types::Arg; + +const FAKE_SSH: &str = r#"#!/bin/sh +echo $$ > "${0%/*}/pid" +echo "args: $*" +while read -r line; do + [ "$line" = block ] && while read -r _; do :; done + echo "in: $line" +done +echo done >&2 +exit 3 +"#; + +fn broker(directory: &Path, ops: serde_json::Value) -> Arc { + let ssh = directory.join("ssh"); + std::fs::write(&ssh, FAKE_SSH).unwrap(); + std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let config: Config = serde_json::from_value(json!({ + "requesters": { "agent": { "policy": "agent" } }, + "policies": { "agent": { "ops": ops } }, + "timeout": 2, + "approve_socket": "/unused", + "approver_group": "root", + "audit_log": directory.join("audit.jsonl"), + "ssh": { + "ssh": ssh, + "key": "/key", + "known_hosts": "/kh", + "targets": { "river": { "hostname": "river.example.org", "user": "deploy", "ssh_opts": [] } }, + }, + })) + .unwrap(); + + Arc::new(Broker::new(config).unwrap()) +} + +struct Client { + transport: Transport, +} + +impl Client { + async fn start(broker: &Arc, operation: Operation) -> Client { + Client::start_with(broker, Request { version: PROTOCOL_VERSION, label: Some("test".into()), operation }).await + } + + async fn start_with(broker: &Arc, request: Request) -> Client { + let (client, server) = tokio::io::duplex(1 << 16); + tokio::spawn(handle(broker.clone(), server, "agent".into())); + let mut client = Client { transport: transport(client) }; + client.send(ClientMessage::Request(request)).await; + client + } + + async fn send(&mut self, message: ClientMessage) { + self.transport.send(encode(&message).unwrap()).await.unwrap(); + } + + /// Reads until the next message other than output, collecting output. + async fn next(&mut self, output: &mut String) -> ServerMessage { + loop { + let frame = + tokio::time::timeout(Duration::from_secs(10), self.transport.next()).await.unwrap().unwrap().unwrap(); + match decode::(&frame).unwrap() { + ServerMessage::Stdout(data) | ServerMessage::Stderr(data) => { + output.push_str(&String::from_utf8_lossy(&data)) + } + message => return message, + } + } + } +} + +fn ssh(command: &[&str]) -> Operation { + Operation::Ssh { + destination: Destination::Node("river".parse().unwrap()), + command: command.iter().map(|c| c.parse::().unwrap()).collect(), + } +} + +fn finished(exit: i32) -> ServerMessage { + ServerMessage::Finished { exit, result: None } +} + +#[tokio::test] +async fn auto_runs_with_stdio_and_exit_status() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); + + let mut client = Client::start(&broker, ssh(&["uptime", "-p"])).await; + let mut output = String::new(); + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: true }); + + client.send(ClientMessage::Stdin(b"hello\n".to_vec())).await; + client.send(ClientMessage::StdinEnd).await; + + assert_eq!(client.next(&mut output).await, finished(3)); + assert!(output.contains("-l deploy -- river.example.org uptime -p"), "{output}"); + assert!(output.contains("-o IdentityAgent=none"), "{output}"); + assert!(output.contains("in: hello"), "{output}"); + assert!(output.contains("done"), "{output}"); +} + +#[tokio::test] +async fn policy_can_deny_and_unlisted_operations_are_denied() { + let directory = tempfile::tempdir().unwrap(); + let ops = json!({ "ssh": { "action": "auto", "rules": [{ "match": { "target": "river" }, "action": "deny" }] } }); + let broker = broker(directory.path(), ops); + + let mut client = Client::start(&broker, ssh(&["true"])).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_))); + let broker = self::broker(directory.path(), json!({})); + let mut client = Client::start(&broker, ssh(&["true"])).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_))); +} + +#[tokio::test] +async fn unknown_nodes_and_versions_are_rejected() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); + + let operation = Operation::Ssh { destination: Destination::Node("sfh".parse().unwrap()), command: vec![] }; + let mut client = Client::start(&broker, operation).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("unknown node"))); + + let request = Request { version: PROTOCOL_VERSION + 1, label: None, operation: ssh(&["true"]) }; + let mut client = Client::start_with(&broker, request).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("protocol version"))); +} + +#[tokio::test] +async fn invalid_messages_are_rejected() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); + + let raw = |node: &str, extra: bool| { + let mut ssh = json!({ "destination": { "node": node }, "command": [] }); + if extra { + ssh["unexpected"] = json!(true); + } + json!({ "request": { "version": PROTOCOL_VERSION, "label": null, "operation": { "ssh": ssh } } }) + }; + + for (message, valid) in + [(raw("river", false), true), (raw("-oProxyCommand=x", false), false), (raw("river", true), false)] + { + let (client, server) = tokio::io::duplex(1 << 16); + tokio::spawn(handle(broker.clone(), server, "agent".into())); + let mut client = Client { transport: transport(client) }; + client.transport.send(encode(&message).unwrap()).await.unwrap(); + let reply = client.next(&mut String::new()).await; + assert_eq!(matches!(reply, ServerMessage::Approved { .. }), valid, "{message} → {reply:?}"); + } +} + +async fn pending_id(client: &mut Client) -> String { + match client.next(&mut String::new()).await { + ServerMessage::Pending { id, summary } => { + assert_eq!(summary, "ssh river"); + id + } + other => panic!("expected pending, got {other:?}"), + } +} + +#[tokio::test] +async fn ask_waits_for_an_approver_and_leases_cover_repeats() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "ask", "leases": [300] } })); + + let mut client = Client::start(&broker, ssh(&["true"])).await; + let id = pending_id(&mut client).await; + + let listed = broker.queue.list(); + assert_eq!(listed[0].label.as_deref(), Some("test")); + assert_eq!(listed[0].offers, [Decision::Once, Decision::Lease(300), Decision::Deny]); + + slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test").unwrap(); + let mut output = String::new(); + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true }); + + client.send(ClientMessage::StdinEnd).await; + assert_eq!(client.next(&mut output).await, finished(3)); + + // Same scope, different command: covered by the lease. + let mut client = Client::start(&broker, ssh(&["reboot"])).await; + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Lease, stdin: true }); + + // Every step is in the audit log under the request's ID. + let records = broker.audit.tail(10).unwrap(); + let events: Vec = records.iter().map(|r| r.event.to_string()).collect(); + let short = &id[..6]; + + assert_eq!(events[0], format!("{short} agent asks: ssh river; Command: true (label: test)")); + assert_eq!(events[1], format!("{short} answered 5m by test")); + assert_eq!(events[2], format!("{short} approved by test")); + assert!(events[3].starts_with(&format!("{short} finished with exit status 3 after ")), "{events:?}"); + assert!(events[4].ends_with("agent asks: ssh river; Command: reboot (label: test)"), "{events:?}"); + assert!(events[5].ends_with("approved by a lease"), "{events:?}"); +} + +#[tokio::test] +async fn denial_and_expiry() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } })); + let mut client = Client::start(&broker, ssh(&["true"])).await; + let id = pending_id(&mut client).await; + assert!(slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test").is_err(), "lease not offered"); + slop_broker::approve::approve(&broker, &id, Decision::Deny, "test").unwrap(); + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Denied(_))); + + let mut client = Client::start(&broker, ssh(&["true"])).await; + pending_id(&mut client).await; + assert_eq!(client.next(&mut String::new()).await, ServerMessage::Expired); + assert!(broker.queue.list().is_empty()); +} + +#[tokio::test] +async fn disconnecting_drops_the_request() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } })); + let mut client = Client::start(&broker, ssh(&["true"])).await; + pending_id(&mut client).await; + drop(client); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(broker.queue.list().is_empty()); +} + +#[tokio::test] +async fn disconnecting_kills_the_process() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); + + let mut client = Client::start(&broker, ssh(&["true"])).await; + client.next(&mut String::new()).await; + client.send(ClientMessage::Stdin(b"block\n".to_vec())).await; + + let pid_file = directory.path().join("pid"); + let mut pid = None; + for _ in 0..50 { + tokio::time::sleep(Duration::from_millis(50)).await; + pid = std::fs::read_to_string(&pid_file).ok().and_then(|p| p.trim().parse::().ok()); + if pid.is_some() { + break; + } + } + let pid = pid.expect("fake ssh started"); + + drop(client); + tokio::time::sleep(Duration::from_millis(500)).await; + let alive = kill(Pid::from_raw(pid), None).is_ok(); + assert!(!alive, "process {pid} survived its requester"); +} + +#[tokio::test] +async fn requests_lists_pending_and_leases() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "ask", "leases": [300] } })); + + let mut waiting = Client::start(&broker, ssh(&["true"])).await; + pending_id(&mut waiting).await; + + let mut client = Client::start(&broker, Operation::Requests).await; + let mut output = String::new(); + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false }); + + match client.next(&mut output).await { + ServerMessage::Finished { exit: 0, result: Some(OpResult::Requests { pending, leases }) } => { + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].summary, "ssh river"); + assert!(leases.is_empty()); + } + other => panic!("unexpected {other:?}"), + } +}