gunk-dev/the-valley

repo.go

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