gunk-dev/the-valley

host-module.nix

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