gunk-dev/the-valley

approval.go

source601b054bc28emain's published tip history
27.0 KiB
1package main
2
3// Whether a signed approval authorizes a recorded request.
4//
5// verifyApproval checks one approval note (the approval package) against
6// the integration request it would let land: the note's signature under
7// one selected list of approval keys, the scope and head it names, that
8// head itself, and the change record's history from the record the
9// approver signed to the record read as current. It reads the objects it
10// is given by ID, the record commits between them and the type of each
11// head they add, and nothing else: no ref, no file and no clock. Which
12// list it is given, which record commit is current, and whether the
13// inputs still hold once it has answered, are for its caller.
14//
15// Every value it did not write itself, from the query, the note, the
16// list, the repository or git, is quoted in what it returns.
17
18import (
19 "bufio"
20 "bytes"
21 "context"
22 "encoding/hex"
23 "errors"
24 "fmt"
25 "io"
26 "os"
27 "os/exec"
28 "strconv"
29 "strings"
30 "time"
31
32 "the-valley/approval"
33 "the-valley/change"
34 "the-valley/note"
35)
36
37// The basenames of the two approval lists `identity compile` writes. A
38// policy that requires a hardware key selects the hardware list, and every
39// other policy the general one; neither stands in for the other.
40const (
41 approvalSignersFile = "approval-signers"
42 approvalSignersHardwareFile = "approval-signers-hardware"
43)
44
45// approvalQuery is what an approval is checked against. The caller reads
46// every input and answers for where it came from: the evaluator cannot
47// tell who published a record or a note, or whether a ref still holds
48// what was read from it.
49type approvalQuery struct {
50 // note is the approval note's blob, as the caller read it at
51 // approval.Ref, and record the change record commit the caller reads
52 // as current, at change.Ref of the target and the change. Both are
53 // object IDs, so what is checked cannot move while it is read.
54 note, record string
55
56 // instance, project, target and changeID are the scope the approval
57 // must name: the instance identity (approval.InstanceID), the
58 // project, the target as a branch name, and the change ID. Any
59 // target a record can name is taken; which targets carry records is
60 // the push hook's rule.
61 instance, project, target, changeID string
62
63 // head is the commit the request files, as an object ID.
64 head string
65
66 // hardware is whether the composed policy requires a hardware key.
67 // authorityName and authority are the one list selected for it: its
68 // basename and its whole content, as the caller read it.
69 hardware bool
70 authorityName string
71 authority []byte
72}
73
74// proofKind names what a proof is made of.
75type proofKind string
76
77// proofSignedNote is a proof that is a signed approval note.
78const proofSignedNote proofKind = "signed-note"
79
80// proof is one piece of what authorizes a request, as it was verified.
81type proof struct {
82 kind proofKind
83 signedNote signedNoteProof
84}
85
86// signedNoteProof is a verified approval note and what it was verified
87// against. It shares no memory with the query.
88type signedNoteProof struct {
89 statement approval.Statement
90 // note is the note's exact bytes.
91 note []byte
92 // authorityName and authority are the selected list the signature
93 // verified under, whole.
94 authorityName string
95 authority []byte
96 // records is each record commit the history walk read, from the
97 // current record to the signed one.
98 records []string
99}
100
101// approvalReason is why an approval does not authorize a request.
102type approvalReason string
103
104const (
105 // approvalInvalid is a note that is missing, not a blob, past
106 // approval.MaxNote, not in an approval note's form, or whose
107 // signature does not verify under the listed key it names.
108 approvalInvalid approvalReason = "approval-invalid"
109 // authorityInvalid is a list that is not the one the policy selects,
110 // or that does not read as verifier keys.
111 authorityInvalid approvalReason = "authority-invalid"
112 // keyNotListed is a note signed by a key the selected list does not
113 // hold under the approver's name. An empty list holds none.
114 keyNotListed approvalReason = "key-not-listed"
115 // scopeMismatch is an approval naming another instance, project,
116 // target or change.
117 scopeMismatch approvalReason = "scope-mismatch"
118 // requestMismatch is an approval of another head than the request's,
119 // a request head that is not a commit in the repository, or an
120 // approved version that does not have that head in the signed or the
121 // current record.
122 requestMismatch approvalReason = "request-mismatch"
123 // historyInvalid is a record history that readyHistory does not walk
124 // from the current record to the signed one, or a record on it that
125 // is missing or malformed.
126 historyInvalid approvalReason = "history-invalid"
127 // notReady is a record from the signed one to the current one that is
128 // not ready.
129 notReady approvalReason = "not-ready"
130)
131
132// approvalRefusal is a refusal's reason, and what was found.
133type approvalRefusal struct {
134 reason approvalReason
135 why string
136}
137
138func (r *approvalRefusal) Error() string { return string(r.reason) + ": " + r.why }
139
140func refuse(reason approvalReason, format string, args ...any) error {
141 return &approvalRefusal{reason: reason, why: fmt.Sprintf(format, args...)}
142}
143
144// approvalResult is what verifyApproval decides, read through its
145// methods. Authorized is the one way to learn that an approval authorizes
146// a request, and only verifyApproval's success sets what it reports, so
147// the zero value, a refusal and an error all report not authorized.
148type approvalResult struct {
149 authorized bool
150 proofs []proof
151 refusal *approvalRefusal
152 err error
153}
154
155// Authorized returns the proofs and true when the approval authorizes the
156// request, and nil and false otherwise.
157func (r approvalResult) Authorized() ([]proof, bool) {
158 if !r.authorized || len(r.proofs) == 0 {
159 return nil, false
160 }
161 return r.proofs, true
162}
163
164// Refusal is why the approval does not authorize the request, or nil when
165// it does or when nothing was decided.
166func (r approvalResult) Refusal() *approvalRefusal { return r.refusal }
167
168// Err is why nothing was decided: a query that is not well formed, ctx
169// ending, or git failing to answer. It is nil when a decision was made.
170func (r approvalResult) Err() error { return r.err }
171
172// verifyApproval decides whether the approval note q.note authorizes the
173// request q describes, in repo. When it does, the result's Authorized
174// reports the proofs, one signed-note proof; otherwise it reports false,
175// and the result carries the refusal or the error.
176//
177// ctx must carry a deadline or a cancellation: the evaluator sets none,
178// and a git that stops answering holds it until ctx ends.
179//
180// The approval authorizes the request when:
181//
182// - q.authorityName is the list q.hardware selects, and q.authority
183// reads as verifier keys;
184// - the note is a blob of at most approval.MaxNote bytes in an approval
185// note's form, signed by a key the list holds under the statement's
186// principal, who need not own the change;
187// - the statement names q's instance, project, target and change, and
188// q.head as its head, and q.head is a commit;
189// - the record it signed (statement.Record) and q.record are records of
190// q's change and target, both ready, and both give the signed version
191// the signed head;
192// - readyHistory walks from q.record to the signed record.
193func verifyApproval(ctx context.Context, repo string, q approvalQuery) approvalResult {
194 proofs, err := checkApproval(ctx, repo, q)
195 var refusal *approvalRefusal
196 switch {
197 case errors.As(err, &refusal):
198 return approvalResult{refusal: refusal}
199 case err != nil:
200 return approvalResult{err: err}
201 }
202 return approvalResult{authorized: true, proofs: proofs}
203}
204
205func checkApproval(ctx context.Context, repo string, q approvalQuery) ([]proof, error) {
206 for _, id := range []string{q.note, q.record, q.head} {
207 if !isObjectID(id) {
208 return nil, fmt.Errorf("%q is not 40 lowercase hex digits", id)
209 }
210 }
211 if !change.ValidBranch(q.target) || !change.ValidID(q.changeID) {
212 return nil, fmt.Errorf("the target %q or the change %q is not one a record names", q.target, q.changeID)
213 }
214
215 selected := approvalSignersFile
216 if q.hardware {
217 selected = approvalSignersHardwareFile
218 }
219 if q.authorityName != selected {
220 return nil, refuse(authorityInvalid, "the policy selects %s, and the list given is %q", selected, q.authorityName)
221 }
222 authority := bytes.Clone(q.authority)
223 keys, err := note.ParseVerifierKeys(authority)
224 if err != nil {
225 return nil, refuse(authorityInvalid, "%s does not read: %q", selected, err.Error())
226 }
227
228 objects, err := openObjectReader(ctx, repo)
229 if err != nil {
230 return nil, err
231 }
232 defer objects.close()
233
234 body, err := objects.read(q.note, "blob", approval.MaxNote)
235 if err != nil {
236 return nil, asRefusal(err, approvalInvalid, "the approval note %q", q.note)
237 }
238 s, err := openApproval(body, keys, selected)
239 if err != nil {
240 return nil, err
241 }
242 switch {
243 case s.Instance != q.instance:
244 return nil, refuse(scopeMismatch, "it approves for the instance %q, not %q", s.Instance, q.instance)
245 case s.Project != q.project:
246 return nil, refuse(scopeMismatch, "it approves for the project %q, not %q", s.Project, q.project)
247 case s.Target != q.target:
248 return nil, refuse(scopeMismatch, "it approves landing on %q, not %q", s.Target, q.target)
249 case s.Change != q.changeID:
250 return nil, refuse(scopeMismatch, "it approves the change %q, not %q", s.Change, q.changeID)
251 case s.Head != change.HeadPrefix+q.head:
252 return nil, refuse(requestMismatch, "it approves the head %q, and the request files %q", s.Head, q.head)
253 }
254 // Whatever the walk reads, the head that would land is a commit: when
255 // the signed record is the current one, the walk checks no head.
256 if kind, _, err := objects.info(q.head); err != nil {
257 return nil, asRefusal(err, requestMismatch, "the request's head %q", q.head)
258 } else if kind != "commit" {
259 return nil, refuse(requestMismatch, "the request's head %q is a %q, and a head is a commit", q.head, kind)
260 }
261
262 signed := strings.TrimPrefix(s.Record, change.HeadPrefix)
263 walked, err := readyHistory(objects, q.record, signed, q.target, q.changeID, s.Version, s.Head)
264 if err != nil {
265 return nil, err
266 }
267 return []proof{{kind: proofSignedNote, signedNote: signedNoteProof{
268 statement: s,
269 note: body,
270 authorityName: q.authorityName,
271 authority: authority,
272 records: walked,
273 }}}, nil
274}
275
276// openApproval reads an approval note's form and verifies its signature
277// under keys. ParseNote holds the note to one signature named by the
278// statement's principal, and a verifier key matches a signature only under
279// its own name, so the key that verifies is listed under that principal.
280func openApproval(body []byte, keys []note.VerifierKey, list string) (approval.Statement, error) {
281 s, err := approval.ParseNote(body)
282 if err != nil {
283 return approval.Statement{}, refuse(approvalInvalid, "the approval note does not read: %q", err.Error())
284 }
285 _, sigs, err := note.Split(body)
286 if err != nil {
287 return approval.Statement{}, refuse(approvalInvalid, "the approval note does not read: %q", err.Error())
288 }
289 listed := false
290 for _, k := range keys {
291 listed = listed || k.Name == sigs[0].Name && k.Hash == sigs[0].Hash
292 }
293 if !listed {
294 return approval.Statement{}, refuse(keyNotListed, "it is signed by %q, a key %s does not list", fmt.Sprintf("%s+%08x", sigs[0].Name, sigs[0].Hash), list)
295 }
296 if _, err := approval.Verify(body, keys); err != nil {
297 return approval.Statement{}, refuse(approvalInvalid, "its signature does not verify: %q", err.Error())
298 }
299 return s, nil
300}
301
302// readyHistory walks first parents from the current record commit to the
303// signed one, and stops there. It returns each record commit it read, the
304// current one first.
305//
306// The signed record must be ready and give version n the head head; so
307// must the current one, and the two may be the same commit. Each record
308// after the signed one must be ready, as must the record before it, and
309// must be what the push hook's new-version row admits
310// (valleyhook/record.go, checkUpdate and checkNewVersion): two parents,
311// the first the record it replaces and the second a commit, the head of
312// the one version it adds; every earlier version and the owner kept; the
313// seq raised by one; and the new version, at a head other than the active
314// one, made active. A record whose one parent is the record it replaces
315// changes the state by the hook's rules (checkStateChange), so between two
316// ready records it is refused.
317//
318// The walk does not check what the hook decides by who pushed: that the
319// new version's uploader is the pusher, and that a restack keeps the
320// active version's branch and title. Nor does it check that the target is
321// one the hook keeps records for. It cannot establish who published a
322// record, or that the current record is the one its ref holds; the caller
323// reads that commit from the governed record ref.
324//
325// The second parent is never followed, so a signed record reachable only
326// through a version's head is not reached. Nothing before the signed
327// record is read: a withdrawal there, then a fresh ready and a fresh
328// approval, is a history like any other. A record history deleted and
329// written again with identical objects reads as the history it repeats;
330// only retaining records rules that out.
331//
332// Each step raises the seq by one and adds a version, so the walk takes
333// fewer steps than the current record holds versions, and stops once the
334// seq reaches the signed record's.
335func readyHistory(objects *objectReader, current, signed, target, id string, n int, head string) ([]string, error) {
336 s, err := readRecordCommit(objects, signed, target, id)
337 if err != nil {
338 return nil, asRefusal(err, historyInvalid, "the signed record %q", signed)
339 }
340 if s.record.State != change.Ready {
341 return nil, refuse(notReady, "the signed record %q says the change is %q", signed, s.record.State)
342 }
343 if !namesVersion(s.record, n, head) {
344 return nil, refuse(requestMismatch, "the signed record %q gives v%d no head %q", signed, n, head)
345 }
346
347 walked := []string{current}
348 at := current
349 cur, err := readRecordCommit(objects, current, target, id)
350 if err != nil {
351 return nil, asRefusal(err, historyInvalid, "the current record %q", current)
352 }
353 if cur.record.State != change.Ready {
354 return nil, refuse(notReady, "the current record %q says the change is %q", current, cur.record.State)
355 }
356 if !namesVersion(cur.record, n, head) {
357 return nil, refuse(requestMismatch, "the current record %q gives v%d no head %q", current, n, head)
358 }
359 for at != signed {
360 if cur.record.Seq <= s.record.Seq {
361 return nil, refuse(historyInvalid, "the record %q at seq %d is not the signed record %q, whose seq is %d", at, cur.record.Seq, signed, s.record.Seq)
362 }
363 before := cur.parents[0]
364 prev, err := readRecordCommit(objects, before, target, id)
365 if err != nil {
366 return nil, asRefusal(err, historyInvalid, "the record %q, first parent of %q,", before, at)
367 }
368 if prev.record.State != change.Ready {
369 return nil, refuse(notReady, "the record %q, between the signed and the current record, says the change is %q", before, prev.record.State)
370 }
371 if len(cur.parents) != 2 {
372 return nil, refuse(historyInvalid, "the record %q has one parent, and a ready record after the signed one adds a version: its parents are the record it replaces and the version's head", at)
373 }
374 added := cur.parents[1]
375 if why := addedVersion(prev.record, cur.record, added); why != "" {
376 return nil, refuse(historyInvalid, "the record %q does not add a version to %q: %s", at, before, why)
377 }
378 if kind, _, err := objects.info(added); err != nil {
379 return nil, asRefusal(err, historyInvalid, "the head %q of the record %q", added, at)
380 } else if kind != "commit" {
381 return nil, refuse(historyInvalid, "the record %q adds a version at %q, a %q, and a head is a commit", at, added, kind)
382 }
383 walked = append(walked, before)
384 at, cur = before, prev
385 }
386 return walked, nil
387}
388
389// addedVersion holds after to adding one version, at head h, to before, by
390// the hook's new-version row (valleyhook/record.go, checkNewVersion) less
391// its uploader rule. It returns why not, or "".
392func addedVersion(before, after *change.Record, h string) string {
393 if len(after.Versions) != len(before.Versions)+1 {
394 return fmt.Sprintf("it holds %d versions, and the record before it %d", len(after.Versions), len(before.Versions))
395 }
396 for i, v := range before.Versions {
397 if after.Versions[i] != v {
398 return fmt.Sprintf("it changes version %d", v.N)
399 }
400 }
401 v := after.Last()
402 switch {
403 case v.Head != change.HeadPrefix+h:
404 return fmt.Sprintf("its new version names the head %q, and its second parent is %q", v.Head, h)
405 case v.Head == before.ActiveVersion().Head:
406 return "its new version's head is the active version's"
407 case after.Active != v.N:
408 return fmt.Sprintf("its active is %d, not its new version, %d", after.Active, v.N)
409 case after.Seq != before.Seq+1:
410 return fmt.Sprintf("its seq is %d, and the record before it is at %d", after.Seq, before.Seq)
411 case after.Owner != before.Owner:
412 return fmt.Sprintf("it changes the owner from %q to %q", before.Owner, after.Owner)
413 }
414 return ""
415}
416
417// namesVersion reports whether r gives version n the head head.
418func namesVersion(r *change.Record, n int, head string) bool {
419 return n >= 1 && n <= len(r.Versions) && r.Versions[n-1].Head == head
420}
421
422// recordCommit is a record commit as read: its parents, in order, and its
423// record.
424type recordCommit struct {
425 parents []string
426 record *change.Record
427}
428
429// readRecordCommit reads the record commit id with the layout and bounds
430// the push hook reads one with (valleyhook/record.go: readFileCommit, and
431// checkCreate and checkUpdate for its parents): a commit of one or two
432// parents whose tree holds record.json alone, as a plain file, each object
433// held to its bound before its content is read, and a record of change
434// changeID for target.
435func readRecordCommit(objects *objectReader, id, target, changeID string) (recordCommit, error) {
436 body, err := objects.read(id, "commit", change.MaxRecordCommit)
437 if err != nil {
438 return recordCommit{}, err
439 }
440 tree, parents, err := recordLinks(body)
441 if err != nil {
442 return recordCommit{}, err
443 }
444 if len(parents) < 1 || len(parents) > 2 {
445 return recordCommit{}, objectRefusal{fmt.Sprintf("has %d parents, and a record commit has one or two", len(parents))}
446 }
447 entries, err := objects.read(tree, "tree", change.MaxRecordTree)
448 if err != nil {
449 return recordCommit{}, about(err, "has a tree that")
450 }
451 const entry = "100644 record.json\x00"
452 if len(entries) != len(entry)+20 || !bytes.HasPrefix(entries, []byte(entry)) {
453 return recordCommit{}, objectRefusal{"has a tree that does not hold record.json alone, as a plain file"}
454 }
455 data, err := objects.read(hex.EncodeToString(entries[len(entry):]), "blob", change.MaxRecordBlob)
456 if err != nil {
457 return recordCommit{}, about(err, "has a record.json that")
458 }
459 r, err := change.Parse(data)
460 if err != nil {
461 return recordCommit{}, objectRefusal{fmt.Sprintf("holds a record.json that does not read: %q", err.Error())}
462 }
463 if r.ChangeID != changeID || r.Target != target {
464 return recordCommit{}, objectRefusal{fmt.Sprintf("records change %q for %q, not %q for %q", r.ChangeID, r.Target, changeID, target)}
465 }
466 return recordCommit{parents: parents, record: r}, nil
467}
468
469// recordLinks reads the tree and the parents out of a commit as git does,
470// and as the hook does (valleyhook/record.go, commitLinks): a tree line
471// first, then the parent lines that follow it directly. A parent line
472// anywhere later is refused rather than read two ways.
473func recordLinks(body []byte) (tree string, parents []string, err error) {
474 header, _, _ := bytes.Cut(body, []byte("\n\n"))
475 lines := strings.Split(string(header), "\n")
476 tree, ok := strings.CutPrefix(lines[0], "tree ")
477 if !ok || !isObjectID(tree) {
478 return "", nil, objectRefusal{"does not open with its tree"}
479 }
480 rest := lines[1:]
481 for len(rest) > 0 && strings.HasPrefix(rest[0], "parent ") {
482 parent := strings.TrimPrefix(rest[0], "parent ")
483 if !isObjectID(parent) {
484 return "", nil, objectRefusal{"names a parent that is not an object ID"}
485 }
486 parents = append(parents, parent)
487 rest = rest[1:]
488 }
489 for _, line := range rest {
490 if strings.HasPrefix(line, "parent ") {
491 return "", nil, objectRefusal{"names a parent after its other headers"}
492 }
493 }
494 return tree, parents, nil
495}
496
497// objectRefusal is an object that is missing, or not what it must be. Any
498// other error from reading one is git failing to answer.
499type objectRefusal struct{ why string }
500
501func (o objectRefusal) Error() string { return o.why }
502
503// about names the object a refusal is about, inside the one read.
504func about(err error, prefix string) error {
505 var o objectRefusal
506 if errors.As(err, &o) {
507 return objectRefusal{prefix + " " + o.why}
508 }
509 return err
510}
511
512// asRefusal is err as a refusal for reason, about the object the format
513// names, when err says the object is missing or malformed, and err itself
514// otherwise.
515func asRefusal(err error, reason approvalReason, format string, args ...any) error {
516 var o objectRefusal
517 if errors.As(err, &o) {
518 return refuse(reason, "%s %s", fmt.Sprintf(format, args...), o.why)
519 }
520 return err
521}
522
523// stderrBound is how much of what git writes to stderr is kept for an
524// error: room for the fatal line git ends with.
525const stderrBound = 4 << 10
526
527// objectReader reads objects by ID out of one `git cat-file
528// --batch-command`, asking for an object's type and size before its
529// content, so an object past a bound is never read. asked is each command
530// sent, in order.
531//
532// git runs in the controller's environment (gitEnvironment), built here
533// rather than inherited, so no GIT_ variable of the process's points it at
534// other objects or configuration. Replacement refs are off, so an object
535// ID reads as the object it names, and lazy fetching is off, so an object
536// the repository lacks is missing rather than fetched from a promisor
537// remote its configuration names.
538//
539// When ctx ends, git is killed and its pipes are closed, so a read or a
540// write blocked on them returns.
541type objectReader struct {
542 ctx context.Context
543 cmd *exec.Cmd
544 in, pipe *os.File // the ends of git's stdin and stdout this process holds
545 out *bufio.Reader
546 stderr *firstBytes
547 stop func() bool
548 closed bool
549 asked []string
550}
551
552func openObjectReader(ctx context.Context, repo string) (*objectReader, error) {
553 cmd := exec.CommandContext(ctx, "git", "--no-replace-objects", "cat-file", "--batch-command")
554 cmd.Dir = repo
555 cmd.Env = append(gitEnvironment(os.Environ()), "GIT_NO_LAZY_FETCH=1")
556 stderr := &firstBytes{max: stderrBound}
557 cmd.Stderr = stderr
558 // Once git has exited or been killed, Wait waits this long at most
559 // for stderr to close: only a process git started could hold it open
560 // past git, and nothing in this read starts one.
561 cmd.WaitDelay = time.Second
562 // The pipes are made here rather than by exec, so every way of
563 // failing to start closes each end it opened.
564 stdin, in, err := os.Pipe()
565 if err != nil {
566 return nil, quotedError{"git cat-file has no input pipe", err}
567 }
568 pipe, stdout, err := os.Pipe()
569 if err != nil {
570 _, _ = stdin.Close(), in.Close()
571 return nil, quotedError{"git cat-file has no output pipe", err}
572 }
573 cmd.Stdin, cmd.Stdout = stdin, stdout
574 err = cmd.Start()
575 // A started git holds its own copies of its ends.
576 _, _ = stdin.Close(), stdout.Close()
577 if err != nil {
578 _, _ = in.Close(), pipe.Close()
579 return nil, quotedError{"git cat-file does not start", err}
580 }
581 stop := context.AfterFunc(ctx, func() {
582 _, _ = in.Close(), pipe.Close()
583 })
584 return &objectReader{ctx: ctx, cmd: cmd, in: in, pipe: pipe, out: bufio.NewReader(pipe), stderr: stderr, stop: stop}, nil
585}
586
587// info is the type and size of object id.
588func (o *objectReader) info(id string) (kind string, size int, err error) {
589 return o.ask("info", id)
590}
591
592func (o *objectReader) ask(command, id string) (kind string, size int, err error) {
593 if err := o.ctx.Err(); err != nil {
594 return "", 0, o.failed(err)
595 }
596 o.asked = append(o.asked, command+" "+id)
597 if _, err := fmt.Fprintf(o.in, "%s %s\n", command, id); err != nil {
598 return "", 0, o.failed(err)
599 }
600 header, err := o.out.ReadString('\n')
601 if err != nil {
602 return "", 0, o.failed(err)
603 }
604 fields := strings.Fields(header)
605 if len(fields) == 2 && fields[0] == id && fields[1] == "missing" {
606 return "", 0, objectRefusal{"is not in the repository"}
607 }
608 if len(fields) != 3 || fields[0] != id {
609 return "", 0, fmt.Errorf("git cat-file answered %q for %q", strings.TrimSpace(header), id)
610 }
611 size, err = strconv.Atoi(fields[2])
612 if err != nil || size < 0 {
613 return "", 0, fmt.Errorf("git cat-file answered %q for %q", strings.TrimSpace(header), id)
614 }
615 return fields[1], size, nil
616}
617
618// read is the content of object id, which must be of type kind and at
619// most max bytes.
620func (o *objectReader) read(id, kind string, max int) ([]byte, error) {
621 got, size, err := o.info(id)
622 switch {
623 case err != nil:
624 return nil, err
625 case got != kind:
626 return nil, objectRefusal{fmt.Sprintf("is a %q, not a %s", got, kind)}
627 case size > max:
628 return nil, objectRefusal{fmt.Sprintf("is a %s of %d bytes, more than %d", kind, size, max)}
629 }
630 again, confirmed, err := o.ask("contents", id)
631 if err != nil {
632 return nil, err
633 }
634 if again != kind || confirmed != size {
635 return nil, fmt.Errorf("git cat-file sized %q as a %s of %d bytes, and then read a %q of %d", id, kind, size, again, confirmed)
636 }
637 body := make([]byte, size+1) // the content and git's closing newline
638 if _, err := io.ReadFull(o.out, body); err != nil {
639 return nil, o.failed(err)
640 }
641 return body[:size], nil
642}
643
644// failed is the error for a read or a write of git's pipes that failed:
645// ctx's, once it has ended, since that is what closes them, and otherwise
646// what git wrote to stderr before it exited, once it is reaped.
647func (o *objectReader) failed(err error) error {
648 if ctxErr := o.ctx.Err(); ctxErr != nil {
649 return quotedError{"git cat-file stopped", ctxErr}
650 }
651 o.close()
652 return quotedError{fmt.Sprintf("git cat-file wrote %q to stderr", o.stderr.b), err}
653}
654
655// close kills git and reaps it. git is killed rather than asked to
656// finish: a read that stopped early may have left content in its pipe.
657func (o *objectReader) close() {
658 if o.closed {
659 return
660 }
661 o.closed = true
662 o.stop()
663 _ = o.cmd.Process.Kill()
664 _ = o.cmd.Wait()
665 _, _ = o.in.Close(), o.pipe.Close()
666}
667
668// quotedError is an error from the operating system or git, quoted, so a
669// path or a line it carries cannot put a newline or a control byte into a
670// message, while errors.Is and errors.As still reach it.
671type quotedError struct {
672 context string
673 err error
674}
675
676func (e quotedError) Error() string { return e.context + ": " + strconv.Quote(e.err.Error()) }
677
678func (e quotedError) Unwrap() error { return e.err }
679
680// firstBytes keeps the first max bytes written to it and drops the rest,
681// taking every write whole so git never waits on it.
682type firstBytes struct {
683 b []byte
684 max int
685}
686
687func (f *firstBytes) Write(p []byte) (int, error) {
688 if room := f.max - len(f.b); room > 0 {
689 f.b = append(f.b, p[:min(room, len(p))]...)
690 }
691 return len(p), nil
692}
693
694// isObjectID reports whether s is a SHA-1 object ID, the one object format
695// a record's heads name.
696func isObjectID(s string) bool {
697 if len(s) != 40 {
698 return false
699 }
700 for _, c := range []byte(s) {
701 if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
702 return false
703 }
704 }
705 return true
706}