gunk-dev/the-valley

valley-host.nix

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