gunk-dev/the-valley

valley-host.nix

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