gunk-dev/the-valley

repo.go

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