gunk-dev/the-valley

policy_test.go

sourcef6b0e851c548main's published tip history
15.7 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
348func TestATargetWithNoProjectLayerIsJudgedUnderTheFloorAlone(t *testing.T) {
349 tip := &worktree{dir: t.TempDir()}
350 p := policySource{projectDir: "policy/project"}
351 done, err := p.openProject(tip)
352 if err != nil {
353 t.Fatal(err)
354 }
355 defer done()
356 if p.note == "" {
357 t.Fatal("the pass said nothing about composing the floor alone")
358 }
359 // What the deriver and the composer are handed is a layer that adds
360 // nothing, not a directory that is not there.
361 docs, err := filepath.Glob(filepath.Join(p.project, "*.cue"))
362 if err != nil || len(docs) != 1 {
363 t.Fatalf("the resolved project layer holds %v (%v)", docs, err)
364 }
365 if body, err := os.ReadFile(docs[0]); err != nil || strings.TrimSpace(string(body)) != "package verification" {
366 t.Fatalf("the layer that adds nothing reads %q (%v)", body, err)
367 }
368 done()
369 if _, err := os.Stat(p.project); !os.IsNotExist(err) {
370 t.Fatalf("the pass left its scratch layer behind: %v", err)
371 }
372}
373
374func TestATargetsOwnProjectLayerIsUsedWhereItIs(t *testing.T) {
375 tip := &worktree{dir: t.TempDir()}
376 own := filepath.Join(tip.dir, "policy/project")
377 if err := os.MkdirAll(own, 0o755); err != nil {
378 t.Fatal(err)
379 }
380 if err := os.WriteFile(filepath.Join(own, "policy.cue"), []byte("package verification\n"), 0o644); err != nil {
381 t.Fatal(err)
382 }
383 p := policySource{projectDir: "policy/project"}
384 done, err := p.openProject(tip)
385 if err != nil {
386 t.Fatal(err)
387 }
388 defer done()
389 if p.project != own {
390 t.Fatalf("the project layer resolved to %s, not to %s", p.project, own)
391 }
392 if p.note != "" {
393 t.Fatalf("an ordinary composition said %q", p.note)
394 }
395}
396
397func TestAFloorThatIsNotThereIsRefused(t *testing.T) {
398 // The materialized source, which is the one a test can drive without a
399 // repository. The repository source refuses the same way, and the e2e
400 // observes it there.
401 _, done, err := composed.Floor{Path: t.TempDir()}.Open(context.Background(), "valley-integrator-floor")
402 defer done()
403 if err == nil {
404 t.Fatal("a floor directory with no documents in it was accepted")
405 }
406 if !strings.Contains(err.Error(), composed.Floorless) {
407 t.Fatalf("the refusal reads %q", err)
408 }
409}
410
411// The floor is every *.cue document directly in its directory, whatever
412// its name. Listed one name a line, git quotes a name with non-ASCII
413// characters in it, and the quoted name does not end in .cue, so a floor
414// read that way skipped naïve.cue. The repository sets core.quotePath to
415// the default that quotes, and the document is composed into the
416// catalogue like any other.
417func TestAFloorDocumentWithANonASCIINameIsRead(t *testing.T) {
418 cue, err := exec.LookPath("cue")
419 if err != nil {
420 t.Skip("no cue to compose a policy with; the nix check provides one")
421 }
422 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
423 if err != nil {
424 t.Fatal(err)
425 }
426 s := newScratchRepo(t)
427 s.git("config", "core.quotePath", "true")
428 dir := filepath.Join(s.repo, "policy", "instance")
429 if err := os.MkdirAll(dir, 0o755); err != nil {
430 t.Fatal(err)
431 }
432 for name, body := range map[string]string{
433 "floor.cue": `package verification
434floor: {
435 checks: "c-build": {runner: "nix", attribute: "c-build"}
436 classes: code: {paths: "src/**": true, requires: "c-build": true}
437}
438`,
439 "naïve.cue": `package verification
440floor: checks: "c-lint": {runner: "nix", attribute: "c-lint"}
441`,
442 } {
443 if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
444 t.Fatal(err)
445 }
446 }
447 s.git("add", "policy")
448 s.git("commit", "--quiet", "-m", "the floor")
449
450 p := policySource{
451 schema: schema,
452 cue: cue,
453 layer: composed.Floor{Repo: s.repo, Ref: "refs/heads/main", Dir: "policy/instance"},
454 projectDir: "policy/project",
455 }
456 p, done, err := p.open(&worktree{dir: t.TempDir()})
457 defer done()
458 if err != nil {
459 t.Fatal(err)
460 }
461 cat, _, err := p.catalogue()
462 if err != nil {
463 t.Fatal(err)
464 }
465 if _, ok := cat["c-lint"]; !ok {
466 t.Fatalf("the floor's naïve.cue was not read: the catalogue holds %v", cat)
467 }
468 if _, ok := cat["c-build"]; !ok {
469 t.Fatalf("the floor's floor.cue was not read: the catalogue holds %v", cat)
470 }
471}
472
473func TestARefusalIsReadAsTheSentenceItIs(t *testing.T) {
474 // attest reports what it checked, then refuses, then elaborates. The
475 // sentence is the refusal; the elaboration is not.
476 out := `note /tmp/x.note
477text ok (411 bytes signed)
478attest: tree digest mismatch: the statement is about a different tree
479 recorded aaaa
480 found bbbb
481`
482 if got := refusalLine(out); got != "tree digest mismatch: the statement is about a different tree" {
483 t.Fatalf("refusalLine = %q", got)
484 }
485 if got := refusalLine("something with no prefix at all\n"); got != "something with no prefix at all" {
486 t.Fatalf("refusalLine fallback = %q", got)
487 }
488}