gunk-dev/the-valley

read.go

source6a5da001e070main's published tip history
24.7 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// ValidRef reports whether ref is a full ref name, which the registry can be
287// read at: it opens with refs/, and git check-ref-format accepts it. So no
288// component is empty, opens with a dot or ends with .lock, and the name
289// holds no "..", no "@{", no control character, space, ~, ^, :, ?, *, [
290// or backslash, and does not end with a dot.
291func ValidRef(ref string) bool {
292 if !strings.HasPrefix(ref, "refs/") || strings.HasSuffix(ref, ".") ||
293 strings.Contains(ref, "..") || strings.Contains(ref, "@{") ||
294 strings.ContainsFunc(ref, func(r rune) bool { return r < 0x20 || r == 0x7f || strings.ContainsRune(" ~^:?*[\\", r) }) {
295 return false
296 }
297 for _, part := range strings.Split(ref, "/") {
298 if part == "" || strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") {
299 return false
300 }
301 }
302 return true
303}
304
305// ResolveRef reads the object ID that ref, a full ref name, holds in repo.
306// It reads that one ref, with git show-ref. ok is false when repo holds no
307// ref of that name. An error is a repository git could not read.
308//
309// git rev-parse is not used, because it does not stop at the name it is
310// given. When repo holds no refs/heads/registry, rev-parse goes on to try
311// other names, refs/heads/refs/heads/registry among them, and any pusher
312// can make that branch. So a protected ref that is missing would resolve to
313// a ref that no protection covers. Read what the ref holds through the
314// object ID ResolveRef returns, never through the name again.
315func ResolveRef(ctx context.Context, repo, ref string) (oid string, ok bool, err error) {
316 if !ValidRef(ref) {
317 return "", false, fmt.Errorf("%q is not a full ref name", ref)
318 }
319 // show-ref --exists exits 2 for a ref that is missing, and with
320 // another status for a failure to read.
321 _, err = git(ctx, repo, "show-ref", "--exists", "--end-of-options", ref)
322 var exit *exec.ExitError
323 if errors.As(err, &exit) && exit.ExitCode() == 2 {
324 return "", false, nil
325 } else if err != nil {
326 return "", false, err
327 }
328 out, err := git(ctx, repo, "show-ref", "--verify", "--hash", "--end-of-options", ref)
329 if err != nil {
330 return "", false, err
331 }
332 return strings.TrimSpace(string(out)), true, nil
333}
334
335// plainName reports whether name is one plain path component: not empty,
336// not . or .., and with no slash.
337func plainName(name string) bool {
338 return name != "" && name != "." && name != ".." && !strings.Contains(name, "/")
339}
340
341// treeEntry is one entry of a tree, as git ls-tree lists it.
342type treeEntry struct{ mode, kind, oid, name string }
343
344// listTree lists the entries of a tree in repo, as they are stored: a tree
345// written literally can name an entry twice, or with a directory part. dir
346// is where the tree is, for messages.
347func listTree(ctx context.Context, repo, tree, dir string) ([]treeEntry, error) {
348 listing, err := git(ctx, repo, "ls-tree", "-z", tree)
349 if errors.Is(err, errTooLong) {
350 return nil, invalid("%s lists more than %d bytes of entries", dir, maxGitOutput)
351 } else if err != nil {
352 return nil, err
353 }
354 var entries []treeEntry
355 for _, e := range strings.Split(strings.TrimSuffix(string(listing), "\x00"), "\x00") {
356 if e == "" {
357 continue
358 }
359 meta, name, _ := strings.Cut(e, "\t")
360 f := strings.Fields(meta)
361 if len(f) != 3 {
362 return nil, fmt.Errorf("git ls-tree listed %q in %s, which is not an entry", e, dir)
363 }
364 entries = append(entries, treeEntry{f[0], f[1], f[2], name})
365 }
366 return entries, nil
367}
368
369// findDir finds the tree at dir in a commit of repo, one path component at
370// a time. git ls-tree given the path would take the first of two entries
371// of one name, and a tree written literally can hold two: one that
372// consents, and one that does not. So each component is matched by its
373// name exactly, among every entry of the tree above it, and two entries of
374// that name make the document invalid. A component that is not a
375// directory on the way there means there is no document; the directory
376// itself that is not one is invalid.
377func findDir(ctx context.Context, repo, commit, dir string) (string, error) {
378 tree, at := commit, "the commit's root"
379 parts := strings.Split(dir, "/")
380 for i, part := range parts {
381 if !plainName(part) {
382 return "", fmt.Errorf("%q is not a directory a commit can hold", dir)
383 }
384 entries, err := listTree(ctx, repo, tree, at)
385 if err != nil {
386 return "", err
387 }
388 var found []treeEntry
389 for _, e := range entries {
390 if e.name == part {
391 found = append(found, e)
392 }
393 }
394 at = path.Join(parts[:i+1]...)
395 switch {
396 case len(found) == 0:
397 return "", ErrMissing
398 case len(found) > 1:
399 return "", invalid("%s is named by %d entries of its parent, so which is the document is ambiguous", at, len(found))
400 case found[0].kind != "tree" && i < len(parts)-1:
401 return "", ErrMissing
402 case found[0].kind != "tree":
403 return "", invalid("%s is not a directory", dir)
404 }
405 tree = found[0].oid
406 }
407 return tree, nil
408}
409
410// read reads the document in dir at a commit of repo, exports it with cue
411// under schema, and decodes the JSON into doc, which must take every field
412// cue exported. Its error is ErrMissing when the commit holds no document
413// there, an *InvalidError when the document is invalid, and any other
414// error when git or cue could not be run over it.
415func (r *Reader) read(ctx context.Context, repo, commit, dir, schema string, lim bounds, doc any) error {
416 tree, err := findDir(ctx, repo, commit, dir)
417 if err != nil {
418 return err
419 }
420 entries, err := listTree(ctx, repo, tree, dir)
421 if err != nil {
422 return err
423 }
424
425 // A tree git wrote itself never names an entry with a directory part,
426 // nor two entries alike, but one written literally can. Such a
427 // directory is no document: copied out by name, an entry like ../x.cue
428 // would land outside the scratch directory.
429 type document struct{ name, oid string }
430 var docs []document
431 seen := map[string]bool{}
432 for _, e := range entries {
433 if !plainName(e.name) {
434 return invalid("%s holds an entry named %q, which is not a plain file name", dir, e.name)
435 }
436 if seen[e.name] {
437 return invalid("%s holds two entries named %q", dir, e.name)
438 }
439 seen[e.name] = true
440 if !strings.HasSuffix(e.name, ".cue") || e.kind != "blob" || (e.mode != "100644" && e.mode != "100755") {
441 continue
442 }
443 docs = append(docs, document{e.name, e.oid})
444 }
445 if len(docs) == 0 {
446 return ErrMissing
447 }
448 if len(docs) > lim.files {
449 return invalid("%s holds %d documents, more than the %d it may have", dir, len(docs), lim.files)
450 }
451
452 scratch, err := os.MkdirTemp("", "readaccess-")
453 if err != nil {
454 return err
455 }
456 defer os.RemoveAll(scratch)
457 files := []string{"export", "--out", "json", schema}
458 for _, d := range docs {
459 out, err := git(ctx, repo, "cat-file", "-s", d.oid)
460 if err != nil {
461 return err
462 }
463 size, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
464 if err != nil {
465 return fmt.Errorf("git cat-file -s %s: %w", d.oid, err)
466 }
467 if size > lim.file {
468 return invalid("%s/%s is %d bytes, more than the %d a document may be", dir, d.name, size, lim.file)
469 }
470 body, err := git(ctx, repo, "cat-file", "blob", d.oid)
471 if err != nil {
472 return err
473 }
474 file := filepath.Join(scratch, d.name)
475 if err := os.WriteFile(file, body, 0o600); err != nil {
476 return err
477 }
478 files = append(files, file)
479 }
480
481 out, err := r.cue(ctx, scratch, lim.output, files...)
482 if err != nil {
483 return err
484 }
485 if err := decodeStrict(out, doc); err != nil {
486 return invalid("%s is not what its schema exports: %w", dir, err)
487 }
488 return nil
489}
490
491// decodeStrict decodes one JSON document into doc, and refuses any object
492// key that is not a field of doc's type spelled exactly as its json tag
493// spells it. encoding/json matches a key to a field without regard to
494// case, and cue keeps keys that differ in case apart. So a document that
495// reopens a definition could carry anyone.Grants beside an empty
496// anyone.grants, and json would decode the first into the second.
497// decodeStrict checks every key against the field names first, at every
498// depth, and then decodes. It refuses a key that appears twice in one
499// object, and any second document.
500func decodeStrict(data []byte, doc any) error {
501 dec := json.NewDecoder(bytes.NewReader(data))
502 if err := checkKeys(dec, reflect.TypeOf(doc), ""); err != nil {
503 return err
504 }
505 if _, err := dec.Token(); err != io.EOF {
506 return errors.New("it holds more than one document")
507 }
508 dec = json.NewDecoder(bytes.NewReader(data))
509 dec.DisallowUnknownFields()
510 return dec.Decode(doc)
511}
512
513var rawMessage = reflect.TypeFor[json.RawMessage]()
514
515// checkKeys reads one value from dec and checks the keys of every object
516// in it against t, the type the value is decoded into. A struct takes the
517// fields its json tags name, spelled exactly. A map takes any key, and a
518// json.RawMessage is taken whole, unread. at is where the value is in the
519// document, for messages, and "" at its top.
520func checkKeys(dec *json.Decoder, t reflect.Type, at string) error {
521 for t.Kind() == reflect.Pointer {
522 t = t.Elem()
523 }
524 tok, err := dec.Token()
525 if err != nil {
526 return err
527 }
528 delim, ok := tok.(json.Delim)
529 if !ok || t == rawMessage {
530 if ok {
531 return skipValue(dec)
532 }
533 return nil
534 }
535 if delim == '[' {
536 elem := t
537 if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
538 elem = t.Elem()
539 }
540 for i := 0; dec.More(); i++ {
541 if err := checkKeys(dec, elem, fmt.Sprintf("%s[%d]", at, i)); err != nil {
542 return err
543 }
544 }
545 _, err := dec.Token()
546 return err
547 }
548 fields := map[string]reflect.Type{}
549 if t.Kind() == reflect.Struct {
550 for i := range t.NumField() {
551 f := t.Field(i)
552 if name, _, _ := strings.Cut(f.Tag.Get("json"), ","); name != "" && name != "-" {
553 fields[name] = f.Type
554 }
555 }
556 }
557 seen := map[string]bool{}
558 for dec.More() {
559 tok, err := dec.Token()
560 if err != nil {
561 return err
562 }
563 key := tok.(string)
564 if seen[key] {
565 return fmt.Errorf("%s holds the key %q twice", place(at), key)
566 }
567 seen[key] = true
568 elem, path := t, fmt.Sprintf("%s[%q]", at, key)
569 switch t.Kind() {
570 case reflect.Struct:
571 if elem, ok = fields[key]; !ok {
572 return fmt.Errorf("%s holds the field %q, which is not one of the schema's", place(at), key)
573 }
574 path = strings.TrimPrefix(at+"."+key, ".")
575 case reflect.Map:
576 elem = t.Elem()
577 }
578 if err := checkKeys(dec, elem, path); err != nil {
579 return err
580 }
581 }
582 _, err = dec.Token()
583 return err
584}
585
586// place is where at is in the document, for messages.
587func place(at string) string {
588 if at == "" {
589 return "the document"
590 }
591 return at
592}
593
594// skipValue reads the rest of an object or an array whose opening
595// delimiter dec has read.
596func skipValue(dec *json.Decoder) error {
597 for depth := 1; depth > 0; {
598 tok, err := dec.Token()
599 if err != nil {
600 return err
601 }
602 switch tok {
603 case json.Delim('{'), json.Delim('['):
604 depth++
605 case json.Delim('}'), json.Delim(']'):
606 depth--
607 }
608 }
609 return nil
610}
611
612// cue runs cue with args in dir, and returns what it printed, up to limit
613// bytes, or maxGitOutput when limit is zero. Only what the files decide is
614// an *InvalidError: a run that ends with cueRefused, and a run that prints
615// more than limit. Every other failure is an error of its own: a cue that
616// could not be started, that crashed, that was killed or that ran past the
617// timeout, and a read that was cancelled.
618func (r *Reader) cue(ctx context.Context, dir string, limit int, args ...string) ([]byte, error) {
619 timeout := r.CueTimeout
620 if timeout <= 0 {
621 timeout = time.Minute
622 }
623 cueCtx, cancel := context.WithTimeout(ctx, timeout)
624 defer cancel()
625 cmd := exec.CommandContext(cueCtx, "cue", args...)
626 cmd.Dir = dir
627 cmd.Env = cueEnvironment(os.Environ())
628 if limit == 0 {
629 limit = maxGitOutput
630 }
631 stdout := &bounded{max: limit, strict: true}
632 stderr := &bounded{max: maxStderr}
633 cmd.Stdout, cmd.Stderr = stdout, stderr
634 err := cmd.Run()
635 said := fmt.Sprint(err)
636 if first, _, _ := strings.Cut(strings.TrimSpace(stderr.buf.String()), "\n"); first != "" {
637 said += ": " + first
638 }
639 var exit *exec.ExitError
640 switch {
641 case ctx.Err() != nil:
642 return nil, ctx.Err()
643 case stdout.over:
644 return nil, invalid("cue exported more than %d bytes", limit)
645 case cueCtx.Err() != nil:
646 return nil, fmt.Errorf("cue took longer than %v, so the document was not read", timeout)
647 case errors.As(err, &exit) && exit.ExitCode() == cueRefused:
648 return nil, invalid("cue %s: %s", args[0], said)
649 case errors.As(err, &exit):
650 return nil, fmt.Errorf("cue did not finish reading the document: %s", said)
651 case err != nil:
652 return nil, fmt.Errorf("could not run cue: %w", err)
653 }
654 return stdout.buf.Bytes(), nil
655}
656
657// cueEnvironment is the caller's environment without CUE's own variables,
658// so a document is read the same way whoever reads it.
659func cueEnvironment(environ []string) []string {
660 var env []string
661 for _, kv := range environ {
662 if !strings.HasPrefix(kv, "CUE_") {
663 env = append(env, kv)
664 }
665 }
666 return env
667}
668
669// errTooLong is the error for a program that printed more than its bound.
670var errTooLong = errors.New("it printed more than the reader holds of it")
671
672// git runs git in repo with replacement refs off, pathspecs taken
673// literally and no prompt, and returns what it printed, up to
674// maxGitOutput. It keeps the caller's GIT_CONFIG_* variables, which carry
675// the safe.directory entries a host gives for repositories the caller does
676// not own, and drops the ones that would point git at another repository.
677func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
678 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects", "--literal-pathspecs", "-C", repo}, args...)...)
679 var env []string
680 for _, kv := range os.Environ() {
681 switch name, _, _ := strings.Cut(kv, "="); name {
682 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
683 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES",
684 "GIT_TERMINAL_PROMPT", "GIT_NO_REPLACE_OBJECTS":
685 continue
686 }
687 env = append(env, kv)
688 }
689 cmd.Env = append(env, "GIT_TERMINAL_PROMPT=0", "GIT_NO_REPLACE_OBJECTS=1")
690 stdout := &bounded{max: maxGitOutput, strict: true}
691 stderr := &bounded{max: maxStderr}
692 cmd.Stdout, cmd.Stderr = stdout, stderr
693 err := cmd.Run()
694 if stdout.over {
695 return nil, fmt.Errorf("git %s: %w", args[0], errTooLong)
696 }
697 if err != nil {
698 return nil, fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(stderr.buf.String()))
699 }
700 return stdout.buf.Bytes(), nil
701}
702
703// bounded holds what a program prints, up to max bytes. Past max, a write
704// fails when strict is set, which ends the program at its next write, and
705// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
706// through Write.
707type bounded struct {
708 buf bytes.Buffer
709 max int
710 strict bool
711 over bool
712}
713
714func (b *bounded) Write(p []byte) (int, error) {
715 room := max(b.max-b.buf.Len(), 0)
716 if len(p) <= room {
717 return b.buf.Write(p)
718 }
719 b.over = true
720 b.buf.Write(p[:room])
721 if b.strict {
722 return room, errTooLong
723 }
724 return len(p), nil
725}