gunk-dev/the-valley

repo.go

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