11 Commits
Author SHA1 Message Date
jackos1998andClaude Opus 5.5 70a42f6a21 nix: Add the commit to the version
CI / Check (pull_request) Successful in 5m45s
CI / Check (push) Successful in 5m42s
Builds from the flake show the commit they are from in the version,
like `0.3.0+2d59b59`, or `0.3.0+2d59b59-dirty` with uncommitted
changes. It shows in the web app, in `--version`, which `slop` and
`slop-broker` now take, and in the error for an old protocol.

The commit is part of the build, so every commit rebuilds the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:29:17 +00:00
jackos1998andClaude Opus 5.5 398f5927f5 web: Keep pages current with Server-Sent Events
CI / Check (push) Successful in 5m59s
Pages polled `/api/version` every three seconds, then fetched the
pending list and replaced it, or reloaded a request's page. Now each
page follows one stream from `/events`, whose `morph` events carry a
region of the page: the pending list, or the request, as a whole
element with its `id`, rendered by the page's own templates. The page
script morphs it into the page with idiomorph, vendored, so open
details, the focus and typing stay.

The stream starts with the current region, so a page catches up when
the browser reconnects, and it ends when the approver signs out.
`/api/version` and `/pending` are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 14:46:11 +00:00
jackos1998andClaude Opus 5.5 83a9e9d0d6 web: Show the broker's version in the header
CI / Check (pull_request) Successful in 5m45s
CI / Check (push) Successful in 5m43s
Signed-in pages show which version of the broker is running, next to
the approver's name, to check a deploy of the broker took effect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:27:48 +00:00
jackos1998andClaude Opus 5.5 76eb39fb7e demo: Add a binary cache for slop build
The box VM holds the cache's store in a `cache` account, set up by
`services.slop-broker-cache`, and the demo's broker pushes to it, so
`slop build` can be tried by hand. The broker's key is only known at
boot, so the module exposes its forced command for keys it can't list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:27:48 +00:00
jackos1998andClaude Opus 5.5 3f024cd115 demo: Move the host side out of devenv.nix
The demo's host side is a devenv module of its own,
`nix/demo/host.nix`, which `devenv.nix` imports, so `devenv.nix` is
only the development environment. The VMs' settings are grouped with
comments, and the longer scripts are broken into steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:27:48 +00:00
jackos1998andClaude Opus 5.5 474d9fa7e1 demo: Read the builder's store through the ssh wrapper
Deploys and builds read built paths from the builder's store over
`ssh-ng`, with the `ssh` the broker's `nix` finds on its `PATH`. The
demo's wrapper wasn't named `ssh`, so `nix` used the real one, which
couldn't resolve `builder`. The wrapper is now `bin/ssh`, and also
handles how Nix calls it: the host as `builder@builder`, a control
master check and the `LocalCommand` it waits for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:27:48 +00:00
jackos1998andClaude Opus 5.5 50ec4833c1 test: Push a build to a binary cache
`box` also holds a binary cache's store through
`services.slop-broker-cache`, and the agent builds the profile into it
with `slop build`, which no test covered. The test checks the printed
path, the closure in the cache's store and its GC root. The audit
check now reads more than the default 50 records, which the extra
requests outgrew.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:27:48 +00:00
jackos1998andClaude Opus 5.5 c33a28c8b8 test: Deploy a built profile to a second box
The test repository gets two commits of a profile the builder can
build from a static busybox, without nixpkgs, whose `activate-rs`
leaves a mark, and a second VM, `box`, as a node with a store of its
own. The test deploys to `box` and the broker's own box at once, whose
profiles are the same derivation, then the second commit to `box`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:27:48 +00:00
jackos1998andClaude Opus 5.5 d157ff278a test: Tidy the VM test
The test script gets helpers for running `slop` as the agent and
`slop-approve` as the reviewer, and headings for what each part
checks. The settings of `machine` are grouped with comments, its
`deploy` account in a module of its own, for the deploy nodes that
come next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 13:18:46 +00:00
jackos1998andClaude Opus 5.5 e9d4744a06 builder: Point the mirror's HEAD at the main branch
The mirror only has remote branches, so its HEAD named a branch that
doesn't exist, and Nix warned that it couldn't read it on every build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:55:10 +00:00
jackos1998andClaude Opus 5.5 8db6b0f36a builder: Match results of repeated derivations
`nix build --json` gives one result per installable, in order, except
that Nix 2.35 repeats the results of installables that are the same
derivation: two deploy targets with the same profile gave four results
for two installables, and the build failed. When the counts differ,
the builder now matches results by derivation path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 00:55:10 +00:00
30 changed files with 2655 additions and 593 deletions

No files matched your search

+7 -334
View File
@@ -1,347 +1,20 @@
# 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 (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
# `devenv up` runs the demo's host side, from `nix/demo/host.nix` (see `docs/demo.md`).
{ pkgs, ... }:
{
imports = [ ./nix/demo/host.nix ];
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 ];
# 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" ];
};
scripts.vm-test = {
description = "Run the NixOS VM test of the broker module (needs KVM)";
exec = ''nix build -L --no-link "$DEVENV_ROOT#checks.x86_64-linux.vm" "$@"'';
};
# `devenv test`
+3 -3
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`), 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 |
| `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`) |
| `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 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 |
| `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 |
| `.gitea/workflows/ci.yaml` | CI: `nix flake check` |
## Request lifecycle
+28 -4
View File
@@ -40,6 +40,7 @@ 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
@@ -50,6 +51,7 @@ 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 |
@@ -57,14 +59,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, and the deploy target | `localhost:2222`, as `box` | `devenv up` (process `box`) |
| 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`) |
| 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
[`devenv.nix`](../devenv.nix):
[`host.nix`](../nix/demo/host.nix), the devenv module with the demo's host side:
- **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
@@ -81,8 +83,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 ask.
There's no binary cache, so `slop build` says it isn't configured.
- 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.
## Approving
@@ -121,6 +123,9 @@ 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
@@ -164,6 +169,25 @@ 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
+11 -1
View File
@@ -233,7 +233,17 @@ 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 refreshes the list and manages notifications, and a service worker shows them.
- 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.
- 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.
+5 -2
View File
@@ -10,6 +10,9 @@
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 ];
@@ -19,7 +22,7 @@
in
{
packages = forSystems (pkgs: rec {
slop-broker = pkgs.callPackage ./nix/package.nix { };
slop-broker = pkgs.callPackage ./nix/package.nix { inherit rev; };
default = slop-broker;
# The demo's VMs (see `docs/demo.md`)
demo = import ./nix/demo/agent.nix { inherit pkgs slop-broker; };
@@ -27,7 +30,7 @@
});
overlays.default = final: _prev: {
slop-broker = final.callPackage ./nix/package.nix { };
slop-broker = final.callPackage ./nix/package.nix { inherit rev; };
};
nixosModules = {
+12 -4
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` and `vault` are all the box VM.
targets `web`, `router`, `vault` and `box` are all the box VM.
slop status web sshd.service runs without asking (policy: auto)
slop logs web sshd.service -n 20
@@ -40,6 +40,12 @@ 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).
@@ -65,11 +71,12 @@ 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;
@@ -82,8 +89,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]
@@ -91,6 +98,7 @@ 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
+42 -10
View File
@@ -1,15 +1,22 @@
# 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.
# 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.
{ 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" ];
imports = [ "${modulesPath}/virtualisation/qemu-vm.nix" ../modules/nixos/cache.nix ];
system.stateVersion = lib.trivial.release;
networking.hostName = "slop-demo-box";
@@ -17,7 +24,7 @@ in
virtualisation = {
graphics = false;
diskImage = null;
# Copied closures live in memory
# Copied closures live in memory, the cache's too
memorySize = 1024;
restrictNetwork = true;
forwardPorts = [{
@@ -27,9 +34,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" ]; }];
@@ -38,12 +45,28 @@ 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 shared directory is mounted at `/tmp/shared`
# The keys from the shared directory, which is mounted at `/tmp/shared`, before `sshd` starts
systemd.services.slop-demo-keys = {
wantedBy = [ "multi-user.target" ];
before = [ "sshd.service" "sshd-keygen.service" ];
@@ -52,8 +75,17 @@ in
serviceConfig = { Type = "oneshot"; RemainAfterExit = true; };
script = ''
install -m 600 /tmp/shared/host-key ${hostKey}
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
# 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
'';
};
})).vm
+386
View File
@@ -0,0 +1,386 @@
# 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 `devenv.nix`
# Shared by the demo's VMs and its host side in `host.nix`
{
# The agents' VM's vsock CID: anything above 2 that no other VM on the host uses
agentCid = 3626;
+7 -1
View File
@@ -51,6 +51,12 @@ 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 {
@@ -62,7 +68,7 @@ in
];
users.users.${cfg.user}.openssh.authorizedKeys.keys =
map (k: ''restrict,command="${forcedCommand}" ${k}'') cfg.brokerKeys;
map (k: ''restrict,command="${cfg.forcedCommand}" ${k}'') cfg.brokerKeys;
# Expired roots go daily; the store's own garbage collection then takes their paths
systemd = {
+9 -2
View File
@@ -1,10 +1,13 @@
{ lib, rustPlatform, pkg-config, openssl, sqlite }:
# `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 }:
let
inherit (lib.fileset) toSource unions;
inherit ((builtins.fromTOML (builtins.readFile ../Cargo.toml)).package) version;
in
rustPlatform.buildRustPackage {
pname = "slop-broker";
inherit ((builtins.fromTOML (builtins.readFile ../Cargo.toml)).package) version;
inherit version;
src = toSource {
root = ../.;
@@ -16,6 +19,10 @@ 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
+263 -117
View File
@@ -1,209 +1,355 @@
# 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
# 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.
repository = pkgs.runCommand "test-repository" { nativeBuildInputs = [ pkgs.git ]; } ''
mkdir $out
cat > $out/flake.nix <<'EOF'
{
outputs = _: {
deploy.sshUser = "deploy";
deploy.nodes = {
# Profiles aren't built here; their names say which containers there are
local = { hostname = "localhost"; profiles = { system = { }; container-web = { }; }; };
other.hostname = "localhost";
denied.hostname = "localhost";
};
};
}
EOF
install -m755 ${pkgs.pkgsStatic.busybox}/bin/busybox $out/busybox
git -C $out init --quiet --initial-branch=master
git -C $out add flake.nix
git -C $out -c user.name=test -c user.email=test@example.org commit --quiet -m "Add nodes"
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
'';
# 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.machine = { ... }: {
imports = [ ./modules/nixos/broker.nix ./modules/nixos/builder.nix ];
config = {
boot.kernelModules = [ "vsock_loopback" ];
services.openssh.enable = true;
users.users.deploy = { isNormalUser = true; openssh.authorizedKeys.keyFiles = [ "${key}/key.pub" ]; };
users.users.reviewer.isNormalUser = true;
users.users.agent.isNormalUser = true;
environment.systemPackages = [ pkgs.util-linux ];
# Container commands go through `systemd-machined`, as root
security.sudo.extraRules = [ { users = [ "deploy" ]; commands = [ { command = "ALL"; options = [ "NOPASSWD" ]; } ]; } ];
containers.web = {
autoStart = true;
config.system.stateVersion = lib.trivial.release;
};
virtualisation.memorySize = 2048;
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";
nodes.box = { ... }: {
imports = [ deployNode ./modules/nixos/cache.nix ];
services.slop-broker = {
enable = true;
package = slop-broker;
approvers = [ "reviewer" ];
policies.agent.ops = {
query.action = "auto";
ssh = { action = "ask"; leases = [ "5m" ]; rules = [ { match.target = "denied"; action = "deny"; } ]; };
};
policies.workstation.ops.query.action = "auto";
requesters.agent = {
vsockCid = 1;
policy = "agent";
};
requesters.workstation = {
sshKeys = [ (publicKey "requester") ];
policy = "workstation";
};
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;
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 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 ];
# 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 ];
# A container for the container commands, which go through `systemd-machined` as root
containers.web = {
autoStart = true;
config.system.stateVersion = lib.trivial.release;
};
# 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.workstation.ops.query.action = "auto";
requesters.agent = {
vsockCid = 1;
policy = "agent";
};
requesters.workstation = {
sshKeys = [ (publicKey "requester") ];
policy = "workstation";
};
sshApprovers.laptop = [ (publicKey "approver") ];
ssh = {
enable = true;
inherit keyFile;
};
deploy.enable = true;
cache = {
enable = true;
hostname = "box";
user = "cache";
inherit keyFile;
};
};
# 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")
env = "SLOP_BROKER=vsock:1:6262 SLOP_LABEL='vm test'"
# Policy
# Denied by policy, without asking
status, out = machine.execute(f"su agent -c \"{env} slop ssh denied -- true\" 2>&1")
status, out = try_slop("ssh denied -- true")
assert status == 125 and "denied by policy" in out, (status, out)
# Fixed queries run without asking
out = machine.succeed(f"su agent -c \"{env} slop status local sshd.service\"")
out = slop("status local sshd.service")
assert "sshd.service" in out, out
out = machine.succeed(f"su agent -c \"{env} slop logs local sshd.service -n 5 --since 1h\"")
print(out)
print(slop("logs local sshd.service -n 5 --since 1h"))
# 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'")
# 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")
print(listing)
assert "vm test" in listing
request = listing.split()[0][:4]
status, out = machine.execute("su agent -c 'slop-approve " + request + " once' 2>&1")
status, out = machine.execute(f"su agent -c 'slop-approve {request} once' 2>&1")
assert status != 0, out
machine.succeed(f"su reviewer -c 'slop-approve {request} 5m'")
approve(f"{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(f"echo piped | su agent -c \"{env} slop ssh local -- cat\"")
out = machine.succeed("echo piped | " + agent("slop ssh local -- cat"))
assert "piped" in out, out
out = machine.succeed(f"su agent -c \"{env} slop requests\"")
out = slop("requests")
assert "ssh" in out and "lease" in out, out
# Containers: queries run without asking, as for nodes; ssh asks again, since the lease is
# for the host
# Containers
# Queries run without asking, as for nodes
machine.wait_for_unit("container@web.service")
out = machine.succeed(f"su agent -c \"{env} slop status local.container-web systemd-journald.service\"")
out = slop("status local.container-web systemd-journald.service")
assert "systemd-journald.service" in out, out
out = machine.succeed(f"su agent -c \"{env} slop failed local.container-web\"")
print(out)
out = machine.succeed(f"su agent -c \"{env} slop logs local.container-web systemd-journald.service -n 5\"")
print(out)
status, out = machine.execute(f"su agent -c \"{env} slop failed local.container-nope\" 2>&1")
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 = machine.execute(f"su agent -c \"{env} slop failed local.system\" 2>&1")
status, out = try_slop("failed local.system")
assert status == 125 and "only containers" in out, (status, out)
machine.execute(f"echo from stdin | su agent -c \"{env} slop ssh local.container-web -- 'cat; echo in \\$(hostname) as \\$(whoami); exit 3'; echo exit \\$?\" > /tmp/out5 2>&1 &")
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh local.container-web'")
machine.succeed("su reviewer -c 'slop-approve once'")
# `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 = machine.execute(f"su agent -c \"{env} slop ssh nope -- true\" 2>&1")
status, out = try_slop("ssh nope -- true")
assert status == 125 and "unknown node nope;" in out, (status, out)
status, out = machine.execute(f"su agent -c \"{env} slop ssh\" 2>&1")
status, out = try_slop("ssh")
assert status == 125, (status, out)
# Interactive answering on a terminal
machine.execute(f"su agent -c \"{env} slop ssh other -- echo interactive\" > /tmp/out2 2>&1 &")
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
# 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")
out = machine.succeed("(sleep 1; echo x; sleep 1; echo o) | timeout 5 su reviewer -c \"script -qec slop-approve /dev/null\" || true")
print(out)
assert "Not an option" in out and "Recorded: once" in out, out
machine.wait_until_succeeds("grep -q interactive /tmp/out2")
# The only pending request can be answered without its ID
machine.execute(f"su agent -c \"{env} slop ssh other -- true; echo \\$?\" > /tmp/out3 2>&1 &")
machine.wait_until_succeeds("su reviewer -c 'slop-approve list' | grep -q 'ssh other'")
machine.succeed("su reviewer -c 'slop-approve deny'")
slop_in_background("slop ssh other -- true; echo \\$?", "/tmp/out3")
wait_for_request("ssh other")
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
# 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
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 = machine.succeed(f"su agent -c \"{remote} slop status local sshd.service\"")
out = slop("status local sshd.service", broker=remote)
assert "sshd.service" in out, out
status, out = machine.execute(f"su agent -c \"{remote} slop ssh local -- true\" 2>&1")
status, out = try_slop("ssh local -- true", broker=remote)
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)
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'")
# The approver's key answers as `laptop`
slop_in_background("slop ssh other -- echo remote approval", "/tmp/out4")
wait_for_request("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 /etc/slop-broker-test/key /root/builder-key")
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
audit = machine.succeed("su reviewer -c 'slop-approve log'")
# 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")
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
@@ -0,0 +1,46 @@
# 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";
};
};
}
+1 -1
View File
@@ -12,7 +12,7 @@ use slop_broker::server::{self, Broker};
use slop_broker::{approve, web};
#[derive(Parser)]
#[command(about = "Approval broker for coding agents")]
#[command(version = slop_broker::VERSION, about = "Approval broker for coding agents")]
enum Command {
/// Run the broker.
Serve {
+2
View File
@@ -27,6 +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\
+24 -7
View File
@@ -468,6 +468,10 @@ 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(())
}
@@ -693,15 +697,28 @@ async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResu
#[derive(Deserialize)]
struct Built {
#[serde(rename = "drvPath")]
drv_path: String,
outputs: BTreeMap<String, String>,
}
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 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_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();
+7
View File
@@ -15,3 +15,10 @@ 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"),
};
-5
View File
@@ -279,11 +279,6 @@ 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 {
+3 -2
View File
@@ -176,8 +176,9 @@ 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 (the broker uses {PROTOCOL_VERSION}); update slop",
request.version
"protocol version {} is not supported (slop-broker {} uses {PROTOCOL_VERSION}); update slop",
request.version,
crate::VERSION
)));
}
+43 -26
View File
@@ -18,36 +18,48 @@ function formatLeft(seconds) {
return `${seconds}s`;
}
setInterval(() => {
function showCountdowns() {
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);
}
// Polls for changes to the pending set while the page is visible.
async function refresh() {
const pending = document.getElementById("pending");
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() {
const request = document.getElementById("request");
const container = pending || request;
if (!container || document.hidden) return;
if ((!document.getElementById("pending") && !request) || !("EventSource" in window)) return;
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;
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);
});
}
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);
// Whether a details element stays open or closed is the approver's.
function keepOpen(attribute, element) {
return !(attribute === "open" && element.tagName === "DETAILS");
}
function base64urlToBytes(text) {
@@ -128,8 +140,13 @@ function localTimes(root) {
}
}
localTimes(document);
startCountdowns(document);
setInterval(() => refresh().catch(() => {}), 3000);
document.addEventListener("visibilitychange", () => refresh().catch(() => {}));
// What rendered times need, for the page or a region of it
function ready(root) {
localTimes(root);
startCountdowns(root);
showCountdowns();
}
ready(document);
listen();
setUpPush().catch(() => {});
File diff suppressed because it is too large. Load diff
+4
View File
@@ -72,6 +72,10 @@ nav a {
margin-right: 16px;
}
.account .version {
font-size: 0.875em;
}
main {
max-width: 960px;
margin: 0 auto;
+187
View File
@@ -0,0 +1,187 @@
//! 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}");
}
}
+30 -23
View File
@@ -2,6 +2,7 @@
//! 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;
@@ -81,10 +82,9 @@ 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("/api/version", get(version))
.route("/events", get(page_events))
.route("/api/csrf", get(csrf))
.route("/push/key", get(push_key))
.route("/push/subscribe", post(subscribe))
@@ -94,6 +94,7 @@ 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")) }))
@@ -204,14 +205,7 @@ 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, 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())
Ok(page::index(&user.name, &user.csrf, &entries, &leases).into_response())
}
async fn request_page(
@@ -223,14 +217,32 @@ async fn request_page(
Ok(user) => user,
Err(redirect) => return Ok(redirect),
};
// 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())
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))
}
#[derive(Deserialize)]
@@ -310,11 +322,6 @@ 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())
+47 -32
View File
@@ -13,6 +13,9 @@ 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;
@@ -82,7 +85,7 @@ pub fn message(title: &str, text: &str) -> Html<String> {
render(Message { title, text })
}
/// The pending requests and leases, which the page script swaps in when they change.
/// The pending requests and leases: the main page's region that the page script keeps current.
#[derive(Template)]
#[template(path = "pending.html")]
struct Pending<'a> {
@@ -91,8 +94,8 @@ struct Pending<'a> {
leases: &'a [(String, String, u64)],
}
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> Html<String> {
render(Pending { csrf, entries, leases })
pub fn pending(csrf: &str, entries: &[PendingInfo], leases: &[(String, String, u64)]) -> String {
render(Pending { csrf, entries, leases }).0
}
#[derive(Template)]
@@ -102,17 +105,27 @@ 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)],
version: u64,
) -> Html<String> {
render(Index { name, csrf, entries, leases, version })
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)),
}
}
}
#[derive(Template)]
@@ -120,26 +133,23 @@ pub fn index(
struct Request<'a> {
name: &'a str,
csrf: &'a str,
heading: String,
entry: Option<&'a PendingInfo>,
past: Option<&'a History>,
version: u64,
view: &'a RequestView<'a>,
}
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 })
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
}
/// What the log page is filtered by.
@@ -256,7 +266,8 @@ mod tests {
offers: vec![Decision::Once, Decision::Lease(300), Decision::Deny],
expires_in: 125,
};
let html = pending("token", &[entry], &[]).0;
let html = pending("token", &[entry], &[]);
assert!(html.starts_with("<div id=\"pending\">") && html.trim_end().ends_with("</div>"), "{html}");
assert!(html.contains(r#"value="5m""#));
assert!(html.contains("For 5m"));
assert!(html.contains("ssh river &#60;x&#62;"));
@@ -296,9 +307,13 @@ mod tests {
];
let (histories, _) = super::history::gather(records);
let html = request("broker", "token", "abc", None, Some(&histories[0]), 0).0;
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,6 +7,7 @@
<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>
@@ -14,6 +15,7 @@
<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,7 +5,5 @@
<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 %}
+2
View File
@@ -1,4 +1,5 @@
{%- import "macros.html" as m -%}
<div id="pending">
{% if entries.is_empty() %}
<p class="empty">Nothing is waiting for an answer.</p>
{% endif %}
@@ -13,3 +14,4 @@
{% endfor %}
</tbody></table>
{% endif %}
</div>
+1 -16
View File
@@ -1,20 +1,5 @@
{% extends "base.html" %}
{% import "macros.html" as m %}
{% block title %}Approval request{% endblock %}
{% block main %}
<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>
{% include "request_region.html" %}
{% endblock %}
+16
View File
@@ -0,0 +1,16 @@
{%- 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>