gunk-dev/the-valley

policy.go

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