gunk-dev/the-valley

policy.go

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