gunk-dev/the-valley

main.go

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