gunk-dev/the-valley

valley-host.nix

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