gunk-dev/the-valley

policy.go

source9ee0a5aa589dmain's published tip history
9.7 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
14import (
15 "the-valley/integrator/verdict"
16
17 "encoding/json"
18 "fmt"
19 "os"
20 "os/exec"
21 "path/filepath"
22 "strings"
23 "time"
24)
25
26// instanceLayer is where the group's floor comes from. The floor is the
27// instance repository's, read at the tip that has been integrated
28// (dcr-f41f718), and the instance repository is the group's own
29// (dcr-b87f6e8). A host that serves that repository is therefore already
30// holding the authoritative copy, and reading it there is reading it where
31// it is authoritative: no checkout to keep in step, no refresh to schedule,
32// and no way for the floor a controller composes against to differ from the
33// floor the group last landed.
34//
35// The consequence is worth stating, because it is a property and not a
36// limitation. A change to the floor takes effect at the first pass after it
37// lands on that ref, and never before — an edit sitting in a branch, a
38// worktree, or a request that has not been integrated governs nothing.
39//
40// path is the fallback: a directory of `*.cue` on disk, for a host that
41// serves no instance repository and must be given the layer some other way.
42type instanceLayer struct {
43 repo string // the bare repository carrying the floor, read and never written
44 ref string // the ref whose tip is authoritative
45 dir string // the floor's directory in that tip's tree
46 path string // a materialized layer, when no repository carries one
47}
48
49// open resolves the layer to a directory on disk for the length of one pass,
50// and returns what ends it.
51//
52// The tip is taken apart with ls-tree and show rather than checked out. A
53// worktree would write into the instance repository — git keeps worktree
54// metadata under $GIT_DIR — and a controller has no business writing a
55// repository it does not serve. Reading is all this needs, and reading is
56// all it is granted.
57func (l instanceLayer) open() (string, func(), error) {
58 noop := func() {}
59 if l.repo == "" {
60 return l.path, noop, nil
61 }
62 tree := l.ref + ":" + l.dir
63 listing, err := git(l.repo, "ls-tree", "--name-only", tree)
64 if err != nil {
65 return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %w", l.repo, l.dir, l.ref, err)
66 }
67 dir, err := scratch("valley-integrator-floor")
68 if err != nil {
69 return "", noop, err
70 }
71 done := func() { _ = os.RemoveAll(dir) }
72 found := 0
73 for _, name := range strings.Split(strings.TrimSpace(listing), "\n") {
74 // The deriver and the composer both read the layer as the `*.cue`
75 // documents directly in it, so those are what is taken.
76 if !strings.HasSuffix(name, ".cue") {
77 continue
78 }
79 body, err := git(l.repo, "show", tree+"/"+name)
80 if err != nil {
81 done()
82 return "", noop, fmt.Errorf("reading %s/%s from %s at %s: %w", l.dir, name, l.repo, l.ref, err)
83 }
84 if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
85 done()
86 return "", noop, err
87 }
88 found++
89 }
90 if found == 0 {
91 done()
92 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s", l.repo, l.dir, l.ref)
93 }
94 return dir, done, nil
95}
96
97// policySource is where the two layers are read from, and the schema they
98// are composed under.
99type policySource struct {
100 schema string // the verification schema
101 layer instanceLayer
102 instance string // the instance layer as resolved on disk, for one pass
103 project string // the project layer, relative to the target tip's tree
104 valley string // the deriver
105 cue string // the composer, for the catalogue the deriver does not print
106}
107
108// open resolves the instance layer and returns a source that reads it from
109// disk, together with what ends the pass. Held for the whole pass rather
110// than resolved per call, so the deriver and the composer are given the same
111// bytes: they are two readings of one policy, not two policies.
112func (p policySource) open() (policySource, func(), error) {
113 dir, done, err := p.layer.open()
114 if err != nil {
115 return p, done, err
116 }
117 p.instance = dir
118 return p, done, nil
119}
120
121// derived is one run of the deriver over a diff: which classes the diff
122// matched, and which checks that made required.
123type derived struct {
124 classes map[string]bool
125 requires map[string][]string // check name -> the classes requiring it
126}
127
128// derive runs the deriver over a diff, in a checkout of the target tip. The
129// checkout supplies the project layer and the commits the diff names; the
130// instance layer comes from outside it.
131func (p policySource) derive(tip *worktree, from, to string) (derived, error) {
132 cmd := exec.Command(p.valley, "checks",
133 "--schema", p.schema,
134 "--instance", p.instance,
135 "--project", filepath.Join(tip.dir, p.project),
136 from, to)
137 cmd.Dir = tip.dir
138 out, err := cmd.CombinedOutput()
139 if err != nil {
140 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w\n%s", verdict.Short(from), verdict.Short(to), err, strings.TrimSpace(string(out)))
141 }
142 return parseDerived(string(out))
143}
144
145// parseDerived reads what `valley checks` printed. The deriver reports for
146// a person, so this is the one place the two programs are coupled by
147// output; the coupling is pinned by the integrator's own checks rather
148// than assumed.
149func parseDerived(out string) (derived, error) {
150 d := derived{classes: map[string]bool{}, requires: map[string][]string{}}
151 lines := strings.Split(out, "\n")
152 for i := 0; i < len(lines); i++ {
153 line := lines[i]
154 switch {
155 case strings.HasPrefix(line, "classes matched:"):
156 rest := strings.TrimSpace(strings.TrimPrefix(line, "classes matched:"))
157 if rest == "none" {
158 continue
159 }
160 for _, c := range strings.Split(rest, ",") {
161 if c = strings.TrimSpace(c); c != "" {
162 d.classes[c] = true
163 }
164 }
165 case line == "required checks:":
166 for i++; i < len(lines); i++ {
167 body := lines[i]
168 if !strings.HasPrefix(body, " ") || strings.TrimSpace(body) == "" {
169 i--
170 break
171 }
172 // " <name> <mandatory|default> <class>[, <class>…]"
173 fields := strings.Fields(body)
174 if len(fields) < 2 {
175 return derived{}, fmt.Errorf("the deriver printed %q, which is not a required-check line", body)
176 }
177 name := fields[0]
178 var classes []string
179 for _, c := range strings.Split(strings.Join(fields[2:], " "), ",") {
180 if c = strings.TrimSpace(c); c != "" {
181 classes = append(classes, c)
182 }
183 }
184 d.requires[name] = classes
185 }
186 case strings.HasPrefix(line, "required checks: none"):
187 // Nothing owed; the map stays empty.
188 }
189 }
190 return d, nil
191}
192
193// catalogueEntry is one check as the composed policy defines it: how it is
194// run, and how long an observation of it stays good.
195type catalogueEntry struct {
196 Runner string `json:"runner"`
197 Attribute string `json:"attribute"`
198 Command string `json:"command"`
199 Validity string `json:"validity"`
200}
201
202// catalogue reads the composed policy's check definitions. The deriver
203// prints which checks are required and not what a check is, and the
204// integrator needs the latter: a pure check's attribute is what it
205// evaluates a closure over, and an effectful check's window is Δ.
206//
207// This is the same composition the deriver ran, over the same layers and
208// the same schema — `cue export` of a field the deriver does not print,
209// not a second opinion about what the policy says.
210func (p policySource) catalogue(tip *worktree) (map[string]catalogueEntry, string, error) {
211 args := []string{"export", "--out", "json", "-e", "policy", p.schema}
212 for _, dir := range []string{p.instance, filepath.Join(tip.dir, p.project)} {
213 docs, err := filepath.Glob(filepath.Join(dir, "*.cue"))
214 if err != nil || len(docs) == 0 {
215 return nil, "", fmt.Errorf("no policy layer at %s", dir)
216 }
217 args = append(args, docs...)
218 }
219 cmd := exec.Command(p.cue, args...)
220 out, err := cmd.CombinedOutput()
221 if err != nil {
222 return nil, "", fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out)))
223 }
224 var composed struct {
225 Checks map[string]catalogueEntry `json:"checks"`
226 }
227 if err := json.Unmarshal(out, &composed); err != nil {
228 return nil, "", fmt.Errorf("reading the composed policy: %w", err)
229 }
230 return composed.Checks, sha256hex(out), nil
231}
232
233// required turns a derivation and a catalogue into the check set the
234// verdict is computed over.
235func (p policySource) required(d derived, cat map[string]catalogueEntry) ([]verdict.Required, error) {
236 var out []verdict.Required
237 for name, classes := range d.requires {
238 entry, ok := cat[name]
239 if !ok {
240 return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name)
241 }
242 window, err := parseWindow(entry.Validity)
243 if err != nil {
244 return nil, fmt.Errorf("check %s: %w", name, err)
245 }
246 out = append(out, verdict.Required{
247 Name: name,
248 Classes: classes,
249 Runner: entry.Runner,
250 Attribute: entry.Attribute,
251 Validity: window,
252 })
253 }
254 return out, nil
255}
256
257// parseWindow reads a #Duration from the policy. The schema admits whole
258// seconds, minutes, hours and days; an empty window is no window, which is
259// what makes the integrator re-demand the check.
260func parseWindow(s string) (time.Duration, error) {
261 if s == "" {
262 return 0, nil
263 }
264 unit := s[len(s)-1]
265 if unit == 'd' {
266 d, err := time.ParseDuration(s[:len(s)-1] + "h")
267 return d * 24, err
268 }
269 return time.ParseDuration(s)
270}