gunk-dev/the-valley

valley-host.nix

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