gunk-dev/the-valley

main.go

source4cbb5ec9c5dbmain'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/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 and refs/the-valley/flow/data
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 and refs/the-valley/flow/data (that name
123 exactly) open only this way.
124 a protected ref also a declared writer of the project. Protection adds
125 this requirement and removes none of the ones above.
126
127The integrator's own writes are not pushes. A controller updates the refs
128it writes on the host, and no push hook sees a local write.
129
130A push may update at most 1000 refs. One that updates more is refused as a
131whole, at the first update past the bound, before any ref is decided.
132
133A policy, grants or keys file that cannot be read refuses the whole push.
134So does a policy holding a key that does not spell its field exactly, or a
135key twice in one object. The hook fails closed: a policy it cannot read is
136not a policy it can apply. A grants or keys file that does not exist
137grants nothing and names no key.
138
139flags:
140 --project NAME the project, named in what a refusal says
141 --policy FILE the project's push policy, as the host declaration
142 exports it (JSON): its protected refs, their
143 writers, its named grants, and whether it retains
144 its change records
145 --grants FILE grants, one "<grant> <principal>" per line. Repeat
146 the flag to read more than one file; what they
147 grant adds up. A line naming request grants the
148 approve grant, exactly as one naming approve does.
149 --known-signers FILE verifier keys, one per line, that an attestation's
150 signature is checked against. Repeatable. With no
151 key named, no attestation is accepted.
152 --principal NAME the pushing principal; empty for a key that names
153 none
154 --then FILE a further pre-receive hook, run only once this one
155 accepts the push, with the same input. It can refuse
156 what this one accepts and never the reverse.
157`
158
159func main() {
160 if len(os.Args) < 2 {
161 fmt.Fprint(os.Stderr, usage)
162 os.Exit(2)
163 }
164 switch os.Args[1] {
165 case "pre-receive":
166 os.Exit(preReceive(os.Args[2:], os.Stdin, os.Stderr, gitRepository{}))
167 case "shell":
168 os.Exit(shell(os.Args[2:], os.Stderr))
169 case "help", "-h", "--help":
170 fmt.Print(usage)
171 default:
172 fmt.Fprintf(os.Stderr, "valleyhook: unknown command %q\n\n%s", os.Args[1], usage)
173 os.Exit(2)
174 }
175}
176
177// maxUpdates is how many refs one push may update.
178const maxUpdates = 1000
179
180// preReceive runs the hook over the updates on stdin and returns its exit
181// status: 0 accepts the push, anything else refuses it.
182func preReceive(args []string, stdin io.Reader, stderr io.Writer, repo repository) int {
183 fs := flag.NewFlagSet("pre-receive", flag.ContinueOnError)
184 fs.SetOutput(stderr)
185 fs.Usage = func() { fmt.Fprint(stderr, usage) }
186 project := fs.String("project", "", "the project, named in what a refusal says")
187 policyFile := fs.String("policy", "", "the project's push policy (JSON)")
188 principal := fs.String("principal", "", "the pushing principal")
189 then := fs.String("then", "", "a further pre-receive hook")
190 var grantFiles, keyFiles []string
191 fs.Func("grants", "a grants file; repeatable", func(path string) error {
192 grantFiles = append(grantFiles, path)
193 return nil
194 })
195 fs.Func("known-signers", "a verifier keys file; repeatable", func(path string) error {
196 keyFiles = append(keyFiles, path)
197 return nil
198 })
199 if err := fs.Parse(args); err != nil {
200 return 2
201 }
202 if *project == "" || *policyFile == "" {
203 fmt.Fprintf(stderr, "valleyhook: --project and --policy are required\n")
204 return 2
205 }
206
207 // Everything the decision needs is read before any ref is looked at,
208 // so a policy that cannot be read refuses the push as a whole rather
209 // than part of the way through it.
210 p := policy{project: *project, grants: grants{}, repo: repo}
211 push, err := pushpolicy.Read(*policyFile)
212 if err != nil {
213 return failClosed(stderr, err)
214 }
215 p.push = push
216 for _, path := range grantFiles {
217 if err := p.grants.read(path); err != nil {
218 return failClosed(stderr, err)
219 }
220 }
221 for _, path := range keyFiles {
222 keys, err := readVerifiers(path)
223 if err != nil {
224 return failClosed(stderr, err)
225 }
226 p.verifiers = append(p.verifiers, keys...)
227 }
228
229 // The updates are read one line at a time, and a push that updates
230 // more refs than the bound is refused at the first line past it,
231 // before anything more is kept. The rest of the input is read and
232 // dropped, so that git is not left writing to a hook that has gone.
233 var input bytes.Buffer
234 var updates []update
235 lines := bufio.NewScanner(stdin)
236 for lines.Scan() {
237 if strings.TrimSpace(lines.Text()) == "" {
238 continue
239 }
240 if len(updates) == maxUpdates {
241 _, _ = io.Copy(io.Discard, stdin)
242 fmt.Fprintf(stderr, "valley: the push is refused: it updates more than %d refs, the most one push may\n", maxUpdates)
243 return 1
244 }
245 fields := strings.Fields(lines.Text())
246 if len(fields) != 3 {
247 return failClosed(stderr, fmt.Errorf("git sent %q, which is not an old id, a new id and a refname", lines.Text()))
248 }
249 updates = append(updates, update{old: fields[0], new: fields[1], ref: fields[2]})
250 input.WriteString(lines.Text() + "\n")
251 }
252 if err := lines.Err(); err != nil {
253 return failClosed(stderr, err)
254 }
255
256 // The bounds on change records, restack reports and check requests
257 // that are about the push as a whole are checked before any record or
258 // report is read.
259 records := 0
260 for _, u := range updates {
261 if strings.HasPrefix(u.ref, change.RefPrefix) {
262 records++
263 if isZero(u.old) && !isZero(u.new) {
264 p.recordCreates++
265 }
266 }
267 }
268 if records > maxRecordUpdates {
269 fmt.Fprintf(stderr, "valley: the push is refused: it updates %d change records, and a push may update at most %d\n", records, maxRecordUpdates)
270 return 1
271 }
272 reports := 0
273 for _, u := range updates {
274 if strings.HasPrefix(u.ref, change.RestackPrefix) {
275 reports++
276 }
277 }
278 if reports > maxReportUpdates {
279 fmt.Fprintf(stderr, "valley: the push is refused: it updates %d restack reports, and a push may update at most %d\n", reports, maxReportUpdates)
280 return 1
281 }
282 if p.recordCreates > 0 {
283 var err error
284 if p.existingRecords, err = repo.records(); err != nil {
285 return failClosed(stderr, err)
286 }
287 }
288 if p.requestCreates = requestCreates(*principal, updates); p.requestCreates > 0 {
289 var err error
290 if p.existingRequests, err = repo.checkRequests(*principal); err != nil {
291 return failClosed(stderr, err)
292 }
293 }
294
295 // Which of the refs are symbolic is read once for the whole push.
296 refs := make([]string, len(updates))
297 for i, u := range updates {
298 refs[i] = u.ref
299 }
300 symrefs, err := repo.symbolic(refs)
301 if err != nil {
302 return failClosed(stderr, err)
303 }
304 p.symrefs = symrefs
305
306 p.pushed = map[string]string{}
307 for _, u := range updates {
308 p.pushed[u.ref] = u.new
309 }
310 refused := false
311 for _, u := range updates {
312 if refusal := p.decide(*principal, u); refusal != "" {
313 fmt.Fprintln(stderr, refusal)
314 refused = true
315 }
316 }
317 if refused {
318 return 1
319 }
320 if *then != "" {
321 return runThen(*then, input.Bytes(), stderr)
322 }
323 return 0
324}
325
326// runThen runs the composed hook over the same input, in this hook's
327// environment, and its exit status is the push's.
328func runThen(path string, input []byte, stderr io.Writer) int {
329 cmd := exec.Command(path)
330 cmd.Stdin = bytes.NewReader(input)
331 cmd.Stdout = os.Stdout
332 cmd.Stderr = stderr
333 err := cmd.Run()
334 var exit *exec.ExitError
335 switch {
336 case err == nil:
337 return 0
338 case errors.As(err, &exit):
339 return exit.ExitCode()
340 default:
341 return failClosed(stderr, fmt.Errorf("the composed hook %s did not run: %w", path, err))
342 }
343}
344
345// failClosed refuses the whole push for a reason that is not about any one
346// ref.
347func failClosed(stderr io.Writer, err error) int {
348 fmt.Fprintf(stderr, "valley: the push is refused because its policy could not be applied: %v\n", err)
349 return 1
350}