gunk-dev/the-valley

worker-e2e.nix

sourced7aca57f4c15main's published tip history
15.7 KiB
1# The check worker on a host: one NixOS machine running the module with the
2# worker on, beside the controllers and the registry compiler, and a
3# project with ready changes. The worker makes its key the first time it
4# starts, readable by it alone, and says its public halves. Until the
5# registry holds the key, the worker cannot reach the host's repositories.
6# Once it does, a pass builds the nix checks a ready change requires, one
7# build at a time, through the machine's nix daemon, and the evidence is on
8# origin before anyone approves the change. The timer runs the next pass.
9# Then a change whose check eats memory without end is built, and the
10# kernel stops the build at the slice's memory cap while the rest of the
11# host goes on as it was.
12#
13# The operator's caps are 4 CPUs and 8 GiB. The machine here has 2 GiB, so
14# the memory cap is lowered at runtime, after the check reads the module's
15# own values off the slice, to let a build run past it. module-eval holds
16# the values the module renders.
17{
18 pkgs,
19 lib,
20 self,
21 packages,
22 ...
23}:
24let
25 # Throwaway keys, made once at build time. They hold no authority
26 # anywhere: the machine that trusts them exists for one test run. The
27 # worker's key is not among them: the worker makes its own on the host.
28 keys = pkgs.runCommand "valley-worker-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
29 mkdir $out
30 for who in integrator contributor; do
31 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
32 done
33 '';
34 pub = who: lib.fileContents "${keys}/${who}.pub";
35
36 declaration = pkgs.writeText "valley-worker-e2e.cue" ''
37 package valley
38
39 projects: {
40 // The instance repository, which carries the floor and the registry.
41 "instance": protection: refs: ["refs/heads/main"]
42 "project": protection: {}
43 }
44 '';
45
46 # A floor that requires two nix checks of every change.
47 floor = pkgs.writeText "floor.cue" ''
48 package verification
49
50 floor: {
51 checks: {
52 first: {runner: "nix", attribute: "first"}
53 second: {runner: "nix", attribute: "second"}
54 }
55 classes: {}
56 unclassified: {first: true, second: true}
57 }
58 '';
59
60 # The project's flake, with no inputs, so the machine builds it offline.
61 # Each check runs a script from the project's tree in the sandbox's
62 # shell, and the script is the derivation's one input. The project's own
63 # scripts spin for a few seconds, so two builds at once would be seen at
64 # once, and write the cores the daemon gave them. The runaway change's
65 # first script instead doubles a string until something stops it.
66 flake = pkgs.writeText "flake.nix" ''
67 {
68 outputs =
69 { self }:
70 let
71 check = name: script: derivation {
72 inherit name;
73 system = "x86_64-linux";
74 builder = "/bin/sh";
75 args = [ script ];
76 };
77 in
78 {
79 checks.x86_64-linux = {
80 first = check "worker-first" ./first.sh;
81 second = check "worker-second" ./second.sh;
82 };
83 };
84 }
85 '';
86 flakeLock = pkgs.writeText "flake.lock" ''{"nodes":{"root":{}},"root":"root","version":7}'';
87 spin = pkgs.writeText "spin.sh" ''
88 i=0
89 while [ $i -lt 1000000 ]; do i=$((i+1)); done
90 echo $NIX_BUILD_CORES > $out
91 '';
92 runaway = pkgs.writeText "runaway.sh" ''
93 x=a
94 while :; do x=$x$x; done
95 '';
96
97 # What the daemon's builds look like while the worker runs: the number
98 # of build users with a process, and the cgroup of each such process,
99 # sampled ten times a second.
100 sampler = pkgs.writeShellScript "valley-worker-e2e-sampler" ''
101 PATH=${
102 lib.makeBinPath [
103 pkgs.coreutils
104 pkgs.gawk
105 pkgs.procps
106 ]
107 }
108 while :; do
109 ps -eo user:32=,cgroup:512= | awk '$1 ~ /^nixbld/' > /tmp/sample
110 awk '{print $1}' /tmp/sample | sort -u | wc -l >> /tmp/builders
111 awk '{print $2}' /tmp/sample >> /tmp/build-cgroups
112 sleep 0.1
113 done
114 '';
115in
116{
117 worker-e2e = pkgs.testers.runNixOSTest {
118 name = "valley-worker-e2e";
119 nodes.host = {
120 imports = [ self.nixosModules.default ];
121 # Two CPUs, so attest could run two builds at once if the unit let it.
122 virtualisation.cores = 2;
123 virtualisation.memorySize = 2048;
124 environment.systemPackages = [
125 pkgs.git
126 packages.valley
127 ];
128 services.valley = {
129 enable = true;
130 config = declaration;
131 authorizedKeys = [
132 {
133 principal = "contributor";
134 key = pub "contributor";
135 }
136 ];
137 identity.enable = true;
138 integrator = {
139 enable = true;
140 signingKeyFile = "${keys}/integrator";
141 instanceProject = "instance";
142 signerProjects."worker/attestations" = [ "project" ];
143 };
144 worker = {
145 enable = true;
146 projects = [ "project" ];
147 signerName = "worker/attestations";
148 };
149 };
150 # NixOS test machines panic on any OOM, a cgroup's included
151 # (test-instrumentation.nix). A host does not, and the runaway build
152 # below is stopped by the slice's OOM, so a host's default is restored.
153 boot.kernel.sysctl."vm.panic_on_oom" = 0;
154 # The test starts each pass itself until it checks the timer, so no
155 # pass runs before the test is ready for it.
156 systemd.timers.valley-worker.timerConfig.OnBootSec = lib.mkForce "1h";
157 };
158
159 testScript = ''
160 import shlex
161
162 host.wait_for_unit("multi-user.target")
163 host.succeed("systemctl is-active valley-worker.timer")
164 host.succeed("systemctl stop valley-worker.timer")
165
166 git = "sudo -u git git"
167 state = "/var/lib/valley-worker"
168 ssh = shlex.quote(
169 "ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
170 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"
171 )
172 contributor = f"cd /root/project && GIT_SSH_COMMAND={ssh}"
173 commit = "git -c user.name=contributor -c user.email=contributor@localhost commit --quiet"
174
175 def journal():
176 return host.succeed("journalctl -u valley-worker -o cat")
177
178 def attestations():
179 return host.succeed(
180 f"{git} -C /srv/git/project.git for-each-ref --format='%(refname)' refs/the-valley/attestations/"
181 ).split()
182
183 def registry(worker):
184 principals = [
185 '"contributor": {',
186 ' kind: "human"',
187 ' keys: [{class: "ssh-ed25519", bound: "host", public: "${
188 lib.concatStringsSep " " (lib.take 2 (lib.splitString " " (pub "contributor")))
189 }"}]',
190 ' grants: {push: boundary: "push", govern: boundary: "registry"}',
191 "}",
192 ]
193 if worker:
194 principals += [
195 '"worker": {',
196 ' kind: "machine"',
197 f' keys: [{{class: "ssh-ed25519", bound: "host", public: "{worker}", signs: "worker/attestations"}}]',
198 ' grants: push: boundary: "push"',
199 ' expires: "2099-01-01"',
200 "}",
201 ]
202 return "\n".join(
203 [
204 "package identity",
205 'boundaries: {"push": kind: "git-push", "registry": kind: "registry"}',
206 'genesis: "contributor"',
207 "principals: {",
208 ]
209 + principals
210 + ["}"]
211 )
212
213 # The instance's main carries the floor and the registry. It is
214 # landed by a local write, which runs no hook, as an operator seeds
215 # a protected repository.
216 def land_instance(worker):
217 host.succeed(
218 "rm -rf /tmp/instance && mkdir -p /tmp/instance/policy/instance /tmp/instance/identity",
219 "cp ${floor} /tmp/instance/policy/instance/floor.cue",
220 f"cat > /tmp/instance/identity/registry.cue <<'EOF'\n{registry(worker)}\nEOF",
221 f"cd /tmp/instance && git init --quiet --initial-branch=main && git add -A && {commit} -m instance",
222 "chown -R git:git /tmp/instance",
223 f"{git} -C /srv/git/instance.git fetch --quiet --force /tmp/instance main:refs/heads/main",
224 "systemctl start valley-identity.service",
225 )
226
227 # A branch of the project with the first check's script given,
228 # pushed by the contributor and readied.
229 def ready(branch, first):
230 host.succeed(
231 f"cd /root/project && git checkout --quiet -b {branch} origin/main",
232 f"cp {first} /root/project/first.sh && echo {branch} >> /root/project/README.md",
233 f"cd /root/project && git add -A && {commit} -m {branch}",
234 f"{contributor} git push --quiet origin {branch}",
235 f"{contributor} valley ready {branch}",
236 )
237
238 with subtest("the instance and the project are seeded, and a change is ready"):
239 land_instance(None)
240 host.succeed(
241 "mkdir -p /tmp/project/policy",
242 "cp ${flake} /tmp/project/flake.nix",
243 "cp ${flakeLock} /tmp/project/flake.lock",
244 "cp ${spin} /tmp/project/first.sh",
245 "cp ${spin} /tmp/project/second.sh",
246 "echo 'git@host:instance.git' > /tmp/project/policy/valley",
247 "echo project > /tmp/project/README.md",
248 f"cd /tmp/project && git init --quiet --initial-branch=main && git add -A && {commit} -m project",
249 "chown -R git:git /tmp/project",
250 f"{git} -C /srv/git/project.git fetch --quiet /tmp/project main:refs/heads/main",
251 "mkdir -p /root/keys && install -m 600 ${keys}/contributor /root/keys/contributor",
252 f"GIT_SSH_COMMAND={ssh} git clone --quiet git@localhost:project.git /root/project",
253 "git -C /root/project config valley.principal contributor",
254 "git -C /root/project config user.name contributor",
255 "git -C /root/project config user.email contributor@localhost",
256 )
257 ready("good", "${spin}")
258
259 with subtest("the first start makes the key, readable by the worker alone, and says its public halves"):
260 host.fail(f"test -e {state}/key")
261 # Not enrolled yet, so the host's sshd turns the worker away and
262 # the pass stops before it builds anything.
263 host.fail("systemctl start valley-worker.service")
264 assert host.succeed(f"stat -c '%a %U %G' {state}").strip() == "700 valley-worker valley-worker"
265 assert host.succeed(f"stat -c '%a %U %G' {state}/key").strip() == "400 valley-worker valley-worker"
266 host.succeed(f"test -f {state}/key && test ! -L {state}/key")
267 for other in ["git", "valley-integrator", "nobody"]:
268 host.fail(f"sudo -u {other} cat {state}/key")
269 public = host.succeed(f"cat {state}/key.pub").strip()
270 verifier = host.succeed(f"cat {state}/verifier").strip()
271 assert verifier.startswith("worker/attestations+"), verifier
272 keyhash = verifier.split("+")[1]
273 said = journal()
274 assert f"the worker's ssh public key is {public}" in said, said
275 assert f"the worker's verifier line is {verifier}" in said, said
276 assert "PRIVATE KEY" not in said, said
277 assert host.succeed(f"ssh-keygen -y -f {state}/key").split()[1] == public.split()[1]
278 assert attestations() == []
279
280 with subtest("enrolled in the registry, the worker builds the ready change's checks one at a time and publishes them"):
281 land_instance(" ".join(public.split()[:2]))
282 host.succeed(f"grep -q '^worker/attestations+{keyhash}+' /var/lib/valley-identity/known-signers")
283 host.wait_until_succeeds(
284 f"{git} -C /srv/git/instance.git cat-file blob refs/the-valley/signers:known-signers"
285 f" | grep -q '^worker/attestations+{keyhash}+'",
286 timeout=60,
287 )
288 host.succeed("systemd-run --unit=valley-worker-e2e-sampler ${sampler}")
289 host.succeed("systemctl start valley-worker.service")
290 host.succeed("systemctl stop valley-worker-e2e-sampler")
291 said = journal()
292 assert "building first, second" in said, said
293 refs = attestations()
294 assert len(refs) == 1 and refs[0].endswith(f"/{keyhash}"), refs
295 assert f"published {refs[0]}" in said, said
296 for check in ["first", "second"]:
297 host.succeed(f"{git} -C /srv/git/project.git cat-file -e {refs[0]}:{check}/statement.note")
298 # One build at a time, each in the daemon's cgroup, inside the
299 # slice, each told it may use 4 cores.
300 builders = [int(n) for n in host.succeed("cat /tmp/builders").split()]
301 assert max(builders) == 1, builders
302 cgroups = set(host.succeed("cat /tmp/build-cgroups").split())
303 assert cgroups and all(c.startswith("0::/valley.slice/valley-builds.slice/nix-daemon.service") for c in cgroups), cgroups
304 for check in ["first", "second"]:
305 assert host.succeed(f"cat /nix/store/*-worker-{check}").strip() == "4", check
306 for unit in ["valley-worker.service", "nix-daemon.service"]:
307 assert host.succeed(f"systemctl show -p Slice --value {unit}").strip() == "valley-builds.slice", unit
308
309 with subtest("the timer runs the next pass, which finds the evidence on origin and builds nothing"):
310 host.succeed("systemctl start valley-worker.timer")
311 host.wait_until_succeeds(
312 "journalctl -u valley-worker -o cat | grep -q 'origin holds evidence for every nix check it requires'",
313 timeout=150,
314 )
315 host.succeed("systemctl stop valley-worker.timer")
316 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-worker)\" != activating")
317 assert len(attestations()) == 1
318
319 with subtest("the slice holds the operator's caps"):
320 cgroup = "/sys/fs/cgroup/valley.slice/valley-builds.slice"
321 assert host.succeed(f"cat {cgroup}/cpu.max").strip() == "400000 100000"
322 assert host.succeed(f"cat {cgroup}/memory.max").strip() == str(8 * 1024**3)
323 assert host.succeed(f"cat {cgroup}/memory.swap.max").strip() == "0"
324
325 with subtest("a runaway build is stopped at the memory cap, and the rest of the host stays healthy"):
326 ready("runaway", "${runaway}")
327 host.succeed("systemctl set-property --runtime valley-builds.slice MemoryMax=512M")
328 assert host.succeed(f"cat {cgroup}/memory.max").strip() == str(512 * 1024**2)
329 failed_before = set(host.succeed("systemctl list-units --state=failed --no-legend --plain | cut -d' ' -f1").split())
330 host.fail("systemctl start valley-worker.service")
331 said = journal()
332 assert "the batch did not pass" in said, said
333 kills = host.succeed(f"sed -n 's/^oom_kill //p' {cgroup}/memory.events").strip()
334 assert int(kills) >= 1, kills
335 assert len(attestations()) == 1
336 # The units the host runs are as they were, the daemon still
337 # answers, and the git user still serves pushes and fetches.
338 host.succeed(
339 "systemctl is-active sshd.service nix-daemon.service nix-daemon.socket"
340 " valley-integrator@instance.service valley-integrator@project.service"
341 )
342 failed_after = set(host.succeed("systemctl list-units --state=failed --no-legend --plain | cut -d' ' -f1").split())
343 assert failed_after <= failed_before | {"valley-worker.service"}, failed_after
344 host.succeed("nix-store --store daemon --query --hash /run/current-system")
345 host.succeed(f"{contributor} git ls-remote origin refs/heads/runaway | grep -q runaway")
346 # The failed batch waits before it is built again.
347 host.succeed("systemctl start valley-worker.service")
348 assert "failed 1 time in a row, so it is not built again before" in journal()
349 '';
350 };
351}