gunk-dev/the-valley

repo.go

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