1 Commits
Author SHA1 Message Date
jackos1998 f2f52d5b4d ci: Run only on pushes to main 2026-11-25 01:01:41 +00:00
55 changed files with 756 additions and 3716 deletions

No files matched your search

+2 -3
View File
@@ -3,7 +3,6 @@ name: CI
on:
push:
branches: [main]
pull_request:
jobs:
check:
@@ -19,7 +18,7 @@ jobs:
extra-conf: |
sandbox-fallback = false
# Builds the package with its tests, runs clippy, rustfmt, shellcheck and the VM test
# (which needs KVM), and evaluates the other outputs
# Builds the package with its tests, clippy, rustfmt and the VM test (which needs KVM), and
# evaluates the other outputs
- name: Check the flake
run: nix flake check -L
+2 -9
View File
@@ -39,9 +39,8 @@ of devenv's scripts, `devenv test` or the demo's host side.
errors) and the tests.
- `cargo fmt` — the crate is formatted with `rustfmt` (`rustfmt.toml`); run it on code you change.
- `nix build` — the package, which also runs the tests.
- CI ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)) runs `nix flake check` for pull
requests and pushes to `main`:
the package with its tests, `clippy` (warnings as errors), `fmt` (`cargo fmt --check`),
- CI ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)) runs `nix flake check` on pushes to
`main`: the package with its tests, `clippy` (warnings as errors), `fmt` (`cargo fmt --check`),
`shellcheck` on `src/**/*.sh` and the VM test. Keep them passing. `nix flake check --no-build`
fails where the VM test's keys haven't been built, because the test reads them at evaluation.
- `vm-test` (or `nix build -L .#checks.x86_64-linux.vm`) — the NixOS VM test of the broker module
@@ -89,12 +88,6 @@ otherwise `git add -N`) before `nix build` can use it.
one commit even when it touches code, modules and docs; split only when a reader would ask why two
things arrived together.
## Work in progress
Plans, status, next steps and handoffs go in Gitea issues on `dev/slop-broker`, one per piece of
work with its description kept current, not in files in the repository or on branches. When the
work is done, move what lasts into `docs/` or this file and close the issue.
## Writing
- In prose and commit messages, quote code-like identifiers (commands, options, paths, crate and
Generated
+1 -1
View File
@@ -3859,7 +3859,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "slop-broker"
version = "0.3.0"
version = "0.1.0"
dependencies = [
"age",
"anyhow",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "slop-broker"
version = "0.3.0"
version = "0.1.0"
edition = "2024"
description = "Approval broker that runs privileged operations for coding agents"
license = "MIT"
-16
View File
@@ -45,22 +45,6 @@ The development environment is [devenv](https://devenv.sh): direnv with `.envrc`
and `cargo clippy --all-targets` work there, `devenv test` runs both, and `vm-test` runs the NixOS
VM test (needs KVM). See [`AGENTS.md`](AGENTS.md) for conventions.
## Releasing
Use SemVer for the CLI, request protocol and Nix module options. Bump the patch for
compatible fixes and the minor for compatible features. While the major is zero,
use a minor bump for breaking changes and document how to upgrade. After `1.0.0`,
bump the major for breaking changes.
1. In a release pull request of its own, once the changes for it have merged, set
`package.version` in `Cargo.toml` and run `cargo check` to refresh `Cargo.lock`. Feature and
fix pull requests leave the version alone. The Nix package reads the version from
`Cargo.toml`.
2. After the release commit lands on `main` and passes CI, tag it `v<version>` and
push the tag. Keep published tags fixed.
3. Update the `slop-broker` input in nixfiles to `ref=refs/tags/v<version>` and run
`nix flake update slop-broker` there to refresh its lock entry.
## License
MIT; see [`LICENSE`](LICENSE).
+334 -7
View File
@@ -1,20 +1,347 @@
# The development environment: `devenv shell`, or direnv with `.envrc`. The package, modules and
# checks are in `flake.nix`.
#
# `devenv up` runs the demo's host side, from `nix/demo/host.nix` (see `docs/demo.md`).
{ pkgs, ... }:
{
imports = [ ./nix/demo/host.nix ];
# `devenv up` runs the demo's host side (see `docs/demo.md`): the broker from this checkout, with
# its web app and builder, Pocket ID for approvers to sign in with, the box VM its SSH targets
# reach, and the Git repository the agent pushes to.
{ pkgs, lib, config, ... }:
let
demo = import ./nix/demo/settings.nix;
state = "${config.devenv.state}/slop-demo";
# Sockets, whose paths must be short
run = "${config.devenv.runtime}/slop-demo";
issuer = "http://localhost:${toString demo.ports.pocketId}";
# Bare repositories the agents' VM reaches with `git://`
repositories = "${state}/git";
appUrl = "http://localhost:${toString demo.ports.web}";
# The builder: `slop-broker builder`, which the broker reaches through `ssh` (see `ssh` below).
# The repository is a local path, so its key is never used.
builderConfig = (pkgs.formats.toml { }).generate "slop-demo-builder.toml" {
repository = "${repositories}/repo.git";
key = "/nonexistent";
branch = "master";
directory = "${state}/builder";
# The host's own Nix first, so builds go through its daemon as the user
path = [
"${pkgs.git}/bin"
"${pkgs.openssh}/bin"
"/run/current-system/sw/bin"
"/nix/var/nix/profiles/default/bin"
"${pkgs.nix}/bin"
];
};
# The broker's `ssh`: the host `builder` runs the builder from this checkout's build directly, as
# its forced command would; everything else is the real `ssh`.
ssh = pkgs.writeShellScript "slop-demo-ssh" ''
host="" previous=""
for arg; do
if [ "$previous" = -- ]; then host=$arg; break; fi
previous=$arg
done
if [ "$host" = builder ]; then
exec ${config.devenv.root}/target/debug/slop-broker builder --config ${builderConfig}
fi
exec ${pkgs.openssh}/bin/ssh "$@"
'';
# Only `demo-merge` moves `master`, standing in for branch protection and a person merging
preReceive = pkgs.writeShellScript "slop-demo-pre-receive" ''
while read -r old new ref; do
if [ "$ref" = refs/heads/master ]; then
echo "master is protected: push a branch, and merge it with \`demo-merge <branch>\` on the host" >&2
exit 1
fi
done
'';
# `@group@` becomes the user's primary group, whose members may approve, and `@dev@` the demo
# person's age public key
brokerConfig = (pkgs.formats.toml { }).generate "slop-demo.toml" {
requesters.agent = { vsock_cid = demo.agentCid; policy = "agent"; };
policies.agent.ops = {
query.action = "auto";
ssh = {
action = "ask";
leases = [ "5m" "1h" ];
rules = [
{ match.target = "router"; action = "ask"; confirm = "passkey"; }
{ match.target = "vault"; action = "deny"; }
];
};
# Agent-written Nix runs in the builder once its use is approved; `master` is reviewed
builder = {
action = "ask";
leases = [ "5m" "1h" ];
rules = [{ match.on_branch = "true"; action = "auto"; }];
};
deploy = {
action = "ask";
leases = [ "5m" ];
};
# Approvals show whether the file and its recipients match `master`; reading always asks
secret = {
action = "ask";
leases = [ "5m" ];
rules = [{ match.action = "keys"; action = "auto"; }];
};
};
vsock_port = 6262;
approve_socket = "${run}/approve.sock";
approver_group = "@group@";
audit_log = "${state}/audit.jsonl";
ssh = {
ssh = "${ssh}";
key = "${state}/broker-key";
known_hosts = "${state}/known_hosts";
};
deploy = {
builder = { hostname = "builder"; user = "builder"; };
nix = "${pkgs.nix}/bin/nix";
cache = "${state}/nix-cache";
};
secrets = {
identity = "${state}/broker-age.key";
names.dev = "@dev@";
};
web = {
listen = "127.0.0.1:${toString demo.ports.web}";
url = appUrl;
inherit issuer;
client_id = "slop-approve";
client_secret = "${state}/oidc-secret";
group = "slop-approvers";
state_dir = "${state}/web";
};
};
# Pocket ID's admin API, with the key `devenv up` made
pocketIdApi = ''
api() {
local method=$1 path=$2
shift 2
curl -sS --fail-with-body -X "$method" "${issuer}/api/$path" \
-H "X-API-Key: $(sed -n 's/^STATIC_API_KEY=//p' ${state}/pocket-id.env)" -H 'Content-Type: application/json' "$@"
}
'';
in
{
languages.rust.enable = true;
# `pkg-config` with OpenSSL for Web Push's payload encryption and SQLite for the web app's
# sessions, `git` for the builder's tests
packages = with pkgs; [ pkg-config openssl sqlite git nixpkgs-fmt curl jq rage ];
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" "$@"'';
# For `slop-approve` in this shell
env.SLOP_APPROVE = "unix:${run}/approve.sock";
scripts = {
slop-approve = {
description = "Answer the demo's requests (built from this checkout)";
exec = ''exec cargo run -q --manifest-path "$DEVENV_ROOT/Cargo.toml" --bin slop-broker -- approve "$@"'';
};
demo = {
description = "Boot the demo's agents' VM on this terminal; needs `devenv up` running";
exec = ''
if [ ! -S ${run}/approve.sock ]; then
echo "The broker isn't running: start \`devenv up\` first." >&2
exit 1
fi
# Git from the VM: connections to 10.0.2.100:9418, an address only the guest sees, each
# run a `git daemon` on the host serving the demo's repositories. Commas are doubled for
# QEMU.
daemon="${pkgs.git}/bin/git daemon --inetd --export-all --enable=receive-pack --base-path=${repositories}"
export QEMU_NET_OPTS="guestfwd=tcp:10.0.2.100:9418-cmd:''${daemon//,/,,}"
exec nix run "$DEVENV_ROOT#demo" -- "$@"
'';
};
demo-merge = {
description = "Fast-forward the demo repository's `master` to a branch, as a person merging";
exec = ''
set -eu
branch=''${1:?usage: demo-merge <branch>}
cd ${repositories}/repo.git
if ! git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null; then
echo "there's no branch $branch; the agent pushes one with \`git push origin <branch>\`" >&2
exit 1
fi
if ! git merge-base --is-ancestor master "refs/heads/$branch"; then
echo "$branch isn't master plus new commits; rebase it on master first" >&2
exit 1
fi
git update-ref refs/heads/master "refs/heads/$branch"
echo "master is now at $(git rev-parse --short master)"
'';
};
demo-box = {
description = "SSH into the demo's box VM as `box`, with the broker's key";
exec = ''
exec ${pkgs.openssh}/bin/ssh -F none -i ${state}/broker-key -o IdentitiesOnly=yes \
-o UserKnownHostsFile=${state}/known_hosts -o StrictHostKeyChecking=accept-new \
-p ${toString demo.ports.boxSsh} box@localhost "$@"
'';
};
demo-sign-in = {
description = "Print a one-time link that signs in to the demo's Pocket ID as the approver";
exec = ''
${pocketIdApi}
user=$(api GET 'users?search=demo' | jq -r '.data[] | select(.username == "demo") | .id')
echo "${issuer}/lc/$(api POST "users/$user/one-time-access-token" -d '{"ttl":"1h"}' | jq -r .token)"
'';
};
demo-reset = {
description = "Delete the demo's state (Pocket ID's users and passkeys, keys, repository, audit log)";
exec = ''rm -rf ${state}'';
};
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" "$@"'';
};
};
# The demo's host side; not for `devenv test`
tasks = lib.mkIf (!config.devenv.isTesting) {
"slop-demo:keys" = {
description = "Make the demo's secrets and SSH keys";
exec = ''
set -eu
umask 077
mkdir -p ${state}/box ${state}/pocket-id ${state}/web ${state}/builder ${run}
if [ ! -e ${state}/pocket-id.env ]; then
key() { ${pkgs.openssl}/bin/openssl rand -hex 32; }
printf 'ENCRYPTION_KEY=%s\nSTATIC_API_KEY=%s\n' "$(key)" "$(key)" > ${state}/pocket-id.env
fi
# The box VM gets the broker's public key and its own host key through its shared directory
[ -e ${state}/broker-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo -f ${state}/broker-key
cp ${state}/broker-key.pub ${state}/box/broker.pub
[ -e ${state}/box/host-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo-box -f ${state}/box/host-key
'';
};
# Once: the repository, with secrets encrypted to the demo person and the broker. The hook is
# installed every time, so it follows changes here.
"slop-demo:repo" = {
description = "Seed the demo's repository and age identities";
after = [ "slop-demo:keys" ];
exec = ''
set -eu
umask 077
export PATH=${lib.makeBinPath (with pkgs; [ coreutils gnused git rage openssl wireguard-tools jq ])}
if [ ! -d ${repositories}/repo.git ]; then
for name in dev broker; do
[ -e ${state}/$name-age.key ] || rage-keygen -o ${state}/$name-age.key 2>/dev/null
rage-keygen -y ${state}/$name-age.key > ${state}/$name-age.pub
done
dev=$(cat ${state}/dev-age.pub) broker=$(cat ${state}/broker-age.pub)
work=$(mktemp -d)
cp -r ${./nix/demo/repo}/. "$work"
chmod -R u+w "$work"
sed -i "s/@boxSsh@/${toString demo.ports.boxSsh}/" "$work/flake.nix"
mkdir "$work/secrets"
# nixpkgs as this repository locks it, so the builder already has it
jq '{nodes: {root: {inputs: {nixpkgs: "nixpkgs"}}, nixpkgs: .nodes[.nodes.root.inputs.nixpkgs]}, root: "root", version: 7}' \
${./flake.lock} > "$work/flake.lock"
cat > "$work/secrets.nix" <<EOF
# The agenix rules: who each secret is encrypted to.
let
dev = "$dev";
broker = "$broker";
in
{
"secrets/app.env.age".publicKeys = [ dev broker ];
"secrets/wg.key.age".publicKeys = [ dev broker ];
}
EOF
printf 'DB_USER=app\nDB_PASSWORD=%s\n' "$(openssl rand -hex 12)" |
rage -a -r "$dev" -r "$broker" -o "$work/secrets/app.env.age"
wg genkey | rage -a -r "$dev" -r "$broker" -o "$work/secrets/wg.key.age"
export GIT_AUTHOR_NAME=Dev GIT_AUTHOR_EMAIL=dev@example.org
export GIT_COMMITTER_NAME=Dev GIT_COMMITTER_EMAIL=dev@example.org
git -C "$work" init -q --initial-branch=master
git -C "$work" add .
git -C "$work" commit -q -m "Start the demo repository"
mkdir -p ${repositories}
git init -q --bare --initial-branch=master ${repositories}/repo.git
git -C "$work" push -q ${repositories}/repo.git master
rm -rf "$work"
fi
ln -sf ${preReceive} ${repositories}/repo.git/hooks/pre-receive
'';
};
# Once: the approver `demo` in the group `slop-approvers`, and the broker's OIDC client
"slop-demo:pocket-id" = {
description = "Set up the demo's approver and OIDC client in Pocket ID";
after = [ "devenv:processes:pocket-id" ];
status = "test -s ${state}/oidc-secret";
exec = ''
set -eu
umask 077
${pocketIdApi}
user=$(api POST users -d '{"username":"demo","email":"demo@example.org","firstName":"Demo","lastName":"Approver","displayName":"Demo Approver","isAdmin":false}' | jq -r .id)
group=$(api POST user-groups -d '{"name":"slop-approvers","friendlyName":"slop approvers"}' | jq -r .id)
api PUT "user-groups/$group/users" -d "$(jq -n --arg u "$user" '{userIds: [$u]}')" >/dev/null
api POST oidc/clients -d '{"id":"slop-approve","name":"slop-broker demo","callbackURLs":["${appUrl}/auth/callback"],"isPublic":false,"pkceEnabled":true,"isGroupRestricted":true}' >/dev/null
api PUT oidc/clients/slop-approve/allowed-user-groups -d "$(jq -n --arg g "$group" '{userGroupIds: [$g]}')" >/dev/null
api POST oidc/clients/slop-approve/secrets | jq -j .secret > ${state}/oidc-secret.new
mv ${state}/oidc-secret.new ${state}/oidc-secret
'';
};
};
processes = lib.mkIf (!config.devenv.isTesting) {
pocket-id = {
exec = ''
set -a
. ${state}/pocket-id.env
exec ${pkgs.pocket-id}/bin/pocket-id
'';
cwd = "${state}/pocket-id";
env = {
APP_URL = issuer;
HOST = "127.0.0.1";
PORT = toString demo.ports.pocketId;
ANALYTICS_DISABLED = "true";
};
after = [ "slop-demo:keys" ];
ready = {
http.get = { port = demo.ports.pocketId; path = "/.well-known/openid-configuration"; };
period = 1;
};
};
slop-broker = {
exec = ''
sed -e "s/@group@/$(id -gn)/" -e "s/@dev@/$(cat ${state}/dev-age.pub)/" ${brokerConfig} > ${state}/broker.toml
exec cargo run -q --bin slop-broker -- serve --config ${state}/broker.toml
'';
cwd = config.devenv.root;
after = [ "slop-demo:pocket-id" "slop-demo:repo" ];
ready = {
exec = "test -S ${run}/approve.sock";
period = 1;
};
};
box = {
exec = ''SHARED_DIR=${state}/box exec nix run "$DEVENV_ROOT#demo-box"'';
after = [ "slop-demo:keys" ];
};
};
# `devenv test`
+11 -26
View File
@@ -142,10 +142,10 @@ What each request runs, and whose code, decides whether it needs an approval fir
| `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`), each page's Server-Sent Events (`events.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, among them the page script (`assets/app.js`) and idiomorph, vendored (`assets/idiomorph.js`) |
| `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](https://askama.rs) 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`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs, host side and repository template (`demo/`, `packages.<system>.demo` and `demo-box`, and `host.nix`, which `devenv.nix` imports) |
| `devenv.nix` | The development environment and its scripts, with the demo's host side (`devenv up`) from `nix/demo/host.nix`; `nix develop` gives a plainer shell from `flake.nix` without them |
| `nix/` | The package, NixOS modules (`modules/nixos`), home-manager module (`modules/home-manager`), the VM test (`vm-test.nix`, `checks.<system>.vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs and repository template (`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 |
| `.gitea/workflows/ci.yaml` | CI: `nix flake check` |
## Request lifecycle
@@ -183,12 +183,9 @@ sections after this one describe each kind on its own.
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 (`secret set`). `ssh` carries its stdin in the request instead.
`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`.
- If the requester leaves, most operations notice the cancel token and stop. Those
`ops::outlives_requester` names (deploys) ignore it: `see_through` logs `detached` and
keeps waiting, so the outcome is still audited.
7. **Finish.** One terminal message (`Finished`, `Denied`, `Expired` or `Error`), or none if the
requester went away, then the connection closes.
@@ -204,14 +201,11 @@ sections after this one describe each kind on its own.
- `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.
- `ssh::detail` shows the command and all of its stdin, refusing stdin that isn't UTF-8 and
requests too long to show whole.
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` passes the requester's words as they are, for `ssh` to join.
- stdout, stderr and the exit status go back to the requester; `ssh`'s stdin is the bytes its
request carried.
fields; `ssh` quotes the requester's arguments.
- stdout, stderr and the exit status go back to the requester; `ssh` forwards stdin.
### Secrets
@@ -278,9 +272,7 @@ sequenceDiagram
`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. Inside the unit, `activate-rs`'s output goes through a `cat` that, once
the connection is gone, gives way to one discarding it, so a lost connection can't stop it.
Each unit is `slop-deploy-<request ID>-<profile>`.
the first failure's.
### Builds
@@ -303,8 +295,7 @@ Built in: the requester's own pending requests and leases. Always allowed, and n
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` (cancelled), `detached` (the requester left an operation
that carries on), plus `invalid` and `unknown` peers.
`finished`, `failed`, `disconnected`, plus `invalid` and `unknown` peers.
## Protocol
@@ -314,8 +305,7 @@ with a 4-byte big-endian length (`LengthDelimitedCodec`, 1 MiB maximum). The typ
### Requester and broker
A requester sends one `Request`, then stdin only after an `Approved` that asks for it (`ssh`
carries its stdin in the request, so approvers see it). The 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
@@ -332,7 +322,7 @@ struct Request {
}
enum Operation {
Ssh { destination: Destination, command: Vec<Arg>, stdin: Option<bytes> },
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 },
@@ -342,7 +332,6 @@ enum Operation {
enum Destination {
Node(NodeName), // a target
Container { node: NodeName, name: ContainerName }, // `node.container-<name>`
Host { user: UserName, host: HostName, port: u16 }, // `--host`
}
@@ -508,7 +497,7 @@ Every process the broker starts goes through `src/exec.rs`:
| Function | For | Input and output |
|---|---|---|
| `exec::run` | Operations the requester watches | The given stdin, or none; stdout and stderr as frames |
| `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 |
@@ -614,10 +603,6 @@ none can be read as an option, and `--` comes before the hostname.
- ssh keeps the first value of an option. `nix copy` to `ssh://` adds `PermitLocalCommand=yes` and
waits for `echo started`, so the broker's `PermitLocalCommand=no` would hang it forever (see
`copy_options`).
- A copy from the builder's store to a node has one `NIX_SSHOPTS` for both connections.
The builder's store URL therefore carries its port and key (`ssh-ng://user@host:port?ssh-key=`):
Nix puts them after `NIX_SSHOPTS`, and for `-p` the last value wins (see
`DeployConfig::builder_store`).
- A tokio program that reads stdin can't return from `main` while that read blocks; the builder
worker calls `std::process::exit` after writing its result.
- Session variables from home-manager only reach shells started after the next login
+6 -30
View File
@@ -40,7 +40,6 @@ flowchart TB
subgraph boxvm["Box VM"]
sshd["sshd, as box<br>(nodes web, router, vault, box)"]
cache["sshd, as cache<br>(the binary cache's store)"]
end
slop -- "vsock" --> broker
@@ -51,7 +50,6 @@ flowchart TB
shell -- "moves master" --> repo
broker -- "SSH, through a wrapper" --> builder -- "fetches" --> repo
broker -- "SSH, localhost:2222" --> sshd
broker -- "SSH, localhost:2222" --> cache
```
| Part | Where | Runs |
@@ -59,14 +57,14 @@ flowchart TB
| Broker, from this checkout (`cargo run`) | Host | `devenv up` (process `slop-broker`) |
| Web app | <http://localhost:8095> | Part of the broker |
| [Pocket ID](https://pocket-id.org), for approvers to sign in | <http://localhost:1411> | `devenv up` (process `pocket-id`) |
| Box VM ([`box.nix`](../nix/demo/box.nix)): `sshd` for the targets, the deploy target and the binary cache | `localhost:2222`, as `box`, and as `cache` for the cache | `devenv up` (process `box`) |
| Box VM ([`box.nix`](../nix/demo/box.nix)): `sshd` for the targets, and the deploy target | `localhost:2222`, as `box` | `devenv up` (process `box`) |
| Agents' VM ([`agent.nix`](../nix/demo/agent.nix)), signed in as `agent` | Your terminal | `demo` |
| The repository, seeded from [`repo/`](../nix/demo/repo) | `.devenv/state/slop-demo/git/repo.git` | `git daemon`, one per connection from the agents' VM |
| The builder (`slop-broker builder`, from this checkout) | Host | The broker, through its `ssh` |
The ports are on the host's loopback, so they must be free there; they and the agents' VM's vsock
CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuration is in
[`host.nix`](../nix/demo/host.nix), the devenv module with the demo's host side:
[`devenv.nix`](../devenv.nix):
- **Requester:** `agent`, the agents' VM's vsock CID. The VMs have no network beyond their
forwarded ports, and only vsock and Git link the agents' VM to the host (see
@@ -83,8 +81,8 @@ CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuratio
- `slop ssh vault` is denied.
- `slop secret keys` runs without asking; the other secret requests ask, with a 5-minute
lease, except reading, which asks every time.
- Using the builder asks, with leases, except for commits already on `master`; deploys and
builds into the binary cache ask, with a 5-minute lease.
- Using the builder asks, with leases, except for commits already on `master`; deploys ask.
There's no binary cache, so `slop build` says it isn't configured.
## Approving
@@ -94,8 +92,8 @@ CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuratio
passkey when Pocket ID asks, then sign in to <http://localhost:8095>; the passkey also approves
`router` requests. Web Push works when the broker can reach the browser's push service.
A request blocks until it's answered, and `slop ssh` reads stdin to its end before asking. To keep
the agent's shell, run requests in the background with stdin closed:
A request blocks until it's answered, and `slop ssh` forwards stdin. To keep the agent's shell, run
requests in the background with stdin closed:
```sh
slop ssh web -- uptime </dev/null &
@@ -123,9 +121,6 @@ slop ssh web -- uptime </dev/null &
- **The builder** is reached over SSH, as in a real deployment.
- The broker's `ssh` is a wrapper that runs `slop-broker builder` from this checkout's build
when the host is `builder`, and the real `ssh` otherwise.
- It's named `ssh`, so the broker's `nix copy` and `nix path-info` use it too when they read
built paths from the builder's store (`ssh-ng://builder@builder`), which the builder serves
as `nix-daemon --stdio`.
- The builder fetches from the repository's path and evaluates with the host's Nix.
### Secrets
@@ -169,25 +164,6 @@ profile). `demo-box cat /run/demo/version` on the host shows what's active.
The box VM lets `box` use `sudo` without a password and copy unsigned paths into its store, which
lives in memory, like everything else in the VMs.
### The binary cache
The box VM holds the binary cache's store, at `/var/lib/slop-cache`, owned by its `cache`
account, as [`services.slop-broker-cache`](../nix/modules/nixos/cache.nix) sets it up: the
broker's key may only run `nix-daemon --stdio` on that store and add GC roots. Nothing serves it
to other boxes; it's for seeing what `slop build` pushes. In `~/repo` on the agents' VM:
```sh
slop build packages.x86_64-linux.default </dev/null &
```
As with a deploy, the builder's use is approved first (or covered by a lease), then the build
request shows the outputs and their closure sizes, and once approved the broker pushes them and
prints their paths. To see them on the host:
```sh
demo-box ls /var/lib/slop-cache/nix/var/nix/gcroots/slop-broker
```
## The box VM
`demo-box` in the devenv shell logs in to the box VM as `box`, with the broker's key, to see what
+12 -66
View File
@@ -101,15 +101,11 @@ and `slop-approve`. How the code does it is in
- 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 (`ssh`
carries its stdin in the request instead, below). The broker drops stdin an operation
doesn't read, and treats a requester sending more than 1 MiB as gone;
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. A
deploy's activation is the exception: stopping it partway would leave boxes half changed, so
the broker waits for it and logs how it ended.
If the connection closes, the broker cancels the request or kills the process it started.
### Other requesters and approvers
@@ -196,8 +192,8 @@ own fields. The module and the broker refuse any other operation or field.
| Operation | Fields rules can match |
|---|---|
| `query` (`status`, `logs`, `failed`) | `target` (a node) and `container` (only for a container on it), or `host` and `port` (`--host`); `query` |
| `ssh` | `target` and `container`, or `host` and `port` |
| `query` (`status`, `logs`, `failed`) | `target` (a node), or `host` and `port` (`--host`); `query` |
| `ssh` | `target`, or `host` and `port` |
| `deploy` | `node`, `profile`, `mode` (`switch` or `boot`), `commit`; checked per target, and the strictest answer applies |
| `builder` | `commit`, `on_branch` (`true` or `false`), `for` (`deploy` or `build`) |
| `build` | `attr`, `commit`; checked per attribute |
@@ -214,8 +210,7 @@ own fields. The module and the broker refuse any other operation or field.
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. Deploying the broker's box doesn't restart it;
restart `slop-broker.service` for a new version or configuration to take effect.
- **Restarts** drop pending requests and leases.
### Approvals web app
@@ -233,17 +228,7 @@ on a desktop shows what `slop-approve` can only print.
- 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 keeps the page current and manages notifications, and a service worker shows
them.
- **Live updates.** Each open page follows one stream of Server-Sent Events (`/events`).
- Each event carries a region of the page as HTML: a whole element with its `id`, such as the
pending list or a request, rendered by the same templates as the page. Agent-supplied text
is only ever escaped by them, never in the browser.
- The script morphs each region into the page with
[idiomorph](https://github.com/bigskysoftware/idiomorph) (vendored), so open details, the
focus and what's being typed stay.
- A region comes when the stream starts, so a page that lost its connection catches up when
the browser reconnects, and then when it changes. Signing out ends the stream.
- 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.
@@ -339,9 +324,8 @@ operation, and nothing acts on the structure besides showing it.
Each request, decision, approver, lease use and result is an event with the request's ID. The
broker writes it to the journal as a line of text and to `audit.jsonl` in its state directory as a
line of JSON, keeping what approvers were shown with its structure, so the web app's history shows
it as the request did. `slop-approve log [-n 50] [--json]` shows the recent events through the
approve socket, with each request's full detail. Secret operations record the file and the blob ID of the
line of JSON. `slop-approve log [-n 50] [--json]` shows the recent events through the approve
socket, with each request's full detail. Secret operations record the file and the blob ID of the
ciphertext they were sent, never values.
## Operations
@@ -351,38 +335,15 @@ ciphertext they were sent, never values.
- **Targets** are the deploy-rs nodes on the main branch, by name, so a new box needs a commit
there rather than a new broker config. SSH therefore needs deploys set up.
- The builder evaluates each node's `hostname`, `sshUser`, `sshOpts` and `sudo`, falling back to
the flake-wide `sshUser` and `sudo`, and its profiles' names. Only the protected branch's Nix
runs, as for secrets.
the flake-wide `sshUser` and `sudo`. Only the protected branch's Nix runs, as for secrets.
- 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.
- **Containers** are targets too, as `node.container-<name>`, the same name `slop deploy` takes:
a node's `container-<name>` profiles say which containers it has, and `<name>` is the machine
name `systemd-machined` knows the container by (a NixOS container, or any `systemd-nspawn`
machine).
- The broker reaches the node as usual and runs the command there as root, through the node's
`sudo`: `systemctl --machine`, `journalctl --machine` and, for `ssh`, `systemd-run --machine
--pipe --wait` with `/bin/sh -l -c <line>`. Stdin, output and the exit status pass through.
- Approvers see the container and the remote command, including `sudo … root` and
`--machine`.
- A container's scope has the node as `target` and the container as `container`. Rules for a
node therefore apply to its containers (match `container = "*"` to tell them apart), but a
lease covers only the target it was granted for.
- Commands go to the node's login shell as one string, quoted so that a POSIX shell and `fish`
read the same words.
- **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.
- **Approvers see everything that reaches the box.** A script piped to `bash -s` is as much the
command as its arguments, so `slop ssh` sends its whole stdin with the request.
- Approvers see the line the remote shell runs (the words joined with spaces, as `ssh` sends
them) and all of the stdin, and the audit log keeps both.
- The command gets exactly that stdin and nothing more.
- Stdin must be UTF-8 text, and the command and stdin together are limited
([`MAX_SSH_SHOWN`](../src/proto.rs)) so they're always shown whole; anything else is
refused.
- **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.
@@ -412,10 +373,6 @@ broker runs it over SSH.
Nix daemon.
- Only `git` gets the repository key, never the evaluator.
- Build logs stream to the agent. One build runs at a time.
- The broker reads built paths from the builder's store, `nix copy --from ssh-ng://` its
user with the broker's key; the builder key's forced command serves `nix-daemon --stdio`
for that. So the builder can be on another box with a store of its own, and nothing lands
in the broker's store. The builder never holds a key to the nodes or the cache.
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.
@@ -427,17 +384,8 @@ broker runs it over SSH.
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.
Its output streams back until then and is discarded after, since `activate-rs` stops when
it can't write.
- Switching doesn't restart the broker (`restartIfChanged = false`), so it can deploy its own
box and report the result. A new version or configuration of the broker takes effect when
it's next restarted.
- **If the agent goes away,** the broker keeps waiting for the activations and logs their
outcome. The audit log says the requester left, then how the deploy finished.
- **If the broker goes away** (a crash, or its box rebooting), the activations still finish.
Their units are named `slop-deploy-<request ID>-<profile>`, so the audit record leads to
their journals on each node.
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.
@@ -542,9 +490,7 @@ only people should be able to push to, and the approval shows what that branch s
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.
- Keys are labelled by name from `secrets.names` (well-known keys, such as people's), then from
SSH keys' comments anywhere in the branch's rules (`ssh-ed25519 AAAA… shill`, which age
ignores). Other keys are shown abbreviated.
- `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
+2 -5
View File
@@ -10,9 +10,6 @@
systems = [ "x86_64-linux" "aarch64-linux" ];
forSystems = f: lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
# The commit the package's version shows, if the flake is from Git
rev = self.shortRev or self.dirtyShortRev or null;
# Each module defaults its `package` to this flake's build for the system it's used on
withPackage = path: option: { lib, pkgs, ... }: {
imports = [ path ];
@@ -22,7 +19,7 @@
in
{
packages = forSystems (pkgs: rec {
slop-broker = pkgs.callPackage ./nix/package.nix { inherit rev; };
slop-broker = pkgs.callPackage ./nix/package.nix { };
default = slop-broker;
# The demo's VMs (see `docs/demo.md`)
demo = import ./nix/demo/agent.nix { inherit pkgs slop-broker; };
@@ -30,7 +27,7 @@
});
overlays.default = final: _prev: {
slop-broker = final.callPackage ./nix/package.nix { inherit rev; };
slop-broker = final.callPackage ./nix/package.nix { };
};
nixosModules = {
+4 -12
View File
@@ -13,7 +13,7 @@ let
cat <<'EOF'
slop-broker demo. You're `agent` on the agents' VM; the broker runs on the host, and the
targets `web`, `router`, `vault` and `box` are all the box VM.
targets `web`, `router` and `vault` are all the box VM.
slop status web sshd.service runs without asking (policy: auto)
slop logs web sshd.service -n 20
@@ -40,12 +40,6 @@ let
git switch -c bump && git commit -am "Bump the app" && git push origin bump
slop deploy box </dev/null & asks to use the builder, builds, then asks again
Builds into the binary cache, which is on the box VM (its GC roots, under
/var/lib/slop-cache/nix/var/nix/gcroots/slop-broker, show what's been pushed):
slop build packages.x86_64-linux.default </dev/null &
asks to use the builder, builds, then asks to push
Approve on the host: `slop-approve` in the devenv shell, or the web app at
http://localhost:${toString settings.ports.web} (`demo-sign-in` prints a sign-in link).
@@ -71,12 +65,11 @@ in
qemu.options = [ "-device vhost-vsock-pci,guest-cid=${toString settings.agentCid}" ];
};
# `agent`, signed in on the serial console, the only one `demo` shows. A second autologin on
# `tty1` would also run the login script below, and its clone would race this one's.
users.users.agent.isNormalUser = true;
services.getty.autologinUser = "agent";
# The serial console is the only one `demo` shows. A second autologin on `tty1` would also run
# the login script below, and its clone would race this one's.
systemd.services."autovt@tty1".enable = false;
# So `poweroff` works from the serial console
security.polkit = {
enable = true;
@@ -89,8 +82,8 @@ in
'';
};
# `slop`, and Git and Nix for working in the repository. `slop secret` evaluates `secrets.nix`.
environment.systemPackages = [ slop-broker help pkgs.git ];
# For `slop secret`, which evaluates `secrets.nix`
nix.settings.experimental-features = [ "nix-command" "flakes" ];
environment.etc.gitconfig.text = ''
[user]
@@ -98,7 +91,6 @@ in
email = agent@example.org
'';
# At login: the clone, once, then the help
programs.bash.loginShellInit = ''
if [ "$USER" = agent ]; then
if [ ! -d ~/repo ] && ! git clone -q ${repository} ~/repo; then
+10 -42
View File
@@ -1,22 +1,15 @@
# The box the demo's SSH targets reach, over `sshd` on a port forwarded to the host's loopback:
#
# - `box`, for the broker's key, which may use `sudo` and copy store paths, so the broker can
# deploy to it;
# - `cache`, holding the binary cache's store, which `slop build` pushes to.
#
# `devenv up` runs it with `SHARED_DIR` holding the broker's public key and the box's host key,
# which it keeps between runs so the broker's `known_hosts` stays valid.
# The box the demo's SSH targets reach: `sshd` with a `box` account for the broker's key, which may
# use `sudo` and copy store paths, so the broker can deploy to it. `devenv up` runs it with
# `SHARED_DIR` holding the broker's public key and the box's host key, which it keeps between runs
# so the broker's `known_hosts` stays valid.
{ pkgs }:
let
inherit (pkgs) lib;
settings = import ./settings.nix;
hostKey = "/etc/ssh/ssh_host_ed25519_key";
cacheStore = "/var/lib/slop-cache";
cacheHome = "/var/lib/slop-cache-home";
in
(pkgs.nixos ({ config, modulesPath, ... }: {
imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ../modules/nixos/cache.nix ];
imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ];
system.stateVersion = lib.trivial.release;
networking.hostName = "slop-demo-box";
@@ -24,7 +17,7 @@ in
virtualisation = {
graphics = false;
diskImage = null;
# Copied closures live in memory, the cache's too
# Copied closures live in memory
memorySize = 1024;
restrictNetwork = true;
forwardPorts = [{
@@ -34,9 +27,9 @@ in
}];
};
users.users.box.isNormalUser = true;
# Deploys: activation as root, and closures copied in unsigned (the store is the VM runner's
# writable overlay). Nothing is substituted, since the VM has no network.
users.users.box.isNormalUser = true;
security.sudo.extraRules = [{
users = [ "box" ];
commands = [{ command = "ALL"; options = [ "NOPASSWD" ]; }];
@@ -45,28 +38,12 @@ in
trusted-users = [ "root" "box" ];
substituters = lib.mkForce [ ];
};
# The binary cache: a store of its own, owned by `cache`. Nothing serves it to other boxes; it's
# for seeing what `slop build` pushes. The broker's key is authorized at boot, below.
users.users.cache = {
isNormalUser = true;
home = cacheHome;
createHome = true;
};
systemd.tmpfiles.rules = [ "d ${cacheStore} 0755 cache users -" ];
services.slop-broker-cache = {
enable = true;
user = "cache";
store = cacheStore;
home = cacheHome;
};
services.openssh = {
enable = true;
hostKeys = [{ path = hostKey; type = "ed25519"; }];
};
# The keys from the shared directory, which is mounted at `/tmp/shared`, before `sshd` starts
# The shared directory is mounted at `/tmp/shared`
systemd.services.slop-demo-keys = {
wantedBy = [ "multi-user.target" ];
before = [ "sshd.service" "sshd-keygen.service" ];
@@ -75,17 +52,8 @@ in
serviceConfig = { Type = "oneshot"; RemainAfterExit = true; };
script = ''
install -m 600 /tmp/shared/host-key ${hostKey}
# The broker logs in as `box` with its key, for anything
box=${config.users.users.box.home}/.ssh
install -d -m 700 -o box -g users $box
install -m 600 -o box -g users /tmp/shared/broker.pub $box/authorized_keys
# and as `cache`, only through the cache's forced command
cache=${cacheHome}/.ssh
install -d -m 700 -o cache -g users $cache
echo "restrict,command=\"${config.services.slop-broker-cache.forcedCommand}\" $(cat /tmp/shared/broker.pub)" |
install -m 600 -o cache -g users /dev/stdin $cache/authorized_keys
install -d -m 700 -o box -g users ${config.users.users.box.home}/.ssh
install -m 600 -o box -g users /tmp/shared/broker.pub ${config.users.users.box.home}/.ssh/authorized_keys
'';
};
})).vm
-386
View File
@@ -1,386 +0,0 @@
# The demo's host side, a devenv module that `devenv.nix` imports (see `docs/demo.md`). `devenv up`
# runs the broker from this checkout, with its web app and builder, Pocket ID for approvers to sign
# in with, the box VM its SSH targets reach, and the Git repository the agent pushes to. The
# devenv shell gets the commands to drive it (`demo`, `slop-approve`, `demo-merge` and the like).
{ pkgs, lib, config, ... }:
let
settings = import ./settings.nix;
# State kept between runs, and sockets, whose paths must be short
state = "${config.devenv.state}/slop-demo";
run = "${config.devenv.runtime}/slop-demo";
# Bare repositories the agents' VM reaches with `git://`
repositories = "${state}/git";
issuer = "http://localhost:${toString settings.ports.pocketId}";
appUrl = "http://localhost:${toString settings.ports.web}";
# The builder: `slop-broker builder`, which the broker reaches through `ssh` (see `ssh` below).
# The repository is a local path, so its key is never used.
builderConfig = (pkgs.formats.toml { }).generate "slop-demo-builder.toml" {
repository = "${repositories}/repo.git";
key = "/nonexistent";
branch = "master";
directory = "${state}/builder";
# The host's own Nix first, so builds go through its daemon as the user
path = [
"${pkgs.git}/bin"
"${pkgs.openssh}/bin"
"/run/current-system/sw/bin"
"/nix/var/nix/profiles/default/bin"
"${pkgs.nix}/bin"
];
};
# The broker's `ssh`, also `ssh` on the `PATH` of its `nix` (which takes it from the same
# directory): the host `builder` runs the builder from this checkout's build directly, as its
# forced command would, with the remote command in `SSH_ORIGINAL_COMMAND`. Everything else is
# the real `ssh`.
#
# - The broker passes the host after `--`, then the command.
# - Nix passes `builder@builder` and the command after `--`, first checks for a control master,
# and waits for the `LocalCommand` it asks for.
ssh = pkgs.writeShellScriptBin "ssh" ''
builder="" master=0 remote=() after=0 started=0
for arg; do
if [ "$after" = 1 ]; then
remote+=("$arg")
elif [ "$arg" = -- ]; then
after=1
elif [ "$arg" = builder@builder ]; then
builder=nix
elif [ "$arg" = "-oLocalCommand=echo started" ]; then
started=1
elif [ "$arg" = -O ]; then
master=1
fi
done
if [ "''${#remote[@]}" -gt 0 ] && [ "''${remote[0]}" = builder ] && [ -z "$builder" ]; then
builder=broker
remote=("''${remote[@]:1}")
fi
if [ -n "$builder" ]; then
# The builder has no control master
[ "$master" = 1 ] && exit 255
[ "$started" = 1 ] && echo started
SSH_ORIGINAL_COMMAND="''${remote[*]}" exec ${config.devenv.root}/target/debug/slop-broker builder --config ${builderConfig}
fi
exec ${pkgs.openssh}/bin/ssh "$@"
'';
# Only `demo-merge` moves `master`, standing in for branch protection and a person merging
preReceive = pkgs.writeShellScript "slop-demo-pre-receive" ''
while read -r old new ref; do
if [ "$ref" = refs/heads/master ]; then
echo "master is protected: push a branch, and merge it with \`demo-merge <branch>\` on the host" >&2
exit 1
fi
done
'';
# The broker's configuration. `@group@` becomes the user's primary group, whose members may
# approve, and `@dev@` the demo person's age public key.
brokerConfig = (pkgs.formats.toml { }).generate "slop-demo.toml" {
requesters.agent = { vsock_cid = settings.agentCid; policy = "agent"; };
policies.agent.ops = {
query.action = "auto";
ssh = {
action = "ask";
leases = [ "5m" "1h" ];
rules = [
{ match.target = "router"; action = "ask"; confirm = "passkey"; }
{ match.target = "vault"; action = "deny"; }
];
};
# Agent-written Nix runs in the builder once its use is approved; `master` is reviewed
builder = {
action = "ask";
leases = [ "5m" "1h" ];
rules = [{ match.on_branch = "true"; action = "auto"; }];
};
deploy = {
action = "ask";
leases = [ "5m" ];
};
build = {
action = "ask";
leases = [ "5m" ];
};
# Approvals show whether the file and its recipients match `master`; reading always asks
secret = {
action = "ask";
leases = [ "5m" ];
rules = [{ match.action = "keys"; action = "auto"; }];
};
};
vsock_port = 6262;
approve_socket = "${run}/approve.sock";
approver_group = "@group@";
audit_log = "${state}/audit.jsonl";
# SSH to the box VM, and to the builder through the wrapper
ssh = {
ssh = "${ssh}/bin/ssh";
key = "${state}/broker-key";
known_hosts = "${state}/known_hosts";
};
deploy = {
builder = { hostname = "builder"; user = "builder"; };
nix = "${pkgs.nix}/bin/nix";
cache = "${state}/nix-cache";
};
# The box VM's `cache` account, which holds the binary cache's store
cache = {
hostname = "localhost";
user = "cache";
ssh_opts = [ "-p" (toString settings.ports.boxSsh) ];
key = "${state}/broker-key";
};
secrets = {
identity = "${state}/broker-age.key";
names.dev = "@dev@";
};
web = {
listen = "127.0.0.1:${toString settings.ports.web}";
url = appUrl;
inherit issuer;
client_id = "slop-approve";
client_secret = "${state}/oidc-secret";
group = "slop-approvers";
state_dir = "${state}/web";
};
};
# Pocket ID's admin API, with the key `devenv up` made
pocketIdApi = ''
api() {
local method=$1 path=$2
shift 2
curl -sS --fail-with-body -X "$method" "${issuer}/api/$path" \
-H "X-API-Key: $(sed -n 's/^STATIC_API_KEY=//p' ${state}/pocket-id.env)" -H 'Content-Type: application/json' "$@"
}
'';
in
{
# For `slop-approve` in this shell
env.SLOP_APPROVE = "unix:${run}/approve.sock";
scripts = {
slop-approve = {
description = "Answer the demo's requests (built from this checkout)";
exec = ''exec cargo run -q --manifest-path "$DEVENV_ROOT/Cargo.toml" --bin slop-broker -- approve "$@"'';
};
demo = {
description = "Boot the demo's agents' VM on this terminal; needs `devenv up` running";
exec = ''
if [ ! -S ${run}/approve.sock ]; then
echo "The broker isn't running: start \`devenv up\` first." >&2
exit 1
fi
# Git from the VM: connections to 10.0.2.100:9418, an address only the guest sees, each
# run a `git daemon` on the host serving the demo's repositories. Commas are doubled for
# QEMU.
daemon="${pkgs.git}/bin/git daemon --inetd --export-all --enable=receive-pack --base-path=${repositories}"
export QEMU_NET_OPTS="guestfwd=tcp:10.0.2.100:9418-cmd:''${daemon//,/,,}"
exec nix run "$DEVENV_ROOT#demo" -- "$@"
'';
};
demo-merge = {
description = "Fast-forward the demo repository's `master` to a branch, as a person merging";
exec = ''
set -eu
branch=''${1:?usage: demo-merge <branch>}
cd ${repositories}/repo.git
if ! git rev-parse --verify --quiet "refs/heads/$branch" >/dev/null; then
echo "there's no branch $branch; the agent pushes one with \`git push origin <branch>\`" >&2
exit 1
fi
if ! git merge-base --is-ancestor master "refs/heads/$branch"; then
echo "$branch isn't master plus new commits; rebase it on master first" >&2
exit 1
fi
git update-ref refs/heads/master "refs/heads/$branch"
echo "master is now at $(git rev-parse --short master)"
'';
};
demo-box = {
description = "SSH into the demo's box VM as `box`, with the broker's key";
exec = ''
exec ${pkgs.openssh}/bin/ssh -F none -i ${state}/broker-key -o IdentitiesOnly=yes \
-o UserKnownHostsFile=${state}/known_hosts -o StrictHostKeyChecking=accept-new \
-p ${toString settings.ports.boxSsh} box@localhost "$@"
'';
};
demo-sign-in = {
description = "Print a one-time link that signs in to the demo's Pocket ID as the approver";
exec = ''
${pocketIdApi}
user=$(api GET 'users?search=demo' | jq -r '.data[] | select(.username == "demo") | .id')
echo "${issuer}/lc/$(api POST "users/$user/one-time-access-token" -d '{"ttl":"1h"}' | jq -r .token)"
'';
};
demo-reset = {
description = "Delete the demo's state (Pocket ID's users and passkeys, keys, repository, audit log)";
exec = ''rm -rf ${state}'';
};
};
# Not for `devenv test`
tasks = lib.mkIf (!config.devenv.isTesting) {
"slop-demo:keys" = {
description = "Make the demo's secrets and SSH keys";
exec = ''
set -eu
umask 077
mkdir -p ${state}/box ${state}/pocket-id ${state}/web ${state}/builder ${run}
if [ ! -e ${state}/pocket-id.env ]; then
key() { ${pkgs.openssl}/bin/openssl rand -hex 32; }
printf 'ENCRYPTION_KEY=%s\nSTATIC_API_KEY=%s\n' "$(key)" "$(key)" > ${state}/pocket-id.env
fi
# The box VM gets the broker's public key and its own host key through its shared directory
[ -e ${state}/broker-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo -f ${state}/broker-key
cp ${state}/broker-key.pub ${state}/box/broker.pub
[ -e ${state}/box/host-key ] || ${pkgs.openssh}/bin/ssh-keygen -q -t ed25519 -N "" -C slop-demo-box -f ${state}/box/host-key
'';
};
# Once: the repository, with secrets encrypted to the demo person and the broker. The hook is
# installed every time, so it follows changes here.
"slop-demo:repo" = {
description = "Seed the demo's repository and age identities";
after = [ "slop-demo:keys" ];
exec = ''
set -eu
umask 077
export PATH=${lib.makeBinPath (with pkgs; [ coreutils gnused git rage openssl wireguard-tools jq ])}
if [ ! -d ${repositories}/repo.git ]; then
# Age identities for the demo person and the broker
for name in dev broker; do
[ -e ${state}/$name-age.key ] || rage-keygen -o ${state}/$name-age.key 2>/dev/null
rage-keygen -y ${state}/$name-age.key > ${state}/$name-age.pub
done
dev=$(cat ${state}/dev-age.pub) broker=$(cat ${state}/broker-age.pub)
# The files from `repo/`, with the box VM's SSH port
work=$(mktemp -d)
cp -r ${./repo}/. "$work"
chmod -R u+w "$work"
sed -i "s/@boxSsh@/${toString settings.ports.boxSsh}/" "$work/flake.nix"
# nixpkgs as this repository locks it, so the builder already has it
jq '{nodes: {root: {inputs: {nixpkgs: "nixpkgs"}}, nixpkgs: .nodes[.nodes.root.inputs.nixpkgs]}, root: "root", version: 7}' \
${../../flake.lock} > "$work/flake.lock"
# The agenix rules and the secrets, encrypted to both
cat > "$work/secrets.nix" <<EOF
# The agenix rules: who each secret is encrypted to.
let
dev = "$dev";
broker = "$broker";
in
{
"secrets/app.env.age".publicKeys = [ dev broker ];
"secrets/wg.key.age".publicKeys = [ dev broker ];
}
EOF
mkdir "$work/secrets"
printf 'DB_USER=app\nDB_PASSWORD=%s\n' "$(openssl rand -hex 12)" |
rage -a -r "$dev" -r "$broker" -o "$work/secrets/app.env.age"
wg genkey | rage -a -r "$dev" -r "$broker" -o "$work/secrets/wg.key.age"
# Committed to `master` as Dev, and pushed to the bare repository
export GIT_AUTHOR_NAME=Dev GIT_AUTHOR_EMAIL=dev@example.org
export GIT_COMMITTER_NAME=Dev GIT_COMMITTER_EMAIL=dev@example.org
git -C "$work" init -q --initial-branch=master
git -C "$work" add .
git -C "$work" commit -q -m "Start the demo repository"
mkdir -p ${repositories}
git init -q --bare --initial-branch=master ${repositories}/repo.git
git -C "$work" push -q ${repositories}/repo.git master
rm -rf "$work"
fi
ln -sf ${preReceive} ${repositories}/repo.git/hooks/pre-receive
'';
};
# Once: the approver `demo` in the group `slop-approvers`, and the broker's OIDC client
"slop-demo:pocket-id" = {
description = "Set up the demo's approver and OIDC client in Pocket ID";
after = [ "devenv:processes:pocket-id" ];
status = "test -s ${state}/oidc-secret";
exec = ''
set -eu
umask 077
${pocketIdApi}
user=$(api POST users -d '{"username":"demo","email":"demo@example.org","firstName":"Demo","lastName":"Approver","displayName":"Demo Approver","isAdmin":false}' | jq -r .id)
group=$(api POST user-groups -d '{"name":"slop-approvers","friendlyName":"slop approvers"}' | jq -r .id)
api PUT "user-groups/$group/users" -d "$(jq -n --arg u "$user" '{userIds: [$u]}')" >/dev/null
api POST oidc/clients -d '{"id":"slop-approve","name":"slop-broker demo","callbackURLs":["${appUrl}/auth/callback"],"isPublic":false,"pkceEnabled":true,"isGroupRestricted":true}' >/dev/null
api PUT oidc/clients/slop-approve/allowed-user-groups -d "$(jq -n --arg g "$group" '{userGroupIds: [$g]}')" >/dev/null
api POST oidc/clients/slop-approve/secrets | jq -j .secret > ${state}/oidc-secret.new
mv ${state}/oidc-secret.new ${state}/oidc-secret
'';
};
};
processes = lib.mkIf (!config.devenv.isTesting) {
pocket-id = {
exec = ''
set -a
. ${state}/pocket-id.env
exec ${pkgs.pocket-id}/bin/pocket-id
'';
cwd = "${state}/pocket-id";
env = {
APP_URL = issuer;
HOST = "127.0.0.1";
PORT = toString settings.ports.pocketId;
ANALYTICS_DISABLED = "true";
};
after = [ "slop-demo:keys" ];
ready = {
http.get = { port = settings.ports.pocketId; path = "/.well-known/openid-configuration"; };
period = 1;
};
};
slop-broker = {
exec = ''
sed -e "s/@group@/$(id -gn)/" -e "s/@dev@/$(cat ${state}/dev-age.pub)/" ${brokerConfig} > ${state}/broker.toml
exec cargo run -q --bin slop-broker -- serve --config ${state}/broker.toml
'';
cwd = config.devenv.root;
after = [ "slop-demo:pocket-id" "slop-demo:repo" ];
ready = {
exec = "test -S ${run}/approve.sock";
period = 1;
};
};
box = {
exec = ''SHARED_DIR=${state}/box exec nix run "$DEVENV_ROOT#demo-box"'';
after = [ "slop-demo:keys" ];
};
};
}
+1 -1
View File
@@ -1,4 +1,4 @@
# Shared by the demo's VMs and its host side in `host.nix`
# Shared by the demo's VMs and its host side in `devenv.nix`
{
# The agents' VM's vsock CID: anything above 2 that no other VM on the host uses
agentCid = 3626;
+3 -6
View File
@@ -37,8 +37,8 @@ let
# The operations a policy can allow, as the broker names them (`OpName`), and the scope fields
# their rules can match (`OpName::fields`)
opFields = {
query = [ "target" "container" "host" "port" "query" ];
ssh = [ "target" "container" "host" "port" ];
query = [ "target" "host" "port" "query" ];
ssh = [ "target" "host" "port" ];
deploy = [ "node" "profile" "mode" "commit" ];
builder = [ "commit" "on_branch" "for" ];
build = [ "attr" "commit" ];
@@ -169,7 +169,7 @@ in
hostname = mkOpt' str "localhost" "Box running the builder (`services.slop-broker-builder`).";
user = mkOpt' str "slop-broker-build" "The builder's user.";
sshOpts = mkOpt' (listOf str) [ "-p" (toString (head config.services.openssh.ports)) ]
"SSH arguments for reaching the builder: only `-p <port>`, which goes in the store URL built paths are copied from.";
"Extra SSH arguments for reaching the builder.";
};
};
@@ -270,9 +270,6 @@ in
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
# Switching doesn't restart the broker, so it can deploy its own box and see the deploy
# through; a new version or configuration takes effect at the next restart.
restartIfChanged = false;
serviceConfig = {
ExecStart = "${cfg.package}/bin/slop-broker serve --config ${brokerConfig}";
LoadCredential =
+1 -7
View File
@@ -51,12 +51,6 @@ in
home = mkOpt' str null "`HOME` for the store's commands; a directory `user` can write to.";
keepDays = mkOpt' ints.positive 14 "Days a pushed path stays rooted after its last push.";
brokerKeys = mkOpt' (listOf str) [ ] "SSH public keys of brokers that may push.";
forcedCommand = lib.mkOption {
type = path;
default = forcedCommand;
readOnly = true;
description = "The forced command for brokers' keys, for keys `brokerKeys` can't list, such as ones made at boot.";
};
};
config = mkIf cfg.enable {
@@ -68,7 +62,7 @@ in
];
users.users.${cfg.user}.openssh.authorizedKeys.keys =
map (k: ''restrict,command="${cfg.forcedCommand}" ${k}'') cfg.brokerKeys;
map (k: ''restrict,command="${forcedCommand}" ${k}'') cfg.brokerKeys;
# Expired roots go daily; the store's own garbage collection then takes their paths
systemd = {
+2 -9
View File
@@ -1,13 +1,10 @@
# `rev` is the commit the build is from, like `2d59b59` or `2d59b59-dirty`, which the version
# shows. It's part of the build, so every commit rebuilds the package.
{ lib, rustPlatform, pkg-config, openssl, sqlite, rev ? null }:
{ lib, rustPlatform, pkg-config, openssl, sqlite }:
let
inherit (lib.fileset) toSource unions;
inherit ((builtins.fromTOML (builtins.readFile ../Cargo.toml)).package) version;
in
rustPlatform.buildRustPackage {
pname = "slop-broker";
inherit version;
version = "0.1.0";
src = toSource {
root = ../.;
@@ -19,10 +16,6 @@ rustPlatform.buildRustPackage {
nativeBuildInputs = [ pkg-config ];
buildInputs = [ openssl sqlite ];
env = lib.optionalAttrs (rev != null) {
SLOP_BROKER_VERSION = "${version}+${rev}";
};
postInstall = ''
ln -s slop-broker $out/bin/slop-approve
install -Dm644 slop-tools.md $out/share/slop-broker/slop-tools.md
+90 -273
View File
@@ -1,355 +1,172 @@
# 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`).
#
# - `machine` runs the broker, its builder and the requesters, and is also the deploy node `local`
# (and `other` and `denied`), with a container, `web`.
# - `box` is a second deploy node with a store of its own, and holds the binary cache's store.
{ pkgs, slop-broker }:
let
inherit (pkgs) lib;
# SSH keys: the broker's own (`key`), a requester's and an approver's on other boxes
key = pkgs.runCommand "test-key" { nativeBuildInputs = [ pkgs.openssh ]; } ''
mkdir $out
for k in key requester approver; do ssh-keygen -q -t ed25519 -N "" -f $out/$k; done
'';
publicKey = name: builtins.readFile "${key}/${name}.pub";
# The broker's key at runtime: not a store path, as the module requires
keyFile = "/etc/slop-broker-test/key";
# The builder's repository: a flake whose deploy-rs nodes are the broker's SSH targets, with a
# profile it can build without nixpkgs. Two commits, `one` and `two`, differ only in the profile.
# The builder's repository: a flake whose deploy-rs nodes are the broker's SSH targets
repository = pkgs.runCommand "test-repository" { nativeBuildInputs = [ pkgs.git ]; } ''
mkdir $out
install -m755 ${pkgs.pkgsStatic.busybox}/bin/busybox $out/busybox
cat > $out/flake.nix <<'EOF'
{
outputs = _: {
deploy.sshUser = "deploy";
deploy.nodes = {
local.hostname = "localhost";
other.hostname = "localhost";
denied.hostname = "localhost";
};
};
}
EOF
git -C $out init --quiet --initial-branch=master
for version in one two; do
sed "s/@version@/$version/g" ${./vm-test/flake.nix} > $out/flake.nix
git -C $out add flake.nix busybox
git -C $out -c user.name=test -c user.email=test@example.org commit --quiet -m "Profile $version"
git -C $out rev-parse HEAD > $out/commit-$version
done
git -C $out add flake.nix
git -C $out -c user.name=test -c user.email=test@example.org commit --quiet -m "Add nodes"
'';
# A deploy node: the broker logs in as `deploy`, which may use `sudo` (for activation and
# container commands) and copy unsigned paths into the store. Nothing is substituted, since the
# test is offline: everything is built or already in the store.
deployNode = {
services.openssh.enable = true;
users.users.deploy = {
isNormalUser = true;
openssh.authorizedKeys.keyFiles = [ "${key}/key.pub" ];
};
security.sudo.extraRules = [{
users = [ "deploy" ];
commands = [{ command = "ALL"; options = [ "NOPASSWD" ]; }];
}];
nix.settings = {
trusted-users = [ "deploy" ];
substituters = lib.mkForce [ ];
};
};
in
pkgs.testers.runNixOSTest {
name = "slop-broker";
nodes.box = { ... }: {
imports = [ deployNode ./modules/nixos/cache.nix ];
# The binary cache: a store of its own, owned by `cache`, which the broker's key may only use
# through the cache's forced command
users.users.cache = {
isNormalUser = true;
home = "/var/lib/slop-cache-home";
createHome = true;
};
systemd.tmpfiles.rules = [ "d /var/lib/slop-cache 0755 cache users -" ];
services.slop-broker-cache = {
enable = true;
user = "cache";
store = "/var/lib/slop-cache";
home = "/var/lib/slop-cache-home";
brokerKeys = [ (publicKey "key") ];
};
};
nodes.machine = { ... }: {
imports = [ deployNode ./modules/nixos/broker.nix ./modules/nixos/builder.nix ];
imports = [ ./modules/nixos/broker.nix ./modules/nixos/builder.nix ];
# The agent reaches the broker over vsock loopback (CID 1); `reviewer` approves
boot.kernelModules = [ "vsock_loopback" ];
users.users.reviewer.isNormalUser = true;
users.users.agent.isNormalUser = true;
virtualisation.memorySize = 2048;
# `script`, for answering on a terminal
environment.systemPackages = [ pkgs.util-linux ];
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 ];
programs.ssh.extraConfig = ''
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
LogLevel ERROR
'';
# Not a store path, as the module requires
environment.etc."slop-broker-test/key".source = "${key}/key";
# A container for the container commands, which go through `systemd-machined` as root
containers.web = {
autoStart = true;
config.system.stateVersion = lib.trivial.release;
};
services.slop-broker = {
enable = true;
package = slop-broker;
approvers = [ "reviewer" ];
# The broker's SSH connections trust any host key, and say nothing about it
programs.ssh.extraConfig = ''
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
LogLevel ERROR
'';
environment.etc."slop-broker-test/key".source = "${key}/key";
services.slop-broker = {
enable = true;
package = slop-broker;
approvers = [ "reviewer" ];
# Everything runs without asking except `slop ssh`, which tests the approvals
policies.agent.ops = {
query.action = "auto";
builder.action = "auto";
deploy.action = "auto";
build.action = "auto";
ssh = {
action = "ask";
leases = [ "5m" ];
rules = [{ match.target = "denied"; action = "deny"; }];
policies.agent.ops = {
query.action = "auto";
ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; };
};
};
policies.workstation.ops.query.action = "auto";
policies.workstation.ops.query.action = "auto";
requesters.agent = {
vsockCid = 1;
policy = "agent";
};
requesters.workstation = {
sshKeys = [ (publicKey "requester") ];
policy = "workstation";
};
sshApprovers.laptop = [ (publicKey "approver") ];
requesters.agent = {
vsockCid = 1;
policy = "agent";
};
requesters.workstation = {
sshKeys = [ (publicKey "requester") ];
policy = "workstation";
};
ssh = {
sshApprovers.laptop = [ (publicKey "approver") ];
ssh = {
enable = true;
keyFile = "/etc/slop-broker-test/key";
};
deploy.enable = true;
};
# Only reads the repository, so its key is never used
services.slop-broker-builder = {
enable = true;
inherit keyFile;
};
deploy.enable = true;
cache = {
enable = true;
hostname = "box";
user = "cache";
inherit keyFile;
package = slop-broker;
repository = "/var/lib/slop-test-repository";
keyFile = "/etc/slop-broker-test/key";
brokerKeys = [ (publicKey "key") ];
};
systemd.tmpfiles.rules = [ "C /var/lib/slop-test-repository - - - - ${repository}" "Z /var/lib/slop-test-repository - slop-broker-build - - -" ];
};
# The builder only reads the repository, a local copy, so its key is never used
services.slop-broker-builder = {
enable = true;
package = slop-broker;
repository = "/var/lib/slop-test-repository";
inherit keyFile;
brokerKeys = [ (publicKey "key") ];
};
systemd.tmpfiles.rules = [
"C /var/lib/slop-test-repository - - - - ${repository}"
"Z /var/lib/slop-test-repository - slop-broker-build - - -"
];
};
testScript = ''
# Commands as the agent, sending requests over vsock (or `broker`)
vsock = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'"
def agent(command, broker=vsock):
return f"su agent -c \"{broker} {command}\""
def slop(args, broker=vsock):
"""Runs `slop`, which must succeed; returns its stdout."""
return machine.succeed(agent(f"slop {args}", broker))
def try_slop(args, broker=vsock):
"""Runs `slop`; returns its exit status and output, stderr included."""
return machine.execute(agent(f"slop {args}", broker) + " 2>&1")
def slop_in_background(command, output):
"""Starts an agent's command that waits for an answer, writing its output to a file."""
machine.execute(agent(command) + f" > {output} 2>&1 &")
# Commands as the reviewer
def approve(args):
return machine.succeed(f"su reviewer -c 'slop-approve {args}'")
def wait_for_request(summary):
machine.wait_until_succeeds(f"su reviewer -c 'slop-approve list' | grep -q '{summary}'")
start_all()
machine.wait_for_unit("sshd.service")
machine.wait_for_unit("slop-broker.service")
machine.wait_for_file("/run/slop-broker/approve.sock")
# Policy
env = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'"
# Denied by policy, without asking
status, out = try_slop("ssh denied -- true")
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)
# Fixed queries run without asking
out = slop("status local sshd.service")
out = machine.succeed(f"su agent -c \"{env} slop status local sshd.service\"")
assert "sshd.service" in out, out
print(slop("logs local sshd.service -n 5 --since 1h"))
out = machine.succeed(f"su agent -c \"{env} slop logs local sshd.service -n 5 --since 1h\"")
print(out)
# Approvals and leases
# Ask, approve from a terminal, and see the real ssh run. Only approvers can answer.
slop_in_background("slop ssh local -- 'echo hi from \\$(whoami)'", "/tmp/out")
wait_for_request("ssh local")
listing = approve("list")
# 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(f"su agent -c 'slop-approve {request} once' 2>&1")
status, out = machine.execute("su agent -c 'slop-approve " + request + " once' 2>&1")
assert status != 0, out
approve(f"{request} 5m")
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 goes with the request
out = machine.succeed("echo piped | " + agent("slop ssh local -- cat"))
# 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 = slop("requests")
out = machine.succeed(f"su agent -c \"{env} slop requests\"")
assert "ssh" in out and "lease" in out, out
# Containers
# Queries run without asking, as for nodes
machine.wait_for_unit("container@web.service")
out = slop("status local.container-web systemd-journald.service")
assert "systemd-journald.service" in out, out
print(slop("failed local.container-web"))
print(slop("logs local.container-web systemd-journald.service -n 5"))
# Only `container-*` profiles are containers
status, out = try_slop("failed local.container-nope")
assert status == 125 and "unknown container local.container-nope" in out, (status, out)
status, out = try_slop("failed local.system")
assert status == 125 and "only containers" in out, (status, out)
# `slop ssh` asks again, since the lease is for the host, and runs in the container as root,
# with stdin and the command's exit status
machine.execute(
"echo from stdin | "
+ agent("slop ssh local.container-web -- 'cat; echo in \\$(hostname) as \\$(whoami); exit 3'; echo exit \\$?")
+ " > /tmp/out5 2>&1 &"
)
wait_for_request("ssh local.container-web")
approve("once")
machine.wait_until_succeeds("grep -q 'exit 3' /tmp/out5")
out = machine.succeed("cat /tmp/out5")
print(out)
assert "from stdin" in out and "in web as root" in out, out
# Errors
# Unknown nodes are named plainly; usage errors exit 125 like other refusals
status, out = try_slop("ssh nope -- true")
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 = try_slop("ssh")
status, out = machine.execute(f"su agent -c \"{env} slop ssh\" 2>&1")
assert status == 125, (status, out)
# Answering
# Interactively on a terminal, where a wrong answer is asked again
slop_in_background("slop ssh other -- echo interactive", "/tmp/out2")
wait_for_request("ssh other")
# 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
slop_in_background("slop ssh other -- true; echo \\$?", "/tmp/out3")
wait_for_request("ssh other")
approve("deny")
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)
# Over SSH
# Each key names its owner and role: the agent's key here is the workstation's, which may
# only query, and can't approve
# Over SSH: each key names its owner and role
for user, k in [("agent", "requester"), ("reviewer", "approver")]:
machine.succeed(f"install -D -m600 -o {user} ${key}/{k} /home/{user}/.ssh/id_ed25519")
remote = "SLOP_BROKER=ssh:slop@localhost"
out = slop("status local sshd.service", broker=remote)
out = machine.succeed(f"su agent -c \"{remote} slop status local sshd.service\"")
assert "sshd.service" in out, out
status, out = try_slop("ssh local -- true", broker=remote)
status, out = machine.execute(f"su agent -c \"{remote} slop ssh local -- true\" 2>&1")
assert status == 125 and "denied by policy" in out, (status, out)
status, out = machine.execute("su agent -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve list' 2>&1")
assert status != 0 and "for sending requests" in out, (status, out)
# The approver's key answers as `laptop`
slop_in_background("slop ssh other -- echo remote approval", "/tmp/out4")
wait_for_request("ssh other")
machine.execute(f"su agent -c \"{env} slop ssh other -- echo remote approval\" > /tmp/out4 2>&1 &")
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
machine.succeed("su reviewer -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve once'")
machine.wait_until_succeeds("grep -q 'remote approval' /tmp/out4")
# Deploys
# A builder with a store of its own serves it to the broker's key as `nix-daemon --stdio`
machine.succeed("install -m600 ${keyFile} /root/builder-key")
system = machine.succeed("readlink -f /run/current-system").strip()
store = "ssh-ng://slop-broker-build@localhost:22?ssh-key=/root/builder-key"
out = machine.succeed(f"nix --extra-experimental-features nix-command path-info --store '{store}' {system}")
assert out.strip() == system, out
# Deploys build, copy, compare and activate, on both nodes at once, though their profiles are
# the same derivation. Copying to `box` fills a store of its own: the profile and busybox.
box.wait_for_unit("sshd.service")
repository = "/var/lib/slop-test-repository"
one = machine.succeed(f"cat {repository}/commit-one").strip()
two = machine.succeed(f"cat {repository}/commit-two").strip()
status, out = try_slop(f"deploy box.system local.system --commit {one}")
print(out)
assert status == 0, (status, out)
for line in ["[box.system] activating one", "[local.system] activating one"]:
assert line in out, (line, out)
box.succeed("test -e /tmp/slop-activated-one")
machine.succeed("test -e /tmp/slop-activated-one")
profile = box.succeed("ls -d /nix/store/*-test-profile-one").strip()
out = box.succeed(f"nix --extra-experimental-features nix-command path-info -r {profile}")
assert len(out.split()) == 2, out
# The second commit, with its build's log
status, out = try_slop(f"deploy box.system --commit {two}")
print(out)
assert status == 0 and "build line two" in out, (status, out)
box.succeed("test -e /tmp/slop-activated-two")
# The binary cache
# Builds go to the cache's store on `box`, closure and all, with a GC root; the output path
# is the last line
status, out = try_slop(f"build packages.x86_64-linux.profile --commit {two}")
print(out)
assert status == 0, (status, out)
path = out.strip().splitlines()[-1]
assert path.startswith("/nix/store/") and path.endswith("-test-profile-two"), out
out = box.succeed(f"nix --extra-experimental-features nix-command path-info --store /var/lib/slop-cache -r {path}")
assert len(out.split()) == 2, out
box.succeed(f"test -L /var/lib/slop-cache/nix/var/nix/gcroots/slop-broker/{path.removeprefix('/nix/store/')}")
# The audit log
# It has the answers and the outcomes; the default 50 records don't reach back far enough
audit = approve("log -n 200")
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
assert "answered once by laptop (ssh)" in audit, audit
assert "finished with exit status 0" in audit, audit
'';
}
-46
View File
@@ -1,46 +0,0 @@
# The VM test's repository, committed once for each version of its profile (`@version@`).
{
outputs = _:
let
# A stand-in for deploy-rs's activation wrapper, built with only a static busybox, whose
# `activate-rs` leaves a mark. It refers to busybox, so its closure is two paths.
profile = derivation {
name = "test-profile-@version@";
system = "x86_64-linux";
builder = ./busybox;
args = [
"sh"
"-c"
''
b=${./busybox}
echo "build line @version@"
$b mkdir $out
printf '#!/bin/sh\n# %s\necho activating @version@\ntouch /tmp/slop-activated-@version@\n' $b > $out/activate-rs
$b chmod +x $out/activate-rs
''
];
};
# Its own profile path, so comparing doesn't take in the box's own system
system = { path = profile; profilePath = "/nix/var/nix/profiles/slop-test"; };
in
{
# For `slop build`
packages.x86_64-linux.profile = profile;
deploy.sshUser = "deploy";
deploy.nodes = {
local = {
hostname = "localhost";
profiles = {
inherit system;
# Only its name is used: it says which containers there are
container-web = { };
};
};
# Another box, with a store of its own to copy to
box = { hostname = "box"; profiles = { inherit system; }; };
other.hostname = "localhost";
denied.hostname = "localhost";
};
};
}
+4 -12
View File
@@ -6,11 +6,9 @@ applies a policy, and asks a human to approve most requests.
## How requests behave
- A request that needs approval blocks while a human answers, for as long as the broker allows:
five minutes by default, but often much longer. `slop` prints how long when it starts waiting
(`approvers have 45m to answer`), and a deploy or build waits that long at each approval. Run
`slop` in the background, or with a tool timeout longer than that. Don't retry a request that
is waiting, denied or expired in a loop; tell the user instead.
- 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
@@ -34,10 +32,6 @@ applies a policy, and asks a human to approve most requests.
- Prefer `status`, `logs` and `failed` to `slop ssh` for looking at a box: they don't wait for a
human.
- Every box command (`status`, `logs`, `failed`, `ssh`) also takes a container instead of a node,
as `<node>.container-<name>` (the name `slop deploy` takes, such as `host.container-web`). It
runs in the container as root, and `slop ssh` runs the command with `/bin/sh -l`. A lease for
the node doesn't cover its containers.
- Every box command also takes `--host <user>@<host> [-p <port>]` instead of a node, for hosts
outside the deploy nodes.
- `--json` prints structured results (such as `slop requests`) as JSON.
@@ -46,9 +40,7 @@ applies a policy, and asks a human to approve most requests.
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`).
- `slop ssh` reads all of its stdin (unless it's a terminal) before asking, and the approver sees
it with the command. It must be text, and the command and stdin together at most 32 KiB; copy
larger or binary files another way.
- `slop ssh` forwards stdin once the request is approved.
### Deploying
+6 -61
View File
@@ -10,7 +10,6 @@ use std::time::SystemTime;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::detail::{Detail, Section};
use crate::proto::ApprovedBy;
/// One line of the audit file.
@@ -41,14 +40,14 @@ pub enum Event {
requester: String,
op: String,
summary: String,
detail: Shown,
detail: String,
/// Agent-supplied.
label: Option<String>,
},
/// What approvers are shown once preparing a request (such as building a deploy) finished.
Prepared {
id: String,
detail: Shown,
detail: String,
},
Approved {
id: String,
@@ -78,11 +77,6 @@ pub enum Event {
Disconnected {
id: String,
},
/// The requester left while an operation that can't be stopped partway (a deploy's
/// activation) ran; the broker still waits for it and logs how it ended.
Detached {
id: String,
},
Finished {
id: String,
exit: i32,
@@ -101,39 +95,6 @@ impl Event {
}
}
/// What approvers were shown of a request. Records from before the broker kept the structure
/// have its text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Shown {
Detail(Detail),
Text(String),
}
impl Shown {
pub fn to_text(&self) -> String {
match self {
Shown::Detail(detail) => detail.to_text(),
Shown::Text(text) => text.clone(),
}
}
/// The structure, with old records' text as one text section.
pub fn to_detail(&self) -> Detail {
match self {
Shown::Detail(detail) => detail.clone(),
Shown::Text(text) if text.is_empty() => Detail::default(),
Shown::Text(text) => Detail { fields: vec![], sections: vec![Section::text("Text", text)] },
}
}
}
impl From<Detail> for Shown {
fn from(detail: Detail) -> Shown {
Shown::Detail(detail)
}
}
/// Request IDs are long; approvers type a prefix, and logs show the same.
pub fn short(id: &str) -> &str {
&id[..id.len().min(6)]
@@ -149,7 +110,7 @@ impl fmt::Display for Event {
}
Event::Request { id, requester, summary, detail, label, .. } => {
write!(f, "{} {requester} asks: {summary}", short(id))?;
if let Some(line) = detail.to_text().lines().next() {
if let Some(line) = detail.lines().next() {
write!(f, "; {line}")?;
}
if let Some(label) = label {
@@ -159,7 +120,7 @@ impl fmt::Display for Event {
}
Event::Prepared { id, detail } => {
write!(f, "{} ready for approval", short(id))?;
if let Some(line) = detail.to_text().lines().next() {
if let Some(line) = detail.lines().next() {
write!(f, "; {line}")?;
}
Ok(())
@@ -182,9 +143,6 @@ impl fmt::Display for Event {
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::Detached { id } => {
write!(f, "{} the requester disconnected; waiting for it to finish anyway", short(id))
}
Event::Finished { id, exit, seconds } => {
write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id))
}
@@ -199,7 +157,7 @@ impl Record {
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, .. } | Event::Prepared { detail, .. } = &self.event {
for line in detail.to_text().lines().skip(1) {
for line in detail.lines().skip(1) {
text += &format!("{:21}{line}\n", "");
}
}
@@ -282,7 +240,7 @@ mod tests {
requester: "slop-cannon".into(),
op: "ssh".into(),
summary: "ssh river".into(),
detail: Shown::Text("Command: a\nmore".into()),
detail: "Command: a\nmore".into(),
label: Some("why".into()),
},
};
@@ -292,17 +250,4 @@ mod tests {
\x20 more\n"
);
}
#[test]
fn keeps_what_approvers_saw_and_reads_old_text() {
let detail = Detail::code("Command", "uptime");
let event = Event::Prepared { id: "a".into(), detail: detail.clone().into() };
let line = serde_json::to_string(&event).unwrap();
assert_eq!(serde_json::from_str::<Event>(&line).unwrap(), event);
let old: Event = serde_json::from_str(r#"{"event":"prepared","id":"a","detail":"Command: uptime"}"#).unwrap();
let Event::Prepared { detail: old, .. } = old else { panic!("{old:?}") };
assert_eq!(old, Shown::Text("Command: uptime".into()));
assert_eq!(old.to_text(), detail.to_text());
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ use slop_broker::server::{self, Broker};
use slop_broker::{approve, web};
#[derive(Parser)]
#[command(version = slop_broker::VERSION, about = "Approval broker for coding agents")]
#[command(about = "Approval broker for coding agents")]
enum Command {
/// Run the broker.
Serve {
+4 -36
View File
@@ -10,7 +10,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use slop_broker::proto::{
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, MAX_SSH_SHOWN, OpResult, Operation,
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, OpResult, Operation,
PROTOCOL_VERSION, Query, Request, SecretFile, SecretOp, ServerMessage, Target as SecretTarget, decode, encode,
transport,
};
@@ -27,11 +27,8 @@ const GUIDE: &str = include_str!("../../slop-tools.md");
#[derive(Parser)]
#[command(
name = "slop",
version = slop_broker::VERSION,
about = "Ask the slop broker to run privileged operations",
after_help = "Requests wait for an approver for as long as the broker allows (it says how long);\n\
don't retry them in a loop.\n\
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, or broker in ~/.config/slop/config.toml, selects the broker:\n\
vsock:<cid>:<port>, unix:<path> or ssh:<destination>."
@@ -49,7 +46,7 @@ struct Cli {
#[derive(Args)]
struct Target {
/// Deploy node, a container on one (node.container-<name>), or user@host with --host.
/// Deploy node, or user@host with --host.
target: String,
/// Treat TARGET as user@host instead of a deploy node.
#[arg(long)]
@@ -65,12 +62,6 @@ impl Target {
if self.port.is_some() {
bail!("--port needs --host; deploy nodes use their configured port");
}
if let Some((node, profile)) = self.target.split_once('.') {
let name = profile.strip_prefix("container-").with_context(|| {
format!("{}: only containers can be named after a node (node.container-<name>)", self.target)
})?;
return Ok(Destination::Container { node: parse(node)?, name: parse(name)? });
}
return Ok(Destination::Node(parse::<NodeName>(&self.target)?));
}
@@ -91,7 +82,6 @@ enum Command {
#[command(flatten)]
target: Target,
/// Remote command, after `--`; joined with spaces and run by the remote shell, as ssh does.
/// Stdin, unless it's a terminal, is read in full first and shown to the approver.
#[arg(last = true)]
command: Vec<Arg>,
},
@@ -365,9 +355,7 @@ fn secret_operation(action: SecretCommand) -> Result<(Operation, Located)> {
fn operation(command: Command) -> Result<Operation> {
Ok(match command {
Command::Ssh { target, command } => {
Operation::Ssh { destination: target.destination()?, command, stdin: whole_stdin()? }
}
Command::Ssh { target, command } => Operation::Ssh { destination: target.destination()?, command },
Command::Status { target, unit } => {
Operation::Query { destination: target.destination()?, query: Query::Status { unit } }
}
@@ -382,26 +370,6 @@ fn operation(command: Command) -> Result<Operation> {
})
}
/// All of stdin, unless it's a terminal or empty, to send with the request.
fn whole_stdin() -> Result<Option<Vec<u8>>> {
use std::io::{IsTerminal, Read};
let stdin = std::io::stdin();
if stdin.is_terminal() {
return Ok(None);
}
let mut data = Vec::new();
stdin.lock().take(MAX_SSH_SHOWN as u64 + 1).read_to_end(&mut data).context("reading stdin")?;
if data.len() > MAX_SSH_SHOWN {
bail!(
"stdin is over {} KiB; approvers have to see all of it, so copy large files another way",
MAX_SSH_SHOWN / 1024
);
}
Ok((!data.is_empty()).then_some(data))
}
/// A full commit ID, from Git in the working directory unless it already is one.
fn resolve(revision: &str) -> Result<CommitId> {
if let Ok(commit) = revision.parse() {
+10 -55
View File
@@ -79,9 +79,6 @@ pub struct Node {
/// Only the node's own: the flake-wide ones usually name the operator's key.
pub ssh_opts: Vec<String>,
pub sudo: Option<String>,
/// Its profiles' names, such as `system` and `container-<name>`.
#[serde(default)]
pub profiles: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -106,9 +103,6 @@ pub struct SecretContext {
pub paths: Vec<String>,
/// The path's recipients in the branch's rules file, or `None` if it has no entry.
pub recipients: Option<Vec<String>>,
/// Keys by name, from SSH keys' comments anywhere in the rules file.
#[serde(default)]
pub names: BTreeMap<String, String>,
}
/// A commit as approvers see it before anything is built. Everything but `on_branch` is
@@ -284,19 +278,11 @@ async fn call<R: DeserializeOwned>(
// The builder's side
/// The forced command: one build per connection, one at a time. A broker whose builder has a
/// store of its own also reads built paths from it, as `nix-daemon --stdio` (`ssh-ng`).
/// The forced command: one build per connection, one at a time.
pub async fn worker(config: &Path) -> Result<()> {
let text = std::fs::read_to_string(config).with_context(|| format!("reading {}", config.display()))?;
let config: BuilderConfig = toml::from_str(&text)?;
if std::env::var("SSH_ORIGINAL_COMMAND").is_ok_and(|c| c == "nix-daemon --stdio") {
use std::os::unix::process::CommandExt;
let daemon = config.path.iter().map(|d| d.join("nix-daemon")).find(|p| p.exists());
let daemon = daemon.context("no nix-daemon in the builder's path")?;
return Err(std::process::Command::new(daemon).arg("--stdio").exec()).context("running nix-daemon");
}
let mut stdin = FramedRead::new(tokio::io::stdin(), codec());
let request: BuilderRequest = decode(&stdin.next().await.context("no request")??)?;
// Nothing else comes on stdin; it closing means the broker gave up.
@@ -468,10 +454,6 @@ async fn fetch_all(config: &BuilderConfig) -> Result<()> {
]))
.await
.context("fetching")?;
// Nix reads HEAD for a commit's flake; the mirror only has remote branches.
let branch = format!("refs/remotes/origin/{}", config.branch);
output(git(config, &repository).args(["symbolic-ref", "HEAD", &branch])).await?;
Ok(())
}
@@ -542,19 +524,7 @@ async fn secret_context(config: &BuilderConfig, request: &SecretRequest) -> Resu
let rules = rules(config, &commit, &request.rules).await?;
let recipients = rules.get(&*request.path).cloned();
let names = commented(rules.values().flatten());
Ok(SecretContext { branch: config.branch.clone(), commit, paths, recipients, names })
}
/// SSH keys by their comments, like `ssh-ed25519 AAAA… shill`; age ignores the comment.
fn commented<'a>(keys: impl Iterator<Item = &'a String>) -> BTreeMap<String, String> {
keys.filter_map(|key| match key.split_whitespace().collect::<Vec<_>>().as_slice() {
[kind, key, comment @ ..] if kind.starts_with("ssh-") && !comment.is_empty() => {
Some((comment.join(" "), format!("{kind} {key}")))
}
_ => None,
})
.collect()
Ok(SecretContext { branch: config.branch.clone(), commit, paths, recipients })
}
/// Paths in `git ls-tree -r -z` output whose object is `blob`.
@@ -609,8 +579,7 @@ async fn rules(config: &BuilderConfig, commit: &CommitId, rules: &RulesPath) ->
async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
let commit = branch_tip(config).await?;
let cache = config.directory.join("deploy-nodes");
// Named for what's evaluated, so a broker reading more evaluates again.
let file = cache.join(format!("{commit}.profiles.json"));
let file = cache.join(format!("{commit}.json"));
if let Ok(text) = std::fs::read_to_string(&file) {
return Ok(Nodes { commit, nodes: serde_json::from_str(&text)? });
}
@@ -622,7 +591,6 @@ async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
sshUser = n.sshUser or d.sshUser or null; \
sshOpts = n.sshOpts or [ ]; \
sudo = n.sudo or d.sudo or null; \
profiles = builtins.attrNames (n.profiles or { }); \
}) d.nodes";
let evaluated = output(
command(config, "nix")
@@ -697,28 +665,15 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResu
#[derive(Deserialize)]
struct Built {
#[serde(rename = "drvPath")]
drv_path: String,
outputs: BTreeMap<String, String>,
}
let mut built: Vec<Built> = serde_json::from_slice(&built.stdout).context("reading nix build's result")?;
// One result per installable, in order, except that some versions of Nix repeat the results
// of installables that are the same derivation; then they're matched by derivation.
if built.len() != installables.len() {
let mut matched = Vec::new();
for installable in &installables {
let drv_path = output(
command(config, "nix").args(["eval", "--raw"]).args(NIX_OPTIONS).arg(format!("{installable}.drvPath")),
)
.await
.with_context(|| format!("finding the derivation of {installable}"))?;
let result = built.iter().find(|b| b.drv_path == drv_path.trim());
let result = result.with_context(|| format!("nix build returned nothing for {installable}"))?;
matched.push(Built { drv_path: result.drv_path.clone(), outputs: result.outputs.clone() });
}
built = matched;
}
let built: Vec<Built> = serde_json::from_slice(&built.stdout).context("reading nix build's result")?;
ensure!(
built.len() == installables.len(),
"nix build returned {} results for {} installables",
built.len(),
installables.len()
);
let (built_profiles, built_attrs) = built.split_at(profiles.len());
for (profile, built) in profiles.iter_mut().zip(built_profiles) {
profile.path = built.outputs.get("out").context("no out output")?.clone();
+1 -64
View File
@@ -124,32 +124,6 @@ pub struct DeployConfig {
pub cache: PathBuf,
}
impl DeployConfig {
/// The builder's store, which built paths are copied from, as a `nix` store URL reached with
/// the broker's `key`; the builder's forced command serves it. That works whether the builder
/// is on this box (the same store) or another. The port is always given: it comes after
/// `NIX_SSHOPTS`, so a node's `-p` can't send the builder's connection elsewhere when one copy
/// uses both.
pub fn builder_store(&self, key: &Path) -> anyhow::Result<String> {
let builder = &self.builder;
let port: u16 = match builder.ssh_opts.as_slice() {
[] => 22,
[flag, port] if flag == "-p" => port.parse().context("the builder's port")?,
_ => anyhow::bail!("the builder's ssh_opts can only set a port (-p <port>)"),
};
let host =
if builder.hostname.contains(':') { format!("[{}]", builder.hostname) } else { builder.hostname.clone() };
let key = credential(key);
let key = key.to_str().context("the SSH key's path isn't UTF-8")?;
anyhow::ensure!(
!key.contains(|c: char| c.is_whitespace() || "?&#%".contains(c)),
"the SSH key's path can't go in a store URL: {key}"
);
Ok(format!("ssh-ng://{}@{host}:{port}?ssh-key={key}", builder.user))
}
}
/// The binary cache that `slop build` pushes to: a Nix store reached over SSH (`ssh-ng`), whose
/// key's forced command allows only the store protocol and adding GC roots. Needs `deploy`, whose
/// builder it uses.
@@ -236,9 +210,6 @@ pub struct SshTarget {
/// How `user` becomes root, followed by the user name (deploy-rs's `sudo`); nodes only.
#[serde(default = "default_sudo")]
pub sudo: String,
/// The containers on it that requests can name; nodes only.
#[serde(default)]
pub containers: std::collections::BTreeSet<String>,
}
/// deploy-rs's default.
@@ -338,9 +309,6 @@ impl Config {
self.ssh.is_none() || self.deploy.is_some(),
"ssh needs deploy, whose builder reads the main branch's deploy-rs nodes"
);
if let (Some(ssh), Some(deploy)) = (&self.ssh, &self.deploy) {
deploy.builder_store(&ssh.key)?;
}
Ok(())
}
@@ -418,38 +386,7 @@ mod tests {
let rules = &mut misspelt.policies.get_mut("agent").unwrap().ops.get_mut(&OpName::Ssh).unwrap().rules;
rules[0].matches = BTreeMap::from([("node".to_owned(), "river".to_owned())]);
let error = misspelt.validate().unwrap_err().to_string();
assert!(
error.contains("ssh rules can't match \"node\"; its fields are target, container, host, port"),
"{error}"
);
}
#[test]
fn builder_stores() {
let builder = |hostname: &str, ssh_opts: &[&str]| SshTarget {
hostname: hostname.into(),
user: "build".into(),
ssh_opts: ssh_opts.iter().map(|o| o.to_string()).collect(),
sudo: default_sudo(),
containers: Default::default(),
};
let deploy = |builder| DeployConfig { builder, nix: "/nix".into(), cache: "/cache".into() };
let key = Path::new("/run/key");
assert_eq!(
deploy(builder("localhost", &["-p", "2222"])).builder_store(key).unwrap(),
"ssh-ng://build@localhost:2222?ssh-key=/run/key"
);
assert_eq!(
deploy(builder("builder.example", &[])).builder_store(key).unwrap(),
"ssh-ng://build@builder.example:22?ssh-key=/run/key"
);
assert_eq!(
deploy(builder("fd00::1", &["-p", "22"])).builder_store(key).unwrap(),
"ssh-ng://build@[fd00::1]:22?ssh-key=/run/key"
);
assert!(deploy(builder("b", &["-o", "ProxyJump=x"])).builder_store(key).is_err());
assert!(deploy(builder("b", &[])).builder_store(Path::new("/run/a key")).is_err());
assert!(error.contains("ssh rules can't match \"node\"; its fields are target, host, port"), "{error}");
}
#[test]
+2 -2
View File
@@ -1,6 +1,6 @@
//! What approvers are shown of a request: fields, then tables, lists and text. Operations build
//! it; every surface renders it. The web app shows the structure (also in the audit history,
//! which keeps it), the others [`Detail::to_text`], which passkey confirmations fingerprint.
//! it; every surface renders it. The web app shows the structure, the others [`Detail::to_text`],
//! which is also what the audit log keeps and passkey confirmations fingerprint.
//!
//! The structure is the same for every operation, so surfaces don't need to know any of them.
//! All of it can carry agent-written text, which every surface makes printable when it shows it.
+17 -13
View File
@@ -1,5 +1,5 @@
//! Runs processes for approved requests, wired to the requester's stdout and stderr (carried as
//! messages).
//! 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;
@@ -30,9 +30,8 @@ impl Output {
/// The requester's side of an approved operation.
pub struct Io {
/// Chunks of the requester's stdin, which it sends after approval for operations that ask for
/// it; closed at EOF.
pub stdin: mpsc::UnboundedReceiver<Vec<u8>>,
/// 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,
@@ -43,11 +42,11 @@ pub fn exit_code(status: ExitStatus) -> i32 {
status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0))
}
/// Runs `command` in its own process group with the requester's stdout and stderr, and `stdin` (or
/// none) as its whole input. If the requester goes away, the whole group is terminated.
pub async fn run(mut command: Command, io: &mut Io, stdin: Option<&[u8]>) -> Result<i32> {
/// 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 stdin.is_some() { Stdio::piped() } else { Stdio::null() })
.stdin(if with_stdin { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
@@ -59,12 +58,17 @@ pub async fn run(mut command: Command, io: &mut Io, stdin: Option<&[u8]>) -> Res
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));
// Closing the pipe once it's written is the end of the input.
let child_stdin = child.stdin.take();
let mut child_stdin = child.stdin.take();
let stdin_rx = &mut io.stdin;
let feed = async move {
if let (Some(mut pipe), Some(data)) = (child_stdin, stdin) {
let _ = pipe.write_all(data).await;
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);
-7
View File
@@ -15,10 +15,3 @@ pub mod server;
pub mod targets;
pub mod types;
pub mod web;
/// The version, like `0.3.0+2d59b59`: Nix builds add the commit they're built from (with `-dirty`
/// for uncommitted changes) in `SLOP_BROKER_VERSION`.
pub const VERSION: &str = match option_env!("SLOP_BROKER_VERSION") {
Some(version) => version,
None => env!("CARGO_PKG_VERSION"),
};
+3 -14
View File
@@ -70,7 +70,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?;
let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect();
let sizes = closure_sizes(ssh, deploy, &paths, &io.cancel).await?;
let sizes = closure_sizes(deploy, &paths, &io.cancel).await?;
let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?;
let mut detail = Detail::new();
@@ -135,13 +135,10 @@ fn copy_command(ssh: &SshConfig, deploy: &DeployConfig, cache: &CacheConfig, pat
let options = nix_ssh_options(ssh::options_with_key(ssh, &cache.key), &cache.ssh_opts);
ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy");
let from = deploy.builder_store(&ssh.key)?;
let mut command = nix(deploy, ssh.ssh.parent());
command
.env("NIX_SSHOPTS", options.join(" "))
.args(["--extra-experimental-features", "nix-command", "copy", "--no-check-sigs"])
.args(["--from", &from])
.arg("--to")
.arg(format!("ssh-ng://{}@{}", cache.user, cache.hostname))
.args(paths);
@@ -159,17 +156,14 @@ fn nix(deploy: &DeployConfig, ssh_directory: Option<&Path>) -> Command {
command
}
/// Each path's closure size, human-readable, from the builder's store.
/// Each path's closure size, human-readable, from the local store.
async fn closure_sizes(
ssh: &SshConfig,
deploy: &DeployConfig,
paths: &[&str],
cancel: &CancellationToken,
) -> Result<Vec<(String, String)>> {
let mut command = nix(deploy, ssh.ssh.parent());
command.env("NIX_SSHOPTS", nix_ssh_options(ssh::options(ssh), &[]).join(" "));
let mut command = nix(deploy, None);
command.args(["--extra-experimental-features", "nix-command", "path-info", "--closure-size", "--human-readable"]);
command.args(["--store", &deploy.builder_store(&ssh.key)?]);
command.args(paths);
let (exit, stdout, stderr) = exec::capture(command, cancel).await?;
@@ -225,11 +219,6 @@ mod tests {
assert!(options.contains("-i /cache-key") && options.ends_with("-p 2222"), "{options}");
assert!(!options.contains("PermitLocalCommand=no"), "{options}");
assert!(args(&copy).contains(&"ssh-ng://harmonia@object.example".to_owned()));
// From the builder's store, with the broker's key
let copy = args(&copy);
let from = copy.iter().position(|a| a == "--from").unwrap();
assert_eq!(copy[from + 1], "ssh-ng://deploy@river.example.org:2222?ssh-key=/key");
}
#[test]
+23 -94
View File
@@ -13,7 +13,6 @@ use anyhow::{Context, Result, bail, ensure};
use futures_util::future::join_all;
use serde_json::json;
use tokio::process::Command;
use tokio_util::sync::CancellationToken;
use super::{Parsed, shell_quote, ssh};
use crate::builder::{self, BuildRequest, BuiltProfile};
@@ -118,22 +117,17 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
Ok(())
}
/// Activates every node; its transient units are named after the request `id`, so its audit
/// record leads to their journals. It ignores the requester leaving (see
/// [`super::outlives_requester`]).
pub async fn execute(broker: &Broker, id: &str, parsed: &Parsed, io: &mut Io) -> Result<i32> {
pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<i32> {
let Operation::Deploy { boot, .. } = &parsed.operation else { unreachable!() };
let (ssh, _) = configs(broker)?;
let ssh = &*ssh;
let built = parsed.prepared.build.as_ref().context("nothing was built")?;
// Never cancelled: activations run to the end, and their output is dropped once the
// requester has gone.
let never = CancellationToken::new();
let (out, cancel) = (&io.out, &never);
let run = &crate::queue::new_id();
let (out, cancel) = (&io.out, &io.cancel);
let results = join_all(group(&built.profiles).into_iter().map(|(node, profiles)| async move {
for profile in profiles {
let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, id)?)];
let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, run)?)];
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &remote)?;
let prefix = format!("[{node}.{}] ", profile.profile);
@@ -177,14 +171,12 @@ async fn copy(
node: &str,
profiles: &[&BuiltProfile],
out: &Output,
cancel: &CancellationToken,
cancel: &tokio_util::sync::CancellationToken,
) -> Result<()> {
let target = ssh::target(ssh, node)?;
let options = copy_options(ssh, node)?;
ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy");
let from = deploy.builder_store(&ssh.key)?;
let ssh_directory = ssh.ssh.parent().map(|p| p.display().to_string()).unwrap_or_default();
let mut command = Command::new(&deploy.nix);
command
@@ -200,7 +192,6 @@ async fn copy(
"--no-check-sigs",
"--substitute-on-destination",
])
.args(["--from", &from])
.arg("--to")
.arg(format!("ssh://{}@{}", target.user, target.hostname))
.args(profiles.iter().map(|p| &p.path));
@@ -231,7 +222,12 @@ pub(super) fn nix_ssh_options(mut options: Vec<String>, extra: &[String]) -> Vec
/// Compares a profile on a node with the new one; see the script for its output.
const INSPECT: &str = include_str!("inspect.sh");
async fn inspect(ssh: &SshConfig, node: &str, profile: &BuiltProfile, cancel: &CancellationToken) -> Result<Changes> {
async fn inspect(
ssh: &SshConfig,
node: &str,
profile: &BuiltProfile,
cancel: &tokio_util::sync::CancellationToken,
) -> Result<Changes> {
let words = ["bash", "-c", INSPECT, "bash", &profile.profile_path, &profile.path];
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &[shell_quote(&words)])?;
@@ -242,16 +238,11 @@ async fn inspect(ssh: &SshConfig, node: &str, profile: &BuiltProfile, cancel: &C
Ok(Changes::parse(&String::from_utf8_lossy(&stdout)))
}
/// Runs its arguments with their output to stdout until that breaks, then to nowhere, so a lost
/// connection can't stop an activation halfway: `activate-rs` panics when it can't write.
const UNTIL_DISCONNECTED: &str = r#"set -o pipefail; "$@" 2>&1 | { cat || cat >/dev/null; }"#;
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, id: &str) -> Result<Vec<String>> {
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, run: &str) -> Result<Vec<String>> {
let mut words: Vec<String> = ssh::target(ssh, node)?.sudo.split_whitespace().map(Into::into).collect();
words.push("root".into());
// A transient unit, so activation finishes even if this connection drops or the process
// running it is killed
// A transient unit, so activation finishes even if this connection drops
words.extend(
[
"/run/current-system/sw/bin/systemd-run",
@@ -264,8 +255,7 @@ fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: b
]
.map(Into::into),
);
words.push(format!("--unit=slop-deploy-{id}-{}", profile.profile));
words.extend(["/run/current-system/sw/bin/bash", "-c", UNTIL_DISCONNECTED, "slop-deploy"].map(Into::into));
words.push(format!("--unit=slop-deploy-{}-{}", &run[..8], profile.profile));
// What deploy-rs runs, without magic rollback
words.push(format!("{}/activate-rs", profile.path));
@@ -418,35 +408,14 @@ impl Changes {
/// A line of `nix store diff-closures` (`name: 1.0 → 1.1, +3.4 KiB`) as package, version change
/// and size change.
fn package_cells(line: &str) -> [String; 3] {
let Some((name, rest)) = line.split_once(": ") else { return [line.into(), String::new(), String::new()] };
if let Some((version, size)) = rest.rsplit_once(", ")
&& let Some(size) = package_size(size)
{
return [name.into(), version.into(), size];
fn package_cells(line: &str) -> [&str; 3] {
let Some((name, rest)) = line.split_once(": ") else { return [line, "", ""] };
let is_size = |s: &str| s.starts_with(['+', '-']);
match rest.rsplit_once(", ") {
Some((version, size)) if is_size(size) => [name, version, size],
_ if is_size(rest) => [name, "", rest],
_ => [name, rest, ""],
}
if let Some(size) = package_size(rest) {
return [name.into(), "unchanged".into(), size];
}
[name.into(), rest.into(), String::new()]
}
/// A size change, signed. Nix versions differ: some sign increases, some only colour them (even
/// on piped output), and some do neither; decreases always have a sign.
fn package_size(value: &str) -> Option<String> {
let plain = value
.strip_prefix("\x1b[31;1m")
.or_else(|| value.strip_prefix("\x1b[32;1m"))
.and_then(|size| size.strip_suffix("\x1b[0m"))
.unwrap_or(value);
let (sign, size) = match plain.strip_prefix(['+', '-']) {
Some(size) => (&plain[..1], size),
None => ("+", plain),
};
let (number, unit) = size.split_once(' ')?;
let sized = number.parse::<f64>().is_ok() && ["B", "KiB", "MiB", "GiB", "TiB"].contains(&unit);
sized.then(|| format!("{sign}{size}"))
}
#[cfg(test)]
@@ -456,15 +425,7 @@ mod tests {
#[test]
fn splits_package_lines() {
assert_eq!(package_cells("a: 1.0 → 1.1, +3.4 KiB"), ["a", "1.0 → 1.1", "+3.4 KiB"]);
assert_eq!(package_cells("b: -12.0 KiB"), ["b", "unchanged", "-12.0 KiB"]);
assert_eq!(package_cells("b: \x1b[31;1m12.0 KiB\x1b[0m"), ["b", "unchanged", "+12.0 KiB"]);
assert_eq!(package_cells("b: 12.0 KiB"), ["b", "unchanged", "+12.0 KiB"]);
assert_eq!(
package_cells("slop: 0.1.0, 0.1.0-fish → 0.2.0, 0.2.0-fish, 129.0 KiB"),
["slop", "0.1.0, 0.1.0-fish → 0.2.0, 0.2.0-fish", "+129.0 KiB"]
);
assert_eq!(package_cells("c: 1.0, 2 KiB → 1.1"), ["c", "1.0, 2 KiB → 1.1", ""]);
assert_eq!(package_cells("b: 1.0 → 1.1, \x1b[32;1m-12.0 KiB\x1b[0m"), ["b", "1.0 → 1.1", "-12.0 KiB"]);
assert_eq!(package_cells("b: -12.0 KiB"), ["b", "", "-12.0 KiB"]);
assert_eq!(package_cells("c: ∅ → 2.0"), ["c", "∅ → 2.0", ""]);
assert_eq!(package_cells("odd"), ["odd", "", ""]);
}
@@ -528,39 +489,7 @@ mod tests {
};
let words = activate_command(&config, "river", &profile, true, "0123456789abcdef").unwrap();
assert_eq!(&words[..3], ["doas", "-u", "root"]);
assert!(words.contains(&"--unit=slop-deploy-0123456789abcdef-system".to_owned()));
assert!(words.contains(&"--unit=slop-deploy-01234567-system".to_owned()));
assert_eq!(words.last().unwrap(), "--boot");
}
#[test]
fn activation_outlives_its_output() {
use std::io::Read;
use std::process::{Command, Stdio};
let directory = tempfile::tempdir().unwrap();
let marker = directory.path().join("finished");
let activation = format!("sleep 0.5; for i in $(seq 1000); do echo line $i; done; touch {}", marker.display());
// The connection's end of the output closes before the activation writes anything.
let mut child = Command::new("bash")
.args(["-c", UNTIL_DISCONNECTED, "slop-deploy", "bash", "-c", &activation])
.stdout(Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take());
assert!(child.wait().unwrap().success());
assert!(marker.exists());
// While it's there, output goes through.
let mut child = Command::new("bash")
.args(["-c", UNTIL_DISCONNECTED, "slop-deploy", "sh", "-c", "echo out; echo err >&2; exit 3"])
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut output = String::new();
child.stdout.take().unwrap().read_to_string(&mut output).unwrap();
assert_eq!(output, "out\nerr\n");
assert_eq!(child.wait().unwrap().code(), Some(3));
}
}
+24 -48
View File
@@ -7,7 +7,7 @@ use crate::builder::Description;
use crate::detail::{Detail, Field, Section, Tone};
use crate::exec::Io;
use crate::policy::{Limits, OpName};
use crate::proto::{Destination, LeaseSummary, OpResult, Operation, PendingSummary};
use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary};
use crate::server::Broker;
use crate::types::CommitId;
@@ -100,17 +100,15 @@ fn fields_known(parsed: &Parsed) -> bool {
fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
match &operation {
Operation::Ssh { destination, command, stdin } => {
Operation::Ssh { destination, command } => {
let config = &broker.targets.ssh()?;
ssh::check(config, destination)?;
let shown =
if command.is_empty() { "(no command)".to_owned() } else { truncate(&shell_quote(command), 1000) };
let summary = format!("ssh {}", ssh::describe(destination));
let mut detail = ssh::detail(command, stdin.as_deref())?;
if let Destination::Container { node, name } = destination {
let how = format!("as root, by /bin/sh -l in the container (systemd-run --machine={name} on {node})");
detail.field(Field::new("Runs", how));
}
Ok(Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation))
let detail = Detail::code("Command", shown);
Ok(Parsed { stdin: true, ..Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation) })
}
Operation::Query { destination, query } => {
let config = &broker.targets.ssh()?;
@@ -119,7 +117,7 @@ fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
scope.insert("query".into(), Value::from(query::name(query)));
let summary = format!("{} on {}", query::name(query), ssh::describe(destination));
let detail = Detail::code("Command", shell_quote(&query::remote_command(config, destination, query)?));
let detail = Detail::code("Command", shell_quote(&query::remote_command(query)));
Ok(Parsed::new(OpName::Query, scope, summary, detail, operation))
}
Operation::Deploy { .. } => deploy::plan(broker, operation),
@@ -148,12 +146,6 @@ fn commit(operation: &Operation) -> Result<&CommitId> {
}
}
/// Operations that carry on when their requester leaves, since stopping them partway would leave
/// boxes half changed: the broker waits for them and logs how they ended.
pub fn outlives_requester(parsed: &Parsed) -> bool {
matches!(parsed.operation, Operation::Deploy { .. })
}
/// Fetches and describes the commit an operation builds; runs only Git.
pub async fn describe(broker: &Broker, parsed: &Parsed, io: &Io) -> Result<Description> {
let commit = commit(&parsed.operation)?;
@@ -212,18 +204,17 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
}
}
/// Runs an approved request; `id` is its ID.
pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed, io: &mut Io) -> Result<Outcome> {
pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut Io) -> Result<Outcome> {
match parsed.operation {
Operation::Deploy { .. } => return deploy::execute(broker, id, &parsed, io).await.map(Into::into),
Operation::Deploy { .. } => return deploy::execute(broker, &parsed, io).await.map(Into::into),
Operation::Build { .. } => return build::execute(broker, &parsed, io).await.map(Into::into),
Operation::Secret(_) => return secret::execute(broker, &parsed, io).await,
_ => {}
}
match parsed.operation {
Operation::Ssh { destination, command, stdin } => {
ssh::execute(broker, &destination, &command, stdin.as_deref(), io).await.map(Into::into)
Operation::Ssh { destination, command } => {
ssh::execute(broker, &destination, &command, io).await.map(Into::into)
}
Operation::Query { destination, query } => {
query::execute(broker, &destination, &query, io).await.map(Into::into)
@@ -248,34 +239,20 @@ pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed,
}
}
/// Quotes words for a POSIX shell or `fish`, for showing commands and for remote commands built
/// here. `fish` reads `\\` and `\'` as escapes even in single quotes, so quotes and backslashes are
/// escaped outside them, which both read the same way.
/// 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| quote_word(w.as_ref())).collect::<Vec<_>>().join(" ")
}
fn quote_word(word: &str) -> String {
if !word.is_empty() && word.bytes().all(|c| c.is_ascii_alphanumeric() || b"_-./=:@%+,".contains(&c)) {
return word.to_owned();
}
let (mut quoted, mut open) = (String::new(), false);
for c in word.chars() {
let escaped = matches!(c, '\'' | '\\');
if escaped == open {
quoted.push('\'');
open = !open;
}
if escaped {
quoted.push('\\');
}
quoted.push(c);
}
if open {
quoted.push('\'');
}
if quoted.is_empty() { "''".into() } else { quoted }
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,
@@ -338,6 +315,5 @@ mod tests {
#[test]
fn quotes_for_the_shell() {
assert_eq!(shell_quote(&["systemctl", "status", "a b", "it's", ""]), r"systemctl status 'a b' 'it'\''s' ''");
assert_eq!(shell_quote(&[r"a\\b", "'", r"\x2d"]), r"'a'\\\\'b' \' \\'x2d'");
}
}
+8 -42
View File
@@ -1,9 +1,8 @@
//! Fixed read-only queries on boxes and their containers over SSH. The broker builds and quotes
//! the remote command from validated values, so policy can safely approve these by itself.
//! Fixed read-only queries on boxes over SSH. The broker builds and quotes the remote command
//! from validated values, so policy can safely approve these by itself.
use anyhow::Result;
use super::{shell_quote, ssh};
use crate::config::SshConfig;
use crate::exec::{self, Io};
use crate::proto::{Destination, Query};
use crate::server::Broker;
@@ -16,20 +15,7 @@ pub fn name(query: &Query) -> &'static str {
}
}
/// The command to run on the destination's box. A container's runs on its host, as root, with
/// `--machine`.
pub fn remote_command(config: &SshConfig, destination: &Destination, query: &Query) -> Result<Vec<String>> {
match destination {
Destination::Container { node, name } => {
let mut words = command(query);
words.insert(1, format!("--machine={name}"));
ssh::as_root(config, node, words)
}
_ => Ok(command(query)),
}
}
fn command(query: &Query) -> Vec<String> {
pub fn remote_command(query: &Query) -> Vec<String> {
let mut words: Vec<String> = match query {
Query::Status { .. } => vec!["systemctl".into(), "status".into(), "--no-pager".into()],
Query::Failed => vec!["systemctl".into(), "list-units".into(), "--failed".into(), "--no-pager".into()],
@@ -52,8 +38,8 @@ fn command(query: &Query) -> Vec<String> {
pub async fn execute(broker: &Broker, destination: &Destination, query: &Query, io: &mut Io) -> Result<i32> {
let config = broker.targets.ssh()?;
// One quoted string, so the remote login shell (POSIX or fish) sees exactly these words.
let remote = [shell_quote(&remote_command(&config, destination, query)?)];
exec::run(ssh::command(&config, destination, &remote)?, io, None).await
let remote = [shell_quote(&remote_command(query))];
exec::run(ssh::command(&config, destination, &remote)?, io, false).await
}
#[cfg(test)]
@@ -69,31 +55,11 @@ mod tests {
since: Some("2026-01-31 12:00".parse().unwrap()),
};
assert_eq!(
shell_quote(&command(&logs)),
shell_quote(&remote_command(&logs)),
"journalctl --no-pager --output=short-iso --lines=50 '--since=2026-01-31 12:00' --unit=nginx.service"
);
let status = Query::Status { unit: Some("nginx.service".parse().unwrap()) };
assert_eq!(shell_quote(&command(&status)), "systemctl status --no-pager -- nginx.service");
assert_eq!(shell_quote(&command(&Query::Failed)), "systemctl list-units --failed --no-pager");
}
#[test]
fn container_commands_run_on_the_host_as_root() {
let config = ssh::tests::config();
let node = Destination::Node("river".parse().unwrap());
let web = Destination::Container { node: "river".parse().unwrap(), name: "web".parse().unwrap() };
let status = Query::Status { unit: Some("nginx.service".parse().unwrap()) };
assert_eq!(shell_quote(&remote_command(&config, &node, &status).unwrap()), shell_quote(&command(&status)));
assert_eq!(
shell_quote(&remote_command(&config, &web, &status).unwrap()),
"doas -u root systemctl --machine=web status --no-pager -- nginx.service"
);
let logs =
Query::Logs { unit: "nginx.service".parse().unwrap(), lines: Lines::try_from(5).unwrap(), since: None };
assert_eq!(
shell_quote(&remote_command(&config, &web, &logs).unwrap()),
"doas -u root journalctl --machine=web --no-pager --output=short-iso --lines=5 --unit=nginx.service"
);
assert_eq!(shell_quote(&remote_command(&status)), "systemctl status --no-pager -- nginx.service");
assert_eq!(shell_quote(&remote_command(&Query::Failed)), "systemctl list-units --failed --no-pager");
}
}
+1 -22
View File
@@ -152,8 +152,7 @@ fn describe(op: &SecretOp, context: &SecretContext, config: &SecretsConfig, own:
if let Some(requested) = op.recipients() {
let (recipients, added) = with_own(requested, own);
let rules = &config.rules;
let names = names(config, context);
let label = |r: &Recipient| label(r, &names);
let label = |r: &Recipient| label(r, &config.names);
let rows: Vec<Row> = match context.recipients.as_ref().map(|keys| expected(keys)) {
Some(expected) => {
@@ -217,17 +216,6 @@ fn same(a: &[Recipient], b: &[Recipient]) -> bool {
a.iter().all(|r| b.contains(r)) && b.iter().all(|r| a.contains(r))
}
/// The configured names, then the comments on the main branch's keys.
fn names(config: &SecretsConfig, context: &SecretContext) -> BTreeMap<String, Recipient> {
let mut names = config.names.clone();
for (name, key) in &context.names {
if let Ok(key) = Recipient::normalize(key) {
names.entry(name.clone()).or_insert(key);
}
}
names
}
fn label(recipient: &Recipient, names: &BTreeMap<String, Recipient>) -> String {
names.iter().find(|(_, r)| *r == recipient).map_or_else(|| recipient.abbreviated(), |(name, _)| name.clone())
}
@@ -424,7 +412,6 @@ mod tests {
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
paths: paths.iter().map(|p| p.to_string()).collect(),
recipients,
names: BTreeMap::new(),
}
}
@@ -541,14 +528,6 @@ mod tests {
let (detail, sensitive) = describe(&set(vec![dev.clone()]), &context(&[], None), &config, &own);
assert!(sensitive && detail.to_text().contains("isn't in secrets.nix"), "{}", detail.to_text());
// The main branch's key comments name recipients, though not over the configured names.
let mut named = context(&[], Some(vec![dev.to_string()]));
named.names = BTreeMap::from([("box".into(), host.to_string()), ("not-dev".into(), dev.to_string())]);
named.names.insert("bad".into(), "nonsense".into());
let (detail, _) = describe(&set(vec![host.clone(), dev.clone()]), &named, &config, &own);
let labels: Vec<_> = statuses(&detail).into_iter().map(|(label, ..)| label).collect();
assert_eq!(labels, ["box".to_owned(), "dev".to_owned(), own.abbreviated()]);
}
/// Each recipient row's key, status and tone.
+10 -128
View File
@@ -1,37 +1,28 @@
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes, containers on
//! them, or explicit `user@host`s.
use anyhow::{Context, Result, bail};
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes or explicit
//! `user@host`s.
use anyhow::{Result, bail};
use serde_json::{Map, Value, json};
use tokio::process::Command;
use crate::config::{SshConfig, SshTarget, credential};
use crate::detail::{Detail, Field, Section};
use crate::exec::{self, Io};
use crate::proto::{Destination, MAX_SSH_SHOWN};
use crate::proto::Destination;
use crate::server::Broker;
use crate::types::{Arg, ContainerName};
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 Some(node) = destination.node()
if let Destination::Node(node) = destination
&& !config.targets.contains_key(&**node)
{
bail!("unknown node {node}; nodes are the main branch's deploy-rs nodes, and --host reaches other boxes");
}
if let Destination::Container { node, name } = destination
&& !config.targets[&**node].containers.contains(&**name)
{
bail!("unknown container {node}.container-{name}; containers are a node's container-* deploy-rs profiles");
}
Ok(())
}
/// What an approval covers. A container's has the node as `target`, so rules for a node apply
/// to its containers too, but leases for one don't cover the other.
pub fn scope(destination: &Destination) -> Map<String, Value> {
let value = match destination {
Destination::Node(node) => json!({ "target": node }),
Destination::Container { node, name } => json!({ "target": node, "container": name }),
Destination::Host { user, host, port } => json!({ "host": format!("{user}@{host}"), "port": port.get() }),
};
value.as_object().unwrap().clone()
@@ -40,78 +31,10 @@ pub fn scope(destination: &Destination) -> Map<String, Value> {
pub fn describe(destination: &Destination) -> String {
match destination {
Destination::Node(node) => node.to_string(),
Destination::Container { node, name } => format!("{node}.container-{name}"),
Destination::Host { user, host, port } => format!("{user}@{host} port {port} (host)"),
}
}
/// The words that run `words` as root on a node: its `sudo` (deploy-rs's, such as `sudo -u`)
/// and `root`. Commands for its containers go through `systemd-machined`, which needs root.
pub fn as_root(config: &SshConfig, node: &str, words: impl IntoIterator<Item = String>) -> Result<Vec<String>> {
let mut all: Vec<String> = target(config, node)?.sudo.split_whitespace().map(Into::into).collect();
all.push("root".into());
all.extend(words);
Ok(all)
}
/// The command on the host that runs `line` in container `name` as root, with a login shell
/// the way `ssh` runs it on a node: stdin, output and the exit status pass through.
pub fn container_shell(config: &SshConfig, node: &str, name: &ContainerName, line: &str) -> Result<Vec<String>> {
let mut words: Vec<String> = [
"systemd-run",
&format!("--machine={name}"),
"--quiet",
"--wait",
"--collect",
"--pipe",
"--expand-environment=no",
"--",
"/bin/sh",
"-l",
]
.map(Into::into)
.into();
if !line.is_empty() {
words.extend(["-c".into(), line.into()]);
}
as_root(config, node, words)
}
/// What approvers see: the line the remote shell runs and all of its stdin, in full, since nothing
/// else reaches the box. Requests too long to show whole are refused.
pub fn detail(command: &[Arg], stdin: Option<&[u8]>) -> Result<Detail> {
// `ssh` joins the words with spaces, unquoted, and the remote shell runs the result.
let line = command.iter().map(|w| &**w).collect::<Vec<_>>().join(" ");
let stdin =
stdin.map(std::str::from_utf8).transpose().context("stdin isn't UTF-8 text; approvers have to read it")?;
let size = line.len() + stdin.map_or(0, str::len);
if size > MAX_SSH_SHOWN {
bail!(
"the command and its stdin are over {} KiB; approvers have to see all of them, so copy large files another way",
MAX_SSH_SHOWN / 1024
);
}
let mut detail = Detail::new();
if line.is_empty() {
let shown = if stdin.is_some() { "(none: the login shell runs stdin)" } else { "(none)" };
detail.field(Field::new("Command", shown));
} else if line.contains('\n') || line.chars().count() > 200 {
detail.section(Section::text("Command", &line));
} else {
detail.field(Field::new("Command", &line).code());
}
if let Some(stdin) = stdin {
// A field as well as the text, so it shows where sections are folded away.
let lines = stdin.lines().count();
detail.field(Field::new("Stdin", format!("{lines} lines, {} bytes", stdin.len())));
detail.section(Section::text("Stdin", stdin));
}
Ok(detail)
}
/// Options for every connection; they come before any from target config, so they win.
pub fn options(config: &SshConfig) -> Vec<String> {
options_with_key(config, &config.key)
@@ -148,7 +71,7 @@ pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, rem
command.arg("-T").args(options(config));
match destination {
Destination::Node(node) | Destination::Container { node, .. } => {
Destination::Node(node) => {
let target = target(config, node)?;
command.args(&target.ssh_opts).args(["-l", &target.user, "--", &target.hostname]);
}
@@ -177,24 +100,9 @@ pub fn command_to<S: AsRef<str>>(config: &SshConfig, target: &SshTarget, remote:
command
}
pub async fn execute(
broker: &Broker,
destination: &Destination,
remote: &[Arg],
stdin: Option<&[u8]>,
io: &mut Io,
) -> Result<i32> {
pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], io: &mut Io) -> Result<i32> {
let config = broker.targets.ssh()?;
let command = match destination {
Destination::Container { node, name } => {
// `ssh` joins the words with spaces; so does this, and the container's shell runs it.
let line = remote.iter().map(|w| &**w).collect::<Vec<_>>().join(" ");
let words = container_shell(&config, node, name, &line)?;
self::command(&config, destination, &[super::shell_quote(&words)])?
}
_ => command(&config, destination, remote)?,
};
exec::run(command, io, Some(stdin.unwrap_or_default())).await
exec::run(command(&config, destination, remote)?, io, true).await
}
#[cfg(test)]
@@ -211,41 +119,15 @@ pub(crate) mod tests {
user: "deploy".into(),
ssh_opts: vec!["-p".into(), "2222".into()],
sudo: "doas -u".into(),
containers: ["web".to_owned()].into(),
},
);
SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets }
}
fn container(node: &str, name: &str) -> Destination {
Destination::Container { node: node.parse().unwrap(), name: name.parse().unwrap() }
}
#[test]
fn unknown_nodes_and_containers_are_refused() {
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());
assert!(check(&config(), &container("river", "web")).is_ok());
assert!(check(&config(), &container("river", "db")).is_err());
assert!(check(&config(), &container("sfh", "web")).is_err());
}
#[test]
fn containers_have_their_own_scope() {
assert_eq!(Value::Object(scope(&container("river", "web"))), json!({ "target": "river", "container": "web" }));
assert_eq!(describe(&container("river", "web")), "river.container-web");
}
#[test]
fn container_commands_run_as_root_through_systemd_run() {
let words = container_shell(&config(), "river", &"web".parse().unwrap(), "echo $HOME").unwrap();
assert_eq!(
super::super::shell_quote(&words),
"doas -u root systemd-run --machine=web --quiet --wait --collect --pipe --expand-environment=no -- /bin/sh \
-l -c 'echo $HOME'"
);
let words = container_shell(&config(), "river", &"web".parse().unwrap(), "").unwrap();
assert_eq!(words.last().unwrap(), "-l");
}
#[test]
+2 -2
View File
@@ -53,8 +53,8 @@ impl OpName {
/// targets, a build's attributes), that scope's fields.
pub fn fields(self) -> &'static [&'static str] {
match self {
OpName::Query => &["target", "container", "host", "port", "query"],
OpName::Ssh => &["target", "container", "host", "port"],
OpName::Query => &["target", "host", "port", "query"],
OpName::Ssh => &["target", "host", "port"],
OpName::Deploy => &["node", "profile", "mode", "commit"],
OpName::Builder => &["commit", "on_branch", "for"],
OpName::Build => &["attr", "commit"],
+5 -29
View File
@@ -2,7 +2,7 @@
//!
//! 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. `ssh` carries its stdin in the request instead, so approvers see it. The broker answers with [`ServerMessage`]s and closes after a terminal one.
//! it) stdin. The broker answers with [`ServerMessage`]s and closes after a terminal one.
use std::num::NonZeroU16;
use anyhow::{Context, Result, bail};
@@ -16,15 +16,13 @@ use tokio_util::codec::{Framed, LengthDelimitedCodec};
use crate::audit::Record;
use crate::queue::{Decision, PendingInfo};
use crate::types::{
Arg, CommitId, ContainerName, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath,
Since, UnitName, UserName,
Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since,
UnitName, UserName,
};
/// Bumped on any incompatible change; the broker refuses other versions.
pub const PROTOCOL_VERSION: u32 = 3;
pub const PROTOCOL_VERSION: u32 = 1;
pub const MAX_MESSAGE: usize = 1 << 20;
/// Bytes of an `ssh` request's command and stdin together: all of it is shown to approvers.
pub const MAX_SSH_SHOWN: usize = 32 * 1024;
pub const DEFAULT_VSOCK_PORT: u32 = 6262;
/// The host's CID, as seen from a guest.
pub const HOST_CID: u32 = 2;
@@ -50,13 +48,7 @@ pub struct Request {
#[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>,
/// All of the command's stdin, as UTF-8 text; approvers see it before it runs.
#[serde(with = "serde_bytes")]
stdin: Option<Vec<u8>>,
},
Ssh { destination: Destination, command: Vec<Arg> },
/// A fixed read-only query, run over SSH with a command the broker builds.
Query { destination: Destination, query: Query },
/// This requester's pending requests and leases.
@@ -196,12 +188,6 @@ impl GenKind {
pub enum Destination {
/// A configured target (normally a deploy-rs node), with its configured user and options.
Node(NodeName),
/// A container on a node, reached through the node's host: one of the node's
/// `container-<name>` deploy-rs profiles.
Container {
node: NodeName,
name: ContainerName,
},
Host {
user: UserName,
host: HostName,
@@ -209,16 +195,6 @@ pub enum Destination {
},
}
impl Destination {
/// The node it's reached through, if any.
pub fn node(&self) -> Option<&NodeName> {
match self {
Destination::Node(node) | Destination::Container { node, .. } => Some(node),
Destination::Host { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Query {
+5
View File
@@ -279,6 +279,11 @@ impl Queue {
leases.sort();
leases
}
/// The current version of the pending set, which [`Queue::subscribe`] reports changes of.
pub fn version(&self) -> u64 {
self.state.lock().unwrap().sequence
}
}
fn info(id: &str, entry: &Entry, now: Instant) -> PendingInfo {
+12 -87
View File
@@ -23,10 +23,6 @@ use crate::proto::{ApprovedBy, ClientMessage, PROTOCOL_VERSION, Request, ServerM
use crate::queue::{NewRequest, Outcome, Queue, new_id};
use crate::targets::Targets;
/// The most stdin a requester may send. Operations that read it have their own, smaller limits;
/// a requester sending more than this is treated as gone.
const MAX_STDIN: usize = 1 << 20;
pub struct Broker {
pub config: Config,
pub queue: Queue,
@@ -127,25 +123,18 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
};
// After the request, the requester only sends stdin; anything else, or the connection
// closing, means it's gone. The reader never waits on the operation, so it always notices:
// stdin is buffered up to a limit, and dropped once the operation can't take it.
// closing, means it's gone.
let cancel = CancellationToken::new();
let (stdin_tx, stdin_rx) = mpsc::unbounded_channel();
let (stdin_tx, stdin_rx) = mpsc::channel(16);
let reader = {
let cancel = cancel.clone();
tokio::spawn(async move {
let (mut stdin_tx, mut total) = (Some(stdin_tx), 0);
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 {
total += data.len();
if total > MAX_STDIN {
break;
}
if tx.send(data).is_err() {
stdin_tx = None;
}
let _ = tx.send(data).await;
}
}
Ok(ClientMessage::StdinEnd) => stdin_tx = None,
@@ -176,9 +165,8 @@ pub async fn handle<S: AsyncRead + AsyncWrite + Send + 'static>(broker: Arc<Brok
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 (slop-broker {} uses {PROTOCOL_VERSION}); update slop",
request.version,
crate::VERSION
"protocol version {} is not supported (the broker uses {PROTOCOL_VERSION}); update slop",
request.version
)));
}
@@ -194,10 +182,6 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
}
};
if !parsed.stdin {
io.stdin.close();
}
// Built-in operations only read the broker's own state, so they aren't logged.
let builtin = parsed.op.builtin();
let log = |event| {
@@ -211,7 +195,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
requester: requester.to_owned(),
op: parsed.op.to_string(),
summary: parsed.summary.clone(),
detail: parsed.detail.clone().into(),
detail: parsed.detail.to_text(),
label: label.clone(),
});
@@ -255,7 +239,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
Ok(gate) => gate,
Err(error) => return failed(error),
};
log(Event::Prepared { id: id.clone(), detail: gate.detail.clone().into() });
log(Event::Prepared { id: id.clone(), detail: gate.detail.to_text() });
let (by, approver) = match authorize(broker, &id, requester, &gate, label.clone(), io).await {
Ok(Some(approval)) => approval,
@@ -279,7 +263,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
return failed(error);
}
log(Event::Prepared { id: id.clone(), detail: parsed.detail.clone().into() });
log(Event::Prepared { id: id.clone(), detail: parsed.detail.to_text() });
}
let (approved_by, approver) = match authorize(broker, &id, requester, &parsed, label, io).await {
@@ -298,18 +282,15 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
io.out.send(ServerMessage::Approved { by: approved_by, stdin: parsed.stdin }).await;
let (start, builtin) = (std::time::Instant::now(), parsed.op.builtin());
let result = ops::execute(broker, requester, parsed, io).await;
let log = |event| {
if !builtin {
broker.audit.log(event)
}
};
// Some operations carry on if the requester leaves, and their outcome is still logged.
let (outlives, cancel) = (ops::outlives_requester(&parsed), io.cancel.clone());
let execution = ops::execute(broker, &id, requester, parsed, io);
let result = see_through(execution, outlives, &cancel, || log(Event::Detached { id: id.clone() })).await;
if cancel.is_cancelled() && !outlives {
if io.cancel.is_cancelled() {
log(Event::Disconnected { id });
return None;
}
@@ -327,24 +308,6 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
}
}
/// Runs an operation to the end. If the requester leaves and the operation `outlives` it, this
/// calls `detached` and keeps waiting; otherwise the operation notices `cancel` itself.
async fn see_through<T>(
execution: impl Future<Output = T>,
outlives: bool,
cancel: &CancellationToken,
detached: impl FnOnce(),
) -> T {
tokio::pin!(execution);
tokio::select! {
result = &mut execution => result,
_ = cancel.cancelled(), if outlives => {
detached();
execution.await
}
}
}
/// What policy says about a request.
fn verdict(broker: &Broker, requester: &str, parsed: &ops::Parsed) -> Result<policy::Verdict, ServerMessage> {
let settings = broker.config.policy(requester).ok_or_else(|| denied("unknown requester"))?;
@@ -403,8 +366,6 @@ async fn authorize(
.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 window = humantime::format_duration(broker.queue.timeout());
io.out.send(ServerMessage::Info(format!("approvers have {window} to answer"))).await;
let outcome = tokio::select! {
outcome = reply => outcome.unwrap_or(Outcome::Expired),
@@ -457,39 +418,3 @@ pub fn check_runtime_dir(path: &Path) -> Result<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
/// Finishes after a while, unless it notices `cancel` first.
async fn operation(cancel: CancellationToken) -> &'static str {
tokio::select! {
_ = tokio::time::sleep(Duration::from_millis(200)) => "finished",
_ = cancel.cancelled() => "stopped",
}
}
#[tokio::test]
async fn operations_that_outlive_the_requester_are_seen_through() {
for (outlives, expected) in [(true, "finished"), (false, "stopped")] {
let (cancel, detached) = (CancellationToken::new(), Cell::new(0));
let leave = {
let cancel = cancel.clone();
async move {
tokio::time::sleep(Duration::from_millis(50)).await;
cancel.cancel();
}
};
// Operations that outlive their requester don't watch its token.
let watched = if outlives { CancellationToken::new() } else { cancel.clone() };
let execution = see_through(operation(watched), outlives, &cancel, || detached.set(detached.get() + 1));
let (result, ()) = tokio::join!(execution, leave);
assert_eq!(result, expected);
assert_eq!(detached.get(), usize::from(outlives));
}
}
}
+8 -33
View File
@@ -46,11 +46,7 @@ impl Targets {
}
let mut looked = self.looked.lock().await;
let known = self.ssh().is_ok_and(|ssh| {
names.iter().all(|(node, container)| {
ssh.targets.get(*node).is_some_and(|t| container.is_none_or(|c| t.containers.contains(c)))
})
});
let known = self.ssh().is_ok_and(|ssh| names.iter().all(|n| ssh.targets.contains_key(*n)));
let due = match *looked {
None => true,
Some((at, succeeded)) => {
@@ -86,29 +82,16 @@ impl Targets {
}
}
/// The nodes an operation reaches, each with the container on it it names, if any.
fn nodes(operation: &Operation) -> Vec<(&str, Option<&str>)> {
/// The node names an operation reaches.
fn nodes(operation: &Operation) -> Vec<&str> {
match operation {
Operation::Ssh { destination, .. } | Operation::Query { destination, .. } => match destination {
Destination::Node(node) => vec![(&**node, None)],
Destination::Container { node, name } => vec![(&**node, Some(&**name))],
Destination::Host { .. } => Vec::new(),
},
Operation::Deploy { targets, .. } => targets.iter().map(|t| (t.node(), None)).collect(),
Operation::Ssh { destination: Destination::Node(node), .. }
| Operation::Query { destination: Destination::Node(node), .. } => vec![&**node],
Operation::Deploy { targets, .. } => targets.iter().map(|t| t.node()).collect(),
_ => Vec::new(),
}
}
/// The containers a node's `container-<name>` profiles deploy.
fn containers(profiles: &[String]) -> std::collections::BTreeSet<String> {
profiles
.iter()
.filter_map(|p| p.strip_prefix("container-"))
.filter(|name| name.parse::<crate::types::ContainerName>().is_ok())
.map(Into::into)
.collect()
}
/// The SSH settings with `nodes` as targets. Nodes without an SSH user or with an invalid name are
/// left out, since nothing could reach them.
fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
@@ -119,8 +102,7 @@ fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
}
let Some(user) = node.ssh_user else { continue };
let sudo = node.sudo.unwrap_or_else(default_sudo);
let containers = containers(&node.profiles);
targets.insert(name, SshTarget { hostname: node.hostname, user, ssh_opts: node.ssh_opts, sudo, containers });
targets.insert(name, SshTarget { hostname: node.hostname, user, ssh_opts: node.ssh_opts, sudo });
}
SshConfig { targets, ..ssh.clone() }
}
@@ -135,7 +117,6 @@ mod tests {
ssh_user: user.map(Into::into),
ssh_opts: vec!["-p".into(), "2222".into()],
sudo: sudo.map(Into::into),
profiles: vec!["system".into(), "container-web".into(), "container--x".into(), "containerx".into()],
}
}
@@ -155,7 +136,6 @@ mod tests {
assert_eq!(ssh.targets["web"].sudo, "doas -u");
assert_eq!(ssh.targets["plain"].sudo, "sudo -u");
assert_eq!(ssh.targets["web"].ssh_opts, ["-p", "2222"]);
assert_eq!(ssh.targets["web"].containers.iter().collect::<Vec<_>>(), ["web"]);
}
#[test]
@@ -165,12 +145,7 @@ mod tests {
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
boot: false,
};
assert_eq!(nodes(&deploy), [("web", None), ("river", None)]);
let query = Operation::Query {
destination: Destination::Container { node: "shill".parse().unwrap(), name: "web".parse().unwrap() },
query: crate::proto::Query::Failed,
};
assert_eq!(nodes(&query), [("shill", Some("web"))]);
assert_eq!(nodes(&deploy), ["web", "river"]);
assert!(nodes(&Operation::Requests).is_empty());
}
}
-14
View File
@@ -68,20 +68,6 @@ validated_string!(
}
);
validated_string!(
/// A container's machine name (as `machinectl` lists it), such as a deploy-rs node's
/// `container-<name>` profile names.
ContainerName,
"container name",
|s| {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 64
&& b[0].is_ascii_alphanumeric()
&& b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
}
);
validated_string!(
/// A remote login name.
UserName,
+26 -43
View File
@@ -18,48 +18,36 @@ function formatLeft(seconds) {
return `${seconds}s`;
}
function showCountdowns() {
setInterval(() => {
for (const element of document.querySelectorAll(".expires[data-until]")) {
const seconds = Math.max(0, Math.round((Number(element.dataset.until) - Date.now()) / 1000));
element.textContent = seconds > 0 ? `expires in ${formatLeft(seconds)}` : "expired";
}
}
}, 1000);
setInterval(showCountdowns, 1000);
// Follows the broker's events for this page. Each `morph` event is a region of the page, a whole
// element with its `id`, which is morphed into the one here (with idiomorph) rather than replacing
// it, so open details, the focus and what's being typed stay.
function listen() {
// Polls for changes to the pending set while the page is visible.
async function refresh() {
const pending = document.getElementById("pending");
const request = document.getElementById("request");
if ((!document.getElementById("pending") && !request) || !("EventSource" in window)) return;
const container = pending || request;
if (!container || document.hidden) return;
const path = request ? `/events?request=${encodeURIComponent(request.dataset.id)}` : "/events";
const source = new EventSource(path);
source.addEventListener("morph", (event) => {
const template = document.createElement("template");
template.innerHTML = event.data;
for (const region of template.content.children) {
const current = document.getElementById(region.id);
if (!current) continue;
Idiomorph.morph(current, region, { ignoreActiveValue: true, callbacks: { beforeAttributeUpdated: keepOpen } });
ready(document.getElementById(region.id));
}
});
// Signed out: reloading leads to signing in again.
source.addEventListener("signed-out", () => {
source.close();
location.reload();
});
// The browser reconnects by itself, unless the broker refused; then start again later.
source.addEventListener("error", () => {
if (source.readyState === EventSource.CLOSED) setTimeout(() => location.reload(), 30000);
});
}
const response = await fetch("/api/version", { credentials: "same-origin" });
if (response.status === 401) return location.reload();
if (!response.ok) return;
const { version } = await response.json();
if (String(version) === container.dataset.version) return;
// Whether a details element stays open or closed is the approver's.
function keepOpen(attribute, element) {
return !(attribute === "open" && element.tagName === "DETAILS");
if (request) return location.reload();
// Swap in the new list, keeping open details open.
const open = new Set([...pending.querySelectorAll("article details[open]")].map((d) => d.closest("article").id));
const fragment = await fetch("/pending", { credentials: "same-origin" });
if (!fragment.ok) return;
pending.innerHTML = await fragment.text();
pending.dataset.version = String(version);
for (const id of open) document.getElementById(id)?.querySelector("details")?.setAttribute("open", "");
startCountdowns(pending);
}
function base64urlToBytes(text) {
@@ -140,13 +128,8 @@ function localTimes(root) {
}
}
// What rendered times need, for the page or a region of it
function ready(root) {
localTimes(root);
startCountdowns(root);
showCountdowns();
}
ready(document);
listen();
localTimes(document);
startCountdowns(document);
setInterval(() => refresh().catch(() => {}), 3000);
document.addEventListener("visibilitychange", () => refresh().catch(() => {}));
setUpPush().catch(() => {});
File diff suppressed because it is too large. Load diff
-4
View File
@@ -72,10 +72,6 @@ nav a {
margin-right: 16px;
}
.account .version {
font-size: 0.875em;
}
main {
max-width: 960px;
margin: 0 auto;
-187
View File
@@ -1,187 +0,0 @@
//! Keeps open pages current with one stream of Server-Sent Events each.
//!
//! - Each `morph` event carries a region of the page: a whole element with its `id`, which the
//! page script morphs into the one it has, so open details and the focus stay. The main page's
//! region is the pending list (`#pending`), and a request's page's is the request (`#request`).
//! - A region comes when the stream starts, so a page catches up after reconnecting, and then
//! whenever it changes.
//! - `signed-out` ends the stream, when the approver signs out or the session expires.
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use tokio::sync::watch;
use tower_sessions::Session;
use super::{User, page};
use crate::server::Broker;
/// How often a page gets updates at most.
const INTERVAL: Duration = Duration::from_secs(1);
/// The signed-in approver's CSRF token, or `None` once they've signed out.
type SignedIn = Box<dyn FnMut() -> Pin<Box<dyn Future<Output = Option<String>> + Send>> + Send>;
pub fn stream(broker: Arc<Broker>, session: Session, request: Option<String>) -> Response {
let signed_in: SignedIn = Box::new(move || {
let session = session.clone();
Box::pin(async move { session.get::<User>(super::USER).await.ok().flatten().map(|user| user.csrf) })
});
let updates = Updates::new(broker, signed_in, request);
let events = futures_util::stream::unfold(updates, |mut updates| async move {
let (name, data) = updates.next().await?;
Some((Ok::<_, Infallible>(Event::default().event(name).data(data)), updates))
});
let mut response = Sse::new(events).keep_alive(KeepAlive::default()).into_response();
// Proxies such as nginx would otherwise hold events back.
response.headers_mut().insert("x-accel-buffering", axum::http::HeaderValue::from_static("no"));
response
}
struct Updates {
broker: Arc<Broker>,
signed_in: SignedIn,
/// The request whose page it is, or none for the main page.
request: Option<String>,
queue: watch::Receiver<u64>,
/// The region last sent.
sent: Option<String>,
last: Option<Instant>,
ended: bool,
}
impl Updates {
fn new(broker: Arc<Broker>, signed_in: SignedIn, request: Option<String>) -> Updates {
let queue = broker.queue.subscribe();
Updates { broker, signed_in, request, queue, sent: None, last: None, ended: false }
}
/// The next event, as a name and data, once something changes; `None` ends the stream.
async fn next(&mut self) -> Option<(&'static str, String)> {
if self.ended {
return None;
}
loop {
// The region at first, then when it changes, at most once an interval
if let Some(last) = self.last {
self.queue.changed().await.ok()?;
tokio::time::sleep(INTERVAL.saturating_sub(last.elapsed())).await;
}
self.last = Some(Instant::now());
self.queue.borrow_and_update();
// Signing out, or the session expiring, ends it.
let Some(csrf) = (self.signed_in)().await else {
self.ended = true;
return Some(("signed-out", "signed out".into()));
};
let region = self.region(&csrf);
if self.sent.as_ref() != Some(&region) {
self.sent = Some(region.clone());
return Some(("morph", region));
}
}
}
fn region(&self, csrf: &str) -> String {
match &self.request {
None => page::pending(csrf, &self.broker.queue.list(), &self.broker.queue.all_leases()),
Some(id) => {
let entry = self.broker.queue.list().into_iter().find(|e| &e.id == id);
let past = super::past(&self.broker, id);
let view = page::RequestView { id, entry: entry.as_ref(), past: past.as_ref() };
page::request_region(csrf, &view)
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
use crate::detail::Detail;
use crate::queue::NewRequest;
fn broker() -> Arc<Broker> {
let config = serde_json::from_value(serde_json::json!({
"requesters": {},
"policies": {},
"approve_socket": "/unused",
"approver_group": "root",
}))
.unwrap();
Arc::new(Broker::new(config).unwrap())
}
fn submit(broker: &Broker, id: &str) -> tokio::sync::oneshot::Receiver<crate::queue::Outcome> {
let request = NewRequest {
requester: "agent".into(),
op: "ssh".into(),
lease_key: "k".into(),
summary: "ssh river".into(),
detail: Detail::new(),
label: None,
sensitive: false,
passkey: false,
leases: vec![300],
};
broker.queue.submit(id, request, 4).unwrap()
}
#[tokio::test]
async fn the_main_page_gets_its_list_as_it_changes() {
let broker = broker();
let signed_out = Arc::new(AtomicBool::new(false));
let check = signed_out.clone();
let signed_in: SignedIn = Box::new(move || {
let out = check.load(Ordering::SeqCst);
Box::pin(async move { (!out).then(|| "token".to_owned()) })
});
let mut updates = Updates::new(broker.clone(), signed_in, None);
// The list to start with, as a whole element
let (name, data) = updates.next().await.unwrap();
assert_eq!(name, "morph");
assert!(data.starts_with(r#"<div id="pending">"#) && data.contains("Nothing is waiting"), "{data}");
// A new request, then its leaving
let _reply = submit(&broker, "abc");
let (_, data) = updates.next().await.unwrap();
assert!(data.contains("ssh river"), "{data}");
broker.queue.cancel("abc");
let (_, data) = updates.next().await.unwrap();
assert!(data.contains("Nothing is waiting"), "{data}");
signed_out.store(true, Ordering::SeqCst);
let _reply = submit(&broker, "def");
assert_eq!(updates.next().await.unwrap().0, "signed-out");
assert!(updates.next().await.is_none());
}
#[tokio::test]
async fn a_request_page_gets_its_request() {
let broker = broker();
let signed_in: SignedIn = Box::new(|| Box::pin(async { Some("token".to_owned()) }));
let mut updates = Updates::new(broker.clone(), signed_in, Some("abc".into()));
let (_, data) = updates.next().await.unwrap();
assert!(data.starts_with(r#"<div id="request" data-id="abc">"#), "{data}");
assert!(data.contains("The audit log has nothing"), "{data}");
// Other requests change nothing here, so nothing comes until this one does
let _other = submit(&broker, "xyz");
let _reply = submit(&broker, "abc");
let (_, data) = updates.next().await.unwrap();
assert!(data.contains("<h1>ssh river</h1>"), "{data}");
}
}
+9 -28
View File
@@ -1,8 +1,7 @@
//! The audit log gathered by request: what was asked, who approved it and how it ended.
use std::collections::HashMap;
use crate::audit::{Event, Record, Shown};
use crate::detail::Detail;
use crate::audit::{Event, Record};
use crate::proto::ApprovedBy;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -84,7 +83,6 @@ fn id_of(event: &Event) -> Option<&str> {
| Event::Denied { id, .. }
| Event::Expired { id }
| Event::Disconnected { id }
| Event::Detached { id }
| Event::Finished { id, .. }
| Event::Failed { id, .. } => Some(id),
}
@@ -158,7 +156,7 @@ fn summarize(id: String, records: Vec<Record>) -> History {
Event::Finished { exit: 0, .. } => history.outcome = Outcome::Succeeded,
Event::Finished { exit, .. } => history.outcome = Outcome::ExitedWith(*exit),
Event::Failed { .. } => history.outcome = Outcome::Failed,
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } | Event::Detached { .. } => {}
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } => {}
}
}
@@ -166,8 +164,8 @@ fn summarize(id: String, records: Vec<Record>) -> History {
history
}
/// One event in a request's timeline: what happened, and what approvers were shown with it.
pub fn describe(event: &Event) -> (String, Option<Detail>) {
/// One event in a request's timeline: what happened, and any longer text to show with it.
pub fn describe(event: &Event) -> (String, Option<String>) {
match event {
Event::Unknown { peer } => (format!("Refused a connection from {peer}"), None),
Event::Invalid { error, .. } => (format!("Invalid request: {error}"), None),
@@ -176,9 +174,11 @@ pub fn describe(event: &Event) -> (String, Option<Detail>) {
if let Some(label) = label {
text += &format!(" (label: {label})");
}
(text, shown(detail))
(text, Some(detail.clone()).filter(|d| !d.is_empty()))
}
Event::Prepared { detail, .. } => {
("Prepared for approval".into(), Some(detail.clone()).filter(|d| !d.is_empty()))
}
Event::Prepared { detail, .. } => ("Prepared for approval".into(), shown(detail)),
Event::Approved { by, approver, step, .. } => {
let by = match (by, approver) {
(ApprovedBy::Policy, _) => "policy".to_owned(),
@@ -195,7 +195,6 @@ pub fn describe(event: &Event) -> (String, Option<Detail>) {
Event::Denied { reason, .. } => (format!("Refused: {reason}"), None),
Event::Expired { .. } => ("Expired without an answer".into(), None),
Event::Disconnected { .. } => ("Cancelled: the requester disconnected".into(), None),
Event::Detached { .. } => ("The requester disconnected; carried on to the end".into(), None),
Event::Finished { exit, seconds, .. } => {
(format!("Finished with exit status {exit} after {seconds:.1}s"), None)
}
@@ -203,10 +202,6 @@ pub fn describe(event: &Event) -> (String, Option<Detail>) {
}
}
fn shown(detail: &Shown) -> Option<Detail> {
Some(detail.to_detail()).filter(|d| !d.fields.is_empty() || !d.sections.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
@@ -221,7 +216,7 @@ mod tests {
requester: "slop-cannon".into(),
op: "ssh".into(),
summary: format!("ssh {id}"),
detail: Detail::code("Command", "uptime").into(),
detail: "Command: uptime".into(),
label: None,
}
}
@@ -283,18 +278,4 @@ mod tests {
assert_eq!(histories[0].outcome, Outcome::Waiting);
assert_eq!(histories[0].approved_by, None);
}
#[test]
fn a_requester_leaving_doesnt_hide_how_a_deploy_ended() {
let approved = Event::Approved { id: "a".into(), by: ApprovedBy::Policy, approver: None, step: None };
let mut records =
vec![record("1", request("a")), record("2", approved), record("3", Event::Detached { id: "a".into() })];
let (histories, _) = gather(records.clone());
assert_eq!(histories[0].outcome, Outcome::Running);
records.push(record("4", Event::Finished { id: "a".into(), exit: 0, seconds: 30.0 }));
let (histories, _) = gather(records);
assert_eq!(histories[0].outcome, Outcome::Succeeded);
}
}
+23 -30
View File
@@ -2,7 +2,6 @@
//! for approvers signed in through an OpenID Connect provider, plus Web Push notifications. It
//! sits behind a reverse proxy, which is the only thing that should reach its listener.
mod auth;
mod events;
mod history;
mod page;
mod push;
@@ -82,9 +81,10 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
let app = Router::new()
.route("/", get(index))
.route("/pending", get(pending_fragment))
.route("/requests/{id}", get(request_page).post(answer))
.route("/log", get(log_page))
.route("/events", get(page_events))
.route("/api/version", get(version))
.route("/api/csrf", get(csrf))
.route("/push/key", get(push_key))
.route("/push/subscribe", post(subscribe))
@@ -94,7 +94,6 @@ pub async fn run(broker: Arc<Broker>, config: WebConfig, secret: String) -> Resu
.route("/auth/logout", post(logout))
.route("/signed-out", get(signed_out))
.route("/app.js", get(|| async { page::asset("text/javascript", include_str!("assets/app.js")) }))
.route("/idiomorph.js", get(|| async { page::asset("text/javascript", include_str!("assets/idiomorph.js")) }))
.route("/sw.js", get(|| async { page::asset("text/javascript", include_str!("assets/sw.js")) }))
.route("/style.css", get(|| async { page::asset("text/css", include_str!("assets/style.css")) }))
.route("/icon.svg", get(|| async { page::asset("image/svg+xml", include_str!("assets/icon.svg")) }))
@@ -205,7 +204,14 @@ async fn index(State(web): State<Arc<Web>>, session: Session) -> Result<Response
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::index(&user.name, &user.csrf, &entries, &leases).into_response())
Ok(page::index(&user.name, &user.csrf, &entries, &leases, web.broker.queue.version()).into_response())
}
async fn pending_fragment(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
let entries = web.broker.queue.list();
let leases = web.broker.queue.all_leases();
Ok(page::pending(&user.csrf, &entries, &leases).into_response())
}
async fn request_page(
@@ -217,32 +223,14 @@ async fn request_page(
Ok(user) => user,
Err(redirect) => return Ok(redirect),
};
let (entry, past) = (pending(&web, &id), past(&web.broker, &id));
let view = page::RequestView { id: &id, entry: entry.as_ref(), past: past.as_ref() };
Ok(page::request(&user.name, &user.csrf, &view).into_response())
}
/// What the audit log has of a request. The log may be missing or unreadable; the request itself
/// still shows.
fn past(broker: &Broker, id: &str) -> Option<History> {
let records = broker.audit.tail(LOG_RECORDS).ok()?;
let (histories, _) = history::gather(records);
histories.into_iter().find(|h| h.id == id)
}
#[derive(Deserialize)]
struct EventsQuery {
request: Option<String>,
}
/// The page's stream of updates (see [`events`]): the main page's, or a request's.
async fn page_events(
State(web): State<Arc<Web>>,
session: Session,
Query(query): Query<EventsQuery>,
) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(events::stream(web.broker.clone(), session, query.request))
// The log may be missing or unreadable; the request itself still shows.
let past = web.broker.audit.tail(LOG_RECORDS).ok().and_then(|records| {
let (histories, _) = history::gather(records);
histories.into_iter().find(|h| h.id == id)
});
let current = pending(&web, &id);
Ok(page::request(&user.name, &user.csrf, &id, current.as_ref(), past.as_ref(), web.broker.queue.version())
.into_response())
}
#[derive(Deserialize)]
@@ -322,6 +310,11 @@ async fn log_page(
Ok(page::log(&user.name, &user.csrf, &view).into_response())
}
async fn version(State(web): State<Arc<Web>>, session: Session) -> Result<Response, Failure> {
api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "version": web.broker.queue.version() })).into_response())
}
async fn csrf(session: Session) -> Result<Response, Failure> {
let user = api_user(&session).await?;
Ok(axum::Json(serde_json::json!({ "csrf": user.csrf })).into_response())
+32 -78
View File
@@ -13,9 +13,6 @@ use crate::detail::{Column, Detail, Section};
use crate::ops::printable;
use crate::queue::{Decision, PendingInfo};
/// The broker's version, which signed-in pages show.
pub use crate::VERSION;
/// HTML escaping, after replacing what [`printable`] replaces.
#[derive(Debug, Clone, Copy)]
pub struct Printable;
@@ -70,7 +67,7 @@ fn section_titles(detail: &Detail) -> String {
detail.sections.iter().map(Section::title).collect::<Vec<_>>().join(", ")
}
fn describe(record: &Record) -> (String, Option<Detail>) {
fn describe(record: &Record) -> (String, Option<String>) {
history::describe(&record.event)
}
@@ -85,7 +82,7 @@ pub fn message(title: &str, text: &str) -> Html<String> {
render(Message { title, text })
}
/// The pending requests and leases: the main page's region that the page script keeps current.
/// The pending requests and leases, which the page script swaps in when they change.
#[derive(Template)]
#[template(path = "pending.html")]
struct Pending<'a> {
@@ -94,8 +91,8 @@ struct Pending<'a> {
leases: &'a [(String, String, u64)],
}
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> String {
render(Pending { csrf, entries, leases }).0
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
render(Pending { csrf, entries, leases })
}
#[derive(Template)]
@@ -105,27 +102,17 @@ struct Index<'a> {
csrf: &'a str,
entries: &'a [PendingInfo],
leases: &'a [(String, String, u64)],
version: u64,
}
pub fn index(name: &str, csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
render(Index { name, csrf, entries, leases })
}
/// What a request's page shows: the request while it waits, and what the audit log has of it.
pub struct RequestView<'a> {
pub id: &'a str,
pub entry: Option<&'a PendingInfo>,
pub past: Option<&'a History>,
}
impl RequestView<'_> {
fn heading(&self) -> String {
match (self.entry, self.past) {
(Some(entry), _) => entry.summary.clone(),
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(self.id)),
}
}
pub fn index(
name: &str,
csrf: &str,
entries: &[PendingInfo],
leases: &[(String, String, u64)],
version: u64,
) -> Html<String> {
render(Index { name, csrf, entries, leases, version })
}
#[derive(Template)]
@@ -133,23 +120,26 @@ impl RequestView<'_> {
struct Request<'a> {
name: &'a str,
csrf: &'a str,
view: &'a RequestView<'a>,
heading: String,
entry: Option<&'a PendingInfo>,
past: Option<&'a History>,
version: u64,
}
pub fn request(name: &str, csrf: &str, view: &RequestView) -> Html<String> {
render(Request { name, csrf, view })
}
/// A request's page without the rest: the region that the page script keeps current.
#[derive(Template)]
#[template(path = "request_region.html")]
struct RequestRegion<'a> {
csrf: &'a str,
view: &'a RequestView<'a>,
}
pub fn request_region(csrf: &str, view: &RequestView) -> String {
render(RequestRegion { csrf, view }).0
pub fn request(
name: &str,
csrf: &str,
id: &str,
entry: Option<&PendingInfo>,
past: Option<&History>,
version: u64,
) -> Html<String> {
let heading = match (entry, past) {
(Some(entry), _) => entry.summary.clone(),
(None, Some(past)) if !past.summary.is_empty() => past.summary.clone(),
_ => format!("Request {}", short(id)),
};
render(Request { name, csrf, heading, entry, past, version })
}
/// What the log page is filtered by.
@@ -266,8 +256,7 @@ mod tests {
offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny],
expires_in: 125,
};
let html = pending("token", &[entry], &[]);
assert!(html.starts_with("<div id=\"pending\">") && html.trim_end().ends_with("</div>"), "{html}");
let html = pending("token", &[entry], &[]).0;
assert!(html.contains(r#"value="5m""#));
assert!(html.contains("For 5m"));
assert!(html.contains("ssh river &#60;x&#62;"));
@@ -281,39 +270,4 @@ mod tests {
assert!(html.contains("needs-passkey"));
assert!(html.contains("Needs passkey"));
}
#[test]
fn history_shows_what_approvers_saw() {
use crate::audit::{Event, Record, Shown};
let mut detail = Detail::code("Command", "uptime");
detail.section(Section::diff("Diff", "@@ -1 +1 @@\n-b\n+a"));
let records = vec![
Record {
time: "2026-11-27T10:00:00Z".into(),
event: Event::Request {
id: "abc".into(),
requester: "slop-cannon".into(),
op: "ssh".into(),
summary: "ssh river".into(),
detail: detail.into(),
label: None,
},
},
Record {
time: "2026-11-27T10:00:01Z".into(),
event: Event::Prepared { id: "abc".into(), detail: Shown::Text("Old: text".into()) },
},
];
let (histories, _) = super::history::gather(records);
let view = RequestView { id: "abc", entry: None, past: Some(&histories[0]) };
let html = request("broker", "token", &view).0;
assert!(html.contains(r#"<div id="request" data-id="abc">"#), "{html}");
assert!(html.contains(request_region("token", &view).trim()), "{html}");
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"), "{html}");
assert!(html.contains("<span class=\"diff-add\">+a</span>"), "{html}");
assert!(html.contains("Details (Text)") && html.contains("<pre>Old: text</pre>"), "{html}");
assert!(html.contains(&format!("slop-broker {VERSION}")), "{html}");
}
}
-2
View File
@@ -7,7 +7,6 @@
<link rel="stylesheet" href="/style.css">
<link rel="manifest" href="/manifest.webmanifest">
<link rel="icon" href="/icon.svg">
<script src="/idiomorph.js" defer></script>
<script src="/app.js" defer></script>
</head>
<body>
@@ -15,7 +14,6 @@
<header>
<nav><a href="/">Pending</a> <a href="/log">Log</a></nav>
<form method="post" action="/auth/logout" class="account">
<span class="version">slop-broker {{ crate::web::page::VERSION }}</span>
<span>{{ name }}</span>
<input type="hidden" name="csrf" value="{{ csrf }}">
<button type="submit" class="quiet">Sign out</button>
+2
View File
@@ -5,5 +5,7 @@
<section id="push" hidden>
<p><span id="push-state"></span> <button type="button" id="push-toggle" class="quiet"></button></p>
</section>
<div id="pending" data-version="{{ version }}">
{% include "pending.html" %}
</div>
{% endblock %}
+1 -1
View File
@@ -80,7 +80,7 @@
{% for record in records %}
{% let (text, detail) = self::describe(record) %}
<li>{% call time(record.time) %}{% endcall %} <span>{{ text }}</span>
{%- if let Some(detail) = detail %}{% call detail(detail, false) %}{% endcall %}{% endif %}</li>
{%- if let Some(detail) = detail %}<details><summary>Details</summary><pre>{{ detail }}</pre></details>{% endif %}</li>
{% endfor %}
</ol>
{% endmacro %}
-2
View File
@@ -1,5 +1,4 @@
{%- import "macros.html" as m -%}
<div id="pending">
{% if entries.is_empty() %}
<p class="empty">Nothing is waiting for an answer.</p>
{% endif %}
@@ -14,4 +13,3 @@
{% endfor %}
</tbody></table>
{% endif %}
</div>
+16 -1
View File
@@ -1,5 +1,20 @@
{% extends "base.html" %}
{% import "macros.html" as m %}
{% block title %}Approval request{% endblock %}
{% block main %}
{% include "request_region.html" %}
<h1>{{ heading }}</h1>
<div id="request" data-version="{{ version }}">
{% if let Some(entry) = entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(past) = past %}
{% if entry.is_none() %}
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
{% endif %}
<h2>History</h2>
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
{% else if entry.is_none() %}
<p class="empty">The audit log has nothing about this request.</p>
{% endif %}
</div>
{% endblock %}
-16
View File
@@ -1,16 +0,0 @@
{%- import "macros.html" as m -%}
<div id="request" data-id="{{ view.id }}">
<h1>{{ view.heading() }}</h1>
{% if let Some(entry) = view.entry %}
{% call m::card(entry, csrf, true) %}{% endcall %}
{% endif %}
{% if let Some(past) = view.past %}
{% if view.entry.is_none() %}
<p class="meta">{{ past.requester }} · {{ past.op }} · {% call m::outcome(past.outcome) %}{% endcall %}</p>
{% endif %}
<h2>History</h2>
{% call m::timeline(past.records.as_slice()) %}{% endcall %}
{% else if view.entry.is_none() %}
<p class="empty">The audit log has nothing about this request.</p>
{% endif %}
</div>
+17 -141
View File
@@ -26,7 +26,7 @@ const FAKE_SSH: &str = r#"#!/bin/sh
echo $$ > "${0%/*}/pid"
echo "args: $*"
while read -r line; do
[ "$line" = block ] && exec sleep 60
[ "$line" = block ] && while read -r _; do :; done
echo "in: $line"
done
echo done >&2
@@ -57,13 +57,8 @@ fn broker(directory: &Path, ops: serde_json::Value) -> Arc<Broker> {
// The main branch's nodes, as the builder would have found them
let broker = Broker::new(config).unwrap();
let river = Node {
hostname: "river.example.org".into(),
ssh_user: Some("deploy".into()),
ssh_opts: vec![],
sudo: None,
profiles: vec!["system".into(), "container-web".into()],
};
let river =
Node { hostname: "river.example.org".into(), ssh_user: Some("deploy".into()), ssh_opts: vec![], sudo: None };
broker.targets.assume(&broker.config, [("river".to_owned(), river)].into());
Arc::new(broker)
}
@@ -105,14 +100,9 @@ impl Client {
}
fn ssh(command: &[&str]) -> Operation {
ssh_with(command, None)
}
fn ssh_with(command: &[&str], stdin: Option<&[u8]>) -> Operation {
Operation::Ssh {
destination: Destination::Node("river".parse().unwrap()),
command: command.iter().map(|c| c.parse::<Arg>().unwrap()).collect(),
stdin: stdin.map(<[u8]>::to_vec),
}
}
@@ -125,9 +115,12 @@ 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_with(&["uptime", "-p"], Some(b"hello\n"))).await;
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: false });
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}");
@@ -155,8 +148,7 @@ 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![], stdin: None };
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")));
@@ -200,7 +192,7 @@ async fn invalid_messages_are_rejected() {
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let raw = |node: &str, extra: bool| {
let mut ssh = json!({ "destination": { "node": node }, "command": [], "stdin": null });
let mut ssh = json!({ "destination": { "node": node }, "command": [] });
if extra {
ssh["unexpected"] = json!(true);
}
@@ -219,63 +211,10 @@ async fn invalid_messages_are_rejected() {
}
}
#[tokio::test]
async fn approvers_see_the_whole_command_and_stdin_that_run() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
// The words go to the remote shell joined with spaces, so that's what approvers see.
let script = b"echo one\necho two\n";
let mut client = Client::start(&broker, ssh_with(&["bash", "-s", "a b"], Some(script))).await;
let id = pending_id(&mut client).await;
let detail = broker.queue.list()[0].detail.to_text();
assert!(detail.starts_with("Command: bash -s a b\nStdin: 2 lines, 18 bytes\n"), "{detail}");
assert!(detail.ends_with("Stdin:\necho one\necho two"), "{detail}");
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
let mut output = String::new();
client.next(&mut output).await;
assert_eq!(client.next(&mut output).await, finished(3));
assert!(output.contains("in: echo one\nin: echo two\n"), "{output}");
// So is the audit log.
let records = broker.audit.tail(10).unwrap();
let slop_broker::audit::Event::Request { detail: logged, .. } = &records[0].event else { panic!("{records:?}") };
assert_eq!(logged.to_text(), detail);
// Multi-line commands are shown as text rather than a one-line field.
let mut client = Client::start(&broker, ssh(&["echo one\necho two"])).await;
pending_id(&mut client).await;
let detail = broker.queue.list()[0].detail.to_text();
assert_eq!(detail, "Command:\necho one\necho two");
}
#[tokio::test]
async fn stdin_that_cant_be_shown_is_refused() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let binary = ssh_with(&["tar", "x"], Some(b"\xff\xfe"));
let mut client = Client::start(&broker, binary).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("UTF-8")));
let large = vec![b'x'; slop_broker::proto::MAX_SSH_SHOWN];
let mut client = Client::start(&broker, ssh_with(&["cat"], Some(&large))).await;
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("KiB")));
}
async fn pending_id(client: &mut Client) -> String {
pending_for(client, "ssh river").await
}
async fn pending_for(client: &mut Client, expected: &str) -> String {
match client.next(&mut String::new()).await {
ServerMessage::Pending { id, summary } => {
assert_eq!(summary, expected);
// Then how long approvers have, so agents know how long to wait.
let window = client.next(&mut String::new()).await;
assert!(matches!(&window, ServerMessage::Info(m) if m.starts_with("approvers have ")), "{window:?}");
assert_eq!(summary, "ssh river");
id
}
other => panic!("expected pending, got {other:?}"),
@@ -296,12 +235,14 @@ async fn ask_waits_for_an_approver_and_leases_cover_repeats() {
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).unwrap();
let mut output = String::new();
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: false });
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: false });
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();
@@ -351,36 +292,9 @@ 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_with(&["true"], Some(b"block\n"))).await;
let mut client = Client::start(&broker, ssh(&["true"])).await;
client.next(&mut String::new()).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 stdin_an_operation_doesnt_read_doesnt_hide_a_disconnect() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
let mut client = Client::start(&broker, ssh_with(&["true"], Some(b"block\n"))).await;
client.next(&mut String::new()).await;
for _ in 0..64 {
client.send(ClientMessage::Stdin(b"ignored\n".to_vec())).await;
}
client.send(ClientMessage::Stdin(b"block\n".to_vec())).await;
let pid_file = directory.path().join("pid");
let mut pid = None;
@@ -424,41 +338,6 @@ async fn queries_run_a_fixed_quoted_command_without_stdin() {
);
}
#[tokio::test]
async fn containers_are_queried_through_their_host_and_must_be_known() {
let directory = tempfile::tempdir().unwrap();
let broker = broker(
directory.path(),
json!({ "query": { "action": "auto", "rules": [
{ "match": { "container": "*" }, "action": "ask" },
] } }),
);
let container = |name: &str| Destination::Container { node: "river".parse().unwrap(), name: name.parse().unwrap() };
// Rules can tell container queries apart.
let mut client =
Client::start(&broker, Operation::Query { destination: container("web"), query: Query::Failed }).await;
let id = pending_for(&mut client, "failed on river.container-web").await;
assert_eq!(
broker.queue.list()[0].detail.to_text(),
"Command: sudo -u root systemctl --machine=web list-units --failed --no-pager"
);
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
let mut output = String::new();
client.next(&mut output).await;
assert_eq!(client.next(&mut output).await, finished(3));
assert!(
output.contains("river.example.org sudo -u root systemctl --machine=web list-units --failed --no-pager"),
"{output}"
);
let mut client =
Client::start(&broker, Operation::Query { destination: container("db"), query: Query::Failed }).await;
let ServerMessage::Error(error) = client.next(&mut String::new()).await else { panic!() };
assert!(error.contains("unknown container river.container-db"), "{error}");
}
#[tokio::test]
async fn requests_lists_pending_and_leases() {
let directory = tempfile::tempdir().unwrap();
@@ -500,9 +379,6 @@ async fn remote_requesters_and_approvers_use_one_socket() {
let request = ClientMessage::Request(Request { version: PROTOCOL_VERSION, label: None, operation: ssh(&["true"]) });
send(&mut requester, &request).await.unwrap();
let Some(ServerMessage::Pending { id, .. }) = receive(&mut requester).await.unwrap() else { panic!("not pending") };
let Some(ServerMessage::Info(_)) = receive::<_, ServerMessage>(&mut requester).await.unwrap() else {
panic!("no window")
};
// One approver connection carries several requests.
let mut approver = remote(&path, Role::Approver, "laptop").await;
+2 -7
View File
@@ -122,16 +122,13 @@ fn secrets_are_looked_up_on_the_branch() {
git(&work, &["init", "--quiet", "--initial-branch=master"]);
std::fs::write(work.join("secrets/a.age"), "age-encryption.org/v1\nreal\n").unwrap();
std::fs::write(work.join("secrets/copy.age"), "age-encryption.org/v1\nreal\n").unwrap();
let rules = |keys: &str| {
format!("{{ \"secrets/a.age\".publicKeys = [ \"age1dev\" ]; \"secrets/b.age\".publicKeys = [ {keys} ]; }}\n")
};
std::fs::write(work.join("secrets.nix"), rules("\"ssh-ed25519 AAAA box\"")).unwrap();
std::fs::write(work.join("secrets.nix"), "{ \"secrets/a.age\".publicKeys = [ \"age1dev\" ]; }\n").unwrap();
git(&work, &["add", "."]);
git(&work, &["commit", "--quiet", "-m", "Secrets"]);
// An agent's branch can't change what the main branch says.
git(&work, &["checkout", "--quiet", "-b", "agent"]);
std::fs::write(work.join("secrets.nix"), rules("\"ssh-ed25519 AAAA box\" \"ssh-ed25519 BBBB box\"")).unwrap();
std::fs::write(work.join("secrets.nix"), "{ \"secrets/a.age\".publicKeys = [ \"age1agent\" ]; }\n").unwrap();
git(&work, &["commit", "--quiet", "-am", "Change the rules"]);
let state = directory.path().join("state");
@@ -157,8 +154,6 @@ fn secrets_are_looked_up_on_the_branch() {
let context: SecretContext = ask(&config, &BuilderRequest::Secret(request.clone()));
assert_eq!(context.paths, ["secrets/a.age", "secrets/copy.age"]);
assert_eq!(context.recipients, Some(vec!["age1dev".to_owned()]));
// Names come from comments on every path's keys.
assert_eq!(context.names, std::collections::BTreeMap::from([("box".to_owned(), "ssh-ed25519 AAAA".to_owned())]));
assert_eq!(&*context.commit, git(&work, &["rev-parse", "master"]));
let unknown = SecretRequest { blob: None, path: "secrets/new.age".parse().unwrap(), ..request };