The design and architecture docs come from nixfiles' `docs/slop-broker.md` and its working notes, rewritten to describe the broker rather than one deployment: roles such as the agents' VM and the broker's box replace box names, and the rollout plan and deployment's agent setup stay in nixfiles. `AGENTS.md` carries over the general rules from nixfiles plus this repository's commands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 KiB
Architecture
How the code is put together, and how to extend it. The design and its rationale are in
design.md.
Layout
| File | Responsibility |
|---|---|
src/proto.rs |
Messages (ClientMessage, ServerMessage, Operation, OpResult, approver messages), framing and encoding |
src/types.rs |
Validated value types (NodeName, UnitName, Since, Lines, …) used inside messages |
src/config.rs |
TOML config from the NixOS module (durations as "5m"); credential path, user and group lookups |
src/policy.rs |
auto / ask / deny evaluation, rules with globs, per-operation Limits |
src/queue.rs |
Pending approvals, decisions, leases, per-requester limits and rate limits |
src/server.rs |
Listeners (vsock, Unix), the per-connection handler, authorize |
src/exec.rs |
Running processes on the requester's framed stdio; cancellation |
src/ops/mod.rs |
plan (request → Parsed: scope, approval text), execute, quoting |
src/ops/ssh.rs, src/ops/query.rs, src/ops/deploy.rs, src/ops/build.rs |
Operations; deploy.rs also has the INSPECT comparison script and its parser |
src/builder.rs |
Both sides of the builder: the worker (forced command) and the broker's client |
src/approve.rs |
Approver connections (many requests each), slop-approve client, approve() used by every approver |
src/remote.rs |
SSH transport: the slop-broker remote forced command, the remote socket, connect for both clients, and address (environment, then ~/.config/slop/config.toml, then the default) |
src/ha.rs |
Home Assistant Companion notifications |
src/audit.rs |
Typed audit events: a text line to the journal, a JSON line to the file; tail for slop-approve log |
src/bin/slop-broker.rs |
Daemon (serve); slop-approve when run under that name |
src/bin/slop.rs |
Agent client; slop guide prints slop-tools.md |
tests/broker.rs |
Handler tests over an in-memory duplex stream with a fake ssh |
src/web/ |
The approvals web app: routes (mod.rs), OIDC sign-in and passkey confirmation (auth.rs), Web Push (push.rs), the audit log by request (history.rs), the pages (page.rs) and static assets |
templates/, askama.toml |
The web app's HTML, as askama templates compiled into the broker; askama.toml passes everything they show through ops::printable before escaping it |
nix/ |
The package, NixOS modules (modules/nixos), home-manager module (modules/home-manager), the VM test (vm-test.nix, checks.<system>.vm) and the demo's VMs (demo/, packages.<system>.demo and demo-box) |
devenv.nix |
The development environment, its scripts and the demo's host side (devenv up); nix develop gives a plainer shell from flake.nix without them |
Request lifecycle
- A listener accepts a connection and maps it to a requester name: vsock by peer CID, the Unix
request socket by peer UID, the remote socket by the
Helloits forced command sends. Anything unknown is refused and logged. server::handlereads oneClientMessage::Request(10-second limit), then starts a reader task that forwardsStdinto a channel (closing it atStdinEnd) and cancels aCancellationTokenwhen the connection closes or misbehaves. A writer task sends everyServerMessagefrom anmpscchannel, in order.- The protocol version is checked.
ops::planchecks the already-typedOperationagainst config (does the node exist?) and returnsParsed: the scope, what approvers are shown, limits, whether stdin is used, and the operation. For operations that build (ops::builds), a policy pre-check (deny stops here), thenops::describe(the builder's Git-only stage), thenauthorizeof theops::builder_gaterequest (opbuilder, empty scope, audited asapprovedwithstep: builder), thenops::prepare: build, copy, compare, and fill in the detail (Event::Prepared). authorizeevaluates policy for the requester and operation.denyrefuses.autotakes a rate-limit slot.askuses a matching lease if there is one, otherwise submits to the queue, sendsPending, and waits for a decision, the timeout or a disconnect.- The handler sends
Approved { by, stdin }. The client starts forwarding stdin only then, and only ifstdinis set. ops::executeruns the operation withIo(stdin channel, output sender, cancel token) and returns an exit status and an optionalOpResult.- The handler sends one terminal message (
Finished,Denied,Expired,Error), or nothing if the requester went away, then closes.
Every step is audited as an audit::Event carrying the request's ID (the same ID approvers see):
request, prepared, approved (with the approver's name), decision, denied, expired,
finished, failed, disconnected, plus invalid and unknown peers. Built-in operations (requests) aren't logged.
Protocol
- Each message is a serde enum from
src/proto.rs, encoded as CBOR (ciborium; byte strings viaserde_bytes) and framed byLengthDelimitedCodec(4-byte big-endian length, 1 MiB maximum). - Requester → broker:
Request { version, label, operation }, thenStdin(bytes)/StdinEnd. - Broker → requester:
Pending,Approved { by, stdin },Info,Stdout,Stderr, then one ofFinished { exit, result },Denied,ExpiredorError. - Every enum and struct has
deny_unknown_fields, and value types validate inTryFrom, so a request that decodes is well-formed.planonly checks it against config. - Bump
PROTOCOL_VERSIONon any incompatible change: brokers and clients are deployed separately. - Approver connections use the same framing with
ApproveRequest/ApproveResponse, any number per connection. - The remote socket starts with a
remote::Hello { role, name }, written as one length-prefixed frame without the codec so nothing after it is read ahead, then carries either protocol. - The builder gets one
BuildRequestframe on stdin and answers with oneBuildResultframe on stdout; build logs go to stderr, which the broker forwards to the requester. slopexits with the operation's status forFinishedand 125 for anything else.--jsonprints anOpResultas JSON.
Policy, leases and limits
- Config: named
policies.<name> = { max_pending, auto_per_minute, ops.<op> = { action, leases, rules } }, andrequesters.<name>.policypicks one, so requesters can share a policy.Config::validate(called byBroker::new) refuses a requester whose policy is missing, and the module asserts the same. A missing operation is denied. - Rules match scope fields with globs (
*,?); the first match wins and can replaceleases. - An operation's
Limitsoverride policy:never_autoturnsautointoask, andnever_leaseremoves leases (for example,secret read). - The lease key is the operation name plus the scope's canonical JSON (serde_json maps are sorted), per requester. The command is in the detail, not the scope, so a lease covers any command to the same target.
- Approvers are offered
once, each allowed lease (5m,1h, …) anddeny. A lease that wasn't offered is refused. - Limits: pending requests per requester and overall, and
autorequests per minute per requester. A shared policy shares the numbers, not the counters or leases. Everything is in memory; a restart drops pending requests and leases.
Execution
exec::run starts the process in its own process group, pumps stdout and stderr into frames, and
feeds stdin from the channel. On cancellation it sends SIGTERM to the group, then SIGKILL after
five seconds. It retries a spawn that fails with ETXTBSY, which happens when another thread forks
while an executable is still open for writing (seen in parallel tests). exec::capture runs a
process without the requester's stdio, for broker-internal steps. exec::run_prefixed runs one
without stdin and sends each output line with a prefix, so several nodes can share the output
(deploy copies and activations).
SSH always uses options fixed in ssh::command: -F none, the credential key, no agent,
BatchMode, no forwarding, its own known_hosts (accept-new), and -- before the hostname.
Arguments from the requester are validated so none can be read as an option.
Approvers
approve.sockis restricted to theslop-broker-approvegroup. A requester's UID is refused even if it is in the group. The approver is recorded by user name.- Over SSH, approvers are named in
sshApproversand recorded as<name> (ssh). - Home Assistant: an outbound WebSocket connection. Each pending request becomes a persistent,
sticky notification with random action IDs for Once, the shortest lease and Deny (Android shows
at most three). Replies must match a live action and the configured
device_id, which is the Companion app's own ID (the broker logs the ID of answers it ignores). It resyncs whenever the queue changes (Queue::subscribe) and every five seconds, and logs why a connection failed. - All of them call
approve::approve, which records the decision and audits it; the approver's name travels with the outcome into theapprovedevent.
NixOS side
nix/modules/nixos/broker.nix(services.slop-broker) turns options into the TOML config (pkgs.formats.toml, nulls dropped). Credentials arrive throughLoadCredentialunder fixed names (ssh-key,cache-key,ha-token,oidc-secret), whichconfig::credentialresolves in$CREDENTIALS_DIRECTORY.- The service runs as
slop-brokerwith a strict systemd sandbox. Each operation that needs more (address families, writable paths, helper users) adds it in the module, and the VM test should be rerun. - Remote keys become
authorized_keysentries for theslopuser with a forcedslop-broker remote <role> <name>; the broker getsslop's group to share the remote socket. - The
programs.slophome-manager module installs both clients and sets uprequestandapprovekeys:Hostentriesslop-request/slop-approveand~/.config/slop/config.tomlpointing at them. - Deploys:
services.slop-broker.deploy(broker side) andservices.slop-broker-builder(theslop-broker-builduser, its read-only Git key and forced command). The broker can reach the builder over SSH to localhost. - Builds:
services.slop-broker.cache(broker side) andservices.slop-broker-cacheon the cache's box, whose forced command allowsnix-daemon --stdio(exactly whatssh-ngsends) androot <path>…. The broker adds roots before copying, in case the store collects garbage often. - Home Assistant: the broker's user there must be an admin, because non-admins can't subscribe to notification actions.
- What the modules leave to the deployment: persisting
/var/lib/slop-brokerand the builder's home on an ephemeral root, the firewall in front of the web app's port, which boxes are SSH targets, and the policies. nixfiles is the reference, andnix/vm-test.nixa minimal example.
Adding an operation
- Add the
Operationvariant insrc/proto.rs, using validated types fromsrc/types.rs(add new ones there), and anOpResultvariant if it returns data. BumpPROTOCOL_VERSIONif old clients would misread anything. src/ops/<op>.rsand aplanarm insrc/ops/mod.rs: the config checks, a scope that is exactly what an approval should cover, and anexecutearm.- Put anything shown but not part of the approval (commands, diffs) in
detail. - Set
limitsandsensitivewhere the operation reveals or redistributes secrets.
- Put anything shown but not part of the approval (commands, diffs) in
- Add the client subcommand in
src/bin/slop.rs(clap parses validated types directly throughFromStr), and how to print itsOpResult. - Tests: parsing in the module, behaviour in
tests/broker.rswith fakes of what it calls. - Module options and sandbox changes; the deployment's policy entry follows in its own repo.
- Agent guide (
slop-tools.md) anddesign.md.
Conventions and gotchas
- Run
cargo fmt(rustfmt.toml: width 120) andcargo clippy --all-targetsin the devenv shell; keep both clean (devenv testruns clippy and the tests). - Report errors to requesters with
{error:#}so the cause chain is included. - Messages to requesters are read by agents. Make them say what to do instead (for example "use --host for other boxes").
- Remote login shells may be
fish. Commands the broker builds are oneshell_quoted string, which both POSIX shells andfishread the same way as long as the words contain no\\or\'. - Unix socket paths are limited to about 108 bytes, so deep scratch directories are too long for
manual tests; put sockets under
$XDG_RUNTIME_DIR. - The demo is the easiest manual test of the web app. Against a real OpenID Connect
provider instead, run the broker with a
[web]section andurl = "http://localhost:<port>"; the provider's client needs that callback URL too. Remove it again afterwards. - Claude Code's default Bash timeout is two minutes, shorter than the approval timeout; the agent
guide tells agents to use a longer timeout or run
slopin the background. - tokio's
Command::output()captures stdout and stderr whatever they're set to; to let a child's stderr through,spawn()andwait_with_output(). - ssh keeps the first value of an option.
nix copytossh://addsPermitLocalCommand=yesand waits forecho started, so the broker'sPermitLocalCommand=nowould hang it forever (seecopy_options). - A tokio program that reads stdin can't return from
mainwhile that read blocks; the builder worker callsstd::process::exitafter writing its result. - Session variables from home-manager only reach shells started after the next login
(
__HM_SESS_VARS_SOURCEDis inherited), which is whyprograms.slopwrites a config file instead. - Changes that touch several stack changes at once (such as spacing sweeps) can be made at the tip
and moved with
jj absorb; it leaves lines whose neighbours come from different changes, which go into the later of the two.
Known gaps
- Home Assistant notifications can be swiped away on Android 14 and later;
persistentno longer prevents it. The possible fix (re-post onmobile_app_notification_cleared, on a quiet channel) is described indesign.mdand left for now. nix/vm-test.nixneeds KVM; runvm-testin the devenv shell. It doesn't cover deploys, Home Assistant or the web app; the demo covers the web app by hand.