| 1 | package readaccess |
| 2 | |
| 3 | import ( |
| 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 | |
| 20 | const ( |
| 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 | |
| 30 | var day = time.Date(2026, 10, 26, 12, 0, 0, 0, time.UTC) |
| 31 | |
| 32 | func 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. |
| 43 | type repo struct { |
| 44 | t *testing.T |
| 45 | dir string |
| 46 | reader *Reader |
| 47 | } |
| 48 | |
| 49 | func 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 | |
| 63 | func 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 | |
| 72 | func (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. |
| 91 | func (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. |
| 114 | func (r *repo) commit(files map[string]string) string { |
| 115 | r.t.Helper() |
| 116 | return r.commitTree(r.tree(files)) |
| 117 | } |
| 118 | |
| 119 | func (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. |
| 125 | func policy(body string) map[string]string { |
| 126 | return map[string]string{"policy/read/read.cue": "package read\n\n" + body + "\n"} |
| 127 | } |
| 128 | |
| 129 | func appPolicy(readers string) map[string]string { |
| 130 | return policy(`project: "app" |
| 131 | identity: "` + idApp + `" |
| 132 | readers: {` + 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. |
| 137 | func registry(more string) map[string]string { |
| 138 | return map[string]string{"identity/registry.cue": `package identity |
| 139 | |
| 140 | boundaries: { |
| 141 | registry: kind: "registry" |
| 142 | push: kind: "git-push" |
| 143 | web: {kind: "edge-read", destination: "` + destination + `"} |
| 144 | } |
| 145 | genesis: "root" |
| 146 | principals: 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. |
| 155 | func 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 | |
| 163 | func (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 | |
| 168 | func (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 | |
| 173 | func 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. |
| 184 | func 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. |
| 236 | func 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" |
| 256 | identity: "`+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. |
| 264 | func 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. |
| 301 | func 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. |
| 324 | func TestDestinationsAndExpiry(t *testing.T) { |
| 325 | r := newRepo(t) |
| 326 | g, err := r.grants(registry(`boundaries: other: {kind: "edge-read", destination: "other.example.org"} |
| 327 | anyone: grants: read: {boundary: "other", projects: "all"} |
| 328 | principals: 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. |
| 359 | func 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. |
| 375 | func (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. |
| 391 | func 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. |
| 421 | func 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 |
| 425 | project: "app" |
| 426 | identity: "` + idApp + `" |
| 427 | readers: {"../x": true}`, |
| 428 | "readers reopened to any key": `readers: [string]: _ |
| 429 | project: "app" |
| 430 | identity: "` + idApp + `" |
| 431 | readers: {"two words": true}`, |
| 432 | "a project and identity past redeclared patterns": `#ProjectName: string |
| 433 | #Identity: string |
| 434 | project: "../app" |
| 435 | identity: "x" |
| 436 | readers: {}`, |
| 437 | } { |
| 438 | _, err := r.consent(policy(body), "app") |
| 439 | mustInvalid(t, what, err) |
| 440 | } |
| 441 | |
| 442 | // Reopened in the registry, #Grant and #Anyone take fields cue then |
| 443 | // accepts: a note on a grant, and a key for anyone. The reader refuses |
| 444 | // both. |
| 445 | for what, more := range map[string]string{ |
| 446 | "a grant reopened to a note": `#Grant: note?: string |
| 447 | anyone: grants: read: {boundary: "web", projects: "all", note: "widened"}`, |
| 448 | "anyone reopened to keys": `#Anyone: keys?: [...] |
| 449 | anyone: {keys: [{class: "ssh-ed25519", bound: "host", public: "` + key + `"}], grants: read: {boundary: "web", projects: "all"}}`, |
| 450 | } { |
| 451 | files := registry(more) |
| 452 | dir := t.TempDir() |
| 453 | file := filepath.Join(dir, "registry.cue") |
| 454 | if err := os.WriteFile(file, []byte(files["identity/registry.cue"]), 0o600); err != nil { |
| 455 | t.Fatal(err) |
| 456 | } |
| 457 | if out, err := exec.Command("cue", "vet", "-c", r.reader.IdentitySchema, file).CombinedOutput(); err != nil { |
| 458 | t.Fatalf("%s: cue refused it, so the case proves nothing of the reader: %s", what, out) |
| 459 | } |
| 460 | _, err := r.grants(files) |
| 461 | mustInvalid(t, what, err) |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | // A policy past the bounds is invalid: more documents than it may have. |
| 466 | func TestBounds(t *testing.T) { |
| 467 | r := newRepo(t) |
| 468 | files := appPolicy("anyone: true") |
| 469 | for i := range policyBounds.files { |
| 470 | files["policy/read/more-"+string(rune('a'+i%26))+string(rune('a'+i/26))+".cue"] = "package read\n" |
| 471 | } |
| 472 | _, err := r.consent(files, "app") |
| 473 | mustInvalid(t, "a policy of 33 documents", err) |
| 474 | } |