gunk-dev/the-valley

valley-host.nix

source9ee95920e399main's published tip history
176.7 KiB
1# The valley host installer: declarative bare-git hosting over SSH, driven
2# by a CUE host declaration (../schema/valley.cue).
3#
4# Layering: the CUE file owns the domain model — which projects exist, their
5# stores, their push mirrors, whether the host's data has offsite backup and
6# with what cadence and retention. This module owns machine integration
7# only: data directory, unix user, SSH keys, backup credentials. At build
8# time the CUE config is vetted against the shipped schema and exported to
9# JSON; an invalid config fails the system build with cue's error. Nix
10# never redefines the schema.
11#
12# Repos are only ever created, never deleted or overwritten — removing a
13# project (or disabling its git store) leaves the data on disk untouched.
14#
15# Identity is deliberately thin and host-level: one git user, git-shell,
16# key-only, network ACLs in front. Per-project *access* is not honestly
17# enforceable with this mechanism, so it is deliberately not an option
18# (archive/.the-valley/decisions/dcr-0f5d9b1-cue-config-host-module.md). Per-project
19# *write protection* is, because the pre-receive hook below is a real
20# enforcement boundary and each key carries a principal name it can read
21# (archive/.the-valley/decisions/dcr-b87f6e8-identity-is-a-governed-registry.md) —
22# so it is declared, in the project's `protection` block, and this module
23# only binds principal names to keys and grants, and installs the hook.
24# Those bindings are declared by hand or compiled from the instance's
25# identity registry, and the compiler is off until a consumer turns it on.
26#
27# Mirror credentials are the consumer's concern: the module assumes the git
28# user's SSH identity and known_hosts are provisioned by the host (e.g.
29# through its secrets). Every mirror push runs as the git user, whether
30# a push or an integrator landing moved the ref. Nothing here plumbs
31# secrets: the backup options below take *paths* to consumer-provisioned
32# secret files; the contents never pass through this module or the store.
33#
34# Three services run under their own unix users rather than the git one:
35# the integrator, which is the first half of the split bd-500adf7 asks
36# for, and the check worker and the restacker, which are not in the git
37# group at all.
38{
39 config,
40 pkgs,
41 lib,
42 ...
43}:
44
45let
46 cfg = config.services.valley;
47
48 schema = ../schema/valley.cue;
49
50 # Build-time vet + export of the host declaration. the vet checks the
51 # declaration against the schema (whose top level applies #Host), so unknown
52 # fields and unsafe project names fail the build, with cue's error.
53 configJSON =
54 pkgs.runCommand "valley-config.json"
55 {
56 nativeBuildInputs = [ pkgs.cue ];
57 }
58 ''
59 cue vet -c ${schema} ${cfg.config}
60 cue export ${schema} ${cfg.config} > $out
61 '';
62
63 host = lib.importJSON configJSON;
64
65 # Projects whose git store is enabled get a bare repository.
66 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
67 repoNames = lib.attrNames gitProjects;
68
69 # Where valley-init publishes repoNames in the instance repository.
70 projectsRef = "refs/the-valley/projects";
71
72 # The declared durability policy, if any. `backup` is optional in the
73 # schema: a declaration without it (or with enable = false) renders zero
74 # backup machinery, exactly as before the field existed.
75 backupPolicy = host.backup or null;
76 backupEnabled = backupPolicy != null && backupPolicy.enable;
77
78 # The declared cadence names policy; its wall-clock rendering is this
79 # installer's choice. A lookup rather than a literal, so a cadence this
80 # module does not know fails eval loudly instead of mis-scheduling.
81 backupTimer = {
82 # Late night with a spread; Persistent runs a missed window at boot.
83 nightly = {
84 OnCalendar = "03:30";
85 RandomizedDelaySec = "30m";
86 Persistent = true;
87 };
88 };
89
90 # The projects the integrator serves: exactly the ones the declaration
91 # protects. A protected ref is one only a declared writer may push, and
92 # the integrator is what lands everyone else's changes onto it.
93 integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects;
94
95 # The programs this flake builds (nix/packages.nix), the defaults of
96 # services.valley.packages.
97 flakePackages = import ./packages.nix { inherit pkgs lib; };
98
99 # The integrator this flake builds, in its shipping form: attest, the
100 # deriver, cue, git and natscli pinned inside the wrapper, so every host
101 # judges with the same tools (nix/packages.nix).
102 integratorPackage = cfg.packages.integrator;
103
104 # The whole of a controller's configuration: which repository it serves,
105 # who it signs as, and whose evidence it accepts. No policy — the
106 # integrator reads the project layer from the target tip and the instance
107 # layer from its own side (bd-eaefe82) — and no project name, which the
108 # binary derives from the bare repo's own directory, the same way the
109 # post-receive hook does.
110 integratorCommand = lib.concatStringsSep " " (
111 [
112 "${integratorPackage}/bin/integrator watch"
113 "--repo ${cfg.dataDir}/%i.git"
114 "--key ${toString cfg.integrator.signingKeyFile}"
115 "--known-signers ${knownSigners}"
116 "--interval ${cfg.integrator.interval}"
117 ]
118 ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}"
119 ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}"
120 ++ (
121 if cfg.integrator.instanceProject != null then
122 [ "--instance-repo ${instanceRepo}" ]
123 else
124 [ "--instance ${toString cfg.integrator.instancePolicy}" ]
125 )
126 ++ lib.optional cfg.bus.enable "--bus ${busUrl}"
127 ++ [ "--publish-queue ${cfg.dataDir}/%i.git/${publishQueueName}" ]
128 # The worker's wake directory, for the projects whose landings it reads:
129 # the unit's environment file for the instance names it (integratorEnv
130 # below), and empty, which marks nothing, for every other project.
131 ++ lib.optional cfg.worker.enable "--wake=\${VALLEY_WAKE}"
132 # The controller's own wake directory, which it watches and consumes.
133 # --wake above is output, to the worker; this is the controller's input.
134 ++ [ "--woken-by ${integratorWakeRoot}/%i" ]
135 # The approval inputs, which the controller takes as paths and reads
136 # nothing from: the compiler's approval signers files on a host that
137 # compiles a registry, and the project's push policy, the store file
138 # its pre-receive hook reads, which the unit's environment file names
139 # (integratorEnv below).
140 ++ lib.optionals cfg.identity.enable [
141 "--approval-signers ${identityApprovalSigners}"
142 "--approval-signers-hardware ${identityApprovalHardware}"
143 ]
144 ++ [ "--push-policy=\${VALLEY_PUSH_POLICY}" ]
145 # The floor's readers, for the instance project's controller alone: its
146 # environment file names one --wake-floor-reader per other controller,
147 # and $VALLEY_FLOOR_READERS, unbraced, is split into those words. Every
148 # other controller's file names none, and the variable is no word at all.
149 ++ lib.optional (floorReaders != [ ]) "$VALLEY_FLOOR_READERS"
150 );
151
152 # The controllers' wake directories (integrator/wake.go), one per
153 # controller under integratorWakeRoot. A writer that moves a ref the
154 # controller reads creates the empty file due in it, and the controller
155 # starts a pass. The host makes each one, owned by the integrator's user
156 # and the writers' group: the git user, whose post-receive hook marks a
157 # push, and the integrator's user, whose instance controller marks a
158 # floor landing. Mode 0770 and no sticky bit, so the controller can
159 # remove a due whichever writer made it. They sit in /run, outside the
160 # integrator's 0700 state directory and outside the repositories: a boot
161 # loses them, and a controller's first pass reads every ref anyway.
162 integratorWakeRoot = "/run/valley-integrator-wake";
163 integratorWakeGroup = "valley-integrator-wake";
164 integratorWakeDir = name: "${integratorWakeRoot}/${name}";
165
166 # The ref the floor is read from: the integrator's default --instance-ref,
167 # which the host does not change.
168 floorRef = "refs/heads/main";
169
170 # The controllers that read the floor the instance project's controller
171 # lands: every other one. Empty when the host serves no instance
172 # repository, since then no landing here moves the floor.
173 floorReaders =
174 if instanceRepo == null then
175 [ ]
176 else
177 lib.filter (name: name != cfg.integrator.instanceProject) (lib.attrNames integratedProjects);
178
179 # The one filesystem grant the integrator's user gets. It writes refs,
180 # objects, and the worktree metadata `git worktree add` keeps inside the
181 # repository, so read access is not enough: the repos it serves become
182 # group-shared, and its primary group is the git group. Re-applied on
183 # every activation, because a repo can predate the service.
184 # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by
185 # whichever user got there first. Left alone that user is the integrator,
186 # and this sweep runs as the git user, which cannot chmod a directory it
187 # does not own. So init makes that directory itself, ahead of any
188 # controller: owned by the git user, group-writable, and setgid, so what a
189 # controller creates inside it lands in the git group and stays reachable.
190 integratorShareCommands =
191 ''
192 # A chmod the git user is not allowed to make is a path some other
193 # user owns; chmod -R applies what it can and then says so. Warn and
194 # carry on, and the trade is worth stating. Failing here fails
195 # valley-init, which every valley unit requires, so the alternative to
196 # a partly shared repository is no git service on the host at all: no
197 # controllers, and no ssh access to any project. A degraded share
198 # costs the integrator the paths it cannot write, is visible in the
199 # journal, and is fixed by one chown. That is the recoverable half of
200 # the trade, and it is the half to take. The warning is what keeps the
201 # degraded state from being a silent one.
202 share() {
203 "$@" || echo "valley-init: $* failed — a path the git user does not own is left as it was, and the integrator may be unable to write it" >&2
204 }
205 ''
206 + lib.concatMapStrings (name: ''
207 repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
208 git -C "$repo" config core.sharedRepository group
209 # Before the sweep below, so the sweep never meets a root it cannot
210 # touch. On a host where a controller already made it, this is the
211 # chmod that warns, and the repository is served either way.
212 mkdir -p "$repo/worktrees"
213 share chmod g+rwxs "$repo/worktrees"
214 # The publish queue is the git user's for the same reason: the
215 # integrator writes into it and the publish unit deletes from it.
216 mkdir -p "$repo/${publishQueueName}"
217 share chmod g+rwxs "$repo/${publishQueueName}"
218 share chmod -R g+rwX "$repo"
219 share find "$repo" -type d -exec chmod g+s {} +
220 '') (lib.attrNames integratedProjects);
221
222 # The integrator's own directory. Four unit settings have to agree about
223 # it — its state directory, its working directory, the scratch root TMPDIR
224 # names, and the read-write path that makes all three usable — so they name
225 # it once here.
226 # The bare repository the group's floor is read from: the instance
227 # project's, served by this host. Null when the host serves no instance
228 # repository and the layer is supplied as a directory instead.
229 instanceRepo =
230 if cfg.integrator.instanceProject != null then
231 "${cfg.dataDir}/${cfg.integrator.instanceProject}.git"
232 else
233 null;
234
235 integratorStateName = "valley-integrator";
236 integratorStateDir = "/var/lib/${integratorStateName}";
237
238 # The identity registry compiler this flake builds. It renders the
239 # registry at the instance repository's integrated tip into what the gates
240 # check (dcr-b87f6e8): the known-signers file the integrator and any
241 # reader of an attestation use, and a tagged authorized_keys for the git
242 # user.
243 identityPackage = cfg.packages.identity;
244
245 identityStateName = "valley-identity";
246 identityStateDir = "/var/lib/${identityStateName}";
247 identityKnownSigners = "${identityStateDir}/known-signers";
248
249 # The grants the pre-receive hook checks, as the registry names them.
250 identityGrants = "${identityStateDir}/grants";
251
252 # The approval signers files: the keys of every approval key, and of the
253 # hardware ones. The signers publication publishes both, and each
254 # controller is handed their paths.
255 identityApprovalSigners = "${identityStateDir}/approval-signers";
256 identityApprovalHardware = "${identityStateDir}/approval-signers-hardware";
257
258 # The compiled authorized keys. sshd reads them for the git user alone:
259 # the git user's Match block below names the files its keys come from.
260 identityAuthorizedKeys = "${identityStateDir}/authorized_keys.${cfg.user}";
261
262 identityCommand = lib.concatStringsSep " " [
263 "${identityPackage}/bin/identity compile"
264 "--repo ${toString instanceRepo}"
265 "--ref ${cfg.identity.ref}"
266 "--dir ${cfg.identity.directory}"
267 "--known-signers ${identityKnownSigners}"
268 "--authorized-keys ${identityAuthorizedKeys}"
269 "--grants ${identityGrants}"
270 "--approval-signers ${identityApprovalSigners}"
271 "--approval-signers-hardware ${identityApprovalHardware}"
272 "--declared-keys ${declaredKeysFile}"
273 ];
274
275 # What the compiler's path unit watches for a move of the registry's ref:
276 # its loose file, and nothing else. Under git's files ref storage that
277 # covers the ref's creation, its updates, which replace the file, and
278 # pack-refs or gc packing it, which deletes the file. It does not cover
279 # deleting a ref already packed, a rewrite of packed-refs alone, a
280 # symbolic ref's target, or reftable storage. packed-refs is not watched
281 # beside it, because a second watch in the unit, on an absent
282 # packed-refs, reports the HEAD.lock git takes at every update of main,
283 # and systemd then sets the unit's watches up again and loses the event
284 # on main.
285 identityInputs = [ "${toString instanceRepo}/${cfg.identity.ref}" ];
286
287 # Whose evidence a controller accepts: the compiled artifact once the
288 # registry machinery is on, and the file the consumer supplied otherwise.
289 knownSigners =
290 if cfg.identity.enable then identityKnownSigners else toString cfg.integrator.knownSignersFile;
291
292 # Which signers count in which projects, as the integrator reads it: one
293 # line per restricted signer, its name and then its projects. Null when
294 # the consumer restricts nobody, so a host that sets nothing passes no
295 # file to anything. The file is in the store, so a changed list is a
296 # changed command line for the controllers and the publisher alike, and
297 # an activation restarts the one and runs the other again.
298 signerProjects =
299 if cfg.integrator.signerProjects == { } then
300 null
301 else
302 pkgs.writeText "valley-signer-projects" (
303 lib.concatStrings (
304 lib.mapAttrsToList (
305 name: projects: lib.concatStringsSep " " ([ name ] ++ projects) + "\n"
306 ) cfg.integrator.signerProjects
307 )
308 );
309
310 # What a client verifies this host's transfer statements with, published
311 # in the instance repository: the known-signers file the controllers read,
312 # whichever wrote it, and the name they sign under. Unset, the name is the
313 # integrator's own default, and the publisher computes it with the same
314 # code on the same host, so what is published is what the controllers use.
315 # A host publishes it while the integrator runs and the host serves the
316 # instance repository; any other host publishes nothing.
317 #
318 # Beside them, who may approve: the compiler's two approval signers files
319 # when the registry machinery is on, and empty files otherwise, since no
320 # other source of approval keys exists. The publisher also derives the
321 # instance's identity from the instance repository's main.
322 publishesSigners = cfg.integrator.enable && instanceRepo != null;
323 signersCommand = lib.concatStringsSep " " (
324 [
325 "${integratorPackage}/bin/integrator publish-signers"
326 "--instance-repo ${toString instanceRepo}"
327 "--known-signers ${knownSigners}"
328 ]
329 ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}"
330 ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}"
331 ++ lib.optionals cfg.identity.enable [
332 "--approval-signers ${identityApprovalSigners}"
333 "--approval-signers-hardware ${identityApprovalHardware}"
334 ]
335 ++ lib.optional cfg.worker.enable "--wake ${workerWakeDir}"
336 );
337
338 # Every file a publication is read from, which the path unit watches: the
339 # signers and approval files, and the instance repository's main, which
340 # the identity is derived from. git moves main by writing its loose ref,
341 # and pack-refs moves it into packed-refs, so both are watched.
342 signersInputs = [
343 knownSigners
344 ]
345 ++ lib.optionals cfg.identity.enable [
346 identityApprovalSigners
347 identityApprovalHardware
348 ]
349 ++ [
350 "${toString instanceRepo}/refs/heads/main"
351 "${toString instanceRepo}/packed-refs"
352 ];
353
354 # The check worker (status/worker.go), as this flake packages it, and the
355 # attest it signs with.
356 workerPackage = (import ./packages.nix { inherit pkgs lib; }).valley-worker;
357 attestPackage = (import ./packages.nix { inherit pkgs lib; }).attest;
358
359 workerDir = toString cfg.worker.stateDir;
360
361 # The worker's one key. It signs the worker's notes, and it is the ssh
362 # key the worker reaches this host's repositories with. It is made on
363 # the host the first time the service starts, and the service never
364 # copies or prints it. Anything running as the worker can read it.
365 workerKey = "${workerDir}/key";
366
367 # The worker's wake directory (status/wake.go): a writer that moves a
368 # ref the worker reads creates the empty file due in it, and the path
369 # unit starts a pass while due is there. The host makes it, owned by the
370 # worker, outside the worker's own directory, which is the worker's
371 # alone. Its group is the writers': the git user, whose post-receive
372 # hook and signer publisher write, and the integrator's user, which
373 # writes after a landing. Mode 0770 and no sticky bit, so the worker can
374 # rename a due whichever writer made it. Nothing in it is read as data.
375 workerWakeDir = toString cfg.worker.wakeDir;
376 workerWakeGroup = "valley-worker-wake";
377
378 # The integrator's environment, one file per controller. VALLEY_WAKE names
379 # the worker's wake directory to --wake for each project in wakeProjects,
380 # and is empty, which marks nothing, for every other.
381 # VALLEY_FLOOR_READERS names the floor's readers to the instance project's
382 # controller, and nothing to any other. VALLEY_PUSH_POLICY names each
383 # controller's project's push policy to --push-policy: the same store
384 # file the project's pre-receive hook reads.
385 integratorEnv = pkgs.runCommand "valley-integrator-env" { } (
386 "mkdir $out\n"
387 + lib.concatMapStrings (
388 name:
389 let
390 lines =
391 lib.optional (cfg.worker.enable && lib.elem name wakeProjects) "VALLEY_WAKE=${workerWakeDir}"
392 ++ lib.optional (name == cfg.integrator.instanceProject && floorReaders != [ ]) (
393 "VALLEY_FLOOR_READERS="
394 + lib.concatMapStringsSep " " (r: "--wake-floor-reader=${integratorWakeDir r}") floorReaders
395 )
396 ++ [ "VALLEY_PUSH_POLICY=${pushPolicy name integratedProjects.${name}}" ];
397 in
398 "printf '%s\\n' ${lib.escapeShellArgs lines} > $out/${lib.escapeShellArg name}\n"
399 ) (lib.attrNames integratedProjects)
400 );
401
402 # The projects whose moves can change what the worker builds: its own,
403 # and the instance project its floor is read from, whether or not the
404 # worker builds the instance project too.
405
406 wakeProjects = lib.unique (
407 cfg.worker.projects ++ lib.optional (cfg.integrator.instanceProject != null) cfg.integrator.instanceProject
408 );
409
410 # The worker reads and pushes as an ssh client of this host, as the git
411 # user, so its pushes pass the pre-receive hook like anyone else's. It
412 # holds no grant on the repositories' files. The repository it runs in
413 # names the instance repository as origin, and the projects are found
414 # through it, the way valley pending --repo finds them.
415 workerOrigin = "${cfg.user}@localhost:${toString cfg.integrator.instanceProject}.git";
416
417 # Every host the worker connects to is checked against this host's own
418 # keys, under one alias. A project's policy/valley may name this host by
419 # another name, such as git@valley-host:valley.git, and that still
420 # reaches this host's sshd. A name that reaches any other host fails the
421 # check, so the worker talks to no other host.
422 workerSsh = lib.concatStringsSep " " [
423 "${config.programs.ssh.package}/bin/ssh -F none"
424 "-i ${workerKey}"
425 "-p ${toString (lib.head config.services.openssh.ports)}"
426 "-o IdentitiesOnly=yes -o BatchMode=yes"
427 "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost"
428 "-o UserKnownHostsFile=${workerDir}/known_hosts -o GlobalKnownHostsFile=/dev/null"
429 ];
430
431 # The nix settings the worker's nix commands run with. The daemon applies
432 # max-jobs and cores to every connection, a client's that is not trusted
433 # included: each nix build the worker starts builds up to worker.maxJobs
434 # derivations at once, and tells each builder it may use worker.cores
435 # cores. cores is a hint the builder reads as NIX_BUILD_CORES; the build
436 # slice is what holds a build to its CPUs. The worker uses no remote
437 # builder, and no flake's nixConfig.
438 workerNixConfig = ''
439 extra-experimental-features = nix-command flakes
440 max-jobs = ${toString cfg.worker.maxJobs}
441 cores = ${toString cfg.worker.cores}
442 builders =
443 accept-flake-config = false
444 '';
445
446 # The build slice (services.valley.buildSlice): the one slice every
447 # build of this machine's nix daemon runs in, under the host's caps.
448 buildSlice = "valley-builds.slice";
449
450 # What each of the worker's capacity options says about the slice.
451 workerCapacityBound = ''
452 The build slice's {option}`services.valley.buildSlice.cpuQuota` and
453 {option}`services.valley.buildSlice.memoryMax` set aggregate CPU-time
454 and memory limits for the worker, its child processes, and the nix
455 daemon with its local builds for all users. Concurrent builds share
456 these limits, and the worker has no reserved share. Builds outside the
457 slice are not covered.
458
459 If memory cannot be reclaimed below `memoryMax`, the kernel kills a
460 process in the slice. That may be an unrelated build, a daemon
461 process, or the worker. If `attest` returns a failure and the worker
462 survives to save it, later passes back off that batch. Killing the
463 worker before it records the failure does not establish that backoff.
464 '';
465
466 # What the service does each time it starts: make the key if there is
467 # none, write its public halves and this host's ssh keys, make the
468 # repository it runs in, and run one pass.
469 workerScript = ''
470 set -eu
471 state=${lib.escapeShellArg workerDir}
472 key="$state/key"
473
474 # The key is made once, under a temporary name and renamed into place,
475 # so a start that is killed half way leaves no key, and the next start
476 # makes one. The public half is renamed first, so a key is never
477 # without it. The private half is never printed.
478 if [ ! -e "$key" ]; then
479 rm -f "$key.new" "$key.new.pub"
480 ssh-keygen -q -t ed25519 -N "" -C "valley-worker@${config.networking.hostName}" -f "$key.new"
481 chmod 0400 "$key.new"
482 mv -f "$key.new.pub" "$key.pub"
483 mv -f "$key.new" "$key"
484 fi
485
486 # The verifier line the known-signers file holds for the key, under
487 # the worker's signing name. A changed name is a changed line, so it is
488 # written again on every start, and said whenever it changes.
489 attest key --key "$key" --name ${lib.escapeShellArg cfg.worker.signerName} > "$state/verifier.new"
490 if cmp -s "$state/verifier.new" "$state/verifier"; then
491 rm -f "$state/verifier.new"
492 else
493 mv -f "$state/verifier.new" "$state/verifier"
494 echo "valley-worker: the worker's ssh public key is $(cat "$state/key.pub")"
495 echo "valley-worker: the worker's verifier line is $(cat "$state/verifier")"
496 fi
497
498 # This host's own ssh keys, the only ones the worker's ssh accepts.
499 : > "$state/known_hosts.new"
500 for pub in ${lib.escapeShellArgs (map (k: "${k.path}.pub") config.services.openssh.hostKeys)}; do
501 if [ -r "$pub" ]; then
502 printf 'localhost %s\n' "$(cut -d' ' -f1,2 "$pub")" >> "$state/known_hosts.new"
503 fi
504 done
505 mv -f "$state/known_hosts.new" "$state/known_hosts"
506
507 # The repository the pass runs in. It holds no checkout, and origin is
508 # the instance repository.
509 origin="$state/origin"
510 git init --quiet "$origin"
511 if [ "$(git -C "$origin" remote get-url origin 2>/dev/null)" != ${lib.escapeShellArg workerOrigin} ]; then
512 git -C "$origin" remote remove origin 2>/dev/null || true
513 git -C "$origin" remote add origin ${lib.escapeShellArg workerOrigin}
514 fi
515
516 cd "$origin"
517 exec valley-worker ${
518 lib.concatMapStringsSep " " (p: "--repo ${lib.escapeShellArg p}") cfg.worker.projects
519 } --key "$key" --name ${lib.escapeShellArg cfg.worker.signerName} --state "$state" --wake ${lib.escapeShellArg workerWakeDir} --slots ${toString cfg.worker.buildSlots} --batches ${toString cfg.worker.batches} --interval ${lib.escapeShellArg cfg.worker.interval} ${
520 if cfg.worker.evalMemoryBudget != null then
521 "--eval-budget ${cfg.worker.evalMemoryBudget}"
522 else
523 "--eval-share ${builtins.toJSON cfg.worker.evalMemoryShare}"
524 }${
525 lib.optionalString (
526 cfg.worker.keepOutputs != null
527 ) " --keep-outputs ${toString (cfg.worker.keepOutputs * 24)}h"
528 }
529 '';
530
531 # The name the controllers sign under, which the worker's must not be.
532 integratorName =
533 if cfg.integrator.signingName != null then
534 cfg.integrator.signingName
535 else
536 "${config.networking.hostName}/attestations";
537
538 # The restacker (restack/): one controller for each project listed,
539 # under its own Unix user. Its state for a project is a directory of its
540 # own, and it reaches the repositories as an ssh client of this host,
541 # as its own principal, so every push it makes passes the pre-receive
542 # hook like anyone else's. It is in no group that can read or write them
543 # on disk.
544 restackerPackage = cfg.packages.restacker;
545 restackerStateName = "valley-restacker";
546 restackerState = "%S/${restackerStateName}/%i";
547
548 # It authenticates with the key the operator provisions, which systemd
549 # hands it as a credential, and accepts only this host's own ssh keys,
550 # under one alias, as the worker does.
551 restackerSsh = lib.concatStringsSep " " [
552 "${config.programs.ssh.package}/bin/ssh -F none"
553 "-i %d/key"
554 "-p ${toString (lib.head config.services.openssh.ports)}"
555 "-o IdentitiesOnly=yes -o BatchMode=yes"
556 "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost"
557 "-o UserKnownHostsFile=${restackerState}/known_hosts -o GlobalKnownHostsFile=/dev/null"
558 ];
559
560 # This host's own ssh keys, written into the state directory before each
561 # start: the only keys the restacker's ssh accepts.
562 restackerKnownHosts = pkgs.writeShellScript "valley-restacker-known-hosts" ''
563 set -eu
564 : > "$1/known_hosts.new"
565 for pub in ${lib.escapeShellArgs (map (k: "${k.path}.pub") config.services.openssh.hostKeys)}; do
566 if [ -r "$pub" ]; then
567 printf 'localhost %s\n' "$(cut -d' ' -f1,2 "$pub")" >> "$1/known_hosts.new"
568 fi
569 done
570 mv -f "$1/known_hosts.new" "$1/known_hosts"
571 '';
572
573 # A pass reads landings with the verifier keys and the name the
574 # controllers read and sign under, and the floor from where the
575 # controllers read it: the instance repository, over ssh as itself, or
576 # the materialized directory.
577 restackerCommand = lib.concatStringsSep " " (
578 [
579 "${restackerPackage}/bin/valley-restacker run"
580 "--repo ${cfg.user}@localhost:%i.git"
581 "--state ${restackerState}"
582 "--principal ${cfg.restacker.principal}"
583 "--interval ${cfg.restacker.interval}"
584 "--integrator-name ${integratorName}"
585 ]
586 ++ lib.optional (knownSigners != "") "--known-signers ${knownSigners}"
587 ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}"
588 ++ (
589 if cfg.integrator.instanceProject != null then
590 [ "--instance-repo ${cfg.user}@localhost:${cfg.integrator.instanceProject}.git" ]
591 else
592 [ "--instance ${toString cfg.integrator.instancePolicy}" ]
593 )
594 );
595
596 # The paths the consumer must supply once the integrator is enabled,
597 # with what each names — for the assertion message. The signers file is
598 # among them only while the registry does not compile one.
599 integratorPathOptions = {
600 signingKeyFile = "the key its transfer statements are signed with";
601 }
602 // lib.optionalAttrs (!cfg.identity.enable) {
603 knownSignersFile = "the signers whose evidence it accepts";
604 };
605
606 # The secret-path options the consumer must supply once the declaration
607 # enables backup, with what each names — for the assertion message.
608 backupSecretOptions = {
609 repositoryFile = "the restic repository URL";
610 passwordFile = "the repository encryption password";
611 sshKeyFile = "the SSH identity for the sftp target";
612 knownHostsFile = "the pinned host key of the sftp target";
613 };
614
615 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
616 # this script, which chains every executable dropped into the repo's
617 # hooks/post-receive.d/ directory.
618 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
619 # Managed by services.valley — do not edit.
620 # Drop executable hooks into post-receive.d/ next to this symlink.
621 set -eu
622 hook_dir="$(dirname "$0")/post-receive.d"
623 [ -d "$hook_dir" ] || exit 0
624 updates="$(cat)"
625 [ -n "$updates" ] || exit 0
626 for hook in "$hook_dir"/*; do
627 [ -x "$hook" ] || continue
628 printf '%s\n' "$updates" | "$hook" "$@"
629 done
630 '';
631
632 # Push replication. A publication mirror gets main and the tags, and
633 # nothing else. Only the publish drain further down runs it, for pushes
634 # and integrator landings alike.
635 # Topic branches are review-queue state, not published: the mirror exists
636 # so consumers can fetch what has been integrated, and durability is
637 # restic's job, not the mirror's. The two refspecs are what keep every
638 # other ref of the project off the mirror.
639 # --prune propagates tag deletions through the tags glob. The heads
640 # refspec names one ref, so --prune deletes no head.
641 # The pusher deletes nothing else on a mirror. Deleting a ref that a
642 # public mirror has served unpublishes nothing, because forges keep its
643 # objects fetchable by SHA. And a mirror holds refs that other writers put
644 # there, such as a forge's own namespaces or a bot's branches; those are
645 # theirs. --mirror is refused for the same reason: it deletes every mirror
646 # ref the primary lacks, and on GitHub the read-only refs/pull/* makes
647 # that fail every push, masking real replication failures.
648 # The pusher exits non-zero when a replication push fails, and the drain
649 # retries on that: git's exit status decides. A failure carries its
650 # reason, which pushreason (../pushreason) makes from git's error output:
651 # the remote's own words, with any word that looks like an address or
652 # carries a parameter dropped, in one line fit for the journal. The URL
653 # in the line is the declared one, as written: it is configuration the
654 # operator wrote, not text a remote chose. The line goes to the unit's
655 # output as well as the log, because the journal files the unit's output
656 # under the unit, and the unit's journal is what telemetry reads.
657 mirrorPusher =
658 name: mirrors:
659 pkgs.writeShellScript "valley-mirror-push-${name}" ''
660 reason=${lib.getExe pushreasonPackage}
661 log() { ${pkgs.util-linux}/bin/logger -t valley-mirror "$1" || true; }
662 status=0
663 for url in ${lib.escapeShellArgs mirrors}; do
664 if why="$(${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' 2>&1 >/dev/null | "$reason"
665 exit "''${PIPESTATUS[0]}")"; then
666 log "${name}: pushed to $url"
667 else
668 msg="${name}: push to $url FAILED: $why"
669 log "$msg"
670 printf '%s\n' "$msg" >&2
671 status=1
672 fi
673 done
674 exit "$status"
675 '';
676
677 # The post-receive.d hook of a project with mirrors. It does not push. It
678 # queues the push's ref moves for the publish drain, as the integrator
679 # queues a landing, and returns. So a dead mirror can only ever cost a log
680 # line and a retry, never block or fail the primary push. The file is
681 # written beside the queue and renamed into it, so the drain never reads a
682 # partial one. A push whose moves cannot be queued is logged, and stands.
683 mirrorHook =
684 name:
685 pkgs.writeShellScript "valley-mirrors-${name}" ''
686 # Managed by services.valley — queue this push for ${name}'s mirrors.
687 bin=${pkgs.coreutils}/bin
688 tmp="$($bin/mktemp .valley-publish-XXXXXXXX)" &&
689 $bin/cat >"$tmp" &&
690 $bin/mv -- "$tmp" "${publishQueueName}/$($bin/date +%s%N)-push-$$" || {
691 $bin/rm -f -- "$tmp"
692 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: queueing a push FAILED" || true
693 }
694 exit 0
695 '';
696
697 # The event bus (archive/design/roadmap.md, Phase 1): NATS JetStream, onto which
698 # the ref-updated hook below projects this host's git activity. The bus is
699 # never load-bearing for durable state — per-repo events are durable in
700 # git itself, and `valley replay` rebuilds the stream from a repo's refs —
701 # so losing its storage costs one replay, nothing more.
702 busUrl = "nats://${cfg.bus.listen}";
703
704 busServerConfig = pkgs.writeText "valley-bus.conf" ''
705 listen: ${cfg.bus.listen}
706 jetstream {
707 store_dir: "${cfg.bus.storeDir}"
708 # The store directory defaults to living on the repo volume; the cap
709 # keeps a runaway or malicious local publisher from filling it.
710 max_file_store: 2GiB
711 }
712 '';
713
714 # One ref-updated event per updated ref, read from the post-receive stdin
715 # this script inherits. Every payload field is derivable from git alone —
716 # no wall-clock time, no hostname — so replaying a repo's refs reproduces
717 # the same events (the roadmap's determinism criterion). `valley replay`
718 # builds the identical payload (status/bus.go); change one only with the
719 # other.
720 busPublisher = pkgs.writeShellScript "valley-bus-publish" ''
721 repo="$(basename "$PWD" .git)"
722 while read -r old new ref; do
723 [ -n "$ref" ] || continue
724 # " is the only JSON-significant character a refname can contain
725 # (git forbids \ and control characters); names and ids are safe.
726 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
727 "$repo" "''${ref//\"/\\\"}" "$old" "$new")"
728 if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \
729 "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then
730 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true
731 else
732 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true
733 fi
734 done
735 '';
736
737 # How a move reaches the mirrors: the publish queue.
738 #
739 # One thing pushes a project's mirrors: the publish drain, a oneshot unit
740 # per project that runs as the git user. Whatever moves a ref writes the
741 # move into a queue directory in the repository, as the line post-receive
742 # reads: old, new, ref. A path unit watches the queue, and when it holds
743 # anything, starts the drain. A push queues its moves from post-receive,
744 # through the mirror hook above. The integrator moves refs with
745 # update-ref, which runs no post-receive hook, so it queues each landing
746 # itself (integrator/bus.go). It runs as its own user, which does not hold
747 # the git user's mirror credentials and must not. valley-init queues one
748 # push of each mirrored project too, so a newly declared mirror is pushed
749 # without waiting for a move (publishQueueCommands, below).
750 #
751 # A single publisher is what keeps a mirror from being rewound. git reads
752 # the local refs before it contacts the mirror, so two pushers running at
753 # once can rewind it: one reads an old main and stalls, the other pushes a
754 # newer main, and the first then force-pushes its old main over it.
755 # systemd never runs two instances of one unit at the same time, so the
756 # drain's pushes for a project never overlap, and nothing else pushes.
757 # The drain lists the queue before git reads any ref, and deletes only what
758 # it listed, after the push succeeds. A move is queued after its ref moved,
759 # so the push covers every listed move. A move queued during the push stays
760 # for the next run, which pushes the newer main. No lock is taken: the
761 # drain runs only as the unit. To publish by hand, start the unit
762 # (systemctl start valley-publish@<project>), never the script.
763 #
764 # A run that fails leaves the queue as it was, and systemd runs it again
765 # after a delay (the unit, further down). So a failed mirror push does not
766 # wait for another move to be retried. Repeating a push is harmless: it
767 # pushes the current main, whatever the queue records.
768 #
769 # The bus is not the drain's business. A push publishes its ref-updated
770 # events from post-receive, through the bus hook below. The integrator
771 # publishes its landing's ref-updated event itself. So a mirror outage, and
772 # the drain's retries, never delay an event.
773 #
774 # The alternatives fall to the user split. Calling the post-receive
775 # dispatcher from the integrator would push as the integrator's user, and
776 # so would a reference-transaction hook, which runs as whoever ran git; it
777 # would also fire inside every push and for every bookkeeping ref the
778 # integrator writes. Starting a unit directly would take a polkit grant
779 # and carry no record of what moved. The queue costs one directory, the
780 # path unit is woken by inotify rather than a poll, and the queue is
781 # durable, so a move queued while the host goes down is published after.
782 publishQueueName = "valley-publish-queue";
783
784 # The projects with a publish queue and a drain: every one with mirrors,
785 # and every one the integrator serves. The integrator queues its landings
786 # whether or not the project has mirrors. A drain with no mirrors to push
787 # only empties the queue.
788 publishedProjects = lib.filterAttrs (
789 name: p: p.mirrors != [ ] || (cfg.integrator.enable && integratedProjects ? ${name})
790 ) gitProjects;
791
792 # The drain, per project. Its working directory is the repository. It runs
793 # synchronously: the unit is already detached from the push or the
794 # landing, and a detached child would be killed with the oneshot's cgroup
795 # when it exits.
796 publishDrain =
797 name: p:
798 pkgs.writeShellScript "valley-publish-${name}" ''
799 # Managed by services.valley — push the moves queued on ${name} to its mirrors.
800 shopt -s nullglob
801 # Listed before the pusher reads any ref, so the push covers them all.
802 moves=( ${publishQueueName}/* )
803 [ "''${#moves[@]}" -gt 0 ] || exit 0
804 ${lib.optionalString (p.mirrors != [ ]) "${mirrorPusher name p.mirrors} || exit 1"}
805 # A move that cannot be deleted fails the run, so systemd retries it
806 # after a delay. A run that succeeded would leave the queue non-empty,
807 # and the path unit would start the drain again at once, over and over.
808 rm -f -- "''${moves[@]}" || exit 1
809 '';
810
811 # Every drain, by project name, so the template unit runs its instance's.
812 publishDrains = pkgs.linkFarm "valley-publish-drains" (
813 lib.mapAttrsToList (name: p: {
814 inherit name;
815 path = publishDrain name p;
816 }) publishedProjects
817 );
818
819 # The queue directory of every published project. The integrator's
820 # projects also get it group-shared, with the rest of the repository.
821 #
822 # Every run of valley-init also queues one push for each project with
823 # mirrors and a main: an empty entry, a push with no move recorded. So a
824 # mirror declared on a project that already has history is pushed when
825 # the declaration is activated, not at the project's next move. It
826 # queues on every run rather than keeping a record of what each mirror
827 # was last sent, because a repeated push is harmless. A project with no
828 # main has nothing to publish, and its push would fail and retry until
829 # it had one, so its first move queues its first push instead. Only git
830 # saying main is absent (rev-parse's 1) skips the push: a repository git
831 # cannot read is queued, so the drain fails and logs git's reason. A
832 # push that cannot be queued costs the mirror and not the host, so it
833 # warns.
834 publishQueueCommands = lib.concatStrings (
835 lib.mapAttrsToList (
836 name: p:
837 let
838 repo = lib.escapeShellArg "${cfg.dataDir}/${name}.git";
839 queue = lib.escapeShellArg "${cfg.dataDir}/${name}.git/${publishQueueName}";
840 in
841 ''
842 mkdir -p ${queue}
843 ''
844 + lib.optionalString (p.mirrors != [ ]) ''
845 absent=0
846 git -C ${repo} rev-parse --verify --quiet refs/heads/main >/dev/null || absent=$?
847 if [ "$absent" -ne 1 ]; then
848 : >${queue}/"$(date +%s%N)-declared" ||
849 echo "valley-init: could not queue a push of ${name} to its mirrors; they are pushed at its next move" >&2
850 fi
851 ''
852 ) publishedProjects
853 );
854
855 # The post-receive.d hook that publishes a push's ref-updated events. The
856 # publisher runs detached (setsid, inheriting the updates on stdin), so a
857 # bus problem can only ever cost a log line — never block or fail the
858 # push. git is the source of truth; the bus is the replaceable component.
859 busEventHook = pkgs.writeShellScript "valley-bus-events" ''
860 # Managed by services.valley — project ref updates onto the event bus.
861 ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1
862 exit 0
863 '';
864
865 # The post-receive.d hook that marks the check worker due. It runs in the
866 # push, after the refs moved, so it does nothing slow: it reads the moves
867 # and creates one empty file, and it never fails the push. A push of
868 # nothing but knots or integration bookkeeping marks nothing, since the
869 # worker does not read those refs. Every other ref is a mark, so a ref
870 # the worker comes to read is covered without a change here. The
871 # worker's own evidence marks it too, and the pass that follows finds
872 # the evidence and builds nothing. noclobber makes the redirection
873 # O_EXCL, and a due that is there already is a mark already made. A
874 # mark that fails is logged; the worker's timer reads the push later.
875 wakeHook = pkgs.writeShellScript "valley-wake" ''
876 # Managed by services.valley — marks the check worker due.
877 due=${lib.escapeShellArg "${workerWakeDir}/due"}
878 marks=
879 while read -r old new ref; do
880 case "$ref" in
881 refs/the-valley/knots | refs/the-valley/knots/* | \
882 refs/the-valley/integration-outcomes/* | refs/the-valley/integration-landings/*) ;;
883 *) marks=1 ;;
884 esac
885 done
886 [ -n "$marks" ] || exit 0
887 set -C
888 { : > "$due"; } 2>/dev/null || [ -e "$due" ] || { : > "$due"; } 2>/dev/null || [ -e "$due" ] ||
889 ${pkgs.util-linux}/bin/logger -t valley-wake "could not mark the check worker due in ${workerWakeDir}" || true
890 exit 0
891 '';
892
893 # The post-receive.d hook that marks a project's integrator due. Like the
894 # worker's, it runs in the push after the refs moved, reads the moves,
895 # creates at most a few empty files, and exits 0 whatever happens: the
896 # dispatcher stops at the first hook that fails, and the hooks after it
897 # must still run. A push of nothing but knots, integration bookkeeping or
898 # the signers publication marks nothing, since no controller decides
899 # from those refs; the compiled signers file is what it reads, and a
900 # change to it waits for the interval. Every other ref marks the
901 # project's own controller. In the instance project, a push that moves
902 # the floor's ref also marks every controller that reads the floor, and
903 # nothing else is marked across projects. A mark that fails is logged,
904 # and the controller's interval reads the push later.
905 integratorWakeHook =
906 name:
907 pkgs.writeShellScript "valley-integrator-wake-${name}" ''
908 # Managed by services.valley — marks the integrator for ${name} due.
909 mark() {
910 { set -C; : > "$1/due"; } 2>/dev/null || [ -e "$1/due" ] ||
911 ${pkgs.util-linux}/bin/logger -t valley-integrator-wake "could not mark the integrator due in $1" || true
912 }
913 own=
914 floor=
915 while read -r old new ref; do
916 case "$ref" in
917 refs/the-valley/knots | refs/the-valley/knots/* | refs/the-valley/signers | \
918 refs/the-valley/integration-outcomes/* | refs/the-valley/integration-inputs/* | \
919 refs/the-valley/integration-landings/*) ;;
920 ${floorRef}) own=1 floor=1 ;;
921 *) own=1 ;;
922 esac
923 done
924 [ -z "$own" ] || mark ${lib.escapeShellArg (integratorWakeDir name)}
925 ${lib.optionalString (name == cfg.integrator.instanceProject) (
926 lib.concatMapStrings (
927 r: "[ -z \"$floor\" ] || mark ${lib.escapeShellArg (integratorWakeDir r)}\n"
928 ) floorReaders
929 )}
930 exit 0
931 '';
932
933 # Integrator-wake-hook wiring, one symlink per repo, by the bus hook's
934 # rules: every project a controller serves gets it, and every other
935 # repository loses a store symlink of the name.
936 integratorWakeHookCommands = lib.concatMapStrings (
937 name:
938 let
939 ihook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-integrator-wake";
940 in
941 if cfg.integrator.enable && integratedProjects ? ${name} then
942 ''
943 ihook=${ihook}
944 if [ -L "$ihook" ]; then
945 case "$(readlink "$ihook")" in
946 /nix/store/*) ln -sfn ${integratorWakeHook name} "$ihook" ;;
947 esac
948 elif [ ! -e "$ihook" ]; then
949 ln -s ${integratorWakeHook name} "$ihook"
950 fi
951 ''
952 else
953 ''
954 ihook=${ihook}
955 if [ -L "$ihook" ]; then
956 case "$(readlink "$ihook")" in
957 /nix/store/*) rm -f "$ihook" ;;
958 esac
959 fi
960 ''
961 ) repoNames;
962
963 # Wake-hook wiring, one symlink per repo, by the bus hook's rules: the
964 # worker's projects and the instance project get it, and every other
965 # repository loses a store symlink of the name.
966 wakeHookCommands = lib.concatMapStrings (
967 name:
968 let
969 whook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-wake";
970 in
971 if cfg.worker.enable && lib.elem name wakeProjects then
972 ''
973 whook=${whook}
974 if [ -L "$whook" ]; then
975 case "$(readlink "$whook")" in
976 /nix/store/*) ln -sfn ${wakeHook} "$whook" ;;
977 esac
978 elif [ ! -e "$whook" ]; then
979 ln -s ${wakeHook} "$whook"
980 fi
981 ''
982 else
983 ''
984 whook=${whook}
985 if [ -L "$whook" ]; then
986 case "$(readlink "$whook")" in
987 /nix/store/*) rm -f "$whook" ;;
988 esac
989 fi
990 ''
991 ) repoNames;
992
993 # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks:
994 # only ever installs, updates, or removes a store symlink — a hand-written
995 # hook of the same name is left alone.
996 busHookCommands = lib.concatMapStrings (
997 name:
998 let
999 bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus";
1000 in
1001 if cfg.bus.enable then
1002 ''
1003 bhook=${bhook}
1004 if [ -L "$bhook" ]; then
1005 case "$(readlink "$bhook")" in
1006 /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;;
1007 esac
1008 elif [ ! -e "$bhook" ]; then
1009 ln -s ${busEventHook} "$bhook"
1010 fi
1011 ''
1012 else
1013 ''
1014 bhook=${bhook}
1015 if [ -L "$bhook" ]; then
1016 case "$(readlink "$bhook")" in
1017 /nix/store/*) rm -f "$bhook" ;;
1018 esac
1019 fi
1020 ''
1021 ) repoNames;
1022
1023 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
1024 # a store symlink — a hand-written hook of the same name is left alone.
1025 mirrorHookCommands = lib.concatStrings (
1026 lib.mapAttrsToList (
1027 name: p:
1028 let
1029 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
1030 in
1031 if p.mirrors != [ ] then
1032 ''
1033 mhook=${mhook}
1034 if [ -L "$mhook" ]; then
1035 case "$(readlink "$mhook")" in
1036 /nix/store/*) ln -sfn ${mirrorHook name} "$mhook" ;;
1037 esac
1038 elif [ ! -e "$mhook" ]; then
1039 ln -s ${mirrorHook name} "$mhook"
1040 fi
1041 ''
1042 else
1043 ''
1044 mhook=${mhook}
1045 if [ -L "$mhook" ]; then
1046 case "$(readlink "$mhook")" in
1047 /nix/store/*) rm -f "$mhook" ;;
1048 esac
1049 fi
1050 ''
1051 ) gitProjects
1052 );
1053
1054 # The environment variable carrying the pushing key's principal name. The
1055 # git user's shell sets it from the tag on the authenticated key's own
1056 # authorized_keys entry, and the pre-receive hook reads it.
1057 principalEnv = "VALLEY_PRINCIPAL";
1058
1059 authorizedKeyLine =
1060 k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}'';
1061
1062 # What valley-init does to converge the host: create missing repositories
1063 # and (re)wire the managed hooks. Its last step refuses to report the host
1064 # converged over anything that would run instead of the push policy.
1065 valleyInitBody = ''
1066 conflicts=0
1067
1068 repos=( ${lib.escapeShellArgs repoNames} )
1069 for name in "''${repos[@]}"; do
1070 repo="${cfg.dataDir}/$name.git"
1071 # Check HEAD rather than the directory itself so a pre-existing
1072 # empty directory still gets initialized.
1073 if [ ! -e "$repo/HEAD" ]; then
1074 git init --bare --initial-branch=main "$repo"
1075 fi
1076
1077 # Replacement refs make one object stand in for another wherever
1078 # git looks it up. No push may write one, and every reader that
1079 # makes a decision disables them, but a ref written before the
1080 # hook refused them is still there. It is reported on every
1081 # activation and left in place: what it is evidence of is the
1082 # operator's to read before anyone deletes it.
1083 replaced="$(git -C "$repo" for-each-ref --format=' %(refname) -> %(objectname)' refs/replace/)" || replaced=""
1084 if [ -n "$replaced" ]; then
1085 printf 'valley-init: %s holds replacement refs, which no push may write; inspect each and delete it with git update-ref -d:\n%s\n' "$repo" "$replaced" >&2
1086 fi
1087
1088 # Hook scaffolding: post-receive dispatches to post-receive.d/.
1089 # Only manage the hook if it is absent or already ours (a store
1090 # symlink) — a hand-written hook is left alone.
1091 mkdir -p "$repo/hooks/post-receive.d"
1092 hook="$repo/hooks/post-receive"
1093 if [ -L "$hook" ]; then
1094 case "$(readlink "$hook")" in
1095 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
1096 esac
1097 elif [ ! -e "$hook" ]; then
1098 ln -s ${postReceiveDispatch} "$hook"
1099 fi
1100 done
1101
1102 # Per-project push-mirror hooks, and the queue they write.
1103 ${mirrorHookCommands}
1104 ${publishQueueCommands}
1105
1106 # The one structural invariant, on every project the host serves.
1107 ${protectHookCommands}
1108
1109 # The ref-updated publisher hook, on every repo when the bus is on.
1110 ${busHookCommands}
1111 ${wakeHookCommands}
1112 ${integratorWakeHookCommands}
1113
1114 # The project list, published in the instance repository for clients to
1115 # discover this host's projects by (valley changes --all): a blob at
1116 # ${projectsRef} naming every enabled git project, one per line,
1117 # sorted, and nothing else. A host without an instance repository
1118 # publishes nothing. The name of every project is disclosed to whoever
1119 # can read the instance repository. No push may write the ref, since
1120 # the hook refuses every refs/the-valley/* it does not name, so init is
1121 # its only writer. It is written before the share sweep below, which
1122 # then gives the new object the group's permissions. A list that cannot
1123 # be written costs discovery and not the host, so it warns.
1124 ${lib.optionalString (instanceRepo != null) ''
1125 {
1126 projects="$(printf '%s\n' ${lib.escapeShellArgs (lib.sort lib.lessThan repoNames)} |
1127 git -C ${instanceRepo} hash-object -w --stdin)" &&
1128 git -C ${instanceRepo} update-ref ${projectsRef} "$projects"
1129 } || echo "valley-init: could not publish the project list at ${projectsRef} in ${instanceRepo}; clients cannot discover this host's projects until it is" >&2
1130 ''}
1131
1132 # Group-shared repositories, on what the integrator serves.
1133 ${lib.optionalString cfg.integrator.enable integratorShareCommands}
1134
1135 if [ "$conflicts" -ne 0 ]; then
1136 echo "valley-init: refusing to report this host converged: the push policy is not what every repository runs" >&2
1137 exit 1
1138 fi
1139 '';
1140
1141 # The configuration a convergence is of: the init script itself, which
1142 # names every hook and every policy file it wires. valley-init records it
1143 # when it converges, and the git user's shell lets a push through only
1144 # while the record names the configuration the shell was rendered with.
1145 convergenceId = builtins.substring 0 32 (builtins.hashString "sha256" valleyInitBody);
1146
1147 # The record, in the git user's home: valley-init writes it, and nothing
1148 # a session reaches can. A dot file never collides with a repository,
1149 # because project names begin with an alphanumeric.
1150 convergedRecord = "${cfg.dataDir}/.valley-converged";
1151
1152 # The operator's hold on pushes: while this file exists, the git user's
1153 # shell refuses every push, whatever valley-init has recorded. valley-init
1154 # never touches it, so a hold placed before a deploy outlasts the
1155 # convergence and lasts until the operator removes it — the window a
1156 # deploy's audits need.
1157 pushHold = "${cfg.dataDir}/.valley-hold";
1158
1159 # The git user's login shell (valleyhook shell). sshd runs it for every
1160 # session, and it names the key files sshd authorizes the git user's keys
1161 # from, in sshd's order, so it can find the authenticated key's tag.
1162 gitShell = pkgs.writeShellScriptBin "valley-git-shell" ''
1163 exec ${valleyhookPackage}/bin/valleyhook shell \
1164 --converged ${convergedRecord} \
1165 --expect ${convergenceId} \
1166 --hold ${pushHold} \
1167 --authorized-keys /etc/ssh/authorized_keys.d/${cfg.user} ${
1168 lib.optionalString cfg.identity.enable "--authorized-keys ${identityAuthorizedKeys}"
1169 } \
1170 ${cfg.telemetry.shellFlags} \
1171 -- "$@"
1172 '';
1173
1174 # The program every project's pre-receive hook runs: the whole of the ref
1175 # policy (valleyhook/), built by this flake.
1176 valleyhookPackage = cfg.packages.valleyhook;
1177 pushreasonPackage = cfg.packages.pushreason;
1178
1179 # The grants declared by hand, in the format the compiler writes, so the
1180 # hook reads one format whichever wrote it. The holders of the approve
1181 # grant are one set under either option, written under the name request
1182 # the way the compiler writes them, and a principal named in both is
1183 # written once.
1184 declaredGrants = pkgs.writeText "valley-grants" (
1185 ''
1186 # Declared in services.valley.grants — do not edit.
1187 ''
1188 + lib.concatMapStrings (principal: "request ${principal}\n") (
1189 lib.unique (cfg.grants.approve ++ cfg.grants.request)
1190 )
1191 + lib.concatMapStrings (principal: "restack ${principal}\n") cfg.grants.restack
1192 );
1193
1194 # Every file the hook reads grants from. The compiled file is added to the
1195 # declared one rather than replacing it, the same way the compiled keys
1196 # are added to the declared keys: a compilation can only ever grant more.
1197 grantFiles = [ declaredGrants ] ++ lib.optional cfg.identity.enable identityGrants;
1198
1199 # The keys a pushed attestation's signature is checked against: the ones
1200 # a controller accepts evidence from. An attestation no controller here
1201 # would accept cannot take a name in the attestation namespace, and a host
1202 # that names no such keys accepts no attestation at all.
1203 hookVerifiers = lib.optional (knownSigners != "") knownSigners;
1204
1205 # What each project declares about pushes, as valleyhook reads it: the
1206 # protected refs and their writers, empty for a project that declares no
1207 # protection, and the project's named grants. A project that retains its
1208 # change records says so too; one that does not leaves the key out, and
1209 # valleyhook reads it as false.
1210 pushPolicies = lib.mapAttrs (
1211 _: p:
1212 {
1213 refs = p.protection.refs or [ ];
1214 writers = p.protection.writers or [ ];
1215 grants = p.grants or { };
1216 }
1217 // lib.optionalAttrs (p.retainChangeRecords or false) { retainChangeRecords = true; }
1218 ) gitProjects;
1219
1220 pushPolicy =
1221 name: _:
1222 pkgs.writeText "valley-push-policy-${name}.json" (builtins.toJSON pushPolicies.${name});
1223
1224 # The pre-receive hook: the one structural git invariant
1225 # (archive/design/architecture.md, archive/design/contribute.md), which is what a push may
1226 # write. It is installed on every project the host serves. Replacement
1227 # refs, notes and the valley's own namespace take no push, but for the
1228 # namespaces below; a symbolic ref takes none; topic branches are
1229 # open; an attestation ref holds only what its name says, and takes
1230 # added notes but no other change and no delete; an integration request
1231 # and an approval take the approve grant; a change record moves only by
1232 # the transitions the hook allows, and a project that retains its records
1233 # takes no delete of one; the plan graph, refs/the-valley/knots, takes any named
1234 # principal's write of one commit on its tip that keeps the graph valid;
1235 # every other ref, tags included, takes a named grant of the project; and
1236 # a protected ref also takes a declared writer. All policy beyond this lives in the integrator.
1237 #
1238 # The rules are valleyhook's, in Go, and this script is only how git
1239 # reaches it. It hands over what the policy is a function of: the pushing
1240 # principal, the project's declared push policy, the grants, the keys an
1241 # attestation is checked against, and the hook a project composes after
1242 # it, if it declares one.
1243 #
1244 # A declaration usually names no writer at all, and then the protected
1245 # refs take no push from anyone. That is the norm, not a
1246 # misconfiguration: the integrator writes the ref locally, and a local
1247 # write is not a push.
1248 #
1249 # Pushes arrive over SSH as one shared git user, so the unix account
1250 # behind a push says nothing about who pushed. The principal comes from
1251 # the key instead: services.valley.authorizedKeys tags each key's
1252 # authorized_keys entry, the git user's shell reads the tag off the entry
1253 # of the key sshd authenticated and puts it in the environment of the
1254 # receive-pack this hook runs under, and an untagged key has no principal
1255 # at all. The client cannot supply the tag itself: the shell drops any it
1256 # arrives with, and the assertions below hold sshd to offering no client
1257 # environment that could carry it.
1258 #
1259 # This governs pushes, which is every write that crosses the host
1260 # boundary. It does not govern writes made on the host: the integrator
1261 # updates refs locally, as could anyone holding the git user's shell.
1262 # Local access is the host's own boundary, not this hook's.
1263 protectHook =
1264 name: p:
1265 pkgs.writeShellScript "valley-protect-${name}" ''
1266 # Managed by services.valley — do not edit.
1267 exec ${valleyhookPackage}/bin/valleyhook pre-receive \
1268 --project ${lib.escapeShellArg name} \
1269 --policy ${pushPolicy name p} \
1270 ${lib.concatMapStringsSep " " (f: "--grants ${f}") grantFiles} \
1271 ${lib.concatMapStringsSep " " (f: "--known-signers ${f}") hookVerifiers} \
1272 ${lib.optionalString (cfg.extraPreReceive ? ${name}) "--then ${cfg.extraPreReceive.${name}}"} \
1273 --principal="''${${principalEnv}:-}"
1274 '';
1275
1276 # Per-project pre-receive wiring, on every project the host serves. A
1277 # hook that is not this module's is a hook that would run instead of the
1278 # push policy, so valley-init refuses to leave one in place: it says so,
1279 # and the activation fails once everything else is wired. The one
1280 # exception is a hook identical to the one the project composes after the
1281 # policy (services.valley.extraPreReceive), which is checked byte for byte
1282 # and then replaced, since the managed hook runs it. A store symlink is
1283 # this module's, whichever store path it names, and is re-pointed.
1284 #
1285 # core.hooksPath moves where git looks for hooks at all, from any scope
1286 # the git user reads — the repository's config, the user's, the system's,
1287 # or a file one of them includes. A repository whose hooks path is set at
1288 # all, to an empty value included, is refused the same way, with no
1289 # exception.
1290 protectHookCommands = lib.concatStrings (
1291 lib.mapAttrsToList (name: p: ''
1292 served=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
1293 phook="$served/hooks/pre-receive"
1294 managed=${protectHook name p}
1295 composed=${lib.escapeShellArg (toString (cfg.extraPreReceive.${name} or ""))}
1296 if [ -L "$phook" ] && [[ "$(readlink "$phook")" == /nix/store/* ]]; then
1297 ln -sfn "$managed" "$phook"
1298 elif [ ! -e "$phook" ] && [ ! -L "$phook" ]; then
1299 ln -s "$managed" "$phook"
1300 elif [ -n "$composed" ] && [ -f "$phook" ] && cmp -s "$phook" "$composed"; then
1301 echo "valley-init: ${name}: the pre-receive hook in $served is the one services.valley.extraPreReceive.${name} composes after the push policy, so the managed hook replaces it and runs it" >&2
1302 ln -sfn "$managed" "$phook"
1303 else
1304 echo "valley-init: ${name}: $phook is a pre-receive hook this module did not write, and git would run it instead of the push policy. Declare it as services.valley.extraPreReceive.${name} to run it after the policy, or remove it." >&2
1305 conflicts=1
1306 fi
1307 # Exit status 1 is the one answer that means unset. A value, an
1308 # empty one included — git then looks for hooks relative to where it
1309 # runs — and a configuration git cannot read are all refused.
1310 hooks_path="$(git -C "$served" config --get core.hooksPath)" && status=0 || status=$?
1311 if [ "$status" -ne 1 ]; then
1312 echo "valley-init: ${name}: core.hooksPath is set for $served (to '$hooks_path'), so git would look for hooks there and the push policy would not run. Remove the setting, wherever it is." >&2
1313 conflicts=1
1314 fi
1315 '') gitProjects
1316 );
1317
1318 # sshd's environment patterns, for the assertions that hold it to
1319 # accepting no client environment the push boundary reads. `*` and `?` are
1320 # the only wildcards an AcceptEnv pattern has, and a pattern is matched
1321 # as written: variable names are case-sensitive.
1322 sshPatternMatches =
1323 pattern: name:
1324 builtins.match (lib.concatMapStrings (
1325 c:
1326 if c == "*" then
1327 ".*"
1328 else if c == "?" then
1329 "."
1330 else if builtins.match "[A-Za-z0-9_]" c != null then
1331 c
1332 else
1333 "\\${c}"
1334 ) (lib.stringToCharacters pattern)) name != null;
1335
1336 # Whether some name beginning with prefix matches pattern: the pattern
1337 # walked over the prefix, with the rest of the name free.
1338 sshPatternMatchesSomeName =
1339 pattern: prefix:
1340 if prefix == "" then
1341 true
1342 else if pattern == "" then
1343 false
1344 else
1345 let
1346 c = builtins.substring 0 1 pattern;
1347 rest = builtins.substring 1 (-1) pattern;
1348 next = builtins.substring 1 (-1) prefix;
1349 in
1350 if c == "*" then
1351 sshPatternMatchesSomeName rest prefix || sshPatternMatchesSomeName pattern next
1352 else if c == "?" || c == builtins.substring 0 1 prefix then
1353 sshPatternMatchesSomeName rest next
1354 else
1355 false;
1356
1357 # A variable the push boundary reads, and no client may supply: the
1358 # principal, and anything git reads its configuration, hooks or objects
1359 # from.
1360 boundaryVariable = pattern: sshPatternMatches pattern principalEnv || sshPatternMatchesSomeName pattern "GIT_";
1361
1362 # A refname glob as the declaration writes one, where `*` crosses path
1363 # separators (schema/valley.cue).
1364 refPatternMatches =
1365 pattern: ref:
1366 builtins.match (lib.concatMapStrings (
1367 c:
1368 if c == "*" then
1369 ".*"
1370 else if builtins.match "[A-Za-z0-9/_-]" c != null then
1371 c
1372 else
1373 "\\${c}"
1374 ) (lib.stringToCharacters pattern)) ref != null;
1375
1376 # Whether ref is a full ref name, which the identity registry is read at.
1377 # It opens with refs/ and holds letters, digits, dots, dashes, underscores
1378 # and slashes alone. git check-ref-format accepts it: no component is
1379 # empty, opens with a dot or ends with .lock, and it holds no ".." and
1380 # does not end with a dot. readaccess.ValidRef accepts every name this
1381 # accepts.
1382 fullRefName =
1383 ref:
1384 builtins.match "refs/[A-Za-z0-9._/-]+" ref != null
1385 && !(lib.hasInfix ".." ref)
1386 && !(lib.hasSuffix "." ref)
1387 && lib.all (part: part != "" && !(lib.hasPrefix "." part) && !(lib.hasSuffix ".lock" part)) (
1388 lib.splitString "/" ref
1389 );
1390
1391 # Every value sshd is given for one keyword, from the settings and from
1392 # every line of extraConfig, inside a Match block or not. The keyword is
1393 # matched in any case, as sshd matches it, with or without `=` after it;
1394 # the values are kept as written, because sshd's patterns and variable
1395 # names are case-sensitive. Values are split on any whitespace, tabs
1396 # included, as sshd splits them. Quoting and escapes are not unpicked
1397 # here: a value holding a quote or a backslash is refused below instead,
1398 # because a reading that differed from sshd's would be a hole.
1399 sshdValues =
1400 keyword:
1401 let
1402 settings = config.services.openssh.settings;
1403 word = x: if lib.isBool x then (if x then "yes" else "no") else toString x;
1404 words = v: lib.filter (w: lib.isString w && w != "") (builtins.split "[[:space:]]+" v);
1405 fromSettings = lib.concatMap (
1406 k:
1407 let
1408 v = settings.${k};
1409 in
1410 if lib.isList v then lib.concatMap (x: words (word x)) v else words (word v)
1411 ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings));
1412 fromExtra = lib.concatMap (
1413 line:
1414 let
1415 m = builtins.match "[[:space:]]*([A-Za-z]+)[[:space:]]*=?[[:space:]]*(.*)" line;
1416 in
1417 if m == null || lib.toLower (lib.head m) != lib.toLower keyword then
1418 [ ]
1419 else
1420 words (lib.elemAt m 1)
1421 ) (lib.splitString "\n" config.services.openssh.extraConfig);
1422 in
1423 fromSettings ++ fromExtra;
1424
1425 # Every key line the git user's declared authorized_keys holds, from this
1426 # module and from any other, with the principal its tag names ("" for
1427 # none) and the key itself.
1428 declaredKeyEntries = lib.concatMap (
1429 line:
1430 let
1431 key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line;
1432 tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line;
1433 in
1434 lib.optional (key != null) {
1435 key = lib.elemAt key 3;
1436 principal = if tag == null then "" else lib.head tag;
1437 }
1438 ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys;
1439
1440 # Keys declared more than once under different tags. sshd authorizes a
1441 # key by the first entry that names it, so which principal such a key
1442 # pushes as depends on file order; the assertion below refuses it.
1443 conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) (
1444 lib.groupBy (e: e.key) declaredKeyEntries
1445 );
1446
1447 # The declared key lines, for the compiler: a compiled key that is also
1448 # declared under another tag is refused there, for the same reason.
1449 declaredKeysFile = pkgs.writeText "valley-declared-keys" (
1450 lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys
1451 );
1452
1453 # The onMain bindings (services.valley.onMain). Each runs a bridge
1454 # (../onmain) under a unit and a user of the same name, and a path unit of
1455 # that name that starts the bound unit. The bridge writes the commit to
1456 # run and its request in its runtime directory, which only its user can
1457 # write. The bound unit's environment file is root's, in a directory only
1458 # root can write: systemd imports every assignment in such a file, so the
1459 # bridge's user never writes one.
1460 onMainBridge = name: "valley-on-main-${name}";
1461 onMainCommit = name: "/run/${onMainBridge name}/commit";
1462 onMainRequest = name: "/run/${onMainBridge name}/request";
1463 onMainEnvironmentDir = "/run/valley-on-main";
1464 onMainEnvironment = name: "${onMainEnvironmentDir}/${name}.environment";
1465 onMainRepo = b: "${toString cfg.dataDir}/${b.project}.git";
1466
1467 # A bound unit's name: a service named whole, in characters that stand in
1468 # a unit file and on a command line without quoting. No @, so no
1469 # template's instance: the module would render one as a unit of its own,
1470 # without the template's command.
1471 onMainUnitName = "[A-Za-z0-9_.:][A-Za-z0-9_.:-]*[.]service";
1472 onMainService = b: config.systemd.services.${lib.removeSuffix ".service" b.unit};
1473
1474 # Every bridge, path unit and bound unit, for telemetry's on-main source.
1475 onMainUnits = lib.concatLists (
1476 lib.mapAttrsToList (name: b: [
1477 "${onMainBridge name}.service"
1478 "${onMainBridge name}.path"
1479 b.unit
1480 ]) cfg.onMain
1481 );
1482
1483 # Units bound by more than one binding.
1484 onMainBoundTwice = lib.attrNames (
1485 lib.filterAttrs (_: names: lib.length names > 1) (
1486 lib.groupBy (name: cfg.onMain.${name}.unit) (lib.attrNames cfg.onMain)
1487 )
1488 );
1489in
1490{
1491 # Telemetry (./telemetry.nix), given what this module derives from the
1492 # declaration, so its catalog names the units this host runs.
1493 imports = [
1494 (import ./telemetry.nix {
1495 inherit
1496 integratedProjects
1497 publishedProjects
1498 publishesSigners
1499 backupEnabled
1500 workerPackage
1501 attestPackage
1502 integratorPackage
1503 restackerPackage
1504 onMainUnits
1505 ;
1506 })
1507 ];
1508
1509 options.services.valley = {
1510 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
1511
1512 user = lib.mkOption {
1513 type = lib.types.str;
1514 default = "git";
1515 description = "System user that owns the repositories and accepts SSH pushes.";
1516 };
1517
1518 group = lib.mkOption {
1519 type = lib.types.str;
1520 default = "git";
1521 description = "Primary group of the valley git user.";
1522 };
1523
1524 dataDir = lib.mkOption {
1525 type = lib.types.path;
1526 default = "/srv/git";
1527 example = "/mnt/git";
1528 description = ''
1529 Directory holding the bare repositories, one `<name>.git` per
1530 project declared in {option}`services.valley.config`. Also the git
1531 user's home, so clone URLs are relative to it (`git@host:name.git`).
1532 Consumers typically point it at a dedicated dataset.
1533 '';
1534 };
1535
1536 authorizedKeys = lib.mkOption {
1537 type = lib.types.listOf (
1538 lib.types.either lib.types.str (
1539 lib.types.submodule {
1540 options = {
1541 key = lib.mkOption {
1542 type = lib.types.str;
1543 description = "The SSH public key, as it would appear in `authorized_keys`.";
1544 };
1545
1546 principal = lib.mkOption {
1547 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
1548 example = "integrator";
1549 description = ''
1550 Name of the principal this key acts as. Every push made
1551 with the key carries the name, and the pre-receive hook
1552 decides what the name may write: from the project's
1553 `protection` block and named grants in
1554 {option}`services.valley.config`, and from the grants the
1555 name holds ({option}`services.valley.grants`, and the
1556 registry's when it is compiled). Nothing else uses it.
1557 A key is declared once: the same key under two tags, or
1558 tagged and untagged, is refused.
1559 '';
1560 };
1561 };
1562 }
1563 )
1564 );
1565 default = [ ];
1566 example = lib.literalExpression ''
1567 [
1568 "ssh-ed25519 AAAA… someone@somewhere"
1569 {
1570 principal = "integrator";
1571 key = "ssh-ed25519 AAAA… integrator";
1572 }
1573 ]
1574 '';
1575 description = ''
1576 SSH public keys allowed to push/fetch as the git user. Access is
1577 host-level by design: every key can reach every project.
1578
1579 A key written as a plain string is anonymous — it can push, and it
1580 can write nothing protected. A key written as an attribute set
1581 names the principal it acts as, which is the only thing that can
1582 tell one pusher from another: pushes arrive as the shared git user,
1583 so identity has to ride on the key.
1584
1585 Which refs a principal may write is declared, not an option here:
1586 it is a statement about what the host serves, and lives in the
1587 project's `protection` block in
1588 {option}`services.valley.config`. Binding a name to keys is the
1589 machine half — the hand-written form of what the identity registry
1590 compiles (dcr-b87f6e8).
1591
1592 With {option}`services.valley.identity.enable` on, the compiled
1593 keys are added to what sshd reads and the keys here stay
1594 authorized beside them. The list is therefore the way back in when
1595 a compilation is wrong or has not happened yet, and it is never
1596 empty.
1597 '';
1598 };
1599
1600 extraPreReceive = lib.mkOption {
1601 type = lib.types.attrsOf lib.types.pathInStore;
1602 default = { };
1603 example = lib.literalExpression ''
1604 {
1605 app = pkgs.writeShellScript "app-pre-receive" ;
1606 }
1607 '';
1608 description = ''
1609 A further pre-receive hook per project, run after the push policy
1610 accepts a push, with the same input. It can refuse what the policy
1611 accepts and never accept what the policy refuses.
1612
1613 This is the one way to compose a hook with the managed one. A
1614 pre-receive hook the module did not write fails valley-init,
1615 because git would run it instead of the policy. A hook that is
1616 byte-for-byte the one declared here is the exception: valley-init
1617 replaces it with the managed hook, which runs it. The value is a
1618 store path, so what runs is exactly what was declared.
1619 '';
1620 };
1621
1622 # Grants held by hand. The registry names who holds a grant
1623 # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written
1624 # form of what it compiles, beside it the way the declared keys sit
1625 # beside the compiled ones.
1626 grants = {
1627 approve = lib.mkOption {
1628 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1629 default = [ ];
1630 example = [ "operator" ];
1631 description = ''
1632 Principals holding the approve grant (also accepted as
1633 {option}`services.valley.grants.request`): the ones whose pushes
1634 may file, replace and withdraw an integration request
1635 (`refs/the-valley/integration-requests/*`) on a protected
1636 project. The pre-receive hook refuses every other write to that
1637 namespace, so a principal named neither here, nor in
1638 {option}`services.valley.grants.request`, nor in the registry
1639 cannot file an integration request.
1640
1641 The two options are one grant. The holders are the principals
1642 named in either list, and a principal named in both holds the
1643 grant once.
1644
1645 The grant rides on push. Only a key sshd admits reaches the hook,
1646 so a principal named here also needs a key, declared in
1647 {option}`services.valley.authorizedKeys` or compiled from the
1648 registry.
1649
1650 With {option}`services.valley.identity.enable` on, the holders
1651 the registry names are added to these, and a compiled file can
1652 only ever add. The list is therefore how a host grants approve
1653 before its registry does — including to the operator who has to
1654 file the registry change that grants it.
1655 '';
1656 };
1657
1658 request = lib.mkOption {
1659 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1660 default = [ ];
1661 example = [ "operator" ];
1662 description = ''
1663 Principals holding the approve grant, under the name it had
1664 first. A principal named here holds exactly what one named in
1665 {option}`services.valley.grants.approve` holds, and the holders
1666 are the principals named in either list.
1667 '';
1668 };
1669
1670 restack = lib.mkOption {
1671 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1672 default = [ ];
1673 example = [ "valley-restacker" ];
1674 description = ''
1675 Principals holding the restack grant: the host restacker's. A
1676 holder that neither owns a change nor holds the approve grant may
1677 add exactly one version to the change's record while the change
1678 is ready, on the branch and under the title of its active version,
1679 with itself as the uploader. It may also write restack reports
1680 (`refs/the-valley/restack/main/<change-id>`). The grant permits
1681 no other record write and nothing on integration requests, and a
1682 holder keeps every ordinary power of a named principal.
1683
1684 The grant rides on push, like approve: a principal named here also
1685 needs a key. With {option}`services.valley.identity.enable` on,
1686 the holders the registry names are added to these. The list is
1687 how a host grants restack before its registry does; remove an
1688 entry once the registry grants the same principal.
1689 '';
1690 };
1691 };
1692
1693 config = lib.mkOption {
1694 type = lib.types.path;
1695 example = lib.literalExpression "./valley.cue";
1696 description = ''
1697 Path to the host's CUE declaration (`package valley`) — the
1698 canonical statement of what this valley host serves, validated
1699 against the shipped schema at build time. This is the single domain
1700 input: projects, their push mirrors, and the backup policy are
1701 declared here, never as Nix options.
1702 '';
1703 };
1704
1705 # The event bus. Machine options, not domain: whether this machine runs
1706 # a bus, where it listens, and where its storage lives. What gets
1707 # published onto it is defined portably in ../schema/events.cue.
1708 bus = {
1709 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
1710
1711 listen = lib.mkOption {
1712 type = lib.types.str;
1713 default = "127.0.0.1:4222";
1714 example = "192.0.2.10:4222";
1715 description = ''
1716 Address the bus listens on, `host:port`. Localhost by default:
1717 nothing off the host can reach the bus until the consumer widens
1718 this deliberately — e.g. to the host's private network address once a
1719 remote `valley tail` wants in. Local publishers (the ref-updated
1720 hook) connect to this same address, so it must be reachable from
1721 the host itself.
1722 '';
1723 };
1724
1725 storeDir = lib.mkOption {
1726 type = lib.types.path;
1727 default = "${cfg.dataDir}/.bus";
1728 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
1729 description = ''
1730 Directory holding the JetStream file storage. The default lives
1731 under {option}`services.valley.dataDir`; it can never collide
1732 with a repository because project names must start with an
1733 alphanumeric. The stream is a projection of git, rebuildable
1734 with `valley replay` — losing this directory costs one replay.
1735 '';
1736 };
1737 };
1738
1739 # The integrator (archive/design/roadmap.md, Phase 3): the controller that
1740 # lands a change once its evidence still transfers to the current tip.
1741 # Machine options only — whether this host runs controllers, who they
1742 # are, and how often they look. Which projects get one is not an option
1743 # either: it follows from which projects the declaration protects,
1744 # because a protected ref is exactly what a controller exists to write.
1745 integrator = {
1746 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
1747
1748 user = lib.mkOption {
1749 type = lib.types.str;
1750 default = "valley-integrator";
1751 description = ''
1752 System user the controllers run as. Deliberately not
1753 {option}`services.valley.user`: one unix identity per service is
1754 the split bd-500adf7 asks for, and this service begins it.
1755
1756 The account exists only to write the repositories it serves. It
1757 gets no shell and no SSH key, and its primary group is
1758 {option}`services.valley.group`, which is the whole of its
1759 permission model: {option}`services.valley.dataDir` is already
1760 group-readable, and each served repository is made group-shared
1761 (group write, setgid directories) so a controller can write
1762 refs, objects, and git's worktree metadata. Nothing else on the
1763 host belongs to that group, and the bus's store directory (mode
1764 0700) stays out of reach.
1765
1766 The key and signers files are the consumer's to provision; both
1767 must be readable by this user.
1768 '';
1769 };
1770
1771 signingKeyFile = lib.mkOption {
1772 type = lib.types.nullOr lib.types.path;
1773 default = null;
1774 example = "/run/agenix/valley-integrator-key";
1775 description = ''
1776 ed25519 private key the controllers sign their transfer
1777 statements with. A runtime path the consumer provisions (e.g.
1778 agenix), never a store path — the store is world-readable.
1779 '';
1780 };
1781
1782 knownSignersFile = lib.mkOption {
1783 type = lib.types.nullOr lib.types.path;
1784 default = null;
1785 example = "/var/lib/valley-instance/known_signers";
1786 description = ''
1787 File of verifier keys whose attestations count, one per line, in
1788 `attest key` format. This is the identity registry's interim
1789 compilation (dcr-b87f6e8), supplied directly for a host that does
1790 not compile one: turning on
1791 {option}`services.valley.identity.enable` renders the same file
1792 from the registry, and then this option must be left unset.
1793 Evidence signed by nobody in it does not transfer, which a
1794 controller reports per check rather than treating as a forgery.
1795 '';
1796 };
1797
1798 signerProjects = lib.mkOption {
1799 type = lib.types.attrsOf (lib.types.listOf lib.types.str);
1800 default = { };
1801 example = {
1802 "worker/attestations" = [ "app" ];
1803 };
1804 description = ''
1805 Signers whose attestations count only in the projects listed for
1806 them, by the name each signs under. A signer named here counts
1807 in its listed projects alone; in any other project a controller
1808 reports its evidence as signed by no signer it holds. An empty
1809 list lets the signer count nowhere. A signer not named here
1810 counts wherever the known-signers file lets it.
1811
1812 This is how a check worker's key, which every controller sharing
1813 the known-signers file would otherwise accept, is trusted only
1814 for the projects it builds. When
1815 {option}`services.valley.worker.enable` is on, the module lists
1816 {option}`services.valley.worker.projects` here under
1817 {option}`services.valley.worker.signerName`. A host's own entry
1818 for that name replaces the module's. The push hook still admits
1819 the worker's evidence everywhere; only the controllers restrict
1820 it.
1821
1822 List every other controller whose key the known-signers file
1823 holds, such as another host's integrator, with an empty list.
1824 A controller countersigns the attestations a landing carried,
1825 and its own signature never counts as check evidence here;
1826 another controller's counts only until it is listed.
1827
1828 The list is rendered into a file every controller reads at start.
1829 A host that publishes its signers publishes the file beside them,
1830 so a client can read the same restriction. Names and projects are
1831 words of printable ASCII with no space, and a name holds no plus
1832 and does not open with #. The list may not name the name the
1833 controllers sign under: a controller given such a list refuses to
1834 start.
1835 '';
1836 };
1837
1838 signingName = lib.mkOption {
1839 type = lib.types.nullOr lib.types.str;
1840 default = null;
1841 example = "integrator";
1842 description = ''
1843 The name a controller's transfer statements are signed under.
1844 Unset leaves the binary's own default, which is this host's
1845 attestations name — the machine signing as itself.
1846
1847 Set it to the name the identity registry publishes the
1848 integrator's key under. The note format's key hash binds the name
1849 to the key (dcr-de9d996), so a controller signing under one name
1850 while the registry publishes it under another produces notes no
1851 verifier can find a key for.
1852 '';
1853 };
1854
1855 instanceProject = lib.mkOption {
1856 type = lib.types.nullOr lib.types.str;
1857 default = null;
1858 example = "valley";
1859 description = ''
1860 The project whose served repository carries the group's floor —
1861 the instance policy layer every controller on this host composes
1862 against. A controller reads it from `policy/instance/` in that
1863 bare repository's integrated tip, and nothing is materialized on
1864 disk in between. It is also where the identity registry is read
1865 from, for the same reason and at the same altitude: both are the
1866 instance's, so a host serving that repository already holds the
1867 authoritative copy.
1868
1869 The floor is the instance repository's, read at the tip that has
1870 been integrated (dcr-f41f718); the instance repository is the
1871 group's own (dcr-b87f6e8). A host serving it is therefore already
1872 holding the authoritative copy.
1873
1874 What follows is a property of that design, and worth knowing
1875 before editing a floor. A change to it takes effect at the first
1876 pass after it lands on that ref, and never before. An edit in a
1877 branch, in a worktree, or in an integration request that has not
1878 been integrated governs nothing. There is no refresh to trigger
1879 and no staleness to wait out: landing is the whole of publishing
1880 a floor.
1881
1882 The project has to declare protection covering refs/heads/main,
1883 and the registry's ref when the identity compiler is on. Both
1884 are read from that tip, so a ref any push-capable key could move
1885 would hand every key the floor and the registry.
1886
1887 Every controller on the host reads the same repository, the
1888 controller serving that repository included. Both layers are
1889 resolved from the controller's own side — this one, and the
1890 project's `policy/project/` at the target tip — so a change can
1891 never supply the policy that gates it (bd-eaefe82).
1892
1893 Those two directories are the convention, and the module states
1894 neither: a controller takes each layer from the place the
1895 integrator defaults to, so a host declaration that says nothing
1896 about policy gets the layout the worked example lays out
1897 (dcr-f41f718).
1898 '';
1899 };
1900
1901 instancePolicy = lib.mkOption {
1902 type = lib.types.nullOr lib.types.path;
1903 default = null;
1904 example = "/var/lib/valley-instance/policy/instance";
1905 description = ''
1906 Directory of `*.cue` files holding the instance policy layer, for
1907 a host that serves no instance repository. It holds what
1908 `policy/instance/` in the instance repository holds. Set this or
1909 {option}`services.valley.integrator.instanceProject`, never both.
1910
1911 Keeping such a directory in step with the instance repository is
1912 the consumer's to arrange, which is the reason to prefer the
1913 project option wherever the host serves the repository.
1914 '';
1915 };
1916
1917 interval = lib.mkOption {
1918 type = lib.types.str;
1919 default = "15s";
1920 example = "1m";
1921 description = ''
1922 How long a controller waits after a pass before the next, when
1923 nothing starts one sooner. A push to the project, a floor moved
1924 in the instance project, and a landing by the controller itself
1925 each start a pass promptly. This interval is the recovery pass: it
1926 reads what a lost mark, a failed watch or a changed
1927 known-signers file left waiting, since integration requests are
1928 durable in git and the controller level-triggers over those refs.
1929 '';
1930 };
1931 };
1932
1933 # The build slice (oc-03b6f8c): caps on every build this machine's nix
1934 # daemon runs, whoever asked for it. A host decision of its own, and a
1935 # condition of the check worker, which builds through the daemon.
1936 buildSlice = {
1937 enable = lib.mkEnableOption ''
1938 capping every build the nix daemon on this host runs, for every user
1939 of it, together: the daemon runs in one slice with a CPU quota, a
1940 memory cap and no swap'';
1941
1942 cpuQuota = lib.mkOption {
1943 type = lib.types.str;
1944 default = "400%";
1945 example = "800%";
1946 description = ''
1947 The CPU time every build the daemon runs gets together, as
1948 systemd's CPUQuota: 400% is four CPUs' worth.
1949 '';
1950 };
1951
1952 memoryMax = lib.mkOption {
1953 type = lib.types.str;
1954 default = "8G";
1955 example = "16G";
1956 description = ''
1957 The memory every build the daemon runs gets together, as
1958 systemd's MemoryMax. The slice gets no swap. A build that takes
1959 the slice past it is ended by the kernel's OOM killer, which kills
1960 the process in the slice using the most memory: usually the
1961 build that went past, but any build in the slice can be the one
1962 killed.
1963 '';
1964 };
1965 };
1966
1967 # The check worker (oc-13c6bd6): a timer that runs one pass of
1968 # valley-worker over its projects, so ready changes have their
1969 # nix checks built before anyone approves them. Machine options only —
1970 # whether this host runs the worker, for which of its projects, under
1971 # which signing name, with how much build capacity, how often, and
1972 # where it keeps its state.
1973 worker = {
1974 enable = lib.mkEnableOption ''
1975 the valley check worker: a timer that builds the nix checks ready
1976 changes require and publishes the evidence, under its own key, for
1977 the projects selected by {option}`services.valley.worker.projects`,
1978 which defaults to every Git-enabled project with a protection block'';
1979
1980 projects = lib.mkOption {
1981 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1982 default = lib.attrNames integratedProjects;
1983 defaultText = lib.literalMD "every Git-enabled project in the host declaration that has a protection block";
1984 example = [ "app" ];
1985 description = ''
1986 The projects the worker builds evidence for. Each is a Git
1987 repository this host serves. Unset, the list is every Git-enabled
1988 project in the host declaration that has a protection block. This
1989 includes the instance project.
1990
1991 The worker builds evidence only for these projects. It also reads
1992 the instance repository for discovery, and any owning instance
1993 repository needed to load a project's policy floor.
1994
1995 When the host and the worker are enabled, the module defaults
1996 {option}`services.valley.integrator.signerProjects` for
1997 {option}`services.valley.worker.signerName` to this list. An
1998 explicit entry must name the same projects, or evaluation fails.
1999 When the worker is disabled, this option does not configure signer
2000 restrictions.
2001 '';
2002 };
2003
2004 signerName = lib.mkOption {
2005 type = lib.types.str;
2006 example = "worker/attestations";
2007 description = ''
2008 The name the worker signs its notes under. It is a name of the
2009 worker's own: never the operator's, and never the name the
2010 controllers sign under, which the module refuses.
2011
2012 Enrolled with the worker's key, it is what the known-signers file
2013 and the identity registry hold for the worker: the registry key's
2014 `signs`, and the name in the verifier line.
2015 '';
2016 };
2017
2018 buildSlots = lib.mkOption {
2019 type = lib.types.ints.positive;
2020 default = 1;
2021 example = 3;
2022 description = ''
2023 The most `nix build` processes the worker runs at once for
2024 distinct check derivations in one batch, as `valley-worker
2025 --slots`. Checks with the same derivation share one process.
2026
2027 ${workerCapacityBound}
2028 '';
2029 };
2030
2031 maxJobs = lib.mkOption {
2032 type = lib.types.ints.positive;
2033 default = 1;
2034 example = 2;
2035 description = ''
2036 Each worker `nix build` may run up to this many local derivation
2037 jobs at once, including dependencies of its check, as nix's
2038 `max-jobs` setting. During the build phase, the worker's
2039 concurrent builds therefore allow up to
2040 {option}`services.valley.worker.buildSlots` times this many such
2041 jobs. Other clients' jobs are additional.
2042
2043 ${workerCapacityBound}
2044 '';
2045 };
2046
2047 cores = lib.mkOption {
2048 type = lib.types.ints.positive;
2049 default = 4;
2050 example = 2;
2051 description = ''
2052 The `cores` hint each derivation's builder gets, as nix's `cores`
2053 setting. The builder reads it as `NIX_BUILD_CORES`, and a build
2054 that honours it may use that value to limit its own parallel
2055 jobs. It caps nothing.
2056
2057 ${workerCapacityBound}
2058 '';
2059 };
2060
2061 batches = lib.mkOption {
2062 type = lib.types.ints.positive;
2063 default = 2;
2064 example = 3;
2065 description = ''
2066 The most batches a pass runs at once, as `valley-worker
2067 --batches`. A batch is one ready change's missing checks, built by
2068 one `attest run`. While a long batch runs, a pass starts the next
2069 ready change's batch in a free slot, so a short change does not
2070 wait behind a long one.
2071
2072 At worst, the worker has this many times
2073 {option}`services.valley.worker.buildSlots` `nix build`
2074 processes at once, and each may build
2075 {option}`services.valley.worker.maxJobs` derivations at once:
2076 `batches × buildSlots × maxJobs` local derivation builds, besides
2077 the evaluations. They share {option}`services.valley.buildSlice.memoryMax`
2078 with the worker and the nix daemon. Batches overlap their builds,
2079 and their evaluations run together only while their estimated
2080 peaks fit {option}`services.valley.worker.evalMemoryBudget`, so
2081 more batches overlap more builds but no more evaluation memory.
2082 Measure the slice's peak
2083 memory under a real load before raising this:
2084 `systemctl status valley-builds.slice` shows its memory now and
2085 its peak.
2086
2087 ${workerCapacityBound}
2088 '';
2089 };
2090
2091 evalMemoryShare = lib.mkOption {
2092 type = lib.types.numbers.between 0.05 1;
2093 default = 0.6;
2094 example = 0.75;
2095 description = ''
2096 The share of the worker's memory limit that the evaluations of
2097 its batches may hold together, as `valley-worker --eval-share`.
2098 The limit is the smallest `memory.max` of the worker's cgroup and
2099 its ancestors, which is
2100 {option}`services.valley.buildSlice.memoryMax`, and never more
2101 than the host's memory. When the worker cannot find that limit,
2102 it evaluates one batch at a time and says so, and
2103 {option}`services.valley.worker.evalMemoryBudget` should be set.
2104 The rest is left to the builds of batches
2105 that are past their evaluations, to the nix daemon and to the
2106 worker. A batch's evaluation starts when its estimated peak fits
2107 this budget beside the evaluations already running; otherwise it
2108 waits. An evaluation estimated at more than the whole budget runs
2109 alone, and the worker reports it.
2110 {option}`services.valley.worker.evalMemoryBudget` overrides this.
2111 '';
2112 };
2113
2114 evalMemoryBudget = lib.mkOption {
2115 type = lib.types.nullOr (lib.types.strMatching "[0-9]+[KMGT]?");
2116 default = null;
2117 example = "12G";
2118 description = ''
2119 The memory the evaluations of the worker's batches may hold
2120 together, as `valley-worker --eval-budget`, in bytes or with a K,
2121 M, G or T suffix for powers of 1024, as systemd's MemoryMax.
2122 `null` takes {option}`services.valley.worker.evalMemoryShare` of
2123 the worker's memory limit. Give a budget at least as large as the
2124 largest project's evaluation peak, which the `eval.end`
2125 telemetry records as `eval_max_rss_bytes`, and no more than
2126 {option}`services.valley.buildSlice.memoryMax` less what the
2127 builds of {option}`services.valley.worker.batches` batches need.
2128 '';
2129 };
2130
2131 keepOutputs = lib.mkOption {
2132 type = lib.types.nullOr lib.types.ints.positive;
2133 default = 7;
2134 example = 30;
2135 description = ''
2136 How many days the worker keeps the outputs of the checks it
2137 builds, counted from the last batch that used each, as
2138 `valley-worker --keep-outputs`. The worker roots every output in
2139 `roots/` in its state directory, so the host's garbage collection
2140 keeps it, and a later change whose check has the same derivation
2141 finds it built instead of building it again. Each pass first
2142 removes the roots no batch has used for longer than this; nix's
2143 garbage collection then frees those outputs. `null` roots
2144 nothing.
2145 '';
2146 };
2147
2148 interval = lib.mkOption {
2149 type = lib.types.str;
2150 default = "1m";
2151 example = "5m";
2152 description = ''
2153 How long the timer waits after one pass ends before it starts the
2154 next; systemd's default timer accuracy can add up to a minute. A
2155 pass that has nothing to build reads origin and ends. A move the
2156 worker reads starts a pass sooner, through the wake directory;
2157 the timer is the recovery scan, and what retries a failed batch
2158 or push once its wait is over. It is also the hold-off after a
2159 pass that could not claim its wake mark. A pass whose batches
2160 still run reads its projects again at this interval, passed as
2161 `valley-worker --interval`, since the timer starts no pass while
2162 one runs. It is a systemd time span, such as `1m` or `5min`;
2163 the worker reads every span the timer reads.
2164 '';
2165 };
2166
2167 wakeDir = lib.mkOption {
2168 type = lib.types.path;
2169 default = "/var/lib/valley-worker-wake";
2170 description = ''
2171 The worker's wake directory, mode 0770, owned by the
2172 `valley-worker` user and the `valley-worker-wake` group, whose
2173 members are the git user and the integrator's user. A push to
2174 one of the worker's projects or to the instance project, a
2175 landing in one, and a moved signer publication create the empty
2176 file `due` in it, and a path unit starts a pass while it is
2177 there. It holds no more than `due`, `claimed` and `lock`.
2178 '';
2179 };
2180
2181 stateDir = lib.mkOption {
2182 type = lib.types.path;
2183 default = "/var/lib/valley-worker";
2184 description = ''
2185 The worker's own directory, mode 0700 and owned by the
2186 `valley-worker` user. It holds the worker's key, made on the
2187 first start and readable by the worker alone; its public halves,
2188 `key.pub` and `verifier`; the lock and the record of failed
2189 batches; the clones the worker reads projects through; and
2190 `roots/`, the garbage-collector roots of the check outputs it
2191 keeps.
2192 '';
2193 };
2194 };
2195
2196 # The restacker (restack/): one controller for each project it serves,
2197 # which rebases the project's ready changes onto main when main moves,
2198 # as its own principal. Machine options only. Registering the principal
2199 # (its key and its restack grant, in services.valley.authorizedKeys and
2200 # services.valley.grants.restack or in the registry) and provisioning
2201 # its private key are the operator's, and nothing here does either.
2202 restacker = {
2203 enable = lib.mkEnableOption ''
2204 the valley restacker: one controller for each project it serves, which
2205 rebases the project's ready changes onto main when main moves,
2206 pushing over this host's sshd as its own principal'';
2207
2208 projects = lib.mkOption {
2209 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
2210 default = lib.attrNames integratedProjects;
2211 defaultText = lib.literalExpression "every Git-enabled project with a protection block";
2212 example = [ "the-valley" ];
2213 description = ''
2214 The projects the restacker serves, each a project this host
2215 serves. By default it serves every Git-enabled project with a
2216 protection block. Setting `projects` selects exactly the projects
2217 listed, which must be non-empty. Each gets a controller of its own,
2218 `valley-restacker@<project>.service`, with a state directory of
2219 its own under `/var/lib/valley-restacker`.
2220 '';
2221 };
2222
2223 principal = lib.mkOption {
2224 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
2225 default = "valley-restacker";
2226 description = ''
2227 The principal the restacker pushes as, and names as the uploader
2228 of every version it adds. Its key must be declared under this
2229 name, and the name must hold the restack grant, for the hook to
2230 take its versions and reports. A deployment declares both; this
2231 module does neither.
2232 '';
2233 };
2234
2235 sshKeyFile = lib.mkOption {
2236 type = lib.types.nullOr lib.types.str;
2237 default = null;
2238 example = "/run/agenix/valley-restacker-key";
2239 description = ''
2240 The private ssh key the restacker authenticates with, kept
2241 outside the Nix store. systemd reads it as root and hands it to
2242 each controller as a credential, so the file may stay readable
2243 by root alone. Its public half is what the operator declares
2244 for {option}`services.valley.restacker.principal`.
2245 '';
2246 };
2247
2248 interval = lib.mkOption {
2249 type = lib.types.str;
2250 default = "15s";
2251 example = "1m";
2252 description = ''
2253 How long a controller waits after one pass before the next. A
2254 pass reads origin whether or not main has moved, so a change
2255 readied since the last pass is found without another landing.
2256 After a pass that fails, the wait doubles, up to five minutes,
2257 until a pass succeeds.
2258 '';
2259 };
2260 };
2261
2262 onMain = lib.mkOption {
2263 type = lib.types.attrsOf (
2264 lib.types.submodule {
2265 options = {
2266 project = lib.mkOption {
2267 type = lib.types.str;
2268 example = "app";
2269 description = "The project whose main is followed: one this host serves.";
2270 };
2271 unit = lib.mkOption {
2272 type = lib.types.str;
2273 example = "converge.service";
2274 description = ''
2275 The service started for each new tip, which the host
2276 declares itself in {option}`systemd.services`, with its
2277 command, user, credentials, sandbox and timeout. Name it
2278 whole, with `.service`, in letters, digits, `_`, `.`, `:`
2279 and hyphens after the first character; a template's
2280 instance is refused. It must not set `Restart`: a failed
2281 run stays failed.
2282 '';
2283 };
2284 };
2285 }
2286 );
2287 default = { };
2288 example = lib.literalExpression ''{ deploy = { project = "app"; unit = "converge.service"; }; }'';
2289 description = ''
2290 Units of the host's own, each started when a project's main moves.
2291 Each binding runs a bridge, `valley-on-main-<name>.service`, as a
2292 user of its own of that name, which reads the repository, and a
2293 path unit, `valley-on-main-<name>.path`, which starts the bound
2294 unit. The name is a lower-case letter, then up to 15 lower-case
2295 letters, digits or hyphens.
2296
2297 The bridge converges on the latest tip. When main names a commit
2298 it has not requested, it writes the commit and a request file in
2299 its runtime directory, and the path unit starts the unit while a
2300 request exists and the unit is not running. The module adds a
2301 first `ExecStartPre` to the unit, run as root, that removes the
2302 request and writes the unit's environment from the commit:
2303 `VALLEY_REPOSITORY`, the repository's path, and `VALLEY_COMMIT`,
2304 the commit. Moves made during a run become one run at the newest
2305 tip. Every start of the bridge requests the current tip, so a unit
2306 must tolerate running again for a commit it has already run. A
2307 failed run is left failed until main moves or the operator starts
2308 the unit.
2309
2310 Make the unit a oneshot without `RemainAfterExit`: the path unit
2311 starts it again only once it has stopped. The unit's own start
2312 limit applies, and a start it refuses stops the path unit until
2313 the operator resets the unit and restarts the path unit. The
2314 bridge reads the repository directory that existed when it
2315 started, so restart the bridge after replacing a repository, as a
2316 restore does. Observers read the units through telemetry, as the
2317 source `on-main`.
2318 '';
2319 };
2320
2321 # The identity registry compiler (dcr-b87f6e8): the step between the
2322 # instance's declared registry and the two gates that read what it
2323 # compiles to. Machine options only — whether this host compiles, and
2324 # from where. Who the principals are, what they hold and when their
2325 # entries end is the registry's, and the registry is a document in the
2326 # instance repository, never an option here.
2327 identity = {
2328 enable = lib.mkEnableOption ''
2329 compiling the identity registry into what the gates check: the
2330 verifier keys a controller accepts evidence from, and the git
2331 user's authorized keys, both rendered from the instance
2332 repository's integrated tip'';
2333
2334 ref = lib.mkOption {
2335 type = lib.types.str;
2336 default = "refs/heads/main";
2337 description = ''
2338 The ref of the instance repository whose tip carries the
2339 registry: a full ref name, opening with `refs/`, in letters,
2340 digits, dots, dashes, underscores and slashes. A short name such
2341 as `main` is refused. A registry edit takes effect once a
2342 compilation after its landing on this ref has written the files,
2343 and never before: an edit in a branch, in a worktree, or in an
2344 integration request that has not been integrated governs
2345 nothing. The web publisher (`services.valley.webPublisher`) reads
2346 its read grants from the registry at this ref too.
2347
2348 A move of this ref starts a compilation through a path unit
2349 watching the ref's loose file. Under git's files ref storage that
2350 covers creating, updating and packing the ref, but not deleting a
2351 ref already packed, a rewrite of `packed-refs` alone, a symbolic
2352 ref's target, or reftable storage, where the path unit fails to
2353 start. Name a direct ref, in a repository using files storage.
2354 What the path unit cannot see waits for the turn of the day, the
2355 recovery timer ({option}`services.valley.identity.interval`), a
2356 boot, a successful initialization or a controller start.
2357 '';
2358 };
2359
2360 directory = lib.mkOption {
2361 type = lib.types.str;
2362 default = "identity";
2363 description = ''
2364 The registry's directory in that tip. It is a CUE package: the
2365 directory is the enumeration, and every `*.cue` document
2366 directly in it unifies into one registry.
2367 '';
2368 };
2369
2370 interval = lib.mkOption {
2371 type = lib.types.str;
2372 default = "5m";
2373 example = "1m";
2374 description = ''
2375 How long after the last start of a compilation the recovery
2376 timer starts the next, within systemd's default timer accuracy of
2377 a minute. A move of {option}`services.valley.identity.ref` starts
2378 a compilation, and so does 00:00 UTC, when entries expire; this
2379 timer catches what those miss: a move made while the path unit
2380 was not watching, a compilation that failed or ran out of
2381 retries, or a ref the path unit cannot watch. A compilation with
2382 nothing new reads the registry with git, vets and exports it with
2383 cue, and renders it, then writes nothing, since it replaces an
2384 artifact only when its bytes changed. A shorter interval bounds
2385 those cases more tightly for that cost per interval.
2386 '';
2387 };
2388 };
2389
2390 # Machine integration for the declared backup policy. The declaration
2391 # states WHAT must hold (offsite backup, cadence, retention); these
2392 # options supply HOW on this machine — where the repository is and how
2393 # to authenticate. All are paths to files the consumer provisions
2394 # (e.g. agenix), required when the declaration enables backup. Point
2395 # them at runtime paths, never at files in the Nix store.
2396 backup = {
2397 repositoryFile = lib.mkOption {
2398 type = lib.types.nullOr lib.types.path;
2399 default = null;
2400 example = "/run/agenix/valley-restic-repo";
2401 description = ''
2402 File containing the restic repository URL, for the sftp target
2403 e.g. `sftp://backup@backup.example.org:23//./backups/valley`.
2404 '';
2405 };
2406
2407 passwordFile = lib.mkOption {
2408 type = lib.types.nullOr lib.types.path;
2409 default = null;
2410 example = "/run/agenix/valley-restic-password";
2411 description = ''
2412 File containing the restic repository encryption password.
2413 Losing it loses the backups — keep a copy somewhere that
2414 survives this host.
2415 '';
2416 };
2417
2418 sshKeyFile = lib.mkOption {
2419 type = lib.types.nullOr lib.types.path;
2420 default = null;
2421 example = "/run/agenix/valley-git-ssh-key";
2422 description = ''
2423 SSH private key that authenticates to the sftp target. The
2424 backup service runs as root, so any identity the target
2425 authorizes works — reusing the mirror key is fine.
2426 '';
2427 };
2428
2429 knownHostsFile = lib.mkOption {
2430 type = lib.types.nullOr lib.types.path;
2431 default = null;
2432 example = "/var/lib/valley-backup/known_hosts";
2433 description = ''
2434 known_hosts file pinning the sftp target's host key. Pin from
2435 the provider's published fingerprints, not a blind ssh-keyscan.
2436 '';
2437 };
2438 };
2439
2440 pushPolicies = lib.mkOption {
2441 type = lib.types.attrs;
2442 internal = true;
2443 readOnly = true;
2444 default = pushPolicies;
2445 description = "Each served project's push policy, before it is written as the JSON valleyhook reads; module-eval reads it.";
2446 };
2447
2448 # The programs the host runs, as this flake builds them
2449 # (nix/packages.nix). These options are internal: a host has no reason
2450 # to set them. The module checks set them to stand-ins with the same
2451 # binary names (nix/checks/hosts.nix), so a check that reads only what
2452 # the module renders does not change when one of the programs does.
2453 packages = {
2454 integrator = lib.mkOption {
2455 type = lib.types.package;
2456 internal = true;
2457 default = flakePackages.integrator;
2458 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).integrator";
2459 description = "The integrator, which the controllers and the signers publisher run.";
2460 };
2461
2462 identity = lib.mkOption {
2463 type = lib.types.package;
2464 internal = true;
2465 default = flakePackages.identity;
2466 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).identity";
2467 description = "The identity registry compiler, which valley-identity runs.";
2468 };
2469
2470 valleyhook = lib.mkOption {
2471 type = lib.types.package;
2472 internal = true;
2473 default = flakePackages.valleyhook;
2474 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valleyhook";
2475 description = "The push policy, which every pre-receive hook and the git user's login shell run.";
2476 };
2477
2478 restacker = lib.mkOption {
2479 type = lib.types.package;
2480 internal = true;
2481 default = flakePackages.valley-restacker;
2482 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-restacker";
2483 description = "The restacker, which each restacker controller runs.";
2484 };
2485
2486 pushreason = lib.mkOption {
2487 type = lib.types.package;
2488 internal = true;
2489 default = flakePackages.pushreason;
2490 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).pushreason";
2491 description = "The reason a failed mirror push is logged with, which each mirror pusher runs.";
2492 };
2493
2494 onmain = lib.mkOption {
2495 type = lib.types.package;
2496 internal = true;
2497 default = flakePackages.onmain;
2498 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).onmain";
2499 description = "The bridge each services.valley.onMain binding runs.";
2500 };
2501 };
2502 };
2503
2504 config = lib.mkIf cfg.enable (lib.mkMerge [ {
2505 assertions = [
2506 {
2507 assertion = cfg.authorizedKeys != [ ];
2508 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
2509 }
2510 ]
2511 ++ lib.optionals backupEnabled (
2512 lib.mapAttrsToList (name: what: {
2513 assertion = cfg.backup.${name} != null;
2514 message = "services.valley.backup.${name} must be set: the host declaration enables backup, and ${what} is machine integration the consumer supplies (e.g. from its secrets).";
2515 }) backupSecretOptions
2516 )
2517 ++ lib.optionals cfg.integrator.enable (
2518 lib.mapAttrsToList (name: what: {
2519 assertion = cfg.integrator.${name} != null;
2520 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
2521 }) integratorPathOptions
2522 ++ [
2523 {
2524 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
2525 message = "exactly one of services.valley.integrator.instanceProject and services.valley.integrator.instancePolicy must be set: the floor is read from the instance repository this host serves, or supplied as a directory for a host that serves none, and two sources for one layer is a question about which one won.";
2526 }
2527 # The rule the integrator reads the rendered file by
2528 # (note/signerprojects.go): every name and project is printable
2529 # ASCII with no space, so only the spaces this renders separate
2530 # words, and a name holds no plus and opens with no #, which
2531 # would make its line a comment.
2532 {
2533 assertion =
2534 let
2535 word = w: builtins.match "[!-~]+" w != null;
2536 name = n: word n && !lib.hasInfix "+" n && !lib.hasPrefix "#" n;
2537 in
2538 lib.all (n: name n && lib.all word cfg.integrator.signerProjects.${n}) (
2539 lib.attrNames cfg.integrator.signerProjects
2540 );
2541 message = "services.valley.integrator.signerProjects holds a name or project that is empty or not printable ASCII with no space, or a name with a plus or an opening #. The list is rendered one signer per line, its name and projects separated by spaces, and read back by that rule, so such a word would be read as some other signer or project, or refused. Write each as one such word.";
2542 }
2543 {
2544 assertion =
2545 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
2546 message = "services.valley.integrator.instanceProject names ${toString cfg.integrator.instanceProject}, which this host declaration does not serve: the floor is read from that repository's tip, so the host has to hold it.";
2547 }
2548 {
2549 assertion = cfg.integrator.user != cfg.user;
2550 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
2551 }
2552 {
2553 assertion = integratedProjects != { };
2554 message = "services.valley.integrator.enable is on and the host declaration protects no project — a controller only ever serves a protected target, so this would render no service at all.";
2555 }
2556 ]
2557 )
2558 # The web publisher (web-publisher.nix) reads the registry at
2559 # identity.ref too, when its module is imported and on.
2560 ++ lib.optional (cfg.identity.enable || config.services.valley.webPublisher.enable or false) {
2561 assertion = fullRefName cfg.identity.ref;
2562 message = "services.valley.identity.ref is ${cfg.identity.ref}, which is not a full ref name. The identity registry is read at that ref, so name it whole, opening with refs/, as git check-ref-format accepts it: refs/heads/main, not main.";
2563 }
2564 ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) (
2565 let
2566 name = cfg.integrator.instanceProject;
2567 protected = gitProjects.${name}.protection.refs or [ ];
2568 # The web publisher (web-publisher.nix) reads the registry at
2569 # identity.ref too, when its module is imported and on.
2570 publisher = config.services.valley.webPublisher.enable or false;
2571 read =
2572 lib.optional cfg.integrator.enable "refs/heads/main"
2573 ++ lib.optional (cfg.identity.enable || publisher) cfg.identity.ref;
2574 in
2575 map (ref: {
2576 assertion = lib.any (pattern: refPatternMatches pattern ref) protected;
2577 message = "services.valley.integrator.instanceProject names ${name}, whose ${ref} is not protected: the floor and the registry are read from it, so any key that can push could rewrite them. Declare a protection block for ${name} covering ${ref}.";
2578 }) read
2579 )
2580 ++ [
2581 {
2582 assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) (
2583 sshdValues "AcceptEnv" ++ sshdValues "SetEnv"
2584 ));
2585 message = "sshd's AcceptEnv or SetEnv here holds a quote or a backslash, which sshd unpicks and this module does not. Write each name plainly, separated by spaces, so what is checked is what sshd reads.";
2586 }
2587 {
2588 assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv"));
2589 message = "sshd accepts ${lib.concatStringsSep " " (lib.filter boundaryVariable (sshdValues "AcceptEnv"))} from the client (AcceptEnv), a pattern that admits ${principalEnv} or a GIT_ variable. The git user's shell drops them, and sshd must not offer them either. Remove the pattern.";
2590 }
2591 {
2592 assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv"));
2593 message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it.";
2594 }
2595 {
2596 assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment");
2597 message = "sshd's PermitUserEnvironment must be no: the git user's shell derives the principal from the authenticated key, and nothing a key's entry or ~/.ssh/environment sets is the push boundary's to read.";
2598 }
2599 {
2600 assertion = conflictingKeys == { };
2601 message = "the git user's authorized keys name ${lib.concatStringsSep ", " (lib.attrNames conflictingKeys)} under more than one principal tag (an untagged entry counts as one): sshd authorizes a key by the first entry naming it, so which principal it pushes as would depend on file order. Declare each key once.";
2602 }
2603 {
2604 assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ];
2605 message = "users.users.${cfg.user}.openssh.authorizedKeys.keyFiles must be empty: the git user's keys carry the principal tag the push policy reads, so they are declared in services.valley.authorizedKeys, where their tags can be checked.";
2606 }
2607 ]
2608 ++ lib.optionals cfg.identity.enable [
2609 {
2610 assertion = cfg.integrator.instanceProject != null;
2611 message = "services.valley.integrator.instanceProject must be set: the identity registry is read from the served instance repository's integrated tip, so the host has to hold that repository.";
2612 }
2613 {
2614 assertion = cfg.integrator.knownSignersFile == null;
2615 message = "services.valley.integrator.knownSignersFile must be unset: the registry compiles that file (${identityKnownSigners}), and two sources for one file is a question about which one won.";
2616 }
2617 ]
2618 ++ lib.optionals cfg.worker.enable (
2619 let
2620 name = cfg.worker.signerName;
2621 listed = cfg.integrator.signerProjects.${name} or null;
2622 sorted = l: lib.sort lib.lessThan (lib.unique l);
2623 unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.worker.projects;
2624 in
2625 [
2626 {
2627 assertion = cfg.integrator.enable;
2628 message = "services.valley.worker.enable needs services.valley.integrator.enable: the worker builds evidence for this host's controllers, and they are what restrict its key to its projects.";
2629 }
2630 {
2631 assertion = cfg.integrator.instanceProject != null;
2632 message = "services.valley.worker.enable needs services.valley.integrator.instanceProject: the worker finds this host's projects through the instance repository, as valley pending --repo does.";
2633 }
2634 {
2635 assertion = cfg.worker.projects != [ ] && unserved == [ ];
2636 message = "services.valley.worker.projects must name at least one project, and only projects this host serves${
2637 lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}"
2638 }.";
2639 }
2640 # The restriction (oc-13c6bd6). Every controller that shares the
2641 # known-signers file counts a key it holds in every project, so a
2642 # worker whose key is not restricted would be trusted for projects
2643 # it never builds. The module sets the entry to the worker's
2644 # projects below; this holds a host that sets it itself.
2645 {
2646 assertion = listed != null && sorted listed == sorted cfg.worker.projects;
2647 message = "services.valley.integrator.signerProjects must restrict ${name}, the worker's signer, to exactly the worker's projects: without the restriction, every controller that holds the worker's key counts its evidence in every project. Set services.valley.integrator.signerProjects.\"${name}\" = [ ${
2648 lib.concatMapStringsSep " " (p: "\"${p}\"") cfg.worker.projects
2649 } ], or leave the entry unset and the module sets it to the worker's projects.";
2650 }
2651 {
2652 assertion = name != integratorName;
2653 message = "services.valley.worker.signerName must differ from ${integratorName}, the name the controllers sign under: a controller's signature never counts as check evidence, and a controller refuses to start when the signer projects list names it.";
2654 }
2655 {
2656 assertion = cfg.buildSlice.enable;
2657 message = "services.valley.worker.enable needs services.valley.buildSlice.enable: the worker builds through this host's nix daemon, and only the build slice caps what it makes the daemon do. The slice caps every build the daemon runs, for every user, so turning it on is a decision about the host, made on its own.";
2658 }
2659 {
2660 assertion = config.services.openssh.enable && config.nix.enable;
2661 message = "services.valley.worker.enable needs services.openssh.enable and nix.enable: the worker reaches this host's repositories through its sshd, and builds through its nix daemon.";
2662 }
2663 ]
2664 )
2665 ++ lib.optionals cfg.restacker.enable (
2666 let
2667 unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.restacker.projects;
2668 in
2669 [
2670 {
2671 assertion = cfg.restacker.projects != [ ] && unserved == [ ];
2672 message = "services.valley.restacker.projects must name at least one project, and only projects this host serves${
2673 lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}"
2674 }.";
2675 }
2676 {
2677 assertion = cfg.restacker.sshKeyFile != null;
2678 message = "services.valley.restacker.sshKeyFile must be set: the restacker pushes over this host's sshd with a key the operator provisions outside the Nix store.";
2679 }
2680 {
2681 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
2682 message = "services.valley.restacker.enable needs exactly one of services.valley.integrator.instanceProject and services.valley.integrator.instancePolicy: the restacker reads the cap on its versions from the policy the controllers compose, over the floor they read.";
2683 }
2684 {
2685 assertion = config.services.openssh.enable;
2686 message = "services.valley.restacker.enable needs services.openssh.enable: the restacker reaches this host's repositories through its sshd.";
2687 }
2688 ]
2689 )
2690 ++ lib.concatLists (
2691 lib.mapAttrsToList (name: b: [
2692 {
2693 assertion = builtins.match "[a-z][a-z0-9-]{0,15}" name != null;
2694 message = "services.valley.onMain.${name}: a binding's name is a lower-case letter, then up to 15 lower-case letters, digits or hyphens, because its bridge's unit and user are named ${onMainBridge "<name>"}, and a user's name holds at most 31 characters.";
2695 }
2696 {
2697 assertion = gitProjects ? ${b.project};
2698 message = "services.valley.onMain.${name}.project names ${b.project}, which this host declaration does not serve: the bridge follows main in that repository, so the host has to hold it.";
2699 }
2700 {
2701 assertion = builtins.match onMainUnitName b.unit != null;
2702 message = "services.valley.onMain.${name}.unit is ${builtins.toJSON b.unit}: name a service whole, ending in .service, in letters, digits, _, ., : and hyphens after the first character, which need no quoting in a unit file. A template's instance is refused: the module would render it as a unit of its own, without the template's command.";
2703 }
2704 {
2705 assertion = toString (onMainService b).serviceConfig.Restart or "no" == "no";
2706 message = "services.valley.onMain.${name}: ${b.unit} sets Restart=${toString (onMainService b).serviceConfig.Restart or ""}. A failed run must stay failed until main moves or the operator starts the unit, so a bound unit does not restart.";
2707 }
2708 ]) cfg.onMain
2709 )
2710 ++ [
2711 {
2712 assertion = onMainBoundTwice == [ ];
2713 message = "services.valley.onMain binds ${lib.concatStringsSep ", " onMainBoundTwice} more than once. Each binding starts its unit with an environment file of its own, so two would start one unit for two projects' tips, each run reading both files. Bind each unit once.";
2714 }
2715 ];
2716
2717 # The worker's signer counts in the worker's projects and no others
2718 # (oc-e092038). On a host that sets neither list, the worker builds for
2719 # every project the controllers serve, and the controllers count its
2720 # evidence in exactly those. A host that narrows the worker's projects
2721 # narrows the signer's entry with them. The entry is a default, so a
2722 # host's own entry replaces it, and the assertion above holds that
2723 # entry to the worker's projects.
2724 services.valley.integrator.signerProjects = lib.mkIf cfg.worker.enable {
2725 ${cfg.worker.signerName} = lib.mkDefault cfg.worker.projects;
2726 };
2727
2728 users.groups.${cfg.group} = { };
2729
2730 users.users.${cfg.user} = {
2731 isSystemUser = true;
2732 group = cfg.group;
2733 home = cfg.dataDir;
2734 # The valley's shell, in front of git-shell: it derives the principal
2735 # from the authenticated key, drops the GIT_ environment, and pauses
2736 # pushes until valley-init has converged. git-shell then allows only
2737 # git-upload-pack, git-receive-pack and git-upload-archive, and rejects
2738 # interactive logins (no ~/git-shell-commands).
2739 shell = "${gitShell}/bin/valley-git-shell";
2740 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
2741 };
2742
2743 # The integrator's own account. No shell, no keys, no home of its own
2744 # beyond the state directory its units get; the git group is the only
2745 # thing it holds.
2746 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
2747 isSystemUser = true;
2748 group = cfg.group;
2749 home = "/var/lib/valley-integrator";
2750 description = "The valley integrator";
2751 };
2752
2753 # The worker's own account. Its group is its own, not the git group, so
2754 # it can neither read nor write the repositories on disk: it reaches
2755 # them as an ssh client, as anyone else does.
2756 users.users.valley-worker = lib.mkIf cfg.worker.enable {
2757 isSystemUser = true;
2758 group = "valley-worker";
2759 home = workerDir;
2760 description = "The valley check worker";
2761 };
2762 users.groups.valley-worker = lib.mkIf cfg.worker.enable { };
2763 # The writers of the integrator's wake directories: the git user, whose
2764 # post-receive hook marks a push, and the integrator's user, whose
2765 # instance controller marks a floor landing. The worker is not in it.
2766 users.groups.${integratorWakeGroup} = lib.mkIf cfg.integrator.enable {
2767 members = [
2768 cfg.user
2769 cfg.integrator.user
2770 ];
2771 };
2772 users.groups.${workerWakeGroup} = lib.mkIf cfg.worker.enable {
2773 members = [
2774 cfg.user
2775 cfg.integrator.user
2776 ];
2777 };
2778
2779 # The restacker's own account. Its group is its own, not the git group,
2780 # so it can neither read nor write the repositories on disk, and it is
2781 # in no group that reads the integrator's or the worker's keys: it
2782 # reaches the repositories as an ssh client, as its own principal.
2783 users.users.valley-restacker = lib.mkIf cfg.restacker.enable {
2784 isSystemUser = true;
2785 group = "valley-restacker";
2786 home = "/var/lib/${restackerStateName}";
2787 description = "The valley restacker";
2788 };
2789 users.groups.valley-restacker = lib.mkIf cfg.restacker.enable { };
2790
2791 services.openssh.enable = lib.mkDefault true;
2792
2793 # The git user's key files, named in its Match block so no other file
2794 # can authorize a key for it. The declared keys come first, and they stay
2795 # authorized beside the compiled ones: a compiled file can only ever
2796 # add, so an empty or missing one — a first boot before the first
2797 # compilation, a registry that lost an entry, a bug here — cannot take
2798 # the git user's access away. Which is the point: the assertion above
2799 # keeps at least one key declared, and that key is the way back in.
2800 #
2801 # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys
2802 # under its home is not read, and no AuthorizedKeysCommand runs, so every
2803 # entry a pusher can arrive through carries the tag this module or the
2804 # compiler wrote, and the assertions and the compiler hold those to one
2805 # tag per key.
2806 #
2807 # Belt-and-braces hardening for the git user beside it. The trailing
2808 # `Match All` closes the block so it can't scope directives appended to
2809 # sshd_config after this snippet.
2810 services.openssh.extraConfig = ''
2811 Match User ${cfg.user}
2812 AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"}
2813 AuthorizedKeysCommand none
2814 ExposeAuthInfo yes
2815 AllowTcpForwarding no
2816 AllowAgentForwarding no
2817 X11Forwarding no
2818 PermitTunnel no
2819 Match All
2820 '';
2821
2822 # git-shell spawns git-receive-pack/git-upload-pack from PATH
2823 environment.systemPackages = [ pkgs.git ];
2824
2825 systemd.tmpfiles.rules = [
2826 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
2827 ]
2828 ++ lib.optionals cfg.bus.enable [
2829 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
2830 ]
2831 ++ lib.optionals cfg.worker.enable [
2832 "d ${workerDir} 0700 valley-worker valley-worker - -"
2833 "d ${workerWakeDir} 0770 valley-worker ${workerWakeGroup} - -"
2834 ]
2835 ++ lib.optionals cfg.integrator.enable (
2836 [ "d ${integratorWakeRoot} 0755 root root - -" ]
2837 ++ map (
2838 name: "d ${integratorWakeDir name} 0770 ${cfg.integrator.user} ${integratorWakeGroup} - -"
2839 ) (lib.attrNames integratedProjects)
2840 );
2841
2842 # The bus itself. It runs as the git user — the store directory lives in
2843 # that user's data — but the sandbox is what confines it: the unit can
2844 # write nowhere except its store directory.
2845 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
2846 description = "The valley event bus (NATS JetStream)";
2847 wantedBy = [ "multi-user.target" ];
2848 after = [
2849 "network.target"
2850 "systemd-tmpfiles-setup.service"
2851 ];
2852 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
2853 serviceConfig = {
2854 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
2855 Restart = "on-failure";
2856 User = cfg.user;
2857 Group = cfg.group;
2858 LimitNOFILE = 65536;
2859 NoNewPrivileges = true;
2860 ProtectSystem = "strict";
2861 ReadWritePaths = [ cfg.bus.storeDir ];
2862 ProtectHome = true;
2863 PrivateTmp = true;
2864 PrivateDevices = true;
2865 ProtectClock = true;
2866 ProtectHostname = true;
2867 ProtectKernelLogs = true;
2868 ProtectKernelModules = true;
2869 ProtectKernelTunables = true;
2870 ProtectControlGroups = true;
2871 ProtectProc = "invisible";
2872 RestrictAddressFamilies = [
2873 "AF_INET"
2874 "AF_INET6"
2875 "AF_UNIX"
2876 ];
2877 RestrictNamespaces = true;
2878 RestrictRealtime = true;
2879 RestrictSUIDSGID = true;
2880 LockPersonality = true;
2881 CapabilityBoundingSet = "";
2882 SystemCallArchitectures = "native";
2883 SystemCallFilter = [ "@system-service" ];
2884 UMask = "0077";
2885 };
2886 };
2887
2888 # The stream is config, not state: (re)created idempotently on every
2889 # boot, capturing everything under valley.>. An existing stream — and
2890 # the events in it — is left untouched.
2891 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
2892 description = "Create the valley event stream";
2893 wantedBy = [ "multi-user.target" ];
2894 requires = [ "valley-bus.service" ];
2895 after = [ "valley-bus.service" ];
2896 serviceConfig = {
2897 Type = "oneshot";
2898 User = cfg.user;
2899 Group = cfg.group;
2900 };
2901 path = [ pkgs.natscli ];
2902 script = ''
2903 # The server needs a moment to accept connections after startup.
2904 for _ in $(seq 1 50); do
2905 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
2906 sleep 0.2
2907 done
2908 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
2909 nats --server ${busUrl} stream add valley \
2910 --subjects 'valley.>' --storage file --defaults
2911 fi
2912 '';
2913 };
2914
2915 # Create missing bare repos and (re)wire the managed hooks on every
2916 # activation where the declaration changed.
2917 # It stays active after it succeeds, so its state says whether its
2918 # latest start succeeded: the registry compiler and the signers
2919 # publisher start only while it is active (Requisite=), and never start
2920 # it. Activation runs it again only when its unit changed, stopping it
2921 # first, which stops the units that require it, the controllers among
2922 # them. Its success starts the compiler, the publisher and the
2923 # controllers, whether activation or a restart by hand started it, so
2924 # starting it again once a failure's fault is fixed restores all three.
2925 # Nothing else retries it. The controllers are named one by one rather
2926 # than through valley-integrators.target: systemd drops the start of a
2927 # target already active, and the starts it would pull in with it.
2928 systemd.services.valley-init = {
2929 description = "Initialize the valley host's bare git repositories";
2930 wantedBy = [ "multi-user.target" ];
2931 after = [ "systemd-tmpfiles-setup.service" ];
2932 wants =
2933 lib.optional cfg.identity.enable "valley-identity.service"
2934 ++ lib.optional publishesSigners "valley-signers.service"
2935 ++ lib.optionals cfg.integrator.enable (
2936 map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects)
2937 );
2938 unitConfig.RequiresMountsFor = cfg.dataDir;
2939 # Each run queues a push to every mirrored project's mirrors, and the
2940 # pushers name the mirrors. A mirror added to a project that already
2941 # has one changes no line of the script, so the pushers are named
2942 # here, and activation runs init again to queue the new mirror's
2943 # first push.
2944 restartTriggers = lib.mapAttrsToList (name: p: mirrorPusher name p.mirrors) (
2945 lib.filterAttrs (_: p: p.mirrors != [ ]) gitProjects
2946 );
2947 serviceConfig = {
2948 Type = "oneshot";
2949 RemainAfterExit = true;
2950 User = cfg.user;
2951 Group = cfg.group;
2952 };
2953 path = [
2954 pkgs.git
2955 pkgs.diffutils
2956 ];
2957 # Everything init can wire is wired before it fails. A conflict in one
2958 # repository is reported, the rest of the host is still converged,
2959 # and only then does the unit fail, so the activation fails loudly
2960 # without leaving another repository's hook out of date.
2961 script = ''
2962 # Pushes pause the moment a convergence starts, and resume only once
2963 # it has finished: the record is removed first and written last.
2964 rm -f ${convergedRecord}
2965 ${valleyInitBody}
2966 printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp
2967 mv -f ${convergedRecord}.tmp ${convergedRecord}
2968 '';
2969 };
2970
2971 # The registry compiler. It renders the instance repository's
2972 # integrated tip into the artifacts the gates read; nothing else on the
2973 # host writes them.
2974 #
2975 # It runs as the git user rather than under an identity of its own,
2976 # which is the one place this module steps back from the service split
2977 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
2978 # anyone but root or the account it authorizes, so the choice is the git
2979 # user or root, and the git user is the smaller grant.
2980 #
2981 # What starts it: every boot, every successful valley-init, a
2982 # controller starting, the path unit below whenever the registry's ref
2983 # moves, and the timer at 00:00 UTC, when entries expire, since expiry
2984 # is judged by UTC day. It starts only while valley-init is active
2985 # (Requisite=): a start while valley-init runs waits for it, one after
2986 # valley-init failed fails, and none starts valley-init, whose run
2987 # would pause every push. After a failure, valley-init must be started
2988 # again, by activation or by hand, once its fault is fixed. Neither the path unit nor the compiler has a
2989 # trigger or start limit: each start needs a move of the ref or a
2990 # timer, the path unit starts the compiler again only once the run it
2991 # started has ended, and the compiler writes nothing the path unit
2992 # watches, so no loop exists for a limit to stop, and a limit reached
2993 # would leave the ref unwatched until someone restarted the path unit.
2994 #
2995 # systemd holds no watch on the ref while the compiler runs, does not
2996 # see afterwards that the ref was replaced, and merges a start
2997 # requested meanwhile into the run under way. So after each compilation
2998 # the compiler reads the ref and the day again, and compiles again
2999 # until a reading matches what it compiled, within a retry budget of
3000 # three compilations. The budget bounds one run, not the work: a ref
3001 # that keeps moving keeps starting runs. The files can still lag the
3002 # ref: after a move
3003 # made between the last reading and the path unit watching again, a
3004 # compilation that failed or spent its budget, a start refused while
3005 # valley-init has failed, or a ref the path unit cannot watch (see
3006 # identity.ref). The next move of the ref, a successful valley-init, or
3007 # the interval timer, which is recovery and not the mechanism,
3008 # compiles it then.
3009 #
3010 # Level-triggered, like the rest: a compilation reads the current tip
3011 # and replaces an artifact only when its bytes changed, so the starts
3012 # need no coordination.
3013 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
3014 description = "Compile the valley identity registry into what the gates check";
3015 wantedBy = [ "multi-user.target" ];
3016 after = [ "valley-init.service" ];
3017 requisite = [ "valley-init.service" ];
3018 startLimitIntervalSec = 0;
3019 unitConfig.RequiresMountsFor = cfg.dataDir;
3020 serviceConfig = {
3021 Type = "oneshot";
3022 ExecStart = identityCommand;
3023 User = cfg.user;
3024 Group = cfg.group;
3025 StateDirectory = identityStateName;
3026 # sshd walks every directory above an authorized-keys file and
3027 # refuses a group- or world-writable one, so the state directory is
3028 # 0755 deliberately rather than the 0700 a service's state usually
3029 # takes. Nothing secret lives in it: a registry is public keys.
3030 StateDirectoryMode = "0755";
3031 NoNewPrivileges = true;
3032 ProtectSystem = "strict";
3033 ReadWritePaths = [ identityStateDir ];
3034 ProtectHome = true;
3035 PrivateTmp = true;
3036 PrivateDevices = true;
3037 ProtectClock = true;
3038 ProtectHostname = true;
3039 ProtectKernelLogs = true;
3040 ProtectKernelModules = true;
3041 ProtectKernelTunables = true;
3042 ProtectControlGroups = true;
3043 ProtectProc = "invisible";
3044 RestrictAddressFamilies = [ "AF_UNIX" ];
3045 RestrictNamespaces = true;
3046 RestrictRealtime = true;
3047 RestrictSUIDSGID = true;
3048 LockPersonality = true;
3049 CapabilityBoundingSet = "";
3050 SystemCallArchitectures = "native";
3051 SystemCallFilter = [ "@system-service" ];
3052 UMask = "0022";
3053 };
3054 };
3055
3056 systemd.paths.valley-identity = lib.mkIf cfg.identity.enable {
3057 description = "Watch the ref the valley identity registry is read at";
3058 wantedBy = [ "multi-user.target" ];
3059 pathConfig = {
3060 PathChanged = identityInputs;
3061 TriggerLimitIntervalSec = 0;
3062 };
3063 };
3064
3065 # The turn of the UTC day, when a declared expiry takes effect. It asks
3066 # for promptness: no randomized delay, and a scheduling accuracy of a
3067 # second rather than systemd's default minute. It is not persistent: a midnight passed
3068 # while the host was off needs no catch-up start, because every boot
3069 # compiles, judging expiry by the day it boots on.
3070 systemd.timers.valley-identity-midnight = lib.mkIf cfg.identity.enable {
3071 description = "Compile the valley identity registry at the turn of the UTC day";
3072 wantedBy = [ "timers.target" ];
3073 timerConfig = {
3074 Unit = "valley-identity.service";
3075 OnCalendar = "*-*-* 00:00:00 UTC";
3076 AccuracySec = "1s";
3077 RandomizedDelaySec = "0";
3078 Persistent = false;
3079 };
3080 };
3081
3082 # Recovery, for a start the path unit missed.
3083 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
3084 description = "Re-compile the valley identity registry";
3085 wantedBy = [ "timers.target" ];
3086 timerConfig = {
3087 OnBootSec = "1m";
3088 OnUnitActiveSec = cfg.identity.interval;
3089 };
3090 };
3091
3092 # The signers publication, refs/the-valley/signers, is written by a
3093 # oneshot of its own. It runs as the git user, which owns the instance
3094 # repository, and its sandbox lets it write that repository and nothing
3095 # else. It is not part of valley-init, which runs only on activation,
3096 # nor of the registry compiler, whose sandbox writes only its state
3097 # directory. Only the host's machinery writes the ref, never a push:
3098 # the hook refuses every push to it. This unit writes it, and the
3099 # integrator can, being in the group the repository is shared with
3100 # because it lands code there.
3101 #
3102 # What starts it: every boot and every activation, after valley-init,
3103 # which covers a changed signing name, signers path or signer projects
3104 # list; and the path unit below, whenever a file it publishes from
3105 # changes: the known-signers file, either approval signers file, or the
3106 # instance repository's main. That covers each compilation that changed
3107 # a file, a hand-provisioned file being replaced, an approval key
3108 # revoked while the signing keys stay, and a landing on the instance.
3109 # Like the registry compiler, it starts only while valley-init is
3110 # active (Requisite=) and never starts valley-init, so a landing on the
3111 # instance's main reruns no valley-init and pauses no push, and a
3112 # successful valley-init starts it.
3113 # A run reads every input and writes the ref only when the tree it
3114 # makes differs, so a run with nothing new is free. Every value is in
3115 # one tree under one ref, so a client never reads one value without the
3116 # others. The path unit holds no watch while the service it started
3117 # runs, and when the service ends it does not see that an existing
3118 # file was replaced. So after each publication the publisher reads
3119 # every input again, and publishes again until a reading matches what
3120 # it published: a change made up to its last reading is published by
3121 # that run. A change made after it starts no run, and waits for the
3122 # next change to a published input or the next move of main. A run
3123 # makes at most one publication more than the inputs that can change,
3124 # and fails if they are still changing then; the unit shows failed,
3125 # and nothing retries it before that next change. A run holds a lock
3126 # in the instance repository from its first reading to its last, so two
3127 # runs take turns, and one that read older files cannot publish them
3128 # over newer ones. The ref also moves with a compare-and-swap.
3129 #
3130 # A run that cannot read a file, or reads one that is not a list of
3131 # verifier keys, fails and leaves the last publication in place. That
3132 # is the file the controllers were given before it changed, and the
3133 # journal says why. A file with no key in it, as the compiler writes
3134 # once every signing or approval key is revoked, is published, so
3135 # clients stop verifying with the revoked keys.
3136 systemd.services.valley-signers = lib.mkIf publishesSigners {
3137 description = "Publish what clients verify the valley integrator's transfer statements with";
3138 wantedBy = [ "multi-user.target" ];
3139 after = [ "valley-init.service" ] ++ lib.optional cfg.identity.enable "valley-identity.service";
3140 requisite = [ "valley-init.service" ];
3141 unitConfig.RequiresMountsFor = cfg.dataDir;
3142 serviceConfig = {
3143 Type = "oneshot";
3144 ExecStart = signersCommand;
3145 User = cfg.user;
3146 Group = cfg.group;
3147 NoNewPrivileges = true;
3148 ProtectSystem = "strict";
3149 ReadWritePaths = [ instanceRepo ] ++ lib.optional cfg.worker.enable workerWakeDir;
3150 ProtectHome = true;
3151 PrivateTmp = true;
3152 PrivateDevices = true;
3153 ProtectClock = true;
3154 ProtectHostname = true;
3155 ProtectKernelLogs = true;
3156 ProtectKernelModules = true;
3157 ProtectKernelTunables = true;
3158 ProtectControlGroups = true;
3159 ProtectProc = "invisible";
3160 RestrictAddressFamilies = [ "AF_UNIX" ];
3161 RestrictNamespaces = true;
3162 RestrictRealtime = true;
3163 RestrictSUIDSGID = true;
3164 LockPersonality = true;
3165 CapabilityBoundingSet = "";
3166 SystemCallArchitectures = "native";
3167 SystemCallFilter = [ "@system-service" ];
3168 # The instance repository is always one the integrator serves, since
3169 # it has to be protected, so it is group-shared and its directories
3170 # are setgid. With the default umask, git would chmod each directory
3171 # it makes to add group write, setgid bit included, and
3172 # RestrictSUIDSGID refuses that chmod. Group write from the start
3173 # leaves git nothing to chmod, as for the controllers.
3174 UMask = "0002";
3175 };
3176 };
3177
3178 systemd.paths.valley-signers = lib.mkIf publishesSigners {
3179 description = "Watch what the valley signers publication is read from";
3180 wantedBy = [ "multi-user.target" ];
3181 pathConfig.PathChanged = signersInputs;
3182 };
3183
3184 # One controller per served project, as instances of a single template:
3185 # the units differ only in the repository they serve, which is the
3186 # instance name. One long-lived `watch` per project, rather than a timer
3187 # or a path unit starting `reconcile`: the binary watches its own wake
3188 # directory, follows a landing with another pass, and keeps its
3189 # interval as the recovery pass. A unit started for each mark would
3190 # repeat the start's sweep and could not interrupt a pass in progress
3191 # anyway, and starting a service that is already running wakes nothing.
3192 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
3193 description = "The valley integrator for %i";
3194 after = [
3195 "network.target"
3196 "valley-init.service"
3197 "systemd-tmpfiles-setup.service"
3198 ]
3199 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
3200 ++ lib.optional cfg.identity.enable "valley-identity.service";
3201 requires = [ "valley-init.service" ];
3202 # Wants, not requires: a controller reads the compiled signers file,
3203 # so it starts after the first compilation — but a compilation that
3204 # failed must not keep the controllers down. One that finds no file
3205 # says so and restarts, which is the same loop and a louder one.
3206 wants = lib.optional cfg.identity.enable "valley-identity.service";
3207 unitConfig.RequiresMountsFor = cfg.dataDir;
3208 # nix is not pinned, for the reason the integrator package does not
3209 # pin it: a check's input closure must be recomputed by the nix this
3210 # machine actually runs. Everything else a controller drives is
3211 # pinned inside the wrapper.
3212 path = [ config.nix.package ];
3213 # The repositories belong to the git user and the controller does
3214 # not, so git refuses to touch them as dubiously owned. The exception
3215 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
3216 # command-scope config, which is protected config, so safe.directory
3217 # is honoured from it — a repository-scoped setting would be ignored,
3218 # deliberately. And every git the controller drives is a child of
3219 # this unit, whether run by the integrator itself or by attest or the
3220 # deriver, so one environment covers all of them.
3221 #
3222 # One repository per instance: never a global gitconfig, never a
3223 # wildcard. Every other repository on the host stays refused. Linked
3224 # worktrees need no entry of their own — the controller creates them,
3225 # so it owns them, and git checks the worktree and its gitdir rather
3226 # than the repository they point at.
3227 #
3228 # TMPDIR is the same kind of wiring, for the same reason. A verdict
3229 # wants a checkout of the tip on disk, and the integrator asks for one
3230 # the ordinary way — a temporary directory, then a linked worktree in
3231 # it. The sandbox below leaves no writable temporary directory, so
3232 # every tick died on `could not create leading directories`. The
3233 # scratch belongs under the state directory the unit already has:
3234 # writable by construction, owned by this service, and gone when the
3235 # service's state is. Setting it in the environment rather than
3236 # teaching the binary a flag covers every process in the unit at once
3237 # — the integrator, attest, the deriver, and the git each of them runs
3238 # all read TMPDIR, and all of them want scratch in the same place.
3239 #
3240 # A second exception, for the instance repository. Every controller
3241 # reads the group's floor from that repository's tip, and it need not
3242 # be the project the controller serves — the controller for one
3243 # project reads the floor out of another project's repository, which
3244 # it likewise does not own. Without the exception git refuses it as
3245 # dubiously owned and every pass fails, exactly as it did for the
3246 # served repository. Two entries, both named; still never a wildcard.
3247 #
3248 # Reading needs no sandbox entry beside it. ProtectSystem=strict
3249 # leaves the filesystem readable and only takes write away, so the
3250 # ReadWritePaths list above stays the list of what may be written,
3251 # which is what makes it worth reading. What read does need is a
3252 # filesystem grant, and valley-init makes it: the instance repository
3253 # is group-readable whether or not it is one of the served projects.
3254 environment = {
3255 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
3256 GIT_CONFIG_KEY_0 = "safe.directory";
3257 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
3258 TMPDIR = integratorStateDir;
3259 }
3260 // lib.optionalAttrs (instanceRepo != null) {
3261 GIT_CONFIG_KEY_1 = "safe.directory";
3262 GIT_CONFIG_VALUE_1 = instanceRepo;
3263 };
3264 serviceConfig = {
3265 ExecStart = integratorCommand;
3266 EnvironmentFile = "-${integratorEnv}/%i";
3267 Restart = "on-failure";
3268 RestartSec = "10s";
3269 User = cfg.integrator.user;
3270 Group = cfg.group;
3271 StateDirectory = integratorStateName;
3272 StateDirectoryMode = "0700";
3273 WorkingDirectory = integratorStateDir;
3274 NoNewPrivileges = true;
3275 ProtectSystem = "strict";
3276 # Everything the controller may write, named where a reader of the
3277 # unit meets it. Under ProtectSystem=strict the rest of the
3278 # filesystem is read-only, so this list is the whole of what the
3279 # service can touch, and it is worth being able to read it as such
3280 # rather than as the exceptions plus whatever else is implied.
3281 #
3282 # Its own directory: its state, and the scratch root TMPDIR names.
3283 # A declaration says it here rather than relying on the state
3284 # directory being read-write by virtue of being declared, which is
3285 # not something this unit found to be true.
3286 #
3287 # The one repository it serves, and the nix daemon's socket —
3288 # recomputing a closure means asking the daemon, and connecting to
3289 # a unix socket needs write access to it.
3290 #
3291 # Its own wake directory, where it removes due.
3292 # The leading - starts the controller even when the directory is
3293 # missing; it then says so and passes on its interval.
3294 #
3295 # The worker's wake directory, where a landing marks the worker due.
3296 #
3297 # The instance project's controller also writes the floor readers'
3298 # wake directories, in the drop-in below, and no other controller
3299 # does.
3300 ReadWritePaths = [
3301 integratorStateDir
3302 "${cfg.dataDir}/%i.git"
3303 "/nix/var/nix/daemon-socket"
3304 "-${integratorWakeRoot}/%i"
3305 ]
3306 ++ lib.optional cfg.worker.enable workerWakeDir;
3307 ProtectHome = true;
3308 PrivateTmp = true;
3309 PrivateDevices = true;
3310 ProtectClock = true;
3311 ProtectHostname = true;
3312 ProtectKernelLogs = true;
3313 ProtectKernelModules = true;
3314 ProtectKernelTunables = true;
3315 ProtectControlGroups = true;
3316 ProtectProc = "invisible";
3317 RestrictAddressFamilies = [
3318 "AF_INET"
3319 "AF_INET6"
3320 "AF_UNIX"
3321 ];
3322 RestrictNamespaces = true;
3323 RestrictRealtime = true;
3324 RestrictSUIDSGID = true;
3325 LockPersonality = true;
3326 CapabilityBoundingSet = "";
3327 SystemCallArchitectures = "native";
3328 SystemCallFilter = [ "@system-service" ];
3329 # Group write, not the bus unit's 0077: the git user owns these
3330 # repositories and has to stay able to write what a controller
3331 # leaves in them.
3332 UMask = "0002";
3333 };
3334 };
3335
3336 # The instance project's controller marks every floor reader after a
3337 # floor landing, so its sandbox may write their wake directories. A
3338 # drop-in on that one instance adds them to the template's list, which
3339 # it extends. It is written as text, and sets nothing else: a drop-in
3340 # declared as a service would carry the default PATH, which would
3341 # replace the template's and its nix.
3342 systemd.units."valley-integrator@${toString cfg.integrator.instanceProject}.service" =
3343 lib.mkIf (cfg.integrator.enable && floorReaders != [ ])
3344 {
3345 overrideStrategy = "asDropin";
3346 text = ''
3347 [Service]
3348 ${lib.concatMapStrings (r: "ReadWritePaths=-${integratorWakeDir r}\n") floorReaders}'';
3349 };
3350
3351 # What pushes the mirrors: a path unit per published project, watching
3352 # its publish queue, and the drain it starts.
3353 systemd.paths."valley-publish@" = lib.mkIf (publishedProjects != { }) {
3354 description = "Watch the publish queue of %i";
3355 pathConfig.DirectoryNotEmpty = "${cfg.dataDir}/%i.git/${publishQueueName}";
3356 };
3357
3358 # It runs as the git user, with ssh on its path, because the mirror
3359 # credentials are that user's. Each run drains the whole queue, so starts
3360 # are at most one per queued move, and a burst of moves must not trip
3361 # systemd's start limit and leave the queue undrained. A run is bounded
3362 # instead: one that hangs on a mirror is cut off after 15 minutes, and
3363 # systemd stops its whole cgroup, so nothing it started outlives it. A
3364 # run that fails or is cut off leaves its moves queued, and systemd
3365 # starts it again after a delay that grows from 30 seconds to 15 minutes,
3366 # until a run succeeds. While it waits to restart, the unit is not
3367 # inactive, so the path unit does not start it again sooner.
3368 systemd.services."valley-publish@" = lib.mkIf (publishedProjects != { }) {
3369 description = "Push the moves queued on %i to its mirrors";
3370 after = [ "valley-init.service" ];
3371 unitConfig.RequiresMountsFor = cfg.dataDir;
3372 startLimitIntervalSec = 0;
3373 path = [ config.programs.ssh.package ];
3374 serviceConfig = {
3375 Type = "oneshot";
3376 ExecStart = "${publishDrains}/%i";
3377 User = cfg.user;
3378 Group = cfg.group;
3379 WorkingDirectory = "${cfg.dataDir}/%i.git";
3380 TimeoutStartSec = "15min";
3381 Restart = "on-failure";
3382 RestartSec = "30s";
3383 RestartSteps = 5;
3384 RestartMaxDelaySec = "15min";
3385 };
3386 };
3387
3388 # wantedBy on a template unit enables nothing, so the instances the
3389 # declaration asks for are pulled in by name.
3390 systemd.targets.valley-publish = lib.mkIf (publishedProjects != { }) {
3391 description = "What pushes the valley's mirrors";
3392 wantedBy = [ "multi-user.target" ];
3393 wants = map (name: "valley-publish@${name}.path") (lib.attrNames publishedProjects);
3394 };
3395
3396 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
3397 description = "The valley integrator's controllers";
3398 wantedBy = [ "multi-user.target" ];
3399 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
3400 };
3401
3402 # The build slice. The daemon runs every build in its own cgroup,
3403 # whoever asked for it, so a cap on a build is a cap on the daemon: the
3404 # slice holds nix-daemon.service, and the check worker when it runs,
3405 # and the kernel holds everything in it to the quota and the memory cap
3406 # together, with no swap. Every user's builds through the daemon share
3407 # the caps. A nix command that does not go through the daemon, such as
3408 # one root runs on the store directly, is outside the slice and
3409 # uncapped.
3410 #
3411 # A build that takes the slice past its memory cap is ended by the
3412 # kernel's OOM killer, which kills the process in the slice using the
3413 # most memory. That is usually the build that went past, and it can be
3414 # another build in the slice. The rest of the host goes on as it was.
3415 # When the OOM killer kills one of the daemon's processes, systemd keeps
3416 # the daemon's unit running, since the unit delegates its cgroup
3417 # (OOMPolicy=continue). Nothing exempts the daemon's own processes from
3418 # being the one chosen.
3419 # The slice sets no device policy, so a build keeps the /dev/kvm the
3420 # daemon gives NixOS tests.
3421 systemd.slices.valley-builds = lib.mkIf cfg.buildSlice.enable {
3422 description = "Every build of the nix daemon, under the host's caps";
3423 sliceConfig = {
3424 CPUQuota = cfg.buildSlice.cpuQuota;
3425 MemoryMax = cfg.buildSlice.memoryMax;
3426 MemorySwapMax = "0";
3427 };
3428 };
3429
3430 systemd.services.nix-daemon.serviceConfig.Slice = lib.mkIf cfg.buildSlice.enable buildSlice;
3431
3432 # One pass of the worker, as a oneshot the timer below starts. A pass
3433 # that finds nothing to build reads origin and ends. Two passes never
3434 # overlap: systemd starts the unit only while it is inactive, and the
3435 # worker's own lock in its state directory serializes any pass started
3436 # by hand.
3437 #
3438 # The unit runs in the build slice, so its evaluation shares the caps
3439 # with the builds. A pass runs worker.batches batches at once, attest
3440 # builds worker.buildSlots checks at once in each, and NIX_CONFIG lets
3441 # each of those builds build worker.maxJobs derivations at once. The
3442 # builds themselves run in the daemon, under the slice's quota and
3443 # memory cap, which they share with the worker. A stop of the unit
3444 # stops the pass and every attest it started.
3445 systemd.services.valley-worker = lib.mkIf cfg.worker.enable {
3446 description = "One pass of the valley check worker";
3447 after = [
3448 "network.target"
3449 "sshd.service"
3450 "valley-init.service"
3451 "systemd-tmpfiles-setup.service"
3452 ];
3453 unitConfig.RequiresMountsFor = [
3454 workerDir
3455 workerWakeDir
3456 ];
3457 # A burst of marks must never leave the unit refusing to start: the
3458 # path unit starts a pass at most once per pass that ends, and a pass
3459 # that could not claim due waits out RestartSec first.
3460 unitConfig.StartLimitIntervalSec = 0;
3461 # A switch never starts, restarts or stops the worker. Restarting a
3462 # oneshot that is mid-pass makes the switch wait for the pass to end,
3463 # and a pass can run for many minutes. A pass already running ends on
3464 # the binary and configuration it started with; the next pass, from
3465 # the timer or the path unit, uses the new ones.
3466 restartIfChanged = false;
3467 stopIfChanged = false;
3468 # nix is the machine's own, for the reason the integrator's is.
3469 path = [
3470 workerPackage
3471 attestPackage
3472 pkgs.git
3473 pkgs.diffutils
3474 config.programs.ssh.package
3475 config.nix.package
3476 ];
3477 environment = {
3478 HOME = workerDir;
3479 XDG_CACHE_HOME = "${workerDir}/cache";
3480 GIT_SSH_COMMAND = workerSsh;
3481 NIX_CONFIG = workerNixConfig;
3482 };
3483 script = workerScript;
3484 serviceConfig = {
3485 Type = "oneshot";
3486 User = "valley-worker";
3487 Group = "valley-worker";
3488 # A pass that could not claim its due mark exits 75 (status/wake.go),
3489 # and the due is still there. It is started again one interval
3490 # later, and the path unit, which sees the unit restarting, starts
3491 # nothing meanwhile. Any other status is left to the timer.
3492 RestartForceExitStatus = "75";
3493 RestartSec = cfg.worker.interval;
3494 Slice = buildSlice;
3495 NoNewPrivileges = true;
3496 ProtectSystem = "strict";
3497 # Its own directory, its wake directory, and the nix daemon's
3498 # socket, which a client writes to connect. The roots attest adds
3499 # are symlinks in its own directory, which the daemon records
3500 # through the socket.
3501 ReadWritePaths = [
3502 workerDir
3503 workerWakeDir
3504 "/nix/var/nix/daemon-socket"
3505 ];
3506 ProtectHome = true;
3507 PrivateTmp = true;
3508 PrivateDevices = true;
3509 ProtectClock = true;
3510 ProtectHostname = true;
3511 ProtectKernelLogs = true;
3512 ProtectKernelModules = true;
3513 ProtectKernelTunables = true;
3514 ProtectControlGroups = true;
3515 ProtectProc = "invisible";
3516 RestrictAddressFamilies = [
3517 "AF_INET"
3518 "AF_INET6"
3519 "AF_UNIX"
3520 ];
3521 RestrictNamespaces = true;
3522 RestrictRealtime = true;
3523 RestrictSUIDSGID = true;
3524 LockPersonality = true;
3525 CapabilityBoundingSet = "";
3526 SystemCallArchitectures = "native";
3527 SystemCallFilter = [ "@system-service" ];
3528 UMask = "0077";
3529 };
3530 };
3531
3532 # The timer is the worker's recovery scan. Its first pass starts soon
3533 # after the timer starts, at boot or at the switch that adds it, and
3534 # reads everything, so a mark lost between a ref moving and its hook
3535 # running, or a claim a killed pass left, is made good. Each later pass
3536 # starts one interval after the last one ended, and is what retries a
3537 # failed batch or push once its wait is over. A pass may start inside a
3538 # switch. Nothing waits for it: the service is wanted by no target.
3539 systemd.timers.valley-worker = lib.mkIf cfg.worker.enable {
3540 description = "Run the valley check worker";
3541 wantedBy = [ "timers.target" ];
3542 timerConfig = {
3543 OnActiveSec = "1s";
3544 OnUnitInactiveSec = cfg.worker.interval;
3545 };
3546 };
3547
3548 # A pass whenever the wake directory holds due. A pass claims each mark
3549 # made while it runs, and reads again. PathExists, and not PathChanged:
3550 # a mark made after a pass's last claim is seen when that pass ends,
3551 # and starts the next one then. claimed starts nothing.
3552 systemd.paths.valley-worker = lib.mkIf cfg.worker.enable {
3553 description = "Start the valley check worker when a ref it reads moves";
3554 wantedBy = [ "multi-user.target" ];
3555 pathConfig.PathExists = "${workerWakeDir}/due";
3556 };
3557
3558 # One restacker controller for each project listed: valley-restacker
3559 # run, which reconciles at its start and then every interval. It holds
3560 # the lock on its state directory for as long as it runs, so one
3561 # controller serves a project at a time. A controller that fails is
3562 # restarted. It needs no ordering on the repositories' mounts or on
3563 # valley-init: it reads and pushes through sshd, and the git user's
3564 # shell holds a push until valley-init has converged.
3565 systemd.services."valley-restacker@" = lib.mkIf cfg.restacker.enable {
3566 description = "The valley restacker for %i";
3567 after = [
3568 "network.target"
3569 "sshd.service"
3570 ];
3571 path = [ config.programs.ssh.package ];
3572 environment = {
3573 HOME = restackerState;
3574 GIT_SSH_COMMAND = restackerSsh;
3575 };
3576 serviceConfig = {
3577 ExecStartPre = "${restackerKnownHosts} ${restackerState}";
3578 ExecStart = restackerCommand;
3579 Restart = "on-failure";
3580 RestartSec = "10s";
3581 User = "valley-restacker";
3582 Group = "valley-restacker";
3583 StateDirectory = "${restackerStateName}/%i";
3584 StateDirectoryMode = "0700";
3585 WorkingDirectory = restackerState;
3586 LoadCredential = [ "key:${toString cfg.restacker.sshKeyFile}" ];
3587 NoNewPrivileges = true;
3588 ProtectSystem = "strict";
3589 ProtectHome = true;
3590 PrivateTmp = true;
3591 PrivateDevices = true;
3592 ProtectClock = true;
3593 ProtectHostname = true;
3594 ProtectKernelLogs = true;
3595 ProtectKernelModules = true;
3596 ProtectKernelTunables = true;
3597 ProtectControlGroups = true;
3598 ProtectProc = "invisible";
3599 RestrictAddressFamilies = [
3600 "AF_INET"
3601 "AF_INET6"
3602 "AF_UNIX"
3603 ];
3604 RestrictNamespaces = true;
3605 RestrictRealtime = true;
3606 RestrictSUIDSGID = true;
3607 LockPersonality = true;
3608 CapabilityBoundingSet = "";
3609 SystemCallArchitectures = "native";
3610 SystemCallFilter = [ "@system-service" ];
3611 UMask = "0077";
3612 };
3613 };
3614
3615 # wantedBy on a template unit enables nothing, so the controllers the
3616 # declaration asks for are pulled in by name.
3617 systemd.targets.valley-restackers = lib.mkIf cfg.restacker.enable {
3618 description = "The valley restacker's controllers";
3619 wantedBy = [ "multi-user.target" ];
3620 wants = map (name: "valley-restacker@${name}.service") cfg.restacker.projects;
3621 };
3622
3623 # Offsite backup, rendered only when the declaration asks for it. The
3624 # declaration states the policy — that backup exists, its cadence and
3625 # retention; the services.valley.backup.* options supply the machine
3626 # half. Declaration absent or disabled ⇒ no restic config at all.
3627 services.restic.backups = lib.mkIf backupEnabled {
3628 valley = {
3629 initialize = true;
3630 repositoryFile = cfg.backup.repositoryFile;
3631 passwordFile = cfg.backup.passwordFile;
3632 # With the web publisher, the backup also holds the read links'
3633 # credential file's directory and the publisher's durable state:
3634 # its export key, its authorization counter and its record of what
3635 # the receiver holds. Under DynamicUser that state lives under
3636 # /var/lib/private.
3637 paths = [
3638 cfg.dataDir
3639 ]
3640 ++ lib.optionals (config.services.valley.webPublisher.enable or false) (
3641 let
3642 web = config.services.valley.webPublisher;
3643 in
3644 [
3645 (dirOf (toString web.linksFile))
3646 "/var/lib/private/${lib.removePrefix "/var/lib/" (toString web.stateDir)}"
3647 ]
3648 );
3649 # The schema admits only the restic-sftp target today; a second
3650 # target would grow a dispatch here. The service runs as root:
3651 # authenticate with the supplied identity and only the pinned
3652 # host key. No prompt can be answered inside a systemd unit, so
3653 # BatchMode + strict host key checking turn a would-be hang into
3654 # an immediate error.
3655 extraOptions = [
3656 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
3657 ];
3658 timerConfig = backupTimer.${backupPolicy.cadence};
3659 pruneOpts = [
3660 "--keep-daily ${toString backupPolicy.retention.daily}"
3661 "--keep-weekly ${toString backupPolicy.retention.weekly}"
3662 "--keep-monthly ${toString backupPolicy.retention.monthly}"
3663 ];
3664 };
3665 };
3666 }
3667
3668 # The onMain bindings (services.valley.onMain): for each, a bridge that
3669 # requests a run of the host's own unit when the project's main moves, a
3670 # path unit that starts it, and the wiring that unit needs. The module
3671 # does not generate the bound unit: the host declares it, and the module
3672 # adds the step that writes its environment and the environment file to
3673 # it.
3674 #
3675 # The bridge watches the repository's ref storage itself, with inotify:
3676 # a path unit's PathChanged= holds no watch while the unit it started
3677 # runs, so a move during a run would wait for the next move (see
3678 # identityInputs). It turns each move into a request file, which is a
3679 # level: PathExists=, as for the worker's due, looks for the file again
3680 # when the unit stops, so a request made during a run starts the next
3681 # one. The bridge starts nothing itself, so it needs no grant.
3682 (lib.mkIf (cfg.onMain != { }) {
3683 # Each bridge's user, in no group but its own. The git group, which
3684 # reads the repositories, is given to the bridge's unit alone.
3685 users.users = lib.mapAttrs' (
3686 name: _:
3687 lib.nameValuePair (onMainBridge name) {
3688 isSystemUser = true;
3689 group = onMainBridge name;
3690 description = "The valley onMain bridge ${name}";
3691 }
3692 ) cfg.onMain;
3693 users.groups = lib.mapAttrs' (name: _: lib.nameValuePair (onMainBridge name) { }) cfg.onMain;
3694
3695 systemd.tmpfiles.rules = [ "d ${onMainEnvironmentDir} 0755 root root - -" ];
3696
3697 # Each binding's path unit starts its bound unit while the bridge's
3698 # request exists and the unit is not running. The unit's first command
3699 # removes the request (onmain/main.go, writeEnvironment).
3700 systemd.paths = lib.mapAttrs' (
3701 name: b:
3702 lib.nameValuePair (onMainBridge name) {
3703 description = "Start ${b.unit} when the onMain bridge ${name} requests a run";
3704 wantedBy = [ "multi-user.target" ];
3705 pathConfig = {
3706 PathExists = onMainRequest name;
3707 Unit = b.unit;
3708 };
3709 }
3710 ) cfg.onMain;
3711
3712 systemd.services = lib.mkMerge [
3713 (lib.mapAttrs' (
3714 name: b:
3715 lib.nameValuePair (onMainBridge name) {
3716 description = "Request a run of ${b.unit} when ${b.project}'s main moves";
3717 wantedBy = [ "multi-user.target" ];
3718 after = [ "valley-init.service" ];
3719 unitConfig.RequiresMountsFor = cfg.dataDir;
3720 # git refuses a repository its caller does not own. An empty
3721 # entry resets what the system's configuration trusts, and one
3722 # exact entry follows, as for the web publisher.
3723 environment = {
3724 GIT_CONFIG_COUNT = "2";
3725 GIT_CONFIG_KEY_0 = "safe.directory";
3726 GIT_CONFIG_VALUE_0 = "";
3727 GIT_CONFIG_KEY_1 = "safe.directory";
3728 GIT_CONFIG_VALUE_1 = onMainRepo b;
3729 };
3730 # No Restart: a bridge stops only when its watch cannot be set up
3731 # on the repository or the repository cannot be read as files ref
3732 # storage, and each start requests a run again. The operator
3733 # restarts it once the fault is fixed.
3734 serviceConfig = {
3735 ExecStart = lib.escapeShellArgs [
3736 (lib.getExe cfg.packages.onmain)
3737 "watch"
3738 "--repo"
3739 (onMainRepo b)
3740 "--commit-file"
3741 (onMainCommit name)
3742 "--request-file"
3743 (onMainRequest name)
3744 ];
3745 User = onMainBridge name;
3746 Group = onMainBridge name;
3747 SupplementaryGroups = [ cfg.group ];
3748 # Kept when the bridge stops, so a start of the unit by hand
3749 # still finds the commit, until the host reboots.
3750 RuntimeDirectory = onMainBridge name;
3751 RuntimeDirectoryPreserve = true;
3752 UMask = "0022";
3753 # The data directory is an empty, read-only file system here
3754 # with the one repository bound into it, read-only: the git
3755 # group reads every repository, and writes the integrated
3756 # ones. The keys the host module is given are out of reach. The
3757 # bind holds the repository directory that existed when the
3758 # bridge started, so a repository replaced at its path, as by a
3759 # restore, is followed once the bridge is restarted.
3760 ProtectSystem = "strict";
3761 TemporaryFileSystem = "${toString cfg.dataDir}:ro";
3762 BindReadOnlyPaths = [ (onMainRepo b) ];
3763 InaccessiblePaths = map (p: "-${toString p}") (
3764 lib.filter (p: p != null) [
3765 cfg.integrator.signingKeyFile
3766 cfg.restacker.sshKeyFile
3767 cfg.backup.sshKeyFile
3768 cfg.backup.passwordFile
3769 cfg.backup.repositoryFile
3770 ]
3771 );
3772 NoNewPrivileges = true;
3773 ProtectHome = true;
3774 PrivateTmp = true;
3775 PrivateDevices = true;
3776 PrivateNetwork = true;
3777 ProtectClock = true;
3778 ProtectHostname = true;
3779 ProtectKernelLogs = true;
3780 ProtectKernelModules = true;
3781 ProtectKernelTunables = true;
3782 ProtectControlGroups = true;
3783 ProtectProc = "invisible";
3784 RestrictAddressFamilies = [ "AF_UNIX" ];
3785 RestrictNamespaces = true;
3786 RestrictRealtime = true;
3787 RestrictSUIDSGID = true;
3788 LockPersonality = true;
3789 CapabilityBoundingSet = "";
3790 SystemCallArchitectures = "native";
3791 SystemCallFilter = [ "@system-service" ];
3792 };
3793 }
3794 ) cfg.onMain)
3795 # The bound units. Their first ExecStartPre=, run as root, removes the
3796 # bridge's request, reads its commit file, accepts it only as one
3797 # commit ID, and writes the environment file with the repository this
3798 # module names. systemd reads an environment file again for each
3799 # command it starts, so the unit's command reads the values just
3800 # written. The file is added after any the host names, so its values
3801 # are the ones the unit reads, and it may be missing for that first
3802 # command. The unit's start limit is the host's.
3803 (lib.mapAttrs' (
3804 name: b:
3805 lib.nameValuePair (lib.removeSuffix ".service" b.unit) {
3806 serviceConfig.ExecStartPre = lib.mkBefore [
3807 "+${
3808 lib.escapeShellArgs [
3809 (lib.getExe cfg.packages.onmain)
3810 "environment"
3811 "--repo"
3812 (onMainRepo b)
3813 "--commit-file"
3814 (onMainCommit name)
3815 "--request-file"
3816 (onMainRequest name)
3817 "--out"
3818 (onMainEnvironment name)
3819 ]
3820 }"
3821 ];
3822 serviceConfig.EnvironmentFile = lib.mkAfter [ "-${onMainEnvironment name}" ];
3823 }
3824 ) cfg.onMain)
3825 ];
3826 })
3827 ]);
3828}