gunk-dev/the-valley

publish-e2e.nix

source4cbb5ec9c5dbmain's published tip history
17.6 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 knots, flow's conversation ref and the integrator's own
161 # bookkeeping mark nothing, and the request's move marks the project's
162 # controller, which lands it at 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"
176 f" {zero} {change} refs/the-valley/flow/data | sudo -u git {hook}"
177 )
178 host.sleep(2)
179 assert due_passes("project") == before, "bookkeeping marked the controller"
180 marked = time.monotonic()
181 host.succeed(
182 f"printf '%s %s %s\\n' {zero} {change} refs/the-valley/integration-requests/main/one | sudo -u git {hook}"
183 )
184
185 # The change lands as one commit the integrator makes on the base,
186 # with the change's tree. That commit is what main, the mirror and
187 # the events carry from here on.
188 with subtest("the landing moves main"):
189 host.wait_until_succeeds(
190 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
191 )
192 took = time.monotonic() - marked
193 print(f"mark to landing, one-hour interval, VM: {took:.1f}s")
194 assert took < 60, took
195 assert due_passes("project") > before
196 landing = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
197 assert landing != change, "the change's own commit landed"
198 tree = f"{git} -C /srv/git/project.git rev-parse"
199 assert host.succeed(f"{tree} {landing}^{{tree}}") == host.succeed(f"{tree} {change}^{{tree}}")
200
201 # The failure's reason is in the unit's own journal, which is what
202 # telemetry reads for the mirrors source.
203 with subtest("a failed mirror push says why, keeps the move queued and fails the run"):
204 host.wait_until_succeeds(
205 "journalctl -u valley-publish@project -o cat | grep -q 'project: push to /srv/mirror.git FAILED: .'", timeout=60
206 )
207 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
208 host.succeed(f"test -n \"$(ls -A {queue})\"")
209
210 # The integrator publishes the event itself, so the mirror being down
211 # does not hold it back. Its payload is byte for byte the one the host
212 # publishes for a push of the same move.
213 with subtest("the landing is on the bus while the mirror is down"):
214 host.wait_until_succeeds(
215 "nats --server nats://127.0.0.1:4222 stream get valley --last-for valley.git.project.ref-updated"
216 )
217 host.succeed(f"test -n \"$(ls -A {queue})\"")
218 moved = [p for p in payloads() if '"event":"ref-updated"' in p and '"ref":"refs/heads/main"' in p]
219 assert moved == [
220 f'{{"event":"ref-updated","repo":"project","ref":"refs/heads/main","old":"{base}","new":"{landing}"}}'
221 ], moved
222
223 with subtest("once the mirror is there, the next run pushes the queued move and empties the queue"):
224 host.succeed(
225 "mkdir /srv/mirror.git && chown git:git /srv/mirror.git",
226 f"{git} init --quiet --bare /srv/mirror.git",
227 "systemctl restart valley-publish@project",
228 )
229 assert host.succeed(f"{git} -C /srv/mirror.git rev-parse refs/heads/main").strip() == landing
230 host.wait_until_succeeds("journalctl -t valley-mirror | grep -q 'project: pushed to /srv/mirror.git'")
231 host.succeed(f"test -z \"$(ls -A {queue})\"")
232 assert unit("ActiveState") == "inactive"
233
234 with subtest("a move that cannot be deleted fails the run and stays queued, and the next run empties the queue"):
235 # A directory in the queue is a move rm -f cannot delete.
236 host.succeed(f"sudo -u git mkdir {queue}/stuck", f"sudo -u git touch {queue}/stuck/x")
237 host.wait_until_succeeds(
238 "journalctl -u valley-publish@project | grep -q 'cannot remove .*stuck'", timeout=60
239 )
240 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
241 host.succeed(f"test -e {queue}/stuck/x")
242 host.succeed("systemctl is-active valley-publish@project.path")
243 host.succeed(f"rm -r {queue}/stuck", "systemctl restart valley-publish@project")
244 host.succeed(f"test -z \"$(ls -A {queue})\"")
245 assert unit("ActiveState") == "inactive"
246
247 with subtest("the landing is one ref-updated event on the bus"):
248 moved = [e for e in events() if e["event"] == "ref-updated" and e["ref"] == "refs/heads/main"]
249 assert moved == [
250 {"event": "ref-updated", "repo": "project", "ref": "refs/heads/main", "old": base, "new": landing}
251 ], moved
252 landed = [e for e in events() if e["event"] == "integration-succeeded"]
253 assert len(landed) == 1 and landed[0]["new"] == landing, landed
254
255 # What a client verifies the landing with, in the instance repository:
256 # the controllers' signers file, and the name they sign under, which
257 # this host leaves to the default, the machine's own name. The file
258 # replaced by a rename, as the registry compiler replaces its own, is
259 # published again with no activation.
260 with subtest("the host publishes the controllers' signers, and again when the file changes"):
261 ref = "refs/the-valley/signers"
262 instance = f"{git} -C /srv/git/instance.git"
263 signers = "/var/lib/valley-signers-file/known_signers"
264 host.succeed(
265 f"test \"$({instance} cat-file -t {ref})\" = tree",
266 f"test \"$({instance} cat-file blob {ref}:integrator-name)\" = host/attestations",
267 f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}",
268 )
269 host.succeed(
270 f"cat {signers} ${keys}/integrator_signer > /var/lib/valley-signers-file/next",
271 f"mv -f /var/lib/valley-signers-file/next {signers}",
272 )
273 host.wait_until_succeeds(f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}", timeout=60)
274 host.succeed(f"{instance} cat-file blob {ref}:known-signers | grep -q '^host/attestations+'")
275
276 # Only the host's machinery writes the publication. A push over ssh,
277 # by a key the host authorizes, cannot replace it with a well-formed
278 # publication of a key the pusher holds, and cannot delete it.
279 with subtest("no push over ssh replaces or deletes the publication"):
280 host.wait_for_unit("sshd.service")
281 published = host.succeed(f"{instance} rev-parse {ref}").strip()
282 host.succeed(
283 "mkdir -p /root/keys",
284 "install -m 600 ${keys}/contributor /root/keys/contributor",
285 "git init --quiet --bare /root/forged.git",
286 )
287 forged = host.succeed(
288 "cd /root/forged.git"
289 " && name=$(echo host/attestations | git hash-object -w --stdin)"
290 " && file=$(git hash-object -w ${keys}/forged_signer)"
291 " && printf '100644 blob %s\\tintegrator-name\\n100644 blob %s\\tknown-signers\\n' $name $file | git mktree"
292 ).strip()
293 ssh = (
294 "GIT_SSH_COMMAND='ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
295 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'"
296 )
297 for refspec in [f"+{forged}:{ref}", f":{ref}"]:
298 out = host.fail(f"cd /root/forged.git && {ssh} git push git@localhost:instance.git {refspec} 2>&1")
299 assert f"{ref} is written only by the machinery on the host, and no push may write it" in out, out
300 assert host.succeed(f"{instance} rev-parse {ref}").strip() == published, refspec
301
302 # The wake directories are the host's: one per controller, owned by
303 # the integrator's user and the writers' group, which is the git user
304 # and the integrator's user. An idle one holds nothing.
305 with subtest("each controller's wake directory is its own, and a writer group's"):
306 for project in ["instance", "project"]:
307 assert host.succeed(f"stat -c '%a %U %G' {wakes}/{project}").strip() == "770 valley-integrator valley-integrator-wake"
308 host.wait_until_succeeds(f"test -z \"$(ls -A {wakes}/{project})\"")
309 members = host.succeed("getent group valley-integrator-wake").strip().split(":")[3].split(",")
310 assert sorted(members) == ["git", "valley-integrator"], members
311
312 # A push over ssh runs the dispatcher, whose hooks run in turn. A topic
313 # branch, which anyone may push, marks the project's controller and
314 # not the instance's.
315 with subtest("a push over ssh wakes the controller of the project it moved, and no other"):
316 host.succeed(
317 f"git init --quiet /root/topic && cd /root/topic && {commit} --allow-empty -m topic"
318 )
319 project_before, instance_before = due_passes("project"), due_passes("instance")
320 host.succeed(f"cd /root/topic && {ssh} git push --quiet git@localhost:project.git HEAD:refs/heads/topic")
321 host.wait_until_succeeds(f"test {project_before} -lt $(journalctl -u valley-integrator@project -o cat | grep -c '^pass: due$')", timeout=30)
322 host.sleep(2)
323 assert due_passes("instance") == instance_before, "a push to project woke the instance's controller"
324
325 # The floor moves by the instance's controller, which runs no hook. It
326 # marks the project's controller itself, from inside its sandbox, after
327 # the landing. The request is fetched, so only a push to a topic branch
328 # of the instance marks the instance's controller.
329 with subtest("a floor landed by the instance's controller wakes the controller that reads it"):
330 floor_base = host.succeed(f"{git} -C /srv/git/instance.git rev-parse refs/heads/main").strip()
331 host.succeed(
332 f"cd /tmp/work && sudo -u git git checkout --quiet -b floor {floor_base}",
333 "cd /tmp/work && sudo -u git sh -c 'echo moved > moved.txt' && sudo -u git git add moved.txt",
334 f"cd /tmp/work && sudo -u git {commit} -m 'the floor, moved'",
335 )
336 seed("instance", "floor:refs/the-valley/integration-requests/main/floor")
337 before = due_passes("project")
338 host.succeed(f"cd /root/topic && {ssh} git push --quiet git@localhost:instance.git HEAD:refs/heads/topic")
339 host.wait_until_succeeds(
340 f"test \"$({git} -C /srv/git/instance.git rev-parse refs/heads/main^)\" = {floor_base}", timeout=60
341 )
342 host.wait_until_succeeds(
343 f"journalctl -u valley-integrator@instance -o cat | grep -q '^ wake the floor reader at {wakes}/project is due$'",
344 timeout=30,
345 )
346 host.wait_until_succeeds(f"test {before} -lt $(journalctl -u valley-integrator@project -o cat | grep -c '^pass: due$')", timeout=30)
347 '';
348 };
349}