gunk-dev/the-valley

policy.go

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