gunk-dev/the-valley

main.go

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