gunk-dev/the-valley

read.go

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