gunk-dev/the-valley

policy.go

source2886163c0514main's published tip history
17.2 KiB
1package main
2
3// The policy bridge. The integrator does not derive required checks; it
4// asks the deriver, which is `valley checks` (dcr-f41f718). The whole of
5// the mandatory-versus-overridable distinction is CUE unification, so a
6// second implementation of the composition here would be a second copy of
7// the decision.
8//
9// Both layers are resolved from the integrator's own side and never from
10// the submitted tree (bd-eaefe82): the project layer from a checkout of the
11// target tip, the instance layer from where the integrator is configured to
12// find it. A change therefore never supplies the policy that gates it.
13//
14// Each layer is a directory of its own under `policy/`, which is the layout
15// dcr-f41f718's worked example lays out and the layout the defaults name:
16// the floor at `policy/instance` in the instance repository's tip, the
17// project's own layer at `policy/project` in the target tip. A repository
18// that keeps either somewhere else says so with --instance-policy or
19// --project-policy.
20//
21// A layer that is not there defaults in the safe direction of that layer's
22// job (dcr-f41f718), and the two directions are opposite: an absent project
23// layer composes the floor alone, and an absent floor is refused.
24
25import (
26 "the-valley/integrator/verdict"
27
28 "encoding/json"
29 "fmt"
30 "os"
31 "os/exec"
32 "path/filepath"
33 "regexp"
34 "strconv"
35 "strings"
36 "time"
37)
38
39// instanceLayer is where the group's floor comes from. The floor is the
40// instance repository's, read at the tip that has been integrated
41// (dcr-f41f718), and the instance repository is the group's own
42// (dcr-b87f6e8). A host that serves that repository is therefore already
43// holding the authoritative copy, and reading it there is reading it where
44// it is authoritative: no checkout to keep in step, no refresh to schedule,
45// and no way for the floor a controller composes against to differ from the
46// floor the group last landed.
47//
48// The consequence is worth stating, because it is a property and not a
49// limitation. A change to the floor takes effect at the first pass after it
50// lands on that ref, and never before — an edit sitting in a branch, a
51// worktree, or a request that has not been integrated governs nothing.
52//
53// path is the fallback: a directory of `*.cue` on disk, for a host that
54// serves no instance repository and must be given the layer some other way.
55type instanceLayer struct {
56 repo string // the bare repository carrying the floor, read and never written
57 ref string // the ref whose tip is authoritative
58 dir string // the floor's directory in that tip's tree
59 path string // a materialized layer, when no repository carries one
60}
61
62// floorless ends every refusal to find a floor. The floor is the minimum,
63// and a missing minimum reads equally as a controller pointed at the wrong
64// directory, a repository nobody seeded, or a floor somebody deleted. What
65// is refused is the absent document; a floor that states it requires
66// nothing composes and judges like any other.
67const floorless = "a valley without a written floor is not a valley whose changes land"
68
69// open resolves the layer to a directory on disk for the length of one pass,
70// and returns what ends it.
71//
72// The tip is taken apart with ls-tree and show rather than checked out. A
73// worktree would write into the instance repository — git keeps worktree
74// metadata under $GIT_DIR — and a controller has no business writing a
75// repository it does not serve. Reading is all this needs, and reading is
76// all it is granted.
77func (l instanceLayer) open() (string, func(), error) {
78 noop := func() {}
79 if l.repo == "" {
80 // The materialized layer is held to the same minimum as the one a
81 // repository carries: a directory with no documents in it is a floor
82 // nobody wrote.
83 if docs, err := filepath.Glob(filepath.Join(l.path, "*.cue")); err != nil || len(docs) == 0 {
84 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", l.path, floorless)
85 }
86 return l.path, noop, nil
87 }
88 tree := l.ref + ":" + l.dir
89 listing, err := git(l.repo, "ls-tree", "--name-only", tree)
90 if err != nil {
91 return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %s", l.repo, l.dir, l.ref, floorless)
92 }
93 dir, err := scratch("valley-integrator-floor")
94 if err != nil {
95 return "", noop, err
96 }
97 done := func() { _ = os.RemoveAll(dir) }
98 found := 0
99 for _, name := range strings.Split(strings.TrimSpace(listing), "\n") {
100 // The deriver and the composer both read the layer as the `*.cue`
101 // documents directly in it, so those are what is taken.
102 if !strings.HasSuffix(name, ".cue") {
103 continue
104 }
105 body, err := git(l.repo, "show", tree+"/"+name)
106 if err != nil {
107 done()
108 return "", noop, fmt.Errorf("reading %s/%s from %s at %s: %w", l.dir, name, l.repo, l.ref, err)
109 }
110 if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
111 done()
112 return "", noop, err
113 }
114 found++
115 }
116 if found == 0 {
117 done()
118 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %s", l.repo, l.dir, l.ref, floorless)
119 }
120 return dir, done, nil
121}
122
123// policySource is where the two layers are read from, and the schema they
124// are composed under.
125type policySource struct {
126 schema string // the verification schema
127 layer instanceLayer
128 projectDir string // the project layer's directory in the target tip's tree
129 valley string // the deriver
130 cue string // the composer, for the catalogue the deriver does not print
131
132 // Both layers as directories of *.cue on disk, resolved by open and
133 // good for one pass.
134 instance string
135 project string
136
137 // note is the one thing a pass has to say about how the layers
138 // resolved, when that is not what the configuration reads as. Empty
139 // when both were where they are configured to be.
140 note string
141}
142
143// open resolves both layers and returns a source that reads them from disk,
144// together with what ends the pass. Held for the whole pass rather than
145// resolved per call, so the deriver and the composer are given the same
146// bytes: they are two readings of one policy, not two policies.
147func (p policySource) open(tip *worktree) (policySource, func(), error) {
148 dir, done, err := p.layer.open()
149 if err != nil {
150 return p, done, err
151 }
152 p.instance = dir
153 endProject, err := p.openProject(tip)
154 if err != nil {
155 done()
156 return p, func() {}, err
157 }
158 return p, func() { endProject(); done() }, nil
159}
160
161// openProject resolves the project's own layer in the checkout of the target
162// tip, and returns what ends it.
163//
164// A target that carries no layer of its own is judged under the floor
165// alone. The project layer only ever adds (dcr-f41f718), and the identity
166// of "adds" is "adds nothing", so that is what absence means. Refusing the
167// target instead would make a repository unlandable until its first policy
168// commit, which cannot land either: a change never supplies the policy that
169// gates it.
170//
171// Absence is answered with a document that adds nothing rather than with an
172// argument left off, because the deriver and the composer are each handed a
173// directory of *.cue and neither has a spelling for "no layer".
174func (p *policySource) openProject(tip *worktree) (func(), error) {
175 noop := func() {}
176 p.project = filepath.Join(tip.dir, p.projectDir)
177 if docs, err := filepath.Glob(filepath.Join(p.project, "*.cue")); err == nil && len(docs) > 0 {
178 return noop, nil
179 }
180 dir, err := scratch("valley-integrator-project")
181 if err != nil {
182 return noop, err
183 }
184 // A package clause and nothing else: `project` stays what the schema
185 // leaves it, which is three empty sets.
186 if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil {
187 _ = os.RemoveAll(dir)
188 return noop, err
189 }
190 p.project = dir
191 p.note = fmt.Sprintf("no project layer at %s; the floor alone", p.projectDir)
192 return func() { _ = os.RemoveAll(dir) }, nil
193}
194
195// derived is one run of the deriver over a diff: how many changed paths it
196// read, which classes the diff matched, which checks that made required,
197// and the change's carry mode.
198type derived struct {
199 paths int
200 classes map[string]bool
201 requires map[string][]string // check name -> the classes requiring it
202 carry string // how far an approval carries across a rebase
203}
204
205// carryModes are the modes a report may state (schema/verification.cue's
206// #Carry). The integrator reads the mode and does not act on it: approval
207// carry is what reads it.
208var carryModes = map[string]bool{"same-paths": true, "same-class": true, "exact": true}
209
210// derive runs the deriver over a diff, in a checkout of the target tip. The
211// checkout supplies the project layer and the commits the diff names; the
212// instance layer comes from outside it.
213func (p policySource) derive(tip *worktree, from, to string) (derived, error) {
214 cmd := exec.Command(p.valley, "checks",
215 "--schema", p.schema,
216 "--instance", p.instance,
217 "--project", p.project,
218 from, to)
219 cmd.Dir = tip.dir
220 out, err := cmd.CombinedOutput()
221 if err != nil {
222 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w\n%s", verdict.Short(from), verdict.Short(to), err, strings.TrimSpace(string(out)))
223 }
224 d, err := parseDerived(string(out))
225 if err != nil {
226 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w", verdict.Short(from), verdict.Short(to), err)
227 }
228 // A diff the deriver failed to read reads as no changed paths, and no
229 // changed paths require nothing. So a report of none is believed only when
230 // git agrees that the two trees are the same.
231 if d.paths == 0 {
232 if _, err := git(tip.dir, "diff-tree", "--quiet", from, to); err != nil {
233 return derived{}, fmt.Errorf("the deriver read no changed paths in %s..%s, and git does not agree: %w", verdict.Short(from), verdict.Short(to), err)
234 }
235 }
236 return d, nil
237}
238
239// reportHeader is the first line of the deriver's report: the two commits,
240// and how many changed paths it read between them.
241var reportHeader = regexp.MustCompile(`^\S+\.\.\S+: ([0-9]+) changed path\(s\)$`)
242
243// parseDerived reads what `valley checks` printed. The deriver reports for
244// a person, so this is the one place the two programs are coupled by
245// output; the coupling is pinned by the integrator's own checks rather
246// than assumed.
247//
248// Output that is not a whole report is refused rather than read as one
249// that requires nothing: no header, no carry mode or one that is not a
250// mode, no required-checks section, a required-checks heading with no
251// checks under it, or classes that disagree with the number of changed
252// paths. The deriver never prints any of those, so each is a deriver that
253// failed partway and still exited zero.
254//
255// A report that says one thing twice is refused too: a second header,
256// classes line, carry mode or required-checks section, or a second row for
257// one check. The deriver prints each once, so a second is a forged line,
258// and reading the last one would let the forgery win.
259func parseDerived(out string) (derived, error) {
260 d := derived{classes: map[string]bool{}, requires: map[string][]string{}}
261 header, classes, required := false, false, false
262 lines := strings.Split(out, "\n")
263 for i := 0; i < len(lines); i++ {
264 line := lines[i]
265 switch {
266 case reportHeader.MatchString(line):
267 if header {
268 return derived{}, fmt.Errorf("the deriver printed a second header line, %q", line)
269 }
270 n, err := strconv.Atoi(reportHeader.FindStringSubmatch(line)[1])
271 if err != nil {
272 return derived{}, fmt.Errorf("the deriver printed %q, which is not a count of changed paths", line)
273 }
274 d.paths, header = n, true
275 case strings.HasPrefix(line, "classes matched:"):
276 if classes {
277 return derived{}, fmt.Errorf("the deriver printed a second classes line, %q", line)
278 }
279 classes = true
280 rest := strings.TrimSpace(strings.TrimPrefix(line, "classes matched:"))
281 if rest == "none" {
282 continue
283 }
284 for _, c := range strings.Split(rest, ",") {
285 if c = strings.TrimSpace(c); c != "" {
286 d.classes[c] = true
287 }
288 }
289 case strings.HasPrefix(line, "carry mode:"):
290 mode := strings.TrimSpace(strings.TrimPrefix(line, "carry mode:"))
291 if !carryModes[mode] {
292 return derived{}, fmt.Errorf("the deriver printed %q, which is not a carry mode", line)
293 }
294 if d.carry != "" {
295 return derived{}, fmt.Errorf("the deriver printed a second carry mode, %q", line)
296 }
297 d.carry = mode
298 case line == "required checks:":
299 if required {
300 return derived{}, fmt.Errorf("the deriver printed a second required-checks section")
301 }
302 required = true
303 rows := len(d.requires)
304 for i++; i < len(lines); i++ {
305 body := lines[i]
306 if !strings.HasPrefix(body, " ") || strings.TrimSpace(body) == "" {
307 i--
308 break
309 }
310 // " <name> <mandatory|default> <class>[, <class>…]"
311 fields := strings.Fields(body)
312 if len(fields) < 2 {
313 return derived{}, fmt.Errorf("the deriver printed %q, which is not a required-check line", body)
314 }
315 name := fields[0]
316 if _, twice := d.requires[name]; twice {
317 return derived{}, fmt.Errorf("the deriver printed a second row for check %s, %q", name, body)
318 }
319 var by []string
320 for _, c := range strings.Split(strings.Join(fields[2:], " "), ",") {
321 if c = strings.TrimSpace(c); c != "" {
322 by = append(by, c)
323 }
324 }
325 d.requires[name] = by
326 }
327 if len(d.requires) == rows {
328 return derived{}, fmt.Errorf("the deriver printed a required-checks heading with no checks under it")
329 }
330 case strings.HasPrefix(line, "required checks: none"):
331 // Nothing is required; the map stays empty.
332 if required {
333 return derived{}, fmt.Errorf("the deriver printed a second required-checks section")
334 }
335 required = true
336 }
337 }
338 switch {
339 case !header:
340 return derived{}, fmt.Errorf("the deriver printed no header line counting the changed paths, so this is not a report")
341 case d.carry == "":
342 return derived{}, fmt.Errorf("the deriver printed no carry mode, so this is not a report")
343 case !required:
344 return derived{}, fmt.Errorf("the deriver printed no required-checks section, so this is not a report")
345 case d.paths > 0 && len(d.classes) == 0:
346 // Every changed path matches a class, or else it is unclassified,
347 // which the deriver reports as a class of that name.
348 return derived{}, fmt.Errorf("the deriver read %d changed path(s) and matched no class", d.paths)
349 case d.paths == 0 && (len(d.classes) > 0 || len(d.requires) > 0):
350 return derived{}, fmt.Errorf("the deriver read no changed paths and still matched classes or required checks")
351 }
352 return d, nil
353}
354
355// catalogueEntry is one check as the composed policy defines it: how it is
356// run, and how long an observation of it stays good.
357type catalogueEntry struct {
358 Runner string `json:"runner"`
359 Attribute string `json:"attribute"`
360 Command string `json:"command"`
361 Validity string `json:"validity"`
362}
363
364// catalogue reads the composed policy's check definitions. The deriver
365// prints which checks are required and not what a check is, and the
366// integrator needs the latter: a pure check's attribute is what it
367// evaluates a closure over, and an effectful check's window is Δ.
368//
369// This is the same composition the deriver ran, over the same layers and
370// the same schema — `cue export` of a field the deriver does not print,
371// not a second opinion about what the policy says.
372//
373// The digest it returns is of the whole export, so everything the policy
374// composes is in it: every check, every class's paths, requirements and
375// carry mode, and the restacker's cap.
376func (p policySource) catalogue() (map[string]catalogueEntry, string, error) {
377 args := []string{"export", "--out", "json", "-e", "policy", p.schema}
378 for _, dir := range []string{p.instance, p.project} {
379 docs, err := filepath.Glob(filepath.Join(dir, "*.cue"))
380 if err != nil || len(docs) == 0 {
381 return nil, "", fmt.Errorf("no policy layer at %s", dir)
382 }
383 args = append(args, docs...)
384 }
385 cmd := exec.Command(p.cue, args...)
386 out, err := cmd.CombinedOutput()
387 if err != nil {
388 return nil, "", fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out)))
389 }
390 var composed struct {
391 Checks map[string]catalogueEntry `json:"checks"`
392 }
393 if err := json.Unmarshal(out, &composed); err != nil {
394 return nil, "", fmt.Errorf("reading the composed policy: %w", err)
395 }
396 return composed.Checks, sha256hex(out), nil
397}
398
399// required turns a derivation and a catalogue into the check set the
400// verdict is computed over.
401func (p policySource) required(d derived, cat map[string]catalogueEntry) ([]verdict.Required, error) {
402 var out []verdict.Required
403 for name, classes := range d.requires {
404 entry, ok := cat[name]
405 if !ok {
406 return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name)
407 }
408 window, err := parseWindow(entry.Validity)
409 if err != nil {
410 return nil, fmt.Errorf("check %s: %w", name, err)
411 }
412 out = append(out, verdict.Required{
413 Name: name,
414 Classes: classes,
415 Runner: entry.Runner,
416 Attribute: entry.Attribute,
417 Validity: window,
418 })
419 }
420 return out, nil
421}
422
423// parseWindow reads a #Duration from the policy. The schema admits whole
424// seconds, minutes, hours and days; an empty window is no window, which is
425// what makes the integrator re-demand the check.
426func parseWindow(s string) (time.Duration, error) {
427 if s == "" {
428 return 0, nil
429 }
430 unit := s[len(s)-1]
431 if unit == 'd' {
432 d, err := time.ParseDuration(s[:len(s)-1] + "h")
433 return d * 24, err
434 }
435 return time.ParseDuration(s)
436}