gunk-dev/the-valley

main.go

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