gunk-dev/the-valley

host-module.nix

sourcec0fb7f7caad5main's published tip history
65.3 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 unservedRestackerHost
56 keylessRestackerHost
57 ;
58
59 # The web publisher's module (nix/web-publisher.nix) beside the host
60 # module, over integratorHost: its instance repository is the one the
61 # controllers read the floor from. The host also has a backup key the
62 # publisher must not read. The publisher is a stand-in, as the host's
63 # programs are. webPublisherOffHost imports the module and leaves it off.
64 webPublisherStub = pkgs.writeShellScriptBin "valley-web-publish" ''
65 echo "valley-web-publish: a stand-in the module checks render hosts over, which runs nothing" >&2
66 exit 1
67 '';
68 webPublisherOffHost = stubbedHosts.integratorHost.extendModules {
69 modules = [
70 self.nixosModules.web-publisher
71 { services.valley.webPublisher.package = webPublisherStub; }
72 ];
73 };
74 webPublisherHost = webPublisherOffHost.extendModules {
75 modules = [
76 {
77 networking.hostName = "valley-host";
78 services.valley.backup.sshKeyFile = "/run/agenix/valley-git-ssh-key";
79 services.valley.webPublisher = {
80 enable = true;
81 destination = "example.org";
82 receiver = "https://example.org";
83 receiverTokenFile = "/run/keys/valley-web-receiver-token";
84 allowedAddresses = [
85 "192.0.2.10"
86 "2001:db8::10"
87 ];
88 principals = {
89 operator = "operator";
90 alice = "agent";
91 };
92 };
93 }
94 ];
95 };
96 # The publisher on a host whose declaration asks for a backup.
97 backupWebPublisherHost = webPublisherHost.extendModules {
98 modules = [
99 {
100 services.valley.config = lib.mkForce (
101 pkgs.runCommand "protected-with-backup.cue" { } ''
102 cat ${../../examples/hosts/protected.cue} > $out
103 printf '\nbackup: target: "restic-sftp"\n' >> $out
104 ''
105 );
106 services.valley.backup = {
107 repositoryFile = "/run/agenix/valley-restic-repo";
108 passwordFile = "/run/agenix/valley-restic-password";
109 knownHostsFile = "/var/lib/valley-backup/known_hosts";
110 };
111 }
112 ];
113 };
114 # The publisher reading the registry at a ref the instance repository's
115 # protection does not cover.
116 unprotectedRegistryWebPublisherHost = webPublisherHost.extendModules {
117 modules = [ { services.valley.identity.ref = "refs/heads/registry"; } ];
118 };
119 # The publisher reading the registry at a short ref name, which git would
120 # resolve by trying other names in turn.
121 shortRegistryRefWebPublisherHost = webPublisherHost.extendModules {
122 modules = [ { services.valley.identity.ref = "registry"; } ];
123 };
124 # The publisher with no instance repository to discover the projects and
125 # the signers through.
126 noInstanceWebPublisherHost = webPublisherHost.extendModules {
127 modules = [
128 {
129 services.valley.integrator = {
130 instanceProject = lib.mkForce null;
131 instancePolicy = "/var/lib/valley-instance/policy/instance";
132 };
133 }
134 ];
135 };
136
137 # The web receiver module (nix/web-receiver.nix) on a standalone edge
138 # host, evaluated with stand-in binaries. webReceiverOffHost imports the
139 # module while leaving it disabled.
140 edgeStub =
141 name:
142 pkgs.writeShellScriptBin name ''
143 echo "${name}: a stand-in the module checks render hosts over, which runs nothing" >&2
144 exit 1
145 '';
146 webReceiverOffHost = lib.nixosSystem {
147 inherit pkgs;
148 modules = [
149 self.nixosModules.web-receiver
150 {
151 fileSystems."/" = {
152 device = "/dev/disk/by-label/nixos";
153 fsType = "ext4";
154 };
155 boot.loader.grub.enable = false;
156 system.stateVersion = "25.11";
157 services.valley.webReceiver = {
158 receiverPackage = edgeStub "valley-web-receive";
159 webPackage = edgeStub "valley-web";
160 };
161 }
162 ];
163 };
164 webReceiverHost = webReceiverOffHost.extendModules {
165 modules = [
166 {
167 services.valley.webReceiver = {
168 enable = true;
169 instance = "valley-host";
170 destination = "example.org";
171 verifiers = [ "valley-host/web-export+1a2b3c4d+AQ" ];
172 tokenFile = "/run/keys/valley-web-receiver-token";
173 listen = "192.0.2.10:8081";
174 webListen = "127.0.0.1:8080";
175 };
176 }
177 ];
178 };
179 # The receiver and valley-web with readers signing in at an origin.
180 webReaderHost = webReceiverHost.extendModules {
181 modules = [ { services.valley.webReceiver.origin = "https://example.org"; } ];
182 };
183 # The receiver with its token in the Nix store, and with no verifier.
184 storeTokenWebReceiverHost = webReceiverHost.extendModules {
185 modules = [
186 { services.valley.webReceiver.tokenFile = lib.mkForce "${pkgs.writeText "token" "x"}"; }
187 ];
188 };
189 noVerifierWebReceiverHost = webReceiverHost.extendModules {
190 modules = [ { services.valley.webReceiver.verifiers = lib.mkForce [ ]; } ];
191 };
192 # The publisher allowed to connect to no address.
193 noAddressWebPublisherHost = webPublisherHost.extendModules {
194 modules = [ { services.valley.webPublisher.allowedAddresses = lib.mkForce [ ]; } ];
195 };
196 # The publisher allowed the canary its unit's check must be denied.
197 canaryWebPublisherHost = webPublisherHost.extendModules {
198 modules = [ { services.valley.webPublisher.allowedAddresses = [ "198.51.100.0/24" ]; } ];
199 };
200 # The publisher with its token in the Nix store.
201 storeTokenWebPublisherHost = webPublisherHost.extendModules {
202 modules = [
203 { services.valley.webPublisher.receiverTokenFile = lib.mkForce "${pkgs.writeText "token" "x"}"; }
204 ];
205 };
206
207 failedAssertions = builtins.filter (a: !a.assertion) (
208 host.config.assertions
209 ++ noBackupHost.config.assertions
210 ++ busHost.config.assertions
211 ++ mirrorHost.config.assertions
212 ++ protectedHost.config.assertions
213 ++ integratorHost.config.assertions
214 ++ integratorSelfHost.config.assertions
215 ++ restrictedHost.config.assertions
216 ++ identityHost.config.assertions
217 ++ workerHost.config.assertions
218 ++ capacityWorkerHost.config.assertions
219 ++ defaultWorkerHost.config.assertions
220 ++ narrowedWorkerHost.config.assertions
221 ++ restackerHost.config.assertions
222 ++ buildSliceHost.config.assertions
223 ++ webPublisherHost.config.assertions
224 ++ webPublisherOffHost.config.assertions
225 ++ webReceiverHost.config.assertions
226 ++ webReaderHost.config.assertions
227 ++ webReceiverOffHost.config.assertions
228 );
229
230 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
231
232 # The hosts the module must refuse, each with the words its refusal must
233 # say. An assertion that stopped firing would leave the push policy
234 # quietly wrong, so each is held to naming what is wrong.
235 refusedHosts = [
236 {
237 host = unprotectedInstanceHost;
238 says = "whose refs/heads/main is not protected";
239 why = "an instance repository without protection would let any key that can push rewrite the floor and the registry";
240 }
241 {
242 host = acceptEnvHost;
243 says = "AcceptEnv";
244 why = "sshd accepting the principal variable from the client would let any key name any principal";
245 }
246 {
247 host = matchAcceptEnvHost;
248 says = "GIT_CONFIG_*";
249 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";
250 }
251 {
252 host = wildcardAcceptEnvHost;
253 says = "G?T_*";
254 why = "a wildcard that admits GIT_ variables admits them however it is spelled";
255 }
256 {
257 host = quotedAcceptEnvHost;
258 says = "holds a quote or a backslash";
259 why = "a quoted name is one sshd unquotes and admits, so a check that read it differently would pass it";
260 }
261 {
262 host = tabAcceptEnvHost;
263 says = "VALLEY_PRINCIPAL from the client";
264 why = "a name after a tab is a name sshd admits";
265 }
266 {
267 host = setEnvHost;
268 says = "SetEnv";
269 why = "sshd setting the principal itself would make every key push as it";
270 }
271 {
272 host = permitUserEnvironmentHost;
273 says = "PermitUserEnvironment";
274 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";
275 }
276 {
277 host = spacedSignerProjectsHost;
278 says = "services.valley.integrator.signerProjects holds";
279 why = "a project with a space in it would be read back as two projects the declaration never listed";
280 }
281 {
282 host = unicodeSpacedSignerProjectsHost;
283 says = "services.valley.integrator.signerProjects holds";
284 why = "a project holding a no-break space would be read back by the integrator as two projects, or refused at start";
285 }
286 {
287 host = noSliceWorkerHost;
288 says = "services.valley.worker.enable needs services.valley.buildSlice.enable";
289 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";
290 }
291 {
292 host = unrestrictedWorkerHost;
293 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
294 why = "a worker whose signer no project list restricts would have its evidence counted in every project by every controller that holds its key";
295 }
296 {
297 host = widerWorkerHost;
298 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
299 why = "a worker trusted in a project it does not build would be trusted where it does no work";
300 }
301 {
302 host = mismatchedWorkerHost;
303 says = "must restrict worker.valley.invalid/attestations, the worker's signer, to exactly the worker's projects";
304 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";
305 }
306 {
307 host = integratorNamedWorkerHost;
308 says = "services.valley.worker.signerName must differ from integrator";
309 why = "a worker signing under the controllers' name would make every controller refuse to start";
310 }
311 {
312 host = unservedRestackerHost;
313 says = "services.valley.restacker.projects must name at least one project, and only projects this host serves, and it names nowhere";
314 why = "a controller for a project the host does not serve would fail every pass";
315 }
316 {
317 host = keylessRestackerHost;
318 says = "services.valley.restacker.sshKeyFile must be set";
319 why = "a restacker with no key cannot reach the repositories it serves, except as a user that could write them on disk";
320 }
321 {
322 host = conflictingKeysHost;
323 says = "more than one principal tag";
324 why = "a key declared under two tags would push as whichever entry sshd reads first";
325 }
326 {
327 host = unprotectedRegistryWebPublisherHost;
328 says = "whose refs/heads/registry is not protected";
329 why = "a publisher reading the registry at an unprotected ref would let any key that can push there grant anyone read";
330 }
331 {
332 host = shortRegistryRefWebPublisherHost;
333 says = "services.valley.identity.ref is registry, which is not a full ref name";
334 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";
335 }
336 {
337 host = storeTokenWebPublisherHost;
338 says = "services.valley.webPublisher.receiverTokenFile is in the Nix store";
339 why = "the publisher's receiver token is in the Nix store";
340 }
341 {
342 host = noAddressWebPublisherHost;
343 says = "services.valley.webPublisher.allowedAddresses is empty: list the receiver's IP addresses";
344 why = "a publisher with no allowed address would either reach nothing or, allowed everything, reach any host";
345 }
346 {
347 host = canaryWebPublisherHost;
348 says = "services.valley.webPublisher.allowedAddresses covers 198.51.100.1";
349 why = "the check before each pass could not prove the filter in force if the filter allowed its canary";
350 }
351 {
352 host = storeTokenWebReceiverHost;
353 says = "services.valley.webReceiver.tokenFile is in the Nix store";
354 why = "the receiver's token is in the Nix store";
355 }
356 {
357 host = noVerifierWebReceiverHost;
358 says = "services.valley.webReceiver.verifiers names no verifier line";
359 why = "the receiver pins no verifier";
360 }
361 {
362 host = noInstanceWebPublisherHost;
363 says = "services.valley.webPublisher needs services.valley.integrator.instanceProject";
364 why = "a publisher with no instance repository has no publication to discover the projects and their signers through";
365 }
366 ];
367
368 unrefusedHosts = builtins.filter (
369 r: !(lib.any (a: !a.assertion && lib.hasInfix r.says a.message) r.host.config.assertions)
370 ) refusedHosts;
371
372 protectedKeyLines = protectedHost.config.users.users.git.openssh.authorizedKeys.keys;
373
374 resticRenderedWithoutDeclaration =
375 noBackupHost.config.systemd.services ? "restic-backups-valley"
376 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
377
378 # The bus defaults off; a host that never asked for one must
379 # render zero bus machinery.
380 busRenderedWithoutEnable =
381 noBackupHost.config.systemd.services ? valley-bus
382 || noBackupHost.config.systemd.services ? valley-bus-init;
383
384 # A declaration with no protection block and no tagged key still gets
385 # the push policy on every project — the policy is the host's, and a
386 # protection block only adds protected refs to it — and nothing of the
387 # principal machinery: no tag on a key, no sshd change.
388 protectionRenderedWithoutDeclaration =
389 noBackupHost.config.services.openssh.settings ? PermitUserEnvironment
390 || lib.any (lib.hasInfix "environment=") (
391 noBackupHost.config.users.users.git.openssh.authorizedKeys.keys
392 );
393
394 policyMissingWithoutDeclaration =
395 !(lib.hasInfix "valley-protect-the-valley" noBackupHost.config.systemd.services.valley-init.script);
396
397 # The integrator's units. What a controller *does* is not checked here
398 # and no VM is booted: that is integrator-e2e's job (the real binaries
399 # over real repositories) and, past it, live exercise on a host. These
400 # assertions cover the wiring — that a controller is rendered for what
401 # the declaration protects and for nothing else, under an identity that
402 # is not the git user's, pointed at the key and the signers the consumer
403 # supplied.
404 #
405 # There is a seam between those two halves that neither reaches, and in a
406 # single day it produced five deployment failures. Every assertion below is
407 # an eval of the unit's text; integrator-e2e runs the binaries with no unit
408 # around them at all. What sits between is the unit's sandbox and identity
409 # meeting the filesystem the binaries actually use at runtime:
410 #
411 # - git refusing a repository the service does not own (bd-500adf7)
412 # - a push authenticating as the operator rather than as the run
413 # (bd-353c59d)
414 # - no writable temporary directory, so no worktree could be made
415 # - the worktree metadata root, created by whichever service reached it
416 # first and then unchmodable by the other, which failed valley-init and
417 # took every valley unit down with it
418 # - the state directory not writable under ProtectSystem=strict unless
419 # the unit names it, which the previous fix had made the scratch root
420 #
421 # Each was found by a host, minutes of a live service after a deploy that
422 # every check here passed. They compose: the third's fix set up the fourth,
423 # and the fourth's fix set up the fifth. That is the argument. A seam whose
424 # failures feed each other is not one to pin an assertion at a time, and
425 # each assertion here that marks a piece of it — the git ownership
426 # exception, TMPDIR, the worktrees root, ReadWritePaths — marks a place a
427 # smoke boot would have spoken first.
428 #
429 # A nixosTest that boots one host, starts the units and reconciles one
430 # change end to end is the next check this module needs. Nothing else
431 # closes the seam, and five incidents is enough evidence of what it costs
432 # to leave open. Not built here.
433 #
434 # Protection and integration are separable declarations: protectedHost
435 # declares the same protected projects with the service off, and must
436 # evaluate to no controller at all.
437 integratorRenderedWithoutEnable =
438 protectedHost.config.systemd.services ? "valley-integrator@"
439 || protectedHost.config.systemd.targets ? valley-integrators
440 || lib.hasInfix "sharedRepository" protectedHost.config.systemd.services.valley-init.script;
441
442 # One target pulls in each controller, and another the path unit that
443 # publishes each project's queued moves, landings included.
444 integratorWants = integratorHost.config.systemd.targets.valley-integrators.wants;
445 controllers = lib.filter (lib.hasPrefix "valley-integrator@") integratorWants;
446 publishers = integratorHost.config.systemd.targets.valley-publish.wants;
447
448 integratorUser = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.User;
449
450 # The controller is not the repositories' owner, which is the whole point
451 # of running it as itself — so git needs an ownership exception, and
452 # where that exception lives is load-bearing. GIT_CONFIG_* is command
453 # scope, the only scope besides system and global that safe.directory is
454 # read from, and the unit's environment is inherited by every git the
455 # controller drives. It names one repository: a wildcard here would hand
456 # a compromised controller every repository on the host.
457 integratorGitEnv = integratorHost.config.systemd.services."valley-integrator@".environment;
458
459 # The count is what git reads; an entry past it is an entry git ignores,
460 # silently. So it is checked against the entries actually rendered rather
461 # than against a number written here, which would have to be edited every
462 # time a grant is added and would go on passing if it were not.
463 integratorSafeDirectory =
464 integratorGitEnv.GIT_CONFIG_KEY_0 or null != "safe.directory"
465 || integratorGitEnv.GIT_CONFIG_VALUE_0 or null != "/srv/git/%i.git"
466 || integratorGitEnv.GIT_CONFIG_COUNT or null
467 != toString (
468 lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames integratorGitEnv))
469 );
470
471 integratorService = integratorHost.config.systemd.services."valley-integrator@".serviceConfig;
472
473 # Scratch goes under the state directory, because the sandbox leaves no
474 # writable temporary directory and a verdict needs a checkout on disk. Two
475 # halves, and each was a live failure on its own. TMPDIR naming a path
476 # outside the state directory is the first; the state directory not being
477 # named in ReadWritePaths is the second, which failed even though
478 # ProtectSystem=strict is documented to leave a declared state directory
479 # writable. Everything the unit may write is enumerated, so what a reader
480 # of the unit sees is the whole of it.
481 # The floor is read from the instance repository's integrated tip
482 # (dcr-f41f718, dcr-b87f6e8), so a controller is told which repository
483 # carries it and reads it there. Three things have to be true of that, and
484 # each was a way for it to be silently wrong.
485 #
486 # The controller has to be told at all — the failure this replaced was a
487 # binary looking for a materialized directory nothing populated.
488 #
489 # It has to work when the repository carrying the floor is not the one the
490 # controller serves, which is the ordinary case: on integratorHost every
491 # controller serves a protected project and reads the floor out of
492 # "open", which no controller serves. git refuses a repository the caller
493 # does not own, so that read needs its own safe.directory entry, named and
494 # not wildcarded — the same failure as the served repository's, one
495 # repository over.
496 #
497 # And it has to keep working when the two coincide, which is what an
498 # instance's own host looks like: integratorSelfHost's controller for
499 # "guarded" reads the floor from "guarded".
500 integratorFloor =
501 let
502 command = integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
503 selfCommand = integratorSelfHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
504 env = integratorHost.config.systemd.services."valley-integrator@".environment;
505 in
506 !(lib.hasInfix "--instance-repo /srv/git/sealed.git" command)
507 || !(lib.hasInfix "--instance-repo /srv/git/guarded.git" selfCommand)
508 || env.GIT_CONFIG_COUNT or null != "2"
509 || env.GIT_CONFIG_KEY_1 or null != "safe.directory"
510 || env.GIT_CONFIG_VALUE_1 or null != "/srv/git/sealed.git";
511
512 integratorScratch =
513 integratorGitEnv.TMPDIR or null != "/var/lib/${integratorService.StateDirectory}"
514 || !(builtins.elem "/var/lib/${integratorService.StateDirectory}" integratorService.ReadWritePaths);
515
516 # The controllers' wake directories. Each controller watches its own,
517 # under /run, which the host makes owned by the integrator's user and the
518 # writers' group of the git user and the integrator's user. Its sandbox
519 # may write its own and, for the instance project's controller alone,
520 # each other controller's, which that controller marks after a floor
521 # landing. The drop-in that grants those sets nothing else. The push hook
522 # is wired for every served project and no other repository.
523 integratorWakeMisrendered =
524 let
525 wakeOf = name: "/run/valley-integrator-wake/${name}";
526 dropIn = host: name: host.config.systemd.units."valley-integrator@${name}.service" or null;
527 readers =
528 host: instance: others:
529 let
530 unit = dropIn host instance;
531 in
532 unit == null
533 || unit.overrideStrategy or null != "asDropin"
534 || unit.text != "[Service]\n" + lib.concatMapStrings (o: "ReadWritePaths=-${wakeOf o}\n") others;
535 init = integratorHost.config.systemd.services.valley-init.script;
536 in
537 !(lib.hasInfix "--woken-by /run/valley-integrator-wake/%i" integratorService.ExecStart)
538 || !(lib.hasInfix "$VALLEY_FLOOR_READERS" integratorService.ExecStart)
539 || !(lib.hasPrefix "-/nix/store/" integratorService.EnvironmentFile or "")
540 || !(builtins.elem "-${wakeOf "%i"}" integratorService.ReadWritePaths)
541 || builtins.elem "/run/valley-integrator-wake" integratorService.ReadWritePaths
542 || lib.any (
543 name:
544 !(builtins.elem "d ${wakeOf name} 0770 valley-integrator valley-integrator-wake - -" integratorHost.config.systemd.tmpfiles.rules)
545 || !(lib.hasInfix "${name}.git/hooks/post-receive.d/valley-integrator-wake" init)
546 ) [ "guarded" "released" "sealed" ]
547 || 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)))
548 || lib.sort lib.lessThan integratorHost.config.users.groups.valley-integrator-wake.members != lib.sort lib.lessThan [
549 integratorHost.config.services.valley.user
550 integratorHost.config.services.valley.integrator.user
551 ]
552 || readers integratorHost "sealed" [ "guarded" "released" ]
553 || readers integratorSelfHost "guarded" [ "released" "sealed" ]
554 || dropIn integratorHost "guarded" != null
555 || dropIn integratorHost "released" != null
556 || protectedHost.config.users.groups ? valley-integrator-wake;
557
558 # The registry compiler. It is off by default and must stay inert: a
559 # consumer that has not asked for it renders the system it always did.
560 # integratorHost is the strongest witness available — the integrator on,
561 # the signers file supplied by hand, and every option of the identity
562 # block left alone.
563 identityRenderedWithoutEnable =
564 integratorHost.config.systemd.services ? valley-identity
565 || integratorHost.config.systemd.timers ? valley-identity
566 || integratorHost.config.services.openssh.settings ? PermitUserEnvironment
567 || lib.any (lib.hasInfix "valley-identity") integratorHost.config.services.openssh.authorizedKeysFiles
568 || lib.hasInfix "valley-identity" integratorHost.config.services.openssh.extraConfig
569 || lib.hasInfix "valley-identity" (
570 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
571 )
572 || lib.hasInfix "--name " (
573 integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
574 );
575
576 identityService = identityHost.config.systemd.services.valley-identity.serviceConfig;
577
578 identityStateDir = "/var/lib/${identityService.StateDirectory or ""}";
579
580 # What the compiled artifacts have to be true of, and each was a way for
581 # the machinery to be quietly wrong.
582 #
583 # The compiler writes into its state directory and nowhere else, so that
584 # directory has to be the one path the unit may write.
585 #
586 # sshd walks every directory above an authorized-keys file and refuses a
587 # group- or world-writable one, so the state directory is 0755 rather than
588 # the 0700 a service's state usually takes — and the unit runs as the git
589 # user, because sshd equally refuses a file owned by anyone but root or
590 # the account it authorizes.
591 #
592 # The compiled file is added to what sshd reads for the git user rather
593 # than replacing it, and for the git user alone: the user's Match block
594 # names the declared keys and the compiled ones, and nothing else — no
595 # ~/.ssh/authorized_keys, no AuthorizedKeysCommand — so every key the git
596 # user accepts carries a tag this module or the compiler wrote. The
597 # compiler is handed the declared keys, so it can refuse a registry key
598 # declared under another tag.
599 identityCompiler =
600 identityService.User or null != identityHost.config.services.valley.user
601 || identityService.StateDirectoryMode or null != "0755"
602 || identityService.ReadWritePaths or [ ] != [ identityStateDir ]
603 || !(lib.hasInfix "--repo /srv/git/sealed.git" identityService.ExecStart)
604 || !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" identityService.ExecStart)
605 || !(lib.hasInfix "--authorized-keys ${identityStateDir}/authorized_keys.git" identityService.ExecStart)
606 || !(lib.hasInfix "--grants ${identityStateDir}/grants" identityService.ExecStart)
607 || !(lib.hasInfix "-valley-declared-keys" identityService.ExecStart)
608 || !(lib.hasInfix "AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u ${identityStateDir}/authorized_keys.git\n" identityHost.config.services.openssh.extraConfig)
609 || !(lib.hasInfix "AuthorizedKeysCommand none" identityHost.config.services.openssh.extraConfig);
610
611 # A controller under a compiled registry reads the compiled signers file
612 # and signs under the name the registry publishes its key under. The key
613 # hash binds name to key, so a controller signing under the host's default
614 # name while the registry publishes it as "integrator" would produce notes
615 # no verifier can find a key for.
616 identityIntegrator =
617 let
618 command = identityHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
619 in
620 !(lib.hasInfix "--known-signers ${identityStateDir}/known-signers" command)
621 || !(lib.hasInfix "--name integrator" command)
622 || !(builtins.elem "valley-identity.service"
623 identityHost.config.systemd.services."valley-integrator@".after
624 );
625
626 # The signers publication. A host whose integrator runs and which serves
627 # the instance repository publishes there what a client verifies its
628 # transfer statements with. What it publishes has to be what the
629 # controllers use: the same signers file and the same --name, or none on
630 # either, in which case both take the binary's default. The publisher
631 # writes as the git user, which owns the instance repository, may write
632 # that repository and nothing else, runs after the compilation when there
633 # is one, and runs again whenever the signers file changes. The signer
634 # projects file is the controllers' too, or neither has one.
635 flagValue =
636 flag: command:
637 let
638 m = builtins.match ".*--${flag} ([^ ]+).*" command;
639 in
640 if m == null then null else lib.head m;
641
642 signersPublisher =
643 host: repo:
644 let
645 unit = host.config.systemd.services.valley-signers;
646 publish = unit.serviceConfig.ExecStart;
647 controller = host.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
648 in
649 !(lib.hasInfix "/bin/integrator publish-signers " publish)
650 || flagValue "instance-repo" publish != repo
651 || flagValue "known-signers" publish != flagValue "known-signers" controller
652 || flagValue "name" publish != flagValue "name" controller
653 || flagValue "signer-projects" publish != flagValue "signer-projects" controller
654 || unit.serviceConfig.User or null != "git"
655 || unit.serviceConfig.ReadWritePaths or [ ] != [ repo ]
656 || !(builtins.elem "valley-init.service" unit.after)
657 || !(builtins.elem "multi-user.target" unit.wantedBy)
658 || host.config.systemd.paths.valley-signers.pathConfig.PathChanged or null
659 != flagValue "known-signers" controller
660 || !(builtins.elem "multi-user.target" host.config.systemd.paths.valley-signers.wantedBy);
661
662 signersRenderedWithoutIntegrator =
663 protectedHost.config.systemd.services ? valley-signers
664 || protectedHost.config.systemd.paths ? valley-signers;
665
666 signersUnpublished =
667 signersPublisher integratorHost "/srv/git/sealed.git"
668 || signersPublisher restrictedHost "/srv/git/sealed.git"
669 || signersPublisher integratorSelfHost "/srv/git/guarded.git"
670 || signersPublisher identityHost "/srv/git/sealed.git"
671 || flagValue "name" identityHost.config.systemd.services.valley-signers.serviceConfig.ExecStart
672 != "integrator"
673 || !(builtins.elem "valley-identity.service" identityHost.config.systemd.services.valley-signers.after);
674
675 # A host that restricts no signer gives its controllers no signer
676 # projects file, and one that restricts some gives them one.
677 signerProjectsMisrendered =
678 flagValue "signer-projects" integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
679 != null
680 || flagValue "signer-projects" restrictedHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
681 == null;
682
683 # The declared keys stay authorized beside the compiled ones. A compiled
684 # file that replaced them would make a bad compilation — or a first boot
685 # before the first one — a locked-out git user, which is the one failure
686 # this machinery must never have.
687 identityKeepsDeclaredKeys =
688 identityHost.config.users.users.git.openssh.authorizedKeys.keys == [ ];
689
690 # The check worker and the build slice. Both are off by default, and a
691 # host that never asked for them renders none of either: no unit, no
692 # account, no slice, and a nix daemon where NixOS puts it. integratorHost
693 # is the strongest witness, with the integrator the worker would need
694 # already on.
695 workerRenderedWithoutEnable =
696 integratorHost.config.systemd.services ? valley-worker
697 || integratorHost.config.systemd.timers ? valley-worker
698 || integratorHost.config.systemd.paths ? valley-worker
699 || integratorHost.config.users.groups ? valley-worker-wake
700 || lib.hasInfix "--wake" integratorHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart
701 || integratorHost.config.systemd.slices ? valley-builds
702 || integratorHost.config.users.users ? valley-worker
703 || integratorHost.config.systemd.services.nix-daemon.serviceConfig ? Slice;
704
705 # The build slice is a host decision of its own. On, it puts the daemon
706 # in the slice at the caps the host names, with no swap, and nothing of
707 # the worker.
708 buildSliceMisrendered =
709 let
710 slice = buildSliceHost.config.systemd.slices.valley-builds.sliceConfig or { };
711 in
712 buildSliceHost.config.systemd.services.nix-daemon.serviceConfig.Slice or null
713 != "valley-builds.slice"
714 || slice.CPUQuota or null != "200%"
715 || slice.MemoryMax or null != "4G"
716 || slice.MemorySwapMax or null != "0"
717 || buildSliceHost.config.systemd.services ? valley-worker
718 || buildSliceHost.config.users.users ? valley-worker;
719
720 # What the VM check runs, held at the operator's values. worker-e2e
721 # boots the worker and lowers the memory cap at runtime to make a build
722 # run past it, so the values themselves are held here. The caps are on
723 # a slice that holds the worker and the nix daemon both, since a build
724 # runs in the daemon's cgroup and never in the worker's; the slice and
725 # the daemon set no device policy, so a NixOS test still gets /dev/kvm.
726 # The worker may run on any CPU. A host that sets no build capacity has
727 # the worker build one check at a time, each nix build building one
728 # derivation at a time with 4 cores. capacityWorkerHost's values reach
729 # the worker's --slots and its NIX_CONFIG. The account is not in the git
730 # group, so the repositories on disk are not the worker's to read or
731 # write, and it reaches them only through this host's sshd, checking the
732 # host's key. Its timer starts the first pass a second after the timer
733 # starts, not after boot, and each later pass one minute after the last
734 # one ended. Its path unit starts a pass while the wake directory holds
735 # due; the directory is the worker's, in a group of the git user and the
736 # integrator's user, and every writer's sandbox may write it. Nothing
737 # waits for the service at boot, a burst never start-limits it, and a
738 # pass that could not claim due is started again one interval later.
739 workerMisrendered =
740 let
741 unit = workerHost.config.systemd.services.valley-worker;
742 capacity = capacityWorkerHost.config.systemd.services.valley-worker;
743 service = unit.serviceConfig;
744 daemon = workerHost.config.systemd.services.nix-daemon.serviceConfig;
745 slice = workerHost.config.systemd.slices.valley-builds.sliceConfig;
746 account = workerHost.config.users.users.valley-worker;
747 timer = workerHost.config.systemd.timers.valley-worker;
748 wakePath = workerHost.config.systemd.paths.valley-worker;
749 integrator = workerHost.config.systemd.services."valley-integrator@".serviceConfig;
750 signers = workerHost.config.systemd.services.valley-signers.serviceConfig;
751 devicePolicy = c: c ? DevicePolicy || c ? DeviceAllow || c ? PrivateDevices;
752 in
753 service.User or null != "valley-worker"
754 || account.group != "valley-worker"
755 || account.extraGroups != [ ]
756 || service.Type or null != "oneshot"
757 || service.Slice or null != "valley-builds.slice"
758 || daemon.Slice or null != "valley-builds.slice"
759 || slice.CPUQuota or null != "400%"
760 || slice.MemoryMax or null != "8G"
761 || slice.MemorySwapMax or null != "0"
762 || devicePolicy slice
763 || devicePolicy daemon
764 || service ? CPUAffinity
765 || !(lib.hasInfix "max-jobs = 1\n" unit.environment.NIX_CONFIG)
766 || !(lib.hasInfix "cores = 4\n" unit.environment.NIX_CONFIG)
767 || !(lib.hasInfix "max-jobs = 2\n" capacity.environment.NIX_CONFIG)
768 || !(lib.hasInfix "cores = 2\n" capacity.environment.NIX_CONFIG)
769 || capacity.serviceConfig ? CPUAffinity
770 || !(lib.hasInfix "builders =\n" unit.environment.NIX_CONFIG)
771 || !(lib.hasInfix "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" unit.environment.GIT_SSH_COMMAND)
772 || service.ReadWritePaths or [ ] != [
773 "/var/lib/valley-worker"
774 "/var/lib/valley-worker-wake"
775 "/nix/var/nix/daemon-socket"
776 ]
777 || !(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\n" unit.script)
778 || !(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\n" capacity.script)
779 || unit.wantedBy != [ ]
780 || unit.unitConfig.StartLimitIntervalSec or null != 0
781 || service.RestartForceExitStatus or null != "75"
782 || service.RestartSec or null != "1m"
783 || service ? Restart
784 || wakePath.pathConfig.PathExists or null != "/var/lib/valley-worker-wake/due"
785 || !(builtins.elem "multi-user.target" wakePath.wantedBy)
786 || !(builtins.elem "d /var/lib/valley-worker-wake 0770 valley-worker valley-worker-wake - -" workerHost.config.systemd.tmpfiles.rules)
787 || lib.sort lib.lessThan workerHost.config.users.groups.valley-worker-wake.members != lib.sort lib.lessThan [
788 workerHost.config.services.valley.user
789 workerHost.config.services.valley.integrator.user
790 ]
791 || !(builtins.elem "/var/lib/valley-worker-wake" integrator.ReadWritePaths)
792 || !(lib.hasInfix "--wake=\${VALLEY_WAKE}" integrator.ExecStart)
793 || !(lib.hasPrefix "-/nix/store/" integrator.EnvironmentFile or "")
794 || !(lib.hasInfix "--wake /var/lib/valley-worker-wake" signers.ExecStart)
795 || !(builtins.elem "/var/lib/valley-worker-wake" signers.ReadWritePaths)
796 || !(lib.hasInfix "git -C \"$origin\" remote add origin git@localhost:sealed.git\n" unit.script)
797 || timer.timerConfig.OnActiveSec or null != "1s"
798 || timer.timerConfig ? OnBootSec
799 || timer.timerConfig.OnUnitInactiveSec or null != "1m"
800 || !(builtins.elem "timers.target" timer.wantedBy);
801
802 # The worker's projects when a host leaves them unwritten. A worker host
803 # that writes neither list builds for every project its controllers
804 # serve, one that narrows the worker's projects builds for those alone,
805 # and the signers publication carries the controllers' signer projects
806 # file. That file's lines are pinned by module-eval.sh.
807 workerDefaultsMisrendered =
808 let
809 unpublished =
810 host:
811 flagValue "signer-projects" host.config.systemd.services.valley-signers.serviceConfig.ExecStart
812 != flagValue "signer-projects"
813 host.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
814 in
815 defaultWorkerHost.config.services.valley.worker.projects != [
816 "guarded"
817 "released"
818 "sealed"
819 ]
820 || !(lib.hasInfix "exec valley-worker --repo guarded --repo released --repo sealed --key "
821 defaultWorkerHost.config.systemd.services.valley-worker.script
822 )
823 || !(lib.hasInfix "exec valley-worker --repo guarded --key "
824 narrowedWorkerHost.config.systemd.services.valley-worker.script
825 )
826 || unpublished defaultWorkerHost
827 || unpublished narrowedWorkerHost;
828
829 # The restacker. When disabled, it renders no units or user account on
830 # integratorHost. When enabled, each configured project gets a
831 # valley-restacker@<project>.service running valley-restacker run as the
832 # valley-restacker user in its own group, with no access to the bare
833 # repositories on disk. It connects through localhost sshd as its
834 # principal using the key passed via LoadCredential, verifies the host's
835 # own SSH key, has its 0700 state directory as its only persistent
836 # writable path (its private temporary directories are writable too),
837 # and reads the floor from the instance repository over the same SSH
838 # connection.
839 restackerRenderedWithoutEnable =
840 integratorHost.config.systemd.services ? "valley-restacker@"
841 || integratorHost.config.systemd.targets ? valley-restackers
842 || integratorHost.config.users.users ? valley-restacker;
843
844 restackerMisrendered =
845 let
846 unit = restackerHost.config.systemd.services."valley-restacker@";
847 service = unit.serviceConfig;
848 account = restackerHost.config.users.users.valley-restacker;
849 target = restackerHost.config.systemd.targets.valley-restackers;
850 command = service.ExecStart;
851 in
852 service.User or null != "valley-restacker"
853 || service.Group or null != "valley-restacker"
854 || account.group != "valley-restacker"
855 || account.extraGroups != [ ]
856 || service.LoadCredential or [ ] != [ "key:/run/agenix/valley-restacker-key" ]
857 || service.StateDirectory or null != "valley-restacker/%i"
858 || service.StateDirectoryMode or null != "0700"
859 || service.ProtectSystem or null != "strict"
860 || service ? ReadWritePaths
861 || !(lib.hasInfix " -i %d/key " unit.environment.GIT_SSH_COMMAND)
862 || !(lib.hasInfix "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost" unit.environment.GIT_SSH_COMMAND)
863 || !(lib.hasInfix "-o UserKnownHostsFile=%S/valley-restacker/%i/known_hosts -o GlobalKnownHostsFile=/dev/null" unit.environment.GIT_SSH_COMMAND)
864 || !(lib.hasInfix "/bin/valley-restacker run --repo git@localhost:%i.git --state %S/valley-restacker/%i --principal valley-restacker --interval 15s " command)
865 || !(lib.hasInfix " --instance-repo git@localhost:sealed.git" command)
866 || target.wants != [ "valley-restacker@guarded.service" ]
867 || !(builtins.elem "multi-user.target" target.wantedBy);
868
869 # The web publisher (nix/web-publisher.nix). Off, it renders nothing.
870 # On, one pass is a oneshot on a five-minute timer whose first pass waits
871 # five minutes after the timer starts, and which no switch starts or
872 # restarts. It runs as the dynamic user valley-web-publish, which the
873 # policy path's unit shares, in the git group, with an empty
874 # safe.directory entry that resets the system's and the user's, then an
875 # exact entry for each repository the host serves and no wildcard, the
876 # repositories read-only, nothing writable but its state and cache, and
877 # the mirror, backup and signing keys out of reach. It may connect to the
878 # addresses it is allowed and to no other, and checks before each pass that
879 # this filter is in force. Its Go lookups use the C library. Its memory is
880 # capped with no swap. It reads the instance repository the controllers
881 # read, names the host as the instance, and is given the receiver, the
882 # destination, the display mapping and the bounds on its bundles and its
883 # storage.
884 webPublisherRenderedWithoutEnable =
885 webPublisherOffHost.config.systemd.services ? valley-web-publish
886 || webPublisherOffHost.config.systemd.services ? valley-web-publish-policy
887 || webPublisherOffHost.config.systemd.timers ? valley-web-publish
888 || lib.any (p: (p.name or "") == "valley-web-link") webPublisherOffHost.config.environment.systemPackages;
889
890 # The read links: the policy path's own unit, the same pass with
891 # --policy-only in the same sandbox, as the same dynamic user, so the two
892 # share their state and cache directories, and with the same
893 # credentials; the
894 # credential file read live by both through a static group, root's to
895 # write, under the links lock tmpfiles makes beside it, which only root
896 # can make or replace; the operator's wrapper, with the unit's
897 # safe.directory entries, passing issue alone the flags for reading the
898 # registry, and starting the policy pass after every issue or revoke,
899 # and once more while a link is pending; and the backup holding the
900 # file's directory and the publisher's durable state beside the data
901 # directory.
902 webPublisherLinksMisrendered =
903 let
904 units = webPublisherHost.config.systemd.services;
905 pass = units.valley-web-publish.serviceConfig;
906 policy = units.valley-web-publish-policy.serviceConfig or { };
907 wrapper = lib.findFirst (
908 p: (p.name or "") == "valley-web-link"
909 ) null webPublisherHost.config.environment.systemPackages;
910 in
911 lib.filter (x: x != null) (lib.imap0 (i: c: if c then i else null) [
912 (!(units ? valley-web-publish-policy))
913 (lib.any (u: u.DynamicUser or null != true || u.User or null != "valley-web-publish" || u.Group or null != "valley-web-publish") [
914 pass
915 policy
916 ])
917 (policy.ExecStart or null != "${pass.ExecStart} --policy-only")
918 (removeAttrs policy [ "ExecStart" ] != removeAttrs pass [ "ExecStart" ])
919 (units.valley-web-publish-policy.environment != units.valley-web-publish.environment)
920 (!(lib.hasSuffix " --links /var/lib/valley-web-links/links" pass.ExecStart))
921 (!(lib.all (r: builtins.elem r webPublisherHost.config.systemd.tmpfiles.rules) [
922 "d /var/lib/valley-web-links 0750 root valley-web-links -"
923 "f /var/lib/valley-web-links/links 0640 root valley-web-links -"
924 "f /var/lib/valley-web-links/lock 0640 root valley-web-links -"
925 ]))
926 (!(webPublisherHost.config.users.groups ? valley-web-links))
927 (wrapper == null)
928 (!(lib.hasInfix "valley-web-publish link \"$@\" --links /var/lib/valley-web-links/links \\\n --state /var/lib/valley-web-publish\n}" wrapper.text or ""))
929 (!(lib.hasInfix "issue)\n link \"$@\" --instance-repo /srv/git/sealed.git" wrapper.text or ""))
930 (!(lib.hasInfix "revoke) link \"$@\" ;;" wrapper.text or ""))
931 (!(lib.all (e: lib.hasInfix e wrapper.text or "") [
932 "ulimit -c 0\n"
933 "export GIT_CONFIG_COUNT=5\n"
934 "export GIT_CONFIG_VALUE_0=''\n"
935 "export GIT_CONFIG_VALUE_4=/srv/git/sealed.git\n"
936 "systemctl start valley-web-publish-policy.service"
937 "deliver\nif ! link list --check > /dev/null 2>&1; then\n deliver\nfi\nif link list --check > /dev/null; then"
938 ]))
939 (backupWebPublisherHost.config.services.restic.backups.valley.paths or [ ] != [
940 "/srv/git"
941 "/var/lib/valley-web-links"
942 "/var/lib/private/valley-web-publish"
943 ])
944 ]);
945
946 webPublisherMisrendered =
947 let
948 unit = webPublisherHost.config.systemd.services.valley-web-publish;
949 service = unit.serviceConfig;
950 env = unit.environment;
951 timer = webPublisherHost.config.systemd.timers.valley-web-publish;
952 repos = [
953 "/srv/git/guarded.git"
954 "/srv/git/open.git"
955 "/srv/git/released.git"
956 "/srv/git/sealed.git"
957 ];
958 entries = lib.genList (i: {
959 key = env."GIT_CONFIG_KEY_${toString i}" or null;
960 value = env."GIT_CONFIG_VALUE_${toString i}" or null;
961 }) (lib.length (lib.filter (lib.hasPrefix "GIT_CONFIG_KEY_") (lib.attrNames env)));
962 command = service.ExecStart;
963 in
964 service.Type or null != "oneshot"
965 || service.DynamicUser or null != true
966 || service.User or null != "valley-web-publish"
967 || service.Group or null != "valley-web-publish"
968 || service.SupplementaryGroups or [ ] != [
969 "git"
970 "valley-web-links"
971 ]
972 || env.GIT_CONFIG_COUNT or null != toString (lib.length repos + 1)
973 || entries != map (r: {
974 key = "safe.directory";
975 value = r;
976 }) ([ "" ] ++ repos)
977 || lib.any (e: lib.hasInfix "*" e.value) entries
978 || service.ProtectSystem or null != "strict"
979 || service ? ReadWritePaths
980 || service.ReadOnlyPaths or [ ] != map (r: "-${r}") repos
981 || service.StateDirectory or null != "valley-web-publish"
982 || service.CacheDirectory or null != "valley-web-publish"
983 || env.XDG_CACHE_HOME or null != "/var/cache/valley-web-publish"
984 || !(lib.all (p: builtins.elem p service.InaccessiblePaths) [
985 "-/srv/git/.ssh"
986 "-/run/agenix/valley-integrator-key"
987 "-/run/agenix/valley-git-ssh-key"
988 "-/var/lib/valley-integrator"
989 ])
990 || !(lib.hasInfix "/bin/valley-web-publish --instance-repo /srv/git/sealed.git --instance valley-host --destination example.org --host /nix/store/" command)
991 || !(lib.hasInfix "-valley-config.json --receiver https://example.org --receiver-token %d/receiver-token --principals /nix/store/" command)
992 || service.LoadCredential or [ ] != [ "receiver-token:/run/keys/valley-web-receiver-token" ]
993 || !(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)
994 || !(lib.hasSuffix "/bin/valley-web-publish-egress-check 198.51.100.1 9" (service.ExecStartPre or ""))
995 || env.GODEBUG or null != "netdns=cgo"
996 || service.IPAddressDeny or null != "any"
997 || service.IPAddressAllow or null != [
998 "192.0.2.10"
999 "2001:db8::10"
1000 ]
1001 || service.RestrictAddressFamilies or null != [
1002 "AF_INET"
1003 "AF_INET6"
1004 "AF_UNIX"
1005 ]
1006 || service.MemoryMax or null != "1G"
1007 || service.MemorySwapMax or null != "0"
1008 || unit.restartIfChanged != false
1009 || unit.wantedBy != [ ]
1010 || timer.timerConfig.OnActiveSec or null != "5min"
1011 || timer.timerConfig.OnUnitInactiveSec or null != "5min"
1012 || !(builtins.elem "timers.target" timer.wantedBy);
1013
1014 # The web receiver module (nix/web-receiver.nix). When disabled, it
1015 # renders no units or users. When enabled, it renders separate systemd
1016 # units for valley-web-receive and valley-web; both start at boot, restart
1017 # on failure, and run independently. The receiver runs as
1018 # valley-web-receive in group valley-web, owns the mode-0750 state
1019 # directory, and takes the instance, the destination, the pinned verifiers
1020 # from the Nix store, the bearer token as a systemd credential from outside
1021 # the store, and the body and storage caps. valley-web runs as valley-web
1022 # in the same group, orders after the receiver, mounts the state directory
1023 # read-only with no persistent writable paths, and takes the state
1024 # directory and its listener address. Each unit has its own memory cap and
1025 # disables swap.
1026 webReceiverRenderedWithoutEnable =
1027 webReceiverOffHost.config.systemd.services ? valley-web-receive
1028 || webReceiverOffHost.config.systemd.services ? valley-web
1029 || webReceiverOffHost.config.users.users ? valley-web-receive;
1030
1031 webReceiverMisrendered =
1032 let
1033 cfg = webReceiverHost.config;
1034 receive = cfg.systemd.services.valley-web-receive;
1035 web = cfg.systemd.services.valley-web;
1036 confined =
1037 unit:
1038 unit.serviceConfig.ProtectSystem or null == "strict"
1039 && unit.serviceConfig.NoNewPrivileges or null == true
1040 && unit.serviceConfig.CapabilityBoundingSet or null == ""
1041 && unit.serviceConfig.MemorySwapMax or null == "0"
1042 && unit.serviceConfig.Restart or null == "on-failure"
1043 && builtins.elem "multi-user.target" unit.wantedBy
1044 && unit.requires == [ ]
1045 && unit.bindsTo == [ ];
1046 in
1047 !(confined receive && confined web)
1048 || cfg.users.users.valley-web-receive.group != "valley-web"
1049 || cfg.users.users.valley-web.group != "valley-web"
1050 || receive.serviceConfig.User or null != "valley-web-receive"
1051 || receive.serviceConfig.Group or null != "valley-web"
1052 || receive.serviceConfig.StateDirectory or null != "valley-web"
1053 || receive.serviceConfig.StateDirectoryMode or null != "0750"
1054 || receive.serviceConfig.LoadCredential or [ ] != [ "token:/run/keys/valley-web-receiver-token" ]
1055 || receive.serviceConfig.MemoryMax or null != "2G"
1056 || !(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)
1057 || !(lib.hasSuffix "-valley-web-verifiers --token-file %d/token --max-body 1G --max-upload 2G --max-storage 8G" receive.serviceConfig.ExecStart)
1058 || web.serviceConfig.User or null != "valley-web"
1059 || web.serviceConfig.Group or null != "valley-web"
1060 || web.serviceConfig ? StateDirectory
1061 || web.serviceConfig ? ReadWritePaths
1062 || web.serviceConfig ? LoadCredential
1063 || web.serviceConfig.ReadOnlyPaths or [ ] != [ "-/var/lib/valley-web" ]
1064 || web.serviceConfig.MemoryMax or null != "1G"
1065 || !(builtins.elem "valley-web-receive.service" web.after)
1066 || !(lib.hasSuffix "/bin/valley-web --state /var/lib/valley-web/store --listen 127.0.0.1:8080" web.serviceConfig.ExecStart)
1067 || receive.serviceConfig ? InaccessiblePaths
1068 || lib.any (lib.hasInfix "/var/lib/valley-web") cfg.systemd.tmpfiles.rules;
1069
1070 # With an origin, valley-web signs readers in: it takes --origin, and may
1071 # write browser/ in the state directory alone, which tmpfiles makes as
1072 # its own, mode 0700, under the state directory made as the receiver's.
1073 # Its unit takes no core dump. The receiver's unit cannot reach browser/.
1074 webReaderMisrendered =
1075 let
1076 cfg = webReaderHost.config;
1077 receive = cfg.systemd.services.valley-web-receive.serviceConfig;
1078 web = cfg.systemd.services.valley-web.serviceConfig;
1079 in
1080 !(lib.hasSuffix "/bin/valley-web --state /var/lib/valley-web/store --listen 127.0.0.1:8080 --origin https://example.org" web.ExecStart)
1081 || web.ReadOnlyPaths or [ ] != [ "-/var/lib/valley-web" ]
1082 || web.ReadWritePaths or [ ] != [ "/var/lib/valley-web/browser" ]
1083 || web.LimitCORE or null != 0
1084 || receive.InaccessiblePaths or [ ] != [ "-/var/lib/valley-web/browser" ]
1085 || receive.StateDirectory or null != "valley-web"
1086 || !(lib.all (r: builtins.elem r cfg.systemd.tmpfiles.rules) [
1087 "d /var/lib/valley-web 0750 valley-web-receive valley-web -"
1088 "d /var/lib/valley-web/browser 0700 valley-web valley-web -"
1089 ]);
1090in
1091{
1092 module-eval =
1093 if failedAssertions != [ ] then
1094 throw "valley module-eval: failed assertions: ${
1095 lib.concatMapStringsSep "; " (a: a.message) failedAssertions
1096 }"
1097 else if resticRenderedWithoutDeclaration then
1098 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
1099 else if busRenderedWithoutEnable then
1100 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
1101 else if
1102 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
1103 then
1104 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
1105 else if unrefusedHosts != [ ] then
1106 throw "valley module-eval: ${lib.concatMapStringsSep "; " (r: "a host was not refused although ${r.why}") unrefusedHosts}"
1107 else if protectionRenderedWithoutDeclaration then
1108 throw "valley module-eval: principal machinery rendered for a declaration with no protection block and no tagged key"
1109 else if policyMissingWithoutDeclaration then
1110 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"
1111 else if protectedHost.config.services.openssh.settings ? PermitUserEnvironment then
1112 throw "valley module-eval: sshd must pass no key's environment on: the git user's shell derives the principal from the authenticated key"
1113 else if
1114 !(lib.hasInfix "valley-git-shell" protectedHost.config.users.users.git.shell)
1115 then
1116 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"
1117 else if integratorRenderedWithoutEnable then
1118 throw "valley module-eval: integrator machinery rendered for a protected declaration that never enabled the service"
1119 else if !(integratorHost.config.systemd.services ? "valley-integrator@") then
1120 throw "valley module-eval: the integrator is enabled and no controller unit was rendered"
1121 else if
1122 controllers != [
1123 "valley-integrator@guarded.service"
1124 "valley-integrator@released.service"
1125 "valley-integrator@sealed.service"
1126 ]
1127 then
1128 throw "valley module-eval: a controller runs for each protected project and no other, not ${lib.concatStringsSep ", " controllers}"
1129 else if
1130 publishers != [
1131 "valley-publish@guarded.path"
1132 "valley-publish@released.path"
1133 "valley-publish@sealed.path"
1134 ]
1135 then
1136 throw "valley module-eval: each controller's landings are published by a path unit of its own, not ${lib.concatStringsSep ", " publishers}"
1137 else if integratorHost.config.systemd.services."valley-publish@".serviceConfig.User != "git" then
1138 throw "valley module-eval: a landing is published as the git user, which holds the mirror credentials"
1139 else if integratorUser == integratorHost.config.services.valley.user then
1140 throw "valley module-eval: the integrator must not run as the git user — it has its own (bd-500adf7)"
1141 else if !(integratorHost.config.users.users ? ${integratorUser}) then
1142 throw "valley module-eval: the integrator runs as ${integratorUser}, which the module never declares"
1143 else if integratorHost.config.users.users.${integratorUser}.group != "git" then
1144 throw "valley module-eval: the integrator reaches the repositories through the git group, and holds no other grant"
1145 else if integratorSafeDirectory then
1146 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"
1147 else if integratorFloor then
1148 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"
1149 else if integratorScratch then
1150 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"
1151 else if integratorWakeMisrendered then
1152 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"
1153 else if identityRenderedWithoutEnable then
1154 throw "valley module-eval: registry-compilation machinery rendered for a host that never enabled it — nothing may change until a consumer opts in"
1155 else if identityCompiler then
1156 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"
1157 else if identityIntegrator then
1158 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"
1159 else if signersRenderedWithoutIntegrator then
1160 throw "valley module-eval: a signers publication rendered for a host whose integrator is off — there is no transfer statement to verify"
1161 else if signersUnpublished then
1162 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"
1163 else if signerProjectsMisrendered then
1164 throw "valley module-eval: a controller is given a signer projects file exactly when the host restricts a signer to projects"
1165 else if identityKeepsDeclaredKeys then
1166 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"
1167 else if workerRenderedWithoutEnable then
1168 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"
1169 else if buildSliceMisrendered then
1170 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"
1171 else if workerMisrendered then
1172 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), 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, 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"
1173 else if workerDefaultsMisrendered then
1174 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"
1175 else if restackerRenderedWithoutEnable then
1176 throw "valley module-eval: restacker machinery rendered for a host that never enabled it"
1177 else if restackerMisrendered then
1178 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"
1179 else if webPublisherRenderedWithoutEnable then
1180 throw "valley module-eval: web publisher machinery rendered for a host that imports its module and never enabled it"
1181 else if webPublisherMisrendered then
1182 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"
1183 else if webPublisherLinksMisrendered != [ ] then
1184 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"
1185 else if webReceiverRenderedWithoutEnable then
1186 throw "valley module-eval: web receiver machinery rendered for a host that imports its module and never enabled it"
1187 else if webReceiverMisrendered then
1188 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"
1189 else if webReaderMisrendered then
1190 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/"
1191 else
1192 pkgs.runCommand "valley-module-eval" {
1193 initScript = host.config.systemd.services.valley-init.script;
1194 sshdConfig = host.config.services.openssh.extraConfig;
1195 resticService = host.config.systemd.units."restic-backups-valley.service".text;
1196 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
1197 protectedInit = protectedHost.config.systemd.services.valley-init.script;
1198 protectedKeys = lib.concatStringsSep "\n" protectedKeyLines;
1199 protectedShell = protectedHost.config.users.users.git.shell;
1200 integratorUnit = integratorHost.config.systemd.units."valley-integrator@.service".text;
1201 integratorInit = integratorHost.config.systemd.services.valley-init.script;
1202 publishUnit = host.config.systemd.units."valley-publish@.service".text;
1203 identityInit = identityHost.config.systemd.services.valley-init.script;
1204 defaultWorkerController =
1205 defaultWorkerHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
1206 narrowedWorkerController =
1207 narrowedWorkerHost.config.systemd.services."valley-integrator@".serviceConfig.ExecStart;
1208 passAsFile = [
1209 "initScript"
1210 "sshdConfig"
1211 "resticService"
1212 "resticTimer"
1213 "protectedInit"
1214 "protectedKeys"
1215 "integratorUnit"
1216 "integratorInit"
1217 "publishUnit"
1218 "identityInit"
1219 ];
1220 } (builtins.readFile ./module-eval.sh);
1221}