gunk-dev/the-valley

policy.go

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