gunk-dev/the-valley

model.go

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