gunk-dev/the-valley

read_test.go

source19a79dd5dbc9main's published tip history
16.2 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, name and blob, as git
374// would never write one: by its bytes, unchecked.
375func (r *repo) literalTree(entries [][2]string) string {
376 r.t.Helper()
377 var raw []byte
378 for _, e := range entries {
379 oid, err := hex.DecodeString(e[1])
380 if err != nil {
381 r.t.Fatal(err)
382 }
383 raw = append(append(raw, "100644 "+e[0]+"\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 tmp := t.TempDir()
394 t.Setenv("TMPDIR", filepath.Join(tmp, "scratch"))
395 if err := os.Mkdir(filepath.Join(tmp, "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 _, entries := range [][][2]string{
400 {{"../escape.cue", good}},
401 {{"read.cue", good}, {"sub/escape.cue", good}},
402 {{"..", good}},
403 {{".", good}},
404 {{"read.cue", good}, {"read.cue", good}},
405 } {
406 read := r.literalTree(entries)
407 policyTree := r.git("040000 tree "+read+"\tread\n", "mktree")
408 root := r.git("040000 tree "+policyTree+"\tpolicy\n", "mktree")
409 _, err := r.reader.Consent(context.Background(), r.dir, r.commitTree(root), "app")
410 mustInvalid(t, entries[len(entries)-1][0], err)
411 }
412 if _, err := os.Stat(filepath.Join(tmp, "escape.cue")); !errors.Is(err, os.ErrNotExist) {
413 t.Errorf("an entry named ../escape.cue was written outside the scratch directory")
414 }
415}
416
417// A document may declare definitions of the schema's again, and cue unifies
418// them with the schema's. A redeclaration can reopen a closed definition to
419// fields it did not allow, so the reader holds the exported JSON to the
420// schema's own fields and names: no redeclaration widens what it accepts.
421func TestRedeclaredDefinitionsWidenNothing(t *testing.T) {
422 r := newRepo(t)
423 for what, body := range map[string]string{
424 "a reader name past a redeclared #Principal": `#Principal: string
425project: "app"
426identity: "` + idApp + `"
427readers: {"../x": true}`,
428 "readers reopened to any key": `readers: [string]: _
429project: "app"
430identity: "` + idApp + `"
431readers: {"two words": true}`,
432 "a project and identity past redeclared patterns": `#ProjectName: string
433#Identity: string
434project: "../app"
435identity: "x"
436readers: {}`,
437 } {
438 _, err := r.consent(policy(body), "app")
439 mustInvalid(t, what, err)
440 }
441
442 // Reopened in the registry, #Grant, #Anyone and #Principal take fields
443 // cue then accepts: a note on a grant, and a key for anyone. A field
444 // can also be spelled again in another case, which cue keeps apart from
445 // the schema's and encoding/json would read as the schema's: Grants
446 // beside an empty grants, and Projects beside an empty projects. The
447 // reader refuses every one.
448 for what, more := range map[string]string{
449 "a grant reopened to a note": `#Grant: note?: string
450anyone: grants: read: {boundary: "web", projects: "all", note: "widened"}`,
451 "anyone reopened to keys": `#Anyone: keys?: [...]
452anyone: {keys: [{class: "ssh-ed25519", bound: "host", public: "` + key + `"}], grants: read: {boundary: "web", projects: "all"}}`,
453 "anyone's grants spelled Grants": `#Anyone: Grants?: _
454anyone: grants: {}
455anyone: Grants: read: {boundary: "web", projects: "all"}`,
456 "a grant's projects spelled Projects": `#Grant: Projects?: _
457anyone: grants: read: {boundary: "web", projects: {}, Projects: "all"}`,
458 "a principal's grants spelled Grants": `#Principal: Grants?: _
459principals: alice: {
460 kind: "human"
461 keys: [{class: "ssh-ed25519", bound: "hardware", public: "` + key + `"}]
462 grants: {}
463 Grants: read: {boundary: "web", projects: "all"}
464}`,
465 } {
466 files := registry(more)
467 dir := t.TempDir()
468 file := filepath.Join(dir, "registry.cue")
469 if err := os.WriteFile(file, []byte(files["identity/registry.cue"]), 0o600); err != nil {
470 t.Fatal(err)
471 }
472 if out, err := exec.Command("cue", "vet", "-c", r.reader.IdentitySchema, file).CombinedOutput(); err != nil {
473 t.Fatalf("%s: cue refused it, so the case proves nothing of the reader: %s", what, out)
474 }
475 _, err := r.grants(files)
476 mustInvalid(t, what, err)
477 }
478}
479
480// A policy past the bounds is invalid: more documents than it may have.
481func TestBounds(t *testing.T) {
482 r := newRepo(t)
483 files := appPolicy("anyone: true")
484 for i := range policyBounds.files {
485 files["policy/read/more-"+string(rune('a'+i%26))+string(rune('a'+i/26))+".cue"] = "package read\n"
486 }
487 _, err := r.consent(files, "app")
488 mustInvalid(t, "a policy of 33 documents", err)
489}