gunk-dev/the-valley

publish-e2e.nix

source58e68be0d151main's published tip history
17.4 KiB
1# An integrator landing, published: one NixOS machine running the module
2# with a controller, the bus and a push mirror, and a change that lands by
3# integration rather than by push. The landing has to reach the mirror and
4# the bus exactly as a push does, though the integrator moves the ref with
5# update-ref under its own user, and post-receive never runs. The mirror is
6# missing at first. The landing's event has to reach the bus anyway, at
7# once, and the landing has to stay queued through the failed mirror push
8# until a later run of the drain publishes it. The test starts that run
9# itself: when systemd retries a failed run is the module's restart
10# settings, which module-eval holds. The host also publishes, in its
11# instance repository, the signers a client verifies the landing with, and
12# publishes them again when the signers file is replaced. No push over ssh
13# replaces that publication or deletes it. The controllers pass on a
14# one-hour interval, so every landing here is started by a mark in a
15# controller's wake directory: the host's hook on a push, and the instance
16# controller's own mark after it lands the floor.
17{
18 pkgs,
19 lib,
20 self,
21 packages,
22 ...
23}:
24let
25 # Throwaway keys, made once at build time, and the signers file the
26 # controller is given. They hold no authority anywhere: the machine that
27 # trusts them exists for one test run. forged_signer is the contributor's
28 # key under the integrator's name, what a forged publication would hold.
29 keys =
30 pkgs.runCommand "valley-publish-e2e-keys"
31 {
32 nativeBuildInputs = [
33 pkgs.openssh
34 packages.attest
35 ];
36 }
37 ''
38 mkdir $out
39 for who in integrator contributor; do
40 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
41 done
42 attest key --key "$out/contributor" --name contributor/attestations > "$out/known_signers"
43 attest key --key "$out/integrator" --name host/attestations > "$out/integrator_signer"
44 attest key --key "$out/contributor" --name host/attestations > "$out/forged_signer"
45 '';
46
47 declaration = pkgs.writeText "valley-publish-e2e.cue" ''
48 package valley
49
50 projects: {
51 // The instance repository, which carries the floor.
52 "instance": protection: refs: ["refs/heads/main"]
53 "project": {
54 protection: {}
55 mirrors: ["/srv/mirror.git"]
56 }
57 }
58 '';
59
60 # A floor that requires nothing, so a change lands on the strength of its
61 # delta applying, and the test needs no evidence and no nix evaluation.
62 floor = pkgs.writeText "floor.cue" ''
63 package verification
64
65 floor: {
66 checks: {}
67 classes: {}
68 unclassified: {}
69 }
70 '';
71in
72{
73 publish-e2e = pkgs.testers.runNixOSTest {
74 name = "valley-publish-e2e";
75 nodes.host = {
76 imports = [ self.nixosModules.default ];
77 environment.systemPackages = [
78 pkgs.git
79 pkgs.natscli
80 pkgs.jq
81 ];
82 # The signers file is a copy made at boot, at a path the test
83 # replaces as the registry compiler replaces its own file.
84 systemd.tmpfiles.rules = [
85 "d /var/lib/valley-signers-file 0755 root root - -"
86 "C /var/lib/valley-signers-file/known_signers 0644 root root - ${keys}/known_signers"
87 ];
88 services.valley = {
89 enable = true;
90 config = declaration;
91 authorizedKeys = [ (lib.fileContents "${keys}/contributor.pub") ];
92 bus.enable = true;
93 integrator = {
94 enable = true;
95 signingKeyFile = "${keys}/integrator";
96 knownSignersFile = "/var/lib/valley-signers-file/known_signers";
97 instanceProject = "instance";
98 interval = "1h";
99 };
100 };
101 };
102
103 testScript = ''
104 import json
105 import time
106
107 host.wait_for_unit("multi-user.target")
108 host.wait_for_unit("valley-publish@project.path")
109 host.wait_until_succeeds("test -d /srv/git/project.git/valley-publish-queue")
110
111 # The repositories belong to the git user, so git reads them as it.
112 git = "sudo -u git git"
113 queue = "/srv/git/project.git/valley-publish-queue"
114
115 def unit(prop):
116 return host.succeed(f"systemctl show -p {prop} --value valley-publish@project").strip()
117
118 # Every payload on the bus, as published.
119 def payloads():
120 out = host.succeed(
121 "n=$(nats --server nats://127.0.0.1:4222 stream info valley --json | jq .state.messages);"
122 " for i in $(seq 1 $n); do"
123 " nats --server nats://127.0.0.1:4222 stream get valley $i --json | jq -r .data | base64 -d; echo;"
124 " done"
125 )
126 return [line for line in out.splitlines() if line.strip()]
127
128 def events():
129 return [json.loads(line) for line in payloads()]
130
131 # The mirror does not exist yet, so the first push to it fails.
132
133 # Two commits: the floor, which is main on both repositories, and a
134 # change one commit ahead of it.
135 commit = "git -c user.name=valley-check -c user.email=valley-check@localhost commit --quiet"
136 host.succeed(
137 "mkdir -p /tmp/work/policy/instance",
138 "cp ${floor} /tmp/work/policy/instance/floor.cue",
139 f"cd /tmp/work && git init --quiet --initial-branch=main && git add -A && {commit} -m floor",
140 f"cd /tmp/work && echo change > change.txt && git add -A && {commit} -m change",
141 )
142 base = host.succeed("git -C /tmp/work rev-parse HEAD~1").strip()
143 change = host.succeed("git -C /tmp/work rev-parse HEAD").strip()
144 host.succeed("chown -R git:git /tmp/work")
145
146 # Seeded by fetching into the served repositories. A fetch runs no
147 # hook, so nothing here is published, and the mirror and the bus see
148 # only what the landing does.
149 def seed(repo, refspec):
150 host.succeed(f"{git} -C /srv/git/{repo}.git fetch --quiet /tmp/work {refspec}")
151
152 seed("instance", f"{base}:refs/heads/main")
153 seed("project", f"{base}:refs/heads/main")
154 host.fail(f"{git} -C /srv/mirror.git rev-parse --verify --quiet refs/heads/main")
155 # The request ref alone files the change for integration.
156 seed("project", f"{change}:refs/the-valley/integration-requests/main/one")
157
158 # The fetch ran no hook, so nothing marked the controller. The hook the
159 # host installed is run by hand as the git user, as a push runs it:
160 # moves of the integrator's own bookkeeping mark nothing, and the
161 # request's move marks the project's controller, which lands it at
162 # once on its one-hour interval.
163 wakes = "/run/valley-integrator-wake"
164 hook = "/srv/git/project.git/hooks/post-receive.d/valley-integrator-wake"
165 zero = "0" * 40
166
167 def due_passes(project):
168 return int(host.succeed(f"journalctl -u valley-integrator@{project} -o cat | grep -c '^pass: due$' || true").strip())
169
170 with subtest("the host's hook marks the controller for what it reads, and only that"):
171 host.succeed(f"test -L {hook}")
172 before = due_passes("project")
173 host.succeed(
174 f"printf '%s %s %s\\n' {zero} {change} refs/the-valley/integration-outcomes/main/one"
175 f" {zero} {change} refs/the-valley/knots | sudo -u git {hook}"
176 )
177 host.sleep(2)
178 assert due_passes("project") == before, "bookkeeping marked the controller"
179 marked = time.monotonic()
180 host.succeed(
181 f"printf '%s %s %s\\n' {zero} {change} refs/the-valley/integration-requests/main/one | sudo -u git {hook}"
182 )
183
184 # The change lands as one commit the integrator makes on the base,
185 # with the change's tree. That commit is what main, the mirror and
186 # the events carry from here on.
187 with subtest("the landing moves main"):
188 host.wait_until_succeeds(
189 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
190 )
191 took = time.monotonic() - marked
192 print(f"mark to landing, one-hour interval, VM: {took:.1f}s")
193 assert took < 60, took
194 assert due_passes("project") > before
195 landing = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
196 assert landing != change, "the change's own commit landed"
197 tree = f"{git} -C /srv/git/project.git rev-parse"
198 assert host.succeed(f"{tree} {landing}^{{tree}}") == host.succeed(f"{tree} {change}^{{tree}}")
199
200 with subtest("a failed mirror push keeps the move queued and fails the run"):
201 host.wait_until_succeeds(
202 "journalctl -t valley-mirror | grep -q 'project: push to /srv/mirror.git FAILED'", timeout=60
203 )
204 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
205 host.succeed(f"test -n \"$(ls -A {queue})\"")
206
207 # The integrator publishes the event itself, so the mirror being down
208 # does not hold it back. Its payload is byte for byte the one the host
209 # publishes for a push of the same move.
210 with subtest("the landing is on the bus while the mirror is down"):
211 host.wait_until_succeeds(
212 "nats --server nats://127.0.0.1:4222 stream get valley --last-for valley.git.project.ref-updated"
213 )
214 host.succeed(f"test -n \"$(ls -A {queue})\"")
215 moved = [p for p in payloads() if '"event":"ref-updated"' in p and '"ref":"refs/heads/main"' in p]
216 assert moved == [
217 f'{{"event":"ref-updated","repo":"project","ref":"refs/heads/main","old":"{base}","new":"{landing}"}}'
218 ], moved
219
220 with subtest("once the mirror is there, the next run pushes the queued move and empties the queue"):
221 host.succeed(
222 "mkdir /srv/mirror.git && chown git:git /srv/mirror.git",
223 f"{git} init --quiet --bare /srv/mirror.git",
224 "systemctl restart valley-publish@project",
225 )
226 assert host.succeed(f"{git} -C /srv/mirror.git rev-parse refs/heads/main").strip() == landing
227 host.wait_until_succeeds("journalctl -t valley-mirror | grep -q 'project: pushed to /srv/mirror.git'")
228 host.succeed(f"test -z \"$(ls -A {queue})\"")
229 assert unit("ActiveState") == "inactive"
230
231 with subtest("a move that cannot be deleted fails the run and stays queued, and the next run empties the queue"):
232 # A directory in the queue is a move rm -f cannot delete.
233 host.succeed(f"sudo -u git mkdir {queue}/stuck", f"sudo -u git touch {queue}/stuck/x")
234 host.wait_until_succeeds(
235 "journalctl -u valley-publish@project | grep -q 'cannot remove .*stuck'", timeout=60
236 )
237 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
238 host.succeed(f"test -e {queue}/stuck/x")
239 host.succeed("systemctl is-active valley-publish@project.path")
240 host.succeed(f"rm -r {queue}/stuck", "systemctl restart valley-publish@project")
241 host.succeed(f"test -z \"$(ls -A {queue})\"")
242 assert unit("ActiveState") == "inactive"
243
244 with subtest("the landing is one ref-updated event on the bus"):
245 moved = [e for e in events() if e["event"] == "ref-updated" and e["ref"] == "refs/heads/main"]
246 assert moved == [
247 {"event": "ref-updated", "repo": "project", "ref": "refs/heads/main", "old": base, "new": landing}
248 ], moved
249 landed = [e for e in events() if e["event"] == "integration-succeeded"]
250 assert len(landed) == 1 and landed[0]["new"] == landing, landed
251
252 # What a client verifies the landing with, in the instance repository:
253 # the controllers' signers file, and the name they sign under, which
254 # this host leaves to the default, the machine's own name. The file
255 # replaced by a rename, as the registry compiler replaces its own, is
256 # published again with no activation.
257 with subtest("the host publishes the controllers' signers, and again when the file changes"):
258 ref = "refs/the-valley/signers"
259 instance = f"{git} -C /srv/git/instance.git"
260 signers = "/var/lib/valley-signers-file/known_signers"
261 host.succeed(
262 f"test \"$({instance} cat-file -t {ref})\" = tree",
263 f"test \"$({instance} cat-file blob {ref}:integrator-name)\" = host/attestations",
264 f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}",
265 )
266 host.succeed(
267 f"cat {signers} ${keys}/integrator_signer > /var/lib/valley-signers-file/next",
268 f"mv -f /var/lib/valley-signers-file/next {signers}",
269 )
270 host.wait_until_succeeds(f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}", timeout=60)
271 host.succeed(f"{instance} cat-file blob {ref}:known-signers | grep -q '^host/attestations+'")
272
273 # Only the host's machinery writes the publication. A push over ssh,
274 # by a key the host authorizes, cannot replace it with a well-formed
275 # publication of a key the pusher holds, and cannot delete it.
276 with subtest("no push over ssh replaces or deletes the publication"):
277 host.wait_for_unit("sshd.service")
278 published = host.succeed(f"{instance} rev-parse {ref}").strip()
279 host.succeed(
280 "mkdir -p /root/keys",
281 "install -m 600 ${keys}/contributor /root/keys/contributor",
282 "git init --quiet --bare /root/forged.git",
283 )
284 forged = host.succeed(
285 "cd /root/forged.git"
286 " && name=$(echo host/attestations | git hash-object -w --stdin)"
287 " && file=$(git hash-object -w ${keys}/forged_signer)"
288 " && printf '100644 blob %s\\tintegrator-name\\n100644 blob %s\\tknown-signers\\n' $name $file | git mktree"
289 ).strip()
290 ssh = (
291 "GIT_SSH_COMMAND='ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
292 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'"
293 )
294 for refspec in [f"+{forged}:{ref}", f":{ref}"]:
295 out = host.fail(f"cd /root/forged.git && {ssh} git push git@localhost:instance.git {refspec} 2>&1")
296 assert f"{ref} is written only by the machinery on the host, and no push may write it" in out, out
297 assert host.succeed(f"{instance} rev-parse {ref}").strip() == published, refspec
298
299 # The wake directories are the host's: one per controller, owned by
300 # the integrator's user and the writers' group, which is the git user
301 # and the integrator's user. An idle one holds nothing.
302 with subtest("each controller's wake directory is its own, and a writer group's"):
303 for project in ["instance", "project"]:
304 assert host.succeed(f"stat -c '%a %U %G' {wakes}/{project}").strip() == "770 valley-integrator valley-integrator-wake"
305 host.wait_until_succeeds(f"test -z \"$(ls -A {wakes}/{project})\"")
306 members = host.succeed("getent group valley-integrator-wake").strip().split(":")[3].split(",")
307 assert sorted(members) == ["git", "valley-integrator"], members
308
309 # A push over ssh runs the dispatcher, whose hooks run in turn. A topic
310 # branch, which anyone may push, marks the project's controller and
311 # not the instance's.
312 with subtest("a push over ssh wakes the controller of the project it moved, and no other"):
313 host.succeed(
314 f"git init --quiet /root/topic && cd /root/topic && {commit} --allow-empty -m topic"
315 )
316 project_before, instance_before = due_passes("project"), due_passes("instance")
317 host.succeed(f"cd /root/topic && {ssh} git push --quiet git@localhost:project.git HEAD:refs/heads/topic")
318 host.wait_until_succeeds(f"test {project_before} -lt $(journalctl -u valley-integrator@project -o cat | grep -c '^pass: due$')", timeout=30)
319 host.sleep(2)
320 assert due_passes("instance") == instance_before, "a push to project woke the instance's controller"
321
322 # The floor moves by the instance's controller, which runs no hook. It
323 # marks the project's controller itself, from inside its sandbox, after
324 # the landing. The request is fetched, so only a push to a topic branch
325 # of the instance marks the instance's controller.
326 with subtest("a floor landed by the instance's controller wakes the controller that reads it"):
327 floor_base = host.succeed(f"{git} -C /srv/git/instance.git rev-parse refs/heads/main").strip()
328 host.succeed(
329 f"cd /tmp/work && sudo -u git git checkout --quiet -b floor {floor_base}",
330 "cd /tmp/work && sudo -u git sh -c 'echo moved > moved.txt' && sudo -u git git add moved.txt",
331 f"cd /tmp/work && sudo -u git {commit} -m 'the floor, moved'",
332 )
333 seed("instance", "floor:refs/the-valley/integration-requests/main/floor")
334 before = due_passes("project")
335 host.succeed(f"cd /root/topic && {ssh} git push --quiet git@localhost:instance.git HEAD:refs/heads/topic")
336 host.wait_until_succeeds(
337 f"test \"$({git} -C /srv/git/instance.git rev-parse refs/heads/main^)\" = {floor_base}", timeout=60
338 )
339 host.wait_until_succeeds(
340 f"journalctl -u valley-integrator@instance -o cat | grep -q '^ wake the floor reader at {wakes}/project is due$'",
341 timeout=30,
342 )
343 host.wait_until_succeeds(f"test {before} -lt $(journalctl -u valley-integrator@project -o cat | grep -c '^pass: due$')", timeout=30)
344 '';
345 };
346}