gunk-dev/the-valley

valley-host.nix

sourceffab7f1a0441main's published tip history
113.7 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. The web publisher
1569 (`services.valley.webPublisher`) reads its read grants from the
1570 registry at this ref too.
1571 '';
1572 };
1573
1574 directory = lib.mkOption {
1575 type = lib.types.str;
1576 default = "identity";
1577 description = ''
1578 The registry's directory in that tip. It is a CUE package: the
1579 directory is the enumeration, and every `*.cue` document
1580 directly in it unifies into one registry.
1581 '';
1582 };
1583
1584 interval = lib.mkOption {
1585 type = lib.types.str;
1586 default = "5m";
1587 example = "1m";
1588 description = ''
1589 How long between compilations. The compiler is level-triggered
1590 and idempotent — it renders the current tip and replaces an
1591 artifact only when its bytes changed — so a timer is the whole
1592 of the trigger, and a landed registry change takes effect within
1593 one interval.
1594 '';
1595 };
1596 };
1597
1598 # Machine integration for the declared backup policy. The declaration
1599 # states WHAT must hold (offsite backup, cadence, retention); these
1600 # options supply HOW on this machine — where the repository is and how
1601 # to authenticate. All are paths to files the consumer provisions
1602 # (e.g. agenix), required when the declaration enables backup. Point
1603 # them at runtime paths, never at files in the Nix store.
1604 backup = {
1605 repositoryFile = lib.mkOption {
1606 type = lib.types.nullOr lib.types.path;
1607 default = null;
1608 example = "/run/agenix/valley-restic-repo";
1609 description = ''
1610 File containing the restic repository URL, for the sftp target
1611 e.g. `sftp://backup@backup.example.org:23//./backups/valley`.
1612 '';
1613 };
1614
1615 passwordFile = lib.mkOption {
1616 type = lib.types.nullOr lib.types.path;
1617 default = null;
1618 example = "/run/agenix/valley-restic-password";
1619 description = ''
1620 File containing the restic repository encryption password.
1621 Losing it loses the backups — keep a copy somewhere that
1622 survives this host.
1623 '';
1624 };
1625
1626 sshKeyFile = lib.mkOption {
1627 type = lib.types.nullOr lib.types.path;
1628 default = null;
1629 example = "/run/agenix/valley-git-ssh-key";
1630 description = ''
1631 SSH private key that authenticates to the sftp target. The
1632 backup service runs as root, so any identity the target
1633 authorizes works — reusing the mirror key is fine.
1634 '';
1635 };
1636
1637 knownHostsFile = lib.mkOption {
1638 type = lib.types.nullOr lib.types.path;
1639 default = null;
1640 example = "/var/lib/valley-backup/known_hosts";
1641 description = ''
1642 known_hosts file pinning the sftp target's host key. Pin from
1643 the provider's published fingerprints, not a blind ssh-keyscan.
1644 '';
1645 };
1646 };
1647
1648 # The programs the host runs, as this flake builds them
1649 # (nix/packages.nix). These options are internal: a host has no reason
1650 # to set them. The module checks set them to stand-ins with the same
1651 # binary names (nix/checks/hosts.nix), so a check that reads only what
1652 # the module renders does not change when one of the programs does.
1653 packages = {
1654 integrator = lib.mkOption {
1655 type = lib.types.package;
1656 internal = true;
1657 default = flakePackages.integrator;
1658 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).integrator";
1659 description = "The integrator, which the controllers and the signers publisher run.";
1660 };
1661
1662 identity = lib.mkOption {
1663 type = lib.types.package;
1664 internal = true;
1665 default = flakePackages.identity;
1666 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).identity";
1667 description = "The identity registry compiler, which valley-identity runs.";
1668 };
1669
1670 valleyhook = lib.mkOption {
1671 type = lib.types.package;
1672 internal = true;
1673 default = flakePackages.valleyhook;
1674 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valleyhook";
1675 description = "The push policy, which every pre-receive hook and the git user's login shell run.";
1676 };
1677 };
1678 };
1679
1680 config = lib.mkIf cfg.enable {
1681 assertions = [
1682 {
1683 assertion = cfg.authorizedKeys != [ ];
1684 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
1685 }
1686 ]
1687 ++ lib.optionals backupEnabled (
1688 lib.mapAttrsToList (name: what: {
1689 assertion = cfg.backup.${name} != null;
1690 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).";
1691 }) backupSecretOptions
1692 )
1693 ++ lib.optionals cfg.integrator.enable (
1694 lib.mapAttrsToList (name: what: {
1695 assertion = cfg.integrator.${name} != null;
1696 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
1697 }) integratorPathOptions
1698 ++ [
1699 {
1700 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
1701 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.";
1702 }
1703 # The rule the integrator reads the rendered file by
1704 # (note/signerprojects.go): every name and project is printable
1705 # ASCII with no space, so only the spaces this renders separate
1706 # words, and a name holds no plus and opens with no #, which
1707 # would make its line a comment.
1708 {
1709 assertion =
1710 let
1711 word = w: builtins.match "[!-~]+" w != null;
1712 name = n: word n && !lib.hasInfix "+" n && !lib.hasPrefix "#" n;
1713 in
1714 lib.all (n: name n && lib.all word cfg.integrator.signerProjects.${n}) (
1715 lib.attrNames cfg.integrator.signerProjects
1716 );
1717 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.";
1718 }
1719 {
1720 assertion =
1721 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
1722 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.";
1723 }
1724 {
1725 assertion = cfg.integrator.user != cfg.user;
1726 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
1727 }
1728 {
1729 assertion = integratedProjects != { };
1730 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.";
1731 }
1732 ]
1733 )
1734 ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) (
1735 let
1736 name = cfg.integrator.instanceProject;
1737 protected = gitProjects.${name}.protection.refs or [ ];
1738 # The web publisher (webui-publisher.nix) reads the registry at
1739 # identity.ref too, when its module is imported and on.
1740 publisher = config.services.valley.webPublisher.enable or false;
1741 read =
1742 lib.optional cfg.integrator.enable "refs/heads/main"
1743 ++ lib.optional (cfg.identity.enable || publisher) cfg.identity.ref;
1744 in
1745 map (ref: {
1746 assertion = lib.any (pattern: refPatternMatches pattern ref) protected;
1747 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}.";
1748 }) read
1749 )
1750 ++ [
1751 {
1752 assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) (
1753 sshdValues "AcceptEnv" ++ sshdValues "SetEnv"
1754 ));
1755 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.";
1756 }
1757 {
1758 assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv"));
1759 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.";
1760 }
1761 {
1762 assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv"));
1763 message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it.";
1764 }
1765 {
1766 assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment");
1767 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.";
1768 }
1769 {
1770 assertion = conflictingKeys == { };
1771 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.";
1772 }
1773 {
1774 assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ];
1775 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.";
1776 }
1777 ]
1778 ++ lib.optionals cfg.identity.enable [
1779 {
1780 assertion = cfg.integrator.instanceProject != null;
1781 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.";
1782 }
1783 {
1784 assertion = cfg.integrator.knownSignersFile == null;
1785 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.";
1786 }
1787 ]
1788 ++ lib.optionals cfg.worker.enable (
1789 let
1790 name = cfg.worker.signerName;
1791 listed = cfg.integrator.signerProjects.${name} or null;
1792 sorted = l: lib.sort lib.lessThan (lib.unique l);
1793 unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.worker.projects;
1794 in
1795 [
1796 {
1797 assertion = cfg.integrator.enable;
1798 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.";
1799 }
1800 {
1801 assertion = cfg.integrator.instanceProject != null;
1802 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.";
1803 }
1804 {
1805 assertion = cfg.worker.projects != [ ] && unserved == [ ];
1806 message = "services.valley.worker.projects must name at least one project, and only projects this host serves${
1807 lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}"
1808 }.";
1809 }
1810 # The restriction (oc-13c6bd6). Every controller that shares the
1811 # known-signers file counts a key it holds in every project, so a
1812 # worker whose key is not restricted would be trusted for projects
1813 # it never builds.
1814 {
1815 assertion = listed != null && sorted listed == sorted cfg.worker.projects;
1816 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}\" = [ ${
1817 lib.concatMapStringsSep " " (p: "\"${p}\"") cfg.worker.projects
1818 } ];";
1819 }
1820 {
1821 assertion = name != integratorName;
1822 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.";
1823 }
1824 {
1825 assertion = cfg.buildSlice.enable;
1826 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.";
1827 }
1828 {
1829 assertion = config.services.openssh.enable && config.nix.enable;
1830 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.";
1831 }
1832 ]
1833 );
1834
1835 users.groups.${cfg.group} = { };
1836
1837 users.users.${cfg.user} = {
1838 isSystemUser = true;
1839 group = cfg.group;
1840 home = cfg.dataDir;
1841 # The valley's shell, in front of git-shell: it derives the principal
1842 # from the authenticated key, drops the GIT_ environment, and pauses
1843 # pushes until valley-init has converged. git-shell then allows only
1844 # git-upload-pack, git-receive-pack and git-upload-archive, and rejects
1845 # interactive logins (no ~/git-shell-commands).
1846 shell = "${gitShell}/bin/valley-git-shell";
1847 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
1848 };
1849
1850 # The integrator's own account. No shell, no keys, no home of its own
1851 # beyond the state directory its units get; the git group is the only
1852 # thing it holds.
1853 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
1854 isSystemUser = true;
1855 group = cfg.group;
1856 home = "/var/lib/valley-integrator";
1857 description = "The valley integrator";
1858 };
1859
1860 # The worker's own account. Its group is its own, not the git group, so
1861 # it can neither read nor write the repositories on disk: it reaches
1862 # them as an ssh client, as anyone else does.
1863 users.users.valley-worker = lib.mkIf cfg.worker.enable {
1864 isSystemUser = true;
1865 group = "valley-worker";
1866 home = workerDir;
1867 description = "The valley check worker";
1868 };
1869 users.groups.valley-worker = lib.mkIf cfg.worker.enable { };
1870
1871 services.openssh.enable = lib.mkDefault true;
1872
1873 # The git user's key files, named in its Match block so no other file
1874 # can authorize a key for it. The declared keys come first, and they stay
1875 # authorized beside the compiled ones: a compiled file can only ever
1876 # add, so an empty or missing one — a first boot before the first
1877 # compilation, a registry that lost an entry, a bug here — cannot take
1878 # the git user's access away. Which is the point: the assertion above
1879 # keeps at least one key declared, and that key is the way back in.
1880 #
1881 # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys
1882 # under its home is not read, and no AuthorizedKeysCommand runs, so every
1883 # entry a pusher can arrive through carries the tag this module or the
1884 # compiler wrote, and the assertions and the compiler hold those to one
1885 # tag per key.
1886 #
1887 # Belt-and-braces hardening for the git user beside it. The trailing
1888 # `Match All` closes the block so it can't scope directives appended to
1889 # sshd_config after this snippet.
1890 services.openssh.extraConfig = ''
1891 Match User ${cfg.user}
1892 AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"}
1893 AuthorizedKeysCommand none
1894 ExposeAuthInfo yes
1895 AllowTcpForwarding no
1896 AllowAgentForwarding no
1897 X11Forwarding no
1898 PermitTunnel no
1899 Match All
1900 '';
1901
1902 # git-shell spawns git-receive-pack/git-upload-pack from PATH
1903 environment.systemPackages = [ pkgs.git ];
1904
1905 systemd.tmpfiles.rules = [
1906 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
1907 ]
1908 ++ lib.optionals cfg.bus.enable [
1909 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
1910 ]
1911 ++ lib.optionals cfg.worker.enable [
1912 "d ${workerDir} 0700 valley-worker valley-worker - -"
1913 ];
1914
1915 # The bus itself. It runs as the git user — the store directory lives in
1916 # that user's data — but the sandbox is what confines it: the unit can
1917 # write nowhere except its store directory.
1918 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
1919 description = "The valley event bus (NATS JetStream)";
1920 wantedBy = [ "multi-user.target" ];
1921 after = [
1922 "network.target"
1923 "systemd-tmpfiles-setup.service"
1924 ];
1925 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
1926 serviceConfig = {
1927 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
1928 Restart = "on-failure";
1929 User = cfg.user;
1930 Group = cfg.group;
1931 LimitNOFILE = 65536;
1932 NoNewPrivileges = true;
1933 ProtectSystem = "strict";
1934 ReadWritePaths = [ cfg.bus.storeDir ];
1935 ProtectHome = true;
1936 PrivateTmp = true;
1937 PrivateDevices = true;
1938 ProtectClock = true;
1939 ProtectHostname = true;
1940 ProtectKernelLogs = true;
1941 ProtectKernelModules = true;
1942 ProtectKernelTunables = true;
1943 ProtectControlGroups = true;
1944 ProtectProc = "invisible";
1945 RestrictAddressFamilies = [
1946 "AF_INET"
1947 "AF_INET6"
1948 "AF_UNIX"
1949 ];
1950 RestrictNamespaces = true;
1951 RestrictRealtime = true;
1952 RestrictSUIDSGID = true;
1953 LockPersonality = true;
1954 CapabilityBoundingSet = "";
1955 SystemCallArchitectures = "native";
1956 SystemCallFilter = [ "@system-service" ];
1957 UMask = "0077";
1958 };
1959 };
1960
1961 # The stream is config, not state: (re)created idempotently on every
1962 # boot, capturing everything under valley.>. An existing stream — and
1963 # the events in it — is left untouched.
1964 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
1965 description = "Create the valley event stream";
1966 wantedBy = [ "multi-user.target" ];
1967 requires = [ "valley-bus.service" ];
1968 after = [ "valley-bus.service" ];
1969 serviceConfig = {
1970 Type = "oneshot";
1971 User = cfg.user;
1972 Group = cfg.group;
1973 };
1974 path = [ pkgs.natscli ];
1975 script = ''
1976 # The server needs a moment to accept connections after startup.
1977 for _ in $(seq 1 50); do
1978 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
1979 sleep 0.2
1980 done
1981 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
1982 nats --server ${busUrl} stream add valley \
1983 --subjects 'valley.>' --storage file --defaults
1984 fi
1985 '';
1986 };
1987
1988 # Create missing bare repos and (re)wire the managed hooks on every
1989 # activation where the declaration changed.
1990 systemd.services.valley-init = {
1991 description = "Initialize the valley host's bare git repositories";
1992 wantedBy = [ "multi-user.target" ];
1993 after = [ "systemd-tmpfiles-setup.service" ];
1994 unitConfig.RequiresMountsFor = cfg.dataDir;
1995 serviceConfig = {
1996 Type = "oneshot";
1997 User = cfg.user;
1998 Group = cfg.group;
1999 };
2000 path = [
2001 pkgs.git
2002 pkgs.diffutils
2003 ];
2004 # Everything init can wire is wired before it fails. A conflict in one
2005 # repository is reported, the rest of the host is still converged,
2006 # and only then does the unit fail, so the activation fails loudly
2007 # without leaving another repository's hook out of date.
2008 script = ''
2009 # Pushes pause the moment a convergence starts, and resume only once
2010 # it has finished: the record is removed first and written last.
2011 rm -f ${convergedRecord}
2012 ${valleyInitBody}
2013 printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp
2014 mv -f ${convergedRecord}.tmp ${convergedRecord}
2015 '';
2016 };
2017
2018 # The registry compiler, on a timer. It renders the instance
2019 # repository's integrated tip into the two artifacts the gates read;
2020 # nothing else on the host writes them.
2021 #
2022 # It runs as the git user rather than under an identity of its own,
2023 # which is the one place this module steps back from the service split
2024 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
2025 # anyone but root or the account it authorizes, so the choice is the git
2026 # user or root, and the git user is the smaller grant.
2027 #
2028 # Level-triggered, like the rest: a compilation reads the current tip
2029 # and replaces an artifact only when its bytes changed, so re-running is
2030 # free and the timer needs no coordination with anything.
2031 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
2032 description = "Compile the valley identity registry into what the gates check";
2033 wantedBy = [ "multi-user.target" ];
2034 after = [ "valley-init.service" ];
2035 requires = [ "valley-init.service" ];
2036 unitConfig.RequiresMountsFor = cfg.dataDir;
2037 serviceConfig = {
2038 Type = "oneshot";
2039 ExecStart = identityCommand;
2040 User = cfg.user;
2041 Group = cfg.group;
2042 StateDirectory = identityStateName;
2043 # sshd walks every directory above an authorized-keys file and
2044 # refuses a group- or world-writable one, so the state directory is
2045 # 0755 deliberately rather than the 0700 a service's state usually
2046 # takes. Nothing secret lives in it: a registry is public keys.
2047 StateDirectoryMode = "0755";
2048 NoNewPrivileges = true;
2049 ProtectSystem = "strict";
2050 ReadWritePaths = [ identityStateDir ];
2051 ProtectHome = true;
2052 PrivateTmp = true;
2053 PrivateDevices = true;
2054 ProtectClock = true;
2055 ProtectHostname = true;
2056 ProtectKernelLogs = true;
2057 ProtectKernelModules = true;
2058 ProtectKernelTunables = true;
2059 ProtectControlGroups = true;
2060 ProtectProc = "invisible";
2061 RestrictAddressFamilies = [ "AF_UNIX" ];
2062 RestrictNamespaces = true;
2063 RestrictRealtime = true;
2064 RestrictSUIDSGID = true;
2065 LockPersonality = true;
2066 CapabilityBoundingSet = "";
2067 SystemCallArchitectures = "native";
2068 SystemCallFilter = [ "@system-service" ];
2069 UMask = "0022";
2070 };
2071 };
2072
2073 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
2074 description = "Re-compile the valley identity registry";
2075 wantedBy = [ "timers.target" ];
2076 timerConfig = {
2077 OnBootSec = "1m";
2078 OnUnitActiveSec = cfg.identity.interval;
2079 };
2080 };
2081
2082 # The signers publication, refs/the-valley/signers, is written by a
2083 # oneshot of its own. It runs as the git user, which owns the instance
2084 # repository, and its sandbox lets it write that repository and nothing
2085 # else. It is not part of valley-init, which runs only on activation,
2086 # nor of the registry compiler, whose sandbox writes only its state
2087 # directory. Only the host's machinery writes the ref, never a push:
2088 # the hook refuses every push to it. This unit writes it, and the
2089 # integrator can, being in the group the repository is shared with
2090 # because it lands code there.
2091 #
2092 # What starts it: every boot and every activation, after valley-init,
2093 # which covers a changed signing name, signers path or signer projects
2094 # list; and the path
2095 # unit below, whenever the known-signers file changes, which covers
2096 # each compilation that changed it and a hand-provisioned file being
2097 # replaced. A run reads the current file and name and writes the ref
2098 # only when the tree it makes differs, so a run with nothing new is
2099 # free. Both values are in one tree under one ref, so a client never
2100 # reads one value without the other. A run holds a lock in the
2101 # instance repository from reading the file to moving the ref, so two
2102 # runs take turns, and one that read an older file cannot publish it
2103 # over a newer one. The ref also moves with a compare-and-swap.
2104 #
2105 # A run that cannot read the file, or reads one that is not a list of
2106 # verifier keys, fails and leaves the last publication in place. That
2107 # is the file the controllers were given before it changed, and the
2108 # journal says why. A file with no key in it, as the compiler writes
2109 # once every signing key is revoked, is published, so clients stop
2110 # verifying with the revoked keys.
2111 systemd.services.valley-signers = lib.mkIf publishesSigners {
2112 description = "Publish what clients verify the valley integrator's transfer statements with";
2113 wantedBy = [ "multi-user.target" ];
2114 after = [ "valley-init.service" ] ++ lib.optional cfg.identity.enable "valley-identity.service";
2115 requires = [ "valley-init.service" ];
2116 unitConfig.RequiresMountsFor = cfg.dataDir;
2117 serviceConfig = {
2118 Type = "oneshot";
2119 ExecStart = signersCommand;
2120 User = cfg.user;
2121 Group = cfg.group;
2122 NoNewPrivileges = true;
2123 ProtectSystem = "strict";
2124 ReadWritePaths = [ instanceRepo ];
2125 ProtectHome = true;
2126 PrivateTmp = true;
2127 PrivateDevices = true;
2128 ProtectClock = true;
2129 ProtectHostname = true;
2130 ProtectKernelLogs = true;
2131 ProtectKernelModules = true;
2132 ProtectKernelTunables = true;
2133 ProtectControlGroups = true;
2134 ProtectProc = "invisible";
2135 RestrictAddressFamilies = [ "AF_UNIX" ];
2136 RestrictNamespaces = true;
2137 RestrictRealtime = true;
2138 RestrictSUIDSGID = true;
2139 LockPersonality = true;
2140 CapabilityBoundingSet = "";
2141 SystemCallArchitectures = "native";
2142 SystemCallFilter = [ "@system-service" ];
2143 # The instance repository is always one the integrator serves, since
2144 # it has to be protected, so it is group-shared and its directories
2145 # are setgid. With the default umask, git would chmod each directory
2146 # it makes to add group write, setgid bit included, and
2147 # RestrictSUIDSGID refuses that chmod. Group write from the start
2148 # leaves git nothing to chmod, as for the controllers.
2149 UMask = "0002";
2150 };
2151 };
2152
2153 systemd.paths.valley-signers = lib.mkIf publishesSigners {
2154 description = "Watch the known-signers file the valley integrator reads";
2155 wantedBy = [ "multi-user.target" ];
2156 pathConfig.PathChanged = knownSigners;
2157 };
2158
2159 # One controller per served project, as instances of a single template:
2160 # the units differ only in the repository they serve, which is the
2161 # instance name. `watch` rather than a timer firing `reconcile`: the
2162 # binary owns its poll loop and its interval, and a timer would be a
2163 # second cadence over the same level-triggered refs.
2164 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
2165 description = "The valley integrator for %i";
2166 after = [
2167 "network.target"
2168 "valley-init.service"
2169 ]
2170 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
2171 ++ lib.optional cfg.identity.enable "valley-identity.service";
2172 requires = [ "valley-init.service" ];
2173 # Wants, not requires: a controller reads the compiled signers file,
2174 # so it starts after the first compilation — but a compilation that
2175 # failed must not keep the controllers down. One that finds no file
2176 # says so and restarts, which is the same loop and a louder one.
2177 wants = lib.optional cfg.identity.enable "valley-identity.service";
2178 unitConfig.RequiresMountsFor = cfg.dataDir;
2179 # nix is not pinned, for the reason the integrator package does not
2180 # pin it: a check's input closure must be recomputed by the nix this
2181 # machine actually runs. Everything else a controller drives is
2182 # pinned inside the wrapper.
2183 path = [ config.nix.package ];
2184 # The repositories belong to the git user and the controller does
2185 # not, so git refuses to touch them as dubiously owned. The exception
2186 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
2187 # command-scope config, which is protected config, so safe.directory
2188 # is honoured from it — a repository-scoped setting would be ignored,
2189 # deliberately. And every git the controller drives is a child of
2190 # this unit, whether run by the integrator itself or by attest or the
2191 # deriver, so one environment covers all of them.
2192 #
2193 # One repository per instance: never a global gitconfig, never a
2194 # wildcard. Every other repository on the host stays refused. Linked
2195 # worktrees need no entry of their own — the controller creates them,
2196 # so it owns them, and git checks the worktree and its gitdir rather
2197 # than the repository they point at.
2198 #
2199 # TMPDIR is the same kind of wiring, for the same reason. A verdict
2200 # wants a checkout of the tip on disk, and the integrator asks for one
2201 # the ordinary way — a temporary directory, then a linked worktree in
2202 # it. The sandbox below leaves no writable temporary directory, so
2203 # every tick died on `could not create leading directories`. The
2204 # scratch belongs under the state directory the unit already has:
2205 # writable by construction, owned by this service, and gone when the
2206 # service's state is. Setting it in the environment rather than
2207 # teaching the binary a flag covers every process in the unit at once
2208 # — the integrator, attest, the deriver, and the git each of them runs
2209 # all read TMPDIR, and all of them want scratch in the same place.
2210 #
2211 # A second exception, for the instance repository. Every controller
2212 # reads the group's floor from that repository's tip, and it need not
2213 # be the project the controller serves — the controller for one
2214 # project reads the floor out of another project's repository, which
2215 # it likewise does not own. Without the exception git refuses it as
2216 # dubiously owned and every pass fails, exactly as it did for the
2217 # served repository. Two entries, both named; still never a wildcard.
2218 #
2219 # Reading needs no sandbox entry beside it. ProtectSystem=strict
2220 # leaves the filesystem readable and only takes write away, so the
2221 # ReadWritePaths list above stays the list of what may be written,
2222 # which is what makes it worth reading. What read does need is a
2223 # filesystem grant, and valley-init makes it: the instance repository
2224 # is group-readable whether or not it is one of the served projects.
2225 environment = {
2226 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
2227 GIT_CONFIG_KEY_0 = "safe.directory";
2228 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
2229 TMPDIR = integratorStateDir;
2230 }
2231 // lib.optionalAttrs (instanceRepo != null) {
2232 GIT_CONFIG_KEY_1 = "safe.directory";
2233 GIT_CONFIG_VALUE_1 = instanceRepo;
2234 };
2235 serviceConfig = {
2236 ExecStart = integratorCommand;
2237 Restart = "on-failure";
2238 RestartSec = "10s";
2239 User = cfg.integrator.user;
2240 Group = cfg.group;
2241 StateDirectory = integratorStateName;
2242 StateDirectoryMode = "0700";
2243 WorkingDirectory = integratorStateDir;
2244 NoNewPrivileges = true;
2245 ProtectSystem = "strict";
2246 # Everything the controller may write, named where a reader of the
2247 # unit meets it. Under ProtectSystem=strict the rest of the
2248 # filesystem is read-only, so this list is the whole of what the
2249 # service can touch, and it is worth being able to read it as such
2250 # rather than as the exceptions plus whatever else is implied.
2251 #
2252 # Its own directory: its state, and the scratch root TMPDIR names.
2253 # A declaration says it here rather than relying on the state
2254 # directory being read-write by virtue of being declared, which is
2255 # not something this unit found to be true.
2256 #
2257 # The one repository it serves, and the nix daemon's socket —
2258 # recomputing a closure means asking the daemon, and connecting to
2259 # a unix socket needs write access to it.
2260 ReadWritePaths = [
2261 integratorStateDir
2262 "${cfg.dataDir}/%i.git"
2263 "/nix/var/nix/daemon-socket"
2264 ];
2265 ProtectHome = true;
2266 PrivateTmp = true;
2267 PrivateDevices = true;
2268 ProtectClock = true;
2269 ProtectHostname = true;
2270 ProtectKernelLogs = true;
2271 ProtectKernelModules = true;
2272 ProtectKernelTunables = true;
2273 ProtectControlGroups = true;
2274 ProtectProc = "invisible";
2275 RestrictAddressFamilies = [
2276 "AF_INET"
2277 "AF_INET6"
2278 "AF_UNIX"
2279 ];
2280 RestrictNamespaces = true;
2281 RestrictRealtime = true;
2282 RestrictSUIDSGID = true;
2283 LockPersonality = true;
2284 CapabilityBoundingSet = "";
2285 SystemCallArchitectures = "native";
2286 SystemCallFilter = [ "@system-service" ];
2287 # Group write, not the bus unit's 0077: the git user owns these
2288 # repositories and has to stay able to write what a controller
2289 # leaves in them.
2290 UMask = "0002";
2291 };
2292 };
2293
2294 # What pushes the mirrors: a path unit per published project, watching
2295 # its publish queue, and the drain it starts.
2296 systemd.paths."valley-publish@" = lib.mkIf (publishedProjects != { }) {
2297 description = "Watch the publish queue of %i";
2298 pathConfig.DirectoryNotEmpty = "${cfg.dataDir}/%i.git/${publishQueueName}";
2299 };
2300
2301 # It runs as the git user, with ssh on its path, because the mirror
2302 # credentials are that user's. Each run drains the whole queue, so starts
2303 # are at most one per queued move, and a burst of moves must not trip
2304 # systemd's start limit and leave the queue undrained. A run is bounded
2305 # instead: one that hangs on a mirror is cut off after 15 minutes, and
2306 # systemd stops its whole cgroup, so nothing it started outlives it. A
2307 # run that fails or is cut off leaves its moves queued, and systemd
2308 # starts it again after a delay that grows from 30 seconds to 15 minutes,
2309 # until a run succeeds. While it waits to restart, the unit is not
2310 # inactive, so the path unit does not start it again sooner.
2311 systemd.services."valley-publish@" = lib.mkIf (publishedProjects != { }) {
2312 description = "Push the moves queued on %i to its mirrors";
2313 after = [ "valley-init.service" ];
2314 unitConfig.RequiresMountsFor = cfg.dataDir;
2315 startLimitIntervalSec = 0;
2316 path = [ config.programs.ssh.package ];
2317 serviceConfig = {
2318 Type = "oneshot";
2319 ExecStart = "${publishDrains}/%i";
2320 User = cfg.user;
2321 Group = cfg.group;
2322 WorkingDirectory = "${cfg.dataDir}/%i.git";
2323 TimeoutStartSec = "15min";
2324 Restart = "on-failure";
2325 RestartSec = "30s";
2326 RestartSteps = 5;
2327 RestartMaxDelaySec = "15min";
2328 };
2329 };
2330
2331 # wantedBy on a template unit enables nothing, so the instances the
2332 # declaration asks for are pulled in by name.
2333 systemd.targets.valley-publish = lib.mkIf (publishedProjects != { }) {
2334 description = "What pushes the valley's mirrors";
2335 wantedBy = [ "multi-user.target" ];
2336 wants = map (name: "valley-publish@${name}.path") (lib.attrNames publishedProjects);
2337 };
2338
2339 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
2340 description = "The valley integrator's controllers";
2341 wantedBy = [ "multi-user.target" ];
2342 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
2343 };
2344
2345 # The build slice. The daemon runs every build in its own cgroup,
2346 # whoever asked for it, so a cap on a build is a cap on the daemon: the
2347 # slice holds nix-daemon.service, and the check worker when it runs,
2348 # and the kernel holds everything in it to the quota and the memory cap
2349 # together, with no swap. Every user's builds through the daemon share
2350 # the caps. A nix command that does not go through the daemon, such as
2351 # one root runs on the store directly, is outside the slice and
2352 # uncapped.
2353 #
2354 # A build that takes the slice past its memory cap is ended by the
2355 # kernel's OOM killer, which kills the process in the slice using the
2356 # most memory. That is usually the build that went past, and it can be
2357 # another build in the slice. The rest of the host goes on as it was.
2358 # When the OOM killer kills one of the daemon's processes, systemd keeps
2359 # the daemon's unit running, since the unit delegates its cgroup
2360 # (OOMPolicy=continue). Nothing exempts the daemon's own processes from
2361 # being the one chosen.
2362 # The slice sets no device policy, so a build keeps the /dev/kvm the
2363 # daemon gives NixOS tests.
2364 systemd.slices.valley-builds = lib.mkIf cfg.buildSlice.enable {
2365 description = "Every build of the nix daemon, under the host's caps";
2366 sliceConfig = {
2367 CPUQuota = cfg.buildSlice.cpuQuota;
2368 MemoryMax = cfg.buildSlice.memoryMax;
2369 MemorySwapMax = "0";
2370 };
2371 };
2372
2373 systemd.services.nix-daemon.serviceConfig.Slice = lib.mkIf cfg.buildSlice.enable buildSlice;
2374
2375 # One pass of the worker, as a oneshot the timer below starts. A pass
2376 # that finds nothing to build reads origin and ends. Two passes never
2377 # overlap: systemd starts the unit only while it is inactive, and the
2378 # worker's own lock in its state directory serializes any pass started
2379 # by hand.
2380 #
2381 # The unit runs in the build slice, so its evaluation shares the caps
2382 # with the builds. It runs on one CPU. attest runs one nix build per
2383 # CPU it may run on, and NIX_CONFIG holds each of those to one
2384 # derivation at a time, so the worker's builds run one at a time. The
2385 # builds themselves run in the daemon, under the slice's quota,
2386 # whatever CPU the worker is on.
2387 systemd.services.valley-worker = lib.mkIf cfg.worker.enable {
2388 description = "One pass of the valley check worker";
2389 after = [
2390 "network.target"
2391 "sshd.service"
2392 "valley-init.service"
2393 "systemd-tmpfiles-setup.service"
2394 ];
2395 unitConfig.RequiresMountsFor = workerDir;
2396 # nix is the machine's own, for the reason the integrator's is.
2397 path = [
2398 workerPackage
2399 attestPackage
2400 pkgs.git
2401 pkgs.diffutils
2402 config.programs.ssh.package
2403 config.nix.package
2404 ];
2405 environment = {
2406 HOME = workerDir;
2407 XDG_CACHE_HOME = "${workerDir}/cache";
2408 GIT_SSH_COMMAND = workerSsh;
2409 NIX_CONFIG = workerNixConfig;
2410 };
2411 script = workerScript;
2412 serviceConfig = {
2413 Type = "oneshot";
2414 User = "valley-worker";
2415 Group = "valley-worker";
2416 Slice = buildSlice;
2417 CPUAffinity = "0";
2418 NoNewPrivileges = true;
2419 ProtectSystem = "strict";
2420 # Its own directory, and the nix daemon's socket, which a client
2421 # writes to connect.
2422 ReadWritePaths = [
2423 workerDir
2424 "/nix/var/nix/daemon-socket"
2425 ];
2426 ProtectHome = true;
2427 PrivateTmp = true;
2428 PrivateDevices = true;
2429 ProtectClock = true;
2430 ProtectHostname = true;
2431 ProtectKernelLogs = true;
2432 ProtectKernelModules = true;
2433 ProtectKernelTunables = true;
2434 ProtectControlGroups = true;
2435 ProtectProc = "invisible";
2436 RestrictAddressFamilies = [
2437 "AF_INET"
2438 "AF_INET6"
2439 "AF_UNIX"
2440 ];
2441 RestrictNamespaces = true;
2442 RestrictRealtime = true;
2443 RestrictSUIDSGID = true;
2444 LockPersonality = true;
2445 CapabilityBoundingSet = "";
2446 SystemCallArchitectures = "native";
2447 SystemCallFilter = [ "@system-service" ];
2448 UMask = "0077";
2449 };
2450 };
2451
2452 # The first pass starts five minutes after the timer starts. Each later
2453 # pass starts one interval after the last one ended, so a long batch is
2454 # never followed at once by another pass. These are delays and nothing
2455 # more: a switch that runs longer than five minutes can see the first
2456 # pass start inside it, and any later switch can see a pass start
2457 # inside it.
2458 systemd.timers.valley-worker = lib.mkIf cfg.worker.enable {
2459 description = "Run the valley check worker";
2460 wantedBy = [ "timers.target" ];
2461 timerConfig = {
2462 OnActiveSec = "5m";
2463 OnUnitInactiveSec = cfg.worker.interval;
2464 };
2465 };
2466
2467 # Offsite backup, rendered only when the declaration asks for it. The
2468 # declaration states the policy — that backup exists, its cadence and
2469 # retention; the services.valley.backup.* options supply the machine
2470 # half. Declaration absent or disabled ⇒ no restic config at all.
2471 services.restic.backups = lib.mkIf backupEnabled {
2472 valley = {
2473 initialize = true;
2474 repositoryFile = cfg.backup.repositoryFile;
2475 passwordFile = cfg.backup.passwordFile;
2476 paths = [ cfg.dataDir ];
2477 # The schema admits only the restic-sftp target today; a second
2478 # target would grow a dispatch here. The service runs as root:
2479 # authenticate with the supplied identity and only the pinned
2480 # host key. No prompt can be answered inside a systemd unit, so
2481 # BatchMode + strict host key checking turn a would-be hang into
2482 # an immediate error.
2483 extraOptions = [
2484 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
2485 ];
2486 timerConfig = backupTimer.${backupPolicy.cadence};
2487 pruneOpts = [
2488 "--keep-daily ${toString backupPolicy.retention.daily}"
2489 "--keep-weekly ${toString backupPolicy.retention.weekly}"
2490 "--keep-monthly ${toString backupPolicy.retention.monthly}"
2491 ];
2492 };
2493 };
2494 };
2495}