gunk-dev/the-valley

valley-host.nix

source7592d0291a10main's published tip history
75.3 KiB
1# The valley host installer: declarative bare-git hosting over SSH, driven
2# by a CUE host declaration (../schema/valley.cue).
3#
4# Layering: the CUE file owns the domain model — which projects exist, their
5# stores, their push mirrors, whether the host's data has offsite backup and
6# with what cadence and retention. This module owns machine integration
7# only: data directory, unix user, SSH keys, backup credentials. At build
8# time the CUE config is vetted against the shipped schema and exported to
9# JSON; an invalid config fails the system build with cue's error. Nix
10# never redefines the schema.
11#
12# Repos are only ever created, never deleted or overwritten — removing a
13# project (or disabling its git store) leaves the data on disk untouched.
14#
15# Identity is deliberately thin and host-level: one git user, git-shell,
16# key-only, Tailscale ACLs in front. Per-project *access* is not honestly
17# enforceable with this mechanism, so it is deliberately not an option
18# (.the-valley/decisions/dcr-0f5d9b1-cue-config-host-module.md). Per-project
19# *write protection* is, because the pre-receive hook below is a real
20# enforcement boundary and each key carries a principal name it can read
21# (.the-valley/decisions/dcr-b87f6e8-identity-is-a-governed-registry.md) —
22# so it is declared, in the project's `protection` block, and this module
23# only binds principal names to keys and 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. The
403 # git user's shell sets it from the tag on the authenticated key's own
404 # authorized_keys entry, and the pre-receive hook reads it.
405 principalEnv = "VALLEY_PRINCIPAL";
406
407 authorizedKeyLine =
408 k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}'';
409
410 # What valley-init does to converge the host: create missing repositories
411 # and (re)wire the managed hooks. Its last step refuses to report the host
412 # converged over anything that would run instead of the push policy.
413 valleyInitBody = ''
414 conflicts=0
415
416 repos=( ${lib.escapeShellArgs repoNames} )
417 for name in "''${repos[@]}"; do
418 repo="${cfg.dataDir}/$name.git"
419 # Check HEAD rather than the directory itself so a pre-existing
420 # empty directory still gets initialized.
421 if [ ! -e "$repo/HEAD" ]; then
422 git init --bare --initial-branch=main "$repo"
423 fi
424
425 # Replacement refs make one object stand in for another wherever
426 # git looks it up. No push may write one, and every reader that
427 # makes a decision disables them, but a ref written before the
428 # hook refused them is still there. It is reported on every
429 # activation and left in place: what it is evidence of is the
430 # operator's to read before anyone deletes it.
431 replaced="$(git -C "$repo" for-each-ref --format=' %(refname) -> %(objectname)' refs/replace/)" || replaced=""
432 if [ -n "$replaced" ]; then
433 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
434 fi
435
436 # Hook scaffolding: post-receive dispatches to post-receive.d/.
437 # Only manage the hook if it is absent or already ours (a store
438 # symlink) — a hand-written hook is left alone.
439 mkdir -p "$repo/hooks/post-receive.d"
440 hook="$repo/hooks/post-receive"
441 if [ -L "$hook" ]; then
442 case "$(readlink "$hook")" in
443 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
444 esac
445 elif [ ! -e "$hook" ]; then
446 ln -s ${postReceiveDispatch} "$hook"
447 fi
448 done
449
450 # Per-project push-mirror hooks.
451 ${mirrorHookCommands}
452
453 # The one structural invariant, on every project the host serves.
454 ${protectHookCommands}
455
456 # The ref-updated publisher hook, on every repo when the bus is on.
457 ${busHookCommands}
458
459 # Group-shared repositories, on what the integrator serves.
460 ${lib.optionalString cfg.integrator.enable integratorShareCommands}
461
462 if [ "$conflicts" -ne 0 ]; then
463 echo "valley-init: refusing to report this host converged: the push policy is not what every repository runs" >&2
464 exit 1
465 fi
466 '';
467
468 # The configuration a convergence is of: the init script itself, which
469 # names every hook and every policy file it wires. valley-init records it
470 # when it converges, and the git user's shell lets a push through only
471 # while the record names the configuration the shell was rendered with.
472 convergenceId = builtins.substring 0 32 (builtins.hashString "sha256" valleyInitBody);
473
474 # The record, in the git user's home: valley-init writes it, and nothing
475 # a session reaches can. A dot file never collides with a repository,
476 # because project names begin with an alphanumeric.
477 convergedRecord = "${cfg.dataDir}/.valley-converged";
478
479 # The operator's hold on pushes: while this file exists, the git user's
480 # shell refuses every push, whatever valley-init has recorded. valley-init
481 # never touches it, so a hold placed before a deploy outlasts the
482 # convergence and lasts until the operator removes it — the window a
483 # deploy's audits need.
484 pushHold = "${cfg.dataDir}/.valley-hold";
485
486 # The git user's login shell (valleyhook shell). sshd runs it for every
487 # session, and it names the key files sshd authorizes the git user's keys
488 # from, in sshd's order, so it can find the authenticated key's tag.
489 gitShell = pkgs.writeShellScriptBin "valley-git-shell" ''
490 exec ${valleyhookPackage}/bin/valleyhook shell \
491 --converged ${convergedRecord} \
492 --expect ${convergenceId} \
493 --hold ${pushHold} \
494 --authorized-keys /etc/ssh/authorized_keys.d/${cfg.user} ${
495 lib.optionalString cfg.identity.enable "--authorized-keys ${identityAuthorizedKeys}"
496 } \
497 -- "$@"
498 '';
499
500 # The program every project's pre-receive hook runs: the whole of the ref
501 # policy (valleyhook/), built by this flake.
502 valleyhookPackage = (import ./packages.nix { inherit pkgs lib; }).valleyhook;
503
504 # The grants declared by hand, in the format the compiler writes, so the
505 # hook reads one format whichever wrote it.
506 declaredGrants = pkgs.writeText "valley-grants" (
507 ''
508 # Declared in services.valley.grants — do not edit.
509 ''
510 + lib.concatMapStrings (principal: "request ${principal}\n") cfg.grants.request
511 );
512
513 # Every file the hook reads grants from. The compiled file is added to the
514 # declared one rather than replacing it, the same way the compiled keys
515 # are added to the declared keys: a compilation can only ever grant more.
516 grantFiles = [ declaredGrants ] ++ lib.optional cfg.identity.enable identityGrants;
517
518 # The keys a pushed attestation's signature is checked against: the ones
519 # a controller accepts evidence from. An attestation no controller here
520 # would accept cannot take a name in the create-only namespace, and a host
521 # that names no such keys accepts no attestation at all.
522 hookVerifiers = lib.optional (knownSigners != "") knownSigners;
523
524 # What a project declares about pushes, as valleyhook reads it: the
525 # protected refs and their writers, empty for a project that declares no
526 # protection, and the project's named grants.
527 pushPolicy =
528 name: p:
529 pkgs.writeText "valley-push-policy-${name}.json" (
530 builtins.toJSON {
531 refs = p.protection.refs or [ ];
532 writers = p.protection.writers or [ ];
533 grants = p.grants or { };
534 }
535 );
536
537 # The pre-receive hook: the one structural git invariant
538 # (design/architecture.md, design/contribute.md), which is what a push may
539 # write. It is installed on every project the host serves. Replacement
540 # refs, notes and the valley's own namespace take no push; a symbolic
541 # ref takes none; topic branches are open; an attestation ref may only be
542 # created, and only holding what its name says; an integration request
543 # takes the request grant; every other ref, tags included, takes a named
544 # grant of the project; and a protected ref also takes a declared writer.
545 # All policy beyond this lives in the integrator.
546 #
547 # The rules are valleyhook's, in Go, and this script is only how git
548 # reaches it. It hands over what the policy is a function of: the pushing
549 # principal, the project's declared push policy, the grants, the keys an
550 # attestation is checked against, and the hook a project composes after
551 # it, if it declares one.
552 #
553 # A declaration usually names no writer at all, and then the protected
554 # refs take no push from anyone. That is the norm, not a
555 # misconfiguration: the integrator writes the ref locally, and a local
556 # write is not a push.
557 #
558 # Pushes arrive over SSH as one shared git user, so the unix account
559 # behind a push says nothing about who pushed. The principal comes from
560 # the key instead: services.valley.authorizedKeys tags each key's
561 # authorized_keys entry, the git user's shell reads the tag off the entry
562 # of the key sshd authenticated and puts it in the environment of the
563 # receive-pack this hook runs under, and an untagged key has no principal
564 # at all. The client cannot supply the tag itself: the shell drops any it
565 # arrives with, and the assertions below hold sshd to offering no client
566 # environment that could carry it.
567 #
568 # This governs pushes, which is every write that crosses the host
569 # boundary. It does not govern writes made on the host: the integrator
570 # updates refs locally, as could anyone holding the git user's shell.
571 # Local access is the host's own boundary, not this hook's.
572 protectHook =
573 name: p:
574 pkgs.writeShellScript "valley-protect-${name}" ''
575 # Managed by services.valley — do not edit.
576 exec ${valleyhookPackage}/bin/valleyhook pre-receive \
577 --project ${lib.escapeShellArg name} \
578 --policy ${pushPolicy name p} \
579 ${lib.concatMapStringsSep " " (f: "--grants ${f}") grantFiles} \
580 ${lib.concatMapStringsSep " " (f: "--known-signers ${f}") hookVerifiers} \
581 ${lib.optionalString (cfg.extraPreReceive ? ${name}) "--then ${cfg.extraPreReceive.${name}}"} \
582 --principal="''${${principalEnv}:-}"
583 '';
584
585 # Per-project pre-receive wiring, on every project the host serves. A
586 # hook that is not this module's is a hook that would run instead of the
587 # push policy, so valley-init refuses to leave one in place: it says so,
588 # and the activation fails once everything else is wired. The one
589 # exception is a hook identical to the one the project composes after the
590 # policy (services.valley.extraPreReceive), which is checked byte for byte
591 # and then replaced, since the managed hook runs it. A store symlink is
592 # this module's, whichever store path it names, and is re-pointed.
593 #
594 # core.hooksPath moves where git looks for hooks at all, from any scope
595 # the git user reads — the repository's config, the user's, the system's,
596 # or a file one of them includes. A repository whose hooks path is set at
597 # all, to an empty value included, is refused the same way, with no
598 # exception.
599 protectHookCommands = lib.concatStrings (
600 lib.mapAttrsToList (name: p: ''
601 served=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
602 phook="$served/hooks/pre-receive"
603 managed=${protectHook name p}
604 composed=${lib.escapeShellArg (toString (cfg.extraPreReceive.${name} or ""))}
605 if [ -L "$phook" ] && [[ "$(readlink "$phook")" == /nix/store/* ]]; then
606 ln -sfn "$managed" "$phook"
607 elif [ ! -e "$phook" ] && [ ! -L "$phook" ]; then
608 ln -s "$managed" "$phook"
609 elif [ -n "$composed" ] && [ -f "$phook" ] && cmp -s "$phook" "$composed"; then
610 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
611 ln -sfn "$managed" "$phook"
612 else
613 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
614 conflicts=1
615 fi
616 # Exit status 1 is the one answer that means unset. A value, an
617 # empty one included — git then looks for hooks relative to where it
618 # runs — and a configuration git cannot read are all refused.
619 hooks_path="$(git -C "$served" config --get core.hooksPath)" && status=0 || status=$?
620 if [ "$status" -ne 1 ]; then
621 echo "valley-init: ${name}: core.hooksPath is set for $served (to '$hooks_path'), so git would look for hooks there and the push policy would not run. Remove the setting, wherever it is." >&2
622 conflicts=1
623 fi
624 '') gitProjects
625 );
626
627 # sshd's environment patterns, for the assertions that hold it to
628 # accepting no client environment the push boundary reads. `*` and `?` are
629 # the only wildcards an AcceptEnv pattern has, and a pattern is matched
630 # as written: variable names are case-sensitive.
631 sshPatternMatches =
632 pattern: name:
633 builtins.match (lib.concatMapStrings (
634 c:
635 if c == "*" then
636 ".*"
637 else if c == "?" then
638 "."
639 else if builtins.match "[A-Za-z0-9_]" c != null then
640 c
641 else
642 "\\${c}"
643 ) (lib.stringToCharacters pattern)) name != null;
644
645 # Whether some name beginning with prefix matches pattern: the pattern
646 # walked over the prefix, with the rest of the name free.
647 sshPatternMatchesSomeName =
648 pattern: prefix:
649 if prefix == "" then
650 true
651 else if pattern == "" then
652 false
653 else
654 let
655 c = builtins.substring 0 1 pattern;
656 rest = builtins.substring 1 (-1) pattern;
657 next = builtins.substring 1 (-1) prefix;
658 in
659 if c == "*" then
660 sshPatternMatchesSomeName rest prefix || sshPatternMatchesSomeName pattern next
661 else if c == "?" || c == builtins.substring 0 1 prefix then
662 sshPatternMatchesSomeName rest next
663 else
664 false;
665
666 # A variable the push boundary reads, and no client may supply: the
667 # principal, and anything git reads its configuration, hooks or objects
668 # from.
669 boundaryVariable = pattern: sshPatternMatches pattern principalEnv || sshPatternMatchesSomeName pattern "GIT_";
670
671 # A refname glob as the declaration writes one, where `*` crosses path
672 # separators (schema/valley.cue).
673 refPatternMatches =
674 pattern: ref:
675 builtins.match (lib.concatMapStrings (
676 c:
677 if c == "*" then
678 ".*"
679 else if builtins.match "[A-Za-z0-9/_-]" c != null then
680 c
681 else
682 "\\${c}"
683 ) (lib.stringToCharacters pattern)) ref != null;
684
685 # Every value sshd is given for one keyword, from the settings and from
686 # every line of extraConfig, inside a Match block or not. The keyword is
687 # matched in any case, as sshd matches it, with or without `=` after it;
688 # the values are kept as written, because sshd's patterns and variable
689 # names are case-sensitive. Values are split on any whitespace, tabs
690 # included, as sshd splits them. Quoting and escapes are not unpicked
691 # here: a value holding a quote or a backslash is refused below instead,
692 # because a reading that differed from sshd's would be a hole.
693 sshdValues =
694 keyword:
695 let
696 settings = config.services.openssh.settings;
697 word = x: if lib.isBool x then (if x then "yes" else "no") else toString x;
698 words = v: lib.filter (w: lib.isString w && w != "") (builtins.split "[[:space:]]+" v);
699 fromSettings = lib.concatMap (
700 k:
701 let
702 v = settings.${k};
703 in
704 if lib.isList v then lib.concatMap (x: words (word x)) v else words (word v)
705 ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings));
706 fromExtra = lib.concatMap (
707 line:
708 let
709 m = builtins.match "[[:space:]]*([A-Za-z]+)[[:space:]]*=?[[:space:]]*(.*)" line;
710 in
711 if m == null || lib.toLower (lib.head m) != lib.toLower keyword then
712 [ ]
713 else
714 words (lib.elemAt m 1)
715 ) (lib.splitString "\n" config.services.openssh.extraConfig);
716 in
717 fromSettings ++ fromExtra;
718
719 # Every key line the git user's declared authorized_keys holds, from this
720 # module and from any other, with the principal its tag names ("" for
721 # none) and the key itself.
722 declaredKeyEntries = lib.concatMap (
723 line:
724 let
725 key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line;
726 tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line;
727 in
728 lib.optional (key != null) {
729 key = lib.elemAt key 3;
730 principal = if tag == null then "" else lib.head tag;
731 }
732 ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys;
733
734 # Keys declared more than once under different tags. sshd authorizes a
735 # key by the first entry that names it, so which principal such a key
736 # pushes as depends on file order; the assertion below refuses it.
737 conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) (
738 lib.groupBy (e: e.key) declaredKeyEntries
739 );
740
741 # The declared key lines, for the compiler: a compiled key that is also
742 # declared under another tag is refused there, for the same reason.
743 declaredKeysFile = pkgs.writeText "valley-declared-keys" (
744 lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys
745 );
746in
747{
748 options.services.valley = {
749 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
750
751 user = lib.mkOption {
752 type = lib.types.str;
753 default = "git";
754 description = "System user that owns the repositories and accepts SSH pushes.";
755 };
756
757 group = lib.mkOption {
758 type = lib.types.str;
759 default = "git";
760 description = "Primary group of the valley git user.";
761 };
762
763 dataDir = lib.mkOption {
764 type = lib.types.path;
765 default = "/srv/git";
766 example = "/mnt/git";
767 description = ''
768 Directory holding the bare repositories, one `<name>.git` per
769 project declared in {option}`services.valley.config`. Also the git
770 user's home, so clone URLs are relative to it (`git@host:name.git`).
771 Consumers typically point it at a dedicated dataset.
772 '';
773 };
774
775 authorizedKeys = lib.mkOption {
776 type = lib.types.listOf (
777 lib.types.either lib.types.str (
778 lib.types.submodule {
779 options = {
780 key = lib.mkOption {
781 type = lib.types.str;
782 description = "The SSH public key, as it would appear in `authorized_keys`.";
783 };
784
785 principal = lib.mkOption {
786 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
787 example = "integrator";
788 description = ''
789 Name of the principal this key acts as. Every push made
790 with the key carries the name, and the pre-receive hook
791 decides what the name may write: from the project's
792 `protection` block and named grants in
793 {option}`services.valley.config`, and from the grants the
794 name holds ({option}`services.valley.grants`, and the
795 registry's when it is compiled). Nothing else uses it.
796 A key is declared once: the same key under two tags, or
797 tagged and untagged, is refused.
798 '';
799 };
800 };
801 }
802 )
803 );
804 default = [ ];
805 example = lib.literalExpression ''
806 [
807 "ssh-ed25519 AAAA… someone@somewhere"
808 {
809 principal = "integrator";
810 key = "ssh-ed25519 AAAA… integrator";
811 }
812 ]
813 '';
814 description = ''
815 SSH public keys allowed to push/fetch as the git user. Access is
816 host-level by design: every key can reach every project.
817
818 A key written as a plain string is anonymous — it can push, and it
819 can write nothing protected. A key written as an attribute set
820 names the principal it acts as, which is the only thing that can
821 tell one pusher from another: pushes arrive as the shared git user,
822 so identity has to ride on the key.
823
824 Which refs a principal may write is declared, not an option here:
825 it is a statement about what the host serves, and lives in the
826 project's `protection` block in
827 {option}`services.valley.config`. Binding a name to keys is the
828 machine half — the hand-written form of what the identity registry
829 compiles (dcr-b87f6e8).
830
831 With {option}`services.valley.identity.enable` on, the compiled
832 keys are added to what sshd reads and the keys here stay
833 authorized beside them. The list is therefore the way back in when
834 a compilation is wrong or has not happened yet, and it is never
835 empty.
836 '';
837 };
838
839 extraPreReceive = lib.mkOption {
840 type = lib.types.attrsOf lib.types.pathInStore;
841 default = { };
842 example = lib.literalExpression ''
843 {
844 cosmo = pkgs.writeShellScript "cosmo-pre-receive" ;
845 }
846 '';
847 description = ''
848 A further pre-receive hook per project, run after the push policy
849 accepts a push, with the same input. It can refuse what the policy
850 accepts and never accept what the policy refuses.
851
852 This is the one way to compose a hook with the managed one. A
853 pre-receive hook the module did not write fails valley-init,
854 because git would run it instead of the policy. A hook that is
855 byte-for-byte the one declared here is the exception: valley-init
856 replaces it with the managed hook, which runs it. The value is a
857 store path, so what runs is exactly what was declared.
858 '';
859 };
860
861 # Grants held by hand. The registry names who holds a grant
862 # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written
863 # form of what it compiles, beside it the way the declared keys sit
864 # beside the compiled ones.
865 grants = {
866 request = lib.mkOption {
867 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
868 default = [ ];
869 example = [ "operator" ];
870 description = ''
871 Principals holding the request grant: the ones whose pushes may
872 file, replace and withdraw an integration request
873 (`refs/the-valley/integration-requests/*`) on a protected
874 project. The pre-receive hook refuses every other write to that
875 namespace, so a principal named neither here nor in the
876 registry cannot ask for anything to land.
877
878 The grant rides on push. Only a key sshd admits reaches the hook,
879 so a principal named here also needs a key, declared in
880 {option}`services.valley.authorizedKeys` or compiled from the
881 registry.
882
883 With {option}`services.valley.identity.enable` on, the holders
884 the registry names are added to these, and a compiled file can
885 only ever add. The list is therefore how a host grants request
886 before its registry does — including to the operator who has to
887 file the registry change that grants it.
888 '';
889 };
890 };
891
892 config = lib.mkOption {
893 type = lib.types.path;
894 example = lib.literalExpression "./valley.cue";
895 description = ''
896 Path to the host's CUE declaration (`package valley`) — the
897 canonical statement of what this valley host serves, validated
898 against the shipped schema at build time. This is the single domain
899 input: projects, their push mirrors, and the backup policy are
900 declared here, never as Nix options.
901 '';
902 };
903
904 # The event bus. Machine options, not domain: whether this machine runs
905 # a bus, where it listens, and where its storage lives. What gets
906 # published onto it is defined portably in ../schema/events.cue.
907 bus = {
908 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
909
910 listen = lib.mkOption {
911 type = lib.types.str;
912 default = "127.0.0.1:4222";
913 example = "100.100.1.7:4222";
914 description = ''
915 Address the bus listens on, `host:port`. Localhost by default:
916 nothing off the host can reach the bus until the consumer widens
917 this deliberately — e.g. to the host's tailnet address once a
918 remote `valley tail` wants in. Local publishers (the ref-updated
919 hook) connect to this same address, so it must be reachable from
920 the host itself.
921 '';
922 };
923
924 storeDir = lib.mkOption {
925 type = lib.types.path;
926 default = "${cfg.dataDir}/.bus";
927 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
928 description = ''
929 Directory holding the JetStream file storage. The default lives
930 under {option}`services.valley.dataDir`; it can never collide
931 with a repository because project names must start with an
932 alphanumeric. The stream is a projection of git, rebuildable
933 with `valley replay` — losing this directory costs one replay.
934 '';
935 };
936 };
937
938 # The integrator (design/roadmap.md, Phase 3): the controller that
939 # lands a change once its evidence still transfers to the current tip.
940 # Machine options only — whether this host runs controllers, who they
941 # are, and how often they look. Which projects get one is not an option
942 # either: it follows from which projects the declaration protects,
943 # because a protected ref is exactly what a controller exists to write.
944 integrator = {
945 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
946
947 user = lib.mkOption {
948 type = lib.types.str;
949 default = "valley-integrator";
950 description = ''
951 System user the controllers run as. Deliberately not
952 {option}`services.valley.user`: one unix identity per service is
953 the split bd-500adf7 asks for, and this service begins it.
954
955 The account exists only to write the repositories it serves. It
956 gets no shell and no SSH key, and its primary group is
957 {option}`services.valley.group`, which is the whole of its
958 permission model: {option}`services.valley.dataDir` is already
959 group-readable, and each served repository is made group-shared
960 (group write, setgid directories) so a controller can write
961 refs, objects, and git's worktree metadata. Nothing else on the
962 host belongs to that group, and the bus's store directory (mode
963 0700) stays out of reach.
964
965 The key and signers files are the consumer's to provision; both
966 must be readable by this user.
967 '';
968 };
969
970 signingKeyFile = lib.mkOption {
971 type = lib.types.nullOr lib.types.path;
972 default = null;
973 example = "/run/agenix/valley-integrator-key";
974 description = ''
975 ed25519 private key the controllers sign their transfer
976 statements with. A runtime path the consumer provisions (e.g.
977 agenix), never a store path — the store is world-readable.
978 '';
979 };
980
981 knownSignersFile = lib.mkOption {
982 type = lib.types.nullOr lib.types.path;
983 default = null;
984 example = "/var/lib/valley-instance/known_signers";
985 description = ''
986 File of verifier keys whose attestations count, one per line, in
987 `attest key` format. This is the identity registry's interim
988 compilation (dcr-b87f6e8), supplied directly for a host that does
989 not compile one: turning on
990 {option}`services.valley.identity.enable` renders the same file
991 from the registry, and then this option must be left unset.
992 Evidence signed by nobody in it does not transfer, which a
993 controller reports per check rather than treating as a forgery.
994 '';
995 };
996
997 signingName = lib.mkOption {
998 type = lib.types.nullOr lib.types.str;
999 default = null;
1000 example = "integrator";
1001 description = ''
1002 The name a controller's transfer statements are signed under.
1003 Unset leaves the binary's own default, which is this host's
1004 attestations name — the machine signing as itself.
1005
1006 Set it to the name the identity registry publishes the
1007 integrator's key under. The note format's key hash binds the name
1008 to the key (dcr-de9d996), so a controller signing under one name
1009 while the registry publishes it under another produces notes no
1010 verifier can find a key for.
1011 '';
1012 };
1013
1014 instanceProject = lib.mkOption {
1015 type = lib.types.nullOr lib.types.str;
1016 default = null;
1017 example = "qinling";
1018 description = ''
1019 The project whose served repository carries the group's floor —
1020 the instance policy layer every controller on this host composes
1021 against. A controller reads it from `policy/instance/` in that
1022 bare repository's integrated tip, and nothing is materialized on
1023 disk in between. It is also where the identity registry is read
1024 from, for the same reason and at the same altitude: both are the
1025 instance's, so a host serving that repository already holds the
1026 authoritative copy.
1027
1028 The floor is the instance repository's, read at the tip that has
1029 been integrated (dcr-f41f718); the instance repository is the
1030 group's own (dcr-b87f6e8). A host serving it is therefore already
1031 holding the authoritative copy.
1032
1033 What follows is a property of that design, and worth knowing
1034 before editing a floor. A change to it takes effect at the first
1035 pass after it lands on that ref, and never before. An edit in a
1036 branch, in a worktree, or in an integration request that has not
1037 been integrated governs nothing. There is no refresh to trigger
1038 and no staleness to wait out: landing is the whole of publishing
1039 a floor.
1040
1041 The project has to declare protection covering refs/heads/main,
1042 and the registry's ref when the identity compiler is on. Both
1043 are read from that tip, so a ref any push-capable key could move
1044 would hand every key the floor and the registry.
1045
1046 Every controller on the host reads the same repository, the
1047 controller serving that repository included. Both layers are
1048 resolved from the controller's own side — this one, and the
1049 project's `policy/project/` at the target tip — so a change can
1050 never supply the policy that gates it (bd-eaefe82).
1051
1052 Those two directories are the convention, and the module states
1053 neither: a controller takes each layer from the place the
1054 integrator defaults to, so a host declaration that says nothing
1055 about policy gets the layout the worked example lays out
1056 (dcr-f41f718).
1057 '';
1058 };
1059
1060 instancePolicy = lib.mkOption {
1061 type = lib.types.nullOr lib.types.path;
1062 default = null;
1063 example = "/var/lib/valley-instance/policy/instance";
1064 description = ''
1065 Directory of `*.cue` files holding the instance policy layer, for
1066 a host that serves no instance repository. It holds what
1067 `policy/instance/` in the instance repository holds. Set this or
1068 {option}`services.valley.integrator.instanceProject`, never both.
1069
1070 Keeping such a directory in step with the instance repository is
1071 the consumer's to arrange, which is the reason to prefer the
1072 project option wherever the host serves the repository.
1073 '';
1074 };
1075
1076 interval = lib.mkOption {
1077 type = lib.types.str;
1078 default = "15s";
1079 example = "1m";
1080 description = ''
1081 How long a controller waits between passes. The integrator polls
1082 deliberately: integration requests are durable in git, and the
1083 controller level-triggers over those refs, so a lost event costs
1084 one interval and nothing more.
1085 '';
1086 };
1087 };
1088
1089 # The identity registry compiler (dcr-b87f6e8): the step between the
1090 # instance's declared registry and the two gates that read what it
1091 # compiles to. Machine options only — whether this host compiles, and
1092 # from where. Who the principals are, what they hold and when their
1093 # entries end is the registry's, and the registry is a document in the
1094 # instance repository, never an option here.
1095 identity = {
1096 enable = lib.mkEnableOption ''
1097 compiling the identity registry into what the gates check: the
1098 verifier keys a controller accepts evidence from, and the git
1099 user's authorized keys, both rendered from the instance
1100 repository's integrated tip'';
1101
1102 ref = lib.mkOption {
1103 type = lib.types.str;
1104 default = "refs/heads/main";
1105 description = ''
1106 The ref of the instance repository whose tip carries the
1107 registry. A registry edit takes effect at the first compilation
1108 after it lands on this ref, and never before: an edit in a
1109 branch, in a worktree, or in an integration request that has not
1110 been integrated governs nothing.
1111 '';
1112 };
1113
1114 directory = lib.mkOption {
1115 type = lib.types.str;
1116 default = "identity";
1117 description = ''
1118 The registry's directory in that tip. It is a CUE package: the
1119 directory is the enumeration, and every `*.cue` document
1120 directly in it unifies into one registry.
1121 '';
1122 };
1123
1124 interval = lib.mkOption {
1125 type = lib.types.str;
1126 default = "5m";
1127 example = "1m";
1128 description = ''
1129 How long between compilations. The compiler is level-triggered
1130 and idempotent — it renders the current tip and replaces an
1131 artifact only when its bytes changed — so a timer is the whole
1132 of the trigger, and a landed registry change takes effect within
1133 one interval.
1134 '';
1135 };
1136 };
1137
1138 # Machine integration for the declared backup policy. The declaration
1139 # states WHAT must hold (offsite backup, cadence, retention); these
1140 # options supply HOW on this machine — where the repository is and how
1141 # to authenticate. All are paths to files the consumer provisions
1142 # (e.g. agenix), required when the declaration enables backup. Point
1143 # them at runtime paths, never at files in the Nix store.
1144 backup = {
1145 repositoryFile = lib.mkOption {
1146 type = lib.types.nullOr lib.types.path;
1147 default = null;
1148 example = "/run/agenix/valley-restic-repo";
1149 description = ''
1150 File containing the restic repository URL, for the sftp target
1151 e.g. `sftp://u123456@u123456.your-storagebox.de:23//./backups/valley`.
1152 '';
1153 };
1154
1155 passwordFile = lib.mkOption {
1156 type = lib.types.nullOr lib.types.path;
1157 default = null;
1158 example = "/run/agenix/valley-restic-password";
1159 description = ''
1160 File containing the restic repository encryption password.
1161 Losing it loses the backups — keep a copy somewhere that
1162 survives this host.
1163 '';
1164 };
1165
1166 sshKeyFile = lib.mkOption {
1167 type = lib.types.nullOr lib.types.path;
1168 default = null;
1169 example = "/run/agenix/valley-git-ssh-key";
1170 description = ''
1171 SSH private key that authenticates to the sftp target. The
1172 backup service runs as root, so any identity the target
1173 authorizes works — reusing the mirror key is fine.
1174 '';
1175 };
1176
1177 knownHostsFile = lib.mkOption {
1178 type = lib.types.nullOr lib.types.path;
1179 default = null;
1180 example = "/var/lib/valley-backup/known_hosts";
1181 description = ''
1182 known_hosts file pinning the sftp target's host key. Pin from
1183 the provider's published fingerprints, not a blind ssh-keyscan.
1184 '';
1185 };
1186 };
1187 };
1188
1189 config = lib.mkIf cfg.enable {
1190 assertions = [
1191 {
1192 assertion = cfg.authorizedKeys != [ ];
1193 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
1194 }
1195 ]
1196 ++ lib.optionals backupEnabled (
1197 lib.mapAttrsToList (name: what: {
1198 assertion = cfg.backup.${name} != null;
1199 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).";
1200 }) backupSecretOptions
1201 )
1202 ++ lib.optionals cfg.integrator.enable (
1203 lib.mapAttrsToList (name: what: {
1204 assertion = cfg.integrator.${name} != null;
1205 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
1206 }) integratorPathOptions
1207 ++ [
1208 {
1209 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
1210 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.";
1211 }
1212 {
1213 assertion =
1214 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
1215 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.";
1216 }
1217 {
1218 assertion = cfg.integrator.user != cfg.user;
1219 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
1220 }
1221 {
1222 assertion = integratedProjects != { };
1223 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.";
1224 }
1225 ]
1226 )
1227 ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) (
1228 let
1229 name = cfg.integrator.instanceProject;
1230 protected = gitProjects.${name}.protection.refs or [ ];
1231 read =
1232 lib.optional cfg.integrator.enable "refs/heads/main" ++ lib.optional cfg.identity.enable cfg.identity.ref;
1233 in
1234 map (ref: {
1235 assertion = lib.any (pattern: refPatternMatches pattern ref) protected;
1236 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}.";
1237 }) read
1238 )
1239 ++ [
1240 {
1241 assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) (
1242 sshdValues "AcceptEnv" ++ sshdValues "SetEnv"
1243 ));
1244 message = "sshd's AcceptEnv or SetEnv here holds a quote or a backslash, which sshd unpicks and this module does not. Write each name plainly, separated by spaces, so what is checked is what sshd reads.";
1245 }
1246 {
1247 assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv"));
1248 message = "sshd accepts ${lib.concatStringsSep " " (lib.filter boundaryVariable (sshdValues "AcceptEnv"))} from the client (AcceptEnv), a pattern that admits ${principalEnv} or a GIT_ variable. The git user's shell drops them, and sshd must not offer them either. Remove the pattern.";
1249 }
1250 {
1251 assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv"));
1252 message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it.";
1253 }
1254 {
1255 assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment");
1256 message = "sshd's PermitUserEnvironment must be no: the git user's shell derives the principal from the authenticated key, and nothing a key's entry or ~/.ssh/environment sets is the push boundary's to read.";
1257 }
1258 {
1259 assertion = conflictingKeys == { };
1260 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.";
1261 }
1262 {
1263 assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ];
1264 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.";
1265 }
1266 ]
1267 ++ lib.optionals cfg.identity.enable [
1268 {
1269 assertion = cfg.integrator.instanceProject != null;
1270 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.";
1271 }
1272 {
1273 assertion = cfg.integrator.knownSignersFile == null;
1274 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.";
1275 }
1276 ];
1277
1278 users.groups.${cfg.group} = { };
1279
1280 users.users.${cfg.user} = {
1281 isSystemUser = true;
1282 group = cfg.group;
1283 home = cfg.dataDir;
1284 # The valley's shell, in front of git-shell: it derives the principal
1285 # from the authenticated key, drops the GIT_ environment, and pauses
1286 # pushes until valley-init has converged. git-shell then allows only
1287 # git-upload-pack, git-receive-pack and git-upload-archive, and rejects
1288 # interactive logins (no ~/git-shell-commands).
1289 shell = "${gitShell}/bin/valley-git-shell";
1290 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
1291 };
1292
1293 # The integrator's own account. No shell, no keys, no home of its own
1294 # beyond the state directory its units get; the git group is the only
1295 # thing it holds.
1296 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
1297 isSystemUser = true;
1298 group = cfg.group;
1299 home = "/var/lib/valley-integrator";
1300 description = "The valley integrator";
1301 };
1302
1303 services.openssh.enable = lib.mkDefault true;
1304
1305 # The git user's key files, named in its Match block so no other file
1306 # can authorize a key for it. The declared keys come first, and they stay
1307 # authorized beside the compiled ones: a compiled file can only ever
1308 # add, so an empty or missing one — a first boot before the first
1309 # compilation, a registry that lost an entry, a bug here — cannot take
1310 # the git user's access away. Which is the point: the assertion above
1311 # keeps at least one key declared, and that key is the way back in.
1312 #
1313 # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys
1314 # under its home is not read, and no AuthorizedKeysCommand runs, so every
1315 # entry a pusher can arrive through carries the tag this module or the
1316 # compiler wrote, and the assertions and the compiler hold those to one
1317 # tag per key.
1318 #
1319 # Belt-and-braces hardening for the git user beside it. The trailing
1320 # `Match All` closes the block so it can't scope directives appended to
1321 # sshd_config after this snippet.
1322 services.openssh.extraConfig = ''
1323 Match User ${cfg.user}
1324 AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"}
1325 AuthorizedKeysCommand none
1326 ExposeAuthInfo yes
1327 AllowTcpForwarding no
1328 AllowAgentForwarding no
1329 X11Forwarding no
1330 PermitTunnel no
1331 Match All
1332 '';
1333
1334 # git-shell spawns git-receive-pack/git-upload-pack from PATH
1335 environment.systemPackages = [ pkgs.git ];
1336
1337 systemd.tmpfiles.rules = [
1338 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
1339 ]
1340 ++ lib.optionals cfg.bus.enable [
1341 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
1342 ];
1343
1344 # The bus itself. It runs as the git user — the store directory lives in
1345 # that user's data — but the sandbox is what confines it: the unit can
1346 # write nowhere except its store directory.
1347 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
1348 description = "The valley event bus (NATS JetStream)";
1349 wantedBy = [ "multi-user.target" ];
1350 after = [
1351 "network.target"
1352 "systemd-tmpfiles-setup.service"
1353 ];
1354 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
1355 serviceConfig = {
1356 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
1357 Restart = "on-failure";
1358 User = cfg.user;
1359 Group = cfg.group;
1360 LimitNOFILE = 65536;
1361 NoNewPrivileges = true;
1362 ProtectSystem = "strict";
1363 ReadWritePaths = [ cfg.bus.storeDir ];
1364 ProtectHome = true;
1365 PrivateTmp = true;
1366 PrivateDevices = true;
1367 ProtectClock = true;
1368 ProtectHostname = true;
1369 ProtectKernelLogs = true;
1370 ProtectKernelModules = true;
1371 ProtectKernelTunables = true;
1372 ProtectControlGroups = true;
1373 ProtectProc = "invisible";
1374 RestrictAddressFamilies = [
1375 "AF_INET"
1376 "AF_INET6"
1377 "AF_UNIX"
1378 ];
1379 RestrictNamespaces = true;
1380 RestrictRealtime = true;
1381 RestrictSUIDSGID = true;
1382 LockPersonality = true;
1383 CapabilityBoundingSet = "";
1384 SystemCallArchitectures = "native";
1385 SystemCallFilter = [ "@system-service" ];
1386 UMask = "0077";
1387 };
1388 };
1389
1390 # The stream is config, not state: (re)created idempotently on every
1391 # boot, capturing everything under valley.>. An existing stream — and
1392 # the events in it — is left untouched.
1393 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
1394 description = "Create the valley event stream";
1395 wantedBy = [ "multi-user.target" ];
1396 requires = [ "valley-bus.service" ];
1397 after = [ "valley-bus.service" ];
1398 serviceConfig = {
1399 Type = "oneshot";
1400 User = cfg.user;
1401 Group = cfg.group;
1402 };
1403 path = [ pkgs.natscli ];
1404 script = ''
1405 # The server needs a moment to accept connections after startup.
1406 for _ in $(seq 1 50); do
1407 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
1408 sleep 0.2
1409 done
1410 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
1411 nats --server ${busUrl} stream add valley \
1412 --subjects 'valley.>' --storage file --defaults
1413 fi
1414 '';
1415 };
1416
1417 # Create missing bare repos and (re)wire the managed hooks on every
1418 # activation where the declaration changed.
1419 systemd.services.valley-init = {
1420 description = "Initialize the valley host's bare git repositories";
1421 wantedBy = [ "multi-user.target" ];
1422 after = [ "systemd-tmpfiles-setup.service" ];
1423 unitConfig.RequiresMountsFor = cfg.dataDir;
1424 serviceConfig = {
1425 Type = "oneshot";
1426 User = cfg.user;
1427 Group = cfg.group;
1428 };
1429 path = [
1430 pkgs.git
1431 pkgs.diffutils
1432 ];
1433 # Everything init can wire is wired before it fails. A conflict in one
1434 # repository is reported, the rest of the host is still converged,
1435 # and only then does the unit fail, so the activation fails loudly
1436 # without leaving another repository's hook out of date.
1437 script = ''
1438 # Pushes pause the moment a convergence starts, and resume only once
1439 # it has finished: the record is removed first and written last.
1440 rm -f ${convergedRecord}
1441 ${valleyInitBody}
1442 printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp
1443 mv -f ${convergedRecord}.tmp ${convergedRecord}
1444 '';
1445 };
1446
1447 # The registry compiler, on a timer. It renders the instance
1448 # repository's integrated tip into the two artifacts the gates read;
1449 # nothing else on the host writes them.
1450 #
1451 # It runs as the git user rather than under an identity of its own,
1452 # which is the one place this module steps back from the service split
1453 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
1454 # anyone but root or the account it authorizes, so the choice is the git
1455 # user or root, and the git user is the smaller grant.
1456 #
1457 # Level-triggered, like the rest: a compilation reads the current tip
1458 # and replaces an artifact only when its bytes changed, so re-running is
1459 # free and the timer needs no coordination with anything.
1460 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
1461 description = "Compile the valley identity registry into what the gates check";
1462 wantedBy = [ "multi-user.target" ];
1463 after = [ "valley-init.service" ];
1464 requires = [ "valley-init.service" ];
1465 unitConfig.RequiresMountsFor = cfg.dataDir;
1466 serviceConfig = {
1467 Type = "oneshot";
1468 ExecStart = identityCommand;
1469 User = cfg.user;
1470 Group = cfg.group;
1471 StateDirectory = identityStateName;
1472 # sshd walks every directory above an authorized-keys file and
1473 # refuses a group- or world-writable one, so the state directory is
1474 # 0755 deliberately rather than the 0700 a service's state usually
1475 # takes. Nothing secret lives in it: a registry is public keys.
1476 StateDirectoryMode = "0755";
1477 NoNewPrivileges = true;
1478 ProtectSystem = "strict";
1479 ReadWritePaths = [ identityStateDir ];
1480 ProtectHome = true;
1481 PrivateTmp = true;
1482 PrivateDevices = true;
1483 ProtectClock = true;
1484 ProtectHostname = true;
1485 ProtectKernelLogs = true;
1486 ProtectKernelModules = true;
1487 ProtectKernelTunables = true;
1488 ProtectControlGroups = true;
1489 ProtectProc = "invisible";
1490 RestrictAddressFamilies = [ "AF_UNIX" ];
1491 RestrictNamespaces = true;
1492 RestrictRealtime = true;
1493 RestrictSUIDSGID = true;
1494 LockPersonality = true;
1495 CapabilityBoundingSet = "";
1496 SystemCallArchitectures = "native";
1497 SystemCallFilter = [ "@system-service" ];
1498 UMask = "0022";
1499 };
1500 };
1501
1502 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
1503 description = "Re-compile the valley identity registry";
1504 wantedBy = [ "timers.target" ];
1505 timerConfig = {
1506 OnBootSec = "1m";
1507 OnUnitActiveSec = cfg.identity.interval;
1508 };
1509 };
1510
1511 # One controller per served project, as instances of a single template:
1512 # the units differ only in the repository they serve, which is the
1513 # instance name. `watch` rather than a timer firing `reconcile`: the
1514 # binary owns its poll loop and its interval, and a timer would be a
1515 # second cadence over the same level-triggered refs.
1516 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
1517 description = "The valley integrator for %i";
1518 after = [
1519 "network.target"
1520 "valley-init.service"
1521 ]
1522 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
1523 ++ lib.optional cfg.identity.enable "valley-identity.service";
1524 requires = [ "valley-init.service" ];
1525 # Wants, not requires: a controller reads the compiled signers file,
1526 # so it starts after the first compilation — but a compilation that
1527 # failed must not keep the controllers down. One that finds no file
1528 # says so and restarts, which is the same loop and a louder one.
1529 wants = lib.optional cfg.identity.enable "valley-identity.service";
1530 unitConfig.RequiresMountsFor = cfg.dataDir;
1531 # nix is not pinned, for the reason the integrator package does not
1532 # pin it: a check's input closure must be recomputed by the nix this
1533 # machine actually runs. Everything else a controller drives is
1534 # pinned inside the wrapper.
1535 path = [ config.nix.package ];
1536 # The repositories belong to the git user and the controller does
1537 # not, so git refuses to touch them as dubiously owned. The exception
1538 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
1539 # command-scope config, which is protected config, so safe.directory
1540 # is honoured from it — a repository-scoped setting would be ignored,
1541 # deliberately. And every git the controller drives is a child of
1542 # this unit, whether run by the integrator itself or by attest or the
1543 # deriver, so one environment covers all of them.
1544 #
1545 # One repository per instance: never a global gitconfig, never a
1546 # wildcard. Every other repository on the host stays refused. Linked
1547 # worktrees need no entry of their own — the controller creates them,
1548 # so it owns them, and git checks the worktree and its gitdir rather
1549 # than the repository they point at.
1550 #
1551 # TMPDIR is the same kind of wiring, for the same reason. A verdict
1552 # wants a checkout of the tip on disk, and the integrator asks for one
1553 # the ordinary way — a temporary directory, then a linked worktree in
1554 # it. The sandbox below leaves no writable temporary directory, so
1555 # every tick died on `could not create leading directories`. The
1556 # scratch belongs under the state directory the unit already has:
1557 # writable by construction, owned by this service, and gone when the
1558 # service's state is. Setting it in the environment rather than
1559 # teaching the binary a flag covers every process in the unit at once
1560 # — the integrator, attest, the deriver, and the git each of them runs
1561 # all read TMPDIR, and all of them want scratch in the same place.
1562 #
1563 # A second exception, for the instance repository. Every controller
1564 # reads the group's floor from that repository's tip, and it need not
1565 # be the project the controller serves — the controller for one
1566 # project reads the floor out of another project's repository, which
1567 # it likewise does not own. Without the exception git refuses it as
1568 # dubiously owned and every pass fails, exactly as it did for the
1569 # served repository. Two entries, both named; still never a wildcard.
1570 #
1571 # Reading needs no sandbox entry beside it. ProtectSystem=strict
1572 # leaves the filesystem readable and only takes write away, so the
1573 # ReadWritePaths list above stays the list of what may be written,
1574 # which is what makes it worth reading. What read does need is a
1575 # filesystem grant, and valley-init makes it: the instance repository
1576 # is group-readable whether or not it is one of the served projects.
1577 environment = {
1578 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
1579 GIT_CONFIG_KEY_0 = "safe.directory";
1580 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
1581 TMPDIR = integratorStateDir;
1582 }
1583 // lib.optionalAttrs (instanceRepo != null) {
1584 GIT_CONFIG_KEY_1 = "safe.directory";
1585 GIT_CONFIG_VALUE_1 = instanceRepo;
1586 };
1587 serviceConfig = {
1588 ExecStart = integratorCommand;
1589 Restart = "on-failure";
1590 RestartSec = "10s";
1591 User = cfg.integrator.user;
1592 Group = cfg.group;
1593 StateDirectory = integratorStateName;
1594 StateDirectoryMode = "0700";
1595 WorkingDirectory = integratorStateDir;
1596 NoNewPrivileges = true;
1597 ProtectSystem = "strict";
1598 # Everything the controller may write, named where a reader of the
1599 # unit meets it. Under ProtectSystem=strict the rest of the
1600 # filesystem is read-only, so this list is the whole of what the
1601 # service can touch, and it is worth being able to read it as such
1602 # rather than as the exceptions plus whatever else is implied.
1603 #
1604 # Its own directory: its state, and the scratch root TMPDIR names.
1605 # A declaration says it here rather than relying on the state
1606 # directory being read-write by virtue of being declared, which is
1607 # not something this unit found to be true.
1608 #
1609 # The one repository it serves, and the nix daemon's socket —
1610 # recomputing a closure means asking the daemon, and connecting to
1611 # a unix socket needs write access to it.
1612 ReadWritePaths = [
1613 integratorStateDir
1614 "${cfg.dataDir}/%i.git"
1615 "/nix/var/nix/daemon-socket"
1616 ];
1617 ProtectHome = true;
1618 PrivateTmp = true;
1619 PrivateDevices = true;
1620 ProtectClock = true;
1621 ProtectHostname = true;
1622 ProtectKernelLogs = true;
1623 ProtectKernelModules = true;
1624 ProtectKernelTunables = true;
1625 ProtectControlGroups = true;
1626 ProtectProc = "invisible";
1627 RestrictAddressFamilies = [
1628 "AF_INET"
1629 "AF_INET6"
1630 "AF_UNIX"
1631 ];
1632 RestrictNamespaces = true;
1633 RestrictRealtime = true;
1634 RestrictSUIDSGID = true;
1635 LockPersonality = true;
1636 CapabilityBoundingSet = "";
1637 SystemCallArchitectures = "native";
1638 SystemCallFilter = [ "@system-service" ];
1639 # Group write, not the bus unit's 0077: the git user owns these
1640 # repositories and has to stay able to write what a controller
1641 # leaves in them.
1642 UMask = "0002";
1643 };
1644 };
1645
1646 # wantedBy on a template unit enables nothing, so the instances the
1647 # declaration asks for are pulled in by name.
1648 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
1649 description = "The valley integrator's controllers";
1650 wantedBy = [ "multi-user.target" ];
1651 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
1652 };
1653
1654 # Offsite backup, rendered only when the declaration asks for it. The
1655 # declaration states the policy — that backup exists, its cadence and
1656 # retention; the services.valley.backup.* options supply the machine
1657 # half. Declaration absent or disabled ⇒ no restic config at all.
1658 services.restic.backups = lib.mkIf backupEnabled {
1659 valley = {
1660 initialize = true;
1661 repositoryFile = cfg.backup.repositoryFile;
1662 passwordFile = cfg.backup.passwordFile;
1663 paths = [ cfg.dataDir ];
1664 # The schema admits only the restic-sftp target today; a second
1665 # target would grow a dispatch here. The service runs as root:
1666 # authenticate with the supplied identity and only the pinned
1667 # host key. No prompt can be answered inside a systemd unit, so
1668 # BatchMode + strict host key checking turn a would-be hang into
1669 # an immediate error.
1670 extraOptions = [
1671 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
1672 ];
1673 timerConfig = backupTimer.${backupPolicy.cadence};
1674 pruneOpts = [
1675 "--keep-daily ${toString backupPolicy.retention.daily}"
1676 "--keep-weekly ${toString backupPolicy.retention.weekly}"
1677 "--keep-monthly ${toString backupPolicy.retention.monthly}"
1678 ];
1679 };
1680 };
1681 };
1682}