gunk-dev/the-valley

publish-e2e.nix

source55ea14a47e8fmain's published tip history
12.2 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 systemd's retry publishes it. The host also publishes, in its
9# instance repository, the signers a client verifies the landing with, and
10# publishes them again when the signers file is replaced. No push over ssh
11# replaces that publication or deletes it.
12{
13 pkgs,
14 lib,
15 self,
16 packages,
17 ...
18}:
19let
20 # Throwaway keys, made once at build time, and the signers file the
21 # controller is given. They hold no authority anywhere: the machine that
22 # trusts them exists for one test run. forged_signer is the contributor's
23 # key under the integrator's name, what a forged publication would hold.
24 keys =
25 pkgs.runCommand "valley-publish-e2e-keys"
26 {
27 nativeBuildInputs = [
28 pkgs.openssh
29 packages.attest
30 ];
31 }
32 ''
33 mkdir $out
34 for who in integrator contributor; do
35 ssh-keygen -q -t ed25519 -N "" -C "$who" -f "$out/$who"
36 done
37 attest key --key "$out/contributor" --name contributor/attestations > "$out/known_signers"
38 attest key --key "$out/integrator" --name host/attestations > "$out/integrator_signer"
39 attest key --key "$out/contributor" --name host/attestations > "$out/forged_signer"
40 '';
41
42 declaration = pkgs.writeText "valley-publish-e2e.cue" ''
43 package valley
44
45 projects: {
46 // The instance repository, which carries the floor.
47 "instance": protection: refs: ["refs/heads/main"]
48 "project": {
49 protection: {}
50 mirrors: ["/srv/mirror.git"]
51 }
52 }
53 '';
54
55 # A floor that requires nothing, so a change lands on the strength of its
56 # delta applying, and the test needs no evidence and no nix evaluation.
57 floor = pkgs.writeText "floor.cue" ''
58 package verification
59
60 floor: {
61 checks: {}
62 classes: {}
63 unclassified: {}
64 }
65 '';
66in
67{
68 publish-e2e = pkgs.testers.runNixOSTest {
69 name = "valley-publish-e2e";
70 nodes.host = {
71 imports = [ self.nixosModules.default ];
72 environment.systemPackages = [
73 pkgs.git
74 pkgs.natscli
75 pkgs.jq
76 ];
77 # The signers file is a copy made at boot, at a path the test
78 # replaces as the registry compiler replaces its own file.
79 systemd.tmpfiles.rules = [
80 "d /var/lib/valley-signers-file 0755 root root - -"
81 "C /var/lib/valley-signers-file/known_signers 0644 root root - ${keys}/known_signers"
82 ];
83 services.valley = {
84 enable = true;
85 config = declaration;
86 authorizedKeys = [ (lib.fileContents "${keys}/contributor.pub") ];
87 bus.enable = true;
88 integrator = {
89 enable = true;
90 signingKeyFile = "${keys}/integrator";
91 knownSignersFile = "/var/lib/valley-signers-file/known_signers";
92 instanceProject = "instance";
93 interval = "2s";
94 };
95 };
96 };
97
98 testScript = ''
99 import json
100
101 host.wait_for_unit("multi-user.target")
102 host.wait_for_unit("valley-publish@project.path")
103 host.wait_until_succeeds("test -d /srv/git/project.git/valley-publish-queue")
104
105 # The repositories belong to the git user, so git reads them as it.
106 git = "sudo -u git git"
107 queue = "/srv/git/project.git/valley-publish-queue"
108
109 def unit(prop):
110 return host.succeed(f"systemctl show -p {prop} --value valley-publish@project").strip()
111
112 # Every payload on the bus, as published.
113 def payloads():
114 out = host.succeed(
115 "n=$(nats --server nats://127.0.0.1:4222 stream info valley --json | jq .state.messages);"
116 " for i in $(seq 1 $n); do"
117 " nats --server nats://127.0.0.1:4222 stream get valley $i --json | jq -r .data | base64 -d; echo;"
118 " done"
119 )
120 return [line for line in out.splitlines() if line.strip()]
121
122 def events():
123 return [json.loads(line) for line in payloads()]
124
125 # The mirror does not exist yet, so the first push to it fails.
126
127 # Two commits: the floor, which is main on both repositories, and a
128 # change one commit ahead of it.
129 commit = "git -c user.name=valley-check -c user.email=valley-check@localhost commit --quiet"
130 host.succeed(
131 "mkdir -p /tmp/work/policy/instance",
132 "cp ${floor} /tmp/work/policy/instance/floor.cue",
133 f"cd /tmp/work && git init --quiet --initial-branch=main && git add -A && {commit} -m floor",
134 f"cd /tmp/work && echo change > change.txt && git add -A && {commit} -m change",
135 )
136 base = host.succeed("git -C /tmp/work rev-parse HEAD~1").strip()
137 change = host.succeed("git -C /tmp/work rev-parse HEAD").strip()
138 host.succeed("chown -R git:git /tmp/work")
139
140 # Seeded by fetching into the served repositories. A fetch runs no
141 # hook, so nothing here is published, and the mirror and the bus see
142 # only what the landing does.
143 def seed(repo, refspec):
144 host.succeed(f"{git} -C /srv/git/{repo}.git fetch --quiet /tmp/work {refspec}")
145
146 seed("instance", f"{base}:refs/heads/main")
147 seed("project", f"{base}:refs/heads/main")
148 host.fail(f"{git} -C /srv/mirror.git rev-parse --verify --quiet refs/heads/main")
149 # The request ref alone files the change for integration.
150 seed("project", f"{change}:refs/the-valley/integration-requests/main/one")
151
152 with subtest("the landing moves main"):
153 host.wait_until_succeeds(
154 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main)\" = {change}", timeout=120
155 )
156
157 with subtest("a failed mirror push keeps the move queued and fails the run"):
158 host.wait_until_succeeds(
159 "journalctl -t valley-mirror | grep -q 'project: push to /srv/mirror.git FAILED'", timeout=60
160 )
161 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
162 host.succeed(f"test -n \"$(ls -A {queue})\"")
163
164 # The integrator publishes the event itself, so the mirror being down
165 # does not hold it back. Its payload is byte for byte the one the host
166 # publishes for a push of the same move.
167 with subtest("the landing is on the bus while the mirror is down"):
168 host.wait_until_succeeds(
169 "nats --server nats://127.0.0.1:4222 stream get valley --last-for valley.git.project.ref-updated"
170 )
171 host.succeed(f"test -n \"$(ls -A {queue})\"")
172 moved = [p for p in payloads() if '"event":"ref-updated"' in p]
173 assert moved == [
174 f'{{"event":"ref-updated","repo":"project","ref":"refs/heads/main","old":"{base}","new":"{change}"}}'
175 ], moved
176
177 with subtest("systemd retries the push after a delay, and the retry reaches the mirror"):
178 host.succeed(
179 "mkdir /srv/mirror.git && chown git:git /srv/mirror.git",
180 f"{git} init --quiet --bare /srv/mirror.git",
181 )
182 host.wait_until_succeeds(
183 f"test \"$({git} -C /srv/mirror.git rev-parse refs/heads/main)\" = {change}", timeout=90
184 )
185 host.wait_until_succeeds("journalctl -t valley-mirror | grep -q 'project: pushed to /srv/mirror.git'")
186 host.wait_until_succeeds(f"test -z \"$(ls -A {queue})\"")
187 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-publish@project)\" = inactive")
188 # One failed run, then one retry 30 seconds later: no respin.
189 restarts = unit("NRestarts")
190 assert restarts == "1", restarts
191
192 with subtest("a move that cannot be deleted fails the run, which waits to retry"):
193 # A directory in the queue is a move rm -f cannot delete.
194 host.succeed(f"sudo -u git mkdir {queue}/stuck", f"sudo -u git touch {queue}/stuck/x")
195 host.wait_until_succeeds(
196 "journalctl -u valley-publish@project | grep -q 'cannot remove .*stuck'", timeout=60
197 )
198 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
199 restarts = unit("NRestarts")
200 host.sleep(10)
201 assert unit("NRestarts") == restarts, "the drain restarted without waiting"
202 assert unit("SubState") == "auto-restart"
203 host.succeed("systemctl is-active valley-publish@project.path")
204 host.succeed(f"rm -r {queue}/stuck")
205 host.wait_until_succeeds(
206 "test \"$(systemctl show -p ActiveState --value valley-publish@project)\" = inactive", timeout=300
207 )
208 host.succeed(f"test -z \"$(ls -A {queue})\"")
209
210 with subtest("the landing is one ref-updated event on the bus"):
211 moved = [e for e in events() if e["event"] == "ref-updated"]
212 assert moved == [
213 {"event": "ref-updated", "repo": "project", "ref": "refs/heads/main", "old": base, "new": change}
214 ], moved
215 landed = [e for e in events() if e["event"] == "integration-succeeded"]
216 assert len(landed) == 1 and landed[0]["new"] == change, landed
217
218 # What a client verifies the landing with, in the instance repository:
219 # the controllers' signers file, and the name they sign under, which
220 # this host leaves to the default, the machine's own name. The file
221 # replaced by a rename, as the registry compiler replaces its own, is
222 # published again with no activation.
223 with subtest("the host publishes the controllers' signers, and again when the file changes"):
224 ref = "refs/the-valley/signers"
225 instance = f"{git} -C /srv/git/instance.git"
226 signers = "/var/lib/valley-signers-file/known_signers"
227 host.succeed(
228 f"test \"$({instance} cat-file -t {ref})\" = tree",
229 f"test \"$({instance} cat-file blob {ref}:integrator-name)\" = host/attestations",
230 f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}",
231 )
232 host.succeed(
233 f"cat {signers} ${keys}/integrator_signer > /var/lib/valley-signers-file/next",
234 f"mv -f /var/lib/valley-signers-file/next {signers}",
235 )
236 host.wait_until_succeeds(f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}", timeout=60)
237 host.succeed(f"{instance} cat-file blob {ref}:known-signers | grep -q '^host/attestations+'")
238
239 # Only the host's machinery writes the publication. A push over ssh,
240 # by a key the host authorizes, cannot replace it with a well-formed
241 # publication of a key the pusher holds, and cannot delete it.
242 with subtest("no push over ssh replaces or deletes the publication"):
243 host.wait_for_unit("sshd.service")
244 published = host.succeed(f"{instance} rev-parse {ref}").strip()
245 host.succeed(
246 "mkdir -p /root/keys",
247 "install -m 600 ${keys}/contributor /root/keys/contributor",
248 "git init --quiet --bare /root/forged.git",
249 )
250 forged = host.succeed(
251 "cd /root/forged.git"
252 " && name=$(echo host/attestations | git hash-object -w --stdin)"
253 " && file=$(git hash-object -w ${keys}/forged_signer)"
254 " && printf '100644 blob %s\\tintegrator-name\\n100644 blob %s\\tknown-signers\\n' $name $file | git mktree"
255 ).strip()
256 ssh = (
257 "GIT_SSH_COMMAND='ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
258 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'"
259 )
260 for refspec in [f"+{forged}:{ref}", f":{ref}"]:
261 out = host.fail(f"cd /root/forged.git && {ssh} git push git@localhost:instance.git {refspec} 2>&1")
262 assert f"{ref} is written only by the machinery on the host, and no push may write it" in out, out
263 assert host.succeed(f"{instance} rev-parse {ref}").strip() == published, refspec
264 '';
265 };
266}