| 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 | // Compose reads the check definitions the integrator reads, the |
| 9 | // restacker's cap, whether an approval must be signed with a hardware key, |
| 10 | // and the policy's digest. Read reads the whole policy the deriver |
| 11 | // (../derive) derives required checks from: every class, the unclassified |
| 12 | // set, and whether each requirement is mandatory. |
| 13 | // |
| 14 | // The floor is read from the instance repository's tip, or from a |
| 15 | // materialized directory for a host that serves no instance repository. |
| 16 | // The project layer is read from the target tip. A layer that is not there |
| 17 | // defaults in the safe direction of its job: an absent project layer |
| 18 | // composes the floor alone, and an absent floor is refused. |
| 19 | // |
| 20 | // Every git and cue it runs runs under the caller's context, in a process |
| 21 | // group of its own. A context that is done kills the whole group, and the |
| 22 | // wait for the output is bounded, so a caller with a deadline is never |
| 23 | // held past it. |
| 24 | package composed |
| 25 | |
| 26 | import ( |
| 27 | "bytes" |
| 28 | "context" |
| 29 | "crypto/sha256" |
| 30 | "encoding/hex" |
| 31 | "encoding/json" |
| 32 | "fmt" |
| 33 | "os" |
| 34 | "os/exec" |
| 35 | "path/filepath" |
| 36 | "sort" |
| 37 | "strings" |
| 38 | "time" |
| 39 | ) |
| 40 | |
| 41 | // Floor is where the group's floor comes from: a repository's tip, read |
| 42 | // with ls-tree and show and never written, or else a directory on disk. |
| 43 | type Floor struct { |
| 44 | Repo string // the repository carrying the floor; "" when Path is set |
| 45 | Ref string // the ref whose tip is authoritative |
| 46 | Dir string // the floor's directory in that tip's tree |
| 47 | Path string // a materialized layer, when no repository carries one |
| 48 | } |
| 49 | |
| 50 | // Floorless ends every refusal to find a floor. The floor is the minimum, |
| 51 | // and a missing minimum reads equally as a reader pointed at the wrong |
| 52 | // directory, a repository nobody seeded, or a floor somebody deleted. What |
| 53 | // is refused is the absent document; a floor that states it requires |
| 54 | // nothing composes like any other. |
| 55 | const Floorless = "a valley without a written floor is not a valley whose changes land" |
| 56 | |
| 57 | // Open resolves the floor to a directory of *.cue on disk, and returns |
| 58 | // what removes it. A floor read from a repository is copied into a |
| 59 | // scratch directory whose name starts with prefix. |
| 60 | func (f Floor) Open(ctx context.Context, prefix string) (string, func(), error) { |
| 61 | noop := func() {} |
| 62 | if f.Repo == "" { |
| 63 | // The materialized layer is held to the same minimum as the one a |
| 64 | // repository carries: a directory with no documents in it is a floor |
| 65 | // nobody wrote. |
| 66 | if _, err := layer(f.Path); err != nil { |
| 67 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", f.Path, Floorless) |
| 68 | } |
| 69 | return f.Path, noop, nil |
| 70 | } |
| 71 | dir, found, done, err := readLayer(ctx, f.Repo, f.Ref, f.Dir, prefix) |
| 72 | switch { |
| 73 | case err != nil: |
| 74 | return "", noop, err |
| 75 | case found == absent: |
| 76 | return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless) |
| 77 | case found == empty: |
| 78 | return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless) |
| 79 | } |
| 80 | return dir, done, nil |
| 81 | } |
| 82 | |
| 83 | // Project resolves the project's own layer at a tree-ish of a repository |
| 84 | // to a directory of *.cue on disk, and returns what removes it, and a note |
| 85 | // when the layer is absent. |
| 86 | // |
| 87 | // A target that carries no layer of its own is composed under the floor |
| 88 | // alone. The project layer only ever adds, and the identity of "adds" is |
| 89 | // "adds nothing", so that is what absence means. Absence is answered with |
| 90 | // a document that adds nothing rather than with an argument left off, |
| 91 | // because cue is handed a directory of *.cue and has no spelling for "no |
| 92 | // layer". |
| 93 | func Project(ctx context.Context, repo, treeish, dir, prefix string) (string, string, func(), error) { |
| 94 | path, found, done, err := readLayer(ctx, repo, treeish, dir, prefix) |
| 95 | if err != nil { |
| 96 | return "", "", func() {}, err |
| 97 | } |
| 98 | if found == present { |
| 99 | return path, "", done, nil |
| 100 | } |
| 101 | done() |
| 102 | path, done, err = AddsNothing(prefix) |
| 103 | return path, fmt.Sprintf("no project layer at %s; the floor alone", dir), done, err |
| 104 | } |
| 105 | |
| 106 | // AddsNothing writes a project layer that adds nothing into a scratch |
| 107 | // directory: a package clause and nothing else, so `project` stays what |
| 108 | // the schema leaves it. |
| 109 | func AddsNothing(prefix string) (string, func(), error) { |
| 110 | dir, err := scratch(prefix) |
| 111 | if err != nil { |
| 112 | return "", func() {}, err |
| 113 | } |
| 114 | done := func() { _ = os.RemoveAll(dir) } |
| 115 | if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil { |
| 116 | done() |
| 117 | return "", func() {}, err |
| 118 | } |
| 119 | return dir, done, nil |
| 120 | } |
| 121 | |
| 122 | // What readLayer found at a directory of a tree. |
| 123 | const ( |
| 124 | present = iota // the directory, with *.cue in it |
| 125 | absent // no such directory |
| 126 | empty // the directory, with no *.cue in it |
| 127 | ) |
| 128 | |
| 129 | // readLayer copies the *.cue documents directly in one directory of a |
| 130 | // tree-ish out of a repository, into a scratch directory. The deriver and |
| 131 | // cue both read a layer as those documents, so they are what is taken. |
| 132 | // The scratch directory is removed unless the layer is present. |
| 133 | // |
| 134 | // The listing is NUL-separated, so every name is read as it is. A |
| 135 | // newline-separated listing quotes a name with non-ASCII characters in it, |
| 136 | // such as naïve.cue, and the quoted name does not end in .cue, so that |
| 137 | // document would be skipped. A materialized floor's glob finds it, and so |
| 138 | // does this. |
| 139 | func readLayer(ctx context.Context, repo, treeish, dir, prefix string) (string, int, func(), error) { |
| 140 | noop := func() {} |
| 141 | tree := treeish + ":" + dir |
| 142 | listing, err := git(ctx, repo, "ls-tree", "--name-only", "-z", tree) |
| 143 | if err != nil { |
| 144 | if ctx.Err() != nil { |
| 145 | return "", absent, noop, fmt.Errorf("reading %s from %s at %s: %w", dir, repo, treeish, ctx.Err()) |
| 146 | } |
| 147 | return "", absent, noop, nil |
| 148 | } |
| 149 | out, err := scratch(prefix) |
| 150 | if err != nil { |
| 151 | return "", absent, noop, err |
| 152 | } |
| 153 | done := func() { _ = os.RemoveAll(out) } |
| 154 | found := 0 |
| 155 | for _, name := range strings.Split(listing, "\x00") { |
| 156 | if !strings.HasSuffix(name, ".cue") { |
| 157 | continue |
| 158 | } |
| 159 | body, err := git(ctx, repo, "show", tree+"/"+name) |
| 160 | if err != nil { |
| 161 | done() |
| 162 | return "", absent, noop, fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, treeish, err) |
| 163 | } |
| 164 | if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil { |
| 165 | done() |
| 166 | return "", absent, noop, err |
| 167 | } |
| 168 | found++ |
| 169 | } |
| 170 | if found == 0 { |
| 171 | done() |
| 172 | return "", empty, noop, nil |
| 173 | } |
| 174 | return out, present, done, nil |
| 175 | } |
| 176 | |
| 177 | // Check is one check as the composed policy defines it: how it is run, how |
| 178 | // long an observation of it stays good, and what running it costs. |
| 179 | type Check struct { |
| 180 | Runner string `json:"runner"` // nix or command |
| 181 | Attribute string `json:"attribute"` // the flake check attribute, for the nix runner |
| 182 | Command string `json:"command"` // the command line, for the command runner |
| 183 | Validity string `json:"validity"` // how long an observation stays good; "" for no window |
| 184 | Cost string `json:"cost"` // quick or slow |
| 185 | } |
| 186 | |
| 187 | // Policy is the composed policy, as far as its readers read it. |
| 188 | type Policy struct { |
| 189 | Checks map[string]Check |
| 190 | |
| 191 | // MaxAutomaticVersions caps how many versions the restacker adds to |
| 192 | // one change over the change's life (restack.maxAutomaticVersions). |
| 193 | // It is kept as cue wrote it. The schema admits any whole number of at |
| 194 | // least 1, and a Go int holds only some of them, so decoding into an |
| 195 | // int would refuse policies the schema admits. The restacker converts |
| 196 | // it where it counts. |
| 197 | MaxAutomaticVersions json.Number |
| 198 | |
| 199 | // HardwareApproval says whether an approval of a change must be signed |
| 200 | // with a key the identity registry enrolled as a hardware key |
| 201 | // (approval.hardware). It selects which keys may sign an approval. It |
| 202 | // does not decide whether a change needs one. A policy that leaves the |
| 203 | // field out does not require a hardware key. |
| 204 | HardwareApproval bool |
| 205 | |
| 206 | // Digest is the SHA-256 of the whole export, so everything the policy |
| 207 | // composes is in it: every check, every class's paths, requirements and |
| 208 | // carry mode, the restacker's cap, and the hardware requirement. |
| 209 | Digest string |
| 210 | } |
| 211 | |
| 212 | // Compose runs `cue export` of the composed policy over the schema, the |
| 213 | // floor's documents and the project layer's documents, and reads it. The |
| 214 | // template is the one the policy's `type` names, which the schema selects |
| 215 | // as it composes. |
| 216 | func Compose(ctx context.Context, cue, schema, instance, project string) (*Policy, error) { |
| 217 | docs, err := documents(schema, instance, project) |
| 218 | if err != nil { |
| 219 | return nil, err |
| 220 | } |
| 221 | pol, _, err := compose(ctx, cue, docs) |
| 222 | return pol, err |
| 223 | } |
| 224 | |
| 225 | // compose exports `policy` over docs and reads the policy from it. It |
| 226 | // returns the export too, for a reader that reads more of it. |
| 227 | func compose(ctx context.Context, cue string, docs []string) (*Policy, []byte, error) { |
| 228 | out, err := export(ctx, cue, docs, "policy") |
| 229 | if err != nil { |
| 230 | return nil, nil, fmt.Errorf("composing the policy: %w", err) |
| 231 | } |
| 232 | if err := exported.check(out); err != nil { |
| 233 | return nil, nil, fmt.Errorf("reading the composed policy: %w", err) |
| 234 | } |
| 235 | var read struct { |
| 236 | Checks map[string]Check `json:"checks"` |
| 237 | Restack struct { |
| 238 | MaxAutomaticVersions json.Number `json:"maxAutomaticVersions"` |
| 239 | } `json:"restack"` |
| 240 | Approval struct { |
| 241 | Hardware bool `json:"hardware"` |
| 242 | } `json:"approval"` |
| 243 | } |
| 244 | if err := json.Unmarshal(out, &read); err != nil { |
| 245 | return nil, nil, fmt.Errorf("reading the composed policy: %w", err) |
| 246 | } |
| 247 | sum := sha256.Sum256(out) |
| 248 | return &Policy{ |
| 249 | Checks: read.Checks, |
| 250 | MaxAutomaticVersions: read.Restack.MaxAutomaticVersions, |
| 251 | HardwareApproval: read.Approval.Hardware, |
| 252 | Digest: hex.EncodeToString(sum[:]), |
| 253 | }, out, nil |
| 254 | } |
| 255 | |
| 256 | // shape is what the reader expects of one value of the export: its kind, |
| 257 | // and for an object either the exact names of its fields or what every |
| 258 | // entry of it holds. |
| 259 | // |
| 260 | // The export is checked against it before it is decoded, because |
| 261 | // encoding/json matches a field's name without regard to case and keeps |
| 262 | // the last match. Any document of the policy may reopen a schema definition, |
| 263 | // since they are all in one package. A project can therefore add |
| 264 | // `Hardware: false` beside the floor's `hardware: true`, and cue exports |
| 265 | // both keys. encoding/json would read whichever of the two comes last. So |
| 266 | // an object read into a struct must hold the names the schema gives it, |
| 267 | // exactly, and nothing else. |
| 268 | type shape struct { |
| 269 | kind string // "object", "string", "number" or "bool" |
| 270 | fields map[string]shape // the fields of an object read into a struct |
| 271 | each *shape // every entry of an object read into a map |
| 272 | } |
| 273 | |
| 274 | var ( |
| 275 | text = shape{kind: "string"} |
| 276 | number = shape{kind: "number"} |
| 277 | flag = shape{kind: "bool"} |
| 278 | set = shape{kind: "object", each: &flag} |
| 279 | |
| 280 | // exported is the composed policy as schema/verification.cue exports |
| 281 | // it. Read reads `classes` and `unclassified` out of the same export. |
| 282 | exported = shape{kind: "object", fields: map[string]shape{ |
| 283 | "checks": {kind: "object", each: &shape{kind: "object", fields: map[string]shape{ |
| 284 | "runner": text, "attribute": text, "command": text, "validity": text, "cost": text, |
| 285 | }}}, |
| 286 | "classes": {kind: "object", each: &shape{kind: "object", fields: map[string]shape{ |
| 287 | "paths": set, "requires": set, "carry": set, |
| 288 | }}}, |
| 289 | "unclassified": set, |
| 290 | "restack": {kind: "object", fields: map[string]shape{"maxAutomaticVersions": number}}, |
| 291 | "approval": {kind: "object", fields: map[string]shape{"hardware": flag}}, |
| 292 | }} |
| 293 | ) |
| 294 | |
| 295 | // check reads data as one JSON value and holds it to s. |
| 296 | func (s shape) check(data []byte) error { |
| 297 | dec := json.NewDecoder(bytes.NewReader(data)) |
| 298 | dec.UseNumber() |
| 299 | var v any |
| 300 | if err := dec.Decode(&v); err != nil { |
| 301 | return err |
| 302 | } |
| 303 | return s.holds("policy", v) |
| 304 | } |
| 305 | |
| 306 | // holds says whether v, found at path, has the shape s. |
| 307 | func (s shape) holds(path string, v any) error { |
| 308 | var ok bool |
| 309 | switch s.kind { |
| 310 | case "string": |
| 311 | _, ok = v.(string) |
| 312 | case "number": |
| 313 | _, ok = v.(json.Number) |
| 314 | case "bool": |
| 315 | _, ok = v.(bool) |
| 316 | case "object": |
| 317 | var obj map[string]any |
| 318 | if obj, ok = v.(map[string]any); !ok { |
| 319 | break |
| 320 | } |
| 321 | names := make([]string, 0, len(obj)) |
| 322 | for name := range obj { |
| 323 | names = append(names, name) |
| 324 | } |
| 325 | sort.Strings(names) |
| 326 | for _, name := range names { |
| 327 | entry := s.each |
| 328 | if entry == nil { |
| 329 | field, known := s.fields[name] |
| 330 | if !known { |
| 331 | return fmt.Errorf("%s has a field %q the schema does not give it, which a document reopening a schema definition can add", path, name) |
| 332 | } |
| 333 | entry = &field |
| 334 | } |
| 335 | if err := entry.holds(path+"."+name, obj[name]); err != nil { |
| 336 | return err |
| 337 | } |
| 338 | } |
| 339 | } |
| 340 | if !ok { |
| 341 | return fmt.Errorf("%s is not a %s", path, s.kind) |
| 342 | } |
| 343 | return nil |
| 344 | } |
| 345 | |
| 346 | // documents is what a policy is composed from: the schema, then the |
| 347 | // floor's documents and the project layer's (layer). |
| 348 | func documents(schema, instance, project string) ([]string, error) { |
| 349 | docs := []string{schema} |
| 350 | for _, dir := range []string{instance, project} { |
| 351 | found, err := layer(dir) |
| 352 | if err != nil { |
| 353 | return nil, err |
| 354 | } |
| 355 | docs = append(docs, found...) |
| 356 | } |
| 357 | return docs, nil |
| 358 | } |
| 359 | |
| 360 | // layer is the documents of one policy layer: the entries directly in dir |
| 361 | // that bin/valley's `"$dir"/*.cue` names, in its order. |
| 362 | // |
| 363 | // dir is a name and never a pattern, as it is quoted there, so a directory |
| 364 | // named policy[1] is that directory and not policy1. Its entries are |
| 365 | // listed, and an entry is a document when its name ends in .cue and does |
| 366 | // not begin with a dot, because bash's glob leaves a dotfile out. They are |
| 367 | // sorted bytewise, as bash sorts them in the C locale bin/valley derives |
| 368 | // in. The first must be a regular file, as bin/valley's `[ -f ]` asks, or |
| 369 | // the layer holds no documents. |
| 370 | func layer(dir string) ([]string, error) { |
| 371 | entries, err := os.ReadDir(dir) |
| 372 | if err != nil { |
| 373 | return nil, fmt.Errorf("no policy layer at %s: %w", dir, err) |
| 374 | } |
| 375 | var docs []string |
| 376 | for _, e := range entries { |
| 377 | if name := e.Name(); strings.HasSuffix(name, ".cue") && !strings.HasPrefix(name, ".") { |
| 378 | docs = append(docs, filepath.Join(dir, name)) |
| 379 | } |
| 380 | } |
| 381 | if len(docs) == 0 { |
| 382 | return nil, fmt.Errorf("no policy layer at %s", dir) |
| 383 | } |
| 384 | if info, err := os.Stat(docs[0]); err != nil || !info.Mode().IsRegular() { |
| 385 | return nil, fmt.Errorf("no policy layer at %s: %s is not a file", dir, docs[0]) |
| 386 | } |
| 387 | return docs, nil |
| 388 | } |
| 389 | |
| 390 | // export runs `cue export` of one expression over docs and returns what |
| 391 | // cue printed. A failure returns what cue said, so the caller can say what |
| 392 | // it was doing. |
| 393 | // |
| 394 | // Its output and its diagnostics are read as one stream, and |
| 395 | // Policy.Digest is of those bytes. Reading them apart would change every |
| 396 | // digest with no change to any policy. |
| 397 | func export(ctx context.Context, cue string, docs []string, expr string) ([]byte, error) { |
| 398 | args := append([]string{"export", "--out", "json", "-e", expr}, docs...) |
| 399 | cmd := command(ctx, cue, args...) |
| 400 | var combined bytes.Buffer |
| 401 | cmd.Stdout, cmd.Stderr = &combined, &combined |
| 402 | if err := cmd.Run(); err != nil { |
| 403 | return nil, fmt.Errorf("%w\n%s", err, strings.TrimSpace(combined.String())) |
| 404 | } |
| 405 | return combined.Bytes(), nil |
| 406 | } |
| 407 | |
| 408 | // waitDelay is how long a wait for a program's output may go on after it |
| 409 | // has exited, or after a done context has killed it. Something it started |
| 410 | // that left its process group may still hold the output open. |
| 411 | const waitDelay = 5 * time.Second |
| 412 | |
| 413 | // command is a program run under ctx in a process group of its own, which |
| 414 | // a done context kills whole, with the wait for its output bounded. |
| 415 | func command(ctx context.Context, name string, args ...string) *exec.Cmd { |
| 416 | cmd := exec.CommandContext(ctx, name, args...) |
| 417 | cmd.WaitDelay = waitDelay |
| 418 | ownGroup(cmd) |
| 419 | return cmd |
| 420 | } |
| 421 | |
| 422 | func git(ctx context.Context, repo string, args ...string) (string, error) { |
| 423 | cmd := command(ctx, "git", args...) |
| 424 | cmd.Dir = repo |
| 425 | var out, errb bytes.Buffer |
| 426 | cmd.Stdout, cmd.Stderr = &out, &errb |
| 427 | if err := cmd.Run(); err != nil { |
| 428 | return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) |
| 429 | } |
| 430 | return out.String(), nil |
| 431 | } |
| 432 | |
| 433 | // scratch makes one throwaway directory under whatever TMPDIR names. The |
| 434 | // error names the operation, the path, and where the path came from. |
| 435 | func scratch(prefix string) (string, error) { |
| 436 | dir, err := os.MkdirTemp("", prefix) |
| 437 | if err != nil { |
| 438 | return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err) |
| 439 | } |
| 440 | return dir, nil |
| 441 | } |