gunk-dev/the-valley

publish-e2e.nix

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