gunk-dev/the-valley

policy.go

sourcebabe14e6c71cmain's published tip history
10.2 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// policy is everything one push is judged against.
61type policy struct {
62 project string
63 push pushPolicy
64 grants grants
65
66 // verifiers are the keys the host accepts evidence from. An
67 // attestation is accepted only under one of them.
68 verifiers []note.VerifierKey
69
70 // repo answers what the decision needs to know about the repository:
71 // what a pushed object holds, and how many change records it has.
72 repo repository
73
74 // symrefs are the refs the push writes that are symbolic in the
75 // repository. preReceive reads them all at once, before any update is
76 // decided.
77 symrefs map[string]bool
78
79 // recordCreates is how many change records the push creates, and
80 // existingRecords how many the repository held before it. preReceive
81 // counts both before any update is decided, and only when the push
82 // creates a record.
83 recordCreates, existingRecords int
84}
85
86// update is one line of what git hands a pre-receive hook.
87type update struct {
88 old, new, ref string
89}
90
91// decide returns "" when principal may make the write, and otherwise the
92// sentence that refuses it. An empty principal is a key that names none:
93// it is nobody's writer and holds no grant, so it writes only what anyone
94// may.
95//
96// A write is allowed only if every rule that applies to the ref allows it,
97// checked in this order:
98//
99// 1. Some refs no push may write, whatever anything declares: replacement
100// refs, notes, and the valley's own namespace apart from attestations,
101// integration requests, change records, restack reports and the plan
102// graph. The plan graph is one ref, refs/the-valley/knots, matched
103// exactly: a ref that only begins with its name is in the closed
104// namespace.
105// 2. A ref that is symbolic in the repository takes no push. git would
106// write the ref it points at, and that ref is not the one decided.
107// 3. The ref's namespace has its own rule. Topic branches are open.
108// Attestations are create-only and must be what their name says.
109// Integration requests take the approve grant. A change record moves
110// only by the transitions checkRecord allows. A restack report takes
111// the restack grant, and moves only by the writes checkReport allows.
112// The plan graph takes a named principal, and moves only by the writes
113// checkGraph allows.
114// Every other ref, tags included, takes a named grant that opens it to
115// the principal.
116// 4. A protected ref also takes a declared writer.
117//
118// Protection only ever adds a requirement. A writer of a pattern that
119// covers integration requests still needs the approve grant, and a writer
120// of a tag pattern still needs a grant that opens the tag.
121func (p policy) decide(principal string, u update) string {
122 who := principal
123 if who == "" {
124 who = "<untagged key>"
125 }
126 refuse := func(verb, why string) string {
127 return fmt.Sprintf("valley: %s may not %s %s — %s", who, verb, u.ref, why)
128 }
129
130 switch {
131 case strings.HasPrefix(u.ref, replacePrefix):
132 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")
133 case strings.HasPrefix(u.ref, notesPrefix):
134 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")
135 case strings.HasPrefix(u.ref, valleyPrefix) && !strings.HasPrefix(u.ref, attestationPrefix) &&
136 !strings.HasPrefix(u.ref, requestPrefix) && !strings.HasPrefix(u.ref, change.RefPrefix) &&
137 !strings.HasPrefix(u.ref, change.RestackPrefix) && u.ref != knot.Ref:
138 return refuse("write", fmt.Sprintf("%s is written only by the machinery on the host, and no push may write it", namespace(u.ref)))
139 }
140
141 if p.symrefs[u.ref] {
142 return refuse("write", "it is a symbolic ref in this repository, and a push to it would write the ref it points at instead")
143 }
144
145 switch {
146 case strings.HasPrefix(u.ref, branchPrefix):
147 // Topic branches are open.
148
149 case strings.HasPrefix(u.ref, attestationPrefix):
150 if !isZero(u.old) {
151 return refuse("update", "attestation refs are create-only")
152 }
153 if err := p.checkAttestation(u.ref, u.new); err != nil {
154 return refuse("create", err.Error())
155 }
156
157 case strings.HasPrefix(u.ref, requestPrefix):
158 if principal == "" || !p.grants.holds(principal, grantApprove) {
159 holder := who + " holds none"
160 if principal == "" {
161 holder = "a key that names no principal holds no grant"
162 }
163 return refuse("write", fmt.Sprintf("%s takes writes only from a principal holding the %s, and %s", requestPrefix, approveGrant, holder))
164 }
165
166 case strings.HasPrefix(u.ref, change.RefPrefix):
167 if verb, why := p.checkRecord(principal, u); why != "" {
168 return refuse(verb, why)
169 }
170
171 case strings.HasPrefix(u.ref, change.RestackPrefix):
172 if verb, why := p.checkReport(principal, u); why != "" {
173 return refuse(verb, why)
174 }
175
176 case u.ref == knot.Ref:
177 if verb, why := p.checkGraph(principal, u); why != "" {
178 return refuse(verb, why)
179 }
180
181 default:
182 names, opened := p.push.openedTo(u.ref)
183 if principal == "" || !contains(opened, principal) {
184 closed := namespace(u.ref)
185 if len(opened) > 0 {
186 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, ", ")))
187 }
188 return refuse("write", fmt.Sprintf("%s opens only through a named grant, and no grant of %s opens this ref", closed, p.project))
189 }
190 }
191
192 if p.push.protects(u.ref) && (principal == "" || !contains(p.push.Writers, principal)) {
193 return refuse("write", fmt.Sprintf("a protected ref of %s (%s)", p.project, p.push.whoMay()))
194 }
195 return ""
196}
197
198// protects reports whether ref is one of the project's protected refs.
199func (p pushPolicy) protects(ref string) bool {
200 for _, pattern := range p.Refs {
201 if match(pattern, ref) {
202 return true
203 }
204 }
205 return false
206}
207
208// whoMay is what a refusal says about who may write a protected ref
209// instead. With no writer declared there is no one, so it says how a
210// change lands.
211func (p pushPolicy) whoMay() string {
212 if len(p.Writers) == 0 {
213 return "no writer is declared — changes land by integration request"
214 }
215 return "writers: " + strings.Join(p.Writers, ", ")
216}
217
218// openedTo lists the grants that open ref and the principals they open it
219// to, both in name order so a refusal reads the same on every push.
220func (p pushPolicy) openedTo(ref string) (names, who []string) {
221 for _, name := range sortedKeys(p.Grants) {
222 g := p.Grants[name]
223 for _, pattern := range g.Refs {
224 if match(pattern, ref) {
225 names = append(names, name)
226 for _, w := range g.Writers {
227 if !contains(who, w) {
228 who = append(who, w)
229 }
230 }
231 break
232 }
233 }
234 }
235 return names, who
236}
237
238func grantList(names []string) string {
239 if len(names) == 1 {
240 return "the grant " + names[0]
241 }
242 return "the grants " + strings.Join(names, ", ")
243}
244
245// match reports whether ref matches a declared pattern. `*` matches any
246// run of characters, path separators included, which is how the patterns
247// are documented (schema/valley.cue). Every other character matches
248// itself: the schema refuses the characters a shell glob would read
249// specially, because git refuses them in a refname too.
250func match(pattern, ref string) bool {
251 p, r := 0, 0
252 star, resume := -1, 0
253 for r < len(ref) {
254 switch {
255 case p < len(pattern) && pattern[p] == '*':
256 star, resume = p, r
257 p++
258 case p < len(pattern) && pattern[p] == ref[r]:
259 p++
260 r++
261 case star >= 0:
262 // Let the last star take one more character, and try the
263 // rest of the pattern again from there.
264 resume++
265 p, r = star+1, resume
266 default:
267 return false
268 }
269 }
270 for p < len(pattern) && pattern[p] == '*' {
271 p++
272 }
273 return p == len(pattern)
274}
275
276// namespace is the part of a refname a refusal names: refs/<kind>/, or
277// refs/the-valley/<kind>/ for the valley's own refs.
278func namespace(ref string) string {
279 parts := strings.Split(ref, "/")
280 n := 2
281 if len(parts) > 1 && parts[1] == "the-valley" {
282 n = 3
283 }
284 if len(parts) <= n {
285 return ref
286 }
287 return strings.Join(parts[:n], "/") + "/"
288}
289
290func isZero(id string) bool {
291 return id != "" && strings.Trim(id, "0") == ""
292}
293
294func contains(list []string, s string) bool {
295 for _, x := range list {
296 if x == s {
297 return true
298 }
299 }
300 return false
301}