gunk-dev/the-valley

read_test.go

source860de91b1a12main's published tip history
19.6 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 principal with no keys is a reader alone: the registry is valid while
299// every grant it holds is an edge read, and it reads under that grant. A
300// keyless principal that also holds a push, a registry or any other grant
301// makes the registry invalid, so it consents to nothing.
302func TestAKeylessPrincipalOnlyReads(t *testing.T) {
303 r := newRepo(t)
304 keyless := strings.Replace(reader("alice", `"all"`), "keys: [{class: \"ssh-ed25519\", bound: \"hardware\", public: \""+key+"\"}]", "keys: []", 1)
305 g, err := r.grants(registry(keyless))
306 if err != nil {
307 t.Fatal(err)
308 }
309 consent, err := r.consent(appPolicy("alice: true"), "app")
310 if err != nil {
311 t.Fatal(err)
312 }
313 if !g.May("alice", consent) {
314 t.Errorf("a keyless reader with a grant and a consent may not read app")
315 }
316 for what, grant := range map[string]string{
317 "a push grant": `push: boundary: "push"`,
318 "a registry grant": `govern: boundary: "registry"`,
319 } {
320 more := strings.Replace(keyless, "grants: read:", "grants: "+grant+"\n\tgrants: read:", 1)
321 _, err := r.grants(registry(more))
322 mustInvalid(t, "a keyless principal holding "+what, err)
323 }
324}
325
326// A policy is for the project it names, and an explicit grant is for the
327// identity it names. A policy read from another project, or a project
328// whose identity is not the grant's, is not read.
329func TestProjectIdentityMismatch(t *testing.T) {
330 r := newRepo(t)
331 _, err := r.consent(appPolicy("anyone: true"), "site")
332 mustInvalid(t, "app's policy read from site", err)
333
334 g, err := r.grants(registry(`anyone: grants: read: {boundary: "web", projects: app: "` + idOther + `"}`))
335 if err != nil {
336 t.Fatal(err)
337 }
338 consent, err := r.consent(appPolicy("anyone: true"), "app")
339 if err != nil {
340 t.Fatal(err)
341 }
342 if g.May(Anyone, consent) {
343 t.Errorf("a grant for app under another identity lets anyone read app")
344 }
345 if !g.Selects(Anyone, "app") || g.Selects(Anyone, "site") {
346 t.Errorf("Selects does not follow the names the grant gives")
347 }
348}
349
350// Read grants at another destination's boundary are not this destination's,
351// and an expired principal holds none, from its expiry day on.
352func TestDestinationsAndExpiry(t *testing.T) {
353 r := newRepo(t)
354 g, err := r.grants(registry(`boundaries: other: {kind: "edge-read", destination: "other.example.org"}
355anyone: grants: read: {boundary: "other", projects: "all"}
356principals: alice: {
357 kind: "human"
358 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
359 grants: read: {boundary: "web", projects: "all"}
360 expires: "2026-10-27"
361}`))
362 if err != nil {
363 t.Fatal(err)
364 }
365 if g.Covers(Anyone, "app", idApp) {
366 t.Errorf("a grant at other.example.org covers app at %s", destination)
367 }
368 if !g.Covers("alice", "app", idApp) {
369 t.Errorf("alice's grant does not count the day before it expires")
370 }
371 expired, err := r.reader.Grants(context.Background(), r.dir, r.commit(registry(`principals: alice: {
372 kind: "human"
373 keys: [{class: "ssh-ed25519", bound: "hardware", public: "`+key+`"}]
374 grants: read: {boundary: "web", projects: "all"}
375 expires: "2026-10-26"
376}`)), "identity", destination, day)
377 if err != nil {
378 t.Fatal(err)
379 }
380 if expired.Covers("alice", "app", idApp) {
381 t.Errorf("alice's grant counts on the day it expires")
382 }
383}
384
385// The old declaration path, policy/web, is not read: a project that
386// declares itself public there and has no policy/read has no consent.
387func TestNoOldPolicyPath(t *testing.T) {
388 r := newRepo(t)
389 _, err := r.consent(map[string]string{
390 "policy/web/web.cue": "package web\n\nproject: visibility: \"public\"\n",
391 }, "app")
392 if !errors.Is(err, ErrMissing) {
393 t.Errorf("a commit with policy/web alone: got %v, want ErrMissing", err)
394 }
395 _, err = r.grants(map[string]string{"policy/web/web.cue": "package web\n\ninstance: projects: app: visibility: \"public\"\n"})
396 if !errors.Is(err, ErrMissing) {
397 t.Errorf("an instance with policy/web alone: got %v, want ErrMissing", err)
398 }
399}
400
401// literalTree writes a tree with the entries given, mode, name and object,
402// as git would never write one: by its bytes, unchecked.
403func (r *repo) literalTree(entries [][3]string) string {
404 r.t.Helper()
405 var raw []byte
406 for _, e := range entries {
407 oid, err := hex.DecodeString(e[2])
408 if err != nil {
409 r.t.Fatal(err)
410 }
411 raw = append(append(raw, e[0]+" "+e[1]+"\x00"...), oid...)
412 }
413 return r.git(string(raw), "hash-object", "-t", "tree", "--literally", "-w", "--stdin")
414}
415
416// A policy/read whose tree names an entry with a directory part, or two
417// entries alike, is invalid, and nothing of it is written outside the
418// scratch directory the reader copies it into.
419func TestMalformedTreeEntryNames(t *testing.T) {
420 r := newRepo(t)
421 scratch := filepath.Join(t.TempDir(), "scratch")
422 t.Setenv("TMPDIR", scratch)
423 if err := os.Mkdir(scratch, 0o700); err != nil {
424 t.Fatal(err)
425 }
426 good := r.git(appPolicy("anyone: true")["policy/read/read.cue"], "hash-object", "-w", "--stdin")
427 for _, names := range [][]string{
428 {"../escape.cue"},
429 {"read.cue", "sub/escape.cue"},
430 {".."},
431 {"."},
432 {"read.cue", "read.cue"},
433 } {
434 var entries [][3]string
435 for _, name := range names {
436 entries = append(entries, [3]string{"100644", name, good})
437 }
438 read := r.literalTree(entries)
439 policyTree := r.git("040000 tree "+read+"\tread\n", "mktree")
440 root := r.git("040000 tree "+policyTree+"\tpolicy\n", "mktree")
441 _, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(root), "app")
442 mustInvalid(t, names[len(names)-1], err)
443 }
444 // The reader copies a document into a directory it makes under
445 // TMPDIR, so ../escape.cue would land in TMPDIR itself. The reader
446 // removes its directory once it has read, so TMPDIR holds nothing.
447 if _, err := os.Stat(filepath.Join(scratch, "escape.cue")); !errors.Is(err, os.ErrNotExist) {
448 t.Errorf("an entry named ../escape.cue was written outside the scratch directory")
449 }
450 if left, err := os.ReadDir(scratch); err != nil || len(left) != 0 {
451 t.Errorf("TMPDIR holds %v after the reads (%v), want nothing", left, err)
452 }
453}
454
455// A tree written literally can name one directory twice on the way to the
456// document, the first that consents and the second that does not. git
457// ls-tree given the path would take the first. Which is the document is
458// ambiguous, so the policy or the registry is invalid, and consents to
459// nothing.
460func TestAmbiguousDocumentDirectory(t *testing.T) {
461 r := newRepo(t)
462 consents := r.tree(map[string]string{"read.cue": appPolicy("anyone: true")["policy/read/read.cue"]})
463 declines := r.tree(map[string]string{"read.cue": appPolicy("")["policy/read/read.cue"]})
464 under := func(name, tree string) string { return r.git("040000 tree "+tree+"\t"+name+"\n", "mktree") }
465
466 // The consenting tree alone consents, so the cases below test the
467 // ambiguity and nothing else.
468 consent, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(under("policy", under("read", consents))), "app")
469 if err != nil || !consent.Names(Anyone) {
470 t.Fatalf("the consenting tree alone reads as %+v, %v", consent, err)
471 }
472 for what, root := range map[string]string{
473 "read named twice in policy": under("policy", r.literalTree([][3]string{
474 {"40000", "read", consents}, {"40000", "read", declines}})),
475 "policy named twice in the root": r.literalTree([][3]string{
476 {"40000", "policy", under("read", consents)}, {"40000", "policy", under("read", declines)}}),
477 } {
478 _, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(root), "app")
479 mustInvalid(t, what, err)
480 }
481
482 registryTree := r.tree(map[string]string{"registry.cue": registry(`anyone: grants: read: {boundary: "web", projects: "all"}`)["identity/registry.cue"]})
483 empty := r.tree(map[string]string{"registry.cue": registry("")["identity/registry.cue"]})
484 _, err = r.reader.Grants(context.Background(), r.dir, r.commitTree(r.literalTree([][3]string{
485 {"40000", "identity", registryTree}, {"40000", "identity", empty}})), "identity", destination, day)
486 mustInvalid(t, "identity named twice in the root", err)
487}
488
489// A document may declare definitions of the schema's again, and cue unifies
490// them with the schema's. A redeclaration can reopen a closed definition to
491// fields it did not allow, so the reader holds the exported JSON to the
492// schema's own fields and names: no redeclaration widens what it accepts.
493func TestRedeclaredDefinitionsWidenNothing(t *testing.T) {
494 r := newRepo(t)
495 for what, body := range map[string]string{
496 "a reader name past a redeclared #Principal": `#Principal: string
497project: "app"
498identity: "` + idApp + `"
499readers: {"../x": true}`,
500 "readers reopened to any key": `readers: [string]: _
501project: "app"
502identity: "` + idApp + `"
503readers: {"two words": true}`,
504 "a project and identity past redeclared patterns": `#ProjectName: string
505#Identity: string
506project: "../app"
507identity: "x"
508readers: {}`,
509 } {
510 _, err := r.consent(policy(body), "app")
511 mustInvalid(t, what, err)
512 }
513
514 // Reopened in the registry, #Grant, #Anyone and #Principal take fields
515 // cue then accepts: a note on a grant, and a key for anyone. A field
516 // can also be spelled again in another case, which cue keeps apart from
517 // the schema's and encoding/json would read as the schema's: Grants
518 // beside an empty grants, and Projects beside an empty projects. The
519 // reader refuses every one.
520 for what, more := range map[string]string{
521 "a grant reopened to a note": `#Grant: note?: string
522anyone: grants: read: {boundary: "web", projects: "all", note: "widened"}`,
523 "anyone reopened to keys": `#Anyone: keys?: [...]
524anyone: {keys: [{class: "ssh-ed25519", bound: "host", public: "` + key + `"}], grants: read: {boundary: "web", projects: "all"}}`,
525 "anyone's grants spelled Grants": `#Anyone: Grants?: _
526anyone: grants: {}
527anyone: Grants: read: {boundary: "web", projects: "all"}`,
528 "a grant's projects spelled Projects": `#Grant: Projects?: _
529anyone: grants: read: {boundary: "web", projects: {}, Projects: "all"}`,
530 "a principal's grants spelled Grants": `#Principal: Grants?: _
531principals: alice: {
532 kind: "human"
533 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
534 grants: {}
535 Grants: read: {boundary: "web", projects: "all"}
536}`,
537 } {
538 files := registry(more)
539 dir := t.TempDir()
540 file := filepath.Join(dir, "registry.cue")
541 if err := os.WriteFile(file, []byte(files["identity/registry.cue"]), 0o600); err != nil {
542 t.Fatal(err)
543 }
544 if out, err := exec.Command("cue", "vet", "-c", r.reader.IdentitySchema, file).CombinedOutput(); err != nil {
545 t.Fatalf("%s: cue refused it, so the case proves nothing of the reader: %s", what, out)
546 }
547 _, err := r.grants(files)
548 mustInvalid(t, what, err)
549 }
550}
551
552// A policy past the bounds is invalid: more documents than it may have.
553func TestBounds(t *testing.T) {
554 r := newRepo(t)
555 files := appPolicy("anyone: true")
556 for i := range policyBounds.files {
557 files["policy/read/more-"+string(rune('a'+i%26))+string(rune('a'+i/26))+".cue"] = "package read\n"
558 }
559 _, err := r.consent(files, "app")
560 mustInvalid(t, "a policy of 33 documents", err)
561}