gunk-dev/the-valley

valley-host.nix

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