gunk-dev/the-valley

model_test.go

source828de97497f3main's published tip history
13.8 KiB
1package derive
2
3import (
4 "fmt"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "reflect"
9 "strings"
10 "testing"
11
12 "the-valley/composed"
13)
14
15// TestReadReadsTheWholePolicy holds composed.Read to what a policy says:
16// each check's runner, attribute or command, validity and cost; each
17// class's paths, requirements, pins and carry mode, with what a project
18// turned off left out; and the digest Compose gives the same layers.
19func TestReadReadsTheWholePolicy(t *testing.T) {
20 r := newRig(t)
21 l := newLayers(t, r.glob(t, "examples/policy/instance/*.cue"), r.glob(t, "examples/policy/project/*.cue"), map[string]string{
22 "live.cue": `package verification
23project: checks: "smoke-live": {runner: "command", command: "curl -fsS https://example.org/health", validity: "15m", cost: "slow"}
24project: classes: live: {paths: "deploy/**": true, requires: "smoke-live": true, carry: exact: true}
25`})
26 m, err := r.read(l)
27 if err != nil {
28 t.Fatal(err)
29 }
30 checks := map[string]composed.Check{
31 "prose-format": {Runner: "nix", Attribute: "prose-format", Cost: "quick"},
32 "link-check": {Runner: "nix", Attribute: "link-check", Cost: "quick"},
33 "knowledge-lint": {Runner: "nix", Attribute: "knowledge-lint", Cost: "quick"},
34 "shellcheck": {Runner: "nix", Attribute: "shellcheck", Cost: "quick"},
35 "install-vm": {Runner: "nix", Attribute: "install-vm", Cost: "slow"},
36 "smoke-live": {Runner: "command", Command: "curl -fsS https://example.org/health", Validity: "15m", Cost: "slow"},
37 }
38 if !reflect.DeepEqual(m.Checks, checks) {
39 t.Errorf("checks = %+v", m.Checks)
40 }
41 classes := map[string]composed.Class{
42 "prose": {Paths: []string{"**/*.md"}, Requires: map[string]composed.Pin{"prose-format": composed.Mandatory, "link-check": composed.Mandatory}, Carry: "same-paths"},
43 // The template offers the lint as a default and the project turns
44 // it off, so the class requires nothing.
45 "knowledge": {Paths: []string{".the-valley/**"}, Requires: map[string]composed.Pin{}, Carry: "same-paths"},
46 "scripts": {Paths: []string{"bin/**"}, Requires: map[string]composed.Pin{"shellcheck": composed.Mandatory, "install-vm": composed.Mandatory}, Carry: "same-paths"},
47 "live": {Paths: []string{"deploy/**"}, Requires: map[string]composed.Pin{"smoke-live": composed.Mandatory}, Carry: "exact"},
48 }
49 if !reflect.DeepEqual(m.Classes, classes) {
50 t.Errorf("classes = %+v", m.Classes)
51 }
52 if want := map[string]composed.Pin{"prose-format": composed.Mandatory}; !reflect.DeepEqual(m.Unclassified, want) {
53 t.Errorf("unclassified = %+v", m.Unclassified)
54 }
55 pol, err := composed.Compose(t.Context(), r.cue, r.schema, l.instance, l.project)
56 if err != nil {
57 t.Fatal(err)
58 }
59 if m.Digest != pol.Digest || len(m.Digest) != 64 {
60 t.Errorf("Read's digest %q is not Compose's %q", m.Digest, pol.Digest)
61 }
62
63 // The template's default, left alone, is a default.
64 tmpl := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil)
65 if m, err = r.read(tmpl); err != nil {
66 t.Fatal(err)
67 }
68 if got := m.Classes["docs"].Requires; got["c-tmpl"] != composed.Default || got["c-docs"] != composed.Mandatory {
69 t.Errorf("docs requires %v", got)
70 }
71}
72
73// TestReadRefuses holds composed.Read to refusing what it cannot read
74// whole: no schema, a layer with no documents, and a layer that does not
75// compose.
76func TestReadRefuses(t *testing.T) {
77 r := newRig(t)
78 good := newLayers(t, r.glob(t, "examples/policy/smoke/instance/*.cue"), nil, nil)
79 empty := layers{instance: t.TempDir(), project: good.project}
80 broken := newLayers(t, r.glob(t, "examples/policy/smoke/instance/*.cue"), nil, map[string]string{"broken.cue": "package verification\nproject: classes: x: requires: nothing: true\n"})
81 for _, c := range []struct {
82 name, schema string
83 l layers
84 says string
85 }{
86 {"no schema", r.path("schema/absent.cue"), good, "no policy schema at"},
87 {"an empty floor", r.schema, empty, "no policy layer at"},
88 {"a layer that does not compose", r.schema, broken, "do not compose"},
89 } {
90 if _, err := composed.Read(t.Context(), r.cue, c.schema, c.l.instance, c.l.project); err == nil || !strings.Contains(err.Error(), c.says) {
91 t.Errorf("%s: %v, not %q", c.name, err, c.says)
92 }
93 }
94}
95
96// TestTheHardwareRequirementIsRead holds Compose and Read to
97// approval.hardware as cue composes it, over the fixtures under
98// examples/policy/approval/. A floor's `true` and a project's `true` both
99// require a hardware key. A template default the project turned off and a
100// policy that never mentions approval do not. A project's `false` against
101// the floor's `true` is refused, rather than read as either.
102func TestTheHardwareRequirementIsRead(t *testing.T) {
103 r := newRig(t)
104 fixture := func(name string) layers {
105 return newLayers(t, []string{r.path("examples/policy/approval/" + name + ".cue")}, nil, nil)
106 }
107 for _, c := range []struct {
108 fixture string
109 want bool
110 }{
111 {"floor-requires-hardware", true},
112 {"project-requires-hardware", true},
113 {"template-default-declined", false},
114 {"no-requirement", false},
115 } {
116 l := fixture(c.fixture)
117 pol, err := composed.Compose(t.Context(), r.cue, r.schema, l.instance, l.project)
118 if err != nil {
119 t.Fatalf("%s: %v", c.fixture, err)
120 }
121 m, err := r.read(l)
122 if err != nil {
123 t.Fatalf("%s: %v", c.fixture, err)
124 }
125 if pol.HardwareApproval != c.want || m.HardwareApproval != c.want {
126 t.Errorf("%s: Compose reads HardwareApproval %v and Read %v, not %v", c.fixture, pol.HardwareApproval, m.HardwareApproval, c.want)
127 }
128 }
129
130 l := fixture("rejected/project-drops-floor-hardware")
131 if pol, err := composed.Compose(t.Context(), r.cue, r.schema, l.instance, l.project); err == nil || !strings.Contains(err.Error(), "policy.approval.hardware") {
132 t.Errorf("a project dropping the floor's hardware requirement composed to %+v, %v", pol, err)
133 }
134 if m, err := r.read(l); err == nil || !strings.Contains(err.Error(), "policy.approval.hardware") {
135 t.Errorf("a project dropping the floor's hardware requirement was read as %+v, %v", m, err)
136 }
137}
138
139// TestAReopenedDefinitionIsRefused holds Compose and Read to refusing an
140// export with a field the schema does not give. Every document of a policy
141// is in one package, so any of them may reopen a schema definition and add
142// a field to it. In the cross-family review's case, the floor writes
143// `hardware: true`, and a project adds `Hardware` to #Policy's approval and
144// writes it false. cue exports both keys, and a reader matching names
145// without regard to case would read whichever comes last.
146//
147// cue unifies the documents in any order, and cannot tell which layer a
148// field came from. The order changes only the order of the keys in the
149// export. So the three documents are composed in every order: the first
150// as the floor layer's document, the other two as the project layer's.
151func TestAReopenedDefinitionIsRefused(t *testing.T) {
152 r := newRig(t)
153 const floor = `package verification
154floor: checks: "c-build": {runner: "nix", attribute: "c-build"}
155floor: classes: code: {paths: "src/**": true, requires: "c-build": true}
156floor: approval: hardware: true
157`
158 docs := []string{floor, "package verification\n#Policy: approval: {Hardware?: bool}\n",
159 "package verification\nproject: approval: {hardware: true, Hardware: false}\n"}
160 layered := func(first string, rest ...string) layers {
161 extra := map[string]string{}
162 for i, doc := range rest {
163 extra[string(rune('a'+i))+".cue"] = doc
164 }
165 l := newLayers(t, nil, nil, extra)
166 if err := os.WriteFile(filepath.Join(l.instance, "a.cue"), []byte(first), 0o644); err != nil {
167 t.Fatal(err)
168 }
169 return l
170 }
171 refused := func(name string, l layers, says string) {
172 t.Helper()
173 if pol, err := composed.Compose(t.Context(), r.cue, r.schema, l.instance, l.project); err == nil || !strings.Contains(err.Error(), says) {
174 t.Errorf("%s: Compose read %+v, %v, not %q", name, pol, err, says)
175 }
176 if m, err := r.read(l); err == nil || !strings.Contains(err.Error(), says) {
177 t.Errorf("%s: Read read %+v, %v, not %q", name, m, err, says)
178 }
179 }
180 for _, o := range [][3]int{{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}} {
181 refused("documents in order "+fmt.Sprint(o), layered(docs[o[0]], docs[o[1]], docs[o[2]]),
182 `policy.approval has a field "Hardware" the schema does not give it`)
183 }
184
185 // The same trick at the other objects the reader reads into a struct.
186 for _, c := range []struct{ name, doc, says string }{
187 {"an Approval beside approval", "#Policy: Approval?: {hardware?: bool}\nproject: Approval: hardware: false\n", `policy has a field "Approval"`},
188 {"a check's Runner", "#Check: Runner?: string\nproject: checks: \"c-build\": {runner: \"nix\", attribute: \"c-build\", Runner: \"command\"}\n", `policy.checks.c-build has a field "Runner"`},
189 {"a class's Requires", "#Class: Requires?: [string]: bool\nproject: classes: code: Requires: \"c-build\": false\n", `policy.classes.code has a field "Requires"`},
190 } {
191 refused(c.name, layered(floor, "package verification\n"+c.doc), c.says)
192 }
193
194 // cue cannot export a value of the wrong kind under the schema, so a
195 // stand-in for cue prints one. encoding/json would read the cap written
196 // as a string as a number.
197 bash, err := exec.LookPath("bash")
198 if err != nil {
199 t.Fatal(err)
200 }
201 l := layered(floor)
202 for _, c := range []struct{ name, export, says string }{
203 {"a requirement written as a string", `"approval":{"hardware":"false"}`, "policy.approval.hardware is not a bool"},
204 {"a cap written as a string", `"restack":{"maxAutomaticVersions":"64"}`, "policy.restack.maxAutomaticVersions is not a number"},
205 } {
206 cue := filepath.Join(t.TempDir(), "cue")
207 script := "#!" + bash + "\nprintf '%s' '{\"checks\":{},\"classes\":{},\"unclassified\":{}," + c.export + "}'\n"
208 if err := os.WriteFile(cue, []byte(script), 0o755); err != nil {
209 t.Fatal(err)
210 }
211 if pol, err := composed.Compose(t.Context(), cue, r.schema, l.instance, l.project); err == nil || !strings.Contains(err.Error(), c.says) {
212 t.Errorf("%s: Compose read %+v, %v, not %q", c.name, pol, err, c.says)
213 }
214 }
215}
216
217// TestDeriveOverAModel holds Derive's own rules, over a policy written
218// here rather than composed: the strictest carry mode among the matched
219// classes, a pin that is mandatory where any requirement of it is, a
220// class named unclassified kept apart from the unclassified set, and a
221// requirement of a check the policy does not define refused.
222func TestDeriveOverAModel(t *testing.T) {
223 nix := composed.Check{Runner: "nix", Cost: "quick"}
224 m := &composed.Model{
225 Policy: composed.Policy{Checks: map[string]composed.Check{"a": nix, "b": nix, "u": nix}},
226 Classes: map[string]composed.Class{
227 "loose": {Paths: []string{"loose/**"}, Requires: map[string]composed.Pin{"a": composed.Default}, Carry: "same-paths"},
228 "strict": {Paths: []string{"strict/*"}, Requires: map[string]composed.Pin{"a": composed.Mandatory, "b": composed.Default}, Carry: "same-class"},
229 "unclassified": {Paths: []string{"odd"}, Requires: map[string]composed.Pin{"b": composed.Default}, Carry: "exact"},
230 },
231 Unclassified: map[string]composed.Pin{"u": composed.Mandatory},
232 }
233 res, err := Derive(m, []string{"strict/x", "loose/y/z", "strict/x", "elsewhere"})
234 if err != nil {
235 t.Fatal(err)
236 }
237 want := &Result{
238 Paths: []string{"elsewhere", "loose/y/z", "strict/x"},
239 Classes: []string{"loose", "strict"},
240 Unclassified: []string{"elsewhere"},
241 Carry: "same-class",
242 Required: []Required{
243 {Name: "a", Classes: []string{"loose", "strict"}, Pin: composed.Mandatory, Check: nix},
244 {Name: "b", Classes: []string{"strict"}, Pin: composed.Default, Check: nix},
245 {Name: "u", Classes: []string{}, Unclassified: true, Pin: composed.Mandatory, Check: nix},
246 },
247 }
248 if !reflect.DeepEqual(res, want) {
249 t.Errorf("Derive = %+v\nwant %+v", res, want)
250 }
251 if res, err = Derive(m, []string{"odd"}); err != nil || res.Carry != "exact" || len(res.Required) != 1 || res.Required[0].Name != "b" || res.Required[0].Unclassified {
252 t.Errorf("the class named unclassified derives %+v, %v", res, err)
253 }
254 if res, err = Derive(m, nil); err != nil || res.Carry != "same-paths" || len(res.Required) != 0 {
255 t.Errorf("no paths derive %+v, %v", res, err)
256 }
257 m.Unclassified["ghost"] = composed.Mandatory
258 if _, err := Derive(m, []string{"elsewhere"}); err == nil || !strings.Contains(err.Error(), "defines no check") {
259 t.Errorf("a requirement of an undefined check derived: %v", err)
260 }
261}
262
263// TestChangedRefusesWhatGitDoesNotWrite holds Changed to a record cut
264// anywhere, and to the records git never writes.
265func TestChangedRefusesWhatGitDoesNotWrite(t *testing.T) {
266 got, err := Changed([]byte("R087\x00old\x00new\x00D\x00gone\nwith a newline\x00M\x00caf\xe9\x00"))
267 if want := []string{"old", "new", "gone\nwith a newline", "caf\xe9"}; err != nil || !reflect.DeepEqual(got, want) {
268 t.Errorf("Changed = %q, %v", got, err)
269 }
270 for _, out := range []string{"M", "M\x00", "M\x00a", "R100\x00old\x00", "M\x00a\x00R1", "Z\x00a\x00", "M\x00\x00", "\x00a\x00", "R1x\x00a\x00b\x00"} {
271 if got, err := Changed([]byte(out)); err == nil {
272 t.Errorf("Changed(%q) = %q", out, got)
273 }
274 }
275}
276
277// TestMatch is the glob language by example.
278func TestMatch(t *testing.T) {
279 for _, c := range []struct {
280 glob, path string
281 want bool
282 }{
283 {"src/*.rs", "src/one.rs", true},
284 {"src/*.rs", "src/deep/two.rs", false},
285 {"src/**/*.rs", "src/one.rs", true},
286 {"src/**/*.rs", "src/deep/two.rs", true},
287 {"a/**/b", "a/b", true},
288 {"a/**/b", "a/x/y/b", true},
289 {"a/**/b", "ab", false},
290 {"docs/**", "docs/x/y", true},
291 {"docs/**", "docs", false},
292 {"**/*.md", "README.md", true},
293 {"**/*.md", "a/b/c.md", true},
294 {"**", "", true},
295 {"a**b", "a/b", false},
296 {"a**b", "axxb", true},
297 {"?", "é", false}, // two bytes
298 {"??", "é", true},
299 {"?", "/", false},
300 {"*", "a\nb", true},
301 {"c.(x)", "c.(x)", true},
302 {"c.(x)", "cx(x)", false},
303 {"docs/", "docs", true}, // one trailing slash is dropped
304 {"docs//", "docs/", true},
305 } {
306 if got := Match(c.glob, c.path); got != c.want {
307 t.Errorf("Match(%q, %q) = %v", c.glob, c.path, got)
308 }
309 }
310}