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 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-23 00:39:36 +00:00
commit 67b11b0c61
31 files changed
+5460

No files matched your search

+4
View File
@@ -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
+6
View File
@@ -0,0 +1,6 @@
/target
/result*
/.direnv
/.devenv*
/devenv.local.nix
/devenv.local.yaml
Generated
+1548
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -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"
+21
View File
@@ -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.
+45
View File
@@ -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
}
+21
View File
@@ -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
'';
}
+4
View File
@@ -0,0 +1,4 @@
# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json
inputs:
nixpkgs:
url: github:NixOS/nixpkgs/nixos-unstable
Generated
+27
View File
@@ -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
}
+55
View File
@@ -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);
};
}
+196
View File
@@ -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";
};
};
};
}
+26
View File
@@ -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;
};
}
+99
View File
@@ -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
'';
}
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"
+49
View File
@@ -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 <node> -- <command>…` | Run a command over SSH on a deploy node, as the node's configured user. |
| `slop ssh --host <user>@<host> [-p <port>] -- <command>…` | 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 <node> -- 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.
+298
View File
@@ -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<Broker>, 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<Broker>, 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<ApproveResponse> {
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<ApproveResponse> {
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<Vec<PendingInfo>> {
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::<Vec<_>>().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 <id> show a request in full
slop-approve <id> <decision> answer a request: once, deny or an offered lease (e.g. 5m)
slop-approve <decision> 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<String> =
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());
}
}
+235
View File
@@ -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<String>,
},
Approved {
id: String,
by: ApprovedBy,
/// Who answered, when an approver did.
#[serde(default, skip_serializing_if = "Option::is_none")]
approver: Option<String>,
},
/// 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<File>)>,
}
impl Audit {
pub fn new(path: Option<&Path>) -> Result<Audit> {
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 `<N>` 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<Vec<Record>> {
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"
);
}
}
+109
View File
@@ -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<String>,
},
}
const DEFAULT_APPROVE_SOCKET: &str = "/run/slop-broker/approve.sock";
#[tokio::main]
async fn main() {
let mut args: Vec<String> = 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")
}
+249
View File
@@ -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:<cid>:<port> or unix:<path>."
)]
struct Cli {
/// Who is asking and why; shown to the approver as agent-supplied.
#[arg(long, env = "SLOP_LABEL", global = true)]
label: Option<String>,
/// 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<NonZeroU16>,
}
impl Target {
fn destination(&self) -> Result<Destination> {
if !self.host {
if self.port.is_some() {
bail!("--port needs --host; deploy nodes use their configured port");
}
return Ok(Destination::Node(parse::<NodeName>(&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::<UserName>(user)?, host: parse::<HostName>(host)?, port })
}
}
fn parse<T: std::str::FromStr<Err = String>>(value: &str) -> Result<T> {
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<Arg>,
},
/// Show your pending requests and active leases.
Requests,
/// Print the guide for agents.
Guide,
}
fn operation(command: Command) -> Result<Operation> {
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<String> {
let directory = std::env::current_dir().ok()?;
Some(format!("in {}", directory.file_name()?.to_string_lossy()))
}
trait Stream: AsyncRead + AsyncWrite + Send + Unpin {}
impl<T: AsyncRead + AsyncWrite + Send + Unpin> Stream for T {}
async fn connect() -> Result<Box<dyn Stream>> {
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:<cid>:<port> or unix:<path>")
}
#[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<i32> {
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::<ClientMessage>(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::<ServerMessage>(&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<ClientMessage>) {
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;
}
}
}
}
}
+243
View File
@@ -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<String, Requester>,
/// Named policies; several requesters can share one.
#[serde(default)]
pub policies: BTreeMap<String, Policy>,
/// 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<u32>,
/// Unix socket for local requesters, identified by UID.
#[serde(default)]
pub request_socket: Option<PathBuf>,
pub approve_socket: PathBuf,
/// Group whose members may answer requests.
pub approver_group: String,
#[serde(default)]
pub audit_log: Option<PathBuf>,
#[serde(default)]
pub ssh: Option<SshConfig>,
#[serde(default)]
pub home_assistant: Option<HomeAssistantConfig>,
}
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<u32>,
#[serde(default)]
pub uid: Option<u32>,
/// 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<String, OpPolicy>,
}
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<String, SshTarget>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SshTarget {
pub hostname: String,
pub user: String,
#[serde(default)]
pub ssh_opts: Vec<String>,
}
#[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<u64, D::Error> {
#[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<Vec<u64>, D::Error> {
#[derive(Deserialize)]
struct Item(#[serde(deserialize_with = "duration")] u64);
Ok(Vec::<Item>::deserialize(deserializer)?.into_iter().map(|i| i.0).collect())
}
pub fn optional_durations<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Vec<u64>>, 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<u32> {
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<Config> {
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::<Config>("approve_socket = \"/a\"\napprover_group = \"g\"\ntimeout = \"5\"\n").is_err()
);
assert!(toml::from_str::<Config>("approve_socket = \"/a\"\napprover_group = \"g\"\nunknown = 1\n").is_err());
let mut missing = config.clone();
missing.policies.clear();
assert!(missing.validate().is_err());
}
}
+136
View File
@@ -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<ServerMessage>);
impl Output {
pub async fn send(&self, message: ServerMessage) {
let _ = self.0.send(message).await;
}
pub async fn info(&self, message: impl Into<String>) {
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<Vec<u8>>,
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<i32> {
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<u8>, Vec<u8>)> {
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<tokio::process::Child> {
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<u8>) -> 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,
}
}
}
+236
View File
@@ -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_<device>");
}
if config.device_id.is_empty() {
bail!("Home Assistant device_id is required");
}
Ok(())
}
pub async fn run(broker: Arc<Broker>, 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<String, (String, Decision)>,
sent: HashSet<String>,
}
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<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
async fn read_message(socket: &mut Socket) -> Result<Value> {
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<String, PendingInfo> =
self.broker.queue.list().into_iter().map(|e| (e.id.clone(), e)).collect();
self.actions.retain(|_, (id, _)| pending.contains_key(id));
let gone: Vec<String> = 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<Value> = 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());
}
}
+13
View File
@@ -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;
+154
View File
@@ -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<String, Value>,
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<OpResult>,
}
impl From<i32> for Outcome {
fn from(exit: i32) -> Outcome {
Outcome { exit, result: None }
}
}
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
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<Outcome> {
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<S: AsRef<str>>(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::<Vec<_>>()
.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' ''");
}
}
+111
View File
@@ -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<String, Value> {
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<S: AsRef<str>>(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<i32> {
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()));
}
}
+168
View File
@@ -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<u64>,
/// First matching rule wins; otherwise `action` and `leases` apply.
#[serde(default)]
pub rules: Vec<Rule>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rule {
#[serde(rename = "match")]
pub matches: BTreeMap<String, String>,
pub action: Action,
#[serde(default, deserialize_with = "crate::config::optional_durations")]
pub leases: Option<Vec<u64>>,
}
/// What policy decided for one request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verdict {
pub action: Action,
pub leases: Vec<u64>,
}
/// 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<String, Value>, 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<String, String>, scope: &Map<String, Value>) -> 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<String, Value> {
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![] });
}
}
+244
View File
@@ -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<u8>),
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<String>,
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<Arg> },
/// 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<u8>),
Stderr(#[serde(with = "serde_bytes")] Vec<u8>),
/// The operation ran; `exit` is its status and `result` any structured output.
Finished {
exit: i32,
result: Option<OpResult>,
},
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<PendingSummary>, leases: Vec<LeaseSummary> },
}
#[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<PendingInfo>),
Recorded,
Log(Vec<Record>),
Error(String),
}
pub type Transport<S> = Framed<S, LengthDelimitedCodec>;
pub fn transport<S: AsyncRead + AsyncWrite>(stream: S) -> Transport<S> {
Framed::new(stream, LengthDelimitedCodec::builder().max_frame_length(MAX_MESSAGE).new_codec())
}
pub fn encode<T: Serialize>(message: &T) -> Result<Bytes> {
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<T: DeserializeOwned>(data: &[u8]) -> Result<T> {
ciborium::from_reader(data).context("invalid message")
}
pub async fn send<S, T>(transport: &mut S, message: &T) -> Result<()>
where
S: futures_util::Sink<Bytes, Error = std::io::Error> + Unpin,
T: Serialize,
{
transport.send(encode(message)?).await?;
Ok(())
}
/// The next message, or `None` at a clean end of stream.
pub async fn receive<S, T>(transport: &mut S) -> Result<Option<T>>
where
S: futures_util::Stream<Item = std::io::Result<bytes::BytesMut>> + 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::<Destination>(&data).is_err());
let data = encode(&Loose::Node("river".into())).unwrap();
assert!(decode::<Destination>(&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());
}
}
+381
View File
@@ -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<Decision> {
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<u64> {
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<String>,
/// Marks requests that reveal a secret or change who can read one.
pub sensitive: bool,
pub offers: Vec<Decision>,
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<String>,
pub sensitive: bool,
pub leases: Vec<u64>,
}
struct Entry {
request: NewRequest,
deadline: Instant,
reply: Option<oneshot::Sender<Outcome>>,
}
#[derive(Default)]
struct State {
sequence: u64,
pending: BTreeMap<String, Entry>,
leases: HashMap<(String, String), Instant>,
auto: HashMap<String, VecDeque<Instant>>,
}
pub struct Queue {
state: Mutex<State>,
timeout: Duration,
max_pending: usize,
changed: watch::Sender<u64>,
}
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<u64> {
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<oneshot::Receiver<Outcome>> {
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<PendingInfo> {
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<PendingInfo> {
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<Outcome>)> {
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());
}
}
+325
View File
@@ -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<Broker> {
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<Broker>, 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<u32>) -> Result<UnixListener> {
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<Broker>, 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<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Broker>, stream: S, requester: String) {
let (mut sink, mut source) = transport(stream).split();
let (tx, mut rx) = mpsc::channel::<ServerMessage>(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::<ClientMessage>(&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::<ClientMessage>(&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<ServerMessage> {
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<String>,
io: &mut Io,
) -> Result<Option<(ApprovedBy, Option<String>)>, 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(())
}
+130
View File
@@ -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<String> for $name {
type Error = String;
fn try_from(value: String) -> Result<Self, String> {
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, String> {
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<str> 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::<std::net::IpAddr>().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::<NodeName>().is_ok());
assert!("container-hass.x_1".parse::<NodeName>().is_ok());
assert!("-oProxyCommand=x".parse::<NodeName>().is_err());
assert!("".parse::<NodeName>().is_err());
assert!("root".parse::<UserName>().is_ok());
assert!("Root".parse::<UserName>().is_err());
assert!("-l".parse::<UserName>().is_err());
assert!("fergal.example.org".parse::<HostName>().is_ok());
assert!("2a0e:97c0:4d2:10::2".parse::<HostName>().is_ok());
assert!("-oProxyCommand=x".parse::<HostName>().is_err());
assert!("a b".parse::<HostName>().is_err());
}
#[test]
fn deserializing_validates() {
let ok: Result<NodeName, _> = serde_json::from_str("\"river\"");
assert!(ok.is_ok());
let bad: Result<NodeName, _> = serde_json::from_str("\"-x\"");
assert!(bad.is_err());
}
}
+294
View File
@@ -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<Broker> {
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<DuplexStream>,
}
impl Client {
async fn start(broker: &Arc<Broker>, operation: Operation) -> Client {
Client::start_with(broker, Request { version: PROTOCOL_VERSION, label: Some("test".into()), operation }).await
}
async fn start_with(broker: &Arc<Broker>, 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::<ServerMessage>(&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::<Arg>().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<String> = 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::<i32>().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:?}"),
}
}