gunk-dev/the-valley

read.go

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