gunk-dev/the-valley

policy_test.go

source08dfaa862db7main's published tip history
11.9 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 report of a diff with nothing in it is still a whole report, and it
175// requires nothing.
176func TestAnEmptyDiffReadsAsRequiringNothing(t *testing.T) {
177 d, err := parseDerived(`abc1234..abc1234: 0 changed path(s)
178policy: instance + policy
179classes matched: none
180carry mode: same-paths
181
182required checks: none
183`)
184 if err != nil {
185 t.Fatal(err)
186 }
187 if d.paths != 0 || len(d.classes) != 0 || len(d.requires) != 0 || d.carry != "same-paths" {
188 t.Fatalf("an empty diff reads as %+v", d)
189 }
190}
191
192// A report of no changed paths is believed only when git agrees. The
193// stand-in deriver prints a whole, well-formed report of no changed paths โ€”
194// what a deriver whose diff failed silently would print โ€” and the
195// derivation is read over two commits with one tree, and refused over two
196// commits whose trees differ.
197func TestAReportOfNoChangedPathsIsCheckedAgainstGit(t *testing.T) {
198 repo := t.TempDir()
199 run := func(args ...string) string {
200 t.Helper()
201 out, err := git(repo, append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
202 if err != nil {
203 t.Fatal(err)
204 }
205 return strings.TrimSpace(out)
206 }
207 run("init", "--quiet")
208 run("commit", "--quiet", "--allow-empty", "-m", "one")
209 one := run("rev-parse", "HEAD")
210 run("commit", "--quiet", "--allow-empty", "-m", "the same tree")
211 same := run("rev-parse", "HEAD")
212 if err := os.WriteFile(filepath.Join(repo, "changed.txt"), []byte("x\n"), 0o644); err != nil {
213 t.Fatal(err)
214 }
215 run("add", "changed.txt")
216 run("commit", "--quiet", "-m", "a change")
217 changed := run("rev-parse", "HEAD")
218
219 deriver := filepath.Join(t.TempDir(), "valley")
220 report := `printf '%s\n' 'x..y: 0 changed path(s)' 'policy: a + b' 'classes matched: none' 'carry mode: same-paths' '' 'required checks: none'`
221 if err := os.WriteFile(deriver, []byte("#!/bin/sh\n"+report+"\n"), 0o755); err != nil {
222 t.Fatal(err)
223 }
224 p := policySource{valley: deriver}
225 tip := &worktree{dir: repo}
226 if _, err := p.derive(tip, one, same); err != nil {
227 t.Fatalf("an empty diff reported as empty was refused: %v", err)
228 }
229 if d, err := p.derive(tip, one, changed); err == nil {
230 t.Fatalf("a change reported as touching nothing was read as %+v", d)
231 }
232}
233
234// The policy digest is of the whole composed policy, so a class's carry
235// mode and the restacker's cap are in it as much as a check is. The layers
236// are composed by the real cue under the real schema, with the floor fixed
237// and the project layer varied.
238func TestThePolicyDigestCoversCarryAndTheCap(t *testing.T) {
239 cue, err := exec.LookPath("cue")
240 if err != nil {
241 t.Skip("no cue to compose a policy with; the nix check provides one")
242 }
243 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
244 if err != nil {
245 t.Fatal(err)
246 }
247 const floor = `package verification
248floor: {
249 checks: "c-build": {runner: "nix", attribute: "c-build"}
250 classes: code: {paths: "src/**": true, requires: "c-build": true}
251}
252`
253 digest := func(project string) string {
254 t.Helper()
255 p := policySource{schema: schema, cue: cue, instance: t.TempDir(), project: t.TempDir()}
256 if err := os.WriteFile(filepath.Join(p.instance, "floor.cue"), []byte(floor), 0o644); err != nil {
257 t.Fatal(err)
258 }
259 if err := os.WriteFile(filepath.Join(p.project, "policy.cue"), []byte("package verification\n"+project), 0o644); err != nil {
260 t.Fatal(err)
261 }
262 _, sum, err := p.catalogue()
263 if err != nil {
264 t.Fatal(err)
265 }
266 return sum
267 }
268
269 base := digest("")
270 if again := digest(""); again != base {
271 t.Fatalf("one policy digested twice gave %s and %s", base, again)
272 }
273 // The digest is of the composition, not of the text: writing the cap's
274 // default composes the same policy.
275 if same := digest("project: restack: maxAutomaticVersions: 64\n"); same != base {
276 t.Errorf("writing the default cap moved the digest from %s to %s", base, same)
277 }
278 seen := map[string]string{base: "the floor alone"}
279 for _, c := range []struct{ name, project string }{
280 {"a class asking for same-class", `project: classes: code: carry: "same-class": true` + "\n"},
281 {"a class asking for exact", "project: classes: code: carry: exact: true\n"},
282 {"a lower cap", "project: restack: maxAutomaticVersions: 16\n"},
283 } {
284 sum := digest(c.project)
285 if other, ok := seen[sum]; ok {
286 t.Errorf("%s digests the same as %s: %s", c.name, other, sum)
287 }
288 seen[sum] = c.name
289 }
290}
291
292func TestValidityWindowsAreReadAsThePolicyWritesThem(t *testing.T) {
293 for _, c := range []struct {
294 in string
295 want time.Duration
296 }{
297 {"", 0},
298 {"30s", 30 * time.Second},
299 {"15m", 15 * time.Minute},
300 {"6h", 6 * time.Hour},
301 {"2d", 48 * time.Hour},
302 } {
303 got, err := parseWindow(c.in)
304 if err != nil || got != c.want {
305 t.Errorf("parseWindow(%q) = %v, %v; want %v", c.in, got, err, c.want)
306 }
307 }
308}
309
310// Each layer's absence defaults in the safe direction of that layer's job,
311// and the two directions are opposite (dcr-f41f718). Both are pinned here,
312// because the value of the rule is that neither is the other.
313
314func TestATargetWithNoProjectLayerIsJudgedUnderTheFloorAlone(t *testing.T) {
315 tip := &worktree{dir: t.TempDir()}
316 p := policySource{projectDir: "policy/project"}
317 done, err := p.openProject(tip)
318 if err != nil {
319 t.Fatal(err)
320 }
321 defer done()
322 if p.note == "" {
323 t.Fatal("the pass said nothing about composing the floor alone")
324 }
325 // What the deriver and the composer are handed is a layer that adds
326 // nothing, not a directory that is not there.
327 docs, err := filepath.Glob(filepath.Join(p.project, "*.cue"))
328 if err != nil || len(docs) != 1 {
329 t.Fatalf("the resolved project layer holds %v (%v)", docs, err)
330 }
331 if body, err := os.ReadFile(docs[0]); err != nil || strings.TrimSpace(string(body)) != "package verification" {
332 t.Fatalf("the layer that adds nothing reads %q (%v)", body, err)
333 }
334 done()
335 if _, err := os.Stat(p.project); !os.IsNotExist(err) {
336 t.Fatalf("the pass left its scratch layer behind: %v", err)
337 }
338}
339
340func TestATargetsOwnProjectLayerIsUsedWhereItIs(t *testing.T) {
341 tip := &worktree{dir: t.TempDir()}
342 own := filepath.Join(tip.dir, "policy/project")
343 if err := os.MkdirAll(own, 0o755); err != nil {
344 t.Fatal(err)
345 }
346 if err := os.WriteFile(filepath.Join(own, "policy.cue"), []byte("package verification\n"), 0o644); err != nil {
347 t.Fatal(err)
348 }
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.project != own {
356 t.Fatalf("the project layer resolved to %s, not to %s", p.project, own)
357 }
358 if p.note != "" {
359 t.Fatalf("an ordinary composition said %q", p.note)
360 }
361}
362
363func TestAFloorThatIsNotThereIsRefused(t *testing.T) {
364 // The materialized source, which is the one a test can drive without a
365 // repository. The repository source refuses the same way, and the e2e
366 // observes it there.
367 _, done, err := instanceLayer{path: t.TempDir()}.open()
368 defer done()
369 if err == nil {
370 t.Fatal("a floor directory with no documents in it was accepted")
371 }
372 if !strings.Contains(err.Error(), floorless) {
373 t.Fatalf("the refusal reads %q", err)
374 }
375}
376
377func TestARefusalIsReadAsTheSentenceItIs(t *testing.T) {
378 // attest reports what it checked, then refuses, then elaborates. The
379 // sentence is the refusal; the elaboration is not.
380 out := `note /tmp/x.note
381text ok (411 bytes signed)
382attest: tree digest mismatch: the statement is about a different tree
383 recorded aaaa
384 found bbbb
385`
386 if got := refusalLine(out); got != "tree digest mismatch: the statement is about a different tree" {
387 t.Fatalf("refusalLine = %q", got)
388 }
389 if got := refusalLine("something with no prefix at all\n"); got != "something with no prefix at all" {
390 t.Fatalf("refusalLine fallback = %q", got)
391 }
392}