gunk-dev/the-valley

composed.go

source8bf5a934d291main's published tip history
20.2 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// The directory is listed with a pathspec, taken literally, so a directory
158// named policy[1] is that directory and not policy1. A directory that is
159// not there is an empty listing, and a listing git could not read, of a
160// tree-ish or a tree object that is missing, is an error: read as absent,
161// a project layer nobody could read would compose as the floor alone,
162// requiring fewer checks from a read that never happened. Each *.cue entry
163// is read as a blob, so one that is a directory or a submodule is an error
164// too.
165//
166// A name beginning with a dot is copied, and counts toward a present
167// layer. The composer leaves it out (layer), so a layer holding dotfiles
168// alone is present, holds no document, and is refused when it is composed.
169//
170// The listing is NUL-separated, so every name is read as it is. A
171// newline-separated listing quotes a name with non-ASCII characters in it,
172// such as naïve.cue, and the quoted name does not end in .cue, so that
173// document would be skipped. A materialized floor's glob finds it, and so
174// does this.
175func readLayer(ctx context.Context, repo, treeish, dir, prefix string) (string, int, func(), error) {
176 noop := func() {}
177 listing, err := git(ctx, repo, "--literal-pathspecs", "ls-tree", "--full-tree", "--name-only", "-z", "--end-of-options", treeish, dir+"/")
178 if err != nil {
179 if ctx.Err() != nil {
180 err = ctx.Err()
181 }
182 return "", absent, noop, fmt.Errorf("reading %s/ from %s at %s: %w", dir, repo, treeish, err)
183 }
184 if listing == "" {
185 return "", absent, noop, nil
186 }
187 out, err := scratch(prefix)
188 if err != nil {
189 return "", absent, noop, err
190 }
191 done := func() { _ = os.RemoveAll(out) }
192 found := 0
193 for _, path := range strings.Split(strings.TrimSuffix(listing, "\x00"), "\x00") {
194 if !strings.HasSuffix(path, ".cue") {
195 continue
196 }
197 name := path[strings.LastIndexByte(path, '/')+1:]
198 body, err := git(ctx, repo, "cat-file", "blob", treeish+":"+path)
199 if err != nil {
200 done()
201 return "", absent, noop, fmt.Errorf("reading %s from %s at %s: %w", path, repo, treeish, err)
202 }
203 if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil {
204 done()
205 return "", absent, noop, err
206 }
207 found++
208 }
209 if found == 0 {
210 done()
211 return "", empty, noop, nil
212 }
213 return out, present, done, nil
214}
215
216// Check is one check as the composed policy defines it: how it is run, how
217// long an observation of it stays good, and what running it costs.
218type Check struct {
219 Runner string `json:"runner"` // nix or command
220 Attribute string `json:"attribute"` // the flake check attribute, for the nix runner
221 Command string `json:"command"` // the command line, for the command runner
222 Validity string `json:"validity"` // how long an observation stays good; "" for no window
223 Cost string `json:"cost"` // quick or slow
224}
225
226// Policy is the composed policy, as far as its readers read it.
227type Policy struct {
228 Checks map[string]Check
229
230 // MaxAutomaticVersions caps how many versions the restacker adds to
231 // one change over the change's life (restack.maxAutomaticVersions).
232 // It is kept as cue wrote it. The schema admits any whole number of at
233 // least 1, and a Go int holds only some of them, so decoding into an
234 // int would refuse policies the schema admits. The restacker converts
235 // it where it counts.
236 MaxAutomaticVersions json.Number
237
238 // HardwareApproval says whether an approval of a change must be signed
239 // with a key the identity registry enrolled as a hardware key
240 // (approval.hardware). It selects which keys may sign an approval. It
241 // does not decide whether a change needs one. A policy that leaves the
242 // field out does not require a hardware key.
243 HardwareApproval bool
244
245 // Digest is the SHA-256 of the whole export, so everything the policy
246 // composes is in it: every check, every class's paths, requirements and
247 // carry mode, the restacker's cap, and the hardware requirement.
248 Digest string
249}
250
251// Compose runs `cue export` of the composed policy over the schema, the
252// floor's documents and the project layer's documents, and reads it. The
253// template is the one the policy's `type` names, which the schema selects
254// as it composes.
255func Compose(ctx context.Context, cue, schema, instance, project string) (*Policy, error) {
256 docs, err := documents(schema, instance, project)
257 if err != nil {
258 return nil, err
259 }
260 pol, _, err := compose(ctx, cue, docs)
261 return pol, err
262}
263
264// compose exports `policy` over docs and reads the policy from it. It
265// returns the export too, for a reader that reads more of it.
266func compose(ctx context.Context, cue string, docs []string) (*Policy, []byte, error) {
267 out, err := export(ctx, cue, docs, "policy")
268 if err != nil {
269 return nil, nil, fmt.Errorf("composing the policy: %w", err)
270 }
271 if err := exported.check(out); err != nil {
272 return nil, nil, fmt.Errorf("reading the composed policy: %w", err)
273 }
274 var read struct {
275 Checks map[string]Check `json:"checks"`
276 Restack struct {
277 MaxAutomaticVersions json.Number `json:"maxAutomaticVersions"`
278 } `json:"restack"`
279 Approval struct {
280 Hardware bool `json:"hardware"`
281 } `json:"approval"`
282 }
283 if err := json.Unmarshal(out, &read); err != nil {
284 return nil, nil, fmt.Errorf("reading the composed policy: %w", err)
285 }
286 sum := sha256.Sum256(out)
287 return &Policy{
288 Checks: read.Checks,
289 MaxAutomaticVersions: read.Restack.MaxAutomaticVersions,
290 HardwareApproval: read.Approval.Hardware,
291 Digest: hex.EncodeToString(sum[:]),
292 }, out, nil
293}
294
295// shape is what the reader expects of one value of the export: its kind,
296// and for an object either the exact names of its fields or what every
297// entry of it holds.
298//
299// The export is checked against it before it is decoded, because
300// encoding/json matches a field's name without regard to case and keeps
301// the last match. Any document of the policy may reopen a schema definition,
302// since they are all in one package. A project can therefore add
303// `Hardware: false` beside the floor's `hardware: true`, and cue exports
304// both keys. encoding/json would read whichever of the two comes last. So
305// an object read into a struct must hold the names the schema gives it,
306// exactly, and nothing else.
307type shape struct {
308 kind string // "object", "string", "number" or "bool"
309 fields map[string]shape // the fields of an object read into a struct
310 each *shape // every entry of an object read into a map
311}
312
313var (
314 text = shape{kind: "string"}
315 number = shape{kind: "number"}
316 flag = shape{kind: "bool"}
317 set = shape{kind: "object", each: &flag}
318
319 // exported is the composed policy as schema/verification.cue exports
320 // it. Read reads `classes` and `unclassified` out of the same export.
321 exported = shape{kind: "object", fields: map[string]shape{
322 "checks": {kind: "object", each: &shape{kind: "object", fields: map[string]shape{
323 "runner": text, "attribute": text, "command": text, "validity": text, "cost": text,
324 }}},
325 "classes": {kind: "object", each: &shape{kind: "object", fields: map[string]shape{
326 "paths": set, "requires": set, "follows": set, "carry": set,
327 }}},
328 "unclassified": set,
329 "restack": {kind: "object", fields: map[string]shape{"maxAutomaticVersions": number}},
330 "approval": {kind: "object", fields: map[string]shape{"hardware": flag}},
331 }}
332)
333
334// check reads data as one JSON value and holds it to s. A key that
335// appears twice in one object is refused first. Of two equal keys,
336// encoding/json keeps the second when it reads into an interface, and
337// merges the two when it reads into a map or a struct, so the value s holds
338// and the value the policy is read from could differ.
339func (s shape) check(data []byte) error {
340 dec := json.NewDecoder(bytes.NewReader(data))
341 dec.UseNumber()
342 if err := keysOnce(dec, "policy"); err != nil {
343 return err
344 }
345 dec = json.NewDecoder(bytes.NewReader(data))
346 dec.UseNumber()
347 var v any
348 if err := dec.Decode(&v); err != nil {
349 return err
350 }
351 return s.holds("policy", v)
352}
353
354// keysOnce reads one value from dec, found at path, and refuses an object
355// in it that holds a key twice.
356func keysOnce(dec *json.Decoder, path string) error {
357 tok, err := dec.Token()
358 if err != nil {
359 return err
360 }
361 switch tok {
362 case json.Delim('['):
363 for i := 0; dec.More(); i++ {
364 if err := keysOnce(dec, fmt.Sprintf("%s[%d]", path, i)); err != nil {
365 return err
366 }
367 }
368 case json.Delim('{'):
369 seen := map[string]bool{}
370 for dec.More() {
371 tok, err := dec.Token()
372 if err != nil {
373 return err
374 }
375 key := tok.(string)
376 if seen[key] {
377 return fmt.Errorf("%s holds the key %q twice", path, key)
378 }
379 seen[key] = true
380 if err := keysOnce(dec, path+"."+key); err != nil {
381 return err
382 }
383 }
384 default:
385 return nil
386 }
387 // The closing delimiter.
388 _, err = dec.Token()
389 return err
390}
391
392// holds says whether v, found at path, has the shape s.
393func (s shape) holds(path string, v any) error {
394 var ok bool
395 switch s.kind {
396 case "string":
397 _, ok = v.(string)
398 case "number":
399 _, ok = v.(json.Number)
400 case "bool":
401 _, ok = v.(bool)
402 case "object":
403 var obj map[string]any
404 if obj, ok = v.(map[string]any); !ok {
405 break
406 }
407 names := make([]string, 0, len(obj))
408 for name := range obj {
409 names = append(names, name)
410 }
411 sort.Strings(names)
412 for _, name := range names {
413 entry := s.each
414 if entry == nil {
415 field, known := s.fields[name]
416 if !known {
417 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)
418 }
419 entry = &field
420 }
421 if err := entry.holds(path+"."+name, obj[name]); err != nil {
422 return err
423 }
424 }
425 }
426 if !ok {
427 return fmt.Errorf("%s is not a %s", path, s.kind)
428 }
429 return nil
430}
431
432// documents is what a policy is composed from: the schema, then the
433// floor's documents and the project layer's (layer).
434func documents(schema, instance, project string) ([]string, error) {
435 docs := []string{schema}
436 for _, dir := range []string{instance, project} {
437 found, err := layer(dir)
438 if err != nil {
439 return nil, err
440 }
441 docs = append(docs, found...)
442 }
443 return docs, nil
444}
445
446// layer is the documents of one policy layer: the *.cue entries directly
447// in dir, sorted bytewise.
448//
449// dir is a name and never a pattern, so a directory named policy[1] is
450// that directory and not policy1. Its entries are listed, and an entry is
451// a document when its name ends in .cue and does not begin with a dot. The
452// first must be a regular file, or the layer holds no documents.
453func layer(dir string) ([]string, error) {
454 entries, err := os.ReadDir(dir)
455 if err != nil {
456 return nil, fmt.Errorf("no policy layer at %s: %w", dir, err)
457 }
458 var docs []string
459 for _, e := range entries {
460 if name := e.Name(); strings.HasSuffix(name, ".cue") && !strings.HasPrefix(name, ".") {
461 docs = append(docs, filepath.Join(dir, name))
462 }
463 }
464 if len(docs) == 0 {
465 return nil, fmt.Errorf("no policy layer at %s", dir)
466 }
467 if info, err := os.Stat(docs[0]); err != nil || !info.Mode().IsRegular() {
468 return nil, fmt.Errorf("no policy layer at %s: %s is not a file", dir, docs[0])
469 }
470 return docs, nil
471}
472
473// export runs `cue export` of one expression over docs and returns what
474// cue printed. A failure returns what cue said, so the caller can say what
475// it was doing.
476//
477// Its output and its diagnostics are read as one stream, and
478// Policy.Digest is of those bytes. Reading them apart would change every
479// digest with no change to any policy.
480func export(ctx context.Context, cue string, docs []string, expr string) ([]byte, error) {
481 args := append([]string{"export", "--out", "json", "-e", expr}, docs...)
482 cmd := command(ctx, cue, args...)
483 var combined bytes.Buffer
484 cmd.Stdout, cmd.Stderr = &combined, &combined
485 if err := cmd.Run(); err != nil {
486 return nil, fmt.Errorf("%w\n%s", err, strings.TrimSpace(combined.String()))
487 }
488 return combined.Bytes(), nil
489}
490
491// waitDelay is how long a wait for a program's output may go on after it
492// has exited, or after a done context has killed it. Something it started
493// that left its process group may still hold the output open.
494const waitDelay = 5 * time.Second
495
496// command is a program run under ctx in a process group of its own, which
497// a done context kills whole, with the wait for its output bounded.
498func command(ctx context.Context, name string, args ...string) *exec.Cmd {
499 cmd := exec.CommandContext(ctx, name, args...)
500 cmd.WaitDelay = waitDelay
501 ownGroup(cmd)
502 return cmd
503}
504
505func git(ctx context.Context, repo string, args ...string) (string, error) {
506 cmd := command(ctx, "git", args...)
507 cmd.Dir = repo
508 var out, errb bytes.Buffer
509 cmd.Stdout, cmd.Stderr = &out, &errb
510 if err := cmd.Run(); err != nil {
511 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
512 }
513 return out.String(), nil
514}
515
516// resolveRef reads the object ID that ref, a full ref name, holds in repo.
517// It reads that one ref, with git show-ref. ok is false when repo holds no
518// ref of that name. An error is a repository git could not read.
519//
520// git rev-parse, and every git command given a ref name, does not stop at
521// the name it is given. When repo holds no refs/heads/main, git goes on to
522// try other names, refs/heads/refs/heads/main among them, and a pusher can
523// make that branch.
524func resolveRef(ctx context.Context, repo, ref string) (oid string, ok bool, err error) {
525 // show-ref --exists exits 2 for a ref that is missing, and with
526 // another status for a failure to read.
527 _, err = git(ctx, repo, "show-ref", "--exists", "--end-of-options", ref)
528 var exit *exec.ExitError
529 if errors.As(err, &exit) && exit.ExitCode() == 2 {
530 return "", false, nil
531 } else if err != nil {
532 return "", false, err
533 }
534 out, err := git(ctx, repo, "show-ref", "--verify", "--hash", "--end-of-options", ref)
535 if err != nil {
536 return "", false, err
537 }
538 return strings.TrimSpace(out), true, nil
539}
540
541// scratch makes one throwaway directory under whatever TMPDIR names. The
542// error names the operation, the path, and where the path came from.
543func scratch(prefix string) (string, error) {
544 dir, err := os.MkdirTemp("", prefix)
545 if err != nil {
546 return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err)
547 }
548 return dir, nil
549}