gunk-dev/the-valley

composed_test.go

sourcec14b0e68e9c3main's published tip history
9.7 KiB
1package composed
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "errors"
8 "maps"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14)
15
16// layerRepo is a scratch repository with one commit, whose tree holds the
17// files written into it.
18type layerRepo struct {
19 t *testing.T
20 dir string
21 tip string
22}
23
24func newLayerRepo(t *testing.T, files map[string]string) *layerRepo {
25 t.Helper()
26 if _, err := exec.LookPath("git"); err != nil {
27 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
28 t.Fatal("no git on PATH, and VALLEY_TEST_TOOLS=required")
29 }
30 t.Skip("no git to read a layer with; the composed-unit check provides one")
31 }
32 t.Setenv("HOME", t.TempDir())
33 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
34 r := &layerRepo{t: t, dir: t.TempDir()}
35 r.git("init", "--quiet", "--initial-branch=main")
36 files["README"] = "a repository\n"
37 for path, body := range files {
38 full := filepath.Join(r.dir, path)
39 if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
40 t.Fatal(err)
41 }
42 if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
43 t.Fatal(err)
44 }
45 }
46 r.git("add", "--all")
47 r.git("-c", "user.name=t", "-c", "user.email=t@localhost", "commit", "--quiet", "-m", "layers")
48 r.tip = r.git("rev-parse", "HEAD")
49 return r
50}
51
52func (r *layerRepo) git(args ...string) string {
53 r.t.Helper()
54 cmd := exec.Command("git", args...)
55 cmd.Dir = r.dir
56 var out, errb bytes.Buffer
57 cmd.Stdout, cmd.Stderr = &out, &errb
58 if err := cmd.Run(); err != nil {
59 r.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, errb.String())
60 }
61 return strings.TrimSpace(out.String())
62}
63
64// lose removes the loose object that path names at the tip, so reading it
65// fails as a damaged repository's read does.
66func (r *layerRepo) lose(path string) {
67 r.t.Helper()
68 oid := r.git("rev-parse", r.tip+":"+path)
69 if err := os.Remove(filepath.Join(r.dir, ".git", "objects", oid[:2], oid[2:])); err != nil {
70 r.t.Fatal(err)
71 }
72}
73
74// project is Project of dir at the tip.
75func (r *layerRepo) project(dir string) (docs map[string]string, note string, err error) {
76 r.t.Helper()
77 path, note, done, err := Project(r.t.Context(), r.dir, r.tip, dir, "composed-test-")
78 defer done()
79 if err != nil {
80 if path != "" {
81 r.t.Errorf("a refusal resolved the layer to %s", path)
82 }
83 return nil, note, err
84 }
85 entries, err := os.ReadDir(path)
86 if err != nil {
87 r.t.Fatal(err)
88 }
89 docs = map[string]string{}
90 for _, e := range entries {
91 body, err := os.ReadFile(filepath.Join(path, e.Name()))
92 if err != nil {
93 r.t.Fatal(err)
94 }
95 docs[e.Name()] = string(body)
96 }
97 return docs, note, nil
98}
99
100const addsNothing = "package verification\n"
101
102// A project layer is the *.cue entries directly in its directory at the
103// tip, dotfiles among them. A
104// directory that is not there, or holds no *.cue, composes the floor
105// alone.
106func TestProjectReadsTheLayerAtTheTip(t *testing.T) {
107 r := newLayerRepo(t, map[string]string{
108 "policy/project/a.cue": "package verification // a\n",
109 "policy/project/.hidden.cue": "package verification // hidden\n",
110 "policy/project/notes.md": "not a document\n",
111 "policy/project/sub/b.cue": "package verification // nested\n",
112 "policy/dotted/.only.cue": "package verification // only\n",
113 "policy/prose/notes.md": "not a document\n",
114 })
115 for _, c := range []struct {
116 dir string
117 want map[string]string
118 alone bool
119 }{
120 {"policy/project", map[string]string{"a.cue": "package verification // a\n", ".hidden.cue": "package verification // hidden\n"}, false},
121 // Present, and the composer reads no document in it (layer), so
122 // composing it is refused.
123 {"policy/dotted", map[string]string{".only.cue": "package verification // only\n"}, false},
124 {"policy/missing", map[string]string{"adds-nothing.cue": addsNothing}, true},
125 {"policy/prose", map[string]string{"adds-nothing.cue": addsNothing}, true},
126 {"README", map[string]string{"adds-nothing.cue": addsNothing}, true},
127 } {
128 t.Run(c.dir, func(t *testing.T) {
129 docs, note, err := r.project(c.dir)
130 if err != nil {
131 t.Fatal(err)
132 }
133 if (note != "") != c.alone {
134 t.Errorf("the note reads %q", note)
135 }
136 if !maps.Equal(docs, c.want) {
137 t.Errorf("the layer holds %q, not %q", docs, c.want)
138 }
139 })
140 }
141}
142
143// A directory is named and never matched: policy/proj* is that directory,
144// and not policy/projX beside it.
145func TestProjectReadsADirectoryNamedLikeAPatternAsNamed(t *testing.T) {
146 r := newLayerRepo(t, map[string]string{
147 "policy/proj*/one.cue": "package verification // one\n",
148 "policy/projX/decoy.cue": "package verification // decoy\n",
149 ":(glob)p/decoy.cue": "package verification // magic\n",
150 "p/two.cue": "package verification // two\n",
151 })
152 docs, _, err := r.project("policy/proj*")
153 if err != nil || !maps.Equal(docs, map[string]string{"one.cue": "package verification // one\n"}) {
154 t.Errorf("policy/proj* read as %q, %v", docs, err)
155 }
156 // Pathspec magic is a name like any other.
157 docs, _, err = r.project(":(glob)p")
158 if err != nil || !maps.Equal(docs, map[string]string{"decoy.cue": "package verification // magic\n"}) {
159 t.Errorf(":(glob)p read as %q, %v", docs, err)
160 }
161}
162
163// A layer that cannot be read is refused, never composed as the floor
164// alone: a tip that names a missing object, a layer whose tree is gone, a
165// document whose blob is gone, and a *.cue entry that is a directory,
166// which reading it as a blob refuses.
167func TestProjectRefusesALayerThatCannotBeRead(t *testing.T) {
168 files := map[string]string{
169 "policy/project/a.cue": "package verification\n",
170 "policy/odd/x.cue/inner.cue": "package verification\n",
171 "policy/odd/y.cue": "package verification\n",
172 }
173 cases := []struct {
174 name, dir string
175 damage func(r *layerRepo)
176 }{
177 {"a missing tip", "policy/project", func(r *layerRepo) { r.tip = strings.Repeat("0", len(r.tip)-1) + "1" }},
178 {"the layer's tree lost", "policy/project", func(r *layerRepo) { r.lose("policy/project") }},
179 {"a document's blob lost", "policy/project", func(r *layerRepo) { r.lose("policy/project/a.cue") }},
180 {"a *.cue directory", "policy/odd", func(*layerRepo) {}},
181 }
182 for _, c := range cases {
183 t.Run(c.name, func(t *testing.T) {
184 r := newLayerRepo(t, maps.Clone(files))
185 c.damage(r)
186 docs, note, err := r.project(c.dir)
187 if err == nil {
188 t.Fatalf("an unreadable layer resolved to %q, %q", docs, note)
189 }
190 if note != "" {
191 t.Errorf("a refusal noted %q", note)
192 }
193 for _, want := range []string{c.dir, r.dir, r.tip} {
194 if !strings.Contains(err.Error(), want) {
195 t.Errorf("the refusal %q does not name %s", err, want)
196 }
197 }
198 })
199 }
200}
201
202// A floor that cannot be read is refused as what it is, and not as a floor
203// that is not there, which a reader may look for elsewhere (ErrNoFloor).
204func TestOpenTellsAnUnreadableFloorFromAnAbsentOne(t *testing.T) {
205 files := map[string]string{
206 "policy/instance/floor.cue": "package verification\n",
207 "policy/prose/notes.md": "not a document\n",
208 }
209 for _, c := range []struct {
210 dir string
211 lose string
212 noFloor bool
213 mentioned string
214 }{
215 {"policy/missing", "", true, "has no policy/missing/"},
216 {"policy/prose", "", true, "holds no *.cue in policy/prose/"},
217 {"policy/instance", "policy/instance", false, "reading policy/instance/"},
218 {"policy/instance", "policy/instance/floor.cue", false, "reading policy/instance/floor.cue"},
219 } {
220 t.Run(c.dir+" "+c.lose, func(t *testing.T) {
221 r := newLayerRepo(t, maps.Clone(files))
222 if c.lose != "" {
223 r.lose(c.lose)
224 }
225 dir, done, err := Floor{Repo: r.dir, Ref: "refs/heads/main", Dir: c.dir}.Open(t.Context(), "composed-test-")
226 defer done()
227 if err == nil {
228 t.Fatalf("the floor resolved to %s", dir)
229 }
230 if errors.Is(err, ErrNoFloor) != c.noFloor {
231 t.Errorf("the refusal %q is read as no floor: %v", err, !c.noFloor)
232 }
233 if !strings.Contains(err.Error(), c.mentioned) {
234 t.Errorf("the refusal %q does not say %q", err, c.mentioned)
235 }
236 })
237 }
238}
239
240// The approval requirements are read from the export as cue wrote it. A
241// field left out reads false, and the digest is of the export's bytes, so
242// a policy writing neither digests as its export alone. A field written
243// out reads as written, false included. A value of another kind, a key
244// spelled another way and a key written twice are refused.
245func TestTheApprovalRequirementsAreReadAsExported(t *testing.T) {
246 const opening = `{"checks":{},"classes":{},"unclassified":{}`
247 for _, c := range []struct {
248 export string
249 required, hardware bool
250 }{
251 {opening + `}`, false, false},
252 {opening + `,"approval":{"hardware":true}}`, false, true},
253 {opening + `,"approval":{"required":true}}`, true, false},
254 {opening + `,"approval":{"required":false}}`, false, false},
255 {opening + `,"approval":{"hardware":false,"required":true}}`, true, false},
256 } {
257 pol, err := readExport([]byte(c.export))
258 if err != nil {
259 t.Errorf("%s: %v", c.export, err)
260 continue
261 }
262 if pol.RequiredApproval != c.required || pol.HardwareApproval != c.hardware {
263 t.Errorf("%s reads RequiredApproval %v and HardwareApproval %v", c.export, pol.RequiredApproval, pol.HardwareApproval)
264 }
265 if sum := sha256.Sum256([]byte(c.export)); pol.Digest != hex.EncodeToString(sum[:]) {
266 t.Errorf("%s digests as %s, not as its bytes", c.export, pol.Digest)
267 }
268 }
269 for _, c := range []struct{ export, says string }{
270 {opening + `,"approval":{"required":"yes"}}`, "policy.approval.required is not a bool"},
271 {opening + `,"approval":{"Required":true}}`, `policy.approval has a field "Required" the schema does not give it`},
272 {opening + `,"approval":{"required":true,"required":false}}`, `policy.approval holds the key "required" twice`},
273 } {
274 if pol, err := readExport([]byte(c.export)); err == nil || !strings.Contains(err.Error(), c.says) {
275 t.Errorf("%s read as %+v, %v, not %q", c.export, pol, err, c.says)
276 }
277 }
278}