gunk-dev/the-valley

policy.go

sourceac6512cd4671main's published tip history
13.8 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/composed"
27 "the-valley/integrator/verdict"
28
29 "context"
30 "fmt"
31 "os/exec"
32 "path/filepath"
33 "regexp"
34 "strconv"
35 "strings"
36 "time"
37)
38
39// The floor is the instance repository's, read at the tip that has been
40// integrated (dcr-f41f718), and the instance repository is the group's own
41// (dcr-b87f6e8). A host that serves that repository is therefore already
42// holding the authoritative copy, and reading it there is reading it where
43// it is authoritative: no checkout to keep in step, no refresh to schedule,
44// and no way for the floor a controller composes against to differ from the
45// floor the group last landed. composed.Floor reads it with ls-tree and
46// show rather than a worktree, because a worktree would write into the
47// instance repository, and a controller has no business writing a
48// repository it does not serve.
49//
50// The consequence is worth stating, because it is a property and not a
51// limitation. A change to the floor takes effect at the first pass after it
52// lands on that ref, and never before — an edit sitting in a branch, a
53// worktree, or a request that has not been integrated governs nothing.
54//
55// A host that serves no instance repository is given a materialized
56// directory of `*.cue` instead.
57
58// policySource is where the two layers are read from, and the schema they
59// are composed under.
60type policySource struct {
61 schema string // the verification schema
62 layer composed.Floor
63 projectDir string // the project layer's directory in the target tip's tree
64 valley string // the deriver
65 cue string // the composer, for the catalogue the deriver does not print
66
67 // Both layers as directories of *.cue on disk, resolved by open and
68 // good for one pass.
69 instance string
70 project string
71
72 // note is the one thing a pass has to say about how the layers
73 // resolved, when that is not what the configuration reads as. Empty
74 // when both were where they are configured to be.
75 note string
76}
77
78// open resolves both layers and returns a source that reads them from disk,
79// together with what ends the pass. Held for the whole pass rather than
80// resolved per call, so the deriver and the composer are given the same
81// bytes: they are two readings of one policy, not two policies.
82func (p policySource) open(tip *worktree) (policySource, func(), error) {
83 dir, done, err := p.layer.Open(context.Background(), "valley-integrator-floor")
84 if err != nil {
85 return p, done, err
86 }
87 p.instance = dir
88 endProject, err := p.openProject(tip)
89 if err != nil {
90 done()
91 return p, func() {}, err
92 }
93 return p, func() { endProject(); done() }, nil
94}
95
96// openProject resolves the project's own layer in the checkout of the target
97// tip, and returns what ends it.
98//
99// A target that carries no layer of its own is judged under the floor
100// alone. The project layer only ever adds (dcr-f41f718), and the identity
101// of "adds" is "adds nothing", so that is what absence means. Refusing the
102// target instead would make a repository unlandable until its first policy
103// commit, which cannot land either: a change never supplies the policy that
104// gates it.
105//
106// Absence is answered with a document that adds nothing rather than with an
107// argument left off, because the deriver and the composer are each handed a
108// directory of *.cue and neither has a spelling for "no layer".
109func (p *policySource) openProject(tip *worktree) (func(), error) {
110 noop := func() {}
111 p.project = filepath.Join(tip.dir, p.projectDir)
112 if docs, err := filepath.Glob(filepath.Join(p.project, "*.cue")); err == nil && len(docs) > 0 {
113 return noop, nil
114 }
115 dir, done, err := composed.AddsNothing("valley-integrator-project")
116 if err != nil {
117 return noop, err
118 }
119 p.project = dir
120 p.note = fmt.Sprintf("no project layer at %s; the floor alone", p.projectDir)
121 return done, nil
122}
123
124// derived is one run of the deriver over a diff: how many changed paths it
125// read, which classes the diff matched, which checks that made required,
126// and the change's carry mode.
127type derived struct {
128 paths int
129 classes map[string]bool
130 requires map[string][]string // check name -> the classes requiring it
131 carry string // how far an approval carries across a rebase
132}
133
134// carryModes are the modes a report may state (schema/verification.cue's
135// #Carry). The integrator reads the mode and does not act on it: approval
136// carry is what reads it.
137var carryModes = map[string]bool{"same-paths": true, "same-class": true, "exact": true}
138
139// derive runs the deriver over a diff, in a checkout of the target tip. The
140// checkout supplies the project layer and the commits the diff names; the
141// instance layer comes from outside it.
142func (p policySource) derive(tip *worktree, from, to string) (derived, error) {
143 cmd := exec.Command(p.valley, "checks",
144 "--schema", p.schema,
145 "--instance", p.instance,
146 "--project", p.project,
147 from, to)
148 cmd.Dir = tip.dir
149 out, err := cmd.CombinedOutput()
150 if err != nil {
151 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w\n%s", verdict.Short(from), verdict.Short(to), err, strings.TrimSpace(string(out)))
152 }
153 d, err := parseDerived(string(out))
154 if err != nil {
155 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w", verdict.Short(from), verdict.Short(to), err)
156 }
157 // A diff the deriver failed to read reads as no changed paths, and no
158 // changed paths require nothing. So a report of none is believed only when
159 // git agrees that the two trees are the same.
160 if d.paths == 0 {
161 if _, err := git(tip.dir, "diff-tree", "--quiet", from, to); err != nil {
162 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)
163 }
164 }
165 return d, nil
166}
167
168// reportHeader is the first line of the deriver's report: the two commits,
169// and how many changed paths it read between them.
170var reportHeader = regexp.MustCompile(`^\S+\.\.\S+: ([0-9]+) changed path\(s\)$`)
171
172// parseDerived reads what `valley checks` printed. The deriver reports for
173// a person, so this is the one place the two programs are coupled by
174// output; the coupling is pinned by the integrator's own checks rather
175// than assumed.
176//
177// Output that is not a whole report is refused rather than read as one
178// that requires nothing: no header, no carry mode or one that is not a
179// mode, no required-checks section, a required-checks heading with no
180// checks under it, or classes that disagree with the number of changed
181// paths. The deriver never prints any of those, so each is a deriver that
182// failed partway and still exited zero.
183//
184// A report that says one thing twice is refused too: a second header,
185// classes line, carry mode or required-checks section, or a second row for
186// one check. The deriver prints each once, so a second is a forged line,
187// and reading the last one would let the forgery win.
188func parseDerived(out string) (derived, error) {
189 d := derived{classes: map[string]bool{}, requires: map[string][]string{}}
190 header, classes, required := false, false, false
191 lines := strings.Split(out, "\n")
192 for i := 0; i < len(lines); i++ {
193 line := lines[i]
194 switch {
195 case reportHeader.MatchString(line):
196 if header {
197 return derived{}, fmt.Errorf("the deriver printed a second header line, %q", line)
198 }
199 n, err := strconv.Atoi(reportHeader.FindStringSubmatch(line)[1])
200 if err != nil {
201 return derived{}, fmt.Errorf("the deriver printed %q, which is not a count of changed paths", line)
202 }
203 d.paths, header = n, true
204 case strings.HasPrefix(line, "classes matched:"):
205 if classes {
206 return derived{}, fmt.Errorf("the deriver printed a second classes line, %q", line)
207 }
208 classes = true
209 rest := strings.TrimSpace(strings.TrimPrefix(line, "classes matched:"))
210 if rest == "none" {
211 continue
212 }
213 for _, c := range strings.Split(rest, ",") {
214 if c = strings.TrimSpace(c); c != "" {
215 d.classes[c] = true
216 }
217 }
218 case strings.HasPrefix(line, "carry mode:"):
219 mode := strings.TrimSpace(strings.TrimPrefix(line, "carry mode:"))
220 if !carryModes[mode] {
221 return derived{}, fmt.Errorf("the deriver printed %q, which is not a carry mode", line)
222 }
223 if d.carry != "" {
224 return derived{}, fmt.Errorf("the deriver printed a second carry mode, %q", line)
225 }
226 d.carry = mode
227 case line == "required checks:":
228 if required {
229 return derived{}, fmt.Errorf("the deriver printed a second required-checks section")
230 }
231 required = true
232 rows := len(d.requires)
233 for i++; i < len(lines); i++ {
234 body := lines[i]
235 if !strings.HasPrefix(body, " ") || strings.TrimSpace(body) == "" {
236 i--
237 break
238 }
239 // " <name> <mandatory|default> <class>[, <class>…]"
240 fields := strings.Fields(body)
241 if len(fields) < 2 {
242 return derived{}, fmt.Errorf("the deriver printed %q, which is not a required-check line", body)
243 }
244 name := fields[0]
245 if _, twice := d.requires[name]; twice {
246 return derived{}, fmt.Errorf("the deriver printed a second row for check %s, %q", name, body)
247 }
248 var by []string
249 for _, c := range strings.Split(strings.Join(fields[2:], " "), ",") {
250 if c = strings.TrimSpace(c); c != "" {
251 by = append(by, c)
252 }
253 }
254 d.requires[name] = by
255 }
256 if len(d.requires) == rows {
257 return derived{}, fmt.Errorf("the deriver printed a required-checks heading with no checks under it")
258 }
259 case strings.HasPrefix(line, "required checks: none"):
260 // Nothing is required; the map stays empty.
261 if required {
262 return derived{}, fmt.Errorf("the deriver printed a second required-checks section")
263 }
264 required = true
265 }
266 }
267 switch {
268 case !header:
269 return derived{}, fmt.Errorf("the deriver printed no header line counting the changed paths, so this is not a report")
270 case d.carry == "":
271 return derived{}, fmt.Errorf("the deriver printed no carry mode, so this is not a report")
272 case !required:
273 return derived{}, fmt.Errorf("the deriver printed no required-checks section, so this is not a report")
274 case d.paths > 0 && len(d.classes) == 0:
275 // Every changed path matches a class, or else it is unclassified,
276 // which the deriver reports as a class of that name.
277 return derived{}, fmt.Errorf("the deriver read %d changed path(s) and matched no class", d.paths)
278 case d.paths == 0 && (len(d.classes) > 0 || len(d.requires) > 0):
279 return derived{}, fmt.Errorf("the deriver read no changed paths and still matched classes or required checks")
280 }
281 return d, nil
282}
283
284// catalogueEntry is one check as the composed policy defines it: how it is
285// run, and how long an observation of it stays good.
286type catalogueEntry = composed.Check
287
288// catalogue reads the composed policy's check definitions. The deriver
289// prints which checks are required and not what a check is, and the
290// integrator needs the latter: a pure check's attribute is what it
291// evaluates a closure over, and an effectful check's window is Δ.
292//
293// This is the same composition the deriver ran, over the same layers and
294// the same schema — `cue export` of a field the deriver does not print,
295// not a second opinion about what the policy says. The restacker reads its
296// cap through the same reader (composed.Compose).
297//
298// The digest it returns is of the whole export, so everything the policy
299// composes is in it: every check, every class's paths, requirements and
300// carry mode, and the restacker's cap.
301func (p policySource) catalogue() (map[string]catalogueEntry, string, error) {
302 pol, err := composed.Compose(context.Background(), p.cue, p.schema, p.instance, p.project)
303 if err != nil {
304 return nil, "", err
305 }
306 return pol.Checks, pol.Digest, nil
307}
308
309// required turns a derivation and a catalogue into the check set the
310// verdict is computed over.
311func (p policySource) required(d derived, cat map[string]catalogueEntry) ([]verdict.Required, error) {
312 var out []verdict.Required
313 for name, classes := range d.requires {
314 entry, ok := cat[name]
315 if !ok {
316 return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name)
317 }
318 window, err := parseWindow(entry.Validity)
319 if err != nil {
320 return nil, fmt.Errorf("check %s: %w", name, err)
321 }
322 out = append(out, verdict.Required{
323 Name: name,
324 Classes: classes,
325 Runner: entry.Runner,
326 Attribute: entry.Attribute,
327 Validity: window,
328 })
329 }
330 return out, nil
331}
332
333// parseWindow reads a #Duration from the policy. The schema admits whole
334// seconds, minutes, hours and days; an empty window is no window, which is
335// what makes the integrator re-demand the check.
336func parseWindow(s string) (time.Duration, error) {
337 if s == "" {
338 return 0, nil
339 }
340 unit := s[len(s)-1]
341 if unit == 'd' {
342 d, err := time.ParseDuration(s[:len(s)-1] + "h")
343 return d * 24, err
344 }
345 return time.ParseDuration(s)
346}