gunk-dev/the-valley

main.go

sourcecfedff357a41main's published tip history
14.3 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/pushpolicy"
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 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
126The integrator's own writes are not pushes. A controller updates the refs
127it writes on the host, and no push hook sees a local write.
128
129A push may update at most 1000 refs. One that updates more is refused as a
130whole, at the first update past the bound, before any ref is decided.
131
132A policy, grants or keys file that cannot be read refuses the whole push.
133So does a policy holding a key that does not spell its field exactly, or a
134key twice in one object. The hook fails closed: a policy it cannot read is
135not a policy it can apply. A grants or keys file that does not exist
136grants nothing and names no key.
137
138flags:
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
158func 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.
177const 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.
181func 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 push, err := pushpolicy.Read(*policyFile)
211 if err != nil {
212 return failClosed(stderr, err)
213 }
214 p.push = push
215 for _, path := range grantFiles {
216 if err := p.grants.read(path); err != nil {
217 return failClosed(stderr, err)
218 }
219 }
220 for _, path := range keyFiles {
221 keys, err := readVerifiers(path)
222 if err != nil {
223 return failClosed(stderr, err)
224 }
225 p.verifiers = append(p.verifiers, keys...)
226 }
227
228 // The updates are read one line at a time, and a push that updates
229 // more refs than the bound is refused at the first line past it,
230 // before anything more is kept. The rest of the input is read and
231 // dropped, so that git is not left writing to a hook that has gone.
232 var input bytes.Buffer
233 var updates []update
234 lines := bufio.NewScanner(stdin)
235 for lines.Scan() {
236 if strings.TrimSpace(lines.Text()) == "" {
237 continue
238 }
239 if len(updates) == maxUpdates {
240 _, _ = io.Copy(io.Discard, stdin)
241 fmt.Fprintf(stderr, "valley: the push is refused: it updates more than %d refs, the most one push may\n", maxUpdates)
242 return 1
243 }
244 fields := strings.Fields(lines.Text())
245 if len(fields) != 3 {
246 return failClosed(stderr, fmt.Errorf("git sent %q, which is not an old id, a new id and a refname", lines.Text()))
247 }
248 updates = append(updates, update{old: fields[0], new: fields[1], ref: fields[2]})
249 input.WriteString(lines.Text() + "\n")
250 }
251 if err := lines.Err(); err != nil {
252 return failClosed(stderr, err)
253 }
254
255 // The bounds on change records, restack reports and check requests
256 // that are about the push as a whole are checked before any record or
257 // report is read.
258 records := 0
259 for _, u := range updates {
260 if strings.HasPrefix(u.ref, change.RefPrefix) {
261 records++
262 if isZero(u.old) && !isZero(u.new) {
263 p.recordCreates++
264 }
265 }
266 }
267 if records > maxRecordUpdates {
268 fmt.Fprintf(stderr, "valley: the push is refused: it updates %d change records, and a push may update at most %d\n", records, maxRecordUpdates)
269 return 1
270 }
271 reports := 0
272 for _, u := range updates {
273 if strings.HasPrefix(u.ref, change.RestackPrefix) {
274 reports++
275 }
276 }
277 if reports > maxReportUpdates {
278 fmt.Fprintf(stderr, "valley: the push is refused: it updates %d restack reports, and a push may update at most %d\n", reports, maxReportUpdates)
279 return 1
280 }
281 if p.recordCreates > 0 {
282 var err error
283 if p.existingRecords, err = repo.records(); err != nil {
284 return failClosed(stderr, err)
285 }
286 }
287 if p.requestCreates = requestCreates(*principal, updates); p.requestCreates > 0 {
288 var err error
289 if p.existingRequests, err = repo.checkRequests(*principal); err != nil {
290 return failClosed(stderr, err)
291 }
292 }
293
294 // Which of the refs are symbolic is read once for the whole push.
295 refs := make([]string, len(updates))
296 for i, u := range updates {
297 refs[i] = u.ref
298 }
299 symrefs, err := repo.symbolic(refs)
300 if err != nil {
301 return failClosed(stderr, err)
302 }
303 p.symrefs = symrefs
304
305 p.pushed = map[string]string{}
306 for _, u := range updates {
307 p.pushed[u.ref] = u.new
308 }
309 refused := false
310 for _, u := range updates {
311 if refusal := p.decide(*principal, u); refusal != "" {
312 fmt.Fprintln(stderr, refusal)
313 refused = true
314 }
315 }
316 if refused {
317 return 1
318 }
319 if *then != "" {
320 return runThen(*then, input.Bytes(), stderr)
321 }
322 return 0
323}
324
325// runThen runs the composed hook over the same input, in this hook's
326// environment, and its exit status is the push's.
327func runThen(path string, input []byte, stderr io.Writer) int {
328 cmd := exec.Command(path)
329 cmd.Stdin = bytes.NewReader(input)
330 cmd.Stdout = os.Stdout
331 cmd.Stderr = stderr
332 err := cmd.Run()
333 var exit *exec.ExitError
334 switch {
335 case err == nil:
336 return 0
337 case errors.As(err, &exit):
338 return exit.ExitCode()
339 default:
340 return failClosed(stderr, fmt.Errorf("the composed hook %s did not run: %w", path, err))
341 }
342}
343
344// failClosed refuses the whole push for a reason that is not about any one
345// ref.
346func failClosed(stderr io.Writer, err error) int {
347 fmt.Fprintf(stderr, "valley: the push is refused because its policy could not be applied: %v\n", err)
348 return 1
349}