gunk-dev/the-valley

valley-host.nix

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