gunk-dev/the-valley

valley-host.nix

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