gunk-dev/the-valley

policy.go

source10091af9534amain's published tip history
11.5 KiB
1package main
2
3import (
4 "fmt"
5 "strings"
6
7 "the-valley/change"
8 "the-valley/knot"
9 "the-valley/note"
10)
11
12// pushPolicy is what a project declares about pushes to it, as the host
13// declaration exports it (schema/valley.cue): the protected refs and their
14// writers from its protection block, and its named ref grants. A project
15// that declares no protection block protects nothing, and every other rule
16// applies to it unchanged.
17type pushPolicy struct {
18 // Refs are the protected ref patterns. A ref one of them matches takes
19 // a push only from one of Writers, on top of whatever else its
20 // namespace requires.
21 Refs []string `json:"refs"`
22 Writers []string `json:"writers"`
23
24 // Grants open refs the namespace rules close, each to the principals
25 // it names. Tags open only this way.
26 Grants map[string]refGrant `json:"grants"`
27}
28
29// refGrant is one named grant: ref patterns, and who may write them.
30type refGrant struct {
31 Refs []string `json:"refs"`
32 Writers []string `json:"writers"`
33}
34
35// The namespaces whose rule is fixed rather than declared.
36const (
37 replacePrefix = "refs/replace/"
38 notesPrefix = "refs/notes/"
39 valleyPrefix = "refs/the-valley/"
40 attestationPrefix = "refs/the-valley/attestations/"
41 requestPrefix = "refs/the-valley/integration-requests/"
42 branchPrefix = "refs/heads/"
43
44 // grantApprove is the grant that opens the integration-request
45 // namespace (dcr-e544f20). It is also accepted under grantRequest, the
46 // name it had first: a principal holding either holds it (grants.go).
47 grantApprove = "approve"
48 grantRequest = "request"
49
50 // approveGrant is how a refusal names the approve grant, with the
51 // other name it is accepted under.
52 approveGrant = grantApprove + " grant (also accepted as " + grantRequest + ")"
53
54 // grantRestack is the host restacker's grant: it adds one version to
55 // another principal's ready change (record.go), and it opens the
56 // restack report namespace (report.go). It opens nothing else.
57 grantRestack = "restack"
58)
59
60// lookupPrefixes are what git puts before a name it looks up, once the
61// name as given is not a ref (git's ref_rev_parse_rules). So a ref the
62// valley reads by its full name, when it is missing, is read, fetched and
63// pushed to as one of these prefixes followed by that name, or under
64// refs/remotes/ with /HEAD after it.
65var lookupPrefixes = []string{"refs/", "refs/tags/", "refs/heads/", "refs/remotes/"}
66
67// lookalike returns the prefix when ref is named like another ref: one of
68// lookupPrefixes followed by a full ref name. Every name git tries in
69// place of a missing full ref name has this shape, so the test needs no
70// list of the refs the valley reads.
71func lookalike(ref string) (string, bool) {
72 for _, prefix := range lookupPrefixes {
73 if strings.HasPrefix(ref, prefix+"refs/") {
74 return prefix, true
75 }
76 }
77 return "", false
78}
79
80// policy is everything one push is judged against.
81type policy struct {
82 project string
83 push pushPolicy
84 grants grants
85
86 // verifiers are the keys the host accepts evidence from. An
87 // attestation is accepted only under one of them.
88 verifiers []note.VerifierKey
89
90 // repo answers what the decision needs to know about the repository:
91 // what a pushed object holds, and how many change records it has.
92 repo repository
93
94 // symrefs are the refs the push writes that are symbolic in the
95 // repository. preReceive reads them all at once, before any update is
96 // decided.
97 symrefs map[string]bool
98
99 // recordCreates is how many change records the push creates, and
100 // existingRecords how many the repository held before it. preReceive
101 // counts both before any update is decided, and only when the push
102 // creates a record.
103 recordCreates, existingRecords int
104}
105
106// update is one line of what git hands a pre-receive hook.
107type update struct {
108 old, new, ref string
109}
110
111// decide returns "" when principal may make the write, and otherwise the
112// sentence that refuses it. An empty principal is a key that names none:
113// it is nobody's writer and holds no grant, so it writes only what anyone
114// may.
115//
116// A write is allowed only if every rule that applies to the ref allows it,
117// checked in this order:
118//
119// 1. Some refs no push may write, whatever anything declares: replacement
120// refs, notes, and the valley's own namespace apart from attestations,
121// integration requests, change records, restack reports and the plan
122// graph. The plan graph is one ref, refs/the-valley/knots, matched
123// exactly: a ref that only begins with its name is in the closed
124// namespace. Nor may a push create or update a ref named like another
125// (lookalike), since git would read it in place of that ref when that
126// ref is missing. A push may still delete one, by the rules below.
127// 2. A ref that is symbolic in the repository takes no push. git would
128// write the ref it points at, and that ref is not the one decided.
129// 3. The ref's namespace has its own rule. Topic branches are open.
130// Attestations are create-only and must be what their name says.
131// Integration requests take the approve grant. A change record moves
132// only by the transitions checkRecord allows. A restack report takes
133// the restack grant, and moves only by the writes checkReport allows.
134// The plan graph takes a named principal, and moves only by the writes
135// checkGraph allows.
136// Every other ref, tags included, takes a named grant that opens it to
137// the principal.
138// 4. A protected ref also takes a declared writer.
139//
140// Protection only ever adds a requirement. A writer of a pattern that
141// covers integration requests still needs the approve grant, and a writer
142// of a tag pattern still needs a grant that opens the tag.
143func (p policy) decide(principal string, u update) string {
144 who := principal
145 if who == "" {
146 who = "<untagged key>"
147 }
148 refuse := func(verb, why string) string {
149 return fmt.Sprintf("valley: %s may not %s %s — %s", who, verb, u.ref, why)
150 }
151
152 switch {
153 case strings.HasPrefix(u.ref, replacePrefix):
154 return refuse("write", "refs/replace/ is closed to every push: a replacement ref makes one object stand in for another wherever git looks it up, so it would change what every reader of the repository sees")
155 case strings.HasPrefix(u.ref, notesPrefix):
156 return refuse("write", "refs/notes/ is closed to every push: a note attaches text to an object that every reader's git shows beside it")
157 case strings.HasPrefix(u.ref, valleyPrefix) && !strings.HasPrefix(u.ref, attestationPrefix) &&
158 !strings.HasPrefix(u.ref, requestPrefix) && !strings.HasPrefix(u.ref, change.RefPrefix) &&
159 !strings.HasPrefix(u.ref, change.RestackPrefix) && u.ref != knot.Ref:
160 return refuse("write", fmt.Sprintf("%s is written only by the machinery on the host, and no push may write it", namespace(u.ref)))
161 }
162 if prefix, ok := lookalike(u.ref); ok && !isZero(u.new) {
163 verb := "update"
164 if isZero(u.old) {
165 verb = "create"
166 }
167 return refuse(verb, fmt.Sprintf("no push may create or update a ref named %s followed by a full ref name: when %s is missing, git reads, fetches and pushes to this ref in its place", prefix, strings.TrimPrefix(u.ref, prefix)))
168 }
169
170 if p.symrefs[u.ref] {
171 return refuse("write", "it is a symbolic ref in this repository, and a push to it would write the ref it points at instead")
172 }
173
174 switch {
175 case strings.HasPrefix(u.ref, branchPrefix):
176 // Topic branches are open.
177
178 case strings.HasPrefix(u.ref, attestationPrefix):
179 if !isZero(u.old) {
180 return refuse("update", "attestation refs are create-only")
181 }
182 if err := p.checkAttestation(u.ref, u.new); err != nil {
183 return refuse("create", err.Error())
184 }
185
186 case strings.HasPrefix(u.ref, requestPrefix):
187 if principal == "" || !p.grants.holds(principal, grantApprove) {
188 holder := who + " holds none"
189 if principal == "" {
190 holder = "a key that names no principal holds no grant"
191 }
192 return refuse("write", fmt.Sprintf("%s takes writes only from a principal holding the %s, and %s", requestPrefix, approveGrant, holder))
193 }
194
195 case strings.HasPrefix(u.ref, change.RefPrefix):
196 if verb, why := p.checkRecord(principal, u); why != "" {
197 return refuse(verb, why)
198 }
199
200 case strings.HasPrefix(u.ref, change.RestackPrefix):
201 if verb, why := p.checkReport(principal, u); why != "" {
202 return refuse(verb, why)
203 }
204
205 case u.ref == knot.Ref:
206 if verb, why := p.checkGraph(principal, u); why != "" {
207 return refuse(verb, why)
208 }
209
210 default:
211 names, opened := p.push.openedTo(u.ref)
212 if principal == "" || !contains(opened, principal) {
213 closed := namespace(u.ref)
214 if len(opened) > 0 {
215 return refuse("write", fmt.Sprintf("%s opens only through a named grant, and %s of %s opens this ref to %s only", closed, grantList(names), p.project, strings.Join(opened, ", ")))
216 }
217 return refuse("write", fmt.Sprintf("%s opens only through a named grant, and no grant of %s opens this ref", closed, p.project))
218 }
219 }
220
221 if p.push.protects(u.ref) && (principal == "" || !contains(p.push.Writers, principal)) {
222 return refuse("write", fmt.Sprintf("a protected ref of %s (%s)", p.project, p.push.whoMay()))
223 }
224 return ""
225}
226
227// protects reports whether ref is one of the project's protected refs.
228func (p pushPolicy) protects(ref string) bool {
229 for _, pattern := range p.Refs {
230 if match(pattern, ref) {
231 return true
232 }
233 }
234 return false
235}
236
237// whoMay is what a refusal says about who may write a protected ref
238// instead. With no writer declared there is no one, so it says how a
239// change lands.
240func (p pushPolicy) whoMay() string {
241 if len(p.Writers) == 0 {
242 return "no writer is declared — changes land by integration request"
243 }
244 return "writers: " + strings.Join(p.Writers, ", ")
245}
246
247// openedTo lists the grants that open ref and the principals they open it
248// to, both in name order so a refusal reads the same on every push.
249func (p pushPolicy) openedTo(ref string) (names, who []string) {
250 for _, name := range sortedKeys(p.Grants) {
251 g := p.Grants[name]
252 for _, pattern := range g.Refs {
253 if match(pattern, ref) {
254 names = append(names, name)
255 for _, w := range g.Writers {
256 if !contains(who, w) {
257 who = append(who, w)
258 }
259 }
260 break
261 }
262 }
263 }
264 return names, who
265}
266
267func grantList(names []string) string {
268 if len(names) == 1 {
269 return "the grant " + names[0]
270 }
271 return "the grants " + strings.Join(names, ", ")
272}
273
274// match reports whether ref matches a declared pattern. `*` matches any
275// run of characters, path separators included, which is how the patterns
276// are documented (schema/valley.cue). Every other character matches
277// itself: the schema refuses the characters a shell glob would read
278// specially, because git refuses them in a refname too.
279func match(pattern, ref string) bool {
280 p, r := 0, 0
281 star, resume := -1, 0
282 for r < len(ref) {
283 switch {
284 case p < len(pattern) && pattern[p] == '*':
285 star, resume = p, r
286 p++
287 case p < len(pattern) && pattern[p] == ref[r]:
288 p++
289 r++
290 case star >= 0:
291 // Let the last star take one more character, and try the
292 // rest of the pattern again from there.
293 resume++
294 p, r = star+1, resume
295 default:
296 return false
297 }
298 }
299 for p < len(pattern) && pattern[p] == '*' {
300 p++
301 }
302 return p == len(pattern)
303}
304
305// namespace is the part of a refname a refusal names: refs/<kind>/, or
306// refs/the-valley/<kind>/ for the valley's own refs.
307func namespace(ref string) string {
308 parts := strings.Split(ref, "/")
309 n := 2
310 if len(parts) > 1 && parts[1] == "the-valley" {
311 n = 3
312 }
313 if len(parts) <= n {
314 return ref
315 }
316 return strings.Join(parts[:n], "/") + "/"
317}
318
319func isZero(id string) bool {
320 return id != "" && strings.Trim(id, "0") == ""
321}
322
323func contains(list []string, s string) bool {
324 for _, x := range list {
325 if x == s {
326 return true
327 }
328 }
329 return false
330}