gunk-dev/the-valley

flake.nix

source07d67d385df1main's published tip history
71.5 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 pkgs.cue # checks only — it composes the policy layers
25 ];
26 text = builtins.readFile ./bin/valley;
27 };
28
29 # The installed package: the wrapped script plus the shell completions,
30 # at the standard paths home-manager/NixOS auto-link.
31 valleyCliFor =
32 pkgs:
33 pkgs.symlinkJoin {
34 name = "valley";
35 paths = [ (valleyScriptFor pkgs) ];
36 nativeBuildInputs = [ pkgs.installShellFiles ];
37 postBuild = ''
38 installShellCompletion --bash --name valley ${./completions/valley.bash}
39 installShellCompletion --zsh --name _valley ${./completions/_valley}
40 '';
41 };
42
43 # Markdown prose is filled paragraphs hard-wrapped at 100 columns
44 # (ida-1ec03b1). One prettier invocation backs both the formatter app
45 # and the prose-format check, so the two cannot drift.
46 # Embedded-language formatting is off so fenced code blocks pass
47 # through byte-for-byte.
48 proseFmtArgs = "--prose-wrap always --print-width 100 --embedded-language-formatting off";
49
50 # `nix run .#fmt` — rewrap every tracked *.md in the repo to 100 columns.
51 proseFmtFor =
52 pkgs:
53 pkgs.writeShellApplication {
54 name = "valley-fmt";
55 runtimeInputs = [
56 pkgs.git
57 pkgs.prettier
58 ];
59 text = ''
60 cd "$(git rev-parse --show-toplevel)"
61 git ls-files -z -- '*.md' | xargs -0 --no-run-if-empty \
62 prettier ${proseFmtArgs} --write
63 '';
64 };
65
66 # The Phase 2 attestation helper (dcr-0de694f). Go, standard library
67 # only — hence vendorHash = null, and hence no module fetch at build
68 # time. Its unit tests run in the checkPhase and need git.
69 attestUnwrappedFor =
70 pkgs:
71 pkgs.buildGoModule {
72 pname = "valley-attest";
73 version = "0";
74 src = ./attest;
75 vendorHash = null;
76 nativeCheckInputs = [ pkgs.git ];
77 meta.mainProgram = "attest";
78 };
79
80 # The shipping form. git, ssh-keygen and cue are pinned to this
81 # flake's nixpkgs, so every host composes and vets a statement with
82 # the same tools. `nix` is deliberately NOT pinned: the check being
83 # attested to must be built by the nix the machine actually runs, and
84 # a nix carried in here would be a second one.
85 attestFor =
86 pkgs:
87 pkgs.runCommand "valley-attest"
88 {
89 nativeBuildInputs = [ pkgs.makeWrapper ];
90 meta.mainProgram = "attest";
91 }
92 ''
93 mkdir -p $out/bin
94 makeWrapper ${lib.getExe (attestUnwrappedFor pkgs)} $out/bin/attest \
95 --prefix PATH : ${
96 lib.makeBinPath [
97 pkgs.git
98 pkgs.openssh
99 pkgs.cue
100 ]
101 } \
102 --set-default VALLEY_ATTEST_SCHEMA ${./schema/attestation.cue}
103 '';
104 in
105 {
106 nixosModules.valley-host = ./nix/valley-host.nix;
107 nixosModules.default = self.nixosModules.valley-host;
108
109 # The knowledge lint, for any project that keeps a `.the-valley/` graph.
110 # This is the check's primary form: a consuming project takes this flake
111 # as an input and instantiates the derivation over its own source, so the
112 # check a policy names is supplied by the instance rather than written
113 # again by every project the policy covers (dcr-f41f718). A whole
114 # consuming flake is:
115 #
116 # {
117 # inputs.the-valley.url = "github:gunk-dev/the-valley";
118 # outputs =
119 # { self, the-valley }:
120 # {
121 # checks.x86_64-linux.knowledge-lint = the-valley.lib.knowledgeLint {
122 # system = "x86_64-linux";
123 # src = self;
124 # };
125 # };
126 # }
127 #
128 # There is no nixpkgs input in that flake on purpose: cue and python come
129 # from this flake's pinned nixpkgs, so every project in a group runs the
130 # same lint against the same toolchain. `root` names the graph directory
131 # for a project that keeps its graph somewhere other than `.the-valley/`.
132 lib.knowledgeLint =
133 {
134 system,
135 src,
136 root ? ".the-valley",
137 }:
138 import ./nix/knowledge-lint.nix {
139 inherit src root;
140 pkgs = nixpkgs.legacyPackages.${system};
141 };
142
143 apps = lib.genAttrs systems (system: {
144 fmt = {
145 type = "app";
146 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
147 };
148 attest = {
149 type = "app";
150 program = lib.getExe (attestFor nixpkgs.legacyPackages.${system});
151 };
152 });
153
154 packages = lib.genAttrs systems (
155 system:
156 let
157 valley = valleyCliFor nixpkgs.legacyPackages.${system};
158 in
159 {
160 inherit valley;
161 default = valley;
162 attest = attestFor nixpkgs.legacyPackages.${system};
163 }
164 );
165
166 checks = lib.genAttrs systems (
167 system:
168 let
169 pkgs = nixpkgs.legacyPackages.${system};
170
171 # Eval-only instantiation of the module — catches option-surface
172 # and cue-export regressions without building or booting anything.
173 # Each check host shares the machine baseline and supplies its own
174 # declaration (and, where the declaration asks for backup, the
175 # secret paths).
176 mkHost =
177 module:
178 lib.nixosSystem {
179 inherit system;
180 modules = [
181 self.nixosModules.default
182 {
183 fileSystems."/" = {
184 device = "/dev/disk/by-label/nixos";
185 fsType = "ext4";
186 };
187 boot.loader.grub.enable = false;
188 system.stateVersion = "25.11";
189 services.valley = {
190 enable = true;
191 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
192 };
193 }
194 module
195 ];
196 };
197
198 # The example declaration enables backup, so this host supplies
199 # the four secret paths (eval-only placeholders).
200 host = mkHost {
201 services.valley = {
202 config = ./examples/host.cue;
203 backup = {
204 repositoryFile = "/run/agenix/valley-restic-repo";
205 passwordFile = "/run/agenix/valley-restic-password";
206 sshKeyFile = "/run/agenix/valley-git-ssh-key";
207 knownHostsFile = "/var/lib/valley-backup/known_hosts";
208 };
209 };
210 };
211
212 # A declaration without a backup block predates the field and must
213 # keep evaluating exactly as before: zero restic machinery.
214 noBackupHost = mkHost {
215 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
216 package valley
217 projects: "the-valley": {}
218 '';
219 };
220
221 # The example declaration with the secret paths left unset: the
222 # module must refuse with assertions naming the missing options.
223 noSecretsHost = mkHost {
224 services.valley.config = ./examples/host.cue;
225 };
226
227 # Bus enabled, minimal declaration. The bus-e2e check drives this
228 # host's rendered hooks and stream-init against a real server.
229 busHost = mkHost {
230 services.valley = {
231 config = pkgs.writeText "bus-host.cue" ''
232 package valley
233 projects: "events-pilot": {}
234 '';
235 bus.enable = true;
236 };
237 };
238
239 # Two mirror URLs the sandbox can serve: git resolves a relative
240 # URL against the pushing repo's directory, so the mirror-e2e
241 # check drives the rendered script with no substitution at all —
242 # one reachable sibling repo, one that does not exist.
243 mirrorHost = mkHost {
244 services.valley.config = pkgs.writeText "mirror-host.cue" ''
245 package valley
246 projects: "mirror-pilot": mirrors: ["../mirror.git"]
247 projects: "dead-mirror": mirrors: ["../nope.git"]
248 '';
249 };
250
251 failedAssertions = builtins.filter (a: !a.assertion) (
252 host.config.assertions
253 ++ noBackupHost.config.assertions
254 ++ busHost.config.assertions
255 ++ mirrorHost.config.assertions
256 );
257
258 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
259
260 resticRenderedWithoutDeclaration =
261 noBackupHost.config.systemd.services ? "restic-backups-valley"
262 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
263
264 # The bus defaults off; a host that never asked for one must
265 # render zero bus machinery.
266 busRenderedWithoutEnable =
267 noBackupHost.config.systemd.services ? valley-bus
268 || noBackupHost.config.systemd.services ? valley-bus-init;
269
270 # A tree in the store, written from a path -> contents map. The
271 # knowledge lint reads a whole graph rather than a file, so every
272 # fixture below is small but complete.
273 mkTree =
274 name: files:
275 pkgs.runCommand name { } (
276 lib.concatStrings (
277 lib.mapAttrsToList (path: text: ''
278 install -Dm444 ${pkgs.writeText "knowledge-lint-fixture" text} $out/${path}
279 '') files
280 )
281 );
282
283 # A project that is nearly nothing: a README, a docs directory, and
284 # two nodes. This is the shape the first consuming project has, and
285 # the knowledge-lint-consumer check instantiates lib.knowledgeLint
286 # over it exactly as that project's own flake would.
287 consumerProject = mkTree "knowledge-lint-consumer-project" {
288 "README.md" = ''
289 # A project
290
291 It keeps its knowledge in [.the-valley](./.the-valley/).
292 '';
293 "docs/design.md" = ''
294 # Design
295
296 ## The shape
297 '';
298 ".the-valley/ideas/ida-0a1b2c3-the-shape.md" = ''
299 ---
300 type: idea
301 id: ida-0a1b2c3
302 status: raw
303 title: The shape the design should take
304 created: 2026-08-02
305 ---
306
307 # The shape the design should take
308
309 As sketched in [design.md](../../docs/design.md#the-shape).
310 '';
311 ".the-valley/outcomes/oc-4d5e6f7-the-design-lands.md" = ''
312 ---
313 type: outcome
314 id: oc-4d5e6f7
315 status: open
316 title: The design lands
317 created: 2026-08-02
318 blocked_by: [ida-0a1b2c3]
319 ---
320
321 # The design lands
322
323 Waits on [[ida-0a1b2c3]].
324 '';
325 };
326
327 # A project with no graph at all. Adding the check must not require
328 # having written a node yet, or no project would ever adopt it
329 # before its first one.
330 graphlessProject = mkTree "knowledge-lint-graphless-project" {
331 "README.md" = ''
332 # A project with no knowledge graph yet
333 '';
334 };
335
336 # What the lint must reject, and the words its failure must contain.
337 # A lint that fails without naming the file and the defect costs the
338 # reader the whole diagnosis, so both are pinned.
339 rejectedGraphs = {
340 unknown-status = {
341 names = ''ida-0000001-a-node.md".status'';
342 files.".the-valley/ideas/ida-0000001-a-node.md" = ''
343 ---
344 type: idea
345 id: ida-0000001
346 status: nonsense
347 title: A node in a state ideas do not have
348 created: 2026-08-02
349 ---
350 '';
351 };
352
353 edge-on-the-wrong-type = {
354 names = "blocked_by: field not allowed";
355 files.".the-valley/ideas/ida-0000002-a-node.md" = ''
356 ---
357 type: idea
358 id: ida-0000002
359 status: raw
360 title: An idea carrying the one edge only outcomes carry
361 created: 2026-08-02
362 blocked_by: []
363 ---
364 '';
365 };
366
367 node-in-the-wrong-directory = {
368 names = "a bug node belongs in .the-valley/bugs/";
369 files.".the-valley/ideas/bd-0000003-a-bug.md" = ''
370 ---
371 type: bug
372 id: bd-0000003
373 status: open
374 title: A bug filed among the ideas
375 created: 2026-08-02
376 ---
377 '';
378 };
379
380 filename-id-mismatch = {
381 names = "filename says id ida-0000004, frontmatter says ida-0000005";
382 files.".the-valley/ideas/ida-0000004-a-node.md" = ''
383 ---
384 type: idea
385 id: ida-0000005
386 status: raw
387 title: A node whose filename and frontmatter disagree
388 created: 2026-08-02
389 ---
390 '';
391 };
392
393 duplicate-id = {
394 names = "is already used by";
395 files = {
396 ".the-valley/ideas/ida-0000006-one.md" = ''
397 ---
398 type: idea
399 id: ida-0000006
400 status: raw
401 title: One node
402 created: 2026-08-02
403 ---
404 '';
405 ".the-valley/ideas/ida-0000006-two.md" = ''
406 ---
407 type: idea
408 id: ida-0000006
409 status: raw
410 title: Another node wearing the same id
411 created: 2026-08-02
412 ---
413 '';
414 };
415 };
416
417 missing-frontmatter = {
418 names = "no YAML frontmatter";
419 files.".the-valley/ideas/ida-0000007-a-node.md" = ''
420 # A node that is only prose
421 '';
422 };
423
424 dangling-wiki-link = {
425 names = "[[ida-9999999]] is not a node id";
426 files.".the-valley/ideas/ida-0000008-a-node.md" = ''
427 ---
428 type: idea
429 id: ida-0000008
430 status: raw
431 title: A node pointing at nothing
432 created: 2026-08-02
433 ---
434
435 It builds on [[ida-9999999]].
436 '';
437 };
438
439 dangling-blocked-by = {
440 names = "blocked_by names oc-9999999, which is not a node";
441 files.".the-valley/outcomes/oc-0000009-an-outcome.md" = ''
442 ---
443 type: outcome
444 id: oc-0000009
445 status: open
446 title: An outcome waiting on nothing that exists
447 created: 2026-08-02
448 blocked_by: [oc-9999999]
449 ---
450 '';
451 };
452
453 broken-link = {
454 names = "./nowhere.md does not exist";
455 files.".the-valley/ideas/ida-000000a-a-node.md" = ''
456 ---
457 type: idea
458 id: ida-000000a
459 status: raw
460 title: A node linking to a file that is not there
461 created: 2026-08-02
462 ---
463
464 See [nowhere](./nowhere.md).
465 '';
466 };
467
468 broken-anchor = {
469 names = "names no heading";
470 files.".the-valley/ideas/ida-000000b-a-node.md" = ''
471 ---
472 type: idea
473 id: ida-000000b
474 status: raw
475 title: A node linking to a heading that is not there
476 created: 2026-08-02
477 ---
478
479 # A heading
480
481 See [above](./ida-000000b-a-node.md#not-this-heading).
482 '';
483 };
484 };
485 in
486 {
487 # The CLI must stay a lint-clean script whose help verb answers
488 # without a repo or a remote — the cheap end of its eviction clause
489 # (dcr-74c3158); anything needing more graduates instead. The
490 # completions are held to the same bar, and the installed package
491 # must carry them at the auto-linked paths.
492 valley-cli =
493 let
494 valley = valleyCliFor pkgs;
495 in
496 pkgs.runCommand "valley-cli"
497 {
498 nativeBuildInputs = [
499 pkgs.shellcheck
500 pkgs.zsh
501 valley
502 ];
503 }
504 ''
505 shellcheck ${./bin/valley}
506 shellcheck ${./completions/valley.bash}
507 # shellcheck cannot lint zsh; a bare parse is the cheap check.
508 zsh -n ${./completions/_valley}
509 valley help > help.txt
510 grep -q '^usage: valley' help.txt
511 test -f ${valley}/share/bash-completion/completions/valley
512 test -f ${valley}/share/zsh/site-functions/_valley
513 touch $out
514 '';
515
516 # Markdown prose format (ida-1ec03b1): the check is formatter
517 # idempotence — formatting the tree must change nothing. On failure,
518 # fix with `nix run .#fmt`.
519 prose-format =
520 pkgs.runCommand "valley-prose-format"
521 {
522 nativeBuildInputs = [ pkgs.prettier ];
523 }
524 ''
525 cd ${self}
526 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
527 prettier ${proseFmtArgs} --check
528 touch $out
529 '';
530
531 # This repo's own graph, checked by the derivation the flake
532 # exposes rather than by a second implementation of it. Whatever a
533 # consuming project runs, this repo runs.
534 knowledge-lint = self.lib.knowledgeLint {
535 inherit system;
536 src = self;
537 };
538
539 # The reusable form, exercised over a foreign tree: a project that
540 # is a README, a docs directory and two nodes, and a project with no
541 # graph at all. Both must pass, and both are checked by depending on
542 # the instantiated derivations rather than by re-running the lint.
543 knowledge-lint-consumer =
544 pkgs.runCommand "valley-knowledge-lint-consumer"
545 {
546 consumer = self.lib.knowledgeLint {
547 inherit system;
548 src = consumerProject;
549 };
550 graphless = self.lib.knowledgeLint {
551 inherit system;
552 src = graphlessProject;
553 };
554 }
555 ''
556 test -e "$consumer" && test -e "$graphless"
557 touch $out
558 '';
559
560 # The lint must fail on a broken graph, and its failure must name
561 # the file and the defect — a check that only says "no" leaves the
562 # reader to find the breakage themselves. The script and the schema
563 # here are the same store paths lib.knowledgeLint uses, so the
564 # rejections cannot drift from what a consumer runs.
565 knowledge-lint-rejects =
566 pkgs.runCommand "valley-knowledge-lint-rejects"
567 {
568 nativeBuildInputs = [
569 pkgs.cue
570 pkgs.python3
571 ];
572 }
573 ''
574 ${lib.concatStrings (
575 lib.mapAttrsToList (case: spec: ''
576 mkdir -p work/${case}
577 if python3 ${./nix/knowledge-lint.py} \
578 --tree ${mkTree "knowledge-lint-${case}" spec.files} \
579 --schema ${./schema/node.cue} \
580 --work work/${case} 2> ${case}.err
581 then
582 echo "knowledge-lint: expected graph '${case}' to be rejected" >&2
583 exit 1
584 fi
585 if ! grep -qF -- ${lib.escapeShellArg spec.names} ${case}.err; then
586 echo "knowledge-lint: '${case}' was rejected without naming" \
587 ${lib.escapeShellArg spec.names} >&2
588 cat ${case}.err >&2
589 exit 1
590 fi
591 '') rejectedGraphs
592 )}
593 touch $out
594 '';
595
596 # The example host declaration must vet against the schema, and the
597 # schema must reject what it claims to reject: unsafe project names,
598 # unknown project fields, stray top-level fields (typos, deployment
599 # concerns), and malformed backup policy (machine concerns, targets
600 # without an implementation, non-positive retention). CUE closedness
601 # is easy to regress silently — e.g. embedding #Host instead of
602 # referencing it opens the schema — so the rejections are pinned
603 # here.
604 cue-vet =
605 let
606 invalidConfigs = {
607 unsafe-project-name = ''
608 package valley
609 projects: ".hidden": {}
610 '';
611 unknown-project-field = ''
612 package valley
613 projects: ok: dataDir: "/srv/git"
614 '';
615 top-level-typo = ''
616 package valley
617 project: oops: {}
618 '';
619 deployment-concern-in-cue = ''
620 package valley
621 user: "git"
622 projects: ok: {}
623 '';
624 machine-concern-in-backup = ''
625 package valley
626 projects: ok: {}
627 backup: repositoryFile: "/run/agenix/valley-restic-repo"
628 '';
629 unimplemented-backup-target = ''
630 package valley
631 projects: ok: {}
632 backup: target: "restic-s3"
633 '';
634 negative-retention = ''
635 package valley
636 projects: ok: {}
637 backup: retention: daily: -1
638 '';
639 };
640 in
641 pkgs.runCommand "valley-cue-vet"
642 {
643 nativeBuildInputs = [ pkgs.cue ];
644 }
645 ''
646 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
647 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
648 grep -q 'gunk-dev/the-valley' example.json
649 grep -q 'restic-sftp' example.json
650
651 # A declaration without a backup block must stay valid —
652 # consumers written before the field existed keep vetting.
653 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
654 package valley
655 projects: "the-valley": {}
656 ''}
657
658 # The event schema accepts what the publisher hook emits …
659 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
660 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
661 ''}
662 # … and stays closed: a field outside the git-derivable
663 # identity — wall-clock time, a hostname — must be rejected,
664 # or replay determinism silently dies.
665 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
666 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
667 ''}; then
668 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
669 exit 1
670 fi
671 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
672 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
673 ''}; then
674 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
675 exit 1
676 fi
677
678 ${lib.concatStrings (
679 lib.mapAttrsToList (name: cfg: ''
680 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
681 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
682 exit 1
683 fi
684 '') invalidConfigs
685 )}
686 touch $out
687 '';
688
689 # The attestation statement schema (dcr-0de694f). A statement the
690 # helper composes must vet, and the schema must reject what it
691 # claims to reject. Two rejections carry the decision's whole
692 # weight and are pinned by name below: a subject with no
693 # content-addressed digest has no identity at all, and a
694 # predicate that crosses the pure/effectful line would let a
695 # notarization pass itself off as re-derivable.
696 attest-schema =
697 let
698 treeDigest = "73847e0b723a444df8c677e5e67d2e7858327259323c76b24f8f11b650b66d69";
699 subject = ''
700 "subject": {
701 "primary": "valley-tree-v1",
702 "digest": {
703 "valley-tree-v1": "${treeDigest}",
704 "git-sha1": "99b5f2f7971e2c8e37a7a579cb761d80272a9a3d"
705 }
706 }
707 '';
708 pureStatement = ''
709 {
710 "statementType": "the-valley/attestation/v1",
711 ${subject},
712 "predicateType": "the-valley/check/pure/v1",
713 "predicate": {
714 "check": {"name": "prose-format", "runner": "nix", "attribute": "prose-format"},
715 "result": "passed",
716 "inputs": {"valley-inputs-v1": "8df8c199decb43eb715790d6fc3a9dd96adaaf3a75073a50acfa51d73aaf3253"},
717 "derivation": {"sha256": "ef69ed0ccc0546a38a40eebbfcac610cedd7cf4f81036cd21ddff483f08d3ad7"},
718 "output": {"valley-tree-v1": "cf1f5a9c96bbdf1d69da451c94168fa3a760f91f94827ba88bdb72de8dfa8af9"}
719 },
720 "provenance": {
721 "harness": "a harness",
722 "model": "a model",
723 "prompt": {"sha256": "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03"},
724 "delegation": [{"principal": "human:integrator", "grant": "land changes"}]
725 }
726 }
727 '';
728 effectfulStatement = ''
729 {
730 "statementType": "the-valley/attestation/v1",
731 ${subject},
732 "predicateType": "the-valley/check/effectful/v1",
733 "predicate": {
734 "check": {"name": "live-api", "runner": "command", "command": "curl -sf https://example.invalid"},
735 "result": "passed",
736 "environment": "a sealed environment",
737 "observedAt": "2026-08-02T13:02:00Z"
738 }
739 }
740 '';
741 # Each case is the pure statement with one thing wrong.
742 invalidStatements = {
743 # Carriage is not statement: a signature inside the signed
744 # bytes is a category error, and the sentinel names it.
745 signature-in-statement = builtins.replaceStrings [ "\"statementType\"" ] [
746 "\"signature\": \"-----BEGIN SSH SIGNATURE-----\", \"statementType\""
747 ] pureStatement;
748 # A subject with only advisory members.
749 no-content-addressed-subject =
750 builtins.replaceStrings [ "\"valley-tree-v1\": \"${treeDigest}\"," ] [ "" ]
751 pureStatement;
752 # A notarization wearing a re-derivable predicate type.
753 effectful-claiming-pure = builtins.replaceStrings [ "the-valley/check/effectful/v1" ] [
754 "the-valley/check/pure/v1"
755 ] effectfulStatement;
756 # A re-derivable claim that drops what it is re-derived
757 # against.
758 pure-without-output = builtins.replaceStrings [ "\"output\"" ] [ "\"outputs\"" ] pureStatement;
759 # A predicate type nobody has published a shape for.
760 unversioned-predicate-type =
761 builtins.replaceStrings [ "the-valley/check/pure/v1" ] [ "the-valley/check/pure" ]
762 pureStatement;
763 # A digest under a scheme no verifier can check.
764 unknown-digest-scheme = builtins.replaceStrings [ "\"git-sha1\"" ] [ "\"md5\"" ] pureStatement;
765 # An abbreviated digest.
766 short-digest = builtins.replaceStrings [ treeDigest ] [ "73847e0b" ] pureStatement;
767 # A check name outside the shape schema/verification.cue
768 # holds check names to.
769 unsafe-check-name = builtins.replaceStrings [ "\"prose-format\", \"runner\"" ] [
770 "\"Prose Format\", \"runner\""
771 ] pureStatement;
772 # A nix check carrying a command line.
773 nix-check-with-a-command = builtins.replaceStrings [ "\"runner\": \"nix\"" ] [
774 "\"runner\": \"nix\", \"command\": \"make\""
775 ] pureStatement;
776 };
777 in
778 pkgs.runCommand "valley-attest-schema"
779 {
780 nativeBuildInputs = [ pkgs.cue ];
781 }
782 ''
783 cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "pure.json" pureStatement}
784 cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "effectful.json" effectfulStatement}
785
786 ${lib.concatStrings (
787 lib.mapAttrsToList (name: text: ''
788 if cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "${name}.json" text} \
789 > ${name}.err 2>&1; then
790 echo "attest-schema: expected invalid statement '${name}' to be rejected" >&2
791 exit 1
792 fi
793 '') invalidStatements
794 )}
795
796 # A map whose keys come from a caller is written as
797 # #AsciiKeyed. Canonical form sorts members by their UTF-8
798 # bytes and RFC 8785 sorts them by UTF-16 code units; the two
799 # agree over ASCII and part company above it, so a non-ASCII
800 # key is two implementations signing different bytes over one
801 # statement. It fails vet rather than reaching a signer.
802 cue vet -d '#AsciiKeyed' ${./schema/attestation.cue} ${
803 pkgs.writeText "ascii-keys.json" ''
804 {"harness": "a harness", "run-id": "1", "": "", "~": "the last printable key"}
805 ''
806 }
807 if cue vet -d '#AsciiKeyed' ${./schema/attestation.cue} ${
808 pkgs.writeText "non-ascii-key.json" ''
809 {"harness": "a harness", "café": "a key two implementations sort differently"}
810 ''
811 } > non-ascii-key.err 2>&1; then
812 echo "attest-schema: expected a non-ASCII key to be rejected" >&2
813 exit 1
814 fi
815 grep -q 'café: field not allowed' non-ascii-key.err
816
817 # A rejection that does not name the field leaves the reader
818 # to find the breakage themselves.
819 grep -q 'signature: conflicting values' signature-in-statement.err
820 grep -q 'subject.digest."valley-tree-v1"' no-content-addressed-subject.err
821 grep -q 'predicate.environment: field not allowed' effectful-claiming-pure.err
822 touch $out
823 '';
824
825 # The canonical form, held to fixed vectors. These bytes are an
826 # interop contract rather than an implementation detail: a
827 # regenerated or independently written attest must render them
828 # identically or every signature already made stops verifying. So
829 # the vectors are checked-in files with a README saying they are
830 # the contract (attest/conformance/), and this check is what holds
831 # a second implementation to them.
832 attest-conformance =
833 pkgs.runCommand "valley-attest-conformance"
834 {
835 nativeBuildInputs = [
836 pkgs.openssh
837 pkgs.cue
838 (attestFor pkgs)
839 ];
840 }
841 ''
842 vectors=${./attest/conformance}
843
844 # One vector rendered and compared, quietly, so the perturbed
845 # run at the end can expect it to fail without saying so.
846 renders() { attest canonical "$1/input.json" | cmp -s - "$1/canonical.json"; }
847
848 found=0
849 signed=0
850 for dir in "$vectors"/vectors/*/; do
851 name="$(basename "$dir")"
852 found=$((found + 1))
853
854 if ! renders "$dir"; then
855 echo "attest-conformance: $name does not render to its recorded bytes" >&2
856 echo " recorded: $(cat "$dir/canonical.json")" >&2
857 echo " rendered: $(attest canonical "$dir/input.json")" >&2
858 exit 1
859 fi
860
861 # The canonical form is a fixed point, or a statement
862 # re-rendered anywhere downstream stops matching what was
863 # signed.
864 if ! attest canonical "$dir/canonical.json" | cmp -s - "$dir/canonical.json"; then
865 echo "attest-conformance: $name is not a fixed point of the canonical form" >&2
866 exit 1
867 fi
868
869 # A vector that is a whole statement is held to the schema
870 # too, so the set cannot drift into documents no verifier
871 # would accept.
872 if grep -q statementType "$dir/canonical.json"; then
873 cue vet -c ${./schema/attestation.cue} "$dir/canonical.json"
874 fi
875
876 # The signed vector pins the whole path from statement to
877 # verifiable signature, not just the serialization. No
878 # --repo: the subject tree is not what this check is about.
879 if [ -e "$dir/statement.sig" ]; then
880 signed=$((signed + 1))
881 attest verify --statement "$dir/canonical.json" \
882 --signature "$dir/statement.sig" \
883 --allowed-signers "$vectors/allowed_signers" > "$name.verify"
884 grep -q 'Good "the-valley.attestation.v1" signature for conformance@the-valley' \
885 "$name.verify"
886 grep -q '^canonical ok' "$name.verify"
887 fi
888 done
889
890 if [ "$found" -lt 8 ] || [ "$signed" -lt 1 ]; then
891 echo "attest-conformance: $found vectors, $signed signed — the set has been emptied" >&2
892 exit 1
893 fi
894
895 # The comparison must be able to fail. One recorded byte
896 # sequence with a single member's value changed is what a
897 # divergent implementation looks like, and it must not pass.
898 mkdir -p perturbed
899 cp "$vectors/vectors/01-key-order/input.json" perturbed/
900 sed 's/"the empty key"/"the empty keys"/' \
901 "$vectors/vectors/01-key-order/canonical.json" > perturbed/canonical.json
902 cmp -s perturbed/canonical.json "$vectors/vectors/01-key-order/canonical.json" \
903 && { echo "attest-conformance: the perturbation changed nothing" >&2; exit 1; }
904 if renders perturbed; then
905 echo "attest-conformance: a perturbed vector passed; the comparison proves nothing" >&2
906 exit 1
907 fi
908
909 echo "attest-conformance: $found vectors render byte for byte, $signed of them signed"
910 touch $out
911 '';
912
913 # The helper itself, driven end to end over scratch repositories
914 # and a throwaway key: what it publishes, what it refuses to
915 # publish, and what a verifier makes of both.
916 #
917 # Every check here uses the command runner. The nix runner cannot
918 # be exercised from inside a nix build — there is no daemon in the
919 # sandbox — so what a pure statement looks like is pinned by
920 # attest-schema above and by the unit tests over the digest
921 # scheme, and the runner itself is exercised by running the helper
922 # outside the sandbox.
923 attest-e2e =
924 pkgs.runCommand "valley-attest-e2e"
925 {
926 nativeBuildInputs = [
927 pkgs.git
928 pkgs.openssh
929 (attestFor pkgs)
930 ];
931 }
932 ''
933 export HOME="$TMPDIR"
934 export GIT_CONFIG_NOSYSTEM=1
935 git config --global user.name valley-check
936 git config --global user.email valley-check@localhost
937 git config --global init.defaultBranch main
938
939 # A throwaway key in a scratch directory. The signer is a
940 # parameter: provisioning a host identity is deployment.
941 ssh-keygen -q -t ed25519 -N "" -C valley-check -f "$TMPDIR/host"
942 ssh-keygen -q -t ed25519 -N "" -C stranger -f "$TMPDIR/stranger"
943 printf 'host@valley %s' "$(cat "$TMPDIR/host.pub")" > "$TMPDIR/allowed_signers"
944 printf 'stranger@elsewhere %s' "$(cat "$TMPDIR/stranger.pub")" > "$TMPDIR/other_signers"
945
946 repo="$TMPDIR/tree"
947 git init --quiet "$repo"
948 cd "$repo"
949 echo hello > hello.txt
950 mkdir -p sub
951 echo nested > sub/nested.txt
952 ln -s hello.txt link
953 printf '#!/bin/sh\ntrue\n' > run.sh
954 chmod 755 run.sh
955 git add -A
956 git commit --quiet -m base
957
958 digest="$(attest digest | sed 's/^valley-tree-v1://')"
959 case "$digest" in
960 [0-9a-f][0-9a-f]*) ;;
961 *) echo "attest-e2e: no tree digest: $digest" >&2; exit 1 ;;
962 esac
963
964 refs() { git for-each-ref --format='%(refname)' refs/the-valley; }
965 nothing_published() {
966 if [ -n "$(refs)" ]; then
967 echo "attest-e2e: $1" >&2
968 git for-each-ref refs/the-valley >&2
969 exit 1
970 fi
971 }
972
973 # Without a key, nothing is emitted — an unsigned statement
974 # is not an attestation.
975 if attest run --command 'ok=true' 2> nokey.err; then
976 echo "attest-e2e: a run with no signing key must fail" >&2
977 exit 1
978 fi
979 grep -q 'no signing key' nokey.err
980 nothing_published "a run with no signing key stored a ref"
981
982 # A failing check publishes nothing, and says which check.
983 if attest run --key "$TMPDIR/host" \
984 --command 'ok=true' --command 'nope=false' > failing.out 2> failing.err; then
985 echo "attest-e2e: a failing check must fail the run" >&2
986 exit 1
987 fi
988 grep -qE '^check nope +command failed$' failing.out
989 grep -q 'nothing published' failing.err
990 nothing_published "a failing check left a ref behind"
991
992 # A statement the schema rejects is stopped before it is
993 # signed or stored. Provenance is the caller's, so a
994 # malformed one is how a malformed statement gets composed
995 # at all.
996 echo '{"harness":"valley-check","authority":"root"}' > bad-provenance.json
997 if attest run --key "$TMPDIR/host" --command 'ok=true' \
998 --provenance bad-provenance.json > malformed.out 2> malformed.err; then
999 echo "attest-e2e: a malformed statement must fail the run" >&2
1000 exit 1
1001 fi
1002 grep -q 'provenance.authority: field not allowed' malformed.err
1003 grep -q 'nothing published' malformed.err
1004 nothing_published "a malformed statement left a ref behind"
1005
1006 # The successful run.
1007 echo '{"harness":"valley-check","model":"none","delegation":[{"principal":"human:integrator","grant":"land changes"}]}' > provenance.json
1008 attest run --key "$TMPDIR/host" --command 'ok=true' \
1009 --provenance provenance.json > run.out
1010 grep -q "^subject valley-tree-v1:$digest\$" run.out
1011 grep -q '^check ok *command passed$' run.out
1012
1013 # Stored at a ref keyed by the subject digest.
1014 ref="$(refs)"
1015 case "$ref" in
1016 refs/the-valley/attestations/"$digest"/*) ;;
1017 *) echo "attest-e2e: ref $ref is not keyed by the subject digest" >&2; exit 1 ;;
1018 esac
1019 git cat-file -p "$ref:ok/statement.json" > statement.json
1020 git cat-file -p "$ref:ok/statement.sig" > statement.sig
1021 grep -q 'BEGIN SSH SIGNATURE' statement.sig
1022 grep -q "\"valley-tree-v1\":\"$digest\"" statement.json
1023 grep -q '"harness":"valley-check"' statement.json
1024
1025 # No git object is signed: the signature is over the
1026 # statement and nothing else.
1027 if git cat-file commit HEAD | grep -q '^gpgsig'; then
1028 echo "attest-e2e: attest signed a git object" >&2
1029 exit 1
1030 fi
1031
1032 verify() {
1033 attest verify --statement "$1" --signature statement.sig \
1034 --allowed-signers "$2" --repo "$repo"
1035 }
1036
1037 verify statement.json "$TMPDIR/allowed_signers" > verify.out
1038 grep -q 'Good "the-valley.attestation.v1" signature for host@valley' verify.out
1039 grep -q 'matches the recorded subject digest' verify.out
1040
1041 # One atomic native-git push carries the branch and the
1042 # attestation ref together.
1043 git init --quiet --bare "$TMPDIR/host.git"
1044 git remote add valley "$TMPDIR/host.git"
1045 attest run --key "$TMPDIR/host" --command 'ok=true' --push valley > push.out
1046 grep -q -- '--atomic' push.out
1047 git -C "$TMPDIR/host.git" for-each-ref --format='%(refname)' > published.txt
1048 grep -qx 'refs/heads/main' published.txt
1049 grep -qx "$ref" published.txt
1050
1051 # A signature by a key the allowed-signers file does not
1052 # list is not a bad signature — it is not a signer.
1053 if verify statement.json "$TMPDIR/other_signers" > stranger.out 2>&1; then
1054 echo "attest-e2e: a statement signed by nobody we allow must not verify" >&2
1055 exit 1
1056 fi
1057 grep -q 'no principal' stranger.out
1058
1059 # Tampering with the signed bytes.
1060 sed "s/$digest/00000000000000000000000000000000000000000000000000000000000000ff/" \
1061 statement.json > tampered.json
1062 if verify tampered.json "$TMPDIR/allowed_signers" > tampered.out 2>&1; then
1063 echo "attest-e2e: a tampered statement must not verify" >&2
1064 exit 1
1065 fi
1066 grep -q 'Signature verification failed' tampered.out
1067
1068 # A statement rendered some other way than canonically.
1069 # It would verify here and fail wherever it was recomposed,
1070 # so it is refused.
1071 sed 's/^{/{ /' statement.json > loose.json
1072 if verify loose.json "$TMPDIR/allowed_signers" > loose.out 2>&1; then
1073 echo "attest-e2e: a non-canonical statement must not verify" >&2
1074 exit 1
1075 fi
1076 grep -q 'not in canonical form' loose.out
1077
1078 # The subject is the tree. Change the tree and the same
1079 # signed statement stops being about it …
1080 echo goodbye > hello.txt
1081 git commit --quiet -am "change the tree"
1082 if verify statement.json "$TMPDIR/allowed_signers" > moved.out 2>&1; then
1083 echo "attest-e2e: a statement about another tree must not verify" >&2
1084 exit 1
1085 fi
1086 grep -q 'tree digest mismatch' moved.out
1087
1088 # … while rewriting the commit over the same tree leaves the
1089 # attestation standing, which is what a subject that is a
1090 # tree digest buys.
1091 git commit --quiet --amend -m "same tree, new commit"
1092 rewritten="$(attest digest | sed 's/^valley-tree-v1://')"
1093 git revert --quiet --no-edit HEAD
1094 restored="$(attest digest | sed 's/^valley-tree-v1://')"
1095 if [ "$restored" != "$digest" ]; then
1096 echo "attest-e2e: restoring the tree did not restore its digest" >&2
1097 echo " original $digest" >&2
1098 echo " restored $restored" >&2
1099 exit 1
1100 fi
1101 if [ "$rewritten" = "$digest" ]; then
1102 echo "attest-e2e: a changed tree kept its digest" >&2
1103 exit 1
1104 fi
1105 verify statement.json "$TMPDIR/allowed_signers" > rebased.out
1106 grep -q 'matches the recorded subject digest' rebased.out
1107 touch $out
1108 '';
1109
1110 # The verification-policy deriver (dcr-f41f718). Composing the two
1111 # layers is CUE's job and is pinned by cue-vet above; matching
1112 # paths is the script's own, and a path matcher is wrong exactly at
1113 # the glob boundaries — `*` inside one segment against `**` across
1114 # segments, `**` matching no segment at all — and at the sides of a
1115 # diff a naive reader drops: a rename's old path and a deletion.
1116 # Each is pinned by driving the real script over a scratch
1117 # repository and a scratch policy, never by reading the code.
1118 policy-deriver =
1119 let
1120 # A floor whose classes are one glob boundary each, and whose
1121 # check names say which class matched.
1122 deriverFloor = pkgs.writeText "deriver-floor.cue" ''
1123 package verification
1124 floor: {
1125 checks: {
1126 "c-docs": {runner: "nix", attribute: "c-docs"}
1127 "c-notes": {runner: "nix", attribute: "c-notes"}
1128 "c-flat": {runner: "nix", attribute: "c-flat"}
1129 "c-deep": {runner: "nix", attribute: "c-deep"}
1130 "c-nested": {runner: "nix", attribute: "c-nested"}
1131 "c-uncovered": {runner: "nix", attribute: "c-uncovered"}
1132 }
1133 classes: {
1134 docs: {paths: "docs/**": true, requires: "c-docs": true}
1135 notes: {paths: "notes/**": true, requires: "c-notes": true}
1136 flat: {paths: "src/*.rs": true, requires: "c-flat": true}
1137 deep: {paths: "src/**/*.rs": true, requires: "c-deep": true}
1138 nested: {paths: "a/**/b": true, requires: "c-nested": true}
1139 }
1140 unclassified: "c-uncovered": true
1141 }
1142 '';
1143 # One requirement that is a template default rather than a
1144 # rule, so the two forms are told apart on real output.
1145 deriverTemplate = pkgs.writeText "deriver-template.cue" ''
1146 package verification
1147 #tmpl: #Policy & {
1148 checks: "c-tmpl": {runner: "nix", attribute: "c-tmpl"}
1149 classes: docs: requires: "c-tmpl": bool | *true
1150 }
1151 '';
1152 deriverProject = pkgs.writeText "deriver-project.cue" ''
1153 package verification
1154 project: {
1155 #tmpl
1156 }
1157 '';
1158 in
1159 pkgs.runCommand "valley-policy-deriver"
1160 {
1161 nativeBuildInputs = [
1162 pkgs.git
1163 pkgs.cue
1164 (valleyScriptFor pkgs)
1165 ];
1166 }
1167 ''
1168 export HOME="$TMPDIR"
1169 export GIT_CONFIG_NOSYSTEM=1
1170 git config --global user.name valley-check
1171 git config --global user.email valley-check@localhost
1172 git config --global init.defaultBranch main
1173
1174 policy="$TMPDIR/policy"
1175 mkdir -p "$policy/instance" "$policy/project"
1176 cp ${deriverFloor} "$policy/instance/floor.cue"
1177 cp ${deriverTemplate} "$policy/instance/template.cue"
1178 cp ${deriverProject} "$policy/project/policy.cue"
1179
1180 repo="$TMPDIR/tree"
1181 git init --quiet "$repo"
1182 cd "$repo"
1183 mkdir -p docs notes src/deep a/x/y
1184 echo moved > docs/moved.md
1185 for f in docs/kept.md docs/gone.md src/one.rs src/deep/two.rs \
1186 a/b a/x/y/b Makefile; do
1187 echo seed > "$f"
1188 done
1189 git add -A
1190 git commit --quiet -m base
1191 base="$(git rev-parse HEAD)"
1192
1193 derive() {
1194 valley checks --schema ${./schema/verification.cue} \
1195 --instance "$policy/instance" --project "$policy/project" \
1196 "$base" HEAD
1197 }
1198
1199 # The check names in the deriver's table, sorted, on one line.
1200 named() {
1201 awk '/^required checks:$/ {f = 1; next}
1202 /^$/ {f = 0}
1203 f && /^ / {print $1}' <<<"$report" | sort | paste -sd' ' -
1204 }
1205
1206 # Start a case from the base tree; assert its check table.
1207 case_start() { git checkout --quiet -B "$1" "$base"; }
1208 expect() {
1209 local got
1210 got="$(named)"
1211 if [ "$got" != "$1" ]; then
1212 echo "policy-deriver: $2" >&2
1213 echo " expected: $1" >&2
1214 echo " got: $got" >&2
1215 echo "$report" >&2
1216 exit 1
1217 fi
1218 }
1219
1220 # `**` crosses segments, `*` does not. One file under src/
1221 # matches both patterns; one a segment deeper matches only
1222 # the `**` one.
1223 case_start flat
1224 echo edit > src/one.rs
1225 git commit --quiet -am flat
1226 report="$(derive)"
1227 expect "c-deep c-flat" "src/*.rs must match a file directly under src/"
1228
1229 case_start deep
1230 echo edit > src/deep/two.rs
1231 git commit --quiet -am deep
1232 report="$(derive)"
1233 expect "c-deep" "src/*.rs must not match across a path separator"
1234
1235 # A `**` between two segments matches no segment at all …
1236 case_start nested-none
1237 echo edit > a/b
1238 git commit --quiet -am nested-none
1239 report="$(derive)"
1240 expect "c-nested" "a/**/b must match a/b"
1241
1242 # … and any number of them.
1243 case_start nested-many
1244 echo edit > a/x/y/b
1245 git commit --quiet -am nested-many
1246 report="$(derive)"
1247 expect "c-nested" "a/**/b must match a/x/y/b"
1248
1249 # A rename counts on both sides: the class covering the old
1250 # path is required as much as the one covering the new.
1251 case_start renamed
1252 git mv docs/moved.md notes/moved.md
1253 git commit --quiet -m renamed
1254 git diff --name-status -M "$base" HEAD | grep -q '^R' \
1255 || { echo "policy-deriver: the rename case is not a rename" >&2; exit 1; }
1256 report="$(derive)"
1257 expect "c-docs c-notes c-tmpl" "a rename must count on both sides"
1258
1259 # A deleted path is still a changed path.
1260 case_start deleted
1261 git rm --quiet docs/gone.md
1262 git commit --quiet -m deleted
1263 report="$(derive)"
1264 expect "c-docs c-tmpl" "a deletion must count"
1265
1266 # The form of the value is the mandatory bit: the floor's
1267 # concrete `true` against the template's `bool | *true`.
1268 grep -qE '^ c-docs +mandatory +docs$' <<<"$report"
1269 grep -qE '^ c-tmpl +default +docs$' <<<"$report"
1270
1271 # A path no class covers takes the unclassified set, and says
1272 # so by name.
1273 case_start uncovered
1274 echo edit > Makefile
1275 git commit --quiet -am uncovered
1276 report="$(derive)"
1277 expect "c-uncovered" "an uncovered path must take the unclassified set"
1278 grep -q '^classes matched: unclassified$' <<<"$report"
1279 grep -q '^unclassified: 1 path(s) matched no class$' <<<"$report"
1280 grep -q '^ Makefile$' <<<"$report"
1281
1282 touch $out
1283 '';
1284
1285 module-eval =
1286 if failedAssertions != [ ] then
1287 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
1288 else if resticRenderedWithoutDeclaration then
1289 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
1290 else if busRenderedWithoutEnable then
1291 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
1292 else if
1293 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
1294 then
1295 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
1296 else
1297 pkgs.runCommand "valley-module-eval"
1298 {
1299 initScript = host.config.systemd.services.valley-init.script;
1300 sshdConfig = host.config.services.openssh.extraConfig;
1301 resticService = host.config.systemd.units."restic-backups-valley.service".text;
1302 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
1303 passAsFile = [
1304 "initScript"
1305 "sshdConfig"
1306 "resticService"
1307 "resticTimer"
1308 ];
1309 }
1310 ''
1311 # The repo init list and mirror hook must be generated from
1312 # the CUE export, and the git user's sshd Match block must
1313 # be terminated so it cannot scope later config.
1314 grep -q "the-valley" "$initScriptPath"
1315 grep -q "valley-mirrors" "$initScriptPath"
1316 grep -q "Match All" "$sshdConfigPath"
1317
1318 # The mirror publishes main and tags only — a heads glob
1319 # would publish every topic branch awaiting review — with
1320 # --prune for tag deletions and a sweep that unpublishes
1321 # any other head (--prune cannot: it ignores non-glob
1322 # refspecs). Never --mirror: it also deletes remote-only
1323 # refs, and GitHub's read-only refs/pull/* fails every such
1324 # push. Follow the hook chain from the init script to the
1325 # rendered push script and pin the invocation there.
1326 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
1327 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
1328 grep -q -- 'push --prune' "$mirrorPush"
1329 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
1330 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
1331 grep -qF -- 'ls-remote --heads' "$mirrorPush"
1332 grep -qF -- 'push "$url" --delete' "$mirrorPush"
1333 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
1334 echo "module-eval: mirror push regressed to publishing every head" >&2
1335 exit 1
1336 fi
1337 if grep -q -- '--mirror' "$mirrorPush"; then
1338 echo "module-eval: mirror push regressed to --mirror" >&2
1339 exit 1
1340 fi
1341 # Deletions must never reach a namespace the mirror owns.
1342 if grep -q 'refs/pull' "$mirrorPush"; then
1343 echo "module-eval: mirror push must not name refs/pull/*" >&2
1344 exit 1
1345 fi
1346
1347 # The rendered restic units must back up the data directory
1348 # to the consumer-supplied repository with the declared
1349 # retention over a pinned host key, on the declared cadence.
1350 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
1351 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
1352 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
1353 grep -q "BatchMode=yes" "$resticServicePath"
1354 grep -q "OnCalendar=03:30" "$resticTimerPath"
1355
1356 # The backup paths render as a --files-from list: follow
1357 # ExecStartPre to that list and pin the data directory.
1358 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
1359 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
1360 grep -qx "/srv/git" "$staticPaths"
1361 touch $out
1362 '';
1363
1364 # What a mirror ends up holding, end to end and unmocked: a bare
1365 # repo wired with the real rendered hooks, pushed to for real, and
1366 # a second bare repo standing in for the mirror. The refspec is
1367 # easy to get subtly wrong — --prune ignores the non-glob heads
1368 # refspec, so pruning heads is the sweep's job — and only running
1369 # git can tell. Relative mirror URLs (mirrorHost) resolve against
1370 # the pushing repo, so the shipped scripts run with no
1371 # substitution: this is exactly what a host executes.
1372 mirror-e2e =
1373 pkgs.runCommand "valley-mirror-e2e"
1374 {
1375 nativeBuildInputs = [ pkgs.git ];
1376 initScript = mirrorHost.config.systemd.services.valley-init.script;
1377 passAsFile = [ "initScript" ];
1378 }
1379 ''
1380 export HOME="$TMPDIR"
1381 export GIT_CONFIG_NOSYSTEM=1
1382 git config --global user.name valley-check
1383 git config --global user.email valley-check@localhost
1384 git config --global init.defaultBranch main
1385 cd "$TMPDIR"
1386
1387 wait_for() {
1388 for _ in $(seq 1 150); do
1389 "$@" >/dev/null 2>&1 && return 0
1390 sleep 0.2
1391 done
1392 echo "mirror-e2e: timed out waiting for: $*" >&2
1393 return 1
1394 }
1395 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
1396 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
1397 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
1398 only_main() { [ "$(heads)" = refs/heads/main ]; }
1399
1400 # A primary repo wired exactly as valley-init wires it, with
1401 # the real store paths followed from the rendered init script.
1402 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1403 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
1404 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
1405 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
1406 wire() {
1407 mkdir -p "$1/hooks/post-receive.d"
1408 ln -s "$dispatch" "$1/hooks/post-receive"
1409 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
1410 }
1411
1412 # The mirror as it stands today: every head and tag of the
1413 # primary, topic branches included. Seeded before the hook is
1414 # wired, so nothing sweeps it out from under the setup.
1415 git init --quiet --bare mirror-pilot.git
1416 git init --quiet --bare mirror.git
1417 git clone --quiet "$PWD/mirror-pilot.git" work
1418 git -C work commit --quiet --allow-empty -m one
1419 git -C work tag v1
1420 git -C work tag doomed
1421 for b in idea/one idea/two; do git -C work branch "$b"; done
1422 git -C work push --quiet origin \
1423 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1424 git -C mirror-pilot.git push --quiet ../mirror.git \
1425 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1426 [ "$(heads | wc -l)" -eq 3 ]
1427 wire mirror-pilot.git "$mhook"
1428
1429 # A real push to the primary — a topic branch alongside main,
1430 # and a tag deleted. The hook replicates asynchronously, so
1431 # wait on main's new tip before judging the rest.
1432 git -C work commit --quiet --allow-empty -m two
1433 git -C work tag -d doomed >/dev/null
1434 git -C work branch idea/three
1435 git -C work push --quiet --follow-tags origin main idea/three
1436 git -C work push --quiet --delete origin doomed
1437 tip="$(git -C work rev-parse HEAD)"
1438 wait_for mirror_main_is
1439
1440 # main and the tags are published; nothing else is, and the
1441 # topic branches that were on the mirror are gone. The sweep
1442 # is a second push, so it converges just after main lands.
1443 wait_for only_main
1444 [ "$(tags)" = refs/tags/v1 ]
1445
1446 # A branch that appears on the mirror by any other route is
1447 # unpublished on the next push.
1448 git -C mirror.git branch sneaky main
1449 git -C work commit --quiet --allow-empty -m three
1450 git -C work push --quiet origin main
1451 tip="$(git -C work rev-parse HEAD)"
1452 wait_for mirror_main_is
1453 wait_for only_main
1454
1455 # An unreachable mirror costs a log line, never the push: the
1456 # hook must return promptly and the push must succeed.
1457 git init --quiet --bare dead-mirror.git
1458 wire dead-mirror.git "$deadhook"
1459 git clone --quiet "$PWD/dead-mirror.git" deadwork
1460 git -C deadwork commit --quiet --allow-empty -m one
1461 timeout 60 git -C deadwork push --quiet origin main
1462 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
1463
1464 touch $out
1465 '';
1466
1467 # Phase 1's exit criteria, end to end and unmocked: a push to a
1468 # bare repo wired with the real rendered hooks produces a
1469 # ref-updated event on a real JetStream server within seconds,
1470 # visible in `valley tail`; replaying the repo's refs is
1471 # deterministic; and a dead bus never fails a push. The hook and
1472 # stream-init scripts are followed from the rendered unit scripts,
1473 # so the check exercises exactly what a host would run — only the
1474 # server invocation differs (the sandbox cannot write /srv), same
1475 # binary and flags, relocated storage.
1476 bus-e2e =
1477 pkgs.runCommand "valley-bus-e2e"
1478 {
1479 nativeBuildInputs = [
1480 pkgs.git
1481 pkgs.natscli
1482 pkgs.nats-server
1483 pkgs.jq
1484 pkgs.cue
1485 (valleyScriptFor pkgs)
1486 ];
1487 initScript = busHost.config.systemd.services.valley-init.script;
1488 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
1489 passAsFile = [
1490 "initScript"
1491 "busInitScript"
1492 ];
1493 }
1494 ''
1495 export HOME="$TMPDIR"
1496 export NATS_URL=nats://127.0.0.1:4222
1497 export GIT_CONFIG_NOSYSTEM=1
1498 git config --global user.name valley-check
1499 git config --global user.email valley-check@localhost
1500 git config --global init.defaultBranch main
1501
1502 wait_for() {
1503 for _ in $(seq 1 150); do
1504 "$@" >/dev/null 2>&1 && return 0
1505 sleep 0.2
1506 done
1507 echo "bus-e2e: timed out waiting for: $*" >&2
1508 return 1
1509 }
1510
1511 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
1512 --store_dir "$TMPDIR/js" &
1513 server_pid=$!
1514
1515 # The real stream-init script the module renders.
1516 bash -eu "$busInitScriptPath"
1517 nats stream info valley >/dev/null
1518
1519 # A bare repo wired exactly as valley-init wires it, with the
1520 # real store paths followed from the rendered init script.
1521 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1522 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
1523 test -x "$dispatch"
1524 test -x "$bushook"
1525 repo="$TMPDIR/events-pilot.git"
1526 git init --quiet --bare "$repo"
1527 mkdir -p "$repo/hooks/post-receive.d"
1528 ln -s "$dispatch" "$repo/hooks/post-receive"
1529 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
1530
1531 git clone --quiet "$repo" "$TMPDIR/work"
1532 cd "$TMPDIR/work"
1533 echo one > file
1534 git add file
1535 git commit --quiet -m one
1536 git push --quiet origin main
1537 first="$(git rev-parse HEAD)"
1538 zeros="$(printf '%040d' 0)"
1539
1540 # Exit criterion 1: the event arrives within seconds, with a
1541 # payload that is exactly the git facts of the push …
1542 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
1543 wait_for msgs_is 1
1544 got="$(nats stream get valley 1 --json)"
1545 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
1546 payload="$(jq -r .data <<<"$got" | base64 -d)"
1547 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
1548 [ "$payload" = "$expected" ]
1549
1550 # … valid against the shipped event schema.
1551 echo "$payload" > "$TMPDIR/payload.json"
1552 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
1553
1554 # … and visible in `valley tail`. Subscribe first, then push.
1555 valley tail > "$TMPDIR/tail.out" 2>&1 &
1556 tail_pid=$!
1557 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
1558 wait_for subscribed
1559 echo two > file
1560 git commit --quiet -am two
1561 git push --quiet origin main
1562 second="$(git rev-parse HEAD)"
1563 wait_for msgs_is 2
1564 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
1565 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
1566 [ "$payload2" = "$expected2" ]
1567 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
1568 wait_for tail_saw
1569 kill "$tail_pid" 2>/dev/null || true
1570
1571 # Exit criterion 2: rebuilding the stream from the repo's
1572 # refs is deterministic — two replays from scratch produce
1573 # identical events, landing on the pushed tip with the
1574 # all-zero id as old.
1575 dump_stream() {
1576 local info first_seq last_seq i
1577 info="$(nats stream info valley --json)"
1578 first_seq="$(jq .state.first_seq <<<"$info")"
1579 last_seq="$(jq .state.last_seq <<<"$info")"
1580 for i in $(seq "$first_seq" "$last_seq"); do
1581 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
1582 done
1583 }
1584 nats stream purge valley --force >/dev/null
1585 valley replay "$repo"
1586 wait_for msgs_is 1
1587 run1="$(dump_stream)"
1588 nats stream purge valley --force >/dev/null
1589 valley replay "$repo"
1590 wait_for msgs_is 1
1591 run2="$(dump_stream)"
1592 [ "$run1" = "$run2" ]
1593 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
1594 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
1595
1596 # A dead bus never blocks a push: the event is simply lost
1597 # (and rebuildable by replay).
1598 kill "$server_pid"
1599 wait "$server_pid" || true
1600 echo three > file
1601 git commit --quiet -am three
1602 git push --quiet origin main
1603
1604 touch $out
1605 '';
1606 }
1607 );
1608 };
1609}