| 1 | package main |
| 2 | |
| 3 | import ( |
| 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. |
| 20 | var gitProgram = "git" |
| 21 | |
| 22 | // repository is what a decision needs to know about the repository a push |
| 23 | // is landing in. |
| 24 | type 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. |
| 41 | const ( |
| 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. |
| 54 | type gitRepository struct{} |
| 55 | |
| 56 | func (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 |
| 72 | // and size are asked for, and checked against the bounds, before its |
| 73 | // content is asked for at all. Any entry that is not a tree or a plain |
| 74 | // file, and any bound crossed, refuses the whole tree. |
| 75 | func (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 | return walkNotes(objects, id) |
| 82 | } |
| 83 | |
| 84 | func walkNotes(objects *objectStream, id string) (map[string][]byte, error) { |
| 85 | w := walk{objects: objects, hashSize: len(id) / 2, found: map[string][]byte{}} |
| 86 | if err := w.tree(id, "", 1); err != nil { |
| 87 | return nil, err |
| 88 | } |
| 89 | if len(w.found) == 0 { |
| 90 | return nil, errors.New("it points at a tree holding no note, and an attestation holds at least one") |
| 91 | } |
| 92 | return w.found, nil |
| 93 | } |
| 94 | |
| 95 | // walk is one bounded walk of an attestation's tree. |
| 96 | type walk struct { |
| 97 | objects *objectStream |
| 98 | hashSize int |
| 99 | entries int |
| 100 | found map[string][]byte |
| 101 | } |
| 102 | |
| 103 | func (w *walk) tree(id, path string, depth int) error { |
| 104 | body, err := w.objects.read(id, "tree", maxTreeSize) |
| 105 | if err != nil { |
| 106 | if path == "" { |
| 107 | return fmt.Errorf("it %v", err) |
| 108 | } |
| 109 | return fmt.Errorf("%s %v", path, err) |
| 110 | } |
| 111 | inTree := 0 |
| 112 | for len(body) > 0 { |
| 113 | inTree++ |
| 114 | w.entries++ |
| 115 | switch { |
| 116 | case inTree > maxEntriesInTree: |
| 117 | return fmt.Errorf("a tree in it holds more than %d entries, the most an attestation's tree may", maxEntriesInTree) |
| 118 | case w.entries > maxEntries: |
| 119 | return fmt.Errorf("its trees name more than %d entries in all, the most an attestation may", maxEntries) |
| 120 | } |
| 121 | mode, name, child, rest, err := treeEntry(body, w.hashSize) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | body = rest |
| 126 | at := name |
| 127 | if path != "" { |
| 128 | at = path + "/" + name |
| 129 | } |
| 130 | switch mode { |
| 131 | case "40000": |
| 132 | if depth+1 > maxDepth { |
| 133 | return fmt.Errorf("%s nests trees deeper than the %d an attestation may", at, maxDepth) |
| 134 | } |
| 135 | if err := w.tree(child, at, depth+1); err != nil { |
| 136 | return err |
| 137 | } |
| 138 | case "100644": |
| 139 | note, err := w.objects.read(child, "blob", maxNoteSize) |
| 140 | if err != nil { |
| 141 | return fmt.Errorf("%s %v", at, err) |
| 142 | } |
| 143 | w.found[at] = note |
| 144 | default: |
| 145 | return fmt.Errorf("%s has mode %s, and an attestation holds only notes, as plain files, and trees of them", at, mode) |
| 146 | } |
| 147 | } |
| 148 | return nil |
| 149 | } |
| 150 | |
| 151 | // treeEntry reads one entry of a tree object as git stores it: the mode in |
| 152 | // octal, a space, the name, a NUL, and the raw object id. |
| 153 | func treeEntry(body []byte, hashSize int) (mode, name, id string, rest []byte, err error) { |
| 154 | space := bytes.IndexByte(body, ' ') |
| 155 | nul := bytes.IndexByte(body, 0) |
| 156 | if space < 0 || nul < space || len(body) < nul+1+hashSize { |
| 157 | return "", "", "", nil, errors.New("it holds a tree git could not have written") |
| 158 | } |
| 159 | return string(body[:space]), string(body[space+1 : nul]), |
| 160 | hex.EncodeToString(body[nul+1 : nul+1+hashSize]), body[nul+1+hashSize:], nil |
| 161 | } |
| 162 | |
| 163 | // objectStream reads objects one at a time out of a single |
| 164 | // `git cat-file --batch-command`. It asks for an object's type and size |
| 165 | // first (`info`), and asks for its content (`contents`) only once those |
| 166 | // have passed every bound, so git is never asked to produce an object the |
| 167 | // walk would refuse. requests records what was asked, in order. |
| 168 | type objectStream struct { |
| 169 | cmd *exec.Cmd |
| 170 | in io.WriteCloser |
| 171 | out *bufio.Reader |
| 172 | spent int |
| 173 | requests []string |
| 174 | } |
| 175 | |
| 176 | func openObjects() (*objectStream, error) { |
| 177 | cmd := exec.Command(gitProgram, "--no-replace-objects", "cat-file", "--batch-command") |
| 178 | cmd.Env = gitEnvironment(os.Environ()) |
| 179 | in, err := cmd.StdinPipe() |
| 180 | if err != nil { |
| 181 | return nil, err |
| 182 | } |
| 183 | out, err := cmd.StdoutPipe() |
| 184 | if err != nil { |
| 185 | return nil, err |
| 186 | } |
| 187 | if err := cmd.Start(); err != nil { |
| 188 | return nil, err |
| 189 | } |
| 190 | return &objectStream{cmd: cmd, in: in, out: bufio.NewReaderSize(out, 4096)}, nil |
| 191 | } |
| 192 | |
| 193 | // ask sends one command and reads the header line git answers it with: |
| 194 | // the object's id, type and size. |
| 195 | func (s *objectStream) ask(command, id string) (kind string, size int, err error) { |
| 196 | s.requests = append(s.requests, command+" "+id) |
| 197 | if _, err := fmt.Fprintf(s.in, "%s %s\n", command, id); err != nil { |
| 198 | return "", 0, err |
| 199 | } |
| 200 | header, err := s.out.ReadString('\n') |
| 201 | if err != nil { |
| 202 | return "", 0, fmt.Errorf("could not be read: %v", err) |
| 203 | } |
| 204 | fields := strings.Fields(header) |
| 205 | if len(fields) == 2 && fields[1] == "missing" { |
| 206 | return "", 0, errors.New("names an object the push did not bring") |
| 207 | } |
| 208 | if len(fields) != 3 { |
| 209 | return "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header)) |
| 210 | } |
| 211 | size, err = strconv.Atoi(fields[2]) |
| 212 | if err != nil || size < 0 { |
| 213 | return "", 0, fmt.Errorf("could not be read: git answered %q", strings.TrimSpace(header)) |
| 214 | } |
| 215 | return fields[1], size, nil |
| 216 | } |
| 217 | |
| 218 | // read returns the content of object id, which must be of type kind and at |
| 219 | // most max bytes, and must fit what is left of the walk's byte budget. The |
| 220 | // type and size are asked for and checked first; the content is asked for |
| 221 | // only once they pass, so an object past a bound is never produced. |
| 222 | func (s *objectStream) read(id, kind string, max int) ([]byte, error) { |
| 223 | got, size, err := s.ask("info", id) |
| 224 | switch { |
| 225 | case err != nil: |
| 226 | return nil, err |
| 227 | case got != kind: |
| 228 | return nil, fmt.Errorf("points at a %s, where an attestation holds a %s", got, kind) |
| 229 | case size > max: |
| 230 | return nil, fmt.Errorf("is a %s of %d bytes, more than the %d an attestation's may be", kind, size, max) |
| 231 | case s.spent+size > maxBytes: |
| 232 | return nil, fmt.Errorf("would take the walk past the %d bytes an attestation may hold", maxBytes) |
| 233 | } |
| 234 | again, confirmed, err := s.ask("contents", id) |
| 235 | if err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | if again != kind || confirmed != size { |
| 239 | return nil, fmt.Errorf("changed between being sized and being read: git answered %s %d", again, confirmed) |
| 240 | } |
| 241 | s.spent += size |
| 242 | body := make([]byte, size+1) // the content and git's closing newline |
| 243 | if _, err := io.ReadFull(s.out, body); err != nil { |
| 244 | return nil, fmt.Errorf("could not be read: %v", err) |
| 245 | } |
| 246 | return body[:size], nil |
| 247 | } |
| 248 | |
| 249 | // close ends the stream. The process is killed rather than asked to |
| 250 | // finish, since a walk that stopped at a bound has nothing more to ask. |
| 251 | func (s *objectStream) close() { |
| 252 | _ = s.in.Close() |
| 253 | _ = s.cmd.Process.Kill() |
| 254 | _ = s.cmd.Wait() |
| 255 | } |
| 256 | |
| 257 | // run runs git in the repository and returns its stdout. |
| 258 | // |
| 259 | // Replacement refs are off: a replacement could make the hook read some |
| 260 | // other object than the one pushed. The rest of git's environment is the |
| 261 | // one receive-pack gave the hook, which the client has no way to set, less |
| 262 | // any GIT_ variable but the four that say where this repository and the |
| 263 | // pushed objects are. System and user configuration are not read. |
| 264 | func run(stdin []byte, args ...string) ([]byte, error) { |
| 265 | cmd := exec.Command(gitProgram, append([]string{"--no-replace-objects"}, args...)...) |
| 266 | cmd.Env = gitEnvironment(os.Environ()) |
| 267 | if stdin != nil { |
| 268 | cmd.Stdin = bytes.NewReader(stdin) |
| 269 | } |
| 270 | var stderr bytes.Buffer |
| 271 | cmd.Stderr = &stderr |
| 272 | out, err := cmd.Output() |
| 273 | if err != nil { |
| 274 | if msg := strings.TrimSpace(stderr.String()); msg != "" { |
| 275 | return nil, fmt.Errorf("git %s: %w: %s", args[0], err, msg) |
| 276 | } |
| 277 | return nil, fmt.Errorf("git %s: %w", args[0], err) |
| 278 | } |
| 279 | return out, nil |
| 280 | } |
| 281 | |
| 282 | // kept are the GIT_ variables receive-pack sets for a hook and that the |
| 283 | // hook's own reads need: the repository, and the quarantine the pushed |
| 284 | // objects sit in until the push is accepted. |
| 285 | var kept = map[string]bool{ |
| 286 | "GIT_DIR": true, |
| 287 | "GIT_OBJECT_DIRECTORY": true, |
| 288 | "GIT_ALTERNATE_OBJECT_DIRECTORIES": true, |
| 289 | "GIT_QUARANTINE_PATH": true, |
| 290 | } |
| 291 | |
| 292 | func gitEnvironment(inherited []string) []string { |
| 293 | var env []string |
| 294 | for _, kv := range inherited { |
| 295 | name, _, _ := strings.Cut(kv, "=") |
| 296 | if strings.HasPrefix(name, "GIT_") && !kept[name] { |
| 297 | continue |
| 298 | } |
| 299 | env = append(env, kv) |
| 300 | } |
| 301 | return append(env, |
| 302 | "GIT_CONFIG_NOSYSTEM=1", |
| 303 | "GIT_CONFIG_SYSTEM=/dev/null", |
| 304 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 305 | "GIT_NO_REPLACE_OBJECTS=1", |
| 306 | "GIT_TERMINAL_PROMPT=0", |
| 307 | "LC_ALL=C", |
| 308 | ) |
| 309 | } |
| 310 | |
| 311 | func sortedKeys[V any](m map[string]V) []string { |
| 312 | keys := make([]string, 0, len(m)) |
| 313 | for k := range m { |
| 314 | keys = append(keys, k) |
| 315 | } |
| 316 | sort.Strings(keys) |
| 317 | return keys |
| 318 | } |