gunk-dev/the-valley

valley-host.nix

source30fe2c053de0main's published tip history
125.0 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, network ACLs in front. Per-project *access* is not honestly
17# enforceable with this mechanism, so it is deliberately not an option
18# (archive/.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# (archive/.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# through its secrets). Every mirror push runs as the git user, whether
30# a push or an integrator landing moved the ref. Nothing here plumbs
31# secrets: the backup options below take *paths* to consumer-provisioned
32# secret files; the contents never pass through this module or the store.
33#
34# Three services run under their own unix users rather than the git one:
35# the integrator, which is the first half of the split bd-500adf7 asks
36# for, and the check worker and the restacker, which are not in the git
37# group at all.
38{
39 config,
40 pkgs,
41 lib,
42 ...
43}:
44
45let
46 cfg = config.services.valley;
47
48 schema = ../schema/valley.cue;
49
50 # Build-time vet + export of the host declaration. the vet checks the
51 # declaration against the schema (whose top level applies #Host), so unknown
52 # fields and unsafe project names fail the build, with cue's error.
53 configJSON =
54 pkgs.runCommand "valley-config.json"
55 {
56 nativeBuildInputs = [ pkgs.cue ];
57 }
58 ''
59 cue vet -c ${schema} ${cfg.config}
60 cue export ${schema} ${cfg.config} > $out
61 '';
62
63 host = lib.importJSON configJSON;
64
65 # Projects whose git store is enabled get a bare repository.
66 gitProjects = lib.filterAttrs (_: p: p.git.enable) host.projects;
67 repoNames = lib.attrNames gitProjects;
68
69 # Where valley-init publishes repoNames in the instance repository.
70 projectsRef = "refs/the-valley/projects";
71
72 # The declared durability policy, if any. `backup` is optional in the
73 # schema: a declaration without it (or with enable = false) renders zero
74 # backup machinery, exactly as before the field existed.
75 backupPolicy = host.backup or null;
76 backupEnabled = backupPolicy != null && backupPolicy.enable;
77
78 # The declared cadence names policy; its wall-clock rendering is this
79 # installer's choice. A lookup rather than a literal, so a cadence this
80 # module does not know fails eval loudly instead of mis-scheduling.
81 backupTimer = {
82 # Late night with a spread; Persistent runs a missed window at boot.
83 nightly = {
84 OnCalendar = "03:30";
85 RandomizedDelaySec = "30m";
86 Persistent = true;
87 };
88 };
89
90 # The projects the integrator serves: exactly the ones the declaration
91 # protects. A protected ref is one only a declared writer may push, and
92 # the integrator is what lands everyone else's changes onto it.
93 integratedProjects = lib.filterAttrs (_: p: p ? protection) gitProjects;
94
95 # The programs this flake builds (nix/packages.nix), the defaults of
96 # services.valley.packages.
97 flakePackages = import ./packages.nix { inherit pkgs lib; };
98
99 # The integrator this flake builds, in its shipping form: attest, the
100 # deriver, cue, git and natscli pinned inside the wrapper, so every host
101 # judges with the same tools (nix/packages.nix).
102 integratorPackage = cfg.packages.integrator;
103
104 # The whole of a controller's configuration: which repository it serves,
105 # who it signs as, and whose evidence it accepts. No policy — the
106 # integrator reads the project layer from the target tip and the instance
107 # layer from its own side (bd-eaefe82) — and no project name, which the
108 # binary derives from the bare repo's own directory, the same way the
109 # post-receive hook does.
110 integratorCommand = lib.concatStringsSep " " (
111 [
112 "${integratorPackage}/bin/integrator watch"
113 "--repo ${cfg.dataDir}/%i.git"
114 "--key ${toString cfg.integrator.signingKeyFile}"
115 "--known-signers ${knownSigners}"
116 "--interval ${cfg.integrator.interval}"
117 ]
118 ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}"
119 ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}"
120 ++ (
121 if cfg.integrator.instanceProject != null then
122 [ "--instance-repo ${instanceRepo}" ]
123 else
124 [ "--instance ${toString cfg.integrator.instancePolicy}" ]
125 )
126 ++ lib.optional cfg.bus.enable "--bus ${busUrl}"
127 ++ [ "--publish-queue ${cfg.dataDir}/%i.git/${publishQueueName}" ]
128 );
129
130 # The one filesystem grant the integrator's user gets. It writes refs,
131 # objects, and the worktree metadata `git worktree add` keeps inside the
132 # repository, so read access is not enough: the repos it serves become
133 # group-shared, and its primary group is the git group. Re-applied on
134 # every activation, because a repo can predate the service.
135 # git creates $GIT_DIR/worktrees on the first `worktree add`, owned by
136 # whichever user got there first. Left alone that user is the integrator,
137 # and this sweep runs as the git user, which cannot chmod a directory it
138 # does not own. So init makes that directory itself, ahead of any
139 # controller: owned by the git user, group-writable, and setgid, so what a
140 # controller creates inside it lands in the git group and stays reachable.
141 integratorShareCommands =
142 ''
143 # A chmod the git user is not allowed to make is a path some other
144 # user owns; chmod -R applies what it can and then says so. Warn and
145 # carry on, and the trade is worth stating. Failing here fails
146 # valley-init, which every valley unit requires, so the alternative to
147 # a partly shared repository is no git service on the host at all: no
148 # controllers, and no ssh access to any project. A degraded share
149 # costs the integrator the paths it cannot write, is visible in the
150 # journal, and is fixed by one chown. That is the recoverable half of
151 # the trade, and it is the half to take. The warning is what keeps the
152 # degraded state from being a silent one.
153 share() {
154 "$@" || 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
155 }
156 ''
157 + lib.concatMapStrings (name: ''
158 repo=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
159 git -C "$repo" config core.sharedRepository group
160 # Before the sweep below, so the sweep never meets a root it cannot
161 # touch. On a host where a controller already made it, this is the
162 # chmod that warns, and the repository is served either way.
163 mkdir -p "$repo/worktrees"
164 share chmod g+rwxs "$repo/worktrees"
165 # The publish queue is the git user's for the same reason: the
166 # integrator writes into it and the publish unit deletes from it.
167 mkdir -p "$repo/${publishQueueName}"
168 share chmod g+rwxs "$repo/${publishQueueName}"
169 share chmod -R g+rwX "$repo"
170 share find "$repo" -type d -exec chmod g+s {} +
171 '') (lib.attrNames integratedProjects);
172
173 # The integrator's own directory. Four unit settings have to agree about
174 # it — its state directory, its working directory, the scratch root TMPDIR
175 # names, and the read-write path that makes all three usable — so they name
176 # it once here.
177 # The bare repository the group's floor is read from: the instance
178 # project's, served by this host. Null when the host serves no instance
179 # repository and the layer is supplied as a directory instead.
180 instanceRepo =
181 if cfg.integrator.instanceProject != null then
182 "${cfg.dataDir}/${cfg.integrator.instanceProject}.git"
183 else
184 null;
185
186 integratorStateName = "valley-integrator";
187 integratorStateDir = "/var/lib/${integratorStateName}";
188
189 # The identity registry compiler this flake builds. It renders the
190 # registry at the instance repository's integrated tip into what the gates
191 # check (dcr-b87f6e8): the known-signers file the integrator and any
192 # reader of an attestation use, and a tagged authorized_keys for the git
193 # user.
194 identityPackage = cfg.packages.identity;
195
196 identityStateName = "valley-identity";
197 identityStateDir = "/var/lib/${identityStateName}";
198 identityKnownSigners = "${identityStateDir}/known-signers";
199
200 # The grants the pre-receive hook checks, as the registry names them.
201 identityGrants = "${identityStateDir}/grants";
202
203 # The compiled authorized keys. sshd reads them for the git user alone:
204 # the git user's Match block below names the files its keys come from.
205 identityAuthorizedKeys = "${identityStateDir}/authorized_keys.${cfg.user}";
206
207 identityCommand = lib.concatStringsSep " " [
208 "${identityPackage}/bin/identity compile"
209 "--repo ${toString instanceRepo}"
210 "--ref ${cfg.identity.ref}"
211 "--dir ${cfg.identity.directory}"
212 "--known-signers ${identityKnownSigners}"
213 "--authorized-keys ${identityAuthorizedKeys}"
214 "--grants ${identityGrants}"
215 "--declared-keys ${declaredKeysFile}"
216 ];
217
218 # Whose evidence a controller accepts: the compiled artifact once the
219 # registry machinery is on, and the file the consumer supplied otherwise.
220 knownSigners =
221 if cfg.identity.enable then identityKnownSigners else toString cfg.integrator.knownSignersFile;
222
223 # Which signers count in which projects, as the integrator reads it: one
224 # line per restricted signer, its name and then its projects. Null when
225 # the consumer restricts nobody, so a host that sets nothing passes no
226 # file to anything. The file is in the store, so a changed list is a
227 # changed command line for the controllers and the publisher alike, and
228 # an activation restarts the one and runs the other again.
229 signerProjects =
230 if cfg.integrator.signerProjects == { } then
231 null
232 else
233 pkgs.writeText "valley-signer-projects" (
234 lib.concatStrings (
235 lib.mapAttrsToList (
236 name: projects: lib.concatStringsSep " " ([ name ] ++ projects) + "\n"
237 ) cfg.integrator.signerProjects
238 )
239 );
240
241 # What a client verifies this host's transfer statements with, published
242 # in the instance repository: the known-signers file the controllers read,
243 # whichever wrote it, and the name they sign under. Unset, the name is the
244 # integrator's own default, and the publisher computes it with the same
245 # code on the same host, so what is published is what the controllers use.
246 # A host publishes it while the integrator runs and the host serves the
247 # instance repository; any other host publishes nothing.
248 publishesSigners = cfg.integrator.enable && instanceRepo != null;
249 signersCommand = lib.concatStringsSep " " (
250 [
251 "${integratorPackage}/bin/integrator publish-signers"
252 "--instance-repo ${toString instanceRepo}"
253 "--known-signers ${knownSigners}"
254 ]
255 ++ lib.optional (cfg.integrator.signingName != null) "--name ${cfg.integrator.signingName}"
256 ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}"
257 );
258
259 # The check worker (status/worker.go), as this flake packages it, and the
260 # attest it signs with.
261 workerPackage = (import ./packages.nix { inherit pkgs lib; }).valley-worker;
262 attestPackage = (import ./packages.nix { inherit pkgs lib; }).attest;
263
264 workerDir = toString cfg.worker.stateDir;
265
266 # The worker's one key. It signs the worker's notes, and it is the ssh
267 # key the worker reaches this host's repositories with. It is made on
268 # the host the first time the service starts, and the service never
269 # copies or prints it. Anything running as the worker can read it.
270 workerKey = "${workerDir}/key";
271
272 # The worker reads and pushes as an ssh client of this host, as the git
273 # user, so its pushes pass the pre-receive hook like anyone else's. It
274 # holds no grant on the repositories' files. The repository it runs in
275 # names the instance repository as origin, and the projects are found
276 # through it, the way valley pending --repo finds them.
277 workerOrigin = "${cfg.user}@localhost:${toString cfg.integrator.instanceProject}.git";
278
279 # Every host the worker connects to is checked against this host's own
280 # keys, under one alias. A project's policy/valley may name this host by
281 # another name, such as git@valley-host:valley.git, and that still
282 # reaches this host's sshd. A name that reaches any other host fails the
283 # check, so the worker talks to no other host.
284 workerSsh = lib.concatStringsSep " " [
285 "${config.programs.ssh.package}/bin/ssh -F none"
286 "-i ${workerKey}"
287 "-p ${toString (lib.head config.services.openssh.ports)}"
288 "-o IdentitiesOnly=yes -o BatchMode=yes"
289 "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost"
290 "-o UserKnownHostsFile=${workerDir}/known_hosts -o GlobalKnownHostsFile=/dev/null"
291 ];
292
293 # The nix settings the worker's nix commands run with. The daemon applies
294 # max-jobs and cores to every connection, a client's that is not trusted
295 # included: each nix build the worker starts builds one derivation at a
296 # time, and tells the builder it may use 4 cores. cores is a hint the
297 # builder reads as NIX_BUILD_CORES; the build slice is what holds a build
298 # to its CPUs. The worker uses no remote builder, and no flake's nixConfig.
299 workerNixConfig = ''
300 extra-experimental-features = nix-command flakes
301 max-jobs = 1
302 cores = 4
303 builders =
304 accept-flake-config = false
305 '';
306
307 # The build slice (services.valley.buildSlice): the one slice every
308 # build of this machine's nix daemon runs in, under the host's caps.
309 buildSlice = "valley-builds.slice";
310
311 # What the service does each time it starts: make the key if there is
312 # none, write its public halves and this host's ssh keys, make the
313 # repository it runs in, and run one pass.
314 workerScript = ''
315 set -eu
316 state=${lib.escapeShellArg workerDir}
317 key="$state/key"
318
319 # The key is made once, under a temporary name and renamed into place,
320 # so a start that is killed half way leaves no key, and the next start
321 # makes one. The public half is renamed first, so a key is never
322 # without it. The private half is never printed.
323 if [ ! -e "$key" ]; then
324 rm -f "$key.new" "$key.new.pub"
325 ssh-keygen -q -t ed25519 -N "" -C "valley-worker@${config.networking.hostName}" -f "$key.new"
326 chmod 0400 "$key.new"
327 mv -f "$key.new.pub" "$key.pub"
328 mv -f "$key.new" "$key"
329 fi
330
331 # The verifier line the known-signers file holds for the key, under
332 # the worker's signing name. A changed name is a changed line, so it is
333 # written again on every start, and said whenever it changes.
334 attest key --key "$key" --name ${lib.escapeShellArg cfg.worker.signerName} > "$state/verifier.new"
335 if cmp -s "$state/verifier.new" "$state/verifier"; then
336 rm -f "$state/verifier.new"
337 else
338 mv -f "$state/verifier.new" "$state/verifier"
339 echo "valley-worker: the worker's ssh public key is $(cat "$state/key.pub")"
340 echo "valley-worker: the worker's verifier line is $(cat "$state/verifier")"
341 fi
342
343 # This host's own ssh keys, the only ones the worker's ssh accepts.
344 : > "$state/known_hosts.new"
345 for pub in ${lib.escapeShellArgs (map (k: "${k.path}.pub") config.services.openssh.hostKeys)}; do
346 if [ -r "$pub" ]; then
347 printf 'localhost %s\n' "$(cut -d' ' -f1,2 "$pub")" >> "$state/known_hosts.new"
348 fi
349 done
350 mv -f "$state/known_hosts.new" "$state/known_hosts"
351
352 # The repository the pass runs in. It holds no checkout, and origin is
353 # the instance repository.
354 origin="$state/origin"
355 git init --quiet "$origin"
356 if [ "$(git -C "$origin" remote get-url origin 2>/dev/null)" != ${lib.escapeShellArg workerOrigin} ]; then
357 git -C "$origin" remote remove origin 2>/dev/null || true
358 git -C "$origin" remote add origin ${lib.escapeShellArg workerOrigin}
359 fi
360
361 cd "$origin"
362 exec valley-worker ${
363 lib.concatMapStringsSep " " (p: "--repo ${lib.escapeShellArg p}") cfg.worker.projects
364 } --key "$key" --name ${lib.escapeShellArg cfg.worker.signerName} --state "$state"
365 '';
366
367 # The name the controllers sign under, which the worker's must not be.
368 integratorName =
369 if cfg.integrator.signingName != null then
370 cfg.integrator.signingName
371 else
372 "${config.networking.hostName}/attestations";
373
374 # The restacker (restack/): one controller for each project listed,
375 # under its own Unix user. Its state for a project is a directory of its
376 # own, and it reaches the repositories as an ssh client of this host,
377 # as its own principal, so every push it makes passes the pre-receive
378 # hook like anyone else's. It is in no group that can read or write them
379 # on disk.
380 restackerPackage = cfg.packages.restacker;
381 restackerStateName = "valley-restacker";
382 restackerState = "%S/${restackerStateName}/%i";
383
384 # It authenticates with the key the operator provisions, which systemd
385 # hands it as a credential, and accepts only this host's own ssh keys,
386 # under one alias, as the worker does.
387 restackerSsh = lib.concatStringsSep " " [
388 "${config.programs.ssh.package}/bin/ssh -F none"
389 "-i %d/key"
390 "-p ${toString (lib.head config.services.openssh.ports)}"
391 "-o IdentitiesOnly=yes -o BatchMode=yes"
392 "-o StrictHostKeyChecking=yes -o HostKeyAlias=localhost"
393 "-o UserKnownHostsFile=${restackerState}/known_hosts -o GlobalKnownHostsFile=/dev/null"
394 ];
395
396 # This host's own ssh keys, written into the state directory before each
397 # start: the only keys the restacker's ssh accepts.
398 restackerKnownHosts = pkgs.writeShellScript "valley-restacker-known-hosts" ''
399 set -eu
400 : > "$1/known_hosts.new"
401 for pub in ${lib.escapeShellArgs (map (k: "${k.path}.pub") config.services.openssh.hostKeys)}; do
402 if [ -r "$pub" ]; then
403 printf 'localhost %s\n' "$(cut -d' ' -f1,2 "$pub")" >> "$1/known_hosts.new"
404 fi
405 done
406 mv -f "$1/known_hosts.new" "$1/known_hosts"
407 '';
408
409 # A pass reads landings with the verifier keys and the name the
410 # controllers read and sign under, and the floor from where the
411 # controllers read it: the instance repository, over ssh as itself, or
412 # the materialized directory.
413 restackerCommand = lib.concatStringsSep " " (
414 [
415 "${restackerPackage}/bin/valley-restacker run"
416 "--repo ${cfg.user}@localhost:%i.git"
417 "--state ${restackerState}"
418 "--principal ${cfg.restacker.principal}"
419 "--interval ${cfg.restacker.interval}"
420 "--integrator-name ${integratorName}"
421 ]
422 ++ lib.optional (knownSigners != "") "--known-signers ${knownSigners}"
423 ++ lib.optional (signerProjects != null) "--signer-projects ${signerProjects}"
424 ++ (
425 if cfg.integrator.instanceProject != null then
426 [ "--instance-repo ${cfg.user}@localhost:${cfg.integrator.instanceProject}.git" ]
427 else
428 [ "--instance ${toString cfg.integrator.instancePolicy}" ]
429 )
430 );
431
432 # The paths the consumer must supply once the integrator is enabled,
433 # with what each names — for the assertion message. The signers file is
434 # among them only while the registry does not compile one.
435 integratorPathOptions = {
436 signingKeyFile = "the key its transfer statements are signed with";
437 }
438 // lib.optionalAttrs (!cfg.identity.enable) {
439 knownSignersFile = "the signers whose evidence it accepts";
440 };
441
442 # The secret-path options the consumer must supply once the declaration
443 # enables backup, with what each names — for the assertion message.
444 backupSecretOptions = {
445 repositoryFile = "the restic repository URL";
446 passwordFile = "the repository encryption password";
447 sshKeyFile = "the SSH identity for the sftp target";
448 knownHostsFile = "the pinned host key of the sftp target";
449 };
450
451 # Managed post-receive dispatcher. Each repo's post-receive is a symlink to
452 # this script, which chains every executable dropped into the repo's
453 # hooks/post-receive.d/ directory.
454 postReceiveDispatch = pkgs.writeShellScript "valley-post-receive" ''
455 # Managed by services.valley — do not edit.
456 # Drop executable hooks into post-receive.d/ next to this symlink.
457 set -eu
458 hook_dir="$(dirname "$0")/post-receive.d"
459 [ -d "$hook_dir" ] || exit 0
460 updates="$(cat)"
461 [ -n "$updates" ] || exit 0
462 for hook in "$hook_dir"/*; do
463 [ -x "$hook" ] || continue
464 printf '%s\n' "$updates" | "$hook" "$@"
465 done
466 '';
467
468 # Push replication. A publication mirror gets main and the tags, and
469 # nothing else. Only the publish drain further down runs it, for pushes
470 # and integrator landings alike.
471 # Topic branches are review-queue state, not published: the mirror exists
472 # so consumers can fetch what has been integrated, and durability is
473 # restic's job, not the mirror's. The two refspecs are what keep every
474 # other ref of the project off the mirror.
475 # --prune propagates tag deletions through the tags glob. The heads
476 # refspec names one ref, so --prune deletes no head.
477 # The pusher deletes nothing else on a mirror. Deleting a ref that a
478 # public mirror has served unpublishes nothing, because forges keep its
479 # objects fetchable by SHA. And a mirror holds refs that other writers put
480 # there, such as a forge's own namespaces or a bot's branches; those are
481 # theirs. --mirror is refused for the same reason: it deletes every mirror
482 # ref the primary lacks, and on GitHub the read-only refs/pull/* makes
483 # that fail every push, masking real replication failures.
484 # The pusher exits non-zero when a replication push fails, and the drain
485 # retries on that.
486 mirrorPusher =
487 name: mirrors:
488 pkgs.writeShellScript "valley-mirror-push-${name}" ''
489 status=0
490 for url in ${lib.escapeShellArgs mirrors}; do
491 if ${pkgs.git}/bin/git push --prune "$url" '+refs/heads/main:refs/heads/main' '+refs/tags/*:refs/tags/*' >/dev/null 2>&1; then
492 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: pushed to $url" || true
493 else
494 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: push to $url FAILED" || true
495 status=1
496 fi
497 done
498 exit "$status"
499 '';
500
501 # The post-receive.d hook of a project with mirrors. It does not push. It
502 # queues the push's ref moves for the publish drain, as the integrator
503 # queues a landing, and returns. So a dead mirror can only ever cost a log
504 # line and a retry, never block or fail the primary push. The file is
505 # written beside the queue and renamed into it, so the drain never reads a
506 # partial one. A push whose moves cannot be queued is logged, and stands.
507 mirrorHook =
508 name:
509 pkgs.writeShellScript "valley-mirrors-${name}" ''
510 # Managed by services.valley — queue this push for ${name}'s mirrors.
511 bin=${pkgs.coreutils}/bin
512 tmp="$($bin/mktemp .valley-publish-XXXXXXXX)" &&
513 $bin/cat >"$tmp" &&
514 $bin/mv -- "$tmp" "${publishQueueName}/$($bin/date +%s%N)-push-$$" || {
515 $bin/rm -f -- "$tmp"
516 ${pkgs.util-linux}/bin/logger -t valley-mirror "${name}: queueing a push FAILED" || true
517 }
518 exit 0
519 '';
520
521 # The event bus (archive/design/roadmap.md, Phase 1): NATS JetStream, onto which
522 # the ref-updated hook below projects this host's git activity. The bus is
523 # never load-bearing for durable state — per-repo events are durable in
524 # git itself, and `valley replay` rebuilds the stream from a repo's refs —
525 # so losing its storage costs one replay, nothing more.
526 busUrl = "nats://${cfg.bus.listen}";
527
528 busServerConfig = pkgs.writeText "valley-bus.conf" ''
529 listen: ${cfg.bus.listen}
530 jetstream {
531 store_dir: "${cfg.bus.storeDir}"
532 # The store directory defaults to living on the repo volume; the cap
533 # keeps a runaway or malicious local publisher from filling it.
534 max_file_store: 2GiB
535 }
536 '';
537
538 # One ref-updated event per updated ref, read from the post-receive stdin
539 # this script inherits. Every payload field is derivable from git alone —
540 # no wall-clock time, no hostname — so replaying a repo's refs reproduces
541 # the same events (the roadmap's determinism criterion). `valley replay`
542 # builds the identical payload; change one only with the other.
543 busPublisher = pkgs.writeShellScript "valley-bus-publish" ''
544 repo="$(basename "$PWD" .git)"
545 while read -r old new ref; do
546 [ -n "$ref" ] || continue
547 # " is the only JSON-significant character a refname can contain
548 # (git forbids \ and control characters); names and ids are safe.
549 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
550 "$repo" "''${ref//\"/\\\"}" "$old" "$new")"
551 if ${pkgs.natscli}/bin/nats --server ${busUrl} pub \
552 "valley.git.$repo.ref-updated" "$event" </dev/null >/dev/null 2>&1; then
553 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: published ref-updated $ref" || true
554 else
555 ${pkgs.util-linux}/bin/logger -t valley-bus "$repo: publish of ref-updated $ref FAILED" || true
556 fi
557 done
558 '';
559
560 # How a move reaches the mirrors: the publish queue.
561 #
562 # One thing pushes a project's mirrors: the publish drain, a oneshot unit
563 # per project that runs as the git user. Whatever moves a ref writes the
564 # move into a queue directory in the repository, as the line post-receive
565 # reads: old, new, ref. A path unit watches the queue, and when it holds
566 # anything, starts the drain. A push queues its moves from post-receive,
567 # through the mirror hook above. The integrator moves refs with
568 # update-ref, which runs no post-receive hook, so it queues each landing
569 # itself (integrator/bus.go). It runs as its own user, which does not hold
570 # the git user's mirror credentials and must not.
571 #
572 # A single publisher is what keeps a mirror from being rewound. git reads
573 # the local refs before it contacts the mirror, so two pushers running at
574 # once can rewind it: one reads an old main and stalls, the other pushes a
575 # newer main, and the first then force-pushes its old main over it.
576 # systemd never runs two instances of one unit at the same time, so the
577 # drain's pushes for a project never overlap, and nothing else pushes.
578 # The drain lists the queue before git reads any ref, and deletes only what
579 # it listed, after the push succeeds. A move is queued after its ref moved,
580 # so the push covers every listed move. A move queued during the push stays
581 # for the next run, which pushes the newer main. No lock is taken: the
582 # drain runs only as the unit. To publish by hand, start the unit
583 # (systemctl start valley-publish@<project>), never the script.
584 #
585 # A run that fails leaves the queue as it was, and systemd runs it again
586 # after a delay (the unit, further down). So a failed mirror push does not
587 # wait for another move to be retried. Repeating a push is harmless: it
588 # pushes the current main, whatever the queue records.
589 #
590 # The bus is not the drain's business. A push publishes its ref-updated
591 # events from post-receive, through the bus hook below. The integrator
592 # publishes its landing's ref-updated event itself. So a mirror outage, and
593 # the drain's retries, never delay an event.
594 #
595 # The alternatives fall to the user split. Calling the post-receive
596 # dispatcher from the integrator would push as the integrator's user, and
597 # so would a reference-transaction hook, which runs as whoever ran git; it
598 # would also fire inside every push and for every bookkeeping ref the
599 # integrator writes. Starting a unit directly would take a polkit grant
600 # and carry no record of what moved. The queue costs one directory, the
601 # path unit is woken by inotify rather than a poll, and the queue is
602 # durable, so a move queued while the host goes down is published after.
603 publishQueueName = "valley-publish-queue";
604
605 # The projects with a publish queue and a drain: every one with mirrors,
606 # and every one the integrator serves. The integrator queues its landings
607 # whether or not the project has mirrors. A drain with no mirrors to push
608 # only empties the queue.
609 publishedProjects = lib.filterAttrs (
610 name: p: p.mirrors != [ ] || (cfg.integrator.enable && integratedProjects ? ${name})
611 ) gitProjects;
612
613 # The drain, per project. Its working directory is the repository. It runs
614 # synchronously: the unit is already detached from the push or the
615 # landing, and a detached child would be killed with the oneshot's cgroup
616 # when it exits.
617 publishDrain =
618 name: p:
619 pkgs.writeShellScript "valley-publish-${name}" ''
620 # Managed by services.valley — push the moves queued on ${name} to its mirrors.
621 shopt -s nullglob
622 # Listed before the pusher reads any ref, so the push covers them all.
623 moves=( ${publishQueueName}/* )
624 [ "''${#moves[@]}" -gt 0 ] || exit 0
625 ${lib.optionalString (p.mirrors != [ ]) "${mirrorPusher name p.mirrors} || exit 1"}
626 # A move that cannot be deleted fails the run, so systemd retries it
627 # after a delay. A run that succeeded would leave the queue non-empty,
628 # and the path unit would start the drain again at once, over and over.
629 rm -f -- "''${moves[@]}" || exit 1
630 '';
631
632 # Every drain, by project name, so the template unit runs its instance's.
633 publishDrains = pkgs.linkFarm "valley-publish-drains" (
634 lib.mapAttrsToList (name: p: {
635 inherit name;
636 path = publishDrain name p;
637 }) publishedProjects
638 );
639
640 # The queue directory of every published project. The integrator's
641 # projects also get it group-shared, with the rest of the repository.
642 publishQueueCommands = lib.concatMapStrings (name: ''
643 mkdir -p ${lib.escapeShellArg "${cfg.dataDir}/${name}.git/${publishQueueName}"}
644 '') (lib.attrNames publishedProjects);
645
646 # The post-receive.d hook that publishes a push's ref-updated events. The
647 # publisher runs detached (setsid, inheriting the updates on stdin), so a
648 # bus problem can only ever cost a log line — never block or fail the
649 # push. git is the source of truth; the bus is the replaceable component.
650 busEventHook = pkgs.writeShellScript "valley-bus-events" ''
651 # Managed by services.valley — project ref updates onto the event bus.
652 ${pkgs.util-linux}/bin/setsid -f ${busPublisher} >/dev/null 2>&1
653 exit 0
654 '';
655
656 # Bus-hook wiring, one symlink per repo. Same rules as the mirror hooks:
657 # only ever installs, updates, or removes a store symlink — a hand-written
658 # hook of the same name is left alone.
659 busHookCommands = lib.concatMapStrings (
660 name:
661 let
662 bhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-bus";
663 in
664 if cfg.bus.enable then
665 ''
666 bhook=${bhook}
667 if [ -L "$bhook" ]; then
668 case "$(readlink "$bhook")" in
669 /nix/store/*) ln -sfn ${busEventHook} "$bhook" ;;
670 esac
671 elif [ ! -e "$bhook" ]; then
672 ln -s ${busEventHook} "$bhook"
673 fi
674 ''
675 else
676 ''
677 bhook=${bhook}
678 if [ -L "$bhook" ]; then
679 case "$(readlink "$bhook")" in
680 /nix/store/*) rm -f "$bhook" ;;
681 esac
682 fi
683 ''
684 ) repoNames;
685
686 # Per-project mirror-hook wiring. Only ever installs, updates, or removes
687 # a store symlink — a hand-written hook of the same name is left alone.
688 mirrorHookCommands = lib.concatStrings (
689 lib.mapAttrsToList (
690 name: p:
691 let
692 mhook = lib.escapeShellArg "${cfg.dataDir}/${name}.git/hooks/post-receive.d/valley-mirrors";
693 in
694 if p.mirrors != [ ] then
695 ''
696 mhook=${mhook}
697 if [ -L "$mhook" ]; then
698 case "$(readlink "$mhook")" in
699 /nix/store/*) ln -sfn ${mirrorHook name} "$mhook" ;;
700 esac
701 elif [ ! -e "$mhook" ]; then
702 ln -s ${mirrorHook name} "$mhook"
703 fi
704 ''
705 else
706 ''
707 mhook=${mhook}
708 if [ -L "$mhook" ]; then
709 case "$(readlink "$mhook")" in
710 /nix/store/*) rm -f "$mhook" ;;
711 esac
712 fi
713 ''
714 ) gitProjects
715 );
716
717 # The environment variable carrying the pushing key's principal name. The
718 # git user's shell sets it from the tag on the authenticated key's own
719 # authorized_keys entry, and the pre-receive hook reads it.
720 principalEnv = "VALLEY_PRINCIPAL";
721
722 authorizedKeyLine =
723 k: if lib.isString k then k else ''environment="${principalEnv}=${k.principal}" ${k.key}'';
724
725 # What valley-init does to converge the host: create missing repositories
726 # and (re)wire the managed hooks. Its last step refuses to report the host
727 # converged over anything that would run instead of the push policy.
728 valleyInitBody = ''
729 conflicts=0
730
731 repos=( ${lib.escapeShellArgs repoNames} )
732 for name in "''${repos[@]}"; do
733 repo="${cfg.dataDir}/$name.git"
734 # Check HEAD rather than the directory itself so a pre-existing
735 # empty directory still gets initialized.
736 if [ ! -e "$repo/HEAD" ]; then
737 git init --bare --initial-branch=main "$repo"
738 fi
739
740 # Replacement refs make one object stand in for another wherever
741 # git looks it up. No push may write one, and every reader that
742 # makes a decision disables them, but a ref written before the
743 # hook refused them is still there. It is reported on every
744 # activation and left in place: what it is evidence of is the
745 # operator's to read before anyone deletes it.
746 replaced="$(git -C "$repo" for-each-ref --format=' %(refname) -> %(objectname)' refs/replace/)" || replaced=""
747 if [ -n "$replaced" ]; then
748 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
749 fi
750
751 # Hook scaffolding: post-receive dispatches to post-receive.d/.
752 # Only manage the hook if it is absent or already ours (a store
753 # symlink) — a hand-written hook is left alone.
754 mkdir -p "$repo/hooks/post-receive.d"
755 hook="$repo/hooks/post-receive"
756 if [ -L "$hook" ]; then
757 case "$(readlink "$hook")" in
758 /nix/store/*) ln -sfn ${postReceiveDispatch} "$hook" ;;
759 esac
760 elif [ ! -e "$hook" ]; then
761 ln -s ${postReceiveDispatch} "$hook"
762 fi
763 done
764
765 # Per-project push-mirror hooks, and the queue they write.
766 ${mirrorHookCommands}
767 ${publishQueueCommands}
768
769 # The one structural invariant, on every project the host serves.
770 ${protectHookCommands}
771
772 # The ref-updated publisher hook, on every repo when the bus is on.
773 ${busHookCommands}
774
775 # The project list, published in the instance repository for clients to
776 # discover this host's projects by (valley changes --all): a blob at
777 # ${projectsRef} naming every enabled git project, one per line,
778 # sorted, and nothing else. A host without an instance repository
779 # publishes nothing. The name of every project is disclosed to whoever
780 # can read the instance repository. No push may write the ref, since
781 # the hook refuses every refs/the-valley/* it does not name, so init is
782 # its only writer. It is written before the share sweep below, which
783 # then gives the new object the group's permissions. A list that cannot
784 # be written costs discovery and not the host, so it warns.
785 ${lib.optionalString (instanceRepo != null) ''
786 {
787 projects="$(printf '%s\n' ${lib.escapeShellArgs (lib.sort lib.lessThan repoNames)} |
788 git -C ${instanceRepo} hash-object -w --stdin)" &&
789 git -C ${instanceRepo} update-ref ${projectsRef} "$projects"
790 } || echo "valley-init: could not publish the project list at ${projectsRef} in ${instanceRepo}; clients cannot discover this host's projects until it is" >&2
791 ''}
792
793 # Group-shared repositories, on what the integrator serves.
794 ${lib.optionalString cfg.integrator.enable integratorShareCommands}
795
796 if [ "$conflicts" -ne 0 ]; then
797 echo "valley-init: refusing to report this host converged: the push policy is not what every repository runs" >&2
798 exit 1
799 fi
800 '';
801
802 # The configuration a convergence is of: the init script itself, which
803 # names every hook and every policy file it wires. valley-init records it
804 # when it converges, and the git user's shell lets a push through only
805 # while the record names the configuration the shell was rendered with.
806 convergenceId = builtins.substring 0 32 (builtins.hashString "sha256" valleyInitBody);
807
808 # The record, in the git user's home: valley-init writes it, and nothing
809 # a session reaches can. A dot file never collides with a repository,
810 # because project names begin with an alphanumeric.
811 convergedRecord = "${cfg.dataDir}/.valley-converged";
812
813 # The operator's hold on pushes: while this file exists, the git user's
814 # shell refuses every push, whatever valley-init has recorded. valley-init
815 # never touches it, so a hold placed before a deploy outlasts the
816 # convergence and lasts until the operator removes it — the window a
817 # deploy's audits need.
818 pushHold = "${cfg.dataDir}/.valley-hold";
819
820 # The git user's login shell (valleyhook shell). sshd runs it for every
821 # session, and it names the key files sshd authorizes the git user's keys
822 # from, in sshd's order, so it can find the authenticated key's tag.
823 gitShell = pkgs.writeShellScriptBin "valley-git-shell" ''
824 exec ${valleyhookPackage}/bin/valleyhook shell \
825 --converged ${convergedRecord} \
826 --expect ${convergenceId} \
827 --hold ${pushHold} \
828 --authorized-keys /etc/ssh/authorized_keys.d/${cfg.user} ${
829 lib.optionalString cfg.identity.enable "--authorized-keys ${identityAuthorizedKeys}"
830 } \
831 -- "$@"
832 '';
833
834 # The program every project's pre-receive hook runs: the whole of the ref
835 # policy (valleyhook/), built by this flake.
836 valleyhookPackage = cfg.packages.valleyhook;
837
838 # The grants declared by hand, in the format the compiler writes, so the
839 # hook reads one format whichever wrote it. The holders of the approve
840 # grant are one set under either option, written under the name request
841 # the way the compiler writes them, and a principal named in both is
842 # written once.
843 declaredGrants = pkgs.writeText "valley-grants" (
844 ''
845 # Declared in services.valley.grants — do not edit.
846 ''
847 + lib.concatMapStrings (principal: "request ${principal}\n") (
848 lib.unique (cfg.grants.approve ++ cfg.grants.request)
849 )
850 + lib.concatMapStrings (principal: "restack ${principal}\n") cfg.grants.restack
851 );
852
853 # Every file the hook reads grants from. The compiled file is added to the
854 # declared one rather than replacing it, the same way the compiled keys
855 # are added to the declared keys: a compilation can only ever grant more.
856 grantFiles = [ declaredGrants ] ++ lib.optional cfg.identity.enable identityGrants;
857
858 # The keys a pushed attestation's signature is checked against: the ones
859 # a controller accepts evidence from. An attestation no controller here
860 # would accept cannot take a name in the create-only namespace, and a host
861 # that names no such keys accepts no attestation at all.
862 hookVerifiers = lib.optional (knownSigners != "") knownSigners;
863
864 # What a project declares about pushes, as valleyhook reads it: the
865 # protected refs and their writers, empty for a project that declares no
866 # protection, and the project's named grants.
867 pushPolicy =
868 name: p:
869 pkgs.writeText "valley-push-policy-${name}.json" (
870 builtins.toJSON {
871 refs = p.protection.refs or [ ];
872 writers = p.protection.writers or [ ];
873 grants = p.grants or { };
874 }
875 );
876
877 # The pre-receive hook: the one structural git invariant
878 # (archive/design/architecture.md, archive/design/contribute.md), which is what a push may
879 # write. It is installed on every project the host serves. Replacement
880 # refs, notes and the valley's own namespace take no push, but for the
881 # four namespaces below; a symbolic ref takes none; topic branches are
882 # open; an attestation ref may only be created, and only holding what its
883 # name says; an integration request takes the approve grant; a change
884 # record moves only by the transitions the hook allows; the plan graph,
885 # refs/the-valley/knots, takes any named principal's write of one commit
886 # on its tip that keeps the graph valid; every other ref, tags included,
887 # takes a named grant of the project; and a protected ref also takes a
888 # declared writer. All policy beyond this lives in the integrator.
889 #
890 # The rules are valleyhook's, in Go, and this script is only how git
891 # reaches it. It hands over what the policy is a function of: the pushing
892 # principal, the project's declared push policy, the grants, the keys an
893 # attestation is checked against, and the hook a project composes after
894 # it, if it declares one.
895 #
896 # A declaration usually names no writer at all, and then the protected
897 # refs take no push from anyone. That is the norm, not a
898 # misconfiguration: the integrator writes the ref locally, and a local
899 # write is not a push.
900 #
901 # Pushes arrive over SSH as one shared git user, so the unix account
902 # behind a push says nothing about who pushed. The principal comes from
903 # the key instead: services.valley.authorizedKeys tags each key's
904 # authorized_keys entry, the git user's shell reads the tag off the entry
905 # of the key sshd authenticated and puts it in the environment of the
906 # receive-pack this hook runs under, and an untagged key has no principal
907 # at all. The client cannot supply the tag itself: the shell drops any it
908 # arrives with, and the assertions below hold sshd to offering no client
909 # environment that could carry it.
910 #
911 # This governs pushes, which is every write that crosses the host
912 # boundary. It does not govern writes made on the host: the integrator
913 # updates refs locally, as could anyone holding the git user's shell.
914 # Local access is the host's own boundary, not this hook's.
915 protectHook =
916 name: p:
917 pkgs.writeShellScript "valley-protect-${name}" ''
918 # Managed by services.valley — do not edit.
919 exec ${valleyhookPackage}/bin/valleyhook pre-receive \
920 --project ${lib.escapeShellArg name} \
921 --policy ${pushPolicy name p} \
922 ${lib.concatMapStringsSep " " (f: "--grants ${f}") grantFiles} \
923 ${lib.concatMapStringsSep " " (f: "--known-signers ${f}") hookVerifiers} \
924 ${lib.optionalString (cfg.extraPreReceive ? ${name}) "--then ${cfg.extraPreReceive.${name}}"} \
925 --principal="''${${principalEnv}:-}"
926 '';
927
928 # Per-project pre-receive wiring, on every project the host serves. A
929 # hook that is not this module's is a hook that would run instead of the
930 # push policy, so valley-init refuses to leave one in place: it says so,
931 # and the activation fails once everything else is wired. The one
932 # exception is a hook identical to the one the project composes after the
933 # policy (services.valley.extraPreReceive), which is checked byte for byte
934 # and then replaced, since the managed hook runs it. A store symlink is
935 # this module's, whichever store path it names, and is re-pointed.
936 #
937 # core.hooksPath moves where git looks for hooks at all, from any scope
938 # the git user reads — the repository's config, the user's, the system's,
939 # or a file one of them includes. A repository whose hooks path is set at
940 # all, to an empty value included, is refused the same way, with no
941 # exception.
942 protectHookCommands = lib.concatStrings (
943 lib.mapAttrsToList (name: p: ''
944 served=${lib.escapeShellArg "${cfg.dataDir}/${name}.git"}
945 phook="$served/hooks/pre-receive"
946 managed=${protectHook name p}
947 composed=${lib.escapeShellArg (toString (cfg.extraPreReceive.${name} or ""))}
948 if [ -L "$phook" ] && [[ "$(readlink "$phook")" == /nix/store/* ]]; then
949 ln -sfn "$managed" "$phook"
950 elif [ ! -e "$phook" ] && [ ! -L "$phook" ]; then
951 ln -s "$managed" "$phook"
952 elif [ -n "$composed" ] && [ -f "$phook" ] && cmp -s "$phook" "$composed"; then
953 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
954 ln -sfn "$managed" "$phook"
955 else
956 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
957 conflicts=1
958 fi
959 # Exit status 1 is the one answer that means unset. A value, an
960 # empty one included — git then looks for hooks relative to where it
961 # runs — and a configuration git cannot read are all refused.
962 hooks_path="$(git -C "$served" config --get core.hooksPath)" && status=0 || status=$?
963 if [ "$status" -ne 1 ]; then
964 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
965 conflicts=1
966 fi
967 '') gitProjects
968 );
969
970 # sshd's environment patterns, for the assertions that hold it to
971 # accepting no client environment the push boundary reads. `*` and `?` are
972 # the only wildcards an AcceptEnv pattern has, and a pattern is matched
973 # as written: variable names are case-sensitive.
974 sshPatternMatches =
975 pattern: name:
976 builtins.match (lib.concatMapStrings (
977 c:
978 if c == "*" then
979 ".*"
980 else if c == "?" then
981 "."
982 else if builtins.match "[A-Za-z0-9_]" c != null then
983 c
984 else
985 "\\${c}"
986 ) (lib.stringToCharacters pattern)) name != null;
987
988 # Whether some name beginning with prefix matches pattern: the pattern
989 # walked over the prefix, with the rest of the name free.
990 sshPatternMatchesSomeName =
991 pattern: prefix:
992 if prefix == "" then
993 true
994 else if pattern == "" then
995 false
996 else
997 let
998 c = builtins.substring 0 1 pattern;
999 rest = builtins.substring 1 (-1) pattern;
1000 next = builtins.substring 1 (-1) prefix;
1001 in
1002 if c == "*" then
1003 sshPatternMatchesSomeName rest prefix || sshPatternMatchesSomeName pattern next
1004 else if c == "?" || c == builtins.substring 0 1 prefix then
1005 sshPatternMatchesSomeName rest next
1006 else
1007 false;
1008
1009 # A variable the push boundary reads, and no client may supply: the
1010 # principal, and anything git reads its configuration, hooks or objects
1011 # from.
1012 boundaryVariable = pattern: sshPatternMatches pattern principalEnv || sshPatternMatchesSomeName pattern "GIT_";
1013
1014 # A refname glob as the declaration writes one, where `*` crosses path
1015 # separators (schema/valley.cue).
1016 refPatternMatches =
1017 pattern: ref:
1018 builtins.match (lib.concatMapStrings (
1019 c:
1020 if c == "*" then
1021 ".*"
1022 else if builtins.match "[A-Za-z0-9/_-]" c != null then
1023 c
1024 else
1025 "\\${c}"
1026 ) (lib.stringToCharacters pattern)) ref != null;
1027
1028 # Whether ref is a full ref name, which the identity registry is read at.
1029 # It opens with refs/ and holds letters, digits, dots, dashes, underscores
1030 # and slashes alone. git check-ref-format accepts it: no component is
1031 # empty, opens with a dot or ends with .lock, and it holds no ".." and
1032 # does not end with a dot. readaccess.ValidRef accepts every name this
1033 # accepts.
1034 fullRefName =
1035 ref:
1036 builtins.match "refs/[A-Za-z0-9._/-]+" ref != null
1037 && !(lib.hasInfix ".." ref)
1038 && !(lib.hasSuffix "." ref)
1039 && lib.all (part: part != "" && !(lib.hasPrefix "." part) && !(lib.hasSuffix ".lock" part)) (
1040 lib.splitString "/" ref
1041 );
1042
1043 # Every value sshd is given for one keyword, from the settings and from
1044 # every line of extraConfig, inside a Match block or not. The keyword is
1045 # matched in any case, as sshd matches it, with or without `=` after it;
1046 # the values are kept as written, because sshd's patterns and variable
1047 # names are case-sensitive. Values are split on any whitespace, tabs
1048 # included, as sshd splits them. Quoting and escapes are not unpicked
1049 # here: a value holding a quote or a backslash is refused below instead,
1050 # because a reading that differed from sshd's would be a hole.
1051 sshdValues =
1052 keyword:
1053 let
1054 settings = config.services.openssh.settings;
1055 word = x: if lib.isBool x then (if x then "yes" else "no") else toString x;
1056 words = v: lib.filter (w: lib.isString w && w != "") (builtins.split "[[:space:]]+" v);
1057 fromSettings = lib.concatMap (
1058 k:
1059 let
1060 v = settings.${k};
1061 in
1062 if lib.isList v then lib.concatMap (x: words (word x)) v else words (word v)
1063 ) (lib.filter (k: lib.toLower k == lib.toLower keyword && settings.${k} != null) (lib.attrNames settings));
1064 fromExtra = lib.concatMap (
1065 line:
1066 let
1067 m = builtins.match "[[:space:]]*([A-Za-z]+)[[:space:]]*=?[[:space:]]*(.*)" line;
1068 in
1069 if m == null || lib.toLower (lib.head m) != lib.toLower keyword then
1070 [ ]
1071 else
1072 words (lib.elemAt m 1)
1073 ) (lib.splitString "\n" config.services.openssh.extraConfig);
1074 in
1075 fromSettings ++ fromExtra;
1076
1077 # Every key line the git user's declared authorized_keys holds, from this
1078 # module and from any other, with the principal its tag names ("" for
1079 # none) and the key itself.
1080 declaredKeyEntries = lib.concatMap (
1081 line:
1082 let
1083 key = builtins.match "(.*[[:space:]])?((ssh|ecdsa|sk)-[^[:space:]\"]+)[[:space:]]+([A-Za-z0-9+/=]+)([[:space:]].*)?" line;
1084 tag = builtins.match ".*environment=\"${principalEnv}=([^\"]*)\".*" line;
1085 in
1086 lib.optional (key != null) {
1087 key = lib.elemAt key 3;
1088 principal = if tag == null then "" else lib.head tag;
1089 }
1090 ) config.users.users.${cfg.user}.openssh.authorizedKeys.keys;
1091
1092 # Keys declared more than once under different tags. sshd authorizes a
1093 # key by the first entry that names it, so which principal such a key
1094 # pushes as depends on file order; the assertion below refuses it.
1095 conflictingKeys = lib.filterAttrs (_: entries: lib.length (lib.unique (map (e: e.principal) entries)) > 1) (
1096 lib.groupBy (e: e.key) declaredKeyEntries
1097 );
1098
1099 # The declared key lines, for the compiler: a compiled key that is also
1100 # declared under another tag is refused there, for the same reason.
1101 declaredKeysFile = pkgs.writeText "valley-declared-keys" (
1102 lib.concatLines config.users.users.${cfg.user}.openssh.authorizedKeys.keys
1103 );
1104in
1105{
1106 options.services.valley = {
1107 enable = lib.mkEnableOption "the valley host: declarative bare-git hosting driven by a CUE declaration";
1108
1109 user = lib.mkOption {
1110 type = lib.types.str;
1111 default = "git";
1112 description = "System user that owns the repositories and accepts SSH pushes.";
1113 };
1114
1115 group = lib.mkOption {
1116 type = lib.types.str;
1117 default = "git";
1118 description = "Primary group of the valley git user.";
1119 };
1120
1121 dataDir = lib.mkOption {
1122 type = lib.types.path;
1123 default = "/srv/git";
1124 example = "/mnt/git";
1125 description = ''
1126 Directory holding the bare repositories, one `<name>.git` per
1127 project declared in {option}`services.valley.config`. Also the git
1128 user's home, so clone URLs are relative to it (`git@host:name.git`).
1129 Consumers typically point it at a dedicated dataset.
1130 '';
1131 };
1132
1133 authorizedKeys = lib.mkOption {
1134 type = lib.types.listOf (
1135 lib.types.either lib.types.str (
1136 lib.types.submodule {
1137 options = {
1138 key = lib.mkOption {
1139 type = lib.types.str;
1140 description = "The SSH public key, as it would appear in `authorized_keys`.";
1141 };
1142
1143 principal = lib.mkOption {
1144 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
1145 example = "integrator";
1146 description = ''
1147 Name of the principal this key acts as. Every push made
1148 with the key carries the name, and the pre-receive hook
1149 decides what the name may write: from the project's
1150 `protection` block and named grants in
1151 {option}`services.valley.config`, and from the grants the
1152 name holds ({option}`services.valley.grants`, and the
1153 registry's when it is compiled). Nothing else uses it.
1154 A key is declared once: the same key under two tags, or
1155 tagged and untagged, is refused.
1156 '';
1157 };
1158 };
1159 }
1160 )
1161 );
1162 default = [ ];
1163 example = lib.literalExpression ''
1164 [
1165 "ssh-ed25519 AAAA… someone@somewhere"
1166 {
1167 principal = "integrator";
1168 key = "ssh-ed25519 AAAA… integrator";
1169 }
1170 ]
1171 '';
1172 description = ''
1173 SSH public keys allowed to push/fetch as the git user. Access is
1174 host-level by design: every key can reach every project.
1175
1176 A key written as a plain string is anonymous — it can push, and it
1177 can write nothing protected. A key written as an attribute set
1178 names the principal it acts as, which is the only thing that can
1179 tell one pusher from another: pushes arrive as the shared git user,
1180 so identity has to ride on the key.
1181
1182 Which refs a principal may write is declared, not an option here:
1183 it is a statement about what the host serves, and lives in the
1184 project's `protection` block in
1185 {option}`services.valley.config`. Binding a name to keys is the
1186 machine half — the hand-written form of what the identity registry
1187 compiles (dcr-b87f6e8).
1188
1189 With {option}`services.valley.identity.enable` on, the compiled
1190 keys are added to what sshd reads and the keys here stay
1191 authorized beside them. The list is therefore the way back in when
1192 a compilation is wrong or has not happened yet, and it is never
1193 empty.
1194 '';
1195 };
1196
1197 extraPreReceive = lib.mkOption {
1198 type = lib.types.attrsOf lib.types.pathInStore;
1199 default = { };
1200 example = lib.literalExpression ''
1201 {
1202 app = pkgs.writeShellScript "app-pre-receive" ;
1203 }
1204 '';
1205 description = ''
1206 A further pre-receive hook per project, run after the push policy
1207 accepts a push, with the same input. It can refuse what the policy
1208 accepts and never accept what the policy refuses.
1209
1210 This is the one way to compose a hook with the managed one. A
1211 pre-receive hook the module did not write fails valley-init,
1212 because git would run it instead of the policy. A hook that is
1213 byte-for-byte the one declared here is the exception: valley-init
1214 replaces it with the managed hook, which runs it. The value is a
1215 store path, so what runs is exactly what was declared.
1216 '';
1217 };
1218
1219 # Grants held by hand. The registry names who holds a grant
1220 # (dcr-b87f6e8, dcr-e544f20), and these options are the hand-written
1221 # form of what it compiles, beside it the way the declared keys sit
1222 # beside the compiled ones.
1223 grants = {
1224 approve = lib.mkOption {
1225 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1226 default = [ ];
1227 example = [ "operator" ];
1228 description = ''
1229 Principals holding the approve grant (also accepted as
1230 {option}`services.valley.grants.request`): the ones whose pushes
1231 may file, replace and withdraw an integration request
1232 (`refs/the-valley/integration-requests/*`) on a protected
1233 project. The pre-receive hook refuses every other write to that
1234 namespace, so a principal named neither here, nor in
1235 {option}`services.valley.grants.request`, nor in the registry
1236 cannot file an integration request.
1237
1238 The two options are one grant. The holders are the principals
1239 named in either list, and a principal named in both holds the
1240 grant once.
1241
1242 The grant rides on push. Only a key sshd admits reaches the hook,
1243 so a principal named here also needs a key, declared in
1244 {option}`services.valley.authorizedKeys` or compiled from the
1245 registry.
1246
1247 With {option}`services.valley.identity.enable` on, the holders
1248 the registry names are added to these, and a compiled file can
1249 only ever add. The list is therefore how a host grants approve
1250 before its registry does — including to the operator who has to
1251 file the registry change that grants it.
1252 '';
1253 };
1254
1255 request = lib.mkOption {
1256 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1257 default = [ ];
1258 example = [ "operator" ];
1259 description = ''
1260 Principals holding the approve grant, under the name it had
1261 first. A principal named here holds exactly what one named in
1262 {option}`services.valley.grants.approve` holds, and the holders
1263 are the principals named in either list.
1264 '';
1265 };
1266
1267 restack = lib.mkOption {
1268 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1269 default = [ ];
1270 example = [ "valley-restacker" ];
1271 description = ''
1272 Principals holding the restack grant: the host restacker's. A
1273 holder that neither owns a change nor holds the approve grant may
1274 add exactly one version to the change's record while the change
1275 is ready, on the branch and under the title of its active version,
1276 with itself as the uploader. It may also write restack reports
1277 (`refs/the-valley/restack/main/<change-id>`). The grant permits
1278 no other record write and nothing on integration requests, and a
1279 holder keeps every ordinary power of a named principal.
1280
1281 The grant rides on push, like approve: a principal named here also
1282 needs a key. With {option}`services.valley.identity.enable` on,
1283 the holders the registry names are added to these. The list is
1284 how a host grants restack before its registry does; remove an
1285 entry once the registry grants the same principal.
1286 '';
1287 };
1288 };
1289
1290 config = lib.mkOption {
1291 type = lib.types.path;
1292 example = lib.literalExpression "./valley.cue";
1293 description = ''
1294 Path to the host's CUE declaration (`package valley`) — the
1295 canonical statement of what this valley host serves, validated
1296 against the shipped schema at build time. This is the single domain
1297 input: projects, their push mirrors, and the backup policy are
1298 declared here, never as Nix options.
1299 '';
1300 };
1301
1302 # The event bus. Machine options, not domain: whether this machine runs
1303 # a bus, where it listens, and where its storage lives. What gets
1304 # published onto it is defined portably in ../schema/events.cue.
1305 bus = {
1306 enable = lib.mkEnableOption "the valley event bus: NATS JetStream, onto which every push's ref updates are projected as events";
1307
1308 listen = lib.mkOption {
1309 type = lib.types.str;
1310 default = "127.0.0.1:4222";
1311 example = "192.0.2.10:4222";
1312 description = ''
1313 Address the bus listens on, `host:port`. Localhost by default:
1314 nothing off the host can reach the bus until the consumer widens
1315 this deliberately — e.g. to the host's private network address once a
1316 remote `valley tail` wants in. Local publishers (the ref-updated
1317 hook) connect to this same address, so it must be reachable from
1318 the host itself.
1319 '';
1320 };
1321
1322 storeDir = lib.mkOption {
1323 type = lib.types.path;
1324 default = "${cfg.dataDir}/.bus";
1325 defaultText = lib.literalExpression ''"''${config.services.valley.dataDir}/.bus"'';
1326 description = ''
1327 Directory holding the JetStream file storage. The default lives
1328 under {option}`services.valley.dataDir`; it can never collide
1329 with a repository because project names must start with an
1330 alphanumeric. The stream is a projection of git, rebuildable
1331 with `valley replay` — losing this directory costs one replay.
1332 '';
1333 };
1334 };
1335
1336 # The integrator (archive/design/roadmap.md, Phase 3): the controller that
1337 # lands a change once its evidence still transfers to the current tip.
1338 # Machine options only — whether this host runs controllers, who they
1339 # are, and how often they look. Which projects get one is not an option
1340 # either: it follows from which projects the declaration protects,
1341 # because a protected ref is exactly what a controller exists to write.
1342 integrator = {
1343 enable = lib.mkEnableOption "the valley integrator: one controller per protected project, landing changes whose evidence transfers";
1344
1345 user = lib.mkOption {
1346 type = lib.types.str;
1347 default = "valley-integrator";
1348 description = ''
1349 System user the controllers run as. Deliberately not
1350 {option}`services.valley.user`: one unix identity per service is
1351 the split bd-500adf7 asks for, and this service begins it.
1352
1353 The account exists only to write the repositories it serves. It
1354 gets no shell and no SSH key, and its primary group is
1355 {option}`services.valley.group`, which is the whole of its
1356 permission model: {option}`services.valley.dataDir` is already
1357 group-readable, and each served repository is made group-shared
1358 (group write, setgid directories) so a controller can write
1359 refs, objects, and git's worktree metadata. Nothing else on the
1360 host belongs to that group, and the bus's store directory (mode
1361 0700) stays out of reach.
1362
1363 The key and signers files are the consumer's to provision; both
1364 must be readable by this user.
1365 '';
1366 };
1367
1368 signingKeyFile = lib.mkOption {
1369 type = lib.types.nullOr lib.types.path;
1370 default = null;
1371 example = "/run/agenix/valley-integrator-key";
1372 description = ''
1373 ed25519 private key the controllers sign their transfer
1374 statements with. A runtime path the consumer provisions (e.g.
1375 agenix), never a store path — the store is world-readable.
1376 '';
1377 };
1378
1379 knownSignersFile = lib.mkOption {
1380 type = lib.types.nullOr lib.types.path;
1381 default = null;
1382 example = "/var/lib/valley-instance/known_signers";
1383 description = ''
1384 File of verifier keys whose attestations count, one per line, in
1385 `attest key` format. This is the identity registry's interim
1386 compilation (dcr-b87f6e8), supplied directly for a host that does
1387 not compile one: turning on
1388 {option}`services.valley.identity.enable` renders the same file
1389 from the registry, and then this option must be left unset.
1390 Evidence signed by nobody in it does not transfer, which a
1391 controller reports per check rather than treating as a forgery.
1392 '';
1393 };
1394
1395 signerProjects = lib.mkOption {
1396 type = lib.types.attrsOf (lib.types.listOf lib.types.str);
1397 default = { };
1398 example = {
1399 "worker/attestations" = [ "the-valley" ];
1400 };
1401 description = ''
1402 Signers whose attestations count only in the projects listed for
1403 them, by the name each signs under. A signer named here counts
1404 in its listed projects alone; in any other project a controller
1405 reports its evidence as signed by no signer it holds. An empty
1406 list lets the signer count nowhere. A signer not named here
1407 counts wherever the known-signers file lets it.
1408
1409 This is how a check worker's key, which every controller sharing
1410 the known-signers file would otherwise accept, is trusted only
1411 for the projects it builds. The push hook still admits the
1412 worker's evidence everywhere; only the controllers restrict it.
1413
1414 List every other controller whose key the known-signers file
1415 holds, such as another host's integrator, with an empty list.
1416 A controller countersigns the attestations a landing carried,
1417 and its own signature never counts as check evidence here;
1418 another controller's counts only until it is listed.
1419
1420 The list is rendered into a file every controller reads at start.
1421 A host that publishes its signers publishes the file beside them,
1422 so a client can read the same restriction. Names and projects are
1423 words of printable ASCII with no space, and a name holds no plus
1424 and does not open with #. The list may not name the name the
1425 controllers sign under: a controller given such a list refuses to
1426 start.
1427 '';
1428 };
1429
1430 signingName = lib.mkOption {
1431 type = lib.types.nullOr lib.types.str;
1432 default = null;
1433 example = "integrator";
1434 description = ''
1435 The name a controller's transfer statements are signed under.
1436 Unset leaves the binary's own default, which is this host's
1437 attestations name — the machine signing as itself.
1438
1439 Set it to the name the identity registry publishes the
1440 integrator's key under. The note format's key hash binds the name
1441 to the key (dcr-de9d996), so a controller signing under one name
1442 while the registry publishes it under another produces notes no
1443 verifier can find a key for.
1444 '';
1445 };
1446
1447 instanceProject = lib.mkOption {
1448 type = lib.types.nullOr lib.types.str;
1449 default = null;
1450 example = "valley";
1451 description = ''
1452 The project whose served repository carries the group's floor —
1453 the instance policy layer every controller on this host composes
1454 against. A controller reads it from `policy/instance/` in that
1455 bare repository's integrated tip, and nothing is materialized on
1456 disk in between. It is also where the identity registry is read
1457 from, for the same reason and at the same altitude: both are the
1458 instance's, so a host serving that repository already holds the
1459 authoritative copy.
1460
1461 The floor is the instance repository's, read at the tip that has
1462 been integrated (dcr-f41f718); the instance repository is the
1463 group's own (dcr-b87f6e8). A host serving it is therefore already
1464 holding the authoritative copy.
1465
1466 What follows is a property of that design, and worth knowing
1467 before editing a floor. A change to it takes effect at the first
1468 pass after it lands on that ref, and never before. An edit in a
1469 branch, in a worktree, or in an integration request that has not
1470 been integrated governs nothing. There is no refresh to trigger
1471 and no staleness to wait out: landing is the whole of publishing
1472 a floor.
1473
1474 The project has to declare protection covering refs/heads/main,
1475 and the registry's ref when the identity compiler is on. Both
1476 are read from that tip, so a ref any push-capable key could move
1477 would hand every key the floor and the registry.
1478
1479 Every controller on the host reads the same repository, the
1480 controller serving that repository included. Both layers are
1481 resolved from the controller's own side — this one, and the
1482 project's `policy/project/` at the target tip — so a change can
1483 never supply the policy that gates it (bd-eaefe82).
1484
1485 Those two directories are the convention, and the module states
1486 neither: a controller takes each layer from the place the
1487 integrator defaults to, so a host declaration that says nothing
1488 about policy gets the layout the worked example lays out
1489 (dcr-f41f718).
1490 '';
1491 };
1492
1493 instancePolicy = lib.mkOption {
1494 type = lib.types.nullOr lib.types.path;
1495 default = null;
1496 example = "/var/lib/valley-instance/policy/instance";
1497 description = ''
1498 Directory of `*.cue` files holding the instance policy layer, for
1499 a host that serves no instance repository. It holds what
1500 `policy/instance/` in the instance repository holds. Set this or
1501 {option}`services.valley.integrator.instanceProject`, never both.
1502
1503 Keeping such a directory in step with the instance repository is
1504 the consumer's to arrange, which is the reason to prefer the
1505 project option wherever the host serves the repository.
1506 '';
1507 };
1508
1509 interval = lib.mkOption {
1510 type = lib.types.str;
1511 default = "15s";
1512 example = "1m";
1513 description = ''
1514 How long a controller waits between passes. The integrator polls
1515 deliberately: integration requests are durable in git, and the
1516 controller level-triggers over those refs, so a lost event costs
1517 one interval and nothing more.
1518 '';
1519 };
1520 };
1521
1522 # The build slice (oc-03b6f8c): caps on every build this machine's nix
1523 # daemon runs, whoever asked for it. A host decision of its own, and a
1524 # condition of the check worker, which builds through the daemon.
1525 buildSlice = {
1526 enable = lib.mkEnableOption ''
1527 capping every build the nix daemon on this host runs, for every user
1528 of it, together: the daemon runs in one slice with a CPU quota, a
1529 memory cap and no swap'';
1530
1531 cpuQuota = lib.mkOption {
1532 type = lib.types.str;
1533 default = "400%";
1534 example = "800%";
1535 description = ''
1536 The CPU time every build the daemon runs gets together, as
1537 systemd's CPUQuota: 400% is four CPUs' worth.
1538 '';
1539 };
1540
1541 memoryMax = lib.mkOption {
1542 type = lib.types.str;
1543 default = "8G";
1544 example = "16G";
1545 description = ''
1546 The memory every build the daemon runs gets together, as
1547 systemd's MemoryMax. The slice gets no swap. A build that takes
1548 the slice past it is ended by the kernel's OOM killer, which kills
1549 the process in the slice using the most memory: usually the
1550 build that went past, but any build in the slice can be the one
1551 killed.
1552 '';
1553 };
1554 };
1555
1556 # The check worker (oc-13c6bd6): a timer that runs one pass of
1557 # valley-worker over the projects listed, so ready changes have their
1558 # nix checks built before anyone approves them. Machine options only —
1559 # whether this host runs the worker, for which of its projects, under
1560 # which signing name, how often, and where it keeps its state.
1561 worker = {
1562 enable = lib.mkEnableOption ''
1563 the valley check worker: a timer that builds the nix checks ready
1564 changes require and publishes the evidence, under its own key, for
1565 the projects listed'';
1566
1567 projects = lib.mkOption {
1568 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1569 default = [ ];
1570 example = [ "the-valley" ];
1571 description = ''
1572 The projects the worker builds evidence for. Each is a project
1573 this host serves, and no other project is read.
1574
1575 The controllers count the worker's evidence in these projects and
1576 no others: {option}`services.valley.integrator.signerProjects`
1577 must list exactly these projects under
1578 {option}`services.valley.worker.signerName`, and the module
1579 refuses a host where it does not.
1580 '';
1581 };
1582
1583 signerName = lib.mkOption {
1584 type = lib.types.str;
1585 example = "worker/attestations";
1586 description = ''
1587 The name the worker signs its notes under. It is a name of the
1588 worker's own: never the operator's, and never the name the
1589 controllers sign under, which the module refuses.
1590
1591 Enrolled with the worker's key, it is what the known-signers file
1592 and the identity registry hold for the worker: the registry key's
1593 `signs`, and the name in the verifier line.
1594 '';
1595 };
1596
1597 interval = lib.mkOption {
1598 type = lib.types.str;
1599 default = "1m";
1600 example = "5m";
1601 description = ''
1602 How long the timer waits after one pass ends before it starts the
1603 next; systemd's default timer accuracy can add up to a minute. A
1604 pass that has nothing to build reads origin and ends.
1605 '';
1606 };
1607
1608 stateDir = lib.mkOption {
1609 type = lib.types.path;
1610 default = "/var/lib/valley-worker";
1611 description = ''
1612 The worker's own directory, mode 0700 and owned by the
1613 `valley-worker` user. It holds the worker's key, made on the
1614 first start and readable by the worker alone; its public halves,
1615 `key.pub` and `verifier`; the lock and the record of failed
1616 batches; and the clones the worker reads projects through.
1617 '';
1618 };
1619 };
1620
1621 # The restacker (restack/): one controller for each project listed,
1622 # which rebases the project's ready changes onto main when main moves,
1623 # as its own principal. Machine options only. Registering the principal
1624 # (its key and its restack grant, in services.valley.authorizedKeys and
1625 # services.valley.grants.restack or in the registry) and provisioning
1626 # its private key are the operator's, and nothing here does either.
1627 restacker = {
1628 enable = lib.mkEnableOption ''
1629 the valley restacker: one controller for each project listed, which
1630 rebases the project's ready changes onto main when main moves,
1631 pushing over this host's sshd as its own principal'';
1632
1633 projects = lib.mkOption {
1634 type = lib.types.listOf (lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*");
1635 default = [ ];
1636 example = [ "the-valley" ];
1637 description = ''
1638 The projects the restacker serves, each a project this host
1639 serves. Each gets a controller of its own,
1640 `valley-restacker@<project>.service`, with a state directory of
1641 its own under `/var/lib/valley-restacker`.
1642 '';
1643 };
1644
1645 principal = lib.mkOption {
1646 type = lib.types.strMatching "[a-zA-Z0-9][a-zA-Z0-9._-]*";
1647 default = "valley-restacker";
1648 description = ''
1649 The principal the restacker pushes as, and names as the uploader
1650 of every version it adds. Its key must be declared under this
1651 name, and the name must hold the restack grant, for the hook to
1652 take its versions and reports. A deployment declares both; this
1653 module does neither.
1654 '';
1655 };
1656
1657 sshKeyFile = lib.mkOption {
1658 type = lib.types.nullOr lib.types.str;
1659 default = null;
1660 example = "/run/agenix/valley-restacker-key";
1661 description = ''
1662 The private ssh key the restacker authenticates with, kept
1663 outside the Nix store. systemd reads it as root and hands it to
1664 each controller as a credential, so the file may stay readable
1665 by root alone. Its public half is what the operator declares
1666 for {option}`services.valley.restacker.principal`.
1667 '';
1668 };
1669
1670 interval = lib.mkOption {
1671 type = lib.types.str;
1672 default = "15s";
1673 example = "1m";
1674 description = ''
1675 How long a controller waits after one pass before the next. A
1676 pass reads origin whether or not main has moved, so a change
1677 readied since the last pass is found without another landing.
1678 After a pass that fails, the wait doubles, up to five minutes,
1679 until a pass succeeds.
1680 '';
1681 };
1682 };
1683
1684 # The identity registry compiler (dcr-b87f6e8): the step between the
1685 # instance's declared registry and the two gates that read what it
1686 # compiles to. Machine options only — whether this host compiles, and
1687 # from where. Who the principals are, what they hold and when their
1688 # entries end is the registry's, and the registry is a document in the
1689 # instance repository, never an option here.
1690 identity = {
1691 enable = lib.mkEnableOption ''
1692 compiling the identity registry into what the gates check: the
1693 verifier keys a controller accepts evidence from, and the git
1694 user's authorized keys, both rendered from the instance
1695 repository's integrated tip'';
1696
1697 ref = lib.mkOption {
1698 type = lib.types.str;
1699 default = "refs/heads/main";
1700 description = ''
1701 The ref of the instance repository whose tip carries the
1702 registry: a full ref name, opening with `refs/`, in letters,
1703 digits, dots, dashes, underscores and slashes. A short name such
1704 as `main` is refused. A registry edit takes effect at the first
1705 compilation after it lands on this ref, and never before: an edit
1706 in a branch, in a worktree, or in an integration request that has
1707 not been integrated governs nothing. The web publisher
1708 (`services.valley.webPublisher`) reads its read grants from the
1709 registry at this ref too.
1710 '';
1711 };
1712
1713 directory = lib.mkOption {
1714 type = lib.types.str;
1715 default = "identity";
1716 description = ''
1717 The registry's directory in that tip. It is a CUE package: the
1718 directory is the enumeration, and every `*.cue` document
1719 directly in it unifies into one registry.
1720 '';
1721 };
1722
1723 interval = lib.mkOption {
1724 type = lib.types.str;
1725 default = "5m";
1726 example = "1m";
1727 description = ''
1728 How long between compilations. The compiler is level-triggered
1729 and idempotent — it renders the current tip and replaces an
1730 artifact only when its bytes changed — so a timer is the whole
1731 of the trigger, and a landed registry change takes effect within
1732 one interval.
1733 '';
1734 };
1735 };
1736
1737 # Machine integration for the declared backup policy. The declaration
1738 # states WHAT must hold (offsite backup, cadence, retention); these
1739 # options supply HOW on this machine — where the repository is and how
1740 # to authenticate. All are paths to files the consumer provisions
1741 # (e.g. agenix), required when the declaration enables backup. Point
1742 # them at runtime paths, never at files in the Nix store.
1743 backup = {
1744 repositoryFile = lib.mkOption {
1745 type = lib.types.nullOr lib.types.path;
1746 default = null;
1747 example = "/run/agenix/valley-restic-repo";
1748 description = ''
1749 File containing the restic repository URL, for the sftp target
1750 e.g. `sftp://backup@backup.example.org:23//./backups/valley`.
1751 '';
1752 };
1753
1754 passwordFile = lib.mkOption {
1755 type = lib.types.nullOr lib.types.path;
1756 default = null;
1757 example = "/run/agenix/valley-restic-password";
1758 description = ''
1759 File containing the restic repository encryption password.
1760 Losing it loses the backups — keep a copy somewhere that
1761 survives this host.
1762 '';
1763 };
1764
1765 sshKeyFile = lib.mkOption {
1766 type = lib.types.nullOr lib.types.path;
1767 default = null;
1768 example = "/run/agenix/valley-git-ssh-key";
1769 description = ''
1770 SSH private key that authenticates to the sftp target. The
1771 backup service runs as root, so any identity the target
1772 authorizes works — reusing the mirror key is fine.
1773 '';
1774 };
1775
1776 knownHostsFile = lib.mkOption {
1777 type = lib.types.nullOr lib.types.path;
1778 default = null;
1779 example = "/var/lib/valley-backup/known_hosts";
1780 description = ''
1781 known_hosts file pinning the sftp target's host key. Pin from
1782 the provider's published fingerprints, not a blind ssh-keyscan.
1783 '';
1784 };
1785 };
1786
1787 # The programs the host runs, as this flake builds them
1788 # (nix/packages.nix). These options are internal: a host has no reason
1789 # to set them. The module checks set them to stand-ins with the same
1790 # binary names (nix/checks/hosts.nix), so a check that reads only what
1791 # the module renders does not change when one of the programs does.
1792 packages = {
1793 integrator = lib.mkOption {
1794 type = lib.types.package;
1795 internal = true;
1796 default = flakePackages.integrator;
1797 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).integrator";
1798 description = "The integrator, which the controllers and the signers publisher run.";
1799 };
1800
1801 identity = lib.mkOption {
1802 type = lib.types.package;
1803 internal = true;
1804 default = flakePackages.identity;
1805 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).identity";
1806 description = "The identity registry compiler, which valley-identity runs.";
1807 };
1808
1809 valleyhook = lib.mkOption {
1810 type = lib.types.package;
1811 internal = true;
1812 default = flakePackages.valleyhook;
1813 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valleyhook";
1814 description = "The push policy, which every pre-receive hook and the git user's login shell run.";
1815 };
1816
1817 restacker = lib.mkOption {
1818 type = lib.types.package;
1819 internal = true;
1820 default = flakePackages.valley-restacker;
1821 defaultText = lib.literalExpression "(import ./packages.nix { inherit pkgs lib; }).valley-restacker";
1822 description = "The restacker, which each restacker controller runs.";
1823 };
1824 };
1825 };
1826
1827 config = lib.mkIf cfg.enable {
1828 assertions = [
1829 {
1830 assertion = cfg.authorizedKeys != [ ];
1831 message = "services.valley.authorizedKeys must not be empty — the git user would be unreachable.";
1832 }
1833 ]
1834 ++ lib.optionals backupEnabled (
1835 lib.mapAttrsToList (name: what: {
1836 assertion = cfg.backup.${name} != null;
1837 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).";
1838 }) backupSecretOptions
1839 )
1840 ++ lib.optionals cfg.integrator.enable (
1841 lib.mapAttrsToList (name: what: {
1842 assertion = cfg.integrator.${name} != null;
1843 message = "services.valley.integrator.${name} must be set: the integrator is enabled, and ${what} is machine integration the consumer supplies.";
1844 }) integratorPathOptions
1845 ++ [
1846 {
1847 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
1848 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.";
1849 }
1850 # The rule the integrator reads the rendered file by
1851 # (note/signerprojects.go): every name and project is printable
1852 # ASCII with no space, so only the spaces this renders separate
1853 # words, and a name holds no plus and opens with no #, which
1854 # would make its line a comment.
1855 {
1856 assertion =
1857 let
1858 word = w: builtins.match "[!-~]+" w != null;
1859 name = n: word n && !lib.hasInfix "+" n && !lib.hasPrefix "#" n;
1860 in
1861 lib.all (n: name n && lib.all word cfg.integrator.signerProjects.${n}) (
1862 lib.attrNames cfg.integrator.signerProjects
1863 );
1864 message = "services.valley.integrator.signerProjects holds a name or project that is empty or not printable ASCII with no space, or a name with a plus or an opening #. The list is rendered one signer per line, its name and projects separated by spaces, and read back by that rule, so such a word would be read as some other signer or project, or refused. Write each as one such word.";
1865 }
1866 {
1867 assertion =
1868 cfg.integrator.instanceProject == null || gitProjects ? ${cfg.integrator.instanceProject};
1869 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.";
1870 }
1871 {
1872 assertion = cfg.integrator.user != cfg.user;
1873 message = "services.valley.integrator.user must differ from services.valley.user: the integrator runs under its own unix identity (bd-500adf7).";
1874 }
1875 {
1876 assertion = integratedProjects != { };
1877 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.";
1878 }
1879 ]
1880 )
1881 # The web publisher (web-publisher.nix) reads the registry at
1882 # identity.ref too, when its module is imported and on.
1883 ++ lib.optional (cfg.identity.enable || config.services.valley.webPublisher.enable or false) {
1884 assertion = fullRefName cfg.identity.ref;
1885 message = "services.valley.identity.ref is ${cfg.identity.ref}, which is not a full ref name. The identity registry is read at that ref, so name it whole, opening with refs/, as git check-ref-format accepts it: refs/heads/main, not main.";
1886 }
1887 ++ lib.optionals (cfg.integrator.instanceProject != null && gitProjects ? ${cfg.integrator.instanceProject}) (
1888 let
1889 name = cfg.integrator.instanceProject;
1890 protected = gitProjects.${name}.protection.refs or [ ];
1891 # The web publisher (web-publisher.nix) reads the registry at
1892 # identity.ref too, when its module is imported and on.
1893 publisher = config.services.valley.webPublisher.enable or false;
1894 read =
1895 lib.optional cfg.integrator.enable "refs/heads/main"
1896 ++ lib.optional (cfg.identity.enable || publisher) cfg.identity.ref;
1897 in
1898 map (ref: {
1899 assertion = lib.any (pattern: refPatternMatches pattern ref) protected;
1900 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}.";
1901 }) read
1902 )
1903 ++ [
1904 {
1905 assertion = !(lib.any (v: builtins.match ".*[\"'\\\\].*" v != null) (
1906 sshdValues "AcceptEnv" ++ sshdValues "SetEnv"
1907 ));
1908 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.";
1909 }
1910 {
1911 assertion = !(lib.any boundaryVariable (sshdValues "AcceptEnv"));
1912 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.";
1913 }
1914 {
1915 assertion = !(lib.any (v: boundaryVariable (lib.head (lib.splitString "=" v))) (sshdValues "SetEnv"));
1916 message = "sshd sets ${principalEnv} or a GIT_ variable itself (SetEnv). Remove it.";
1917 }
1918 {
1919 assertion = lib.all (v: lib.toLower v == "no") (sshdValues "PermitUserEnvironment");
1920 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.";
1921 }
1922 {
1923 assertion = conflictingKeys == { };
1924 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.";
1925 }
1926 {
1927 assertion = config.users.users.${cfg.user}.openssh.authorizedKeys.keyFiles == [ ];
1928 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.";
1929 }
1930 ]
1931 ++ lib.optionals cfg.identity.enable [
1932 {
1933 assertion = cfg.integrator.instanceProject != null;
1934 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.";
1935 }
1936 {
1937 assertion = cfg.integrator.knownSignersFile == null;
1938 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.";
1939 }
1940 ]
1941 ++ lib.optionals cfg.worker.enable (
1942 let
1943 name = cfg.worker.signerName;
1944 listed = cfg.integrator.signerProjects.${name} or null;
1945 sorted = l: lib.sort lib.lessThan (lib.unique l);
1946 unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.worker.projects;
1947 in
1948 [
1949 {
1950 assertion = cfg.integrator.enable;
1951 message = "services.valley.worker.enable needs services.valley.integrator.enable: the worker builds evidence for this host's controllers, and they are what restrict its key to its projects.";
1952 }
1953 {
1954 assertion = cfg.integrator.instanceProject != null;
1955 message = "services.valley.worker.enable needs services.valley.integrator.instanceProject: the worker finds this host's projects through the instance repository, as valley pending --repo does.";
1956 }
1957 {
1958 assertion = cfg.worker.projects != [ ] && unserved == [ ];
1959 message = "services.valley.worker.projects must name at least one project, and only projects this host serves${
1960 lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}"
1961 }.";
1962 }
1963 # The restriction (oc-13c6bd6). Every controller that shares the
1964 # known-signers file counts a key it holds in every project, so a
1965 # worker whose key is not restricted would be trusted for projects
1966 # it never builds.
1967 {
1968 assertion = listed != null && sorted listed == sorted cfg.worker.projects;
1969 message = "services.valley.integrator.signerProjects must restrict ${name}, the worker's signer, to exactly the worker's projects: without the restriction, every controller that holds the worker's key counts its evidence in every project. Set services.valley.integrator.signerProjects.\"${name}\" = [ ${
1970 lib.concatMapStringsSep " " (p: "\"${p}\"") cfg.worker.projects
1971 } ];";
1972 }
1973 {
1974 assertion = name != integratorName;
1975 message = "services.valley.worker.signerName must differ from ${integratorName}, the name the controllers sign under: a controller's signature never counts as check evidence, and a controller refuses to start when the signer projects list names it.";
1976 }
1977 {
1978 assertion = cfg.buildSlice.enable;
1979 message = "services.valley.worker.enable needs services.valley.buildSlice.enable: the worker builds through this host's nix daemon, and only the build slice caps what it makes the daemon do. The slice caps every build the daemon runs, for every user, so turning it on is a decision about the host, made on its own.";
1980 }
1981 {
1982 assertion = config.services.openssh.enable && config.nix.enable;
1983 message = "services.valley.worker.enable needs services.openssh.enable and nix.enable: the worker reaches this host's repositories through its sshd, and builds through its nix daemon.";
1984 }
1985 ]
1986 )
1987 ++ lib.optionals cfg.restacker.enable (
1988 let
1989 unserved = lib.filter (p: !(gitProjects ? ${p})) cfg.restacker.projects;
1990 in
1991 [
1992 {
1993 assertion = cfg.restacker.projects != [ ] && unserved == [ ];
1994 message = "services.valley.restacker.projects must name at least one project, and only projects this host serves${
1995 lib.optionalString (unserved != [ ]) ", and it names ${lib.concatStringsSep ", " unserved}"
1996 }.";
1997 }
1998 {
1999 assertion = cfg.restacker.sshKeyFile != null;
2000 message = "services.valley.restacker.sshKeyFile must be set: the restacker pushes over this host's sshd with a key the operator provisions outside the Nix store.";
2001 }
2002 {
2003 assertion = (cfg.integrator.instanceProject == null) != (cfg.integrator.instancePolicy == null);
2004 message = "services.valley.restacker.enable needs exactly one of services.valley.integrator.instanceProject and services.valley.integrator.instancePolicy: the restacker reads the cap on its versions from the policy the controllers compose, over the floor they read.";
2005 }
2006 {
2007 assertion = config.services.openssh.enable;
2008 message = "services.valley.restacker.enable needs services.openssh.enable: the restacker reaches this host's repositories through its sshd.";
2009 }
2010 ]
2011 );
2012
2013 users.groups.${cfg.group} = { };
2014
2015 users.users.${cfg.user} = {
2016 isSystemUser = true;
2017 group = cfg.group;
2018 home = cfg.dataDir;
2019 # The valley's shell, in front of git-shell: it derives the principal
2020 # from the authenticated key, drops the GIT_ environment, and pauses
2021 # pushes until valley-init has converged. git-shell then allows only
2022 # git-upload-pack, git-receive-pack and git-upload-archive, and rejects
2023 # interactive logins (no ~/git-shell-commands).
2024 shell = "${gitShell}/bin/valley-git-shell";
2025 openssh.authorizedKeys.keys = map authorizedKeyLine cfg.authorizedKeys;
2026 };
2027
2028 # The integrator's own account. No shell, no keys, no home of its own
2029 # beyond the state directory its units get; the git group is the only
2030 # thing it holds.
2031 users.users.${cfg.integrator.user} = lib.mkIf cfg.integrator.enable {
2032 isSystemUser = true;
2033 group = cfg.group;
2034 home = "/var/lib/valley-integrator";
2035 description = "The valley integrator";
2036 };
2037
2038 # The worker's own account. Its group is its own, not the git group, so
2039 # it can neither read nor write the repositories on disk: it reaches
2040 # them as an ssh client, as anyone else does.
2041 users.users.valley-worker = lib.mkIf cfg.worker.enable {
2042 isSystemUser = true;
2043 group = "valley-worker";
2044 home = workerDir;
2045 description = "The valley check worker";
2046 };
2047 users.groups.valley-worker = lib.mkIf cfg.worker.enable { };
2048
2049 # The restacker's own account. Its group is its own, not the git group,
2050 # so it can neither read nor write the repositories on disk, and it is
2051 # in no group that reads the integrator's or the worker's keys: it
2052 # reaches the repositories as an ssh client, as its own principal.
2053 users.users.valley-restacker = lib.mkIf cfg.restacker.enable {
2054 isSystemUser = true;
2055 group = "valley-restacker";
2056 home = "/var/lib/${restackerStateName}";
2057 description = "The valley restacker";
2058 };
2059 users.groups.valley-restacker = lib.mkIf cfg.restacker.enable { };
2060
2061 services.openssh.enable = lib.mkDefault true;
2062
2063 # The git user's key files, named in its Match block so no other file
2064 # can authorize a key for it. The declared keys come first, and they stay
2065 # authorized beside the compiled ones: a compiled file can only ever
2066 # add, so an empty or missing one — a first boot before the first
2067 # compilation, a registry that lost an entry, a bug here — cannot take
2068 # the git user's access away. Which is the point: the assertion above
2069 # keeps at least one key declared, and that key is the way back in.
2070 #
2071 # Nothing else authorizes a key for the git user. ~/.ssh/authorized_keys
2072 # under its home is not read, and no AuthorizedKeysCommand runs, so every
2073 # entry a pusher can arrive through carries the tag this module or the
2074 # compiler wrote, and the assertions and the compiler hold those to one
2075 # tag per key.
2076 #
2077 # Belt-and-braces hardening for the git user beside it. The trailing
2078 # `Match All` closes the block so it can't scope directives appended to
2079 # sshd_config after this snippet.
2080 services.openssh.extraConfig = ''
2081 Match User ${cfg.user}
2082 AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u${lib.optionalString cfg.identity.enable " ${identityAuthorizedKeys}"}
2083 AuthorizedKeysCommand none
2084 ExposeAuthInfo yes
2085 AllowTcpForwarding no
2086 AllowAgentForwarding no
2087 X11Forwarding no
2088 PermitTunnel no
2089 Match All
2090 '';
2091
2092 # git-shell spawns git-receive-pack/git-upload-pack from PATH
2093 environment.systemPackages = [ pkgs.git ];
2094
2095 systemd.tmpfiles.rules = [
2096 "d ${cfg.dataDir} 0750 ${cfg.user} ${cfg.group} - -"
2097 ]
2098 ++ lib.optionals cfg.bus.enable [
2099 "d ${cfg.bus.storeDir} 0700 ${cfg.user} ${cfg.group} - -"
2100 ]
2101 ++ lib.optionals cfg.worker.enable [
2102 "d ${workerDir} 0700 valley-worker valley-worker - -"
2103 ];
2104
2105 # The bus itself. It runs as the git user — the store directory lives in
2106 # that user's data — but the sandbox is what confines it: the unit can
2107 # write nowhere except its store directory.
2108 systemd.services.valley-bus = lib.mkIf cfg.bus.enable {
2109 description = "The valley event bus (NATS JetStream)";
2110 wantedBy = [ "multi-user.target" ];
2111 after = [
2112 "network.target"
2113 "systemd-tmpfiles-setup.service"
2114 ];
2115 unitConfig.RequiresMountsFor = cfg.bus.storeDir;
2116 serviceConfig = {
2117 ExecStart = "${pkgs.nats-server}/bin/nats-server -c ${busServerConfig}";
2118 Restart = "on-failure";
2119 User = cfg.user;
2120 Group = cfg.group;
2121 LimitNOFILE = 65536;
2122 NoNewPrivileges = true;
2123 ProtectSystem = "strict";
2124 ReadWritePaths = [ cfg.bus.storeDir ];
2125 ProtectHome = true;
2126 PrivateTmp = true;
2127 PrivateDevices = true;
2128 ProtectClock = true;
2129 ProtectHostname = true;
2130 ProtectKernelLogs = true;
2131 ProtectKernelModules = true;
2132 ProtectKernelTunables = true;
2133 ProtectControlGroups = true;
2134 ProtectProc = "invisible";
2135 RestrictAddressFamilies = [
2136 "AF_INET"
2137 "AF_INET6"
2138 "AF_UNIX"
2139 ];
2140 RestrictNamespaces = true;
2141 RestrictRealtime = true;
2142 RestrictSUIDSGID = true;
2143 LockPersonality = true;
2144 CapabilityBoundingSet = "";
2145 SystemCallArchitectures = "native";
2146 SystemCallFilter = [ "@system-service" ];
2147 UMask = "0077";
2148 };
2149 };
2150
2151 # The stream is config, not state: (re)created idempotently on every
2152 # boot, capturing everything under valley.>. An existing stream — and
2153 # the events in it — is left untouched.
2154 systemd.services.valley-bus-init = lib.mkIf cfg.bus.enable {
2155 description = "Create the valley event stream";
2156 wantedBy = [ "multi-user.target" ];
2157 requires = [ "valley-bus.service" ];
2158 after = [ "valley-bus.service" ];
2159 serviceConfig = {
2160 Type = "oneshot";
2161 User = cfg.user;
2162 Group = cfg.group;
2163 };
2164 path = [ pkgs.natscli ];
2165 script = ''
2166 # The server needs a moment to accept connections after startup.
2167 for _ in $(seq 1 50); do
2168 nats --server ${busUrl} stream ls >/dev/null 2>&1 && break
2169 sleep 0.2
2170 done
2171 if ! nats --server ${busUrl} stream info valley >/dev/null 2>&1; then
2172 nats --server ${busUrl} stream add valley \
2173 --subjects 'valley.>' --storage file --defaults
2174 fi
2175 '';
2176 };
2177
2178 # Create missing bare repos and (re)wire the managed hooks on every
2179 # activation where the declaration changed.
2180 systemd.services.valley-init = {
2181 description = "Initialize the valley host's bare git repositories";
2182 wantedBy = [ "multi-user.target" ];
2183 after = [ "systemd-tmpfiles-setup.service" ];
2184 unitConfig.RequiresMountsFor = cfg.dataDir;
2185 serviceConfig = {
2186 Type = "oneshot";
2187 User = cfg.user;
2188 Group = cfg.group;
2189 };
2190 path = [
2191 pkgs.git
2192 pkgs.diffutils
2193 ];
2194 # Everything init can wire is wired before it fails. A conflict in one
2195 # repository is reported, the rest of the host is still converged,
2196 # and only then does the unit fail, so the activation fails loudly
2197 # without leaving another repository's hook out of date.
2198 script = ''
2199 # Pushes pause the moment a convergence starts, and resume only once
2200 # it has finished: the record is removed first and written last.
2201 rm -f ${convergedRecord}
2202 ${valleyInitBody}
2203 printf '%s\n' ${convergenceId} > ${convergedRecord}.tmp
2204 mv -f ${convergedRecord}.tmp ${convergedRecord}
2205 '';
2206 };
2207
2208 # The registry compiler, on a timer. It renders the instance
2209 # repository's integrated tip into the two artifacts the gates read;
2210 # nothing else on the host writes them.
2211 #
2212 # It runs as the git user rather than under an identity of its own,
2213 # which is the one place this module steps back from the service split
2214 # bd-500adf7 asks for. sshd refuses an authorized-keys file owned by
2215 # anyone but root or the account it authorizes, so the choice is the git
2216 # user or root, and the git user is the smaller grant.
2217 #
2218 # Level-triggered, like the rest: a compilation reads the current tip
2219 # and replaces an artifact only when its bytes changed, so re-running is
2220 # free and the timer needs no coordination with anything.
2221 systemd.services.valley-identity = lib.mkIf cfg.identity.enable {
2222 description = "Compile the valley identity registry into what the gates check";
2223 wantedBy = [ "multi-user.target" ];
2224 after = [ "valley-init.service" ];
2225 requires = [ "valley-init.service" ];
2226 unitConfig.RequiresMountsFor = cfg.dataDir;
2227 serviceConfig = {
2228 Type = "oneshot";
2229 ExecStart = identityCommand;
2230 User = cfg.user;
2231 Group = cfg.group;
2232 StateDirectory = identityStateName;
2233 # sshd walks every directory above an authorized-keys file and
2234 # refuses a group- or world-writable one, so the state directory is
2235 # 0755 deliberately rather than the 0700 a service's state usually
2236 # takes. Nothing secret lives in it: a registry is public keys.
2237 StateDirectoryMode = "0755";
2238 NoNewPrivileges = true;
2239 ProtectSystem = "strict";
2240 ReadWritePaths = [ identityStateDir ];
2241 ProtectHome = true;
2242 PrivateTmp = true;
2243 PrivateDevices = true;
2244 ProtectClock = true;
2245 ProtectHostname = true;
2246 ProtectKernelLogs = true;
2247 ProtectKernelModules = true;
2248 ProtectKernelTunables = true;
2249 ProtectControlGroups = true;
2250 ProtectProc = "invisible";
2251 RestrictAddressFamilies = [ "AF_UNIX" ];
2252 RestrictNamespaces = true;
2253 RestrictRealtime = true;
2254 RestrictSUIDSGID = true;
2255 LockPersonality = true;
2256 CapabilityBoundingSet = "";
2257 SystemCallArchitectures = "native";
2258 SystemCallFilter = [ "@system-service" ];
2259 UMask = "0022";
2260 };
2261 };
2262
2263 systemd.timers.valley-identity = lib.mkIf cfg.identity.enable {
2264 description = "Re-compile the valley identity registry";
2265 wantedBy = [ "timers.target" ];
2266 timerConfig = {
2267 OnBootSec = "1m";
2268 OnUnitActiveSec = cfg.identity.interval;
2269 };
2270 };
2271
2272 # The signers publication, refs/the-valley/signers, is written by a
2273 # oneshot of its own. It runs as the git user, which owns the instance
2274 # repository, and its sandbox lets it write that repository and nothing
2275 # else. It is not part of valley-init, which runs only on activation,
2276 # nor of the registry compiler, whose sandbox writes only its state
2277 # directory. Only the host's machinery writes the ref, never a push:
2278 # the hook refuses every push to it. This unit writes it, and the
2279 # integrator can, being in the group the repository is shared with
2280 # because it lands code there.
2281 #
2282 # What starts it: every boot and every activation, after valley-init,
2283 # which covers a changed signing name, signers path or signer projects
2284 # list; and the path
2285 # unit below, whenever the known-signers file changes, which covers
2286 # each compilation that changed it and a hand-provisioned file being
2287 # replaced. A run reads the current file and name and writes the ref
2288 # only when the tree it makes differs, so a run with nothing new is
2289 # free. Both values are in one tree under one ref, so a client never
2290 # reads one value without the other. A run holds a lock in the
2291 # instance repository from reading the file to moving the ref, so two
2292 # runs take turns, and one that read an older file cannot publish it
2293 # over a newer one. The ref also moves with a compare-and-swap.
2294 #
2295 # A run that cannot read the file, or reads one that is not a list of
2296 # verifier keys, fails and leaves the last publication in place. That
2297 # is the file the controllers were given before it changed, and the
2298 # journal says why. A file with no key in it, as the compiler writes
2299 # once every signing key is revoked, is published, so clients stop
2300 # verifying with the revoked keys.
2301 systemd.services.valley-signers = lib.mkIf publishesSigners {
2302 description = "Publish what clients verify the valley integrator's transfer statements with";
2303 wantedBy = [ "multi-user.target" ];
2304 after = [ "valley-init.service" ] ++ lib.optional cfg.identity.enable "valley-identity.service";
2305 requires = [ "valley-init.service" ];
2306 unitConfig.RequiresMountsFor = cfg.dataDir;
2307 serviceConfig = {
2308 Type = "oneshot";
2309 ExecStart = signersCommand;
2310 User = cfg.user;
2311 Group = cfg.group;
2312 NoNewPrivileges = true;
2313 ProtectSystem = "strict";
2314 ReadWritePaths = [ instanceRepo ];
2315 ProtectHome = true;
2316 PrivateTmp = true;
2317 PrivateDevices = true;
2318 ProtectClock = true;
2319 ProtectHostname = true;
2320 ProtectKernelLogs = true;
2321 ProtectKernelModules = true;
2322 ProtectKernelTunables = true;
2323 ProtectControlGroups = true;
2324 ProtectProc = "invisible";
2325 RestrictAddressFamilies = [ "AF_UNIX" ];
2326 RestrictNamespaces = true;
2327 RestrictRealtime = true;
2328 RestrictSUIDSGID = true;
2329 LockPersonality = true;
2330 CapabilityBoundingSet = "";
2331 SystemCallArchitectures = "native";
2332 SystemCallFilter = [ "@system-service" ];
2333 # The instance repository is always one the integrator serves, since
2334 # it has to be protected, so it is group-shared and its directories
2335 # are setgid. With the default umask, git would chmod each directory
2336 # it makes to add group write, setgid bit included, and
2337 # RestrictSUIDSGID refuses that chmod. Group write from the start
2338 # leaves git nothing to chmod, as for the controllers.
2339 UMask = "0002";
2340 };
2341 };
2342
2343 systemd.paths.valley-signers = lib.mkIf publishesSigners {
2344 description = "Watch the known-signers file the valley integrator reads";
2345 wantedBy = [ "multi-user.target" ];
2346 pathConfig.PathChanged = knownSigners;
2347 };
2348
2349 # One controller per served project, as instances of a single template:
2350 # the units differ only in the repository they serve, which is the
2351 # instance name. `watch` rather than a timer firing `reconcile`: the
2352 # binary owns its poll loop and its interval, and a timer would be a
2353 # second cadence over the same level-triggered refs.
2354 systemd.services."valley-integrator@" = lib.mkIf cfg.integrator.enable {
2355 description = "The valley integrator for %i";
2356 after = [
2357 "network.target"
2358 "valley-init.service"
2359 ]
2360 ++ lib.optional cfg.bus.enable "valley-bus-init.service"
2361 ++ lib.optional cfg.identity.enable "valley-identity.service";
2362 requires = [ "valley-init.service" ];
2363 # Wants, not requires: a controller reads the compiled signers file,
2364 # so it starts after the first compilation — but a compilation that
2365 # failed must not keep the controllers down. One that finds no file
2366 # says so and restarts, which is the same loop and a louder one.
2367 wants = lib.optional cfg.identity.enable "valley-identity.service";
2368 unitConfig.RequiresMountsFor = cfg.dataDir;
2369 # nix is not pinned, for the reason the integrator package does not
2370 # pin it: a check's input closure must be recomputed by the nix this
2371 # machine actually runs. Everything else a controller drives is
2372 # pinned inside the wrapper.
2373 path = [ config.nix.package ];
2374 # The repositories belong to the git user and the controller does
2375 # not, so git refuses to touch them as dubiously owned. The exception
2376 # rides in the unit's environment, for two reasons. GIT_CONFIG_* is
2377 # command-scope config, which is protected config, so safe.directory
2378 # is honoured from it — a repository-scoped setting would be ignored,
2379 # deliberately. And every git the controller drives is a child of
2380 # this unit, whether run by the integrator itself or by attest or the
2381 # deriver, so one environment covers all of them.
2382 #
2383 # One repository per instance: never a global gitconfig, never a
2384 # wildcard. Every other repository on the host stays refused. Linked
2385 # worktrees need no entry of their own — the controller creates them,
2386 # so it owns them, and git checks the worktree and its gitdir rather
2387 # than the repository they point at.
2388 #
2389 # TMPDIR is the same kind of wiring, for the same reason. A verdict
2390 # wants a checkout of the tip on disk, and the integrator asks for one
2391 # the ordinary way — a temporary directory, then a linked worktree in
2392 # it. The sandbox below leaves no writable temporary directory, so
2393 # every tick died on `could not create leading directories`. The
2394 # scratch belongs under the state directory the unit already has:
2395 # writable by construction, owned by this service, and gone when the
2396 # service's state is. Setting it in the environment rather than
2397 # teaching the binary a flag covers every process in the unit at once
2398 # — the integrator, attest, the deriver, and the git each of them runs
2399 # all read TMPDIR, and all of them want scratch in the same place.
2400 #
2401 # A second exception, for the instance repository. Every controller
2402 # reads the group's floor from that repository's tip, and it need not
2403 # be the project the controller serves — the controller for one
2404 # project reads the floor out of another project's repository, which
2405 # it likewise does not own. Without the exception git refuses it as
2406 # dubiously owned and every pass fails, exactly as it did for the
2407 # served repository. Two entries, both named; still never a wildcard.
2408 #
2409 # Reading needs no sandbox entry beside it. ProtectSystem=strict
2410 # leaves the filesystem readable and only takes write away, so the
2411 # ReadWritePaths list above stays the list of what may be written,
2412 # which is what makes it worth reading. What read does need is a
2413 # filesystem grant, and valley-init makes it: the instance repository
2414 # is group-readable whether or not it is one of the served projects.
2415 environment = {
2416 GIT_CONFIG_COUNT = if instanceRepo != null then "2" else "1";
2417 GIT_CONFIG_KEY_0 = "safe.directory";
2418 GIT_CONFIG_VALUE_0 = "${cfg.dataDir}/%i.git";
2419 TMPDIR = integratorStateDir;
2420 }
2421 // lib.optionalAttrs (instanceRepo != null) {
2422 GIT_CONFIG_KEY_1 = "safe.directory";
2423 GIT_CONFIG_VALUE_1 = instanceRepo;
2424 };
2425 serviceConfig = {
2426 ExecStart = integratorCommand;
2427 Restart = "on-failure";
2428 RestartSec = "10s";
2429 User = cfg.integrator.user;
2430 Group = cfg.group;
2431 StateDirectory = integratorStateName;
2432 StateDirectoryMode = "0700";
2433 WorkingDirectory = integratorStateDir;
2434 NoNewPrivileges = true;
2435 ProtectSystem = "strict";
2436 # Everything the controller may write, named where a reader of the
2437 # unit meets it. Under ProtectSystem=strict the rest of the
2438 # filesystem is read-only, so this list is the whole of what the
2439 # service can touch, and it is worth being able to read it as such
2440 # rather than as the exceptions plus whatever else is implied.
2441 #
2442 # Its own directory: its state, and the scratch root TMPDIR names.
2443 # A declaration says it here rather than relying on the state
2444 # directory being read-write by virtue of being declared, which is
2445 # not something this unit found to be true.
2446 #
2447 # The one repository it serves, and the nix daemon's socket —
2448 # recomputing a closure means asking the daemon, and connecting to
2449 # a unix socket needs write access to it.
2450 ReadWritePaths = [
2451 integratorStateDir
2452 "${cfg.dataDir}/%i.git"
2453 "/nix/var/nix/daemon-socket"
2454 ];
2455 ProtectHome = true;
2456 PrivateTmp = true;
2457 PrivateDevices = true;
2458 ProtectClock = true;
2459 ProtectHostname = true;
2460 ProtectKernelLogs = true;
2461 ProtectKernelModules = true;
2462 ProtectKernelTunables = true;
2463 ProtectControlGroups = true;
2464 ProtectProc = "invisible";
2465 RestrictAddressFamilies = [
2466 "AF_INET"
2467 "AF_INET6"
2468 "AF_UNIX"
2469 ];
2470 RestrictNamespaces = true;
2471 RestrictRealtime = true;
2472 RestrictSUIDSGID = true;
2473 LockPersonality = true;
2474 CapabilityBoundingSet = "";
2475 SystemCallArchitectures = "native";
2476 SystemCallFilter = [ "@system-service" ];
2477 # Group write, not the bus unit's 0077: the git user owns these
2478 # repositories and has to stay able to write what a controller
2479 # leaves in them.
2480 UMask = "0002";
2481 };
2482 };
2483
2484 # What pushes the mirrors: a path unit per published project, watching
2485 # its publish queue, and the drain it starts.
2486 systemd.paths."valley-publish@" = lib.mkIf (publishedProjects != { }) {
2487 description = "Watch the publish queue of %i";
2488 pathConfig.DirectoryNotEmpty = "${cfg.dataDir}/%i.git/${publishQueueName}";
2489 };
2490
2491 # It runs as the git user, with ssh on its path, because the mirror
2492 # credentials are that user's. Each run drains the whole queue, so starts
2493 # are at most one per queued move, and a burst of moves must not trip
2494 # systemd's start limit and leave the queue undrained. A run is bounded
2495 # instead: one that hangs on a mirror is cut off after 15 minutes, and
2496 # systemd stops its whole cgroup, so nothing it started outlives it. A
2497 # run that fails or is cut off leaves its moves queued, and systemd
2498 # starts it again after a delay that grows from 30 seconds to 15 minutes,
2499 # until a run succeeds. While it waits to restart, the unit is not
2500 # inactive, so the path unit does not start it again sooner.
2501 systemd.services."valley-publish@" = lib.mkIf (publishedProjects != { }) {
2502 description = "Push the moves queued on %i to its mirrors";
2503 after = [ "valley-init.service" ];
2504 unitConfig.RequiresMountsFor = cfg.dataDir;
2505 startLimitIntervalSec = 0;
2506 path = [ config.programs.ssh.package ];
2507 serviceConfig = {
2508 Type = "oneshot";
2509 ExecStart = "${publishDrains}/%i";
2510 User = cfg.user;
2511 Group = cfg.group;
2512 WorkingDirectory = "${cfg.dataDir}/%i.git";
2513 TimeoutStartSec = "15min";
2514 Restart = "on-failure";
2515 RestartSec = "30s";
2516 RestartSteps = 5;
2517 RestartMaxDelaySec = "15min";
2518 };
2519 };
2520
2521 # wantedBy on a template unit enables nothing, so the instances the
2522 # declaration asks for are pulled in by name.
2523 systemd.targets.valley-publish = lib.mkIf (publishedProjects != { }) {
2524 description = "What pushes the valley's mirrors";
2525 wantedBy = [ "multi-user.target" ];
2526 wants = map (name: "valley-publish@${name}.path") (lib.attrNames publishedProjects);
2527 };
2528
2529 systemd.targets.valley-integrators = lib.mkIf cfg.integrator.enable {
2530 description = "The valley integrator's controllers";
2531 wantedBy = [ "multi-user.target" ];
2532 wants = map (name: "valley-integrator@${name}.service") (lib.attrNames integratedProjects);
2533 };
2534
2535 # The build slice. The daemon runs every build in its own cgroup,
2536 # whoever asked for it, so a cap on a build is a cap on the daemon: the
2537 # slice holds nix-daemon.service, and the check worker when it runs,
2538 # and the kernel holds everything in it to the quota and the memory cap
2539 # together, with no swap. Every user's builds through the daemon share
2540 # the caps. A nix command that does not go through the daemon, such as
2541 # one root runs on the store directly, is outside the slice and
2542 # uncapped.
2543 #
2544 # A build that takes the slice past its memory cap is ended by the
2545 # kernel's OOM killer, which kills the process in the slice using the
2546 # most memory. That is usually the build that went past, and it can be
2547 # another build in the slice. The rest of the host goes on as it was.
2548 # When the OOM killer kills one of the daemon's processes, systemd keeps
2549 # the daemon's unit running, since the unit delegates its cgroup
2550 # (OOMPolicy=continue). Nothing exempts the daemon's own processes from
2551 # being the one chosen.
2552 # The slice sets no device policy, so a build keeps the /dev/kvm the
2553 # daemon gives NixOS tests.
2554 systemd.slices.valley-builds = lib.mkIf cfg.buildSlice.enable {
2555 description = "Every build of the nix daemon, under the host's caps";
2556 sliceConfig = {
2557 CPUQuota = cfg.buildSlice.cpuQuota;
2558 MemoryMax = cfg.buildSlice.memoryMax;
2559 MemorySwapMax = "0";
2560 };
2561 };
2562
2563 systemd.services.nix-daemon.serviceConfig.Slice = lib.mkIf cfg.buildSlice.enable buildSlice;
2564
2565 # One pass of the worker, as a oneshot the timer below starts. A pass
2566 # that finds nothing to build reads origin and ends. Two passes never
2567 # overlap: systemd starts the unit only while it is inactive, and the
2568 # worker's own lock in its state directory serializes any pass started
2569 # by hand.
2570 #
2571 # The unit runs in the build slice, so its evaluation shares the caps
2572 # with the builds. It runs on one CPU. attest runs one nix build per
2573 # CPU it may run on, and NIX_CONFIG holds each of those to one
2574 # derivation at a time, so the worker's builds run one at a time. The
2575 # builds themselves run in the daemon, under the slice's quota,
2576 # whatever CPU the worker is on.
2577 systemd.services.valley-worker = lib.mkIf cfg.worker.enable {
2578 description = "One pass of the valley check worker";
2579 after = [
2580 "network.target"
2581 "sshd.service"
2582 "valley-init.service"
2583 "systemd-tmpfiles-setup.service"
2584 ];
2585 unitConfig.RequiresMountsFor = workerDir;
2586 # nix is the machine's own, for the reason the integrator's is.
2587 path = [
2588 workerPackage
2589 attestPackage
2590 pkgs.git
2591 pkgs.diffutils
2592 config.programs.ssh.package
2593 config.nix.package
2594 ];
2595 environment = {
2596 HOME = workerDir;
2597 XDG_CACHE_HOME = "${workerDir}/cache";
2598 GIT_SSH_COMMAND = workerSsh;
2599 NIX_CONFIG = workerNixConfig;
2600 };
2601 script = workerScript;
2602 serviceConfig = {
2603 Type = "oneshot";
2604 User = "valley-worker";
2605 Group = "valley-worker";
2606 Slice = buildSlice;
2607 CPUAffinity = "0";
2608 NoNewPrivileges = true;
2609 ProtectSystem = "strict";
2610 # Its own directory, and the nix daemon's socket, which a client
2611 # writes to connect.
2612 ReadWritePaths = [
2613 workerDir
2614 "/nix/var/nix/daemon-socket"
2615 ];
2616 ProtectHome = true;
2617 PrivateTmp = true;
2618 PrivateDevices = true;
2619 ProtectClock = true;
2620 ProtectHostname = true;
2621 ProtectKernelLogs = true;
2622 ProtectKernelModules = true;
2623 ProtectKernelTunables = true;
2624 ProtectControlGroups = true;
2625 ProtectProc = "invisible";
2626 RestrictAddressFamilies = [
2627 "AF_INET"
2628 "AF_INET6"
2629 "AF_UNIX"
2630 ];
2631 RestrictNamespaces = true;
2632 RestrictRealtime = true;
2633 RestrictSUIDSGID = true;
2634 LockPersonality = true;
2635 CapabilityBoundingSet = "";
2636 SystemCallArchitectures = "native";
2637 SystemCallFilter = [ "@system-service" ];
2638 UMask = "0077";
2639 };
2640 };
2641
2642 # The first pass starts five minutes after the timer starts. Each later
2643 # pass starts one interval after the last one ended, so a long batch is
2644 # never followed at once by another pass. These are delays and nothing
2645 # more: a switch that runs longer than five minutes can see the first
2646 # pass start inside it, and any later switch can see a pass start
2647 # inside it.
2648 systemd.timers.valley-worker = lib.mkIf cfg.worker.enable {
2649 description = "Run the valley check worker";
2650 wantedBy = [ "timers.target" ];
2651 timerConfig = {
2652 OnActiveSec = "5m";
2653 OnUnitInactiveSec = cfg.worker.interval;
2654 };
2655 };
2656
2657 # One restacker controller for each project listed: valley-restacker
2658 # run, which reconciles at its start and then every interval. It holds
2659 # the lock on its state directory for as long as it runs, so one
2660 # controller serves a project at a time. A controller that fails is
2661 # restarted. It needs no ordering on the repositories' mounts or on
2662 # valley-init: it reads and pushes through sshd, and the git user's
2663 # shell holds a push until valley-init has converged.
2664 systemd.services."valley-restacker@" = lib.mkIf cfg.restacker.enable {
2665 description = "The valley restacker for %i";
2666 after = [
2667 "network.target"
2668 "sshd.service"
2669 ];
2670 path = [ config.programs.ssh.package ];
2671 environment = {
2672 HOME = restackerState;
2673 GIT_SSH_COMMAND = restackerSsh;
2674 };
2675 serviceConfig = {
2676 ExecStartPre = "${restackerKnownHosts} ${restackerState}";
2677 ExecStart = restackerCommand;
2678 Restart = "on-failure";
2679 RestartSec = "10s";
2680 User = "valley-restacker";
2681 Group = "valley-restacker";
2682 StateDirectory = "${restackerStateName}/%i";
2683 StateDirectoryMode = "0700";
2684 WorkingDirectory = restackerState;
2685 LoadCredential = [ "key:${toString cfg.restacker.sshKeyFile}" ];
2686 NoNewPrivileges = true;
2687 ProtectSystem = "strict";
2688 ProtectHome = true;
2689 PrivateTmp = true;
2690 PrivateDevices = true;
2691 ProtectClock = true;
2692 ProtectHostname = true;
2693 ProtectKernelLogs = true;
2694 ProtectKernelModules = true;
2695 ProtectKernelTunables = true;
2696 ProtectControlGroups = true;
2697 ProtectProc = "invisible";
2698 RestrictAddressFamilies = [
2699 "AF_INET"
2700 "AF_INET6"
2701 "AF_UNIX"
2702 ];
2703 RestrictNamespaces = true;
2704 RestrictRealtime = true;
2705 RestrictSUIDSGID = true;
2706 LockPersonality = true;
2707 CapabilityBoundingSet = "";
2708 SystemCallArchitectures = "native";
2709 SystemCallFilter = [ "@system-service" ];
2710 UMask = "0077";
2711 };
2712 };
2713
2714 # wantedBy on a template unit enables nothing, so the controllers the
2715 # declaration asks for are pulled in by name.
2716 systemd.targets.valley-restackers = lib.mkIf cfg.restacker.enable {
2717 description = "The valley restacker's controllers";
2718 wantedBy = [ "multi-user.target" ];
2719 wants = map (name: "valley-restacker@${name}.service") cfg.restacker.projects;
2720 };
2721
2722 # Offsite backup, rendered only when the declaration asks for it. The
2723 # declaration states the policy — that backup exists, its cadence and
2724 # retention; the services.valley.backup.* options supply the machine
2725 # half. Declaration absent or disabled ⇒ no restic config at all.
2726 services.restic.backups = lib.mkIf backupEnabled {
2727 valley = {
2728 initialize = true;
2729 repositoryFile = cfg.backup.repositoryFile;
2730 passwordFile = cfg.backup.passwordFile;
2731 paths = [ cfg.dataDir ];
2732 # The schema admits only the restic-sftp target today; a second
2733 # target would grow a dispatch here. The service runs as root:
2734 # authenticate with the supplied identity and only the pinned
2735 # host key. No prompt can be answered inside a systemd unit, so
2736 # BatchMode + strict host key checking turn a would-be hang into
2737 # an immediate error.
2738 extraOptions = [
2739 "sftp.args='-i ${cfg.backup.sshKeyFile} -o UserKnownHostsFile=${cfg.backup.knownHostsFile} -o IdentitiesOnly=yes -o BatchMode=yes -o StrictHostKeyChecking=yes'"
2740 ];
2741 timerConfig = backupTimer.${backupPolicy.cadence};
2742 pruneOpts = [
2743 "--keep-daily ${toString backupPolicy.retention.daily}"
2744 "--keep-weekly ${toString backupPolicy.retention.weekly}"
2745 "--keep-monthly ${toString backupPolicy.retention.monthly}"
2746 ];
2747 };
2748 };
2749 };
2750}