gunk-dev/the-valley

flake.nix

source4a1066415374main's published tip history
22.9 KiB
1{
2 description = "the-valley: the CUE domain schema for a valley host, and the NixOS module that installs one";
3
4 inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
5
6 outputs =
7 { self, nixpkgs }:
8 let
9 lib = nixpkgs.lib;
10 # Checks use import-from-derivation (the module's cue export), so they
11 # are only defined for the system that can actually build them here.
12 systems = [ "x86_64-linux" ];
13
14 # The integrator's CLI (bin/valley) wrapped for `nix run`. The script
15 # itself must keep running bare from any checkout — the package is the
16 # second of its two shipping modes, never a dependency of the first.
17 valleyScriptFor =
18 pkgs:
19 pkgs.writeShellApplication {
20 name = "valley";
21 runtimeInputs = [
22 pkgs.git
23 pkgs.natscli # tail and replay only; every other verb needs just git
24 ];
25 text = builtins.readFile ./bin/valley;
26 };
27
28 # The installed package: the wrapped script plus the shell completions,
29 # at the standard paths home-manager/NixOS auto-link.
30 valleyCliFor =
31 pkgs:
32 pkgs.symlinkJoin {
33 name = "valley";
34 paths = [ (valleyScriptFor pkgs) ];
35 nativeBuildInputs = [ pkgs.installShellFiles ];
36 postBuild = ''
37 installShellCompletion --bash --name valley ${./completions/valley.bash}
38 installShellCompletion --zsh --name _valley ${./completions/_valley}
39 '';
40 };
41
42 # Markdown prose is filled paragraphs hard-wrapped at 100 columns
43 # (ida-1ec03b1). One prettier invocation backs both the formatter app
44 # and the prose-format check, so the two cannot drift.
45 # Embedded-language formatting is off so fenced code blocks pass
46 # through byte-for-byte.
47 proseFmtArgs = "--prose-wrap always --print-width 100 --embedded-language-formatting off";
48
49 # `nix run .#fmt` — rewrap every tracked *.md in the repo to 100 columns.
50 proseFmtFor =
51 pkgs:
52 pkgs.writeShellApplication {
53 name = "valley-fmt";
54 runtimeInputs = [
55 pkgs.git
56 pkgs.prettier
57 ];
58 text = ''
59 cd "$(git rev-parse --show-toplevel)"
60 git ls-files -z -- '*.md' | xargs -0 --no-run-if-empty \
61 prettier ${proseFmtArgs} --write
62 '';
63 };
64 in
65 {
66 nixosModules.valley-host = ./nix/valley-host.nix;
67 nixosModules.default = self.nixosModules.valley-host;
68
69 apps = lib.genAttrs systems (system: {
70 fmt = {
71 type = "app";
72 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
73 };
74 });
75
76 packages = lib.genAttrs systems (
77 system:
78 let
79 valley = valleyCliFor nixpkgs.legacyPackages.${system};
80 in
81 {
82 inherit valley;
83 default = valley;
84 }
85 );
86
87 checks = lib.genAttrs systems (
88 system:
89 let
90 pkgs = nixpkgs.legacyPackages.${system};
91
92 # Eval-only instantiation of the module — catches option-surface
93 # and cue-export regressions without building or booting anything.
94 # Each check host shares the machine baseline and supplies its own
95 # declaration (and, where the declaration asks for backup, the
96 # secret paths).
97 mkHost =
98 module:
99 lib.nixosSystem {
100 inherit system;
101 modules = [
102 self.nixosModules.default
103 {
104 fileSystems."/" = {
105 device = "/dev/disk/by-label/nixos";
106 fsType = "ext4";
107 };
108 boot.loader.grub.enable = false;
109 system.stateVersion = "25.11";
110 services.valley = {
111 enable = true;
112 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
113 };
114 }
115 module
116 ];
117 };
118
119 # The example declaration enables backup, so this host supplies
120 # the four secret paths (eval-only placeholders).
121 host = mkHost {
122 services.valley = {
123 config = ./examples/host.cue;
124 backup = {
125 repositoryFile = "/run/agenix/valley-restic-repo";
126 passwordFile = "/run/agenix/valley-restic-password";
127 sshKeyFile = "/run/agenix/valley-git-ssh-key";
128 knownHostsFile = "/var/lib/valley-backup/known_hosts";
129 };
130 };
131 };
132
133 # A declaration without a backup block predates the field and must
134 # keep evaluating exactly as before: zero restic machinery.
135 noBackupHost = mkHost {
136 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
137 package valley
138 projects: "the-valley": {}
139 '';
140 };
141
142 # The example declaration with the secret paths left unset: the
143 # module must refuse with assertions naming the missing options.
144 noSecretsHost = mkHost {
145 services.valley.config = ./examples/host.cue;
146 };
147
148 # Bus enabled, minimal declaration. The bus-e2e check drives this
149 # host's rendered hooks and stream-init against a real server.
150 busHost = mkHost {
151 services.valley = {
152 config = pkgs.writeText "bus-host.cue" ''
153 package valley
154 projects: "events-pilot": {}
155 '';
156 bus.enable = true;
157 };
158 };
159
160 failedAssertions = builtins.filter (a: !a.assertion) (
161 host.config.assertions ++ noBackupHost.config.assertions ++ busHost.config.assertions
162 );
163
164 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
165
166 resticRenderedWithoutDeclaration =
167 noBackupHost.config.systemd.services ? "restic-backups-valley"
168 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
169
170 # The bus defaults off; a host that never asked for one must
171 # render zero bus machinery.
172 busRenderedWithoutEnable =
173 noBackupHost.config.systemd.services ? valley-bus
174 || noBackupHost.config.systemd.services ? valley-bus-init;
175 in
176 {
177 # The CLI must stay a lint-clean script whose help verb answers
178 # without a repo or a remote — the cheap end of its eviction clause
179 # (dcr-74c3158); anything needing more graduates instead. The
180 # completions are held to the same bar, and the installed package
181 # must carry them at the auto-linked paths.
182 valley-cli =
183 let
184 valley = valleyCliFor pkgs;
185 in
186 pkgs.runCommand "valley-cli"
187 {
188 nativeBuildInputs = [
189 pkgs.shellcheck
190 pkgs.zsh
191 valley
192 ];
193 }
194 ''
195 shellcheck ${./bin/valley}
196 shellcheck ${./completions/valley.bash}
197 # shellcheck cannot lint zsh; a bare parse is the cheap check.
198 zsh -n ${./completions/_valley}
199 valley help > help.txt
200 grep -q '^usage: valley' help.txt
201 test -f ${valley}/share/bash-completion/completions/valley
202 test -f ${valley}/share/zsh/site-functions/_valley
203 touch $out
204 '';
205
206 # Markdown prose format (ida-1ec03b1): the check is formatter
207 # idempotence — formatting the tree must change nothing. On failure,
208 # fix with `nix run .#fmt`.
209 prose-format =
210 pkgs.runCommand "valley-prose-format"
211 {
212 nativeBuildInputs = [ pkgs.prettier ];
213 }
214 ''
215 cd ${self}
216 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
217 prettier ${proseFmtArgs} --check
218 touch $out
219 '';
220
221 # The example host declaration must vet against the schema, and the
222 # schema must reject what it claims to reject: unsafe project names,
223 # unknown project fields, stray top-level fields (typos, deployment
224 # concerns), and malformed backup policy (machine concerns, targets
225 # without an implementation, non-positive retention). CUE closedness
226 # is easy to regress silently — e.g. embedding #Host instead of
227 # referencing it opens the schema — so the rejections are pinned
228 # here.
229 cue-vet =
230 let
231 invalidConfigs = {
232 unsafe-project-name = ''
233 package valley
234 projects: ".hidden": {}
235 '';
236 unknown-project-field = ''
237 package valley
238 projects: ok: dataDir: "/srv/git"
239 '';
240 top-level-typo = ''
241 package valley
242 project: oops: {}
243 '';
244 deployment-concern-in-cue = ''
245 package valley
246 user: "git"
247 projects: ok: {}
248 '';
249 machine-concern-in-backup = ''
250 package valley
251 projects: ok: {}
252 backup: repositoryFile: "/run/agenix/valley-restic-repo"
253 '';
254 unimplemented-backup-target = ''
255 package valley
256 projects: ok: {}
257 backup: target: "restic-s3"
258 '';
259 negative-retention = ''
260 package valley
261 projects: ok: {}
262 backup: retention: daily: -1
263 '';
264 };
265 in
266 pkgs.runCommand "valley-cue-vet"
267 {
268 nativeBuildInputs = [ pkgs.cue ];
269 }
270 ''
271 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
272 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
273 grep -q 'gunk-dev/the-valley' example.json
274 grep -q 'restic-sftp' example.json
275
276 # A declaration without a backup block must stay valid —
277 # consumers written before the field existed keep vetting.
278 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
279 package valley
280 projects: "the-valley": {}
281 ''}
282
283 # The event schema accepts what the publisher hook emits …
284 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
285 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
286 ''}
287 # … and stays closed: a field outside the git-derivable
288 # identity — wall-clock time, a hostname — must be rejected,
289 # or replay determinism silently dies.
290 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
291 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
292 ''}; then
293 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
294 exit 1
295 fi
296 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
297 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
298 ''}; then
299 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
300 exit 1
301 fi
302
303 ${lib.concatStrings (
304 lib.mapAttrsToList (name: cfg: ''
305 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
306 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
307 exit 1
308 fi
309 '') invalidConfigs
310 )}
311 touch $out
312 '';
313
314 module-eval =
315 if failedAssertions != [ ] then
316 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
317 else if resticRenderedWithoutDeclaration then
318 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
319 else if busRenderedWithoutEnable then
320 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
321 else if
322 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
323 then
324 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
325 else
326 pkgs.runCommand "valley-module-eval"
327 {
328 initScript = host.config.systemd.services.valley-init.script;
329 sshdConfig = host.config.services.openssh.extraConfig;
330 resticService = host.config.systemd.units."restic-backups-valley.service".text;
331 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
332 passAsFile = [
333 "initScript"
334 "sshdConfig"
335 "resticService"
336 "resticTimer"
337 ];
338 }
339 ''
340 # The repo init list and mirror hook must be generated from
341 # the CUE export, and the git user's sshd Match block must
342 # be terminated so it cannot scope later config.
343 grep -q "the-valley" "$initScriptPath"
344 grep -q "valley-mirrors" "$initScriptPath"
345 grep -q "Match All" "$sshdConfigPath"
346
347 # The mirror push must use explicit head/tag refspecs with
348 # --prune, never --mirror: --mirror also deletes remote-only
349 # refs, and GitHub's read-only refs/pull/* fails every such
350 # push. Follow the hook chain from the init script to the
351 # rendered push script and pin the invocation there.
352 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
353 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
354 grep -q -- 'push --prune' "$mirrorPush"
355 grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"
356 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
357 if grep -q -- '--mirror' "$mirrorPush"; then
358 echo "module-eval: mirror push regressed to --mirror" >&2
359 exit 1
360 fi
361
362 # The rendered restic units must back up the data directory
363 # to the consumer-supplied repository with the declared
364 # retention over a pinned host key, on the declared cadence.
365 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
366 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
367 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
368 grep -q "BatchMode=yes" "$resticServicePath"
369 grep -q "OnCalendar=03:30" "$resticTimerPath"
370
371 # The backup paths render as a --files-from list: follow
372 # ExecStartPre to that list and pin the data directory.
373 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
374 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
375 grep -qx "/srv/git" "$staticPaths"
376 touch $out
377 '';
378
379 # Phase 1's exit criteria, end to end and unmocked: a push to a
380 # bare repo wired with the real rendered hooks produces a
381 # ref-updated event on a real JetStream server within seconds,
382 # visible in `valley tail`; replaying the repo's refs is
383 # deterministic; and a dead bus never fails a push. The hook and
384 # stream-init scripts are followed from the rendered unit scripts,
385 # so the check exercises exactly what a host would run — only the
386 # server invocation differs (the sandbox cannot write /srv), same
387 # binary and flags, relocated storage.
388 bus-e2e =
389 pkgs.runCommand "valley-bus-e2e"
390 {
391 nativeBuildInputs = [
392 pkgs.git
393 pkgs.natscli
394 pkgs.nats-server
395 pkgs.jq
396 pkgs.cue
397 (valleyScriptFor pkgs)
398 ];
399 initScript = busHost.config.systemd.services.valley-init.script;
400 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
401 passAsFile = [
402 "initScript"
403 "busInitScript"
404 ];
405 }
406 ''
407 export HOME="$TMPDIR"
408 export NATS_URL=nats://127.0.0.1:4222
409 export GIT_CONFIG_NOSYSTEM=1
410 git config --global user.name valley-check
411 git config --global user.email valley-check@localhost
412 git config --global init.defaultBranch main
413
414 wait_for() {
415 for _ in $(seq 1 150); do
416 "$@" >/dev/null 2>&1 && return 0
417 sleep 0.2
418 done
419 echo "bus-e2e: timed out waiting for: $*" >&2
420 return 1
421 }
422
423 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
424 --store_dir "$TMPDIR/js" &
425 server_pid=$!
426
427 # The real stream-init script the module renders.
428 bash -eu "$busInitScriptPath"
429 nats stream info valley >/dev/null
430
431 # A bare repo wired exactly as valley-init wires it, with the
432 # real store paths followed from the rendered init script.
433 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
434 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
435 test -x "$dispatch"
436 test -x "$bushook"
437 repo="$TMPDIR/events-pilot.git"
438 git init --quiet --bare "$repo"
439 mkdir -p "$repo/hooks/post-receive.d"
440 ln -s "$dispatch" "$repo/hooks/post-receive"
441 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
442
443 git clone --quiet "$repo" "$TMPDIR/work"
444 cd "$TMPDIR/work"
445 echo one > file
446 git add file
447 git commit --quiet -m one
448 git push --quiet origin main
449 first="$(git rev-parse HEAD)"
450 zeros="$(printf '%040d' 0)"
451
452 # Exit criterion 1: the event arrives within seconds, with a
453 # payload that is exactly the git facts of the push …
454 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
455 wait_for msgs_is 1
456 got="$(nats stream get valley 1 --json)"
457 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
458 payload="$(jq -r .data <<<"$got" | base64 -d)"
459 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
460 [ "$payload" = "$expected" ]
461
462 # … valid against the shipped event schema.
463 echo "$payload" > "$TMPDIR/payload.json"
464 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
465
466 # … and visible in `valley tail`. Subscribe first, then push.
467 valley tail > "$TMPDIR/tail.out" 2>&1 &
468 tail_pid=$!
469 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
470 wait_for subscribed
471 echo two > file
472 git commit --quiet -am two
473 git push --quiet origin main
474 second="$(git rev-parse HEAD)"
475 wait_for msgs_is 2
476 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
477 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
478 [ "$payload2" = "$expected2" ]
479 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
480 wait_for tail_saw
481 kill "$tail_pid" 2>/dev/null || true
482
483 # Exit criterion 2: rebuilding the stream from the repo's
484 # refs is deterministic — two replays from scratch produce
485 # identical events, landing on the pushed tip with the
486 # all-zero id as old.
487 dump_stream() {
488 local info first_seq last_seq i
489 info="$(nats stream info valley --json)"
490 first_seq="$(jq .state.first_seq <<<"$info")"
491 last_seq="$(jq .state.last_seq <<<"$info")"
492 for i in $(seq "$first_seq" "$last_seq"); do
493 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
494 done
495 }
496 nats stream purge valley --force >/dev/null
497 valley replay "$repo"
498 wait_for msgs_is 1
499 run1="$(dump_stream)"
500 nats stream purge valley --force >/dev/null
501 valley replay "$repo"
502 wait_for msgs_is 1
503 run2="$(dump_stream)"
504 [ "$run1" = "$run2" ]
505 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
506 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
507
508 # A dead bus never blocks a push: the event is simply lost
509 # (and rebuildable by replay).
510 kill "$server_pid"
511 wait "$server_pid" || true
512 echo three > file
513 git commit --quiet -am three
514 git push --quiet origin main
515
516 touch $out
517 '';
518 }
519 );
520 };
521}