From 3f024cd11526065d55caed46f236ff344f153623 Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Sun, 29 Nov 2026 13:19:26 +0000 Subject: [PATCH] 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 --- devenv.nix | 363 +--------------------------------------- docs/architecture.md | 4 +- docs/demo.md | 2 +- nix/demo/agent.nix | 8 +- nix/demo/box.nix | 23 ++- nix/demo/host.nix | 375 ++++++++++++++++++++++++++++++++++++++++++ nix/demo/settings.nix | 2 +- 7 files changed, 406 insertions(+), 371 deletions(-) create mode 100644 nix/demo/host.nix diff --git a/devenv.nix b/devenv.nix index a1ff3a7..d055d50 100644 --- a/devenv.nix +++ b/devenv.nix @@ -1,369 +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`, 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 \` 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}/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"; - }; - - 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 } - 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 \`" >&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" </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` diff --git a/docs/architecture.md b/docs/architecture.md index d73ca92..822579d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -144,8 +144,8 @@ What each request runs, and whose code, decides whether it needs an approval fir | `tests/broker.rs` | Handler tests over an in-memory duplex stream with a fake `ssh` | | `src/web/` | The approvals web app: routes (`mod.rs`), OIDC sign-in and passkey confirmation (`auth.rs`), Web Push (`push.rs`), the audit log by request (`history.rs`), the pages (`page.rs`) and static assets | | `templates/`, `askama.toml` | The web app's HTML, as [askama](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..vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs and repository template (`demo/`, `packages..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..vm`), clippy and rustfmt checks (`lints.nix`) and the demo's VMs, host side and repository template (`demo/`, `packages..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 diff --git a/docs/demo.md b/docs/demo.md index 82a0092..af1cc9d 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -64,7 +64,7 @@ flowchart TB 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 diff --git a/nix/demo/agent.nix b/nix/demo/agent.nix index ce6e106..c4201e7 100644 --- a/nix/demo/agent.nix +++ b/nix/demo/agent.nix @@ -65,11 +65,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 +83,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 +92,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 diff --git a/nix/demo/box.nix b/nix/demo/box.nix index 2cab6c3..1b62d9b 100644 --- a/nix/demo/box.nix +++ b/nix/demo/box.nix @@ -1,11 +1,14 @@ -# 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, +# with a `box` account for the broker's key, which may use `sudo` and copy store paths, so the +# broker can deploy to it. +# +# `devenv up` runs it with `SHARED_DIR` holding the broker's public key and the box's host key, +# which it keeps between runs so the broker's `known_hosts` stays valid. { pkgs }: let inherit (pkgs) lib; settings = import ./settings.nix; + hostKey = "/etc/ssh/ssh_host_ed25519_key"; in (pkgs.nixos ({ config, modulesPath, ... }: { @@ -27,9 +30,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 +41,13 @@ in trusted-users = [ "root" "box" ]; substituters = lib.mkForce [ ]; }; + 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 +56,11 @@ 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 + 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 ''; }; })).vm diff --git a/nix/demo/host.nix b/nix/demo/host.nix new file mode 100644 index 0000000..826e122 --- /dev/null +++ b/nix/demo/host.nix @@ -0,0 +1,375 @@ +# 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 \` 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" ]; + }; + + # 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"; + }; + + 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 } + 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 \`" >&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" </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" ]; + }; + }; +} diff --git a/nix/demo/settings.nix b/nix/demo/settings.nix index b598111..8b19d46 100644 --- a/nix/demo/settings.nix +++ b/nix/demo/settings.nix @@ -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;