gunk-dev/the-valley

composed.go

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