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