gunk-dev/the-valley

policy.go

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