gunk-dev/the-valley

main.go

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