gunk-dev/the-valley

host-module.nix

source29062ae11cd8main's published tip history
21.9 KiB
1# What the NixOS module renders from a declaration, and what it must refuse.
2# The refusals are eval-time: a host that must not evaluate is caught by a
3# throw here, since there is nothing to build once it has. What a host does
4# render is pinned by module-eval.sh over the rendered scripts.
5{
6 pkgs,
7 lib,
8 hosts,
9 ...
10}:
11let
12 inherit (hosts)
13 unprotectedInstanceHost
14 acceptEnvHost
15 matchAcceptEnvHost
16 wildcardAcceptEnvHost
17 quotedAcceptEnvHost
18 tabAcceptEnvHost
19 setEnvHost
20 permitUserEnvironmentHost
21 conflictingKeysHost
22 host
23 noBackupHost
24 noSecretsHost
25 protectedHost
26 busHost
27 mirrorHost
28 integratorHost
29 integratorSelfHost
30 identityHost
31 ;
32
33 failedAssertions = builtins.filter (a: !a.assertion) (
34 host.config.assertions
35 ++ noBackupHost.config.assertions
36 ++ busHost.config.assertions
37 ++ mirrorHost.config.assertions
38 ++ protectedHost.config.assertions
39 ++ integratorHost.config.assertions
40 ++ integratorSelfHost.config.assertions
41 ++ identityHost.config.assertions
42 );
43
44 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
45
46 # The hosts the module must refuse, each with the words its refusal must
47 # say. An assertion that stopped firing would leave the push policy
48 # quietly wrong, so each is held to naming what is wrong.
49 refusedHosts = [
50 {
51 host = unprotectedInstanceHost;
52 says = "whose refs/heads/main is not protected";
53 why = "an instance repository without protection would let any key that can push rewrite the floor and the registry";
54 }
55 {
56 host = acceptEnvHost;
57 says = "AcceptEnv";
58 why = "sshd accepting the principal variable from the client would let any key name any principal";
59 }
60 {
61 host = matchAcceptEnvHost;
62 says = "GIT_CONFIG_*";
63 why = "sshd accepting GIT_ variables in the git user's Match block, in whatever case the keyword is written, would let a client set git's configuration";
64 }
65 {
66 host = wildcardAcceptEnvHost;
67 says = "G?T_*";
68 why = "a wildcard that admits GIT_ variables admits them however it is spelled";
69 }
70 {
71 host = quotedAcceptEnvHost;
72 says = "holds a quote or a backslash";
73 why = "a quoted name is one sshd unquotes and admits, so a check that read it differently would pass it";
74 }
75 {
76 host = tabAcceptEnvHost;
77 says = "VALLEY_PRINCIPAL from the client";
78 why = "a name after a tab is a name sshd admits";
79 }
80 {
81 host = setEnvHost;
82 says = "SetEnv";
83 why = "sshd setting the principal itself would make every key push as it";
84 }
85 {
86 host = permitUserEnvironmentHost;
87 says = "PermitUserEnvironment";
88 why = "a PermitUserEnvironment wider than the principal variable would let a key's entry or ~/.ssh/environment set what the push policy does not expect";
89 }
90 {
91 host = conflictingKeysHost;
92 says = "more than one principal tag";
93 why = "a key declared under two tags would push as whichever entry sshd reads first";
94 }
95 ];
96
97 unrefusedHosts = builtins.filter (
98 r: !(lib.any (a: !a.assertion && lib.hasInfix r.says a.message) r.host.config.assertions)
99 ) refusedHosts;
100
101 protectedKeyLines = protectedHost.config.users.users.git.openssh.authorizedKeys.keys;
102
103 resticRenderedWithoutDeclaration =
104 noBackupHost.config.systemd.services ? "restic-backups-valley"
105 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
106
107 # The bus defaults off; a host that never asked for one must
108 # render zero bus machinery.
109 busRenderedWithoutEnable =
110 noBackupHost.config.systemd.services ? valley-bus
111 || noBackupHost.config.systemd.services ? valley-bus-init;
112
113 # A declaration with no protection block and no tagged key still gets
114 # the push policy on every project — the policy is the host's, and a
115 # protection block only adds protected refs to it — and nothing of the
116 # principal machinery: no tag on a key, no sshd change.
117 protectionRenderedWithoutDeclaration =
118 noBackupHost.config.services.openssh.settings ? PermitUserEnvironment
119 || lib.any (lib.hasInfix "environment=") (
120 noBackupHost.config.users.users.git.openssh.authorizedKeys.keys
121 );
122
123 policyMissingWithoutDeclaration =
124 !(lib.hasInfix "valley-protect-the-valley" noBackupHost.config.systemd.services.valley-init.script);
125
126 # The integrator's units. What a controller *does* is not checked here
127 # and no VM is booted: that is integrator-e2e's job (the real binaries
128 # over real repositories) and, past it, live exercise on a host. These
129 # assertions cover the wiring — that a controller is rendered for what
130 # the declaration protects and for nothing else, under an identity that
131 # is not the git user's, pointed at the key and the signers the consumer
132 # supplied.
133 #
134 # There is a seam between those two halves that neither reaches, and in a
135 # single day it produced five deployment failures. Every assertion below is
136 # an eval of the unit's text; integrator-e2e runs the binaries with no unit
137 # around them at all. What sits between is the unit's sandbox and identity
138 # meeting the filesystem the binaries actually use at runtime:
139 #
140 # - git refusing a repository the service does not own (bd-500adf7)
141 # - a push authenticating as the operator rather than as the run
142 # (bd-353c59d)
143 # - no writable temporary directory, so no worktree could be made
144 # - the worktree metadata root, created by whichever service reached it
145 # first and then unchmodable by the other, which failed valley-init and
146 # took every valley unit down with it
147 # - the state directory not writable under ProtectSystem=strict unless
148 # the unit names it, which the previous fix had made the scratch root
149 #
150 # Each was found by a host, minutes of a live service after a deploy that
151 # every check here passed. They compose: the third's fix set up the fourth,
152 # and the fourth's fix set up the fifth. That is the argument. A seam whose
153 # failures feed each other is not one to pin an assertion at a time, and
154 # each assertion here that marks a piece of it — the git ownership
155 # exception, TMPDIR, the worktrees root, ReadWritePaths — marks a place a
156 # smoke boot would have spoken first.
157 #
158 # A nixosTest that boots one host, starts the units and reconciles one
159 # change end to end is the next check this module needs. Nothing else
160 # closes the seam, and five incidents is enough evidence of what it costs
161 # to leave open. Not built here.
162 #
163 # Protection and integration are separable declarations: protectedHost
164 # declares the same protected projects with the service off, and must
165 # evaluate to no controller at all.
166 integratorRenderedWithoutEnable =
167 protectedHost.config.systemd.services ? "valley-integrator@"
168 || protectedHost.config.systemd.targets ? valley-integrators
169 || lib.hasInfix "sharedRepository" protectedHost.config.systemd.services.valley-init.script;
170
171 # One target pulls in each controller, and another the path unit that
172 # publishes each project's queued moves, landings included.
173 integratorWants = integratorHost.config.systemd.targets.valley-integrators.wants;
174 controllers = lib.filter (lib.hasPrefix "valley-integrator@") integratorWants;
175 publishers = integratorHost.config.systemd.targets.valley-publish.wants;
176
177 integratorUser = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.User;
178
179 # The controller is not the repositories' owner, which is the whole point
180 # of running it as itself — so git needs an ownership exception, and
181 # where that exception lives is load-bearing. GIT_CONFIG_* is command
182 # scope, the only scope besides system and global that safe.directory is
183 # read from, and the unit's environment is inherited by every git the
184 # controller drives. It names one repository: a wildcard here would hand
185 # a compromised controller every repository on the host.
186 integratorGitEnv = integratorHost.config.systemd.services."valley-integrator@".environment;
187
188 # The count is what git reads; an entry past it is an entry git ignores,
189 # silently. So it is checked against the entries actually rendered rather
190 # than against a number written here, which would have to be edited every
191 # time a grant is added and would go on passing if it were not.
192 integratorSafeDirectory =
193 integratorGitEnv.GIT_CONFIG_KEY_0 or null != "safe.directory"
194 || integratorGitEnv.GIT_CONFIG_VALUE_0 or null != "/srv/git/%i.git"
195 || integratorGitEnv.GIT_CONFIG_COUNT or null
196 != toString (
197 lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames integratorGitEnv))
198 );
199
200 integratorService = integratorHost.config.systemd.services."valley-integrator@".serviceConfig;
201
202 # Scratch goes under the state directory, because the sandbox leaves no
203 # writable temporary directory and a verdict needs a checkout on disk. Two
204 # halves, and each was a live failure on its own. TMPDIR naming a path
205 # outside the state directory is the first; the state directory not being
206 # named in ReadWritePaths is the second, which failed even though
207 # ProtectSystem=strict is documented to leave a declared state directory
208 # writable. Everything the unit may write is enumerated, so what a reader
209 # of the unit sees is the whole of it.
210 # The floor is read from the instance repository's integrated tip
211 # (dcr-f41f718, dcr-b87f6e8), so a controller is told which repository
212 # carries it and reads it there. Three things have to be true of that, and
213 # each was a way for it to be silently wrong.
214 #
215 # The controller has to be told at all — the failure this replaced was a
216 # binary looking for a materialized directory nothing populated.
217 #
218 # It has to work when the repository carrying the floor is not the one the
219 # controller serves, which is the ordinary case: on integratorHost every
220 # controller serves a protected project and reads the floor out of
221 # "open", which no controller serves. git refuses a repository the caller
222 # does not own, so that read needs its own safe.directory entry, named and
223 # not wildcarded — the same failure as the served repository's, one
224 # repository over.
225 #
226 # And it has to keep working when the two coincide, which is what an
227 # instance's own host looks like: integratorSelfHost's controller for
228 # "guarded" reads the floor from "guarded".
229 integratorFloor =
230 let
231 command = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
232 selfCommand = integratorSelfHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
233 env = integratorHost.config.systemd.services."valley-integrator@".environment;
234 in
235 !(lib.hasInfix "--instance-repo /srv/git/sealed.git" command)
236 || !(lib.hasInfix "--instance-repo /srv/git/guarded.git" selfCommand)
237 || env.GIT_CONFIG_COUNT or null != "2"
238 || env.GIT_CONFIG_KEY_1 or null != "safe.directory"
239 || env.GIT_CONFIG_VALUE_1 or null != "/srv/git/sealed.git";
240
241 integratorScratch =
242 integratorGitEnv.TMPDIR or null != "/var/lib/${integratorService.StateDirectory}"
243 || !(builtins.elem "/var/lib/${integratorService.StateDirectory}" integratorService.ReadWritePaths);
244
245 # The registry compiler. It is off by default and must stay inert: a
246 # consumer that has not asked for it renders the system it always did.
247 # integratorHost is the strongest witness available — the integrator on,
248 # the signers file supplied by hand, and every option of the identity
249 # block left alone.
250 identityRenderedWithoutEnable =
251 integratorHost.config.systemd.services ? valley-identity
252 || integratorHost.config.systemd.timers ? valley-identity
253 || integratorHost.config.services.openssh.settings ? PermitUserEnvironment
254 || lib.any (lib.hasInfix "valley-identity") integratorHost.config.services.openssh.authorizedKeysFiles
255 || lib.hasInfix "valley-identity" integratorHost.config.services.openssh.extraConfig
256 || lib.hasInfix "valley-identity" (
257 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
258 )
259 || lib.hasInfix "--name " (
260 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
261 );
262
263 identityService = identityHost.config.systemd.services.valley-identity.serviceConfig;
264
265 identityStateDir = "/var/lib/${identityService.StateDirectory or ""}";
266
267 # What the compiled artifacts have to be true of, and each was a way for
268 # the machinery to be quietly wrong.
269 #
270 # The compiler writes into its state directory and nowhere else, so that
271 # directory has to be the one path the unit may write.
272 #
273 # sshd walks every directory above an authorized-keys file and refuses a
274 # group- or world-writable one, so the state directory is 0755 rather than
275 # the 0700 a service's state usually takes — and the unit runs as the git
276 # user, because sshd equally refuses a file owned by anyone but root or
277 # the account it authorizes.
278 #
279 # The compiled file is added to what sshd reads for the git user rather
280 # than replacing it, and for the git user alone: the user's Match block
281 # names the declared keys and the compiled ones, and nothing else — no
282 # ~/.ssh/authorized_keys, no AuthorizedKeysCommand — so every key the git
283 # user accepts carries a tag this module or the compiler wrote. The
284 # compiler is handed the declared keys, so it can refuse a registry key
285 # declared under another tag.
286 identityCompiler =
287 identityService.User or null != identityHost.config.services.valley.user
288 || identityService.StateDirectoryMode or null != "0755"
289 || identityService.ReadWritePaths or [ ] != [ identityStateDir ]
290 || !(lib.hasInfix "--repo /srv/git/sealed.git" identityService.ExecStart)
291 || !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" identityService.ExecStart)
292 || !(lib.hasInfix "--authorized-keys ${identityStateDir}/authorized_keys.git" identityService.ExecStart)
293 || !(lib.hasInfix "--grants ${identityStateDir}/grants" identityService.ExecStart)
294 || !(lib.hasInfix "-valley-declared-keys" identityService.ExecStart)
295 || !(lib.hasInfix "AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u ${identityStateDir}/authorized_keys.git\n" identityHost.config.services.openssh.extraConfig)
296 || !(lib.hasInfix "AuthorizedKeysCommand none" identityHost.config.services.openssh.extraConfig);
297
298 # A controller under a compiled registry reads the compiled signers file
299 # and signs under the name the registry publishes its key under. The key
300 # hash binds name to key, so a controller signing under the host's default
301 # name while the registry publishes it as "integrator" would produce notes
302 # no verifier can find a key for.
303 identityIntegrator =
304 let
305 command = identityHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
306 in
307 !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" command)
308 || !(lib.hasInfix "--name integrator" command)
309 || !(builtins.elem "valley-identity.service"
310 identityHost.config.systemd.services."valley-integrator@".after
311 );
312
313 # The declared keys stay authorized beside the compiled ones. A compiled
314 # file that replaced them would make a bad compilation — or a first boot
315 # before the first one — a locked-out git user, which is the one failure
316 # this machinery must never have.
317 identityKeepsDeclaredKeys =
318 identityHost.config.users.users.git.openssh.authorizedKeys.keys == [ ];
319in
320{
321 module-eval =
322 if failedAssertions != [ ] then
323 throw "valley module-eval: failed assertions: ${
324 lib.concatMapStringsSep "; " (a: a.message) failedAssertions
325 }"
326 else if resticRenderedWithoutDeclaration then
327 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
328 else if busRenderedWithoutEnable then
329 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
330 else if
331 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
332 then
333 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
334 else if unrefusedHosts != [ ] then
335 throw "valley module-eval: ${lib.concatMapStringsSep "; " (r: "a host was not refused although ${r.why}") unrefusedHosts}"
336 else if protectionRenderedWithoutDeclaration then
337 throw "valley module-eval: principal machinery rendered for a declaration with no protection block and no tagged key"
338 else if policyMissingWithoutDeclaration then
339 throw "valley module-eval: a project with no protection block got no pre-receive hook — the push policy is installed on every project a host serves"
340 else if protectedHost.config.services.openssh.settings ? PermitUserEnvironment then
341 throw "valley module-eval: sshd must pass no key's environment on: the git user's shell derives the principal from the authenticated key"
342 else if
343 !(lib.hasInfix "valley-git-shell" protectedHost.config.users.users.git.shell)
344 then
345 throw "valley module-eval: the git user's login shell must be the valley's, which derives the principal and pauses pushes until init converges"
346 else if integratorRenderedWithoutEnable then
347 throw "valley module-eval: integrator machinery rendered for a protected declaration that never enabled the service"
348 else if !(integratorHost.config.systemd.services ? "valley-integrator@") then
349 throw "valley module-eval: the integrator is enabled and no controller unit was rendered"
350 else if
351 controllers != [
352 "valley-integrator@guarded.service"
353 "valley-integrator@released.service"
354 "valley-integrator@sealed.service"
355 ]
356 then
357 throw "valley module-eval: a controller runs for each protected project and no other, not ${lib.concatStringsSep ", " controllers}"
358 else if
359 publishers != [
360 "valley-publish@guarded.path"
361 "valley-publish@released.path"
362 "valley-publish@sealed.path"
363 ]
364 then
365 throw "valley module-eval: each controller's landings are published by a path unit of its own, not ${lib.concatStringsSep ", " publishers}"
366 else if integratorHost.config.systemd.services."valley-publish@".serviceConfig.User != "git" then
367 throw "valley module-eval: a landing is published as the git user, which holds the mirror credentials"
368 else if integratorUser == integratorHost.config.services.valley.user then
369 throw "valley module-eval: the integrator must not run as the git user — it has its own (bd-500adf7)"
370 else if !(integratorHost.config.users.users ? ${integratorUser}) then
371 throw "valley module-eval: the integrator runs as ${integratorUser}, which the module never declares"
372 else if integratorHost.config.users.users.${integratorUser}.group != "git" then
373 throw "valley module-eval: the integrator reaches the repositories through the git group, and holds no other grant"
374 else if integratorSafeDirectory then
375 throw "valley module-eval: a controller must carry safe.directory for the one repository it serves in its own environment — it does not own the repositories, and git refuses what it does not own"
376 else if integratorFloor then
377 throw "valley module-eval: a controller must be told which repository carries the floor, and must carry a safe.directory exception for it — the floor is read from that repository's integrated tip, and git refuses a repository its caller does not own"
378 else if integratorScratch then
379 throw "valley module-eval: a controller's TMPDIR must be its state directory and that directory must be named in ReadWritePaths — under ProtectSystem=strict a path the unit does not enumerate is one it cannot write, and a verdict needs a worktree on disk"
380 else if identityRenderedWithoutEnable then
381 throw "valley module-eval: registry-compilation machinery rendered for a host that never enabled it — nothing may change until a consumer opts in"
382 else if identityCompiler then
383 throw "valley module-eval: the compiler must run as the git user, write only its own 0755 state directory, read the registry from the instance repository, write the grants the pre-receive hook reads, and have its authorized_keys added to what sshd reads under the %u token — sshd refuses a keys file owned by anyone but root or the account it authorizes, and a fixed path in that global list would authorize every registry key for every account on the host"
384 else if identityIntegrator then
385 throw "valley module-eval: a controller under a compiled registry must read the compiled signers file, start after the compilation, and sign under the name the registry publishes its key under"
386 else if identityKeepsDeclaredKeys then
387 throw "valley module-eval: the declared authorized keys must stay authorized beside the compiled ones — a compiled file that replaced them would make a bad compilation a locked-out git user"
388 else
389 pkgs.runCommand "valley-module-eval" {
390 initScript = host.config.systemd.services.valley-init.script;
391 sshdConfig = host.config.services.openssh.extraConfig;
392 resticService = host.config.systemd.units."restic-backups-valley.service".text;
393 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
394 protectedInit = protectedHost.config.systemd.services.valley-init.script;
395 protectedKeys = lib.concatStringsSep "\n" protectedKeyLines;
396 protectedShell = protectedHost.config.users.users.git.shell;
397 integratorUnit = integratorHost.config.systemd.units."valley-integrator@.service".text;
398 integratorInit = integratorHost.config.systemd.services.valley-init.script;
399 publishUnit = host.config.systemd.units."valley-publish@.service".text;
400 identityInit = identityHost.config.systemd.services.valley-init.script;
401 passAsFile = [
402 "initScript"
403 "sshdConfig"
404 "resticService"
405 "resticTimer"
406 "protectedInit"
407 "protectedKeys"
408 "integratorUnit"
409 "integratorInit"
410 "publishUnit"
411 "identityInit"
412 ];
413 } (builtins.readFile ./module-eval.sh);
414}