gunk-dev/the-valley

valley-host.nix

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