gunk-dev/the-valley

repo.go

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