| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "reflect" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | ) |
| 16 | |
| 17 | // checksRepo is a repository with a base and a head commit, and a policy |
| 18 | // beside it, for the checks verb's tests. |
| 19 | type checksRepo struct { |
| 20 | schema, instance, project, base, head string |
| 21 | } |
| 22 | |
| 23 | func newChecksRepo(t *testing.T) *checksRepo { |
| 24 | t.Helper() |
| 25 | if _, err := exec.LookPath("cue"); err != nil { |
| 26 | if os.Getenv("VALLEY_TEST_TOOLS") == "required" { |
| 27 | t.Fatal("no cue on PATH, and VALLEY_TEST_TOOLS=required") |
| 28 | } |
| 29 | t.Skip("no cue to compose a policy with; the nix check provides one") |
| 30 | } |
| 31 | schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue")) |
| 32 | if err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | dir := t.TempDir() |
| 36 | t.Setenv("HOME", dir) |
| 37 | t.Setenv("GIT_CONFIG_NOSYSTEM", "1") |
| 38 | r := &checksRepo{schema: schema, instance: filepath.Join(dir, "instance"), project: filepath.Join(dir, "project")} |
| 39 | write := func(path, body string) { |
| 40 | t.Helper() |
| 41 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | } |
| 48 | write(filepath.Join(r.instance, "floor.cue"), `package verification |
| 49 | floor: { |
| 50 | checks: "c-docs": {runner: "nix", attribute: "c-docs"} |
| 51 | checks: "c-live": {runner: "command", command: "probe --live", validity: "1h", cost: "slow"} |
| 52 | classes: docs: {paths: "docs/**": true, requires: "c-docs": true} |
| 53 | classes: run: {paths: "run/**": true, requires: "c-live": true, carry: exact: true} |
| 54 | unclassified: "c-docs": true |
| 55 | } |
| 56 | `) |
| 57 | write(filepath.Join(r.project, "policy.cue"), "package verification\n") |
| 58 | work := filepath.Join(dir, "work") |
| 59 | git := func(args ...string) string { |
| 60 | t.Helper() |
| 61 | cmd := exec.Command("git", args...) |
| 62 | cmd.Dir = work |
| 63 | out, err := cmd.CombinedOutput() |
| 64 | if err != nil { |
| 65 | t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out) |
| 66 | } |
| 67 | return strings.TrimSpace(string(out)) |
| 68 | } |
| 69 | if err := os.Mkdir(work, 0o755); err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | git("init", "--quiet", "--initial-branch=main") |
| 73 | git("config", "user.name", "checks-test") |
| 74 | git("config", "user.email", "checks-test@localhost") |
| 75 | write(filepath.Join(work, "docs", "a.md"), "base\n") |
| 76 | git("add", "-A") |
| 77 | git("commit", "--quiet", "-m", "base") |
| 78 | r.base = git("rev-parse", "HEAD") |
| 79 | write(filepath.Join(work, "run", "caf\xe9.sh"), "new\n") |
| 80 | write(filepath.Join(work, "docs", "new\nline.md"), "new\n") |
| 81 | write(filepath.Join(work, "Makefile"), "new\n") |
| 82 | git("add", "-A") |
| 83 | git("commit", "--quiet", "-m", "head") |
| 84 | r.head = git("rev-parse", "HEAD") |
| 85 | t.Chdir(work) |
| 86 | return r |
| 87 | } |
| 88 | |
| 89 | func (r *checksRepo) checks(args ...string) (stdout, stderr string, code int) { |
| 90 | var out, errb bytes.Buffer |
| 91 | code = run(append([]string{"checks"}, args...), &out, &errb, os.Exit) |
| 92 | return out.String(), errb.String(), code |
| 93 | } |
| 94 | |
| 95 | // TestChecksPrintsTheDerivation holds the valley-checks/v1 document to the |
| 96 | // derivation: every path as git gave it, a path that is not UTF-8 in |
| 97 | // base64, and each required check with its classes, pin, cost and how it |
| 98 | // is run. |
| 99 | func TestChecksPrintsTheDerivation(t *testing.T) { |
| 100 | r := newChecksRepo(t) |
| 101 | out, stderr, code := r.checks("--json", "--schema", r.schema, "--instance", r.instance, "--project="+r.project, r.base, "HEAD") |
| 102 | if code != 0 { |
| 103 | t.Fatalf("checks exited %d: %s", code, stderr) |
| 104 | } |
| 105 | type path struct { |
| 106 | Path *string `json:"path"` |
| 107 | Base64 *string `json:"base64"` |
| 108 | } |
| 109 | var doc struct { |
| 110 | Schema string `json:"schema"` |
| 111 | Base string `json:"base"` |
| 112 | Head string `json:"head"` |
| 113 | PolicyDigest string `json:"policy_digest"` |
| 114 | Paths []path `json:"paths"` |
| 115 | Classes []string |
| 116 | UnclassifiedPaths []path `json:"unclassified_paths"` |
| 117 | Carry string |
| 118 | Required []map[string]any |
| 119 | Follows []map[string]any |
| 120 | } |
| 121 | dec := json.NewDecoder(strings.NewReader(out)) |
| 122 | dec.DisallowUnknownFields() |
| 123 | if err := dec.Decode(&doc); err != nil { |
| 124 | t.Fatalf("the document does not read: %v\n%s", err, out) |
| 125 | } |
| 126 | bytesOf := func(ps []path) []string { |
| 127 | var got []string |
| 128 | for _, p := range ps { |
| 129 | switch { |
| 130 | case p.Path != nil && p.Base64 == nil: |
| 131 | got = append(got, *p.Path) |
| 132 | case p.Base64 != nil && p.Path == nil: |
| 133 | b, err := base64.StdEncoding.Strict().DecodeString(*p.Base64) |
| 134 | if err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | got = append(got, string(b)) |
| 138 | default: |
| 139 | t.Errorf("a path is %+v, not one of path and base64", p) |
| 140 | } |
| 141 | } |
| 142 | return got |
| 143 | } |
| 144 | if doc.Schema != "valley-checks/v1" || doc.Base != r.base || doc.Head != r.head || len(doc.PolicyDigest) != 64 { |
| 145 | t.Errorf("schema %q, base %q, head %q, digest %q", doc.Schema, doc.Base, doc.Head, doc.PolicyDigest) |
| 146 | } |
| 147 | if got, want := bytesOf(doc.Paths), []string{"Makefile", "docs/new\nline.md", "run/caf\xe9.sh"}; !reflect.DeepEqual(got, want) { |
| 148 | t.Errorf("paths = %q", got) |
| 149 | } |
| 150 | if !strings.Contains(out, `"base64": "`+base64.StdEncoding.EncodeToString([]byte("run/caf\xe9.sh"))+`"`) { |
| 151 | t.Error("the path that is not UTF-8 is not in base64") |
| 152 | } |
| 153 | if got := bytesOf(doc.UnclassifiedPaths); !reflect.DeepEqual(got, []string{"Makefile"}) { |
| 154 | t.Errorf("unclassified paths = %q", got) |
| 155 | } |
| 156 | if !reflect.DeepEqual(doc.Classes, []string{"docs", "run"}) || doc.Carry != "exact" { |
| 157 | t.Errorf("classes %q, carry %q", doc.Classes, doc.Carry) |
| 158 | } |
| 159 | want := []map[string]any{ |
| 160 | {"name": "c-docs", "classes": []any{"docs"}, "unclassified": true, "pin": "mandatory", "cost": "quick", "runner": "nix", "attribute": "c-docs"}, |
| 161 | {"name": "c-live", "classes": []any{"run"}, "unclassified": false, "pin": "mandatory", "cost": "slow", "runner": "command", "command": "probe --live", "validity": "1h"}, |
| 162 | } |
| 163 | if !reflect.DeepEqual(doc.Required, want) { |
| 164 | t.Errorf("required = %v", doc.Required) |
| 165 | } |
| 166 | |
| 167 | // The same two commits with nothing between them require nothing, and |
| 168 | // every list is still a list. |
| 169 | out, _, code = r.checks("--json", "--schema", r.schema, "--instance", r.instance, "--project", r.project, r.head, r.head) |
| 170 | for _, field := range []string{`"paths": []`, `"classes": []`, `"unclassified_paths": []`, `"required": []`, `"follows": []`, `"carry": "same-paths"`} { |
| 171 | if code != 0 || !strings.Contains(out, field) { |
| 172 | t.Errorf("an empty change's document has no %s:\n%s", field, out) |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | // TestChecksPrintsNothingWhenItFails holds the verb to printing nothing on |
| 178 | // stdout when it derives nothing, and to saying why. |
| 179 | func TestChecksPrintsNothingWhenItFails(t *testing.T) { |
| 180 | r := newChecksRepo(t) |
| 181 | broken := t.TempDir() |
| 182 | if err := os.WriteFile(filepath.Join(broken, "policy.cue"), []byte("package verification\nproject: classes: x: requires: nothing: true\n"), 0o644); err != nil { |
| 183 | t.Fatal(err) |
| 184 | } |
| 185 | for _, c := range []struct { |
| 186 | name string |
| 187 | args []string |
| 188 | says string |
| 189 | }{ |
| 190 | {"three commits", []string{"--json", "--instance", r.instance, "--project", r.project, r.base, r.head, r.head}, "usage: valley checks"}, |
| 191 | {"the document and the names", []string{"--json", "--names", "--instance", r.instance, "--project", r.project, r.base, r.head}, "usage: valley checks"}, |
| 192 | {"an unknown option", []string{"--json", "--bogus", "--instance", r.instance, "--project", r.project, r.base, r.head}, "unknown option: --bogus"}, |
| 193 | {"no such base", []string{"--json", "--instance", r.instance, "--project", r.project, "nowhere", r.head}, "no such commit: nowhere"}, |
| 194 | {"a layer that does not compose", []string{"--json", "--instance", r.instance, "--project", broken, r.base, r.head}, "do not compose"}, |
| 195 | {"no schema there", []string{"--json", "--schema", filepath.Join(broken, "none.cue"), "--instance", r.instance, "--project", r.project, r.base, r.head}, "no policy schema at"}, |
| 196 | } { |
| 197 | args := c.args |
| 198 | if !strings.HasPrefix(c.name, "no schema") { |
| 199 | args = append([]string{"--schema", r.schema}, args...) |
| 200 | } |
| 201 | out, stderr, code := r.checks(args...) |
| 202 | if code == 0 || out != "" || !strings.Contains(stderr, c.says) { |
| 203 | t.Errorf("%s: exit %d, stdout %q, stderr %q", c.name, code, out, stderr) |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // TestPendingCountsChecksInProcess holds pending's count of a head's |
| 209 | // checks to the derivation under the policy at main's tip: counted by |
| 210 | // cost, refused as "requires ?" when the head shares no history with main |
| 211 | // or the policy does not compose. |
| 212 | func TestPendingCountsChecksInProcess(t *testing.T) { |
| 213 | r := newChecksRepo(t) |
| 214 | t.Setenv("VALLEY_VERIFICATION_SCHEMA", r.schema) |
| 215 | snap := func(project string) *snapshot { |
| 216 | s := &snapshot{g: git{env: os.Environ(), stderr: io.Discard}, tip: r.base} |
| 217 | s.policy.read, s.policy.src = true, layerSource{instance: r.instance, project: project} |
| 218 | return s |
| 219 | } |
| 220 | out, _, code := r.checks("--names", "--schema", r.schema, "--instance", r.instance, "--project", r.project, r.base, r.head) |
| 221 | slow, _, _ := r.checks("--names", "--cost", "slow", "--schema", r.schema, "--instance", r.instance, "--project", r.project, r.base, r.head) |
| 222 | quick, nslow := len(strings.Fields(out))-len(strings.Fields(slow)), len(strings.Fields(slow)) |
| 223 | if code != 0 || quick == 0 { |
| 224 | t.Fatalf("the head requires no quick check: %q", out) |
| 225 | } |
| 226 | noun := "checks" |
| 227 | if quick == 1 { |
| 228 | noun = "check" |
| 229 | } |
| 230 | if got, want := snap(r.project).checks(r.head), fmt.Sprintf("requires %d quick %s, %d slow", quick, noun, nslow); got != want { |
| 231 | t.Errorf("checks = %q, want %q", got, want) |
| 232 | } |
| 233 | if got := snap(r.project).checks(r.base); got != "requires no checks" { |
| 234 | t.Errorf("an empty change: checks = %q", got) |
| 235 | } |
| 236 | |
| 237 | git := func(args ...string) string { |
| 238 | out, err := exec.Command("git", args...).Output() |
| 239 | if err != nil { |
| 240 | t.Fatal(err) |
| 241 | } |
| 242 | return strings.TrimSpace(string(out)) |
| 243 | } |
| 244 | orphan := git("commit-tree", "-m", "orphan", git("rev-parse", r.head+"^{tree}")) |
| 245 | if got := snap(r.project).checks(orphan); got != "requires ? (no merge base with main)" { |
| 246 | t.Errorf("a head with no merge base: checks = %q", got) |
| 247 | } |
| 248 | broken := t.TempDir() |
| 249 | if err := os.WriteFile(filepath.Join(broken, "policy.cue"), []byte("package verification\nproject: classes: x: requires: nothing: true\n"), 0o644); err != nil { |
| 250 | t.Fatal(err) |
| 251 | } |
| 252 | if got := snap(broken).checks(r.head); got != "requires ? (the policy did not derive)" { |
| 253 | t.Errorf("a policy that does not compose: checks = %q", got) |
| 254 | } |
| 255 | } |