gunk-dev/the-valley

main.go

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