gunk-dev/the-valley

composed.go

source61364523a8d7main's published tip history
8.8 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// The floor is read from the instance repository's tip, or from a
9// materialized directory for a host that serves no instance repository.
10// The project layer is read from the target tip. A layer that is not there
11// defaults in the safe direction of its job: an absent project layer
12// composes the floor alone, and an absent floor is refused.
13package composed
14
15import (
16 "bytes"
17 "crypto/sha256"
18 "encoding/hex"
19 "encoding/json"
20 "fmt"
21 "os"
22 "os/exec"
23 "path/filepath"
24 "strings"
25)
26
27// Floor is where the group's floor comes from: a repository's tip, read
28// with ls-tree and show and never written, or else a directory on disk.
29type Floor struct {
30 Repo string // the repository carrying the floor; "" when Path is set
31 Ref string // the ref whose tip is authoritative
32 Dir string // the floor's directory in that tip's tree
33 Path string // a materialized layer, when no repository carries one
34}
35
36// Floorless ends every refusal to find a floor. The floor is the minimum,
37// and a missing minimum reads equally as a reader pointed at the wrong
38// directory, a repository nobody seeded, or a floor somebody deleted. What
39// is refused is the absent document; a floor that states it requires
40// nothing composes like any other.
41const Floorless = "a valley without a written floor is not a valley whose changes land"
42
43// Open resolves the floor to a directory of *.cue on disk, and returns
44// what removes it. A floor read from a repository is copied into a
45// scratch directory whose name starts with prefix.
46func (f Floor) Open(prefix string) (string, func(), error) {
47 noop := func() {}
48 if f.Repo == "" {
49 // The materialized layer is held to the same minimum as the one a
50 // repository carries: a directory with no documents in it is a floor
51 // nobody wrote.
52 if docs, err := filepath.Glob(filepath.Join(f.Path, "*.cue")); err != nil || len(docs) == 0 {
53 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue: %s", f.Path, Floorless)
54 }
55 return f.Path, noop, nil
56 }
57 dir, found, done, err := readLayer(f.Repo, f.Ref, f.Dir, prefix)
58 switch {
59 case err != nil:
60 return "", noop, err
61 case found == absent:
62 return "", noop, fmt.Errorf("no instance policy layer: %s has no %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless)
63 case found == empty:
64 return "", noop, fmt.Errorf("no instance policy layer: %s holds no *.cue in %s/ at %s: %s", f.Repo, f.Dir, f.Ref, Floorless)
65 }
66 return dir, done, nil
67}
68
69// Project resolves the project's own layer at a tree-ish of a repository
70// to a directory of *.cue on disk, and returns what removes it, and a note
71// when the layer is absent.
72//
73// A target that carries no layer of its own is composed under the floor
74// alone. The project layer only ever adds, and the identity of "adds" is
75// "adds nothing", so that is what absence means. Absence is answered with
76// a document that adds nothing rather than with an argument left off,
77// because cue is handed a directory of *.cue and has no spelling for "no
78// layer".
79func Project(repo, treeish, dir, prefix string) (string, string, func(), error) {
80 path, found, done, err := readLayer(repo, treeish, dir, prefix)
81 if err != nil {
82 return "", "", func() {}, err
83 }
84 if found == present {
85 return path, "", done, nil
86 }
87 done()
88 path, done, err = AddsNothing(prefix)
89 return path, fmt.Sprintf("no project layer at %s; the floor alone", dir), done, err
90}
91
92// AddsNothing writes a project layer that adds nothing into a scratch
93// directory: a package clause and nothing else, so `project` stays what
94// the schema leaves it.
95func AddsNothing(prefix string) (string, func(), error) {
96 dir, err := scratch(prefix)
97 if err != nil {
98 return "", func() {}, err
99 }
100 done := func() { _ = os.RemoveAll(dir) }
101 if err := os.WriteFile(filepath.Join(dir, "adds-nothing.cue"), []byte("package verification\n"), 0o644); err != nil {
102 done()
103 return "", func() {}, err
104 }
105 return dir, done, nil
106}
107
108// What readLayer found at a directory of a tree.
109const (
110 present = iota // the directory, with *.cue in it
111 absent // no such directory
112 empty // the directory, with no *.cue in it
113)
114
115// readLayer copies the *.cue documents directly in one directory of a
116// tree-ish out of a repository, into a scratch directory. The deriver and
117// cue both read a layer as those documents, so they are what is taken.
118// The scratch directory is removed unless the layer is present.
119//
120// The listing is NUL-separated, so every name is read as it is. A
121// newline-separated listing quotes a name with non-ASCII characters in it,
122// such as naïve.cue, and the quoted name does not end in .cue, so that
123// document would be skipped. A materialized floor's glob finds it, and so
124// does this.
125func readLayer(repo, treeish, dir, prefix string) (string, int, func(), error) {
126 noop := func() {}
127 tree := treeish + ":" + dir
128 listing, err := git(repo, "ls-tree", "--name-only", "-z", tree)
129 if err != nil {
130 return "", absent, noop, nil
131 }
132 out, err := scratch(prefix)
133 if err != nil {
134 return "", absent, noop, err
135 }
136 done := func() { _ = os.RemoveAll(out) }
137 found := 0
138 for _, name := range strings.Split(listing, "\x00") {
139 if !strings.HasSuffix(name, ".cue") {
140 continue
141 }
142 body, err := git(repo, "show", tree+"/"+name)
143 if err != nil {
144 done()
145 return "", absent, noop, fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, treeish, err)
146 }
147 if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil {
148 done()
149 return "", absent, noop, err
150 }
151 found++
152 }
153 if found == 0 {
154 done()
155 return "", empty, noop, nil
156 }
157 return out, present, done, nil
158}
159
160// Check is one check as the composed policy defines it: how it is run, and
161// how long an observation of it stays good.
162type Check struct {
163 Runner string `json:"runner"`
164 Attribute string `json:"attribute"`
165 Command string `json:"command"`
166 Validity string `json:"validity"`
167}
168
169// Policy is the composed policy, as far as its readers read it.
170type Policy struct {
171 Checks map[string]Check
172
173 // MaxAutomaticVersions caps how many versions the restacker adds to
174 // one change over the change's life (restack.maxAutomaticVersions).
175 // It is kept as cue wrote it. The schema admits any whole number of at
176 // least 1, and a Go int holds only some of them, so decoding into an
177 // int would refuse policies the schema admits. The restacker converts
178 // it where it counts.
179 MaxAutomaticVersions json.Number
180
181 // Digest is the SHA-256 of the whole export, so everything the policy
182 // composes is in it: every check, every class's paths, requirements and
183 // carry mode, and the restacker's cap.
184 Digest string
185}
186
187// Compose runs `cue export` of the composed policy over the schema, the
188// floor's documents and the project layer's documents, and reads it. The
189// template is the one the policy's `type` names, which the schema selects
190// as it composes.
191func Compose(cue, schema, instance, project string) (*Policy, error) {
192 args := []string{"export", "--out", "json", "-e", "policy", schema}
193 for _, dir := range []string{instance, project} {
194 docs, err := filepath.Glob(filepath.Join(dir, "*.cue"))
195 if err != nil || len(docs) == 0 {
196 return nil, fmt.Errorf("no policy layer at %s", dir)
197 }
198 args = append(args, docs...)
199 }
200 out, err := exec.Command(cue, args...).CombinedOutput()
201 if err != nil {
202 return nil, fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out)))
203 }
204 var read struct {
205 Checks map[string]Check `json:"checks"`
206 Restack struct {
207 MaxAutomaticVersions json.Number `json:"maxAutomaticVersions"`
208 } `json:"restack"`
209 }
210 if err := json.Unmarshal(out, &read); err != nil {
211 return nil, fmt.Errorf("reading the composed policy: %w", err)
212 }
213 sum := sha256.Sum256(out)
214 return &Policy{
215 Checks: read.Checks,
216 MaxAutomaticVersions: read.Restack.MaxAutomaticVersions,
217 Digest: hex.EncodeToString(sum[:]),
218 }, nil
219}
220
221func git(repo string, args ...string) (string, error) {
222 cmd := exec.Command("git", args...)
223 cmd.Dir = repo
224 var out, errb bytes.Buffer
225 cmd.Stdout, cmd.Stderr = &out, &errb
226 if err := cmd.Run(); err != nil {
227 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
228 }
229 return out.String(), nil
230}
231
232// scratch makes one throwaway directory under whatever TMPDIR names. The
233// error names the operation, the path, and where the path came from.
234func scratch(prefix string) (string, error) {
235 dir, err := os.MkdirTemp("", prefix)
236 if err != nil {
237 return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err)
238 }
239 return dir, nil
240}