gunk-dev/the-valley

policy.go

source5820f67029d8main's published tip history
6.3 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 "encoding/json"
16 "fmt"
17 "os/exec"
18 "path/filepath"
19 "strings"
20 "time"
21)
22
23// policySource is where the two layers are read from, and the schema they
24// are composed under.
25type policySource struct {
26 schema string // the verification schema
27 instance string // the instance layer, resolved from the instance repository
28 project string // the project layer, relative to the target tip's tree
29 valley string // the deriver
30 cue string // the composer, for the catalogue the deriver does not print
31}
32
33// derived is one run of the deriver over a diff: which classes the diff
34// matched, and which checks that made required.
35type derived struct {
36 classes map[string]bool
37 requires map[string][]string // check name -> the classes requiring it
38 raw string
39}
40
41// derive runs the deriver over a diff, in a checkout of the target tip. The
42// checkout supplies the project layer and the commits the diff names; the
43// instance layer comes from outside it.
44func (p policySource) derive(tip *worktree, from, to string) (derived, error) {
45 cmd := exec.Command(p.valley, "checks",
46 "--schema", p.schema,
47 "--instance", p.instance,
48 "--project", filepath.Join(tip.dir, p.project),
49 from, to)
50 cmd.Dir = tip.dir
51 out, err := cmd.CombinedOutput()
52 if err != nil {
53 return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w\n%s", short(from), short(to), err, strings.TrimSpace(string(out)))
54 }
55 return parseDerived(string(out))
56}
57
58// parseDerived reads what `valley checks` printed. The deriver reports for
59// a person, so this is the one place the two programs are coupled by
60// output; the coupling is pinned by the integrator's own checks rather
61// than assumed.
62func parseDerived(out string) (derived, error) {
63 d := derived{classes: map[string]bool{}, requires: map[string][]string{}, raw: strings.TrimSpace(out)}
64 lines := strings.Split(out, "\n")
65 for i := 0; i < len(lines); i++ {
66 line := lines[i]
67 switch {
68 case strings.HasPrefix(line, "classes matched:"):
69 rest := strings.TrimSpace(strings.TrimPrefix(line, "classes matched:"))
70 if rest == "none" {
71 continue
72 }
73 for _, c := range strings.Split(rest, ",") {
74 if c = strings.TrimSpace(c); c != "" {
75 d.classes[c] = true
76 }
77 }
78 case line == "required checks:":
79 for i++; i < len(lines); i++ {
80 body := lines[i]
81 if !strings.HasPrefix(body, " ") || strings.TrimSpace(body) == "" {
82 i--
83 break
84 }
85 // " <name> <mandatory|default> <class>[, <class>…]"
86 fields := strings.Fields(body)
87 if len(fields) < 2 {
88 return derived{}, fmt.Errorf("the deriver printed %q, which is not a required-check line", body)
89 }
90 name := fields[0]
91 var classes []string
92 for _, c := range strings.Split(strings.Join(fields[2:], " "), ",") {
93 if c = strings.TrimSpace(c); c != "" {
94 classes = append(classes, c)
95 }
96 }
97 d.requires[name] = classes
98 }
99 case strings.HasPrefix(line, "required checks: none"):
100 // Nothing owed; the map stays empty.
101 }
102 }
103 return d, nil
104}
105
106// catalogueEntry is one check as the composed policy defines it: how it is
107// run, and how long an observation of it stays good.
108type catalogueEntry struct {
109 Runner string `json:"runner"`
110 Attribute string `json:"attribute"`
111 Command string `json:"command"`
112 Validity string `json:"validity"`
113}
114
115// catalogue reads the composed policy's check definitions. The deriver
116// prints which checks are required and not what a check is, and the
117// integrator needs the latter: a pure check's attribute is what it
118// evaluates a closure over, and an effectful check's window is Δ.
119//
120// This is the same composition the deriver ran, over the same layers and
121// the same schema — `cue export` of a field the deriver does not print,
122// not a second opinion about what the policy says.
123func (p policySource) catalogue(tip *worktree) (map[string]catalogueEntry, string, error) {
124 args := []string{"export", "--out", "json", "-e", "policy", p.schema}
125 for _, dir := range []string{p.instance, filepath.Join(tip.dir, p.project)} {
126 docs, err := filepath.Glob(filepath.Join(dir, "*.cue"))
127 if err != nil || len(docs) == 0 {
128 return nil, "", fmt.Errorf("no policy layer at %s", dir)
129 }
130 args = append(args, docs...)
131 }
132 cmd := exec.Command(p.cue, args...)
133 out, err := cmd.CombinedOutput()
134 if err != nil {
135 return nil, "", fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out)))
136 }
137 var composed struct {
138 Checks map[string]catalogueEntry `json:"checks"`
139 }
140 if err := json.Unmarshal(out, &composed); err != nil {
141 return nil, "", fmt.Errorf("reading the composed policy: %w", err)
142 }
143 return composed.Checks, sha256hex(out), nil
144}
145
146// required turns a derivation and a catalogue into the check set the
147// verdict is computed over.
148func (p policySource) required(d derived, cat map[string]catalogueEntry) ([]Required, error) {
149 var out []Required
150 for name, classes := range d.requires {
151 entry, ok := cat[name]
152 if !ok {
153 return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name)
154 }
155 window, err := parseWindow(entry.Validity)
156 if err != nil {
157 return nil, fmt.Errorf("check %s: %w", name, err)
158 }
159 out = append(out, Required{
160 Name: name,
161 Classes: classes,
162 Runner: entry.Runner,
163 Attribute: entry.Attribute,
164 Validity: window,
165 })
166 }
167 return out, nil
168}
169
170// parseWindow reads a #Duration from the policy. The schema admits whole
171// seconds, minutes, hours and days; an empty window is no window, which is
172// what makes the integrator re-demand the check.
173func parseWindow(s string) (time.Duration, error) {
174 if s == "" {
175 return 0, nil
176 }
177 unit := s[len(s)-1]
178 if unit == 'd' {
179 d, err := time.ParseDuration(s[:len(s)-1] + "h")
180 return d * 24, err
181 }
182 return time.ParseDuration(s)
183}