gunk-dev/the-valley

main.go

source20b79cbd2afcmain's published tip history
8.0 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
23const usage = `usage: valleyhook pre-receive [flags] < ref updates
24 valleyhook shell [flags] -- [-c COMMAND]
25
26shell is the git user's login shell; see "valleyhook shell -h".
27
28The pre-receive hook of every project on a valley host. git hands it one
29line per ref a push would update: the old id, the new id and the refname.
30It accepts the push only if the pushing principal may make every one of
31those writes. One refusal refuses the whole push, atomic or not, because a
32pre-receive hook answers for the push and not for each ref.
33
34A write is allowed only if every rule that applies to its ref allows it:
35
36 refs/replace/*, refs/notes/*, and refs/the-valley/* other than the two
37 namespaces below
38 nobody, whatever a declaration says. A replacement ref
39 makes one object stand in for another wherever git
40 looks it up; a note attaches text every reader sees;
41 the rest of the valley's namespace is the machinery's.
42 a symbolic ref nobody. A push to one would write the ref it points at.
43 refs/heads/* anyone: topic branches.
44 refs/the-valley/attestations/<digest>/<key hash>
45 anyone, and only to create one. The ref must point at
46 a tree of notes about that digest, read within fixed
47 bounds, each opening under the --known-signers keys
48 the way attest verify opens it, with a verified
49 signature under that key hash.
50 refs/the-valley/integration-requests/*
51 principals holding the request grant. They may file,
52 replace and withdraw a request.
53 anything else principals a named grant of the project opens the ref
54 to. Tags open only this way.
55 a protected ref also a declared writer of the project. Protection adds
56 this requirement and removes none of the ones above.
57
58The integrator's own writes are not pushes. A controller updates the refs
59it writes on the host, and no push hook sees a local write.
60
61A policy, grants or keys file that cannot be read refuses the whole push.
62The hook fails closed: a policy it cannot read is not a policy it can
63apply. A grants or keys file that does not exist grants nothing and names
64no key.
65
66flags:
67 --project NAME the project, named in what a refusal says
68 --policy FILE the project's push policy, as the host declaration
69 exports it (JSON): its protected refs, their
70 writers, and its named grants
71 --grants FILE grants, one "<grant> <principal>" per line. Repeat
72 the flag to read more than one file; what they
73 grant adds up.
74 --known-signers FILE verifier keys, one per line, that an attestation's
75 signature is checked against. Repeatable. With no
76 key named, no attestation is accepted.
77 --principal NAME the pushing principal; empty for a key that names
78 none
79 --then FILE a further pre-receive hook, run only once this one
80 accepts the push, with the same input. It can refuse
81 what this one accepts and never the reverse.
82`
83
84func main() {
85 if len(os.Args) < 2 {
86 fmt.Fprint(os.Stderr, usage)
87 os.Exit(2)
88 }
89 switch os.Args[1] {
90 case "pre-receive":
91 os.Exit(preReceive(os.Args[2:], os.Stdin, os.Stderr, gitRepository{}))
92 case "shell":
93 os.Exit(shell(os.Args[2:], os.Stderr))
94 case "help", "-h", "--help":
95 fmt.Print(usage)
96 default:
97 fmt.Fprintf(os.Stderr, "valleyhook: unknown command %q\n\n%s", os.Args[1], usage)
98 os.Exit(2)
99 }
100}
101
102// preReceive runs the hook over the updates on stdin and returns its exit
103// status: 0 accepts the push, anything else refuses it.
104func preReceive(args []string, stdin io.Reader, stderr io.Writer, repo repository) int {
105 fs := flag.NewFlagSet("pre-receive", flag.ContinueOnError)
106 fs.SetOutput(stderr)
107 fs.Usage = func() { fmt.Fprint(stderr, usage) }
108 project := fs.String("project", "", "the project, named in what a refusal says")
109 policyFile := fs.String("policy", "", "the project's push policy (JSON)")
110 principal := fs.String("principal", "", "the pushing principal")
111 then := fs.String("then", "", "a further pre-receive hook")
112 var grantFiles, keyFiles []string
113 fs.Func("grants", "a grants file; repeatable", func(path string) error {
114 grantFiles = append(grantFiles, path)
115 return nil
116 })
117 fs.Func("known-signers", "a verifier keys file; repeatable", func(path string) error {
118 keyFiles = append(keyFiles, path)
119 return nil
120 })
121 if err := fs.Parse(args); err != nil {
122 return 2
123 }
124 if *project == "" || *policyFile == "" {
125 fmt.Fprintf(stderr, "valleyhook: --project and --policy are required\n")
126 return 2
127 }
128
129 // Everything the decision needs is read before any ref is looked at,
130 // so a policy that cannot be read refuses the push as a whole rather
131 // than part of the way through it.
132 p := policy{project: *project, grants: grants{}, repo: repo}
133 if err := readPolicy(*policyFile, &p.push); err != nil {
134 return failClosed(stderr, err)
135 }
136 for _, path := range grantFiles {
137 if err := p.grants.read(path); err != nil {
138 return failClosed(stderr, err)
139 }
140 }
141 for _, path := range keyFiles {
142 keys, err := readVerifiers(path)
143 if err != nil {
144 return failClosed(stderr, err)
145 }
146 p.verifiers = append(p.verifiers, keys...)
147 }
148
149 input, err := io.ReadAll(stdin)
150 if err != nil {
151 return failClosed(stderr, err)
152 }
153 refused := false
154 lines := bufio.NewScanner(bytes.NewReader(input))
155 for lines.Scan() {
156 if strings.TrimSpace(lines.Text()) == "" {
157 continue
158 }
159 fields := strings.Fields(lines.Text())
160 if len(fields) != 3 {
161 return failClosed(stderr, fmt.Errorf("git sent %q, which is not an old id, a new id and a refname", lines.Text()))
162 }
163 u := update{old: fields[0], new: fields[1], ref: fields[2]}
164 if refusal := p.decide(*principal, u); refusal != "" {
165 fmt.Fprintln(stderr, refusal)
166 refused = true
167 }
168 }
169 if err := lines.Err(); err != nil {
170 return failClosed(stderr, err)
171 }
172 if refused {
173 return 1
174 }
175 if *then != "" {
176 return runThen(*then, input, stderr)
177 }
178 return 0
179}
180
181// runThen runs the composed hook over the same input, in this hook's
182// environment, and its exit status is the push's.
183func runThen(path string, input []byte, stderr io.Writer) int {
184 cmd := exec.Command(path)
185 cmd.Stdin = bytes.NewReader(input)
186 cmd.Stdout = os.Stdout
187 cmd.Stderr = stderr
188 err := cmd.Run()
189 var exit *exec.ExitError
190 switch {
191 case err == nil:
192 return 0
193 case errors.As(err, &exit):
194 return exit.ExitCode()
195 default:
196 return failClosed(stderr, fmt.Errorf("the composed hook %s did not run: %w", path, err))
197 }
198}
199
200// failClosed refuses the whole push for a reason that is not about any one
201// ref.
202func failClosed(stderr io.Writer, err error) int {
203 fmt.Fprintf(stderr, "valley: the push is refused because its policy could not be applied: %v\n", err)
204 return 1
205}
206
207// readPolicy reads the project's push policy. A field this program does
208// not know refuses the read: the policy is exported from the schema this
209// program ships beside, so an unknown field means the two have drifted
210// apart, and the field could be a restriction the hook would otherwise
211// skip.
212func readPolicy(path string, p *pushPolicy) error {
213 f, err := os.Open(path)
214 if err != nil {
215 return err
216 }
217 defer f.Close()
218 dec := json.NewDecoder(f)
219 dec.DisallowUnknownFields()
220 if err := dec.Decode(p); err != nil {
221 return fmt.Errorf("%s: %w", path, err)
222 }
223 return nil
224}