gunk-dev/the-valley

valley-host.nix

source818813f26b40main's published tip history
71.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, 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 grants, and installs the hook.
24# Those bindings are declared by hand or compiled from the instance's
25# identity registry, and the compiler is off until a consumer turns it on.
26#
27# Mirror credentials are the consumer's concern: the module assumes the git
28# user's SSH identity and known_hosts are provisioned by the host (e.g.
29# cosmo, via its secrets). Nothing here plumbs secrets: the backup options
30# below take *paths* to consumer-provisioned secret files; the contents
31# never pass through this module or the store.
32#
33# One service runs under its own unix user rather than the git one: the
34# integrator. That is the first half of the split bd-500adf7 asks for.
35{
36 config,
37 pkgs,
38 lib,
39 ...
40}:
41
42let
43 cfg = config.services.valley;
44
45 schema = ../schema/valley.cue;
46
47 # Build-time vet + export of the host declaration. the vet checks the
48 # declaration against the schema (whose top level applies #Host), so unknown
49 # fields and unsafe project names fail the build, with cue's error.
50 configJSON =
51 pkgs.runCommand "valley-config.json"
52 {
53 nativeBuildInputs = [ pkgs.cue ];
54 }
55 ''
56 cue vet -c ${schema} ${cfg.config}
57 cue export ${schema} ${cfg.config} > $out
58 '';
59
60 host = lib.importJSON configJSON;
61
62 # Projects whose git store is enabled get a bare repository.
63 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
64 repoNames = lib.attrNames gitProjects;
65
66 # The declared durability policy, if any. `backup` is optional in the
67 # schema: a declaration without it (or with enable = false) renders zero
68 # backup machinery, exactly as before the field existed.
69 backupPolicy = host.backup or null;
70 backupEnabled = backupPolicy != null && backupPolicy.enable;
71
72 # The declared cadence names policy; its wall-clock rendering is this
73 # installer's choice. A lookup rather than a literal, so a cadence this
74 # module does not know fails eval loudly instead of mis-scheduling.
75 backupTimer = {
76 # Late night with a spread; Persistent runs a missed window at boot.
77 nightly = {
78 OnCalendar = "03:30";
79 RandomizedDelaySec = "30m";
80 Persistent = true;
81 };
82 };
83
84 # The projects the integrator serves: exactly the ones the declaration
85 # protects. A protected ref is one only a declared writer may push, and
86 # the integrator is what lands everyone else's changes onto it.
87 integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects;
88
89 # The integrator this flake builds, in its shipping form: attest, the
90 # deriver, cue, git and natscli pinned inside the wrapper, so every host
91 # judges with the same tools (nix/packages.nix).
92 integratorPackage = (import ./packages.nix { inherit pkgs lib; }).integrator;
93
94 # The whole of a controller's configuration: which repository it serves,
95 # who it signs as, and whose evidence it accepts. No policy — the
96 # integrator reads the project layer from the target tip and the instance
97 # layer from its own side (bd-eaefe82) — and no project name, which the
98 # binary derives from the bare repo's own directory, the same way the
99 # post-receive hook does.
100 integratorCommand = lib.concatStringsSep " " (
101 [
102 "${integratorPackage}/bin/integrator watch"
103 "--repo ${cfg.dataDir}/%i.git"
104 "--key ${toString cfg.integrator.signingKeyFile}"
105 "--known-signers ${knownSigners}"
106 "--interval ${cfg.integrator.interval}"
107 ]
108 ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}"
109 ++ (
110 if cfg.integrator.instanceProject != null then
111 [ "--instance-repo ${instanceRepo}" ]
112 else
113 [ "--instance ${toString cfg.integrator.instancePolicy}" ]
114 )
115 ++ lib.optional cfg.bus.enable "--bus ${busUrl}"
116 );
117
118 # The one filesystem grant the integrator's user gets. It writes refs,
119 # objects, and the worktree metadata `git worktree add` keeps inside the
120 # repository, so read access is not enough: the repos it serves become
121 # group-shared, and its primary group is the git group. Re-applied on
122 # every activation, because a repo can predate the service.
123 # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by
124 # whichever user got there first. Left alone that user is the integrator,
125 # and this sweep runs as the git user, which cannot chmod a directory it
126 # does not own. So init makes that directory itself, ahead of any
127 # controller: owned by the git user, group-writable, and setgid, so what a
128 # controller creates inside it lands in the git group and stays reachable.
129 integratorShareCommands =
130 ''
131 # A chmod the git user is not allowed to make is a path some other
132 # user owns; chmod -R applies what it can and then says so. Warn and
133 # carry on, and the trade is worth stating. Failing here fails
134 # valley-init, which every valley unit requires, so the alternative to
135 # a partly shared repository is no git service on the host at all: no
136 # controllers, and no ssh access to any project. A degraded share
137 # costs the integrator the paths it cannot write, is visible in the
138 # journal, and is fixed by one chown. That is the recoverable half of
139 # the trade, and it is the half to take. The warning is what keeps the
140 # degraded state from being a silent one.
141 share() {
142 "$@" || echo "valley-init: $* failed — a path the git user does not own is left as it was, and the integrator may be unable to write it" >&2
143 }
144 ''
145 + lib.concatMapStrings (name: ''
146 repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
147 git -C "$repo" config core.sharedRepository group
148 # Before the sweep below, so the sweep never meets a root it cannot
149 # touch. On a host where a controller already made it, this is the
150 # chmod that warns, and the repository is served either way.
151 mkdir -p "$repo/worktrees"
152 share chmod g+rwxs "$repo/worktrees"
153 share chmod -R g+rwX "$repo"
154 share find "$repo" -type d -exec chmod g+s {} +
155 '') (lib.attrNames integratedProjects);
156
157 # The integrator's own directory. Four unit settings have to agree about
158 # it — its state directory, its working directory, the scratch root TMPDIR
159 # names, and the read-write path that makes all three usable — so they name
160 # it once here.
161 # The bare repository the group's floor is read from: the instance
162 # project's, served by this host. Null when the host serves no instance
163 # repository and the layer is supplied as a directory instead.
164 instanceRepo =
165 if cfg.integrator.instanceProject != null then
166 "${cfg.dataDir}/${cfg.integrator.instanceProject}.git"
167 else
168 null;
169
170 integratorStateName = "valley-integrator";
171 integratorStateDir = "/var/lib/${integratorStateName}";
172
173 # The identity registry compiler this flake builds. It renders the
174 # registry at the instance repository's integrated tip into what the gates
175 # check (dcr-b87f6e8): the known-signers file the integrator and any
176 # reader of an attestation use, and a tagged authorized_keys for the git
177 # user.
178 identityPackage = (import ./packages.nix { inherit pkgs lib; }).identity;
179
180 identityStateName = "valley-identity";
181 identityStateDir = "/var/lib/${identityStateName}";
182 identityKnownSigners = "${identityStateDir}/known-signers";
183
184 # The grants the pre-receive hook checks, as the registry names them.
185 identityGrants = "${identityStateDir}/grants";
186
187 # The compiled authorized keys. sshd reads them for the git user alone:
188 # the git user's Match block below names the files its keys come from.
189 identityAuthorizedKeys = "${identityStateDir}/authorized_keys.${cfg.user}";
190
191 identityCommand = lib.concatStringsSep " " [
192 "${identityPackage}/bin/identity compile"
193 "--repo ${toString instanceRepo}"
194 "--ref ${cfg.identity.ref}"
195 "--dir ${cfg.identity.directory}"
196 "--known-signers ${identityKnownSigners}"
197 "--authorized-keys ${identityAuthorizedKeys}"
198 "--grants ${identityGrants}"
199 "--declared-keys ${declaredKeysFile}"
200 ];
201
202 # Whose evidence a controller accepts: the compiled artifact once the
203 # registry machinery is on, and the file the consumer supplied otherwise.
204 knownSigners =
205 if cfg.identity.enable then identityKnownSigners else toString cfg.integrator.knownSignersFile;
206
207 # The paths the consumer must supply once the integrator is enabled,
208 # with what each names — for the assertion message. The signers file is
209 # among them only while the registry does not compile one.
210 integratorPathOptions = {
211 signingKeyFile = "the key its transfer statements are signed with";
212 }
213 // lib.optionalAttrs (!cfg.identity.enable) {
214 knownSignersFile = "the signers whose evidence it accepts";
215 };
216
217 # The secret-path options the consumer must supply once the declaration
218 # enables backup, with what each names — for the assertion message.
219 backupSecretOptions = {
220 repositoryFile = "the restic repository URL";
221 passwordFile = "the repository encryption password";
222 sshKeyFile = "the SSH identity for the sftp target";
223 knownHostsFile = "the pinned host key of the sftp target";
224 };
225
226 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
227 # this script, which chains every executable dropped into the repo's
228 # hooks/post-receive.d/ directory.
229 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
230 # Managed by services.valley — do not edit.
231 # Drop executable hooks into post-receive.d/ next to this symlink.
232 set -eu
233 hook_dir="$(dirname "$0")/post-receive.d"
234 [ -d "$hook_dir" ] || exit 0
235 updates="$(cat)"
236 [ -n "$updates" ] || exit 0
237 for hook in "$hook_dir"/*; do
238 [ -x "$hook" ] || continue
239 printf '%s\n' "$updates" | "$hook" "$@"
240 done
241 '';
242
243 # Best-effort push replication. Publication mirror: main and tags only.
244 # Topic branches are review-queue state, not published — the mirror exists
245 # so consumers can fetch what has been integrated; durability is restic's
246 # job, not the mirror's. Pushes run detached (setsid) so a dead mirror can
247 # only ever cost a log line — never block or fail the primary push.
248 # --prune propagates tag deletions (glob refspec); it is a no-op for heads
249 # now that the heads refspec names one ref, so a separate best-effort sweep
250 # deletes every mirror head but main — which also strips anything that
251 # appears there by other means. The sweep reads only refs/heads (ls-remote
252 # --heads), never refs/pull/*, and is logged apart from the replication
253 # push so it cannot change that push's reported outcome. --mirror is
254 # rejected outright: it also tries to delete remote-only namespaces, and on
255 # GitHub the read-only refs/pull/* makes that fail every push, masking real
256 # replication failures.
257 mirrorPusher =
258 name: mirrors:
259 pkgs.writeShellScript "valley-mirror-push-${name}" ''
260 for url in ${lib.escapeShellArgs mirrors}; do
261 if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then
262 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true
263 else
264 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true
265 fi
266
267 # Unpublish anything but main. Refnames cannot contain whitespace, so
268 # accumulating them space-separated and splitting on expansion is safe.
269 stale=""
270 while read -r _ ref; do
271 [ "$ref" = refs/heads/main ] || stale="$stale $ref"
272 done < <(${pkgs.git}/bin/git ls-remote --heads "$url" 2>/dev/null)
273 if [ -n "$stale" ]; then
274 if ${pkgs.git}/bin/git push "$url" --delete $stale >/dev/null 2>&1; then
275 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublished$stale from $url" || true
276 else
277 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: unpublish from $url failed (ignored)" || true
278 fi
279 fi
280 done
281 '';
282
283 mirrorHook =
284 name: mirrors:
285 pkgs.writeShellScript "valley-mirrors-${name}" ''
286 # Managed by services.valley — best-effort push mirrors for ${name}.
287 cat >/dev/null # updated refs unused: the push replicates main and tags
288 ${pkgs.util-linux}/bin/setsid -f ${mirrorPusher name mirrors} </dev/null >/dev/null 2>&1
289 exit 0
290 '';
291
292 # The event bus (design/roadmap.md, Phase 1): NATS JetStream, onto which
293 # the ref-updated hook below projects this host's git activity. The bus is
294 # never load-bearing for durable state — per-repo events are durable in
295 # git itself, and `valley replay` rebuilds the stream from a repo's refs —
296 # so losing its storage costs one replay, nothing more.
297 busUrl = "nats://${cfg.bus.listen}";
298
299 busServerConfig = pkgs.writeText "valley-bus.conf" ''
300 listen: ${cfg.bus.listen}
301 jetstream {
302 store_dir: "${cfg.bus.storeDir}"
303 # The store directory defaults to living on the repo volume; the cap
304 # keeps a runaway or malicious local publisher from filling it.
305 max_file_store: 2GiB
306 }
307 '';
308
309 # One ref-updated event per updated ref, read from the post-receive stdin
310 # this script inherits. Every payload field is derivable from git alone —
311 # no wall-clock time, no hostname — so replaying a repo's refs reproduces
312 # the same events (the roadmap's determinism criterion). `valley replay`
313 # builds the identical payload; change one only with the other.
314 busPublisher = pkgs.writeShellScript "valley-bus-publish" ''
315 repo="$(basename "$PWD" .git)"
316 while read -r old new ref; do
317 [ -n "$ref" ] || continue
318 # " is the only JSON-significant character a refname can contain
319 # (git forbids \ and control characters); names and ids are safe.
320 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
321 "$repo" "''${ref//\"/\\\"}" "$old" "$new")"
322 if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \
323 "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then
324 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true
325 else
326 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true
327 fi
328 done
329 '';
330
331 # The post-receive.d hook, with the mirror hook's failure semantics: the
332 # publisher runs detached (setsid, inheriting the updates on stdin), so a
333 # bus problem can only ever cost a log line — never block or fail the
334 # push. git is the source of truth; the bus is the replaceable component.
335 busEventHook = pkgs.writeShellScript "valley-bus-events" ''
336 # Managed by services.valley — project ref updates onto the event bus.
337 ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1
338 exit 0
339 '';
340
341 # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks:
342 # only ever installs, updates, or removes a store symlink — a hand-written
343 # hook of the same name is left alone.
344 busHookCommands = lib.concatMapStrings (
345 name:
346 let
347 bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus";
348 in
349 if cfg.bus.enable then
350 ''
351 bhook=${bhook}
352 if [ -L "$bhook" ]; then
353 case "$(readlink "$bhook")" in
354 /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;;
355 esac
356 elif [ ! -e "$bhook" ]; then
357 ln -s ${busEventHook} "$bhook"
358 fi
359 ''
360 else
361 ''
362 bhook=${bhook}
363 if [ -L "$bhook" ]; then
364 case "$(readlink "$bhook")" in
365 /nix/store/*) rm -f "$bhook" ;;
366 esac
367 fi
368 ''
369 ) repoNames;
370
371 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
372 # a store symlink — a hand-written hook of the same name is left alone.
373 mirrorHookCommands = lib.concatStrings (
374 lib.mapAttrsToList (
375 name: p:
376 let
377 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
378 in
379 if p.mirrors != [ ] then
380 ''
381 mhook=${mhook}
382 if [ -L "$mhook" ]; then
383 case "$(readlink "$mhook")" in
384 /nix/store/*) ln -sfn ${mirrorHook name p.mirrors} "$mhook" ;;
385 esac
386 elif [ ! -e "$mhook" ]; then
387 ln -s ${mirrorHook name p.mirrors} "$mhook"
388 fi
389 ''
390 else
391 ''
392 mhook=${mhook}
393 if [ -L "$mhook" ]; then
394 case "$(readlink "$mhook")" in
395 /nix/store/*) rm -f "$mhook" ;;
396 esac
397 fi
398 ''
399 ) gitProjects
400 );
401
402 # The environment variable carrying the pushing key's principal name.
403 # sshd sets it from the key's own authorized_keys entry; the pre-receive
404 # hook reads it. One name, honoured only because PermitUserEnvironment
405 # below names it.
406 principalEnv = "VALLEY_PRINCIPAL";
407
408 # Keys that name a principal. An entry written as a bare string names
409 # none, and renders exactly as it always did.
410 taggedKeys = lib.filter (k: !lib.isString k) cfg.authorizedKeys;
411
412 authorizedKeyLine =
413 k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}'';
414
415 # The program every project's pre-receive hook runs: the whole of the ref
416 # policy (valleyhook/), built by this flake.
417 valleyhookPackage = (import ./packages.nix { inherit pkgs lib; }).valleyhook;
418
419 # The grants declared by hand, in the format the compiler writes, so the
420 # hook reads one format whichever wrote it.
421 declaredGrants = pkgs.writeText "valley-grants" (
422 ''
423 # Declared in services.valley.grants — do not edit.
424 ''
425 + lib.concatMapStrings (principal: "request ${principal}\n") cfg.grants.request
426 );
427
428 # Every file the hook reads grants from. The compiled file is added to the
429 # declared one rather than replacing it, the same way the compiled keys
430 # are added to the declared keys: a compilation can only ever grant more.
431 grantFiles = [ declaredGrants ] ++ lib.optional cfg.identity.enable identityGrants;
432
433 # The keys a pushed attestation's signature is checked against: the ones
434 # a controller accepts evidence from. An attestation no controller here
435 # would accept cannot take a name in the create-only namespace. A host
436 # that names no such keys checks only what a note claims about its signer.
437 hookVerifiers = lib.optional (knownSigners != "") knownSigners;
438
439 # What a project declares about pushes, as valleyhook reads it: the
440 # protected refs and their writers, empty for a project that declares no
441 # protection, and the project's named grants.
442 pushPolicy =
443 name: p:
444 pkgs.writeText "valley-push-policy-${name}.json" (
445 builtins.toJSON {
446 refs = p.protection.refs or [ ];
447 writers = p.protection.writers or [ ];
448 grants = p.grants or { };
449 }
450 );
451
452 # The pre-receive hook: the one structural git invariant
453 # (design/architecture.md, design/contribute.md), which is what a push may
454 # write. It is installed on every project the host serves. Replacement
455 # refs, notes and the valley's own namespace take no push; a symbolic
456 # ref takes none; topic branches are open; an attestation ref may only be
457 # created, and only holding what its name says; an integration request
458 # takes the request grant; every other ref, tags included, takes a named
459 # grant of the project; and a protected ref also takes a declared writer.
460 # All policy beyond this lives in the integrator.
461 #
462 # The rules are valleyhook's, in Go, and this script is only how git
463 # reaches it. It hands over what the policy is a function of: the pushing
464 # principal, the project's declared push policy, the grants, the keys an
465 # attestation is checked against, and the hook a project composes after
466 # it, if it declares one.
467 #
468 # A declaration usually names no writer at all, and then the protected
469 # refs take no push from anyone. That is the norm, not a
470 # misconfiguration: the integrator writes the ref locally, and a local
471 # write is not a push.
472 #
473 # Pushes arrive over SSH as one shared git user, so the unix account
474 # behind a push says nothing about who pushed. The principal comes from
475 # the key instead: services.valley.authorizedKeys tags each key's
476 # authorized_keys entry, sshd puts that tag in the environment of the
477 # receive-pack this hook runs under, and an untagged key has no principal
478 # at all. The client cannot supply the tag itself: the assertions below
479 # hold sshd to accepting no client environment that could carry it, and
480 # valley-init refuses a git user whose own environment file could.
481 #
482 # This governs pushes, which is every write that crosses the host
483 # boundary. It does not govern writes made on the host: the integrator
484 # updates refs locally, as could anyone holding the git user's shell.
485 # Local access is the host's own boundary, not this hook's.
486 protectHook =
487 name: p:
488 pkgs.writeShellScript "valley-protect-${name}" ''
489 # Managed by services.valley — do not edit.
490 exec ${valleyhookPackage}/bin/valleyhook pre-receive \
491 --project ${lib.escapeShellArg name} \
492 --policy ${pushPolicy name p} \
493 ${lib.concatMapStringsSep " " (f: "--grants ${f}") grantFiles} \
494 ${lib.concatMapStringsSep " " (f: "--known-signers ${f}") hookVerifiers} \
495 ${lib.optionalString (cfg.extraPreReceive ? ${name}) "--then ${cfg.extraPreReceive.${name}}"} \
496 --principal="''${${principalEnv}:-}"
497 '';
498
499 # Per-project pre-receive wiring, on every project the host serves. A
500 # hook that is not this module's is a hook that would run instead of the
501 # push policy, so valley-init refuses to leave one in place: it says so,
502 # and the activation fails once everything else is wired. The one
503 # exception is a hook identical to the one the project composes after the
504 # policy (services.valley.extraPreReceive), which is checked byte for byte
505 # and then replaced, since the managed hook runs it. A store symlink is
506 # this module's, whichever store path it names, and is re-pointed.
507 #
508 # core.hooksPath moves where git looks for hooks at all, from any scope
509 # the git user reads — the repository's config, the user's, the system's,
510 # or a file one of them includes. A repository whose hooks path is set is
511 # refused the same way, with no exception.
512 protectHookCommands = lib.concatStrings (
513 lib.mapAttrsToList (name: p: ''
514 served=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
515 phook="$served/hooks/pre-receive"
516 managed=${protectHook name p}
517 composed=${lib.escapeShellArg (toString (cfg.extraPreReceive.${name} or ""))}
518 if [ -L "$phook" ] && [[ "$(readlink "$phook")" == /nix/store/* ]]; then
519 ln -sfn "$managed" "$phook"
520 elif [ ! -e "$phook" ] && [ ! -L "$phook" ]; then
521 ln -s "$managed" "$phook"
522 elif [ -n "$composed" ] && [ -f "$phook" ] && cmp -s "$phook" "$composed"; then
523 echo "valley-init: ${name}: the pre-receive hook in $served is the one services.valley.extraPreReceive.${name} composes after the push policy, so the managed hook replaces it and runs it" >&2
524 ln -sfn "$managed" "$phook"
525 else
526 echo "valley-init: ${name}: $phook is a pre-receive hook this module did not write, and git would run it instead of the push policy. Declare it as services.valley.extraPreReceive.${name} to run it after the policy, or remove it." >&2
527 conflicts=1
528 fi
529 hooks_path="$(git -C "$served" config --get core.hooksPath)" || hooks_path=""
530 if [ -n "$hooks_path" ]; then
531 echo "valley-init: ${name}: core.hooksPath is $hooks_path for $served, so git would look for hooks there and the push policy would not run. Remove the setting." >&2
532 conflicts=1
533 fi
534 '') gitProjects
535 );
536
537 # sshd's patterns, for the assertions that hold it to accepting no client
538 # environment that could carry the principal. `*` and `?` are the only
539 # wildcards an AcceptEnv pattern has.
540 sshPatternMatches =
541 pattern: name:
542 builtins.match (lib.concatMapStrings (
543 c:
544 if c == "*" then
545 ".*"
546 else if c == "?" then
547 "."
548 else if builtins.match "[A-Za-z0-9_]" c != null then
549 c
550 else
551 "\\${c}"
552 ) (lib.stringToCharacters pattern)) name != null;
553
554 # A refname glob as the declaration writes one, where `*` crosses path
555 # separators (schema/valley.cue).
556 refPatternMatches =
557 pattern: ref:
558 builtins.match (lib.concatMapStrings (
559 c:
560 if c == "*" then
561 ".*"
562 else if builtins.match "[A-Za-z0-9/_-]" c != null then
563 c
564 else
565 "\\${c}"
566 ) (lib.stringToCharacters pattern)) ref != null;
567
568 # Every value sshd is given for one keyword, from the settings and from
569 # any line of extraConfig, in any case: sshd keywords are not
570 # case-sensitive.
571 sshdValues =
572 keyword:
573 let
574 settings = config.services.openssh.settings;
575 fromSettings = lib.concatMap (
576 k:
577 let
578 v = settings.${k};
579 word = x: if lib.isBool x then (if x then "yes" else "no") else toString x;
580 in
581 if lib.isList v then map word v else lib.splitString " " (word v)
582 ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings));
583 fromExtra = lib.concatMap (
584 line:
585 let
586 m = builtins.match "[[:space:]]*${lib.toLower keyword}[[:space:]]+(.*)" (lib.toLower line);
587 in
588 if m == null then [ ] else lib.filter (v: v != "") (lib.splitString " " (lib.head m))
589 ) (lib.splitString "\n" config.services.openssh.extraConfig);
590 in
591 fromSettings ++ fromExtra;
592
593 # Every key line the git user's declared authorized_keys holds, from this
594 # module and from any other, with the principal its tag names ("" for
595 # none) and the key itself.
596 declaredKeyEntries = lib.concatMap (
597 line:
598 let
599 key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line;
600 tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line;
601 in
602 lib.optional (key != null) {
603 key = lib.elemAt key 3;
604 principal = if tag == null then "" else lib.head tag;
605 }
606 ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys;
607
608 # Keys declared more than once under different tags. sshd authorizes a
609 # key by the first entry that names it, so which principal such a key
610 # pushes as depends on file order; the assertion below refuses it.
611 conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) (
612 lib.groupBy (e: e.key) declaredKeyEntries
613 );
614
615 # The declared key lines, for the compiler: a compiled key that is also
616 # declared under another tag is refused there, for the same reason.
617 declaredKeysFile = pkgs.writeText "valley-declared-keys" (
618 lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys
619 );
620in
621{
622 options.services.valley = {
623 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
624
625 user = lib.mkOption {
626 type = lib.types.str;
627 default = "git";
628 description = "System user that owns the repositories and accepts SSH pushes.";
629 };
630
631 group = lib.mkOption {
632 type = lib.types.str;
633 default = "git";
634 description = "Primary group of the valley git user.";
635 };
636
637 dataDir = lib.mkOption {
638 type = lib.types.path;
639 default = "/srv/git";
640 example = "/mnt/git";
641 description = ''
642 Directory holding the bare repositories, one `<name>.git` per
643 project declared in {option}`services.valley.config`. Also the git
644 user's home, so clone URLs are relative to it (`git@host:name.git`).
645 Consumers typically point it at a dedicated dataset.
646 '';
647 };
648
649 authorizedKeys = lib.mkOption {
650 type = lib.types.listOf (
651 lib.types.either lib.types.str (
652 lib.types.submodule {
653 options = {
654 key = lib.mkOption {
655 type = lib.types.str;
656 description = "The SSH public key, as it would appear in `authorized_keys`.";
657 };
658
659 principal = lib.mkOption {
660 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
661 example = "integrator";
662 description = ''
663 Name of the principal this key acts as. Every push made
664 with the key carries the name, and the pre-receive hook
665 decides what the name may write: from the project's
666 `protection` block and named grants in
667 {option}`services.valley.config`, and from the grants the
668 name holds ({option}`services.valley.grants`, and the
669 registry's when it is compiled). Nothing else uses it.
670 A key is declared once: the same key under two tags, or
671 tagged and untagged, is refused.
672 '';
673 };
674 };
675 }
676 )
677 );
678 default = [ ];
679 example = lib.literalExpression ''
680 [
681 "ssh-ed25519 AAAA… someone@somewhere"
682 {
683 principal = "integrator";
684 key = "ssh-ed25519 AAAA… integrator";
685 }
686 ]
687 '';
688 description = ''
689 SSH public keys allowed to push/fetch as the git user. Access is
690 host-level by design: every key can reach every project.
691
692 A key written as a plain string is anonymous — it can push, and it
693 can write nothing protected. A key written as an attribute set
694 names the principal it acts as, which is the only thing that can
695 tell one pusher from another: pushes arrive as the shared git user,
696 so identity has to ride on the key.
697
698 Which refs a principal may write is declared, not an option here:
699 it is a statement about what the host serves, and lives in the
700 project's `protection` block in
701 {option}`services.valley.config`. Binding a name to keys is the
702 machine half — the hand-written form of what the identity registry
703 compiles (dcr-b87f6e8).
704
705 With {option}`services.valley.identity.enable` on, the compiled
706 keys are added to what sshd reads and the keys here stay
707 authorized beside them. The list is therefore the way back in when
708 a compilation is wrong or has not happened yet, and it is never
709 empty.
710 '';
711 };
712
713 extraPreReceive = lib.mkOption {
714 type = lib.types.attrsOf lib.types.pathInStore;
715 default = { };
716 example = lib.literalExpression ''
717 {
718 cosmo = pkgs.writeShellScript "cosmo-pre-receive" ;
719 }
720 '';
721 description = ''
722 A further pre-receive hook per project, run after the push policy
723 accepts a push, with the same input. It can refuse what the policy
724 accepts and never accept what the policy refuses.
725
726 This is the one way to compose a hook with the managed one. A
727 pre-receive hook the module did not write fails valley-init,
728 because git would run it instead of the policy. A hook that is
729 byte-for-byte the one declared here is the exception: valley-init
730 replaces it with the managed hook, which runs it. The value is a
731 store path, so what runs is exactly what was declared.
732 '';
733 };
734
735 # Grants held by hand. The registry names who holds a grant
736 # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written
737 # form of what it compiles, beside it the way the declared keys sit
738 # beside the compiled ones.
739 grants = {
740 request = lib.mkOption {
741 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
742 default = [ ];
743 example = [ "operator" ];
744 description = ''
745 Principals holding the request grant: the ones whose pushes may
746 file, replace and withdraw an integration request
747 (`refs/the-valley/integration-requests/*`) on a protected
748 project. The pre-receive hook refuses every other write to that
749 namespace, so a principal named neither here nor in the
750 registry cannot ask for anything to land.
751
752 The grant rides on push. Only a key sshd admits reaches the hook,
753 so a principal named here also needs a key, declared in
754 {option}`services.valley.authorizedKeys` or compiled from the
755 registry.
756
757 With {option}`services.valley.identity.enable` on, the holders
758 the registry names are added to these, and a compiled file can
759 only ever add. The list is therefore how a host grants request
760 before its registry does — including to the operator who has to
761 file the registry change that grants it.
762 '';
763 };
764 };
765
766 config = lib.mkOption {
767 type = lib.types.path;
768 example = lib.literalExpression "./valley.cue";
769 description = ''
770 Path to the host's CUE declaration (`package valley`) — the
771 canonical statement of what this valley host serves, validated
772 against the shipped schema at build time. This is the single domain
773 input: projects, their push mirrors, and the backup policy are
774 declared here, never as Nix options.
775 '';
776 };
777
778 # The event bus. Machine options, not domain: whether this machine runs
779 # a bus, where it listens, and where its storage lives. What gets
780 # published onto it is defined portably in ../schema/events.cue.
781 bus = {
782 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
783
784 listen = lib.mkOption {
785 type = lib.types.str;
786 default = "127.0.0.1:4222";
787 example = "100.100.1.7:4222";
788 description = ''
789 Address the bus listens on, `host:port`. Localhost by default:
790 nothing off the host can reach the bus until the consumer widens
791 this deliberately — e.g. to the host's tailnet address once a
792 remote `valley tail` wants in. Local publishers (the ref-updated
793 hook) connect to this same address, so it must be reachable from
794 the host itself.
795 '';
796 };
797
798 storeDir = lib.mkOption {
799 type = lib.types.path;
800 default = "${cfg.dataDir}/.bus";
801 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
802 description = ''
803 Directory holding the JetStream file storage. The default lives
804 under {option}`services.valley.dataDir`; it can never collide
805 with a repository because project names must start with an
806 alphanumeric. The stream is a projection of git, rebuildable
807 with `valley replay` — losing this directory costs one replay.
808 '';
809 };
810 };
811
812 # The integrator (design/roadmap.md, Phase 3): the controller that
813 # lands a change once its evidence still transfers to the current tip.
814 # Machine options only — whether this host runs controllers, who they
815 # are, and how often they look. Which projects get one is not an option
816 # either: it follows from which projects the declaration protects,
817 # because a protected ref is exactly what a controller exists to write.
818 integrator = {
819 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
820
821 user = lib.mkOption {
822 type = lib.types.str;
823 default = "valley-integrator";
824 description = ''
825 System user the controllers run as. Deliberately not
826 {option}`services.valley.user`: one unix identity per service is
827 the split bd-500adf7 asks for, and this service begins it.
828
829 The account exists only to write the repositories it serves. It
830 gets no shell and no SSH key, and its primary group is
831 {option}`services.valley.group`, which is the whole of its
832 permission model: {option}`services.valley.dataDir` is already
833 group-readable, and each served repository is made group-shared
834 (group write, setgid directories) so a controller can write
835 refs, objects, and git's worktree metadata. Nothing else on the
836 host belongs to that group, and the bus's store directory (mode
837 0700) stays out of reach.
838
839 The key and signers files are the consumer's to provision; both
840 must be readable by this user.
841 '';
842 };
843
844 signingKeyFile = lib.mkOption {
845 type = lib.types.nullOr lib.types.path;
846 default = null;
847 example = "/run/agenix/valley-integrator-key";
848 description = ''
849 ed25519 private key the controllers sign their transfer
850 statements with. A runtime path the consumer provisions (e.g.
851 agenix), never a store path — the store is world-readable.
852 '';
853 };
854
855 knownSignersFile = lib.mkOption {
856 type = lib.types.nullOr lib.types.path;
857 default = null;
858 example = "/var/lib/valley-instance/known_signers";
859 description = ''
860 File of verifier keys whose attestations count, one per line, in
861 `attest key` format. This is the identity registry's interim
862 compilation (dcr-b87f6e8), supplied directly for a host that does
863 not compile one: turning on
864 {option}`services.valley.identity.enable` renders the same file
865 from the registry, and then this option must be left unset.
866 Evidence signed by nobody in it does not transfer, which a
867 controller reports per check rather than treating as a forgery.
868 '';
869 };
870
871 signingName = lib.mkOption {
872 type = lib.types.nullOr lib.types.str;
873 default = null;
874 example = "integrator";
875 description = ''
876 The name a controller's transfer statements are signed under.
877 Unset leaves the binary's own default, which is this host's
878 attestations name — the machine signing as itself.
879
880 Set it to the name the identity registry publishes the
881 integrator's key under. The note format's key hash binds the name
882 to the key (dcr-de9d996), so a controller signing under one name
883 while the registry publishes it under another produces notes no
884 verifier can find a key for.
885 '';
886 };
887
888 instanceProject = lib.mkOption {
889 type = lib.types.nullOr lib.types.str;
890 default = null;
891 example = "qinling";
892 description = ''
893 The project whose served repository carries the group's floor —
894 the instance policy layer every controller on this host composes
895 against. A controller reads it from `policy/instance/` in that
896 bare repository's integrated tip, and nothing is materialized on
897 disk in between. It is also where the identity registry is read
898 from, for the same reason and at the same altitude: both are the
899 instance's, so a host serving that repository already holds the
900 authoritative copy.
901
902 The floor is the instance repository's, read at the tip that has
903 been integrated (dcr-f41f718); the instance repository is the
904 group's own (dcr-b87f6e8). A host serving it is therefore already
905 holding the authoritative copy.
906
907 What follows is a property of that design, and worth knowing
908 before editing a floor. A change to it takes effect at the first
909 pass after it lands on that ref, and never before. An edit in a
910 branch, in a worktree, or in an integration request that has not
911 been integrated governs nothing. There is no refresh to trigger
912 and no staleness to wait out: landing is the whole of publishing
913 a floor.
914
915 The project has to declare protection covering refs/heads/main,
916 and the registry's ref when the identity compiler is on. Both
917 are read from that tip, so a ref any push-capable key could move
918 would hand every key the floor and the registry.
919
920 Every controller on the host reads the same repository, the
921 controller serving that repository included. Both layers are
922 resolved from the controller's own side — this one, and the
923 project's `policy/project/` at the target tip — so a change can
924 never supply the policy that gates it (bd-eaefe82).
925
926 Those two directories are the convention, and the module states
927 neither: a controller takes each layer from the place the
928 integrator defaults to, so a host declaration that says nothing
929 about policy gets the layout the worked example lays out
930 (dcr-f41f718).
931 '';
932 };
933
934 instancePolicy = lib.mkOption {
935 type = lib.types.nullOr lib.types.path;
936 default = null;
937 example = "/var/lib/valley-instance/policy/instance";
938 description = ''
939 Directory of `*.cue` files holding the instance policy layer, for
940 a host that serves no instance repository. It holds what
941 `policy/instance/` in the instance repository holds. Set this or
942 {option}`services.valley.integrator.instanceProject`, never both.
943
944 Keeping such a directory in step with the instance repository is
945 the consumer's to arrange, which is the reason to prefer the
946 project option wherever the host serves the repository.
947 '';
948 };
949
950 interval = lib.mkOption {
951 type = lib.types.str;
952 default = "15s";
953 example = "1m";
954 description = ''
955 How long a controller waits between passes. The integrator polls
956 deliberately: integration requests are durable in git, and the
957 controller level-triggers over those refs, so a lost event costs
958 one interval and nothing more.
959 '';
960 };
961 };
962
963 # The identity registry compiler (dcr-b87f6e8): the step between the
964 # instance's declared registry and the two gates that read what it
965 # compiles to. Machine options only — whether this host compiles, and
966 # from where. Who the principals are, what they hold and when their
967 # entries end is the registry's, and the registry is a document in the
968 # instance repository, never an option here.
969 identity = {
970 enable = lib.mkEnableOption ''
971 compiling the identity registry into what the gates check: the
972 verifier keys a controller accepts evidence from, and the git
973 user's authorized keys, both rendered from the instance
974 repository's integrated tip'';
975
976 ref = lib.mkOption {
977 type = lib.types.str;
978 default = "refs/heads/main";
979 description = ''
980 The ref of the instance repository whose tip carries the
981 registry. A registry edit takes effect at the first compilation
982 after it lands on this ref, and never before: an edit in a
983 branch, in a worktree, or in an integration request that has not
984 been integrated governs nothing.
985 '';
986 };
987
988 directory = lib.mkOption {
989 type = lib.types.str;
990 default = "identity";
991 description = ''
992 The registry's directory in that tip. It is a CUE package: the
993 directory is the enumeration, and every `*.cue` document
994 directly in it unifies into one registry.
995 '';
996 };
997
998 interval = lib.mkOption {
999 type = lib.types.str;
1000 default = "5m";
1001 example = "1m";
1002 description = ''
1003 How long between compilations. The compiler is level-triggered
1004 and idempotent — it renders the current tip and replaces an
1005 artifact only when its bytes changed — so a timer is the whole
1006 of the trigger, and a landed registry change takes effect within
1007 one interval.
1008 '';
1009 };
1010 };
1011
1012 # Machine integration for the declared backup policy. The declaration
1013 # states WHAT must hold (offsite backup, cadence, retention); these
1014 # options supply HOW on this machine — where the repository is and how
1015 # to authenticate. All are paths to files the consumer provisions
1016 # (e.g. agenix), required when the declaration enables backup. Point
1017 # them at runtime paths, never at files in the Nix store.
1018 backup = {
1019 repositoryFile = lib.mkOption {
1020 type = lib.types.nullOr lib.types.path;
1021 default = null;
1022 example = "/run/agenix/valley-restic-repo";
1023 description = ''
1024 File containing the restic repository URL, for the sftp target
1025 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
1026 '';
1027 };
1028
1029 passwordFile = lib.mkOption {
1030 type = lib.types.nullOr lib.types.path;
1031 default = null;
1032 example = "/run/agenix/valley-restic-password";
1033 description = ''
1034 File containing the restic repository encryption password.
1035 Losing it loses the backups — keep a copy somewhere that
1036 survives this host.
1037 '';
1038 };
1039
1040 sshKeyFile = lib.mkOption {
1041 type = lib.types.nullOr lib.types.path;
1042 default = null;
1043 example = "/run/agenix/valley-git-ssh-key";
1044 description = ''
1045 SSH private key that authenticates to the sftp target. The
1046 backup service runs as root, so any identity the target
1047 authorizes works — reusing the mirror key is fine.
1048 '';
1049 };
1050
1051 knownHostsFile = lib.mkOption {
1052 type = lib.types.nullOr lib.types.path;
1053 default = null;
1054 example = "/var/lib/valley-backup/known_hosts";
1055 description = ''
1056 known_hosts file pinning the sftp target's host key. Pin from
1057 the provider's published fingerprints, not a blind ssh-keyscan.
1058 '';
1059 };
1060 };
1061 };
1062
1063 config = lib.mkIf cfg.enable {
1064 assertions = [
1065 {
1066 assertion = cfg.authorizedKeys != [ ];
1067 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
1068 }
1069 ]
1070 ++ lib.optionals backupEnabled (
1071 lib.mapAttrsToList (name: what: {
1072 assertion = cfg.backup.${name} != null;
1073 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).";
1074 }) backupSecretOptions
1075 )
1076 ++ lib.optionals cfg.integrator.enable (
1077 lib.mapAttrsToList (name: what: {
1078 assertion = cfg.integrator.${name} != null;
1079 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
1080 }) integratorPathOptions
1081 ++ [
1082 {
1083 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
1084 message = "exactly one of services.valley.integrator.instanceProject and services.valley.integrator.instancePolicy must be set: the floor is read from the instance repository this host serves, or supplied as a directory for a host that serves none, and two sources for one layer is a question about which one won.";
1085 }
1086 {
1087 assertion =
1088 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
1089 message = "services.valley.integrator.instanceProject names ${toString cfg.integrator.instanceProject}, which this host declaration does not serve: the floor is read from that repository's tip, so the host has to hold it.";
1090 }
1091 {
1092 assertion = cfg.integrator.user != cfg.user;
1093 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
1094 }
1095 {
1096 assertion = integratedProjects != { };
1097 message = "services.valley.integrator.enable is on and the host declaration protects no project — a controller only ever serves a protected target, so this would render no service at all.";
1098 }
1099 ]
1100 )
1101 ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) (
1102 let
1103 name = cfg.integrator.instanceProject;
1104 protected = gitProjects.${name}.protection.refs or [ ];
1105 read =
1106 lib.optional cfg.integrator.enable "refs/heads/main" ++ lib.optional cfg.identity.enable cfg.identity.ref;
1107 in
1108 map (ref: {
1109 assertion = lib.any (pattern: refPatternMatches pattern ref) protected;
1110 message = "services.valley.integrator.instanceProject names ${name}, whose ${ref} is not protected: the floor and the registry are read from it, so any key that can push could rewrite them. Declare a protection block for ${name} covering ${ref}.";
1111 }) read
1112 )
1113 ++ [
1114 {
1115 assertion = !(lib.any (pattern: sshPatternMatches pattern principalEnv) (sshdValues "AcceptEnv"));
1116 message = "sshd accepts ${principalEnv} from the client (AcceptEnv): any key could name any principal. Remove the pattern that admits it.";
1117 }
1118 {
1119 assertion = !(lib.any (lib.hasPrefix "${principalEnv}=") (sshdValues "SetEnv"));
1120 message = "sshd sets ${principalEnv} itself (SetEnv), over the tag on every key. Remove it.";
1121 }
1122 {
1123 assertion = lib.all (v: lib.toLower v == "no" || v == principalEnv) (
1124 sshdValues "PermitUserEnvironment"
1125 );
1126 message = "sshd's PermitUserEnvironment must be no, or exactly ${principalEnv} where keys carry a principal tag: anything wider lets a key's entry or the git user's ~/.ssh/environment set variables the push policy does not expect.";
1127 }
1128 {
1129 assertion = conflictingKeys == { };
1130 message = "the git user's authorized keys name ${lib.concatStringsSep ", " (lib.attrNames conflictingKeys)} under more than one principal tag (an untagged entry counts as one): sshd authorizes a key by the first entry naming it, so which principal it pushes as would depend on file order. Declare each key once.";
1131 }
1132 {
1133 assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ];
1134 message = "users.users.${cfg.user}.openssh.authorizedKeys.keyFiles must be empty: the git user's keys carry the principal tag the push policy reads, so they are declared in services.valley.authorizedKeys, where their tags can be checked.";
1135 }
1136 ]
1137 ++ lib.optionals cfg.identity.enable [
1138 {
1139 assertion = cfg.integrator.instanceProject != null;
1140 message = "services.valley.integrator.instanceProject must be set: the identity registry is read from the served instance repository's integrated tip, so the host has to hold that repository.";
1141 }
1142 {
1143 assertion = cfg.integrator.knownSignersFile == null;
1144 message = "services.valley.integrator.knownSignersFile must be unset: the registry compiles that file (${identityKnownSigners}), and two sources for one file is a question about which one won.";
1145 }
1146 ];
1147
1148 users.groups.${cfg.group} = { };
1149
1150 users.users.${cfg.user} = {
1151 isSystemUser = true;
1152 group = cfg.group;
1153 home = cfg.dataDir;
1154 # git-shell only allows git-upload-pack/git-receive-pack/git-upload-archive;
1155 # interactive logins are rejected (no ~/git-shell-commands).
1156 shell = "${pkgs.git}/bin/git-shell";
1157 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
1158 };
1159
1160 # The integrator's own account. No shell, no keys, no home of its own
1161 # beyond the state directory its units get; the git group is the only
1162 # thing it holds.
1163 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
1164 isSystemUser = true;
1165 group = cfg.group;
1166 home = "/var/lib/valley-integrator";
1167 description = "The valley integrator";
1168 };
1169
1170 services.openssh.enable = lib.mkDefault true;
1171
1172 # Honour the principal tag on a key's entry, and nothing else: the
1173 # pattern-list form admits that one variable name. Rendered only once a
1174 # key names a principal — declared here, or compiled from the registry
1175 # — so a host with none keeps the sshd config it had.
1176 services.openssh.settings = lib.optionalAttrs (taggedKeys != [ ] || cfg.identity.enable) {
1177 PermitUserEnvironment = principalEnv;
1178 };
1179
1180 # The git user's key files, named in its Match block so no other file
1181 # can authorize a key for it. The declared keys come first, and they stay
1182 # authorized beside the compiled ones: a compiled file can only ever
1183 # add, so an empty or missing one — a first boot before the first
1184 # compilation, a registry that lost an entry, a bug here — cannot take
1185 # the git user's access away. Which is the point: the assertion above
1186 # keeps at least one key declared, and that key is the way back in.
1187 #
1188 # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys
1189 # under its home is not read, and no AuthorizedKeysCommand runs, so every
1190 # entry a pusher can arrive through carries the tag this module or the
1191 # compiler wrote, and the assertions and the compiler hold those to one
1192 # tag per key.
1193 #
1194 # Belt-and-braces hardening for the git user beside it. The trailing
1195 # `Match All` closes the block so it can't scope directives appended to
1196 # sshd_config after this snippet.
1197 services.openssh.extraConfig = ''
1198 Match User ${cfg.user}
1199 AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"}
1200 AuthorizedKeysCommand none
1201 AllowTcpForwarding no
1202 AllowAgentForwarding no
1203 X11Forwarding no
1204 PermitTunnel no
1205 Match All
1206 '';
1207
1208 # git-shell spawns git-receive-pack/git-upload-pack from PATH
1209 environment.systemPackages = [ pkgs.git ];
1210
1211 systemd.tmpfiles.rules = [
1212 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
1213 ]
1214 ++ lib.optionals cfg.bus.enable [
1215 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
1216 ];
1217
1218 # The bus itself. It runs as the git user — the store directory lives in
1219 # that user's data — but the sandbox is what confines it: the unit can
1220 # write nowhere except its store directory.
1221 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
1222 description = "The valley event bus (NATS JetStream)";
1223 wantedBy = [ "multi-user.target" ];
1224 after = [
1225 "network.target"
1226 "systemd-tmpfiles-setup.service"
1227 ];
1228 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
1229 serviceConfig = {
1230 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
1231 Restart = "on-failure";
1232 User = cfg.user;
1233 Group = cfg.group;
1234 LimitNOFILE = 65536;
1235 NoNewPrivileges = true;
1236 ProtectSystem = "strict";
1237 ReadWritePaths = [ cfg.bus.storeDir ];
1238 ProtectHome = true;
1239 PrivateTmp = true;
1240 PrivateDevices = true;
1241 ProtectClock = true;
1242 ProtectHostname = true;
1243 ProtectKernelLogs = true;
1244 ProtectKernelModules = true;
1245 ProtectKernelTunables = true;
1246 ProtectControlGroups = true;
1247 ProtectProc = "invisible";
1248 RestrictAddressFamilies = [
1249 "AF_INET"
1250 "AF_INET6"
1251 "AF_UNIX"
1252 ];
1253 RestrictNamespaces = true;
1254 RestrictRealtime = true;
1255 RestrictSUIDSGID = true;
1256 LockPersonality = true;
1257 CapabilityBoundingSet = "";
1258 SystemCallArchitectures = "native";
1259 SystemCallFilter = [ "@system-service" ];
1260 UMask = "0077";
1261 };
1262 };
1263
1264 # The stream is config, not state: (re)created idempotently on every
1265 # boot, capturing everything under valley.>. An existing stream — and
1266 # the events in it — is left untouched.
1267 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
1268 description = "Create the valley event stream";
1269 wantedBy = [ "multi-user.target" ];
1270 requires = [ "valley-bus.service" ];
1271 after = [ "valley-bus.service" ];
1272 serviceConfig = {
1273 Type = "oneshot";
1274 User = cfg.user;
1275 Group = cfg.group;
1276 };
1277 path = [ pkgs.natscli ];
1278 script = ''
1279 # The server needs a moment to accept connections after startup.
1280 for _ in $(seq 1 50); do
1281 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
1282 sleep 0.2
1283 done
1284 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
1285 nats --server ${busUrl} stream add valley \
1286 --subjects 'valley.>' --storage file --defaults
1287 fi
1288 '';
1289 };
1290
1291 # Create missing bare repos and (re)wire the managed hooks on every
1292 # activation where the declaration changed.
1293 systemd.services.valley-init = {
1294 description = "Initialize the valley host's bare git repositories";
1295 wantedBy = [ "multi-user.target" ];
1296 after = [ "systemd-tmpfiles-setup.service" ];
1297 unitConfig.RequiresMountsFor = cfg.dataDir;
1298 serviceConfig = {
1299 Type = "oneshot";
1300 User = cfg.user;
1301 Group = cfg.group;
1302 };
1303 path = [
1304 pkgs.git
1305 pkgs.diffutils
1306 ];
1307 # Everything init can wire is wired before it fails. A conflict in one
1308 # repository is reported, the rest of the host is still converged,
1309 # and only then does the unit fail, so the activation fails loudly
1310 # without leaving another repository's hook out of date.
1311 script = ''
1312 conflicts=0
1313
1314 # sshd reads the git user's ~/.ssh/environment for the principal
1315 # variable, after the tag on the key, so a file there would make
1316 # every key push as whatever it names.
1317 if [ -e ${lib.escapeShellArg "${cfg.dataDir}/.ssh/environment"} ]; then
1318 echo "valley-init: ${cfg.dataDir}/.ssh/environment exists, and sshd would read ${principalEnv} from it for every key the git user authorizes. Remove it." >&2
1319 conflicts=1
1320 fi
1321
1322 repos=( ${lib.escapeShellArgs repoNames} )
1323 for name in "''${repos[@]}"; do
1324 repo="${cfg.dataDir}/$name.git"
1325 # Check HEAD rather than the directory itself so a pre-existing
1326 # empty directory still gets initialized.
1327 if [ ! -e "$repo/HEAD" ]; then
1328 git init --bare --initial-branch=main "$repo"
1329 fi
1330
1331 # Replacement refs make one object stand in for another wherever
1332 # git looks it up. No push may write one, and every reader that
1333 # makes a decision disables them, but a ref written before the
1334 # hook refused them is still there. It is reported on every
1335 # activation and left in place: what it is evidence of is the
1336 # operator's to read before anyone deletes it.
1337 replaced="$(git -C "$repo" for-each-ref --format=' %(refname) -> %(objectname)' refs/replace/)" || replaced=""
1338 if [ -n "$replaced" ]; then
1339 printf 'valley-init: %s holds replacement refs, which no push may write; inspect each and delete it with git update-ref -d:\n%s\n' "$repo" "$replaced" >&2
1340 fi
1341
1342 # Hook scaffolding: post-receive dispatches to post-receive.d/.
1343 # Only manage the hook if it is absent or already ours (a store
1344 # symlink) — a hand-written hook is left alone.
1345 mkdir -p "$repo/hooks/post-receive.d"
1346 hook="$repo/hooks/post-receive"
1347 if [ -L "$hook" ]; then
1348 case "$(readlink "$hook")" in
1349 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
1350 esac
1351 elif [ ! -e "$hook" ]; then
1352 ln -s ${postReceiveDispatch} "$hook"
1353 fi
1354 done
1355
1356 # Per-project push-mirror hooks.
1357 ${mirrorHookCommands}
1358
1359 # The one structural invariant, on every project the host serves.
1360 ${protectHookCommands}
1361
1362 # The ref-updated publisher hook, on every repo when the bus is on.
1363 ${busHookCommands}
1364
1365 # Group-shared repositories, on what the integrator serves.
1366 ${lib.optionalString cfg.integrator.enable integratorShareCommands}
1367
1368 if [ "$conflicts" -ne 0 ]; then
1369 echo "valley-init: refusing to report this host converged: the push policy is not what every repository runs" >&2
1370 exit 1
1371 fi
1372 '';
1373 };
1374
1375 # The registry compiler, on a timer. It renders the instance
1376 # repository's integrated tip into the two artifacts the gates read;
1377 # nothing else on the host writes them.
1378 #
1379 # It runs as the git user rather than under an identity of its own,
1380 # which is the one place this module steps back from the service split
1381 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
1382 # anyone but root or the account it authorizes, so the choice is the git
1383 # user or root, and the git user is the smaller grant.
1384 #
1385 # Level-triggered, like the rest: a compilation reads the current tip
1386 # and replaces an artifact only when its bytes changed, so re-running is
1387 # free and the timer needs no coordination with anything.
1388 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
1389 description = "Compile the valley identity registry into what the gates check";
1390 wantedBy = [ "multi-user.target" ];
1391 after = [ "valley-init.service" ];
1392 requires = [ "valley-init.service" ];
1393 unitConfig.RequiresMountsFor = cfg.dataDir;
1394 serviceConfig = {
1395 Type = "oneshot";
1396 ExecStart = identityCommand;
1397 User = cfg.user;
1398 Group = cfg.group;
1399 StateDirectory = identityStateName;
1400 # sshd walks every directory above an authorized-keys file and
1401 # refuses a group- or world-writable one, so the state directory is
1402 # 0755 deliberately rather than the 0700 a service's state usually
1403 # takes. Nothing secret lives in it: a registry is public keys.
1404 StateDirectoryMode = "0755";
1405 NoNewPrivileges = true;
1406 ProtectSystem = "strict";
1407 ReadWritePaths = [ identityStateDir ];
1408 ProtectHome = true;
1409 PrivateTmp = true;
1410 PrivateDevices = true;
1411 ProtectClock = true;
1412 ProtectHostname = true;
1413 ProtectKernelLogs = true;
1414 ProtectKernelModules = true;
1415 ProtectKernelTunables = true;
1416 ProtectControlGroups = true;
1417 ProtectProc = "invisible";
1418 RestrictAddressFamilies = [ "AF_UNIX" ];
1419 RestrictNamespaces = true;
1420 RestrictRealtime = true;
1421 RestrictSUIDSGID = true;
1422 LockPersonality = true;
1423 CapabilityBoundingSet = "";
1424 SystemCallArchitectures = "native";
1425 SystemCallFilter = [ "@system-service" ];
1426 UMask = "0022";
1427 };
1428 };
1429
1430 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
1431 description = "Re-compile the valley identity registry";
1432 wantedBy = [ "timers.target" ];
1433 timerConfig = {
1434 OnBootSec = "1m";
1435 OnUnitActiveSec = cfg.identity.interval;
1436 };
1437 };
1438
1439 # One controller per served project, as instances of a single template:
1440 # the units differ only in the repository they serve, which is the
1441 # instance name. `watch` rather than a timer firing `reconcile`: the
1442 # binary owns its poll loop and its interval, and a timer would be a
1443 # second cadence over the same level-triggered refs.
1444 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
1445 description = "The valley integrator for %i";
1446 after = [
1447 "network.target"
1448 "valley-init.service"
1449 ]
1450 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
1451 ++ lib.optional cfg.identity.enable "valley-identity.service";
1452 requires = [ "valley-init.service" ];
1453 # Wants, not requires: a controller reads the compiled signers file,
1454 # so it starts after the first compilation — but a compilation that
1455 # failed must not keep the controllers down. One that finds no file
1456 # says so and restarts, which is the same loop and a louder one.
1457 wants = lib.optional cfg.identity.enable "valley-identity.service";
1458 unitConfig.RequiresMountsFor = cfg.dataDir;
1459 # nix is not pinned, for the reason the integrator package does not
1460 # pin it: a check's input closure must be recomputed by the nix this
1461 # machine actually runs. Everything else a controller drives is
1462 # pinned inside the wrapper.
1463 path = [ config.nix.package ];
1464 # The repositories belong to the git user and the controller does
1465 # not, so git refuses to touch them as dubiously owned. The exception
1466 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
1467 # command-scope config, which is protected config, so safe.directory
1468 # is honoured from it — a repository-scoped setting would be ignored,
1469 # deliberately. And every git the controller drives is a child of
1470 # this unit, whether run by the integrator itself or by attest or the
1471 # deriver, so one environment covers all of them.
1472 #
1473 # One repository per instance: never a global gitconfig, never a
1474 # wildcard. Every other repository on the host stays refused. Linked
1475 # worktrees need no entry of their own — the controller creates them,
1476 # so it owns them, and git checks the worktree and its gitdir rather
1477 # than the repository they point at.
1478 #
1479 # TMPDIR is the same kind of wiring, for the same reason. A verdict
1480 # wants a checkout of the tip on disk, and the integrator asks for one
1481 # the ordinary way — a temporary directory, then a linked worktree in
1482 # it. The sandbox below leaves no writable temporary directory, so
1483 # every tick died on `could not create leading directories`. The
1484 # scratch belongs under the state directory the unit already has:
1485 # writable by construction, owned by this service, and gone when the
1486 # service's state is. Setting it in the environment rather than
1487 # teaching the binary a flag covers every process in the unit at once
1488 # — the integrator, attest, the deriver, and the git each of them runs
1489 # all read TMPDIR, and all of them want scratch in the same place.
1490 #
1491 # A second exception, for the instance repository. Every controller
1492 # reads the group's floor from that repository's tip, and it need not
1493 # be the project the controller serves — the controller for one
1494 # project reads the floor out of another project's repository, which
1495 # it likewise does not own. Without the exception git refuses it as
1496 # dubiously owned and every pass fails, exactly as it did for the
1497 # served repository. Two entries, both named; still never a wildcard.
1498 #
1499 # Reading needs no sandbox entry beside it. ProtectSystem=strict
1500 # leaves the filesystem readable and only takes write away, so the
1501 # ReadWritePaths list above stays the list of what may be written,
1502 # which is what makes it worth reading. What read does need is a
1503 # filesystem grant, and valley-init makes it: the instance repository
1504 # is group-readable whether or not it is one of the served projects.
1505 environment = {
1506 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
1507 GIT_CONFIG_KEY_0 = "safe.directory";
1508 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
1509 TMPDIR = integratorStateDir;
1510 }
1511 // lib.optionalAttrs (instanceRepo != null) {
1512 GIT_CONFIG_KEY_1 = "safe.directory";
1513 GIT_CONFIG_VALUE_1 = instanceRepo;
1514 };
1515 serviceConfig = {
1516 ExecStart = integratorCommand;
1517 Restart = "on-failure";
1518 RestartSec = "10s";
1519 User = cfg.integrator.user;
1520 Group = cfg.group;
1521 StateDirectory = integratorStateName;
1522 StateDirectoryMode = "0700";
1523 WorkingDirectory = integratorStateDir;
1524 NoNewPrivileges = true;
1525 ProtectSystem = "strict";
1526 # Everything the controller may write, named where a reader of the
1527 # unit meets it. Under ProtectSystem=strict the rest of the
1528 # filesystem is read-only, so this list is the whole of what the
1529 # service can touch, and it is worth being able to read it as such
1530 # rather than as the exceptions plus whatever else is implied.
1531 #
1532 # Its own directory: its state, and the scratch root TMPDIR names.
1533 # A declaration says it here rather than relying on the state
1534 # directory being read-write by virtue of being declared, which is
1535 # not something this unit found to be true.
1536 #
1537 # The one repository it serves, and the nix daemon's socket —
1538 # recomputing a closure means asking the daemon, and connecting to
1539 # a unix socket needs write access to it.
1540 ReadWritePaths = [
1541 integratorStateDir
1542 "${cfg.dataDir}/%i.git"
1543 "/nix/var/nix/daemon-socket"
1544 ];
1545 ProtectHome = true;
1546 PrivateTmp = true;
1547 PrivateDevices = true;
1548 ProtectClock = true;
1549 ProtectHostname = true;
1550 ProtectKernelLogs = true;
1551 ProtectKernelModules = true;
1552 ProtectKernelTunables = true;
1553 ProtectControlGroups = true;
1554 ProtectProc = "invisible";
1555 RestrictAddressFamilies = [
1556 "AF_INET"
1557 "AF_INET6"
1558 "AF_UNIX"
1559 ];
1560 RestrictNamespaces = true;
1561 RestrictRealtime = true;
1562 RestrictSUIDSGID = true;
1563 LockPersonality = true;
1564 CapabilityBoundingSet = "";
1565 SystemCallArchitectures = "native";
1566 SystemCallFilter = [ "@system-service" ];
1567 # Group write, not the bus unit's 0077: the git user owns these
1568 # repositories and has to stay able to write what a controller
1569 # leaves in them.
1570 UMask = "0002";
1571 };
1572 };
1573
1574 # wantedBy on a template unit enables nothing, so the instances the
1575 # declaration asks for are pulled in by name.
1576 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
1577 description = "The valley integrator's controllers";
1578 wantedBy = [ "multi-user.target" ];
1579 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
1580 };
1581
1582 # Offsite backup, rendered only when the declaration asks for it. The
1583 # declaration states the policy — that backup exists, its cadence and
1584 # retention; the services.valley.backup.* options supply the machine
1585 # half. Declaration absent or disabled ⇒ no restic config at all.
1586 services.restic.backups = lib.mkIf backupEnabled {
1587 valley = {
1588 initialize = true;
1589 repositoryFile = cfg.backup.repositoryFile;
1590 passwordFile = cfg.backup.passwordFile;
1591 paths = [ cfg.dataDir ];
1592 # The schema admits only the restic-sftp target today; a second
1593 # target would grow a dispatch here. The service runs as root:
1594 # authenticate with the supplied identity and only the pinned
1595 # host key. No prompt can be answered inside a systemd unit, so
1596 # BatchMode + strict host key checking turn a would-be hang into
1597 # an immediate error.
1598 extraOptions = [
1599 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
1600 ];
1601 timerConfig = backupTimer.${backupPolicy.cadence};
1602 pruneOpts = [
1603 "--keep-daily ${toString backupPolicy.retention.daily}"
1604 "--keep-weekly ${toString backupPolicy.retention.weekly}"
1605 "--keep-monthly ${toString backupPolicy.retention.monthly}"
1606 ];
1607 };
1608 };
1609 };
1610}