gunk-dev/the-valley

read_test.go

sourceb75ff006984dmain's published tip history
18.5 KiB
1package readaccess
2
3import (
4 "context"
5 "encoding/hex"
6 "errors"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "reflect"
11 "sort"
12 "strings"
13 "testing"
14 "time"
15)
16
17// The tests read consents and grants out of real commits with real git,
18// under the real schemas with the real cue.
19
20const (
21 idApp = "9da6809f038df92138c131cd16bed76d"
22 idSite = "273d5668702918ea7ae079de374db96b"
23 // idOther is another project's identity, under app's name.
24 idOther = "f83927d5a4ed068cdd02a8cdaa09f26d"
25
26 destination = "example.org"
27 key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKeyForARejectedFixtureAAAAAAAAAAA"
28)
29
30var day = time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC)
31
32func needTool(t *testing.T, name string) {
33 t.Helper()
34 if _, err := exec.LookPath(name); err != nil {
35 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
36 t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", name)
37 }
38 t.Skipf("no %s on PATH; the nix check provides one", name)
39 }
40}
41
42// repo is a bare repository for one test, with the schemas to read it under.
43type repo struct {
44 t *testing.T
45 dir string
46 reader *Reader
47}
48
49func newRepo(t *testing.T) *repo {
50 t.Helper()
51 needTool(t, "git")
52 needTool(t, "cue")
53 root := t.TempDir()
54 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
55 t.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(root, "gitconfig"))
56 t.Setenv("HOME", root)
57 r := &repo{t: t, dir: filepath.Join(root, "repo.git"), reader: &Reader{
58 ReadSchema: schema(t, "read.cue"), IdentitySchema: schema(t, "identity.cue")}}
59 r.git("", "init", "--quiet", "--bare", r.dir)
60 return r
61}
62
63func schema(t *testing.T, name string) string {
64 t.Helper()
65 path, err := filepath.Abs(filepath.Join("..", "schema", name))
66 if err != nil {
67 t.Fatal(err)
68 }
69 return path
70}
71
72func (r *repo) git(stdin string, args ...string) string {
73 r.t.Helper()
74 cmd := exec.Command("git", args...)
75 if r.dir != "" && args[0] != "init" {
76 cmd = exec.Command("git", append([]string{"-C", r.dir}, args...)...)
77 }
78 cmd.Stdin = strings.NewReader(stdin)
79 out, err := cmd.Output()
80 if err != nil {
81 var stderr []byte
82 if exit, ok := err.(*exec.ExitError); ok {
83 stderr = exit.Stderr
84 }
85 r.t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, stderr)
86 }
87 return strings.TrimSpace(string(out))
88}
89
90// tree writes a tree holding the files, by path, and returns it.
91func (r *repo) tree(files map[string]string) string {
92 r.t.Helper()
93 dirs := map[string]map[string]string{}
94 var listing []string
95 for path, body := range files {
96 first, rest, nested := strings.Cut(path, "/")
97 if nested {
98 if dirs[first] == nil {
99 dirs[first] = map[string]string{}
100 }
101 dirs[first][rest] = body
102 continue
103 }
104 listing = append(listing, "100644 blob "+r.git(body, "hash-object", "-w", "--stdin")+"\t"+first)
105 }
106 for name, sub := range dirs {
107 listing = append(listing, "040000 tree "+r.tree(sub)+"\t"+name)
108 }
109 sort.Strings(listing)
110 return r.git(strings.Join(listing, "\n")+"\n", "mktree")
111}
112
113// commit writes a commit whose tree holds the files, and returns it.
114func (r *repo) commit(files map[string]string) string {
115 r.t.Helper()
116 return r.commitTree(r.tree(files))
117}
118
119func (r *repo) commitTree(tree string) string {
120 r.t.Helper()
121 return r.git("", "-c", "user.name=test", "-c", "user.email=test@example.org", "commit-tree", tree, "-m", "test")
122}
123
124// policy is a policy/read for app with the readers given.
125func policy(body string) map[string]string {
126 return map[string]string{"policy/read/read.cue": "package read\n\n" + body + "\n"}
127}
128
129func appPolicy(readers string) map[string]string {
130 return policy(`project: "app"
131identity: "` + idApp + `"
132readers: {` + readers + `}`)
133}
134
135// registry is a registry with a genesis entry, root, that governs it, and an
136// edge read boundary, web, at example.org, with more after it.
137func registry(more string) map[string]string {
138 return map[string]string{"identity/registry.cue": `package identity
139
140boundaries: {
141 registry: kind: "registry"
142 push: kind: "git-push"
143 web: {kind: "edge-read", destination: "` + destination + `"}
144}
145genesis: "root"
146principals: root: {
147 kind: "human"
148 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
149 grants: govern: boundary: "registry"
150}
151` + more + "\n"}
152}
153
154// reader is a principal entry holding the read grant given.
155func reader(name, projects string) string {
156 return `principals: "` + name + `": {
157 kind: "human"
158 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
159 grants: read: {boundary: "web", projects: ` + projects + `}
160}`
161}
162
163func (r *repo) consent(files map[string]string, project string) (Consent, error) {
164 r.t.Helper()
165 return r.reader.Consent(context.Background(), r.dir, r.commit(files), project)
166}
167
168func (r *repo) grants(files map[string]string) (Grants, error) {
169 r.t.Helper()
170 return r.reader.Grants(context.Background(), r.dir, r.commit(files), "identity", destination, day)
171}
172
173func mustInvalid(t *testing.T, what string, err error) {
174 t.Helper()
175 var bad *InvalidError
176 if !errors.As(err, &bad) {
177 t.Errorf("%s: got %v, want an invalid document", what, err)
178 }
179}
180
181// A principal reads a project only where both consents say so: the
182// project's policy/read names it, and a read grant at the destination
183// covers the project with the identity the policy declares.
184func TestBothConsents(t *testing.T) {
185 r := newRepo(t)
186 g, err := r.grants(registry(`anyone: grants: read: {boundary: "web", projects: app: "` + idApp + `"}
187` + reader("alice", `"all"`) + "\n" + reader("bob", `{app: "`+idOther+`"}`)))
188 if err != nil {
189 t.Fatal(err)
190 }
191 cases := []struct {
192 readers string
193 want []string
194 }{
195 {"anyone: true, alice: true, bob: true", []string{"alice", "anyone"}},
196 {"alice: true", []string{"alice"}},
197 {"anyone: true", []string{"anyone"}},
198 {"bob: true, carol: true", nil},
199 }
200 for _, c := range cases {
201 consent, err := r.consent(appPolicy(c.readers), "app")
202 if err != nil {
203 t.Fatalf("%s: %v", c.readers, err)
204 }
205 if got := g.Readers(consent); !reflect.DeepEqual(got, c.want) {
206 t.Errorf("readers {%s}: the effective readers are %v, want %v", c.readers, got, c.want)
207 }
208 for _, p := range []string{Anyone, "alice", "bob", "carol"} {
209 want := false
210 for _, w := range c.want {
211 want = want || w == p
212 }
213 if got := g.May(p, consent); got != want {
214 t.Errorf("readers {%s}: May(%s) is %v, want %v", c.readers, p, got, want)
215 }
216 }
217 }
218
219 // The instance's grant to anyone alone does not let anyone read a
220 // project whose policy does not name anyone, and the policy alone does
221 // not either.
222 consent, err := r.consent(appPolicy("anyone: true"), "app")
223 if err != nil {
224 t.Fatal(err)
225 }
226 none, err := r.grants(registry(""))
227 if err != nil {
228 t.Fatal(err)
229 }
230 if none.May(Anyone, consent) || len(none) != 0 {
231 t.Errorf("a registry with no read grant lets anyone read: %v", none)
232 }
233}
234
235// An empty reader set and an empty scope are valid, and let no one read.
236func TestExplicitEmptySets(t *testing.T) {
237 r := newRepo(t)
238 consent, err := r.consent(appPolicy(""), "app")
239 if err != nil {
240 t.Fatal(err)
241 }
242 if len(consent.Readers) != 0 {
243 t.Errorf("an empty reader set reads as %v", consent.Readers)
244 }
245 g, err := r.grants(registry(`anyone: grants: read: {boundary: "web", projects: {}}`))
246 if err != nil {
247 t.Fatal(err)
248 }
249 if len(g[Anyone]) != 1 || g.Covers(Anyone, "app", idApp) || g.Selects(Anyone, "app") {
250 t.Errorf("an empty scope reads as %+v", g)
251 }
252
253 // A policy with no reader set at all is not an empty one: it consents
254 // to nothing, and says so.
255 _, err = r.consent(policy(`project: "app"
256identity: "`+idApp+`"`), "app")
257 mustInvalid(t, "a policy with no readers field", err)
258}
259
260// anyone holds read grants alone, as a variant of its own: no entry under
261// principals and no key. (That it is never genesis is the identity-schema
262// check's genesis-is-anyone.) No principal name is special to the
263// evaluator: operator reads by the same rules as alice.
264func TestAnyoneRestrictions(t *testing.T) {
265 r := newRepo(t)
266 for what, more := range map[string]string{
267 "anyone holding a push grant": `anyone: grants: push: boundary: "push"`,
268 "anyone holding registry": `anyone: grants: govern: boundary: "registry"`,
269 "anyone holding a key": `anyone: {keys: [{class: "ssh-ed25519", bound: "host", public: "` + key + `"}], grants: {}}`,
270 "anyone named under principals": strings.Replace(reader("anyone", `"all"`), "grants: read", "grants: push", 1),
271 } {
272 _, err := r.grants(registry(more))
273 mustInvalid(t, what, err)
274 }
275
276 g, err := r.grants(registry(reader("operator", `"all"`) + "\n" + reader("alice", `"all"`)))
277 if err != nil {
278 t.Fatal(err)
279 }
280 for _, readers := range []string{"operator: true", "alice: true"} {
281 consent, err := r.consent(appPolicy(readers), "app")
282 if err != nil {
283 t.Fatal(err)
284 }
285 if got := g.Readers(consent); len(got) != 1 {
286 t.Errorf("readers {%s}: the effective readers are %v", readers, got)
287 }
288 }
289 consent, err := r.consent(appPolicy("alice: true"), "app")
290 if err != nil {
291 t.Fatal(err)
292 }
293 if g.May("operator", consent) {
294 t.Errorf("operator reads a project whose policy does not name operator, under an all-project grant")
295 }
296}
297
298// A policy is for the project it names, and an explicit grant is for the
299// identity it names. A policy read from another project, or a project
300// whose identity is not the grant's, is not read.
301func TestProjectIdentityMismatch(t *testing.T) {
302 r := newRepo(t)
303 _, err := r.consent(appPolicy("anyone: true"), "site")
304 mustInvalid(t, "app's policy read from site", err)
305
306 g, err := r.grants(registry(`anyone: grants: read: {boundary: "web", projects: app: "` + idOther + `"}`))
307 if err != nil {
308 t.Fatal(err)
309 }
310 consent, err := r.consent(appPolicy("anyone: true"), "app")
311 if err != nil {
312 t.Fatal(err)
313 }
314 if g.May(Anyone, consent) {
315 t.Errorf("a grant for app under another identity lets anyone read app")
316 }
317 if !g.Selects(Anyone, "app") || g.Selects(Anyone, "site") {
318 t.Errorf("Selects does not follow the names the grant gives")
319 }
320}
321
322// Read grants at another destination's boundary are not this destination's,
323// and an expired principal holds none, from its expiry day on.
324func TestDestinationsAndExpiry(t *testing.T) {
325 r := newRepo(t)
326 g, err := r.grants(registry(`boundaries: other: {kind: "edge-read", destination: "other.example.org"}
327anyone: grants: read: {boundary: "other", projects: "all"}
328principals: alice: {
329 kind: "human"
330 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
331 grants: read: {boundary: "web", projects: "all"}
332 expires: "2026-10-27"
333}`))
334 if err != nil {
335 t.Fatal(err)
336 }
337 if g.Covers(Anyone, "app", idApp) {
338 t.Errorf("a grant at other.example.org covers app at %s", destination)
339 }
340 if !g.Covers("alice", "app", idApp) {
341 t.Errorf("alice's grant does not count the day before it expires")
342 }
343 expired, err := r.reader.Grants(context.Background(), r.dir, r.commit(registry(`principals: alice: {
344 kind: "human"
345 keys: [{class: "ssh-ed25519", bound: "hardware", public: "`+key+`"}]
346 grants: read: {boundary: "web", projects: "all"}
347 expires: "2026-10-26"
348}`)), "identity", destination, day)
349 if err != nil {
350 t.Fatal(err)
351 }
352 if expired.Covers("alice", "app", idApp) {
353 t.Errorf("alice's grant counts on the day it expires")
354 }
355}
356
357// The old declaration path, policy/web, is not read: a project that
358// declares itself public there and has no policy/read has no consent.
359func TestNoOldPolicyPath(t *testing.T) {
360 r := newRepo(t)
361 _, err := r.consent(map[string]string{
362 "policy/web/web.cue": "package web\n\nproject: visibility: \"public\"\n",
363 }, "app")
364 if !errors.Is(err, ErrMissing) {
365 t.Errorf("a commit with policy/web alone: got %v, want ErrMissing", err)
366 }
367 _, err = r.grants(map[string]string{"policy/web/web.cue": "package web\n\ninstance: projects: app: visibility: \"public\"\n"})
368 if !errors.Is(err, ErrMissing) {
369 t.Errorf("an instance with policy/web alone: got %v, want ErrMissing", err)
370 }
371}
372
373// literalTree writes a tree with the entries given, mode, name and object,
374// as git would never write one: by its bytes, unchecked.
375func (r *repo) literalTree(entries [][3]string) string {
376 r.t.Helper()
377 var raw []byte
378 for _, e := range entries {
379 oid, err := hex.DecodeString(e[2])
380 if err != nil {
381 r.t.Fatal(err)
382 }
383 raw = append(append(raw, e[0]+" "+e[1]+"\x00"...), oid...)
384 }
385 return r.git(string(raw), "hash-object", "-t", "tree", "--literally", "-w", "--stdin")
386}
387
388// A policy/read whose tree names an entry with a directory part, or two
389// entries alike, is invalid, and nothing of it is written outside the
390// scratch directory the reader copies it into.
391func TestMalformedTreeEntryNames(t *testing.T) {
392 r := newRepo(t)
393 scratch := filepath.Join(t.TempDir(), "scratch")
394 t.Setenv("TMPDIR", scratch)
395 if err := os.Mkdir(scratch, 0o700); err != nil {
396 t.Fatal(err)
397 }
398 good := r.git(appPolicy("anyone: true")["policy/read/read.cue"], "hash-object", "-w", "--stdin")
399 for _, names := range [][]string{
400 {"../escape.cue"},
401 {"read.cue", "sub/escape.cue"},
402 {".."},
403 {"."},
404 {"read.cue", "read.cue"},
405 } {
406 var entries [][3]string
407 for _, name := range names {
408 entries = append(entries, [3]string{"100644", name, good})
409 }
410 read := r.literalTree(entries)
411 policyTree := r.git("040000 tree "+read+"\tread\n", "mktree")
412 root := r.git("040000 tree "+policyTree+"\tpolicy\n", "mktree")
413 _, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(root), "app")
414 mustInvalid(t, names[len(names)-1], err)
415 }
416 // The reader copies a document into a directory it makes under
417 // TMPDIR, so ../escape.cue would land in TMPDIR itself. The reader
418 // removes its directory once it has read, so TMPDIR holds nothing.
419 if _, err := os.Stat(filepath.Join(scratch, "escape.cue")); !errors.Is(err, os.ErrNotExist) {
420 t.Errorf("an entry named ../escape.cue was written outside the scratch directory")
421 }
422 if left, err := os.ReadDir(scratch); err != nil || len(left) != 0 {
423 t.Errorf("TMPDIR holds %v after the reads (%v), want nothing", left, err)
424 }
425}
426
427// A tree written literally can name one directory twice on the way to the
428// document, the first that consents and the second that does not. git
429// ls-tree given the path would take the first. Which is the document is
430// ambiguous, so the policy or the registry is invalid, and consents to
431// nothing.
432func TestAmbiguousDocumentDirectory(t *testing.T) {
433 r := newRepo(t)
434 consents := r.tree(map[string]string{"read.cue": appPolicy("anyone: true")["policy/read/read.cue"]})
435 declines := r.tree(map[string]string{"read.cue": appPolicy("")["policy/read/read.cue"]})
436 under := func(name, tree string) string { return r.git("040000 tree "+tree+"\t"+name+"\n", "mktree") }
437
438 // The consenting tree alone consents, so the cases below test the
439 // ambiguity and nothing else.
440 consent, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(under("policy", under("read", consents))), "app")
441 if err != nil || !consent.Names(Anyone) {
442 t.Fatalf("the consenting tree alone reads as %+v, %v", consent, err)
443 }
444 for what, root := range map[string]string{
445 "read named twice in policy": under("policy", r.literalTree([][3]string{
446 {"40000", "read", consents}, {"40000", "read", declines}})),
447 "policy named twice in the root": r.literalTree([][3]string{
448 {"40000", "policy", under("read", consents)}, {"40000", "policy", under("read", declines)}}),
449 } {
450 _, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(root), "app")
451 mustInvalid(t, what, err)
452 }
453
454 registryTree := r.tree(map[string]string{"registry.cue": registry(`anyone: grants: read: {boundary: "web", projects: "all"}`)["identity/registry.cue"]})
455 empty := r.tree(map[string]string{"registry.cue": registry("")["identity/registry.cue"]})
456 _, err = r.reader.Grants(context.Background(), r.dir, r.commitTree(r.literalTree([][3]string{
457 {"40000", "identity", registryTree}, {"40000", "identity", empty}})), "identity", destination, day)
458 mustInvalid(t, "identity named twice in the root", err)
459}
460
461// A document may declare definitions of the schema's again, and cue unifies
462// them with the schema's. A redeclaration can reopen a closed definition to
463// fields it did not allow, so the reader holds the exported JSON to the
464// schema's own fields and names: no redeclaration widens what it accepts.
465func TestRedeclaredDefinitionsWidenNothing(t *testing.T) {
466 r := newRepo(t)
467 for what, body := range map[string]string{
468 "a reader name past a redeclared #Principal": `#Principal: string
469project: "app"
470identity: "` + idApp + `"
471readers: {"../x": true}`,
472 "readers reopened to any key": `readers: [string]: _
473project: "app"
474identity: "` + idApp + `"
475readers: {"two words": true}`,
476 "a project and identity past redeclared patterns": `#ProjectName: string
477#Identity: string
478project: "../app"
479identity: "x"
480readers: {}`,
481 } {
482 _, err := r.consent(policy(body), "app")
483 mustInvalid(t, what, err)
484 }
485
486 // Reopened in the registry, #Grant, #Anyone and #Principal take fields
487 // cue then accepts: a note on a grant, and a key for anyone. A field
488 // can also be spelled again in another case, which cue keeps apart from
489 // the schema's and encoding/json would read as the schema's: Grants
490 // beside an empty grants, and Projects beside an empty projects. The
491 // reader refuses every one.
492 for what, more := range map[string]string{
493 "a grant reopened to a note": `#Grant: note?: string
494anyone: grants: read: {boundary: "web", projects: "all", note: "widened"}`,
495 "anyone reopened to keys": `#Anyone: keys?: [...]
496anyone: {keys: [{class: "ssh-ed25519", bound: "host", public: "` + key + `"}], grants: read: {boundary: "web", projects: "all"}}`,
497 "anyone's grants spelled Grants": `#Anyone: Grants?: _
498anyone: grants: {}
499anyone: Grants: read: {boundary: "web", projects: "all"}`,
500 "a grant's projects spelled Projects": `#Grant: Projects?: _
501anyone: grants: read: {boundary: "web", projects: {}, Projects: "all"}`,
502 "a principal's grants spelled Grants": `#Principal: Grants?: _
503principals: alice: {
504 kind: "human"
505 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
506 grants: {}
507 Grants: read: {boundary: "web", projects: "all"}
508}`,
509 } {
510 files := registry(more)
511 dir := t.TempDir()
512 file := filepath.Join(dir, "registry.cue")
513 if err := os.WriteFile(file, []byte(files["identity/registry.cue"]), 0o600); err != nil {
514 t.Fatal(err)
515 }
516 if out, err := exec.Command("cue", "vet", "-c", r.reader.IdentitySchema, file).CombinedOutput(); err != nil {
517 t.Fatalf("%s: cue refused it, so the case proves nothing of the reader: %s", what, out)
518 }
519 _, err := r.grants(files)
520 mustInvalid(t, what, err)
521 }
522}
523
524// A policy past the bounds is invalid: more documents than it may have.
525func TestBounds(t *testing.T) {
526 r := newRepo(t)
527 files := appPolicy("anyone: true")
528 for i := range policyBounds.files {
529 files["policy/read/more-"+string(rune('a'+i%26))+string(rune('a'+i/26))+".cue"] = "package read\n"
530 }
531 _, err := r.consent(files, "app")
532 mustInvalid(t, "a policy of 33 documents", err)
533}