gunk-dev/the-valley

repo.go

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