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