gunk-dev/the-valley

valley-host.nix

sourceb901a0ad9cb5main's published tip history
8.8 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. This module owns machine integration only:
6# data directory, unix user, SSH keys. At build time the CUE config is
7# vetted against the shipped schema and exported to JSON; an invalid config
8# fails the system build with cue's error. Nix never redefines the schema.
9#
10# Repos are only ever created, never deleted or overwritten — removing a
11# project (or disabling its git store) leaves the data on disk untouched.
12#
13# Identity is deliberately thin and host-level: one git user, git-shell,
14# key-only, Tailscale ACLs in front. Per-project access is not honestly
15# enforceable with this mechanism, so it is deliberately not an option
16# (.the-valley/decisions/dcr-0f5d9b1-cue-config-host-module.md).
17#
18# Mirror credentials are the consumer's concern: the module assumes the git
19# user's SSH identity and known_hosts are provisioned by the host (e.g.
20# cosmo, via its secrets). Nothing here plumbs secrets.
21{
22 config,
23 pkgs,
24 lib,
25 ...
26}:
27
28let
29 cfg = config.services.valley;
30
31 schema = ../schema/valley.cue;
32
33 # Build-time vet + export of the host declaration. the vet checks the
34 # declaration against the schema (whose top level applies #Host), so unknown
35 # fields and unsafe project names fail the build, with cue's error.
36 configJSON =
37 pkgs.runCommand "valley-config.json"
38 {
39 nativeBuildInputs = [ pkgs.cue ];
40 }
41 ''
42 cue vet -c ${schema} ${cfg.config}
43 cue export ${schema} ${cfg.config} > $out
44 '';
45
46 host = lib.importJSON configJSON;
47
48 # Projects whose git store is enabled get a bare repository.
49 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
50 repoNames = lib.attrNames gitProjects;
51
52 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
53 # this script, which chains every executable dropped into the repo's
54 # hooks/post-receive.d/ directory.
55 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
56 # Managed by services.valley — do not edit.
57 # Drop executable hooks into post-receive.d/ next to this symlink.
58 set -eu
59 hook_dir="$(dirname "$0")/post-receive.d"
60 [ -d "$hook_dir" ] || exit 0
61 updates="$(cat)"
62 [ -n "$updates" ] || exit 0
63 for hook in "$hook_dir"/*; do
64 [ -x "$hook" ] || continue
65 printf '%s\n' "$updates" | "$hook" "$@"
66 done
67 '';
68
69 # Best-effort push replication. The pushes run detached (setsid) so a dead
70 # mirror can only ever cost a log line — never block or fail the primary
71 # push. `--mirror` propagates deletions, the correct semantic for a mirror.
72 mirrorPusher =
73 name: mirrors:
74 pkgs.writeShellScript "valley-mirror-push-${name}" ''
75 for url in ${lib.escapeShellArgs mirrors}; do
76 if ${pkgs.git}/bin/git push --mirror "$url" >/dev/null 2>&1; then
77 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true
78 else
79 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true
80 fi
81 done
82 '';
83
84 mirrorHook =
85 name: mirrors:
86 pkgs.writeShellScript "valley-mirrors-${name}" ''
87 # Managed by services.valley — best-effort push mirrors for ${name}.
88 cat >/dev/null # updated refs unused: --mirror replicates everything
89 ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1
90 exit 0
91 '';
92
93 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
94 # a store symlink — a hand-written hook of the same name is left alone.
95 mirrorHookCommands = lib.concatStrings (
96 lib.mapAttrsToList (
97 name: p:
98 let
99 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
100 in
101 if p.mirrors != [ ] then
102 ''
103 mhook=${mhook}
104 if [ -L "$mhook" ]; then
105 case "$(readlink "$mhook")" in
106 /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;;
107 esac
108 elif [ ! -e "$mhook" ]; then
109 ln -s ${mirrorHook name p.mirrors} "$mhook"
110 fi
111 ''
112 else
113 ''
114 mhook=${mhook}
115 if [ -L "$mhook" ]; then
116 case "$(readlink "$mhook")" in
117 /nix/store/*) rm -f "$mhook" ;;
118 esac
119 fi
120 ''
121 ) gitProjects
122 );
123in
124{
125 options.services.valley = {
126 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
127
128 user = lib.mkOption {
129 type = lib.types.str;
130 default = "git";
131 description = "System user that owns the repositories and accepts SSH pushes.";
132 };
133
134 group = lib.mkOption {
135 type = lib.types.str;
136 default = "git";
137 description = "Primary group of the valley git user.";
138 };
139
140 dataDir = lib.mkOption {
141 type = lib.types.path;
142 default = "/srv/git";
143 example = "/mnt/git";
144 description = ''
145 Directory holding the bare repositories, one `<name>.git` per
146 project declared in {option}`services.valley.config`. Also the git
147 user's home, so clone URLs are relative to it (`git@host:name.git`).
148 Consumers typically point it at a dedicated dataset.
149 '';
150 };
151
152 authorizedKeys = lib.mkOption {
153 type = lib.types.listOf lib.types.str;
154 default = [ ];
155 description = ''
156 SSH public keys allowed to push/fetch as the git user. Access is
157 host-level by design: every key can reach every project.
158 '';
159 };
160
161 config = lib.mkOption {
162 type = lib.types.path;
163 example = lib.literalExpression "./valley.cue";
164 description = ''
165 Path to the host's CUE declaration (`package valley`) — the
166 canonical statement of what this valley host serves, validated
167 against the shipped schema at build time. This is the single domain
168 input: projects and their push mirrors are declared here, never as
169 Nix options.
170 '';
171 };
172 };
173
174 config = lib.mkIf cfg.enable {
175 assertions = [
176 {
177 assertion = cfg.authorizedKeys != [ ];
178 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
179 }
180 ];
181
182 users.groups.${cfg.group} = { };
183
184 users.users.${cfg.user} = {
185 isSystemUser = true;
186 group = cfg.group;
187 home = cfg.dataDir;
188 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
189 # interactive logins are rejected (no ~/git-shell-commands).
190 shell = "${pkgs.git}/bin/git-shell";
191 openssh.authorizedKeys.keys = cfg.authorizedKeys;
192 };
193
194 services.openssh.enable = lib.mkDefault true;
195
196 # Belt-and-braces hardening for the git user. The trailing `Match All`
197 # closes the block so it can't scope directives appended to sshd_config
198 # after this snippet.
199 services.openssh.extraConfig = ''
200 Match User ${cfg.user}
201 AllowTcpForwarding no
202 AllowAgentForwarding no
203 X11Forwarding no
204 PermitTunnel no
205 Match All
206 '';
207
208 # git-shell spawns git-receive-pack/git-upload-pack from PATH
209 environment.systemPackages = [ pkgs.git ];
210
211 systemd.tmpfiles.rules = [
212 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
213 ];
214
215 # Create missing bare repos and (re)wire the managed hooks on every
216 # activation where the declaration changed.
217 systemd.services.valley-init = {
218 description = "Initialize the valley host's bare git repositories";
219 wantedBy = [ "multi-user.target" ];
220 after = [ "systemd-tmpfiles-setup.service" ];
221 unitConfig.RequiresMountsFor = cfg.dataDir;
222 serviceConfig = {
223 Type = "oneshot";
224 User = cfg.user;
225 Group = cfg.group;
226 };
227 path = [ pkgs.git ];
228 script = ''
229 repos=( ${lib.escapeShellArgs repoNames} )
230 for name in "''${repos[@]}"; do
231 repo="${cfg.dataDir}/$name.git"
232 # Check HEAD rather than the directory itself so a pre-existing
233 # empty directory still gets initialized.
234 if [ ! -e "$repo/HEAD" ]; then
235 git init --bare --initial-branch=main "$repo"
236 fi
237
238 # Hook scaffolding: post-receive dispatches to post-receive.d/.
239 # Only manage the hook if it is absent or already ours (a store
240 # symlink) — a hand-written hook is left alone.
241 mkdir -p "$repo/hooks/post-receive.d"
242 hook="$repo/hooks/post-receive"
243 if [ -L "$hook" ]; then
244 case "$(readlink "$hook")" in
245 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
246 esac
247 elif [ ! -e "$hook" ]; then
248 ln -s ${postReceiveDispatch} "$hook"
249 fi
250 done
251
252 # Per-project push-mirror hooks.
253 ${mirrorHookCommands}
254 '';
255 };
256 };
257}