gunk-dev/the-valley

policy.go

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