gunk-dev/the-valley

main.go

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