gunk-dev/the-valley

valley-host.nix

sourceedde5dd8af83main's published tip history
60.1 KiB
1# The valley host installer: declarative bare-git hosting over SSH, driven
2# by a CUE host declaration (../schema/valley.cue).
3#
4# Layering: the CUE file owns the domain model — which projects exist, their
5# stores, their push mirrors, whether the host's data has offsite backup and
6# with what cadence and retention. This module owns machine integration
7# only: data directory, unix user, SSH keys, backup credentials. At build
8# time the CUE config is vetted against the shipped schema and exported to
9# JSON; an invalid config fails the system build with cue's error. Nix
10# never redefines the schema.
11#
12# Repos are only ever created, never deleted or overwritten — removing a
13# project (or disabling its git store) leaves the data on disk untouched.
14#
15# Identity is deliberately thin and host-level: one git user, git-shell,
16# key-only, Tailscale ACLs in front. Per-project *access* is not honestly
17# enforceable with this mechanism, so it is deliberately not an option
18# (.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 # A declaration usually names no writer at all, and then the first clause
437 # refuses every push to the ref. That is the norm, not a misconfiguration:
438 # the integrator writes the ref locally, and a local write is not a push.
439 #
440 # What is protected and who may write it comes from the declaration's
441 # `protection` block, like every other domain fact here. This renders it.
442 #
443 # Pushes arrive over SSH as one shared git user, so the unix account
444 # behind a push says nothing about who pushed. The principal comes from
445 # the key instead: services.valley.authorizedKeys tags each key's
446 # authorized_keys entry, sshd puts that tag in the environment of the
447 # receive-pack this hook runs under, and an untagged key has no principal
448 # at all. The client cannot supply the tag itself — sshd passes on no
449 # client environment (no AcceptEnv).
450 #
451 # This governs pushes, which is every write that crosses the host
452 # boundary. It does not govern writes made on the host: the integrator
453 # updates refs locally, as could anyone holding the git user's shell.
454 # Local access is the host's own boundary, not this hook's.
455 protectHook =
456 name: p:
457 let
458 # What the refusal says about who may write instead. With no writer
459 # declared there is no one, so it says how a change lands.
460 whoMay =
461 if p.writers == [ ] then
462 "no writer is declared — changes land by integration request"
463 else
464 "writers: ${lib.concatStringsSep ", " p.writers}";
465 in
466 pkgs.writeShellScript "valley-protect-${name}" ''
467 # Managed by services.valley — do not edit.
468 set -eu
469
470 principal="''${${principalEnv}:-}"
471 [ -n "$principal" ] || principal="<untagged key>"
472 writers=( ${lib.escapeShellArgs p.writers} )
473 protected=( ${lib.escapeShellArgs p.refs} )
474
475 is_writer() {
476 local w
477 for w in ''${writers[@]+"''${writers[@]}"}; do
478 if [ "$w" = "$principal" ]; then return 0; fi
479 done
480 return 1
481 }
482
483 rejected=0
484 while read -r old new ref; do
485 [ -n "$ref" ] || continue
486
487 # An attestation is a record of what was checked; a record that can
488 # be rewritten or dropped is not one. So the namespace is
489 # create-only, for everyone — an all-zero old id is a creation, at
490 # any hash length.
491 case "$ref" in
492 ${attestationNamespace}*)
493 case "$old" in
494 *[!0]*)
495 echo "valley: $principal may not update $ref — attestation refs are create-only" >&2
496 rejected=1
497 ;;
498 esac
499 continue
500 ;;
501 esac
502
503 # Protected refs, matched as shell globs (so `*` crosses path
504 # separators). Unprotected refs are not the hook's business.
505 for pattern in ''${protected[@]+"''${protected[@]}"}; do
506 case "$ref" in
507 $pattern)
508 if ! is_writer; then
509 echo "valley: $principal may not write $ref — a protected ref of ${name} (${whoMay})" >&2
510 rejected=1
511 fi
512 break
513 ;;
514 esac
515 done
516 done
517 exit "$rejected"
518 '';
519
520 # Per-project pre-receive wiring, from the declaration's protection
521 # blocks. Same rules as the other managed hooks: only ever installs,
522 # updates, or removes a store symlink — a hand-written hook of the same
523 # name is left alone. A project that declares no protection gets no hook,
524 # so a declaration written before the field installs nothing new.
525 protectHookCommands = lib.concatStrings (
526 lib.mapAttrsToList (
527 name: p:
528 let
529 phook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/pre-receive";
530 in
531 if p ? protection then
532 ''
533 phook=${phook}
534 if [ -L "$phook" ]; then
535 case "$(readlink "$phook")" in
536 /nix/store/*) ln -sfn ${protectHook name p.protection} "$phook" ;;
537 esac
538 elif [ ! -e "$phook" ]; then
539 ln -s ${protectHook name p.protection} "$phook"
540 fi
541 ''
542 else
543 ''
544 phook=${phook}
545 if [ -L "$phook" ]; then
546 case "$(readlink "$phook")" in
547 /nix/store/*) rm -f "$phook" ;;
548 esac
549 fi
550 ''
551 ) gitProjects
552 );
553in
554{
555 options.services.valley = {
556 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
557
558 user = lib.mkOption {
559 type = lib.types.str;
560 default = "git";
561 description = "System user that owns the repositories and accepts SSH pushes.";
562 };
563
564 group = lib.mkOption {
565 type = lib.types.str;
566 default = "git";
567 description = "Primary group of the valley git user.";
568 };
569
570 dataDir = lib.mkOption {
571 type = lib.types.path;
572 default = "/srv/git";
573 example = "/mnt/git";
574 description = ''
575 Directory holding the bare repositories, one `<name>.git` per
576 project declared in {option}`services.valley.config`. Also the git
577 user's home, so clone URLs are relative to it (`git@host:name.git`).
578 Consumers typically point it at a dedicated dataset.
579 '';
580 };
581
582 authorizedKeys = lib.mkOption {
583 type = lib.types.listOf (
584 lib.types.either lib.types.str (
585 lib.types.submodule {
586 options = {
587 key = lib.mkOption {
588 type = lib.types.str;
589 description = "The SSH public key, as it would appear in `authorized_keys`.";
590 };
591
592 principal = lib.mkOption {
593 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
594 example = "integrator";
595 description = ''
596 Name of the principal this key acts as. Every push made
597 with the key carries the name, and
598 {option}`services.valley.protect` decides what a name may
599 write. Nothing else uses it.
600 '';
601 };
602 };
603 }
604 )
605 );
606 default = [ ];
607 example = lib.literalExpression ''
608 [
609 "ssh-ed25519 AAAA… someone@somewhere"
610 {
611 principal = "integrator";
612 key = "ssh-ed25519 AAAA… integrator";
613 }
614 ]
615 '';
616 description = ''
617 SSH public keys allowed to push/fetch as the git user. Access is
618 host-level by design: every key can reach every project.
619
620 A key written as a plain string is anonymous — it can push, and it
621 can write nothing protected. A key written as an attribute set
622 names the principal it acts as, which is the only thing that can
623 tell one pusher from another: pushes arrive as the shared git user,
624 so identity has to ride on the key.
625
626 Which refs a principal may write is declared, not an option here:
627 it is a statement about what the host serves, and lives in the
628 project's `protection` block in
629 {option}`services.valley.config`. Binding a name to keys is the
630 machine half — the hand-written form of what the identity registry
631 compiles (dcr-b87f6e8).
632
633 With {option}`services.valley.identity.enable` on, the compiled
634 keys are added to what sshd reads and the keys here stay
635 authorized beside them. The list is therefore the way back in when
636 a compilation is wrong or has not happened yet, and it is never
637 empty.
638 '';
639 };
640
641 config = lib.mkOption {
642 type = lib.types.path;
643 example = lib.literalExpression "./valley.cue";
644 description = ''
645 Path to the host's CUE declaration (`package valley`) — the
646 canonical statement of what this valley host serves, validated
647 against the shipped schema at build time. This is the single domain
648 input: projects, their push mirrors, and the backup policy are
649 declared here, never as Nix options.
650 '';
651 };
652
653 # The event bus. Machine options, not domain: whether this machine runs
654 # a bus, where it listens, and where its storage lives. What gets
655 # published onto it is defined portably in ../schema/events.cue.
656 bus = {
657 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
658
659 listen = lib.mkOption {
660 type = lib.types.str;
661 default = "127.0.0.1:4222";
662 example = "100.100.1.7:4222";
663 description = ''
664 Address the bus listens on, `host:port`. Localhost by default:
665 nothing off the host can reach the bus until the consumer widens
666 this deliberately — e.g. to the host's tailnet address once a
667 remote `valley tail` wants in. Local publishers (the ref-updated
668 hook) connect to this same address, so it must be reachable from
669 the host itself.
670 '';
671 };
672
673 storeDir = lib.mkOption {
674 type = lib.types.path;
675 default = "${cfg.dataDir}/.bus";
676 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
677 description = ''
678 Directory holding the JetStream file storage. The default lives
679 under {option}`services.valley.dataDir`; it can never collide
680 with a repository because project names must start with an
681 alphanumeric. The stream is a projection of git, rebuildable
682 with `valley replay` — losing this directory costs one replay.
683 '';
684 };
685 };
686
687 # The integrator (design/roadmap.md, Phase 3): the controller that
688 # lands a change once its evidence still transfers to the current tip.
689 # Machine options only — whether this host runs controllers, who they
690 # are, and how often they look. Which projects get one is not an option
691 # either: it follows from which projects the declaration protects,
692 # because a protected ref is exactly what a controller exists to write.
693 integrator = {
694 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
695
696 user = lib.mkOption {
697 type = lib.types.str;
698 default = "valley-integrator";
699 description = ''
700 System user the controllers run as. Deliberately not
701 {option}`services.valley.user`: one unix identity per service is
702 the split bd-500adf7 asks for, and this service begins it.
703
704 The account exists only to write the repositories it serves. It
705 gets no shell and no SSH key, and its primary group is
706 {option}`services.valley.group`, which is the whole of its
707 permission model: {option}`services.valley.dataDir` is already
708 group-readable, and each served repository is made group-shared
709 (group write, setgid directories) so a controller can write
710 refs, objects, and git's worktree metadata. Nothing else on the
711 host belongs to that group, and the bus's store directory (mode
712 0700) stays out of reach.
713
714 The key and signers files are the consumer's to provision; both
715 must be readable by this user.
716 '';
717 };
718
719 signingKeyFile = lib.mkOption {
720 type = lib.types.nullOr lib.types.path;
721 default = null;
722 example = "/run/agenix/valley-integrator-key";
723 description = ''
724 ed25519 private key the controllers sign their transfer
725 statements with. A runtime path the consumer provisions (e.g.
726 agenix), never a store path — the store is world-readable.
727 '';
728 };
729
730 knownSignersFile = lib.mkOption {
731 type = lib.types.nullOr lib.types.path;
732 default = null;
733 example = "/var/lib/valley-instance/known_signers";
734 description = ''
735 File of verifier keys whose attestations count, one per line, in
736 `attest key` format. This is the identity registry's interim
737 compilation (dcr-b87f6e8), supplied directly for a host that does
738 not compile one: turning on
739 {option}`services.valley.identity.enable` renders the same file
740 from the registry, and then this option must be left unset.
741 Evidence signed by nobody in it does not transfer, which a
742 controller reports per check rather than treating as a forgery.
743 '';
744 };
745
746 signingName = lib.mkOption {
747 type = lib.types.nullOr lib.types.str;
748 default = null;
749 example = "integrator";
750 description = ''
751 The name a controller's transfer statements are signed under.
752 Unset leaves the binary's own default, which is this host's
753 attestations name — the machine signing as itself.
754
755 Set it to the name the identity registry publishes the
756 integrator's key under. The note format's key hash binds the name
757 to the key (dcr-de9d996), so a controller signing under one name
758 while the registry publishes it under another produces notes no
759 verifier can find a key for.
760 '';
761 };
762
763 instanceProject = lib.mkOption {
764 type = lib.types.nullOr lib.types.str;
765 default = null;
766 example = "qinling";
767 description = ''
768 The project whose served repository carries the group's floor —
769 the instance policy layer every controller on this host composes
770 against. A controller reads it from `policy/instance/` in that
771 bare repository's integrated tip, and nothing is materialized on
772 disk in between. It is also where the identity registry is read
773 from, for the same reason and at the same altitude: both are the
774 instance's, so a host serving that repository already holds the
775 authoritative copy.
776
777 The floor is the instance repository's, read at the tip that has
778 been integrated (dcr-f41f718); the instance repository is the
779 group's own (dcr-b87f6e8). A host serving it is therefore already
780 holding the authoritative copy.
781
782 What follows is a property of that design, and worth knowing
783 before editing a floor. A change to it takes effect at the first
784 pass after it lands on that ref, and never before. An edit in a
785 branch, in a worktree, or in an integration request that has not
786 been integrated governs nothing. There is no refresh to trigger
787 and no staleness to wait out: landing is the whole of publishing
788 a floor.
789
790 Every controller on the host reads the same repository, the
791 controller serving that repository included. Both layers are
792 resolved from the controller's own side — this one, and the
793 project's `policy/project/` at the target tip — so a change can
794 never supply the policy that gates it (bd-eaefe82).
795
796 Those two directories are the convention, and the module states
797 neither: a controller takes each layer from the place the
798 integrator defaults to, so a host declaration that says nothing
799 about policy gets the layout the worked example lays out
800 (dcr-f41f718).
801 '';
802 };
803
804 instancePolicy = lib.mkOption {
805 type = lib.types.nullOr lib.types.path;
806 default = null;
807 example = "/var/lib/valley-instance/policy/instance";
808 description = ''
809 Directory of `*.cue` files holding the instance policy layer, for
810 a host that serves no instance repository. It holds what
811 `policy/instance/` in the instance repository holds. Set this or
812 {option}`services.valley.integrator.instanceProject`, never both.
813
814 Keeping such a directory in step with the instance repository is
815 the consumer's to arrange, which is the reason to prefer the
816 project option wherever the host serves the repository.
817 '';
818 };
819
820 interval = lib.mkOption {
821 type = lib.types.str;
822 default = "15s";
823 example = "1m";
824 description = ''
825 How long a controller waits between passes. The integrator polls
826 deliberately: integration requests are durable in git, and the
827 controller level-triggers over those refs, so a lost event costs
828 one interval and nothing more.
829 '';
830 };
831 };
832
833 # The identity registry compiler (dcr-b87f6e8): the step between the
834 # instance's declared registry and the two gates that read what it
835 # compiles to. Machine options only — whether this host compiles, and
836 # from where. Who the principals are, what they hold and when their
837 # entries end is the registry's, and the registry is a document in the
838 # instance repository, never an option here.
839 identity = {
840 enable = lib.mkEnableOption ''
841 compiling the identity registry into what the gates check: the
842 verifier keys a controller accepts evidence from, and the git
843 user's authorized keys, both rendered from the instance
844 repository's integrated tip'';
845
846 ref = lib.mkOption {
847 type = lib.types.str;
848 default = "refs/heads/main";
849 description = ''
850 The ref of the instance repository whose tip carries the
851 registry. A registry edit takes effect at the first compilation
852 after it lands on this ref, and never before: an edit in a
853 branch, in a worktree, or in an integration request that has not
854 been integrated governs nothing.
855 '';
856 };
857
858 directory = lib.mkOption {
859 type = lib.types.str;
860 default = "identity";
861 description = ''
862 The registry's directory in that tip. It is a CUE package: the
863 directory is the enumeration, and every `*.cue` document
864 directly in it unifies into one registry.
865 '';
866 };
867
868 interval = lib.mkOption {
869 type = lib.types.str;
870 default = "5m";
871 example = "1m";
872 description = ''
873 How long between compilations. The compiler is level-triggered
874 and idempotent — it renders the current tip and replaces an
875 artifact only when its bytes changed — so a timer is the whole
876 of the trigger, and a landed registry change takes effect within
877 one interval.
878 '';
879 };
880 };
881
882 # Machine integration for the declared backup policy. The declaration
883 # states WHAT must hold (offsite backup, cadence, retention); these
884 # options supply HOW on this machine — where the repository is and how
885 # to authenticate. All are paths to files the consumer provisions
886 # (e.g. agenix), required when the declaration enables backup. Point
887 # them at runtime paths, never at files in the Nix store.
888 backup = {
889 repositoryFile = lib.mkOption {
890 type = lib.types.nullOr lib.types.path;
891 default = null;
892 example = "/run/agenix/valley-restic-repo";
893 description = ''
894 File containing the restic repository URL, for the sftp target
895 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
896 '';
897 };
898
899 passwordFile = lib.mkOption {
900 type = lib.types.nullOr lib.types.path;
901 default = null;
902 example = "/run/agenix/valley-restic-password";
903 description = ''
904 File containing the restic repository encryption password.
905 Losing it loses the backups — keep a copy somewhere that
906 survives this host.
907 '';
908 };
909
910 sshKeyFile = lib.mkOption {
911 type = lib.types.nullOr lib.types.path;
912 default = null;
913 example = "/run/agenix/valley-git-ssh-key";
914 description = ''
915 SSH private key that authenticates to the sftp target. The
916 backup service runs as root, so any identity the target
917 authorizes works — reusing the mirror key is fine.
918 '';
919 };
920
921 knownHostsFile = lib.mkOption {
922 type = lib.types.nullOr lib.types.path;
923 default = null;
924 example = "/var/lib/valley-backup/known_hosts";
925 description = ''
926 known_hosts file pinning the sftp target's host key. Pin from
927 the provider's published fingerprints, not a blind ssh-keyscan.
928 '';
929 };
930 };
931 };
932
933 config = lib.mkIf cfg.enable {
934 assertions = [
935 {
936 assertion = cfg.authorizedKeys != [ ];
937 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
938 }
939 ]
940 ++ lib.optionals backupEnabled (
941 lib.mapAttrsToList (name: what: {
942 assertion = cfg.backup.${name} != null;
943 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).";
944 }) backupSecretOptions
945 )
946 ++ lib.optionals cfg.integrator.enable (
947 lib.mapAttrsToList (name: what: {
948 assertion = cfg.integrator.${name} != null;
949 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
950 }) integratorPathOptions
951 ++ [
952 {
953 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
954 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.";
955 }
956 {
957 assertion =
958 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
959 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.";
960 }
961 {
962 assertion = cfg.integrator.user != cfg.user;
963 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
964 }
965 {
966 assertion = integratedProjects != { };
967 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.";
968 }
969 ]
970 )
971 ++ lib.optionals cfg.identity.enable [
972 {
973 assertion = cfg.integrator.instanceProject != null;
974 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.";
975 }
976 {
977 assertion = cfg.integrator.knownSignersFile == null;
978 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.";
979 }
980 ];
981
982 users.groups.${cfg.group} = { };
983
984 users.users.${cfg.user} = {
985 isSystemUser = true;
986 group = cfg.group;
987 home = cfg.dataDir;
988 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
989 # interactive logins are rejected (no ~/git-shell-commands).
990 shell = "${pkgs.git}/bin/git-shell";
991 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
992 };
993
994 # The integrator's own account. No shell, no keys, no home of its own
995 # beyond the state directory its units get; the git group is the only
996 # thing it holds.
997 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
998 isSystemUser = true;
999 group = cfg.group;
1000 home = "/var/lib/valley-integrator";
1001 description = "The valley integrator";
1002 };
1003
1004 services.openssh.enable = lib.mkDefault true;
1005
1006 # Honour the principal tag on a key's entry, and nothing else: the
1007 # pattern-list form admits that one variable name. Rendered only once a
1008 # key names a principal — declared here, or compiled from the registry
1009 # — so a host with none keeps the sshd config it had.
1010 services.openssh.settings = lib.optionalAttrs (taggedKeys != [ ] || cfg.identity.enable) {
1011 PermitUserEnvironment = principalEnv;
1012 };
1013
1014 # The compiled authorized keys, added to the list sshd reads rather than
1015 # replacing it. The declared keys above stay authorized: a compiled file
1016 # can only ever add, so an empty or missing one — a first boot before
1017 # the first compilation, a registry that lost an entry, a bug here —
1018 # cannot take the git user's access away. Which is the point: the
1019 # assertion above keeps at least one key declared, and that key is the
1020 # way back in.
1021 services.openssh.authorizedKeysFiles = lib.mkIf cfg.identity.enable [
1022 identityAuthorizedKeysPattern
1023 ];
1024
1025 # Belt-and-braces hardening for the git user. The trailing `Match All`
1026 # closes the block so it can't scope directives appended to sshd_config
1027 # after this snippet.
1028 services.openssh.extraConfig = ''
1029 Match User ${cfg.user}
1030 AllowTcpForwarding no
1031 AllowAgentForwarding no
1032 X11Forwarding no
1033 PermitTunnel no
1034 Match All
1035 '';
1036
1037 # git-shell spawns git-receive-pack/git-upload-pack from PATH
1038 environment.systemPackages = [ pkgs.git ];
1039
1040 systemd.tmpfiles.rules = [
1041 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
1042 ]
1043 ++ lib.optionals cfg.bus.enable [
1044 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
1045 ];
1046
1047 # The bus itself. It runs as the git user — the store directory lives in
1048 # that user's data — but the sandbox is what confines it: the unit can
1049 # write nowhere except its store directory.
1050 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
1051 description = "The valley event bus (NATS JetStream)";
1052 wantedBy = [ "multi-user.target" ];
1053 after = [
1054 "network.target"
1055 "systemd-tmpfiles-setup.service"
1056 ];
1057 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
1058 serviceConfig = {
1059 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
1060 Restart = "on-failure";
1061 User = cfg.user;
1062 Group = cfg.group;
1063 LimitNOFILE = 65536;
1064 NoNewPrivileges = true;
1065 ProtectSystem = "strict";
1066 ReadWritePaths = [ cfg.bus.storeDir ];
1067 ProtectHome = true;
1068 PrivateTmp = true;
1069 PrivateDevices = true;
1070 ProtectClock = true;
1071 ProtectHostname = true;
1072 ProtectKernelLogs = true;
1073 ProtectKernelModules = true;
1074 ProtectKernelTunables = true;
1075 ProtectControlGroups = true;
1076 ProtectProc = "invisible";
1077 RestrictAddressFamilies = [
1078 "AF_INET"
1079 "AF_INET6"
1080 "AF_UNIX"
1081 ];
1082 RestrictNamespaces = true;
1083 RestrictRealtime = true;
1084 RestrictSUIDSGID = true;
1085 LockPersonality = true;
1086 CapabilityBoundingSet = "";
1087 SystemCallArchitectures = "native";
1088 SystemCallFilter = [ "@system-service" ];
1089 UMask = "0077";
1090 };
1091 };
1092
1093 # The stream is config, not state: (re)created idempotently on every
1094 # boot, capturing everything under valley.>. An existing stream — and
1095 # the events in it — is left untouched.
1096 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
1097 description = "Create the valley event stream";
1098 wantedBy = [ "multi-user.target" ];
1099 requires = [ "valley-bus.service" ];
1100 after = [ "valley-bus.service" ];
1101 serviceConfig = {
1102 Type = "oneshot";
1103 User = cfg.user;
1104 Group = cfg.group;
1105 };
1106 path = [ pkgs.natscli ];
1107 script = ''
1108 # The server needs a moment to accept connections after startup.
1109 for _ in $(seq 1 50); do
1110 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
1111 sleep 0.2
1112 done
1113 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
1114 nats --server ${busUrl} stream add valley \
1115 --subjects 'valley.>' --storage file --defaults
1116 fi
1117 '';
1118 };
1119
1120 # Create missing bare repos and (re)wire the managed hooks on every
1121 # activation where the declaration changed.
1122 systemd.services.valley-init = {
1123 description = "Initialize the valley host's bare git repositories";
1124 wantedBy = [ "multi-user.target" ];
1125 after = [ "systemd-tmpfiles-setup.service" ];
1126 unitConfig.RequiresMountsFor = cfg.dataDir;
1127 serviceConfig = {
1128 Type = "oneshot";
1129 User = cfg.user;
1130 Group = cfg.group;
1131 };
1132 path = [ pkgs.git ];
1133 script = ''
1134 repos=( ${lib.escapeShellArgs repoNames} )
1135 for name in "''${repos[@]}"; do
1136 repo="${cfg.dataDir}/$name.git"
1137 # Check HEAD rather than the directory itself so a pre-existing
1138 # empty directory still gets initialized.
1139 if [ ! -e "$repo/HEAD" ]; then
1140 git init --bare --initial-branch=main "$repo"
1141 fi
1142
1143 # Hook scaffolding: post-receive dispatches to post-receive.d/.
1144 # Only manage the hook if it is absent or already ours (a store
1145 # symlink) — a hand-written hook is left alone.
1146 mkdir -p "$repo/hooks/post-receive.d"
1147 hook="$repo/hooks/post-receive"
1148 if [ -L "$hook" ]; then
1149 case "$(readlink "$hook")" in
1150 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
1151 esac
1152 elif [ ! -e "$hook" ]; then
1153 ln -s ${postReceiveDispatch} "$hook"
1154 fi
1155 done
1156
1157 # Per-project push-mirror hooks.
1158 ${mirrorHookCommands}
1159
1160 # The one structural invariant, on every project declared protected.
1161 ${protectHookCommands}
1162
1163 # The ref-updated publisher hook, on every repo when the bus is on.
1164 ${busHookCommands}
1165
1166 # Group-shared repositories, on what the integrator serves.
1167 ${lib.optionalString cfg.integrator.enable integratorShareCommands}
1168 '';
1169 };
1170
1171 # The registry compiler, on a timer. It renders the instance
1172 # repository's integrated tip into the two artifacts the gates read;
1173 # nothing else on the host writes them.
1174 #
1175 # It runs as the git user rather than under an identity of its own,
1176 # which is the one place this module steps back from the service split
1177 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
1178 # anyone but root or the account it authorizes, so the choice is the git
1179 # user or root, and the git user is the smaller grant.
1180 #
1181 # Level-triggered, like the rest: a compilation reads the current tip
1182 # and replaces an artifact only when its bytes changed, so re-running is
1183 # free and the timer needs no coordination with anything.
1184 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
1185 description = "Compile the valley identity registry into what the gates check";
1186 wantedBy = [ "multi-user.target" ];
1187 after = [ "valley-init.service" ];
1188 requires = [ "valley-init.service" ];
1189 unitConfig.RequiresMountsFor = cfg.dataDir;
1190 serviceConfig = {
1191 Type = "oneshot";
1192 ExecStart = identityCommand;
1193 User = cfg.user;
1194 Group = cfg.group;
1195 StateDirectory = identityStateName;
1196 # sshd walks every directory above an authorized-keys file and
1197 # refuses a group- or world-writable one, so the state directory is
1198 # 0755 deliberately rather than the 0700 a service's state usually
1199 # takes. Nothing secret lives in it: a registry is public keys.
1200 StateDirectoryMode = "0755";
1201 NoNewPrivileges = true;
1202 ProtectSystem = "strict";
1203 ReadWritePaths = [ identityStateDir ];
1204 ProtectHome = true;
1205 PrivateTmp = true;
1206 PrivateDevices = true;
1207 ProtectClock = true;
1208 ProtectHostname = true;
1209 ProtectKernelLogs = true;
1210 ProtectKernelModules = true;
1211 ProtectKernelTunables = true;
1212 ProtectControlGroups = true;
1213 ProtectProc = "invisible";
1214 RestrictAddressFamilies = [ "AF_UNIX" ];
1215 RestrictNamespaces = true;
1216 RestrictRealtime = true;
1217 RestrictSUIDSGID = true;
1218 LockPersonality = true;
1219 CapabilityBoundingSet = "";
1220 SystemCallArchitectures = "native";
1221 SystemCallFilter = [ "@system-service" ];
1222 UMask = "0022";
1223 };
1224 };
1225
1226 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
1227 description = "Re-compile the valley identity registry";
1228 wantedBy = [ "timers.target" ];
1229 timerConfig = {
1230 OnBootSec = "1m";
1231 OnUnitActiveSec = cfg.identity.interval;
1232 };
1233 };
1234
1235 # One controller per served project, as instances of a single template:
1236 # the units differ only in the repository they serve, which is the
1237 # instance name. `watch` rather than a timer firing `reconcile`: the
1238 # binary owns its poll loop and its interval, and a timer would be a
1239 # second cadence over the same level-triggered refs.
1240 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
1241 description = "The valley integrator for %i";
1242 after = [
1243 "network.target"
1244 "valley-init.service"
1245 ]
1246 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
1247 ++ lib.optional cfg.identity.enable "valley-identity.service";
1248 requires = [ "valley-init.service" ];
1249 # Wants, not requires: a controller reads the compiled signers file,
1250 # so it starts after the first compilation — but a compilation that
1251 # failed must not keep the controllers down. One that finds no file
1252 # says so and restarts, which is the same loop and a louder one.
1253 wants = lib.optional cfg.identity.enable "valley-identity.service";
1254 unitConfig.RequiresMountsFor = cfg.dataDir;
1255 # nix is not pinned, for the reason the integrator package does not
1256 # pin it: a check's input closure must be recomputed by the nix this
1257 # machine actually runs. Everything else a controller drives is
1258 # pinned inside the wrapper.
1259 path = [ config.nix.package ];
1260 # The repositories belong to the git user and the controller does
1261 # not, so git refuses to touch them as dubiously owned. The exception
1262 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
1263 # command-scope config, which is protected config, so safe.directory
1264 # is honoured from it — a repository-scoped setting would be ignored,
1265 # deliberately. And every git the controller drives is a child of
1266 # this unit, whether run by the integrator itself or by attest or the
1267 # deriver, so one environment covers all of them.
1268 #
1269 # One repository per instance: never a global gitconfig, never a
1270 # wildcard. Every other repository on the host stays refused. Linked
1271 # worktrees need no entry of their own — the controller creates them,
1272 # so it owns them, and git checks the worktree and its gitdir rather
1273 # than the repository they point at.
1274 #
1275 # TMPDIR is the same kind of wiring, for the same reason. A verdict
1276 # wants a checkout of the tip on disk, and the integrator asks for one
1277 # the ordinary way — a temporary directory, then a linked worktree in
1278 # it. The sandbox below leaves no writable temporary directory, so
1279 # every tick died on `could not create leading directories`. The
1280 # scratch belongs under the state directory the unit already has:
1281 # writable by construction, owned by this service, and gone when the
1282 # service's state is. Setting it in the environment rather than
1283 # teaching the binary a flag covers every process in the unit at once
1284 # — the integrator, attest, the deriver, and the git each of them runs
1285 # all read TMPDIR, and all of them want scratch in the same place.
1286 #
1287 # A second exception, for the instance repository. Every controller
1288 # reads the group's floor from that repository's tip, and it need not
1289 # be the project the controller serves — the controller for one
1290 # project reads the floor out of another project's repository, which
1291 # it likewise does not own. Without the exception git refuses it as
1292 # dubiously owned and every pass fails, exactly as it did for the
1293 # served repository. Two entries, both named; still never a wildcard.
1294 #
1295 # Reading needs no sandbox entry beside it. ProtectSystem=strict
1296 # leaves the filesystem readable and only takes write away, so the
1297 # ReadWritePaths list above stays the list of what may be written,
1298 # which is what makes it worth reading. What read does need is a
1299 # filesystem grant, and valley-init makes it: the instance repository
1300 # is group-readable whether or not it is one of the served projects.
1301 environment = {
1302 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
1303 GIT_CONFIG_KEY_0 = "safe.directory";
1304 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
1305 TMPDIR = integratorStateDir;
1306 }
1307 // lib.optionalAttrs (instanceRepo != null) {
1308 GIT_CONFIG_KEY_1 = "safe.directory";
1309 GIT_CONFIG_VALUE_1 = instanceRepo;
1310 };
1311 serviceConfig = {
1312 ExecStart = integratorCommand;
1313 Restart = "on-failure";
1314 RestartSec = "10s";
1315 User = cfg.integrator.user;
1316 Group = cfg.group;
1317 StateDirectory = integratorStateName;
1318 StateDirectoryMode = "0700";
1319 WorkingDirectory = integratorStateDir;
1320 NoNewPrivileges = true;
1321 ProtectSystem = "strict";
1322 # Everything the controller may write, named where a reader of the
1323 # unit meets it. Under ProtectSystem=strict the rest of the
1324 # filesystem is read-only, so this list is the whole of what the
1325 # service can touch, and it is worth being able to read it as such
1326 # rather than as the exceptions plus whatever else is implied.
1327 #
1328 # Its own directory: its state, and the scratch root TMPDIR names.
1329 # A declaration says it here rather than relying on the state
1330 # directory being read-write by virtue of being declared, which is
1331 # not something this unit found to be true.
1332 #
1333 # The one repository it serves, and the nix daemon's socket —
1334 # recomputing a closure means asking the daemon, and connecting to
1335 # a unix socket needs write access to it.
1336 ReadWritePaths = [
1337 integratorStateDir
1338 "${cfg.dataDir}/%i.git"
1339 "/nix/var/nix/daemon-socket"
1340 ];
1341 ProtectHome = true;
1342 PrivateTmp = true;
1343 PrivateDevices = true;
1344 ProtectClock = true;
1345 ProtectHostname = true;
1346 ProtectKernelLogs = true;
1347 ProtectKernelModules = true;
1348 ProtectKernelTunables = true;
1349 ProtectControlGroups = true;
1350 ProtectProc = "invisible";
1351 RestrictAddressFamilies = [
1352 "AF_INET"
1353 "AF_INET6"
1354 "AF_UNIX"
1355 ];
1356 RestrictNamespaces = true;
1357 RestrictRealtime = true;
1358 RestrictSUIDSGID = true;
1359 LockPersonality = true;
1360 CapabilityBoundingSet = "";
1361 SystemCallArchitectures = "native";
1362 SystemCallFilter = [ "@system-service" ];
1363 # Group write, not the bus unit's 0077: the git user owns these
1364 # repositories and has to stay able to write what a controller
1365 # leaves in them.
1366 UMask = "0002";
1367 };
1368 };
1369
1370 # wantedBy on a template unit enables nothing, so the instances the
1371 # declaration asks for are pulled in by name.
1372 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
1373 description = "The valley integrator's controllers";
1374 wantedBy = [ "multi-user.target" ];
1375 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
1376 };
1377
1378 # Offsite backup, rendered only when the declaration asks for it. The
1379 # declaration states the policy — that backup exists, its cadence and
1380 # retention; the services.valley.backup.* options supply the machine
1381 # half. Declaration absent or disabled ⇒ no restic config at all.
1382 services.restic.backups = lib.mkIf backupEnabled {
1383 valley = {
1384 initialize = true;
1385 repositoryFile = cfg.backup.repositoryFile;
1386 passwordFile = cfg.backup.passwordFile;
1387 paths = [ cfg.dataDir ];
1388 # The schema admits only the restic-sftp target today; a second
1389 # target would grow a dispatch here. The service runs as root:
1390 # authenticate with the supplied identity and only the pinned
1391 # host key. No prompt can be answered inside a systemd unit, so
1392 # BatchMode + strict host key checking turn a would-be hang into
1393 # an immediate error.
1394 extraOptions = [
1395 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
1396 ];
1397 timerConfig = backupTimer.${backupPolicy.cadence};
1398 pruneOpts = [
1399 "--keep-daily ${toString backupPolicy.retention.daily}"
1400 "--keep-weekly ${toString backupPolicy.retention.weekly}"
1401 "--keep-monthly ${toString backupPolicy.retention.monthly}"
1402 ];
1403 };
1404 };
1405 };
1406}