gunk-dev/the-valley

valley-host.nix

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