| 1 | // valleyhook is the pre-receive hook of every project a valley host |
| 2 | // serves: the whole of what a push may write there. The NixOS module |
| 3 | // (nix/valley-host.nix) installs a short script as the hook, and that |
| 4 | // script only hands this program the pushing principal, the project's |
| 5 | // declared push policy, the grants files and the keys attestations are |
| 6 | // checked against. Every decision about a ref is made here, so the policy |
| 7 | // lives in one place. |
| 8 | package main |
| 9 | |
| 10 | import ( |
| 11 | "bufio" |
| 12 | "bytes" |
| 13 | "errors" |
| 14 | "flag" |
| 15 | "fmt" |
| 16 | "io" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "strings" |
| 20 | |
| 21 | "the-valley/change" |
| 22 | "the-valley/exactjson" |
| 23 | ) |
| 24 | |
| 25 | const usage = `usage: valleyhook pre-receive [flags] < ref updates |
| 26 | valleyhook shell [flags] -- [-c COMMAND] |
| 27 | |
| 28 | shell is the git user's login shell; see "valleyhook shell -h". |
| 29 | |
| 30 | The pre-receive hook of every project on a valley host. git hands it one |
| 31 | line per ref a push would update: the old id, the new id and the refname. |
| 32 | It accepts the push only if the pushing principal may make every one of |
| 33 | those writes. One refusal refuses the whole push, atomic or not, because a |
| 34 | pre-receive hook answers for the push and not for each ref. |
| 35 | |
| 36 | A write is allowed only if every rule that applies to its ref allows it: |
| 37 | |
| 38 | refs/replace/*, refs/notes/*, and refs/the-valley/* other than the seven |
| 39 | namespaces below |
| 40 | nobody, whatever a declaration says. A replacement ref |
| 41 | makes one object stand in for another wherever git |
| 42 | looks it up; a note attaches text every reader sees; |
| 43 | the rest of the valley's namespace is the machinery's. |
| 44 | refs/refs/*, refs/heads/refs/*, refs/tags/refs/*, refs/remotes/refs/* |
| 45 | nobody may create or update one, whatever a |
| 46 | declaration says. Each is named like another ref: |
| 47 | when that ref is missing, git reads, fetches and |
| 48 | pushes to one of these in its place. A delete is |
| 49 | decided by the rules below. |
| 50 | a symbolic ref nobody. A push to one would write the ref it points at. |
| 51 | refs/heads/* anyone: topic branches. |
| 52 | refs/the-valley/attestations/<digest>/<key hash> |
| 53 | anyone, to create one or add notes to one. The ref |
| 54 | must point at a tree of notes about that digest, read |
| 55 | within fixed bounds, each opening under the |
| 56 | --known-signers keys the way attest verify opens it, |
| 57 | with a verified signature under that key hash. An |
| 58 | update keeps every note the ref holds, byte for byte, |
| 59 | and adds at least one. No push deletes one. |
| 60 | refs/the-valley/integration-requests/* |
| 61 | principals holding the approve grant (also accepted as |
| 62 | request). They may file, replace and withdraw a |
| 63 | request. |
| 64 | refs/the-valley/approvals/main/c-<change ID> |
| 65 | principals holding the approve grant, to create, |
| 66 | replace or delete. The ref points at one blob of at |
| 67 | most 2048 bytes: an approval note with one signature |
| 68 | line, whose text is a the-valley/approval/v1 |
| 69 | statement about that change and main, signed under |
| 70 | the statement's principal. Whose key signed it is |
| 71 | not checked here. |
| 72 | refs/the-valley/changes/main/<change ID> |
| 73 | a change record: a commit whose tree holds one file, |
| 74 | record.json. Any named principal may create one, and |
| 75 | owns it; its first version's head is the commit's one |
| 76 | parent. The owner or a holder of the approve grant may |
| 77 | add a version, whose head is the commit's second parent |
| 78 | after the record it replaces, or withdraw the change, |
| 79 | with that record as the one parent. Only a holder of |
| 80 | the approve grant may delete one. A holder of the |
| 81 | restack grant that is neither may add one version to a |
| 82 | ready change, on the active version's branch and under |
| 83 | its title, and nothing more. A project whose policy |
| 84 | retains its change records takes no delete of one, |
| 85 | from anyone. Every other write is refused. A push may update at most 32 records, and a |
| 86 | repository may hold at most 2000. That bound is soft: |
| 87 | pushes running at once can pass it by the records |
| 88 | they create. |
| 89 | refs/the-valley/restack/main/<change ID> |
| 90 | a restack report: principals holding the restack |
| 91 | grant, about a change the repository records. A commit |
| 92 | whose tree holds one file, report.json, read within |
| 93 | fixed bounds as a valley-restack-report/v1 report about |
| 94 | that change. The first has no parent, and each later |
| 95 | one has the report it replaces as its one parent. No |
| 96 | push deletes one. A push may update at most 64. |
| 97 | refs/the-valley/check-requests/<principal>/<worktree>/<attempt> |
| 98 | a check request: a commit the host's check worker |
| 99 | builds the required checks of. The worktree and the |
| 100 | attempt are 16 lowercase hexadecimal digits each. A |
| 101 | named principal may create, replace and delete the |
| 102 | requests under its own name, and a holder of the |
| 103 | approve grant may delete any. A principal may hold at |
| 104 | most 32 in a repository, counted with the requests |
| 105 | the push creates. That bound is soft, as the one on |
| 106 | change records is. |
| 107 | refs/the-valley/knots |
| 108 | the plan graph, that name exactly: any named |
| 109 | principal. A create is one commit with no parent, and |
| 110 | an update one commit whose only parent is the old |
| 111 | tip, committed by the pusher, with a Valley-Op |
| 112 | trailer. Its tree is read within fixed bounds, and |
| 113 | must be exactly the graph's layout. No knot or |
| 114 | comment is deleted, a knot keeps its id, type, |
| 115 | created and created_by, a new knot's created_by and a |
| 116 | new comment's author name the pusher, every edge |
| 117 | resolves, and no edge forms a cycle. A comment's |
| 118 | author, or a holder of the approve grant, may edit |
| 119 | it: the edit keeps the author and names the pusher |
| 120 | in edited_by. No push deletes the ref. |
| 121 | anything else principals a named grant of the project opens the ref |
| 122 | to. Tags open only this way. |
| 123 | a protected ref also a declared writer of the project. Protection adds |
| 124 | this requirement and removes none of the ones above. |
| 125 | |
| 126 | The integrator's own writes are not pushes. A controller updates the refs |
| 127 | it writes on the host, and no push hook sees a local write. |
| 128 | |
| 129 | A push may update at most 1000 refs. One that updates more is refused as a |
| 130 | whole, at the first update past the bound, before any ref is decided. |
| 131 | |
| 132 | A policy, grants or keys file that cannot be read refuses the whole push. |
| 133 | So does a policy holding a key that does not spell its field exactly, or a |
| 134 | key twice in one object. The hook fails closed: a policy it cannot read is |
| 135 | not a policy it can apply. A grants or keys file that does not exist |
| 136 | grants nothing and names no key. |
| 137 | |
| 138 | flags: |
| 139 | --project NAME the project, named in what a refusal says |
| 140 | --policy FILE the project's push policy, as the host declaration |
| 141 | exports it (JSON): its protected refs, their |
| 142 | writers, its named grants, and whether it retains |
| 143 | its change records |
| 144 | --grants FILE grants, one "<grant> <principal>" per line. Repeat |
| 145 | the flag to read more than one file; what they |
| 146 | grant adds up. A line naming request grants the |
| 147 | approve grant, exactly as one naming approve does. |
| 148 | --known-signers FILE verifier keys, one per line, that an attestation's |
| 149 | signature is checked against. Repeatable. With no |
| 150 | key named, no attestation is accepted. |
| 151 | --principal NAME the pushing principal; empty for a key that names |
| 152 | none |
| 153 | --then FILE a further pre-receive hook, run only once this one |
| 154 | accepts the push, with the same input. It can refuse |
| 155 | what this one accepts and never the reverse. |
| 156 | ` |
| 157 | |
| 158 | func main() { |
| 159 | if len(os.Args) < 2 { |
| 160 | fmt.Fprint(os.Stderr, usage) |
| 161 | os.Exit(2) |
| 162 | } |
| 163 | switch os.Args[1] { |
| 164 | case "pre-receive": |
| 165 | os.Exit(preReceive(os.Args[2:], os.Stdin, os.Stderr, gitRepository{})) |
| 166 | case "shell": |
| 167 | os.Exit(shell(os.Args[2:], os.Stderr)) |
| 168 | case "help", "-h", "--help": |
| 169 | fmt.Print(usage) |
| 170 | default: |
| 171 | fmt.Fprintf(os.Stderr, "valleyhook: unknown command %q\n\n%s", os.Args[1], usage) |
| 172 | os.Exit(2) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | // maxUpdates is how many refs one push may update. |
| 177 | const maxUpdates = 1000 |
| 178 | |
| 179 | // preReceive runs the hook over the updates on stdin and returns its exit |
| 180 | // status: 0 accepts the push, anything else refuses it. |
| 181 | func preReceive(args []string, stdin io.Reader, stderr io.Writer, repo repository) int { |
| 182 | fs := flag.NewFlagSet("pre-receive", flag.ContinueOnError) |
| 183 | fs.SetOutput(stderr) |
| 184 | fs.Usage = func() { fmt.Fprint(stderr, usage) } |
| 185 | project := fs.String("project", "", "the project, named in what a refusal says") |
| 186 | policyFile := fs.String("policy", "", "the project's push policy (JSON)") |
| 187 | principal := fs.String("principal", "", "the pushing principal") |
| 188 | then := fs.String("then", "", "a further pre-receive hook") |
| 189 | var grantFiles, keyFiles []string |
| 190 | fs.Func("grants", "a grants file; repeatable", func(path string) error { |
| 191 | grantFiles = append(grantFiles, path) |
| 192 | return nil |
| 193 | }) |
| 194 | fs.Func("known-signers", "a verifier keys file; repeatable", func(path string) error { |
| 195 | keyFiles = append(keyFiles, path) |
| 196 | return nil |
| 197 | }) |
| 198 | if err := fs.Parse(args); err != nil { |
| 199 | return 2 |
| 200 | } |
| 201 | if *project == "" || *policyFile == "" { |
| 202 | fmt.Fprintf(stderr, "valleyhook: --project and --policy are required\n") |
| 203 | return 2 |
| 204 | } |
| 205 | |
| 206 | // Everything the decision needs is read before any ref is looked at, |
| 207 | // so a policy that cannot be read refuses the push as a whole rather |
| 208 | // than part of the way through it. |
| 209 | p := policy{project: *project, grants: grants{}, repo: repo} |
| 210 | if err := readPolicy(*policyFile, &p.push); err != nil { |
| 211 | return failClosed(stderr, err) |
| 212 | } |
| 213 | for _, path := range grantFiles { |
| 214 | if err := p.grants.read(path); err != nil { |
| 215 | return failClosed(stderr, err) |
| 216 | } |
| 217 | } |
| 218 | for _, path := range keyFiles { |
| 219 | keys, err := readVerifiers(path) |
| 220 | if err != nil { |
| 221 | return failClosed(stderr, err) |
| 222 | } |
| 223 | p.verifiers = append(p.verifiers, keys...) |
| 224 | } |
| 225 | |
| 226 | // The updates are read one line at a time, and a push that updates |
| 227 | // more refs than the bound is refused at the first line past it, |
| 228 | // before anything more is kept. The rest of the input is read and |
| 229 | // dropped, so that git is not left writing to a hook that has gone. |
| 230 | var input bytes.Buffer |
| 231 | var updates []update |
| 232 | lines := bufio.NewScanner(stdin) |
| 233 | for lines.Scan() { |
| 234 | if strings.TrimSpace(lines.Text()) == "" { |
| 235 | continue |
| 236 | } |
| 237 | if len(updates) == maxUpdates { |
| 238 | _, _ = io.Copy(io.Discard, stdin) |
| 239 | fmt.Fprintf(stderr, "valley: the push is refused: it updates more than %d refs, the most one push may\n", maxUpdates) |
| 240 | return 1 |
| 241 | } |
| 242 | fields := strings.Fields(lines.Text()) |
| 243 | if len(fields) != 3 { |
| 244 | return failClosed(stderr, fmt.Errorf("git sent %q, which is not an old id, a new id and a refname", lines.Text())) |
| 245 | } |
| 246 | updates = append(updates, update{old: fields[0], new: fields[1], ref: fields[2]}) |
| 247 | input.WriteString(lines.Text() + "\n") |
| 248 | } |
| 249 | if err := lines.Err(); err != nil { |
| 250 | return failClosed(stderr, err) |
| 251 | } |
| 252 | |
| 253 | // The bounds on change records, restack reports and check requests |
| 254 | // that are about the push as a whole are checked before any record or |
| 255 | // report is read. |
| 256 | records := 0 |
| 257 | for _, u := range updates { |
| 258 | if strings.HasPrefix(u.ref, change.RefPrefix) { |
| 259 | records++ |
| 260 | if isZero(u.old) && !isZero(u.new) { |
| 261 | p.recordCreates++ |
| 262 | } |
| 263 | } |
| 264 | } |
| 265 | if records > maxRecordUpdates { |
| 266 | fmt.Fprintf(stderr, "valley: the push is refused: it updates %d change records, and a push may update at most %d\n", records, maxRecordUpdates) |
| 267 | return 1 |
| 268 | } |
| 269 | reports := 0 |
| 270 | for _, u := range updates { |
| 271 | if strings.HasPrefix(u.ref, change.RestackPrefix) { |
| 272 | reports++ |
| 273 | } |
| 274 | } |
| 275 | if reports > maxReportUpdates { |
| 276 | fmt.Fprintf(stderr, "valley: the push is refused: it updates %d restack reports, and a push may update at most %d\n", reports, maxReportUpdates) |
| 277 | return 1 |
| 278 | } |
| 279 | if p.recordCreates > 0 { |
| 280 | var err error |
| 281 | if p.existingRecords, err = repo.records(); err != nil { |
| 282 | return failClosed(stderr, err) |
| 283 | } |
| 284 | } |
| 285 | if p.requestCreates = requestCreates(*principal, updates); p.requestCreates > 0 { |
| 286 | var err error |
| 287 | if p.existingRequests, err = repo.checkRequests(*principal); err != nil { |
| 288 | return failClosed(stderr, err) |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // Which of the refs are symbolic is read once for the whole push. |
| 293 | refs := make([]string, len(updates)) |
| 294 | for i, u := range updates { |
| 295 | refs[i] = u.ref |
| 296 | } |
| 297 | symrefs, err := repo.symbolic(refs) |
| 298 | if err != nil { |
| 299 | return failClosed(stderr, err) |
| 300 | } |
| 301 | p.symrefs = symrefs |
| 302 | |
| 303 | p.pushed = map[string]string{} |
| 304 | for _, u := range updates { |
| 305 | p.pushed[u.ref] = u.new |
| 306 | } |
| 307 | refused := false |
| 308 | for _, u := range updates { |
| 309 | if refusal := p.decide(*principal, u); refusal != "" { |
| 310 | fmt.Fprintln(stderr, refusal) |
| 311 | refused = true |
| 312 | } |
| 313 | } |
| 314 | if refused { |
| 315 | return 1 |
| 316 | } |
| 317 | if *then != "" { |
| 318 | return runThen(*then, input.Bytes(), stderr) |
| 319 | } |
| 320 | return 0 |
| 321 | } |
| 322 | |
| 323 | // runThen runs the composed hook over the same input, in this hook's |
| 324 | // environment, and its exit status is the push's. |
| 325 | func runThen(path string, input []byte, stderr io.Writer) int { |
| 326 | cmd := exec.Command(path) |
| 327 | cmd.Stdin = bytes.NewReader(input) |
| 328 | cmd.Stdout = os.Stdout |
| 329 | cmd.Stderr = stderr |
| 330 | err := cmd.Run() |
| 331 | var exit *exec.ExitError |
| 332 | switch { |
| 333 | case err == nil: |
| 334 | return 0 |
| 335 | case errors.As(err, &exit): |
| 336 | return exit.ExitCode() |
| 337 | default: |
| 338 | return failClosed(stderr, fmt.Errorf("the composed hook %s did not run: %w", path, err)) |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | // failClosed refuses the whole push for a reason that is not about any one |
| 343 | // ref. |
| 344 | func failClosed(stderr io.Writer, err error) int { |
| 345 | fmt.Fprintf(stderr, "valley: the push is refused because its policy could not be applied: %v\n", err) |
| 346 | return 1 |
| 347 | } |
| 348 | |
| 349 | // readPolicy reads the project's push policy. A field this program does |
| 350 | // not know refuses the read: the policy is exported from the schema this |
| 351 | // program ships beside, so an unknown field means the two have drifted |
| 352 | // apart, and the field could be a restriction the hook would otherwise |
| 353 | // skip. |
| 354 | // |
| 355 | // Every key must spell its field exactly, and no key may appear twice in |
| 356 | // one object. encoding/json alone matches a key to a field without regard |
| 357 | // to case. A host declaration that reopens a schema definition could then |
| 358 | // name a writer under a field spelled another way, beside the writers a |
| 359 | // reviewer reads. |
| 360 | func readPolicy(path string, p *pushPolicy) error { |
| 361 | data, err := os.ReadFile(path) |
| 362 | if err != nil { |
| 363 | return err |
| 364 | } |
| 365 | if err := exactjson.Decode(data, p); err != nil { |
| 366 | return fmt.Errorf("%s: %w", path, err) |
| 367 | } |
| 368 | return nil |
| 369 | } |