gunk-dev/the-valley

valley-host.nix

source354ed0a386a8main's published tip history
30.3 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 config,
32 pkgs,
33 lib,
34 ...
35}:
36
37let
38 cfg = config.services.valley;
39
40 schema = ../schema/valley.cue;
41
42 # Build-time vet + export of the host declaration. the vet checks the
43 # declaration against the schema (whose top level applies #Host), so unknown
44 # fields and unsafe project names fail the build, with cue's error.
45 configJSON =
46 pkgs.runCommand "valley-config.json"
47 {
48 nativeBuildInputs = [ pkgs.cue ];
49 }
50 ''
51 cue vet -c ${schema} ${cfg.config}
52 cue export ${schema} ${cfg.config} > $out
53 '';
54
55 host = lib.importJSON configJSON;
56
57 # Projects whose git store is enabled get a bare repository.
58 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
59 repoNames = lib.attrNames gitProjects;
60
61 # The declared durability policy, if any. `backup` is optional in the
62 # schema: a declaration without it (or with enable = false) renders zero
63 # backup machinery, exactly as before the field existed.
64 backupPolicy = host.backup or null;
65 backupEnabled = backupPolicy != null && backupPolicy.enable;
66
67 # The declared cadence names policy; its wall-clock rendering is this
68 # installer's choice. A lookup rather than a literal, so a cadence this
69 # module does not know fails eval loudly instead of mis-scheduling.
70 backupTimer = {
71 # Late night with a spread; Persistent runs a missed window at boot.
72 nightly = {
73 OnCalendar = "03:30";
74 RandomizedDelaySec = "30m";
75 Persistent = true;
76 };
77 };
78
79 # The secret-path options the consumer must supply once the declaration
80 # enables backup, with what each names — for the assertion message.
81 backupSecretOptions = {
82 repositoryFile = "the restic repository URL";
83 passwordFile = "the repository encryption password";
84 sshKeyFile = "the SSH identity for the sftp target";
85 knownHostsFile = "the pinned host key of the sftp target";
86 };
87
88 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
89 # this script, which chains every executable dropped into the repo's
90 # hooks/post-receive.d/ directory.
91 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
92 # Managed by services.valley — do not edit.
93 # Drop executable hooks into post-receive.d/ next to this symlink.
94 set -eu
95 hook_dir="$(dirname "$0")/post-receive.d"
96 [ -d "$hook_dir" ] || exit 0
97 updates="$(cat)"
98 [ -n "$updates" ] || exit 0
99 for hook in "$hook_dir"/*; do
100 [ -x "$hook" ] || continue
101 printf '%s\n' "$updates" | "$hook" "$@"
102 done
103 '';
104
105 # Best-effort push replication. Publication mirror: main and tags only.
106 # Topic branches are review-queue state, not published — the mirror exists
107 # so consumers can fetch what has been integrated; durability is restic's
108 # job, not the mirror's. Pushes run detached (setsid) so a dead mirror can
109 # only ever cost a log line — never block or fail the primary push.
110 # --prune propagates tag deletions (glob refspec); it is a no-op for heads
111 # now that the heads refspec names one ref, so a separate best-effort sweep
112 # deletes every mirror head but main — which also strips anything that
113 # appears there by other means. The sweep reads only refs/heads (ls-remote
114 # --heads), never refs/pull/*, and is logged apart from the replication
115 # push so it cannot change that push's reported outcome. --mirror is
116 # rejected outright: it also tries to delete remote-only namespaces, and on
117 # GitHub the read-only refs/pull/* makes that fail every push, masking real
118 # replication failures.
119 mirrorPusher =
120 name: mirrors:
121 pkgs.writeShellScript "valley-mirror-push-${name}" ''
122 for url in ${lib.escapeShellArgs mirrors}; do
123 if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then
124 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true
125 else
126 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true
127 fi
128
129 # Unpublish anything but main. Refnames cannot contain whitespace, so
130 # accumulating them space-separated and splitting on expansion is safe.
131 stale=""
132 while read -r _ ref; do
133 [ "$ref" = refs/heads/main ] || stale="$stale $ref"
134 done < <(${pkgs.git}/bin/git ls-remote --heads "$url" 2>/dev/null)
135 if [ -n "$stale" ]; then
136 if ${pkgs.git}/bin/git push "$url" --delete $stale >/dev/null 2>&1; then
137 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublished$stale from $url" || true
138 else
139 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublish from $url failed (ignored)" || true
140 fi
141 fi
142 done
143 '';
144
145 mirrorHook =
146 name: mirrors:
147 pkgs.writeShellScript "valley-mirrors-${name}" ''
148 # Managed by services.valley — best-effort push mirrors for ${name}.
149 cat >/dev/null # updated refs unused: the push replicates main and tags
150 ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1
151 exit 0
152 '';
153
154 # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which
155 # the ref-updated hook below projects this host's git activity. The bus is
156 # never load-bearing for durable state — per-repo events are durable in
157 # git itself, and `valley replay` rebuilds the stream from a repo's refs —
158 # so losing its storage costs one replay, nothing more.
159 busUrl = "nats://${cfg.bus.listen}";
160
161 busServerConfig = pkgs.writeText "valley-bus.conf" ''
162 listen: ${cfg.bus.listen}
163 jetstream {
164 store_dir: "${cfg.bus.storeDir}"
165 # The store directory defaults to living on the repo volume; the cap
166 # keeps a runaway or malicious local publisher from filling it.
167 max_file_store: 2GiB
168 }
169 '';
170
171 # One ref-updated event per updated ref, read from the post-receive stdin
172 # this script inherits. Every payload field is derivable from git alone —
173 # no wall-clock time, no hostname — so replaying a repo's refs reproduces
174 # the same events (the roadmap's determinism criterion). `valley replay`
175 # builds the identical payload; change one only with the other.
176 busPublisher = pkgs.writeShellScript "valley-bus-publish" ''
177 repo="$(basename "$PWD" .git)"
178 while read -r old new ref; do
179 [ -n "$ref" ] || continue
180 # " is the only JSON-significant character a refname can contain
181 # (git forbids \ and control characters); names and ids are safe.
182 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
183 "$repo" "''${ref//\"/\\\"}" "$old" "$new")"
184 if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \
185 "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then
186 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true
187 else
188 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true
189 fi
190 done
191 '';
192
193 # The post-receive.d hook, with the mirror hook's failure semantics: the
194 # publisher runs detached (setsid, inheriting the updates on stdin), so a
195 # bus problem can only ever cost a log line — never block or fail the
196 # push. git is the source of truth; the bus is the replaceable component.
197 busEventHook = pkgs.writeShellScript "valley-bus-events" ''
198 # Managed by services.valley — project ref updates onto the event bus.
199 ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1
200 exit 0
201 '';
202
203 # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks:
204 # only ever installs, updates, or removes a store symlink — a hand-written
205 # hook of the same name is left alone.
206 busHookCommands = lib.concatMapStrings (
207 name:
208 let
209 bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus";
210 in
211 if cfg.bus.enable then
212 ''
213 bhook=${bhook}
214 if [ -L "$bhook" ]; then
215 case "$(readlink "$bhook")" in
216 /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;;
217 esac
218 elif [ ! -e "$bhook" ]; then
219 ln -s ${busEventHook} "$bhook"
220 fi
221 ''
222 else
223 ''
224 bhook=${bhook}
225 if [ -L "$bhook" ]; then
226 case "$(readlink "$bhook")" in
227 /nix/store/*) rm -f "$bhook" ;;
228 esac
229 fi
230 ''
231 ) repoNames;
232
233 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
234 # a store symlink — a hand-written hook of the same name is left alone.
235 mirrorHookCommands = lib.concatStrings (
236 lib.mapAttrsToList (
237 name: p:
238 let
239 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
240 in
241 if p.mirrors != [ ] then
242 ''
243 mhook=${mhook}
244 if [ -L "$mhook" ]; then
245 case "$(readlink "$mhook")" in
246 /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;;
247 esac
248 elif [ ! -e "$mhook" ]; then
249 ln -s ${mirrorHook name p.mirrors} "$mhook"
250 fi
251 ''
252 else
253 ''
254 mhook=${mhook}
255 if [ -L "$mhook" ]; then
256 case "$(readlink "$mhook")" in
257 /nix/store/*) rm -f "$mhook" ;;
258 esac
259 fi
260 ''
261 ) gitProjects
262 );
263
264 # The environment variable carrying the pushing key's principal name.
265 # sshd sets it from the key's own authorized_keys entry; the pre-receive
266 # hook reads it. One name, honoured only because PermitUserEnvironment
267 # below names it.
268 principalEnv = "VALLEY_PRINCIPAL";
269
270 # Keys that name a principal. An entry written as a bare string names
271 # none, and renders exactly as it always did.
272 taggedKeys = lib.filter (k: !lib.isString k) cfg.authorizedKeys;
273
274 authorizedKeyLine =
275 k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}'';
276
277 # Where a contributor's attestations live (design/contribute.md, step 5).
278 attestationNamespace = "refs/the-valley/attestations/";
279
280 # The pre-receive hook: the one structural git invariant
281 # (design/architecture.md, design/contribute.md). Two clauses and nothing
282 # else — only a declared writer may update a protected ref, and an
283 # attestation ref may only be created. Every other ref is open to anyone
284 # with push access, and all policy beyond this lives in the integrator.
285 #
286 # What is protected and who may write it comes from the declaration's
287 # `protection` block, like every other domain fact here. This renders it.
288 #
289 # Pushes arrive over SSH as one shared git user, so the unix account
290 # behind a push says nothing about who pushed. The principal comes from
291 # the key instead: services.valley.authorizedKeys tags each key's
292 # authorized_keys entry, sshd puts that tag in the environment of the
293 # receive-pack this hook runs under, and an untagged key has no principal
294 # at all. The client cannot supply the tag itself — sshd passes on no
295 # client environment (no AcceptEnv).
296 #
297 # This governs pushes, which is every write that crosses the host
298 # boundary. It does not govern writes made on the host: the integrator
299 # updates refs locally, as could anyone holding the git user's shell.
300 # Local access is the host's own boundary, not this hook's.
301 protectHook =
302 name: p:
303 pkgs.writeShellScript "valley-protect-${name}" ''
304 # Managed by services.valley — do not edit.
305 set -eu
306
307 principal="''${${principalEnv}:-}"
308 [ -n "$principal" ] || principal="<untagged key>"
309 writers=( ${lib.escapeShellArgs p.writers} )
310 protected=( ${lib.escapeShellArgs p.refs} )
311
312 is_writer() {
313 local w
314 for w in ''${writers[@]+"''${writers[@]}"}; do
315 if [ "$w" = "$principal" ]; then return 0; fi
316 done
317 return 1
318 }
319
320 rejected=0
321 while read -r old new ref; do
322 [ -n "$ref" ] || continue
323
324 # An attestation is a record of what was checked; a record that can
325 # be rewritten or dropped is not one. So the namespace is
326 # create-only, for everyone — an all-zero old id is a creation, at
327 # any hash length.
328 case "$ref" in
329 ${attestationNamespace}*)
330 case "$old" in
331 *[!0]*)
332 echo "valley: $principal may not update $ref — attestation refs are create-only" >&2
333 rejected=1
334 ;;
335 esac
336 continue
337 ;;
338 esac
339
340 # Protected refs, matched as shell globs (so `*` crosses path
341 # separators). Unprotected refs are not the hook's business.
342 for pattern in ''${protected[@]+"''${protected[@]}"}; do
343 case "$ref" in
344 $pattern)
345 if ! is_writer; then
346 echo "valley: $principal may not write $ref — a protected ref of ${name} (writers: ${
347 lib.concatStringsSep ", " p.writers
348 })" >&2
349 rejected=1
350 fi
351 break
352 ;;
353 esac
354 done
355 done
356 exit "$rejected"
357 '';
358
359 # Per-project pre-receive wiring, from the declaration's protection
360 # blocks. Same rules as the other managed hooks: only ever installs,
361 # updates, or removes a store symlink — a hand-written hook of the same
362 # name is left alone. A project that declares no protection gets no hook,
363 # so a declaration written before the field installs nothing new.
364 protectHookCommands = lib.concatStrings (
365 lib.mapAttrsToList (
366 name: p:
367 let
368 phook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/pre-receive";
369 in
370 if p ? protection then
371 ''
372 phook=${phook}
373 if [ -L "$phook" ]; then
374 case "$(readlink "$phook")" in
375 /nix/store/*) ln -sfn ${protectHook name p.protection} "$phook" ;;
376 esac
377 elif [ ! -e "$phook" ]; then
378 ln -s ${protectHook name p.protection} "$phook"
379 fi
380 ''
381 else
382 ''
383 phook=${phook}
384 if [ -L "$phook" ]; then
385 case "$(readlink "$phook")" in
386 /nix/store/*) rm -f "$phook" ;;
387 esac
388 fi
389 ''
390 ) gitProjects
391 );
392in
393{
394 options.services.valley = {
395 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
396
397 user = lib.mkOption {
398 type = lib.types.str;
399 default = "git";
400 description = "System user that owns the repositories and accepts SSH pushes.";
401 };
402
403 group = lib.mkOption {
404 type = lib.types.str;
405 default = "git";
406 description = "Primary group of the valley git user.";
407 };
408
409 dataDir = lib.mkOption {
410 type = lib.types.path;
411 default = "/srv/git";
412 example = "/mnt/git";
413 description = ''
414 Directory holding the bare repositories, one `<name>.git` per
415 project declared in {option}`services.valley.config`. Also the git
416 user's home, so clone URLs are relative to it (`git@host:name.git`).
417 Consumers typically point it at a dedicated dataset.
418 '';
419 };
420
421 authorizedKeys = lib.mkOption {
422 type = lib.types.listOf (
423 lib.types.either lib.types.str (
424 lib.types.submodule {
425 options = {
426 key = lib.mkOption {
427 type = lib.types.str;
428 description = "The SSH public key, as it would appear in `authorized_keys`.";
429 };
430
431 principal = lib.mkOption {
432 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
433 example = "integrator";
434 description = ''
435 Name of the principal this key acts as. Every push made
436 with the key carries the name, and
437 {option}`services.valley.protect` decides what a name may
438 write. Nothing else uses it.
439 '';
440 };
441 };
442 }
443 )
444 );
445 default = [ ];
446 example = lib.literalExpression ''
447 [
448 "ssh-ed25519 AAAA… someone@somewhere"
449 {
450 principal = "integrator";
451 key = "ssh-ed25519 AAAA… integrator";
452 }
453 ]
454 '';
455 description = ''
456 SSH public keys allowed to push/fetch as the git user. Access is
457 host-level by design: every key can reach every project.
458
459 A key written as a plain string is anonymous — it can push, and it
460 can write nothing protected. A key written as an attribute set
461 names the principal it acts as, which is the only thing that can
462 tell one pusher from another: pushes arrive as the shared git user,
463 so identity has to ride on the key.
464
465 Which refs a principal may write is declared, not an option here:
466 it is a statement about what the host serves, and lives in the
467 project's `protection` block in
468 {option}`services.valley.config`. Binding a name to keys is the
469 machine half — the interim form of the identity registry's
470 compilation (dcr-b87f6e8).
471 '';
472 };
473
474 config = lib.mkOption {
475 type = lib.types.path;
476 example = lib.literalExpression "./valley.cue";
477 description = ''
478 Path to the host's CUE declaration (`package valley`) — the
479 canonical statement of what this valley host serves, validated
480 against the shipped schema at build time. This is the single domain
481 input: projects, their push mirrors, and the backup policy are
482 declared here, never as Nix options.
483 '';
484 };
485
486 # The event bus. Machine options, not domain: whether this machine runs
487 # a bus, where it listens, and where its storage lives. What gets
488 # published onto it is defined portably in ../schema/events.cue.
489 bus = {
490 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
491
492 listen = lib.mkOption {
493 type = lib.types.str;
494 default = "127.0.0.1:4222";
495 example = "100.100.1.7:4222";
496 description = ''
497 Address the bus listens on, `host:port`. Localhost by default:
498 nothing off the host can reach the bus until the consumer widens
499 this deliberately — e.g. to the host's tailnet address once a
500 remote `valley tail` wants in. Local publishers (the ref-updated
501 hook) connect to this same address, so it must be reachable from
502 the host itself.
503 '';
504 };
505
506 storeDir = lib.mkOption {
507 type = lib.types.path;
508 default = "${cfg.dataDir}/.bus";
509 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
510 description = ''
511 Directory holding the JetStream file storage. The default lives
512 under {option}`services.valley.dataDir`; it can never collide
513 with a repository because project names must start with an
514 alphanumeric. The stream is a projection of git, rebuildable
515 with `valley replay` — losing this directory costs one replay.
516 '';
517 };
518 };
519
520 # Machine integration for the declared backup policy. The declaration
521 # states WHAT must hold (offsite backup, cadence, retention); these
522 # options supply HOW on this machine — where the repository is and how
523 # to authenticate. All are paths to files the consumer provisions
524 # (e.g. agenix), required when the declaration enables backup. Point
525 # them at runtime paths, never at files in the Nix store.
526 backup = {
527 repositoryFile = lib.mkOption {
528 type = lib.types.nullOr lib.types.path;
529 default = null;
530 example = "/run/agenix/valley-restic-repo";
531 description = ''
532 File containing the restic repository URL, for the sftp target
533 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
534 '';
535 };
536
537 passwordFile = lib.mkOption {
538 type = lib.types.nullOr lib.types.path;
539 default = null;
540 example = "/run/agenix/valley-restic-password";
541 description = ''
542 File containing the restic repository encryption password.
543 Losing it loses the backups — keep a copy somewhere that
544 survives this host.
545 '';
546 };
547
548 sshKeyFile = lib.mkOption {
549 type = lib.types.nullOr lib.types.path;
550 default = null;
551 example = "/run/agenix/valley-git-ssh-key";
552 description = ''
553 SSH private key that authenticates to the sftp target. The
554 backup service runs as root, so any identity the target
555 authorizes works — reusing the mirror key is fine.
556 '';
557 };
558
559 knownHostsFile = lib.mkOption {
560 type = lib.types.nullOr lib.types.path;
561 default = null;
562 example = "/var/lib/valley-backup/known_hosts";
563 description = ''
564 known_hosts file pinning the sftp target's host key. Pin from
565 the provider's published fingerprints, not a blind ssh-keyscan.
566 '';
567 };
568 };
569 };
570
571 config = lib.mkIf cfg.enable {
572 assertions = [
573 {
574 assertion = cfg.authorizedKeys != [ ];
575 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
576 }
577 ]
578 ++ lib.optionals backupEnabled (
579 lib.mapAttrsToList (name: what: {
580 assertion = cfg.backup.${name} != null;
581 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).";
582 }) backupSecretOptions
583 );
584
585 users.groups.${cfg.group} = { };
586
587 users.users.${cfg.user} = {
588 isSystemUser = true;
589 group = cfg.group;
590 home = cfg.dataDir;
591 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
592 # interactive logins are rejected (no ~/git-shell-commands).
593 shell = "${pkgs.git}/bin/git-shell";
594 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
595 };
596
597 services.openssh.enable = lib.mkDefault true;
598
599 # Honour the principal tag on a key's entry, and nothing else: the
600 # pattern-list form admits that one variable name. Rendered only once a
601 # key names a principal, so a host with none keeps the sshd config it
602 # had.
603 services.openssh.settings = lib.optionalAttrs (taggedKeys != [ ]) {
604 PermitUserEnvironment = principalEnv;
605 };
606
607 # Belt-and-braces hardening for the git user. The trailing `Match All`
608 # closes the block so it can't scope directives appended to sshd_config
609 # after this snippet.
610 services.openssh.extraConfig = ''
611 Match User ${cfg.user}
612 AllowTcpForwarding no
613 AllowAgentForwarding no
614 X11Forwarding no
615 PermitTunnel no
616 Match All
617 '';
618
619 # git-shell spawns git-receive-pack/git-upload-pack from PATH
620 environment.systemPackages = [ pkgs.git ];
621
622 systemd.tmpfiles.rules = [
623 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
624 ]
625 ++ lib.optionals cfg.bus.enable [
626 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
627 ];
628
629 # The bus itself. It runs as the git user — the store directory lives in
630 # that user's data — but the sandbox is what confines it: the unit can
631 # write nowhere except its store directory.
632 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
633 description = "The valley event bus (NATS JetStream)";
634 wantedBy = [ "multi-user.target" ];
635 after = [
636 "network.target"
637 "systemd-tmpfiles-setup.service"
638 ];
639 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
640 serviceConfig = {
641 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
642 Restart = "on-failure";
643 User = cfg.user;
644 Group = cfg.group;
645 LimitNOFILE = 65536;
646 NoNewPrivileges = true;
647 ProtectSystem = "strict";
648 ReadWritePaths = [ cfg.bus.storeDir ];
649 ProtectHome = true;
650 PrivateTmp = true;
651 PrivateDevices = true;
652 ProtectClock = true;
653 ProtectHostname = true;
654 ProtectKernelLogs = true;
655 ProtectKernelModules = true;
656 ProtectKernelTunables = true;
657 ProtectControlGroups = true;
658 ProtectProc = "invisible";
659 RestrictAddressFamilies = [
660 "AF_INET"
661 "AF_INET6"
662 "AF_UNIX"
663 ];
664 RestrictNamespaces = true;
665 RestrictRealtime = true;
666 RestrictSUIDSGID = true;
667 LockPersonality = true;
668 CapabilityBoundingSet = "";
669 SystemCallArchitectures = "native";
670 SystemCallFilter = [ "@system-service" ];
671 UMask = "0077";
672 };
673 };
674
675 # The stream is config, not state: (re)created idempotently on every
676 # boot, capturing everything under valley.>. An existing stream — and
677 # the events in it — is left untouched.
678 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
679 description = "Create the valley event stream";
680 wantedBy = [ "multi-user.target" ];
681 requires = [ "valley-bus.service" ];
682 after = [ "valley-bus.service" ];
683 serviceConfig = {
684 Type = "oneshot";
685 User = cfg.user;
686 Group = cfg.group;
687 };
688 path = [ pkgs.natscli ];
689 script = ''
690 # The server needs a moment to accept connections after startup.
691 for _ in $(seq 1 50); do
692 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
693 sleep 0.2
694 done
695 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
696 nats --server ${busUrl} stream add valley \
697 --subjects 'valley.>' --storage file --defaults
698 fi
699 '';
700 };
701
702 # Create missing bare repos and (re)wire the managed hooks on every
703 # activation where the declaration changed.
704 systemd.services.valley-init = {
705 description = "Initialize the valley host's bare git repositories";
706 wantedBy = [ "multi-user.target" ];
707 after = [ "systemd-tmpfiles-setup.service" ];
708 unitConfig.RequiresMountsFor = cfg.dataDir;
709 serviceConfig = {
710 Type = "oneshot";
711 User = cfg.user;
712 Group = cfg.group;
713 };
714 path = [ pkgs.git ];
715 script = ''
716 repos=( ${lib.escapeShellArgs repoNames} )
717 for name in "''${repos[@]}"; do
718 repo="${cfg.dataDir}/$name.git"
719 # Check HEAD rather than the directory itself so a pre-existing
720 # empty directory still gets initialized.
721 if [ ! -e "$repo/HEAD" ]; then
722 git init --bare --initial-branch=main "$repo"
723 fi
724
725 # Hook scaffolding: post-receive dispatches to post-receive.d/.
726 # Only manage the hook if it is absent or already ours (a store
727 # symlink) — a hand-written hook is left alone.
728 mkdir -p "$repo/hooks/post-receive.d"
729 hook="$repo/hooks/post-receive"
730 if [ -L "$hook" ]; then
731 case "$(readlink "$hook")" in
732 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
733 esac
734 elif [ ! -e "$hook" ]; then
735 ln -s ${postReceiveDispatch} "$hook"
736 fi
737 done
738
739 # Per-project push-mirror hooks.
740 ${mirrorHookCommands}
741
742 # The one structural invariant, on every project declared protected.
743 ${protectHookCommands}
744
745 # The ref-updated publisher hook, on every repo when the bus is on.
746 ${busHookCommands}
747 '';
748 };
749
750 # Offsite backup, rendered only when the declaration asks for it. The
751 # declaration states the policy — that backup exists, its cadence and
752 # retention; the services.valley.backup.* options supply the machine
753 # half. Declaration absent or disabled ⇒ no restic config at all.
754 services.restic.backups = lib.mkIf backupEnabled {
755 valley = {
756 initialize = true;
757 repositoryFile = cfg.backup.repositoryFile;
758 passwordFile = cfg.backup.passwordFile;
759 paths = [ cfg.dataDir ];
760 # The schema admits only the restic-sftp target today; a second
761 # target would grow a dispatch here. The service runs as root:
762 # authenticate with the supplied identity and only the pinned
763 # host key. No prompt can be answered inside a systemd unit, so
764 # BatchMode + strict host key checking turn a would-be hang into
765 # an immediate error.
766 extraOptions = [
767 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
768 ];
769 timerConfig = backupTimer.${backupPolicy.cadence};
770 pruneOpts = [
771 "--keep-daily ${toString backupPolicy.retention.daily}"
772 "--keep-weekly ${toString backupPolicy.retention.weekly}"
773 "--keep-monthly ${toString backupPolicy.retention.monthly}"
774 ];
775 };
776 };
777 };
778}