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