| 1 | package derive |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | "the-valley/composed" |
| 15 | ) |
| 16 | |
| 17 | // The tests beside this file share this: the rig the deriver runs in, the |
| 18 | // policies on disk it reads, and the scratch repositories it derives over. |
| 19 | |
| 20 | // rig is what the deriver needs: the schema, cue, and an environment of the |
| 21 | // test's own for git, with no configuration of the person running it. |
| 22 | type rig struct { |
| 23 | root, schema, cue string |
| 24 | env []string |
| 25 | } |
| 26 | |
| 27 | func newRig(t *testing.T) *rig { |
| 28 | t.Helper() |
| 29 | for _, tool := range []string{"git", "cue"} { |
| 30 | if _, err := exec.LookPath(tool); err != nil { |
| 31 | if os.Getenv("VALLEY_TEST_TOOLS") == "required" { |
| 32 | t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", tool) |
| 33 | } |
| 34 | t.Skipf("no %s to derive with; the derive-unit check provides one", tool) |
| 35 | } |
| 36 | } |
| 37 | root, err := filepath.Abs("..") |
| 38 | if err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | cue, _ := exec.LookPath("cue") |
| 42 | r := &rig{root: root, schema: filepath.Join(root, "schema", "verification.cue"), cue: cue} |
| 43 | if _, err := os.Stat(r.schema); err != nil { |
| 44 | t.Fatalf("the tests read %s, and it is not there: %v", r.schema, err) |
| 45 | } |
| 46 | r.env = []string{ |
| 47 | "PATH=" + os.Getenv("PATH"), |
| 48 | "HOME=" + t.TempDir(), |
| 49 | "TMPDIR=" + os.TempDir(), |
| 50 | "GIT_CONFIG_NOSYSTEM=1", |
| 51 | "GIT_AUTHOR_NAME=derive-test", "GIT_AUTHOR_EMAIL=derive-test@localhost", |
| 52 | "GIT_COMMITTER_NAME=derive-test", "GIT_COMMITTER_EMAIL=derive-test@localhost", |
| 53 | "GIT_AUTHOR_DATE=2026-10-21T00:00:00Z", "GIT_COMMITTER_DATE=2026-10-21T00:00:00Z", |
| 54 | } |
| 55 | return r |
| 56 | } |
| 57 | |
| 58 | // path is a file of the repository the tests run in. |
| 59 | func (r *rig) path(rel string) string { return filepath.Join(r.root, rel) } |
| 60 | |
| 61 | // glob is every file of the repository a pattern names, sorted. |
| 62 | func (r *rig) glob(t *testing.T, pattern string) []string { |
| 63 | t.Helper() |
| 64 | found, err := filepath.Glob(r.path(pattern)) |
| 65 | if err != nil || len(found) == 0 { |
| 66 | t.Fatalf("no file matches %s", pattern) |
| 67 | } |
| 68 | return found |
| 69 | } |
| 70 | |
| 71 | // layers is a policy on disk: the floor's directory and the project |
| 72 | // layer's. |
| 73 | type layers struct{ instance, project string } |
| 74 | |
| 75 | // naming is what a policy's layer directories are called, and the decoys |
| 76 | // beside them: directories a reader taking a layer's name as a pattern |
| 77 | // would read instead of it, or as well. |
| 78 | type naming struct { |
| 79 | instance, project string |
| 80 | decoys []string |
| 81 | } |
| 82 | |
| 83 | // namings are the layer directories the tests rotate through: plain names, |
| 84 | // and names a glob reads as patterns. |
| 85 | var namings = []naming{ |
| 86 | {"instance", "project", nil}, |
| 87 | {"floor[1]", "proj*", []string{"floor1", "projX"}}, |
| 88 | {`fl\oor?`, "pro ject[a-z]", []string{"floorX", "pro jectq"}}, |
| 89 | } |
| 90 | |
| 91 | // notCUE is what every decoy and dotfile document holds, so a reader that |
| 92 | // composes one of them fails. |
| 93 | const notCUE = "package verification\nthis is not CUE, and no layer holds it\n" |
| 94 | |
| 95 | // newLayers copies the floor's documents and the project's into |
| 96 | // directories of their own, and writes extra, by name, beside the |
| 97 | // project's. A project with no documents is one that adds nothing. |
| 98 | func newLayers(t *testing.T, instance, project []string, extra map[string]string) layers { |
| 99 | t.Helper() |
| 100 | return newLayersAt(t, namings[0], instance, project, extra) |
| 101 | } |
| 102 | |
| 103 | // newLayersAt is newLayers with the directories named as n names them. Each |
| 104 | // directory also holds a dotfile, .shadow.cue, and each decoy a document, |
| 105 | // decoy.cue, neither of them CUE: neither is a document of the policy. |
| 106 | func newLayersAt(t *testing.T, n naming, instance, project []string, extra map[string]string) layers { |
| 107 | t.Helper() |
| 108 | dir := t.TempDir() |
| 109 | l := layers{instance: filepath.Join(dir, n.instance), project: filepath.Join(dir, n.project)} |
| 110 | for _, d := range []string{l.instance, l.project} { |
| 111 | if err := os.Mkdir(d, 0o755); err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | if err := os.WriteFile(filepath.Join(d, ".shadow.cue"), []byte(notCUE), 0o644); err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | } |
| 118 | for _, decoy := range n.decoys { |
| 119 | d := filepath.Join(dir, decoy) |
| 120 | if err := os.Mkdir(d, 0o755); err != nil { |
| 121 | t.Fatal(err) |
| 122 | } |
| 123 | if err := os.WriteFile(filepath.Join(d, "decoy.cue"), []byte(notCUE), 0o644); err != nil { |
| 124 | t.Fatal(err) |
| 125 | } |
| 126 | } |
| 127 | copyTo := func(dest string, files []string) { |
| 128 | for _, f := range files { |
| 129 | body, err := os.ReadFile(f) |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | if err := os.WriteFile(filepath.Join(dest, filepath.Base(f)), body, 0o644); err != nil { |
| 134 | t.Fatal(err) |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | copyTo(l.instance, instance) |
| 139 | copyTo(l.project, project) |
| 140 | if len(project) == 0 && len(extra) == 0 { |
| 141 | extra = map[string]string{"adds-nothing.cue": "package verification\n"} |
| 142 | } |
| 143 | for name, body := range extra { |
| 144 | if err := os.WriteFile(filepath.Join(l.project, name), []byte(body), 0o644); err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | } |
| 148 | return l |
| 149 | } |
| 150 | |
| 151 | // read is composed.Read of the layers under the rig's schema. |
| 152 | func (r *rig) read(l layers) (*composed.Model, error) { |
| 153 | return composed.Read(context.Background(), r.cue, r.schema, l.instance, l.project) |
| 154 | } |
| 155 | |
| 156 | // derive is the deriver over two commits of the repository at dir: Diff, |
| 157 | // then Derive. env is added to the rig's environment. |
| 158 | func (r *rig) derive(m *composed.Model, dir, base, head string, env ...string) (*Result, error) { |
| 159 | paths, err := Diff(context.Background(), dir, append(append([]string{}, r.env...), env...), base, head) |
| 160 | if err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | return Derive(m, paths) |
| 164 | } |
| 165 | |
| 166 | func sameSet(a, b []string) bool { |
| 167 | a, b = sortedSet(a), sortedSet(b) |
| 168 | if len(a) != len(b) { |
| 169 | return false |
| 170 | } |
| 171 | for i := range a { |
| 172 | if a[i] != b[i] { |
| 173 | return false |
| 174 | } |
| 175 | } |
| 176 | return true |
| 177 | } |
| 178 | |
| 179 | // names are the required checks' names, sorted. |
| 180 | func names(res *Result) []string { |
| 181 | var out []string |
| 182 | for _, q := range res.Required { |
| 183 | out = append(out, q.Name) |
| 184 | } |
| 185 | return out |
| 186 | } |
| 187 | |
| 188 | // entry is one file of a scratch tree: its mode and its content, which |
| 189 | // for a symbolic link is its target. |
| 190 | type entry struct{ mode, content string } |
| 191 | |
| 192 | // tree is a scratch commit's files, by path. |
| 193 | type tree map[string]entry |
| 194 | |
| 195 | // repo is a scratch repository whose commits are written straight into |
| 196 | // its object store, so a path may hold any byte a git path may, whatever |
| 197 | // the file system makes of it. |
| 198 | type repo struct { |
| 199 | t *testing.T |
| 200 | dir string |
| 201 | env []string |
| 202 | blobs map[string]string |
| 203 | n int |
| 204 | } |
| 205 | |
| 206 | func newRepo(t *testing.T, r *rig) *repo { |
| 207 | t.Helper() |
| 208 | rp := &repo{t: t, dir: t.TempDir(), env: r.env, blobs: map[string]string{}} |
| 209 | rp.git(nil, "init", "--quiet", "--initial-branch=main") |
| 210 | return rp |
| 211 | } |
| 212 | |
| 213 | func (rp *repo) git(stdin []byte, args ...string) string { |
| 214 | rp.t.Helper() |
| 215 | return rp.gitEnv(nil, stdin, args...) |
| 216 | } |
| 217 | |
| 218 | func (rp *repo) gitEnv(env []string, stdin []byte, args ...string) string { |
| 219 | rp.t.Helper() |
| 220 | cmd := exec.Command("git", args...) |
| 221 | cmd.Dir = rp.dir |
| 222 | cmd.Env = append(append([]string{}, rp.env...), env...) |
| 223 | cmd.Stdin = bytes.NewReader(stdin) |
| 224 | var stdout, stderr bytes.Buffer |
| 225 | cmd.Stdout, cmd.Stderr = &stdout, &stderr |
| 226 | if err := cmd.Run(); err != nil { |
| 227 | rp.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, stderr.String()) |
| 228 | } |
| 229 | return strings.TrimSpace(stdout.String()) |
| 230 | } |
| 231 | |
| 232 | // commit writes files as one commit on parent, which may be "", and |
| 233 | // returns it. |
| 234 | func (rp *repo) commit(parent string, files tree) string { |
| 235 | rp.t.Helper() |
| 236 | var info bytes.Buffer |
| 237 | paths := make([]string, 0, len(files)) |
| 238 | for p := range files { |
| 239 | paths = append(paths, p) |
| 240 | } |
| 241 | sort.Strings(paths) |
| 242 | for _, p := range paths { |
| 243 | e := files[p] |
| 244 | blob, ok := rp.blobs[e.content] |
| 245 | if !ok { |
| 246 | blob = rp.git([]byte(e.content), "hash-object", "-w", "--stdin") |
| 247 | rp.blobs[e.content] = blob |
| 248 | } |
| 249 | fmt.Fprintf(&info, "%s %s\t%s\x00", e.mode, blob, p) |
| 250 | } |
| 251 | rp.n++ |
| 252 | index := []string{"GIT_INDEX_FILE=" + filepath.Join(rp.dir, ".git", fmt.Sprintf("scratch-index-%d", rp.n))} |
| 253 | rp.gitEnv(index, info.Bytes(), "update-index", "--add", "-z", "--index-info") |
| 254 | tr := rp.gitEnv(index, nil, "write-tree") |
| 255 | args := []string{"commit-tree", tr, "-m", fmt.Sprintf("commit %d", rp.n)} |
| 256 | if parent != "" { |
| 257 | args = append(args, "-p", parent) |
| 258 | } |
| 259 | return rp.git(nil, args...) |
| 260 | } |
| 261 | |
| 262 | // file is a regular file holding content. |
| 263 | func file(content string) entry { return entry{mode: "100644", content: content} } |