gunk-dev/the-valley

valley-host.nix

source57f1659f405fmain's published tip history
115.0 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 # Whether ref is a full ref name, which the identity registry is read at.
970 # It opens with refs/ and holds letters, digits, dots, dashes, underscores
971 # and slashes alone. git check-ref-format accepts it: no component is
972 # empty, opens with a dot or ends with .lock, and it holds no ".." and
973 # does not end with a dot. readaccess.ValidRef accepts every name this
974 # accepts.
975 fullRefName =
976 ref:
977 builtins.match "refs/[A-Za-z0-9._/-]+" ref != null
978 && !(lib.hasInfix ".." ref)
979 && !(lib.hasSuffix "." ref)
980 && lib.all (part: part != "" && !(lib.hasPrefix "." part) && !(lib.hasSuffix ".lock" part)) (
981 lib.splitString "/" ref
982 );
983
984 # Every value sshd is given for one keyword, from the settings and from
985 # every line of extraConfig, inside a Match block or not. The keyword is
986 # matched in any case, as sshd matches it, with or without `=` after it;
987 # the values are kept as written, because sshd's patterns and variable
988 # names are case-sensitive. Values are split on any whitespace, tabs
989 # included, as sshd splits them. Quoting and escapes are not unpicked
990 # here: a value holding a quote or a backslash is refused below instead,
991 # because a reading that differed from sshd's would be a hole.
992 sshdValues =
993 keyword:
994 let
995 settings = config.services.openssh.settings;
996 word = x: if lib.isBool x then (if x then "yes" else "no") else toString x;
997 words = v: lib.filter (w: lib.isString w && w != "") (builtins.split "[[:space:]]+" v);
998 fromSettings = lib.concatMap (
999 k:
1000 let
1001 v = settings.${k};
1002 in
1003 if lib.isList v then lib.concatMap (x: words (word x)) v else words (word v)
1004 ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings));
1005 fromExtra = lib.concatMap (
1006 line:
1007 let
1008 m = builtins.match "[[:space:]]*([A-Za-z]+)[[:space:]]*=?[[:space:]]*(.*)" line;
1009 in
1010 if m == null || lib.toLower (lib.head m) != lib.toLower keyword then
1011 [ ]
1012 else
1013 words (lib.elemAt m 1)
1014 ) (lib.splitString "\n" config.services.openssh.extraConfig);
1015 in
1016 fromSettings ++ fromExtra;
1017
1018 # Every key line the git user's declared authorized_keys holds, from this
1019 # module and from any other, with the principal its tag names ("" for
1020 # none) and the key itself.
1021 declaredKeyEntries = lib.concatMap (
1022 line:
1023 let
1024 key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line;
1025 tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line;
1026 in
1027 lib.optional (key != null) {
1028 key = lib.elemAt key 3;
1029 principal = if tag == null then "" else lib.head tag;
1030 }
1031 ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys;
1032
1033 # Keys declared more than once under different tags. sshd authorizes a
1034 # key by the first entry that names it, so which principal such a key
1035 # pushes as depends on file order; the assertion below refuses it.
1036 conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) (
1037 lib.groupBy (e: e.key) declaredKeyEntries
1038 );
1039
1040 # The declared key lines, for the compiler: a compiled key that is also
1041 # declared under another tag is refused there, for the same reason.
1042 declaredKeysFile = pkgs.writeText "valley-declared-keys" (
1043 lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys
1044 );
1045in
1046{
1047 options.services.valley = {
1048 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
1049
1050 user = lib.mkOption {
1051 type = lib.types.str;
1052 default = "git";
1053 description = "System user that owns the repositories and accepts SSH pushes.";
1054 };
1055
1056 group = lib.mkOption {
1057 type = lib.types.str;
1058 default = "git";
1059 description = "Primary group of the valley git user.";
1060 };
1061
1062 dataDir = lib.mkOption {
1063 type = lib.types.path;
1064 default = "/srv/git";
1065 example = "/mnt/git";
1066 description = ''
1067 Directory holding the bare repositories, one `<name>.git` per
1068 project declared in {option}`services.valley.config`. Also the git
1069 user's home, so clone URLs are relative to it (`git@host:name.git`).
1070 Consumers typically point it at a dedicated dataset.
1071 '';
1072 };
1073
1074 authorizedKeys = lib.mkOption {
1075 type = lib.types.listOf (
1076 lib.types.either lib.types.str (
1077 lib.types.submodule {
1078 options = {
1079 key = lib.mkOption {
1080 type = lib.types.str;
1081 description = "The SSH public key, as it would appear in `authorized_keys`.";
1082 };
1083
1084 principal = lib.mkOption {
1085 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
1086 example = "integrator";
1087 description = ''
1088 Name of the principal this key acts as. Every push made
1089 with the key carries the name, and the pre-receive hook
1090 decides what the name may write: from the project's
1091 `protection` block and named grants in
1092 {option}`services.valley.config`, and from the grants the
1093 name holds ({option}`services.valley.grants`, and the
1094 registry's when it is compiled). Nothing else uses it.
1095 A key is declared once: the same key under two tags, or
1096 tagged and untagged, is refused.
1097 '';
1098 };
1099 };
1100 }
1101 )
1102 );
1103 default = [ ];
1104 example = lib.literalExpression ''
1105 [
1106 "ssh-ed25519 AAAA… someone@somewhere"
1107 {
1108 principal = "integrator";
1109 key = "ssh-ed25519 AAAA… integrator";
1110 }
1111 ]
1112 '';
1113 description = ''
1114 SSH public keys allowed to push/fetch as the git user. Access is
1115 host-level by design: every key can reach every project.
1116
1117 A key written as a plain string is anonymous — it can push, and it
1118 can write nothing protected. A key written as an attribute set
1119 names the principal it acts as, which is the only thing that can
1120 tell one pusher from another: pushes arrive as the shared git user,
1121 so identity has to ride on the key.
1122
1123 Which refs a principal may write is declared, not an option here:
1124 it is a statement about what the host serves, and lives in the
1125 project's `protection` block in
1126 {option}`services.valley.config`. Binding a name to keys is the
1127 machine half — the hand-written form of what the identity registry
1128 compiles (dcr-b87f6e8).
1129
1130 With {option}`services.valley.identity.enable` on, the compiled
1131 keys are added to what sshd reads and the keys here stay
1132 authorized beside them. The list is therefore the way back in when
1133 a compilation is wrong or has not happened yet, and it is never
1134 empty.
1135 '';
1136 };
1137
1138 extraPreReceive = lib.mkOption {
1139 type = lib.types.attrsOf lib.types.pathInStore;
1140 default = { };
1141 example = lib.literalExpression ''
1142 {
1143 app = pkgs.writeShellScript "app-pre-receive" ;
1144 }
1145 '';
1146 description = ''
1147 A further pre-receive hook per project, run after the push policy
1148 accepts a push, with the same input. It can refuse what the policy
1149 accepts and never accept what the policy refuses.
1150
1151 This is the one way to compose a hook with the managed one. A
1152 pre-receive hook the module did not write fails valley-init,
1153 because git would run it instead of the policy. A hook that is
1154 byte-for-byte the one declared here is the exception: valley-init
1155 replaces it with the managed hook, which runs it. The value is a
1156 store path, so what runs is exactly what was declared.
1157 '';
1158 };
1159
1160 # Grants held by hand. The registry names who holds a grant
1161 # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written
1162 # form of what it compiles, beside it the way the declared keys sit
1163 # beside the compiled ones.
1164 grants = {
1165 approve = lib.mkOption {
1166 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1167 default = [ ];
1168 example = [ "operator" ];
1169 description = ''
1170 Principals holding the approve grant (also accepted as
1171 {option}`services.valley.grants.request`): the ones whose pushes
1172 may file, replace and withdraw an integration request
1173 (`refs/the-valley/integration-requests/*`) on a protected
1174 project. The pre-receive hook refuses every other write to that
1175 namespace, so a principal named neither here, nor in
1176 {option}`services.valley.grants.request`, nor in the registry
1177 cannot file an integration request.
1178
1179 The two options are one grant. The holders are the principals
1180 named in either list, and a principal named in both holds the
1181 grant once.
1182
1183 The grant rides on push. Only a key sshd admits reaches the hook,
1184 so a principal named here also needs a key, declared in
1185 {option}`services.valley.authorizedKeys` or compiled from the
1186 registry.
1187
1188 With {option}`services.valley.identity.enable` on, the holders
1189 the registry names are added to these, and a compiled file can
1190 only ever add. The list is therefore how a host grants approve
1191 before its registry does — including to the operator who has to
1192 file the registry change that grants it.
1193 '';
1194 };
1195
1196 request = lib.mkOption {
1197 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1198 default = [ ];
1199 example = [ "operator" ];
1200 description = ''
1201 Principals holding the approve grant, under the name it had
1202 first. A principal named here holds exactly what one named in
1203 {option}`services.valley.grants.approve` holds, and the holders
1204 are the principals named in either list.
1205 '';
1206 };
1207
1208 restack = lib.mkOption {
1209 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1210 default = [ ];
1211 example = [ "valley-restacker" ];
1212 description = ''
1213 Principals holding the restack grant: the host restacker's. A
1214 holder that neither owns a change nor holds the approve grant may
1215 add exactly one version to the change's record while the change
1216 is ready, on the branch and under the title of its active version,
1217 with itself as the uploader. It may also write restack reports
1218 (`refs/the-valley/restack/main/<change-id>`). The grant permits
1219 no other record write and nothing on integration requests, and a
1220 holder keeps every ordinary power of a named principal.
1221
1222 The grant rides on push, like approve: a principal named here also
1223 needs a key. With {option}`services.valley.identity.enable` on,
1224 the holders the registry names are added to these. The list is
1225 how a host grants restack before its registry does; remove an
1226 entry once the registry grants the same principal.
1227 '';
1228 };
1229 };
1230
1231 config = lib.mkOption {
1232 type = lib.types.path;
1233 example = lib.literalExpression "./valley.cue";
1234 description = ''
1235 Path to the host's CUE declaration (`package valley`) — the
1236 canonical statement of what this valley host serves, validated
1237 against the shipped schema at build time. This is the single domain
1238 input: projects, their push mirrors, and the backup policy are
1239 declared here, never as Nix options.
1240 '';
1241 };
1242
1243 # The event bus. Machine options, not domain: whether this machine runs
1244 # a bus, where it listens, and where its storage lives. What gets
1245 # published onto it is defined portably in ../schema/events.cue.
1246 bus = {
1247 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
1248
1249 listen = lib.mkOption {
1250 type = lib.types.str;
1251 default = "127.0.0.1:4222";
1252 example = "192.0.2.10:4222";
1253 description = ''
1254 Address the bus listens on, `host:port`. Localhost by default:
1255 nothing off the host can reach the bus until the consumer widens
1256 this deliberately — e.g. to the host's private network address once a
1257 remote `valley tail` wants in. Local publishers (the ref-updated
1258 hook) connect to this same address, so it must be reachable from
1259 the host itself.
1260 '';
1261 };
1262
1263 storeDir = lib.mkOption {
1264 type = lib.types.path;
1265 default = "${cfg.dataDir}/.bus";
1266 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
1267 description = ''
1268 Directory holding the JetStream file storage. The default lives
1269 under {option}`services.valley.dataDir`; it can never collide
1270 with a repository because project names must start with an
1271 alphanumeric. The stream is a projection of git, rebuildable
1272 with `valley replay` — losing this directory costs one replay.
1273 '';
1274 };
1275 };
1276
1277 # The integrator (archive/design/roadmap.md, Phase 3): the controller that
1278 # lands a change once its evidence still transfers to the current tip.
1279 # Machine options only — whether this host runs controllers, who they
1280 # are, and how often they look. Which projects get one is not an option
1281 # either: it follows from which projects the declaration protects,
1282 # because a protected ref is exactly what a controller exists to write.
1283 integrator = {
1284 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
1285
1286 user = lib.mkOption {
1287 type = lib.types.str;
1288 default = "valley-integrator";
1289 description = ''
1290 System user the controllers run as. Deliberately not
1291 {option}`services.valley.user`: one unix identity per service is
1292 the split bd-500adf7 asks for, and this service begins it.
1293
1294 The account exists only to write the repositories it serves. It
1295 gets no shell and no SSH key, and its primary group is
1296 {option}`services.valley.group`, which is the whole of its
1297 permission model: {option}`services.valley.dataDir` is already
1298 group-readable, and each served repository is made group-shared
1299 (group write, setgid directories) so a controller can write
1300 refs, objects, and git's worktree metadata. Nothing else on the
1301 host belongs to that group, and the bus's store directory (mode
1302 0700) stays out of reach.
1303
1304 The key and signers files are the consumer's to provision; both
1305 must be readable by this user.
1306 '';
1307 };
1308
1309 signingKeyFile = lib.mkOption {
1310 type = lib.types.nullOr lib.types.path;
1311 default = null;
1312 example = "/run/agenix/valley-integrator-key";
1313 description = ''
1314 ed25519 private key the controllers sign their transfer
1315 statements with. A runtime path the consumer provisions (e.g.
1316 agenix), never a store path — the store is world-readable.
1317 '';
1318 };
1319
1320 knownSignersFile = lib.mkOption {
1321 type = lib.types.nullOr lib.types.path;
1322 default = null;
1323 example = "/var/lib/valley-instance/known_signers";
1324 description = ''
1325 File of verifier keys whose attestations count, one per line, in
1326 `attest key` format. This is the identity registry's interim
1327 compilation (dcr-b87f6e8), supplied directly for a host that does
1328 not compile one: turning on
1329 {option}`services.valley.identity.enable` renders the same file
1330 from the registry, and then this option must be left unset.
1331 Evidence signed by nobody in it does not transfer, which a
1332 controller reports per check rather than treating as a forgery.
1333 '';
1334 };
1335
1336 signerProjects = lib.mkOption {
1337 type = lib.types.attrsOf (lib.types.listOf lib.types.str);
1338 default = { };
1339 example = {
1340 "worker/attestations" = [ "the-valley" ];
1341 };
1342 description = ''
1343 Signers whose attestations count only in the projects listed for
1344 them, by the name each signs under. A signer named here counts
1345 in its listed projects alone; in any other project a controller
1346 reports its evidence as signed by no signer it holds. An empty
1347 list lets the signer count nowhere. A signer not named here
1348 counts wherever the known-signers file lets it.
1349
1350 This is how a check worker's key, which every controller sharing
1351 the known-signers file would otherwise accept, is trusted only
1352 for the projects it builds. The push hook still admits the
1353 worker's evidence everywhere; only the controllers restrict it.
1354
1355 List every other controller whose key the known-signers file
1356 holds, such as another host's integrator, with an empty list.
1357 A controller countersigns the attestations a landing carried,
1358 and its own signature never counts as check evidence here;
1359 another controller's counts only until it is listed.
1360
1361 The list is rendered into a file every controller reads at start.
1362 A host that publishes its signers publishes the file beside them,
1363 so a client can read the same restriction. Names and projects are
1364 words of printable ASCII with no space, and a name holds no plus
1365 and does not open with #. The list may not name the name the
1366 controllers sign under: a controller given such a list refuses to
1367 start.
1368 '';
1369 };
1370
1371 signingName = lib.mkOption {
1372 type = lib.types.nullOr lib.types.str;
1373 default = null;
1374 example = "integrator";
1375 description = ''
1376 The name a controller's transfer statements are signed under.
1377 Unset leaves the binary's own default, which is this host's
1378 attestations name — the machine signing as itself.
1379
1380 Set it to the name the identity registry publishes the
1381 integrator's key under. The note format's key hash binds the name
1382 to the key (dcr-de9d996), so a controller signing under one name
1383 while the registry publishes it under another produces notes no
1384 verifier can find a key for.
1385 '';
1386 };
1387
1388 instanceProject = lib.mkOption {
1389 type = lib.types.nullOr lib.types.str;
1390 default = null;
1391 example = "valley";
1392 description = ''
1393 The project whose served repository carries the group's floor —
1394 the instance policy layer every controller on this host composes
1395 against. A controller reads it from `policy/instance/` in that
1396 bare repository's integrated tip, and nothing is materialized on
1397 disk in between. It is also where the identity registry is read
1398 from, for the same reason and at the same altitude: both are the
1399 instance's, so a host serving that repository already holds the
1400 authoritative copy.
1401
1402 The floor is the instance repository's, read at the tip that has
1403 been integrated (dcr-f41f718); the instance repository is the
1404 group's own (dcr-b87f6e8). A host serving it is therefore already
1405 holding the authoritative copy.
1406
1407 What follows is a property of that design, and worth knowing
1408 before editing a floor. A change to it takes effect at the first
1409 pass after it lands on that ref, and never before. An edit in a
1410 branch, in a worktree, or in an integration request that has not
1411 been integrated governs nothing. There is no refresh to trigger
1412 and no staleness to wait out: landing is the whole of publishing
1413 a floor.
1414
1415 The project has to declare protection covering refs/heads/main,
1416 and the registry's ref when the identity compiler is on. Both
1417 are read from that tip, so a ref any push-capable key could move
1418 would hand every key the floor and the registry.
1419
1420 Every controller on the host reads the same repository, the
1421 controller serving that repository included. Both layers are
1422 resolved from the controller's own side — this one, and the
1423 project's `policy/project/` at the target tip — so a change can
1424 never supply the policy that gates it (bd-eaefe82).
1425
1426 Those two directories are the convention, and the module states
1427 neither: a controller takes each layer from the place the
1428 integrator defaults to, so a host declaration that says nothing
1429 about policy gets the layout the worked example lays out
1430 (dcr-f41f718).
1431 '';
1432 };
1433
1434 instancePolicy = lib.mkOption {
1435 type = lib.types.nullOr lib.types.path;
1436 default = null;
1437 example = "/var/lib/valley-instance/policy/instance";
1438 description = ''
1439 Directory of `*.cue` files holding the instance policy layer, for
1440 a host that serves no instance repository. It holds what
1441 `policy/instance/` in the instance repository holds. Set this or
1442 {option}`services.valley.integrator.instanceProject`, never both.
1443
1444 Keeping such a directory in step with the instance repository is
1445 the consumer's to arrange, which is the reason to prefer the
1446 project option wherever the host serves the repository.
1447 '';
1448 };
1449
1450 interval = lib.mkOption {
1451 type = lib.types.str;
1452 default = "15s";
1453 example = "1m";
1454 description = ''
1455 How long a controller waits between passes. The integrator polls
1456 deliberately: integration requests are durable in git, and the
1457 controller level-triggers over those refs, so a lost event costs
1458 one interval and nothing more.
1459 '';
1460 };
1461 };
1462
1463 # The build slice (oc-03b6f8c): caps on every build this machine's nix
1464 # daemon runs, whoever asked for it. A host decision of its own, and a
1465 # condition of the check worker, which builds through the daemon.
1466 buildSlice = {
1467 enable = lib.mkEnableOption ''
1468 capping every build the nix daemon on this host runs, for every user
1469 of it, together: the daemon runs in one slice with a CPU quota, a
1470 memory cap and no swap'';
1471
1472 cpuQuota = lib.mkOption {
1473 type = lib.types.str;
1474 default = "400%";
1475 example = "800%";
1476 description = ''
1477 The CPU time every build the daemon runs gets together, as
1478 systemd's CPUQuota: 400% is four CPUs' worth.
1479 '';
1480 };
1481
1482 memoryMax = lib.mkOption {
1483 type = lib.types.str;
1484 default = "8G";
1485 example = "16G";
1486 description = ''
1487 The memory every build the daemon runs gets together, as
1488 systemd's MemoryMax. The slice gets no swap. A build that takes
1489 the slice past it is ended by the kernel's OOM killer, which kills
1490 the process in the slice using the most memory: usually the
1491 build that went past, but any build in the slice can be the one
1492 killed.
1493 '';
1494 };
1495 };
1496
1497 # The check worker (oc-13c6bd6): a timer that runs one pass of
1498 # valley-worker over the projects listed, so ready changes have their
1499 # nix checks built before anyone approves them. Machine options only —
1500 # whether this host runs the worker, for which of its projects, under
1501 # which signing name, how often, and where it keeps its state.
1502 worker = {
1503 enable = lib.mkEnableOption ''
1504 the valley check worker: a timer that builds the nix checks ready
1505 changes require and publishes the evidence, under its own key, for
1506 the projects listed'';
1507
1508 projects = lib.mkOption {
1509 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1510 default = [ ];
1511 example = [ "the-valley" ];
1512 description = ''
1513 The projects the worker builds evidence for. Each is a project
1514 this host serves, and no other project is read.
1515
1516 The controllers count the worker's evidence in these projects and
1517 no others: {option}`services.valley.integrator.signerProjects`
1518 must list exactly these projects under
1519 {option}`services.valley.worker.signerName`, and the module
1520 refuses a host where it does not.
1521 '';
1522 };
1523
1524 signerName = lib.mkOption {
1525 type = lib.types.str;
1526 example = "worker/attestations";
1527 description = ''
1528 The name the worker signs its notes under. It is a name of the
1529 worker's own: never the operator's, and never the name the
1530 controllers sign under, which the module refuses.
1531
1532 Enrolled with the worker's key, it is what the known-signers file
1533 and the identity registry hold for the worker: the registry key's
1534 `signs`, and the name in the verifier line.
1535 '';
1536 };
1537
1538 interval = lib.mkOption {
1539 type = lib.types.str;
1540 default = "1m";
1541 example = "5m";
1542 description = ''
1543 How long the timer waits after one pass ends before it starts the
1544 next; systemd's default timer accuracy can add up to a minute. A
1545 pass that has nothing to build reads origin and ends.
1546 '';
1547 };
1548
1549 stateDir = lib.mkOption {
1550 type = lib.types.path;
1551 default = "/var/lib/valley-worker";
1552 description = ''
1553 The worker's own directory, mode 0700 and owned by the
1554 `valley-worker` user. It holds the worker's key, made on the
1555 first start and readable by the worker alone; its public halves,
1556 `key.pub` and `verifier`; the lock and the record of failed
1557 batches; and the clones the worker reads projects through.
1558 '';
1559 };
1560 };
1561
1562 # The identity registry compiler (dcr-b87f6e8): the step between the
1563 # instance's declared registry and the two gates that read what it
1564 # compiles to. Machine options only — whether this host compiles, and
1565 # from where. Who the principals are, what they hold and when their
1566 # entries end is the registry's, and the registry is a document in the
1567 # instance repository, never an option here.
1568 identity = {
1569 enable = lib.mkEnableOption ''
1570 compiling the identity registry into what the gates check: the
1571 verifier keys a controller accepts evidence from, and the git
1572 user's authorized keys, both rendered from the instance
1573 repository's integrated tip'';
1574
1575 ref = lib.mkOption {
1576 type = lib.types.str;
1577 default = "refs/heads/main";
1578 description = ''
1579 The ref of the instance repository whose tip carries the
1580 registry: a full ref name, opening with `refs/`, in letters,
1581 digits, dots, dashes, underscores and slashes. A short name such
1582 as `main` is refused. A registry edit takes effect at the first
1583 compilation after it lands on this ref, and never before: an edit
1584 in a branch, in a worktree, or in an integration request that has
1585 not been integrated governs nothing. The web publisher
1586 (`services.valley.webPublisher`) reads its read grants from the
1587 registry at this ref too.
1588 '';
1589 };
1590
1591 directory = lib.mkOption {
1592 type = lib.types.str;
1593 default = "identity";
1594 description = ''
1595 The registry's directory in that tip. It is a CUE package: the
1596 directory is the enumeration, and every `*.cue` document
1597 directly in it unifies into one registry.
1598 '';
1599 };
1600
1601 interval = lib.mkOption {
1602 type = lib.types.str;
1603 default = "5m";
1604 example = "1m";
1605 description = ''
1606 How long between compilations. The compiler is level-triggered
1607 and idempotent — it renders the current tip and replaces an
1608 artifact only when its bytes changed — so a timer is the whole
1609 of the trigger, and a landed registry change takes effect within
1610 one interval.
1611 '';
1612 };
1613 };
1614
1615 # Machine integration for the declared backup policy. The declaration
1616 # states WHAT must hold (offsite backup, cadence, retention); these
1617 # options supply HOW on this machine — where the repository is and how
1618 # to authenticate. All are paths to files the consumer provisions
1619 # (e.g. agenix), required when the declaration enables backup. Point
1620 # them at runtime paths, never at files in the Nix store.
1621 backup = {
1622 repositoryFile = lib.mkOption {
1623 type = lib.types.nullOr lib.types.path;
1624 default = null;
1625 example = "/run/agenix/valley-restic-repo";
1626 description = ''
1627 File containing the restic repository URL, for the sftp target
1628 e.g. `sftp://backup@backup.example.org:23//./backups/valley`.
1629 '';
1630 };
1631
1632 passwordFile = lib.mkOption {
1633 type = lib.types.nullOr lib.types.path;
1634 default = null;
1635 example = "/run/agenix/valley-restic-password";
1636 description = ''
1637 File containing the restic repository encryption password.
1638 Losing it loses the backups — keep a copy somewhere that
1639 survives this host.
1640 '';
1641 };
1642
1643 sshKeyFile = lib.mkOption {
1644 type = lib.types.nullOr lib.types.path;
1645 default = null;
1646 example = "/run/agenix/valley-git-ssh-key";
1647 description = ''
1648 SSH private key that authenticates to the sftp target. The
1649 backup service runs as root, so any identity the target
1650 authorizes works — reusing the mirror key is fine.
1651 '';
1652 };
1653
1654 knownHostsFile = lib.mkOption {
1655 type = lib.types.nullOr lib.types.path;
1656 default = null;
1657 example = "/var/lib/valley-backup/known_hosts";
1658 description = ''
1659 known_hosts file pinning the sftp target's host key. Pin from
1660 the provider's published fingerprints, not a blind ssh-keyscan.
1661 '';
1662 };
1663 };
1664
1665 # The programs the host runs, as this flake builds them
1666 # (nix/packages.nix). These options are internal: a host has no reason
1667 # to set them. The module checks set them to stand-ins with the same
1668 # binary names (nix/checks/hosts.nix), so a check that reads only what
1669 # the module renders does not change when one of the programs does.
1670 packages = {
1671 integrator = lib.mkOption {
1672 type = lib.types.package;
1673 internal = true;
1674 default = flakePackages.integrator;
1675 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).integrator";
1676 description = "The integrator, which the controllers and the signers publisher run.";
1677 };
1678
1679 identity = lib.mkOption {
1680 type = lib.types.package;
1681 internal = true;
1682 default = flakePackages.identity;
1683 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).identity";
1684 description = "The identity registry compiler, which valley-identity runs.";
1685 };
1686
1687 valleyhook = lib.mkOption {
1688 type = lib.types.package;
1689 internal = true;
1690 default = flakePackages.valleyhook;
1691 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valleyhook";
1692 description = "The push policy, which every pre-receive hook and the git user's login shell run.";
1693 };
1694 };
1695 };
1696
1697 config = lib.mkIf cfg.enable {
1698 assertions = [
1699 {
1700 assertion = cfg.authorizedKeys != [ ];
1701 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
1702 }
1703 ]
1704 ++ lib.optionals backupEnabled (
1705 lib.mapAttrsToList (name: what: {
1706 assertion = cfg.backup.${name} != null;
1707 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).";
1708 }) backupSecretOptions
1709 )
1710 ++ lib.optionals cfg.integrator.enable (
1711 lib.mapAttrsToList (name: what: {
1712 assertion = cfg.integrator.${name} != null;
1713 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
1714 }) integratorPathOptions
1715 ++ [
1716 {
1717 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
1718 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.";
1719 }
1720 # The rule the integrator reads the rendered file by
1721 # (note/signerprojects.go): every name and project is printable
1722 # ASCII with no space, so only the spaces this renders separate
1723 # words, and a name holds no plus and opens with no #, which
1724 # would make its line a comment.
1725 {
1726 assertion =
1727 let
1728 word = w: builtins.match "[!-~]+" w != null;
1729 name = n: word n && !lib.hasInfix "+" n && !lib.hasPrefix "#" n;
1730 in
1731 lib.all (n: name n && lib.all word cfg.integrator.signerProjects.${n}) (
1732 lib.attrNames cfg.integrator.signerProjects
1733 );
1734 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.";
1735 }
1736 {
1737 assertion =
1738 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
1739 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.";
1740 }
1741 {
1742 assertion = cfg.integrator.user != cfg.user;
1743 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
1744 }
1745 {
1746 assertion = integratedProjects != { };
1747 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.";
1748 }
1749 ]
1750 )
1751 # The web publisher (webui-publisher.nix) reads the registry at
1752 # identity.ref too, when its module is imported and on.
1753 ++ lib.optional (cfg.identity.enable || config.services.valley.webPublisher.enable or false) {
1754 assertion = fullRefName cfg.identity.ref;
1755 message = "services.valley.identity.ref is ${cfg.identity.ref}, which is not a full ref name. The identity registry is read at that ref, so name it whole, opening with refs/, as git check-ref-format accepts it: refs/heads/main, not main.";
1756 }
1757 ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) (
1758 let
1759 name = cfg.integrator.instanceProject;
1760 protected = gitProjects.${name}.protection.refs or [ ];
1761 # The web publisher (webui-publisher.nix) reads the registry at
1762 # identity.ref too, when its module is imported and on.
1763 publisher = config.services.valley.webPublisher.enable or false;
1764 read =
1765 lib.optional cfg.integrator.enable "refs/heads/main"
1766 ++ lib.optional (cfg.identity.enable || publisher) cfg.identity.ref;
1767 in
1768 map (ref: {
1769 assertion = lib.any (pattern: refPatternMatches pattern ref) protected;
1770 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}.";
1771 }) read
1772 )
1773 ++ [
1774 {
1775 assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) (
1776 sshdValues "AcceptEnv" ++ sshdValues "SetEnv"
1777 ));
1778 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.";
1779 }
1780 {
1781 assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv"));
1782 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.";
1783 }
1784 {
1785 assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv"));
1786 message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it.";
1787 }
1788 {
1789 assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment");
1790 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.";
1791 }
1792 {
1793 assertion = conflictingKeys == { };
1794 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.";
1795 }
1796 {
1797 assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ];
1798 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.";
1799 }
1800 ]
1801 ++ lib.optionals cfg.identity.enable [
1802 {
1803 assertion = cfg.integrator.instanceProject != null;
1804 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.";
1805 }
1806 {
1807 assertion = cfg.integrator.knownSignersFile == null;
1808 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.";
1809 }
1810 ]
1811 ++ lib.optionals cfg.worker.enable (
1812 let
1813 name = cfg.worker.signerName;
1814 listed = cfg.integrator.signerProjects.${name} or null;
1815 sorted = l: lib.sort lib.lessThan (lib.unique l);
1816 unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.worker.projects;
1817 in
1818 [
1819 {
1820 assertion = cfg.integrator.enable;
1821 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.";
1822 }
1823 {
1824 assertion = cfg.integrator.instanceProject != null;
1825 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.";
1826 }
1827 {
1828 assertion = cfg.worker.projects != [ ] && unserved == [ ];
1829 message = "services.valley.worker.projects must name at least one project, and only projects this host serves${
1830 lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}"
1831 }.";
1832 }
1833 # The restriction (oc-13c6bd6). Every controller that shares the
1834 # known-signers file counts a key it holds in every project, so a
1835 # worker whose key is not restricted would be trusted for projects
1836 # it never builds.
1837 {
1838 assertion = listed != null && sorted listed == sorted cfg.worker.projects;
1839 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}\" = [ ${
1840 lib.concatMapStringsSep " " (p: "\"${p}\"") cfg.worker.projects
1841 } ];";
1842 }
1843 {
1844 assertion = name != integratorName;
1845 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.";
1846 }
1847 {
1848 assertion = cfg.buildSlice.enable;
1849 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.";
1850 }
1851 {
1852 assertion = config.services.openssh.enable && config.nix.enable;
1853 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.";
1854 }
1855 ]
1856 );
1857
1858 users.groups.${cfg.group} = { };
1859
1860 users.users.${cfg.user} = {
1861 isSystemUser = true;
1862 group = cfg.group;
1863 home = cfg.dataDir;
1864 # The valley's shell, in front of git-shell: it derives the principal
1865 # from the authenticated key, drops the GIT_ environment, and pauses
1866 # pushes until valley-init has converged. git-shell then allows only
1867 # git-upload-pack, git-receive-pack and git-upload-archive, and rejects
1868 # interactive logins (no ~/git-shell-commands).
1869 shell = "${gitShell}/bin/valley-git-shell";
1870 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
1871 };
1872
1873 # The integrator's own account. No shell, no keys, no home of its own
1874 # beyond the state directory its units get; the git group is the only
1875 # thing it holds.
1876 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
1877 isSystemUser = true;
1878 group = cfg.group;
1879 home = "/var/lib/valley-integrator";
1880 description = "The valley integrator";
1881 };
1882
1883 # The worker's own account. Its group is its own, not the git group, so
1884 # it can neither read nor write the repositories on disk: it reaches
1885 # them as an ssh client, as anyone else does.
1886 users.users.valley-worker = lib.mkIf cfg.worker.enable {
1887 isSystemUser = true;
1888 group = "valley-worker";
1889 home = workerDir;
1890 description = "The valley check worker";
1891 };
1892 users.groups.valley-worker = lib.mkIf cfg.worker.enable { };
1893
1894 services.openssh.enable = lib.mkDefault true;
1895
1896 # The git user's key files, named in its Match block so no other file
1897 # can authorize a key for it. The declared keys come first, and they stay
1898 # authorized beside the compiled ones: a compiled file can only ever
1899 # add, so an empty or missing one — a first boot before the first
1900 # compilation, a registry that lost an entry, a bug here — cannot take
1901 # the git user's access away. Which is the point: the assertion above
1902 # keeps at least one key declared, and that key is the way back in.
1903 #
1904 # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys
1905 # under its home is not read, and no AuthorizedKeysCommand runs, so every
1906 # entry a pusher can arrive through carries the tag this module or the
1907 # compiler wrote, and the assertions and the compiler hold those to one
1908 # tag per key.
1909 #
1910 # Belt-and-braces hardening for the git user beside it. The trailing
1911 # `Match All` closes the block so it can't scope directives appended to
1912 # sshd_config after this snippet.
1913 services.openssh.extraConfig = ''
1914 Match User ${cfg.user}
1915 AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"}
1916 AuthorizedKeysCommand none
1917 ExposeAuthInfo yes
1918 AllowTcpForwarding no
1919 AllowAgentForwarding no
1920 X11Forwarding no
1921 PermitTunnel no
1922 Match All
1923 '';
1924
1925 # git-shell spawns git-receive-pack/git-upload-pack from PATH
1926 environment.systemPackages = [ pkgs.git ];
1927
1928 systemd.tmpfiles.rules = [
1929 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
1930 ]
1931 ++ lib.optionals cfg.bus.enable [
1932 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
1933 ]
1934 ++ lib.optionals cfg.worker.enable [
1935 "d ${workerDir} 0700 valley-worker valley-worker - -"
1936 ];
1937
1938 # The bus itself. It runs as the git user — the store directory lives in
1939 # that user's data — but the sandbox is what confines it: the unit can
1940 # write nowhere except its store directory.
1941 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
1942 description = "The valley event bus (NATS JetStream)";
1943 wantedBy = [ "multi-user.target" ];
1944 after = [
1945 "network.target"
1946 "systemd-tmpfiles-setup.service"
1947 ];
1948 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
1949 serviceConfig = {
1950 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
1951 Restart = "on-failure";
1952 User = cfg.user;
1953 Group = cfg.group;
1954 LimitNOFILE = 65536;
1955 NoNewPrivileges = true;
1956 ProtectSystem = "strict";
1957 ReadWritePaths = [ cfg.bus.storeDir ];
1958 ProtectHome = true;
1959 PrivateTmp = true;
1960 PrivateDevices = true;
1961 ProtectClock = true;
1962 ProtectHostname = true;
1963 ProtectKernelLogs = true;
1964 ProtectKernelModules = true;
1965 ProtectKernelTunables = true;
1966 ProtectControlGroups = true;
1967 ProtectProc = "invisible";
1968 RestrictAddressFamilies = [
1969 "AF_INET"
1970 "AF_INET6"
1971 "AF_UNIX"
1972 ];
1973 RestrictNamespaces = true;
1974 RestrictRealtime = true;
1975 RestrictSUIDSGID = true;
1976 LockPersonality = true;
1977 CapabilityBoundingSet = "";
1978 SystemCallArchitectures = "native";
1979 SystemCallFilter = [ "@system-service" ];
1980 UMask = "0077";
1981 };
1982 };
1983
1984 # The stream is config, not state: (re)created idempotently on every
1985 # boot, capturing everything under valley.>. An existing stream — and
1986 # the events in it — is left untouched.
1987 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
1988 description = "Create the valley event stream";
1989 wantedBy = [ "multi-user.target" ];
1990 requires = [ "valley-bus.service" ];
1991 after = [ "valley-bus.service" ];
1992 serviceConfig = {
1993 Type = "oneshot";
1994 User = cfg.user;
1995 Group = cfg.group;
1996 };
1997 path = [ pkgs.natscli ];
1998 script = ''
1999 # The server needs a moment to accept connections after startup.
2000 for _ in $(seq 1 50); do
2001 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
2002 sleep 0.2
2003 done
2004 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
2005 nats --server ${busUrl} stream add valley \
2006 --subjects 'valley.>' --storage file --defaults
2007 fi
2008 '';
2009 };
2010
2011 # Create missing bare repos and (re)wire the managed hooks on every
2012 # activation where the declaration changed.
2013 systemd.services.valley-init = {
2014 description = "Initialize the valley host's bare git repositories";
2015 wantedBy = [ "multi-user.target" ];
2016 after = [ "systemd-tmpfiles-setup.service" ];
2017 unitConfig.RequiresMountsFor = cfg.dataDir;
2018 serviceConfig = {
2019 Type = "oneshot";
2020 User = cfg.user;
2021 Group = cfg.group;
2022 };
2023 path = [
2024 pkgs.git
2025 pkgs.diffutils
2026 ];
2027 # Everything init can wire is wired before it fails. A conflict in one
2028 # repository is reported, the rest of the host is still converged,
2029 # and only then does the unit fail, so the activation fails loudly
2030 # without leaving another repository's hook out of date.
2031 script = ''
2032 # Pushes pause the moment a convergence starts, and resume only once
2033 # it has finished: the record is removed first and written last.
2034 rm -f ${convergedRecord}
2035 ${valleyInitBody}
2036 printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp
2037 mv -f ${convergedRecord}.tmp ${convergedRecord}
2038 '';
2039 };
2040
2041 # The registry compiler, on a timer. It renders the instance
2042 # repository's integrated tip into the two artifacts the gates read;
2043 # nothing else on the host writes them.
2044 #
2045 # It runs as the git user rather than under an identity of its own,
2046 # which is the one place this module steps back from the service split
2047 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
2048 # anyone but root or the account it authorizes, so the choice is the git
2049 # user or root, and the git user is the smaller grant.
2050 #
2051 # Level-triggered, like the rest: a compilation reads the current tip
2052 # and replaces an artifact only when its bytes changed, so re-running is
2053 # free and the timer needs no coordination with anything.
2054 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
2055 description = "Compile the valley identity registry into what the gates check";
2056 wantedBy = [ "multi-user.target" ];
2057 after = [ "valley-init.service" ];
2058 requires = [ "valley-init.service" ];
2059 unitConfig.RequiresMountsFor = cfg.dataDir;
2060 serviceConfig = {
2061 Type = "oneshot";
2062 ExecStart = identityCommand;
2063 User = cfg.user;
2064 Group = cfg.group;
2065 StateDirectory = identityStateName;
2066 # sshd walks every directory above an authorized-keys file and
2067 # refuses a group- or world-writable one, so the state directory is
2068 # 0755 deliberately rather than the 0700 a service's state usually
2069 # takes. Nothing secret lives in it: a registry is public keys.
2070 StateDirectoryMode = "0755";
2071 NoNewPrivileges = true;
2072 ProtectSystem = "strict";
2073 ReadWritePaths = [ identityStateDir ];
2074 ProtectHome = true;
2075 PrivateTmp = true;
2076 PrivateDevices = true;
2077 ProtectClock = true;
2078 ProtectHostname = true;
2079 ProtectKernelLogs = true;
2080 ProtectKernelModules = true;
2081 ProtectKernelTunables = true;
2082 ProtectControlGroups = true;
2083 ProtectProc = "invisible";
2084 RestrictAddressFamilies = [ "AF_UNIX" ];
2085 RestrictNamespaces = true;
2086 RestrictRealtime = true;
2087 RestrictSUIDSGID = true;
2088 LockPersonality = true;
2089 CapabilityBoundingSet = "";
2090 SystemCallArchitectures = "native";
2091 SystemCallFilter = [ "@system-service" ];
2092 UMask = "0022";
2093 };
2094 };
2095
2096 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
2097 description = "Re-compile the valley identity registry";
2098 wantedBy = [ "timers.target" ];
2099 timerConfig = {
2100 OnBootSec = "1m";
2101 OnUnitActiveSec = cfg.identity.interval;
2102 };
2103 };
2104
2105 # The signers publication, refs/the-valley/signers, is written by a
2106 # oneshot of its own. It runs as the git user, which owns the instance
2107 # repository, and its sandbox lets it write that repository and nothing
2108 # else. It is not part of valley-init, which runs only on activation,
2109 # nor of the registry compiler, whose sandbox writes only its state
2110 # directory. Only the host's machinery writes the ref, never a push:
2111 # the hook refuses every push to it. This unit writes it, and the
2112 # integrator can, being in the group the repository is shared with
2113 # because it lands code there.
2114 #
2115 # What starts it: every boot and every activation, after valley-init,
2116 # which covers a changed signing name, signers path or signer projects
2117 # list; and the path
2118 # unit below, whenever the known-signers file changes, which covers
2119 # each compilation that changed it and a hand-provisioned file being
2120 # replaced. A run reads the current file and name and writes the ref
2121 # only when the tree it makes differs, so a run with nothing new is
2122 # free. Both values are in one tree under one ref, so a client never
2123 # reads one value without the other. A run holds a lock in the
2124 # instance repository from reading the file to moving the ref, so two
2125 # runs take turns, and one that read an older file cannot publish it
2126 # over a newer one. The ref also moves with a compare-and-swap.
2127 #
2128 # A run that cannot read the file, or reads one that is not a list of
2129 # verifier keys, fails and leaves the last publication in place. That
2130 # is the file the controllers were given before it changed, and the
2131 # journal says why. A file with no key in it, as the compiler writes
2132 # once every signing key is revoked, is published, so clients stop
2133 # verifying with the revoked keys.
2134 systemd.services.valley-signers = lib.mkIf publishesSigners {
2135 description = "Publish what clients verify the valley integrator's transfer statements with";
2136 wantedBy = [ "multi-user.target" ];
2137 after = [ "valley-init.service" ] ++ lib.optional cfg.identity.enable "valley-identity.service";
2138 requires = [ "valley-init.service" ];
2139 unitConfig.RequiresMountsFor = cfg.dataDir;
2140 serviceConfig = {
2141 Type = "oneshot";
2142 ExecStart = signersCommand;
2143 User = cfg.user;
2144 Group = cfg.group;
2145 NoNewPrivileges = true;
2146 ProtectSystem = "strict";
2147 ReadWritePaths = [ instanceRepo ];
2148 ProtectHome = true;
2149 PrivateTmp = true;
2150 PrivateDevices = true;
2151 ProtectClock = true;
2152 ProtectHostname = true;
2153 ProtectKernelLogs = true;
2154 ProtectKernelModules = true;
2155 ProtectKernelTunables = true;
2156 ProtectControlGroups = true;
2157 ProtectProc = "invisible";
2158 RestrictAddressFamilies = [ "AF_UNIX" ];
2159 RestrictNamespaces = true;
2160 RestrictRealtime = true;
2161 RestrictSUIDSGID = true;
2162 LockPersonality = true;
2163 CapabilityBoundingSet = "";
2164 SystemCallArchitectures = "native";
2165 SystemCallFilter = [ "@system-service" ];
2166 # The instance repository is always one the integrator serves, since
2167 # it has to be protected, so it is group-shared and its directories
2168 # are setgid. With the default umask, git would chmod each directory
2169 # it makes to add group write, setgid bit included, and
2170 # RestrictSUIDSGID refuses that chmod. Group write from the start
2171 # leaves git nothing to chmod, as for the controllers.
2172 UMask = "0002";
2173 };
2174 };
2175
2176 systemd.paths.valley-signers = lib.mkIf publishesSigners {
2177 description = "Watch the known-signers file the valley integrator reads";
2178 wantedBy = [ "multi-user.target" ];
2179 pathConfig.PathChanged = knownSigners;
2180 };
2181
2182 # One controller per served project, as instances of a single template:
2183 # the units differ only in the repository they serve, which is the
2184 # instance name. `watch` rather than a timer firing `reconcile`: the
2185 # binary owns its poll loop and its interval, and a timer would be a
2186 # second cadence over the same level-triggered refs.
2187 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
2188 description = "The valley integrator for %i";
2189 after = [
2190 "network.target"
2191 "valley-init.service"
2192 ]
2193 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
2194 ++ lib.optional cfg.identity.enable "valley-identity.service";
2195 requires = [ "valley-init.service" ];
2196 # Wants, not requires: a controller reads the compiled signers file,
2197 # so it starts after the first compilation — but a compilation that
2198 # failed must not keep the controllers down. One that finds no file
2199 # says so and restarts, which is the same loop and a louder one.
2200 wants = lib.optional cfg.identity.enable "valley-identity.service";
2201 unitConfig.RequiresMountsFor = cfg.dataDir;
2202 # nix is not pinned, for the reason the integrator package does not
2203 # pin it: a check's input closure must be recomputed by the nix this
2204 # machine actually runs. Everything else a controller drives is
2205 # pinned inside the wrapper.
2206 path = [ config.nix.package ];
2207 # The repositories belong to the git user and the controller does
2208 # not, so git refuses to touch them as dubiously owned. The exception
2209 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
2210 # command-scope config, which is protected config, so safe.directory
2211 # is honoured from it — a repository-scoped setting would be ignored,
2212 # deliberately. And every git the controller drives is a child of
2213 # this unit, whether run by the integrator itself or by attest or the
2214 # deriver, so one environment covers all of them.
2215 #
2216 # One repository per instance: never a global gitconfig, never a
2217 # wildcard. Every other repository on the host stays refused. Linked
2218 # worktrees need no entry of their own — the controller creates them,
2219 # so it owns them, and git checks the worktree and its gitdir rather
2220 # than the repository they point at.
2221 #
2222 # TMPDIR is the same kind of wiring, for the same reason. A verdict
2223 # wants a checkout of the tip on disk, and the integrator asks for one
2224 # the ordinary way — a temporary directory, then a linked worktree in
2225 # it. The sandbox below leaves no writable temporary directory, so
2226 # every tick died on `could not create leading directories`. The
2227 # scratch belongs under the state directory the unit already has:
2228 # writable by construction, owned by this service, and gone when the
2229 # service's state is. Setting it in the environment rather than
2230 # teaching the binary a flag covers every process in the unit at once
2231 # — the integrator, attest, the deriver, and the git each of them runs
2232 # all read TMPDIR, and all of them want scratch in the same place.
2233 #
2234 # A second exception, for the instance repository. Every controller
2235 # reads the group's floor from that repository's tip, and it need not
2236 # be the project the controller serves — the controller for one
2237 # project reads the floor out of another project's repository, which
2238 # it likewise does not own. Without the exception git refuses it as
2239 # dubiously owned and every pass fails, exactly as it did for the
2240 # served repository. Two entries, both named; still never a wildcard.
2241 #
2242 # Reading needs no sandbox entry beside it. ProtectSystem=strict
2243 # leaves the filesystem readable and only takes write away, so the
2244 # ReadWritePaths list above stays the list of what may be written,
2245 # which is what makes it worth reading. What read does need is a
2246 # filesystem grant, and valley-init makes it: the instance repository
2247 # is group-readable whether or not it is one of the served projects.
2248 environment = {
2249 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
2250 GIT_CONFIG_KEY_0 = "safe.directory";
2251 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
2252 TMPDIR = integratorStateDir;
2253 }
2254 // lib.optionalAttrs (instanceRepo != null) {
2255 GIT_CONFIG_KEY_1 = "safe.directory";
2256 GIT_CONFIG_VALUE_1 = instanceRepo;
2257 };
2258 serviceConfig = {
2259 ExecStart = integratorCommand;
2260 Restart = "on-failure";
2261 RestartSec = "10s";
2262 User = cfg.integrator.user;
2263 Group = cfg.group;
2264 StateDirectory = integratorStateName;
2265 StateDirectoryMode = "0700";
2266 WorkingDirectory = integratorStateDir;
2267 NoNewPrivileges = true;
2268 ProtectSystem = "strict";
2269 # Everything the controller may write, named where a reader of the
2270 # unit meets it. Under ProtectSystem=strict the rest of the
2271 # filesystem is read-only, so this list is the whole of what the
2272 # service can touch, and it is worth being able to read it as such
2273 # rather than as the exceptions plus whatever else is implied.
2274 #
2275 # Its own directory: its state, and the scratch root TMPDIR names.
2276 # A declaration says it here rather than relying on the state
2277 # directory being read-write by virtue of being declared, which is
2278 # not something this unit found to be true.
2279 #
2280 # The one repository it serves, and the nix daemon's socket —
2281 # recomputing a closure means asking the daemon, and connecting to
2282 # a unix socket needs write access to it.
2283 ReadWritePaths = [
2284 integratorStateDir
2285 "${cfg.dataDir}/%i.git"
2286 "/nix/var/nix/daemon-socket"
2287 ];
2288 ProtectHome = true;
2289 PrivateTmp = true;
2290 PrivateDevices = true;
2291 ProtectClock = true;
2292 ProtectHostname = true;
2293 ProtectKernelLogs = true;
2294 ProtectKernelModules = true;
2295 ProtectKernelTunables = true;
2296 ProtectControlGroups = true;
2297 ProtectProc = "invisible";
2298 RestrictAddressFamilies = [
2299 "AF_INET"
2300 "AF_INET6"
2301 "AF_UNIX"
2302 ];
2303 RestrictNamespaces = true;
2304 RestrictRealtime = true;
2305 RestrictSUIDSGID = true;
2306 LockPersonality = true;
2307 CapabilityBoundingSet = "";
2308 SystemCallArchitectures = "native";
2309 SystemCallFilter = [ "@system-service" ];
2310 # Group write, not the bus unit's 0077: the git user owns these
2311 # repositories and has to stay able to write what a controller
2312 # leaves in them.
2313 UMask = "0002";
2314 };
2315 };
2316
2317 # What pushes the mirrors: a path unit per published project, watching
2318 # its publish queue, and the drain it starts.
2319 systemd.paths."valley-publish@" = lib.mkIf (publishedProjects != { }) {
2320 description = "Watch the publish queue of %i";
2321 pathConfig.DirectoryNotEmpty = "${cfg.dataDir}/%i.git/${publishQueueName}";
2322 };
2323
2324 # It runs as the git user, with ssh on its path, because the mirror
2325 # credentials are that user's. Each run drains the whole queue, so starts
2326 # are at most one per queued move, and a burst of moves must not trip
2327 # systemd's start limit and leave the queue undrained. A run is bounded
2328 # instead: one that hangs on a mirror is cut off after 15 minutes, and
2329 # systemd stops its whole cgroup, so nothing it started outlives it. A
2330 # run that fails or is cut off leaves its moves queued, and systemd
2331 # starts it again after a delay that grows from 30 seconds to 15 minutes,
2332 # until a run succeeds. While it waits to restart, the unit is not
2333 # inactive, so the path unit does not start it again sooner.
2334 systemd.services."valley-publish@" = lib.mkIf (publishedProjects != { }) {
2335 description = "Push the moves queued on %i to its mirrors";
2336 after = [ "valley-init.service" ];
2337 unitConfig.RequiresMountsFor = cfg.dataDir;
2338 startLimitIntervalSec = 0;
2339 path = [ config.programs.ssh.package ];
2340 serviceConfig = {
2341 Type = "oneshot";
2342 ExecStart = "${publishDrains}/%i";
2343 User = cfg.user;
2344 Group = cfg.group;
2345 WorkingDirectory = "${cfg.dataDir}/%i.git";
2346 TimeoutStartSec = "15min";
2347 Restart = "on-failure";
2348 RestartSec = "30s";
2349 RestartSteps = 5;
2350 RestartMaxDelaySec = "15min";
2351 };
2352 };
2353
2354 # wantedBy on a template unit enables nothing, so the instances the
2355 # declaration asks for are pulled in by name.
2356 systemd.targets.valley-publish = lib.mkIf (publishedProjects != { }) {
2357 description = "What pushes the valley's mirrors";
2358 wantedBy = [ "multi-user.target" ];
2359 wants = map (name: "valley-publish@${name}.path") (lib.attrNames publishedProjects);
2360 };
2361
2362 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
2363 description = "The valley integrator's controllers";
2364 wantedBy = [ "multi-user.target" ];
2365 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
2366 };
2367
2368 # The build slice. The daemon runs every build in its own cgroup,
2369 # whoever asked for it, so a cap on a build is a cap on the daemon: the
2370 # slice holds nix-daemon.service, and the check worker when it runs,
2371 # and the kernel holds everything in it to the quota and the memory cap
2372 # together, with no swap. Every user's builds through the daemon share
2373 # the caps. A nix command that does not go through the daemon, such as
2374 # one root runs on the store directly, is outside the slice and
2375 # uncapped.
2376 #
2377 # A build that takes the slice past its memory cap is ended by the
2378 # kernel's OOM killer, which kills the process in the slice using the
2379 # most memory. That is usually the build that went past, and it can be
2380 # another build in the slice. The rest of the host goes on as it was.
2381 # When the OOM killer kills one of the daemon's processes, systemd keeps
2382 # the daemon's unit running, since the unit delegates its cgroup
2383 # (OOMPolicy=continue). Nothing exempts the daemon's own processes from
2384 # being the one chosen.
2385 # The slice sets no device policy, so a build keeps the /dev/kvm the
2386 # daemon gives NixOS tests.
2387 systemd.slices.valley-builds = lib.mkIf cfg.buildSlice.enable {
2388 description = "Every build of the nix daemon, under the host's caps";
2389 sliceConfig = {
2390 CPUQuota = cfg.buildSlice.cpuQuota;
2391 MemoryMax = cfg.buildSlice.memoryMax;
2392 MemorySwapMax = "0";
2393 };
2394 };
2395
2396 systemd.services.nix-daemon.serviceConfig.Slice = lib.mkIf cfg.buildSlice.enable buildSlice;
2397
2398 # One pass of the worker, as a oneshot the timer below starts. A pass
2399 # that finds nothing to build reads origin and ends. Two passes never
2400 # overlap: systemd starts the unit only while it is inactive, and the
2401 # worker's own lock in its state directory serializes any pass started
2402 # by hand.
2403 #
2404 # The unit runs in the build slice, so its evaluation shares the caps
2405 # with the builds. It runs on one CPU. attest runs one nix build per
2406 # CPU it may run on, and NIX_CONFIG holds each of those to one
2407 # derivation at a time, so the worker's builds run one at a time. The
2408 # builds themselves run in the daemon, under the slice's quota,
2409 # whatever CPU the worker is on.
2410 systemd.services.valley-worker = lib.mkIf cfg.worker.enable {
2411 description = "One pass of the valley check worker";
2412 after = [
2413 "network.target"
2414 "sshd.service"
2415 "valley-init.service"
2416 "systemd-tmpfiles-setup.service"
2417 ];
2418 unitConfig.RequiresMountsFor = workerDir;
2419 # nix is the machine's own, for the reason the integrator's is.
2420 path = [
2421 workerPackage
2422 attestPackage
2423 pkgs.git
2424 pkgs.diffutils
2425 config.programs.ssh.package
2426 config.nix.package
2427 ];
2428 environment = {
2429 HOME = workerDir;
2430 XDG_CACHE_HOME = "${workerDir}/cache";
2431 GIT_SSH_COMMAND = workerSsh;
2432 NIX_CONFIG = workerNixConfig;
2433 };
2434 script = workerScript;
2435 serviceConfig = {
2436 Type = "oneshot";
2437 User = "valley-worker";
2438 Group = "valley-worker";
2439 Slice = buildSlice;
2440 CPUAffinity = "0";
2441 NoNewPrivileges = true;
2442 ProtectSystem = "strict";
2443 # Its own directory, and the nix daemon's socket, which a client
2444 # writes to connect.
2445 ReadWritePaths = [
2446 workerDir
2447 "/nix/var/nix/daemon-socket"
2448 ];
2449 ProtectHome = true;
2450 PrivateTmp = true;
2451 PrivateDevices = true;
2452 ProtectClock = true;
2453 ProtectHostname = true;
2454 ProtectKernelLogs = true;
2455 ProtectKernelModules = true;
2456 ProtectKernelTunables = true;
2457 ProtectControlGroups = true;
2458 ProtectProc = "invisible";
2459 RestrictAddressFamilies = [
2460 "AF_INET"
2461 "AF_INET6"
2462 "AF_UNIX"
2463 ];
2464 RestrictNamespaces = true;
2465 RestrictRealtime = true;
2466 RestrictSUIDSGID = true;
2467 LockPersonality = true;
2468 CapabilityBoundingSet = "";
2469 SystemCallArchitectures = "native";
2470 SystemCallFilter = [ "@system-service" ];
2471 UMask = "0077";
2472 };
2473 };
2474
2475 # The first pass starts five minutes after the timer starts. Each later
2476 # pass starts one interval after the last one ended, so a long batch is
2477 # never followed at once by another pass. These are delays and nothing
2478 # more: a switch that runs longer than five minutes can see the first
2479 # pass start inside it, and any later switch can see a pass start
2480 # inside it.
2481 systemd.timers.valley-worker = lib.mkIf cfg.worker.enable {
2482 description = "Run the valley check worker";
2483 wantedBy = [ "timers.target" ];
2484 timerConfig = {
2485 OnActiveSec = "5m";
2486 OnUnitInactiveSec = cfg.worker.interval;
2487 };
2488 };
2489
2490 # Offsite backup, rendered only when the declaration asks for it. The
2491 # declaration states the policy — that backup exists, its cadence and
2492 # retention; the services.valley.backup.* options supply the machine
2493 # half. Declaration absent or disabled ⇒ no restic config at all.
2494 services.restic.backups = lib.mkIf backupEnabled {
2495 valley = {
2496 initialize = true;
2497 repositoryFile = cfg.backup.repositoryFile;
2498 passwordFile = cfg.backup.passwordFile;
2499 paths = [ cfg.dataDir ];
2500 # The schema admits only the restic-sftp target today; a second
2501 # target would grow a dispatch here. The service runs as root:
2502 # authenticate with the supplied identity and only the pinned
2503 # host key. No prompt can be answered inside a systemd unit, so
2504 # BatchMode + strict host key checking turn a would-be hang into
2505 # an immediate error.
2506 extraOptions = [
2507 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
2508 ];
2509 timerConfig = backupTimer.${backupPolicy.cadence};
2510 pruneOpts = [
2511 "--keep-daily ${toString backupPolicy.retention.daily}"
2512 "--keep-weekly ${toString backupPolicy.retention.weekly}"
2513 "--keep-monthly ${toString backupPolicy.retention.monthly}"
2514 ];
2515 };
2516 };
2517 };
2518}