gunk-dev/the-valley

host-module.nix

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