gunk-dev/the-valley

main.go

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