gunk-dev/the-valley

valley-host.nix

sourcec180c63dc908main's published tip history
22.9 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).
19#
20# Mirror credentials are the consumer's concern: the module assumes the git
21# user's SSH identity and known_hosts are provisioned by the host (e.g.
22# cosmo, via its secrets). Nothing here plumbs secrets: the backup options
23# below take *paths* to consumer-provisioned secret files; the contents
24# never pass through this module or the store.
25{
26 config,
27 pkgs,
28 lib,
29 ...
30}:
31
32let
33 cfg = config.services.valley;
34
35 schema = ../schema/valley.cue;
36
37 # Build-time vet + export of the host declaration. the vet checks the
38 # declaration against the schema (whose top level applies #Host), so unknown
39 # fields and unsafe project names fail the build, with cue's error.
40 configJSON =
41 pkgs.runCommand "valley-config.json"
42 {
43 nativeBuildInputs = [ pkgs.cue ];
44 }
45 ''
46 cue vet -c ${schema} ${cfg.config}
47 cue export ${schema} ${cfg.config} > $out
48 '';
49
50 host = lib.importJSON configJSON;
51
52 # Projects whose git store is enabled get a bare repository.
53 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
54 repoNames = lib.attrNames gitProjects;
55
56 # The declared durability policy, if any. `backup` is optional in the
57 # schema: a declaration without it (or with enable = false) renders zero
58 # backup machinery, exactly as before the field existed.
59 backupPolicy = host.backup or null;
60 backupEnabled = backupPolicy != null && backupPolicy.enable;
61
62 # The declared cadence names policy; its wall-clock rendering is this
63 # installer's choice. A lookup rather than a literal, so a cadence this
64 # module does not know fails eval loudly instead of mis-scheduling.
65 backupTimer = {
66 # Late night with a spread; Persistent runs a missed window at boot.
67 nightly = {
68 OnCalendar = "03:30";
69 RandomizedDelaySec = "30m";
70 Persistent = true;
71 };
72 };
73
74 # The secret-path options the consumer must supply once the declaration
75 # enables backup, with what each names — for the assertion message.
76 backupSecretOptions = {
77 repositoryFile = "the restic repository URL";
78 passwordFile = "the repository encryption password";
79 sshKeyFile = "the SSH identity for the sftp target";
80 knownHostsFile = "the pinned host key of the sftp target";
81 };
82
83 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
84 # this script, which chains every executable dropped into the repo's
85 # hooks/post-receive.d/ directory.
86 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
87 # Managed by services.valley — do not edit.
88 # Drop executable hooks into post-receive.d/ next to this symlink.
89 set -eu
90 hook_dir="$(dirname "$0")/post-receive.d"
91 [ -d "$hook_dir" ] || exit 0
92 updates="$(cat)"
93 [ -n "$updates" ] || exit 0
94 for hook in "$hook_dir"/*; do
95 [ -x "$hook" ] || continue
96 printf '%s\n' "$updates" | "$hook" "$@"
97 done
98 '';
99
100 # Best-effort push replication. Publication mirror: main and tags only.
101 # Topic branches are review-queue state, not published — the mirror exists
102 # so consumers can fetch what has been integrated; durability is restic's
103 # job, not the mirror's. Pushes run detached (setsid) so a dead mirror can
104 # only ever cost a log line — never block or fail the primary push.
105 # --prune propagates tag deletions (glob refspec); it is a no-op for heads
106 # now that the heads refspec names one ref, so a separate best-effort sweep
107 # deletes every mirror head but main — which also strips anything that
108 # appears there by other means. The sweep reads only refs/heads (ls-remote
109 # --heads), never refs/pull/*, and is logged apart from the replication
110 # push so it cannot change that push's reported outcome. --mirror is
111 # rejected outright: it also tries to delete remote-only namespaces, and on
112 # GitHub the read-only refs/pull/* makes that fail every push, masking real
113 # replication failures.
114 mirrorPusher =
115 name: mirrors:
116 pkgs.writeShellScript "valley-mirror-push-${name}" ''
117 for url in ${lib.escapeShellArgs mirrors}; do
118 if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then
119 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true
120 else
121 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true
122 fi
123
124 # Unpublish anything but main. Refnames cannot contain whitespace, so
125 # accumulating them space-separated and splitting on expansion is safe.
126 stale=""
127 while read -r _ ref; do
128 [ "$ref" = refs/heads/main ] || stale="$stale $ref"
129 done < <(${pkgs.git}/bin/git ls-remote --heads "$url" 2>/dev/null)
130 if [ -n "$stale" ]; then
131 if ${pkgs.git}/bin/git push "$url" --delete $stale >/dev/null 2>&1; then
132 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublished$stale from $url" || true
133 else
134 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublish from $url failed (ignored)" || true
135 fi
136 fi
137 done
138 '';
139
140 mirrorHook =
141 name: mirrors:
142 pkgs.writeShellScript "valley-mirrors-${name}" ''
143 # Managed by services.valley — best-effort push mirrors for ${name}.
144 cat >/dev/null # updated refs unused: the push replicates main and tags
145 ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1
146 exit 0
147 '';
148
149 # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which
150 # the ref-updated hook below projects this host's git activity. The bus is
151 # never load-bearing for durable state — per-repo events are durable in
152 # git itself, and `valley replay` rebuilds the stream from a repo's refs —
153 # so losing its storage costs one replay, nothing more.
154 busUrl = "nats://${cfg.bus.listen}";
155
156 busServerConfig = pkgs.writeText "valley-bus.conf" ''
157 listen: ${cfg.bus.listen}
158 jetstream {
159 store_dir: "${cfg.bus.storeDir}"
160 # The store directory defaults to living on the repo volume; the cap
161 # keeps a runaway or malicious local publisher from filling it.
162 max_file_store: 2GiB
163 }
164 '';
165
166 # One ref-updated event per updated ref, read from the post-receive stdin
167 # this script inherits. Every payload field is derivable from git alone —
168 # no wall-clock time, no hostname — so replaying a repo's refs reproduces
169 # the same events (the roadmap's determinism criterion). `valley replay`
170 # builds the identical payload; change one only with the other.
171 busPublisher = pkgs.writeShellScript "valley-bus-publish" ''
172 repo="$(basename "$PWD" .git)"
173 while read -r old new ref; do
174 [ -n "$ref" ] || continue
175 # " is the only JSON-significant character a refname can contain
176 # (git forbids \ and control characters); names and ids are safe.
177 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
178 "$repo" "''${ref//\"/\\\"}" "$old" "$new")"
179 if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \
180 "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then
181 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true
182 else
183 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true
184 fi
185 done
186 '';
187
188 # The post-receive.d hook, with the mirror hook's failure semantics: the
189 # publisher runs detached (setsid, inheriting the updates on stdin), so a
190 # bus problem can only ever cost a log line — never block or fail the
191 # push. git is the source of truth; the bus is the replaceable component.
192 busEventHook = pkgs.writeShellScript "valley-bus-events" ''
193 # Managed by services.valley — project ref updates onto the event bus.
194 ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1
195 exit 0
196 '';
197
198 # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks:
199 # only ever installs, updates, or removes a store symlink — a hand-written
200 # hook of the same name is left alone.
201 busHookCommands = lib.concatMapStrings (
202 name:
203 let
204 bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus";
205 in
206 if cfg.bus.enable then
207 ''
208 bhook=${bhook}
209 if [ -L "$bhook" ]; then
210 case "$(readlink "$bhook")" in
211 /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;;
212 esac
213 elif [ ! -e "$bhook" ]; then
214 ln -s ${busEventHook} "$bhook"
215 fi
216 ''
217 else
218 ''
219 bhook=${bhook}
220 if [ -L "$bhook" ]; then
221 case "$(readlink "$bhook")" in
222 /nix/store/*) rm -f "$bhook" ;;
223 esac
224 fi
225 ''
226 ) repoNames;
227
228 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
229 # a store symlink — a hand-written hook of the same name is left alone.
230 mirrorHookCommands = lib.concatStrings (
231 lib.mapAttrsToList (
232 name: p:
233 let
234 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
235 in
236 if p.mirrors != [ ] then
237 ''
238 mhook=${mhook}
239 if [ -L "$mhook" ]; then
240 case "$(readlink "$mhook")" in
241 /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;;
242 esac
243 elif [ ! -e "$mhook" ]; then
244 ln -s ${mirrorHook name p.mirrors} "$mhook"
245 fi
246 ''
247 else
248 ''
249 mhook=${mhook}
250 if [ -L "$mhook" ]; then
251 case "$(readlink "$mhook")" in
252 /nix/store/*) rm -f "$mhook" ;;
253 esac
254 fi
255 ''
256 ) gitProjects
257 );
258in
259{
260 options.services.valley = {
261 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
262
263 user = lib.mkOption {
264 type = lib.types.str;
265 default = "git";
266 description = "System user that owns the repositories and accepts SSH pushes.";
267 };
268
269 group = lib.mkOption {
270 type = lib.types.str;
271 default = "git";
272 description = "Primary group of the valley git user.";
273 };
274
275 dataDir = lib.mkOption {
276 type = lib.types.path;
277 default = "/srv/git";
278 example = "/mnt/git";
279 description = ''
280 Directory holding the bare repositories, one `<name>.git` per
281 project declared in {option}`services.valley.config`. Also the git
282 user's home, so clone URLs are relative to it (`git@host:name.git`).
283 Consumers typically point it at a dedicated dataset.
284 '';
285 };
286
287 authorizedKeys = lib.mkOption {
288 type = lib.types.listOf lib.types.str;
289 default = [ ];
290 description = ''
291 SSH public keys allowed to push/fetch as the git user. Access is
292 host-level by design: every key can reach every project.
293 '';
294 };
295
296 config = lib.mkOption {
297 type = lib.types.path;
298 example = lib.literalExpression "./valley.cue";
299 description = ''
300 Path to the host's CUE declaration (`package valley`) — the
301 canonical statement of what this valley host serves, validated
302 against the shipped schema at build time. This is the single domain
303 input: projects, their push mirrors, and the backup policy are
304 declared here, never as Nix options.
305 '';
306 };
307
308 # The event bus. Machine options, not domain: whether this machine runs
309 # a bus, where it listens, and where its storage lives. What gets
310 # published onto it is defined portably in ../schema/events.cue.
311 bus = {
312 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
313
314 listen = lib.mkOption {
315 type = lib.types.str;
316 default = "127.0.0.1:4222";
317 example = "100.100.1.7:4222";
318 description = ''
319 Address the bus listens on, `host:port`. Localhost by default:
320 nothing off the host can reach the bus until the consumer widens
321 this deliberately — e.g. to the host's tailnet address once a
322 remote `valley tail` wants in. Local publishers (the ref-updated
323 hook) connect to this same address, so it must be reachable from
324 the host itself.
325 '';
326 };
327
328 storeDir = lib.mkOption {
329 type = lib.types.path;
330 default = "${cfg.dataDir}/.bus";
331 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
332 description = ''
333 Directory holding the JetStream file storage. The default lives
334 under {option}`services.valley.dataDir`; it can never collide
335 with a repository because project names must start with an
336 alphanumeric. The stream is a projection of git, rebuildable
337 with `valley replay` — losing this directory costs one replay.
338 '';
339 };
340 };
341
342 # Machine integration for the declared backup policy. The declaration
343 # states WHAT must hold (offsite backup, cadence, retention); these
344 # options supply HOW on this machine — where the repository is and how
345 # to authenticate. All are paths to files the consumer provisions
346 # (e.g. agenix), required when the declaration enables backup. Point
347 # them at runtime paths, never at files in the Nix store.
348 backup = {
349 repositoryFile = lib.mkOption {
350 type = lib.types.nullOr lib.types.path;
351 default = null;
352 example = "/run/agenix/valley-restic-repo";
353 description = ''
354 File containing the restic repository URL, for the sftp target
355 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
356 '';
357 };
358
359 passwordFile = lib.mkOption {
360 type = lib.types.nullOr lib.types.path;
361 default = null;
362 example = "/run/agenix/valley-restic-password";
363 description = ''
364 File containing the restic repository encryption password.
365 Losing it loses the backups — keep a copy somewhere that
366 survives this host.
367 '';
368 };
369
370 sshKeyFile = lib.mkOption {
371 type = lib.types.nullOr lib.types.path;
372 default = null;
373 example = "/run/agenix/valley-git-ssh-key";
374 description = ''
375 SSH private key that authenticates to the sftp target. The
376 backup service runs as root, so any identity the target
377 authorizes works — reusing the mirror key is fine.
378 '';
379 };
380
381 knownHostsFile = lib.mkOption {
382 type = lib.types.nullOr lib.types.path;
383 default = null;
384 example = "/var/lib/valley-backup/known_hosts";
385 description = ''
386 known_hosts file pinning the sftp target's host key. Pin from
387 the provider's published fingerprints, not a blind ssh-keyscan.
388 '';
389 };
390 };
391 };
392
393 config = lib.mkIf cfg.enable {
394 assertions = [
395 {
396 assertion = cfg.authorizedKeys != [ ];
397 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
398 }
399 ]
400 ++ lib.optionals backupEnabled (
401 lib.mapAttrsToList (name: what: {
402 assertion = cfg.backup.${name} != null;
403 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).";
404 }) backupSecretOptions
405 );
406
407 users.groups.${cfg.group} = { };
408
409 users.users.${cfg.user} = {
410 isSystemUser = true;
411 group = cfg.group;
412 home = cfg.dataDir;
413 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
414 # interactive logins are rejected (no ~/git-shell-commands).
415 shell = "${pkgs.git}/bin/git-shell";
416 openssh.authorizedKeys.keys = cfg.authorizedKeys;
417 };
418
419 services.openssh.enable = lib.mkDefault true;
420
421 # Belt-and-braces hardening for the git user. The trailing `Match All`
422 # closes the block so it can't scope directives appended to sshd_config
423 # after this snippet.
424 services.openssh.extraConfig = ''
425 Match User ${cfg.user}
426 AllowTcpForwarding no
427 AllowAgentForwarding no
428 X11Forwarding no
429 PermitTunnel no
430 Match All
431 '';
432
433 # git-shell spawns git-receive-pack/git-upload-pack from PATH
434 environment.systemPackages = [ pkgs.git ];
435
436 systemd.tmpfiles.rules = [
437 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
438 ]
439 ++ lib.optionals cfg.bus.enable [
440 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
441 ];
442
443 # The bus itself. It runs as the git user — the store directory lives in
444 # that user's data — but the sandbox is what confines it: the unit can
445 # write nowhere except its store directory.
446 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
447 description = "The valley event bus (NATS JetStream)";
448 wantedBy = [ "multi-user.target" ];
449 after = [
450 "network.target"
451 "systemd-tmpfiles-setup.service"
452 ];
453 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
454 serviceConfig = {
455 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
456 Restart = "on-failure";
457 User = cfg.user;
458 Group = cfg.group;
459 LimitNOFILE = 65536;
460 NoNewPrivileges = true;
461 ProtectSystem = "strict";
462 ReadWritePaths = [ cfg.bus.storeDir ];
463 ProtectHome = true;
464 PrivateTmp = true;
465 PrivateDevices = true;
466 ProtectClock = true;
467 ProtectHostname = true;
468 ProtectKernelLogs = true;
469 ProtectKernelModules = true;
470 ProtectKernelTunables = true;
471 ProtectControlGroups = true;
472 ProtectProc = "invisible";
473 RestrictAddressFamilies = [
474 "AF_INET"
475 "AF_INET6"
476 "AF_UNIX"
477 ];
478 RestrictNamespaces = true;
479 RestrictRealtime = true;
480 RestrictSUIDSGID = true;
481 LockPersonality = true;
482 CapabilityBoundingSet = "";
483 SystemCallArchitectures = "native";
484 SystemCallFilter = [ "@system-service" ];
485 UMask = "0077";
486 };
487 };
488
489 # The stream is config, not state: (re)created idempotently on every
490 # boot, capturing everything under valley.>. An existing stream — and
491 # the events in it — is left untouched.
492 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
493 description = "Create the valley event stream";
494 wantedBy = [ "multi-user.target" ];
495 requires = [ "valley-bus.service" ];
496 after = [ "valley-bus.service" ];
497 serviceConfig = {
498 Type = "oneshot";
499 User = cfg.user;
500 Group = cfg.group;
501 };
502 path = [ pkgs.natscli ];
503 script = ''
504 # The server needs a moment to accept connections after startup.
505 for _ in $(seq 1 50); do
506 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
507 sleep 0.2
508 done
509 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
510 nats --server ${busUrl} stream add valley \
511 --subjects 'valley.>' --storage file --defaults
512 fi
513 '';
514 };
515
516 # Create missing bare repos and (re)wire the managed hooks on every
517 # activation where the declaration changed.
518 systemd.services.valley-init = {
519 description = "Initialize the valley host's bare git repositories";
520 wantedBy = [ "multi-user.target" ];
521 after = [ "systemd-tmpfiles-setup.service" ];
522 unitConfig.RequiresMountsFor = cfg.dataDir;
523 serviceConfig = {
524 Type = "oneshot";
525 User = cfg.user;
526 Group = cfg.group;
527 };
528 path = [ pkgs.git ];
529 script = ''
530 repos=( ${lib.escapeShellArgs repoNames} )
531 for name in "''${repos[@]}"; do
532 repo="${cfg.dataDir}/$name.git"
533 # Check HEAD rather than the directory itself so a pre-existing
534 # empty directory still gets initialized.
535 if [ ! -e "$repo/HEAD" ]; then
536 git init --bare --initial-branch=main "$repo"
537 fi
538
539 # Hook scaffolding: post-receive dispatches to post-receive.d/.
540 # Only manage the hook if it is absent or already ours (a store
541 # symlink) — a hand-written hook is left alone.
542 mkdir -p "$repo/hooks/post-receive.d"
543 hook="$repo/hooks/post-receive"
544 if [ -L "$hook" ]; then
545 case "$(readlink "$hook")" in
546 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
547 esac
548 elif [ ! -e "$hook" ]; then
549 ln -s ${postReceiveDispatch} "$hook"
550 fi
551 done
552
553 # Per-project push-mirror hooks.
554 ${mirrorHookCommands}
555
556 # The ref-updated publisher hook, on every repo when the bus is on.
557 ${busHookCommands}
558 '';
559 };
560
561 # Offsite backup, rendered only when the declaration asks for it. The
562 # declaration states the policy — that backup exists, its cadence and
563 # retention; the services.valley.backup.* options supply the machine
564 # half. Declaration absent or disabled ⇒ no restic config at all.
565 services.restic.backups = lib.mkIf backupEnabled {
566 valley = {
567 initialize = true;
568 repositoryFile = cfg.backup.repositoryFile;
569 passwordFile = cfg.backup.passwordFile;
570 paths = [ cfg.dataDir ];
571 # The schema admits only the restic-sftp target today; a second
572 # target would grow a dispatch here. The service runs as root:
573 # authenticate with the supplied identity and only the pinned
574 # host key. No prompt can be answered inside a systemd unit, so
575 # BatchMode + strict host key checking turn a would-be hang into
576 # an immediate error.
577 extraOptions = [
578 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
579 ];
580 timerConfig = backupTimer.${backupPolicy.cadence};
581 pruneOpts = [
582 "--keep-daily ${toString backupPolicy.retention.daily}"
583 "--keep-weekly ${toString backupPolicy.retention.weekly}"
584 "--keep-monthly ${toString backupPolicy.retention.monthly}"
585 ];
586 };
587 };
588 };
589}