gunk-dev/the-valley

main.go

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