gunk-dev/the-valley

valley-host.nix

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