gunk-dev/the-valley

valley-host.nix

source6545b7fdec50main's published tip history
59.6 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# (.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# (.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 renders the hook. Those bindings
24# are declared by hand or compiled from the instance's identity registry,
25# 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). Nothing here plumbs secrets: the backup options
30# below take *paths* to consumer-provisioned secret files; the contents
31# never pass through this module or the store.
32#
33# One service runs under its own unix user rather than the git one: the
34# integrator. That is the first half of the split bd-500adf7 asks for.
35{
36 config,
37 pkgs,
38 lib,
39 ...
40}:
41
42let
43 cfg = config.services.valley;
44
45 schema = ../schema/valley.cue;
46
47 # Build-time vet + export of the host declaration. the vet checks the
48 # declaration against the schema (whose top level applies #Host), so unknown
49 # fields and unsafe project names fail the build, with cue's error.
50 configJSON =
51 pkgs.runCommand "valley-config.json"
52 {
53 nativeBuildInputs = [ pkgs.cue ];
54 }
55 ''
56 cue vet -c ${schema} ${cfg.config}
57 cue export ${schema} ${cfg.config} > $out
58 '';
59
60 host = lib.importJSON configJSON;
61
62 # Projects whose git store is enabled get a bare repository.
63 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
64 repoNames = lib.attrNames gitProjects;
65
66 # The declared durability policy, if any. `backup` is optional in the
67 # schema: a declaration without it (or with enable = false) renders zero
68 # backup machinery, exactly as before the field existed.
69 backupPolicy = host.backup or null;
70 backupEnabled = backupPolicy != null && backupPolicy.enable;
71
72 # The declared cadence names policy; its wall-clock rendering is this
73 # installer's choice. A lookup rather than a literal, so a cadence this
74 # module does not know fails eval loudly instead of mis-scheduling.
75 backupTimer = {
76 # Late night with a spread; Persistent runs a missed window at boot.
77 nightly = {
78 OnCalendar = "03:30";
79 RandomizedDelaySec = "30m";
80 Persistent = true;
81 };
82 };
83
84 # The projects the integrator serves: exactly the ones the declaration
85 # protects. A protected ref is one only a declared writer may push, and
86 # the integrator is what lands everyone else's changes onto it.
87 integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects;
88
89 # The integrator this flake builds, in its shipping form: attest, the
90 # deriver, cue, git and natscli pinned inside the wrapper, so every host
91 # judges with the same tools (nix/packages.nix).
92 integratorPackage = (import ./packages.nix { inherit pkgs lib; }).integrator;
93
94 # The whole of a controller's configuration: which repository it serves,
95 # who it signs as, and whose evidence it accepts. No policy — the
96 # integrator reads the project layer from the target tip and the instance
97 # layer from its own side (bd-eaefe82) — and no project name, which the
98 # binary derives from the bare repo's own directory, the same way the
99 # post-receive hook does.
100 integratorCommand = lib.concatStringsSep " " (
101 [
102 "${integratorPackage}/bin/integrator watch"
103 "--repo ${cfg.dataDir}/%i.git"
104 "--key ${toString cfg.integrator.signingKeyFile}"
105 "--known-signers ${knownSigners}"
106 "--interval ${cfg.integrator.interval}"
107 ]
108 ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}"
109 ++ (
110 if cfg.integrator.instanceProject != null then
111 [ "--instance-repo ${instanceRepo}" ]
112 else
113 [ "--instance ${toString cfg.integrator.instancePolicy}" ]
114 )
115 ++ lib.optional cfg.bus.enable "--bus ${busUrl}"
116 );
117
118 # The one filesystem grant the integrator's user gets. It writes refs,
119 # objects, and the worktree metadata `git worktree add` keeps inside the
120 # repository, so read access is not enough: the repos it serves become
121 # group-shared, and its primary group is the git group. Re-applied on
122 # every activation, because a repo can predate the service.
123 # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by
124 # whichever user got there first. Left alone that user is the integrator,
125 # and this sweep runs as the git user, which cannot chmod a directory it
126 # does not own. So init makes that directory itself, ahead of any
127 # controller: owned by the git user, group-writable, and setgid, so what a
128 # controller creates inside it lands in the git group and stays reachable.
129 integratorShareCommands =
130 ''
131 # A chmod the git user is not allowed to make is a path some other
132 # user owns; chmod -R applies what it can and then says so. Warn and
133 # carry on, and the trade is worth stating. Failing here fails
134 # valley-init, which every valley unit requires, so the alternative to
135 # a partly shared repository is no git service on the host at all: no
136 # controllers, and no ssh access to any project. A degraded share
137 # costs the integrator the paths it cannot write, is visible in the
138 # journal, and is fixed by one chown. That is the recoverable half of
139 # the trade, and it is the half to take. The warning is what keeps the
140 # degraded state from being a silent one.
141 share() {
142 "$@" || 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
143 }
144 ''
145 + lib.concatMapStrings (name: ''
146 repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
147 git -C "$repo" config core.sharedRepository group
148 # Before the sweep below, so the sweep never meets a root it cannot
149 # touch. On a host where a controller already made it, this is the
150 # chmod that warns, and the repository is served either way.
151 mkdir -p "$repo/worktrees"
152 share chmod g+rwxs "$repo/worktrees"
153 share chmod -R g+rwX "$repo"
154 share find "$repo" -type d -exec chmod g+s {} +
155 '') (lib.attrNames integratedProjects)
156 # The instance repository, when it is not one of the served projects.
157 # Every controller reads the floor from it and none of them writes it,
158 # so read is the whole of the grant — no group write, and no
159 # core.sharedRepository, which is a statement about who writes.
160 + lib.optionalString
161 (
162 cfg.integrator.instanceProject != null
163 && !(integratedProjects ? ${cfg.integrator.instanceProject})
164 )
165 ''
166 repo=${lib.escapeShellArg (toString instanceRepo)}
167 share chmod -R g+rX "$repo"
168 share find "$repo" -type d -exec chmod g+s {} +
169 '';
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 = (import ./packages.nix { inherit pkgs lib; }).identity;
193
194 identityStateName = "valley-identity";
195 identityStateDir = "/var/lib/${identityStateName}";
196 identityKnownSigners = "${identityStateDir}/known-signers";
197
198 # sshd's AuthorizedKeysFile list is global, so the compiled file is named
199 # with the %u token and only the git user's exists. A fixed path would
200 # authorize every registry key for every account on the host, root
201 # included.
202 identityAuthorizedKeys = "${identityStateDir}/authorized_keys.${cfg.user}";
203 identityAuthorizedKeysPattern = "${identityStateDir}/authorized_keys.%u";
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 ];
213
214 # Whose evidence a controller accepts: the compiled artifact once the
215 # registry machinery is on, and the file the consumer supplied otherwise.
216 knownSigners =
217 if cfg.identity.enable then identityKnownSigners else toString cfg.integrator.knownSignersFile;
218
219 # The paths the consumer must supply once the integrator is enabled,
220 # with what each names — for the assertion message. The signers file is
221 # among them only while the registry does not compile one.
222 integratorPathOptions = {
223 signingKeyFile = "the key its transfer statements are signed with";
224 }
225 // lib.optionalAttrs (!cfg.identity.enable) {
226 knownSignersFile = "the signers whose evidence it accepts";
227 };
228
229 # The secret-path options the consumer must supply once the declaration
230 # enables backup, with what each names — for the assertion message.
231 backupSecretOptions = {
232 repositoryFile = "the restic repository URL";
233 passwordFile = "the repository encryption password";
234 sshKeyFile = "the SSH identity for the sftp target";
235 knownHostsFile = "the pinned host key of the sftp target";
236 };
237
238 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
239 # this script, which chains every executable dropped into the repo's
240 # hooks/post-receive.d/ directory.
241 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
242 # Managed by services.valley — do not edit.
243 # Drop executable hooks into post-receive.d/ next to this symlink.
244 set -eu
245 hook_dir="$(dirname "$0")/post-receive.d"
246 [ -d "$hook_dir" ] || exit 0
247 updates="$(cat)"
248 [ -n "$updates" ] || exit 0
249 for hook in "$hook_dir"/*; do
250 [ -x "$hook" ] || continue
251 printf '%s\n' "$updates" | "$hook" "$@"
252 done
253 '';
254
255 # Best-effort push replication. Publication mirror: main and tags only.
256 # Topic branches are review-queue state, not published — the mirror exists
257 # so consumers can fetch what has been integrated; durability is restic's
258 # job, not the mirror's. Pushes run detached (setsid) so a dead mirror can
259 # only ever cost a log line — never block or fail the primary push.
260 # --prune propagates tag deletions (glob refspec); it is a no-op for heads
261 # now that the heads refspec names one ref, so a separate best-effort sweep
262 # deletes every mirror head but main — which also strips anything that
263 # appears there by other means. The sweep reads only refs/heads (ls-remote
264 # --heads), never refs/pull/*, and is logged apart from the replication
265 # push so it cannot change that push's reported outcome. --mirror is
266 # rejected outright: it also tries to delete remote-only namespaces, and on
267 # GitHub the read-only refs/pull/* makes that fail every push, masking real
268 # replication failures.
269 mirrorPusher =
270 name: mirrors:
271 pkgs.writeShellScript "valley-mirror-push-${name}" ''
272 for url in ${lib.escapeShellArgs mirrors}; do
273 if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then
274 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true
275 else
276 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true
277 fi
278
279 # Unpublish anything but main. Refnames cannot contain whitespace, so
280 # accumulating them space-separated and splitting on expansion is safe.
281 stale=""
282 while read -r _ ref; do
283 [ "$ref" = refs/heads/main ] || stale="$stale $ref"
284 done < <(${pkgs.git}/bin/git ls-remote --heads "$url" 2>/dev/null)
285 if [ -n "$stale" ]; then
286 if ${pkgs.git}/bin/git push "$url" --delete $stale >/dev/null 2>&1; then
287 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublished$stale from $url" || true
288 else
289 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublish from $url failed (ignored)" || true
290 fi
291 fi
292 done
293 '';
294
295 mirrorHook =
296 name: mirrors:
297 pkgs.writeShellScript "valley-mirrors-${name}" ''
298 # Managed by services.valley — best-effort push mirrors for ${name}.
299 cat >/dev/null # updated refs unused: the push replicates main and tags
300 ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1
301 exit 0
302 '';
303
304 # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which
305 # the ref-updated hook below projects this host's git activity. The bus is
306 # never load-bearing for durable state — per-repo events are durable in
307 # git itself, and `valley replay` rebuilds the stream from a repo's refs —
308 # so losing its storage costs one replay, nothing more.
309 busUrl = "nats://${cfg.bus.listen}";
310
311 busServerConfig = pkgs.writeText "valley-bus.conf" ''
312 listen: ${cfg.bus.listen}
313 jetstream {
314 store_dir: "${cfg.bus.storeDir}"
315 # The store directory defaults to living on the repo volume; the cap
316 # keeps a runaway or malicious local publisher from filling it.
317 max_file_store: 2GiB
318 }
319 '';
320
321 # One ref-updated event per updated ref, read from the post-receive stdin
322 # this script inherits. Every payload field is derivable from git alone —
323 # no wall-clock time, no hostname — so replaying a repo's refs reproduces
324 # the same events (the roadmap's determinism criterion). `valley replay`
325 # builds the identical payload; change one only with the other.
326 busPublisher = pkgs.writeShellScript "valley-bus-publish" ''
327 repo="$(basename "$PWD" .git)"
328 while read -r old new ref; do
329 [ -n "$ref" ] || continue
330 # " is the only JSON-significant character a refname can contain
331 # (git forbids \ and control characters); names and ids are safe.
332 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
333 "$repo" "''${ref//\"/\\\"}" "$old" "$new")"
334 if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \
335 "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then
336 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true
337 else
338 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true
339 fi
340 done
341 '';
342
343 # The post-receive.d hook, with the mirror hook's failure semantics: the
344 # publisher runs detached (setsid, inheriting the updates on stdin), so a
345 # bus problem can only ever cost a log line — never block or fail the
346 # push. git is the source of truth; the bus is the replaceable component.
347 busEventHook = pkgs.writeShellScript "valley-bus-events" ''
348 # Managed by services.valley — project ref updates onto the event bus.
349 ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1
350 exit 0
351 '';
352
353 # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks:
354 # only ever installs, updates, or removes a store symlink — a hand-written
355 # hook of the same name is left alone.
356 busHookCommands = lib.concatMapStrings (
357 name:
358 let
359 bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus";
360 in
361 if cfg.bus.enable then
362 ''
363 bhook=${bhook}
364 if [ -L "$bhook" ]; then
365 case "$(readlink "$bhook")" in
366 /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;;
367 esac
368 elif [ ! -e "$bhook" ]; then
369 ln -s ${busEventHook} "$bhook"
370 fi
371 ''
372 else
373 ''
374 bhook=${bhook}
375 if [ -L "$bhook" ]; then
376 case "$(readlink "$bhook")" in
377 /nix/store/*) rm -f "$bhook" ;;
378 esac
379 fi
380 ''
381 ) repoNames;
382
383 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
384 # a store symlink — a hand-written hook of the same name is left alone.
385 mirrorHookCommands = lib.concatStrings (
386 lib.mapAttrsToList (
387 name: p:
388 let
389 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
390 in
391 if p.mirrors != [ ] then
392 ''
393 mhook=${mhook}
394 if [ -L "$mhook" ]; then
395 case "$(readlink "$mhook")" in
396 /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;;
397 esac
398 elif [ ! -e "$mhook" ]; then
399 ln -s ${mirrorHook name p.mirrors} "$mhook"
400 fi
401 ''
402 else
403 ''
404 mhook=${mhook}
405 if [ -L "$mhook" ]; then
406 case "$(readlink "$mhook")" in
407 /nix/store/*) rm -f "$mhook" ;;
408 esac
409 fi
410 ''
411 ) gitProjects
412 );
413
414 # The environment variable carrying the pushing key's principal name.
415 # sshd sets it from the key's own authorized_keys entry; the pre-receive
416 # hook reads it. One name, honoured only because PermitUserEnvironment
417 # below names it.
418 principalEnv = "VALLEY_PRINCIPAL";
419
420 # Keys that name a principal. An entry written as a bare string names
421 # none, and renders exactly as it always did.
422 taggedKeys = lib.filter (k: !lib.isString k) cfg.authorizedKeys;
423
424 authorizedKeyLine =
425 k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}'';
426
427 # Where a contributor's attestations live (design/contribute.md, step 5).
428 attestationNamespace = "refs/the-valley/attestations/";
429
430 # The pre-receive hook: the one structural git invariant
431 # (design/architecture.md, design/contribute.md). Two clauses and nothing
432 # else — only a declared writer may update a protected ref, and an
433 # attestation ref may only be created. Every other ref is open to anyone
434 # with push access, and all policy beyond this lives in the integrator.
435 #
436 # What is protected and who may write it comes from the declaration's
437 # `protection` block, like every other domain fact here. This renders it.
438 #
439 # Pushes arrive over SSH as one shared git user, so the unix account
440 # behind a push says nothing about who pushed. The principal comes from
441 # the key instead: services.valley.authorizedKeys tags each key's
442 # authorized_keys entry, sshd puts that tag in the environment of the
443 # receive-pack this hook runs under, and an untagged key has no principal
444 # at all. The client cannot supply the tag itself — sshd passes on no
445 # client environment (no AcceptEnv).
446 #
447 # This governs pushes, which is every write that crosses the host
448 # boundary. It does not govern writes made on the host: the integrator
449 # updates refs locally, as could anyone holding the git user's shell.
450 # Local access is the host's own boundary, not this hook's.
451 protectHook =
452 name: p:
453 pkgs.writeShellScript "valley-protect-${name}" ''
454 # Managed by services.valley — do not edit.
455 set -eu
456
457 principal="''${${principalEnv}:-}"
458 [ -n "$principal" ] || principal="<untagged key>"
459 writers=( ${lib.escapeShellArgs p.writers} )
460 protected=( ${lib.escapeShellArgs p.refs} )
461
462 is_writer() {
463 local w
464 for w in ''${writers[@]+"''${writers[@]}"}; do
465 if [ "$w" = "$principal" ]; then return 0; fi
466 done
467 return 1
468 }
469
470 rejected=0
471 while read -r old new ref; do
472 [ -n "$ref" ] || continue
473
474 # An attestation is a record of what was checked; a record that can
475 # be rewritten or dropped is not one. So the namespace is
476 # create-only, for everyone — an all-zero old id is a creation, at
477 # any hash length.
478 case "$ref" in
479 ${attestationNamespace}*)
480 case "$old" in
481 *[!0]*)
482 echo "valley: $principal may not update $ref — attestation refs are create-only" >&2
483 rejected=1
484 ;;
485 esac
486 continue
487 ;;
488 esac
489
490 # Protected refs, matched as shell globs (so `*` crosses path
491 # separators). Unprotected refs are not the hook's business.
492 for pattern in ''${protected[@]+"''${protected[@]}"}; do
493 case "$ref" in
494 $pattern)
495 if ! is_writer; then
496 echo "valley: $principal may not write $ref — a protected ref of ${name} (writers: ${
497 lib.concatStringsSep ", " p.writers
498 })" >&2
499 rejected=1
500 fi
501 break
502 ;;
503 esac
504 done
505 done
506 exit "$rejected"
507 '';
508
509 # Per-project pre-receive wiring, from the declaration's protection
510 # blocks. Same rules as the other managed hooks: only ever installs,
511 # updates, or removes a store symlink — a hand-written hook of the same
512 # name is left alone. A project that declares no protection gets no hook,
513 # so a declaration written before the field installs nothing new.
514 protectHookCommands = lib.concatStrings (
515 lib.mapAttrsToList (
516 name: p:
517 let
518 phook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/pre-receive";
519 in
520 if p ? protection then
521 ''
522 phook=${phook}
523 if [ -L "$phook" ]; then
524 case "$(readlink "$phook")" in
525 /nix/store/*) ln -sfn ${protectHook name p.protection} "$phook" ;;
526 esac
527 elif [ ! -e "$phook" ]; then
528 ln -s ${protectHook name p.protection} "$phook"
529 fi
530 ''
531 else
532 ''
533 phook=${phook}
534 if [ -L "$phook" ]; then
535 case "$(readlink "$phook")" in
536 /nix/store/*) rm -f "$phook" ;;
537 esac
538 fi
539 ''
540 ) gitProjects
541 );
542in
543{
544 options.services.valley = {
545 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
546
547 user = lib.mkOption {
548 type = lib.types.str;
549 default = "git";
550 description = "System user that owns the repositories and accepts SSH pushes.";
551 };
552
553 group = lib.mkOption {
554 type = lib.types.str;
555 default = "git";
556 description = "Primary group of the valley git user.";
557 };
558
559 dataDir = lib.mkOption {
560 type = lib.types.path;
561 default = "/srv/git";
562 example = "/mnt/git";
563 description = ''
564 Directory holding the bare repositories, one `<name>.git` per
565 project declared in {option}`services.valley.config`. Also the git
566 user's home, so clone URLs are relative to it (`git@host:name.git`).
567 Consumers typically point it at a dedicated dataset.
568 '';
569 };
570
571 authorizedKeys = lib.mkOption {
572 type = lib.types.listOf (
573 lib.types.either lib.types.str (
574 lib.types.submodule {
575 options = {
576 key = lib.mkOption {
577 type = lib.types.str;
578 description = "The SSH public key, as it would appear in `authorized_keys`.";
579 };
580
581 principal = lib.mkOption {
582 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
583 example = "integrator";
584 description = ''
585 Name of the principal this key acts as. Every push made
586 with the key carries the name, and
587 {option}`services.valley.protect` decides what a name may
588 write. Nothing else uses it.
589 '';
590 };
591 };
592 }
593 )
594 );
595 default = [ ];
596 example = lib.literalExpression ''
597 [
598 "ssh-ed25519 AAAA… someone@somewhere"
599 {
600 principal = "integrator";
601 key = "ssh-ed25519 AAAA… integrator";
602 }
603 ]
604 '';
605 description = ''
606 SSH public keys allowed to push/fetch as the git user. Access is
607 host-level by design: every key can reach every project.
608
609 A key written as a plain string is anonymous — it can push, and it
610 can write nothing protected. A key written as an attribute set
611 names the principal it acts as, which is the only thing that can
612 tell one pusher from another: pushes arrive as the shared git user,
613 so identity has to ride on the key.
614
615 Which refs a principal may write is declared, not an option here:
616 it is a statement about what the host serves, and lives in the
617 project's `protection` block in
618 {option}`services.valley.config`. Binding a name to keys is the
619 machine half — the hand-written form of what the identity registry
620 compiles (dcr-b87f6e8).
621
622 With {option}`services.valley.identity.enable` on, the compiled
623 keys are added to what sshd reads and the keys here stay
624 authorized beside them. The list is therefore the way back in when
625 a compilation is wrong or has not happened yet, and it is never
626 empty.
627 '';
628 };
629
630 config = lib.mkOption {
631 type = lib.types.path;
632 example = lib.literalExpression "./valley.cue";
633 description = ''
634 Path to the host's CUE declaration (`package valley`) — the
635 canonical statement of what this valley host serves, validated
636 against the shipped schema at build time. This is the single domain
637 input: projects, their push mirrors, and the backup policy are
638 declared here, never as Nix options.
639 '';
640 };
641
642 # The event bus. Machine options, not domain: whether this machine runs
643 # a bus, where it listens, and where its storage lives. What gets
644 # published onto it is defined portably in ../schema/events.cue.
645 bus = {
646 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
647
648 listen = lib.mkOption {
649 type = lib.types.str;
650 default = "127.0.0.1:4222";
651 example = "100.100.1.7:4222";
652 description = ''
653 Address the bus listens on, `host:port`. Localhost by default:
654 nothing off the host can reach the bus until the consumer widens
655 this deliberately — e.g. to the host's tailnet address once a
656 remote `valley tail` wants in. Local publishers (the ref-updated
657 hook) connect to this same address, so it must be reachable from
658 the host itself.
659 '';
660 };
661
662 storeDir = lib.mkOption {
663 type = lib.types.path;
664 default = "${cfg.dataDir}/.bus";
665 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
666 description = ''
667 Directory holding the JetStream file storage. The default lives
668 under {option}`services.valley.dataDir`; it can never collide
669 with a repository because project names must start with an
670 alphanumeric. The stream is a projection of git, rebuildable
671 with `valley replay` — losing this directory costs one replay.
672 '';
673 };
674 };
675
676 # The integrator (design/roadmap.md, Phase 3): the controller that
677 # lands a change once its evidence still transfers to the current tip.
678 # Machine options only — whether this host runs controllers, who they
679 # are, and how often they look. Which projects get one is not an option
680 # either: it follows from which projects the declaration protects,
681 # because a protected ref is exactly what a controller exists to write.
682 integrator = {
683 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
684
685 user = lib.mkOption {
686 type = lib.types.str;
687 default = "valley-integrator";
688 description = ''
689 System user the controllers run as. Deliberately not
690 {option}`services.valley.user`: one unix identity per service is
691 the split bd-500adf7 asks for, and this service begins it.
692
693 The account exists only to write the repositories it serves. It
694 gets no shell and no SSH key, and its primary group is
695 {option}`services.valley.group`, which is the whole of its
696 permission model: {option}`services.valley.dataDir` is already
697 group-readable, and each served repository is made group-shared
698 (group write, setgid directories) so a controller can write
699 refs, objects, and git's worktree metadata. Nothing else on the
700 host belongs to that group, and the bus's store directory (mode
701 0700) stays out of reach.
702
703 The key and signers files are the consumer's to provision; both
704 must be readable by this user.
705 '';
706 };
707
708 signingKeyFile = lib.mkOption {
709 type = lib.types.nullOr lib.types.path;
710 default = null;
711 example = "/run/agenix/valley-integrator-key";
712 description = ''
713 ed25519 private key the controllers sign their transfer
714 statements with. A runtime path the consumer provisions (e.g.
715 agenix), never a store path — the store is world-readable.
716 '';
717 };
718
719 knownSignersFile = lib.mkOption {
720 type = lib.types.nullOr lib.types.path;
721 default = null;
722 example = "/var/lib/valley-instance/known_signers";
723 description = ''
724 File of verifier keys whose attestations count, one per line, in
725 `attest key` format. This is the identity registry's interim
726 compilation (dcr-b87f6e8), supplied directly for a host that does
727 not compile one: turning on
728 {option}`services.valley.identity.enable` renders the same file
729 from the registry, and then this option must be left unset.
730 Evidence signed by nobody in it does not transfer, which a
731 controller reports per check rather than treating as a forgery.
732 '';
733 };
734
735 signingName = lib.mkOption {
736 type = lib.types.nullOr lib.types.str;
737 default = null;
738 example = "integrator";
739 description = ''
740 The name a controller's transfer statements are signed under.
741 Unset leaves the binary's own default, which is this host's
742 attestations name — the machine signing as itself.
743
744 Set it to the name the identity registry publishes the
745 integrator's key under. The note format's key hash binds the name
746 to the key (dcr-de9d996), so a controller signing under one name
747 while the registry publishes it under another produces notes no
748 verifier can find a key for.
749 '';
750 };
751
752 instanceProject = lib.mkOption {
753 type = lib.types.nullOr lib.types.str;
754 default = null;
755 example = "qinling";
756 description = ''
757 The project whose served repository carries the group's floor —
758 the instance policy layer every controller on this host composes
759 against. A controller reads it from `policy/instance/` in that
760 bare repository's integrated tip, and nothing is materialized on
761 disk in between. It is also where the identity registry is read
762 from, for the same reason and at the same altitude: both are the
763 instance's, so a host serving that repository already holds the
764 authoritative copy.
765
766 The floor is the instance repository's, read at the tip that has
767 been integrated (dcr-f41f718); the instance repository is the
768 group's own (dcr-b87f6e8). A host serving it is therefore already
769 holding the authoritative copy.
770
771 What follows is a property of that design, and worth knowing
772 before editing a floor. A change to it takes effect at the first
773 pass after it lands on that ref, and never before. An edit in a
774 branch, in a worktree, or in an integration request that has not
775 been integrated governs nothing. There is no refresh to trigger
776 and no staleness to wait out: landing is the whole of publishing
777 a floor.
778
779 Every controller on the host reads the same repository, the
780 controller serving that repository included. Both layers are
781 resolved from the controller's own side — this one, and the
782 project's `policy/project/` at the target tip — so a change can
783 never supply the policy that gates it (bd-eaefe82).
784
785 Those two directories are the convention, and the module states
786 neither: a controller takes each layer from the place the
787 integrator defaults to, so a host declaration that says nothing
788 about policy gets the layout the worked example lays out
789 (dcr-f41f718).
790 '';
791 };
792
793 instancePolicy = lib.mkOption {
794 type = lib.types.nullOr lib.types.path;
795 default = null;
796 example = "/var/lib/valley-instance/policy/instance";
797 description = ''
798 Directory of `*.cue` files holding the instance policy layer, for
799 a host that serves no instance repository. It holds what
800 `policy/instance/` in the instance repository holds. Set this or
801 {option}`services.valley.integrator.instanceProject`, never both.
802
803 Keeping such a directory in step with the instance repository is
804 the consumer's to arrange, which is the reason to prefer the
805 project option wherever the host serves the repository.
806 '';
807 };
808
809 interval = lib.mkOption {
810 type = lib.types.str;
811 default = "15s";
812 example = "1m";
813 description = ''
814 How long a controller waits between passes. The integrator polls
815 deliberately: integration requests are durable in git, and the
816 controller level-triggers over those refs, so a lost event costs
817 one interval and nothing more.
818 '';
819 };
820 };
821
822 # The identity registry compiler (dcr-b87f6e8): the step between the
823 # instance's declared registry and the two gates that read what it
824 # compiles to. Machine options only — whether this host compiles, and
825 # from where. Who the principals are, what they hold and when their
826 # entries end is the registry's, and the registry is a document in the
827 # instance repository, never an option here.
828 identity = {
829 enable = lib.mkEnableOption ''
830 compiling the identity registry into what the gates check: the
831 verifier keys a controller accepts evidence from, and the git
832 user's authorized keys, both rendered from the instance
833 repository's integrated tip'';
834
835 ref = lib.mkOption {
836 type = lib.types.str;
837 default = "refs/heads/main";
838 description = ''
839 The ref of the instance repository whose tip carries the
840 registry. A registry edit takes effect at the first compilation
841 after it lands on this ref, and never before: an edit in a
842 branch, in a worktree, or in an integration request that has not
843 been integrated governs nothing.
844 '';
845 };
846
847 directory = lib.mkOption {
848 type = lib.types.str;
849 default = "identity";
850 description = ''
851 The registry's directory in that tip. It is a CUE package: the
852 directory is the enumeration, and every `*.cue` document
853 directly in it unifies into one registry.
854 '';
855 };
856
857 interval = lib.mkOption {
858 type = lib.types.str;
859 default = "5m";
860 example = "1m";
861 description = ''
862 How long between compilations. The compiler is level-triggered
863 and idempotent — it renders the current tip and replaces an
864 artifact only when its bytes changed — so a timer is the whole
865 of the trigger, and a landed registry change takes effect within
866 one interval.
867 '';
868 };
869 };
870
871 # Machine integration for the declared backup policy. The declaration
872 # states WHAT must hold (offsite backup, cadence, retention); these
873 # options supply HOW on this machine — where the repository is and how
874 # to authenticate. All are paths to files the consumer provisions
875 # (e.g. agenix), required when the declaration enables backup. Point
876 # them at runtime paths, never at files in the Nix store.
877 backup = {
878 repositoryFile = lib.mkOption {
879 type = lib.types.nullOr lib.types.path;
880 default = null;
881 example = "/run/agenix/valley-restic-repo";
882 description = ''
883 File containing the restic repository URL, for the sftp target
884 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
885 '';
886 };
887
888 passwordFile = lib.mkOption {
889 type = lib.types.nullOr lib.types.path;
890 default = null;
891 example = "/run/agenix/valley-restic-password";
892 description = ''
893 File containing the restic repository encryption password.
894 Losing it loses the backups — keep a copy somewhere that
895 survives this host.
896 '';
897 };
898
899 sshKeyFile = lib.mkOption {
900 type = lib.types.nullOr lib.types.path;
901 default = null;
902 example = "/run/agenix/valley-git-ssh-key";
903 description = ''
904 SSH private key that authenticates to the sftp target. The
905 backup service runs as root, so any identity the target
906 authorizes works — reusing the mirror key is fine.
907 '';
908 };
909
910 knownHostsFile = lib.mkOption {
911 type = lib.types.nullOr lib.types.path;
912 default = null;
913 example = "/var/lib/valley-backup/known_hosts";
914 description = ''
915 known_hosts file pinning the sftp target's host key. Pin from
916 the provider's published fingerprints, not a blind ssh-keyscan.
917 '';
918 };
919 };
920 };
921
922 config = lib.mkIf cfg.enable {
923 assertions = [
924 {
925 assertion = cfg.authorizedKeys != [ ];
926 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
927 }
928 ]
929 ++ lib.optionals backupEnabled (
930 lib.mapAttrsToList (name: what: {
931 assertion = cfg.backup.${name} != null;
932 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).";
933 }) backupSecretOptions
934 )
935 ++ lib.optionals cfg.integrator.enable (
936 lib.mapAttrsToList (name: what: {
937 assertion = cfg.integrator.${name} != null;
938 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
939 }) integratorPathOptions
940 ++ [
941 {
942 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
943 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.";
944 }
945 {
946 assertion =
947 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
948 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.";
949 }
950 {
951 assertion = cfg.integrator.user != cfg.user;
952 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
953 }
954 {
955 assertion = integratedProjects != { };
956 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.";
957 }
958 ]
959 )
960 ++ lib.optionals cfg.identity.enable [
961 {
962 assertion = cfg.integrator.instanceProject != null;
963 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.";
964 }
965 {
966 assertion = cfg.integrator.knownSignersFile == null;
967 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.";
968 }
969 ];
970
971 users.groups.${cfg.group} = { };
972
973 users.users.${cfg.user} = {
974 isSystemUser = true;
975 group = cfg.group;
976 home = cfg.dataDir;
977 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
978 # interactive logins are rejected (no ~/git-shell-commands).
979 shell = "${pkgs.git}/bin/git-shell";
980 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
981 };
982
983 # The integrator's own account. No shell, no keys, no home of its own
984 # beyond the state directory its units get; the git group is the only
985 # thing it holds.
986 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
987 isSystemUser = true;
988 group = cfg.group;
989 home = "/var/lib/valley-integrator";
990 description = "The valley integrator";
991 };
992
993 services.openssh.enable = lib.mkDefault true;
994
995 # Honour the principal tag on a key's entry, and nothing else: the
996 # pattern-list form admits that one variable name. Rendered only once a
997 # key names a principal — declared here, or compiled from the registry
998 # — so a host with none keeps the sshd config it had.
999 services.openssh.settings = lib.optionalAttrs (taggedKeys != [ ] || cfg.identity.enable) {
1000 PermitUserEnvironment = principalEnv;
1001 };
1002
1003 # The compiled authorized keys, added to the list sshd reads rather than
1004 # replacing it. The declared keys above stay authorized: a compiled file
1005 # can only ever add, so an empty or missing one — a first boot before
1006 # the first compilation, a registry that lost an entry, a bug here —
1007 # cannot take the git user's access away. Which is the point: the
1008 # assertion above keeps at least one key declared, and that key is the
1009 # way back in.
1010 services.openssh.authorizedKeysFiles = lib.mkIf cfg.identity.enable [
1011 identityAuthorizedKeysPattern
1012 ];
1013
1014 # Belt-and-braces hardening for the git user. The trailing `Match All`
1015 # closes the block so it can't scope directives appended to sshd_config
1016 # after this snippet.
1017 services.openssh.extraConfig = ''
1018 Match User ${cfg.user}
1019 AllowTcpForwarding no
1020 AllowAgentForwarding no
1021 X11Forwarding no
1022 PermitTunnel no
1023 Match All
1024 '';
1025
1026 # git-shell spawns git-receive-pack/git-upload-pack from PATH
1027 environment.systemPackages = [ pkgs.git ];
1028
1029 systemd.tmpfiles.rules = [
1030 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
1031 ]
1032 ++ lib.optionals cfg.bus.enable [
1033 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
1034 ];
1035
1036 # The bus itself. It runs as the git user — the store directory lives in
1037 # that user's data — but the sandbox is what confines it: the unit can
1038 # write nowhere except its store directory.
1039 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
1040 description = "The valley event bus (NATS JetStream)";
1041 wantedBy = [ "multi-user.target" ];
1042 after = [
1043 "network.target"
1044 "systemd-tmpfiles-setup.service"
1045 ];
1046 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
1047 serviceConfig = {
1048 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
1049 Restart = "on-failure";
1050 User = cfg.user;
1051 Group = cfg.group;
1052 LimitNOFILE = 65536;
1053 NoNewPrivileges = true;
1054 ProtectSystem = "strict";
1055 ReadWritePaths = [ cfg.bus.storeDir ];
1056 ProtectHome = true;
1057 PrivateTmp = true;
1058 PrivateDevices = true;
1059 ProtectClock = true;
1060 ProtectHostname = true;
1061 ProtectKernelLogs = true;
1062 ProtectKernelModules = true;
1063 ProtectKernelTunables = true;
1064 ProtectControlGroups = true;
1065 ProtectProc = "invisible";
1066 RestrictAddressFamilies = [
1067 "AF_INET"
1068 "AF_INET6"
1069 "AF_UNIX"
1070 ];
1071 RestrictNamespaces = true;
1072 RestrictRealtime = true;
1073 RestrictSUIDSGID = true;
1074 LockPersonality = true;
1075 CapabilityBoundingSet = "";
1076 SystemCallArchitectures = "native";
1077 SystemCallFilter = [ "@system-service" ];
1078 UMask = "0077";
1079 };
1080 };
1081
1082 # The stream is config, not state: (re)created idempotently on every
1083 # boot, capturing everything under valley.>. An existing stream — and
1084 # the events in it — is left untouched.
1085 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
1086 description = "Create the valley event stream";
1087 wantedBy = [ "multi-user.target" ];
1088 requires = [ "valley-bus.service" ];
1089 after = [ "valley-bus.service" ];
1090 serviceConfig = {
1091 Type = "oneshot";
1092 User = cfg.user;
1093 Group = cfg.group;
1094 };
1095 path = [ pkgs.natscli ];
1096 script = ''
1097 # The server needs a moment to accept connections after startup.
1098 for _ in $(seq 1 50); do
1099 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
1100 sleep 0.2
1101 done
1102 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
1103 nats --server ${busUrl} stream add valley \
1104 --subjects 'valley.>' --storage file --defaults
1105 fi
1106 '';
1107 };
1108
1109 # Create missing bare repos and (re)wire the managed hooks on every
1110 # activation where the declaration changed.
1111 systemd.services.valley-init = {
1112 description = "Initialize the valley host's bare git repositories";
1113 wantedBy = [ "multi-user.target" ];
1114 after = [ "systemd-tmpfiles-setup.service" ];
1115 unitConfig.RequiresMountsFor = cfg.dataDir;
1116 serviceConfig = {
1117 Type = "oneshot";
1118 User = cfg.user;
1119 Group = cfg.group;
1120 };
1121 path = [ pkgs.git ];
1122 script = ''
1123 repos=( ${lib.escapeShellArgs repoNames} )
1124 for name in "''${repos[@]}"; do
1125 repo="${cfg.dataDir}/$name.git"
1126 # Check HEAD rather than the directory itself so a pre-existing
1127 # empty directory still gets initialized.
1128 if [ ! -e "$repo/HEAD" ]; then
1129 git init --bare --initial-branch=main "$repo"
1130 fi
1131
1132 # Hook scaffolding: post-receive dispatches to post-receive.d/.
1133 # Only manage the hook if it is absent or already ours (a store
1134 # symlink) — a hand-written hook is left alone.
1135 mkdir -p "$repo/hooks/post-receive.d"
1136 hook="$repo/hooks/post-receive"
1137 if [ -L "$hook" ]; then
1138 case "$(readlink "$hook")" in
1139 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
1140 esac
1141 elif [ ! -e "$hook" ]; then
1142 ln -s ${postReceiveDispatch} "$hook"
1143 fi
1144 done
1145
1146 # Per-project push-mirror hooks.
1147 ${mirrorHookCommands}
1148
1149 # The one structural invariant, on every project declared protected.
1150 ${protectHookCommands}
1151
1152 # The ref-updated publisher hook, on every repo when the bus is on.
1153 ${busHookCommands}
1154
1155 # Group-shared repositories, on what the integrator serves.
1156 ${lib.optionalString cfg.integrator.enable integratorShareCommands}
1157 '';
1158 };
1159
1160 # The registry compiler, on a timer. It renders the instance
1161 # repository's integrated tip into the two artifacts the gates read;
1162 # nothing else on the host writes them.
1163 #
1164 # It runs as the git user rather than under an identity of its own,
1165 # which is the one place this module steps back from the service split
1166 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
1167 # anyone but root or the account it authorizes, so the choice is the git
1168 # user or root, and the git user is the smaller grant.
1169 #
1170 # Level-triggered, like the rest: a compilation reads the current tip
1171 # and replaces an artifact only when its bytes changed, so re-running is
1172 # free and the timer needs no coordination with anything.
1173 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
1174 description = "Compile the valley identity registry into what the gates check";
1175 wantedBy = [ "multi-user.target" ];
1176 after = [ "valley-init.service" ];
1177 requires = [ "valley-init.service" ];
1178 unitConfig.RequiresMountsFor = cfg.dataDir;
1179 serviceConfig = {
1180 Type = "oneshot";
1181 ExecStart = identityCommand;
1182 User = cfg.user;
1183 Group = cfg.group;
1184 StateDirectory = identityStateName;
1185 # sshd walks every directory above an authorized-keys file and
1186 # refuses a group- or world-writable one, so the state directory is
1187 # 0755 deliberately rather than the 0700 a service's state usually
1188 # takes. Nothing secret lives in it: a registry is public keys.
1189 StateDirectoryMode = "0755";
1190 NoNewPrivileges = true;
1191 ProtectSystem = "strict";
1192 ReadWritePaths = [ identityStateDir ];
1193 ProtectHome = true;
1194 PrivateTmp = true;
1195 PrivateDevices = true;
1196 ProtectClock = true;
1197 ProtectHostname = true;
1198 ProtectKernelLogs = true;
1199 ProtectKernelModules = true;
1200 ProtectKernelTunables = true;
1201 ProtectControlGroups = true;
1202 ProtectProc = "invisible";
1203 RestrictAddressFamilies = [ "AF_UNIX" ];
1204 RestrictNamespaces = true;
1205 RestrictRealtime = true;
1206 RestrictSUIDSGID = true;
1207 LockPersonality = true;
1208 CapabilityBoundingSet = "";
1209 SystemCallArchitectures = "native";
1210 SystemCallFilter = [ "@system-service" ];
1211 UMask = "0022";
1212 };
1213 };
1214
1215 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
1216 description = "Re-compile the valley identity registry";
1217 wantedBy = [ "timers.target" ];
1218 timerConfig = {
1219 OnBootSec = "1m";
1220 OnUnitActiveSec = cfg.identity.interval;
1221 };
1222 };
1223
1224 # One controller per served project, as instances of a single template:
1225 # the units differ only in the repository they serve, which is the
1226 # instance name. `watch` rather than a timer firing `reconcile`: the
1227 # binary owns its poll loop and its interval, and a timer would be a
1228 # second cadence over the same level-triggered refs.
1229 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
1230 description = "The valley integrator for %i";
1231 after = [
1232 "network.target"
1233 "valley-init.service"
1234 ]
1235 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
1236 ++ lib.optional cfg.identity.enable "valley-identity.service";
1237 requires = [ "valley-init.service" ];
1238 # Wants, not requires: a controller reads the compiled signers file,
1239 # so it starts after the first compilation — but a compilation that
1240 # failed must not keep the controllers down. One that finds no file
1241 # says so and restarts, which is the same loop and a louder one.
1242 wants = lib.optional cfg.identity.enable "valley-identity.service";
1243 unitConfig.RequiresMountsFor = cfg.dataDir;
1244 # nix is not pinned, for the reason the integrator package does not
1245 # pin it: a check's input closure must be recomputed by the nix this
1246 # machine actually runs. Everything else a controller drives is
1247 # pinned inside the wrapper.
1248 path = [ config.nix.package ];
1249 # The repositories belong to the git user and the controller does
1250 # not, so git refuses to touch them as dubiously owned. The exception
1251 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
1252 # command-scope config, which is protected config, so safe.directory
1253 # is honoured from it — a repository-scoped setting would be ignored,
1254 # deliberately. And every git the controller drives is a child of
1255 # this unit, whether run by the integrator itself or by attest or the
1256 # deriver, so one environment covers all of them.
1257 #
1258 # One repository per instance: never a global gitconfig, never a
1259 # wildcard. Every other repository on the host stays refused. Linked
1260 # worktrees need no entry of their own — the controller creates them,
1261 # so it owns them, and git checks the worktree and its gitdir rather
1262 # than the repository they point at.
1263 #
1264 # TMPDIR is the same kind of wiring, for the same reason. A verdict
1265 # wants a checkout of the tip on disk, and the integrator asks for one
1266 # the ordinary way — a temporary directory, then a linked worktree in
1267 # it. The sandbox below leaves no writable temporary directory, so
1268 # every tick died on `could not create leading directories`. The
1269 # scratch belongs under the state directory the unit already has:
1270 # writable by construction, owned by this service, and gone when the
1271 # service's state is. Setting it in the environment rather than
1272 # teaching the binary a flag covers every process in the unit at once
1273 # — the integrator, attest, the deriver, and the git each of them runs
1274 # all read TMPDIR, and all of them want scratch in the same place.
1275 #
1276 # A second exception, for the instance repository. Every controller
1277 # reads the group's floor from that repository's tip, and it need not
1278 # be the project the controller serves — the controller for one
1279 # project reads the floor out of another project's repository, which
1280 # it likewise does not own. Without the exception git refuses it as
1281 # dubiously owned and every pass fails, exactly as it did for the
1282 # served repository. Two entries, both named; still never a wildcard.
1283 #
1284 # Reading needs no sandbox entry beside it. ProtectSystem=strict
1285 # leaves the filesystem readable and only takes write away, so the
1286 # ReadWritePaths list above stays the list of what may be written,
1287 # which is what makes it worth reading. What read does need is a
1288 # filesystem grant, and valley-init makes it: the instance repository
1289 # is group-readable whether or not it is one of the served projects.
1290 environment = {
1291 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
1292 GIT_CONFIG_KEY_0 = "safe.directory";
1293 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
1294 TMPDIR = integratorStateDir;
1295 }
1296 // lib.optionalAttrs (instanceRepo != null) {
1297 GIT_CONFIG_KEY_1 = "safe.directory";
1298 GIT_CONFIG_VALUE_1 = instanceRepo;
1299 };
1300 serviceConfig = {
1301 ExecStart = integratorCommand;
1302 Restart = "on-failure";
1303 RestartSec = "10s";
1304 User = cfg.integrator.user;
1305 Group = cfg.group;
1306 StateDirectory = integratorStateName;
1307 StateDirectoryMode = "0700";
1308 WorkingDirectory = integratorStateDir;
1309 NoNewPrivileges = true;
1310 ProtectSystem = "strict";
1311 # Everything the controller may write, named where a reader of the
1312 # unit meets it. Under ProtectSystem=strict the rest of the
1313 # filesystem is read-only, so this list is the whole of what the
1314 # service can touch, and it is worth being able to read it as such
1315 # rather than as the exceptions plus whatever else is implied.
1316 #
1317 # Its own directory: its state, and the scratch root TMPDIR names.
1318 # A declaration says it here rather than relying on the state
1319 # directory being read-write by virtue of being declared, which is
1320 # not something this unit found to be true.
1321 #
1322 # The one repository it serves, and the nix daemon's socket —
1323 # recomputing a closure means asking the daemon, and connecting to
1324 # a unix socket needs write access to it.
1325 ReadWritePaths = [
1326 integratorStateDir
1327 "${cfg.dataDir}/%i.git"
1328 "/nix/var/nix/daemon-socket"
1329 ];
1330 ProtectHome = true;
1331 PrivateTmp = true;
1332 PrivateDevices = true;
1333 ProtectClock = true;
1334 ProtectHostname = true;
1335 ProtectKernelLogs = true;
1336 ProtectKernelModules = true;
1337 ProtectKernelTunables = true;
1338 ProtectControlGroups = true;
1339 ProtectProc = "invisible";
1340 RestrictAddressFamilies = [
1341 "AF_INET"
1342 "AF_INET6"
1343 "AF_UNIX"
1344 ];
1345 RestrictNamespaces = true;
1346 RestrictRealtime = true;
1347 RestrictSUIDSGID = true;
1348 LockPersonality = true;
1349 CapabilityBoundingSet = "";
1350 SystemCallArchitectures = "native";
1351 SystemCallFilter = [ "@system-service" ];
1352 # Group write, not the bus unit's 0077: the git user owns these
1353 # repositories and has to stay able to write what a controller
1354 # leaves in them.
1355 UMask = "0002";
1356 };
1357 };
1358
1359 # wantedBy on a template unit enables nothing, so the instances the
1360 # declaration asks for are pulled in by name.
1361 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
1362 description = "The valley integrator's controllers";
1363 wantedBy = [ "multi-user.target" ];
1364 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
1365 };
1366
1367 # Offsite backup, rendered only when the declaration asks for it. The
1368 # declaration states the policy — that backup exists, its cadence and
1369 # retention; the services.valley.backup.* options supply the machine
1370 # half. Declaration absent or disabled ⇒ no restic config at all.
1371 services.restic.backups = lib.mkIf backupEnabled {
1372 valley = {
1373 initialize = true;
1374 repositoryFile = cfg.backup.repositoryFile;
1375 passwordFile = cfg.backup.passwordFile;
1376 paths = [ cfg.dataDir ];
1377 # The schema admits only the restic-sftp target today; a second
1378 # target would grow a dispatch here. The service runs as root:
1379 # authenticate with the supplied identity and only the pinned
1380 # host key. No prompt can be answered inside a systemd unit, so
1381 # BatchMode + strict host key checking turn a would-be hang into
1382 # an immediate error.
1383 extraOptions = [
1384 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
1385 ];
1386 timerConfig = backupTimer.${backupPolicy.cadence};
1387 pruneOpts = [
1388 "--keep-daily ${toString backupPolicy.retention.daily}"
1389 "--keep-weekly ${toString backupPolicy.retention.weekly}"
1390 "--keep-monthly ${toString backupPolicy.retention.monthly}"
1391 ];
1392 };
1393 };
1394 };
1395}