gunk-dev/the-valley

valley-host.nix

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