gunk-dev/the-valley

policy.go

source40b311d8f0demain's published tip history
13.4 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 // pushed is the value every ref the push writes takes, a delete's
114 // zero ID included. A decision about one ref reads it for another ref
115 // the same push writes (besideRequest).
116 pushed map[string]string
117
118 // requestCreates is how many check requests the push creates under
119 // the pushing principal's name, and existingRequests how many that
120 // principal held before it. preReceive counts both the same way.
121 requestCreates, existingRequests int
122}
123
124// update is one line of what git hands a pre-receive hook.
125type update struct {
126 old, new, ref string
127}
128
129// decide returns "" when principal may make the write, and otherwise the
130// sentence that refuses it. An empty principal is a key that names none:
131// it is nobody's writer and holds no grant, so it writes only what anyone
132// may.
133//
134// A write is allowed only if every rule that applies to the ref allows it,
135// checked in this order:
136//
137// 1. Some refs no push may write, whatever anything declares: replacement
138// refs, notes, and the valley's own namespace apart from attestations,
139// integration requests, approvals, change records, restack reports,
140// check requests and the plan graph. The plan graph is one ref, refs/the-valley/knots, matched
141// exactly: a ref that only begins with its name is in the closed
142// namespace. Nor may a push create or update a ref named like another
143// (lookalike), since git would read it in place of that ref when that
144// ref is missing. A push may still delete one, by the rules below.
145// 2. A ref that is symbolic in the repository takes no push. git would
146// write the ref it points at, and that ref is not the one decided.
147// 3. The ref's namespace has its own rule. Topic branches are open.
148// Attestations must be what their name says, and an existing one
149// only takes added notes.
150// Integration requests take the approve grant. An approval takes the
151// approve grant, and holds an approval note about the change its name
152// says (checkApproval). A change record moves only by the transitions
153// checkRecord allows, and is never deleted from a project that retains
154// its records. A restack report takes
155// the restack grant, and moves only by the writes checkReport allows.
156// A check request takes a named principal under its own name, or a
157// holder of the approve grant deleting it, and points at a commit
158// (checkCheckRequest).
159// The plan graph takes a named principal, and moves only by the writes
160// checkGraph allows.
161// Every other ref, tags included, takes a named grant that opens it to
162// the principal.
163// 4. A protected ref also takes a declared writer.
164//
165// Protection only ever adds a requirement. A writer of a pattern that
166// covers integration requests still needs the approve grant, and a writer
167// of a tag pattern still needs a grant that opens the tag.
168func (p policy) decide(principal string, u update) string {
169 who := principal
170 if who == "" {
171 who = "<untagged key>"
172 }
173 refuse := func(verb, why string) string {
174 return fmt.Sprintf("valley: %s may not %s %s — %s", who, verb, u.ref, why)
175 }
176
177 switch {
178 case strings.HasPrefix(u.ref, replacePrefix):
179 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")
180 case strings.HasPrefix(u.ref, notesPrefix):
181 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")
182 case strings.HasPrefix(u.ref, valleyPrefix) && !strings.HasPrefix(u.ref, attestationPrefix) &&
183 !strings.HasPrefix(u.ref, requestPrefix) && !strings.HasPrefix(u.ref, approval.RefPrefix) && !strings.HasPrefix(u.ref, change.RefPrefix) &&
184 !strings.HasPrefix(u.ref, change.RestackPrefix) && !strings.HasPrefix(u.ref, change.CheckRequestPrefix) && u.ref != knot.Ref:
185 return refuse("write", fmt.Sprintf("%s is written only by the machinery on the host, and no push may write it", namespace(u.ref)))
186 }
187 if prefix, ok := lookalike(u.ref); ok && !isZero(u.new) {
188 verb := "update"
189 if isZero(u.old) {
190 verb = "create"
191 }
192 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)))
193 }
194
195 if p.symrefs[u.ref] {
196 return refuse("write", "it is a symbolic ref in this repository, and a push to it would write the ref it points at instead")
197 }
198
199 switch {
200 case strings.HasPrefix(u.ref, branchPrefix):
201 // Topic branches are open.
202
203 case strings.HasPrefix(u.ref, attestationPrefix):
204 switch {
205 case isZero(u.new):
206 return refuse("delete", "published evidence is never removed, so no push deletes an attestation ref")
207 case isZero(u.old):
208 if err := p.checkAttestation(u.ref, u.new); err != nil {
209 return refuse("create", err.Error())
210 }
211 default:
212 if err := p.checkAttestationUpdate(u.ref, u.old, u.new); err != nil {
213 return refuse("update", err.Error())
214 }
215 }
216
217 case strings.HasPrefix(u.ref, requestPrefix):
218 if principal == "" || !p.grants.holds(principal, grantApprove) {
219 holder := who + " holds none"
220 if principal == "" {
221 holder = "a key that names no principal holds no grant"
222 }
223 return refuse("write", fmt.Sprintf("%s takes writes only from a principal holding the %s, and %s", requestPrefix, approveGrant, holder))
224 }
225
226 case strings.HasPrefix(u.ref, approval.RefPrefix):
227 if verb, why := p.checkApproval(principal, u); why != "" {
228 return refuse(verb, why)
229 }
230
231 case strings.HasPrefix(u.ref, change.RefPrefix):
232 if verb, why := p.checkRecord(principal, u); why != "" {
233 return refuse(verb, why)
234 }
235
236 case strings.HasPrefix(u.ref, change.RestackPrefix):
237 if verb, why := p.checkReport(principal, u); why != "" {
238 return refuse(verb, why)
239 }
240
241 case strings.HasPrefix(u.ref, change.CheckRequestPrefix):
242 if verb, why := p.checkCheckRequest(principal, u); why != "" {
243 return refuse(verb, why)
244 }
245
246 case u.ref == knot.Ref:
247 if verb, why := p.checkGraph(principal, u); why != "" {
248 return refuse(verb, why)
249 }
250
251 default:
252 names, opened := p.push.openedTo(u.ref)
253 if principal == "" || !contains(opened, principal) {
254 closed := namespace(u.ref)
255 if len(opened) > 0 {
256 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, ", ")))
257 }
258 return refuse("write", fmt.Sprintf("%s opens only through a named grant, and no grant of %s opens this ref", closed, p.project))
259 }
260 }
261
262 if p.push.protects(u.ref) && (principal == "" || !contains(p.push.Writers, principal)) {
263 return refuse("write", fmt.Sprintf("a protected ref of %s (%s)", p.project, p.push.whoMay()))
264 }
265 return ""
266}
267
268// protects reports whether ref is one of the project's protected refs.
269func (p pushPolicy) protects(ref string) bool {
270 for _, pattern := range p.Refs {
271 if match(pattern, ref) {
272 return true
273 }
274 }
275 return false
276}
277
278// whoMay is what a refusal says about who may write a protected ref
279// instead. With no writer declared there is no one, so it says how a
280// change lands.
281func (p pushPolicy) whoMay() string {
282 if len(p.Writers) == 0 {
283 return "no writer is declared — changes land by integration request"
284 }
285 return "writers: " + strings.Join(p.Writers, ", ")
286}
287
288// openedTo lists the grants that open ref and the principals they open it
289// to, both in name order so a refusal reads the same on every push.
290func (p pushPolicy) openedTo(ref string) (names, who []string) {
291 for _, name := range sortedKeys(p.Grants) {
292 g := p.Grants[name]
293 for _, pattern := range g.Refs {
294 if match(pattern, ref) {
295 names = append(names, name)
296 for _, w := range g.Writers {
297 if !contains(who, w) {
298 who = append(who, w)
299 }
300 }
301 break
302 }
303 }
304 }
305 return names, who
306}
307
308func grantList(names []string) string {
309 if len(names) == 1 {
310 return "the grant " + names[0]
311 }
312 return "the grants " + strings.Join(names, ", ")
313}
314
315// match reports whether ref matches a declared pattern. `*` matches any
316// run of characters, path separators included, which is how the patterns
317// are documented (schema/valley.cue). Every other character matches
318// itself: the schema refuses the characters a shell glob would read
319// specially, because git refuses them in a refname too.
320func match(pattern, ref string) bool {
321 p, r := 0, 0
322 star, resume := -1, 0
323 for r < len(ref) {
324 switch {
325 case p < len(pattern) && pattern[p] == '*':
326 star, resume = p, r
327 p++
328 case p < len(pattern) && pattern[p] == ref[r]:
329 p++
330 r++
331 case star >= 0:
332 // Let the last star take one more character, and try the
333 // rest of the pattern again from there.
334 resume++
335 p, r = star+1, resume
336 default:
337 return false
338 }
339 }
340 for p < len(pattern) && pattern[p] == '*' {
341 p++
342 }
343 return p == len(pattern)
344}
345
346// namespace is the part of a refname a refusal names: refs/<kind>/, or
347// refs/the-valley/<kind>/ for the valley's own refs.
348func namespace(ref string) string {
349 parts := strings.Split(ref, "/")
350 n := 2
351 if len(parts) > 1 && parts[1] == "the-valley" {
352 n = 3
353 }
354 if len(parts) <= n {
355 return ref
356 }
357 return strings.Join(parts[:n], "/") + "/"
358}
359
360func isZero(id string) bool {
361 return id != "" && strings.Trim(id, "0") == ""
362}
363
364func contains(list []string, s string) bool {
365 for _, x := range list {
366 if x == s {
367 return true
368 }
369 }
370 return false
371}