diff --git a/devenv.nix b/devenv.nix index bd4389b..d055d50 100644 --- a/devenv.nix +++ b/devenv.nix @@ -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 \` 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 } - 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 a35935e..98cde2c 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -40,6 +40,7 @@ flowchart TB subgraph boxvm["Box VM"] sshd["sshd, as box
(nodes web, router, vault, box)"] + cache["sshd, as cache
(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 | | Part of the broker | | [Pocket ID](https://pocket-id.org), for approvers to sign in | | `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 \` 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 } + 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; diff --git a/nix/modules/nixos/cache.nix b/nix/modules/nixos/cache.nix index 2de8d31..3683017 100644 --- a/nix/modules/nixos/cache.nix +++ b/nix/modules/nixos/cache.nix @@ -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 = { diff --git a/nix/vm-test.nix b/nix/vm-test.nix index f7ca7d2..96d6ccc 100644 --- a/nix/vm-test.nix +++ b/nix/vm-test.nix @@ -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 ''; } diff --git a/nix/vm-test/flake.nix b/nix/vm-test/flake.nix new file mode 100644 index 0000000..de2ff88 --- /dev/null +++ b/nix/vm-test/flake.nix @@ -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"; + }; + }; +} diff --git a/src/builder.rs b/src/builder.rs index bff2f0f..b7dacb4 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -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, } - let built: Vec = 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 = 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(); diff --git a/src/web/assets/style.css b/src/web/assets/style.css index 2fd072c..946f19a 100644 --- a/src/web/assets/style.css +++ b/src/web/assets/style.css @@ -72,6 +72,10 @@ nav a { margin-right: 16px; } +.account .version { + font-size: 0.875em; +} + main { max-width: 960px; margin: 0 auto; diff --git a/src/web/page.rs b/src/web/page.rs index f33d9de..5ea240a 100644 --- a/src/web/page.rs +++ b/src/web/page.rs @@ -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 const VERSION: &str = env!("CARGO_PKG_VERSION"); + /// HTML escaping, after replacing what [`printable`] replaces. #[derive(Debug, Clone, Copy)] pub struct Printable; @@ -300,5 +303,6 @@ mod tests { assert!(html.contains("
Command
uptime
"), "{html}"); assert!(html.contains("+a"), "{html}"); assert!(html.contains("Details (Text)") && html.contains("
Old: text
"), "{html}"); + assert!(html.contains(&format!("slop-broker {VERSION}")), "{html}"); } } diff --git a/templates/base.html b/templates/base.html index d6bc518..10376a7 100644 --- a/templates/base.html +++ b/templates/base.html @@ -14,6 +14,7 @@