gunk-dev/the-valley

valley-host.nix

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