gunk-dev/the-valley

composed.go

source1c34f8c82a43main's published tip history
13.3 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 "fmt"
33 "os"
34 "os/exec"
35 "path/filepath"
36 "strings"
37 "time"
38)
39
40// Floor is where the group's floor comes from: a repository's tip, read
41// with ls-tree and show and never written, or else a directory on disk.
42type Floor struct {
43 Repo string // the repository carrying the floor; "" when Path is set
44 Ref string // the ref whose tip is authoritative
45 Dir string // the floor's directory in that tip's tree
46 Path string // a materialized layer, when no repository carries one
47}
48
49// Floorless ends every refusal to find a floor. The floor is the minimum,
50// and a missing minimum reads equally as a reader pointed at the wrong
51// directory, a repository nobody seeded, or a floor somebody deleted. What
52// is refused is the absent document; a floor that states it requires
53// nothing composes like any other.
54const Floorless = "a valley without a written floor is not a valley whose changes land"
55
56// Open resolves the floor to a directory of *.cue on disk, and returns
57// what removes it. A floor read from a repository is copied into a
58// scratch directory whose name starts with prefix.
59func (f Floor) Open(ctx context.Context, prefix string) (string, func(), error) {
60 noop := func() {}
61 if f.Repo == "" {
62 // The materialized layer is held to the same minimum as the one a
63 // repository carries: a directory with no documents in it is a floor
64 // nobody wrote.
65 if _, err := layer(f.Path); err != nil {
66 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", f.Path, Floorless)
67 }
68 return f.Path, noop, nil
69 }
70 dir, found, done, err := readLayer(ctx, f.Repo, f.Ref, f.Dir, prefix)
71 switch {
72 case err != nil:
73 return "", noop, err
74 case found == absent:
75 return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless)
76 case found == empty:
77 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless)
78 }
79 return dir, done, nil
80}
81
82// Project resolves the project's own layer at a tree-ish of a repository
83// to a directory of *.cue on disk, and returns what removes it, and a note
84// when the layer is absent.
85//
86// A target that carries no layer of its own is composed under the floor
87// alone. The project layer only ever adds, and the identity of "adds" is
88// "adds nothing", so that is what absence means. Absence is answered with
89// a document that adds nothing rather than with an argument left off,
90// because cue is handed a directory of *.cue and has no spelling for "no
91// layer".
92func Project(ctx context.Context, repo, treeish, dir, prefix string) (string, string, func(), error) {
93 path, found, done, err := readLayer(ctx, repo, treeish, dir, prefix)
94 if err != nil {
95 return "", "", func() {}, err
96 }
97 if found == present {
98 return path, "", done, nil
99 }
100 done()
101 path, done, err = AddsNothing(prefix)
102 return path, fmt.Sprintf("no project layer at %s; the floor alone", dir), done, err
103}
104
105// AddsNothing writes a project layer that adds nothing into a scratch
106// directory: a package clause and nothing else, so `project` stays what
107// the schema leaves it.
108func AddsNothing(prefix string) (string, func(), error) {
109 dir, err := scratch(prefix)
110 if err != nil {
111 return "", func() {}, err
112 }
113 done := func() { _ = os.RemoveAll(dir) }
114 if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil {
115 done()
116 return "", func() {}, err
117 }
118 return dir, done, nil
119}
120
121// What readLayer found at a directory of a tree.
122const (
123 present = iota // the directory, with *.cue in it
124 absent // no such directory
125 empty // the directory, with no *.cue in it
126)
127
128// readLayer copies the *.cue documents directly in one directory of a
129// tree-ish out of a repository, into a scratch directory. The deriver and
130// cue both read a layer as those documents, so they are what is taken.
131// The scratch directory is removed unless the layer is present.
132//
133// The listing is NUL-separated, so every name is read as it is. A
134// newline-separated listing quotes a name with non-ASCII characters in it,
135// such as naïve.cue, and the quoted name does not end in .cue, so that
136// document would be skipped. A materialized floor's glob finds it, and so
137// does this.
138func readLayer(ctx context.Context, repo, treeish, dir, prefix string) (string, int, func(), error) {
139 noop := func() {}
140 tree := treeish + ":" + dir
141 listing, err := git(ctx, repo, "ls-tree", "--name-only", "-z", tree)
142 if err != nil {
143 if ctx.Err() != nil {
144 return "", absent, noop, fmt.Errorf("reading %s from %s at %s: %w", dir, repo, treeish, ctx.Err())
145 }
146 return "", absent, noop, nil
147 }
148 out, err := scratch(prefix)
149 if err != nil {
150 return "", absent, noop, err
151 }
152 done := func() { _ = os.RemoveAll(out) }
153 found := 0
154 for _, name := range strings.Split(listing, "\x00") {
155 if !strings.HasSuffix(name, ".cue") {
156 continue
157 }
158 body, err := git(ctx, repo, "show", tree+"/"+name)
159 if err != nil {
160 done()
161 return "", absent, noop, fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, treeish, err)
162 }
163 if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil {
164 done()
165 return "", absent, noop, err
166 }
167 found++
168 }
169 if found == 0 {
170 done()
171 return "", empty, noop, nil
172 }
173 return out, present, done, nil
174}
175
176// Check is one check as the composed policy defines it: how it is run, how
177// long an observation of it stays good, and what running it costs.
178type Check struct {
179 Runner string `json:"runner"` // nix or command
180 Attribute string `json:"attribute"` // the flake check attribute, for the nix runner
181 Command string `json:"command"` // the command line, for the command runner
182 Validity string `json:"validity"` // how long an observation stays good; "" for no window
183 Cost string `json:"cost"` // quick or slow
184}
185
186// Policy is the composed policy, as far as its readers read it.
187type Policy struct {
188 Checks map[string]Check
189
190 // MaxAutomaticVersions caps how many versions the restacker adds to
191 // one change over the change's life (restack.maxAutomaticVersions).
192 // It is kept as cue wrote it. The schema admits any whole number of at
193 // least 1, and a Go int holds only some of them, so decoding into an
194 // int would refuse policies the schema admits. The restacker converts
195 // it where it counts.
196 MaxAutomaticVersions json.Number
197
198 // HardwareApproval says whether an approval of a change must be signed
199 // with a key the identity registry enrolled as a hardware key
200 // (approval.hardware). It selects which keys may sign an approval. It
201 // does not decide whether a change needs one. A policy that leaves the
202 // field out does not require a hardware key.
203 HardwareApproval bool
204
205 // Digest is the SHA-256 of the whole export, so everything the policy
206 // composes is in it: every check, every class's paths, requirements and
207 // carry mode, the restacker's cap, and the hardware requirement.
208 Digest string
209}
210
211// Compose runs `cue export` of the composed policy over the schema, the
212// floor's documents and the project layer's documents, and reads it. The
213// template is the one the policy's `type` names, which the schema selects
214// as it composes.
215func Compose(ctx context.Context, cue, schema, instance, project string) (*Policy, error) {
216 docs, err := documents(schema, instance, project)
217 if err != nil {
218 return nil, err
219 }
220 pol, _, err := compose(ctx, cue, docs)
221 return pol, err
222}
223
224// compose exports `policy` over docs and reads the policy from it. It
225// returns the export too, for a reader that reads more of it.
226func compose(ctx context.Context, cue string, docs []string) (*Policy, []byte, error) {
227 out, err := export(ctx, cue, docs, "policy")
228 if err != nil {
229 return nil, nil, fmt.Errorf("composing the policy: %w", err)
230 }
231 var read struct {
232 Checks map[string]Check `json:"checks"`
233 Restack struct {
234 MaxAutomaticVersions json.Number `json:"maxAutomaticVersions"`
235 } `json:"restack"`
236 Approval struct {
237 Hardware bool `json:"hardware"`
238 } `json:"approval"`
239 }
240 if err := json.Unmarshal(out, &read); err != nil {
241 return nil, nil, fmt.Errorf("reading the composed policy: %w", err)
242 }
243 sum := sha256.Sum256(out)
244 return &Policy{
245 Checks: read.Checks,
246 MaxAutomaticVersions: read.Restack.MaxAutomaticVersions,
247 HardwareApproval: read.Approval.Hardware,
248 Digest: hex.EncodeToString(sum[:]),
249 }, out, nil
250}
251
252// documents is what a policy is composed from: the schema, then the
253// floor's documents and the project layer's (layer).
254func documents(schema, instance, project string) ([]string, error) {
255 docs := []string{schema}
256 for _, dir := range []string{instance, project} {
257 found, err := layer(dir)
258 if err != nil {
259 return nil, err
260 }
261 docs = append(docs, found...)
262 }
263 return docs, nil
264}
265
266// layer is the documents of one policy layer: the entries directly in dir
267// that bin/valley's `"$dir"/*.cue` names, in its order.
268//
269// dir is a name and never a pattern, as it is quoted there, so a directory
270// named policy[1] is that directory and not policy1. Its entries are
271// listed, and an entry is a document when its name ends in .cue and does
272// not begin with a dot, because bash's glob leaves a dotfile out. They are
273// sorted bytewise, as bash sorts them in the C locale bin/valley derives
274// in. The first must be a regular file, as bin/valley's `[ -f ]` asks, or
275// the layer holds no documents.
276func layer(dir string) ([]string, error) {
277 entries, err := os.ReadDir(dir)
278 if err != nil {
279 return nil, fmt.Errorf("no policy layer at %s: %w", dir, err)
280 }
281 var docs []string
282 for _, e := range entries {
283 if name := e.Name(); strings.HasSuffix(name, ".cue") && !strings.HasPrefix(name, ".") {
284 docs = append(docs, filepath.Join(dir, name))
285 }
286 }
287 if len(docs) == 0 {
288 return nil, fmt.Errorf("no policy layer at %s", dir)
289 }
290 if info, err := os.Stat(docs[0]); err != nil || !info.Mode().IsRegular() {
291 return nil, fmt.Errorf("no policy layer at %s: %s is not a file", dir, docs[0])
292 }
293 return docs, nil
294}
295
296// export runs `cue export` of one expression over docs and returns what
297// cue printed. A failure returns what cue said, so the caller can say what
298// it was doing.
299//
300// Its output and its diagnostics are read as one stream, and
301// Policy.Digest is of those bytes. Reading them apart would change every
302// digest with no change to any policy.
303func export(ctx context.Context, cue string, docs []string, expr string) ([]byte, error) {
304 args := append([]string{"export", "--out", "json", "-e", expr}, docs...)
305 cmd := command(ctx, cue, args...)
306 var combined bytes.Buffer
307 cmd.Stdout, cmd.Stderr = &combined, &combined
308 if err := cmd.Run(); err != nil {
309 return nil, fmt.Errorf("%w\n%s", err, strings.TrimSpace(combined.String()))
310 }
311 return combined.Bytes(), nil
312}
313
314// waitDelay is how long a wait for a program's output may go on after it
315// has exited, or after a done context has killed it. Something it started
316// that left its process group may still hold the output open.
317const waitDelay = 5 * time.Second
318
319// command is a program run under ctx in a process group of its own, which
320// a done context kills whole, with the wait for its output bounded.
321func command(ctx context.Context, name string, args ...string) *exec.Cmd {
322 cmd := exec.CommandContext(ctx, name, args...)
323 cmd.WaitDelay = waitDelay
324 ownGroup(cmd)
325 return cmd
326}
327
328func git(ctx context.Context, repo string, args ...string) (string, error) {
329 cmd := command(ctx, "git", args...)
330 cmd.Dir = repo
331 var out, errb bytes.Buffer
332 cmd.Stdout, cmd.Stderr = &out, &errb
333 if err := cmd.Run(); err != nil {
334 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
335 }
336 return out.String(), nil
337}
338
339// scratch makes one throwaway directory under whatever TMPDIR names. The
340// error names the operation, the path, and where the path came from.
341func scratch(prefix string) (string, error) {
342 dir, err := os.MkdirTemp("", prefix)
343 if err != nil {
344 return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err)
345 }
346 return dir, nil
347}