gunk-dev/the-valley

flake.nix

source0f6e55723d65main's published tip history
90.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 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, note format included — hence vendorHash = null, and hence no
68 # module fetch at build time. Its unit tests run in the checkPhase and
69 # need git and ssh-keygen.
70 attestUnwrappedFor =
71 pkgs:
72 pkgs.buildGoModule {
73 pname = "valley-attest";
74 version = "0";
75 src = ./attest;
76 vendorHash = null;
77 nativeCheckInputs = [
78 pkgs.git
79 pkgs.openssh
80 ];
81 meta.mainProgram = "attest";
82 };
83
84 # The shipping form. git and cue are pinned to this flake's nixpkgs,
85 # so every host composes and vets a statement with the same tools.
86 # Signing needs no tool at all: a note is signed on crypto/ed25519
87 # inside the binary. `nix` is deliberately NOT pinned: the check being
88 # attested to must be built by the nix the machine actually runs, and
89 # a nix carried in here would be a second one.
90 attestFor =
91 pkgs:
92 pkgs.runCommand "valley-attest"
93 {
94 nativeBuildInputs = [ pkgs.makeWrapper ];
95 meta.mainProgram = "attest";
96 }
97 ''
98 mkdir -p $out/bin
99 makeWrapper ${lib.getExe (attestUnwrappedFor pkgs)} $out/bin/attest \
100 --prefix PATH : ${
101 lib.makeBinPath [
102 pkgs.git
103 pkgs.cue
104 ]
105 } \
106 --set-default VALLEY_ATTEST_SCHEMA ${./schema/attestation.cue}
107 '';
108
109 # The Phase 3 integrator (dcr-439b771). Go, standard library only,
110 # same trade as attest — hence vendorHash = null and no module fetch.
111 integratorUnwrappedFor =
112 pkgs:
113 pkgs.buildGoModule {
114 pname = "valley-integrator";
115 version = "0";
116 src = ./integrator;
117 vendorHash = null;
118 meta.mainProgram = "integrator";
119 };
120
121 # The shipping form. The integrator drives four programs rather than
122 # reimplementing what they do: attest judges every statement and
123 # every note, the valley deriver and cue compose the policy, and git
124 # holds the requests and the refs. All four are pinned to this
125 # flake's nixpkgs so an instance's integrators agree; `nix` is
126 # deliberately absent for the same reason it is absent from attest —
127 # a closure must be recomputed by the nix the machine actually runs.
128 integratorFor =
129 pkgs:
130 pkgs.runCommand "valley-integrator"
131 {
132 nativeBuildInputs = [ pkgs.makeWrapper ];
133 meta.mainProgram = "integrator";
134 }
135 ''
136 mkdir -p $out/bin
137 makeWrapper ${lib.getExe (integratorUnwrappedFor pkgs)} $out/bin/integrator \
138 --prefix PATH : ${
139 lib.makeBinPath [
140 pkgs.git
141 pkgs.cue
142 pkgs.natscli
143 (attestFor pkgs)
144 (valleyScriptFor pkgs)
145 ]
146 } \
147 --set-default VALLEY_ATTEST_SCHEMA ${./schema/attestation.cue} \
148 --set-default VALLEY_VERIFICATION_SCHEMA ${./schema/verification.cue} \
149 --set-default VALLEY_EVENT_SCHEMA ${./schema/events.cue}
150 '';
151 in
152 {
153 nixosModules.valley-host = ./nix/valley-host.nix;
154 nixosModules.default = self.nixosModules.valley-host;
155
156 # The knowledge lint, for any project that keeps a `.the-valley/` graph.
157 # This is the check's primary form: a consuming project takes this flake
158 # as an input and instantiates the derivation over its own source, so the
159 # check a policy names is supplied by the instance rather than written
160 # again by every project the policy covers (dcr-f41f718). A whole
161 # consuming flake is:
162 #
163 # {
164 # inputs.the-valley.url = "github:gunk-dev/the-valley";
165 # outputs =
166 # { self, the-valley }:
167 # {
168 # checks.x86_64-linux.knowledge-lint = the-valley.lib.knowledgeLint {
169 # system = "x86_64-linux";
170 # src = self;
171 # };
172 # };
173 # }
174 #
175 # There is no nixpkgs input in that flake on purpose: cue and python come
176 # from this flake's pinned nixpkgs, so every project in a group runs the
177 # same lint against the same toolchain. `root` names the graph directory
178 # for a project that keeps its graph somewhere other than `.the-valley/`.
179 lib.knowledgeLint =
180 {
181 system,
182 src,
183 root ? ".the-valley",
184 }:
185 import ./nix/knowledge-lint.nix {
186 inherit src root;
187 pkgs = nixpkgs.legacyPackages.${system};
188 };
189
190 apps = lib.genAttrs systems (system: {
191 fmt = {
192 type = "app";
193 program = lib.getExe (proseFmtFor nixpkgs.legacyPackages.${system});
194 };
195 attest = {
196 type = "app";
197 program = lib.getExe (attestFor nixpkgs.legacyPackages.${system});
198 };
199 integrator = {
200 type = "app";
201 program = lib.getExe (integratorFor nixpkgs.legacyPackages.${system});
202 };
203 });
204
205 packages = lib.genAttrs systems (
206 system:
207 let
208 valley = valleyCliFor nixpkgs.legacyPackages.${system};
209 in
210 {
211 inherit valley;
212 default = valley;
213 attest = attestFor nixpkgs.legacyPackages.${system};
214 integrator = integratorFor nixpkgs.legacyPackages.${system};
215 }
216 );
217
218 checks = lib.genAttrs systems (
219 system:
220 let
221 pkgs = nixpkgs.legacyPackages.${system};
222
223 # Eval-only instantiation of the module — catches option-surface
224 # and cue-export regressions without building or booting anything.
225 # Each check host shares the machine baseline and supplies its own
226 # declaration (and, where the declaration asks for backup, the
227 # secret paths).
228 mkHost =
229 module:
230 lib.nixosSystem {
231 inherit system;
232 modules = [
233 self.nixosModules.default
234 {
235 fileSystems."/" = {
236 device = "/dev/disk/by-label/nixos";
237 fsType = "ext4";
238 };
239 boot.loader.grub.enable = false;
240 system.stateVersion = "25.11";
241 services.valley = {
242 enable = true;
243 authorizedKeys = [ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholderKeyForEvalOnlyCheck0 valley-check" ];
244 };
245 }
246 module
247 ];
248 };
249
250 # The example declaration enables backup, so this host supplies
251 # the four secret paths (eval-only placeholders).
252 host = mkHost {
253 services.valley = {
254 config = ./examples/host.cue;
255 backup = {
256 repositoryFile = "/run/agenix/valley-restic-repo";
257 passwordFile = "/run/agenix/valley-restic-password";
258 sshKeyFile = "/run/agenix/valley-git-ssh-key";
259 knownHostsFile = "/var/lib/valley-backup/known_hosts";
260 };
261 };
262 };
263
264 # A declaration without a backup block predates the field and must
265 # keep evaluating exactly as before: zero restic machinery.
266 noBackupHost = mkHost {
267 services.valley.config = pkgs.writeText "no-backup-host.cue" ''
268 package valley
269 projects: "the-valley": {}
270 '';
271 };
272
273 # The example declaration with the secret paths left unset: the
274 # module must refuse with assertions naming the missing options.
275 noSecretsHost = mkHost {
276 services.valley.config = ./examples/host.cue;
277 };
278
279 # Bus enabled, minimal declaration. The bus-e2e check drives this
280 # host's rendered hooks and stream-init against a real server.
281 busHost = mkHost {
282 services.valley = {
283 config = pkgs.writeText "bus-host.cue" ''
284 package valley
285 projects: "events-pilot": {}
286 '';
287 bus.enable = true;
288 };
289 };
290
291 # Two mirror URLs the sandbox can serve: git resolves a relative
292 # URL against the pushing repo's directory, so the mirror-e2e
293 # check drives the rendered script with no substitution at all —
294 # one reachable sibling repo, one that does not exist.
295 mirrorHost = mkHost {
296 services.valley.config = pkgs.writeText "mirror-host.cue" ''
297 package valley
298 projects: "mirror-pilot": mirrors: ["../mirror.git"]
299 projects: "dead-mirror": mirrors: ["../nope.git"]
300 '';
301 };
302
303 failedAssertions = builtins.filter (a: !a.assertion) (
304 host.config.assertions
305 ++ noBackupHost.config.assertions
306 ++ busHost.config.assertions
307 ++ mirrorHost.config.assertions
308 );
309
310 missingSecretAssertions = builtins.filter (a: !a.assertion) noSecretsHost.config.assertions;
311
312 resticRenderedWithoutDeclaration =
313 noBackupHost.config.systemd.services ? "restic-backups-valley"
314 || noBackupHost.config.systemd.timers ? "restic-backups-valley";
315
316 # The bus defaults off; a host that never asked for one must
317 # render zero bus machinery.
318 busRenderedWithoutEnable =
319 noBackupHost.config.systemd.services ? valley-bus
320 || noBackupHost.config.systemd.services ? valley-bus-init;
321
322 # A tree in the store, written from a path -> contents map. The
323 # knowledge lint reads a whole graph rather than a file, so every
324 # fixture below is small but complete.
325 mkTree =
326 name: files:
327 pkgs.runCommand name { } (
328 lib.concatStrings (
329 lib.mapAttrsToList (path: text: ''
330 install -Dm444 ${pkgs.writeText "knowledge-lint-fixture" text} $out/${path}
331 '') files
332 )
333 );
334
335 # A project that is nearly nothing: a README, a docs directory, and
336 # five nodes carrying one of each typed edge. This is the shape the
337 # first consuming project has, and the knowledge-lint-consumer check
338 # instantiates lib.knowledgeLint over it exactly as that project's
339 # own flake would. The nodes created on or before the id-rule
340 # cutoff carry ids their slugs do not derive, and must pass anyway;
341 # the graduated idea postdates the cutoff and carries the derived
342 # id its slug demands.
343 consumerProject = mkTree "knowledge-lint-consumer-project" {
344 "README.md" = ''
345 # A project
346
347 It keeps its knowledge in [.the-valley](./.the-valley/).
348 '';
349 "docs/design.md" = ''
350 # Design
351
352 ## The shape
353 '';
354 ".the-valley/ideas/ida-0a1b2c3-the-shape.md" = ''
355 ---
356 type: idea
357 id: ida-0a1b2c3
358 status: raw
359 title: The shape the design should take
360 created: 2026-08-02
361 ---
362
363 # The shape the design should take
364
365 As sketched in [design.md](../../docs/design.md#the-shape).
366 '';
367 ".the-valley/outcomes/oc-4d5e6f7-the-design-lands.md" = ''
368 ---
369 type: outcome
370 id: oc-4d5e6f7
371 status: open
372 title: The design lands
373 created: 2026-08-02
374 blocked_by: [ida-0a1b2c3]
375 ---
376
377 # The design lands
378
379 Waits on [[ida-0a1b2c3]].
380 '';
381 ".the-valley/decisions/dcr-1122334-where-the-graph-lives.md" = ''
382 ---
383 type: decision
384 id: dcr-1122334
385 status: superseded
386 title: Where the graph lives
387 created: 2026-08-02
388 ---
389
390 # Where the graph lives
391
392 The graph is a directory of markdown files under the project root.
393 '';
394 ".the-valley/decisions/dcr-5566778-where-the-graph-lives.md" = ''
395 ---
396 type: decision
397 id: dcr-5566778
398 status: decided
399 title: Where the graph lives
400 created: 2026-08-02
401 supersedes: [dcr-1122334]
402 ---
403
404 # Where the graph lives
405
406 The graph is a directory of markdown files at `.the-valley/`, alongside the code.
407 '';
408 # sha256("the-shape-graduates") begins ba2b574.
409 ".the-valley/ideas/ida-ba2b574-the-shape-graduates.md" = ''
410 ---
411 type: idea
412 id: ida-ba2b574
413 status: graduated
414 title: An idea whose thinking now lives in a decision
415 created: 2026-08-06
416 graduated_into: dcr-5566778
417 ---
418
419 # An idea whose thinking now lives in a decision
420
421 Graduated into [[dcr-5566778]].
422 '';
423 };
424
425 # A project with no graph at all. Adding the check must not require
426 # having written a node yet, or no project would ever adopt it
427 # before its first one.
428 graphlessProject = mkTree "knowledge-lint-graphless-project" {
429 "README.md" = ''
430 # A project with no knowledge graph yet
431 '';
432 };
433
434 # What the lint must reject, and the words its failure must contain.
435 # A lint that fails without naming the file and the defect costs the
436 # reader the whole diagnosis, so both are pinned.
437 rejectedGraphs = {
438 unknown-status = {
439 names = ''ida-0000001-a-node.md".status'';
440 files.".the-valley/ideas/ida-0000001-a-node.md" = ''
441 ---
442 type: idea
443 id: ida-0000001
444 status: nonsense
445 title: A node in a state ideas do not have
446 created: 2026-08-02
447 ---
448 '';
449 };
450
451 edge-on-the-wrong-type = {
452 names = "blocked_by: field not allowed";
453 files.".the-valley/ideas/ida-0000002-a-node.md" = ''
454 ---
455 type: idea
456 id: ida-0000002
457 status: raw
458 title: An idea carrying the one edge only outcomes carry
459 created: 2026-08-02
460 blocked_by: []
461 ---
462 '';
463 };
464
465 node-in-the-wrong-directory = {
466 names = "a bug node belongs in .the-valley/bugs/";
467 files.".the-valley/ideas/bd-0000003-a-bug.md" = ''
468 ---
469 type: bug
470 id: bd-0000003
471 status: open
472 title: A bug filed among the ideas
473 created: 2026-08-02
474 ---
475 '';
476 };
477
478 filename-id-mismatch = {
479 names = "filename says id ida-0000004, frontmatter says ida-0000005";
480 files.".the-valley/ideas/ida-0000004-a-node.md" = ''
481 ---
482 type: idea
483 id: ida-0000005
484 status: raw
485 title: A node whose filename and frontmatter disagree
486 created: 2026-08-02
487 ---
488 '';
489 };
490
491 duplicate-id = {
492 names = "is already used by";
493 files = {
494 ".the-valley/ideas/ida-0000006-one.md" = ''
495 ---
496 type: idea
497 id: ida-0000006
498 status: raw
499 title: One node
500 created: 2026-08-02
501 ---
502 '';
503 ".the-valley/ideas/ida-0000006-two.md" = ''
504 ---
505 type: idea
506 id: ida-0000006
507 status: raw
508 title: Another node wearing the same id
509 created: 2026-08-02
510 ---
511 '';
512 };
513 };
514
515 missing-frontmatter = {
516 names = "no YAML frontmatter";
517 files.".the-valley/ideas/ida-0000007-a-node.md" = ''
518 # A node that is only prose
519 '';
520 };
521
522 dangling-wiki-link = {
523 names = "[[ida-9999999]] is not a node id";
524 files.".the-valley/ideas/ida-0000008-a-node.md" = ''
525 ---
526 type: idea
527 id: ida-0000008
528 status: raw
529 title: A node pointing at nothing
530 created: 2026-08-02
531 ---
532
533 It builds on [[ida-9999999]].
534 '';
535 };
536
537 dangling-blocked-by = {
538 names = "blocked_by names oc-9999999, which is not a node";
539 files.".the-valley/outcomes/oc-0000009-an-outcome.md" = ''
540 ---
541 type: outcome
542 id: oc-0000009
543 status: open
544 title: An outcome waiting on nothing that exists
545 created: 2026-08-02
546 blocked_by: [oc-9999999]
547 ---
548 '';
549 };
550
551 dangling-supersedes = {
552 names = "supersedes names dcr-9999999, which is not a node";
553 files.".the-valley/decisions/dcr-000000c-a-decision.md" = ''
554 ---
555 type: decision
556 id: dcr-000000c
557 status: decided
558 title: A decision replacing nothing that exists
559 created: 2026-08-02
560 supersedes: [dcr-9999999]
561 ---
562 '';
563 };
564
565 # The edge alone is half a supersession. A node declared replaced
566 # while its own status still reads otherwise leaves the graph
567 # saying two things, which is the defect the edge exists to end.
568 supersedes-a-node-still-standing = {
569 names = "whose status is adopted, not superseded";
570 files = {
571 ".the-valley/ideas/ida-000000d-the-replacement.md" = ''
572 ---
573 type: idea
574 id: ida-000000d
575 status: adopted
576 title: An idea replacing one that has not been told
577 created: 2026-08-02
578 supersedes: [ida-000000e]
579 ---
580 '';
581 ".the-valley/ideas/ida-000000e-the-replaced.md" = ''
582 ---
583 type: idea
584 id: ida-000000e
585 status: adopted
586 title: An idea replaced in fact but not in its status
587 created: 2026-08-02
588 ---
589 '';
590 };
591 };
592
593 supersedes-on-the-wrong-type = {
594 names = "supersedes: field not allowed";
595 files.".the-valley/outcomes/oc-000000f-an-outcome.md" = ''
596 ---
597 type: outcome
598 id: oc-000000f
599 status: open
600 title: An outcome carrying the edge only ideas and decisions carry
601 created: 2026-08-02
602 blocked_by: []
603 supersedes: []
604 ---
605 '';
606 };
607
608 # Only ideas and decisions have a `superseded` status, so an edge
609 # naming any other type is rejected on shape by the schema.
610 supersedes-a-type-that-cannot-be = {
611 names = ''supersedes.0: invalid value "bd-0000011"'';
612 files.".the-valley/ideas/ida-0000010-a-node.md" = ''
613 ---
614 type: idea
615 id: ida-0000010
616 status: adopted
617 title: An idea claiming to replace a bug
618 created: 2026-08-02
619 supersedes: [bd-0000011]
620 ---
621 '';
622 };
623
624 # The id rule: a node created after the cutoff must carry the id
625 # its slug derives, and the failure names the id it should have.
626 non-derived-id = {
627 names = "sha256 of the slug gives ida-d1d9c0c";
628 files.".the-valley/ideas/ida-1111111-a-node.md" = ''
629 ---
630 type: idea
631 id: ida-1111111
632 status: raw
633 title: A node whose id its slug does not derive
634 created: 2026-08-06
635 ---
636 '';
637 };
638
639 # Graduation cannot be half-declared: the status without the
640 # destination is rejected by the schema.
641 graduated-without-destination = {
642 names = "graduated_into: incomplete value";
643 files.".the-valley/ideas/ida-d1d9c0c-a-node.md" = ''
644 ---
645 type: idea
646 id: ida-d1d9c0c
647 status: graduated
648 title: A graduated idea that does not say where it went
649 created: 2026-08-06
650 ---
651 '';
652 };
653
654 dangling-graduated-into = {
655 names = "graduated_into names dcr-9999999, which is not a node";
656 files.".the-valley/ideas/ida-d1d9c0c-a-node.md" = ''
657 ---
658 type: idea
659 id: ida-d1d9c0c
660 status: graduated
661 title: A graduated idea naming a decision that is not there
662 created: 2026-08-06
663 graduated_into: dcr-9999999
664 ---
665 '';
666 };
667
668 broken-link = {
669 names = "./nowhere.md does not exist";
670 files.".the-valley/ideas/ida-000000a-a-node.md" = ''
671 ---
672 type: idea
673 id: ida-000000a
674 status: raw
675 title: A node linking to a file that is not there
676 created: 2026-08-02
677 ---
678
679 See [nowhere](./nowhere.md).
680 '';
681 };
682
683 broken-anchor = {
684 names = "names no heading";
685 files.".the-valley/ideas/ida-000000b-a-node.md" = ''
686 ---
687 type: idea
688 id: ida-000000b
689 status: raw
690 title: A node linking to a heading that is not there
691 created: 2026-08-02
692 ---
693
694 # A heading
695
696 See [above](./ida-000000b-a-node.md#not-this-heading).
697 '';
698 };
699 };
700 in
701 {
702 # The CLI must stay a lint-clean script whose help verb answers
703 # without a repo or a remote — the cheap end of its eviction clause
704 # (dcr-74c3158); anything needing more graduates instead. The
705 # completions are held to the same bar, and the installed package
706 # must carry them at the auto-linked paths.
707 valley-cli =
708 let
709 valley = valleyCliFor pkgs;
710 in
711 pkgs.runCommand "valley-cli"
712 {
713 nativeBuildInputs = [
714 pkgs.shellcheck
715 pkgs.zsh
716 valley
717 ];
718 }
719 ''
720 shellcheck ${./bin/valley}
721 shellcheck ${./completions/valley.bash}
722 # shellcheck cannot lint zsh; a bare parse is the cheap check.
723 zsh -n ${./completions/_valley}
724 valley help > help.txt
725 grep -q '^usage: valley' help.txt
726 test -f ${valley}/share/bash-completion/completions/valley
727 test -f ${valley}/share/zsh/site-functions/_valley
728 touch $out
729 '';
730
731 # Markdown prose format (ida-1ec03b1): the check is formatter
732 # idempotence — formatting the tree must change nothing. On failure,
733 # fix with `nix run .#fmt`.
734 prose-format =
735 pkgs.runCommand "valley-prose-format"
736 {
737 nativeBuildInputs = [ pkgs.prettier ];
738 }
739 ''
740 cd ${self}
741 find . -name '*.md' -print0 | xargs -0 --no-run-if-empty \
742 prettier ${proseFmtArgs} --check
743 touch $out
744 '';
745
746 # This repo's own graph, checked by the derivation the flake
747 # exposes rather than by a second implementation of it. Whatever a
748 # consuming project runs, this repo runs.
749 knowledge-lint = self.lib.knowledgeLint {
750 inherit system;
751 src = self;
752 };
753
754 # The reusable form, exercised over a foreign tree: a project that
755 # is a README, a docs directory and two nodes, and a project with no
756 # graph at all. Both must pass, and both are checked by depending on
757 # the instantiated derivations rather than by re-running the lint.
758 knowledge-lint-consumer =
759 pkgs.runCommand "valley-knowledge-lint-consumer"
760 {
761 consumer = self.lib.knowledgeLint {
762 inherit system;
763 src = consumerProject;
764 };
765 graphless = self.lib.knowledgeLint {
766 inherit system;
767 src = graphlessProject;
768 };
769 }
770 ''
771 test -e "$consumer" && test -e "$graphless"
772 touch $out
773 '';
774
775 # The lint must fail on a broken graph, and its failure must name
776 # the file and the defect — a check that only says "no" leaves the
777 # reader to find the breakage themselves. The script and the schema
778 # here are the same store paths lib.knowledgeLint uses, so the
779 # rejections cannot drift from what a consumer runs.
780 knowledge-lint-rejects =
781 pkgs.runCommand "valley-knowledge-lint-rejects"
782 {
783 nativeBuildInputs = [
784 pkgs.cue
785 pkgs.python3
786 ];
787 }
788 ''
789 ${lib.concatStrings (
790 lib.mapAttrsToList (case: spec: ''
791 mkdir -p work/${case}
792 if python3 ${./nix/knowledge-lint.py} \
793 --tree ${mkTree "knowledge-lint-${case}" spec.files} \
794 --schema ${./schema/node.cue} \
795 --work work/${case} 2> ${case}.err
796 then
797 echo "knowledge-lint: expected graph '${case}' to be rejected" >&2
798 exit 1
799 fi
800 if ! grep -qF -- ${lib.escapeShellArg spec.names} ${case}.err; then
801 echo "knowledge-lint: '${case}' was rejected without naming" \
802 ${lib.escapeShellArg spec.names} >&2
803 cat ${case}.err >&2
804 exit 1
805 fi
806 '') rejectedGraphs
807 )}
808 touch $out
809 '';
810
811 # The example host declaration must vet against the schema, and the
812 # schema must reject what it claims to reject: unsafe project names,
813 # unknown project fields, stray top-level fields (typos, deployment
814 # concerns), and malformed backup policy (machine concerns, targets
815 # without an implementation, non-positive retention). CUE closedness
816 # is easy to regress silently — e.g. embedding #Host instead of
817 # referencing it opens the schema — so the rejections are pinned
818 # here.
819 cue-vet =
820 let
821 invalidConfigs = {
822 unsafe-project-name = ''
823 package valley
824 projects: ".hidden": {}
825 '';
826 unknown-project-field = ''
827 package valley
828 projects: ok: dataDir: "/srv/git"
829 '';
830 top-level-typo = ''
831 package valley
832 project: oops: {}
833 '';
834 deployment-concern-in-cue = ''
835 package valley
836 user: "git"
837 projects: ok: {}
838 '';
839 machine-concern-in-backup = ''
840 package valley
841 projects: ok: {}
842 backup: repositoryFile: "/run/agenix/valley-restic-repo"
843 '';
844 unimplemented-backup-target = ''
845 package valley
846 projects: ok: {}
847 backup: target: "restic-s3"
848 '';
849 negative-retention = ''
850 package valley
851 projects: ok: {}
852 backup: retention: daily: -1
853 '';
854 };
855 in
856 pkgs.runCommand "valley-cue-vet"
857 {
858 nativeBuildInputs = [ pkgs.cue ];
859 }
860 ''
861 cue vet -c ${./schema/valley.cue} ${./examples/host.cue}
862 cue export ${./schema/valley.cue} ${./examples/host.cue} > example.json
863 grep -q 'gunk-dev/the-valley' example.json
864 grep -q 'restic-sftp' example.json
865
866 # A declaration without a backup block must stay valid —
867 # consumers written before the field existed keep vetting.
868 cue vet -c ${./schema/valley.cue} ${pkgs.writeText "no-backup.cue" ''
869 package valley
870 projects: "the-valley": {}
871 ''}
872
873 # The event schema accepts what the publisher hook emits …
874 cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated.json" ''
875 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"}
876 ''}
877 # … and stays closed: a field outside the git-derivable
878 # identity — wall-clock time, a hostname — must be rejected,
879 # or replay determinism silently dies.
880 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-timestamped.json" ''
881 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3","time":"2026-07-16T00:00:00Z"}
882 ''}; then
883 echo "cue-vet: expected the timestamped ref-updated payload to be rejected" >&2
884 exit 1
885 fi
886 if cue vet -d '#RefUpdated' ${./schema/events.cue} ${pkgs.writeText "ref-updated-short-sha.json" ''
887 {"event":"ref-updated","repo":"the-valley","ref":"refs/heads/main","old":"0000000000000000000000000000000000000000","new":"a94a8fe"}
888 ''}; then
889 echo "cue-vet: expected the abbreviated object id to be rejected" >&2
890 exit 1
891 fi
892
893 ${lib.concatStrings (
894 lib.mapAttrsToList (name: cfg: ''
895 if cue vet -c ${./schema/valley.cue} ${pkgs.writeText "${name}.cue" cfg}; then
896 echo "cue-vet: expected invalid config '${name}' to be rejected" >&2
897 exit 1
898 fi
899 '') invalidConfigs
900 )}
901 touch $out
902 '';
903
904 # The attestation statement schema (dcr-0de694f). A statement the
905 # helper composes must vet, and the schema must reject what it
906 # claims to reject. Two rejections carry the decision's whole
907 # weight and are pinned by name below: a subject with no
908 # content-addressed digest has no identity at all, and a
909 # predicate that crosses the pure/effectful line would let a
910 # notarization pass itself off as re-derivable.
911 attest-schema =
912 let
913 treeDigest = "73847e0b723a444df8c677e5e67d2e7858327259323c76b24f8f11b650b66d69";
914 subject = ''
915 "subject": {
916 "primary": "valley-tree-v1",
917 "digest": {
918 "valley-tree-v1": "${treeDigest}",
919 "git-sha1": "99b5f2f7971e2c8e37a7a579cb761d80272a9a3d"
920 }
921 }
922 '';
923 pureStatement = ''
924 {
925 "statementType": "the-valley/attestation/v1",
926 ${subject},
927 "predicateType": "the-valley/check/pure/v1",
928 "predicate": {
929 "check": {"name": "prose-format", "runner": "nix", "attribute": "prose-format"},
930 "result": "passed",
931 "inputs": {"valley-inputs-v1": "8df8c199decb43eb715790d6fc3a9dd96adaaf3a75073a50acfa51d73aaf3253"},
932 "derivation": {"sha256": "ef69ed0ccc0546a38a40eebbfcac610cedd7cf4f81036cd21ddff483f08d3ad7"},
933 "output": {"valley-tree-v1": "cf1f5a9c96bbdf1d69da451c94168fa3a760f91f94827ba88bdb72de8dfa8af9"}
934 },
935 "provenance": {
936 "harness": "a harness",
937 "model": "a model",
938 "prompt": {"sha256": "5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03"},
939 "delegation": [{"principal": "human:integrator", "grant": "land changes"}]
940 }
941 }
942 '';
943 effectfulStatement = ''
944 {
945 "statementType": "the-valley/attestation/v1",
946 ${subject},
947 "predicateType": "the-valley/check/effectful/v1",
948 "predicate": {
949 "check": {"name": "live-api", "runner": "command", "command": "curl -sf https://example.invalid"},
950 "result": "passed",
951 "environment": "a sealed environment",
952 "observedAt": "2026-08-02T13:02:00Z"
953 }
954 }
955 '';
956 # Each case is the pure statement with one thing wrong.
957 invalidStatements = {
958 # Carriage is not statement: a signature inside the signed
959 # bytes is a category error, and the sentinel names it.
960 signature-in-statement = builtins.replaceStrings [ "\"statementType\"" ] [
961 "\"signature\": \"-----BEGIN SSH SIGNATURE-----\", \"statementType\""
962 ] pureStatement;
963 # A subject with only advisory members.
964 no-content-addressed-subject =
965 builtins.replaceStrings [ "\"valley-tree-v1\": \"${treeDigest}\"," ] [ "" ]
966 pureStatement;
967 # A notarization wearing a re-derivable predicate type.
968 effectful-claiming-pure = builtins.replaceStrings [ "the-valley/check/effectful/v1" ] [
969 "the-valley/check/pure/v1"
970 ] effectfulStatement;
971 # A re-derivable claim that drops what it is re-derived
972 # against.
973 pure-without-output = builtins.replaceStrings [ "\"output\"" ] [ "\"outputs\"" ] pureStatement;
974 # A predicate type nobody has published a shape for.
975 unversioned-predicate-type =
976 builtins.replaceStrings [ "the-valley/check/pure/v1" ] [ "the-valley/check/pure" ]
977 pureStatement;
978 # A digest under a scheme no verifier can check.
979 unknown-digest-scheme = builtins.replaceStrings [ "\"git-sha1\"" ] [ "\"md5\"" ] pureStatement;
980 # An abbreviated digest.
981 short-digest = builtins.replaceStrings [ treeDigest ] [ "73847e0b" ] pureStatement;
982 # A check name outside the shape schema/verification.cue
983 # holds check names to.
984 unsafe-check-name = builtins.replaceStrings [ "\"prose-format\", \"runner\"" ] [
985 "\"Prose Format\", \"runner\""
986 ] pureStatement;
987 # A nix check carrying a command line.
988 nix-check-with-a-command = builtins.replaceStrings [ "\"runner\": \"nix\"" ] [
989 "\"runner\": \"nix\", \"command\": \"make\""
990 ] pureStatement;
991 # A value with no written form. The statement is written
992 # out as lines and the form has no escapes, so a command
993 # spanning two of them is stopped at the gate rather than
994 # in a renderer after the check has already run.
995 command-over-two-lines = builtins.replaceStrings [ "curl -sf https://example.invalid" ] [
996 "curl -sf https://example.invalid \\\\\\n --retry 3"
997 ] effectfulStatement;
998 # And the other value a line cannot carry.
999 empty-environment = builtins.replaceStrings [ "\"a sealed environment\"" ] [
1000 "\"\""
1001 ] effectfulStatement;
1002 };
1003 in
1004 pkgs.runCommand "valley-attest-schema"
1005 {
1006 nativeBuildInputs = [ pkgs.cue ];
1007 }
1008 ''
1009 cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "pure.json" pureStatement}
1010 cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "effectful.json" effectfulStatement}
1011
1012 ${lib.concatStrings (
1013 lib.mapAttrsToList (name: text: ''
1014 if cue vet -c ${./schema/attestation.cue} ${pkgs.writeText "${name}.json" text} \
1015 > ${name}.err 2>&1; then
1016 echo "attest-schema: expected invalid statement '${name}' to be rejected" >&2
1017 exit 1
1018 fi
1019 '') invalidStatements
1020 )}
1021
1022 # A map whose keys come from a caller is written as
1023 # #SegmentKeyed. A field's name is written into the key that
1024 # names its line, so a name holding the dot that separates
1025 # segments, the space that separates key from value, or
1026 # anything a line cannot carry is a statement with no written
1027 # form. It fails vet rather than reaching a signer.
1028 cue vet -d '#SegmentKeyed' ${./schema/attestation.cue} ${
1029 pkgs.writeText "segment-keys.json" ''
1030 {"harness": "a harness", "run-id": "1", "z9": "the last shape a segment takes"}
1031 ''
1032 }
1033 ${lib.concatStrings (
1034 lib.mapAttrsToList (name: key: ''
1035 if cue vet -d '#SegmentKeyed' ${./schema/attestation.cue} ${
1036 pkgs.writeText "${name}.json" ''
1037 {"harness": "a harness", ${builtins.toJSON key}: "a key with no written form"}
1038 ''
1039 } > ${name}.err 2>&1; then
1040 echo "attest-schema: expected the key '${key}' to be rejected" >&2
1041 exit 1
1042 fi
1043 grep -q 'field not allowed' ${name}.err
1044 '') {
1045 non-ascii-key = "café";
1046 dotted-key = "a.b";
1047 spaced-key = "a b";
1048 index-shaped-key = "0";
1049 }
1050 )}
1051
1052 # A rejection that does not name the field leaves the reader
1053 # to find the breakage themselves.
1054 grep -q 'signature: conflicting values' signature-in-statement.err
1055 grep -q 'subject.digest."valley-tree-v1"' no-content-addressed-subject.err
1056 grep -q 'predicate.environment: field not allowed' effectful-claiming-pure.err
1057 grep -q 'predicate.check.command' command-over-two-lines.err
1058 touch $out
1059 '';
1060
1061 # The written form and the note envelope, held to fixed vectors.
1062 # These bytes are an interop contract rather than an
1063 # implementation detail: a regenerated or independently written
1064 # attest must produce them identically or every signature already
1065 # made stops verifying. So the vectors are checked-in files with a
1066 # README saying they are the contract (attest/conformance/), and
1067 # this check is what holds a second implementation to them.
1068 attest-conformance =
1069 pkgs.runCommand "valley-attest-conformance"
1070 {
1071 nativeBuildInputs = [
1072 pkgs.cue
1073 (attestFor pkgs)
1074 ];
1075 }
1076 ''
1077 vectors=${./attest/conformance}
1078
1079 # One vector written out and compared, quietly, so the
1080 # perturbed run at the end can expect it to fail without
1081 # saying so.
1082 writes() { attest render "$1/input.json" | cmp -s - "$1/statement.txt"; }
1083
1084 found=0
1085 signed=0
1086 for dir in "$vectors"/vectors/*/; do
1087 name="$(basename "$dir")"
1088 found=$((found + 1))
1089
1090 if ! writes "$dir"; then
1091 echo "attest-conformance: $name is not written as its recorded bytes" >&2
1092 diff -u "$dir/statement.txt" <(attest render "$dir/input.json") >&2 || true
1093 exit 1
1094 fi
1095
1096 # The written form is a fixed point, or a statement written
1097 # out again anywhere downstream stops matching what was
1098 # signed.
1099 if ! attest render "$dir/statement.txt" | cmp -s - "$dir/statement.txt"; then
1100 echo "attest-conformance: $name is not a fixed point of the written form" >&2
1101 exit 1
1102 fi
1103
1104 # Every vector is a whole statement — order is defined per
1105 # predicate type, so a fragment has no written form — and is
1106 # held to the schema too, so the set cannot drift into
1107 # documents no verifier would accept.
1108 cue vet -c ${./schema/attestation.cue} "$dir/input.json"
1109
1110 # The signed vector pins the whole path from a statement to
1111 # a note something else can check, not just the written
1112 # form. No --repo: the subject tree is not what this check
1113 # is about.
1114 if [ -e "$dir/statement.note" ]; then
1115 signed=$((signed + 1))
1116 attest verify --note "$dir/statement.note" \
1117 --known-keys "$vectors/known_keys" > "$name.verify"
1118 grep -q '^signature ok' "$name.verify"
1119 grep -q '^text ok' "$name.verify"
1120
1121 # The text a verifier reads back is the text on disk: a
1122 # note is its statement, and reading one gives the other.
1123 sed '/^$/q' "$dir/statement.note" | sed '$d' | cmp - "$dir/statement.txt"
1124 fi
1125 done
1126
1127 # Two signers over one statement is the property the note
1128 # format is here for, so the set must actually hold one.
1129 siblings="$(grep -c '^— ' "$vectors"/vectors/04-two-signers/statement.note)"
1130 if [ "$siblings" -ne 2 ]; then
1131 echo "attest-conformance: the two-signer vector carries $siblings signatures" >&2
1132 exit 1
1133 fi
1134 attest verify --note "$vectors"/vectors/04-two-signers/statement.note \
1135 --known-keys "$vectors/known_keys" \
1136 --signer conformance.the-valley.invalid/attestations \
1137 --signer witness.the-valley.invalid/attestations > siblings.verify
1138 if [ "$(grep -c '^signature ok' siblings.verify)" -ne 2 ]; then
1139 echo "attest-conformance: both sibling signatures must verify" >&2
1140 cat siblings.verify >&2
1141 exit 1
1142 fi
1143
1144 if [ "$found" -lt 4 ] || [ "$signed" -lt 2 ]; then
1145 echo "attest-conformance: $found vectors, $signed signed — the set has been emptied" >&2
1146 exit 1
1147 fi
1148
1149 # The other half of the contract: what must not be written or
1150 # read at all. A document with no written form, and text that
1151 # is not the written form of anything.
1152 refused=0
1153 for file in "$vectors"/refused/*; do
1154 refused=$((refused + 1))
1155 if attest render "$file" > /dev/null 2> "$(basename "$file").err"; then
1156 echo "attest-conformance: $(basename "$file") was accepted" >&2
1157 exit 1
1158 fi
1159 done
1160 if [ "$refused" -lt 30 ]; then
1161 echo "attest-conformance: only $refused refusals — the set has been emptied" >&2
1162 exit 1
1163 fi
1164
1165 # The comparison must be able to fail. One recorded byte
1166 # sequence with a single value changed is what a divergent
1167 # implementation looks like, and it must not pass.
1168 mkdir -p perturbed
1169 cp "$vectors/vectors/01-statement-minimal/input.json" perturbed/
1170 sed 's/^predicate.result passed$/predicate.result failed/' \
1171 "$vectors/vectors/01-statement-minimal/statement.txt" > perturbed/statement.txt
1172 cmp -s perturbed/statement.txt "$vectors/vectors/01-statement-minimal/statement.txt" \
1173 && { echo "attest-conformance: the perturbation changed nothing" >&2; exit 1; }
1174 if writes perturbed; then
1175 echo "attest-conformance: a perturbed vector passed; the comparison proves nothing" >&2
1176 exit 1
1177 fi
1178
1179 # And so must the signature check. One byte of the signed
1180 # text changed is a signature that no longer covers it.
1181 sed 's/a sealed environment/a sealed environmenT/' \
1182 "$vectors"/vectors/04-two-signers/statement.note > perturbed/statement.note
1183 if attest verify --note perturbed/statement.note \
1184 --known-keys "$vectors/known_keys" > perturbed.verify 2>&1; then
1185 echo "attest-conformance: a note whose text was edited still verified" >&2
1186 exit 1
1187 fi
1188 grep -q 'does not check out over this text' perturbed.verify
1189
1190 echo "attest-conformance: $found vectors written byte for byte, $signed signed, $refused refused"
1191 touch $out
1192 '';
1193
1194 # The helper itself, driven end to end over scratch repositories
1195 # and a throwaway key: what it publishes, what it refuses to
1196 # publish, and what a verifier makes of both.
1197 #
1198 # Every check here uses the command runner. The nix runner cannot
1199 # be exercised from inside a nix build — there is no daemon in the
1200 # sandbox — so what a pure statement looks like is pinned by
1201 # attest-schema above and by the unit tests over the digest
1202 # scheme, and the runner itself is exercised by running the helper
1203 # outside the sandbox.
1204 attest-e2e =
1205 pkgs.runCommand "valley-attest-e2e"
1206 {
1207 nativeBuildInputs = [
1208 pkgs.git
1209 pkgs.openssh
1210 (attestFor pkgs)
1211 ];
1212 }
1213 ''
1214 export HOME="$TMPDIR"
1215 export GIT_CONFIG_NOSYSTEM=1
1216 git config --global user.name valley-check
1217 git config --global user.email valley-check@localhost
1218 git config --global init.defaultBranch main
1219
1220 # Throwaway keys in a scratch directory. The signer is a
1221 # parameter: provisioning a host identity is deployment, and
1222 # nothing here reads or writes anything under a real ~/.ssh.
1223 # A verifier is given key names and hashes, so what it holds
1224 # is what `attest key` prints and nothing more.
1225 ssh-keygen -q -t ed25519 -N "" -C valley-check -f "$TMPDIR/host"
1226 ssh-keygen -q -t ed25519 -N "" -C witness -f "$TMPDIR/witness"
1227 ssh-keygen -q -t ed25519 -N "" -C stranger -f "$TMPDIR/stranger"
1228 host=host.valley.invalid/attestations
1229 witness=witness.valley.invalid/attestations
1230 stranger=stranger.elsewhere.invalid/attestations
1231 attest key --key "$TMPDIR/host" --name "$host" > "$TMPDIR/known_keys"
1232 attest key --key "$TMPDIR/witness" --name "$witness" >> "$TMPDIR/known_keys"
1233 attest key --key "$TMPDIR/stranger" --name "$stranger" > "$TMPDIR/other_keys"
1234 grep -q "^$host+[0-9a-f]\{8\}+A" "$TMPDIR/known_keys"
1235
1236 # A key behind a passphrase is refused rather than prompted
1237 # for: attest runs unattended.
1238 ssh-keygen -q -t ed25519 -N "a passphrase" -C locked -f "$TMPDIR/locked"
1239 if attest key --key "$TMPDIR/locked" --name "$host" 2> locked.err; then
1240 echo "attest-e2e: an encrypted key must be refused" >&2
1241 exit 1
1242 fi
1243 grep -q 'cannot ask for a passphrase' locked.err
1244
1245 repo="$TMPDIR/tree"
1246 git init --quiet "$repo"
1247 cd "$repo"
1248 echo hello > hello.txt
1249 mkdir -p sub
1250 echo nested > sub/nested.txt
1251 ln -s hello.txt link
1252 printf '#!/bin/sh\ntrue\n' > run.sh
1253 chmod 755 run.sh
1254 git add -A
1255 git commit --quiet -m base
1256
1257 digest="$(attest digest | sed 's/^valley-tree-v1://')"
1258 case "$digest" in
1259 [0-9a-f][0-9a-f]*) ;;
1260 *) echo "attest-e2e: no tree digest: $digest" >&2; exit 1 ;;
1261 esac
1262
1263 refs() { git for-each-ref --format='%(refname)' refs/the-valley; }
1264 nothing_published() {
1265 if [ -n "$(refs)" ]; then
1266 echo "attest-e2e: $1" >&2
1267 git for-each-ref refs/the-valley >&2
1268 exit 1
1269 fi
1270 }
1271
1272 # Without a key, nothing is emitted — an unsigned statement
1273 # is not an attestation.
1274 if attest run --command 'ok=true' 2> nokey.err; then
1275 echo "attest-e2e: a run with no signing key must fail" >&2
1276 exit 1
1277 fi
1278 grep -q 'no signing key' nokey.err
1279 nothing_published "a run with no signing key stored a ref"
1280
1281 # A failing check publishes nothing, and says which check.
1282 if attest run --key "$TMPDIR/host" --name "$host" \
1283 --command 'ok=true' --command 'nope=false' > failing.out 2> failing.err; then
1284 echo "attest-e2e: a failing check must fail the run" >&2
1285 exit 1
1286 fi
1287 grep -qE '^check nope +command failed$' failing.out
1288 grep -q 'nothing published' failing.err
1289 nothing_published "a failing check left a ref behind"
1290
1291 # A statement the schema rejects is stopped before it is
1292 # signed or stored. Provenance is the caller's, so a
1293 # malformed one is how a malformed statement gets composed
1294 # at all.
1295 echo '{"harness":"valley-check","authority":"root"}' > bad-provenance.json
1296 if attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1297 --provenance bad-provenance.json > malformed.out 2> malformed.err; then
1298 echo "attest-e2e: a malformed statement must fail the run" >&2
1299 exit 1
1300 fi
1301 grep -q 'provenance.authority: field not allowed' malformed.err
1302 grep -q 'nothing published' malformed.err
1303 nothing_published "a malformed statement left a ref behind"
1304
1305 # A statement the schema admits but no line can carry is
1306 # stopped too, at the same point and for the same reason.
1307 printf '{"harness":"valley\\ncheck"}\n' > unwritable-provenance.json
1308 if attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1309 --provenance unwritable-provenance.json > unwritable.out 2> unwritable.err; then
1310 echo "attest-e2e: a statement with no written form must fail the run" >&2
1311 exit 1
1312 fi
1313 grep -q 'nothing published' unwritable.err
1314 nothing_published "a statement with no written form left a ref behind"
1315
1316 # The successful run.
1317 echo '{"harness":"valley-check","model":"none","delegation":[{"principal":"human:integrator","grant":"land changes"}]}' > provenance.json
1318 attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1319 --provenance provenance.json > run.out
1320 grep -q "^subject valley-tree-v1:$digest\$" run.out
1321 grep -q '^check ok *command passed$' run.out
1322 grep -q "^signer $host+" run.out
1323
1324 # Stored at a ref keyed by the subject digest, as one note
1325 # rather than a statement and a signature beside it.
1326 ref="$(refs)"
1327 case "$ref" in
1328 refs/the-valley/attestations/"$digest"/*) ;;
1329 *) echo "attest-e2e: ref $ref is not keyed by the subject digest" >&2; exit 1 ;;
1330 esac
1331 git cat-file -p "$ref:ok/statement.note" > statement.note
1332 head -n 1 statement.note | grep -qx 'the-valley/attestation/v1'
1333 grep -qx "subject.digest.valley-tree-v1 $digest" statement.note
1334 grep -qx 'provenance.harness valley-check' statement.note
1335 grep -q "^— $host " statement.note
1336
1337 # No git object is signed: the signature is over the
1338 # statement's text and nothing else.
1339 if git cat-file commit HEAD | grep -q '^gpgsig'; then
1340 echo "attest-e2e: attest signed a git object" >&2
1341 exit 1
1342 fi
1343
1344 verify() {
1345 attest verify --note "$1" --known-keys "$2" --repo "$repo"
1346 }
1347
1348 verify statement.note "$TMPDIR/known_keys" > verify.out
1349 grep -q "^signature ok $host+" verify.out
1350 grep -q 'matches the recorded subject digest' verify.out
1351
1352 # One atomic native-git push carries the branch and the
1353 # attestation ref together.
1354 git init --quiet --bare "$TMPDIR/host.git"
1355 git remote add valley "$TMPDIR/host.git"
1356 attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1357 --push valley > push.out
1358 grep -q -- '--atomic' push.out
1359 git -C "$TMPDIR/host.git" for-each-ref --format='%(refname)' > published.txt
1360 grep -qx 'refs/heads/main' published.txt
1361 grep -qx "$ref" published.txt
1362
1363 # A second party attests to the same statement, and its
1364 # signature lands beside the first under the text both cover.
1365 # This is what the note format is here for.
1366 attest sign --key "$TMPDIR/witness" --name "$witness" statement.note \
1367 > countersigned.note
1368 if [ "$(grep -c '^— ' countersigned.note)" -ne 2 ]; then
1369 echo "attest-e2e: countersigning did not add a sibling signature line" >&2
1370 cat countersigned.note >&2
1371 exit 1
1372 fi
1373 sed '/^$/q' countersigned.note | sed '$d' | cmp - <(sed '/^$/q' statement.note | sed '$d')
1374 attest verify --note countersigned.note --known-keys "$TMPDIR/known_keys" \
1375 --repo "$repo" --signer "$host" --signer "$witness" > countersigned.out
1376 if [ "$(grep -c '^signature ok' countersigned.out)" -ne 2 ]; then
1377 echo "attest-e2e: both signatures over one statement must verify" >&2
1378 cat countersigned.out >&2
1379 exit 1
1380 fi
1381
1382 # A verifier that does not hold the witness's key still
1383 # accepts the note, and says which signature it cannot speak
1384 # to. Requiring that signer is how it refuses instead.
1385 attest key --key "$TMPDIR/host" --name "$host" > "$TMPDIR/host_only"
1386 attest verify --note countersigned.note --known-keys "$TMPDIR/host_only" \
1387 --repo "$repo" > partial.out
1388 grep -q "^signature ok $host+" partial.out
1389 grep -q "^signature unknown $witness+" partial.out
1390 if attest verify --note countersigned.note --known-keys "$TMPDIR/host_only" \
1391 --repo "$repo" --signer "$witness" > required.out 2>&1; then
1392 echo "attest-e2e: a required signer with no verified signature must fail" >&2
1393 exit 1
1394 fi
1395 grep -q "no signature on this note is by $witness" required.out
1396
1397 # A note signed by a key the verifier does not hold is not a
1398 # bad signature — it is not a signer.
1399 if verify statement.note "$TMPDIR/other_keys" > stranger.out 2>&1; then
1400 echo "attest-e2e: a note signed by nobody we hold a key for must not verify" >&2
1401 exit 1
1402 fi
1403 grep -q 'no signature on this note is by a key the verifier holds' stranger.out
1404
1405 # Tampering with the signed bytes: one byte of the text the
1406 # signature covers.
1407 sed "s/$digest/00000000000000000000000000000000000000000000000000000000000000ff/" \
1408 statement.note > tampered.note
1409 if verify tampered.note "$TMPDIR/known_keys" > tampered.out 2>&1; then
1410 echo "attest-e2e: a tampered statement must not verify" >&2
1411 exit 1
1412 fi
1413 grep -q 'does not check out over this text' tampered.out
1414
1415 # A signature cannot be lifted onto a statement it was not
1416 # made about: it sits under the text it covers, so moving it
1417 # means moving that text with it.
1418 sed '/^$/q' statement.note | sed '$d' > lifted.txt
1419 sed 's/^provenance.harness .*/provenance.harness somebody-else/' lifted.txt > lifted.body
1420 sed -n '/^$/,$p' statement.note | tail -n +2 > lifted.sigs
1421 { cat lifted.body; echo; cat lifted.sigs; } > lifted.note
1422 if verify lifted.note "$TMPDIR/known_keys" > lifted.out 2>&1; then
1423 echo "attest-e2e: a signature was lifted onto another statement" >&2
1424 exit 1
1425 fi
1426 grep -q 'does not check out over this text' lifted.out
1427
1428 # A statement written some other way than the one written
1429 # form, signed properly over those bytes. The signature is
1430 # good and the statement is still refused: it would verify
1431 # here and fail wherever it was written out again, so the
1432 # form is a rule rather than a convention.
1433 { head -n 1 lifted.txt; tail -n +2 lifted.txt | sort -r; } > loose.txt
1434 cmp -s loose.txt lifted.txt \
1435 && { echo "attest-e2e: the reordering changed nothing" >&2; exit 1; }
1436 attest sign --key "$TMPDIR/host" --name "$host" loose.txt > loose.note
1437 if verify loose.note "$TMPDIR/known_keys" > loose.out 2>&1; then
1438 echo "attest-e2e: a statement not in the written form must not verify" >&2
1439 exit 1
1440 fi
1441 grep -q 'not the written form of what it says' loose.out
1442
1443 # The subject is the tree. Change the tree and the same
1444 # signed statement stops being about it …
1445 echo goodbye > hello.txt
1446 git commit --quiet -am "change the tree"
1447 if verify statement.note "$TMPDIR/known_keys" > moved.out 2>&1; then
1448 echo "attest-e2e: a statement about another tree must not verify" >&2
1449 exit 1
1450 fi
1451 grep -q 'tree digest mismatch' moved.out
1452
1453 # … while rewriting the commit over the same tree leaves the
1454 # attestation standing, which is what a subject that is a
1455 # tree digest buys.
1456 git commit --quiet --amend -m "same tree, new commit"
1457 rewritten="$(attest digest | sed 's/^valley-tree-v1://')"
1458 git revert --quiet --no-edit HEAD
1459 restored="$(attest digest | sed 's/^valley-tree-v1://')"
1460 if [ "$restored" != "$digest" ]; then
1461 echo "attest-e2e: restoring the tree did not restore its digest" >&2
1462 echo " original $digest" >&2
1463 echo " restored $restored" >&2
1464 exit 1
1465 fi
1466 if [ "$rewritten" = "$digest" ]; then
1467 echo "attest-e2e: a changed tree kept its digest" >&2
1468 exit 1
1469 fi
1470 verify statement.note "$TMPDIR/known_keys" > rebased.out
1471 grep -q 'matches the recorded subject digest' rebased.out
1472 touch $out
1473 '';
1474
1475 # The integrator's verdict, case by case, with no repository in
1476 # sight. Every rule of dcr-439b771 is a function of data, so the
1477 # unit tests state each one directly; what a repository does to
1478 # produce those inputs is integrator-e2e's.
1479 integrator-unit = integratorUnwrappedFor pkgs;
1480
1481 # The integrator itself, driven end to end over scratch bare
1482 # repositories and throwaway keys, running the real binaries: the
1483 # helper produces the evidence, the deriver composes the policy,
1484 # the controller judges and lands. The scenarios are Phase 3's
1485 # exit criteria, observed rather than asserted about.
1486 #
1487 # Only the nix evaluator is stood in for — a nix build has no
1488 # daemon in the sandbox, the same wall attest-e2e meets — and the
1489 # stand-in models the one property the pure rule rests on: a
1490 # check's input closure is the content of the files it reads.
1491 # Everything downstream of it is real: attest builds the manifest
1492 # and the digest, and the integrator compares them.
1493 integrator-e2e =
1494 pkgs.runCommand "valley-integrator-e2e"
1495 {
1496 nativeBuildInputs = [
1497 pkgs.bash
1498 pkgs.git
1499 pkgs.openssh
1500 pkgs.coreutils
1501 pkgs.findutils
1502 pkgs.gnused
1503 pkgs.gnugrep
1504 pkgs.cue
1505 (attestFor pkgs)
1506 (valleyScriptFor pkgs)
1507 (integratorFor pkgs)
1508 ];
1509 SCHEMA_ATTESTATION = ./schema/attestation.cue;
1510 SCHEMA_VERIFICATION = ./schema/verification.cue;
1511 SCHEMA_EVENTS = ./schema/events.cue;
1512 # No bus in a sandbox: the payloads are still composed and
1513 # vetted against the vocabulary, and printed rather than
1514 # published. What publishing does is the post-receive hook's
1515 # one `nats pub`, which this shares.
1516 }
1517 ''
1518 cp -r ${./integrator/e2e} e2e
1519 chmod -R +w e2e
1520 # The stand-ins go on PATH and are executed by name, so
1521 # their /usr/bin/env shebangs have to resolve in a sandbox
1522 # that has no /usr/bin.
1523 patchShebangs e2e
1524 bash e2e/run.sh 2>&1 | tee log
1525 grep -q 'every scenario held' log
1526 cp log $out
1527 '';
1528
1529 # The verification-policy deriver (dcr-f41f718). Composing the two
1530 # layers is CUE's job and is pinned by cue-vet above; matching
1531 # paths is the script's own, and a path matcher is wrong exactly at
1532 # the glob boundaries — `*` inside one segment against `**` across
1533 # segments, `**` matching no segment at all — and at the sides of a
1534 # diff a naive reader drops: a rename's old path and a deletion.
1535 # Each is pinned by driving the real script over a scratch
1536 # repository and a scratch policy, never by reading the code.
1537 policy-deriver =
1538 let
1539 # A floor whose classes are one glob boundary each, and whose
1540 # check names say which class matched.
1541 deriverFloor = pkgs.writeText "deriver-floor.cue" ''
1542 package verification
1543 floor: {
1544 checks: {
1545 "c-docs": {runner: "nix", attribute: "c-docs"}
1546 "c-notes": {runner: "nix", attribute: "c-notes"}
1547 "c-flat": {runner: "nix", attribute: "c-flat"}
1548 "c-deep": {runner: "nix", attribute: "c-deep"}
1549 "c-nested": {runner: "nix", attribute: "c-nested"}
1550 "c-uncovered": {runner: "nix", attribute: "c-uncovered"}
1551 }
1552 classes: {
1553 docs: {paths: "docs/**": true, requires: "c-docs": true}
1554 notes: {paths: "notes/**": true, requires: "c-notes": true}
1555 flat: {paths: "src/*.rs": true, requires: "c-flat": true}
1556 deep: {paths: "src/**/*.rs": true, requires: "c-deep": true}
1557 nested: {paths: "a/**/b": true, requires: "c-nested": true}
1558 }
1559 unclassified: "c-uncovered": true
1560 }
1561 '';
1562 # One requirement that is a template default rather than a
1563 # rule, so the two forms are told apart on real output.
1564 deriverTemplate = pkgs.writeText "deriver-template.cue" ''
1565 package verification
1566 #tmpl: #Policy & {
1567 checks: "c-tmpl": {runner: "nix", attribute: "c-tmpl"}
1568 classes: docs: requires: "c-tmpl": bool | *true
1569 }
1570 '';
1571 deriverProject = pkgs.writeText "deriver-project.cue" ''
1572 package verification
1573 project: {
1574 #tmpl
1575 }
1576 '';
1577 in
1578 pkgs.runCommand "valley-policy-deriver"
1579 {
1580 nativeBuildInputs = [
1581 pkgs.git
1582 pkgs.cue
1583 (valleyScriptFor pkgs)
1584 ];
1585 }
1586 ''
1587 export HOME="$TMPDIR"
1588 export GIT_CONFIG_NOSYSTEM=1
1589 git config --global user.name valley-check
1590 git config --global user.email valley-check@localhost
1591 git config --global init.defaultBranch main
1592
1593 policy="$TMPDIR/policy"
1594 mkdir -p "$policy/instance" "$policy/project"
1595 cp ${deriverFloor} "$policy/instance/floor.cue"
1596 cp ${deriverTemplate} "$policy/instance/template.cue"
1597 cp ${deriverProject} "$policy/project/policy.cue"
1598
1599 repo="$TMPDIR/tree"
1600 git init --quiet "$repo"
1601 cd "$repo"
1602 mkdir -p docs notes src/deep a/x/y
1603 echo moved > docs/moved.md
1604 for f in docs/kept.md docs/gone.md src/one.rs src/deep/two.rs \
1605 a/b a/x/y/b Makefile; do
1606 echo seed > "$f"
1607 done
1608 git add -A
1609 git commit --quiet -m base
1610 base="$(git rev-parse HEAD)"
1611
1612 derive() {
1613 valley checks --schema ${./schema/verification.cue} \
1614 --instance "$policy/instance" --project "$policy/project" \
1615 "$base" HEAD
1616 }
1617
1618 # The check names in the deriver's table, sorted, on one line.
1619 named() {
1620 awk '/^required checks:$/ {f = 1; next}
1621 /^$/ {f = 0}
1622 f && /^ / {print $1}' <<<"$report" | sort | paste -sd' ' -
1623 }
1624
1625 # Start a case from the base tree; assert its check table.
1626 case_start() { git checkout --quiet -B "$1" "$base"; }
1627 expect() {
1628 local got
1629 got="$(named)"
1630 if [ "$got" != "$1" ]; then
1631 echo "policy-deriver: $2" >&2
1632 echo " expected: $1" >&2
1633 echo " got: $got" >&2
1634 echo "$report" >&2
1635 exit 1
1636 fi
1637 }
1638
1639 # `**` crosses segments, `*` does not. One file under src/
1640 # matches both patterns; one a segment deeper matches only
1641 # the `**` one.
1642 case_start flat
1643 echo edit > src/one.rs
1644 git commit --quiet -am flat
1645 report="$(derive)"
1646 expect "c-deep c-flat" "src/*.rs must match a file directly under src/"
1647
1648 case_start deep
1649 echo edit > src/deep/two.rs
1650 git commit --quiet -am deep
1651 report="$(derive)"
1652 expect "c-deep" "src/*.rs must not match across a path separator"
1653
1654 # A `**` between two segments matches no segment at all …
1655 case_start nested-none
1656 echo edit > a/b
1657 git commit --quiet -am nested-none
1658 report="$(derive)"
1659 expect "c-nested" "a/**/b must match a/b"
1660
1661 # … and any number of them.
1662 case_start nested-many
1663 echo edit > a/x/y/b
1664 git commit --quiet -am nested-many
1665 report="$(derive)"
1666 expect "c-nested" "a/**/b must match a/x/y/b"
1667
1668 # A rename counts on both sides: the class covering the old
1669 # path is required as much as the one covering the new.
1670 case_start renamed
1671 git mv docs/moved.md notes/moved.md
1672 git commit --quiet -m renamed
1673 git diff --name-status -M "$base" HEAD | grep -q '^R' \
1674 || { echo "policy-deriver: the rename case is not a rename" >&2; exit 1; }
1675 report="$(derive)"
1676 expect "c-docs c-notes c-tmpl" "a rename must count on both sides"
1677
1678 # A deleted path is still a changed path.
1679 case_start deleted
1680 git rm --quiet docs/gone.md
1681 git commit --quiet -m deleted
1682 report="$(derive)"
1683 expect "c-docs c-tmpl" "a deletion must count"
1684
1685 # The form of the value is the mandatory bit: the floor's
1686 # concrete `true` against the template's `bool | *true`.
1687 grep -qE '^ c-docs +mandatory +docs$' <<<"$report"
1688 grep -qE '^ c-tmpl +default +docs$' <<<"$report"
1689
1690 # A path no class covers takes the unclassified set, and says
1691 # so by name.
1692 case_start uncovered
1693 echo edit > Makefile
1694 git commit --quiet -am uncovered
1695 report="$(derive)"
1696 expect "c-uncovered" "an uncovered path must take the unclassified set"
1697 grep -q '^classes matched: unclassified$' <<<"$report"
1698 grep -q '^unclassified: 1 path(s) matched no class$' <<<"$report"
1699 grep -q '^ Makefile$' <<<"$report"
1700
1701 touch $out
1702 '';
1703
1704 module-eval =
1705 if failedAssertions != [ ] then
1706 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
1707 else if resticRenderedWithoutDeclaration then
1708 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
1709 else if busRenderedWithoutEnable then
1710 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
1711 else if
1712 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
1713 then
1714 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
1715 else
1716 pkgs.runCommand "valley-module-eval"
1717 {
1718 initScript = host.config.systemd.services.valley-init.script;
1719 sshdConfig = host.config.services.openssh.extraConfig;
1720 resticService = host.config.systemd.units."restic-backups-valley.service".text;
1721 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
1722 passAsFile = [
1723 "initScript"
1724 "sshdConfig"
1725 "resticService"
1726 "resticTimer"
1727 ];
1728 }
1729 ''
1730 # The repo init list and mirror hook must be generated from
1731 # the CUE export, and the git user's sshd Match block must
1732 # be terminated so it cannot scope later config.
1733 grep -q "the-valley" "$initScriptPath"
1734 grep -q "valley-mirrors" "$initScriptPath"
1735 grep -q "Match All" "$sshdConfigPath"
1736
1737 # The mirror publishes main and tags only — a heads glob
1738 # would publish every topic branch awaiting review — with
1739 # --prune for tag deletions and a sweep that unpublishes
1740 # any other head (--prune cannot: it ignores non-glob
1741 # refspecs). Never --mirror: it also deletes remote-only
1742 # refs, and GitHub's read-only refs/pull/* fails every such
1743 # push. Follow the hook chain from the init script to the
1744 # rendered push script and pin the invocation there.
1745 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
1746 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
1747 grep -q -- 'push --prune' "$mirrorPush"
1748 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
1749 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
1750 grep -qF -- 'ls-remote --heads' "$mirrorPush"
1751 grep -qF -- 'push "$url" --delete' "$mirrorPush"
1752 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
1753 echo "module-eval: mirror push regressed to publishing every head" >&2
1754 exit 1
1755 fi
1756 if grep -q -- '--mirror' "$mirrorPush"; then
1757 echo "module-eval: mirror push regressed to --mirror" >&2
1758 exit 1
1759 fi
1760 # Deletions must never reach a namespace the mirror owns.
1761 if grep -q 'refs/pull' "$mirrorPush"; then
1762 echo "module-eval: mirror push must not name refs/pull/*" >&2
1763 exit 1
1764 fi
1765
1766 # The rendered restic units must back up the data directory
1767 # to the consumer-supplied repository with the declared
1768 # retention over a pinned host key, on the declared cadence.
1769 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
1770 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
1771 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
1772 grep -q "BatchMode=yes" "$resticServicePath"
1773 grep -q "OnCalendar=03:30" "$resticTimerPath"
1774
1775 # The backup paths render as a --files-from list: follow
1776 # ExecStartPre to that list and pin the data directory.
1777 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
1778 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
1779 grep -qx "/srv/git" "$staticPaths"
1780 touch $out
1781 '';
1782
1783 # What a mirror ends up holding, end to end and unmocked: a bare
1784 # repo wired with the real rendered hooks, pushed to for real, and
1785 # a second bare repo standing in for the mirror. The refspec is
1786 # easy to get subtly wrong — --prune ignores the non-glob heads
1787 # refspec, so pruning heads is the sweep's job — and only running
1788 # git can tell. Relative mirror URLs (mirrorHost) resolve against
1789 # the pushing repo, so the shipped scripts run with no
1790 # substitution: this is exactly what a host executes.
1791 mirror-e2e =
1792 pkgs.runCommand "valley-mirror-e2e"
1793 {
1794 nativeBuildInputs = [ pkgs.git ];
1795 initScript = mirrorHost.config.systemd.services.valley-init.script;
1796 passAsFile = [ "initScript" ];
1797 }
1798 ''
1799 export HOME="$TMPDIR"
1800 export GIT_CONFIG_NOSYSTEM=1
1801 git config --global user.name valley-check
1802 git config --global user.email valley-check@localhost
1803 git config --global init.defaultBranch main
1804 cd "$TMPDIR"
1805
1806 wait_for() {
1807 for _ in $(seq 1 150); do
1808 "$@" >/dev/null 2>&1 && return 0
1809 sleep 0.2
1810 done
1811 echo "mirror-e2e: timed out waiting for: $*" >&2
1812 return 1
1813 }
1814 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
1815 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
1816 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
1817 only_main() { [ "$(heads)" = refs/heads/main ]; }
1818
1819 # A primary repo wired exactly as valley-init wires it, with
1820 # the real store paths followed from the rendered init script.
1821 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1822 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
1823 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
1824 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
1825 wire() {
1826 mkdir -p "$1/hooks/post-receive.d"
1827 ln -s "$dispatch" "$1/hooks/post-receive"
1828 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
1829 }
1830
1831 # The mirror as it stands today: every head and tag of the
1832 # primary, topic branches included. Seeded before the hook is
1833 # wired, so nothing sweeps it out from under the setup.
1834 git init --quiet --bare mirror-pilot.git
1835 git init --quiet --bare mirror.git
1836 git clone --quiet "$PWD/mirror-pilot.git" work
1837 git -C work commit --quiet --allow-empty -m one
1838 git -C work tag v1
1839 git -C work tag doomed
1840 for b in idea/one idea/two; do git -C work branch "$b"; done
1841 git -C work push --quiet origin \
1842 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1843 git -C mirror-pilot.git push --quiet ../mirror.git \
1844 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1845 [ "$(heads | wc -l)" -eq 3 ]
1846 wire mirror-pilot.git "$mhook"
1847
1848 # A real push to the primary — a topic branch alongside main,
1849 # and a tag deleted. The hook replicates asynchronously, so
1850 # wait on main's new tip before judging the rest.
1851 git -C work commit --quiet --allow-empty -m two
1852 git -C work tag -d doomed >/dev/null
1853 git -C work branch idea/three
1854 git -C work push --quiet --follow-tags origin main idea/three
1855 git -C work push --quiet --delete origin doomed
1856 tip="$(git -C work rev-parse HEAD)"
1857 wait_for mirror_main_is
1858
1859 # main and the tags are published; nothing else is, and the
1860 # topic branches that were on the mirror are gone. The sweep
1861 # is a second push, so it converges just after main lands.
1862 wait_for only_main
1863 [ "$(tags)" = refs/tags/v1 ]
1864
1865 # A branch that appears on the mirror by any other route is
1866 # unpublished on the next push.
1867 git -C mirror.git branch sneaky main
1868 git -C work commit --quiet --allow-empty -m three
1869 git -C work push --quiet origin main
1870 tip="$(git -C work rev-parse HEAD)"
1871 wait_for mirror_main_is
1872 wait_for only_main
1873
1874 # An unreachable mirror costs a log line, never the push: the
1875 # hook must return promptly and the push must succeed.
1876 git init --quiet --bare dead-mirror.git
1877 wire dead-mirror.git "$deadhook"
1878 git clone --quiet "$PWD/dead-mirror.git" deadwork
1879 git -C deadwork commit --quiet --allow-empty -m one
1880 timeout 60 git -C deadwork push --quiet origin main
1881 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
1882
1883 touch $out
1884 '';
1885
1886 # Phase 1's exit criteria, end to end and unmocked: a push to a
1887 # bare repo wired with the real rendered hooks produces a
1888 # ref-updated event on a real JetStream server within seconds,
1889 # visible in `valley tail`; replaying the repo's refs is
1890 # deterministic; and a dead bus never fails a push. The hook and
1891 # stream-init scripts are followed from the rendered unit scripts,
1892 # so the check exercises exactly what a host would run — only the
1893 # server invocation differs (the sandbox cannot write /srv), same
1894 # binary and flags, relocated storage.
1895 bus-e2e =
1896 pkgs.runCommand "valley-bus-e2e"
1897 {
1898 nativeBuildInputs = [
1899 pkgs.git
1900 pkgs.natscli
1901 pkgs.nats-server
1902 pkgs.jq
1903 pkgs.cue
1904 (valleyScriptFor pkgs)
1905 ];
1906 initScript = busHost.config.systemd.services.valley-init.script;
1907 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
1908 passAsFile = [
1909 "initScript"
1910 "busInitScript"
1911 ];
1912 }
1913 ''
1914 export HOME="$TMPDIR"
1915 export NATS_URL=nats://127.0.0.1:4222
1916 export GIT_CONFIG_NOSYSTEM=1
1917 git config --global user.name valley-check
1918 git config --global user.email valley-check@localhost
1919 git config --global init.defaultBranch main
1920
1921 wait_for() {
1922 for _ in $(seq 1 150); do
1923 "$@" >/dev/null 2>&1 && return 0
1924 sleep 0.2
1925 done
1926 echo "bus-e2e: timed out waiting for: $*" >&2
1927 return 1
1928 }
1929
1930 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
1931 --store_dir "$TMPDIR/js" &
1932 server_pid=$!
1933
1934 # The real stream-init script the module renders.
1935 bash -eu "$busInitScriptPath"
1936 nats stream info valley >/dev/null
1937
1938 # A bare repo wired exactly as valley-init wires it, with the
1939 # real store paths followed from the rendered init script.
1940 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1941 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
1942 test -x "$dispatch"
1943 test -x "$bushook"
1944 repo="$TMPDIR/events-pilot.git"
1945 git init --quiet --bare "$repo"
1946 mkdir -p "$repo/hooks/post-receive.d"
1947 ln -s "$dispatch" "$repo/hooks/post-receive"
1948 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
1949
1950 git clone --quiet "$repo" "$TMPDIR/work"
1951 cd "$TMPDIR/work"
1952 echo one > file
1953 git add file
1954 git commit --quiet -m one
1955 git push --quiet origin main
1956 first="$(git rev-parse HEAD)"
1957 zeros="$(printf '%040d' 0)"
1958
1959 # Exit criterion 1: the event arrives within seconds, with a
1960 # payload that is exactly the git facts of the push …
1961 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
1962 wait_for msgs_is 1
1963 got="$(nats stream get valley 1 --json)"
1964 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
1965 payload="$(jq -r .data <<<"$got" | base64 -d)"
1966 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
1967 [ "$payload" = "$expected" ]
1968
1969 # … valid against the shipped event schema.
1970 echo "$payload" > "$TMPDIR/payload.json"
1971 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
1972
1973 # … and visible in `valley tail`. Subscribe first, then push.
1974 valley tail > "$TMPDIR/tail.out" 2>&1 &
1975 tail_pid=$!
1976 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
1977 wait_for subscribed
1978 echo two > file
1979 git commit --quiet -am two
1980 git push --quiet origin main
1981 second="$(git rev-parse HEAD)"
1982 wait_for msgs_is 2
1983 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
1984 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
1985 [ "$payload2" = "$expected2" ]
1986 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
1987 wait_for tail_saw
1988 kill "$tail_pid" 2>/dev/null || true
1989
1990 # Exit criterion 2: rebuilding the stream from the repo's
1991 # refs is deterministic — two replays from scratch produce
1992 # identical events, landing on the pushed tip with the
1993 # all-zero id as old.
1994 dump_stream() {
1995 local info first_seq last_seq i
1996 info="$(nats stream info valley --json)"
1997 first_seq="$(jq .state.first_seq <<<"$info")"
1998 last_seq="$(jq .state.last_seq <<<"$info")"
1999 for i in $(seq "$first_seq" "$last_seq"); do
2000 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
2001 done
2002 }
2003 nats stream purge valley --force >/dev/null
2004 valley replay "$repo"
2005 wait_for msgs_is 1
2006 run1="$(dump_stream)"
2007 nats stream purge valley --force >/dev/null
2008 valley replay "$repo"
2009 wait_for msgs_is 1
2010 run2="$(dump_stream)"
2011 [ "$run1" = "$run2" ]
2012 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
2013 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
2014
2015 # A dead bus never blocks a push: the event is simply lost
2016 # (and rebuildable by replay).
2017 kill "$server_pid"
2018 wait "$server_pid" || true
2019 echo three > file
2020 git commit --quiet -am three
2021 git push --quiet origin main
2022
2023 touch $out
2024 '';
2025 }
2026 );
2027 };
2028}