gunk-dev/the-valley

policy_test.go

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