gunk-dev/the-valley

policy_test.go

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