gunk-dev/the-valley

policy.go

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