gunk-dev/the-valley

valley-host.nix

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