gunk-dev/the-valley

policy.go

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