gunk-dev/the-valley

publish-e2e.nix

sourcefefe7833f700main's published tip history
12.7 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 # The change lands as one commit the integrator makes on the base,
153 # with the change's tree. That commit is what main, the mirror and
154 # the events carry from here on.
155 with subtest("the landing moves main"):
156 host.wait_until_succeeds(
157 f"test \"$({git} -C /srv/git/project.git rev-parse refs/heads/main^)\" = {base}", timeout=120
158 )
159 landing = host.succeed(f"{git} -C /srv/git/project.git rev-parse refs/heads/main").strip()
160 assert landing != change, "the change's own commit landed"
161 tree = f"{git} -C /srv/git/project.git rev-parse"
162 assert host.succeed(f"{tree} {landing}^{{tree}}") == host.succeed(f"{tree} {change}^{{tree}}")
163
164 with subtest("a failed mirror push keeps the move queued and fails the run"):
165 host.wait_until_succeeds(
166 "journalctl -t valley-mirror | grep -q 'project: push to /srv/mirror.git FAILED'", timeout=60
167 )
168 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
169 host.succeed(f"test -n \"$(ls -A {queue})\"")
170
171 # The integrator publishes the event itself, so the mirror being down
172 # does not hold it back. Its payload is byte for byte the one the host
173 # publishes for a push of the same move.
174 with subtest("the landing is on the bus while the mirror is down"):
175 host.wait_until_succeeds(
176 "nats --server nats://127.0.0.1:4222 stream get valley --last-for valley.git.project.ref-updated"
177 )
178 host.succeed(f"test -n \"$(ls -A {queue})\"")
179 moved = [p for p in payloads() if '"event":"ref-updated"' in p]
180 assert moved == [
181 f'{{"event":"ref-updated","repo":"project","ref":"refs/heads/main","old":"{base}","new":"{landing}"}}'
182 ], moved
183
184 with subtest("systemd retries the push after a delay, and the retry reaches the mirror"):
185 host.succeed(
186 "mkdir /srv/mirror.git && chown git:git /srv/mirror.git",
187 f"{git} init --quiet --bare /srv/mirror.git",
188 )
189 host.wait_until_succeeds(
190 f"test \"$({git} -C /srv/mirror.git rev-parse refs/heads/main)\" = {landing}", timeout=90
191 )
192 host.wait_until_succeeds("journalctl -t valley-mirror | grep -q 'project: pushed to /srv/mirror.git'")
193 host.wait_until_succeeds(f"test -z \"$(ls -A {queue})\"")
194 host.wait_until_succeeds("test \"$(systemctl show -p ActiveState --value valley-publish@project)\" = inactive")
195 # One failed run, then one retry 30 seconds later: no respin.
196 restarts = unit("NRestarts")
197 assert restarts == "1", restarts
198
199 with subtest("a move that cannot be deleted fails the run, which waits to retry"):
200 # A directory in the queue is a move rm -f cannot delete.
201 host.succeed(f"sudo -u git mkdir {queue}/stuck", f"sudo -u git touch {queue}/stuck/x")
202 host.wait_until_succeeds(
203 "journalctl -u valley-publish@project | grep -q 'cannot remove .*stuck'", timeout=60
204 )
205 host.wait_until_succeeds("test \"$(systemctl show -p SubState --value valley-publish@project)\" = auto-restart")
206 restarts = unit("NRestarts")
207 host.sleep(10)
208 assert unit("NRestarts") == restarts, "the drain restarted without waiting"
209 assert unit("SubState") == "auto-restart"
210 host.succeed("systemctl is-active valley-publish@project.path")
211 host.succeed(f"rm -r {queue}/stuck")
212 host.wait_until_succeeds(
213 "test \"$(systemctl show -p ActiveState --value valley-publish@project)\" = inactive", timeout=300
214 )
215 host.succeed(f"test -z \"$(ls -A {queue})\"")
216
217 with subtest("the landing is one ref-updated event on the bus"):
218 moved = [e for e in events() if e["event"] == "ref-updated"]
219 assert moved == [
220 {"event": "ref-updated", "repo": "project", "ref": "refs/heads/main", "old": base, "new": landing}
221 ], moved
222 landed = [e for e in events() if e["event"] == "integration-succeeded"]
223 assert len(landed) == 1 and landed[0]["new"] == landing, landed
224
225 # What a client verifies the landing with, in the instance repository:
226 # the controllers' signers file, and the name they sign under, which
227 # this host leaves to the default, the machine's own name. The file
228 # replaced by a rename, as the registry compiler replaces its own, is
229 # published again with no activation.
230 with subtest("the host publishes the controllers' signers, and again when the file changes"):
231 ref = "refs/the-valley/signers"
232 instance = f"{git} -C /srv/git/instance.git"
233 signers = "/var/lib/valley-signers-file/known_signers"
234 host.succeed(
235 f"test \"$({instance} cat-file -t {ref})\" = tree",
236 f"test \"$({instance} cat-file blob {ref}:integrator-name)\" = host/attestations",
237 f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}",
238 )
239 host.succeed(
240 f"cat {signers} ${keys}/integrator_signer > /var/lib/valley-signers-file/next",
241 f"mv -f /var/lib/valley-signers-file/next {signers}",
242 )
243 host.wait_until_succeeds(f"{instance} cat-file blob {ref}:known-signers | cmp - {signers}", timeout=60)
244 host.succeed(f"{instance} cat-file blob {ref}:known-signers | grep -q '^host/attestations+'")
245
246 # Only the host's machinery writes the publication. A push over ssh,
247 # by a key the host authorizes, cannot replace it with a well-formed
248 # publication of a key the pusher holds, and cannot delete it.
249 with subtest("no push over ssh replaces or deletes the publication"):
250 host.wait_for_unit("sshd.service")
251 published = host.succeed(f"{instance} rev-parse {ref}").strip()
252 host.succeed(
253 "mkdir -p /root/keys",
254 "install -m 600 ${keys}/contributor /root/keys/contributor",
255 "git init --quiet --bare /root/forged.git",
256 )
257 forged = host.succeed(
258 "cd /root/forged.git"
259 " && name=$(echo host/attestations | git hash-object -w --stdin)"
260 " && file=$(git hash-object -w ${keys}/forged_signer)"
261 " && printf '100644 blob %s\\tintegrator-name\\n100644 blob %s\\tknown-signers\\n' $name $file | git mktree"
262 ).strip()
263 ssh = (
264 "GIT_SSH_COMMAND='ssh -i /root/keys/contributor -o IdentitiesOnly=yes -o BatchMode=yes"
265 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'"
266 )
267 for refspec in [f"+{forged}:{ref}", f":{ref}"]:
268 out = host.fail(f"cd /root/forged.git && {ssh} git push git@localhost:instance.git {refspec} 2>&1")
269 assert f"{ref} is written only by the machinery on the host, and no push may write it" in out, out
270 assert host.succeed(f"{instance} rev-parse {ref}").strip() == published, refspec
271 '';
272 };
273}