gunk-dev/the-valley

repo.go

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