gunk-dev/the-valley

repo.go

sourceb115ae7362ffmain's published tip history
18.5 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "os"
12 "os/exec"
13 "sort"
14 "strconv"
15 "strings"
16 "time"
17
18 "the-valley/change"
19)
20
21// gitProgram is the git this program runs. The package sets it at build
22// time to an absolute store path, so nothing in a caller's PATH decides
23// which git reads the repository.
24var gitProgram = "git"
25
26// repository is what a decision needs to know about the repository a push
27// is landing in.
28type repository interface {
29 // symbolic reports which of refs are symbolic refs there now, all in
30 // one read.
31 symbolic(refs []string) (map[string]bool, error)
32 // notes returns every blob under the tree id names, keyed by path,
33 // or an error saying why id is not such a tree.
34 notes(id string) (map[string][]byte, error)
35 // record reads the change record commit id names (record.go): its
36 // parents, and the record.json its tree holds, or an error saying why
37 // id is not such a commit.
38 record(id string) (fileCommit, error)
39 // report reads the restack report commit id names (report.go) the
40 // same way: its parents, and the report.json its tree holds.
41 report(id string) (fileCommit, error)
42 // approval reads the approval note blob id names (approval.go), or
43 // returns an error saying why id is not such a blob.
44 approval(id string) ([]byte, error)
45 // hasRecord reports whether the repository holds a record of the
46 // change with the ID given now.
47 hasRecord(id string) (bool, error)
48 // ref is the object the ref named exactly holds now, and false when
49 // the repository holds no such ref.
50 ref(name string) (string, bool, error)
51 // kind is the type of the object id names.
52 kind(id string) (string, error)
53 // records counts the change records the repository holds now, with
54 // one for-each-ref.
55 records() (int, error)
56 // checkRequests counts the check requests the principal named holds
57 // now, with one for-each-ref (checkrequest.go).
58 checkRequests(principal string) (int, error)
59 // graph opens a reading of the plan graph's objects (knots.go),
60 // within the graph's own bounds.
61 graph() (graphReader, error)
62}
63
64// ref reads the one ref named, exactly, with show-ref --verify, which
65// lists nothing: however many refs a push has left beneath the name, the
66// read is one ref and its object ID. When that read fails, show-ref
67// --exists tells a ref that is not there (status 2) from a failure.
68func (gitRepository) ref(name string) (string, bool, error) {
69 out, err := run(nil, "show-ref", "--verify", "--hash", "--", name)
70 if err != nil {
71 _, missing := run(nil, "show-ref", "--exists", "--", name)
72 var exit *exec.ExitError
73 if errors.As(missing, &exit) && exit.ExitCode() == 2 {
74 return "", false, nil
75 }
76 return "", false, err
77 }
78 oid := strings.TrimSpace(string(out))
79 if !isHexID(oid, 20) && !isHexID(oid, 32) {
80 return "", false, fmt.Errorf("git show-ref read %q for %s, which is no object ID", oid, name)
81 }
82 return oid, true, nil
83}
84
85// budget is what one reading of pushed objects may cost: how deep its
86// trees nest, the root's counted as 1; the entries in any one tree and in
87// the whole walk; the bytes in any one tree and in any one file; the bytes
88// read in all; and, when it is not zero, how long the reading may take.
89// The bounds exist because what is read is a pushed object, and git trees
90// can share subtrees: a few dozen small trees, each naming the next many
91// times over, describe more paths than any machine can walk. A walk
92// counts every entry it visits, a shared subtree once per time it is
93// named, and stops at the first bound it would cross, before reading or
94// allocating anything past it. Each reader passes its own budget.
95type budget struct {
96 // subject is what the objects make up, as a refusal names it.
97 subject string
98 depth, entriesInTree, entries int
99 treeSize, fileSize, bytes int
100 deadline time.Duration
101}
102
103// The bounds on reading an attestation ref. attest writes a tree holding
104// one subtree per check, each holding one note. The integrator adds its
105// countersignatures there, and writes its transfer statements two levels
106// of directories down from transfer.d (change.TransferPath), so a tree it
107// writes is four trees deep. Every bound is shared with the integrator,
108// which refuses to write a tree past any of them.
109const (
110 maxDepth = change.AttestationDepth // trees from the ref's tree down, inclusive
111 maxEntriesInTree = change.AttestationTreeEntries // entries in any one tree
112 maxEntries = change.AttestationEntries // entries visited in the whole walk
113 maxTreeSize = change.AttestationTreeBytes // bytes in any one tree object
114 maxNoteSize = change.AttestationNoteBytes // bytes in any one note
115 maxBytes = change.AttestationBytes // bytes read in the whole walk
116)
117
118// context is a context for one reading within the budget: it ends when the
119// deadline passes, if the budget has one, and when it is cancelled.
120func (b budget) context() (context.Context, context.CancelFunc) {
121 if b.deadline > 0 {
122 return context.WithTimeout(context.Background(), b.deadline)
123 }
124 return context.WithCancel(context.Background())
125}
126
127var attestationBudget = budget{
128 subject: "an attestation", depth: maxDepth, entriesInTree: maxEntriesInTree, entries: maxEntries,
129 treeSize: maxTreeSize, fileSize: maxNoteSize, bytes: maxBytes,
130}
131
132// gitRepository reads the repository the hook runs in. receive-pack runs
133// the hook inside the repository, with the pushed objects in a quarantine
134// directory its environment names, so the objects a push brings are
135// readable here before any ref points at them.
136type gitRepository struct{}
137
138// symbolic asks git, with git symbolic-ref, whether each of refs is a
139// symbolic ref. It is git's own reading, so it agrees with git on every
140// form git accepts: "ref:" followed by any white space, a filesystem
141// symlink in the files backend, any other ref storage, and a dangling
142// symbolic ref that names a ref which does not exist. for-each-ref skips a
143// dangling one, and a push through it would create the ref it names,
144// which could be a protected main a project does not have yet. That is one
145// git call per ref, and preReceive bounds a push at maxUpdates refs.
146func (gitRepository) symbolic(refs []string) (map[string]bool, error) {
147 found := map[string]bool{}
148 for _, ref := range refs {
149 symbolic, err := symbolicRef(ref)
150 if err != nil {
151 return nil, fmt.Errorf("whether %s is a symbolic ref could not be read: %w", ref, err)
152 }
153 found[ref] = symbolic
154 }
155 return found, nil
156}
157
158func symbolicRef(ref string) (bool, error) {
159 _, err := run(nil, "symbolic-ref", "--quiet", "--end-of-options", ref)
160 var exit *exec.ExitError
161 switch {
162 case err == nil:
163 return true, nil
164 case errors.As(err, &exit) && exit.ExitCode() == 1:
165 // Not a symbolic ref, or no ref at all.
166 return false, nil
167 default:
168 return false, err
169 }
170}
171
172// notes walks the tree id names and returns every note in it, keyed by
173// path. Every tree is read one level at a time, and every object's type
174// and size are asked for, and checked against the bounds, before its
175// content is asked for at all. Any entry that is not a tree or a plain
176// file, and any bound crossed, refuses the whole tree.
177func (gitRepository) notes(id string) (map[string][]byte, error) {
178 objects, err := openObjects()
179 if err != nil {
180 return nil, err
181 }
182 defer objects.close()
183 return walkNotes(objects, id)
184}
185
186func walkNotes(objects *objectStream, id string) (map[string][]byte, error) {
187 found := map[string][]byte{}
188 w := walk{objects: objects, hashSize: len(id) / 2, visit: func(at, mode, child string) error {
189 switch mode {
190 case "40000":
191 return nil
192 case "100644":
193 note, err := objects.read(child, "blob", maxNoteSize)
194 if err != nil {
195 return fmt.Errorf("%s %v", at, err)
196 }
197 found[at] = note
198 return nil
199 }
200 return fmt.Errorf("%s has mode %s, and an attestation holds only notes, as plain files, and trees of them", at, mode)
201 }}
202 if err := w.tree(id, "", 1); err != nil {
203 return nil, err
204 }
205 if len(found) == 0 {
206 return nil, errors.New("it points at a tree holding no note, and an attestation holds at least one")
207 }
208 return found, nil
209}
210
211// walk is one bounded walk of a tree, within its stream's budget. It
212// hands visit every entry it finds, trees included, and walks each tree
213// after visit has seen it.
214type walk struct {
215 objects *objectStream
216 hashSize int
217 entries int
218 visit func(at, mode, id string) error
219}
220
221func (w *walk) tree(id, path string, depth int) error {
222 b := w.objects.budget
223 body, err := w.objects.read(id, "tree", b.treeSize)
224 if err != nil {
225 if path == "" {
226 return fmt.Errorf("it %v", err)
227 }
228 return fmt.Errorf("%s %v", path, err)
229 }
230 inTree := 0
231 for len(body) > 0 {
232 inTree++
233 w.entries++
234 switch {
235 case inTree > b.entriesInTree:
236 return fmt.Errorf("a tree in it holds more than %d entries, the most %s's tree may", b.entriesInTree, b.subject)
237 case w.entries > b.entries:
238 return fmt.Errorf("its trees name more than %d entries in all, the most %s may", b.entries, b.subject)
239 }
240 mode, name, child, rest, err := treeEntry(body, w.hashSize)
241 if err != nil {
242 if path == "" {
243 return fmt.Errorf("it %v", err)
244 }
245 return fmt.Errorf("%s %v", path, err)
246 }
247 body = rest
248 at := name
249 if path != "" {
250 at = path + "/" + name
251 }
252 if mode == "40000" && depth+1 > b.depth {
253 return fmt.Errorf("%s nests trees deeper than the %d %s may", at, b.depth, b.subject)
254 }
255 if err := w.visit(at, mode, child); err != nil {
256 return err
257 }
258 if mode == "40000" {
259 if err := w.tree(child, at, depth+1); err != nil {
260 return err
261 }
262 }
263 }
264 return nil
265}
266
267// gitModes are the modes git writes in a tree, each spelled as git spells
268// it: a plain file, an executable, a symlink, a tree and a submodule.
269var gitModes = map[string]bool{"100644": true, "100755": true, "120000": true, "40000": true, "160000": true}
270
271// treeEntry reads one entry of a tree object as git stores it: the mode in
272// octal, a space, the name, a NUL, and the raw object id. It refuses an
273// entry git does not write, whatever the tree's reader would make of it.
274// A tree object can be written by hand with any bytes in it, and the host
275// does not run git's fsck on what a push brings, so this is where a mode
276// such as 040000, which git reads as a tree, or a name such as
277// ideas/<id>-<slug>.md, which a walk would join into a path no tree has,
278// is refused. An error is worded to follow a name for the tree, as in
279// "comments holds an entry ...".
280func treeEntry(body []byte, hashSize int) (mode, name, id string, rest []byte, err error) {
281 space := bytes.IndexByte(body, ' ')
282 nul := bytes.IndexByte(body, 0)
283 if space < 0 || nul < space || len(body) < nul+1+hashSize {
284 return "", "", "", nil, errors.New("holds an entry git could not have written")
285 }
286 mode, name = string(body[:space]), string(body[space+1:nul])
287 switch {
288 case name == "":
289 return "", "", "", nil, errors.New("holds an entry with an empty name, which git does not write")
290 case name == "." || name == "..":
291 return "", "", "", nil, fmt.Errorf("holds an entry named %q, which git does not write", name)
292 case strings.ContainsAny(name, "/\x00"):
293 return "", "", "", nil, fmt.Errorf("holds an entry named %q, and git writes no name with a slash or a NUL in it", name)
294 case !gitModes[mode]:
295 return "", "", "", nil, fmt.Errorf("holds %q with mode %s, and git writes only the modes 100644, 100755, 120000, 40000 and 160000", name, mode)
296 }
297 return mode, name, hex.EncodeToString(body[nul+1 : nul+1+hashSize]), body[nul+1+hashSize:], nil
298}
299
300// objectStream reads objects one at a time out of a single
301// `git cat-file --batch-command`. It asks for an object's type and size
302// first (`info`), and asks for its content (`contents`) only once those
303// have passed every bound, so git is never asked to produce an object the
304// walk would refuse. requests records what was asked, in order.
305type objectStream struct {
306 cmd *exec.Cmd
307 in io.WriteCloser
308 out *bufio.Reader
309 spent int
310 requests []string
311
312 // budget is what the reading may cost, and names what the objects
313 // make up in a refusal. ctx ends when the budget's deadline passes,
314 // if it has one, and when the stream is closed.
315 budget budget
316 ctx context.Context
317 cancel context.CancelFunc
318}
319
320// openObjects opens a stream within an attestation's budget.
321func openObjects() (*objectStream, error) {
322 return openObjectsWithin(attestationBudget)
323}
324
325// openObjectsWithin starts git cat-file and opens a stream on it within
326// the budget. When the budget's deadline passes, git is killed and its
327// pipes are closed, so a read or write it has left waiting returns then.
328func openObjectsWithin(b budget) (*objectStream, error) {
329 ctx, cancel := b.context()
330 cmd := exec.CommandContext(ctx, gitProgram, "--no-replace-objects", "cat-file", "--batch-command")
331 cmd.Env = gitEnvironment(os.Environ())
332 in, err := cmd.StdinPipe()
333 if err != nil {
334 cancel()
335 return nil, err
336 }
337 out, err := cmd.StdoutPipe()
338 if err != nil {
339 cancel()
340 return nil, err
341 }
342 if err := cmd.Start(); err != nil {
343 cancel()
344 return nil, err
345 }
346 s := newObjectStream(ctx, cancel, in, out, b)
347 s.cmd = cmd
348 return s, nil
349}
350
351// newObjectStream reads answers from out to the commands it writes to
352// in, within the budget. Once ctx ends, both are closed, so a read or a
353// write blocked on them returns at once, and the stream answers nothing
354// more.
355func newObjectStream(ctx context.Context, cancel context.CancelFunc, in io.WriteCloser, out io.ReadCloser, b budget) *objectStream {
356 context.AfterFunc(ctx, func() {
357 _ = in.Close()
358 _ = out.Close()
359 })
360 return &objectStream{in: in, out: bufio.NewReaderSize(out, 4096), budget: b, ctx: ctx, cancel: cancel}
361}
362
363// expired reports whether the budget's deadline has passed.
364func (s *objectStream) expired() bool {
365 until, ok := s.ctx.Deadline()
366 return ok && !time.Now().Before(until)
367}
368
369// failed is the error for a read or write of the stream that failed: the
370// deadline's, when it has passed, since passing it is what closes the
371// stream, and otherwise err.
372func (s *objectStream) failed(err error) error {
373 if s.expired() {
374 return s.late()
375 }
376 return err
377}
378
379func (s *objectStream) late() error {
380 return fmt.Errorf("could not be read within the %s the hook spends reading %s", s.budget.deadline, s.budget.subject)
381}
382
383// ask sends one command and reads the header line git answers it with:
384// the object's id, type and size.
385func (s *objectStream) ask(command, id string) (kind string, size int, err error) {
386 if s.expired() {
387 return "", 0, s.late()
388 }
389 s.requests = append(s.requests, command+" "+id)
390 if _, err := fmt.Fprintf(s.in, "%s %s\n", command, id); err != nil {
391 return "", 0, s.failed(fmt.Errorf("could not be asked for: %v", err))
392 }
393 header, err := s.out.ReadString('\n')
394 if err != nil {
395 return "", 0, s.failed(fmt.Errorf("could not be read: %v", err))
396 }
397 fields := strings.Fields(header)
398 if len(fields) == 2 && fields[1] == "missing" {
399 return "", 0, errors.New("names an object the push did not bring")
400 }
401 if len(fields) != 3 {
402 return "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header))
403 }
404 size, err = strconv.Atoi(fields[2])
405 if err != nil || size < 0 {
406 return "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header))
407 }
408 return fields[1], size, nil
409}
410
411// read returns the content of object id, which must be of type kind and at
412// most max bytes, and must fit what is left of the walk's byte budget. The
413// type and size are asked for and checked first; the content is asked for
414// only once they pass, so an object past a bound is never produced.
415func (s *objectStream) read(id, kind string, max int) ([]byte, error) {
416 got, size, err := s.ask("info", id)
417 switch {
418 case err != nil:
419 return nil, err
420 case got != kind:
421 return nil, fmt.Errorf("points at a %s, where %s holds a %s", got, s.budget.subject, kind)
422 case size > max:
423 return nil, fmt.Errorf("is a %s of %d bytes, more than the %d %s's may be", kind, size, max, s.budget.subject)
424 case s.spent+size > s.budget.bytes:
425 return nil, fmt.Errorf("would take the walk past the %d bytes %s may hold", s.budget.bytes, s.budget.subject)
426 }
427 again, confirmed, err := s.ask("contents", id)
428 if err != nil {
429 return nil, err
430 }
431 if again != kind || confirmed != size {
432 return nil, fmt.Errorf("changed between being sized and being read: git answered %s %d", again, confirmed)
433 }
434 s.spent += size
435 body := make([]byte, size+1) // the content and git's closing newline
436 if _, err := io.ReadFull(s.out, body); err != nil {
437 return nil, s.failed(fmt.Errorf("could not be read: %v", err))
438 }
439 return body[:size], nil
440}
441
442// close ends the stream. The process is killed rather than asked to
443// finish, since a walk that stopped at a bound has nothing more to ask.
444func (s *objectStream) close() {
445 s.cancel()
446 if s.cmd != nil {
447 _ = s.cmd.Process.Kill()
448 _ = s.cmd.Wait()
449 }
450}
451
452// run runs git in the repository and returns its stdout.
453//
454// Replacement refs are off: a replacement could make the hook read some
455// other object than the one pushed. The rest of git's environment is the
456// one receive-pack gave the hook, which the client has no way to set, less
457// any GIT_ variable but the four that say where this repository and the
458// pushed objects are. System and user configuration are not read.
459func run(stdin []byte, args ...string) ([]byte, error) {
460 cmd := exec.Command(gitProgram, append([]string{"--no-replace-objects"}, args...)...)
461 cmd.Env = gitEnvironment(os.Environ())
462 if stdin != nil {
463 cmd.Stdin = bytes.NewReader(stdin)
464 }
465 var stderr bytes.Buffer
466 cmd.Stderr = &stderr
467 out, err := cmd.Output()
468 if err != nil {
469 if msg := strings.TrimSpace(stderr.String()); msg != "" {
470 return nil, fmt.Errorf("git %s: %w: %s", args[0], err, msg)
471 }
472 return nil, fmt.Errorf("git %s: %w", args[0], err)
473 }
474 return out, nil
475}
476
477// kept are the GIT_ variables receive-pack sets for a hook and that the
478// hook's own reads need: the repository, and the quarantine the pushed
479// objects sit in until the push is accepted.
480var kept = map[string]bool{
481 "GIT_DIR": true,
482 "GIT_OBJECT_DIRECTORY": true,
483 "GIT_ALTERNATE_OBJECT_DIRECTORIES": true,
484 "GIT_QUARANTINE_PATH": true,
485}
486
487func gitEnvironment(inherited []string) []string {
488 var env []string
489 for _, kv := range inherited {
490 name, _, _ := strings.Cut(kv, "=")
491 if strings.HasPrefix(name, "GIT_") && !kept[name] {
492 continue
493 }
494 env = append(env, kv)
495 }
496 return append(env,
497 "GIT_CONFIG_NOSYSTEM=1",
498 "GIT_CONFIG_SYSTEM=/dev/null",
499 "GIT_CONFIG_GLOBAL=/dev/null",
500 "GIT_NO_REPLACE_OBJECTS=1",
501 "GIT_TERMINAL_PROMPT=0",
502 "LC_ALL=C",
503 )
504}
505
506func sortedKeys[V any](m map[string]V) []string {
507 keys := make([]string, 0, len(m))
508 for k := range m {
509 keys = append(keys, k)
510 }
511 sort.Strings(keys)
512 return keys
513}