gunk-dev/the-valley

policy_test.go

sourcea0a0b015e569main's published tip history
17.8 KiB
1package main
2
3// The policy bridge, where this program is coupled to two others: the
4// deriver's output, and the policy cue composes, with the window a check
5// writes down and the digest of the whole. Both are pinned here rather than
6// assumed.
7
8import (
9 "the-valley/composed"
10
11 "context"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "reflect"
16 "strings"
17 "testing"
18 "time"
19)
20
21func TestDeriverOutputIsRead(t *testing.T) {
22 out := `abc1234..def5678: 3 changed path(s)
23policy: instance + policy
24classes matched: code, prose
25carry mode: same-class
26
27required checks:
28 code-build mandatory code
29 prose-format default prose, knowledge
30
31unclassified: 1 path(s) matched no class
32 odd.txt
33`
34 d, err := parseDerived(out)
35 if err != nil {
36 t.Fatal(err)
37 }
38 if !d.classes["code"] || !d.classes["prose"] || len(d.classes) != 2 {
39 t.Fatalf("classes = %v", d.classes)
40 }
41 if got := strings.Join(d.requires["prose-format"], "+"); got != "prose+knowledge" {
42 t.Fatalf("prose-format required by %q", got)
43 }
44 if got := strings.Join(d.requires["code-build"], "+"); got != "code" {
45 t.Fatalf("code-build required by %q", got)
46 }
47 if len(d.requires) != 2 {
48 t.Fatalf("required = %v", d.requires)
49 }
50 if d.carry != "same-class" {
51 t.Fatalf("carry mode = %q", d.carry)
52 }
53}
54
55// The deriver ends its report with what each required check costs. Those
56// lines group the required checks and require nothing more, so a report
57// carrying them reads as exactly the report without them — with an
58// unclassified block between the table and the summary, and with the
59// summary straight after the table.
60func TestTheCostSummaryChangesNothingRead(t *testing.T) {
61 table := `abc1234..def5678: 2 changed path(s)
62policy: instance + policy
63classes matched: code, prose
64carry mode: same-paths
65
66required checks:
67 code-build mandatory code
68 vm-test default code
69 prose-format default prose, knowledge
70`
71 unclassified := `
72unclassified: 1 path(s) matched no class
73 odd.txt
74`
75 summary := `
76quick: code-build, prose-format
77slow: vm-test
78`
79 for _, before := range []string{table, table + unclassified} {
80 want, err := parseDerived(before)
81 if err != nil {
82 t.Fatal(err)
83 }
84 if len(want.requires) != 3 || len(want.classes) != 2 {
85 t.Fatalf("the report without a summary reads as %+v", want)
86 }
87 got, err := parseDerived(before + summary)
88 if err != nil {
89 t.Fatal(err)
90 }
91 if !reflect.DeepEqual(got, want) {
92 t.Errorf("with the cost summary, the report reads as %+v, not %+v", got, want)
93 }
94 }
95}
96
97// A deriver that fails partway and still exits zero prints something that
98// is not a whole report. Read as one, each of these requires nothing, so
99// each is refused.
100func TestAPartialReportIsRefused(t *testing.T) {
101 for _, c := range []struct{ name, out string }{
102 {"a required-checks heading with no checks under it", `abc1234..def5678: 2 changed path(s)
103policy: instance + policy
104classes matched: code
105carry mode: same-paths
106
107required checks:
108
109quick: none
110slow: none
111`},
112 {"a required-checks heading that ends the output", `abc1234..def5678: 2 changed path(s)
113policy: instance + policy
114classes matched: code
115carry mode: same-paths
116
117required checks:
118`},
119 {"no required-checks section", `abc1234..def5678: 2 changed path(s)
120policy: instance + policy
121classes matched: code
122carry mode: same-paths
123`},
124 {"no header", `policy: instance + policy
125classes matched: code
126carry mode: same-paths
127
128required checks:
129 code-build mandatory code
130`},
131 {"nothing at all", ``},
132 {"changed paths and no class", `abc1234..def5678: 2 changed path(s)
133policy: instance + policy
134classes matched: none
135carry mode: same-paths
136
137required checks: none
138`},
139 {"no changed paths and a class", `abc1234..def5678: 0 changed path(s)
140policy: instance + policy
141classes matched: code
142carry mode: same-paths
143
144required checks:
145 code-build mandatory code
146`},
147 {"no carry mode", `abc1234..def5678: 2 changed path(s)
148policy: instance + policy
149classes matched: code
150
151required checks:
152 code-build mandatory code
153`},
154 {"a carry mode that is not one", `abc1234..def5678: 2 changed path(s)
155policy: instance + policy
156classes matched: code
157carry mode: same-file
158
159required checks:
160 code-build mandatory code
161`},
162 {"an empty carry mode", `abc1234..def5678: 2 changed path(s)
163policy: instance + policy
164classes matched: code
165carry mode:
166
167required checks:
168 code-build mandatory code
169`},
170 } {
171 if d, err := parseDerived(c.out); err == nil {
172 t.Errorf("%s: read as %+v", c.name, d)
173 }
174 }
175}
176
177// The deriver states each thing once. A report that states one twice holds
178// a forged line, such as a looser carry mode after the real one, and a
179// parser that kept the last would let the forgery win. Each forged line
180// here follows the real one, as a sorted forgery did, and is refused.
181func TestAReportThatSaysOneThingTwiceIsRefused(t *testing.T) {
182 const header = "abc1234..def5678: 2 changed path(s)\n"
183 const classes = "classes matched: guarded\n"
184 const carry = "carry mode: exact\n"
185 const table = "\nrequired checks:\n c-build mandatory guarded\n"
186 whole := header + "policy: instance + policy\n" + classes + carry + table
187 if _, err := parseDerived(whole); err != nil {
188 t.Fatalf("the report without a forged line is refused: %v", err)
189 }
190 for _, c := range []struct{ name, out string }{
191 {"a second carry mode", header + classes + carry + "carry mode: same-paths\n" + table},
192 {"the same carry mode twice", header + classes + carry + carry + table},
193 {"a second row for one check", header + classes + carry + table + " c-build default unclassified\n"},
194 {"a second required-checks section", header + classes + carry + table + "\nrequired checks: none\n"},
195 {"a second header", header + "abc1234..def5678: 0 changed path(s)\n" + classes + carry + table},
196 {"a second classes line", header + classes + "classes matched: none\n" + carry + table},
197 } {
198 if d, err := parseDerived(c.out); err == nil {
199 t.Errorf("%s: read as %+v", c.name, d)
200 }
201 }
202}
203
204// The report of a diff with nothing in it is still a whole report, and it
205// requires nothing.
206func TestAnEmptyDiffReadsAsRequiringNothing(t *testing.T) {
207 d, err := parseDerived(`abc1234..abc1234: 0 changed path(s)
208policy: instance + policy
209classes matched: none
210carry mode: same-paths
211
212required checks: none
213`)
214 if err != nil {
215 t.Fatal(err)
216 }
217 if d.paths != 0 || len(d.classes) != 0 || len(d.requires) != 0 || d.carry != "same-paths" {
218 t.Fatalf("an empty diff reads as %+v", d)
219 }
220}
221
222// A report of no changed paths is believed only when git agrees. The
223// stand-in deriver prints a whole, well-formed report of no changed paths —
224// what a deriver whose diff failed silently would print — and the
225// derivation is read over two commits with one tree, and refused over two
226// commits whose trees differ.
227func TestAReportOfNoChangedPathsIsCheckedAgainstGit(t *testing.T) {
228 repo := t.TempDir()
229 run := func(args ...string) string {
230 t.Helper()
231 out, err := git(repo, append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
232 if err != nil {
233 t.Fatal(err)
234 }
235 return strings.TrimSpace(out)
236 }
237 run("init", "--quiet")
238 run("commit", "--quiet", "--allow-empty", "-m", "one")
239 one := run("rev-parse", "HEAD")
240 run("commit", "--quiet", "--allow-empty", "-m", "the same tree")
241 same := run("rev-parse", "HEAD")
242 if err := os.WriteFile(filepath.Join(repo, "changed.txt"), []byte("x\n"), 0o644); err != nil {
243 t.Fatal(err)
244 }
245 run("add", "changed.txt")
246 run("commit", "--quiet", "-m", "a change")
247 changed := run("rev-parse", "HEAD")
248
249 deriver := filepath.Join(t.TempDir(), "valley")
250 report := `printf '%s\n' 'x..y: 0 changed path(s)' 'policy: a + b' 'classes matched: none' 'carry mode: same-paths' '' 'required checks: none'`
251 if err := os.WriteFile(deriver, []byte("#!/bin/sh\n"+report+"\n"), 0o755); err != nil {
252 t.Fatal(err)
253 }
254 p := policySource{valley: deriver}
255 tip := &worktree{dir: repo}
256 if _, err := p.derive(tip, one, same); err != nil {
257 t.Fatalf("an empty diff reported as empty was refused: %v", err)
258 }
259 if d, err := p.derive(tip, one, changed); err == nil {
260 t.Fatalf("a change reported as touching nothing was read as %+v", d)
261 }
262}
263
264// The policy digest is of the whole composed policy, so a class's carry
265// mode, the restacker's cap and the hardware approval requirement are in it
266// as much as a check is. The layers are composed by the real cue under the
267// real schema, with the floor fixed and the project layer varied.
268func TestThePolicyDigestCoversCarryTheCapAndHardware(t *testing.T) {
269 cue, err := exec.LookPath("cue")
270 if err != nil {
271 t.Skip("no cue to compose a policy with; the nix check provides one")
272 }
273 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
274 if err != nil {
275 t.Fatal(err)
276 }
277 const floor = `package verification
278floor: {
279 checks: "c-build": {runner: "nix", attribute: "c-build"}
280 classes: code: {paths: "src/**": true, requires: "c-build": true}
281}
282`
283 digest := func(project string) string {
284 t.Helper()
285 p := policySource{schema: schema, cue: cue, instance: t.TempDir(), project: t.TempDir()}
286 if err := os.WriteFile(filepath.Join(p.instance, "floor.cue"), []byte(floor), 0o644); err != nil {
287 t.Fatal(err)
288 }
289 if err := os.WriteFile(filepath.Join(p.project, "policy.cue"), []byte("package verification\n"+project), 0o644); err != nil {
290 t.Fatal(err)
291 }
292 _, sum, err := p.catalogue()
293 if err != nil {
294 t.Fatal(err)
295 }
296 return sum
297 }
298
299 base := digest("")
300 if again := digest(""); again != base {
301 t.Fatalf("one policy digested twice gave %s and %s", base, again)
302 }
303 // The digest is of the composition, not of the text: writing the cap's
304 // default composes the same policy.
305 if same := digest("project: restack: maxAutomaticVersions: 64\n"); same != base {
306 t.Errorf("writing the default cap moved the digest from %s to %s", base, same)
307 }
308 seen := map[string]string{base: "the floor alone"}
309 for _, c := range []struct{ name, project string }{
310 {"a class asking for same-class", `project: classes: code: carry: "same-class": true` + "\n"},
311 {"a class asking for exact", "project: classes: code: carry: exact: true\n"},
312 {"a lower cap", "project: restack: maxAutomaticVersions: 16\n"},
313 // The schema puts no upper bound on the cap. The integrator does
314 // not read the cap, so it composes and digests one no Go int holds.
315 {"a cap no int holds", "project: restack: maxAutomaticVersions: 9223372036854775808\n"},
316 {"a hardware approval requirement", "project: approval: hardware: true\n"},
317 } {
318 sum := digest(c.project)
319 if other, ok := seen[sum]; ok {
320 t.Errorf("%s digests the same as %s: %s", c.name, other, sum)
321 }
322 seen[sum] = c.name
323 }
324}
325
326func TestValidityWindowsAreReadAsThePolicyWritesThem(t *testing.T) {
327 for _, c := range []struct {
328 in string
329 want time.Duration
330 }{
331 {"", 0},
332 {"30s", 30 * time.Second},
333 {"15m", 15 * time.Minute},
334 {"6h", 6 * time.Hour},
335 {"2d", 48 * time.Hour},
336 } {
337 got, err := parseWindow(c.in)
338 if err != nil || got != c.want {
339 t.Errorf("parseWindow(%q) = %v, %v; want %v", c.in, got, err, c.want)
340 }
341 }
342}
343
344// Each layer's absence defaults in the safe direction of that layer's job,
345// and the two directions are opposite (dcr-f41f718). Both are pinned here,
346// because the value of the rule is that neither is the other.
347
348// targetTip commits files onto a scratch repository's main and returns
349// the tip as a pass checks it out.
350func targetTip(t *testing.T, files map[string]string) (*scratchRepo, *worktree) {
351 t.Helper()
352 s := newScratchRepo(t)
353 for path, body := range files {
354 full := filepath.Join(s.repo, path)
355 if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
356 t.Fatal(err)
357 }
358 if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
359 t.Fatal(err)
360 }
361 }
362 s.git("add", "--all")
363 s.git("commit", "--quiet", "--allow-empty", "-m", "the target")
364 return s, &worktree{repo: s.repo, dir: s.repo, rev: s.git("rev-parse", "HEAD")}
365}
366
367func TestATargetWithNoProjectLayerIsJudgedUnderTheFloorAlone(t *testing.T) {
368 _, tip := targetTip(t, map[string]string{"policy/project/notes.md": "not a document\n"})
369 p := policySource{projectDir: "policy/project"}
370 done, err := p.openProject(tip)
371 if err != nil {
372 t.Fatal(err)
373 }
374 defer done()
375 if p.note == "" {
376 t.Fatal("the pass said nothing about composing the floor alone")
377 }
378 // What the deriver and the composer are handed is a layer that adds
379 // nothing, not a directory that is not there.
380 docs, err := filepath.Glob(filepath.Join(p.project, "*.cue"))
381 if err != nil || len(docs) != 1 {
382 t.Fatalf("the resolved project layer holds %v (%v)", docs, err)
383 }
384 if body, err := os.ReadFile(docs[0]); err != nil || strings.TrimSpace(string(body)) != "package verification" {
385 t.Fatalf("the layer that adds nothing reads %q (%v)", body, err)
386 }
387 done()
388 if _, err := os.Stat(p.project); !os.IsNotExist(err) {
389 t.Fatalf("the pass left its scratch layer behind: %v", err)
390 }
391}
392
393// The project layer is read from the tip's commit, and its directory is a
394// name, never a pattern: --project-policy policy/proj* reads that
395// directory, and not policy/projX beside it.
396func TestATargetsOwnProjectLayerIsReadAtTheTip(t *testing.T) {
397 for _, dir := range []string{"policy/project", "policy/proj*"} {
398 t.Run(dir, func(t *testing.T) {
399 _, tip := targetTip(t, map[string]string{
400 dir + "/policy.cue": "package verification // own\n",
401 "policy/projX/decoy.cue": "package verification // decoy\n",
402 })
403 p := policySource{projectDir: dir}
404 done, err := p.openProject(tip)
405 if err != nil {
406 t.Fatal(err)
407 }
408 defer done()
409 if p.note != "" {
410 t.Fatalf("an ordinary composition said %q", p.note)
411 }
412 entries, err := os.ReadDir(p.project)
413 if err != nil || len(entries) != 1 || entries[0].Name() != "policy.cue" {
414 t.Fatalf("the project layer resolved to %s, holding %v (%v)", p.project, entries, err)
415 }
416 if body, _ := os.ReadFile(filepath.Join(p.project, "policy.cue")); string(body) != "package verification // own\n" {
417 t.Fatalf("the project layer reads %q", body)
418 }
419 })
420 }
421}
422
423// A project layer that cannot be read refuses the pass. Read as absent, it
424// would judge the change under the floor alone, requiring fewer checks
425// from a read that never happened.
426func TestAProjectLayerThatCannotBeReadIsRefused(t *testing.T) {
427 for _, lost := range []string{"policy/project", "policy/project/policy.cue"} {
428 t.Run(lost, func(t *testing.T) {
429 s, tip := targetTip(t, map[string]string{"policy/project/policy.cue": "package verification\n"})
430 oid := s.git("rev-parse", tip.rev+":"+lost)
431 if err := os.Remove(filepath.Join(s.repo, ".git", "objects", oid[:2], oid[2:])); err != nil {
432 t.Fatal(err)
433 }
434 p := policySource{projectDir: "policy/project"}
435 done, err := p.openProject(tip)
436 defer done()
437 if err == nil {
438 t.Fatalf("an unreadable project layer resolved to %s, noting %q", p.project, p.note)
439 }
440 if !strings.Contains(err.Error(), "policy/project") {
441 t.Fatalf("the refusal reads %q", err)
442 }
443 })
444 }
445}
446
447func TestAFloorThatIsNotThereIsRefused(t *testing.T) {
448 // The materialized source, which is the one a test can drive without a
449 // repository. The repository source refuses the same way, and the e2e
450 // observes it there.
451 _, done, err := composed.Floor{Path: t.TempDir()}.Open(context.Background(), "valley-integrator-floor")
452 defer done()
453 if err == nil {
454 t.Fatal("a floor directory with no documents in it was accepted")
455 }
456 if !strings.Contains(err.Error(), composed.Floorless) {
457 t.Fatalf("the refusal reads %q", err)
458 }
459}
460
461// The floor is every *.cue document directly in its directory, whatever
462// its name. Listed one name a line, git quotes a name with non-ASCII
463// characters in it, and the quoted name does not end in .cue, so a floor
464// read that way skipped naïve.cue. The repository sets core.quotePath to
465// the default that quotes, and the document is composed into the
466// catalogue like any other.
467func TestAFloorDocumentWithANonASCIINameIsRead(t *testing.T) {
468 cue, err := exec.LookPath("cue")
469 if err != nil {
470 t.Skip("no cue to compose a policy with; the nix check provides one")
471 }
472 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
473 if err != nil {
474 t.Fatal(err)
475 }
476 s := newScratchRepo(t)
477 s.git("config", "core.quotePath", "true")
478 dir := filepath.Join(s.repo, "policy", "instance")
479 if err := os.MkdirAll(dir, 0o755); err != nil {
480 t.Fatal(err)
481 }
482 for name, body := range map[string]string{
483 "floor.cue": `package verification
484floor: {
485 checks: "c-build": {runner: "nix", attribute: "c-build"}
486 classes: code: {paths: "src/**": true, requires: "c-build": true}
487}
488`,
489 "naïve.cue": `package verification
490floor: checks: "c-lint": {runner: "nix", attribute: "c-lint"}
491`,
492 } {
493 if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
494 t.Fatal(err)
495 }
496 }
497 s.git("add", "policy")
498 s.git("commit", "--quiet", "-m", "the floor")
499
500 p := policySource{
501 schema: schema,
502 cue: cue,
503 layer: composed.Floor{Repo: s.repo, Ref: "refs/heads/main", Dir: "policy/instance"},
504 projectDir: "policy/project",
505 }
506 p, done, err := p.open(&worktree{repo: s.repo, dir: s.repo, rev: s.git("rev-parse", "HEAD")})
507 defer done()
508 if err != nil {
509 t.Fatal(err)
510 }
511 cat, _, err := p.catalogue()
512 if err != nil {
513 t.Fatal(err)
514 }
515 if _, ok := cat["c-lint"]; !ok {
516 t.Fatalf("the floor's naïve.cue was not read: the catalogue holds %v", cat)
517 }
518 if _, ok := cat["c-build"]; !ok {
519 t.Fatalf("the floor's floor.cue was not read: the catalogue holds %v", cat)
520 }
521}
522
523func TestARefusalIsReadAsTheSentenceItIs(t *testing.T) {
524 // attest reports what it checked, then refuses, then elaborates. The
525 // sentence is the refusal; the elaboration is not.
526 out := `note /tmp/x.note
527text ok (411 bytes signed)
528attest: tree digest mismatch: the statement is about a different tree
529 recorded aaaa
530 found bbbb
531`
532 if got := refusalLine(out); got != "tree digest mismatch: the statement is about a different tree" {
533 t.Fatalf("refusalLine = %q", got)
534 }
535 if got := refusalLine("something with no prefix at all\n"); got != "something with no prefix at all" {
536 t.Fatalf("refusalLine fallback = %q", got)
537 }
538}