gunk-dev/the-valley

host-module.nix

sourcec14b0e68e9c3main's published tip history
84.2 KiB
1# What the NixOS modules render from a declaration, and what they must refuse.
2# This covers the valley host module, the web publisher module alongside it,
3# and the web receiver module on an edge host.
4# The refusals are eval-time: a host that must not evaluate is caught by a
5# throw here, since there is nothing to build once it has. What a host does
6# render is pinned by module-eval.sh over the rendered scripts.
7#
8# Every host here runs the stand-ins for this flake's programs
9# (nix/checks/hosts.nix). Nothing here runs a program: each assertion is
10# about the units, hooks and scripts the module renders, which name a
11# program's path and the flags it is given. So module-eval changes when the
12# module, a host declaration or this check does, and not when a program
13# does.
14{
15 pkgs,
16 lib,
17 self,
18 stubbedHosts,
19 ...
20}:
21let
22 inherit (stubbedHosts)
23 unprotectedInstanceHost
24 acceptEnvHost
25 matchAcceptEnvHost
26 wildcardAcceptEnvHost
27 quotedAcceptEnvHost
28 tabAcceptEnvHost
29 setEnvHost
30 permitUserEnvironmentHost
31 conflictingKeysHost
32 host
33 noBackupHost
34 noSecretsHost
35 protectedHost
36 busHost
37 mirrorHost
38 integratorHost
39 integratorSelfHost
40 restrictedHost
41 spacedSignerProjectsHost
42 unicodeSpacedSignerProjectsHost
43 identityHost
44 workerHost
45 capacityWorkerHost
46 defaultWorkerHost
47 narrowedWorkerHost
48 mismatchedWorkerHost
49 buildSliceHost
50 noSliceWorkerHost
51 unrestrictedWorkerHost
52 widerWorkerHost
53 integratorNamedWorkerHost
54 restackerHost
55 defaultRestackerHost
56 unservedRestackerHost
57 keylessRestackerHost
58 telemetryHost
59 onMainHost
60 ;
61
62 # The web publisher's module (nix/web-publisher.nix) beside the host
63 # module, over integratorHost: its instance repository is the one the
64 # controllers read the floor from. The host also has a backup key the
65 # publisher must not read. The publisher is a stand-in, as the host's
66 # programs are. webPublisherOffHost imports the module and leaves it off.
67 webPublisherStub = pkgs.writeShellScriptBin "valley-web-publish" ''
68 echo "valley-web-publish: a stand-in the module checks render hosts over, which runs nothing" >&2
69 exit 1
70 '';
71 webPublisherOffHost = stubbedHosts.integratorHost.extendModules {
72 modules = [
73 self.nixosModules.web-publisher
74 { services.valley.webPublisher.package = webPublisherStub; }
75 ];
76 };
77 webPublisherHost = webPublisherOffHost.extendModules {
78 modules = [
79 {
80 networking.hostName = "valley-host";
81 services.valley.backup.sshKeyFile = "/run/agenix/valley-git-ssh-key";
82 services.valley.webPublisher = {
83 enable = true;
84 destination = "example.org";
85 receiver = "https://example.org";
86 receiverTokenFile = "/run/keys/valley-web-receiver-token";
87 allowedAddresses = [
88 "192.0.2.10"
89 "2001:db8::10"
90 ];
91 principals = {
92 operator = "operator";
93 alice = "agent";
94 };
95 };
96 }
97 ];
98 };
99 # The publisher on a host whose declaration asks for a backup.
100 backupWebPublisherHost = webPublisherHost.extendModules {
101 modules = [
102 {
103 services.valley.config = lib.mkForce (
104 pkgs.runCommand "protected-with-backup.cue" { } ''
105 cat ${../../examples/hosts/protected.cue} > $out
106 printf '\nbackup: target: "restic-sftp"\n' >> $out
107 ''
108 );
109 services.valley.backup = {
110 repositoryFile = "/run/agenix/valley-restic-repo";
111 passwordFile = "/run/agenix/valley-restic-password";
112 knownHostsFile = "/var/lib/valley-backup/known_hosts";
113 };
114 }
115 ];
116 };
117 # The publisher reading the registry at a ref the instance repository's
118 # protection does not cover.
119 unprotectedRegistryWebPublisherHost = webPublisherHost.extendModules {
120 modules = [ { services.valley.identity.ref = "refs/heads/registry"; } ];
121 };
122 # The publisher reading the registry at a short ref name, which git would
123 # resolve by trying other names in turn.
124 shortRegistryRefWebPublisherHost = webPublisherHost.extendModules {
125 modules = [ { services.valley.identity.ref = "registry"; } ];
126 };
127 # The publisher with no instance repository to discover the projects and
128 # the signers through.
129 noInstanceWebPublisherHost = webPublisherHost.extendModules {
130 modules = [
131 {
132 services.valley.integrator = {
133 instanceProject = lib.mkForce null;
134 instancePolicy = "/var/lib/valley-instance/policy/instance";
135 };
136 }
137 ];
138 };
139
140 # The web receiver module (nix/web-receiver.nix) on a standalone edge
141 # host, evaluated with stand-in binaries. webReceiverOffHost imports the
142 # module while leaving it disabled.
143 edgeStub =
144 name:
145 pkgs.writeShellScriptBin name ''
146 echo "${name}: a stand-in the module checks render hosts over, which runs nothing" >&2
147 exit 1
148 '';
149 webReceiverOffHost = lib.nixosSystem {
150 inherit pkgs;
151 modules = [
152 self.nixosModules.web-receiver
153 {
154 fileSystems."/" = {
155 device = "/dev/disk/by-label/nixos";
156 fsType = "ext4";
157 };
158 boot.loader.grub.enable = false;
159 system.stateVersion = "25.11";
160 services.valley.webReceiver = {
161 receiverPackage = edgeStub "valley-web-receive";
162 webPackage = edgeStub "valley-web";
163 };
164 }
165 ];
166 };
167 webReceiverHost = webReceiverOffHost.extendModules {
168 modules = [
169 {
170 services.valley.webReceiver = {
171 enable = true;
172 instance = "valley-host";
173 destination = "example.org";
174 verifiers = [ "valley-host/web-export+1a2b3c4d+AQ" ];
175 tokenFile = "/run/keys/valley-web-receiver-token";
176 listen = "192.0.2.10:8081";
177 webListen = "127.0.0.1:8080";
178 };
179 }
180 ];
181 };
182 # The receiver and valley-web with readers signing in at an origin.
183 webReaderHost = webReceiverHost.extendModules {
184 modules = [ { services.valley.webReceiver.origin = "https://example.org"; } ];
185 };
186 # The receiver with its token in the Nix store, and with no verifier.
187 storeTokenWebReceiverHost = webReceiverHost.extendModules {
188 modules = [
189 { services.valley.webReceiver.tokenFile = lib.mkForce "${pkgs.writeText "token" "x"}"; }
190 ];
191 };
192 noVerifierWebReceiverHost = webReceiverHost.extendModules {
193 modules = [ { services.valley.webReceiver.verifiers = lib.mkForce [ ]; } ];
194 };
195 # The publisher allowed to connect to no address.
196 noAddressWebPublisherHost = webPublisherHost.extendModules {
197 modules = [ { services.valley.webPublisher.allowedAddresses = lib.mkForce [ ]; } ];
198 };
199 # The publisher allowed the canary its unit's check must be denied.
200 canaryWebPublisherHost = webPublisherHost.extendModules {
201 modules = [ { services.valley.webPublisher.allowedAddresses = [ "198.51.100.0/24" ]; } ];
202 };
203 # The publisher with its token in the Nix store.
204 storeTokenWebPublisherHost = webPublisherHost.extendModules {
205 modules = [
206 { services.valley.webPublisher.receiverTokenFile = lib.mkForce "${pkgs.writeText "token" "x"}"; }
207 ];
208 };
209
210 # The same, with the source named as one of the module's own.
211 collidingTelemetryHost = telemetryHost.extendModules {
212 modules = [
213 {
214 services.valley.telemetry.localSources = [
215 {
216 name = "worker";
217 description = "a name the module already uses";
218 units = [ "converge.service" ];
219 }
220 ];
221 }
222 ];
223 };
224
225 # The onMain bindings the module must refuse: a project the host does not
226 # serve, a unit bound twice, a name too long for a user's, unit names
227 # that would need quoting, and a bound unit that restarts.
228 unservedOnMainHost = onMainHost.extendModules {
229 modules = [ { services.valley.onMain.deploy.project = lib.mkForce "nowhere"; } ];
230 };
231 boundTwiceOnMainHost = onMainHost.extendModules {
232 modules = [ { services.valley.onMain.docs.unit = lib.mkForce "converge.service"; } ];
233 };
234 longNameOnMainHost = onMainHost.extendModules {
235 modules = [
236 {
237 services.valley.onMain.a-name-of-seventeen = {
238 project = "open";
239 unit = "long.service";
240 };
241 }
242 ];
243 };
244 onMainUnitNamedHost =
245 unit:
246 onMainHost.extendModules {
247 modules = [ { services.valley.onMain.docs.unit = lib.mkForce unit; } ];
248 };
249 restartingOnMainHost = onMainHost.extendModules {
250 modules = [ { systemd.services.converge.serviceConfig.Restart = "on-failure"; } ];
251 };
252
253 # mirrorHost with a second mirror on mirror-pilot, which already has one.
254 addedMirrorHost = mirrorHost.extendModules {
255 modules = [
256 {
257 services.valley.config = lib.mkForce (
258 pkgs.writeText "valley-added-mirror.cue" (
259 builtins.replaceStrings
260 [ ''"mirror-pilot": mirrors: ["../mirror.git"]'' ]
261 [ ''"mirror-pilot": mirrors: ["../mirror.git", "../second-mirror.git"]'' ]
262 (builtins.readFile ../../examples/hosts/mirrors.cue)
263 )
264 );
265 }
266 ];
267 };
268
269 failedAssertions = builtins.filter (a: !a.assertion) (
270 host.config.assertions
271 ++ noBackupHost.config.assertions
272 ++ busHost.config.assertions
273 ++ mirrorHost.config.assertions
274 ++ protectedHost.config.assertions
275 ++ integratorHost.config.assertions
276 ++ integratorSelfHost.config.assertions
277 ++ restrictedHost.config.assertions
278 ++ identityHost.config.assertions
279 ++ workerHost.config.assertions
280 ++ capacityWorkerHost.config.assertions
281 ++ defaultWorkerHost.config.assertions
282 ++ narrowedWorkerHost.config.assertions
283 ++ restackerHost.config.assertions
284 ++ telemetryHost.config.assertions
285 ++ onMainHost.config.assertions
286 ++ defaultRestackerHost.config.assertions
287 ++ buildSliceHost.config.assertions
288 ++ webPublisherHost.config.assertions
289 ++ webPublisherOffHost.config.assertions
290 ++ webReceiverHost.config.assertions
291 ++ webReaderHost.config.assertions
292 ++ webReceiverOffHost.config.assertions
293 );
294
295 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
296
297 # The hosts the module must refuse, each with the words its refusal must
298 # say. An assertion that stopped firing would leave the push policy
299 # quietly wrong, so each is held to naming what is wrong.
300 refusedHosts = [
301 {
302 host = unprotectedInstanceHost;
303 says = "whose refs/heads/main is not protected";
304 why = "an instance repository without protection would let any key that can push rewrite the floor and the registry";
305 }
306 {
307 host = acceptEnvHost;
308 says = "AcceptEnv";
309 why = "sshd accepting the principal variable from the client would let any key name any principal";
310 }
311 {
312 host = matchAcceptEnvHost;
313 says = "GIT_CONFIG_*";
314 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";
315 }
316 {
317 host = wildcardAcceptEnvHost;
318 says = "G?T_*";
319 why = "a wildcard that admits GIT_ variables admits them however it is spelled";
320 }
321 {
322 host = quotedAcceptEnvHost;
323 says = "holds a quote or a backslash";
324 why = "a quoted name is one sshd unquotes and admits, so a check that read it differently would pass it";
325 }
326 {
327 host = tabAcceptEnvHost;
328 says = "VALLEY_PRINCIPAL from the client";
329 why = "a name after a tab is a name sshd admits";
330 }
331 {
332 host = setEnvHost;
333 says = "SetEnv";
334 why = "sshd setting the principal itself would make every key push as it";
335 }
336 {
337 host = permitUserEnvironmentHost;
338 says = "PermitUserEnvironment";
339 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";
340 }
341 {
342 host = spacedSignerProjectsHost;
343 says = "services.valley.integrator.signerProjects holds";
344 why = "a project with a space in it would be read back as two projects the declaration never listed";
345 }
346 {
347 host = unicodeSpacedSignerProjectsHost;
348 says = "services.valley.integrator.signerProjects holds";
349 why = "a project holding a no-break space would be read back by the integrator as two projects, or refused at start";
350 }
351 {
352 host = noSliceWorkerHost;
353 says = "services.valley.worker.enable needs services.valley.buildSlice.enable";
354 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";
355 }
356 {
357 host = unrestrictedWorkerHost;
358 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
359 why = "a worker whose signer no project list restricts would have its evidence counted in every project by every controller that holds its key";
360 }
361 {
362 host = widerWorkerHost;
363 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
364 why = "a worker trusted in a project it does not build would be trusted where it does no work";
365 }
366 {
367 host = mismatchedWorkerHost;
368 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
369 why = "a host that writes the signer's list must write the worker's projects, and the module's own entry must not be merged into it";
370 }
371 {
372 host = integratorNamedWorkerHost;
373 says = "services.valley.worker.signerName must differ from integrator";
374 why = "a worker signing under the controllers' name would make every controller refuse to start";
375 }
376 {
377 host = unservedRestackerHost;
378 says = "services.valley.restacker.projects must name at least one project, and only projects this host serves, and it names nowhere";
379 why = "a controller for a project the host does not serve would fail every pass";
380 }
381 {
382 host = keylessRestackerHost;
383 says = "services.valley.restacker.sshKeyFile must be set";
384 why = "a restacker with no key cannot reach the repositories it serves, except as a user that could write them on disk";
385 }
386 {
387 host = conflictingKeysHost;
388 says = "more than one principal tag";
389 why = "a key declared under two tags would push as whichever entry sshd reads first";
390 }
391 {
392 host = unprotectedRegistryWebPublisherHost;
393 says = "whose refs/heads/registry is not protected";
394 why = "a publisher reading the registry at an unprotected ref would let any key that can push there grant anyone read";
395 }
396 {
397 host = shortRegistryRefWebPublisherHost;
398 says = "services.valley.identity.ref is registry, which is not a full ref name";
399 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";
400 }
401 {
402 host = storeTokenWebPublisherHost;
403 says = "services.valley.webPublisher.receiverTokenFile is in the Nix store";
404 why = "the publisher's receiver token is in the Nix store";
405 }
406 {
407 host = noAddressWebPublisherHost;
408 says = "services.valley.webPublisher.allowedAddresses is empty: list the receiver's IP addresses";
409 why = "a publisher with no allowed address would either reach nothing or, allowed everything, reach any host";
410 }
411 {
412 host = canaryWebPublisherHost;
413 says = "services.valley.webPublisher.allowedAddresses covers 198.51.100.1";
414 why = "the check before each pass could not prove the filter in force if the filter allowed its canary";
415 }
416 {
417 host = storeTokenWebReceiverHost;
418 says = "services.valley.webReceiver.tokenFile is in the Nix store";
419 why = "the receiver's token is in the Nix store";
420 }
421 {
422 host = noVerifierWebReceiverHost;
423 says = "services.valley.webReceiver.verifiers names no verifier line";
424 why = "the receiver pins no verifier";
425 }
426 {
427 host = collidingTelemetryHost;
428 says = "source names must be unique, and localSources or remoteSources repeats one: worker";
429 why = "a local source named as one of the module's own would make the catalog name two sources alike";
430 }
431 {
432 host = unservedOnMainHost;
433 says = "services.valley.onMain.deploy.project names nowhere, which this host declaration does not serve";
434 why = "a bridge for a project the host does not serve would follow a repository that is not there";
435 }
436 {
437 host = boundTwiceOnMainHost;
438 says = "services.valley.onMain binds converge.service more than once";
439 why = "a unit bound twice would read two bridges' environment files, and run for two projects' tips";
440 }
441 {
442 host = onMainUnitNamedHost "docs\\x2d.service";
443 says = "services.valley.onMain.docs.unit is \"docs\\\\x2d.service\": name a service whole";
444 why = "a unit name with a backslash would be read as an escape wherever the name is written";
445 }
446 {
447 host = onMainUnitNamedHost "-docs.service";
448 says = "services.valley.onMain.docs.unit is \"-docs.service\": name a service whole";
449 why = "a unit name with a leading hyphen would be read as an option by a command given it";
450 }
451 {
452 host = onMainUnitNamedHost "docs@app.service";
453 says = "services.valley.onMain.docs.unit is \"docs@app.service\": name a service whole";
454 why = "a template's instance would be rendered as a unit of its own, without the template's command";
455 }
456 {
457 host = restartingOnMainHost;
458 says = "services.valley.onMain.deploy: converge.service sets Restart=on-failure. A failed run must stay failed";
459 why = "a bound unit that restarts would run a failed tip again, which only the next tip or the operator may do";
460 }
461 {
462 host = longNameOnMainHost;
463 says = "services.valley.onMain.a-name-of-seventeen: a binding's name is a lower-case letter, then up to 15";
464 why = "a binding's name longer than a user's name can carry would fail the system's build later, with no word of onMain";
465 }
466 {
467 host = noInstanceWebPublisherHost;
468 says = "services.valley.webPublisher needs services.valley.integrator.instanceProject";
469 why = "a publisher with no instance repository has no publication to discover the projects and their signers through";
470 }
471 ];
472
473 unrefusedHosts = builtins.filter (
474 r: !(lib.any (a: !a.assertion && lib.hasInfix r.says a.message) r.host.config.assertions)
475 ) refusedHosts;
476
477 protectedKeyLines = protectedHost.config.users.users.git.openssh.authorizedKeys.keys;
478
479 resticRenderedWithoutDeclaration =
480 noBackupHost.config.systemd.services ? "restic-backups-valley"
481 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
482
483 # The bus defaults off; a host that never asked for one must
484 # render zero bus machinery.
485 busRenderedWithoutEnable =
486 noBackupHost.config.systemd.services ? valley-bus
487 || noBackupHost.config.systemd.services ? valley-bus-init;
488
489 # A declaration with no protection block and no tagged key still gets
490 # the push policy on every project — the policy is the host's, and a
491 # protection block only adds protected refs to it — and nothing of the
492 # principal machinery: no tag on a key, no sshd change.
493 protectionRenderedWithoutDeclaration =
494 noBackupHost.config.services.openssh.settings ? PermitUserEnvironment
495 || lib.any (lib.hasInfix "environment=") (
496 noBackupHost.config.users.users.git.openssh.authorizedKeys.keys
497 );
498
499 policyMissingWithoutDeclaration =
500 !(lib.hasInfix "valley-protect-the-valley" noBackupHost.config.systemd.services.valley-init.script);
501
502 # The integrator's units. What a controller *does* is not checked here
503 # and no VM is booted: that is integrator-e2e's job (the real binaries
504 # over real repositories) and, past it, live exercise on a host. These
505 # assertions cover the wiring — that a controller is rendered for what
506 # the declaration protects and for nothing else, under an identity that
507 # is not the git user's, pointed at the key and the signers the consumer
508 # supplied.
509 #
510 # There is a seam between those two halves that neither reaches, and in a
511 # single day it produced five deployment failures. Every assertion below is
512 # an eval of the unit's text; integrator-e2e runs the binaries with no unit
513 # around them at all. What sits between is the unit's sandbox and identity
514 # meeting the filesystem the binaries actually use at runtime:
515 #
516 # - git refusing a repository the service does not own (bd-500adf7)
517 # - a push authenticating as the operator rather than as the run
518 # (bd-353c59d)
519 # - no writable temporary directory, so no worktree could be made
520 # - the worktree metadata root, created by whichever service reached it
521 # first and then unchmodable by the other, which failed valley-init and
522 # took every valley unit down with it
523 # - the state directory not writable under ProtectSystem=strict unless
524 # the unit names it, which the previous fix had made the scratch root
525 #
526 # Each was found by a host, minutes of a live service after a deploy that
527 # every check here passed. They compose: the third's fix set up the fourth,
528 # and the fourth's fix set up the fifth. That is the argument. A seam whose
529 # failures feed each other is not one to pin an assertion at a time, and
530 # each assertion here that marks a piece of it — the git ownership
531 # exception, TMPDIR, the worktrees root, ReadWritePaths — marks a place a
532 # smoke boot would have spoken first.
533 #
534 # A nixosTest that boots one host, starts the units and reconciles one
535 # change end to end is the next check this module needs. Nothing else
536 # closes the seam, and five incidents is enough evidence of what it costs
537 # to leave open. Not built here.
538 #
539 # Protection and integration are separable declarations: protectedHost
540 # declares the same protected projects with the service off, and must
541 # evaluate to no controller at all.
542 integratorRenderedWithoutEnable =
543 protectedHost.config.systemd.services ? "valley-integrator@"
544 || protectedHost.config.systemd.targets ? valley-integrators
545 || lib.hasInfix "sharedRepository" protectedHost.config.systemd.services.valley-init.script;
546
547 # One target pulls in each controller, and another the path unit that
548 # publishes each project's queued moves, landings included.
549 integratorWants = integratorHost.config.systemd.targets.valley-integrators.wants;
550 controllers = lib.filter (lib.hasPrefix "valley-integrator@") integratorWants;
551 publishers = integratorHost.config.systemd.targets.valley-publish.wants;
552
553 integratorUser = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.User;
554
555 # The controller is not the repositories' owner, which is the whole point
556 # of running it as itself — so git needs an ownership exception, and
557 # where that exception lives is load-bearing. GIT_CONFIG_* is command
558 # scope, the only scope besides system and global that safe.directory is
559 # read from, and the unit's environment is inherited by every git the
560 # controller drives. It names one repository: a wildcard here would hand
561 # a compromised controller every repository on the host.
562 integratorGitEnv = integratorHost.config.systemd.services."valley-integrator@".environment;
563
564 # The count is what git reads; an entry past it is an entry git ignores,
565 # silently. So it is checked against the entries actually rendered rather
566 # than against a number written here, which would have to be edited every
567 # time a grant is added and would go on passing if it were not.
568 integratorSafeDirectory =
569 integratorGitEnv.GIT_CONFIG_KEY_0 or null != "safe.directory"
570 || integratorGitEnv.GIT_CONFIG_VALUE_0 or null != "/srv/git/%i.git"
571 || integratorGitEnv.GIT_CONFIG_COUNT or null
572 != toString (
573 lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames integratorGitEnv))
574 );
575
576 integratorService = integratorHost.config.systemd.services."valley-integrator@".serviceConfig;
577
578 # Scratch goes under the state directory, because the sandbox leaves no
579 # writable temporary directory and a verdict needs a checkout on disk. Two
580 # halves, and each was a live failure on its own. TMPDIR naming a path
581 # outside the state directory is the first; the state directory not being
582 # named in ReadWritePaths is the second, which failed even though
583 # ProtectSystem=strict is documented to leave a declared state directory
584 # writable. Everything the unit may write is enumerated, so what a reader
585 # of the unit sees is the whole of it.
586 # The floor is read from the instance repository's integrated tip
587 # (dcr-f41f718, dcr-b87f6e8), so a controller is told which repository
588 # carries it and reads it there. Three things have to be true of that, and
589 # each was a way for it to be silently wrong.
590 #
591 # The controller has to be told at all — the failure this replaced was a
592 # binary looking for a materialized directory nothing populated.
593 #
594 # It has to work when the repository carrying the floor is not the one the
595 # controller serves, which is the ordinary case: on integratorHost every
596 # controller serves a protected project and reads the floor out of
597 # "open", which no controller serves. git refuses a repository the caller
598 # does not own, so that read needs its own safe.directory entry, named and
599 # not wildcarded — the same failure as the served repository's, one
600 # repository over.
601 #
602 # And it has to keep working when the two coincide, which is what an
603 # instance's own host looks like: integratorSelfHost's controller for
604 # "guarded" reads the floor from "guarded".
605 integratorFloor =
606 let
607 command = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
608 selfCommand = integratorSelfHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
609 env = integratorHost.config.systemd.services."valley-integrator@".environment;
610 in
611 !(lib.hasInfix "--instance-repo /srv/git/sealed.git" command)
612 || !(lib.hasInfix "--instance-repo /srv/git/guarded.git" selfCommand)
613 || env.GIT_CONFIG_COUNT or null != "2"
614 || env.GIT_CONFIG_KEY_1 or null != "safe.directory"
615 || env.GIT_CONFIG_VALUE_1 or null != "/srv/git/sealed.git";
616
617 integratorScratch =
618 integratorGitEnv.TMPDIR or null != "/var/lib/${integratorService.StateDirectory}"
619 || !(builtins.elem "/var/lib/${integratorService.StateDirectory}" integratorService.ReadWritePaths);
620
621 # The controllers' wake directories. Each controller watches its own,
622 # under /run, which the host makes owned by the integrator's user and the
623 # writers' group of the git user and the integrator's user. Its sandbox
624 # may write its own and, for the instance project's controller alone,
625 # each other controller's, which that controller marks after a floor
626 # landing. The drop-in that grants those sets nothing else. The push hook
627 # is wired for every served project and no other repository.
628 integratorWakeMisrendered =
629 let
630 wakeOf = name: "/run/valley-integrator-wake/${name}";
631 dropIn = host: name: host.config.systemd.units."valley-integrator@${name}.service" or null;
632 readers =
633 host: instance: others:
634 let
635 unit = dropIn host instance;
636 in
637 unit == null
638 || unit.overrideStrategy or null != "asDropin"
639 || unit.text != "[Service]\n" + lib.concatMapStrings (o: "ReadWritePaths=-${wakeOf o}\n") others;
640 init = integratorHost.config.systemd.services.valley-init.script;
641 in
642 !(lib.hasInfix "--woken-by /run/valley-integrator-wake/%i" integratorService.ExecStart)
643 || !(lib.hasInfix "$VALLEY_FLOOR_READERS" integratorService.ExecStart)
644 || !(lib.hasPrefix "-/nix/store/" integratorService.EnvironmentFile or "")
645 || !(builtins.elem "-${wakeOf "%i"}" integratorService.ReadWritePaths)
646 || builtins.elem "/run/valley-integrator-wake" integratorService.ReadWritePaths
647 || lib.any (
648 name:
649 !(builtins.elem "d ${wakeOf name} 0770 valley-integrator valley-integrator-wake - -" integratorHost.config.systemd.tmpfiles.rules)
650 || !(lib.hasInfix "${name}.git/hooks/post-receive.d/valley-integrator-wake" init)
651 ) [ "guarded" "released" "sealed" ]
652 || lib.hasInfix "ln -s /nix/store/" (lib.concatStrings (lib.filter (lib.hasInfix "open.git/hooks/post-receive.d/valley-integrator-wake") (lib.splitString "ihook=" init)))
653 || lib.sort lib.lessThan integratorHost.config.users.groups.valley-integrator-wake.members != lib.sort lib.lessThan [
654 integratorHost.config.services.valley.user
655 integratorHost.config.services.valley.integrator.user
656 ]
657 || readers integratorHost "sealed" [ "guarded" "released" ]
658 || readers integratorSelfHost "guarded" [ "released" "sealed" ]
659 || dropIn integratorHost "guarded" != null
660 || dropIn integratorHost "released" != null
661 || protectedHost.config.users.groups ? valley-integrator-wake;
662
663 # The registry compiler. It is off by default and must stay inert: a
664 # consumer that has not asked for it renders the system it always did.
665 # integratorHost is the strongest witness available — the integrator on,
666 # the signers file supplied by hand, and every option of the identity
667 # block left alone.
668 identityRenderedWithoutEnable =
669 integratorHost.config.systemd.services ? valley-identity
670 || integratorHost.config.systemd.timers ? valley-identity
671 || integratorHost.config.systemd.timers ? valley-identity-midnight
672 || integratorHost.config.systemd.paths ? valley-identity
673 || integratorHost.config.services.openssh.settings ? PermitUserEnvironment
674 || lib.any (lib.hasInfix "valley-identity") integratorHost.config.services.openssh.authorizedKeysFiles
675 || lib.hasInfix "valley-identity" integratorHost.config.services.openssh.extraConfig
676 || lib.hasInfix "valley-identity" (
677 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
678 )
679 || lib.hasInfix "--name " (
680 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
681 );
682
683 identityService = identityHost.config.systemd.services.valley-identity.serviceConfig;
684
685 identityStateDir = "/var/lib/${identityService.StateDirectory or ""}";
686
687 # What the compiled artifacts have to be true of, and each was a way for
688 # the machinery to be quietly wrong.
689 #
690 # The compiler writes into its state directory and nowhere else, so that
691 # directory has to be the one path the unit may write.
692 #
693 # sshd walks every directory above an authorized-keys file and refuses a
694 # group- or world-writable one, so the state directory is 0755 rather than
695 # the 0700 a service's state usually takes — and the unit runs as the git
696 # user, because sshd equally refuses a file owned by anyone but root or
697 # the account it authorizes.
698 #
699 # The compiled file is added to what sshd reads for the git user rather
700 # than replacing it, and for the git user alone: the user's Match block
701 # names the declared keys and the compiled ones, and nothing else — no
702 # ~/.ssh/authorized_keys, no AuthorizedKeysCommand — so every key the git
703 # user accepts carries a tag this module or the compiler wrote. The
704 # compiler is handed the declared keys, so it can refuse a registry key
705 # declared under another tag.
706 identityCompiler =
707 identityService.User or null != identityHost.config.services.valley.user
708 || identityService.StateDirectoryMode or null != "0755"
709 || identityService.ReadWritePaths or [ ] != [ identityStateDir ]
710 || !(lib.hasInfix "--repo /srv/git/sealed.git" identityService.ExecStart)
711 || !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" identityService.ExecStart)
712 || !(lib.hasInfix "--authorized-keys ${identityStateDir}/authorized_keys.git" identityService.ExecStart)
713 || !(lib.hasInfix "--grants ${identityStateDir}/grants" identityService.ExecStart)
714 || !(lib.hasInfix "-valley-declared-keys" identityService.ExecStart)
715 || !(lib.hasInfix "AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u ${identityStateDir}/authorized_keys.git\n" identityHost.config.services.openssh.extraConfig)
716 || !(lib.hasInfix "AuthorizedKeysCommand none" identityHost.config.services.openssh.extraConfig);
717
718 # A unit that must not run unless valley-init's latest start succeeded,
719 # and must not run valley-init either: ordered after it and requisite on
720 # it, which valley-init stays active after success for, never requiring
721 # it, which would start it again; and started by valley-init's success.
722 gatedOnInit =
723 host: name:
724 let
725 unit = host.config.systemd.services.${name};
726 init = host.config.systemd.services.valley-init;
727 in
728 builtins.elem "valley-init.service" unit.after
729 && builtins.elem "valley-init.service" unit.requisite
730 && !(builtins.elem "valley-init.service" unit.requires)
731 && !(unit.serviceConfig ? ExecCondition)
732 && init.serviceConfig.RemainAfterExit or false
733 && builtins.elem "${name}.service" init.wants;
734
735 # What starts the compiler: a move of the registry's ref in the instance
736 # repository, seen at its loose file, the one path the unit watches;
737 # 00:00 UTC, when entries expire, at once and with no catch-up start,
738 # since every boot compiles; and the interval timer, kept as recovery.
739 # None of them reruns valley-init, and no burst of starts can fail the
740 # path unit or the compiler.
741 identityStarts =
742 let
743 timers = identityHost.config.systemd.timers;
744 path = identityHost.config.systemd.paths.valley-identity or { };
745 in
746 !(gatedOnInit identityHost "valley-identity")
747 # A successful valley-init starts the controllers too, which require
748 # it, so its repair restores them.
749 || identityHost.config.systemd.targets.valley-integrators.wants == [ ]
750 || !(lib.all (
751 controller: builtins.elem controller identityHost.config.systemd.services.valley-init.wants
752 ) identityHost.config.systemd.targets.valley-integrators.wants)
753 || !(builtins.elem "valley-init.service" identityHost.config.systemd.services."valley-integrator@".requires)
754 || path.pathConfig or null != {
755 PathChanged = [ "/srv/git/sealed.git/refs/heads/main" ];
756 TriggerLimitIntervalSec = 0;
757 }
758 || identityHost.config.systemd.services.valley-identity.startLimitIntervalSec or null != 0
759 || !(builtins.elem "multi-user.target" path.wantedBy or [ ])
760 || timers.valley-identity-midnight.timerConfig or null != {
761 Unit = "valley-identity.service";
762 OnCalendar = "*-*-* 00:00:00 UTC";
763 AccuracySec = "1s";
764 RandomizedDelaySec = "0";
765 Persistent = false;
766 }
767 || !(builtins.elem "timers.target" timers.valley-identity-midnight.wantedBy or [ ])
768 || timers.valley-identity.timerConfig or null != {
769 OnBootSec = "1m";
770 OnUnitActiveSec = "5m";
771 };
772
773 # A controller under a compiled registry reads the compiled signers file
774 # and signs under the name the registry publishes its key under. The key
775 # hash binds name to key, so a controller signing under the host's default
776 # name while the registry publishes it as "integrator" would produce notes
777 # no verifier can find a key for.
778 identityIntegrator =
779 let
780 command = identityHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
781 in
782 !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" command)
783 || !(lib.hasInfix "--name integrator" command)
784 || !(builtins.elem "valley-identity.service"
785 identityHost.config.systemd.services."valley-integrator@".after
786 );
787
788 # The signers publication. A host whose integrator runs and which serves
789 # the instance repository publishes there what a client verifies its
790 # transfer statements with. What it publishes has to be what the
791 # controllers use: the same signers file and the same --name, or none on
792 # either, in which case both take the binary's default. The publisher
793 # writes as the git user, which owns the instance repository, may write
794 # that repository and nothing else, runs after the compilation when there
795 # is one, and runs again whenever a file it publishes from changes: the
796 # signers file, the approval signers files, and the instance repository's
797 # main, loose or packed. The signer projects file is the controllers'
798 # too, or neither has one. The approval signers files are the ones the
799 # compiler writes, or none on a host that compiles no registry.
800 flagValue =
801 flag: command:
802 let
803 m = builtins.match ".*--${flag} ([^ ]+).*" command;
804 in
805 if m == null then null else lib.head m;
806
807 signersPublisher =
808 host: repo:
809 let
810 unit = host.config.systemd.services.valley-signers;
811 publish = unit.serviceConfig.ExecStart;
812 controller = host.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
813 compile = host.config.systemd.services.valley-identity.serviceConfig.ExecStart or "";
814 approvalFlags = [
815 "approval-signers"
816 "approval-signers-hardware"
817 ];
818 approvalFiles = map (flag: flagValue flag publish) approvalFlags;
819 compiled = map (flag: flagValue flag compile) approvalFlags;
820 inputs = [
821 (flagValue "known-signers" controller)
822 ]
823 ++ lib.remove null approvalFiles
824 ++ [
825 "${repo}/refs/heads/main"
826 "${repo}/packed-refs"
827 ];
828 in
829 !(lib.hasInfix "/bin/integrator publish-signers " publish)
830 || flagValue "instance-repo" publish != repo
831 || flagValue "known-signers" publish != flagValue "known-signers" controller
832 || flagValue "name" publish != flagValue "name" controller
833 || flagValue "signer-projects" publish != flagValue "signer-projects" controller
834 || unit.serviceConfig.User or null != "git"
835 || unit.serviceConfig.ReadWritePaths or [ ] != [ repo ]
836 || !(gatedOnInit host "valley-signers")
837 || !(builtins.elem "multi-user.target" unit.wantedBy)
838 || approvalFiles != compiled
839 || (compile != "" && lib.elem null approvalFiles)
840 || host.config.systemd.paths.valley-signers.pathConfig.PathChanged or null != inputs
841 || !(builtins.elem "multi-user.target" host.config.systemd.paths.valley-signers.wantedBy);
842
843 # Each controller takes the approval inputs as paths: the approval
844 # signers files the compiler writes, or none on a host that compiles no
845 # registry, and its project's push policy, which its environment file
846 # names. module-eval.sh follows that file to the one the hook reads.
847 controllerApprovalInputsMisrendered = lib.any (
848 host:
849 let
850 controller = host.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
851 compile = host.config.systemd.services.valley-identity.serviceConfig.ExecStart or "";
852 flags = [
853 "approval-signers"
854 "approval-signers-hardware"
855 ];
856 in
857 map (f: flagValue f controller) flags != map (f: flagValue f compile) flags
858 || !(lib.hasInfix "--push-policy=\${VALLEY_PUSH_POLICY}" controller)
859 ) [
860 integratorHost
861 identityHost
862 ];
863
864 # A project that retains its change records hands the hook that setting,
865 # and one that does not leaves it out, which the hook reads as false.
866 retentionMisrendered =
867 protectedHost.config.services.valley.pushPolicies.sealed.retainChangeRecords or null != true
868 || protectedHost.config.services.valley.pushPolicies.open ? retainChangeRecords;
869
870 # Every run of valley-init queues a push to each mirrored project's
871 # mirrors. A mirror added beside another changes no line of its script,
872 # so the unit must change some other way, or activation would not run
873 # init and the new mirror would wait for the project's next move.
874 addedMirrorUnqueued =
875 mirrorHost.config.systemd.units."valley-init.service".text
876 == addedMirrorHost.config.systemd.units."valley-init.service".text;
877
878 signersRenderedWithoutIntegrator =
879 protectedHost.config.systemd.services ? valley-signers
880 || protectedHost.config.systemd.paths ? valley-signers;
881
882 signersUnpublished =
883 signersPublisher integratorHost "/srv/git/sealed.git"
884 || signersPublisher restrictedHost "/srv/git/sealed.git"
885 || signersPublisher integratorSelfHost "/srv/git/guarded.git"
886 || signersPublisher identityHost "/srv/git/sealed.git"
887 || flagValue "name" identityHost.config.systemd.services.valley-signers.serviceConfig.ExecStart
888 != "integrator"
889 || !(builtins.elem "valley-identity.service" identityHost.config.systemd.services.valley-signers.after);
890
891 # A host that restricts no signer gives its controllers no signer
892 # projects file, and one that restricts some gives them one.
893 signerProjectsMisrendered =
894 flagValue "signer-projects" integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
895 != null
896 || flagValue "signer-projects" restrictedHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
897 == null;
898
899 # The declared keys stay authorized beside the compiled ones. A compiled
900 # file that replaced them would make a bad compilation — or a first boot
901 # before the first one — a locked-out git user, which is the one failure
902 # this machinery must never have.
903 identityKeepsDeclaredKeys =
904 identityHost.config.users.users.git.openssh.authorizedKeys.keys == [ ];
905
906 # The check worker and the build slice. Both are off by default, and a
907 # host that never asked for them renders none of either: no unit, no
908 # account, no slice, and a nix daemon where NixOS puts it. integratorHost
909 # is the strongest witness, with the integrator the worker would need
910 # already on.
911 workerRenderedWithoutEnable =
912 integratorHost.config.systemd.services ? valley-worker
913 || integratorHost.config.systemd.timers ? valley-worker
914 || integratorHost.config.systemd.paths ? valley-worker
915 || integratorHost.config.users.groups ? valley-worker-wake
916 || lib.hasInfix "--wake" integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
917 || integratorHost.config.systemd.slices ? valley-builds
918 || integratorHost.config.users.users ? valley-worker
919 || integratorHost.config.systemd.services.nix-daemon.serviceConfig ? Slice;
920
921 # The build slice is a host decision of its own. On, it puts the daemon
922 # in the slice at the caps the host names, with no swap, and nothing of
923 # the worker.
924 buildSliceMisrendered =
925 let
926 slice = buildSliceHost.config.systemd.slices.valley-builds.sliceConfig or { };
927 in
928 buildSliceHost.config.systemd.services.nix-daemon.serviceConfig.Slice or null
929 != "valley-builds.slice"
930 || slice.CPUQuota or null != "200%"
931 || slice.MemoryMax or null != "4G"
932 || slice.MemorySwapMax or null != "0"
933 || buildSliceHost.config.systemd.services ? valley-worker
934 || buildSliceHost.config.users.users ? valley-worker;
935
936 # What the VM check runs, held at the operator's values. worker-e2e
937 # boots the worker and lowers the memory cap at runtime to make a build
938 # run past it, so the values themselves are held here. The caps are on
939 # a slice that holds the worker and the nix daemon both, since a build
940 # runs in the daemon's cgroup and never in the worker's; the slice and
941 # the daemon set no device policy, so a NixOS test still gets /dev/kvm.
942 # The worker may run on any CPU. A host that sets no build capacity has
943 # the worker run two batches at once and build one check at a time in
944 # each, each nix build building one derivation at a time with 4 cores,
945 # and a pass whose batches run reads again every minute. Its
946 # evaluations share 0.6 of its memory limit (--eval-share 0.6).
947 # capacityWorkerHost's values reach the worker's --batches, --slots,
948 # --interval, --eval-budget and its NIX_CONFIG. The worker keeps check
949 # outputs for 7 days unless a host sets keepOutputs to null, as
950 # capacityWorkerHost does. The account is not in the git
951 # group, so the repositories on disk are not the worker's to read or
952 # write, and it reaches them only through this host's sshd, checking the
953 # host's key. Its timer starts the first pass a second after the timer
954 # starts, not after boot, and each later pass one minute after the last
955 # one ended. Its path unit starts a pass while the wake directory holds
956 # due; the directory is the worker's, in a group of the git user and the
957 # integrator's user, and every writer's sandbox may write it. Nothing
958 # waits for the service at boot, a burst never start-limits it, and a
959 # pass that could not claim due is started again one interval later.
960 workerMisrendered =
961 let
962 unit = workerHost.config.systemd.services.valley-worker;
963 capacity = capacityWorkerHost.config.systemd.services.valley-worker;
964 service = unit.serviceConfig;
965 daemon = workerHost.config.systemd.services.nix-daemon.serviceConfig;
966 slice = workerHost.config.systemd.slices.valley-builds.sliceConfig;
967 account = workerHost.config.users.users.valley-worker;
968 timer = workerHost.config.systemd.timers.valley-worker;
969 wakePath = workerHost.config.systemd.paths.valley-worker;
970 integrator = workerHost.config.systemd.services."valley-integrator@".serviceConfig;
971 signers = workerHost.config.systemd.services.valley-signers.serviceConfig;
972 devicePolicy = c: c ? DevicePolicy || c ? DeviceAllow || c ? PrivateDevices;
973 in
974 service.User or null != "valley-worker"
975 || account.group != "valley-worker"
976 || account.extraGroups != [ ]
977 || service.Type or null != "oneshot"
978 # A switch must not wait on a running pass: the unit is neither
979 # restarted nor stopped when it changes, and no target starts it.
980 || unit.restartIfChanged != false
981 || unit.stopIfChanged != false
982 || unit.wantedBy != [ ]
983 || unit.requiredBy != [ ]
984 || service.Slice or null != "valley-builds.slice"
985 || daemon.Slice or null != "valley-builds.slice"
986 || slice.CPUQuota or null != "400%"
987 || slice.MemoryMax or null != "8G"
988 || slice.MemorySwapMax or null != "0"
989 # The daemon's unit delegates its cgroup, so systemd's OOM policy for
990 # it is continue: a build the kernel's OOM killer kills leaves the
991 # daemon running. Nothing here may set another.
992 || daemon.OOMPolicy or "continue" != "continue"
993 || devicePolicy slice
994 || devicePolicy daemon
995 || service ? CPUAffinity
996 || !(lib.hasInfix "max-jobs = 1\n" unit.environment.NIX_CONFIG)
997 || !(lib.hasInfix "cores = 4\n" unit.environment.NIX_CONFIG)
998 || !(lib.hasInfix "max-jobs = 2\n" capacity.environment.NIX_CONFIG)
999 || !(lib.hasInfix "cores = 2\n" capacity.environment.NIX_CONFIG)
1000 || capacity.serviceConfig ? CPUAffinity
1001 || !(lib.hasInfix "builders =\n" unit.environment.NIX_CONFIG)
1002 || !(lib.hasInfix "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" unit.environment.GIT_SSH_COMMAND)
1003 || service.ReadWritePaths or [ ] != [
1004 "/var/lib/valley-worker"
1005 "/var/lib/valley-worker-wake"
1006 "/nix/var/nix/daemon-socket"
1007 ]
1008 || !(lib.hasInfix "exec valley-worker --repo guarded --repo sealed --key \"$key\" --name worker.valley.invalid/attestations --state \"$state\" --wake /var/lib/valley-worker-wake --slots 1 --batches 2 --interval 1m --eval-share 0.6 --keep-outputs 168h\n" unit.script)
1009 || !(lib.hasInfix "exec valley-worker --repo guarded --repo sealed --key \"$key\" --name worker.valley.invalid/attestations --state \"$state\" --wake /var/lib/valley-worker-wake --slots 3 --batches 3 --interval 5min --eval-budget 12G\n" capacity.script)
1010 || unit.wantedBy != [ ]
1011 || unit.unitConfig.StartLimitIntervalSec or null != 0
1012 || service.RestartForceExitStatus or null != "75"
1013 || service.RestartSec or null != "1m"
1014 || service ? Restart
1015 || wakePath.pathConfig.PathExists or null != "/var/lib/valley-worker-wake/due"
1016 || !(builtins.elem "multi-user.target" wakePath.wantedBy)
1017 || !(builtins.elem "d /var/lib/valley-worker-wake 0770 valley-worker valley-worker-wake - -" workerHost.config.systemd.tmpfiles.rules)
1018 || lib.sort lib.lessThan workerHost.config.users.groups.valley-worker-wake.members != lib.sort lib.lessThan [
1019 workerHost.config.services.valley.user
1020 workerHost.config.services.valley.integrator.user
1021 ]
1022 || !(builtins.elem "/var/lib/valley-worker-wake" integrator.ReadWritePaths)
1023 || !(lib.hasInfix "--wake=\${VALLEY_WAKE}" integrator.ExecStart)
1024 || !(lib.hasPrefix "-/nix/store/" integrator.EnvironmentFile or "")
1025 || !(lib.hasInfix "--wake /var/lib/valley-worker-wake" signers.ExecStart)
1026 || !(builtins.elem "/var/lib/valley-worker-wake" signers.ReadWritePaths)
1027 || !(lib.hasInfix "git -C \"$origin\" remote add origin git@localhost:sealed.git\n" unit.script)
1028 || timer.timerConfig.OnActiveSec or null != "1s"
1029 || timer.timerConfig ? OnBootSec
1030 || timer.timerConfig.OnUnitInactiveSec or null != "1m"
1031 || !(builtins.elem "timers.target" timer.wantedBy);
1032
1033 # The worker's projects when a host leaves them unwritten. A worker host
1034 # that writes neither list builds for every project its controllers
1035 # serve, one that narrows the worker's projects builds for those alone,
1036 # and the signers publication carries the controllers' signer projects
1037 # file. That file's lines are pinned by module-eval.sh.
1038 workerDefaultsMisrendered =
1039 let
1040 unpublished =
1041 host:
1042 flagValue "signer-projects" host.config.systemd.services.valley-signers.serviceConfig.ExecStart
1043 != flagValue "signer-projects"
1044 host.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
1045 in
1046 defaultWorkerHost.config.services.valley.worker.projects != [
1047 "guarded"
1048 "released"
1049 "sealed"
1050 ]
1051 || !(lib.hasInfix "exec valley-worker --repo guarded --repo released --repo sealed --key "
1052 defaultWorkerHost.config.systemd.services.valley-worker.script
1053 )
1054 || !(lib.hasInfix "exec valley-worker --repo guarded --key "
1055 narrowedWorkerHost.config.systemd.services.valley-worker.script
1056 )
1057 || unpublished defaultWorkerHost
1058 || unpublished narrowedWorkerHost;
1059
1060 # The restacker. When disabled, it renders no units or user account on
1061 # integratorHost. When enabled, each configured project gets a
1062 # valley-restacker@<project>.service running valley-restacker run as the
1063 # valley-restacker user in its own group, with no access to the bare
1064 # repositories on disk. It connects through localhost sshd as its
1065 # principal using the key passed via LoadCredential, verifies the host's
1066 # own SSH key, has its 0700 state directory as its only persistent
1067 # writable path (its private temporary directories are writable too),
1068 # and reads the floor from the instance repository over the same SSH
1069 # connection. A host that lists one project gets only that one; a host
1070 # that lists none gets one for each project it integrates.
1071 restackerRenderedWithoutEnable =
1072 integratorHost.config.systemd.services ? "valley-restacker@"
1073 || integratorHost.config.systemd.targets ? valley-restackers
1074 || integratorHost.config.users.users ? valley-restacker;
1075
1076 # The host's own unit is one more local source, enabled, with the units
1077 # it lists, and the module's own sources stay beside it.
1078 telemetrySourceMisrendered =
1079 let
1080 sources = telemetryHost.config.services.valley.telemetry.catalog.sources;
1081 named = builtins.filter (s: s.name == "converge") sources;
1082 in
1083 lib.length named != 1
1084 || (lib.head named) != {
1085 name = "converge";
1086 description = "the service that converges this host";
1087 enabled = true;
1088 units = [ "converge.service" ];
1089 location = "local";
1090 }
1091 || !(lib.any (s: s.name == "worker") sources);
1092
1093 # Each onMain binding runs its bridge as a user of its own, outside the
1094 # git group, which only its unit is given. The unit sees the data
1095 # directory as an empty read-only file system with the one repository
1096 # bound into it read-only, writes nothing but its runtime directory,
1097 # trusts that repository alone, and has the host's keys out of reach. It
1098 # is given no grant: a path unit starts the bound unit while the bridge's
1099 # request exists. The bound unit's first command, run as root, consumes
1100 # the request and writes the unit's environment from the bridge's commit
1101 # file into a directory only root writes; the unit reads that file after
1102 # its own, and keeps the start limit the host gives it. A host with no
1103 # binding renders none of it, and telemetry catalogues the three units of
1104 # each binding.
1105 onMainRenderedWithoutBinding =
1106 lib.any (n: lib.hasPrefix "valley-on-main-" n) (
1107 lib.attrNames telemetryHost.config.systemd.services
1108 ++ lib.attrNames telemetryHost.config.systemd.paths
1109 ++ lib.attrNames telemetryHost.config.users.users
1110 )
1111 || !(lib.any (s: s.name == "on-main" && !s.enabled && s.units == [ ]) telemetryHost.config.services.valley.telemetry.catalog.sources);
1112
1113 onMainMisrendered =
1114 let
1115 cfg = onMainHost.config;
1116 unit = cfg.systemd.services.valley-on-main-deploy;
1117 service = unit.serviceConfig;
1118 account = cfg.users.users.valley-on-main-deploy;
1119 path = cfg.systemd.paths.valley-on-main-deploy;
1120 bound = cfg.systemd.units."converge.service".text;
1121 source = lib.filter (s: s.name == "on-main") cfg.services.valley.telemetry.catalog.sources;
1122 in
1123 service.User or null != "valley-on-main-deploy"
1124 || service.Group or null != "valley-on-main-deploy"
1125 || service.SupplementaryGroups or [ ] != [ "git" ]
1126 || account.group != "valley-on-main-deploy"
1127 || account.extraGroups != [ ]
1128 || !account.isSystemUser
1129 || !(lib.hasSuffix "/bin/onmain watch --repo /srv/git/open.git --commit-file /run/valley-on-main-deploy/commit --request-file /run/valley-on-main-deploy/request" service.ExecStart)
1130 || service.RuntimeDirectory or null != "valley-on-main-deploy"
1131 || service.ProtectSystem or null != "strict"
1132 || service ? ReadWritePaths
1133 || service.TemporaryFileSystem or null != "/srv/git:ro"
1134 || service.BindReadOnlyPaths or [ ] != [ "/srv/git/open.git" ]
1135 || service.InaccessiblePaths or [ ] != [ "-/run/agenix/valley-git-ssh-key" ]
1136 || service.Restart or "no" != "no"
1137 || unit.environment.GIT_CONFIG_COUNT or null != "2"
1138 || unit.environment.GIT_CONFIG_VALUE_0 or null != ""
1139 || unit.environment.GIT_CONFIG_VALUE_1 or null != "/srv/git/open.git"
1140 || !(builtins.elem "valley-init.service" unit.after)
1141 || !(builtins.elem "multi-user.target" unit.wantedBy)
1142 || cfg.security.polkit.enable
1143 || path.pathConfig != {
1144 PathExists = "/run/valley-on-main-deploy/request";
1145 Unit = "converge.service";
1146 }
1147 || !(builtins.elem "multi-user.target" path.wantedBy)
1148 || cfg.systemd.paths.valley-on-main-docs.pathConfig.Unit or null != "docs.service"
1149 || cfg.systemd.services.converge.serviceConfig.EnvironmentFile != [
1150 "/etc/converge.env"
1151 "-/run/valley-on-main/deploy.environment"
1152 ]
1153 || cfg.systemd.services.docs.serviceConfig.EnvironmentFile != [ "-/run/valley-on-main/docs.environment" ]
1154 || (
1155 let
1156 first = lib.head cfg.systemd.services.converge.serviceConfig.ExecStartPre;
1157 in
1158 !(lib.hasPrefix "+/nix/store/" first)
1159 || !(lib.hasSuffix "/bin/onmain environment --repo /srv/git/open.git --commit-file /run/valley-on-main-deploy/commit --request-file /run/valley-on-main-deploy/request --out /run/valley-on-main/deploy.environment" first)
1160 )
1161 || !(builtins.elem "d /run/valley-on-main 0755 root root - -" cfg.systemd.tmpfiles.rules)
1162 || lib.hasInfix "StartLimit" bound
1163 || cfg.systemd.services.docs.serviceConfig.ExecStart or null == null
1164 || source != [
1165 {
1166 name = "on-main";
1167 description = "the onMain bridges, their path units and the units they start";
1168 enabled = true;
1169 location = "local";
1170 units = [
1171 "valley-on-main-deploy.service"
1172 "valley-on-main-deploy.path"
1173 "converge.service"
1174 "valley-on-main-docs.service"
1175 "valley-on-main-docs.path"
1176 "docs.service"
1177 ];
1178 not_instrumented = [ "no producer records: lifecycle and output only" ];
1179 }
1180 ];
1181
1182 restackerMisrendered =
1183 let
1184 unit = restackerHost.config.systemd.services."valley-restacker@";
1185 service = unit.serviceConfig;
1186 account = restackerHost.config.users.users.valley-restacker;
1187 target = restackerHost.config.systemd.targets.valley-restackers;
1188 command = service.ExecStart;
1189 in
1190 service.User or null != "valley-restacker"
1191 || service.Group or null != "valley-restacker"
1192 || account.group != "valley-restacker"
1193 || account.extraGroups != [ ]
1194 || service.LoadCredential or [ ] != [ "key:/run/agenix/valley-restacker-key" ]
1195 || service.StateDirectory or null != "valley-restacker/%i"
1196 || service.StateDirectoryMode or null != "0700"
1197 || service.ProtectSystem or null != "strict"
1198 || service ? ReadWritePaths
1199 || !(lib.hasInfix " -i %d/key " unit.environment.GIT_SSH_COMMAND)
1200 || !(lib.hasInfix "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" unit.environment.GIT_SSH_COMMAND)
1201 || !(lib.hasInfix "-o UserKnownHostsFile=%S/valley-restacker/%i/known_hosts -o GlobalKnownHostsFile=/dev/null" unit.environment.GIT_SSH_COMMAND)
1202 || !(lib.hasInfix "/bin/valley-restacker run --repo git@localhost:%i.git --state %S/valley-restacker/%i --principal valley-restacker --interval 15s " command)
1203 || !(lib.hasInfix " --instance-repo git@localhost:sealed.git" command)
1204 || target.wants != [ "valley-restacker@guarded.service" ]
1205 || !(builtins.elem "multi-user.target" target.wantedBy)
1206 # A host that lists no projects serves every project it integrates.
1207 || defaultRestackerHost.config.systemd.targets.valley-restackers.wants != [
1208 "valley-restacker@guarded.service"
1209 "valley-restacker@released.service"
1210 "valley-restacker@sealed.service"
1211 ];
1212
1213 # The web publisher (nix/web-publisher.nix). Off, it renders nothing.
1214 # On, one pass is a oneshot on a five-minute timer whose first pass waits
1215 # five minutes after the timer starts, and which no switch starts or
1216 # restarts. It runs as the dynamic user valley-web-publish, which the
1217 # policy path's unit shares, in the git group, with an empty
1218 # safe.directory entry that resets the system's and the user's, then an
1219 # exact entry for each repository the host serves and no wildcard, the
1220 # repositories read-only, nothing writable but its state and cache, and
1221 # the mirror, backup and signing keys out of reach. It may connect to the
1222 # addresses it is allowed and to no other, and checks before each pass that
1223 # this filter is in force. Its Go lookups use the C library. Its memory is
1224 # capped with no swap. It reads the instance repository the controllers
1225 # read, names the host as the instance, and is given the receiver, the
1226 # destination, the display mapping and the bounds on its bundles and its
1227 # storage.
1228 webPublisherRenderedWithoutEnable =
1229 webPublisherOffHost.config.systemd.services ? valley-web-publish
1230 || webPublisherOffHost.config.systemd.services ? valley-web-publish-policy
1231 || webPublisherOffHost.config.systemd.timers ? valley-web-publish
1232 || lib.any (p: (p.name or "") == "valley-web-link") webPublisherOffHost.config.environment.systemPackages;
1233
1234 # The read links: the policy path's own unit, the same pass with
1235 # --policy-only in the same sandbox, as the same dynamic user, so the two
1236 # share their state and cache directories, and with the same
1237 # credentials; the
1238 # credential file read live by both through a static group, root's to
1239 # write, under the links lock tmpfiles makes beside it, which only root
1240 # can make or replace; the operator's wrapper, with the unit's
1241 # safe.directory entries, passing issue alone the flags for reading the
1242 # registry, and starting the policy pass after every issue or revoke,
1243 # and once more while a link is pending; and the backup holding the
1244 # file's directory and the publisher's durable state beside the data
1245 # directory.
1246 webPublisherLinksMisrendered =
1247 let
1248 units = webPublisherHost.config.systemd.services;
1249 pass = units.valley-web-publish.serviceConfig;
1250 policy = units.valley-web-publish-policy.serviceConfig or { };
1251 wrapper = lib.findFirst (
1252 p: (p.name or "") == "valley-web-link"
1253 ) null webPublisherHost.config.environment.systemPackages;
1254 in
1255 lib.filter (x: x != null) (lib.imap0 (i: c: if c then i else null) [
1256 (!(units ? valley-web-publish-policy))
1257 (lib.any (u: u.DynamicUser or null != true || u.User or null != "valley-web-publish" || u.Group or null != "valley-web-publish") [
1258 pass
1259 policy
1260 ])
1261 (policy.ExecStart or null != "${pass.ExecStart} --policy-only")
1262 (removeAttrs policy [ "ExecStart" ] != removeAttrs pass [ "ExecStart" ])
1263 (units.valley-web-publish-policy.environment != units.valley-web-publish.environment)
1264 (!(lib.hasSuffix " --links /var/lib/valley-web-links/links" pass.ExecStart))
1265 (!(lib.all (r: builtins.elem r webPublisherHost.config.systemd.tmpfiles.rules) [
1266 "d /var/lib/valley-web-links 0750 root valley-web-links -"
1267 "f /var/lib/valley-web-links/links 0640 root valley-web-links -"
1268 "f /var/lib/valley-web-links/lock 0640 root valley-web-links -"
1269 ]))
1270 (!(webPublisherHost.config.users.groups ? valley-web-links))
1271 (wrapper == null)
1272 (!(lib.hasInfix "valley-web-publish link \"$@\" --links /var/lib/valley-web-links/links \\\n --state /var/lib/valley-web-publish\n}" wrapper.text or ""))
1273 (!(lib.hasInfix "issue)\n link \"$@\" --instance-repo /srv/git/sealed.git" wrapper.text or ""))
1274 (!(lib.hasInfix "revoke) link \"$@\" ;;" wrapper.text or ""))
1275 (!(lib.all (e: lib.hasInfix e wrapper.text or "") [
1276 "ulimit -c 0\n"
1277 "export GIT_CONFIG_COUNT=5\n"
1278 "export GIT_CONFIG_VALUE_0=''\n"
1279 "export GIT_CONFIG_VALUE_4=/srv/git/sealed.git\n"
1280 "systemctl start valley-web-publish-policy.service"
1281 "deliver\nif ! link list --check > /dev/null 2>&1; then\n deliver\nfi\nif link list --check > /dev/null; then"
1282 ]))
1283 (backupWebPublisherHost.config.services.restic.backups.valley.paths or [ ] != [
1284 "/srv/git"
1285 "/var/lib/valley-web-links"
1286 "/var/lib/private/valley-web-publish"
1287 ])
1288 ]);
1289
1290 webPublisherMisrendered =
1291 let
1292 unit = webPublisherHost.config.systemd.services.valley-web-publish;
1293 service = unit.serviceConfig;
1294 env = unit.environment;
1295 timer = webPublisherHost.config.systemd.timers.valley-web-publish;
1296 repos = [
1297 "/srv/git/guarded.git"
1298 "/srv/git/open.git"
1299 "/srv/git/released.git"
1300 "/srv/git/sealed.git"
1301 ];
1302 entries = lib.genList (i: {
1303 key = env."GIT_CONFIG_KEY_${toString i}" or null;
1304 value = env."GIT_CONFIG_VALUE_${toString i}" or null;
1305 }) (lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames env)));
1306 command = service.ExecStart;
1307 in
1308 service.Type or null != "oneshot"
1309 || service.DynamicUser or null != true
1310 || service.User or null != "valley-web-publish"
1311 || service.Group or null != "valley-web-publish"
1312 || service.SupplementaryGroups or [ ] != [
1313 "git"
1314 "valley-web-links"
1315 ]
1316 || env.GIT_CONFIG_COUNT or null != toString (lib.length repos + 1)
1317 || entries != map (r: {
1318 key = "safe.directory";
1319 value = r;
1320 }) ([ "" ] ++ repos)
1321 || lib.any (e: lib.hasInfix "*" e.value) entries
1322 || service.ProtectSystem or null != "strict"
1323 || service ? ReadWritePaths
1324 || service.ReadOnlyPaths or [ ] != map (r: "-${r}") repos
1325 || service.StateDirectory or null != "valley-web-publish"
1326 || service.CacheDirectory or null != "valley-web-publish"
1327 || env.XDG_CACHE_HOME or null != "/var/cache/valley-web-publish"
1328 || !(lib.all (p: builtins.elem p service.InaccessiblePaths) [
1329 "-/srv/git/.ssh"
1330 "-/run/agenix/valley-integrator-key"
1331 "-/run/agenix/valley-git-ssh-key"
1332 "-/var/lib/valley-integrator"
1333 ])
1334 || !(lib.hasInfix "/bin/valley-web-publish --instance-repo /srv/git/sealed.git --instance valley-host --destination example.org --host /nix/store/" command)
1335 || !(lib.hasInfix "-valley-config.json --receiver https://example.org --receiver-token %d/receiver-token --principals /nix/store/" command)
1336 || service.LoadCredential or [ ] != [ "receiver-token:/run/keys/valley-web-receiver-token" ]
1337 || !(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)
1338 || !(lib.hasSuffix "/bin/valley-web-publish-egress-check 198.51.100.1 9" (service.ExecStartPre or ""))
1339 || env.GODEBUG or null != "netdns=cgo"
1340 || service.IPAddressDeny or null != "any"
1341 || service.IPAddressAllow or null != [
1342 "192.0.2.10"
1343 "2001:db8::10"
1344 ]
1345 || service.RestrictAddressFamilies or null != [
1346 "AF_INET"
1347 "AF_INET6"
1348 "AF_UNIX"
1349 ]
1350 || service.MemoryMax or null != "1G"
1351 || service.MemorySwapMax or null != "0"
1352 || unit.restartIfChanged != false
1353 || unit.wantedBy != [ ]
1354 || timer.timerConfig.OnActiveSec or null != "5min"
1355 || timer.timerConfig.OnUnitInactiveSec or null != "5min"
1356 || !(builtins.elem "timers.target" timer.wantedBy);
1357
1358 # The web receiver module (nix/web-receiver.nix). When disabled, it
1359 # renders no units or users. When enabled, it renders separate systemd
1360 # units for valley-web-receive and valley-web; both start at boot, restart
1361 # on failure, and run independently. The receiver runs as
1362 # valley-web-receive in group valley-web, owns the mode-0750 state
1363 # directory, and takes the instance, the destination, the pinned verifiers
1364 # from the Nix store, the bearer token as a systemd credential from outside
1365 # the store, and the body and storage caps. valley-web runs as valley-web
1366 # in the same group, orders after the receiver, mounts the state directory
1367 # read-only with no persistent writable paths, and takes the state
1368 # directory and its listener address. Each unit has its own memory cap and
1369 # disables swap.
1370 webReceiverRenderedWithoutEnable =
1371 webReceiverOffHost.config.systemd.services ? valley-web-receive
1372 || webReceiverOffHost.config.systemd.services ? valley-web
1373 || webReceiverOffHost.config.users.users ? valley-web-receive;
1374
1375 webReceiverMisrendered =
1376 let
1377 cfg = webReceiverHost.config;
1378 receive = cfg.systemd.services.valley-web-receive;
1379 web = cfg.systemd.services.valley-web;
1380 confined =
1381 unit:
1382 unit.serviceConfig.ProtectSystem or null == "strict"
1383 && unit.serviceConfig.NoNewPrivileges or null == true
1384 && unit.serviceConfig.CapabilityBoundingSet or null == ""
1385 && unit.serviceConfig.MemorySwapMax or null == "0"
1386 && unit.serviceConfig.Restart or null == "on-failure"
1387 && builtins.elem "multi-user.target" unit.wantedBy
1388 && unit.requires == [ ]
1389 && unit.bindsTo == [ ];
1390 in
1391 !(confined receive && confined web)
1392 || cfg.users.users.valley-web-receive.group != "valley-web"
1393 || cfg.users.users.valley-web.group != "valley-web"
1394 || receive.serviceConfig.User or null != "valley-web-receive"
1395 || receive.serviceConfig.Group or null != "valley-web"
1396 || receive.serviceConfig.StateDirectory or null != "valley-web"
1397 || receive.serviceConfig.StateDirectoryMode or null != "0750"
1398 || receive.serviceConfig.LoadCredential or [ ] != [ "token:/run/keys/valley-web-receiver-token" ]
1399 || receive.serviceConfig.MemoryMax or null != "2G"
1400 || !(lib.hasInfix "/bin/valley-web-receive --state /var/lib/valley-web/store --listen 192.0.2.10:8081 --instance valley-host --destination example.org --verifiers /nix/store/" receive.serviceConfig.ExecStart)
1401 || !(lib.hasSuffix "-valley-web-verifiers --token-file %d/token --max-body 1G --max-upload 2G --max-storage 8G" receive.serviceConfig.ExecStart)
1402 || web.serviceConfig.User or null != "valley-web"
1403 || web.serviceConfig.Group or null != "valley-web"
1404 || web.serviceConfig ? StateDirectory
1405 || web.serviceConfig ? ReadWritePaths
1406 || web.serviceConfig ? LoadCredential
1407 || web.serviceConfig.ReadOnlyPaths or [ ] != [ "-/var/lib/valley-web" ]
1408 || web.serviceConfig.MemoryMax or null != "1G"
1409 || !(builtins.elem "valley-web-receive.service" web.after)
1410 || !(lib.hasSuffix "/bin/valley-web --state /var/lib/valley-web/store --listen 127.0.0.1:8080" web.serviceConfig.ExecStart)
1411 || receive.serviceConfig ? InaccessiblePaths
1412 || lib.any (lib.hasInfix "/var/lib/valley-web") cfg.systemd.tmpfiles.rules;
1413
1414 # With an origin, valley-web signs readers in: it takes --origin, and may
1415 # write browser/ in the state directory alone, which tmpfiles makes as
1416 # its own, mode 0700, under the state directory made as the receiver's.
1417 # Its unit takes no core dump. The receiver's unit cannot reach browser/.
1418 webReaderMisrendered =
1419 let
1420 cfg = webReaderHost.config;
1421 receive = cfg.systemd.services.valley-web-receive.serviceConfig;
1422 web = cfg.systemd.services.valley-web.serviceConfig;
1423 in
1424 !(lib.hasSuffix "/bin/valley-web --state /var/lib/valley-web/store --listen 127.0.0.1:8080 --origin https://example.org" web.ExecStart)
1425 || web.ReadOnlyPaths or [ ] != [ "-/var/lib/valley-web" ]
1426 || web.ReadWritePaths or [ ] != [ "/var/lib/valley-web/browser" ]
1427 || web.LimitCORE or null != 0
1428 || receive.InaccessiblePaths or [ ] != [ "-/var/lib/valley-web/browser" ]
1429 || receive.StateDirectory or null != "valley-web"
1430 || !(lib.all (r: builtins.elem r cfg.systemd.tmpfiles.rules) [
1431 "d /var/lib/valley-web 0750 valley-web-receive valley-web -"
1432 "d /var/lib/valley-web/browser 0700 valley-web valley-web -"
1433 ]);
1434in
1435{
1436 module-eval =
1437 if failedAssertions != [ ] then
1438 throw "valley module-eval: failed assertions: ${
1439 lib.concatMapStringsSep "; " (a: a.message) failedAssertions
1440 }"
1441 else if resticRenderedWithoutDeclaration then
1442 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
1443 else if busRenderedWithoutEnable then
1444 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
1445 else if
1446 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
1447 then
1448 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
1449 else if unrefusedHosts != [ ] then
1450 throw "valley module-eval: ${lib.concatMapStringsSep "; " (r: "a host was not refused although ${r.why}") unrefusedHosts}"
1451 else if protectionRenderedWithoutDeclaration then
1452 throw "valley module-eval: principal machinery rendered for a declaration with no protection block and no tagged key"
1453 else if policyMissingWithoutDeclaration then
1454 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"
1455 else if protectedHost.config.services.openssh.settings ? PermitUserEnvironment then
1456 throw "valley module-eval: sshd must pass no key's environment on: the git user's shell derives the principal from the authenticated key"
1457 else if
1458 !(lib.hasInfix "valley-git-shell" protectedHost.config.users.users.git.shell)
1459 then
1460 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"
1461 else if integratorRenderedWithoutEnable then
1462 throw "valley module-eval: integrator machinery rendered for a protected declaration that never enabled the service"
1463 else if !(integratorHost.config.systemd.services ? "valley-integrator@") then
1464 throw "valley module-eval: the integrator is enabled and no controller unit was rendered"
1465 else if
1466 controllers != [
1467 "valley-integrator@guarded.service"
1468 "valley-integrator@released.service"
1469 "valley-integrator@sealed.service"
1470 ]
1471 then
1472 throw "valley module-eval: a controller runs for each protected project and no other, not ${lib.concatStringsSep ", " controllers}"
1473 else if
1474 publishers != [
1475 "valley-publish@guarded.path"
1476 "valley-publish@released.path"
1477 "valley-publish@sealed.path"
1478 ]
1479 then
1480 throw "valley module-eval: each controller's landings are published by a path unit of its own, not ${lib.concatStringsSep ", " publishers}"
1481 else if integratorHost.config.systemd.services."valley-publish@".serviceConfig.User != "git" then
1482 throw "valley module-eval: a landing is published as the git user, which holds the mirror credentials"
1483 else if
1484 let
1485 drain = integratorHost.config.systemd.services."valley-publish@".serviceConfig;
1486 in
1487 drain.Restart or null != "on-failure"
1488 || drain.RestartSec or null != "30s"
1489 || drain.RestartSteps or null != 5
1490 || drain.RestartMaxDelaySec or null != "15min"
1491 then
1492 throw "valley module-eval: a failed drain must be run again 30 seconds later, each later retry waiting longer, up to 15 minutes from the fifth, so a queued move reaches its mirror once the mirror is back"
1493 else if integratorUser == integratorHost.config.services.valley.user then
1494 throw "valley module-eval: the integrator must not run as the git user — it has its own (bd-500adf7)"
1495 else if !(integratorHost.config.users.users ? ${integratorUser}) then
1496 throw "valley module-eval: the integrator runs as ${integratorUser}, which the module never declares"
1497 else if integratorHost.config.users.users.${integratorUser}.group != "git" then
1498 throw "valley module-eval: the integrator reaches the repositories through the git group, and holds no other grant"
1499 else if integratorSafeDirectory then
1500 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"
1501 else if integratorFloor then
1502 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"
1503 else if integratorScratch then
1504 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"
1505 else if integratorWakeMisrendered then
1506 throw "valley module-eval: each controller watches its own wake directory under /run/valley-integrator-wake, owned by the integrator and the group of the git user and the integrator; its sandbox writes that one, the instance project's controller alone writes the floor readers' too, and every served project carries the push hook that marks it"
1507 else if identityRenderedWithoutEnable then
1508 throw "valley module-eval: registry-compilation machinery rendered for a host that never enabled it — nothing may change until a consumer opts in"
1509 else if identityCompiler then
1510 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"
1511 else if identityStarts then
1512 throw "valley module-eval: the compiler must start when the registry's ref moves in the instance repository, watching its loose file alone with no trigger or start limit, and at 00:00 UTC within a second, with no randomized delay and no catch-up start, beside the recovery timer five minutes after each compilation, and it must start only while valley-init is active after success, which starts it and the controllers, without ever starting valley-init"
1513 else if identityIntegrator then
1514 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"
1515 else if signersRenderedWithoutIntegrator then
1516 throw "valley module-eval: a signers publication rendered for a host whose integrator is off — there is no transfer statement to verify"
1517 else if signersUnpublished then
1518 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 a file it publishes from changes, starting only while valley-init is active after success, which starts it, without ever starting valley-init"
1519 else if controllerApprovalInputsMisrendered then
1520 throw "valley module-eval: each controller must be handed the approval signers files the compiler writes, or none on a host that compiles no registry, and its project's push policy through its environment file"
1521 else if addedMirrorUnqueued then
1522 throw "valley module-eval: a mirror added to a project that already has one must change valley-init's unit, so activation runs init and queues the new mirror's first push"
1523 else if retentionMisrendered then
1524 throw "valley module-eval: a project that retains its change records must hand the hook retainChangeRecords = true, and one that does not must leave the key out"
1525 else if signerProjectsMisrendered then
1526 throw "valley module-eval: a controller is given a signer projects file exactly when the host restricts a signer to projects"
1527 else if identityKeepsDeclaredKeys then
1528 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"
1529 else if workerRenderedWithoutEnable then
1530 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"
1531 else if buildSliceMisrendered then
1532 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"
1533 else if workerMisrendered then
1534 throw "valley module-eval: the check worker must run as its own account outside the git group, free to run on any CPU, building as many checks at once as worker.buildSlots says (1 unset), keeping their outputs for worker.keepOutputs days (7 unset, none when null), each with nix's max-jobs and cores set from worker.maxJobs and worker.cores (1 and 4 unset), in a slice that holds it and the nix daemon to 4 CPUs and 8 GiB with no swap and no device policy, leaving the daemon's OOM policy at continue, 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"
1535 else if workerDefaultsMisrendered then
1536 throw "valley module-eval: a check worker whose projects the host leaves unwritten must build for every project the controllers serve, one the host narrows must build for those alone, and the signers publication must carry the controllers' signer projects file"
1537 else if restackerRenderedWithoutEnable then
1538 throw "valley module-eval: restacker machinery rendered for a host that never enabled it"
1539 else if restackerMisrendered then
1540 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 persistent 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"
1541 else if onMainRenderedWithoutBinding then
1542 throw "valley module-eval: onMain machinery rendered for a host that binds no unit: no bridge, path unit or user may appear until a host binds one, and the on-main telemetry source is catalogued disabled with no unit"
1543 else if onMainMisrendered then
1544 throw "valley module-eval: each onMain bridge must run onmain for its project's repository, commit file and request file as a user of its own outside the git group, the git group given to its unit alone, seeing the data directory as an empty read-only file system with that one repository bound in read-only, writing only its runtime directory, trusting that repository alone, with the host's keys out of reach, no restart and no polkit grant; a path unit per binding must start the bound unit while the bridge's request exists; each bound unit's first command must consume the request and write its environment as root from its bridge's commit file into a directory only root writes, and the unit must read that file after its own and keep the host's start limit; and telemetry must catalogue each bridge, its path unit and its unit as the on-main source"
1545 else if telemetrySourceMisrendered then
1546 throw "valley module-eval: a unit the host lists in telemetry.localSources must be catalogued as an enabled local source with exactly those units, beside the module's own"
1547 else if webPublisherRenderedWithoutEnable then
1548 throw "valley module-eval: web publisher machinery rendered for a host that imports its module and never enabled it"
1549 else if webPublisherMisrendered then
1550 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, its token as a credential, the destination, the display mapping, the bounds on its bundles and storage, and the identity registry's directory"
1551 else if webPublisherLinksMisrendered != [ ] then
1552 throw "${builtins.toJSON webPublisherLinksMisrendered} valley module-eval: the web publisher's read links must be read live by each pass through the valley-web-links group from a file only root writes, under a links lock tmpfiles makes beside it, with a policy-only unit in the same sandbox that valley-web-link starts after every issue or revoke and once more while a link is pending, the wrapper trusting the unit's repositories and dumping no core, and the backup must hold the credential file's directory and the publisher's state"
1553 else if webReceiverRenderedWithoutEnable then
1554 throw "valley module-eval: web receiver machinery rendered for a host that imports its module and never enabled it"
1555 else if webReceiverMisrendered then
1556 throw "valley module-eval: the web receiver and valley-web must be two confined units started at boot, restarted on failure and requiring nothing of each other, as two users of the valley-web group, the receiver owning the state directory at 0750 with its token as a credential, its pinned verifiers, its caps and its own memory cap, and valley-web after it with the state directory read-only, no credential and a memory cap of its own"
1557 else if webReaderMisrendered then
1558 throw "valley module-eval: with an origin, valley-web must take --origin, take no core dump, and write the state directory's browser/ alone, which tmpfiles makes as its own at 0700 under the receiver's state directory at 0750, and the receiver's unit must not reach browser/"
1559 else
1560 pkgs.runCommand "valley-module-eval" {
1561 initScript = host.config.systemd.services.valley-init.script;
1562 sshdConfig = host.config.services.openssh.extraConfig;
1563 resticService = host.config.systemd.units."restic-backups-valley.service".text;
1564 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
1565 protectedInit = protectedHost.config.systemd.services.valley-init.script;
1566 protectedKeys = lib.concatStringsSep "\n" protectedKeyLines;
1567 protectedShell = protectedHost.config.users.users.git.shell;
1568 integratorUnit = integratorHost.config.systemd.units."valley-integrator@.service".text;
1569 integratorInit = integratorHost.config.systemd.services.valley-init.script;
1570 integratorGuardedEnv = lib.removePrefix "-" (
1571 lib.replaceStrings [ "%i" ] [ "guarded" ]
1572 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.EnvironmentFile
1573 );
1574 publishUnit = host.config.systemd.units."valley-publish@.service".text;
1575 identityInit = identityHost.config.systemd.services.valley-init.script;
1576 defaultWorkerController =
1577 defaultWorkerHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
1578 narrowedWorkerController =
1579 narrowedWorkerHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
1580 passAsFile = [
1581 "initScript"
1582 "sshdConfig"
1583 "resticService"
1584 "resticTimer"
1585 "protectedInit"
1586 "protectedKeys"
1587 "integratorUnit"
1588 "integratorInit"
1589 "publishUnit"
1590 "identityInit"
1591 ];
1592 } (builtins.readFile ./module-eval.sh);
1593}