gunk-dev/the-valley

composed.go

source9d8f53c82aaemain's published tip history
8.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// 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.
119func readLayer(repo, treeish, dir, prefix string) (string, int, func(), error) {
120 noop := func() {}
121 tree := treeish + ":" + dir
122 listing, err := git(repo, "ls-tree", "--name-only", "-z", tree)
123 if err != nil {
124 return "", absent, noop, nil
125 }
126 out, err := scratch(prefix)
127 if err != nil {
128 return "", absent, noop, err
129 }
130 done := func() { _ = os.RemoveAll(out) }
131 found := 0
132 for _, name := range strings.Split(listing, "\x00") {
133 if !strings.HasSuffix(name, ".cue") {
134 continue
135 }
136 body, err := git(repo, "cat-file", "blob", tree+"/"+name)
137 if err != nil {
138 done()
139 return "", absent, noop, fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, treeish, err)
140 }
141 if err := os.WriteFile(filepath.Join(out, name), []byte(body), 0o644); err != nil {
142 done()
143 return "", absent, noop, err
144 }
145 found++
146 }
147 if found == 0 {
148 done()
149 return "", empty, noop, nil
150 }
151 return out, present, done, nil
152}
153
154// Check is one check as the composed policy defines it: how it is run, and
155// how long an observation of it stays good.
156type Check struct {
157 Runner string `json:"runner"`
158 Attribute string `json:"attribute"`
159 Command string `json:"command"`
160 Validity string `json:"validity"`
161}
162
163// Policy is the composed policy, as far as its readers read it.
164type Policy struct {
165 Checks map[string]Check
166
167 // MaxAutomaticVersions caps how many versions the restacker adds to
168 // one change over the change's life (restack.maxAutomaticVersions).
169 MaxAutomaticVersions int
170
171 // Digest is the SHA-256 of the whole export, so everything the policy
172 // composes is in it: every check, every class's paths, requirements and
173 // carry mode, and the restacker's cap.
174 Digest string
175}
176
177// Compose runs `cue export` of the composed policy over the schema, the
178// floor's documents and the project layer's documents, and reads it. The
179// template is the one the policy's `type` names, which the schema selects
180// as it composes.
181func Compose(cue, schema, instance, project string) (*Policy, error) {
182 args := []string{"export", "--out", "json", "-e", "policy", schema}
183 for _, dir := range []string{instance, project} {
184 docs, err := filepath.Glob(filepath.Join(dir, "*.cue"))
185 if err != nil || len(docs) == 0 {
186 return nil, fmt.Errorf("no policy layer at %s", dir)
187 }
188 args = append(args, docs...)
189 }
190 out, err := exec.Command(cue, args...).CombinedOutput()
191 if err != nil {
192 return nil, fmt.Errorf("composing the policy: %w\n%s", err, strings.TrimSpace(string(out)))
193 }
194 var read struct {
195 Checks map[string]Check `json:"checks"`
196 Restack struct {
197 MaxAutomaticVersions int `json:"maxAutomaticVersions"`
198 } `json:"restack"`
199 }
200 if err := json.Unmarshal(out, &read); err != nil {
201 return nil, fmt.Errorf("reading the composed policy: %w", err)
202 }
203 sum := sha256.Sum256(out)
204 return &Policy{
205 Checks: read.Checks,
206 MaxAutomaticVersions: read.Restack.MaxAutomaticVersions,
207 Digest: hex.EncodeToString(sum[:]),
208 }, nil
209}
210
211func git(repo string, args ...string) (string, error) {
212 cmd := exec.Command("git", args...)
213 cmd.Dir = repo
214 var out, errb bytes.Buffer
215 cmd.Stdout, cmd.Stderr = &out, &errb
216 if err := cmd.Run(); err != nil {
217 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
218 }
219 return out.String(), nil
220}
221
222// scratch makes one throwaway directory under whatever TMPDIR names. The
223// error names the operation, the path, and where the path came from.
224func scratch(prefix string) (string, error) {
225 dir, err := os.MkdirTemp("", prefix)
226 if err != nil {
227 return "", fmt.Errorf("creating a scratch directory under %s, which TMPDIR names: %w", os.TempDir(), err)
228 }
229 return dir, nil
230}