gunk-dev/the-valley

repo.go

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