gunk-dev/the-valley

valley-host.nix

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