gunk-dev/the-valley

flake.nix

source7038f6b66cdcmain's published tip history
80.5 KiB
1{
2 description = "the-valley: the CUE domain schema for a valley host, and the NixOS module that installs one";
3
4 inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
5
6 outputs =
7 { self, nixpkgs }:
8 let
9 lib = nixpkgs.lib;
10 # Checks use import-from-derivation (the module's cue export), so they
11 # are only defined for the system that can actually build them here.
12 systems = [ "x86_64-linux" ];
13
14 # The integrator's CLI (bin/valley) wrapped for `nix run`. The script
15 # itself must keep running bare from any checkout — the package is the
16 # second of its two shipping modes, never a dependency of the first.
17 valleyScriptFor =
18 pkgs:
19 pkgs.writeShellApplication {
20 name = "valley";
21 runtimeInputs = [
22 pkgs.git
23 pkgs.natscli # tail and replay only; every other verb needs just git
24 pkgs.cue # checks only — it composes the policy layers
25 ];
26 text = builtins.readFile ./bin/valley;
27 };
28
29 # The installed package: the wrapped script plus the shell completions,
30 # at the standard paths home-manager/NixOS auto-link.
31 valleyCliFor =
32 pkgs:
33 pkgs.symlinkJoin {
34 name = "valley";
35 paths = [ (valleyScriptFor pkgs) ];
36 nativeBuildInputs = [ pkgs.installShellFiles ];
37 postBuild = ''
38 installShellCompletion --bash --name valley ${./completions/valley.bash}
39 installShellCompletion --zsh --name _valley ${./completions/_valley}
40 '';
41 };
42
43 # Markdown prose is filled paragraphs hard-wrapped at 100 columns
44 # (ida-1ec03b1). One prettier invocation backs both the formatter app
45 # and the prose-format check, so the two cannot drift.
46 # Embedded-language formatting is off so fenced code blocks pass
47 # through byte-for-byte.
48 proseFmtArgs = "--prose-wrap always --print-width 100 --embedded-language-formatting off";
49
50 # `nix run .#fmt` — rewrap every tracked *.md in the repo to 100 columns.
51 proseFmtFor =
52 pkgs:
53 pkgs.writeShellApplication {
54 name = "valley-fmt";
55 runtimeInputs = [
56 pkgs.git
57 pkgs.prettier
58 ];
59 text = ''
60 cd "$(git rev-parse --show-toplevel)"
61 git ls-files -z -- '*.md' | xargs -0 --no-run-if-empty \
62 prettier ${proseFmtArgs} --write
63 '';
64 };
65
66 # The Phase 2 attestation helper (dcr-0de694f). Go, standard library
67 # only, 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 # Every vector is a whole statement — order is defined per
894 # predicate type, so a fragment has no written form — and is
895 # held to the schema too, so the set cannot drift into
896 # documents no verifier would accept.
897 cue vet -c ${./schema/attestation.cue} "$dir/input.json"
898
899 # The signed vector pins the whole path from a statement to
900 # a note something else can check, not just the written
901 # form. No --repo: the subject tree is not what this check
902 # is about.
903 if [ -e "$dir/statement.note" ]; then
904 signed=$((signed + 1))
905 attest verify --note "$dir/statement.note" \
906 --known-keys "$vectors/known_keys" > "$name.verify"
907 grep -q '^signature ok' "$name.verify"
908 grep -q '^text ok' "$name.verify"
909
910 # The text a verifier reads back is the text on disk: a
911 # note is its statement, and reading one gives the other.
912 sed '/^$/q' "$dir/statement.note" | sed '$d' | cmp - "$dir/statement.txt"
913 fi
914 done
915
916 # Two signers over one statement is the property the note
917 # format is here for, so the set must actually hold one.
918 siblings="$(grep -c '^— ' "$vectors"/vectors/04-two-signers/statement.note)"
919 if [ "$siblings" -ne 2 ]; then
920 echo "attest-conformance: the two-signer vector carries $siblings signatures" >&2
921 exit 1
922 fi
923 attest verify --note "$vectors"/vectors/04-two-signers/statement.note \
924 --known-keys "$vectors/known_keys" \
925 --signer conformance.the-valley.invalid/attestations \
926 --signer witness.the-valley.invalid/attestations > siblings.verify
927 if [ "$(grep -c '^signature ok' siblings.verify)" -ne 2 ]; then
928 echo "attest-conformance: both sibling signatures must verify" >&2
929 cat siblings.verify >&2
930 exit 1
931 fi
932
933 if [ "$found" -lt 4 ] || [ "$signed" -lt 2 ]; then
934 echo "attest-conformance: $found vectors, $signed signed — the set has been emptied" >&2
935 exit 1
936 fi
937
938 # The other half of the contract: what must not be written or
939 # read at all. A document with no written form, and text that
940 # is not the written form of anything.
941 refused=0
942 for file in "$vectors"/refused/*; do
943 refused=$((refused + 1))
944 if attest render "$file" > /dev/null 2> "$(basename "$file").err"; then
945 echo "attest-conformance: $(basename "$file") was accepted" >&2
946 exit 1
947 fi
948 done
949 if [ "$refused" -lt 30 ]; then
950 echo "attest-conformance: only $refused refusals — the set has been emptied" >&2
951 exit 1
952 fi
953
954 # The comparison must be able to fail. One recorded byte
955 # sequence with a single value changed is what a divergent
956 # implementation looks like, and it must not pass.
957 mkdir -p perturbed
958 cp "$vectors/vectors/01-statement-minimal/input.json" perturbed/
959 sed 's/^predicate.result passed$/predicate.result failed/' \
960 "$vectors/vectors/01-statement-minimal/statement.txt" > perturbed/statement.txt
961 cmp -s perturbed/statement.txt "$vectors/vectors/01-statement-minimal/statement.txt" \
962 && { echo "attest-conformance: the perturbation changed nothing" >&2; exit 1; }
963 if writes perturbed; then
964 echo "attest-conformance: a perturbed vector passed; the comparison proves nothing" >&2
965 exit 1
966 fi
967
968 # And so must the signature check. One byte of the signed
969 # text changed is a signature that no longer covers it.
970 sed 's/a sealed environment/a sealed environmenT/' \
971 "$vectors"/vectors/04-two-signers/statement.note > perturbed/statement.note
972 if attest verify --note perturbed/statement.note \
973 --known-keys "$vectors/known_keys" > perturbed.verify 2>&1; then
974 echo "attest-conformance: a note whose text was edited still verified" >&2
975 exit 1
976 fi
977 grep -q 'does not check out over this text' perturbed.verify
978
979 echo "attest-conformance: $found vectors written byte for byte, $signed signed, $refused refused"
980 touch $out
981 '';
982
983 # The helper itself, driven end to end over scratch repositories
984 # and a throwaway key: what it publishes, what it refuses to
985 # publish, and what a verifier makes of both.
986 #
987 # Every check here uses the command runner. The nix runner cannot
988 # be exercised from inside a nix build — there is no daemon in the
989 # sandbox — so what a pure statement looks like is pinned by
990 # attest-schema above and by the unit tests over the digest
991 # scheme, and the runner itself is exercised by running the helper
992 # outside the sandbox.
993 attest-e2e =
994 pkgs.runCommand "valley-attest-e2e"
995 {
996 nativeBuildInputs = [
997 pkgs.git
998 pkgs.openssh
999 (attestFor pkgs)
1000 ];
1001 }
1002 ''
1003 export HOME="$TMPDIR"
1004 export GIT_CONFIG_NOSYSTEM=1
1005 git config --global user.name valley-check
1006 git config --global user.email valley-check@localhost
1007 git config --global init.defaultBranch main
1008
1009 # Throwaway keys in a scratch directory. The signer is a
1010 # parameter: provisioning a host identity is deployment, and
1011 # nothing here reads or writes anything under a real ~/.ssh.
1012 # A verifier is given key names and hashes, so what it holds
1013 # is what `attest key` prints and nothing more.
1014 ssh-keygen -q -t ed25519 -N "" -C valley-check -f "$TMPDIR/host"
1015 ssh-keygen -q -t ed25519 -N "" -C witness -f "$TMPDIR/witness"
1016 ssh-keygen -q -t ed25519 -N "" -C stranger -f "$TMPDIR/stranger"
1017 host=host.valley.invalid/attestations
1018 witness=witness.valley.invalid/attestations
1019 stranger=stranger.elsewhere.invalid/attestations
1020 attest key --key "$TMPDIR/host" --name "$host" > "$TMPDIR/known_keys"
1021 attest key --key "$TMPDIR/witness" --name "$witness" >> "$TMPDIR/known_keys"
1022 attest key --key "$TMPDIR/stranger" --name "$stranger" > "$TMPDIR/other_keys"
1023 grep -q "^$host+[0-9a-f]\{8\}+A" "$TMPDIR/known_keys"
1024
1025 # A key behind a passphrase is refused rather than prompted
1026 # for: attest runs unattended.
1027 ssh-keygen -q -t ed25519 -N "a passphrase" -C locked -f "$TMPDIR/locked"
1028 if attest key --key "$TMPDIR/locked" --name "$host" 2> locked.err; then
1029 echo "attest-e2e: an encrypted key must be refused" >&2
1030 exit 1
1031 fi
1032 grep -q 'cannot ask for a passphrase' locked.err
1033
1034 repo="$TMPDIR/tree"
1035 git init --quiet "$repo"
1036 cd "$repo"
1037 echo hello > hello.txt
1038 mkdir -p sub
1039 echo nested > sub/nested.txt
1040 ln -s hello.txt link
1041 printf '#!/bin/sh\ntrue\n' > run.sh
1042 chmod 755 run.sh
1043 git add -A
1044 git commit --quiet -m base
1045
1046 digest="$(attest digest | sed 's/^valley-tree-v1://')"
1047 case "$digest" in
1048 [0-9a-f][0-9a-f]*) ;;
1049 *) echo "attest-e2e: no tree digest: $digest" >&2; exit 1 ;;
1050 esac
1051
1052 refs() { git for-each-ref --format='%(refname)' refs/the-valley; }
1053 nothing_published() {
1054 if [ -n "$(refs)" ]; then
1055 echo "attest-e2e: $1" >&2
1056 git for-each-ref refs/the-valley >&2
1057 exit 1
1058 fi
1059 }
1060
1061 # Without a key, nothing is emitted — an unsigned statement
1062 # is not an attestation.
1063 if attest run --command 'ok=true' 2> nokey.err; then
1064 echo "attest-e2e: a run with no signing key must fail" >&2
1065 exit 1
1066 fi
1067 grep -q 'no signing key' nokey.err
1068 nothing_published "a run with no signing key stored a ref"
1069
1070 # A failing check publishes nothing, and says which check.
1071 if attest run --key "$TMPDIR/host" --name "$host" \
1072 --command 'ok=true' --command 'nope=false' > failing.out 2> failing.err; then
1073 echo "attest-e2e: a failing check must fail the run" >&2
1074 exit 1
1075 fi
1076 grep -qE '^check nope +command failed$' failing.out
1077 grep -q 'nothing published' failing.err
1078 nothing_published "a failing check left a ref behind"
1079
1080 # A statement the schema rejects is stopped before it is
1081 # signed or stored. Provenance is the caller's, so a
1082 # malformed one is how a malformed statement gets composed
1083 # at all.
1084 echo '{"harness":"valley-check","authority":"root"}' > bad-provenance.json
1085 if attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1086 --provenance bad-provenance.json > malformed.out 2> malformed.err; then
1087 echo "attest-e2e: a malformed statement must fail the run" >&2
1088 exit 1
1089 fi
1090 grep -q 'provenance.authority: field not allowed' malformed.err
1091 grep -q 'nothing published' malformed.err
1092 nothing_published "a malformed statement left a ref behind"
1093
1094 # A statement the schema admits but no line can carry is
1095 # stopped too, at the same point and for the same reason.
1096 printf '{"harness":"valley\\ncheck"}\n' > unwritable-provenance.json
1097 if attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1098 --provenance unwritable-provenance.json > unwritable.out 2> unwritable.err; then
1099 echo "attest-e2e: a statement with no written form must fail the run" >&2
1100 exit 1
1101 fi
1102 grep -q 'nothing published' unwritable.err
1103 nothing_published "a statement with no written form left a ref behind"
1104
1105 # The successful run.
1106 echo '{"harness":"valley-check","model":"none","delegation":[{"principal":"human:integrator","grant":"land changes"}]}' > provenance.json
1107 attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1108 --provenance provenance.json > run.out
1109 grep -q "^subject valley-tree-v1:$digest\$" run.out
1110 grep -q '^check ok *command passed$' run.out
1111 grep -q "^signer $host+" run.out
1112
1113 # Stored at a ref keyed by the subject digest, as one note
1114 # rather than a statement and a signature beside it.
1115 ref="$(refs)"
1116 case "$ref" in
1117 refs/the-valley/attestations/"$digest"/*) ;;
1118 *) echo "attest-e2e: ref $ref is not keyed by the subject digest" >&2; exit 1 ;;
1119 esac
1120 git cat-file -p "$ref:ok/statement.note" > statement.note
1121 head -n 1 statement.note | grep -qx 'the-valley/attestation/v1'
1122 grep -qx "subject.digest.valley-tree-v1 $digest" statement.note
1123 grep -qx 'provenance.harness valley-check' statement.note
1124 grep -q "^— $host " statement.note
1125
1126 # No git object is signed: the signature is over the
1127 # statement's text and nothing else.
1128 if git cat-file commit HEAD | grep -q '^gpgsig'; then
1129 echo "attest-e2e: attest signed a git object" >&2
1130 exit 1
1131 fi
1132
1133 verify() {
1134 attest verify --note "$1" --known-keys "$2" --repo "$repo"
1135 }
1136
1137 verify statement.note "$TMPDIR/known_keys" > verify.out
1138 grep -q "^signature ok $host+" verify.out
1139 grep -q 'matches the recorded subject digest' verify.out
1140
1141 # One atomic native-git push carries the branch and the
1142 # attestation ref together.
1143 git init --quiet --bare "$TMPDIR/host.git"
1144 git remote add valley "$TMPDIR/host.git"
1145 attest run --key "$TMPDIR/host" --name "$host" --command 'ok=true' \
1146 --push valley > push.out
1147 grep -q -- '--atomic' push.out
1148 git -C "$TMPDIR/host.git" for-each-ref --format='%(refname)' > published.txt
1149 grep -qx 'refs/heads/main' published.txt
1150 grep -qx "$ref" published.txt
1151
1152 # A second party attests to the same statement, and its
1153 # signature lands beside the first under the text both cover.
1154 # This is what the note format is here for.
1155 attest sign --key "$TMPDIR/witness" --name "$witness" statement.note \
1156 > countersigned.note
1157 if [ "$(grep -c '^— ' countersigned.note)" -ne 2 ]; then
1158 echo "attest-e2e: countersigning did not add a sibling signature line" >&2
1159 cat countersigned.note >&2
1160 exit 1
1161 fi
1162 sed '/^$/q' countersigned.note | sed '$d' | cmp - <(sed '/^$/q' statement.note | sed '$d')
1163 attest verify --note countersigned.note --known-keys "$TMPDIR/known_keys" \
1164 --repo "$repo" --signer "$host" --signer "$witness" > countersigned.out
1165 if [ "$(grep -c '^signature ok' countersigned.out)" -ne 2 ]; then
1166 echo "attest-e2e: both signatures over one statement must verify" >&2
1167 cat countersigned.out >&2
1168 exit 1
1169 fi
1170
1171 # A verifier that does not hold the witness's key still
1172 # accepts the note, and says which signature it cannot speak
1173 # to. Requiring that signer is how it refuses instead.
1174 attest key --key "$TMPDIR/host" --name "$host" > "$TMPDIR/host_only"
1175 attest verify --note countersigned.note --known-keys "$TMPDIR/host_only" \
1176 --repo "$repo" > partial.out
1177 grep -q "^signature ok $host+" partial.out
1178 grep -q "^signature unknown $witness+" partial.out
1179 if attest verify --note countersigned.note --known-keys "$TMPDIR/host_only" \
1180 --repo "$repo" --signer "$witness" > required.out 2>&1; then
1181 echo "attest-e2e: a required signer with no verified signature must fail" >&2
1182 exit 1
1183 fi
1184 grep -q "no signature on this note is by $witness" required.out
1185
1186 # A note signed by a key the verifier does not hold is not a
1187 # bad signature — it is not a signer.
1188 if verify statement.note "$TMPDIR/other_keys" > stranger.out 2>&1; then
1189 echo "attest-e2e: a note signed by nobody we hold a key for must not verify" >&2
1190 exit 1
1191 fi
1192 grep -q 'no signature on this note is by a key the verifier holds' stranger.out
1193
1194 # Tampering with the signed bytes: one byte of the text the
1195 # signature covers.
1196 sed "s/$digest/00000000000000000000000000000000000000000000000000000000000000ff/" \
1197 statement.note > tampered.note
1198 if verify tampered.note "$TMPDIR/known_keys" > tampered.out 2>&1; then
1199 echo "attest-e2e: a tampered statement must not verify" >&2
1200 exit 1
1201 fi
1202 grep -q 'does not check out over this text' tampered.out
1203
1204 # A signature cannot be lifted onto a statement it was not
1205 # made about: it sits under the text it covers, so moving it
1206 # means moving that text with it.
1207 sed '/^$/q' statement.note | sed '$d' > lifted.txt
1208 sed 's/^provenance.harness .*/provenance.harness somebody-else/' lifted.txt > lifted.body
1209 sed -n '/^$/,$p' statement.note | tail -n +2 > lifted.sigs
1210 { cat lifted.body; echo; cat lifted.sigs; } > lifted.note
1211 if verify lifted.note "$TMPDIR/known_keys" > lifted.out 2>&1; then
1212 echo "attest-e2e: a signature was lifted onto another statement" >&2
1213 exit 1
1214 fi
1215 grep -q 'does not check out over this text' lifted.out
1216
1217 # A statement written some other way than the one written
1218 # form, signed properly over those bytes. The signature is
1219 # good and the statement is still refused: it would verify
1220 # here and fail wherever it was written out again, so the
1221 # form is a rule rather than a convention.
1222 { head -n 1 lifted.txt; tail -n +2 lifted.txt | sort -r; } > loose.txt
1223 cmp -s loose.txt lifted.txt \
1224 && { echo "attest-e2e: the reordering changed nothing" >&2; exit 1; }
1225 attest sign --key "$TMPDIR/host" --name "$host" loose.txt > loose.note
1226 if verify loose.note "$TMPDIR/known_keys" > loose.out 2>&1; then
1227 echo "attest-e2e: a statement not in the written form must not verify" >&2
1228 exit 1
1229 fi
1230 grep -q 'not the written form of what it says' loose.out
1231
1232 # The subject is the tree. Change the tree and the same
1233 # signed statement stops being about it …
1234 echo goodbye > hello.txt
1235 git commit --quiet -am "change the tree"
1236 if verify statement.note "$TMPDIR/known_keys" > moved.out 2>&1; then
1237 echo "attest-e2e: a statement about another tree must not verify" >&2
1238 exit 1
1239 fi
1240 grep -q 'tree digest mismatch' moved.out
1241
1242 # … while rewriting the commit over the same tree leaves the
1243 # attestation standing, which is what a subject that is a
1244 # tree digest buys.
1245 git commit --quiet --amend -m "same tree, new commit"
1246 rewritten="$(attest digest | sed 's/^valley-tree-v1://')"
1247 git revert --quiet --no-edit HEAD
1248 restored="$(attest digest | sed 's/^valley-tree-v1://')"
1249 if [ "$restored" != "$digest" ]; then
1250 echo "attest-e2e: restoring the tree did not restore its digest" >&2
1251 echo " original $digest" >&2
1252 echo " restored $restored" >&2
1253 exit 1
1254 fi
1255 if [ "$rewritten" = "$digest" ]; then
1256 echo "attest-e2e: a changed tree kept its digest" >&2
1257 exit 1
1258 fi
1259 verify statement.note "$TMPDIR/known_keys" > rebased.out
1260 grep -q 'matches the recorded subject digest' rebased.out
1261 touch $out
1262 '';
1263
1264 # The verification-policy deriver (dcr-f41f718). Composing the two
1265 # layers is CUE's job and is pinned by cue-vet above; matching
1266 # paths is the script's own, and a path matcher is wrong exactly at
1267 # the glob boundaries — `*` inside one segment against `**` across
1268 # segments, `**` matching no segment at all — and at the sides of a
1269 # diff a naive reader drops: a rename's old path and a deletion.
1270 # Each is pinned by driving the real script over a scratch
1271 # repository and a scratch policy, never by reading the code.
1272 policy-deriver =
1273 let
1274 # A floor whose classes are one glob boundary each, and whose
1275 # check names say which class matched.
1276 deriverFloor = pkgs.writeText "deriver-floor.cue" ''
1277 package verification
1278 floor: {
1279 checks: {
1280 "c-docs": {runner: "nix", attribute: "c-docs"}
1281 "c-notes": {runner: "nix", attribute: "c-notes"}
1282 "c-flat": {runner: "nix", attribute: "c-flat"}
1283 "c-deep": {runner: "nix", attribute: "c-deep"}
1284 "c-nested": {runner: "nix", attribute: "c-nested"}
1285 "c-uncovered": {runner: "nix", attribute: "c-uncovered"}
1286 }
1287 classes: {
1288 docs: {paths: "docs/**": true, requires: "c-docs": true}
1289 notes: {paths: "notes/**": true, requires: "c-notes": true}
1290 flat: {paths: "src/*.rs": true, requires: "c-flat": true}
1291 deep: {paths: "src/**/*.rs": true, requires: "c-deep": true}
1292 nested: {paths: "a/**/b": true, requires: "c-nested": true}
1293 }
1294 unclassified: "c-uncovered": true
1295 }
1296 '';
1297 # One requirement that is a template default rather than a
1298 # rule, so the two forms are told apart on real output.
1299 deriverTemplate = pkgs.writeText "deriver-template.cue" ''
1300 package verification
1301 #tmpl: #Policy & {
1302 checks: "c-tmpl": {runner: "nix", attribute: "c-tmpl"}
1303 classes: docs: requires: "c-tmpl": bool | *true
1304 }
1305 '';
1306 deriverProject = pkgs.writeText "deriver-project.cue" ''
1307 package verification
1308 project: {
1309 #tmpl
1310 }
1311 '';
1312 in
1313 pkgs.runCommand "valley-policy-deriver"
1314 {
1315 nativeBuildInputs = [
1316 pkgs.git
1317 pkgs.cue
1318 (valleyScriptFor pkgs)
1319 ];
1320 }
1321 ''
1322 export HOME="$TMPDIR"
1323 export GIT_CONFIG_NOSYSTEM=1
1324 git config --global user.name valley-check
1325 git config --global user.email valley-check@localhost
1326 git config --global init.defaultBranch main
1327
1328 policy="$TMPDIR/policy"
1329 mkdir -p "$policy/instance" "$policy/project"
1330 cp ${deriverFloor} "$policy/instance/floor.cue"
1331 cp ${deriverTemplate} "$policy/instance/template.cue"
1332 cp ${deriverProject} "$policy/project/policy.cue"
1333
1334 repo="$TMPDIR/tree"
1335 git init --quiet "$repo"
1336 cd "$repo"
1337 mkdir -p docs notes src/deep a/x/y
1338 echo moved > docs/moved.md
1339 for f in docs/kept.md docs/gone.md src/one.rs src/deep/two.rs \
1340 a/b a/x/y/b Makefile; do
1341 echo seed > "$f"
1342 done
1343 git add -A
1344 git commit --quiet -m base
1345 base="$(git rev-parse HEAD)"
1346
1347 derive() {
1348 valley checks --schema ${./schema/verification.cue} \
1349 --instance "$policy/instance" --project "$policy/project" \
1350 "$base" HEAD
1351 }
1352
1353 # The check names in the deriver's table, sorted, on one line.
1354 named() {
1355 awk '/^required checks:$/ {f = 1; next}
1356 /^$/ {f = 0}
1357 f && /^ / {print $1}' <<<"$report" | sort | paste -sd' ' -
1358 }
1359
1360 # Start a case from the base tree; assert its check table.
1361 case_start() { git checkout --quiet -B "$1" "$base"; }
1362 expect() {
1363 local got
1364 got="$(named)"
1365 if [ "$got" != "$1" ]; then
1366 echo "policy-deriver: $2" >&2
1367 echo " expected: $1" >&2
1368 echo " got: $got" >&2
1369 echo "$report" >&2
1370 exit 1
1371 fi
1372 }
1373
1374 # `**` crosses segments, `*` does not. One file under src/
1375 # matches both patterns; one a segment deeper matches only
1376 # the `**` one.
1377 case_start flat
1378 echo edit > src/one.rs
1379 git commit --quiet -am flat
1380 report="$(derive)"
1381 expect "c-deep c-flat" "src/*.rs must match a file directly under src/"
1382
1383 case_start deep
1384 echo edit > src/deep/two.rs
1385 git commit --quiet -am deep
1386 report="$(derive)"
1387 expect "c-deep" "src/*.rs must not match across a path separator"
1388
1389 # A `**` between two segments matches no segment at all …
1390 case_start nested-none
1391 echo edit > a/b
1392 git commit --quiet -am nested-none
1393 report="$(derive)"
1394 expect "c-nested" "a/**/b must match a/b"
1395
1396 # … and any number of them.
1397 case_start nested-many
1398 echo edit > a/x/y/b
1399 git commit --quiet -am nested-many
1400 report="$(derive)"
1401 expect "c-nested" "a/**/b must match a/x/y/b"
1402
1403 # A rename counts on both sides: the class covering the old
1404 # path is required as much as the one covering the new.
1405 case_start renamed
1406 git mv docs/moved.md notes/moved.md
1407 git commit --quiet -m renamed
1408 git diff --name-status -M "$base" HEAD | grep -q '^R' \
1409 || { echo "policy-deriver: the rename case is not a rename" >&2; exit 1; }
1410 report="$(derive)"
1411 expect "c-docs c-notes c-tmpl" "a rename must count on both sides"
1412
1413 # A deleted path is still a changed path.
1414 case_start deleted
1415 git rm --quiet docs/gone.md
1416 git commit --quiet -m deleted
1417 report="$(derive)"
1418 expect "c-docs c-tmpl" "a deletion must count"
1419
1420 # The form of the value is the mandatory bit: the floor's
1421 # concrete `true` against the template's `bool | *true`.
1422 grep -qE '^ c-docs +mandatory +docs$' <<<"$report"
1423 grep -qE '^ c-tmpl +default +docs$' <<<"$report"
1424
1425 # A path no class covers takes the unclassified set, and says
1426 # so by name.
1427 case_start uncovered
1428 echo edit > Makefile
1429 git commit --quiet -am uncovered
1430 report="$(derive)"
1431 expect "c-uncovered" "an uncovered path must take the unclassified set"
1432 grep -q '^classes matched: unclassified$' <<<"$report"
1433 grep -q '^unclassified: 1 path(s) matched no class$' <<<"$report"
1434 grep -q '^ Makefile$' <<<"$report"
1435
1436 touch $out
1437 '';
1438
1439 module-eval =
1440 if failedAssertions != [ ] then
1441 throw "valley module-eval: failed assertions: ${lib.concatMapStringsSep "; " (a: a.message) failedAssertions}"
1442 else if resticRenderedWithoutDeclaration then
1443 throw "valley module-eval: restic machinery rendered for a declaration without a backup block"
1444 else if busRenderedWithoutEnable then
1445 throw "valley module-eval: bus machinery rendered without services.valley.bus.enable"
1446 else if
1447 !(lib.any (a: lib.hasInfix "services.valley.backup." a.message) missingSecretAssertions)
1448 then
1449 throw "valley module-eval: enabling backup without the secret-path options must fail an assertion naming them"
1450 else
1451 pkgs.runCommand "valley-module-eval"
1452 {
1453 initScript = host.config.systemd.services.valley-init.script;
1454 sshdConfig = host.config.services.openssh.extraConfig;
1455 resticService = host.config.systemd.units."restic-backups-valley.service".text;
1456 resticTimer = host.config.systemd.units."restic-backups-valley.timer".text;
1457 passAsFile = [
1458 "initScript"
1459 "sshdConfig"
1460 "resticService"
1461 "resticTimer"
1462 ];
1463 }
1464 ''
1465 # The repo init list and mirror hook must be generated from
1466 # the CUE export, and the git user's sshd Match block must
1467 # be terminated so it cannot scope later config.
1468 grep -q "the-valley" "$initScriptPath"
1469 grep -q "valley-mirrors" "$initScriptPath"
1470 grep -q "Match All" "$sshdConfigPath"
1471
1472 # The mirror publishes main and tags only — a heads glob
1473 # would publish every topic branch awaiting review — with
1474 # --prune for tag deletions and a sweep that unpublishes
1475 # any other head (--prune cannot: it ignores non-glob
1476 # refspecs). Never --mirror: it also deletes remote-only
1477 # refs, and GitHub's read-only refs/pull/* fails every such
1478 # push. Follow the hook chain from the init script to the
1479 # rendered push script and pin the invocation there.
1480 mirrorHook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-[^ ]*' "$initScriptPath" | head -n1)"
1481 mirrorPush="$(grep -o '/nix/store/[^ ]*-valley-mirror-push-[^ ]*' "$mirrorHook" | head -n1)"
1482 grep -q -- 'push --prune' "$mirrorPush"
1483 grep -qF -- '+refs/heads/main:refs/heads/main' "$mirrorPush"
1484 grep -qF -- '+refs/tags/*:refs/tags/*' "$mirrorPush"
1485 grep -qF -- 'ls-remote --heads' "$mirrorPush"
1486 grep -qF -- 'push "$url" --delete' "$mirrorPush"
1487 if grep -qF -- '+refs/heads/*:refs/heads/*' "$mirrorPush"; then
1488 echo "module-eval: mirror push regressed to publishing every head" >&2
1489 exit 1
1490 fi
1491 if grep -q -- '--mirror' "$mirrorPush"; then
1492 echo "module-eval: mirror push regressed to --mirror" >&2
1493 exit 1
1494 fi
1495 # Deletions must never reach a namespace the mirror owns.
1496 if grep -q 'refs/pull' "$mirrorPush"; then
1497 echo "module-eval: mirror push must not name refs/pull/*" >&2
1498 exit 1
1499 fi
1500
1501 # The rendered restic units must back up the data directory
1502 # to the consumer-supplied repository with the declared
1503 # retention over a pinned host key, on the declared cadence.
1504 grep -q "RESTIC_REPOSITORY_FILE=/run/agenix/valley-restic-repo" "$resticServicePath"
1505 grep -q -- "--keep-daily 7 --keep-weekly 4 --keep-monthly 6" "$resticServicePath"
1506 grep -q "UserKnownHostsFile=/var/lib/valley-backup/known_hosts" "$resticServicePath"
1507 grep -q "BatchMode=yes" "$resticServicePath"
1508 grep -q "OnCalendar=03:30" "$resticTimerPath"
1509
1510 # The backup paths render as a --files-from list: follow
1511 # ExecStartPre to that list and pin the data directory.
1512 preStart="$(sed -n 's/^ExecStartPre=//p' "$resticServicePath" | head -n1)"
1513 staticPaths="$(grep -o '/nix/store/[^ ]*-staticPaths' "$preStart" | head -n1)"
1514 grep -qx "/srv/git" "$staticPaths"
1515 touch $out
1516 '';
1517
1518 # What a mirror ends up holding, end to end and unmocked: a bare
1519 # repo wired with the real rendered hooks, pushed to for real, and
1520 # a second bare repo standing in for the mirror. The refspec is
1521 # easy to get subtly wrong — --prune ignores the non-glob heads
1522 # refspec, so pruning heads is the sweep's job — and only running
1523 # git can tell. Relative mirror URLs (mirrorHost) resolve against
1524 # the pushing repo, so the shipped scripts run with no
1525 # substitution: this is exactly what a host executes.
1526 mirror-e2e =
1527 pkgs.runCommand "valley-mirror-e2e"
1528 {
1529 nativeBuildInputs = [ pkgs.git ];
1530 initScript = mirrorHost.config.systemd.services.valley-init.script;
1531 passAsFile = [ "initScript" ];
1532 }
1533 ''
1534 export HOME="$TMPDIR"
1535 export GIT_CONFIG_NOSYSTEM=1
1536 git config --global user.name valley-check
1537 git config --global user.email valley-check@localhost
1538 git config --global init.defaultBranch main
1539 cd "$TMPDIR"
1540
1541 wait_for() {
1542 for _ in $(seq 1 150); do
1543 "$@" >/dev/null 2>&1 && return 0
1544 sleep 0.2
1545 done
1546 echo "mirror-e2e: timed out waiting for: $*" >&2
1547 return 1
1548 }
1549 heads() { git -C mirror.git for-each-ref --format='%(refname)' refs/heads; }
1550 tags() { git -C mirror.git for-each-ref --format='%(refname)' refs/tags; }
1551 mirror_main_is() { [ "$(git -C mirror.git rev-parse main)" = "$tip" ]; }
1552 only_main() { [ "$(heads)" = refs/heads/main ]; }
1553
1554 # A primary repo wired exactly as valley-init wires it, with
1555 # the real store paths followed from the rendered init script.
1556 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1557 mhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-mirror-pilot' "$initScriptPath" | head -n1)"
1558 deadhook="$(grep -o '/nix/store/[^ ]*-valley-mirrors-dead-mirror' "$initScriptPath" | head -n1)"
1559 test -x "$dispatch" && test -x "$mhook" && test -x "$deadhook"
1560 wire() {
1561 mkdir -p "$1/hooks/post-receive.d"
1562 ln -s "$dispatch" "$1/hooks/post-receive"
1563 ln -s "$2" "$1/hooks/post-receive.d/valley-mirrors"
1564 }
1565
1566 # The mirror as it stands today: every head and tag of the
1567 # primary, topic branches included. Seeded before the hook is
1568 # wired, so nothing sweeps it out from under the setup.
1569 git init --quiet --bare mirror-pilot.git
1570 git init --quiet --bare mirror.git
1571 git clone --quiet "$PWD/mirror-pilot.git" work
1572 git -C work commit --quiet --allow-empty -m one
1573 git -C work tag v1
1574 git -C work tag doomed
1575 for b in idea/one idea/two; do git -C work branch "$b"; done
1576 git -C work push --quiet origin \
1577 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1578 git -C mirror-pilot.git push --quiet ../mirror.git \
1579 '+refs/heads/*:refs/heads/*' '+refs/tags/*:refs/tags/*'
1580 [ "$(heads | wc -l)" -eq 3 ]
1581 wire mirror-pilot.git "$mhook"
1582
1583 # A real push to the primary — a topic branch alongside main,
1584 # and a tag deleted. The hook replicates asynchronously, so
1585 # wait on main's new tip before judging the rest.
1586 git -C work commit --quiet --allow-empty -m two
1587 git -C work tag -d doomed >/dev/null
1588 git -C work branch idea/three
1589 git -C work push --quiet --follow-tags origin main idea/three
1590 git -C work push --quiet --delete origin doomed
1591 tip="$(git -C work rev-parse HEAD)"
1592 wait_for mirror_main_is
1593
1594 # main and the tags are published; nothing else is, and the
1595 # topic branches that were on the mirror are gone. The sweep
1596 # is a second push, so it converges just after main lands.
1597 wait_for only_main
1598 [ "$(tags)" = refs/tags/v1 ]
1599
1600 # A branch that appears on the mirror by any other route is
1601 # unpublished on the next push.
1602 git -C mirror.git branch sneaky main
1603 git -C work commit --quiet --allow-empty -m three
1604 git -C work push --quiet origin main
1605 tip="$(git -C work rev-parse HEAD)"
1606 wait_for mirror_main_is
1607 wait_for only_main
1608
1609 # An unreachable mirror costs a log line, never the push: the
1610 # hook must return promptly and the push must succeed.
1611 git init --quiet --bare dead-mirror.git
1612 wire dead-mirror.git "$deadhook"
1613 git clone --quiet "$PWD/dead-mirror.git" deadwork
1614 git -C deadwork commit --quiet --allow-empty -m one
1615 timeout 60 git -C deadwork push --quiet origin main
1616 [ "$(git -C dead-mirror.git rev-parse main)" = "$(git -C deadwork rev-parse HEAD)" ]
1617
1618 touch $out
1619 '';
1620
1621 # Phase 1's exit criteria, end to end and unmocked: a push to a
1622 # bare repo wired with the real rendered hooks produces a
1623 # ref-updated event on a real JetStream server within seconds,
1624 # visible in `valley tail`; replaying the repo's refs is
1625 # deterministic; and a dead bus never fails a push. The hook and
1626 # stream-init scripts are followed from the rendered unit scripts,
1627 # so the check exercises exactly what a host would run — only the
1628 # server invocation differs (the sandbox cannot write /srv), same
1629 # binary and flags, relocated storage.
1630 bus-e2e =
1631 pkgs.runCommand "valley-bus-e2e"
1632 {
1633 nativeBuildInputs = [
1634 pkgs.git
1635 pkgs.natscli
1636 pkgs.nats-server
1637 pkgs.jq
1638 pkgs.cue
1639 (valleyScriptFor pkgs)
1640 ];
1641 initScript = busHost.config.systemd.services.valley-init.script;
1642 busInitScript = busHost.config.systemd.services.valley-bus-init.script;
1643 passAsFile = [
1644 "initScript"
1645 "busInitScript"
1646 ];
1647 }
1648 ''
1649 export HOME="$TMPDIR"
1650 export NATS_URL=nats://127.0.0.1:4222
1651 export GIT_CONFIG_NOSYSTEM=1
1652 git config --global user.name valley-check
1653 git config --global user.email valley-check@localhost
1654 git config --global init.defaultBranch main
1655
1656 wait_for() {
1657 for _ in $(seq 1 150); do
1658 "$@" >/dev/null 2>&1 && return 0
1659 sleep 0.2
1660 done
1661 echo "bus-e2e: timed out waiting for: $*" >&2
1662 return 1
1663 }
1664
1665 nats-server --addr 127.0.0.1 --port 4222 --jetstream \
1666 --store_dir "$TMPDIR/js" &
1667 server_pid=$!
1668
1669 # The real stream-init script the module renders.
1670 bash -eu "$busInitScriptPath"
1671 nats stream info valley >/dev/null
1672
1673 # A bare repo wired exactly as valley-init wires it, with the
1674 # real store paths followed from the rendered init script.
1675 dispatch="$(grep -o '/nix/store/[^ ]*-valley-post-receive' "$initScriptPath" | head -n1)"
1676 bushook="$(grep -o '/nix/store/[^ ]*-valley-bus-events' "$initScriptPath" | head -n1)"
1677 test -x "$dispatch"
1678 test -x "$bushook"
1679 repo="$TMPDIR/events-pilot.git"
1680 git init --quiet --bare "$repo"
1681 mkdir -p "$repo/hooks/post-receive.d"
1682 ln -s "$dispatch" "$repo/hooks/post-receive"
1683 ln -s "$bushook" "$repo/hooks/post-receive.d/valley-bus"
1684
1685 git clone --quiet "$repo" "$TMPDIR/work"
1686 cd "$TMPDIR/work"
1687 echo one > file
1688 git add file
1689 git commit --quiet -m one
1690 git push --quiet origin main
1691 first="$(git rev-parse HEAD)"
1692 zeros="$(printf '%040d' 0)"
1693
1694 # Exit criterion 1: the event arrives within seconds, with a
1695 # payload that is exactly the git facts of the push …
1696 msgs_is() { [ "$(nats stream info valley --json | jq .state.messages)" -eq "$1" ]; }
1697 wait_for msgs_is 1
1698 got="$(nats stream get valley 1 --json)"
1699 [ "$(jq -r .subject <<<"$got")" = valley.git.events-pilot.ref-updated ]
1700 payload="$(jq -r .data <<<"$got" | base64 -d)"
1701 expected='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$first"'"}'
1702 [ "$payload" = "$expected" ]
1703
1704 # … valid against the shipped event schema.
1705 echo "$payload" > "$TMPDIR/payload.json"
1706 cue vet -d '#RefUpdated' ${./schema/events.cue} "$TMPDIR/payload.json"
1707
1708 # … and visible in `valley tail`. Subscribe first, then push.
1709 valley tail > "$TMPDIR/tail.out" 2>&1 &
1710 tail_pid=$!
1711 subscribed() { grep -q 'valley.>' "$TMPDIR/tail.out"; }
1712 wait_for subscribed
1713 echo two > file
1714 git commit --quiet -am two
1715 git push --quiet origin main
1716 second="$(git rev-parse HEAD)"
1717 wait_for msgs_is 2
1718 payload2="$(nats stream get valley 2 --json | jq -r .data | base64 -d)"
1719 expected2='{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$first"'","new":"'"$second"'"}'
1720 [ "$payload2" = "$expected2" ]
1721 tail_saw() { grep -qF "$expected2" "$TMPDIR/tail.out"; }
1722 wait_for tail_saw
1723 kill "$tail_pid" 2>/dev/null || true
1724
1725 # Exit criterion 2: rebuilding the stream from the repo's
1726 # refs is deterministic — two replays from scratch produce
1727 # identical events, landing on the pushed tip with the
1728 # all-zero id as old.
1729 dump_stream() {
1730 local info first_seq last_seq i
1731 info="$(nats stream info valley --json)"
1732 first_seq="$(jq .state.first_seq <<<"$info")"
1733 last_seq="$(jq .state.last_seq <<<"$info")"
1734 for i in $(seq "$first_seq" "$last_seq"); do
1735 nats stream get valley "$i" --json | jq -c '{subject: .subject, data: .data}'
1736 done
1737 }
1738 nats stream purge valley --force >/dev/null
1739 valley replay "$repo"
1740 wait_for msgs_is 1
1741 run1="$(dump_stream)"
1742 nats stream purge valley --force >/dev/null
1743 valley replay "$repo"
1744 wait_for msgs_is 1
1745 run2="$(dump_stream)"
1746 [ "$run1" = "$run2" ]
1747 replayed="$(jq -r .data <<<"$run1" | base64 -d)"
1748 [ "$replayed" = '{"event":"ref-updated","repo":"events-pilot","ref":"refs/heads/main","old":"'"$zeros"'","new":"'"$second"'"}' ]
1749
1750 # A dead bus never blocks a push: the event is simply lost
1751 # (and rebuildable by replay).
1752 kill "$server_pid"
1753 wait "$server_pid" || true
1754 echo three > file
1755 git commit --quiet -am three
1756 git push --quiet origin main
1757
1758 touch $out
1759 '';
1760 }
1761 );
1762 };
1763}