gunk-dev/the-valley

host-module.nix

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