gunk-dev/the-valley

composed.go

source8043b5e912d0main's published tip history
20.6 KiB
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. A layer that
19// cannot be read is refused, whichever it is.
20//
21// Every git and cue it runs runs under the caller's context, in a process
22// group of its own. A context that is done kills the whole group, and the
23// wait for the output is bounded, so a caller with a deadline is never
24// held past it.
25package composed
26
27import (
28 "bytes"
29 "context"
30 "crypto/sha256"
31 "encoding/hex"
32 "encoding/json"
33 "errors"
34 "fmt"
35 "os"
36 "os/exec"
37 "path/filepath"
38 "sort"
39 "strings"
40 "time"
41)
42
43// Floor is where the group's floor comes from: a repository's tip, read
44// with ls-tree and show and never written, or else a directory on disk.
45//
46// A Ref that is a full ref name, opening with refs/, is read by that exact
47// name, once, and the floor is read at the commit it held. Anything else,
48// such as an object ID or FETCH_HEAD, is read as given.
49type Floor struct {
50 Repo string // the repository carrying the floor; "" when Path is set
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// Floorless ends every refusal to find a floor. The floor is the minimum,
57// and a missing minimum reads equally as a reader pointed at the wrong
58// directory, a repository nobody seeded, or a floor somebody deleted. What
59// is refused is the absent document; a floor that states it requires
60// nothing composes like any other.
61const Floorless = "a valley without a written floor is not a valley whose changes land"
62
63// ErrNoFloor is what Open's refusal wraps when the tree-ish it reads
64// carries no floor: no such directory, or one holding no *.cue. A reader
65// with another place to look, as the worker looks to the owning valley
66// when a project's tip carries no floor of its own, looks there. Every
67// other refusal, a floor that could not be read among them, is final.
68var ErrNoFloor = errors.New(Floorless)
69
70// Open resolves the floor to a directory of *.cue on disk, and returns
71// what removes it. A floor read from a repository is copied into a
72// scratch directory whose name starts with prefix.
73func (f Floor) Open(ctx context.Context, prefix string) (string, func(), error) {
74 noop := func() {}
75 if f.Repo == "" {
76 // The materialized layer is held to the same minimum as the one a
77 // repository carries: a directory with no documents in it is a floor
78 // nobody wrote.
79 if _, err := layer(f.Path); err != nil {
80 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", f.Path, Floorless)
81 }
82 return f.Path, noop, nil
83 }
84 at := f.Ref
85 if strings.HasPrefix(at, "refs/") {
86 oid, ok, err := resolveRef(ctx, f.Repo, f.Ref)
87 if err != nil {
88 return "", noop, err
89 } else if !ok {
90 return "", noop, fmt.Errorf("no instance policy layer: %s has no %s: %s", f.Repo, f.Ref, Floorless)
91 }
92 at = oid
93 }
94 dir, found, done, err := readLayer(ctx, f.Repo, at, f.Dir, prefix)
95 switch {
96 case err != nil:
97 return "", noop, err
98 case found == absent:
99 return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %w", f.Repo, f.Dir, f.Ref, ErrNoFloor)
100 case found == empty:
101 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %w", f.Repo, f.Dir, f.Ref, ErrNoFloor)
102 }
103 return dir, done, nil
104}
105
106// Project resolves the project's own layer at a tree-ish of a repository
107// to a directory of *.cue on disk, and returns what removes it, and a note
108// when the layer is absent. A layer that cannot be read is an error.
109//
110// A target that carries no layer of its own is composed under the floor
111// alone. The project layer only ever adds, and the identity of "adds" is
112// "adds nothing", so that is what absence means. Absence is answered with
113// a document that adds nothing rather than with an argument left off,
114// because cue is handed a directory of *.cue and has no spelling for "no
115// layer".
116func Project(ctx context.Context, repo, treeish, dir, prefix string) (string, string, func(), error) {
117 path, found, done, err := readLayer(ctx, repo, treeish, dir, prefix)
118 if err != nil {
119 return "", "", func() {}, err
120 }
121 if found == present {
122 return path, "", done, nil
123 }
124 done()
125 path, done, err = AddsNothing(prefix)
126 return path, fmt.Sprintf("no project layer at %s; the floor alone", dir), done, err
127}
128
129// AddsNothing writes a project layer that adds nothing into a scratch
130// directory: a package clause and nothing else, so `project` stays what
131// the schema leaves it.
132func AddsNothing(prefix string) (string, func(), error) {
133 dir, err := scratch(prefix)
134 if err != nil {
135 return "", func() {}, err
136 }
137 done := func() { _ = os.RemoveAll(dir) }
138 if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil {
139 done()
140 return "", func() {}, err
141 }
142 return dir, done, nil
143}
144
145// What readLayer found at a directory of a tree.
146const (
147 present = iota // the directory, with *.cue in it
148 absent // no such directory: an empty listing
149 empty // the directory, with no *.cue in it
150)
151
152// readLayer copies the *.cue documents directly in one directory of a
153// tree-ish out of a repository, into a scratch directory. The deriver and
154// cue both read a layer as those documents, so they are what is taken.
155// The scratch directory is removed unless the layer is present.
156//
157// It decides as bin/valley's copy_layer, which approve reads the layers
158// with, so the two cannot disagree about which layer is there. The
159// directory is listed with a pathspec, taken literally, so a directory
160// named policy[1] is that directory and not policy1. A directory that is
161// not there is an empty listing, and a listing git could not read, of a
162// tree-ish or a tree object that is missing, is an error: read as absent,
163// a project layer nobody could read would compose as the floor alone,
164// requiring fewer checks from a read that never happened. Each *.cue entry
165// is read as a blob, so one that is a directory or a submodule is an error
166// too.
167//
168// A name beginning with a dot is copied as copy_layer copies it, and
169// counts toward a present layer. The composer leaves it out (layer), so a
170// layer holding dotfiles alone is present, holds no document, and is
171// refused when it is composed, as bin/valley refuses it.
172//
173// The listing is NUL-separated, so every name is read as it is. A
174// newline-separated listing quotes a name with non-ASCII characters in it,
175// such as naïve.cue, and the quoted name does not end in .cue, so that
176// document would be skipped. A materialized floor's glob finds it, and so
177// does this.
178func readLayer(ctx context.Context, repo, treeish, dir, prefix string) (string, int, func(), error) {
179 noop := func() {}
180 listing, err := git(ctx, repo, "--literal-pathspecs", "ls-tree", "--full-tree", "--name-only", "-z", "--end-of-options", treeish, dir+"/")
181 if err != nil {
182 if ctx.Err() != nil {
183 err = ctx.Err()
184 }
185 return "", absent, noop, fmt.Errorf("reading %s/ from %s at %s: %w", dir, repo, treeish, err)
186 }
187 if listing == "" {
188 return "", absent, noop, nil
189 }
190 out, err := scratch(prefix)
191 if err != nil {
192 return "", absent, noop, err
193 }
194 done := func() { _ = os.RemoveAll(out) }
195 found := 0
196 for _, path := range strings.Split(strings.TrimSuffix(listing, "\x00"), "\x00") {
197 if !strings.HasSuffix(path, ".cue") {
198 continue
199 }
200 name := path[strings.LastIndexByte(path, '/')+1:]
201 body, err := git(ctx, repo, "cat-file", "blob", treeish+":"+path)
202 if err != nil {
203 done()
204 return "", absent, noop, fmt.Errorf("reading %s from %s at %s: %w", path, repo, treeish, err)
205 }
206 if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil {
207 done()
208 return "", absent, noop, err
209 }
210 found++
211 }
212 if found == 0 {
213 done()
214 return "", empty, noop, nil
215 }
216 return out, present, done, nil
217}
218
219// Check is one check as the composed policy defines it: how it is run, how
220// long an observation of it stays good, and what running it costs.
221type Check struct {
222 Runner string `json:"runner"` // nix or command
223 Attribute string `json:"attribute"` // the flake check attribute, for the nix runner
224 Command string `json:"command"` // the command line, for the command runner
225 Validity string `json:"validity"` // how long an observation stays good; "" for no window
226 Cost string `json:"cost"` // quick or slow
227}
228
229// Policy is the composed policy, as far as its readers read it.
230type Policy struct {
231 Checks map[string]Check
232
233 // MaxAutomaticVersions caps how many versions the restacker adds to
234 // one change over the change's life (restack.maxAutomaticVersions).
235 // It is kept as cue wrote it. The schema admits any whole number of at
236 // least 1, and a Go int holds only some of them, so decoding into an
237 // int would refuse policies the schema admits. The restacker converts
238 // it where it counts.
239 MaxAutomaticVersions json.Number
240
241 // HardwareApproval says whether an approval of a change must be signed
242 // with a key the identity registry enrolled as a hardware key
243 // (approval.hardware). It selects which keys may sign an approval. It
244 // does not decide whether a change needs one. A policy that leaves the
245 // field out does not require a hardware key.
246 HardwareApproval bool
247
248 // Digest is the SHA-256 of the whole export, so everything the policy
249 // composes is in it: every check, every class's paths, requirements and
250 // carry mode, the restacker's cap, and the hardware requirement.
251 Digest string
252}
253
254// Compose runs `cue export` of the composed policy over the schema, the
255// floor's documents and the project layer's documents, and reads it. The
256// template is the one the policy's `type` names, which the schema selects
257// as it composes.
258func Compose(ctx context.Context, cue, schema, instance, project string) (*Policy, error) {
259 docs, err := documents(schema, instance, project)
260 if err != nil {
261 return nil, err
262 }
263 pol, _, err := compose(ctx, cue, docs)
264 return pol, err
265}
266
267// compose exports `policy` over docs and reads the policy from it. It
268// returns the export too, for a reader that reads more of it.
269func compose(ctx context.Context, cue string, docs []string) (*Policy, []byte, error) {
270 out, err := export(ctx, cue, docs, "policy")
271 if err != nil {
272 return nil, nil, fmt.Errorf("composing the policy: %w", err)
273 }
274 if err := exported.check(out); err != nil {
275 return nil, nil, fmt.Errorf("reading the composed policy: %w", err)
276 }
277 var read struct {
278 Checks map[string]Check `json:"checks"`
279 Restack struct {
280 MaxAutomaticVersions json.Number `json:"maxAutomaticVersions"`
281 } `json:"restack"`
282 Approval struct {
283 Hardware bool `json:"hardware"`
284 } `json:"approval"`
285 }
286 if err := json.Unmarshal(out, &read); err != nil {
287 return nil, nil, fmt.Errorf("reading the composed policy: %w", err)
288 }
289 sum := sha256.Sum256(out)
290 return &Policy{
291 Checks: read.Checks,
292 MaxAutomaticVersions: read.Restack.MaxAutomaticVersions,
293 HardwareApproval: read.Approval.Hardware,
294 Digest: hex.EncodeToString(sum[:]),
295 }, out, nil
296}
297
298// shape is what the reader expects of one value of the export: its kind,
299// and for an object either the exact names of its fields or what every
300// entry of it holds.
301//
302// The export is checked against it before it is decoded, because
303// encoding/json matches a field's name without regard to case and keeps
304// the last match. Any document of the policy may reopen a schema definition,
305// since they are all in one package. A project can therefore add
306// `Hardware: false` beside the floor's `hardware: true`, and cue exports
307// both keys. encoding/json would read whichever of the two comes last. So
308// an object read into a struct must hold the names the schema gives it,
309// exactly, and nothing else.
310type shape struct {
311 kind string // "object", "string", "number" or "bool"
312 fields map[string]shape // the fields of an object read into a struct
313 each *shape // every entry of an object read into a map
314}
315
316var (
317 text = shape{kind: "string"}
318 number = shape{kind: "number"}
319 flag = shape{kind: "bool"}
320 set = shape{kind: "object", each: &flag}
321
322 // exported is the composed policy as schema/verification.cue exports
323 // it. Read reads `classes` and `unclassified` out of the same export.
324 exported = shape{kind: "object", fields: map[string]shape{
325 "checks": {kind: "object", each: &shape{kind: "object", fields: map[string]shape{
326 "runner": text, "attribute": text, "command": text, "validity": text, "cost": text,
327 }}},
328 "classes": {kind: "object", each: &shape{kind: "object", fields: map[string]shape{
329 "paths": set, "requires": set, "follows": set, "carry": set,
330 }}},
331 "unclassified": set,
332 "restack": {kind: "object", fields: map[string]shape{"maxAutomaticVersions": number}},
333 "approval": {kind: "object", fields: map[string]shape{"hardware": flag}},
334 }}
335)
336
337// check reads data as one JSON value and holds it to s. A key that
338// appears twice in one object is refused first. Of two equal keys,
339// encoding/json keeps the second when it reads into an interface, and
340// merges the two when it reads into a map or a struct, so the value s holds
341// and the value the policy is read from could differ.
342func (s shape) check(data []byte) error {
343 dec := json.NewDecoder(bytes.NewReader(data))
344 dec.UseNumber()
345 if err := keysOnce(dec, "policy"); err != nil {
346 return err
347 }
348 dec = json.NewDecoder(bytes.NewReader(data))
349 dec.UseNumber()
350 var v any
351 if err := dec.Decode(&v); err != nil {
352 return err
353 }
354 return s.holds("policy", v)
355}
356
357// keysOnce reads one value from dec, found at path, and refuses an object
358// in it that holds a key twice.
359func keysOnce(dec *json.Decoder, path string) error {
360 tok, err := dec.Token()
361 if err != nil {
362 return err
363 }
364 switch tok {
365 case json.Delim('['):
366 for i := 0; dec.More(); i++ {
367 if err := keysOnce(dec, fmt.Sprintf("%s[%d]", path, i)); err != nil {
368 return err
369 }
370 }
371 case json.Delim('{'):
372 seen := map[string]bool{}
373 for dec.More() {
374 tok, err := dec.Token()
375 if err != nil {
376 return err
377 }
378 key := tok.(string)
379 if seen[key] {
380 return fmt.Errorf("%s holds the key %q twice", path, key)
381 }
382 seen[key] = true
383 if err := keysOnce(dec, path+"."+key); err != nil {
384 return err
385 }
386 }
387 default:
388 return nil
389 }
390 // The closing delimiter.
391 _, err = dec.Token()
392 return err
393}
394
395// holds says whether v, found at path, has the shape s.
396func (s shape) holds(path string, v any) error {
397 var ok bool
398 switch s.kind {
399 case "string":
400 _, ok = v.(string)
401 case "number":
402 _, ok = v.(json.Number)
403 case "bool":
404 _, ok = v.(bool)
405 case "object":
406 var obj map[string]any
407 if obj, ok = v.(map[string]any); !ok {
408 break
409 }
410 names := make([]string, 0, len(obj))
411 for name := range obj {
412 names = append(names, name)
413 }
414 sort.Strings(names)
415 for _, name := range names {
416 entry := s.each
417 if entry == nil {
418 field, known := s.fields[name]
419 if !known {
420 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)
421 }
422 entry = &field
423 }
424 if err := entry.holds(path+"."+name, obj[name]); err != nil {
425 return err
426 }
427 }
428 }
429 if !ok {
430 return fmt.Errorf("%s is not a %s", path, s.kind)
431 }
432 return nil
433}
434
435// documents is what a policy is composed from: the schema, then the
436// floor's documents and the project layer's (layer).
437func documents(schema, instance, project string) ([]string, error) {
438 docs := []string{schema}
439 for _, dir := range []string{instance, project} {
440 found, err := layer(dir)
441 if err != nil {
442 return nil, err
443 }
444 docs = append(docs, found...)
445 }
446 return docs, nil
447}
448
449// layer is the documents of one policy layer: the entries directly in dir
450// that bin/valley's `"$dir"/*.cue` names, in its order.
451//
452// dir is a name and never a pattern, as it is quoted there, so a directory
453// named policy[1] is that directory and not policy1. Its entries are
454// listed, and an entry is a document when its name ends in .cue and does
455// not begin with a dot, because bash's glob leaves a dotfile out. They are
456// sorted bytewise, as bash sorts them in the C locale bin/valley derives
457// in. The first must be a regular file, as bin/valley's `[ -f ]` asks, or
458// the layer holds no documents.
459func layer(dir string) ([]string, error) {
460 entries, err := os.ReadDir(dir)
461 if err != nil {
462 return nil, fmt.Errorf("no policy layer at %s: %w", dir, err)
463 }
464 var docs []string
465 for _, e := range entries {
466 if name := e.Name(); strings.HasSuffix(name, ".cue") && !strings.HasPrefix(name, ".") {
467 docs = append(docs, filepath.Join(dir, name))
468 }
469 }
470 if len(docs) == 0 {
471 return nil, fmt.Errorf("no policy layer at %s", dir)
472 }
473 if info, err := os.Stat(docs[0]); err != nil || !info.Mode().IsRegular() {
474 return nil, fmt.Errorf("no policy layer at %s: %s is not a file", dir, docs[0])
475 }
476 return docs, nil
477}
478
479// export runs `cue export` of one expression over docs and returns what
480// cue printed. A failure returns what cue said, so the caller can say what
481// it was doing.
482//
483// Its output and its diagnostics are read as one stream, and
484// Policy.Digest is of those bytes. Reading them apart would change every
485// digest with no change to any policy.
486func export(ctx context.Context, cue string, docs []string, expr string) ([]byte, error) {
487 args := append([]string{"export", "--out", "json", "-e", expr}, docs...)
488 cmd := command(ctx, cue, args...)
489 var combined bytes.Buffer
490 cmd.Stdout, cmd.Stderr = &combined, &combined
491 if err := cmd.Run(); err != nil {
492 return nil, fmt.Errorf("%w\n%s", err, strings.TrimSpace(combined.String()))
493 }
494 return combined.Bytes(), nil
495}
496
497// waitDelay is how long a wait for a program's output may go on after it
498// has exited, or after a done context has killed it. Something it started
499// that left its process group may still hold the output open.
500const waitDelay = 5 * time.Second
501
502// command is a program run under ctx in a process group of its own, which
503// a done context kills whole, with the wait for its output bounded.
504func command(ctx context.Context, name string, args ...string) *exec.Cmd {
505 cmd := exec.CommandContext(ctx, name, args...)
506 cmd.WaitDelay = waitDelay
507 ownGroup(cmd)
508 return cmd
509}
510
511func git(ctx context.Context, repo string, args ...string) (string, error) {
512 cmd := command(ctx, "git", args...)
513 cmd.Dir = repo
514 var out, errb bytes.Buffer
515 cmd.Stdout, cmd.Stderr = &out, &errb
516 if err := cmd.Run(); err != nil {
517 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
518 }
519 return out.String(), nil
520}
521
522// resolveRef reads the object ID that ref, a full ref name, holds in repo.
523// It reads that one ref, with git show-ref. ok is false when repo holds no
524// ref of that name. An error is a repository git could not read.
525//
526// git rev-parse, and every git command given a ref name, does not stop at
527// the name it is given. When repo holds no refs/heads/main, git goes on to
528// try other names, refs/heads/refs/heads/main among them, and a pusher can
529// make that branch.
530func resolveRef(ctx context.Context, repo, ref string) (oid string, ok bool, err error) {
531 // show-ref --exists exits 2 for a ref that is missing, and with
532 // another status for a failure to read.
533 _, err = git(ctx, repo, "show-ref", "--exists", "--end-of-options", ref)
534 var exit *exec.ExitError
535 if errors.As(err, &exit) && exit.ExitCode() == 2 {
536 return "", false, nil
537 } else if err != nil {
538 return "", false, err
539 }
540 out, err := git(ctx, repo, "show-ref", "--verify", "--hash", "--end-of-options", ref)
541 if err != nil {
542 return "", false, err
543 }
544 return strings.TrimSpace(out), true, nil
545}
546
547// scratch makes one throwaway directory under whatever TMPDIR names. The
548// error names the operation, the path, and where the path came from.
549func scratch(prefix string) (string, error) {
550 dir, err := os.MkdirTemp("", prefix)
551 if err != nil {
552 return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err)
553 }
554 return dir, nil
555}