gunk-dev/the-valley

policy.go

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