gunk-dev/the-valley

model.go

sourceb1cafbe3a404main's published tip history
8.8 KiB
1package composed
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "runtime"
13 "sort"
14 "strings"
15 "sync"
16)
17
18// Pin says whether a requirement is mandatory or a default. The form of
19// the composed value is the bit. A concrete `true`, which the floor writes,
20// cannot be turned off: a project writing `false` conflicts. `bool |
21// *true`, which a template writes, is a default a project may turn off.
22type Pin string
23
24const (
25 Mandatory Pin = "mandatory"
26 Default Pin = "default"
27)
28
29// Class is one path class of the composed policy.
30type Class struct {
31 // Paths are the globs the class covers: each pattern whose value is
32 // true, sorted. A pattern a project turned off covers nothing.
33 Paths []string
34
35 // Requires are the checks the class requires: each check whose value
36 // is true, with whether that requirement is mandatory.
37 Requires map[string]Pin
38
39 // Carry is the class's carry mode as the schema resolves it (_mode):
40 // exact, same-class or same-paths.
41 Carry string
42}
43
44// Model is the whole composed policy, as the deriver reads it: the policy
45// Compose reads, every class, and what a path no class covers requires.
46type Model struct {
47 Policy
48
49 // Documents are the files the policy was composed from, in the order
50 // cue was given them: the schema, then the floor's documents and the
51 // project layer's.
52 Documents []string
53
54 Classes map[string]Class
55
56 // Unclassified are the checks a path no class covers requires: each
57 // check of the policy's `unclassified` set whose value is true, with
58 // whether that requirement is mandatory.
59 Unclassified map[string]Pin
60}
61
62// The values the schema gives a check's runner and cost, and a class's
63// carry mode. A schema older than this reader lacks one of them, and is
64// refused rather than read as the loosest value.
65var (
66 runners = map[string]bool{"nix": true, "command": true}
67 costs = map[string]bool{"quick": true, "slow": true}
68 modes = map[string]bool{"exact": true, "same-class": true, "same-paths": true}
69)
70
71// Read composes the policy as Compose does and reads all of it: each
72// class's paths, requirements and carry mode, what the `unclassified` set
73// requires, and whether each requirement is mandatory. The digest is the
74// one Compose gives, of the same export.
75//
76// It reads as `valley checks` does. The layers are vetted concretely
77// first, so a composition with an error outside `policy` is refused too. A
78// class's carry mode is the schema's own resolution (_mode). Whether a
79// requirement is mandatory is asked of cue, one requirement at a time: a
80// document setting it to `false` is vetted with the layers, and a
81// requirement that then fails to vet is mandatory. That is the test a
82// project writing `false` would meet. A probe that fails for any reason
83// reads as mandatory, the strict answer, and the bit never changes which
84// checks are required.
85//
86// Read refuses a policy that requires a check it does not define. The
87// schema's cross-check refuses one in a layer, but not in a class added by
88// refining `policy` directly, and a required check that nobody can run is
89// the one failure a policy must never have.
90func Read(ctx context.Context, cue, schema, instance, project string) (*Model, error) {
91 if info, err := os.Stat(schema); err != nil || !info.Mode().IsRegular() {
92 return nil, fmt.Errorf("no policy schema at %s", schema)
93 }
94 docs, err := documents(schema, instance, project)
95 if err != nil {
96 return nil, err
97 }
98 vet := command(ctx, cue, append([]string{"vet", "-c"}, docs...)...)
99 if out, err := vet.CombinedOutput(); err != nil {
100 return nil, fmt.Errorf("the policy layers do not compose: %w\n%s", err, strings.TrimSpace(string(out)))
101 }
102 pol, out, err := compose(ctx, cue, docs)
103 if err != nil {
104 return nil, err
105 }
106 var read struct {
107 Classes map[string]struct {
108 Paths map[string]bool `json:"paths"`
109 Requires map[string]bool `json:"requires"`
110 } `json:"classes"`
111 Unclassified map[string]bool `json:"unclassified"`
112 }
113 if err := json.Unmarshal(out, &read); err != nil {
114 return nil, fmt.Errorf("reading the composed policy: %w", err)
115 }
116 modeOut, err := export(ctx, cue, docs, "_mode")
117 if err != nil {
118 return nil, fmt.Errorf("reading the classes' carry modes: %w", err)
119 }
120 var resolved map[string]string
121 if err := json.Unmarshal(modeOut, &resolved); err != nil {
122 return nil, fmt.Errorf("reading the classes' carry modes: %w", err)
123 }
124
125 for name, c := range pol.Checks {
126 if !runners[c.Runner] {
127 return nil, fmt.Errorf("check %s has no runner this deriver knows (%q)", name, c.Runner)
128 }
129 if !costs[c.Cost] {
130 return nil, fmt.Errorf("check %s has no cost this deriver knows (%q)", name, c.Cost)
131 }
132 }
133 m := &Model{Policy: *pol, Documents: docs, Classes: map[string]Class{}, Unclassified: map[string]Pin{}}
134 var probes []probe
135 for name, c := range read.Classes {
136 mode := resolved[name]
137 if !modes[mode] {
138 return nil, fmt.Errorf("class %s has no carry mode this deriver knows (%q)", name, mode)
139 }
140 class := Class{Paths: trueKeys(c.Paths), Requires: map[string]Pin{}, Carry: mode}
141 for _, check := range trueKeys(c.Requires) {
142 if _, ok := pol.Checks[check]; !ok {
143 return nil, fmt.Errorf("class %s requires check %s, which the composed policy does not define", name, check)
144 }
145 probes = append(probes, probe{class: name, check: check})
146 }
147 m.Classes[name] = class
148 }
149 for name := range resolved {
150 if _, ok := read.Classes[name]; !ok {
151 return nil, fmt.Errorf("the schema resolved a carry mode for class %s, which the composed policy does not have", name)
152 }
153 }
154 for _, check := range trueKeys(read.Unclassified) {
155 if _, ok := pol.Checks[check]; !ok {
156 return nil, fmt.Errorf("the unclassified set requires check %s, which the composed policy does not define", check)
157 }
158 probes = append(probes, probe{unclassified: true, check: check})
159 }
160
161 pins, err := pinAll(ctx, cue, docs, probes)
162 if err != nil {
163 return nil, err
164 }
165 for i, p := range probes {
166 if p.unclassified {
167 m.Unclassified[p.check] = pins[i]
168 } else {
169 m.Classes[p.class].Requires[p.check] = pins[i]
170 }
171 }
172 return m, nil
173}
174
175// trueKeys are the keys of a set written as a struct whose value is true,
176// sorted.
177func trueKeys(set map[string]bool) []string {
178 var out []string
179 for k, on := range set {
180 if on {
181 out = append(out, k)
182 }
183 }
184 sort.Strings(out)
185 return out
186}
187
188// probe is one requirement whose pin is asked of cue: a check a class
189// requires, or one the unclassified set requires.
190type probe struct {
191 class string
192 unclassified bool
193 check string
194}
195
196// document is the probe's one field: the requirement set to false.
197func (p probe) document() (string, error) {
198 check, err := json.Marshal(p.check)
199 if err != nil {
200 return "", err
201 }
202 if p.unclassified {
203 return fmt.Sprintf("package verification\npolicy: unclassified: %s: false\n", check), nil
204 }
205 class, err := json.Marshal(p.class)
206 if err != nil {
207 return "", err
208 }
209 return fmt.Sprintf("package verification\npolicy: classes: %s: requires: %s: false\n", class, check), nil
210}
211
212// pinAll asks cue the pin of every probe, several at a time, and returns
213// them in the probes' order. Each probe is its own document, vetted with
214// the layers alone, so one probe never answers for another.
215func pinAll(ctx context.Context, cue string, docs []string, probes []probe) ([]Pin, error) {
216 if len(probes) == 0 {
217 return nil, nil
218 }
219 dir, err := scratch("valley-probe-")
220 if err != nil {
221 return nil, err
222 }
223 defer os.RemoveAll(dir)
224
225 pins := make([]Pin, len(probes))
226 errs := make([]error, len(probes))
227 slots := make(chan struct{}, runtime.NumCPU())
228 var wg sync.WaitGroup
229 for i, p := range probes {
230 wg.Add(1)
231 go func() {
232 defer wg.Done()
233 slots <- struct{}{}
234 defer func() { <-slots }()
235 pins[i], errs[i] = pin(ctx, cue, docs, filepath.Join(dir, fmt.Sprintf("probe-%d.cue", i)), p)
236 }()
237 }
238 wg.Wait()
239 if err := errors.Join(errs...); err != nil {
240 return nil, err
241 }
242 return pins, nil
243}
244
245// pin vets the layers with one probe written at path. A vet that fails, for
246// whatever reason, is a requirement no project can turn off. A cue that
247// cannot be run at all, or a context that is done, answers nothing.
248func pin(ctx context.Context, cue string, docs []string, path string, p probe) (Pin, error) {
249 doc, err := p.document()
250 if err != nil {
251 return "", err
252 }
253 if err := os.WriteFile(path, []byte(doc), 0o644); err != nil {
254 return "", fmt.Errorf("writing a probe of whether %s is mandatory: %w", p.check, err)
255 }
256 cmd := command(ctx, cue, append(append([]string{"vet"}, docs...), path)...)
257 var discard bytes.Buffer
258 cmd.Stdout, cmd.Stderr = &discard, &discard
259 err = cmd.Run()
260 if ctx.Err() != nil {
261 return "", fmt.Errorf("probing whether %s is mandatory: %w", p.check, ctx.Err())
262 }
263 var exit *exec.ExitError
264 switch {
265 case err == nil:
266 return Default, nil
267 case errors.As(err, &exit):
268 return Mandatory, nil
269 default:
270 return "", fmt.Errorf("probing whether %s is mandatory: %w", p.check, err)
271 }
272}