gunk-dev/the-valley

policy_test.go

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