| 1 | package 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 | // |
| 14 | // Each layer is a directory of its own under `policy/`, which is the layout |
| 15 | // dcr-f41f718's worked example lays out and the layout the defaults name: |
| 16 | // the floor at `policy/instance` in the instance repository's tip, the |
| 17 | // project's own layer at `policy/project` in the target tip. A repository |
| 18 | // that keeps either somewhere else says so with --instance-policy or |
| 19 | // --project-policy. |
| 20 | // |
| 21 | // A layer that is not there defaults in the safe direction of that layer's |
| 22 | // job (dcr-f41f718), and the two directions are opposite: an absent project |
| 23 | // layer composes the floor alone, and an absent floor is refused. |
| 24 | |
| 25 | import ( |
| 26 | "the-valley/integrator/verdict" |
| 27 | |
| 28 | "encoding/json" |
| 29 | "fmt" |
| 30 | "os" |
| 31 | "os/exec" |
| 32 | "path/filepath" |
| 33 | "regexp" |
| 34 | "strconv" |
| 35 | "strings" |
| 36 | "time" |
| 37 | ) |
| 38 | |
| 39 | // instanceLayer is where the group's floor comes from. The floor is the |
| 40 | // instance repository's, read at the tip that has been integrated |
| 41 | // (dcr-f41f718), and the instance repository is the group's own |
| 42 | // (dcr-b87f6e8). A host that serves that repository is therefore already |
| 43 | // holding the authoritative copy, and reading it there is reading it where |
| 44 | // it is authoritative: no checkout to keep in step, no refresh to schedule, |
| 45 | // and no way for the floor a controller composes against to differ from the |
| 46 | // floor the group last landed. |
| 47 | // |
| 48 | // The consequence is worth stating, because it is a property and not a |
| 49 | // limitation. A change to the floor takes effect at the first pass after it |
| 50 | // lands on that ref, and never before — an edit sitting in a branch, a |
| 51 | // worktree, or a request that has not been integrated governs nothing. |
| 52 | // |
| 53 | // path is the fallback: a directory of `*.cue` on disk, for a host that |
| 54 | // serves no instance repository and must be given the layer some other way. |
| 55 | type instanceLayer struct { |
| 56 | repo string // the bare repository carrying the floor, read and never written |
| 57 | ref string // the ref whose tip is authoritative |
| 58 | dir string // the floor's directory in that tip's tree |
| 59 | path string // a materialized layer, when no repository carries one |
| 60 | } |
| 61 | |
| 62 | // floorless ends every refusal to find a floor. The floor is the minimum, |
| 63 | // and a missing minimum reads equally as a controller pointed at the wrong |
| 64 | // directory, a repository nobody seeded, or a floor somebody deleted. What |
| 65 | // is refused is the absent document; a floor that states it requires |
| 66 | // nothing composes and judges like any other. |
| 67 | const floorless = "a valley without a written floor is not a valley whose changes land" |
| 68 | |
| 69 | // open resolves the layer to a directory on disk for the length of one pass, |
| 70 | // and returns what ends it. |
| 71 | // |
| 72 | // The tip is taken apart with ls-tree and show rather than checked out. A |
| 73 | // worktree would write into the instance repository — git keeps worktree |
| 74 | // metadata under $GIT_DIR — and a controller has no business writing a |
| 75 | // repository it does not serve. Reading is all this needs, and reading is |
| 76 | // all it is granted. |
| 77 | func (l instanceLayer) open() (string, func(), error) { |
| 78 | noop := func() {} |
| 79 | if l.repo == "" { |
| 80 | // The materialized layer is held to the same minimum as the one a |
| 81 | // repository carries: a directory with no documents in it is a floor |
| 82 | // nobody wrote. |
| 83 | if docs, err := filepath.Glob(filepath.Join(l.path, "*.cue")); err != nil || len(docs) == 0 { |
| 84 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", l.path, floorless) |
| 85 | } |
| 86 | return l.path, noop, nil |
| 87 | } |
| 88 | tree := l.ref + ":" + l.dir |
| 89 | listing, err := git(l.repo, "ls-tree", "--name-only", tree) |
| 90 | if err != nil { |
| 91 | return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %s", l.repo, l.dir, l.ref, floorless) |
| 92 | } |
| 93 | dir, err := scratch("valley-integrator-floor") |
| 94 | if err != nil { |
| 95 | return "", noop, err |
| 96 | } |
| 97 | done := func() { _ = os.RemoveAll(dir) } |
| 98 | found := 0 |
| 99 | for _, name := range strings.Split(strings.TrimSpace(listing), "\n") { |
| 100 | // The deriver and the composer both read the layer as the `*.cue` |
| 101 | // documents directly in it, so those are what is taken. |
| 102 | if !strings.HasSuffix(name, ".cue") { |
| 103 | continue |
| 104 | } |
| 105 | body, err := git(l.repo, "show", tree+"/"+name) |
| 106 | if err != nil { |
| 107 | done() |
| 108 | return "", noop, fmt.Errorf("reading %s/%s from %s at %s: %w", l.dir, name, l.repo, l.ref, err) |
| 109 | } |
| 110 | if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { |
| 111 | done() |
| 112 | return "", noop, err |
| 113 | } |
| 114 | found++ |
| 115 | } |
| 116 | if found == 0 { |
| 117 | done() |
| 118 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %s", l.repo, l.dir, l.ref, floorless) |
| 119 | } |
| 120 | return dir, done, nil |
| 121 | } |
| 122 | |
| 123 | // policySource is where the two layers are read from, and the schema they |
| 124 | // are composed under. |
| 125 | type policySource struct { |
| 126 | schema string // the verification schema |
| 127 | layer instanceLayer |
| 128 | projectDir string // the project layer's directory in the target tip's tree |
| 129 | valley string // the deriver |
| 130 | cue string // the composer, for the catalogue the deriver does not print |
| 131 | |
| 132 | // Both layers as directories of *.cue on disk, resolved by open and |
| 133 | // good for one pass. |
| 134 | instance string |
| 135 | project string |
| 136 | |
| 137 | // note is the one thing a pass has to say about how the layers |
| 138 | // resolved, when that is not what the configuration reads as. Empty |
| 139 | // when both were where they are configured to be. |
| 140 | note string |
| 141 | } |
| 142 | |
| 143 | // open resolves both layers and returns a source that reads them from disk, |
| 144 | // together with what ends the pass. Held for the whole pass rather than |
| 145 | // resolved per call, so the deriver and the composer are given the same |
| 146 | // bytes: they are two readings of one policy, not two policies. |
| 147 | func (p policySource) open(tip *worktree) (policySource, func(), error) { |
| 148 | dir, done, err := p.layer.open() |
| 149 | if err != nil { |
| 150 | return p, done, err |
| 151 | } |
| 152 | p.instance = dir |
| 153 | endProject, err := p.openProject(tip) |
| 154 | if err != nil { |
| 155 | done() |
| 156 | return p, func() {}, err |
| 157 | } |
| 158 | return p, func() { endProject(); done() }, nil |
| 159 | } |
| 160 | |
| 161 | // openProject resolves the project's own layer in the checkout of the target |
| 162 | // tip, and returns what ends it. |
| 163 | // |
| 164 | // A target that carries no layer of its own is judged under the floor |
| 165 | // alone. The project layer only ever adds (dcr-f41f718), and the identity |
| 166 | // of "adds" is "adds nothing", so that is what absence means. Refusing the |
| 167 | // target instead would make a repository unlandable until its first policy |
| 168 | // commit, which cannot land either: a change never supplies the policy that |
| 169 | // gates it. |
| 170 | // |
| 171 | // Absence is answered with a document that adds nothing rather than with an |
| 172 | // argument left off, because the deriver and the composer are each handed a |
| 173 | // directory of *.cue and neither has a spelling for "no layer". |
| 174 | func (p *policySource) openProject(tip *worktree) (func(), error) { |
| 175 | noop := func() {} |
| 176 | p.project = filepath.Join(tip.dir, p.projectDir) |
| 177 | if docs, err := filepath.Glob(filepath.Join(p.project, "*.cue")); err == nil && len(docs) > 0 { |
| 178 | return noop, nil |
| 179 | } |
| 180 | dir, err := scratch("valley-integrator-project") |
| 181 | if err != nil { |
| 182 | return noop, err |
| 183 | } |
| 184 | // A package clause and nothing else: `project` stays what the schema |
| 185 | // leaves it, which is three empty sets. |
| 186 | if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil { |
| 187 | _ = os.RemoveAll(dir) |
| 188 | return noop, err |
| 189 | } |
| 190 | p.project = dir |
| 191 | p.note = fmt.Sprintf("no project layer at %s; the floor alone", p.projectDir) |
| 192 | return func() { _ = os.RemoveAll(dir) }, nil |
| 193 | } |
| 194 | |
| 195 | // derived is one run of the deriver over a diff: how many changed paths it |
| 196 | // read, which classes the diff matched, and which checks that made |
| 197 | // required. |
| 198 | type derived struct { |
| 199 | paths int |
| 200 | classes map[string]bool |
| 201 | requires map[string][]string // check name -> the classes requiring it |
| 202 | } |
| 203 | |
| 204 | // derive runs the deriver over a diff, in a checkout of the target tip. The |
| 205 | // checkout supplies the project layer and the commits the diff names; the |
| 206 | // instance layer comes from outside it. |
| 207 | func (p policySource) derive(tip *worktree, from, to string) (derived, error) { |
| 208 | cmd := exec.Command(p.valley, "checks", |
| 209 | "--schema", p.schema, |
| 210 | "--instance", p.instance, |
| 211 | "--project", p.project, |
| 212 | from, to) |
| 213 | cmd.Dir = tip.dir |
| 214 | out, err := cmd.CombinedOutput() |
| 215 | if err != nil { |
| 216 | return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w\n%s", verdict.Short(from), verdict.Short(to), err, strings.TrimSpace(string(out))) |
| 217 | } |
| 218 | d, err := parseDerived(string(out)) |
| 219 | if err != nil { |
| 220 | return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w", verdict.Short(from), verdict.Short(to), err) |
| 221 | } |
| 222 | // A diff the deriver failed to read reads as no changed paths, and no |
| 223 | // changed paths require nothing. So a report of none is believed only when |
| 224 | // git agrees that the two trees are the same. |
| 225 | if d.paths == 0 { |
| 226 | if _, err := git(tip.dir, "diff-tree", "--quiet", from, to); err != nil { |
| 227 | return derived{}, fmt.Errorf("the deriver read no changed paths in %s..%s, and git does not agree: %w", verdict.Short(from), verdict.Short(to), err) |
| 228 | } |
| 229 | } |
| 230 | return d, nil |
| 231 | } |
| 232 | |
| 233 | // reportHeader is the first line of the deriver's report: the two commits, |
| 234 | // and how many changed paths it read between them. |
| 235 | var reportHeader = regexp.MustCompile(`^\S+\.\.\S+: ([0-9]+) changed path\(s\)$`) |
| 236 | |
| 237 | // parseDerived reads what `valley checks` printed. The deriver reports for |
| 238 | // a person, so this is the one place the two programs are coupled by |
| 239 | // output; the coupling is pinned by the integrator's own checks rather |
| 240 | // than assumed. |
| 241 | // |
| 242 | // Output that is not a whole report is refused rather than read as one |
| 243 | // that requires nothing: no header, no required-checks section, a required-checks |
| 244 | // heading with no checks under it, or classes that disagree with the |
| 245 | // number of changed paths. The deriver never prints any of those, so each |
| 246 | // is a deriver that failed partway and still exited zero. |
| 247 | func parseDerived(out string) (derived, error) { |
| 248 | d := derived{classes: map[string]bool{}, requires: map[string][]string{}} |
| 249 | header, required := false, false |
| 250 | lines := strings.Split(out, "\n") |
| 251 | for i := 0; i < len(lines); i++ { |
| 252 | line := lines[i] |
| 253 | switch { |
| 254 | case reportHeader.MatchString(line): |
| 255 | n, err := strconv.Atoi(reportHeader.FindStringSubmatch(line)[1]) |
| 256 | if err != nil { |
| 257 | return derived{}, fmt.Errorf("the deriver printed %q, which is not a count of changed paths", line) |
| 258 | } |
| 259 | d.paths, header = n, true |
| 260 | case strings.HasPrefix(line, "classes matched:"): |
| 261 | rest := strings.TrimSpace(strings.TrimPrefix(line, "classes matched:")) |
| 262 | if rest == "none" { |
| 263 | continue |
| 264 | } |
| 265 | for _, c := range strings.Split(rest, ",") { |
| 266 | if c = strings.TrimSpace(c); c != "" { |
| 267 | d.classes[c] = true |
| 268 | } |
| 269 | } |
| 270 | case line == "required checks:": |
| 271 | required = true |
| 272 | rows := len(d.requires) |
| 273 | for i++; i < len(lines); i++ { |
| 274 | body := lines[i] |
| 275 | if !strings.HasPrefix(body, " ") || strings.TrimSpace(body) == "" { |
| 276 | i-- |
| 277 | break |
| 278 | } |
| 279 | // " <name> <mandatory|default> <class>[, <class>…]" |
| 280 | fields := strings.Fields(body) |
| 281 | if len(fields) < 2 { |
| 282 | return derived{}, fmt.Errorf("the deriver printed %q, which is not a required-check line", body) |
| 283 | } |
| 284 | name := fields[0] |
| 285 | var classes []string |
| 286 | for _, c := range strings.Split(strings.Join(fields[2:], " "), ",") { |
| 287 | if c = strings.TrimSpace(c); c != "" { |
| 288 | classes = append(classes, c) |
| 289 | } |
| 290 | } |
| 291 | d.requires[name] = classes |
| 292 | } |
| 293 | if len(d.requires) == rows { |
| 294 | return derived{}, fmt.Errorf("the deriver printed a required-checks heading with no checks under it") |
| 295 | } |
| 296 | case strings.HasPrefix(line, "required checks: none"): |
| 297 | // Nothing is required; the map stays empty. |
| 298 | required = true |
| 299 | } |
| 300 | } |
| 301 | switch { |
| 302 | case !header: |
| 303 | return derived{}, fmt.Errorf("the deriver printed no header line counting the changed paths, so this is not a report") |
| 304 | case !required: |
| 305 | return derived{}, fmt.Errorf("the deriver printed no required-checks section, so this is not a report") |
| 306 | case d.paths > 0 && len(d.classes) == 0: |
| 307 | // Every changed path matches a class, or else it is unclassified, |
| 308 | // which the deriver reports as a class of that name. |
| 309 | return derived{}, fmt.Errorf("the deriver read %d changed path(s) and matched no class", d.paths) |
| 310 | case d.paths == 0 && (len(d.classes) > 0 || len(d.requires) > 0): |
| 311 | return derived{}, fmt.Errorf("the deriver read no changed paths and still matched classes or required checks") |
| 312 | } |
| 313 | return d, nil |
| 314 | } |
| 315 | |
| 316 | // catalogueEntry is one check as the composed policy defines it: how it is |
| 317 | // run, and how long an observation of it stays good. |
| 318 | type catalogueEntry struct { |
| 319 | Runner string `json:"runner"` |
| 320 | Attribute string `json:"attribute"` |
| 321 | Command string `json:"command"` |
| 322 | Validity string `json:"validity"` |
| 323 | } |
| 324 | |
| 325 | // catalogue reads the composed policy's check definitions. The deriver |
| 326 | // prints which checks are required and not what a check is, and the |
| 327 | // integrator needs the latter: a pure check's attribute is what it |
| 328 | // evaluates a closure over, and an effectful check's window is Δ. |
| 329 | // |
| 330 | // This is the same composition the deriver ran, over the same layers and |
| 331 | // the same schema — `cue export` of a field the deriver does not print, |
| 332 | // not a second opinion about what the policy says. |
| 333 | func (p policySource) catalogue() (map[string]catalogueEntry, string, error) { |
| 334 | args := []string{"export", "--out", "json", "-e", "policy", p.schema} |
| 335 | for _, dir := range []string{p.instance, p.project} { |
| 336 | docs, err := filepath.Glob(filepath.Join(dir, "*.cue")) |
| 337 | if err != nil || len(docs) == 0 { |
| 338 | return nil, "", fmt.Errorf("no policy layer at %s", dir) |
| 339 | } |
| 340 | args = append(args, docs...) |
| 341 | } |
| 342 | cmd := exec.Command(p.cue, args...) |
| 343 | out, err := cmd.CombinedOutput() |
| 344 | if err != nil { |
| 345 | return nil, "", fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out))) |
| 346 | } |
| 347 | var composed struct { |
| 348 | Checks map[string]catalogueEntry `json:"checks"` |
| 349 | } |
| 350 | if err := json.Unmarshal(out, &composed); err != nil { |
| 351 | return nil, "", fmt.Errorf("reading the composed policy: %w", err) |
| 352 | } |
| 353 | return composed.Checks, sha256hex(out), nil |
| 354 | } |
| 355 | |
| 356 | // required turns a derivation and a catalogue into the check set the |
| 357 | // verdict is computed over. |
| 358 | func (p policySource) required(d derived, cat map[string]catalogueEntry) ([]verdict.Required, error) { |
| 359 | var out []verdict.Required |
| 360 | for name, classes := range d.requires { |
| 361 | entry, ok := cat[name] |
| 362 | if !ok { |
| 363 | return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name) |
| 364 | } |
| 365 | window, err := parseWindow(entry.Validity) |
| 366 | if err != nil { |
| 367 | return nil, fmt.Errorf("check %s: %w", name, err) |
| 368 | } |
| 369 | out = append(out, verdict.Required{ |
| 370 | Name: name, |
| 371 | Classes: classes, |
| 372 | Runner: entry.Runner, |
| 373 | Attribute: entry.Attribute, |
| 374 | Validity: window, |
| 375 | }) |
| 376 | } |
| 377 | return out, nil |
| 378 | } |
| 379 | |
| 380 | // parseWindow reads a #Duration from the policy. The schema admits whole |
| 381 | // seconds, minutes, hours and days; an empty window is no window, which is |
| 382 | // what makes the integrator re-demand the check. |
| 383 | func parseWindow(s string) (time.Duration, error) { |
| 384 | if s == "" { |
| 385 | return 0, nil |
| 386 | } |
| 387 | unit := s[len(s)-1] |
| 388 | if unit == 'd' { |
| 389 | d, err := time.ParseDuration(s[:len(s)-1] + "h") |
| 390 | return d * 24, err |
| 391 | } |
| 392 | return time.ParseDuration(s) |
| 393 | } |