gunk-dev/the-valley

read.go

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