gunk-dev/the-valley

composed.go

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