gunk-dev/the-valley

valley-host.nix

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