gunk-dev/the-valley

model.go

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