docs: Restructure the design and architecture docs

- The architecture gets diagrams of the boxes, the broker's parts and
  the builder, and a deploy's sequence. The request lifecycle has the
  steps every request takes, then each kind on its own, and the
  protocol is shown as its types and fields.
- The design starts with what happens to each kind of request.
- Long bullets and steps become short nested bullets and tables.
- Each fact has one home: the design keeps behaviour and rationale,
  and the architecture the code. The tests move to the architecture.
- `AGENTS.md`'s writing rules say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-24 23:38:08 +00:00
1 parent 6933750dc5
commit d012b83b30
3 files changed
+766 -281

No files matched your search

+10 -6
View File
@@ -94,11 +94,15 @@ otherwise `git add -N`) before `nix build` can use it.
attribute names) in backticks.
- Keep docs plain — avoid vague filler. Use "layout"/"structure" rather than "shape", and name things
directly instead of reaching for umbrella words.
- Use tables for lists of structured items, with the item's name as the link. Break up long prose:
a bullet running past about four lines over several distinct facts becomes a `###` subheading
with a lead sentence and nested bullets.
- Use tables for lists of structured items, with the item's name as the link.
- Break up long prose. A bullet or numbered step running past about three lines over several facts
becomes a short lead (a bold phrase or one sentence) with nested bullets, a fact each; several
such points on one topic become a `###` subheading. A paragraph listing several facts becomes
bullets or a table. Restructure a long bullet you're adding to rather than lengthening it.
- Prefer durable concepts and named configuration identifiers over exact numbers that are tunable
and likely to drift; describe those by purpose and point at their source.
- Each fact has one home. Update the doc that owns a topic when the code changes it: the design and
its rationale in `docs/design.md`, the code's structure in `docs/architecture.md`, the agents'
guide in `slop-tools.md` (update it with each new operation).
- Each fact has one home. Update the doc that owns a topic when the code changes it:
- `docs/design.md`: what the broker does and why, for deployers and reviewers;
- `docs/architecture.md`: where the code does it, for contributors. It links to the design for
behaviour rather than restating it;
- `slop-tools.md`: the agents' guide (update it with each new operation).
+507 -93
View File
@@ -3,6 +3,122 @@
How the code is put together, and how to extend it. The design and its rationale are in
[`design.md`](design.md).
## Overview
### Boxes
```mermaid
flowchart TB
subgraph vm["Agents' VM"]
slop["slop"]
end
others["slop on other boxes"]
subgraph box["Broker's box"]
broker["slop-broker serve"]
approve["slop-approve"]
end
subgraph builderbox["Builder's box (can be the broker's box)"]
builder["slop-broker builder<br>(its own user; only a read-only Git key)"]
end
browser["Web app in a browser"]
slop -- "vsock" --> broker
others -- "SSH, forced command" --> broker
approve -- "approve.sock, or SSH" --> broker
browser -- "HTTPS through a reverse proxy;<br>OIDC sign-in" --> broker
broker -- "Web Push" --> browser
broker -- "SSH, forced command" --> builder
builder -- "read-only key" --> git[("Git server")]
broker -- "SSH, deploy key" --> nodes["Boxes<br>(deploy-rs nodes)"]
broker -- "ssh-ng, cache key" --> cache[("Binary cache")]
```
- **`slop-broker serve`** holds every credential and runs every privileged step. Requesters reach it
over vsock, a Unix socket or SSH; approvers over `approve.sock`, SSH or the web app.
- **The builder** is a separate user with only a read-only Git key, on any box the broker can reach
over SSH; usually the broker's own, reached over SSH to localhost.
- It fetches commits itself, and evaluates and builds them (agent-written Nix).
- It reads the main branch for the deploy-rs nodes and for secrets.
- **Boxes and the cache** are reached over SSH with the broker's own keys, using options the broker
fixes.
### Inside the broker
The parts of `slop-broker serve`, and the module each is in. The builder is a separate process the
broker only talks to through `builder.rs`, over SSH; see [Inside the builder](#inside-the-builder).
```mermaid
flowchart TB
requesters["Requesters"] --> listeners
approvers["slop-approve"] --> approve
browser["Browsers"] --> web
subgraph serve["slop-broker serve"]
listeners["Listeners<br>server.rs, remote.rs"] --> handler["Request handler<br>server.rs"]
handler -- "names a node" --> targets["Targets<br>targets.rs"]
handler -- "plan, prepare, execute" --> ops["Operations<br>ops/"]
handler -- "authorize" --> policy["Policy<br>policy.rs"]
handler -- "ask" --> queue["Pending requests, leases, limits<br>queue.rs"]
approve["Approver connections<br>approve.rs"] -- "decide" --> queue
web["Web app<br>web/"] -- "decide" --> queue
targets --> client["Builder client<br>builder.rs"]
ops --> client
ops --> exec["Processes: ssh, nix copy<br>exec.rs, ops/ssh.rs"]
handler --> audit["Audit log<br>audit.rs"]
approve --> audit
end
client -- "SSH" --> builder["slop-broker builder"]
exec --> boxes["Boxes and the binary cache"]
web -. "Web Push" .-> browser
```
- **Listeners** turn a connection into a requester's name and hand it to the handler.
- **The handler** (`server::handle`) takes one request through the steps below, and is the only
part that sends the requester messages.
- **Operations** (`ops::plan`, `ops::prepare`, `ops::execute`) know what each kind of request means:
its scope, what approvers see, and how to carry it out.
- **The queue** holds what waits for an approver. Approvers answer through `approve::approve`,
whichever way they connect, and the handler waiting on that request carries on.
- **Targets** keep the main branch's deploy-rs nodes, from the builder.
### Inside the builder
`slop-broker builder` (`builder::worker`) is the forced command of the builder user's
`authorized_keys`, so every SSH connection from the broker runs it once: it reads one
`BuilderRequest` on stdin, answers on stdout, and exits. Its log goes to stderr, which the broker
passes on to the requester, if one is waiting. It holds nothing but a read-only Git key.
```mermaid
flowchart LR
broker["Broker<br>builder.rs"] -- "SSH: one request,<br>one answer" --> worker["slop-broker builder<br>builder::worker"]
subgraph home["Builder's home"]
mirror[("repository.git<br>(bare mirror)")]
caches[("deploy-nodes/, secret-rules/<br>per main-branch commit")]
end
worker -- "git fetch, log, diff, ls-tree" --> mirror
mirror -- "read-only key" --> git[("Git server")]
worker -- "nix eval, nix build" --> daemon["nix-daemon"]
worker --> caches
```
What each request runs, and whose code, decides whether it needs an approval first:
| Request | Runs | Whose code | Approval first |
|---|---|---|---|
| `Describe` | `git fetch` of every branch, then `log`, `diff --stat` and `diff` since the main branch | None: Git only | No |
| `Nodes` | `nix eval` of `deploy.nodes` on the main branch | The main branch's | No |
| `Secret` | `git ls-tree` of the main branch, and `nix eval` of its rules file | The main branch's | No |
| `Build` | `nix eval` of the targets' profiles, then `nix build` | The requester's commit | Yes: `builder` |
- The main branch is protected, so evaluating it runs reviewed Nix; a requester's commit only
runs in `Build`, after an approver has seen its diff.
- `Nodes` and `Secret` evaluate once per main-branch commit and keep the result in
`deploy-nodes/` and `secret-rules/`, only for the newest commit.
- Locks in the home directory keep one fetch (`fetch.lock`) and one build (`build.lock`) at a time;
a waiting request says so in its log.
- If the broker closes the connection (the requester went away), the builder stops.
## Layout
| File | Responsibility |
@@ -34,120 +150,406 @@ How the code is put together, and how to extend it. The design and its rationale
## Request lifecycle
1. 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 `Hello` its forced command sends. Anything
unknown is refused and logged.
2. `server::handle` reads one `ClientMessage::Request` (10-second limit), then starts a reader task
that forwards `Stdin` to a channel (closing it at `StdinEnd`) and cancels a `CancellationToken`
when the connection closes or misbehaves. A writer task sends every `ServerMessage` from an
`mpsc` channel, in order.
3. The protocol version is checked, and `targets::refresh` looks the main branch's nodes up again
if the operation names a node and they're stale or don't include it. `ops::plan` checks the already-typed `Operation` against config
(does the node exist?) and returns `Parsed`: 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), then `ops::describe` (the builder's Git-only stage), then `authorize` of the
`ops::builder_gate` request (op `builder`, empty scope, audited as `approved` with
`step: builder`), then `ops::prepare`: build, copy, compare, and fill in the detail
(`Event::Prepared`).
4. `authorize` evaluates policy for the requester and operation. `deny` refuses. `auto` takes a
rate-limit slot. `ask` uses a matching lease if there is one, otherwise submits to the queue,
sends `Pending`, and waits for a decision, the timeout or a disconnect.
5. The handler sends `Approved { by, stdin }`. The client starts forwarding stdin only then, and
only if `stdin` is set.
6. `ops::execute` runs the operation with `Io` (stdin channel, output sender, cancel token) and
returns an exit status and an optional `OpResult`.
7. The handler sends one terminal message (`Finished`, `Denied`, `Expired`, `Error`), or nothing if
the requester went away, then closes.
Every request takes the same steps, in `server::handle`. Secrets, deploys and builds add a
**prepare** step before approval, because approvers should see what a request really does; the
sections after this one describe each kind on its own.
### Every request
1. **Connect.** A listener names the requester:
- vsock by the peer's CID;
- the Unix request socket by the peer's UID;
- the remote socket by the `Hello` that `slop-broker remote` (the forced command) writes.
Anything unknown is refused and audited.
2. **Read.** `server::handle` reads one `ClientMessage::Request`, within 10 seconds, and starts two
tasks:
- a reader, which forwards `Stdin` to a channel, closes it at `StdinEnd`, and cancels the
request's `CancellationToken` when the connection closes or sends anything else;
- a writer, which sends every `ServerMessage` from an `mpsc` channel in order, and stops after a
terminal one.
3. **Plan.**
- The protocol version is checked.
- `Targets::refresh` runs if the operation names a node (see
[Queries and SSH](#queries-and-ssh)).
- `ops::plan` checks the already-typed `Operation` against config and returns `Parsed`: the
operation's name, its scope, what approvers see, limits and whether it reads stdin.
- An error is sent back and audited as `invalid`; otherwise the request is audited.
4. **Prepare**, for secrets, deploys and builds only (below).
5. **Authorize.** `authorize` evaluates the requester's policy for the operation:
- `deny` refuses;
- `auto` takes a rate-limit slot;
- `ask` uses a matching lease if there is one. Otherwise it submits the request to the queue,
sends `Pending`, and waits for a decision, the timeout or a disconnect.
6. **Run.**
- The handler sends `Approved { by, stdin }`; the client sends stdin only then, and only if
`stdin` is set.
- `ops::execute` runs the operation with `Io` (the stdin channel, the output sender and the
cancel token) and returns an exit status and an optional `OpResult`.
7. **Finish.** One terminal message (`Finished`, `Denied`, `Expired` or `Error`), or none if the
requester went away, then the connection closes.
### Queries and SSH
`status`, `logs`, `failed` and `ssh`: no prepare step, since the command is the whole story.
1. **Plan.**
- **Targets:** `Targets::refresh` asks the builder for the main branch's nodes
(`BuilderRequest::Nodes`) when they're more than a minute old, or when the request names one
it doesn't know and the last lookup is more than 10 seconds old. A failed lookup is logged and
the last nodes are kept.
- `ssh::check` refuses a node that isn't one of them.
- The scope is the destination: `{ target }`, or `{ host, port }` for `--host`. The command is
only in the detail, so a lease covers any command to the same destination.
2. **Run.**
- `ssh::command` builds the `ssh` command with the broker's fixed options (see
[Execution](#execution)). The queries build the remote command themselves from validated
fields; `ssh` quotes the requester's arguments.
- stdout, stderr and the exit status go back to the requester; `ssh` forwards stdin.
### Secrets
`secret keys|read|set|generate|rekey`.
1. **Plan.** `ops::secret::plan`:
- the scope is `{ action, path }`;
- `read` is marked sensitive, can never run as `auto` and is never leased.
2. **Prepare.**
- **Policy first:** a request policy would deny stops here, before anything is looked up.
- **Look up:** the builder reads the main branch (`BuilderRequest::Secret`): which paths hold
the requester's ciphertext (by its Git blob ID), and the rules file's recipients for the path.
- **Detail:** what the content really is, and how the recipients differ from the rules. A
mismatch marks the request sensitive. Audited as `prepared`.
3. **Run.** `ops::secret::execute` decrypts with the broker's age identity, then:
- `keys` returns the key names (`OpResult::SecretKeys`);
- `read` writes the plaintext to stdout;
- `set`, `generate` and `rekey` encrypt the new plaintext to the recipients, adding the
broker's own key, and return it (`OpResult::Secret`, with the public half of generated
keypairs).
### Deploys
```mermaid
sequenceDiagram
participant S as slop
participant B as Broker
participant G as Builder
participant A as Approver
participant N as Node
S->>B: Request { Deploy }
B->>G: Describe(commit), Git only
G-->>B: commits, diffstat, diff
B->>A: "builder" request: commits and diff
A-->>B: once / lease
B->>G: Build(targets)
G-->>S: build logs
G-->>B: built profiles
B->>N: copy closures, compare (read-only)
B->>A: "deploy" request: packages, units, files
A-->>B: once / lease
B-->>S: Approved
B->>N: activate as root (systemd-run)
B-->>S: output, then Finished { exit }
```
1. **Plan.** `ops::deploy::plan`:
- the targets' nodes are refreshed and checked as for SSH;
- the scope is `{ targets, mode, commit }`, and each target also gets a rule scope, so a rule
about one node applies to any deploy that includes it.
2. **Prepare.**
1. **Policy first**, as for secrets.
2. **Describe:** the builder fetches every branch and returns the commit's log, diffstat and
diff since the main branch (`BuilderRequest::Describe`). Only Git runs.
3. **Builder approval:** `ops::builder_gate` makes a separate request for operation `builder`
(its scope and rule fields are in [the design](design.md#deploys)), and `authorize` handles
it like any other. Audited as `approved` with `step: builder`.
4. **Build:** the builder evaluates and builds the targets' profiles
(`BuilderRequest::Build`); its log goes to the requester.
5. **Copy and compare**, on every node at once: `nix copy` the closures (substituting on the
node), then compare them with what the node runs, read-only (the `INSPECT` script).
6. **Detail:** the commits, then the package, unit and file changes per profile. Audited as
`prepared`.
3. **Run.** `ops::deploy::execute` activates every node at once, its profiles in order, as root
through `systemd-run`. Each line of output is prefixed with `[node.profile]`; the exit status is
the first failure's.
### Builds
`build`: like a deploy up to building, then the binary cache instead of nodes.
1. **Plan.** `ops::build::plan` needs a cache; the scope is `{ attrs, commit }`, with a rule scope
per attribute.
2. **Prepare.**
1. **Policy first**, **describe** and **builder approval**, as for deploys.
2. **Build:** the builder builds the attributes (`BuilderRequest::Build`).
3. **Detail:** the commits, and each output's path and closure size.
3. **Run.** `ops::build::execute` adds GC roots for the outputs in the cache, then pushes them over
`ssh-ng`, and prints their paths.
### `requests`
Built in: the requester's own pending requests and leases. Always allowed, and not audited.
### Audit events
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.
`finished`, `failed`, `disconnected`, plus `invalid` and `unknown` peers.
## Protocol
- Each message is a serde enum from `src/proto.rs`, encoded as CBOR (`ciborium`; byte strings via
`serde_bytes`) and framed by `LengthDelimitedCodec` (4-byte big-endian length, 1 MiB maximum).
- Requester → broker: `Request { version, label, operation }`, then `Stdin(bytes)` / `StdinEnd`.
- Broker → requester: `Pending`, `Approved { by, stdin }`, `Info`, `Stdout`, `Stderr`, then one of
`Finished { exit, result }`, `Denied`, `Expired` or `Error`.
Every connection carries CBOR messages (`ciborium`; byte strings via `serde_bytes`), each framed
with a 4-byte big-endian length (`LengthDelimitedCodec`, 1 MiB maximum). The types are in
`src/proto.rs`; values such as `NodeName` are from `src/types.rs` and validate when decoded.
### Requester and broker
A requester sends one `Request`, then stdin only after an `Approved` that asks for it. The broker
sends any number of progress messages and closes after a terminal one.
```rust
enum ClientMessage {
Request(Request),
Stdin(bytes),
StdinEnd,
}
struct Request {
version: u32, // PROTOCOL_VERSION; the broker refuses others
label: Option<String>, // agent-supplied, shown as such
operation: Operation,
}
enum Operation {
Ssh { destination: Destination, command: Vec<Arg> },
Query { destination: Destination, query: Query },
Deploy { targets: Vec<DeployTarget>, commit: CommitId, boot: bool },
Build { attrs: Vec<FlakeAttr>, commit: CommitId },
Secret(SecretOp),
Requests,
}
enum Destination {
Node(NodeName), // a target
Host { user: UserName, host: HostName, port: u16 }, // `--host`
}
enum Query {
Status { unit: Option<UnitName> },
Logs { unit: UnitName, lines: Lines, since: Option<Since> },
Failed,
}
enum SecretOp {
Keys { file: SecretFile },
Read { file: SecretFile },
Set { path: SecretPath, base: Option<bytes>, target: Target, recipients: Vec<Recipient> },
Generate { path: SecretPath, base: Option<bytes>, target: Target, kind: GenKind,
recipients: Vec<Recipient> },
Rekey { file: SecretFile, recipients: Vec<Recipient> },
}
struct SecretFile { path: SecretPath, ciphertext: bytes }
enum Target { Whole, Field(SecretKey) }
enum GenKind { Password, Hex, Base64, Wireguard, SshEd25519, Age }
enum ServerMessage {
Pending { id: String, summary: String },
Approved { by: ApprovedBy, stdin: bool }, // ApprovedBy: Policy, Lease or Approver
Info(String),
Stdout(bytes),
Stderr(bytes),
// terminal:
Finished { exit: i32, result: Option<OpResult> },
Denied(String),
Expired,
Error(String),
}
enum OpResult {
Requests { pending: Vec<PendingSummary>, leases: Vec<LeaseSummary> },
SecretKeys(Vec<String>),
Secret { ciphertext: bytes, public: Option<String> },
}
```
### Approvers
Any number of requests per connection, each answered by one response.
```rust
enum ApproveRequest {
List,
Decide { id: String, decision: Decision }, // Decision: Once, Lease(seconds) or Deny
Log { count: usize }, // at most 200 records
}
enum ApproveResponse {
Pending(Vec<PendingInfo>),
Recorded,
Log(Vec<audit::Record>),
Error(String),
}
struct PendingInfo {
id: String,
requester: String,
op: String,
summary: String,
detail: Detail, // src/detail.rs
label: Option<String>,
sensitive: bool,
passkey: bool, // only the web app can approve it
offers: Vec<Decision>,
expires_in: u64,
}
```
### The remote socket and the builder
```rust
// Written once by `slop-broker remote`, as one length-prefixed frame without the codec, so
// nothing after it is read ahead; either protocol above follows.
struct Hello { role: Role, name: String } // Role: Requester or Approver
// One request on the builder's stdin, one answer on its stdout; logs on stderr.
enum BuilderRequest {
Describe(CommitId), // -> Description { log, stat, diff, on_branch }
Build(BuildRequest), // -> BuildResult { profiles, outputs }
Secret(SecretRequest), // -> SecretContext { branch, commit, paths, recipients }
Nodes, // -> Nodes { commit, nodes: { name: Node } }
}
```
### Rules
- Every enum and struct has `deny_unknown_fields`, and value types validate in `TryFrom`, so a
request that decodes is well-formed. `plan` only checks it against config.
- Bump `PROTOCOL_VERSION` on 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 `BuildRequest` frame on stdin and answers with one `BuildResult` frame on
stdout; build logs go to stderr, which the broker forwards to the requester.
- Bump `PROTOCOL_VERSION` on any incompatible change: brokers and clients are deployed separately.
- `slop` exits with the operation's status for `Finished` and 125 for anything else. `--json`
prints an `OpResult` as JSON.
## Policy, leases and limits
- Config: named `policies.<name> = { max_pending, auto_per_minute, ops.<op> = { action, leases,
rules } }`, and `requesters.<name>.policy` picks one, so requesters can share a policy.
`Config::validate` (called by `Broker::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 replace `leases`.
- An operation's `Limits` override policy: `never_auto` turns `auto` into `ask`, and `never_lease`
removes 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`, …) and `deny`. A lease that wasn't
offered is refused.
- Limits: pending requests per requester and overall, and `auto` requests 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.
Policies are named, and each requester picks one, so requesters can share one. The module writes
them from `services.slop-broker.policies` into the broker's TOML, for example:
```toml
[requesters.agent]
vsock_cid = 3626
policy = "agents"
[policies.agents]
max_pending = 4
auto_per_minute = 60
[policies.agents.ops.status]
action = "auto"
[policies.agents.ops.ssh]
action = "ask"
leases = ["5m", "1h"]
[[policies.agents.ops.ssh.rules]]
match = { target = "router*" }
action = "ask"
confirm = "passkey"
```
`Config::validate` (called by `Broker::new`) refuses a requester whose policy is missing, and the
module asserts the same.
### Deciding
`policy::evaluate` answers a request from its operation's entry and its scope:
1. No entry for the operation: deny.
2. The first rule whose `match` globs (`*`, `?`) all fit the scope wins. It replaces `action`, and
`leases` and `confirm` where it sets them.
3. The operation's `Limits` apply on top, whatever the policy says:
- `never_auto` turns `auto` into `ask`;
- `never_lease` removes leases.
`secret read` sets both.
### Leases
- A lease is keyed by the requester, the operation name and the scope's canonical JSON
(serde_json maps are sorted).
- The command is in the detail, not the scope, so an SSH lease covers any command to the same
target.
- An answer with a lease the policy doesn't offer is refused.
### Limits
- Pending requests, per requester (`max_pending` in the policy) and overall.
- `auto` requests per minute, per requester (`auto_per_minute`).
- A shared policy shares the numbers, not the counters or leases.
- Counters, leases and pending requests are only in memory.
## 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).
Every process the broker starts goes through `src/exec.rs`:
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.
| Function | For | Input and output |
|---|---|---|
| `exec::run` | Operations the requester watches | stdin from the connection; stdout and stderr as frames |
| `exec::capture` | The broker's own steps | Captured, none of the requester's stdio |
| `exec::run_prefixed` | Several nodes sharing the output (deploy copies and activations) | No stdin; each line prefixed with its node |
- Each process runs in its own process group. On cancellation the group gets `SIGTERM`, then
`SIGKILL` after five seconds.
- A spawn that fails with `ETXTBSY` is retried. It happens when another thread forks while an
executable is still open for writing (seen in parallel tests).
SSH always uses the options `ssh::command` fixes, which
[the design lists](design.md#box-queries-and-ssh). Arguments from the requester are validated so
none can be read as an option, and `--` comes before the hostname.
## Approvers
- `approve.sock` is restricted to the `slop-broker-approve` group. 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 `sshApprovers` and recorded as `<name> (ssh)`.
- All of them call `approve::approve`, which records the decision and audits it; the approver's
| Approver | Connects through | Recorded as |
|---|---|---|
| `slop-approve` on the broker's box | `approve.sock`, for the `slop-broker-approve` group | The user name |
| `slop-approve` on another box | SSH, a key in `sshApprovers` | `<name> (ssh)` |
| The web app | OpenID Connect | `<name> (web)`, or `<name> (web, passkey)` |
- A requester's UID is refused on `approve.sock` even if it's in the group.
- All of them call `approve::approve`, which records the decision and audits it. The approver's
name travels with the outcome into the `approved` event.
## NixOS side
- `nix/modules/nixos/broker.nix` (`services.slop-broker`) turns options into the TOML config
(`pkgs.formats.toml`, nulls dropped). Credentials arrive through `LoadCredential` under fixed
names (`ssh-key`, `cache-key`, `oidc-secret`, `age-identity`), which `config::credential` resolves in
`$CREDENTIALS_DIRECTORY`.
- The service runs as `slop-broker` with 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_keys` entries for the `slop` user with a forced
`slop-broker remote <role> <name>`; the broker gets `slop`'s group to share the remote socket.
- The `programs.slop` home-manager module installs both clients and sets up `request` and
`approve` keys: `Host` entries `slop-request` / `slop-approve` and `~/.config/slop/config.toml`
pointing at them.
- Deploys: `services.slop-broker.deploy` (broker side) and `services.slop-broker-builder` (the
`slop-broker-build` user, 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) and `services.slop-broker-cache` on the cache's
box, whose forced command allows `nix-daemon --stdio` (exactly what `ssh-ng` sends) and
`root <path>…`. The broker adds roots before copying, in case the store collects garbage often.
- Targets: every deploy-rs node on the main branch, so adding a box needs a commit there rather
than a new broker config; SSH therefore needs `deploy`.
- What the modules leave to the deployment: persisting `/var/lib/slop-broker` and the builder's
home on an ephemeral root, the firewall in front of the web app's port, and the policies.
[nixfiles](https://git.nul.ie/dev/nixfiles) is the reference, and
[`nix/vm-test.nix`](../nix/vm-test.nix) a minimal example.
| Module | On | Sets up |
|---|---|---|
| [`services.slop-broker`](../nix/modules/nixos/broker.nix) | The broker's box | The service and its config, and the `slop` user for requesters and approvers over SSH |
| [`services.slop-broker-builder`](../nix/modules/nixos/builder.nix) | The builder's box, which the broker reaches over SSH (to localhost when they share one) | The `slop-broker-build` user, its read-only Git key and its forced command |
| [`services.slop-broker-cache`](../nix/modules/nixos/cache.nix) | The cache's box | A forced command for the store's owner, and a timer that expires roots ([design](design.md#binary-cache)) |
| [`programs.slop`](../nix/modules/home-manager/slop.nix) (home-manager) | Requesters' and approvers' boxes | Both clients, their keys and the config pointing at them ([design](design.md#other-requesters-and-approvers)) |
### The broker's module
- **Config:** options become the TOML config (`pkgs.formats.toml`, nulls dropped).
- **Parts:** each operation group has its own section, and some need others:
- `ssh` and `deploy` need each other: SSH targets are the deploy-rs nodes on the main branch,
which the builder reads, so adding a box needs a commit there rather than a new broker config.
- `cache` (builds) and `secrets` need `deploy`, whose builder builds and looks secrets up.
- `web` needs a URL, an issuer and a client secret.
- **Credentials** arrive through `LoadCredential` under fixed names (`ssh-key`, `cache-key`,
`oidc-secret`, `age-identity`), which `config::credential` resolves in `$CREDENTIALS_DIRECTORY`.
- **Sandbox:** the service runs as `slop-broker` with a strict systemd sandbox. An operation that
needs more (address families, writable paths, helper users) adds it in the module; rerun the VM
test afterwards.
- **Remote keys** become `authorized_keys` entries for `slop`, each with a forced
`slop-broker remote <role> <name>`. The broker gets `slop`'s group to share the remote socket.
### Left to the deployment
- Persisting `/var/lib/slop-broker`, and the builder's home, on an ephemeral root.
- The firewall in front of the web app's port.
- The policies.
[nixfiles](https://git.nul.ie/dev/nixfiles) is the reference, and
[`nix/vm-test.nix`](../nix/vm-test.nix) a minimal example.
## Adding an operation
@@ -200,7 +602,19 @@ Arguments from the requester are validated so none can be read as an option.
and moved with `jj absorb`; it leaves lines whose neighbours come from different changes, which go
into the later of the two.
## Known gaps
## Tests
- `nix/vm-test.nix` needs KVM; run `vm-test` in the devenv shell. It looks the nodes up through a
real builder, but doesn't cover deploys or the web app; the demo covers the web app by hand.
How to run them is in [`AGENTS.md`](../AGENTS.md#commands).
| Tests | Cover |
|---|---|
| Unit tests, in each module | Parsing and validation, policy, leases, details, the web app's pieces |
| [`tests/broker.rs`](../tests/broker.rs) | Requests end to end, against a fake `ssh` and fakes of what operations call |
| [`tests/builder.rs`](../tests/builder.rs) | The builder against a local Git repository |
| [`nix/vm-test.nix`](../nix/vm-test.nix) | The broker through `services.slop-broker`, with its real service hardening, over vsock loopback, against a local `sshd` and a real builder; run it after changing the module, the service or the transport |
| [The demo](demo.md) | Not a test, but the quickest way to try the web app, passkey approvals, secrets and deploys by hand |
Gaps:
- The VM test needs KVM.
- It doesn't cover deploys or the web app; the demo covers the web app by hand.
+249 -182
View File
@@ -17,73 +17,129 @@ designed but not built yet (see [Planned operations](#planned-operations)). How
together is in [`architecture.md`](architecture.md); the NixOS and home-manager modules are in
[`nix/modules`](../nix/modules).
## Requests at a glance
Every request names an operation, which the requester's policy answers with `deny`, `auto` or
`ask`. What happens before that answer depends on the kind of request, because approvers should
see what a request really does, and that sometimes needs a look at the repository first.
```mermaid
flowchart TD
request["Request from slop"] --> kind{"Kind"}
kind -- "query, ssh" --> approve
kind -- "secret" --> lookup["Builder reads the main branch:<br>what the file is, its recipients"] --> approve
kind -- "deploy, build" --> describe["Builder fetches the commit:<br>commits and diff (Git only)"]
describe --> gate{"Approve use of the builder"}
gate -- "approved" --> build["Builder builds; deploys also<br>copy to the nodes and compare"] --> approve
gate -- "denied" --> denied["Denied"]
approve{"Approve the request:<br>auto, a lease or a person"}
approve -- "approved" --> run["Broker runs it with its credentials"]
approve -- "denied or expired" --> denied
```
- **Box queries and SSH** (`status`, `logs`, `failed`, `ssh`)
- Before approval: nothing. Approvers see the command.
- Once approved: the broker runs it over SSH and streams the output.
- **Secrets** (`secret keys|set|generate|rekey|read`)
- Before approval: the builder reads the main branch, so approvers see which file the content
really is and whether the recipients match the rules.
- Once approved: the broker decrypts, changes and re-encrypts, and returns the new ciphertext.
- **Deploys** (`deploy`)
- Before approval: the builder fetches the commit, and approvers first allow it to build
(they see the commits and diff). It builds, and the broker copies the result to each node and
compares it with what's installed, so approvers see package, unit and file changes.
- Once approved: the broker activates on every node.
- **Builds** (`build`)
- Before approval: as for deploys, up to building. Approvers see each output's size.
- Once approved: the broker pushes the outputs to the binary cache.
- **`requests`**: the requester's own pending requests and leases; always allowed.
Pending requests go to every approver at once: the [web app](#approvals-web-app) (with Web Push)
and `slop-approve`. How the code does it is in
[`architecture.md`](architecture.md#request-lifecycle).
## Trust model
- Everything inside the agents' VM is agent-controlled, including root, and so is any other
requester. Anything a requester sends is untrusted: commands, file contents, commit IDs,
labels and its own descriptions of requests.
- The broker holds the credentials and runs every privileged step itself. A credential never
reaches a requester. The only exception is an explicit `slop secret read`.
- Each requester names a policy, and several requesters can share one. Leases and request
limits are still counted per requester.
- Each request has a **scope**, which is what an approval covers (for example: deploy `web` at
commit X). The broker builds both the scope and the text shown to the approver from validated
fields, never from text the agent wrote.
- Anything returned to a requester should be treated as published. It ends up in the agent's
context, so in the model provider's transcript and in the agent's session logs.
- The broker never evaluates agent-written Nix itself. A builder does, as a separate user that only
holds a read-only Git key. The broker's privileged half only copies, signs, encrypts or
activates the results.
- The broker's box should already be trusted with what the broker holds. With deploys, the deploy
key is root on every box it reaches, so also giving the broker access to secrets adds little.
- The repository's main branch is trusted: only people can push to it. Approvals show changes
relative to it, and secrets are checked against it, so requesters' Git credentials must not be
able to push to it (protect the branch).
| Part | Trusted with | Because |
|---|---|---|
| The agents' VM and other requesters | Nothing | Everything in them is agent-controlled, including root |
| The broker | Every credential; it runs each privileged step itself | It's outside the agents' reach |
| The builder | A read-only Git key | It evaluates agent-written Nix |
| The broker's box | Everything the broker holds | It should be trusted with that already |
| The repository's main branch | What approvals compare against | Only people can push to it |
- **Requests are untrusted.** That includes commands, file contents, commit IDs, labels and a
requester's own descriptions of its requests.
- **Credentials stay with the broker.** None reaches a requester; the one exception is an explicit
`slop secret read`.
- **Scopes.** Each request has a scope, which is what an approval covers (for example: deploy
`web` at commit X). The broker builds both the scope and the text shown to approvers from
validated fields, never from text the agent wrote.
- **Results are published.** Anything returned to a requester ends up in the agent's context, so
in the model provider's transcript and in the agent's session logs.
- **No agent Nix in the broker.** A builder evaluates it, as a separate user. The broker's
privileged half only copies, signs, encrypts or activates the results.
- **Secrets add little.** With deploys, the deploy key is root on every box it reaches, so also
giving the broker access to secrets doesn't widen what its box must be trusted with.
- **Protect the main branch.** Approvals show changes relative to it, and secrets are checked
against it, so requesters' Git credentials must not be able to push to it.
- **Policies are per requester.** Each requester names a policy, and several can share one; leases
and request limits are still counted per requester.
## Transport
- The agents' VM gets a `vhost-vsock` device with a fixed CID. The broker listens on `AF_VSOCK` on
its box, and the kernel-reported peer CID identifies the requester. Nothing the guest sends can
change its CID.
- Messages are typed Rust enums shared by `slop` and the broker, encoded as CBOR and framed with
a length prefix (`tokio-util`'s `LengthDelimitedCodec`). Decoding validates every value (node and
unit names, ports and so on) and rejects unknown fields. The request carries a protocol version,
so a mismatched `slop` gets a clear error.
- One connection carries the request, then the operation's stdin (only after approval, and only
for operations that read it), its stdout and stderr, and a final message with the exit status
and any structured result. If the connection closes, the broker cancels the request or kills the
process it started.
- The VM never connects to the broker over the network, so the VM's network can stay isolated
from the broker's box.
- Local users on the broker's box can be requesters too, identified by UID on a Unix socket.
- **vsock for the agents' VM.** The VM gets a `vhost-vsock` device with a fixed CID, and the broker
listens on `AF_VSOCK` on its box.
- The kernel-reported peer CID identifies the requester; nothing the guest sends can change it.
- The VM never connects to the broker over the network, so its network can stay isolated from
the broker's box.
- **Unix sockets** for local users on the broker's box, identified by UID.
- **Messages** are typed Rust enums shared by `slop` and the broker (the encoding is in
[`architecture.md`](architecture.md#protocol)).
- Decoding validates every value (node and unit names, ports and so on) and rejects unknown
fields.
- The request carries a protocol version, so a mismatched `slop` gets a clear error.
- **One connection per request**, carrying in order:
1. the request;
2. the operation's stdin, only after approval and only for operations that read it;
3. its stdout and stderr;
4. a final message with the exit status and any structured result.
If the connection closes, the broker cancels the request or kills the process it started.
### Other requesters and approvers
Requesters and approvers on other boxes connect with SSH instead of vsock. That reuses `sshd` for
Requesters and approvers on other boxes connect with SSH instead, which reuses `sshd` for
authentication and stream handling.
- They log in as `slop` on the broker's box. Each key has a forced command,
`slop-broker remote <requester|approver> <name>`, set from
`services.slop-broker.requesters.<name>.sshKeys` or `services.slop-broker.sshApprovers.<name>`.
It connects to the broker's remote socket, which only `slop` can use, and tells the broker whose
key it is. The broker trusts that the same way it trusts a CID.
- A key does one job. The module refuses the same key as both requester and approver, and the
client says which job it wants (`ssh … request` or `ssh … approve`), so a key used with the
wrong client fails with a clear error.
- A requester key only allows making requests, so it's fine for the agents on that box to be able
to read it. An approver key must be out of their reach.
- Each requester names a policy. The agents' VM is identified by its CID, the others by their
key. For example, workstations might share a policy that only allows `dns`, the box queries
and `requests`.
- `slop` connects to `$SLOP_BROKER`, else `broker` in `~/.config/slop/config.toml`, else vsock;
`slop-approve` likewise uses `$SLOP_APPROVE`, else `approve`, else `approve.sock` on the box.
- **Forced commands.** They log in as `slop` on the broker's box, and each key's forced command is
`slop-broker remote <requester|approver> <name>`.
- Keys come from `services.slop-broker.requesters.<name>.sshKeys` and
`services.slop-broker.sshApprovers.<name>`.
- The command connects to the broker's remote socket, which only `slop` can use, and tells the
broker whose key it is. The broker trusts that the same way it trusts a CID.
- **One job per key.** The module refuses the same key as both requester and approver, and the
client says which job it wants (`ssh … request` or `ssh … approve`), so a key used with the wrong
client fails with a clear error.
- A requester key only allows making requests, so the agents on that box may read it.
- An approver key must be out of their reach.
- **Policies.** The agents' VM is identified by its CID, the others by their key, and each names a
policy. For example, workstations might share one that only allows `dns`, the box queries and
`requests`.
- **Finding the broker.** The first that is set wins:
| Client | Variable | `~/.config/slop/config.toml` | Default |
|---|---|---|---|
| `slop` | `$SLOP_BROKER` | `broker` | vsock |
| `slop-approve` | `$SLOP_APPROVE` | `approve` | `approve.sock` on the box |
An `ssh:<destination>` address goes to `ssh` as is, so a `Host` entry with `IdentitiesOnly` can
pick the right key when a box has both kinds. `SLOP_SSH` replaces the `ssh` command, like
`GIT_SSH_COMMAND`.
- The `programs.slop` home-manager module sets this up: `programs.slop.request` and
`programs.slop.approve` each take a key file, and get the `slop-request` and `slop-approve`
`Host` entries and the config file pointing at them. A config file rather than session
variables, because shells started before a switch don't see new variables.
- **home-manager.** `programs.slop.request` and `programs.slop.approve` each take a key file, and
get the `slop-request` and `slop-approve` `Host` entries and the config file pointing at them. It
writes a config file rather than session variables, because shells started before a switch don't
see new variables.
## The `slop` CLI
@@ -106,22 +162,25 @@ automatically where it can. Approvals show it marked as agent-supplied.
## Approvals and policy
- Each operation has a policy, configured in Nix: `auto`, `ask` or `deny`, plus the lease lengths
it allows (`"5m"`, `"1h"`). The module writes the broker's configuration as TOML. Narrower rules
override wider ones, for example per node, per DNS name or per secret path.
- Policies are named in `services.slop-broker.policies`, and each requester picks one with
`policy`, so several requesters, for example agents on different boxes, can share the same rules.
- An `ask` request waits for an answer (`services.slop-broker.timeout`) from the
[approvals web app](#approvals-web-app), `slop-approve` (on the broker's box, or over SSH from
another box). The answers are **once**, a **lease**
(the same scope is approved for a while, and only lengths the policy allows are offered) or
**deny**.
- An operation or rule can also set `confirm = "passkey"`: approving such a request needs a fresh
passkey in the web app, so `slop-approve` can only deny it. Deploys to routers
are a typical use.
- `auto` operations are rate-limited per requester, so a looping agent can't hammer boxes or APIs.
- Pending requests are capped per requester and overall to limit notification spam. If the broker
restarts, pending requests and leases are dropped.
- **Actions.** Each operation has a policy, configured in Nix: `auto`, `ask` or `deny`, plus the
lease lengths it allows (`"5m"`, `"1h"`). The module writes the broker's configuration as TOML.
- **Rules** override the operation's policy for narrower scopes, for example per node, per DNS
name or per secret path.
- **Named policies.** Policies are named in `services.slop-broker.policies`, and each requester
picks one with `policy`, so several requesters (agents on different boxes, say) can share rules.
- **Answers.** An `ask` request waits for an answer from the [web app](#approvals-web-app) or
`slop-approve` (on the broker's box, or over SSH from another), up to
`services.slop-broker.timeout`. The answers are:
- **once**;
- a **lease**: the same scope is approved for a while, and only lengths the policy allows are
offered;
- **deny**.
- **Passkeys.** An operation or rule can set `confirm = "passkey"`. Approving such a request then
needs a fresh passkey in the web app, so `slop-approve` can only deny it. Deploys to routers are a
typical use.
- **Limits.** `auto` operations are rate-limited per requester, so a looping agent can't hammer
boxes or APIs. Pending requests are capped per requester and overall to limit notification spam.
- **Restarts** drop pending requests and leases.
### Approvals web app
@@ -130,17 +189,19 @@ app (`services.slop-broker.web`, code in [`src/web`](../src/web)) that makes app
on a desktop shows what `slop-approve` can only print.
- **The page is the source of truth.** It lists what's pending with full detail and the active
leases, and updates itself, so a dismissed or missed notification costs nothing; a notification
only points at its request. Requests that need a passkey are marked, with a padlock on their
approve buttons.
leases, and updates itself.
- A dismissed or missed notification costs nothing; a notification only points at its request.
- Requests that need a passkey are marked, with a padlock on their approve buttons.
- **Audit log.** The log page groups the audit file by request: who asked, what, the outcome and
who approved it, with filters by requester, operation and outcome and a search. Each request's
page shows its full timeline, including the detail approvers saw, so a notification for a
request that's since been answered still leads somewhere useful.
- **Front end.** Server-rendered HTML that works without JavaScript; a small script refreshes the
list and manages notifications, and a service worker shows them. Everything shown passes through
the same filter as `slop-approve` for control and bidirectional characters, and a strict content
security policy allows only the app's own scripts.
who approved it.
- Filters by requester, operation and outcome, and a search.
- Each request's page shows its full timeline, including the detail approvers saw, so a
notification for a request that's since been answered still leads somewhere useful.
- **Front end.** Server-rendered HTML that works without JavaScript.
- A small script refreshes the list and manages notifications, and a service worker shows them.
- Everything shown passes through the same filter as `slop-approve` for control and
bidirectional characters.
- A strict content security policy allows only the app's own scripts.
#### Sign-in
@@ -150,23 +211,27 @@ Connect provider. [Pocket ID](https://pocket-id.org), which only uses passkeys,
tested with, and the [demo](demo.md) runs it.
- **Signing in.** The broker is an OIDC client (`web.clientId`, the `openidconnect` crate, with
PKCE), checking the ID token itself rather than trusting a header from the proxy. Only members of
`web.group` may sign in: the provider should restrict the client to that group, and the broker
checks the token's `groups` claim too. Every sign-in asks the provider to authenticate afresh
(`max_age=0`) and checks the token's `auth_time`, so signing out of the app means the next
sign-in needs the passkey, even while the provider's own session lasts.
PKCE), and checks the ID token itself rather than trusting a header from the proxy.
- Only members of `web.group` may sign in. The provider should restrict the client to that
group, and the broker checks the token's `groups` claim too.
- Every sign-in asks the provider to authenticate afresh (`max_age=0`) and checks the token's
`auth_time`. Signing out of the app therefore means the next sign-in needs the passkey, even
while the provider's own session lasts.
- **Sessions.** A sign-in gives a session cookie (`tower-sessions`) that lasts seven days without
use. Sessions are kept in an SQLite database in the broker's state directory, so a restart
doesn't sign phones out.
Answers are POSTs that need the browser's `Origin` to be the app and the session's token. The
audit log names web approvers like `alice (web)`.
- **Per-request passkeys, optional.** Approving a request whose policy says
`confirm = "passkey"` sends the approver back to the provider with `max_age=0`, which makes it ask
for the passkey again. The sign-in remembers the request, the answer and a hash of what was
shown; the broker accepts it only if the ID token is the same account's and its `auth_time` is no
older than the challenge, and the request hasn't changed. Pocket ID was tested to prompt and
return a fresh `auth_time` for both `max_age=0` and `prompt=login`; a provider that doesn't
can't confirm these requests. The audit log names these approvers like `alice (web, passkey)`.
use.
- Sessions are kept in an SQLite database in the broker's state directory, so a restart doesn't
sign phones out.
- Answers are POSTs that need the browser's `Origin` to be the app and the session's token.
- The audit log names web approvers like `alice (web)`.
- **Per-request passkeys, optional.** Approving a request whose policy says `confirm = "passkey"`
sends the approver back to the provider with `max_age=0`, which makes it ask for the passkey
again.
- The sign-in remembers the request, the answer and a hash of what was shown.
- The broker accepts it only if the ID token is the same account's, its `auth_time` is no older
than the challenge, and the request hasn't changed.
- Pocket ID was tested to prompt and return a fresh `auth_time` for both `max_age=0` and
`prompt=login`. A provider that doesn't can't confirm these requests.
- The audit log names these approvers like `alice (web, passkey)`.
- **What a session trusts.** Anything that can use the approver's session can answer requests that
don't need a fresh passkey, including agents running as that user on a workstation. That's
accepted when agents mostly run in the agents' VM; per-request passkeys cover operations where it
@@ -244,13 +309,14 @@ ciphertext they were sent, never values.
- The broker looks them up again when they're stale, or when a request names a node it doesn't
know.
- `--host` covers boxes outside them (OpenWrt, switches) with an explicit `user@host` and port.
- SSH runs with options fixed by the broker: `-F none`, the key with `IdentitiesOnly`, no agent,
`BatchMode`, no forwarding or local commands, and the broker's own `known_hosts`.
- `ssh` joins its arguments into a string that the remote shell runs. Because of that, a
free-form command's text can't be judged as read-only, so `slop ssh` should always be `ask`.
- The fixed queries (`status`, `logs`, `failed`) validate their arguments (unit names, `--since`,
line counts), and the broker builds the quoted remote command. That makes them safe to run as
`auto`, which covers most of what agents need SSH for without prompting.
- **Fixed options.** SSH runs with `-F none`, the key with `IdentitiesOnly`, no agent,
`BatchMode`, no forwarding or local commands, and the broker's own `known_hosts` (new hosts are
accepted, changed ones refused).
- **`slop ssh` always asks.** `ssh` joins its arguments into a string that the remote shell runs,
so a free-form command's text can't be judged as read-only.
- **The queries can be `auto`.** `status`, `logs` and `failed` validate their arguments (unit
names, `--since`, line counts), and the broker builds the quoted remote command. They cover most
of what agents need SSH for without prompting.
### Deploys
@@ -259,32 +325,39 @@ ciphertext they were sent, never values.
its profiles, like `deploy .#node`) or `node.profile` (such as `host.container-web`). The client
resolves `--commit` (default `HEAD`) to a full ID in its checkout.
1. **Describe, then approve use of the builder.** The broker runs the builder over SSH. The
builder is a user without keys, `slop-broker-build`, whose key's forced command is
`slop-broker builder` ([`services.slop-broker-builder`](../nix/modules/nixos/builder.nix)).
It fetches every branch from the Git server with a read-only key, so the agent never supplies
the source, and refuses commits that aren't on a branch. This first stage runs only Git: it
returns the commits since the main branch, their diffstat and their diff. Evaluation runs
agent-written Nix, so it waits for a separate `builder` request to be approved, which shows
those. Its scope is empty, so a lease lets the agent build any commit for a while; rules see
the `commit`, `on_branch` (whether it's already on the main branch) and `for` (`deploy` or
`build`).
2. **Build.** The builder evaluates the targets' deploy-rs profiles and builds them with the box's
Nix daemon. Only `git` gets the repository key, never the evaluator. Build logs stream to the
agent. One build runs at a time.
3. **Compare, before approval.** The broker copies the closures to each node, as deploy-rs does
(nodes substitute what the caches have; progress streams to the agent), and runs a fixed
read-only script on the node that compares each profile with the one installed. Nothing runs as
root, and no agent-written code runs.
4. **Approve.** One approval covers every target, the commit and the mode. Policy rules see one
scope per target (`node`, `profile`, `mode`, `commit`), and the strictest answer applies, so
for example a rule can allow routers only `boot`.
5. **Activate, once approved.** On every node at once, the broker runs deploy-rs's `activate-rs`
on each profile in deploy-rs's order, as root through the target's `sudo` command (`sudo -u` by
default), inside a transient unit (`systemd-run`). The activation therefore finishes even if the
connection drops, including when the broker deploys its own box and restarts. Output comes back
prefixed with the node. Deploys run in parallel; an agent that needs an order sends separate
requests.
The builder is a user without keys, `slop-broker-build`, whose key's forced command is
`slop-broker builder` ([`services.slop-broker-builder`](../nix/modules/nixos/builder.nix)). The
broker runs it over SSH.
1. **Describe.** The builder fetches every branch from the Git server with a read-only key, so the
agent never supplies the source.
- It refuses commits that aren't on a branch.
- This stage runs only Git: it returns the commits since the main branch, their diffstat and
their diff.
2. **Approve use of the builder.** Evaluation runs agent-written Nix, so it waits for a separate
`builder` request to be approved, which shows the commits and the diff.
- Its scope is empty, so a lease lets the agent build any commit for a while.
- Rules see the `commit`, `on_branch` (whether it's already on the main branch) and `for`
(`deploy` or `build`).
3. **Build.** The builder evaluates the targets' deploy-rs profiles and builds them with the box's
Nix daemon.
- Only `git` gets the repository key, never the evaluator.
- Build logs stream to the agent. One build runs at a time.
4. **Compare, before approval.** The broker copies the closures to each node, as deploy-rs does,
and compares each profile with the one installed.
- Nodes substitute what the caches have; progress streams to the agent.
- The comparison is a fixed read-only script. Nothing runs as root, and no agent-written code
runs.
5. **Approve the deploy.** One approval covers every target, the commit and the mode.
- Policy rules see one scope per target (`node`, `profile`, `mode`, `commit`), and the
strictest answer applies, so for example a rule can allow routers only `boot`.
6. **Activate.** On every node at once, the broker runs deploy-rs's `activate-rs` on each profile in
deploy-rs's order.
- It runs as root through the target's `sudo` command (`sudo -u` by default), inside a
transient unit (`systemd-run`), so the activation finishes even if the connection drops,
including when the broker deploys its own box and restarts.
- Output comes back prefixed with the node.
- Deploys run in parallel; an agent that needs an order sends separate requests.
There is no magic rollback, unlike deploy-rs from a workstation. `--boot` makes the new
configuration the boot default without switching to it. Activation, including `dry-activate`, runs
@@ -292,12 +365,14 @@ the new system's own code as root, so none of it happens before approval.
#### Approval contents
Package versions come from `nix store diff-closures`. Configuration changes come from comparing
the two profiles' `etc` trees, whose entries are links into the store: changed, added and removed
systemd units (drop-ins count as their unit) and `/etc` files. That approximates what activation
will restart without running anything. A kernel or initrd change is called out because it needs a
reboot. The commit messages and diffstat are Git's, from the commits since the main branch. The
full view, in `slop-approve show <id>` or the web app, looks like this:
- **Packages:** version and size changes, from `nix store diff-closures`.
- **Configuration:** changed, added and removed systemd units (drop-ins count as their unit) and
`/etc` files, from comparing the two profiles' `etc` trees, whose entries are links into the
store. That approximates what activation will restart without running anything.
- **Reboots:** a kernel or initrd change is called out.
- **Commits:** Git's messages and diffstat, for the commits since the main branch.
The full view, in `slop-approve show <id>` or the web app, looks like this:
```text
deploy hub (switch) at 3f9c2e1a8b0c
@@ -325,20 +400,23 @@ large deploy. For those, approve from the web app or a terminal.
Anything in a cache's store is signed and trusted by every box that uses it. A path built inside
the agents' VM proves nothing, because the agent could upload a different output under the hash of
a real derivation. So the cache is filled only from builds done by the builder (`slop build`):
a real derivation. So the cache is filled only from builds done by the builder.
- `slop build <attr>… [--commit <rev>]` works like a deploy up to approval: once use of the
builder is approved, it builds the flake attributes, and the `build` request shows the commits
and each output with its closure size. The `builder` approval is where a person reviews the
source; a policy can then let `build` push without asking again.
- Once approved, the broker pushes the outputs with `nix copy --to ssh-ng://` as the store's owner
(`services.slop-broker.cache`). That key's forced command
([`services.slop-broker-cache`](../nix/modules/nixos/cache.nix)) allows only `nix-daemon --stdio`
on the cache's store and `root <path>…`, which adds GC roots under `gcroots/slop-broker`.
- The broker adds the roots before copying, so a garbage collection in that store can't take the
paths mid-copy. A daily timer removes roots `keepDays` after their path was last pushed
(`services.slop-broker-cache`), and the store's next collection takes the paths: agent builds are
for sharing for a while, not for keeping.
- **Requests.** `slop build <attr>… [--commit <rev>]` works like a deploy up to approval.
- Once use of the builder is approved, it builds the flake attributes.
- The `build` request shows the commits and each output with its closure size.
- The `builder` approval is where a person reviews the source; a policy can then let `build`
push without asking again.
- **Pushing.** Once approved, the broker pushes the outputs with `nix copy --to ssh-ng://` as the
store's owner (`services.slop-broker.cache`).
- That key's forced command ([`services.slop-broker-cache`](../nix/modules/nixos/cache.nix))
allows only `nix-daemon --stdio` on the cache's store, and `root <path>…`, which adds GC roots
under `gcroots/slop-broker`.
- The broker adds the roots before copying, so a garbage collection in that store can't take
the paths mid-copy.
- **Expiry.** A daily timer removes roots `keepDays` after their path was last pushed, and the
store's next collection takes the paths: agent builds are for sharing for a while, not for
keeping.
### Secrets
@@ -363,27 +441,31 @@ of strings (`.json.age`). Anything else is changed whole.
#### What approvers see
The path in a request is only the requester's name for the file, and the ciphertext and the
recipients come from the requester too. Before approval, the builder fetches the main branch,
which only people should be able to push to, and the approval shows what that branch says:
recipients come from the requester too. Before approval, the builder fetches the main branch, which
only people should be able to push to, and the approval shows what that branch says.
- **What the content is.** The builder looks the ciphertext's Git blob ID up on the branch. The
approval says the file is the named path as on the branch, the same as *another* path (flagged:
an agent could otherwise send a sensitive file's ciphertext under a harmless name, and have it
read or re-encrypted to a key of its own), or not on the branch at all (new, or changed on a
branch). A pushed commit wouldn't prove anything here, since any branch can copy a blob to any
path.
- **What the content is.** The builder looks the ciphertext's Git blob ID up on the branch, and the
approval says the file is one of:
| Found | Means |
|---|---|
| The named path | The file as on the branch |
| Another path (flagged) | An agent could be sending a sensitive file's ciphertext under a harmless name, to have it read or re-encrypted to a key of its own |
| Nowhere | A new file, or one changed on a branch |
A pushed commit wouldn't prove anything here, since any branch can copy a blob to any path.
- **Whether the recipients are right.** The builder evaluates the branch's own agenix rules file
(`secrets.rules`, cached per commit) for the path. The approval says whether the requested
recipients match it, with a table of the keys, each as in the rules, added or removed; or that
the path isn't in the rules.
Only the protected branch's Nix is evaluated, never a requester's commit, so this doesn't need
the builder approval. `secrets.names` labels well-known keys (such as people's); other keys are
shown abbreviated.
- The broker always adds its own key to the recipients, and says so, so it can change the file
later.
Requests that read a secret, change who can read one or name content as another file are marked
sensitive. The audit log records the approval's text, including the blob ID, never values.
(`secrets.rules`, cached per commit) for the path.
- The approval says whether the requested recipients match it, with a table of the keys, each as
in the rules, added or removed; or that the path isn't in the rules.
- Only the protected branch's Nix is evaluated, never a requester's commit, so this doesn't need
the builder approval.
- `secrets.names` labels well-known keys (such as people's); other keys are shown abbreviated.
- **The broker's own key.** The broker always adds it to the recipients, and says so, so it can
change the file later.
- **Sensitive requests.** Requests that read a secret, change who can read one or name content as
another file are marked sensitive.
- **Audit.** The audit log records the approval's text, including the blob ID, never values.
## Planned operations
@@ -463,18 +545,3 @@ Both wait until a concrete need comes up.
credential proxy for other APIs (forges, package registries). Agents keep using deploy keys of
their own for pushing. If more API operations are needed later, add them one at a time like
`dns`.
## Tests
- **Unit and integration tests** cover the protocol, policy, approvals, leases, SSH execution
against a fake `ssh`, the builder against a local Git repository, and the web app's pieces. They
run in the package build, or in the devenv shell with `cargo test` (`devenv test` adds clippy).
- **VM test** ([`vm-test.nix`](../nix/vm-test.nix)): a minimal system running the broker through
the `services.slop-broker` module, with its real service hardening, over vsock loopback, against
a local `sshd`. Run it after changing the module, the service or the transport (it needs KVM):
`vm-test` in the devenv shell, or `nix build -L .#checks.x86_64-linux.vm`.
- **CI** ([`ci.yaml`](../.gitea/workflows/ci.yaml)): every push runs `nix flake check`, which builds
the package with its tests, checks clippy and rustfmt (`nix/lints.nix`), and runs the VM test.
- **Demo** ([`demo.md`](demo.md)): not a test, but the quickest way to try the web app, passkey
approvals, secrets and deploys (with the builder and a protected main branch) by hand.
- New operations add tests against fakes of what they call (deploy-rs, the DNS provider's API).