gunk-dev/the-valley

host-module.nix

source4be98c5582b6main's published tip history
39.7 KiB
1# What the NixOS module renders from a declaration, and what it must refuse.
2# The web publisher's module, which sits beside it, is held here too.
3# The refusals are eval-time: a host that must not evaluate is caught by a
4# throw here, since there is nothing to build once it has. What a host does
5# render is pinned by module-eval.sh over the rendered scripts.
6#
7# Every host here runs the stand-ins for this flake's programs
8# (nix/checks/hosts.nix). Nothing here runs a program: each assertion is
9# about the units, hooks and scripts the module renders, which name a
10# program's path and the flags it is given. So module-eval changes when the
11# module, a host declaration or this check does, and not when a program
12# does.
13{
14 pkgs,
15 lib,
16 self,
17 stubbedHosts,
18 ...
19}:
20let
21 inherit (stubbedHosts)
22 unprotectedInstanceHost
23 acceptEnvHost
24 matchAcceptEnvHost
25 wildcardAcceptEnvHost
26 quotedAcceptEnvHost
27 tabAcceptEnvHost
28 setEnvHost
29 permitUserEnvironmentHost
30 conflictingKeysHost
31 host
32 noBackupHost
33 noSecretsHost
34 protectedHost
35 busHost
36 mirrorHost
37 integratorHost
38 integratorSelfHost
39 restrictedHost
40 spacedSignerProjectsHost
41 unicodeSpacedSignerProjectsHost
42 identityHost
43 workerHost
44 buildSliceHost
45 noSliceWorkerHost
46 unrestrictedWorkerHost
47 widerWorkerHost
48 integratorNamedWorkerHost
49 ;
50
51 # The web publisher's module (nix/webui-publisher.nix) beside the host
52 # module, over integratorHost: its instance repository is the one the
53 # controllers read the floor from. The host also has a backup key the
54 # publisher must not read. The publisher is a stand-in, as the host's
55 # programs are. webPublisherOffHost imports the module and leaves it off.
56 webPublisherStub = pkgs.writeShellScriptBin "valley-web-publish" ''
57 echo "valley-web-publish: a stand-in the module checks render hosts over, which runs nothing" >&2
58 exit 1
59 '';
60 webPublisherOffHost = stubbedHosts.integratorHost.extendModules {
61 modules = [
62 self.nixosModules.webui-publisher
63 { services.valley.webPublisher.package = webPublisherStub; }
64 ];
65 };
66 webPublisherHost = webPublisherOffHost.extendModules {
67 modules = [
68 {
69 networking.hostName = "valley-host";
70 services.valley.backup.sshKeyFile = "/run/agenix/valley-git-ssh-key";
71 services.valley.webPublisher = {
72 enable = true;
73 destination = "example.org";
74 receiver = "https://example.org";
75 principals = {
76 operator = "operator";
77 alice = "agent";
78 };
79 };
80 }
81 ];
82 };
83 # The publisher reading the registry at a ref the instance repository's
84 # protection does not cover.
85 unprotectedRegistryWebPublisherHost = webPublisherHost.extendModules {
86 modules = [ { services.valley.identity.ref = "refs/heads/registry"; } ];
87 };
88 # The publisher reading the registry at a short ref name, which git would
89 # resolve by trying other names in turn.
90 shortRegistryRefWebPublisherHost = webPublisherHost.extendModules {
91 modules = [ { services.valley.identity.ref = "registry"; } ];
92 };
93 # The publisher with no instance repository to discover the projects and
94 # the signers through.
95 noInstanceWebPublisherHost = webPublisherHost.extendModules {
96 modules = [
97 {
98 services.valley.integrator = {
99 instanceProject = lib.mkForce null;
100 instancePolicy = "/var/lib/valley-instance/policy/instance";
101 };
102 }
103 ];
104 };
105
106 failedAssertions = builtins.filter (a: !a.assertion) (
107 host.config.assertions
108 ++ noBackupHost.config.assertions
109 ++ busHost.config.assertions
110 ++ mirrorHost.config.assertions
111 ++ protectedHost.config.assertions
112 ++ integratorHost.config.assertions
113 ++ integratorSelfHost.config.assertions
114 ++ restrictedHost.config.assertions
115 ++ identityHost.config.assertions
116 ++ workerHost.config.assertions
117 ++ buildSliceHost.config.assertions
118 ++ webPublisherHost.config.assertions
119 ++ webPublisherOffHost.config.assertions
120 );
121
122 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
123
124 # The hosts the module must refuse, each with the words its refusal must
125 # say. An assertion that stopped firing would leave the push policy
126 # quietly wrong, so each is held to naming what is wrong.
127 refusedHosts = [
128 {
129 host = unprotectedInstanceHost;
130 says = "whose refs/heads/main is not protected";
131 why = "an instance repository without protection would let any key that can push rewrite the floor and the registry";
132 }
133 {
134 host = acceptEnvHost;
135 says = "AcceptEnv";
136 why = "sshd accepting the principal variable from the client would let any key name any principal";
137 }
138 {
139 host = matchAcceptEnvHost;
140 says = "GIT_CONFIG_*";
141 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";
142 }
143 {
144 host = wildcardAcceptEnvHost;
145 says = "G?T_*";
146 why = "a wildcard that admits GIT_ variables admits them however it is spelled";
147 }
148 {
149 host = quotedAcceptEnvHost;
150 says = "holds a quote or a backslash";
151 why = "a quoted name is one sshd unquotes and admits, so a check that read it differently would pass it";
152 }
153 {
154 host = tabAcceptEnvHost;
155 says = "VALLEY_PRINCIPAL from the client";
156 why = "a name after a tab is a name sshd admits";
157 }
158 {
159 host = setEnvHost;
160 says = "SetEnv";
161 why = "sshd setting the principal itself would make every key push as it";
162 }
163 {
164 host = permitUserEnvironmentHost;
165 says = "PermitUserEnvironment";
166 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";
167 }
168 {
169 host = spacedSignerProjectsHost;
170 says = "services.valley.integrator.signerProjects holds";
171 why = "a project with a space in it would be read back as two projects the declaration never listed";
172 }
173 {
174 host = unicodeSpacedSignerProjectsHost;
175 says = "services.valley.integrator.signerProjects holds";
176 why = "a project holding a no-break space would be read back by the integrator as two projects, or refused at start";
177 }
178 {
179 host = noSliceWorkerHost;
180 says = "services.valley.worker.enable needs services.valley.buildSlice.enable";
181 why = "a worker on a host without the build slice would build uncapped, and capping every build of the daemon is the host's decision, not the worker's";
182 }
183 {
184 host = unrestrictedWorkerHost;
185 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
186 why = "a worker whose signer no project list restricts would have its evidence counted in every project by every controller that holds its key";
187 }
188 {
189 host = widerWorkerHost;
190 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
191 why = "a worker trusted in a project it does not build would be trusted where it does no work";
192 }
193 {
194 host = integratorNamedWorkerHost;
195 says = "services.valley.worker.signerName must differ from integrator";
196 why = "a worker signing under the controllers' name would make every controller refuse to start";
197 }
198 {
199 host = conflictingKeysHost;
200 says = "more than one principal tag";
201 why = "a key declared under two tags would push as whichever entry sshd reads first";
202 }
203 {
204 host = unprotectedRegistryWebPublisherHost;
205 says = "whose refs/heads/registry is not protected";
206 why = "a publisher reading the registry at an unprotected ref would let any key that can push there grant anyone read";
207 }
208 {
209 host = shortRegistryRefWebPublisherHost;
210 says = "services.valley.identity.ref is registry, which is not a full ref name";
211 why = "git resolves a ref that is not a full name by trying several refs in turn, and a pusher can make one of them";
212 }
213 {
214 host = noInstanceWebPublisherHost;
215 says = "services.valley.webPublisher needs services.valley.integrator.instanceProject";
216 why = "a publisher with no instance repository has no publication to discover the projects and their signers through";
217 }
218 ];
219
220 unrefusedHosts = builtins.filter (
221 r: !(lib.any (a: !a.assertion && lib.hasInfix r.says a.message) r.host.config.assertions)
222 ) refusedHosts;
223
224 protectedKeyLines = protectedHost.config.users.users.git.openssh.authorizedKeys.keys;
225
226 resticRenderedWithoutDeclaration =
227 noBackupHost.config.systemd.services ? "restic-backups-valley"
228 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
229
230 # The bus defaults off; a host that never asked for one must
231 # render zero bus machinery.
232 busRenderedWithoutEnable =
233 noBackupHost.config.systemd.services ? valley-bus
234 || noBackupHost.config.systemd.services ? valley-bus-init;
235
236 # A declaration with no protection block and no tagged key still gets
237 # the push policy on every project — the policy is the host's, and a
238 # protection block only adds protected refs to it — and nothing of the
239 # principal machinery: no tag on a key, no sshd change.
240 protectionRenderedWithoutDeclaration =
241 noBackupHost.config.services.openssh.settings ? PermitUserEnvironment
242 || lib.any (lib.hasInfix "environment=") (
243 noBackupHost.config.users.users.git.openssh.authorizedKeys.keys
244 );
245
246 policyMissingWithoutDeclaration =
247 !(lib.hasInfix "valley-protect-the-valley" noBackupHost.config.systemd.services.valley-init.script);
248
249 # The integrator's units. What a controller *does* is not checked here
250 # and no VM is booted: that is integrator-e2e's job (the real binaries
251 # over real repositories) and, past it, live exercise on a host. These
252 # assertions cover the wiring — that a controller is rendered for what
253 # the declaration protects and for nothing else, under an identity that
254 # is not the git user's, pointed at the key and the signers the consumer
255 # supplied.
256 #
257 # There is a seam between those two halves that neither reaches, and in a
258 # single day it produced five deployment failures. Every assertion below is
259 # an eval of the unit's text; integrator-e2e runs the binaries with no unit
260 # around them at all. What sits between is the unit's sandbox and identity
261 # meeting the filesystem the binaries actually use at runtime:
262 #
263 # - git refusing a repository the service does not own (bd-500adf7)
264 # - a push authenticating as the operator rather than as the run
265 # (bd-353c59d)
266 # - no writable temporary directory, so no worktree could be made
267 # - the worktree metadata root, created by whichever service reached it
268 # first and then unchmodable by the other, which failed valley-init and
269 # took every valley unit down with it
270 # - the state directory not writable under ProtectSystem=strict unless
271 # the unit names it, which the previous fix had made the scratch root
272 #
273 # Each was found by a host, minutes of a live service after a deploy that
274 # every check here passed. They compose: the third's fix set up the fourth,
275 # and the fourth's fix set up the fifth. That is the argument. A seam whose
276 # failures feed each other is not one to pin an assertion at a time, and
277 # each assertion here that marks a piece of it — the git ownership
278 # exception, TMPDIR, the worktrees root, ReadWritePaths — marks a place a
279 # smoke boot would have spoken first.
280 #
281 # A nixosTest that boots one host, starts the units and reconciles one
282 # change end to end is the next check this module needs. Nothing else
283 # closes the seam, and five incidents is enough evidence of what it costs
284 # to leave open. Not built here.
285 #
286 # Protection and integration are separable declarations: protectedHost
287 # declares the same protected projects with the service off, and must
288 # evaluate to no controller at all.
289 integratorRenderedWithoutEnable =
290 protectedHost.config.systemd.services ? "valley-integrator@"
291 || protectedHost.config.systemd.targets ? valley-integrators
292 || lib.hasInfix "sharedRepository" protectedHost.config.systemd.services.valley-init.script;
293
294 # One target pulls in each controller, and another the path unit that
295 # publishes each project's queued moves, landings included.
296 integratorWants = integratorHost.config.systemd.targets.valley-integrators.wants;
297 controllers = lib.filter (lib.hasPrefix "valley-integrator@") integratorWants;
298 publishers = integratorHost.config.systemd.targets.valley-publish.wants;
299
300 integratorUser = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.User;
301
302 # The controller is not the repositories' owner, which is the whole point
303 # of running it as itself — so git needs an ownership exception, and
304 # where that exception lives is load-bearing. GIT_CONFIG_* is command
305 # scope, the only scope besides system and global that safe.directory is
306 # read from, and the unit's environment is inherited by every git the
307 # controller drives. It names one repository: a wildcard here would hand
308 # a compromised controller every repository on the host.
309 integratorGitEnv = integratorHost.config.systemd.services."valley-integrator@".environment;
310
311 # The count is what git reads; an entry past it is an entry git ignores,
312 # silently. So it is checked against the entries actually rendered rather
313 # than against a number written here, which would have to be edited every
314 # time a grant is added and would go on passing if it were not.
315 integratorSafeDirectory =
316 integratorGitEnv.GIT_CONFIG_KEY_0 or null != "safe.directory"
317 || integratorGitEnv.GIT_CONFIG_VALUE_0 or null != "/srv/git/%i.git"
318 || integratorGitEnv.GIT_CONFIG_COUNT or null
319 != toString (
320 lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames integratorGitEnv))
321 );
322
323 integratorService = integratorHost.config.systemd.services."valley-integrator@".serviceConfig;
324
325 # Scratch goes under the state directory, because the sandbox leaves no
326 # writable temporary directory and a verdict needs a checkout on disk. Two
327 # halves, and each was a live failure on its own. TMPDIR naming a path
328 # outside the state directory is the first; the state directory not being
329 # named in ReadWritePaths is the second, which failed even though
330 # ProtectSystem=strict is documented to leave a declared state directory
331 # writable. Everything the unit may write is enumerated, so what a reader
332 # of the unit sees is the whole of it.
333 # The floor is read from the instance repository's integrated tip
334 # (dcr-f41f718, dcr-b87f6e8), so a controller is told which repository
335 # carries it and reads it there. Three things have to be true of that, and
336 # each was a way for it to be silently wrong.
337 #
338 # The controller has to be told at all — the failure this replaced was a
339 # binary looking for a materialized directory nothing populated.
340 #
341 # It has to work when the repository carrying the floor is not the one the
342 # controller serves, which is the ordinary case: on integratorHost every
343 # controller serves a protected project and reads the floor out of
344 # "open", which no controller serves. git refuses a repository the caller
345 # does not own, so that read needs its own safe.directory entry, named and
346 # not wildcarded — the same failure as the served repository's, one
347 # repository over.
348 #
349 # And it has to keep working when the two coincide, which is what an
350 # instance's own host looks like: integratorSelfHost's controller for
351 # "guarded" reads the floor from "guarded".
352 integratorFloor =
353 let
354 command = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
355 selfCommand = integratorSelfHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
356 env = integratorHost.config.systemd.services."valley-integrator@".environment;
357 in
358 !(lib.hasInfix "--instance-repo /srv/git/sealed.git" command)
359 || !(lib.hasInfix "--instance-repo /srv/git/guarded.git" selfCommand)
360 || env.GIT_CONFIG_COUNT or null != "2"
361 || env.GIT_CONFIG_KEY_1 or null != "safe.directory"
362 || env.GIT_CONFIG_VALUE_1 or null != "/srv/git/sealed.git";
363
364 integratorScratch =
365 integratorGitEnv.TMPDIR or null != "/var/lib/${integratorService.StateDirectory}"
366 || !(builtins.elem "/var/lib/${integratorService.StateDirectory}" integratorService.ReadWritePaths);
367
368 # The registry compiler. It is off by default and must stay inert: a
369 # consumer that has not asked for it renders the system it always did.
370 # integratorHost is the strongest witness available — the integrator on,
371 # the signers file supplied by hand, and every option of the identity
372 # block left alone.
373 identityRenderedWithoutEnable =
374 integratorHost.config.systemd.services ? valley-identity
375 || integratorHost.config.systemd.timers ? valley-identity
376 || integratorHost.config.services.openssh.settings ? PermitUserEnvironment
377 || lib.any (lib.hasInfix "valley-identity") integratorHost.config.services.openssh.authorizedKeysFiles
378 || lib.hasInfix "valley-identity" integratorHost.config.services.openssh.extraConfig
379 || lib.hasInfix "valley-identity" (
380 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
381 )
382 || lib.hasInfix "--name " (
383 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
384 );
385
386 identityService = identityHost.config.systemd.services.valley-identity.serviceConfig;
387
388 identityStateDir = "/var/lib/${identityService.StateDirectory or ""}";
389
390 # What the compiled artifacts have to be true of, and each was a way for
391 # the machinery to be quietly wrong.
392 #
393 # The compiler writes into its state directory and nowhere else, so that
394 # directory has to be the one path the unit may write.
395 #
396 # sshd walks every directory above an authorized-keys file and refuses a
397 # group- or world-writable one, so the state directory is 0755 rather than
398 # the 0700 a service's state usually takes — and the unit runs as the git
399 # user, because sshd equally refuses a file owned by anyone but root or
400 # the account it authorizes.
401 #
402 # The compiled file is added to what sshd reads for the git user rather
403 # than replacing it, and for the git user alone: the user's Match block
404 # names the declared keys and the compiled ones, and nothing else — no
405 # ~/.ssh/authorized_keys, no AuthorizedKeysCommand — so every key the git
406 # user accepts carries a tag this module or the compiler wrote. The
407 # compiler is handed the declared keys, so it can refuse a registry key
408 # declared under another tag.
409 identityCompiler =
410 identityService.User or null != identityHost.config.services.valley.user
411 || identityService.StateDirectoryMode or null != "0755"
412 || identityService.ReadWritePaths or [ ] != [ identityStateDir ]
413 || !(lib.hasInfix "--repo /srv/git/sealed.git" identityService.ExecStart)
414 || !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" identityService.ExecStart)
415 || !(lib.hasInfix "--authorized-keys ${identityStateDir}/authorized_keys.git" identityService.ExecStart)
416 || !(lib.hasInfix "--grants ${identityStateDir}/grants" identityService.ExecStart)
417 || !(lib.hasInfix "-valley-declared-keys" identityService.ExecStart)
418 || !(lib.hasInfix "AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u ${identityStateDir}/authorized_keys.git\n" identityHost.config.services.openssh.extraConfig)
419 || !(lib.hasInfix "AuthorizedKeysCommand none" identityHost.config.services.openssh.extraConfig);
420
421 # A controller under a compiled registry reads the compiled signers file
422 # and signs under the name the registry publishes its key under. The key
423 # hash binds name to key, so a controller signing under the host's default
424 # name while the registry publishes it as "integrator" would produce notes
425 # no verifier can find a key for.
426 identityIntegrator =
427 let
428 command = identityHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
429 in
430 !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" command)
431 || !(lib.hasInfix "--name integrator" command)
432 || !(builtins.elem "valley-identity.service"
433 identityHost.config.systemd.services."valley-integrator@".after
434 );
435
436 # The signers publication. A host whose integrator runs and which serves
437 # the instance repository publishes there what a client verifies its
438 # transfer statements with. What it publishes has to be what the
439 # controllers use: the same signers file and the same --name, or none on
440 # either, in which case both take the binary's default. The publisher
441 # writes as the git user, which owns the instance repository, may write
442 # that repository and nothing else, runs after the compilation when there
443 # is one, and runs again whenever the signers file changes. The signer
444 # projects file is the controllers' too, or neither has one.
445 flagValue =
446 flag: command:
447 let
448 m = builtins.match ".*--${flag} ([^ ]+).*" command;
449 in
450 if m == null then null else lib.head m;
451
452 signersPublisher =
453 host: repo:
454 let
455 unit = host.config.systemd.services.valley-signers;
456 publish = unit.serviceConfig.ExecStart;
457 controller = host.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
458 in
459 !(lib.hasInfix "/bin/integrator publish-signers " publish)
460 || flagValue "instance-repo" publish != repo
461 || flagValue "known-signers" publish != flagValue "known-signers" controller
462 || flagValue "name" publish != flagValue "name" controller
463 || flagValue "signer-projects" publish != flagValue "signer-projects" controller
464 || unit.serviceConfig.User or null != "git"
465 || unit.serviceConfig.ReadWritePaths or [ ] != [ repo ]
466 || !(builtins.elem "valley-init.service" unit.after)
467 || !(builtins.elem "multi-user.target" unit.wantedBy)
468 || host.config.systemd.paths.valley-signers.pathConfig.PathChanged or null
469 != flagValue "known-signers" controller
470 || !(builtins.elem "multi-user.target" host.config.systemd.paths.valley-signers.wantedBy);
471
472 signersRenderedWithoutIntegrator =
473 protectedHost.config.systemd.services ? valley-signers
474 || protectedHost.config.systemd.paths ? valley-signers;
475
476 signersUnpublished =
477 signersPublisher integratorHost "/srv/git/sealed.git"
478 || signersPublisher restrictedHost "/srv/git/sealed.git"
479 || signersPublisher integratorSelfHost "/srv/git/guarded.git"
480 || signersPublisher identityHost "/srv/git/sealed.git"
481 || flagValue "name" identityHost.config.systemd.services.valley-signers.serviceConfig.ExecStart
482 != "integrator"
483 || !(builtins.elem "valley-identity.service" identityHost.config.systemd.services.valley-signers.after);
484
485 # A host that restricts no signer gives its controllers no signer
486 # projects file, and one that restricts some gives them one.
487 signerProjectsMisrendered =
488 flagValue "signer-projects" integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
489 != null
490 || flagValue "signer-projects" restrictedHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
491 == null;
492
493 # The declared keys stay authorized beside the compiled ones. A compiled
494 # file that replaced them would make a bad compilation — or a first boot
495 # before the first one — a locked-out git user, which is the one failure
496 # this machinery must never have.
497 identityKeepsDeclaredKeys =
498 identityHost.config.users.users.git.openssh.authorizedKeys.keys == [ ];
499
500 # The check worker and the build slice. Both are off by default, and a
501 # host that never asked for them renders none of either: no unit, no
502 # account, no slice, and a nix daemon where NixOS puts it. integratorHost
503 # is the strongest witness, with the integrator the worker would need
504 # already on.
505 workerRenderedWithoutEnable =
506 integratorHost.config.systemd.services ? valley-worker
507 || integratorHost.config.systemd.timers ? valley-worker
508 || integratorHost.config.systemd.slices ? valley-builds
509 || integratorHost.config.users.users ? valley-worker
510 || integratorHost.config.systemd.services.nix-daemon.serviceConfig ? Slice;
511
512 # The build slice is a host decision of its own. On, it puts the daemon
513 # in the slice at the caps the host names, with no swap, and nothing of
514 # the worker.
515 buildSliceMisrendered =
516 let
517 slice = buildSliceHost.config.systemd.slices.valley-builds.sliceConfig or { };
518 in
519 buildSliceHost.config.systemd.services.nix-daemon.serviceConfig.Slice or null
520 != "valley-builds.slice"
521 || slice.CPUQuota or null != "200%"
522 || slice.MemoryMax or null != "4G"
523 || slice.MemorySwapMax or null != "0"
524 || buildSliceHost.config.systemd.services ? valley-worker
525 || buildSliceHost.config.users.users ? valley-worker;
526
527 # What the VM check runs, held at the operator's values. worker-e2e
528 # boots the worker and lowers the memory cap at runtime to make a build
529 # run past it, so the values themselves are held here. The caps are on
530 # a slice that holds the worker and the nix daemon both, since a build
531 # runs in the daemon's cgroup and never in the worker's; the slice and
532 # the daemon set no device policy, so a NixOS test still gets /dev/kvm.
533 # The worker runs on one CPU, so attest, which runs one nix build per CPU
534 # it may run on, runs one at a time, and each nix build builds one
535 # derivation at a time with 4 cores. The account is not in the git
536 # group, so the repositories on disk are not the worker's to read or
537 # write, and it reaches them only through this host's sshd, checking the
538 # host's key. Its timer starts the first pass five minutes after the
539 # timer starts, not after boot, and each later pass one minute after the
540 # last one ended.
541 workerMisrendered =
542 let
543 unit = workerHost.config.systemd.services.valley-worker;
544 service = unit.serviceConfig;
545 daemon = workerHost.config.systemd.services.nix-daemon.serviceConfig;
546 slice = workerHost.config.systemd.slices.valley-builds.sliceConfig;
547 account = workerHost.config.users.users.valley-worker;
548 timer = workerHost.config.systemd.timers.valley-worker;
549 devicePolicy = c: c ? DevicePolicy || c ? DeviceAllow || c ? PrivateDevices;
550 in
551 service.User or null != "valley-worker"
552 || account.group != "valley-worker"
553 || account.extraGroups != [ ]
554 || service.Type or null != "oneshot"
555 || service.Slice or null != "valley-builds.slice"
556 || daemon.Slice or null != "valley-builds.slice"
557 || slice.CPUQuota or null != "400%"
558 || slice.MemoryMax or null != "8G"
559 || slice.MemorySwapMax or null != "0"
560 || devicePolicy slice
561 || devicePolicy daemon
562 || service.CPUAffinity or null != "0"
563 || !(lib.hasInfix "max-jobs = 1\n" unit.environment.NIX_CONFIG)
564 || !(lib.hasInfix "cores = 4\n" unit.environment.NIX_CONFIG)
565 || !(lib.hasInfix "builders =\n" unit.environment.NIX_CONFIG)
566 || !(lib.hasInfix "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" unit.environment.GIT_SSH_COMMAND)
567 || service.ReadWritePaths or [ ] != [
568 "/var/lib/valley-worker"
569 "/nix/var/nix/daemon-socket"
570 ]
571 || !(lib.hasInfix "exec valley-worker --repo guarded --repo sealed --key \"$key\" --name worker.valley.invalid/attestations --state \"$state\"" unit.script)
572 || !(lib.hasInfix "git -C \"$origin\" remote add origin git@localhost:sealed.git\n" unit.script)
573 || timer.timerConfig.OnActiveSec or null != "5m"
574 || timer.timerConfig ? OnBootSec
575 || timer.timerConfig.OnUnitInactiveSec or null != "1m"
576 || !(builtins.elem "timers.target" timer.wantedBy);
577
578 # The web publisher (nix/webui-publisher.nix). Off, it renders nothing.
579 # On, one pass is a oneshot on a five-minute timer whose first pass waits
580 # five minutes after the timer starts, and which no switch starts or
581 # restarts. It runs as a dynamic user in the git group, with an empty
582 # safe.directory entry that resets the system's and the user's, then an
583 # exact entry for each repository the host serves and no wildcard, the
584 # repositories read-only, nothing writable but its state and cache, and
585 # the mirror, backup and signing keys out of reach. Its memory is capped
586 # with no swap. It reads the instance repository the controllers read,
587 # names the host as the instance, and is given the receiver, the
588 # destination, the display mapping and the bounds on its bundles and its
589 # storage.
590 webPublisherRenderedWithoutEnable =
591 webPublisherOffHost.config.systemd.services ? valley-web-publish
592 || webPublisherOffHost.config.systemd.timers ? valley-web-publish;
593
594 webPublisherMisrendered =
595 let
596 unit = webPublisherHost.config.systemd.services.valley-web-publish;
597 service = unit.serviceConfig;
598 env = unit.environment;
599 timer = webPublisherHost.config.systemd.timers.valley-web-publish;
600 repos = [
601 "/srv/git/guarded.git"
602 "/srv/git/open.git"
603 "/srv/git/released.git"
604 "/srv/git/sealed.git"
605 ];
606 entries = lib.genList (i: {
607 key = env."GIT_CONFIG_KEY_${toString i}" or null;
608 value = env."GIT_CONFIG_VALUE_${toString i}" or null;
609 }) (lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames env)));
610 command = service.ExecStart;
611 in
612 service.Type or null != "oneshot"
613 || service.DynamicUser or null != true
614 || service ? User
615 || service.SupplementaryGroups or [ ] != [ "git" ]
616 || env.GIT_CONFIG_COUNT or null != toString (lib.length repos + 1)
617 || entries != map (r: {
618 key = "safe.directory";
619 value = r;
620 }) ([ "" ] ++ repos)
621 || lib.any (e: lib.hasInfix "*" e.value) entries
622 || service.ProtectSystem or null != "strict"
623 || service ? ReadWritePaths
624 || service.ReadOnlyPaths or [ ] != map (r: "-${r}") repos
625 || service.StateDirectory or null != "valley-web-publish"
626 || service.CacheDirectory or null != "valley-web-publish"
627 || env.XDG_CACHE_HOME or null != "/var/cache/valley-web-publish"
628 || !(lib.all (p: builtins.elem p service.InaccessiblePaths) [
629 "-/srv/git/.ssh"
630 "-/run/agenix/valley-integrator-key"
631 "-/run/agenix/valley-git-ssh-key"
632 "-/var/lib/valley-integrator"
633 ])
634 || !(lib.hasInfix "/bin/valley-web-publish --instance-repo /srv/git/sealed.git --instance valley-host --destination example.org --receiver https://example.org --principals /nix/store/" command)
635 || !(lib.hasInfix "-valley-web-principals.json --state /var/lib/valley-web-publish --max-bundles 1G --max-storage 16G --registry-ref refs/heads/main --registry-dir identity" command)
636 || service.MemoryMax or null != "1G"
637 || service.MemorySwapMax or null != "0"
638 || unit.restartIfChanged != false
639 || unit.wantedBy != [ ]
640 || timer.timerConfig.OnActiveSec or null != "5min"
641 || timer.timerConfig.OnUnitInactiveSec or null != "5min"
642 || !(builtins.elem "timers.target" timer.wantedBy);
643in
644{
645 module-eval =
646 if failedAssertions != [ ] then
647 throw "valley module-eval: failed assertions: ${
648 lib.concatMapStringsSep "; " (a: a.message) failedAssertions
649 }"
650 else if resticRenderedWithoutDeclaration then
651 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
652 else if busRenderedWithoutEnable then
653 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
654 else if
655 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
656 then
657 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
658 else if unrefusedHosts != [ ] then
659 throw "valley module-eval: ${lib.concatMapStringsSep "; " (r: "a host was not refused although ${r.why}") unrefusedHosts}"
660 else if protectionRenderedWithoutDeclaration then
661 throw "valley module-eval: principal machinery rendered for a declaration with no protection block and no tagged key"
662 else if policyMissingWithoutDeclaration then
663 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"
664 else if protectedHost.config.services.openssh.settings ? PermitUserEnvironment then
665 throw "valley module-eval: sshd must pass no key's environment on: the git user's shell derives the principal from the authenticated key"
666 else if
667 !(lib.hasInfix "valley-git-shell" protectedHost.config.users.users.git.shell)
668 then
669 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"
670 else if integratorRenderedWithoutEnable then
671 throw "valley module-eval: integrator machinery rendered for a protected declaration that never enabled the service"
672 else if !(integratorHost.config.systemd.services ? "valley-integrator@") then
673 throw "valley module-eval: the integrator is enabled and no controller unit was rendered"
674 else if
675 controllers != [
676 "valley-integrator@guarded.service"
677 "valley-integrator@released.service"
678 "valley-integrator@sealed.service"
679 ]
680 then
681 throw "valley module-eval: a controller runs for each protected project and no other, not ${lib.concatStringsSep ", " controllers}"
682 else if
683 publishers != [
684 "valley-publish@guarded.path"
685 "valley-publish@released.path"
686 "valley-publish@sealed.path"
687 ]
688 then
689 throw "valley module-eval: each controller's landings are published by a path unit of its own, not ${lib.concatStringsSep ", " publishers}"
690 else if integratorHost.config.systemd.services."valley-publish@".serviceConfig.User != "git" then
691 throw "valley module-eval: a landing is published as the git user, which holds the mirror credentials"
692 else if integratorUser == integratorHost.config.services.valley.user then
693 throw "valley module-eval: the integrator must not run as the git user — it has its own (bd-500adf7)"
694 else if !(integratorHost.config.users.users ? ${integratorUser}) then
695 throw "valley module-eval: the integrator runs as ${integratorUser}, which the module never declares"
696 else if integratorHost.config.users.users.${integratorUser}.group != "git" then
697 throw "valley module-eval: the integrator reaches the repositories through the git group, and holds no other grant"
698 else if integratorSafeDirectory then
699 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"
700 else if integratorFloor then
701 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"
702 else if integratorScratch then
703 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"
704 else if identityRenderedWithoutEnable then
705 throw "valley module-eval: registry-compilation machinery rendered for a host that never enabled it — nothing may change until a consumer opts in"
706 else if identityCompiler then
707 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"
708 else if identityIntegrator then
709 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"
710 else if signersRenderedWithoutIntegrator then
711 throw "valley module-eval: a signers publication rendered for a host whose integrator is off — there is no transfer statement to verify"
712 else if signersUnpublished then
713 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"
714 else if signerProjectsMisrendered then
715 throw "valley module-eval: a controller is given a signer projects file exactly when the host restricts a signer to projects"
716 else if identityKeepsDeclaredKeys then
717 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"
718 else if workerRenderedWithoutEnable then
719 throw "valley module-eval: check-worker machinery rendered for a host that never enabled it — nothing, the nix daemon's slice included, may change until a consumer opts in"
720 else if buildSliceMisrendered then
721 throw "valley module-eval: the build slice must put the nix daemon in valley-builds.slice at the quota and memory cap the host names, with no swap, and render nothing of the worker"
722 else if workerMisrendered then
723 throw "valley module-eval: the check worker must run as its own account outside the git group, on one CPU, with one derivation built at a time on 4 cores, in a slice that holds it and the nix daemon to 4 CPUs and 8 GiB with no swap and no device policy, reaching this host's projects through its sshd under the host's own key, on a timer whose first pass waits five minutes after the timer starts and whose later passes are counted from the end of each pass"
724 else if webPublisherRenderedWithoutEnable then
725 throw "valley module-eval: web publisher machinery rendered for a host that imports its module and never enabled it"
726 else if webPublisherMisrendered then
727 throw "valley module-eval: the web publisher must be a oneshot on a five-minute timer whose first pass waits five minutes and which no switch starts, run as a dynamic user in the git group with an empty safe.directory entry and then one exact entry per served repository, the repositories read-only, only its state and cache writable, the host's keys inaccessible and its memory capped with no swap, reading the instance repository and naming the host, the receiver, the destination, the display mapping, the bounds on its bundles and storage, and the identity registry's directory"
728 else
729 pkgs.runCommand "valley-module-eval" {
730 initScript = host.config.systemd.services.valley-init.script;
731 sshdConfig = host.config.services.openssh.extraConfig;
732 resticService = host.config.systemd.units."restic-backups-valley.service".text;
733 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
734 protectedInit = protectedHost.config.systemd.services.valley-init.script;
735 protectedKeys = lib.concatStringsSep "\n" protectedKeyLines;
736 protectedShell = protectedHost.config.users.users.git.shell;
737 integratorUnit = integratorHost.config.systemd.units."valley-integrator@.service".text;
738 integratorInit = integratorHost.config.systemd.services.valley-init.script;
739 publishUnit = host.config.systemd.units."valley-publish@.service".text;
740 identityInit = identityHost.config.systemd.services.valley-init.script;
741 passAsFile = [
742 "initScript"
743 "sshdConfig"
744 "resticService"
745 "resticTimer"
746 "protectedInit"
747 "protectedKeys"
748 "integratorUnit"
749 "integratorInit"
750 "publishUnit"
751 "identityInit"
752 ];
753 } (builtins.readFile ./module-eval.sh);
754}