| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "sort" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "the-valley/note/statement" |
| 19 | "the-valley/telemetry" |
| 20 | ) |
| 21 | |
| 22 | // These tests run attest against the machine's real nix: they evaluate and |
| 23 | // build flake checks, so they need a nix daemon to talk to. They skip where |
| 24 | // there is none, as inside a nix build, unless ATTEST_NIX_TESTS=require, |
| 25 | // which makes a missing nix fail them instead. attest itself is this test |
| 26 | // binary, run again with ATTEST_AS_MAIN set, so what is run is the |
| 27 | // program's own main with real standard output and error. |
| 28 | |
| 29 | // TestMain runs this test binary as attest when ATTEST_AS_MAIN is set. |
| 30 | func TestMain(m *testing.M) { |
| 31 | if os.Getenv("ATTEST_AS_MAIN") != "" { |
| 32 | main() |
| 33 | os.Exit(0) |
| 34 | } |
| 35 | os.Exit(m.Run()) |
| 36 | } |
| 37 | |
| 38 | // nixFixture is a scratch repository whose flake defines the checks it is |
| 39 | // given, and a bare repository to publish to. Each check is a nix |
| 40 | // expression in which `check NAME SCRIPT` is a derivation that runs SCRIPT |
| 41 | // with /bin/sh, from a file in the store, so the derivation has an input. The flake has no inputs, so nothing is fetched, and every |
| 42 | // derivation carries a nonce, so nothing a test builds is in the store |
| 43 | // before it runs. |
| 44 | type nixFixture struct { |
| 45 | repo string |
| 46 | origin string |
| 47 | state string |
| 48 | key string |
| 49 | name string |
| 50 | env []string |
| 51 | } |
| 52 | |
| 53 | func newNixFixture(t *testing.T, checks map[string]string) nixFixture { |
| 54 | t.Helper() |
| 55 | skip := t.Skipf |
| 56 | if os.Getenv("ATTEST_NIX_TESTS") == "require" { |
| 57 | skip = t.Fatalf |
| 58 | } |
| 59 | for _, tool := range []string{"nix", "nix-store", "git", "cue", "ssh-keygen"} { |
| 60 | if _, err := exec.LookPath(tool); err != nil { |
| 61 | skip("%s is not available: %v", tool, err) |
| 62 | } |
| 63 | } |
| 64 | // A client may send max-jobs to the daemon, so how this machine is |
| 65 | // configured does not decide what the tests see. |
| 66 | nixConfig := os.Getenv("NIX_CONFIG") + "\nextra-experimental-features = nix-command flakes\nmax-jobs = 4\n" |
| 67 | if out, err := exec.Command("env", "NIX_CONFIG="+nixConfig, "nix", "store", "info").CombinedOutput(); err != nil { |
| 68 | skip("no nix store to build in: %v: %s", err, out) |
| 69 | } |
| 70 | t.Setenv("NIX_CONFIG", nixConfig) |
| 71 | |
| 72 | dir := t.TempDir() |
| 73 | f := nixFixture{ |
| 74 | repo: filepath.Join(dir, "repo"), |
| 75 | origin: filepath.Join(dir, "origin.git"), |
| 76 | state: filepath.Join(dir, "state"), |
| 77 | key: filepath.Join(dir, "key"), |
| 78 | name: "test.example/attestations", |
| 79 | } |
| 80 | f.env = append(os.Environ(), |
| 81 | "ATTEST_AS_MAIN=1", |
| 82 | "XDG_STATE_HOME="+f.state, |
| 83 | "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", |
| 84 | "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@l", |
| 85 | "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@l") |
| 86 | if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "t", "-f", f.key).CombinedOutput(); err != nil { |
| 87 | t.Fatalf("ssh-keygen: %v: %s", err, out) |
| 88 | } |
| 89 | |
| 90 | nonce := make([]byte, 8) |
| 91 | if _, err := rand.Read(nonce); err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | names := make([]string, 0, len(checks)) |
| 95 | for name := range checks { |
| 96 | names = append(names, name) |
| 97 | } |
| 98 | sort.Strings(names) |
| 99 | var defs strings.Builder |
| 100 | for _, name := range names { |
| 101 | fmt.Fprintf(&defs, " %s = %s;\n", name, checks[name]) |
| 102 | } |
| 103 | flake := fmt.Sprintf(`{ |
| 104 | outputs = { self }: |
| 105 | let |
| 106 | system = "%s"; |
| 107 | check = name: script: derivation { |
| 108 | inherit name system; |
| 109 | builder = "/bin/sh"; |
| 110 | args = [ (builtins.toFile "${name}.sh" script) ]; |
| 111 | nonce = "%s"; |
| 112 | }; |
| 113 | in { |
| 114 | checks.${system} = { |
| 115 | %s }; |
| 116 | }; |
| 117 | } |
| 118 | `, nixSystem(), hex.EncodeToString(nonce), defs.String()) |
| 119 | if err := os.MkdirAll(f.repo, 0o755); err != nil { |
| 120 | t.Fatal(err) |
| 121 | } |
| 122 | if err := os.WriteFile(filepath.Join(f.repo, "flake.nix"), []byte(flake), 0o644); err != nil { |
| 123 | t.Fatal(err) |
| 124 | } |
| 125 | f.git(t, "", "init", "--quiet", "-b", "main", f.repo) |
| 126 | f.git(t, f.repo, "add", "flake.nix") |
| 127 | f.git(t, f.repo, "commit", "--quiet", "-m", "checks") |
| 128 | f.git(t, "", "init", "--quiet", "--bare", f.origin) |
| 129 | return f |
| 130 | } |
| 131 | |
| 132 | func (f nixFixture) git(t *testing.T, dir string, args ...string) string { |
| 133 | t.Helper() |
| 134 | cmd := exec.Command("git", args...) |
| 135 | cmd.Dir = dir |
| 136 | cmd.Env = f.env |
| 137 | out, err := cmd.CombinedOutput() |
| 138 | if err != nil { |
| 139 | t.Fatalf("git %s: %v: %s", strings.Join(args, " "), err, out) |
| 140 | } |
| 141 | return strings.TrimSpace(string(out)) |
| 142 | } |
| 143 | |
| 144 | // attest runs `attest run` over the fixture's HEAD, publishing to its |
| 145 | // bare repository, with the flags given. |
| 146 | func (f nixFixture) attest(t *testing.T, flags ...string) (stdout, stderr string, err error) { |
| 147 | t.Helper() |
| 148 | schema, err := filepath.Abs(filepath.Join("..", "schema", "attestation.cue")) |
| 149 | if err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | args := append([]string{"run", "--repo", f.repo, "--key", f.key, "--name", f.name, |
| 153 | "--schema", schema, "--push", f.origin, "--branch", "main"}, flags...) |
| 154 | cmd := exec.Command(os.Args[0], args...) |
| 155 | cmd.Env = f.env |
| 156 | var out, errb strings.Builder |
| 157 | cmd.Stdout, cmd.Stderr = &out, &errb |
| 158 | err = cmd.Run() |
| 159 | return out.String(), errb.String(), err |
| 160 | } |
| 161 | |
| 162 | // published is every ref under refs/the-valley/ in the fixture's bare |
| 163 | // repository and in the repository itself. |
| 164 | func (f nixFixture) published(t *testing.T) string { |
| 165 | t.Helper() |
| 166 | return f.git(t, f.origin, "for-each-ref", "refs/the-valley/") + f.git(t, f.repo, "for-each-ref", "refs/the-valley/") |
| 167 | } |
| 168 | |
| 169 | // sequentialOutcome is what the sequential run made of one pure check that |
| 170 | // passes: an evaluation of the check alone, then a nix build of its |
| 171 | // derivation alone, whose printed output path is digested. A run of many |
| 172 | // checks must decide each one as this did. |
| 173 | func sequentialOutcome(t *testing.T, tree string, spec checkSpec) checkOutcome { |
| 174 | t.Helper() |
| 175 | c, _, err := evalClosure(tree, nixSystem(), spec, nil) |
| 176 | if err != nil { |
| 177 | t.Fatal(err) |
| 178 | } |
| 179 | built, errb, err := nix(tree, "build", "--no-link", "--print-out-paths", c.drv+"^*") |
| 180 | if err != nil { |
| 181 | t.Fatalf("building %s alone: %v: %s", spec.name, err, errb) |
| 182 | } |
| 183 | paths := strings.Fields(built) |
| 184 | if len(paths) != 1 { |
| 185 | t.Fatalf("%s built %d outputs", spec.name, len(paths)) |
| 186 | } |
| 187 | entries, err := fsEntries(paths[0]) |
| 188 | if err != nil { |
| 189 | t.Fatal(err) |
| 190 | } |
| 191 | return checkOutcome{spec: spec, passed: true, derivation: c.derivation, inputs: c.inputs, output: statement.TreeDigest(entries)} |
| 192 | } |
| 193 | |
| 194 | // checkLine is the line run prints for a pure check with a result. |
| 195 | func checkLine(name, result string) string { |
| 196 | return fmt.Sprintf("check %-24s %-8s %s\n", name, "nix", result) |
| 197 | } |
| 198 | |
| 199 | func statementText(t *testing.T, subj subject, out checkOutcome) string { |
| 200 | t.Helper() |
| 201 | doc, err := json.Marshal(composeStatement(subj, out, "local", nil)) |
| 202 | if err != nil { |
| 203 | t.Fatal(err) |
| 204 | } |
| 205 | text, err := statement.RenderJSON(doc) |
| 206 | if err != nil { |
| 207 | t.Fatal(err) |
| 208 | } |
| 209 | return string(text) |
| 210 | } |
| 211 | |
| 212 | // Three checks built side by side, one of which fails. The two that pass |
| 213 | // are recorded exactly as the sequential run recorded them, the one that |
| 214 | // fails keeps its own log, and nothing is published. The same two checks |
| 215 | // without the failing one publish statements a sequential run would have |
| 216 | // signed. |
| 217 | func TestEachCheckKeepsItsOwnOutcome(t *testing.T) { |
| 218 | f := newNixFixture(t, map[string]string{ |
| 219 | "one": `check "one" "echo one > $out"`, |
| 220 | "two": `check "two" "echo two > $out"`, |
| 221 | "broken": `check "broken" "echo the broken check says why; exit 3"`, |
| 222 | }) |
| 223 | stdout, stderr, err := f.attest(t, "--check", "one", "--check", "broken", "--check", "two", "--timings") |
| 224 | if err == nil { |
| 225 | t.Fatalf("a run with a failing check succeeded:\n%s%s", stdout, stderr) |
| 226 | } |
| 227 | for _, want := range []string{checkLine("one", "passed"), checkLine("broken", "failed"), checkLine("two", "passed")} { |
| 228 | if !strings.Contains(stdout, want) { |
| 229 | t.Errorf("the run did not report %q:\n%s", want, stdout) |
| 230 | } |
| 231 | } |
| 232 | if _, log, _ := strings.Cut(stderr, "\n--- broken ---\n"); !strings.Contains(log, "the broken check says why") { |
| 233 | t.Errorf("the failing check's log was lost:\n%s", stderr) |
| 234 | } |
| 235 | if !strings.Contains(stderr, "1 of 3 checks failed; nothing published") { |
| 236 | t.Errorf("the run did not say that nothing was published:\n%s", stderr) |
| 237 | } |
| 238 | if refs := f.published(t); refs != "" { |
| 239 | t.Errorf("a run with a failing check published:\n%s", refs) |
| 240 | } |
| 241 | |
| 242 | // Each check is logged on its own line, with the fields it always had |
| 243 | // and its evaluation time, which is part of its duration. |
| 244 | data, err := os.ReadFile(filepath.Join(f.state, "valley", "timings.jsonl")) |
| 245 | if err != nil { |
| 246 | t.Fatal(err) |
| 247 | } |
| 248 | lines := strings.Split(strings.TrimSuffix(string(data), "\n"), "\n") |
| 249 | if len(lines) != 3 { |
| 250 | t.Fatalf("the timing log holds %d lines, want 3:\n%s", len(lines), data) |
| 251 | } |
| 252 | results := map[string]string{} |
| 253 | for _, line := range lines { |
| 254 | var timing checkTiming |
| 255 | if err := json.Unmarshal([]byte(line), &timing); err != nil { |
| 256 | t.Fatal(err) |
| 257 | } |
| 258 | results[timing.Check] = timing.Result |
| 259 | if timing.EvalMS <= 0 || timing.EvalMS > timing.DurationMS || timing.Satisfied != satisfiedRan { |
| 260 | t.Errorf("a pure check's timing reads %s", line) |
| 261 | } |
| 262 | } |
| 263 | if results["one"] != "passed" || results["two"] != "passed" || results["broken"] != "failed" { |
| 264 | t.Errorf("the timing log records the results %v", results) |
| 265 | } |
| 266 | |
| 267 | // The two that passed, decided beside the failing one, are the |
| 268 | // outcomes the sequential run made of them. |
| 269 | tree := t.TempDir() |
| 270 | if err := exportTree(f.repo, "HEAD", tree); err != nil { |
| 271 | t.Fatal(err) |
| 272 | } |
| 273 | subj, err := composeSubject(f.repo, "HEAD") |
| 274 | if err != nil { |
| 275 | t.Fatal(err) |
| 276 | } |
| 277 | specs := []checkSpec{{name: "one", attribute: "one"}, {name: "broken", attribute: "broken"}, {name: "two", attribute: "two"}} |
| 278 | runs, _ := runPure(tree, nixSystem(), specs, false, defaultSlots, "", nil, "", nil, nil) |
| 279 | for i, r := range runs { |
| 280 | if r.err != nil { |
| 281 | t.Fatalf("%s: %v", specs[i].name, r.err) |
| 282 | } |
| 283 | } |
| 284 | if runs[1].out.passed || !strings.Contains(runs[1].out.log, "the broken check says why") { |
| 285 | t.Errorf("the failing check passed, or lost its log: %+v", runs[1].out) |
| 286 | } |
| 287 | sequential := map[string]string{} |
| 288 | for _, i := range []int{0, 2} { |
| 289 | want := statementText(t, subj, sequentialOutcome(t, tree, specs[i])) |
| 290 | if got := statementText(t, subj, runs[i].out); got != want { |
| 291 | t.Errorf("%s beside the others:\n%s\nalone:\n%s", specs[i].name, got, want) |
| 292 | } |
| 293 | sequential[specs[i].name] = want |
| 294 | } |
| 295 | |
| 296 | // Without the failing check, the run publishes, and what it signed is |
| 297 | // what the sequential run would have. |
| 298 | stdout, stderr, err = f.attest(t, "--check", "one", "--check", "two") |
| 299 | if err != nil { |
| 300 | t.Fatalf("a run whose checks pass failed: %v\n%s%s", err, stdout, stderr) |
| 301 | } |
| 302 | host, err := loadSigner(f.key, f.name) |
| 303 | if err != nil { |
| 304 | t.Fatal(err) |
| 305 | } |
| 306 | ref := attestationRef(subj.Digest[subj.Primary], fmt.Sprintf("%08x", host.hash)) |
| 307 | for name, want := range sequential { |
| 308 | note := f.git(t, f.origin, "cat-file", "blob", ref+":"+name+"/statement.note") + "\n" |
| 309 | text, _, err := openNote([]byte(note), []verifierKey{host.verifierKey()}) |
| 310 | if err != nil { |
| 311 | t.Fatalf("%s: %v", name, err) |
| 312 | } |
| 313 | if string(text) != want { |
| 314 | t.Errorf("%s was published as:\n%s\nthe sequential run signs:\n%s", name, text, want) |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // Two slow checks build side by side when attest may run two builds at |
| 320 | // once: the run takes about as long as one of them. Allowed one build at a |
| 321 | // time, the same run takes as long as both. --slots sets the capacity, so |
| 322 | // the machine's CPU count does not decide either. |
| 323 | func TestChecksBuildSideBySide(t *testing.T) { |
| 324 | // The sandbox's /bin/sh may have no sleep, so each check waits on a |
| 325 | // read that never ends a line and times out. |
| 326 | const sleep = 5 * time.Second |
| 327 | script := fmt.Sprintf("read -t %d line < /dev/zero; echo done > $out", int(sleep.Seconds())) |
| 328 | for _, c := range []struct { |
| 329 | slots int |
| 330 | min, max time.Duration |
| 331 | }{ |
| 332 | {slots: 2, min: sleep, max: 2*sleep - time.Second}, |
| 333 | {slots: 1, min: 2 * sleep, max: 3 * sleep}, |
| 334 | } { |
| 335 | // A fixture of its own, so the second run does not find the |
| 336 | // first one's outputs built. |
| 337 | f := newNixFixture(t, map[string]string{ |
| 338 | "slow-one": fmt.Sprintf("check %q %q", "slow-one", script), |
| 339 | "slow-two": fmt.Sprintf("check %q %q", "slow-two", script), |
| 340 | }) |
| 341 | began := time.Now() |
| 342 | stdout, stderr, err := f.attest(t, "--slots", strconv.Itoa(c.slots), "--check", "slow-one", "--check", "slow-two") |
| 343 | took := time.Since(began) |
| 344 | if err != nil { |
| 345 | t.Fatalf("the slow checks did not pass: %v\n%s%s", err, stdout, stderr) |
| 346 | } |
| 347 | if took < c.min || took >= c.max { |
| 348 | t.Errorf("two %v checks, %d build at a time, took %v together", sleep, c.slots, took) |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // A check that does not evaluate is an error for that check alone: every |
| 354 | // other check is still built and reported, and nothing is published. An |
| 355 | // error nix can catch leaves the shared evaluation standing; one it |
| 356 | // cannot, such as a type error, ends it, and every check is evaluated |
| 357 | // alone. |
| 358 | func TestAnEvaluationErrorStopsNoOtherCheck(t *testing.T) { |
| 359 | for name, broken := range map[string]string{ |
| 360 | "a throw": `throw "the broken check does not evaluate"`, |
| 361 | "a type error": `check "broken" (1 + "the broken check does not evaluate")`, |
| 362 | } { |
| 363 | t.Run(name, func(t *testing.T) { |
| 364 | f := newNixFixture(t, map[string]string{ |
| 365 | "fine": `check "fine" "echo fine > $out"`, |
| 366 | "broken": broken, |
| 367 | "also": `check "also" "echo also > $out"`, |
| 368 | }) |
| 369 | stream := &telemetry.Stream{Dir: t.TempDir()} |
| 370 | stdout, stderr, err := f.attest(t, "--telemetry", stream.Dir, "--check", "fine", "--check", "broken", "--check", "also") |
| 371 | if err == nil { |
| 372 | t.Fatalf("a run with a check that does not evaluate succeeded:\n%s%s", stdout, stderr) |
| 373 | } |
| 374 | // The broken check's result carries its error and names no |
| 375 | // derivation; a check that built names the one it built. |
| 376 | records, _, err := stream.Read(0, 100, 1<<20) |
| 377 | if err != nil { |
| 378 | t.Fatal(err) |
| 379 | } |
| 380 | results := map[string]map[string]any{} |
| 381 | for _, r := range records { |
| 382 | if r.Type == "check.result" { |
| 383 | results[r.Check] = r.Data |
| 384 | } |
| 385 | } |
| 386 | if drv, named := results["broken"]["drv"]; named || results["broken"]["error"] == nil { |
| 387 | t.Errorf("the broken check's result names derivation %v, error %v", drv, results["broken"]["error"]) |
| 388 | } |
| 389 | if drv, _ := results["fine"]["drv"].(string); !strings.HasPrefix(drv, "/nix/store/") || !strings.HasSuffix(drv, ".drv") { |
| 390 | t.Errorf("the fine check's result names derivation %q", drv) |
| 391 | } |
| 392 | for _, want := range []string{ |
| 393 | checkLine("fine", "passed"), |
| 394 | checkLine("also", "passed"), |
| 395 | fmt.Sprintf("time %-24s %-8s ", "broken", "error"), |
| 396 | } { |
| 397 | if !strings.Contains(stdout, want) { |
| 398 | t.Errorf("the run did not report %q:\n%s", want, stdout) |
| 399 | } |
| 400 | } |
| 401 | if !strings.Contains(stderr, "evaluating ") || !strings.Contains(stderr, "the broken check does not evaluate") { |
| 402 | t.Errorf("the evaluation error is not reported:\n%s", stderr) |
| 403 | } |
| 404 | if refs := f.published(t); refs != "" { |
| 405 | t.Errorf("a run with a check that does not evaluate published:\n%s", refs) |
| 406 | } |
| 407 | }) |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | // A check attribute produces exactly one output, so a derivation with two |
| 412 | // is an error for that check alone, and the check beside it still passes. |
| 413 | func TestACheckWithTwoOutputsIsAnError(t *testing.T) { |
| 414 | f := newNixFixture(t, map[string]string{ |
| 415 | "fine": `check "fine" "echo fine > $out"`, |
| 416 | "split": `derivation { |
| 417 | name = "split"; |
| 418 | inherit system; |
| 419 | builder = "/bin/sh"; |
| 420 | args = [ (builtins.toFile "split.sh" "echo a > $out; echo b > $dev") ]; |
| 421 | outputs = [ "out" "dev" ]; |
| 422 | }`, |
| 423 | }) |
| 424 | stdout, stderr, err := f.attest(t, "--check", "split", "--check", "fine") |
| 425 | if err == nil { |
| 426 | t.Fatalf("a run with a two-output check succeeded:\n%s%s", stdout, stderr) |
| 427 | } |
| 428 | if !strings.Contains(stdout, checkLine("fine", "passed")) || !strings.Contains(stdout, fmt.Sprintf("time %-24s %-8s ", "split", "error")) { |
| 429 | t.Errorf("the run did not report the two checks apart:\n%s", stdout) |
| 430 | } |
| 431 | if !strings.Contains(stderr, "split produced 2 outputs; a check attribute must produce exactly one") { |
| 432 | t.Errorf("the two-output check's error is not reported:\n%s", stderr) |
| 433 | } |
| 434 | if refs := f.published(t); refs != "" { |
| 435 | t.Errorf("a run with a two-output check published:\n%s", refs) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | // A run with --gc-roots roots every output of every flake check it builds |
| 440 | // in the directory it names, one symlink per output named by its store |
| 441 | // path's basename, and a later run that finds the outputs already built |
| 442 | // makes each symlink afresh. A run without it roots nothing. |
| 443 | func TestGCRootsRootEveryOutputAndAreRefreshedOnReuse(t *testing.T) { |
| 444 | f := newNixFixture(t, map[string]string{ |
| 445 | "one": `check "one" "echo one > $out"`, |
| 446 | "split": `derivation { |
| 447 | name = "split"; |
| 448 | inherit system; |
| 449 | builder = "/bin/sh"; |
| 450 | args = [ (builtins.toFile "split.sh" "echo a > $out; echo b > $dev") ]; |
| 451 | outputs = [ "out" "dev" ]; |
| 452 | }`, |
| 453 | }) |
| 454 | checks := []string{"--check", "one", "--check", "split"} |
| 455 | // The two-output check is an error, but it is built all the same. |
| 456 | if stdout, stderr, err := f.attest(t, checks...); !strings.Contains(stdout, checkLine("one", "passed")) { |
| 457 | t.Fatalf("the run without --gc-roots did not pass one: %v\n%s%s", err, stdout, stderr) |
| 458 | } |
| 459 | var outputs []string |
| 460 | for _, attr := range []string{"one.out", "split.out", "split.dev"} { |
| 461 | out, errb, err := nix(f.repo, "eval", "--raw", ".#checks."+nixSystem()+"."+attr+".outPath") |
| 462 | if err != nil { |
| 463 | t.Fatalf("evaluating %s: %v: %s", attr, err, errb) |
| 464 | } |
| 465 | outputs = append(outputs, out) |
| 466 | } |
| 467 | roots := func(path string) string { |
| 468 | out, errb, err := nixStore(context.Background(), "--query", "--roots", path) |
| 469 | if err != nil { |
| 470 | t.Fatalf("nix-store --query --roots %s: %v: %s", path, err, errb) |
| 471 | } |
| 472 | return out |
| 473 | } |
| 474 | for _, path := range outputs { |
| 475 | if r := roots(path); r != "" { |
| 476 | t.Errorf("a run without --gc-roots rooted %s:\n%s", path, r) |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | dir := filepath.Join(t.TempDir(), "roots") |
| 481 | rooted := func(run string) map[string]time.Time { |
| 482 | t.Helper() |
| 483 | entries, err := os.ReadDir(dir) |
| 484 | if err != nil { |
| 485 | t.Fatal(err) |
| 486 | } |
| 487 | if len(entries) != len(outputs) { |
| 488 | t.Errorf("the %s run left %d roots for %d outputs: %v", run, len(entries), len(outputs), entries) |
| 489 | } |
| 490 | times := map[string]time.Time{} |
| 491 | for _, path := range outputs { |
| 492 | link := filepath.Join(dir, filepath.Base(path)) |
| 493 | if target, err := os.Readlink(link); err != nil || target != path { |
| 494 | t.Errorf("after the %s run, %s points to %q (%v), not %s", run, link, target, err, path) |
| 495 | continue |
| 496 | } |
| 497 | if r := roots(path); !strings.Contains(r, link) { |
| 498 | t.Errorf("after the %s run, the daemon does not know %s as a root of %s:\n%s", run, link, path, r) |
| 499 | } |
| 500 | info, err := os.Lstat(link) |
| 501 | if err != nil { |
| 502 | t.Fatal(err) |
| 503 | } |
| 504 | times[link] = info.ModTime() |
| 505 | } |
| 506 | return times |
| 507 | } |
| 508 | if stdout, stderr, _ := f.attest(t, append(checks, "--gc-roots", dir)...); strings.Contains(stderr, "is not rooted") { |
| 509 | t.Fatalf("the run could not root an output:\n%s%s", stdout, stderr) |
| 510 | } |
| 511 | for link := range rooted("first") { |
| 512 | if out, err := exec.Command("touch", "-h", "-d", "2000-01-01", link).CombinedOutput(); err != nil { |
| 513 | t.Fatalf("touch %s: %v: %s", link, err, out) |
| 514 | } |
| 515 | } |
| 516 | reused := time.Now().Add(-time.Minute) |
| 517 | if stdout, stderr, _ := f.attest(t, append(checks, "--gc-roots", dir)...); !strings.Contains(stdout, checkLine("one", "passed")) { |
| 518 | t.Fatalf("the second run did not pass one:\n%s%s", stdout, stderr) |
| 519 | } |
| 520 | for link, used := range rooted("second") { |
| 521 | if used.Before(reused) { |
| 522 | t.Errorf("the second run used %s but left its last use at %s", link, used) |
| 523 | } |
| 524 | } |
| 525 | } |