gunk-dev/the-valley

valley-host.nix

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