gunk-dev/the-valley

onmain.nix

sourcecfedff357a41main's published tip history
10.6 KiB
1# The onMain bridge (onmain/): its unit tests, and one NixOS machine for
2# the module's wiring around it.
3{
4 pkgs,
5 lib,
6 self,
7 packages,
8 ...
9}:
10let
11 # A throwaway key the machine authorizes for one test run.
12 keys = pkgs.runCommand "valley-onmain-e2e-keys" { nativeBuildInputs = [ pkgs.openssh ]; } ''
13 mkdir $out
14 ssh-keygen -q -t ed25519 -N "" -C pusher -f "$out/pusher"
15 '';
16
17 declaration = pkgs.writeText "valley-onmain-e2e.cue" ''
18 package valley
19
20 projects: app: {}
21 '';
22in
23{
24 # The bridge over real git repositories: a loose ref replaced, packed-refs
25 # rewritten, a missing refs/heads watched for, the tip requested at start
26 # and not again while it stands, a lost watch set up again, and reftable
27 # refused; the handoff to the unit, which runs a commit requested at any
28 # moment of a run; and the unit's environment written from nothing but
29 # one commit ID, with the request consumed whatever the commit file holds.
30 onmain-unit = packages.onmain.unit;
31
32 # What the module wires, on a machine, with systemd's own path units: a
33 # push over ssh to main starts the bound unit, which reads the commit and
34 # the repository from the environment its first command wrote from the
35 # bridge's commit. A run that fails stays failed, with no request left
36 # and the path unit waiting, and the next push runs it. Moves during a
37 # run, and a restart of the bridge then, become one run at the newest
38 # tip once it ends. The bridge's user has no grant to start, stop or
39 # restart any unit, and cannot add an assignment to the unit's
40 # environment, or write where it is kept. A start the unit's start limit
41 # refuses stops the path unit, and resetting both runs the newest tip.
42 onmain-e2e = pkgs.testers.runNixOSTest {
43 name = "valley-onmain-e2e";
44 nodes.host = {
45 imports = [ self.nixosModules.default ];
46 environment.systemPackages = [ pkgs.git ];
47 services.valley = {
48 enable = true;
49 config = declaration;
50 authorizedKeys = [ (lib.fileContents "${keys}/pusher.pub") ];
51 onMain.converge = {
52 project = "app";
53 unit = "converge.service";
54 };
55 onMain.limited = {
56 project = "app";
57 unit = "limited.service";
58 };
59 };
60 # The bound unit records what it was started for. It fails when fail
61 # exists as it starts, and waits while hold, a FIFO, is there until
62 # the test writes to it. The test starts it more often than the
63 # default start limit allows, so the host lifts the limit, as a host
64 # whose project lands faster than that would.
65 systemd.services.converge = {
66 startLimitIntervalSec = 0;
67 serviceConfig = {
68 Type = "oneshot";
69 StateDirectory = "converge";
70 };
71 script = ''
72 echo "$VALLEY_COMMIT $VALLEY_REPOSITORY" >> /var/lib/converge/runs
73 failing=
74 if [ -e /var/lib/converge/fail ]; then failing=1; fi
75 if [ -p /var/lib/converge/hold ]; then read -r _ < /var/lib/converge/hold; fi
76 test -z "$failing"
77 '';
78 };
79 # A bound unit whose start limit allows one start an hour.
80 systemd.services.limited = {
81 startLimitBurst = 1;
82 startLimitIntervalSec = 3600;
83 serviceConfig = {
84 Type = "oneshot";
85 StateDirectory = "limited";
86 };
87 script = ''
88 echo "$VALLEY_COMMIT" >> /var/lib/limited/runs
89 '';
90 };
91 systemd.services.other = {
92 serviceConfig.Type = "oneshot";
93 script = "true";
94 };
95 };
96
97 testScript = ''
98 host.wait_for_unit("multi-user.target")
99 host.wait_for_unit("valley-init.service")
100 host.wait_for_unit("valley-on-main-converge.service")
101 host.wait_for_unit("valley-on-main-converge.path")
102 host.wait_for_unit("sshd.service")
103
104 runs = "/var/lib/converge/runs"
105 request = "/run/valley-on-main-converge/request"
106 ssh = (
107 "GIT_SSH_COMMAND='ssh -i /root/pusher -o IdentitiesOnly=yes -o BatchMode=yes"
108 " -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'"
109 )
110 commit = "git -c user.name=valley-check -c user.email=valley-check@localhost commit --quiet --allow-empty"
111 host.succeed(
112 "install -m 600 ${keys}/pusher /root/pusher",
113 "git init --quiet --initial-branch=main /root/work",
114 )
115
116 def push(message):
117 host.succeed(f"cd /root/work && {commit} -m {message} && {ssh} git push --quiet git@localhost:app.git HEAD:refs/heads/main")
118 return host.succeed("git -C /root/work rev-parse HEAD").strip()
119
120 def recorded():
121 return host.succeed(f"cat {runs} 2>/dev/null || true").splitlines()
122
123 def show(unit, prop):
124 return host.succeed(f"systemctl show -P {prop} {unit}").strip()
125
126 # Waits for the nth run to be recorded, the unit to stop, and the
127 # path unit to wait again: once it waits, it has looked for a
128 # request and found none, so nothing starts the unit until one is
129 # made.
130 def settled(n):
131 host.wait_until_succeeds(
132 f"test \"$(wc -l < {runs})\" -ge {n}"
133 " && systemctl show -P ActiveState converge.service | grep -qxE 'inactive|failed'"
134 " && test \"$(systemctl show -P SubState valley-on-main-converge.path)\" = waiting",
135 timeout=60,
136 )
137 assert len(recorded()) == n, recorded()
138 host.succeed(f"test ! -e {request}")
139
140 with subtest("a push to main starts the bound unit with the commit and the repository"):
141 host.succeed(f"test ! -e {runs}")
142 first = push("first")
143 settled(1)
144 assert recorded() == [f"{first} /srv/git/app.git"], recorded()
145 assert show("converge.service", "Result") == "success"
146
147 with subtest("a failed run stays failed, with no request left and neither limit hit"):
148 host.succeed("touch /var/lib/converge/fail")
149 second = push("second")
150 settled(2)
151 assert recorded()[1:] == [f"{second} /srv/git/app.git"], recorded()
152 assert show("converge.service", "ActiveState") == "failed"
153 assert show("converge.service", "Result") == "exit-code"
154 assert show("valley-on-main-converge.path", "ActiveState") == "active"
155 assert show("valley-on-main-converge.path", "Result") == "success"
156 host.succeed("systemctl is-active valley-on-main-converge.service")
157 host.succeed("rm /var/lib/converge/fail")
158 third = push("third")
159 settled(3)
160 assert recorded()[2:] == [f"{third} /srv/git/app.git"], recorded()
161 assert show("converge.service", "Result") == "success"
162
163 with subtest("moves during a failing run, and a restart of the bridge then, are one run at the newest"):
164 host.succeed("touch /var/lib/converge/fail", "mkfifo /var/lib/converge/hold")
165 held = push("held")
166 host.wait_until_succeeds(f"test \"$(wc -l < {runs})\" -eq 4", timeout=60)
167 host.succeed("rm /var/lib/converge/fail")
168 push("passed-over")
169 newest = push("newest")
170 host.wait_until_succeeds(f"test -e {request} && grep -qx {newest} /run/valley-on-main-converge/commit", timeout=30)
171 host.succeed("systemctl restart valley-on-main-converge.service")
172 host.wait_until_succeeds(
173 "journalctl -o cat"
174 " _SYSTEMD_INVOCATION_ID=$(systemctl show -P InvocationID valley-on-main-converge.service)"
175 f" | grep -qx 'requested a run for {newest}'",
176 timeout=30,
177 )
178 # Opened before it is removed, so the next run does not wait.
179 host.succeed("exec 3>/var/lib/converge/hold && rm /var/lib/converge/hold && echo go >&3")
180 settled(5)
181 assert recorded()[3:] == [f"{held} /srv/git/app.git", f"{newest} /srv/git/app.git"], recorded()
182 assert show("converge.service", "Result") == "success"
183
184 with subtest("the bridge's user has no grant over any unit"):
185 bridge = "sudo -u valley-on-main-converge systemctl --no-ask-password"
186 for refused in [
187 f"{bridge} start converge.service",
188 f"{bridge} start other.service",
189 f"{bridge} stop converge.service",
190 f"{bridge} restart converge.service",
191 "sudo -u git systemctl --no-ask-password start converge.service",
192 ]:
193 out = host.fail(f"{refused} 2>&1")
194 assert "Access denied" in out or "Interactive authentication required" in out, (refused, out)
195 assert len(recorded()) == 5, recorded()
196 host.succeed("test \"$(systemctl show -P ExecMainStartTimestampMonotonic other.service)\" = 0")
197
198 with subtest("the bridge's user chooses the commit, and nothing else of the unit's environment"):
199 commit_file = "/run/valley-on-main-converge/commit"
200 environment = "/run/valley-on-main/converge.environment"
201 as_bridge = "sudo -u valley-on-main-converge"
202 payload = f"{newest}\\nLD_PRELOAD=/nonexistent.so\\n"
203 host.succeed(
204 f"printf '{payload}' | {as_bridge} tee {commit_file}.new >/dev/null",
205 f"{as_bridge} mv {commit_file}.new {commit_file}",
206 f"{as_bridge} touch {request}",
207 )
208 host.wait_until_succeeds("journalctl -u converge -o cat | grep -q 'holds something other than one commit ID'", timeout=60)
209 settled(5)
210 assert show("converge.service", "Result") == "exit-code"
211 assert show("valley-on-main-converge.path", "Result") == "success"
212 host.succeed(f"! grep -q LD_PRELOAD {environment}")
213 host.fail(f"{as_bridge} touch /run/valley-on-main/planted", f"{as_bridge} rm -f {environment}")
214
215 with subtest("a start the unit's start limit refuses stops the path unit until the operator resets both"):
216 limited = "/var/lib/limited/runs"
217 host.wait_until_succeeds("test \"$(systemctl show -P Result valley-on-main-limited.path)\" = unit-start-limit-hit", timeout=60)
218 assert show("limited.service", "Result") == "start-limit-hit"
219 host.succeed("test -e /run/valley-on-main-limited/request")
220 assert host.succeed(f"cat {limited}").splitlines() == [first]
221 host.succeed("systemctl reset-failed limited.service", "systemctl restart valley-on-main-limited.path")
222 host.wait_until_succeeds(f"test \"$(wc -l < {limited})\" -eq 2", timeout=60)
223 assert host.succeed(f"cat {limited}").splitlines() == [first, newest]
224 host.wait_until_succeeds("test \"$(systemctl show -P SubState valley-on-main-limited.path)\" = waiting", timeout=30)
225 host.succeed("test ! -e /run/valley-on-main-limited/request")
226 '';
227 };
228}