gunk-dev/the-valley

repo.go

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