Files
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

356 lines
14 KiB
Nix

# 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.
repository = pkgs.runCommand "test-repository" { nativeBuildInputs = [ pkgs.git ]; } ''
mkdir $out
install -m755 ${pkgs.pkgsStatic.busybox}/bin/busybox $out/busybox
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
'';
# 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 ];
# 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")
# Policy
# Denied by policy, without asking
status, out = try_slop("ssh denied -- true")
assert status == 125 and "denied by policy" in out, (status, out)
# Fixed queries run without asking
out = slop("status local sshd.service")
assert "sshd.service" in out, out
print(slop("logs local sshd.service -n 5 --since 1h"))
# 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(f"su agent -c 'slop-approve {request} once' 2>&1")
assert status != 0, out
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("echo piped | " + agent("slop ssh local -- cat"))
assert "piped" in out, out
out = 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")
assert status == 125 and "unknown node nope;" in out, (status, out)
status, out = try_slop("ssh")
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")
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.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
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)
assert "sshd.service" in out, out
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)
# 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 ${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")
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
'';
}