gunk-dev/the-valley

host-module.nix

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