gunk-dev/the-valley

valley-host.nix

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