gunk-dev/the-valley

read.go

source19a79dd5dbc9main's published tip history
20.5 KiB
1package readaccess
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path"
13 "path/filepath"
14 "reflect"
15 "regexp"
16 "slices"
17 "strconv"
18 "strings"
19 "time"
20)
21
22// PolicyDir is where a project keeps its consent: the *.cue documents
23// directly in this directory of its main.
24const PolicyDir = "policy/read"
25
26// ErrMissing is the error for a commit that holds no document where one is
27// read: no *.cue file directly in the directory, or no directory.
28var ErrMissing = errors.New("no document")
29
30// InvalidError is the error for a document that is there and is not valid:
31// cue refused it under its schema, or it is past the bounds, malformed, or
32// for another project. An invalid document consents to nothing. Every
33// other error of a Reader's is a failure to read, which consents to
34// nothing either, and which a caller reports rather than acting on.
35type InvalidError struct{ Err error }
36
37func (e *InvalidError) Error() string { return e.Err.Error() }
38func (e *InvalidError) Unwrap() error { return e.Err }
39
40func invalid(format string, args ...any) error {
41 return &InvalidError{fmt.Errorf(format, args...)}
42}
43
44// Reader reads the two consents out of git commits, with git and cue. It
45// reads a document's *.cue files with git ls-tree and cat-file, never a
46// checkout, copies them into a scratch directory with no cue.mod, so cue
47// resolves no import beyond its standard library, and exports them as JSON
48// with cue under the document's schema. Its Go reading then holds the JSON
49// to the schema's fields, each spelled exactly as the schema spells it, and
50// to its names again, so a document that redeclares a definition of the
51// schema widens nothing.
52type Reader struct {
53 // ReadSchema is schema/read.cue, and IdentitySchema is
54 // schema/identity.cue.
55 ReadSchema, IdentitySchema string
56
57 // CueTimeout bounds each cue run. Zero is a minute.
58 CueTimeout time.Duration
59}
60
61// The bounds on a document: how many files it may have, how large each may
62// be, and how much cue may print for it. A document past them is invalid.
63// A registry carries keys and attestations, so its bounds are larger.
64type bounds struct {
65 files int
66 file int64
67 output int
68}
69
70var (
71 policyBounds = bounds{files: 32, file: 64 << 10, output: 1 << 20}
72 registryBounds = bounds{files: 64, file: 1 << 20, output: 8 << 20}
73)
74
75// The bounds on what git and cue print. git's output past maxGitOutput
76// fails the call, and what a program prints on stderr past maxStderr is
77// dropped.
78const (
79 maxGitOutput = 4 << 20
80 maxStderr = 64 << 10
81)
82
83// cueRefused is the exit status cue ends with when it reports an error in
84// what it was given, as when a schema refuses a document. A Go program that
85// panics exits 2, and one the kernel kills has no status.
86const cueRefused = 1
87
88// CheckSchemas holds each schema to loading on its own, before any
89// document is read under it. Without it a schema that cannot be read would
90// make every document invalid, and so withdraw every consent.
91func (r *Reader) CheckSchemas(ctx context.Context) error {
92 dir, err := os.MkdirTemp("", "readaccess-")
93 if err != nil {
94 return err
95 }
96 defer os.RemoveAll(dir)
97 for _, schema := range []string{r.ReadSchema, r.IdentitySchema} {
98 if schema == "" {
99 return errors.New("no schema given")
100 }
101 if _, err := r.cue(ctx, dir, 0, "vet", "-c=false", schema); err != nil {
102 return fmt.Errorf("the schema %s does not load: %w", schema, err)
103 }
104 }
105 return nil
106}
107
108// policyDoc is a policy/read as cue exports it under schema/read.cue.
109type policyDoc struct {
110 Project string `json:"project"`
111 Identity string `json:"identity"`
112 Readers map[string]bool `json:"readers"`
113}
114
115// Consent reads the consent of the project at a commit of repo: its
116// policy/read under ReadSchema. A policy that names another project than
117// the one it is read from is invalid.
118func (r *Reader) Consent(ctx context.Context, repo, commit, project string) (Consent, error) {
119 var doc policyDoc
120 if err := r.read(ctx, repo, commit, PolicyDir, r.ReadSchema, policyBounds, &doc); err != nil {
121 return Consent{}, err
122 }
123 switch {
124 case !validProject(doc.Project):
125 return Consent{}, invalid("%s names the project %q, which is not a project name", PolicyDir, doc.Project)
126 case doc.Project != project:
127 return Consent{}, invalid("%s is for the project %q, and was read from %q", PolicyDir, doc.Project, project)
128 case !identityPattern.MatchString(doc.Identity):
129 return Consent{}, invalid("%s declares the identity %q, which is not a publication identity", PolicyDir, doc.Identity)
130 }
131 c := Consent{Project: doc.Project, Identity: doc.Identity, Readers: []string{}}
132 for reader, ok := range doc.Readers {
133 if !ok || !namePattern.MatchString(reader) {
134 return Consent{}, invalid("%s names the reader %q, which is not a principal name", PolicyDir, reader)
135 }
136 c.Readers = append(c.Readers, reader)
137 }
138 slices.Sort(c.Readers)
139 return c, nil
140}
141
142// registryDoc is the identity registry as cue exports it under
143// schema/identity.cue. The parts the read grants do not depend on are
144// taken whole, and every other field is held to the schema's.
145type registryDoc struct {
146 Boundaries map[string]struct {
147 Kind string `json:"kind"`
148 Destination string `json:"destination"`
149 } `json:"boundaries"`
150 Principals map[string]struct {
151 Kind string `json:"kind"`
152 Keys json.RawMessage `json:"keys"`
153 Grants map[string]grantDoc `json:"grants"`
154 External json.RawMessage `json:"external"`
155 Expires string `json:"expires"`
156 } `json:"principals"`
157 Anyone *struct {
158 Grants map[string]grantDoc `json:"grants"`
159 } `json:"anyone"`
160 Genesis string `json:"genesis"`
161 GenesisGovernance json.RawMessage `json:"genesisGovernance"`
162 ExternalGovernance json.RawMessage `json:"externalGovernance"`
163 ReadScopes json.RawMessage `json:"readScopes"`
164}
165
166type grantDoc struct {
167 Boundary string `json:"boundary"`
168 Projects json.RawMessage `json:"projects"`
169}
170
171// edgeRead is the boundary kind that checks read grants.
172const edgeRead = "edge-read"
173
174// Grants reads the instance's read grants at the destination: the grants
175// at every edge read boundary that names it, from the registry in dir at a
176// commit of the instance repository, under IdentitySchema. A principal
177// whose expiry has arrived on day holds none, as the identity compiler
178// omits it from every artifact.
179func (r *Reader) Grants(ctx context.Context, repo, commit, dir, destination string, day time.Time) (Grants, error) {
180 if !validDir(dir) {
181 return nil, fmt.Errorf("%q is not a directory a commit can hold", dir)
182 }
183 if !namePattern.MatchString(destination) {
184 return nil, fmt.Errorf("%q is not a destination name", destination)
185 }
186 var doc registryDoc
187 if err := r.read(ctx, repo, commit, dir, r.IdentitySchema, registryBounds, &doc); err != nil {
188 return nil, err
189 }
190 y, m, d := day.UTC().Date()
191 today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
192
193 g := Grants{}
194 add := func(principal, name string, grant grantDoc) error {
195 b, ok := doc.Boundaries[grant.Boundary]
196 switch {
197 case !ok:
198 return invalid("the grant %s.%s names the boundary %q, which the registry does not declare", principal, name, grant.Boundary)
199 case b.Kind != edgeRead && principal == Anyone:
200 return invalid("anyone holds the grant %s at a boundary of kind %q; anyone holds read grants alone", name, b.Kind)
201 case b.Kind != edgeRead && grant.Projects != nil:
202 return invalid("the grant %s.%s names projects at a boundary of kind %q", principal, name, b.Kind)
203 case b.Kind != edgeRead:
204 return nil
205 case !namePattern.MatchString(b.Destination):
206 return invalid("the boundary %s names the destination %q, which is not a name", grant.Boundary, b.Destination)
207 }
208 s, err := parseScope(grant.Projects)
209 if err != nil {
210 return invalid("the grant %s.%s: %w", principal, name, err)
211 }
212 if b.Destination == destination {
213 g[principal] = append(g[principal], s)
214 }
215 return nil
216 }
217 for principal, p := range doc.Principals {
218 if principal == Anyone || !namePattern.MatchString(principal) {
219 return nil, invalid("the registry names the principal %q, which is reserved or not a principal name", principal)
220 }
221 if p.Expires != "" {
222 end, err := time.Parse(time.DateOnly, p.Expires)
223 if err != nil {
224 return nil, invalid("%s expires %q, which is not a calendar day", principal, p.Expires)
225 }
226 if !today.Before(end) {
227 continue
228 }
229 }
230 for name, grant := range p.Grants {
231 if err := add(principal, name, grant); err != nil {
232 return nil, err
233 }
234 }
235 }
236 if doc.Anyone != nil {
237 for name, grant := range doc.Anyone.Grants {
238 if err := add(Anyone, name, grant); err != nil {
239 return nil, err
240 }
241 }
242 }
243 return g, nil
244}
245
246// parseScope reads a read grant's projects: "all", or an object of project
247// names and publication identities.
248func parseScope(raw json.RawMessage) (Scope, error) {
249 var all string
250 if err := json.Unmarshal(raw, &all); err == nil {
251 if all != "all" {
252 return Scope{}, fmt.Errorf("its projects are %q, which is neither \"all\" nor a set of projects", all)
253 }
254 return Scope{All: true}, nil
255 }
256 s := Scope{Projects: map[string]string{}}
257 if err := json.Unmarshal(raw, &s.Projects); err != nil || s.Projects == nil {
258 return Scope{}, errors.New("its projects are neither \"all\" nor a set of projects")
259 }
260 for project, identity := range s.Projects {
261 if !validProject(project) || !identityPattern.MatchString(identity) {
262 return Scope{}, fmt.Errorf("it names the project %q with the identity %q, and not a project name with a publication identity", project, identity)
263 }
264 }
265 return s, nil
266}
267
268var (
269 namePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`)
270 identityPattern = regexp.MustCompile(`^[0-9a-f]{32}$`)
271)
272
273// validProject reports whether name is a project name: the principal-name
274// pattern, at most 64 bytes, as schema/read.cue holds it.
275func validProject(name string) bool {
276 return len(name) <= 64 && namePattern.MatchString(name)
277}
278
279// validDir reports whether dir is a relative path to a directory below a
280// commit's root, written plainly.
281func validDir(dir string) bool {
282 return dir != "" && dir != "." && path.Clean(dir) == dir && !path.IsAbs(dir) &&
283 dir != ".." && !strings.HasPrefix(dir, "../")
284}
285
286// read reads the document in dir at a commit of repo, exports it with cue
287// under schema, and decodes the JSON into doc, which must take every field
288// cue exported. Its error is ErrMissing when the commit holds no document
289// there, an *InvalidError when the document is invalid, and any other
290// error when git or cue could not be run over it.
291func (r *Reader) read(ctx context.Context, repo, commit, dir, schema string, lim bounds, doc any) error {
292 entry, err := git(ctx, repo, "ls-tree", "-z", commit, "--", dir)
293 if err != nil {
294 return err
295 }
296 if len(entry) == 0 {
297 return ErrMissing
298 }
299 meta, _, _ := strings.Cut(string(entry), "\t")
300 f := strings.Fields(meta)
301 if len(f) != 3 || f[1] != "tree" {
302 return invalid("%s is not a directory", dir)
303 }
304 listing, err := git(ctx, repo, "ls-tree", "-z", f[2])
305 if errors.Is(err, errTooLong) {
306 return invalid("%s lists more than %d bytes of entries", dir, maxGitOutput)
307 } else if err != nil {
308 return err
309 }
310
311 // A tree git wrote itself never names an entry with a directory part,
312 // nor two entries alike, but one written literally can. Such a
313 // directory is no document: copied out by name, an entry like ../x.cue
314 // would land outside the scratch directory.
315 type document struct{ name, oid string }
316 var docs []document
317 seen := map[string]bool{}
318 for _, e := range strings.Split(strings.TrimSuffix(string(listing), "\x00"), "\x00") {
319 if e == "" {
320 continue
321 }
322 meta, name, _ := strings.Cut(e, "\t")
323 if name == "" || name == "." || name == ".." || strings.Contains(name, "/") {
324 return invalid("%s holds an entry named %q, which is not a plain file name", dir, name)
325 }
326 if seen[name] {
327 return invalid("%s holds two entries named %q", dir, name)
328 }
329 seen[name] = true
330 fields := strings.Fields(meta)
331 if !strings.HasSuffix(name, ".cue") || len(fields) != 3 || fields[1] != "blob" ||
332 (fields[0] != "100644" && fields[0] != "100755") {
333 continue
334 }
335 docs = append(docs, document{name, fields[2]})
336 }
337 if len(docs) == 0 {
338 return ErrMissing
339 }
340 if len(docs) > lim.files {
341 return invalid("%s holds %d documents, more than the %d it may have", dir, len(docs), lim.files)
342 }
343
344 scratch, err := os.MkdirTemp("", "readaccess-")
345 if err != nil {
346 return err
347 }
348 defer os.RemoveAll(scratch)
349 files := []string{"export", "--out", "json", schema}
350 for _, d := range docs {
351 out, err := git(ctx, repo, "cat-file", "-s", d.oid)
352 if err != nil {
353 return err
354 }
355 size, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
356 if err != nil {
357 return fmt.Errorf("git cat-file -s %s: %w", d.oid, err)
358 }
359 if size > lim.file {
360 return invalid("%s/%s is %d bytes, more than the %d a document may be", dir, d.name, size, lim.file)
361 }
362 body, err := git(ctx, repo, "cat-file", "blob", d.oid)
363 if err != nil {
364 return err
365 }
366 file := filepath.Join(scratch, d.name)
367 if err := os.WriteFile(file, body, 0o600); err != nil {
368 return err
369 }
370 files = append(files, file)
371 }
372
373 out, err := r.cue(ctx, scratch, lim.output, files...)
374 if err != nil {
375 return err
376 }
377 if err := decodeStrict(out, doc); err != nil {
378 return invalid("%s is not what its schema exports: %w", dir, err)
379 }
380 return nil
381}
382
383// decodeStrict decodes one JSON document into doc, and refuses any object
384// key that is not a field of doc's type spelled exactly as its json tag
385// spells it. encoding/json matches a key to a field without regard to
386// case, and cue keeps keys that differ in case apart. So a document that
387// reopens a definition could carry anyone.Grants beside an empty
388// anyone.grants, and json would decode the first into the second.
389// decodeStrict checks every key against the field names first, at every
390// depth, and then decodes. It refuses a key that appears twice in one
391// object, and any second document.
392func decodeStrict(data []byte, doc any) error {
393 dec := json.NewDecoder(bytes.NewReader(data))
394 if err := checkKeys(dec, reflect.TypeOf(doc), ""); err != nil {
395 return err
396 }
397 if _, err := dec.Token(); err != io.EOF {
398 return errors.New("it holds more than one document")
399 }
400 dec = json.NewDecoder(bytes.NewReader(data))
401 dec.DisallowUnknownFields()
402 return dec.Decode(doc)
403}
404
405var rawMessage = reflect.TypeFor[json.RawMessage]()
406
407// checkKeys reads one value from dec and checks the keys of every object
408// in it against t, the type the value is decoded into. A struct takes the
409// fields its json tags name, spelled exactly. A map takes any key, and a
410// json.RawMessage is taken whole, unread. at is where the value is in the
411// document, for messages, and "" at its top.
412func checkKeys(dec *json.Decoder, t reflect.Type, at string) error {
413 for t.Kind() == reflect.Pointer {
414 t = t.Elem()
415 }
416 tok, err := dec.Token()
417 if err != nil {
418 return err
419 }
420 delim, ok := tok.(json.Delim)
421 if !ok || t == rawMessage {
422 if ok {
423 return skipValue(dec)
424 }
425 return nil
426 }
427 if delim == '[' {
428 elem := t
429 if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
430 elem = t.Elem()
431 }
432 for i := 0; dec.More(); i++ {
433 if err := checkKeys(dec, elem, fmt.Sprintf("%s[%d]", at, i)); err != nil {
434 return err
435 }
436 }
437 _, err := dec.Token()
438 return err
439 }
440 fields := map[string]reflect.Type{}
441 if t.Kind() == reflect.Struct {
442 for i := range t.NumField() {
443 f := t.Field(i)
444 if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name != "" && name != "-" {
445 fields[name] = f.Type
446 }
447 }
448 }
449 seen := map[string]bool{}
450 for dec.More() {
451 tok, err := dec.Token()
452 if err != nil {
453 return err
454 }
455 key := tok.(string)
456 if seen[key] {
457 return fmt.Errorf("%s holds the key %q twice", place(at), key)
458 }
459 seen[key] = true
460 elem, path := t, fmt.Sprintf("%s[%q]", at, key)
461 switch t.Kind() {
462 case reflect.Struct:
463 if elem, ok = fields[key]; !ok {
464 return fmt.Errorf("%s holds the field %q, which is not one of the schema's", place(at), key)
465 }
466 path = strings.TrimPrefix(at+"."+key, ".")
467 case reflect.Map:
468 elem = t.Elem()
469 }
470 if err := checkKeys(dec, elem, path); err != nil {
471 return err
472 }
473 }
474 _, err = dec.Token()
475 return err
476}
477
478// place is where at is in the document, for messages.
479func place(at string) string {
480 if at == "" {
481 return "the document"
482 }
483 return at
484}
485
486// skipValue reads the rest of an object or an array whose opening
487// delimiter dec has read.
488func skipValue(dec *json.Decoder) error {
489 for depth := 1; depth > 0; {
490 tok, err := dec.Token()
491 if err != nil {
492 return err
493 }
494 switch tok {
495 case json.Delim('{'), json.Delim('['):
496 depth++
497 case json.Delim('}'), json.Delim(']'):
498 depth--
499 }
500 }
501 return nil
502}
503
504// cue runs cue with args in dir, and returns what it printed, up to limit
505// bytes, or maxGitOutput when limit is zero. Only what the files decide is
506// an *InvalidError: a run that ends with cueRefused, and a run that prints
507// more than limit. Every other failure is an error of its own: a cue that
508// could not be started, that crashed, that was killed or that ran past the
509// timeout, and a read that was cancelled.
510func (r *Reader) cue(ctx context.Context, dir string, limit int, args ...string) ([]byte, error) {
511 timeout := r.CueTimeout
512 if timeout <= 0 {
513 timeout = time.Minute
514 }
515 cueCtx, cancel := context.WithTimeout(ctx, timeout)
516 defer cancel()
517 cmd := exec.CommandContext(cueCtx, "cue", args...)
518 cmd.Dir = dir
519 cmd.Env = cueEnvironment(os.Environ())
520 if limit == 0 {
521 limit = maxGitOutput
522 }
523 stdout := &bounded{max: limit, strict: true}
524 stderr := &bounded{max: maxStderr}
525 cmd.Stdout, cmd.Stderr = stdout, stderr
526 err := cmd.Run()
527 said := fmt.Sprint(err)
528 if first, _, _ := strings.Cut(strings.TrimSpace(stderr.buf.String()), "\n"); first != "" {
529 said += ": " + first
530 }
531 var exit *exec.ExitError
532 switch {
533 case ctx.Err() != nil:
534 return nil, ctx.Err()
535 case stdout.over:
536 return nil, invalid("cue exported more than %d bytes", limit)
537 case cueCtx.Err() != nil:
538 return nil, fmt.Errorf("cue took longer than %v, so the document was not read", timeout)
539 case errors.As(err, &exit) && exit.ExitCode() == cueRefused:
540 return nil, invalid("cue %s: %s", args[0], said)
541 case errors.As(err, &exit):
542 return nil, fmt.Errorf("cue did not finish reading the document: %s", said)
543 case err != nil:
544 return nil, fmt.Errorf("could not run cue: %w", err)
545 }
546 return stdout.buf.Bytes(), nil
547}
548
549// cueEnvironment is the caller's environment without CUE's own variables,
550// so a document is read the same way whoever reads it.
551func cueEnvironment(environ []string) []string {
552 var env []string
553 for _, kv := range environ {
554 if !strings.HasPrefix(kv, "CUE_") {
555 env = append(env, kv)
556 }
557 }
558 return env
559}
560
561// errTooLong is the error for a program that printed more than its bound.
562var errTooLong = errors.New("it printed more than the reader holds of it")
563
564// git runs git in repo with replacement refs off, pathspecs taken
565// literally and no prompt, and returns what it printed, up to
566// maxGitOutput. It keeps the caller's GIT_CONFIG_* variables, which carry
567// the safe.directory entries a host gives for repositories the caller does
568// not own, and drops the ones that would point git at another repository.
569func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
570 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects", "--literal-pathspecs", "-C", repo}, args...)...)
571 var env []string
572 for _, kv := range os.Environ() {
573 switch name, _, _ := strings.Cut(kv, "="); name {
574 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
575 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES",
576 "GIT_TERMINAL_PROMPT", "GIT_NO_REPLACE_OBJECTS":
577 continue
578 }
579 env = append(env, kv)
580 }
581 cmd.Env = append(env, "GIT_TERMINAL_PROMPT=0", "GIT_NO_REPLACE_OBJECTS=1")
582 stdout := &bounded{max: maxGitOutput, strict: true}
583 stderr := &bounded{max: maxStderr}
584 cmd.Stdout, cmd.Stderr = stdout, stderr
585 err := cmd.Run()
586 if stdout.over {
587 return nil, fmt.Errorf("git %s: %w", args[0], errTooLong)
588 }
589 if err != nil {
590 return nil, fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(stderr.buf.String()))
591 }
592 return stdout.buf.Bytes(), nil
593}
594
595// bounded holds what a program prints, up to max bytes. Past max, a write
596// fails when strict is set, which ends the program at its next write, and
597// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
598// through Write.
599type bounded struct {
600 buf bytes.Buffer
601 max int
602 strict bool
603 over bool
604}
605
606func (b *bounded) Write(p []byte) (int, error) {
607 room := max(b.max-b.buf.Len(), 0)
608 if len(p) <= room {
609 return b.buf.Write(p)
610 }
611 b.over = true
612 b.buf.Write(p[:room])
613 if b.strict {
614 return room, errTooLong
615 }
616 return len(p), nil
617}