gunk-dev/the-valley

repo.go

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