gunk-dev/the-valley

main.go

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