| 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 | import ( |
| 22 | "the-valley/integrator/verdict" |
| 23 | |
| 24 | "encoding/json" |
| 25 | "fmt" |
| 26 | "os" |
| 27 | "os/exec" |
| 28 | "path/filepath" |
| 29 | "strings" |
| 30 | "time" |
| 31 | ) |
| 32 | |
| 33 | // instanceLayer is where the group's floor comes from. The floor is the |
| 34 | // instance repository's, read at the tip that has been integrated |
| 35 | // (dcr-f41f718), and the instance repository is the group's own |
| 36 | // (dcr-b87f6e8). A host that serves that repository is therefore already |
| 37 | // holding the authoritative copy, and reading it there is reading it where |
| 38 | // it is authoritative: no checkout to keep in step, no refresh to schedule, |
| 39 | // and no way for the floor a controller composes against to differ from the |
| 40 | // floor the group last landed. |
| 41 | // |
| 42 | // The consequence is worth stating, because it is a property and not a |
| 43 | // limitation. A change to the floor takes effect at the first pass after it |
| 44 | // lands on that ref, and never before — an edit sitting in a branch, a |
| 45 | // worktree, or a request that has not been integrated governs nothing. |
| 46 | // |
| 47 | // path is the fallback: a directory of `*.cue` on disk, for a host that |
| 48 | // serves no instance repository and must be given the layer some other way. |
| 49 | type instanceLayer struct { |
| 50 | repo string // the bare repository carrying the floor, read and never written |
| 51 | ref string // the ref whose tip is authoritative |
| 52 | dir string // the floor's directory in that tip's tree |
| 53 | path string // a materialized layer, when no repository carries one |
| 54 | } |
| 55 | |
| 56 | // open resolves the layer to a directory on disk for the length of one pass, |
| 57 | // and returns what ends it. |
| 58 | // |
| 59 | // The tip is taken apart with ls-tree and show rather than checked out. A |
| 60 | // worktree would write into the instance repository — git keeps worktree |
| 61 | // metadata under $GIT_DIR — and a controller has no business writing a |
| 62 | // repository it does not serve. Reading is all this needs, and reading is |
| 63 | // all it is granted. |
| 64 | func (l instanceLayer) open() (string, func(), error) { |
| 65 | noop := func() {} |
| 66 | if l.repo == "" { |
| 67 | return l.path, noop, nil |
| 68 | } |
| 69 | tree := l.ref + ":" + l.dir |
| 70 | listing, err := git(l.repo, "ls-tree", "--name-only", tree) |
| 71 | if err != nil { |
| 72 | return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %w", l.repo, l.dir, l.ref, err) |
| 73 | } |
| 74 | dir, err := scratch("valley-integrator-floor") |
| 75 | if err != nil { |
| 76 | return "", noop, err |
| 77 | } |
| 78 | done := func() { _ = os.RemoveAll(dir) } |
| 79 | found := 0 |
| 80 | for _, name := range strings.Split(strings.TrimSpace(listing), "\n") { |
| 81 | // The deriver and the composer both read the layer as the `*.cue` |
| 82 | // documents directly in it, so those are what is taken. |
| 83 | if !strings.HasSuffix(name, ".cue") { |
| 84 | continue |
| 85 | } |
| 86 | body, err := git(l.repo, "show", tree+"/"+name) |
| 87 | if err != nil { |
| 88 | done() |
| 89 | return "", noop, fmt.Errorf("reading %s/%s from %s at %s: %w", l.dir, name, l.repo, l.ref, err) |
| 90 | } |
| 91 | if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { |
| 92 | done() |
| 93 | return "", noop, err |
| 94 | } |
| 95 | found++ |
| 96 | } |
| 97 | if found == 0 { |
| 98 | done() |
| 99 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s", l.repo, l.dir, l.ref) |
| 100 | } |
| 101 | return dir, done, nil |
| 102 | } |
| 103 | |
| 104 | // policySource is where the two layers are read from, and the schema they |
| 105 | // are composed under. |
| 106 | type policySource struct { |
| 107 | schema string // the verification schema |
| 108 | layer instanceLayer |
| 109 | instance string // the instance layer as resolved on disk, for one pass |
| 110 | project string // the project layer, relative to the target tip's tree |
| 111 | valley string // the deriver |
| 112 | cue string // the composer, for the catalogue the deriver does not print |
| 113 | } |
| 114 | |
| 115 | // open resolves the instance layer and returns a source that reads it from |
| 116 | // disk, together with what ends the pass. Held for the whole pass rather |
| 117 | // than resolved per call, so the deriver and the composer are given the same |
| 118 | // bytes: they are two readings of one policy, not two policies. |
| 119 | func (p policySource) open() (policySource, func(), error) { |
| 120 | dir, done, err := p.layer.open() |
| 121 | if err != nil { |
| 122 | return p, done, err |
| 123 | } |
| 124 | p.instance = dir |
| 125 | return p, done, nil |
| 126 | } |
| 127 | |
| 128 | // derived is one run of the deriver over a diff: which classes the diff |
| 129 | // matched, and which checks that made required. |
| 130 | type derived struct { |
| 131 | classes map[string]bool |
| 132 | requires map[string][]string // check name -> the classes requiring it |
| 133 | } |
| 134 | |
| 135 | // derive runs the deriver over a diff, in a checkout of the target tip. The |
| 136 | // checkout supplies the project layer and the commits the diff names; the |
| 137 | // instance layer comes from outside it. |
| 138 | func (p policySource) derive(tip *worktree, from, to string) (derived, error) { |
| 139 | cmd := exec.Command(p.valley, "checks", |
| 140 | "--schema", p.schema, |
| 141 | "--instance", p.instance, |
| 142 | "--project", filepath.Join(tip.dir, p.project), |
| 143 | from, to) |
| 144 | cmd.Dir = tip.dir |
| 145 | out, err := cmd.CombinedOutput() |
| 146 | if err != nil { |
| 147 | return derived{}, fmt.Errorf("deriving required checks for %s..%s: %w\n%s", verdict.Short(from), verdict.Short(to), err, strings.TrimSpace(string(out))) |
| 148 | } |
| 149 | return parseDerived(string(out)) |
| 150 | } |
| 151 | |
| 152 | // parseDerived reads what `valley checks` printed. The deriver reports for |
| 153 | // a person, so this is the one place the two programs are coupled by |
| 154 | // output; the coupling is pinned by the integrator's own checks rather |
| 155 | // than assumed. |
| 156 | func parseDerived(out string) (derived, error) { |
| 157 | d := derived{classes: map[string]bool{}, requires: map[string][]string{}} |
| 158 | lines := strings.Split(out, "\n") |
| 159 | for i := 0; i < len(lines); i++ { |
| 160 | line := lines[i] |
| 161 | switch { |
| 162 | case strings.HasPrefix(line, "classes matched:"): |
| 163 | rest := strings.TrimSpace(strings.TrimPrefix(line, "classes matched:")) |
| 164 | if rest == "none" { |
| 165 | continue |
| 166 | } |
| 167 | for _, c := range strings.Split(rest, ",") { |
| 168 | if c = strings.TrimSpace(c); c != "" { |
| 169 | d.classes[c] = true |
| 170 | } |
| 171 | } |
| 172 | case line == "required checks:": |
| 173 | for i++; i < len(lines); i++ { |
| 174 | body := lines[i] |
| 175 | if !strings.HasPrefix(body, " ") || strings.TrimSpace(body) == "" { |
| 176 | i-- |
| 177 | break |
| 178 | } |
| 179 | // " <name> <mandatory|default> <class>[, <class>…]" |
| 180 | fields := strings.Fields(body) |
| 181 | if len(fields) < 2 { |
| 182 | return derived{}, fmt.Errorf("the deriver printed %q, which is not a required-check line", body) |
| 183 | } |
| 184 | name := fields[0] |
| 185 | var classes []string |
| 186 | for _, c := range strings.Split(strings.Join(fields[2:], " "), ",") { |
| 187 | if c = strings.TrimSpace(c); c != "" { |
| 188 | classes = append(classes, c) |
| 189 | } |
| 190 | } |
| 191 | d.requires[name] = classes |
| 192 | } |
| 193 | case strings.HasPrefix(line, "required checks: none"): |
| 194 | // Nothing owed; the map stays empty. |
| 195 | } |
| 196 | } |
| 197 | return d, nil |
| 198 | } |
| 199 | |
| 200 | // catalogueEntry is one check as the composed policy defines it: how it is |
| 201 | // run, and how long an observation of it stays good. |
| 202 | type catalogueEntry struct { |
| 203 | Runner string `json:"runner"` |
| 204 | Attribute string `json:"attribute"` |
| 205 | Command string `json:"command"` |
| 206 | Validity string `json:"validity"` |
| 207 | } |
| 208 | |
| 209 | // catalogue reads the composed policy's check definitions. The deriver |
| 210 | // prints which checks are required and not what a check is, and the |
| 211 | // integrator needs the latter: a pure check's attribute is what it |
| 212 | // evaluates a closure over, and an effectful check's window is Δ. |
| 213 | // |
| 214 | // This is the same composition the deriver ran, over the same layers and |
| 215 | // the same schema — `cue export` of a field the deriver does not print, |
| 216 | // not a second opinion about what the policy says. |
| 217 | func (p policySource) catalogue(tip *worktree) (map[string]catalogueEntry, string, error) { |
| 218 | args := []string{"export", "--out", "json", "-e", "policy", p.schema} |
| 219 | for _, dir := range []string{p.instance, filepath.Join(tip.dir, p.project)} { |
| 220 | docs, err := filepath.Glob(filepath.Join(dir, "*.cue")) |
| 221 | if err != nil || len(docs) == 0 { |
| 222 | return nil, "", fmt.Errorf("no policy layer at %s", dir) |
| 223 | } |
| 224 | args = append(args, docs...) |
| 225 | } |
| 226 | cmd := exec.Command(p.cue, args...) |
| 227 | out, err := cmd.CombinedOutput() |
| 228 | if err != nil { |
| 229 | return nil, "", fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out))) |
| 230 | } |
| 231 | var composed struct { |
| 232 | Checks map[string]catalogueEntry `json:"checks"` |
| 233 | } |
| 234 | if err := json.Unmarshal(out, &composed); err != nil { |
| 235 | return nil, "", fmt.Errorf("reading the composed policy: %w", err) |
| 236 | } |
| 237 | return composed.Checks, sha256hex(out), nil |
| 238 | } |
| 239 | |
| 240 | // required turns a derivation and a catalogue into the check set the |
| 241 | // verdict is computed over. |
| 242 | func (p policySource) required(d derived, cat map[string]catalogueEntry) ([]verdict.Required, error) { |
| 243 | var out []verdict.Required |
| 244 | for name, classes := range d.requires { |
| 245 | entry, ok := cat[name] |
| 246 | if !ok { |
| 247 | return nil, fmt.Errorf("the policy requires %q and defines no check by that name", name) |
| 248 | } |
| 249 | window, err := parseWindow(entry.Validity) |
| 250 | if err != nil { |
| 251 | return nil, fmt.Errorf("check %s: %w", name, err) |
| 252 | } |
| 253 | out = append(out, verdict.Required{ |
| 254 | Name: name, |
| 255 | Classes: classes, |
| 256 | Runner: entry.Runner, |
| 257 | Attribute: entry.Attribute, |
| 258 | Validity: window, |
| 259 | }) |
| 260 | } |
| 261 | return out, nil |
| 262 | } |
| 263 | |
| 264 | // parseWindow reads a #Duration from the policy. The schema admits whole |
| 265 | // seconds, minutes, hours and days; an empty window is no window, which is |
| 266 | // what makes the integrator re-demand the check. |
| 267 | func parseWindow(s string) (time.Duration, error) { |
| 268 | if s == "" { |
| 269 | return 0, nil |
| 270 | } |
| 271 | unit := s[len(s)-1] |
| 272 | if unit == 'd' { |
| 273 | d, err := time.ParseDuration(s[:len(s)-1] + "h") |
| 274 | return d * 24, err |
| 275 | } |
| 276 | return time.ParseDuration(s) |
| 277 | } |