gunk-dev/the-valley

valley-host.nix

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