gunk-dev/the-valley

valley-host.nix

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