gunk-dev/the-valley

valley-host.nix

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