gunk-dev/the-valley

composed.go

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