gunk-dev/the-valley

valley-host.nix

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