| 1 | // Package composed reads the verification policy as cue composes it: the |
| 2 | // floor, the project-type template the policy names, and the project's own |
| 3 | // layer at the target tip, under the packaged schema |
| 4 | // (schema/verification.cue). It does not compose anything itself. cue |
| 5 | // does, so no second copy of the composition can disagree with the one the |
| 6 | // deriver runs. |
| 7 | // |
| 8 | // The floor is read from the instance repository's tip, or from a |
| 9 | // materialized directory for a host that serves no instance repository. |
| 10 | // The project layer is read from the target tip. A layer that is not there |
| 11 | // defaults in the safe direction of its job: an absent project layer |
| 12 | // composes the floor alone, and an absent floor is refused. |
| 13 | // |
| 14 | // Every git and cue it runs runs under the caller's context, in a process |
| 15 | // group of its own. A context that is done kills the whole group, and the |
| 16 | // wait for the output is bounded, so a caller with a deadline is never |
| 17 | // held past it. |
| 18 | package composed |
| 19 | |
| 20 | import ( |
| 21 | "bytes" |
| 22 | "context" |
| 23 | "crypto/sha256" |
| 24 | "encoding/hex" |
| 25 | "encoding/json" |
| 26 | "fmt" |
| 27 | "os" |
| 28 | "os/exec" |
| 29 | "path/filepath" |
| 30 | "strings" |
| 31 | "time" |
| 32 | ) |
| 33 | |
| 34 | // Floor is where the group's floor comes from: a repository's tip, read |
| 35 | // with ls-tree and show and never written, or else a directory on disk. |
| 36 | type Floor struct { |
| 37 | Repo string // the repository carrying the floor; "" when Path is set |
| 38 | Ref string // the ref whose tip is authoritative |
| 39 | Dir string // the floor's directory in that tip's tree |
| 40 | Path string // a materialized layer, when no repository carries one |
| 41 | } |
| 42 | |
| 43 | // Floorless ends every refusal to find a floor. The floor is the minimum, |
| 44 | // and a missing minimum reads equally as a reader pointed at the wrong |
| 45 | // directory, a repository nobody seeded, or a floor somebody deleted. What |
| 46 | // is refused is the absent document; a floor that states it requires |
| 47 | // nothing composes like any other. |
| 48 | const Floorless = "a valley without a written floor is not a valley whose changes land" |
| 49 | |
| 50 | // Open resolves the floor to a directory of *.cue on disk, and returns |
| 51 | // what removes it. A floor read from a repository is copied into a |
| 52 | // scratch directory whose name starts with prefix. |
| 53 | func (f Floor) Open(ctx context.Context, prefix string) (string, func(), error) { |
| 54 | noop := func() {} |
| 55 | if f.Repo == "" { |
| 56 | // The materialized layer is held to the same minimum as the one a |
| 57 | // repository carries: a directory with no documents in it is a floor |
| 58 | // nobody wrote. |
| 59 | if docs, err := filepath.Glob(filepath.Join(f.Path, "*.cue")); err != nil || len(docs) == 0 { |
| 60 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", f.Path, Floorless) |
| 61 | } |
| 62 | return f.Path, noop, nil |
| 63 | } |
| 64 | dir, found, done, err := readLayer(ctx, f.Repo, f.Ref, f.Dir, prefix) |
| 65 | switch { |
| 66 | case err != nil: |
| 67 | return "", noop, err |
| 68 | case found == absent: |
| 69 | return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless) |
| 70 | case found == empty: |
| 71 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless) |
| 72 | } |
| 73 | return dir, done, nil |
| 74 | } |
| 75 | |
| 76 | // Project resolves the project's own layer at a tree-ish of a repository |
| 77 | // to a directory of *.cue on disk, and returns what removes it, and a note |
| 78 | // when the layer is absent. |
| 79 | // |
| 80 | // A target that carries no layer of its own is composed under the floor |
| 81 | // alone. The project layer only ever adds, and the identity of "adds" is |
| 82 | // "adds nothing", so that is what absence means. Absence is answered with |
| 83 | // a document that adds nothing rather than with an argument left off, |
| 84 | // because cue is handed a directory of *.cue and has no spelling for "no |
| 85 | // layer". |
| 86 | func Project(ctx context.Context, repo, treeish, dir, prefix string) (string, string, func(), error) { |
| 87 | path, found, done, err := readLayer(ctx, repo, treeish, dir, prefix) |
| 88 | if err != nil { |
| 89 | return "", "", func() {}, err |
| 90 | } |
| 91 | if found == present { |
| 92 | return path, "", done, nil |
| 93 | } |
| 94 | done() |
| 95 | path, done, err = AddsNothing(prefix) |
| 96 | return path, fmt.Sprintf("no project layer at %s; the floor alone", dir), done, err |
| 97 | } |
| 98 | |
| 99 | // AddsNothing writes a project layer that adds nothing into a scratch |
| 100 | // directory: a package clause and nothing else, so `project` stays what |
| 101 | // the schema leaves it. |
| 102 | func AddsNothing(prefix string) (string, func(), error) { |
| 103 | dir, err := scratch(prefix) |
| 104 | if err != nil { |
| 105 | return "", func() {}, err |
| 106 | } |
| 107 | done := func() { _ = os.RemoveAll(dir) } |
| 108 | if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil { |
| 109 | done() |
| 110 | return "", func() {}, err |
| 111 | } |
| 112 | return dir, done, nil |
| 113 | } |
| 114 | |
| 115 | // What readLayer found at a directory of a tree. |
| 116 | const ( |
| 117 | present = iota // the directory, with *.cue in it |
| 118 | absent // no such directory |
| 119 | empty // the directory, with no *.cue in it |
| 120 | ) |
| 121 | |
| 122 | // readLayer copies the *.cue documents directly in one directory of a |
| 123 | // tree-ish out of a repository, into a scratch directory. The deriver and |
| 124 | // cue both read a layer as those documents, so they are what is taken. |
| 125 | // The scratch directory is removed unless the layer is present. |
| 126 | // |
| 127 | // The listing is NUL-separated, so every name is read as it is. A |
| 128 | // newline-separated listing quotes a name with non-ASCII characters in it, |
| 129 | // such as naïve.cue, and the quoted name does not end in .cue, so that |
| 130 | // document would be skipped. A materialized floor's glob finds it, and so |
| 131 | // does this. |
| 132 | func readLayer(ctx context.Context, repo, treeish, dir, prefix string) (string, int, func(), error) { |
| 133 | noop := func() {} |
| 134 | tree := treeish + ":" + dir |
| 135 | listing, err := git(ctx, repo, "ls-tree", "--name-only", "-z", tree) |
| 136 | if err != nil { |
| 137 | if ctx.Err() != nil { |
| 138 | return "", absent, noop, fmt.Errorf("reading %s from %s at %s: %w", dir, repo, treeish, ctx.Err()) |
| 139 | } |
| 140 | return "", absent, noop, nil |
| 141 | } |
| 142 | out, err := scratch(prefix) |
| 143 | if err != nil { |
| 144 | return "", absent, noop, err |
| 145 | } |
| 146 | done := func() { _ = os.RemoveAll(out) } |
| 147 | found := 0 |
| 148 | for _, name := range strings.Split(listing, "\x00") { |
| 149 | if !strings.HasSuffix(name, ".cue") { |
| 150 | continue |
| 151 | } |
| 152 | body, err := git(ctx, repo, "show", tree+"/"+name) |
| 153 | if err != nil { |
| 154 | done() |
| 155 | return "", absent, noop, fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, treeish, err) |
| 156 | } |
| 157 | if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil { |
| 158 | done() |
| 159 | return "", absent, noop, err |
| 160 | } |
| 161 | found++ |
| 162 | } |
| 163 | if found == 0 { |
| 164 | done() |
| 165 | return "", empty, noop, nil |
| 166 | } |
| 167 | return out, present, done, nil |
| 168 | } |
| 169 | |
| 170 | // Check is one check as the composed policy defines it: how it is run, and |
| 171 | // how long an observation of it stays good. |
| 172 | type Check struct { |
| 173 | Runner string `json:"runner"` |
| 174 | Attribute string `json:"attribute"` |
| 175 | Command string `json:"command"` |
| 176 | Validity string `json:"validity"` |
| 177 | } |
| 178 | |
| 179 | // Policy is the composed policy, as far as its readers read it. |
| 180 | type Policy struct { |
| 181 | Checks map[string]Check |
| 182 | |
| 183 | // MaxAutomaticVersions caps how many versions the restacker adds to |
| 184 | // one change over the change's life (restack.maxAutomaticVersions). |
| 185 | // It is kept as cue wrote it. The schema admits any whole number of at |
| 186 | // least 1, and a Go int holds only some of them, so decoding into an |
| 187 | // int would refuse policies the schema admits. The restacker converts |
| 188 | // it where it counts. |
| 189 | MaxAutomaticVersions json.Number |
| 190 | |
| 191 | // Digest is the SHA-256 of the whole export, so everything the policy |
| 192 | // composes is in it: every check, every class's paths, requirements and |
| 193 | // carry mode, and the restacker's cap. |
| 194 | Digest string |
| 195 | } |
| 196 | |
| 197 | // Compose runs `cue export` of the composed policy over the schema, the |
| 198 | // floor's documents and the project layer's documents, and reads it. The |
| 199 | // template is the one the policy's `type` names, which the schema selects |
| 200 | // as it composes. |
| 201 | func Compose(ctx context.Context, cue, schema, instance, project string) (*Policy, error) { |
| 202 | args := []string{"export", "--out", "json", "-e", "policy", schema} |
| 203 | for _, dir := range []string{instance, project} { |
| 204 | docs, err := filepath.Glob(filepath.Join(dir, "*.cue")) |
| 205 | if err != nil || len(docs) == 0 { |
| 206 | return nil, fmt.Errorf("no policy layer at %s", dir) |
| 207 | } |
| 208 | args = append(args, docs...) |
| 209 | } |
| 210 | cmd := command(ctx, cue, args...) |
| 211 | var combined bytes.Buffer |
| 212 | cmd.Stdout, cmd.Stderr = &combined, &combined |
| 213 | err := cmd.Run() |
| 214 | out := combined.Bytes() |
| 215 | if err != nil { |
| 216 | return nil, fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out))) |
| 217 | } |
| 218 | var read struct { |
| 219 | Checks map[string]Check `json:"checks"` |
| 220 | Restack struct { |
| 221 | MaxAutomaticVersions json.Number `json:"maxAutomaticVersions"` |
| 222 | } `json:"restack"` |
| 223 | } |
| 224 | if err := json.Unmarshal(out, &read); err != nil { |
| 225 | return nil, fmt.Errorf("reading the composed policy: %w", err) |
| 226 | } |
| 227 | sum := sha256.Sum256(out) |
| 228 | return &Policy{ |
| 229 | Checks: read.Checks, |
| 230 | MaxAutomaticVersions: read.Restack.MaxAutomaticVersions, |
| 231 | Digest: hex.EncodeToString(sum[:]), |
| 232 | }, nil |
| 233 | } |
| 234 | |
| 235 | // waitDelay is how long a wait for a program's output may go on after it |
| 236 | // has exited, or after a done context has killed it. Something it started |
| 237 | // that left its process group may still hold the output open. |
| 238 | const waitDelay = 5 * time.Second |
| 239 | |
| 240 | // command is a program run under ctx in a process group of its own, which |
| 241 | // a done context kills whole, with the wait for its output bounded. |
| 242 | func command(ctx context.Context, name string, args ...string) *exec.Cmd { |
| 243 | cmd := exec.CommandContext(ctx, name, args...) |
| 244 | cmd.WaitDelay = waitDelay |
| 245 | ownGroup(cmd) |
| 246 | return cmd |
| 247 | } |
| 248 | |
| 249 | func git(ctx context.Context, repo string, args ...string) (string, error) { |
| 250 | cmd := command(ctx, "git", args...) |
| 251 | cmd.Dir = repo |
| 252 | var out, errb bytes.Buffer |
| 253 | cmd.Stdout, cmd.Stderr = &out, &errb |
| 254 | if err := cmd.Run(); err != nil { |
| 255 | return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) |
| 256 | } |
| 257 | return out.String(), nil |
| 258 | } |
| 259 | |
| 260 | // scratch makes one throwaway directory under whatever TMPDIR names. The |
| 261 | // error names the operation, the path, and where the path came from. |
| 262 | func scratch(prefix string) (string, error) { |
| 263 | dir, err := os.MkdirTemp("", prefix) |
| 264 | if err != nil { |
| 265 | return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err) |
| 266 | } |
| 267 | return dir, nil |
| 268 | } |