gunk-dev/the-valley

flake.nix

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