gunk-dev/the-valley

valley-host.nix

source86d2314b4164main's published tip history
14.2 KiB
1# The valley host installer: declarative bare-git hosting over SSH, driven
2# by a CUE host declaration (../schema/valley.cue).
3#
4# Layering: the CUE file owns the domain model — which projects exist, their
5# stores, their push mirrors, whether the host's data has offsite backup and
6# with what cadence and retention. This module owns machine integration
7# only: data directory, unix user, SSH keys, backup credentials. At build
8# time the CUE config is vetted against the shipped schema and exported to
9# JSON; an invalid config fails the system build with cue's error. Nix
10# never redefines the schema.
11#
12# Repos are only ever created, never deleted or overwritten — removing a
13# project (or disabling its git store) leaves the data on disk untouched.
14#
15# Identity is deliberately thin and host-level: one git user, git-shell,
16# key-only, Tailscale ACLs in front. Per-project access is not honestly
17# enforceable with this mechanism, so it is deliberately not an option
18# (.the-valley/decisions/dcr-0f5d9b1-cue-config-host-module.md).
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 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
129 # a store symlink — a hand-written hook of the same name is left alone.
130 mirrorHookCommands = lib.concatStrings (
131 lib.mapAttrsToList (
132 name: p:
133 let
134 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
135 in
136 if p.mirrors != [ ] then
137 ''
138 mhook=${mhook}
139 if [ -L "$mhook" ]; then
140 case "$(readlink "$mhook")" in
141 /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;;
142 esac
143 elif [ ! -e "$mhook" ]; then
144 ln -s ${mirrorHook name p.mirrors} "$mhook"
145 fi
146 ''
147 else
148 ''
149 mhook=${mhook}
150 if [ -L "$mhook" ]; then
151 case "$(readlink "$mhook")" in
152 /nix/store/*) rm -f "$mhook" ;;
153 esac
154 fi
155 ''
156 ) gitProjects
157 );
158in
159{
160 options.services.valley = {
161 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
162
163 user = lib.mkOption {
164 type = lib.types.str;
165 default = "git";
166 description = "System user that owns the repositories and accepts SSH pushes.";
167 };
168
169 group = lib.mkOption {
170 type = lib.types.str;
171 default = "git";
172 description = "Primary group of the valley git user.";
173 };
174
175 dataDir = lib.mkOption {
176 type = lib.types.path;
177 default = "/srv/git";
178 example = "/mnt/git";
179 description = ''
180 Directory holding the bare repositories, one `<name>.git` per
181 project declared in {option}`services.valley.config`. Also the git
182 user's home, so clone URLs are relative to it (`git@host:name.git`).
183 Consumers typically point it at a dedicated dataset.
184 '';
185 };
186
187 authorizedKeys = lib.mkOption {
188 type = lib.types.listOf lib.types.str;
189 default = [ ];
190 description = ''
191 SSH public keys allowed to push/fetch as the git user. Access is
192 host-level by design: every key can reach every project.
193 '';
194 };
195
196 config = lib.mkOption {
197 type = lib.types.path;
198 example = lib.literalExpression "./valley.cue";
199 description = ''
200 Path to the host's CUE declaration (`package valley`) — the
201 canonical statement of what this valley host serves, validated
202 against the shipped schema at build time. This is the single domain
203 input: projects, their push mirrors, and the backup policy are
204 declared here, never as Nix options.
205 '';
206 };
207
208 # Machine integration for the declared backup policy. The declaration
209 # states WHAT must hold (offsite backup, cadence, retention); these
210 # options supply HOW on this machine — where the repository is and how
211 # to authenticate. All are paths to files the consumer provisions
212 # (e.g. agenix), required when the declaration enables backup. Point
213 # them at runtime paths, never at files in the Nix store.
214 backup = {
215 repositoryFile = lib.mkOption {
216 type = lib.types.nullOr lib.types.path;
217 default = null;
218 example = "/run/agenix/valley-restic-repo";
219 description = ''
220 File containing the restic repository URL, for the sftp target
221 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
222 '';
223 };
224
225 passwordFile = lib.mkOption {
226 type = lib.types.nullOr lib.types.path;
227 default = null;
228 example = "/run/agenix/valley-restic-password";
229 description = ''
230 File containing the restic repository encryption password.
231 Losing it loses the backups — keep a copy somewhere that
232 survives this host.
233 '';
234 };
235
236 sshKeyFile = lib.mkOption {
237 type = lib.types.nullOr lib.types.path;
238 default = null;
239 example = "/run/agenix/valley-git-ssh-key";
240 description = ''
241 SSH private key that authenticates to the sftp target. The
242 backup service runs as root, so any identity the target
243 authorizes works — reusing the mirror key is fine.
244 '';
245 };
246
247 knownHostsFile = lib.mkOption {
248 type = lib.types.nullOr lib.types.path;
249 default = null;
250 example = "/var/lib/valley-backup/known_hosts";
251 description = ''
252 known_hosts file pinning the sftp target's host key. Pin from
253 the provider's published fingerprints, not a blind ssh-keyscan.
254 '';
255 };
256 };
257 };
258
259 config = lib.mkIf cfg.enable {
260 assertions = [
261 {
262 assertion = cfg.authorizedKeys != [ ];
263 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
264 }
265 ]
266 ++ lib.optionals backupEnabled (
267 lib.mapAttrsToList (name: what: {
268 assertion = cfg.backup.${name} != null;
269 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).";
270 }) backupSecretOptions
271 );
272
273 users.groups.${cfg.group} = { };
274
275 users.users.${cfg.user} = {
276 isSystemUser = true;
277 group = cfg.group;
278 home = cfg.dataDir;
279 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
280 # interactive logins are rejected (no ~/git-shell-commands).
281 shell = "${pkgs.git}/bin/git-shell";
282 openssh.authorizedKeys.keys = cfg.authorizedKeys;
283 };
284
285 services.openssh.enable = lib.mkDefault true;
286
287 # Belt-and-braces hardening for the git user. The trailing `Match All`
288 # closes the block so it can't scope directives appended to sshd_config
289 # after this snippet.
290 services.openssh.extraConfig = ''
291 Match User ${cfg.user}
292 AllowTcpForwarding no
293 AllowAgentForwarding no
294 X11Forwarding no
295 PermitTunnel no
296 Match All
297 '';
298
299 # git-shell spawns git-receive-pack/git-upload-pack from PATH
300 environment.systemPackages = [ pkgs.git ];
301
302 systemd.tmpfiles.rules = [
303 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
304 ];
305
306 # Create missing bare repos and (re)wire the managed hooks on every
307 # activation where the declaration changed.
308 systemd.services.valley-init = {
309 description = "Initialize the valley host's bare git repositories";
310 wantedBy = [ "multi-user.target" ];
311 after = [ "systemd-tmpfiles-setup.service" ];
312 unitConfig.RequiresMountsFor = cfg.dataDir;
313 serviceConfig = {
314 Type = "oneshot";
315 User = cfg.user;
316 Group = cfg.group;
317 };
318 path = [ pkgs.git ];
319 script = ''
320 repos=( ${lib.escapeShellArgs repoNames} )
321 for name in "''${repos[@]}"; do
322 repo="${cfg.dataDir}/$name.git"
323 # Check HEAD rather than the directory itself so a pre-existing
324 # empty directory still gets initialized.
325 if [ ! -e "$repo/HEAD" ]; then
326 git init --bare --initial-branch=main "$repo"
327 fi
328
329 # Hook scaffolding: post-receive dispatches to post-receive.d/.
330 # Only manage the hook if it is absent or already ours (a store
331 # symlink) — a hand-written hook is left alone.
332 mkdir -p "$repo/hooks/post-receive.d"
333 hook="$repo/hooks/post-receive"
334 if [ -L "$hook" ]; then
335 case "$(readlink "$hook")" in
336 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
337 esac
338 elif [ ! -e "$hook" ]; then
339 ln -s ${postReceiveDispatch} "$hook"
340 fi
341 done
342
343 # Per-project push-mirror hooks.
344 ${mirrorHookCommands}
345 '';
346 };
347
348 # Offsite backup, rendered only when the declaration asks for it. The
349 # declaration states the policy — that backup exists, its cadence and
350 # retention; the services.valley.backup.* options supply the machine
351 # half. Declaration absent or disabled ⇒ no restic config at all.
352 services.restic.backups = lib.mkIf backupEnabled {
353 valley = {
354 initialize = true;
355 repositoryFile = cfg.backup.repositoryFile;
356 passwordFile = cfg.backup.passwordFile;
357 paths = [ cfg.dataDir ];
358 # The schema admits only the restic-sftp target today; a second
359 # target would grow a dispatch here. The service runs as root:
360 # authenticate with the supplied identity and only the pinned
361 # host key. No prompt can be answered inside a systemd unit, so
362 # BatchMode + strict host key checking turn a would-be hang into
363 # an immediate error.
364 extraOptions = [
365 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
366 ];
367 timerConfig = backupTimer.${backupPolicy.cadence};
368 pruneOpts = [
369 "--keep-daily ${toString backupPolicy.retention.daily}"
370 "--keep-weekly ${toString backupPolicy.retention.weekly}"
371 "--keep-monthly ${toString backupPolicy.retention.monthly}"
372 ];
373 };
374 };
375 };
376}