gunk-dev/the-valley

main.go

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