gunk-dev/the-valley

main.go

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