gunk-dev/the-valley

host-module.nix

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