gunk-dev/the-valley

valley-host.nix

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