//go:build linux package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io/fs" "net" "os" "os/exec" "path/filepath" "sort" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/pause" "amadan.net/oficina/equipo/internal/runner/provider" "golang.org/x/sys/unix" ) // workTree writes files (path to content) under a fresh workspace; links // (path to target) are made as symlinks. func workTree(t *testing.T, files, links map[string]string) string { t.Helper() ws := t.TempDir() for rel, content := range files { p := filepath.Join(ws, rel) if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { t.Fatal(err) } if err := os.WriteFile(p, []byte(content), 0o644); err != nil { t.Fatal(err) } } for rel, target := range links { p := filepath.Join(ws, rel) if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { t.Fatal(err) } if err := os.Symlink(target, p); err != nil { t.Fatal(err) } } return ws } // siteFiles is a workspace whose release/preview.json names site, with // files outside the output too. func siteFiles() map[string]string { return map[string]string{ "release/preview.json": `{"output": "site"}`, "site/index.html": "

home

", "site/about/index.html": "

about

", "site/a/b/c/d.css": "body{}", "site/_headers": "/*\n X-Tree: 1\n", "secret.txt": "OUTSIDE-THE-OUTPUT", "other/notes.md": "OUTSIDE-THE-OUTPUT", "sitemap/x.html": "OUTSIDE-THE-OUTPUT", } } // copySite runs copyWorkSite into a fresh stage and returns it. func copySite(t *testing.T, ws, headers string) (previewExport, string, error) { t.Helper() stage := filepath.Join(t.TempDir(), "stage") st, err := openSiteStage(stage) if err != nil { t.Fatal(err) } defer st.close() ex, err := copyWorkSite(ws, st, headers, time.Now().Add(time.Minute)) return ex, stage, err } // staged lists the stage's files (path to content) and fails on anything // but regular files and directories. func staged(t *testing.T, stage string) map[string]string { t.Helper() out := map[string]string{} filepath.WalkDir(stage, func(p string, d fs.DirEntry, err error) error { if err != nil { t.Fatal(err) } info, _ := os.Lstat(p) if d.IsDir() { if info.Mode().Perm() != 0o700 { t.Errorf("stage directory %s mode %v", p, info.Mode()) } return nil } if !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 { t.Errorf("stage entry %s mode %v", p, info.Mode()) } raw, _ := os.ReadFile(p) rel, _ := filepath.Rel(stage, p) out[rel] = string(raw) return nil }) return out } // treeState is every entry under dir with its mode, size, mtime and // content digest: what "nothing was written" compares. func treeState(t *testing.T, dir string) string { t.Helper() var lines []string filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { if err != nil { return nil } info, err := os.Lstat(p) if err != nil { return nil } sum := "" if info.Mode().IsRegular() { raw, _ := os.ReadFile(p) h := sha256.Sum256(raw) sum = hex.EncodeToString(h[:]) } lines = append(lines, fmt.Sprintf("%s %v %d %d %s", p, info.Mode(), info.Size(), info.ModTime().UnixNano(), sum)) return nil }) sort.Strings(lines) return strings.Join(lines, "\n") } // Only the output directory is copied, by exportStatic's rules: the // same files, the same digest as an export of the same tree from git // objects, the tree's _headers replaced by the runner's; nothing outside // the output is read into the stage and nothing in the workspace changes. func TestWorkSiteCopiesOnlyTheOutput(t *testing.T) { ws := workTree(t, siteFiles(), nil) before := treeState(t, ws) headers := "/*\n X-Runner: 1\n" ex, stage, err := copySite(t, ws, headers) if err != nil { t.Fatal(err) } got := staged(t, stage) want := map[string]string{ "index.html": "

home

", "about/index.html": "

about

", "a/b/c/d.css": "body{}", "_headers": headers, } if len(got) != len(want) { t.Fatalf("staged %v", got) } for k, v := range want { if got[k] != v { t.Fatalf("staged %s = %q, want %q", k, got[k], v) } } for k, v := range got { if strings.Contains(v, "OUTSIDE") { t.Fatalf("a file outside the output was copied: %s", k) } } if ex.Files != 4 || ex.Bytes != int64(len("

home

about

body{}")+len(headers)) { t.Fatalf("export %+v", ex) } if after := treeState(t, ws); after != before { t.Fatalf("the workspace changed:\n%s\n---\n%s", before, after) } // The same tree exported from git objects has the same digest. git, err := exec.LookPath("git") if err != nil { t.Skip("no git") } run := func(args ...string) string { cmd := exec.Command(git, args...) cmd.Dir = ws cmd.Env = []string{"HOME=/nonexistent", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com"} out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v %s", args, err, out) } return strings.TrimSpace(string(out)) } gitDir := filepath.Join(t.TempDir(), "git") run("init", "-q", "--separate-git-dir", gitDir) run("add", "-A") run("commit", "-q", "-m", "x") sha := run("rev-parse", "HEAD") os.Remove(filepath.Join(ws, ".git")) cfg, err := readPreviewConfig(context.Background(), git, gitDir, sha) if err != nil || cfg.Output != "site" { t.Fatalf("readPreviewConfig %+v %v", cfg, err) } fromGit, err := exportStatic(context.Background(), git, gitDir, sha, cfg.Output, filepath.Join(t.TempDir(), "git-stage"), headers) if err != nil { t.Fatal(err) } if fromGit != ex { t.Fatalf("work %+v, git objects %+v", ex, fromGit) } } // A link at any depth is never followed: not as release/ or its // preview.json, not as the output or any directory above or below it, not // as a file, whether it points inside the workspace or out of it. The // copy is refused and nothing it names reaches the stage. func TestWorkSiteFollowsNoLink(t *testing.T) { outside := t.TempDir() os.WriteFile(filepath.Join(outside, "preview.json"), []byte(`{"output": "site"}`), 0o644) os.WriteFile(filepath.Join(outside, "index.html"), []byte("LINKED"), 0o644) os.MkdirAll(filepath.Join(outside, "deep"), 0o755) os.WriteFile(filepath.Join(outside, "deep", "index.html"), []byte("LINKED"), 0o644) base := siteFiles() without := func(drop ...string) map[string]string { out := map[string]string{} for k, v := range base { out[k] = v } for _, d := range drop { for k := range out { if k == d || strings.HasPrefix(k, d+"/") { delete(out, k) } } } return out } with := func(files map[string]string, extra map[string]string) map[string]string { for k, v := range extra { files[k] = v } return files } for name, c := range map[string]struct { files, links map[string]string }{ "release is a link": {without("release"), map[string]string{"release": outside}}, "preview.json is a link": {without("release/preview.json"), map[string]string{"release/preview.json": filepath.Join(outside, "preview.json")}}, "the output is a link": {without("site"), map[string]string{"site": outside}}, "the output is a link inside": {with(without("site"), map[string]string{"real/index.html": "LINKED"}), map[string]string{"site": "real"}}, "a parent of the output": {with(without("site", "release"), map[string]string{"release/preview.json": `{"output": "web/site"}`}), map[string]string{"web": outside}}, "release is a link inside": {with(without("release"), map[string]string{"conf/preview.json": `{"output": "site"}`}), map[string]string{"release": "conf"}}, "a parent of the output, inside": {with(without("site", "release"), map[string]string{"release/preview.json": `{"output": "web/site"}`, "real/site/index.html": "LINKED"}), map[string]string{"web": "real"}}, "a file at the top": {base, map[string]string{"site/linked.html": filepath.Join(outside, "index.html")}}, "a file inside the tree": {base, map[string]string{"site/linked.html": "index.html"}}, "a directory": {base, map[string]string{"site/linked": filepath.Join(outside, "deep")}}, "a file four deep": {base, map[string]string{"site/a/b/c/linked.html": filepath.Join(outside, "index.html")}}, "a directory four deep": {base, map[string]string{"site/a/b/c/linked": outside}}, "a dangling link": {base, map[string]string{"site/a/gone": filepath.Join(outside, "missing")}}, "a link to /proc": {base, map[string]string{"site/self": "/proc/self/root"}}, } { ws := workTree(t, c.files, c.links) _, stage, err := copySite(t, ws, "") if !errors.Is(err, errPreviewConfig) { t.Errorf("%s: %v", name, err) } for k, v := range staged(t, stage) { if v == "LINKED" || strings.Contains(v, "OUTSIDE") { t.Errorf("%s: %s came through a link", name, k) } } } } // Only regular files and directories: a FIFO (which would block an open // for reading), a socket, a dot file or directory, a marker's name are // all refused, and refusing does not hang. func TestWorkSiteRefusesOtherEntries(t *testing.T) { cases := map[string]func(ws string) error{ "a fifo": func(ws string) error { return unix.Mkfifo(filepath.Join(ws, "site/pipe"), 0o644) }, "a socket": func(ws string) error { // sun_path is short: bind from inside the directory. wd, _ := os.Getwd() defer os.Chdir(wd) os.Chdir(filepath.Join(ws, "site")) l, err := net.Listen("unix", "sock") if err == nil { l.(*net.UnixListener).SetUnlinkOnClose(false) l.Close() } return err }, "a dot file": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/.env"), []byte("x"), 0o644) }, "an empty dot directory": func(ws string) error { return os.Mkdir(filepath.Join(ws, "site/.cache"), 0o755) }, "a nested dot file": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/a/.gitleaks.toml"), []byte("x"), 0o644) }, "the preview marker": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site", previewMarker), []byte("{}"), 0o644) }, "the site marker": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site", siteMarker), []byte("{}"), 0o644) }, "a backslash": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/a\\b"), []byte("x"), 0o644) }, "a newline": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/a\nb"), []byte("x"), 0o644) }, } for name, build := range cases { ws := workTree(t, siteFiles(), nil) if err := build(ws); err != nil { t.Fatalf("%s: %v", name, err) } done := async(func() error { _, _, err := copySite(t, ws, ""); return err }) select { case err := <-done: if !errors.Is(err, errPreviewConfig) { t.Errorf("%s: %v", name, err) } case <-time.After(10 * time.Second): t.Fatalf("%s: the copy hung", name) } } } func async(f func() error) <-chan error { c := make(chan error, 1) go func() { c <- f() }() return c } // release/preview.json by readPreviewConfig's rules: present, a regular // file, at most 4 KiB, strictly {"output": }; the output a // directory holding at least one file. func TestWorkSiteConfig(t *testing.T) { for name, cfg := range map[string]*string{ "missing": nil, "not JSON": ptr(`{"output": `), "an unknown field": ptr(`{"output": "site", "build": ["make"]}`), "two values": ptr(`{"output": "site"} {"output": "site"}`), "too large": ptr(`{"output": "site"}` + strings.Repeat(" ", previewMaxConfig)), "outside": ptr(`{"output": "../site"}`), "absolute": ptr(`{"output": "/site"}`), "a dot output": ptr(`{"output": ".git"}`), "unclean": ptr(`{"output": "site/"}`), "a file output": ptr(`{"output": "secret.txt"}`), "no such output": ptr(`{"output": "missing"}`), "an empty output": ptr(`{"output": "empty"}`), "only dirs": ptr(`{"output": "dirs"}`), } { files := siteFiles() delete(files, "release/preview.json") if cfg != nil { files["release/preview.json"] = *cfg } ws := workTree(t, files, nil) os.Mkdir(filepath.Join(ws, "empty"), 0o755) os.MkdirAll(filepath.Join(ws, "dirs/a/b"), 0o755) if _, _, err := copySite(t, ws, ""); !errors.Is(err, errPreviewConfig) { t.Errorf("%s: %v", name, err) } } // release/preview.json as a directory or a FIFO. ws := workTree(t, map[string]string{"site/index.html": "x"}, nil) os.MkdirAll(filepath.Join(ws, "release/preview.json"), 0o755) if _, _, err := copySite(t, ws, ""); !errors.Is(err, errPreviewConfig) { t.Errorf("a directory config: %v", err) } ws = workTree(t, map[string]string{"site/index.html": "x"}, nil) os.Mkdir(filepath.Join(ws, "release"), 0o755) unix.Mkfifo(filepath.Join(ws, "release/preview.json"), 0o644) select { case err := <-async(func() error { _, _, err := copySite(t, ws, ""); return err }): if !errors.Is(err, errPreviewConfig) { t.Errorf("a fifo config: %v", err) } case <-time.After(10 * time.Second): t.Fatal("a fifo config hung the copy") } } func ptr(s string) *string { return &s } // The caps of exportStatic (files, bytes, one file's size, the runner's // _headers counted), and the walk's own (depth, directories), refuse with // errPreviewTooLarge; at each cap exactly the copy goes through. The tree // starts with one file of one byte; large files are sparse (the caps read // sizes, not blocks). func TestWorkSiteCaps(t *testing.T) { sparse := func(ws, rel string, size int64) { p := filepath.Join(ws, rel) os.MkdirAll(filepath.Dir(p), 0o755) f, err := os.Create(p) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } f.Close() } // bytes fills the output to n bytes beside index.html. bytes := func(n int64) func(string) { return func(ws string) { for i := 0; n > 0; i++ { size := min(n, previewMaxFile) sparse(ws, fmt.Sprintf("site/v%d.bin", i), size) n -= size } } } files := func(n int) func(string) { return func(ws string) { for i := range n { os.WriteFile(filepath.Join(ws, fmt.Sprintf("site/f%d", i)), nil, 0o644) } } } dirs := func(n int) func(string) { return func(ws string) { for i := range n { os.Mkdir(filepath.Join(ws, fmt.Sprintf("site/d%d", i)), 0o755) } } } deep := func(n int) func(string) { return func(ws string) { p := filepath.Join(ws, "site") for range n - 1 { p = filepath.Join(p, "d") } os.MkdirAll(p, 0o755) os.WriteFile(filepath.Join(p, "x.html"), nil, 0o644) } } const h = "/*\n" // a runner _headers of 3 bytes for _, c := range []struct { name string build func(string) headers string refused bool }{ {"a file at the cap", func(ws string) { sparse(ws, "site/v.bin", previewMaxFile) }, "", false}, {"a file too large", func(ws string) { sparse(ws, "site/v.bin", previewMaxFile+1) }, "", true}, {"bytes at the cap", bytes(previewMaxBytes - 1), "", false}, {"too many bytes", bytes(previewMaxBytes), "", true}, {"bytes at the cap with headers", bytes(previewMaxBytes - 1 - 3), h, false}, {"too many bytes with headers", bytes(previewMaxBytes - 1 - 2), h, true}, {"files at the cap", files(previewMaxFiles - 1), "", false}, {"too many files", files(previewMaxFiles), "", true}, {"files at the cap with headers", files(previewMaxFiles - 2), h, false}, {"too many files with headers", files(previewMaxFiles - 1), h, true}, {"depth at the cap", deep(previewMaxDepth), "", false}, {"too deep", deep(previewMaxDepth + 1), "", true}, {"directories at the cap", dirs(previewMaxDirs), "", false}, {"files and directories at the caps, the tree's _headers skipped", func(ws string) { files(previewMaxFiles - 2)(ws) dirs(previewMaxDirs)(ws) os.WriteFile(filepath.Join(ws, "site/_headers"), []byte("/x\n"), 0o644) }, h, false}, {"too many directories", dirs(previewMaxDirs + 1), "", true}, } { ws := workTree(t, map[string]string{"release/preview.json": `{"output": "site"}`, "site/index.html": "x"}, nil) c.build(ws) _, _, err := copySite(t, ws, c.headers) if c.refused && !errors.Is(err, errPreviewTooLarge) || !c.refused && err != nil { t.Errorf("%s: %v", c.name, err) } } } // Past its deadline the copy stops and refuses with errWorkBusy. func TestWorkSiteDeadline(t *testing.T) { ws := workTree(t, siteFiles(), nil) st, err := openSiteStage(filepath.Join(t.TempDir(), "stage")) if err != nil { t.Fatal(err) } defer st.close() if _, err := copyWorkSite(ws, st, "", time.Now().Add(-time.Millisecond)); !errors.Is(err, errWorkBusy) { t.Fatalf("past the deadline: %v", err) } } // TestSnapshotKeepsToTheCallsDeadline (branch review finding 5): the // work snapshot is part of render_page's one deadline. Its pause is // bounded by the time the call has left when that is under the pause's // own bound, and a call already past its deadline pauses nothing: the // snapshot ends with the context's error before it tries (a kept process // that is gone would otherwise be refused busy by the pause). func TestSnapshotKeepsToTheCallsDeadline(t *testing.T) { if b, err := snapshotWithin(context.Background()); b != snapshotBound || err != nil { t.Fatalf("no deadline: %v %v", b, err) } ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if b, err := snapshotWithin(ctx); err != nil || b > time.Second || b < 500*time.Millisecond { t.Fatalf("a second left: %v %v", b, err) } long, cancelLong := context.WithTimeout(context.Background(), time.Hour) defer cancelLong() if b, err := snapshotWithin(long); b != snapshotBound || err != nil { t.Fatalf("an hour left: %v %v", b, err) } past, cancelPast := context.WithDeadline(context.Background(), time.Now().Add(-time.Millisecond)) defer cancelPast() if _, err := snapshotWithin(past); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("past the deadline: %v", err) } h := &sandboxHandle{} h.keep(containment.Record{ID: "ns-1", HostPID: 1 << 30, StartTicks: 99}) stage := filepath.Join(t.TempDir(), "stage") if _, err := h.snapshot(past, workTree(t, siteFiles(), nil), stage, ""); !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("a snapshot past the call's deadline: %v", err) } if _, err := os.Lstat(stage); !errors.Is(err, fs.ErrNotExist) { t.Fatalf("a refused snapshot left its stage: %v", err) } } // The handle keeps the sandbox's first process from the record written // once it runs, not the one written before the launch; a record that // cannot be written keeps nothing. func TestRecordedStartKeepsTheSandbox(t *testing.T) { h := &sandboxHandle{} f := &recordingStarter{records: []containment.Record{{ID: "ns-1"}, {ID: "ns-1", HostPID: 4242, StartTicks: 99, NamespaceID: "pid:[7]"}}} var ids []string if _, err := recordedStartKept(context.Background(), f, provider.Launch{}, []string{"/bin/true"}, func(_ context.Context, id string) error { ids = append(ids, id); return nil }, h); err != nil { t.Fatal(err) } if p, ok := h.current(); !ok || p != (pause.Process{PID: 4242, StartTicks: 99, Namespace: "pid:[7]"}) || len(ids) != 2 { t.Fatalf("kept %+v %v (ids %v)", p, ok, ids) } h.drop() if _, ok := h.current(); ok { t.Fatal("kept after drop") } if _, err := h.snapshot(context.Background(), t.TempDir(), filepath.Join(t.TempDir(), "s"), ""); !errors.Is(err, errWorkBusy) { t.Fatalf("a snapshot with no sandbox: %v", err) } h = &sandboxHandle{} f = &recordingStarter{records: []containment.Record{{ID: "ns-1", HostPID: 4242, StartTicks: 99}}} if _, err := recordedStartKept(context.Background(), f, provider.Launch{}, []string{"/bin/true"}, func(context.Context, string) error { return errors.New("no") }, h); err == nil { t.Fatal("started without its record") } if _, ok := h.current(); ok { t.Fatal("kept a sandbox whose record failed") } // The record written before the launch has no process: nothing kept. h = &sandboxHandle{} f = &recordingStarter{records: []containment.Record{{ID: "ns-1"}}} if _, err := recordedStartKept(context.Background(), f, provider.Launch{}, []string{"/bin/true"}, func(context.Context, string) error { return nil }, h); err != nil { t.Fatal(err) } if p, ok := h.current(); ok { t.Fatalf("kept the pre-launch record %+v", p) } // A nil handle keeps nothing and does not panic. var none *sandboxHandle none.keep(containment.Record{HostPID: 1, StartTicks: 1}) none.drop() } // recordingStarter calls record with each of records in turn, as // containment does before the launch and once it runs. type recordingStarter struct{ records []containment.Record } func (f *recordingStarter) StartRecorded(ctx context.Context, _ provider.Launch, _ []string, record func(context.Context, containment.Record) error) (provider.Process, error) { for _, r := range f.records { if err := record(ctx, r); err != nil { return nil, err } } return nil, nil } // stepSandbox starts script as the first process of a bubblewrap sandbox // made with the step sandbox's namespace arguments, and returns it as // containment records it; it is killed when the test ends. func stepSandbox(t *testing.T, env []string, script string) containment.Record { t.Helper() bwrap, err := exec.LookPath("bwrap") if err != nil { t.Skip("no bwrap") } status, statusW, err := os.Pipe() if err != nil { t.Fatal(err) } defer status.Close() args := append([]string{"--dev-bind", "/", "/", "--proc", "/proc"}, provider.NamespaceArguments()...) cmd := exec.Command(bwrap, append(args, "sh", "-c", script)...) cmd.Env = append([]string{"PATH=/usr/bin:/bin"}, env...) cmd.ExtraFiles = []*os.File{statusW} if err := cmd.Start(); err != nil { t.Fatal(err) } statusW.Close() var msg struct { PID int `json:"child-pid"` } status.SetReadDeadline(time.Now().Add(10 * time.Second)) if err := json.NewDecoder(status).Decode(&msg); err != nil || msg.PID <= 1 { cmd.Process.Kill() cmd.Wait() t.Skipf("bwrap did not start a sandbox here: %v", err) } fd, err := unix.PidfdOpen(msg.PID, 0) if err != nil { t.Fatal(err) } t.Cleanup(func() { unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) unix.Close(fd) cmd.Process.Kill() cmd.Wait() }) raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", msg.PID)) if err != nil { t.Fatal(err) } f := strings.Fields(string(raw[strings.LastIndexByte(string(raw), ')')+1:])) var start uint64 fmt.Sscan(f[19], &start) ns, _ := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", msg.PID)) return containment.Record{ID: "ns-1", HostPID: msg.PID, StartTicks: start, NamespaceID: ns} } // A snapshot of a running step: its writer, inside a nested namespace, // keeps rewriting a page of the site; the copy goes through, holds the // site, and the writer goes on afterwards. (That nothing runs during the // copy is the pause package's test.) A record whose process is gone is // refused as busy. func TestSnapshotWorkPausesTheStep(t *testing.T) { if _, err := exec.LookPath("unshare"); err != nil { t.Skip("no unshare") } ws := workTree(t, siteFiles(), nil) writer := `i=0; while :; do i=$((i+1)); echo $i > "$WS/site/count.txt"; echo $i >> "$LOG"; sleep 0.001; done` logPath := filepath.Join(t.TempDir(), "log") r := stepSandbox(t, []string{"WS=" + ws, "LOG=" + logPath, "W=" + writer}, `until unshare --user --pid --fork sh -c "$W"; do sleep 0.1; done & wait`) h := &sandboxHandle{} h.keep(r) size := func() int64 { info, _ := os.Stat(logPath); return sizeOf(info) } for deadline := time.Now().Add(10 * time.Second); size() < 64; { if time.Now().After(deadline) { t.Fatal("the writer never started") } time.Sleep(5 * time.Millisecond) } stage := filepath.Join(t.TempDir(), "stage") ex, err := h.snapshot(context.Background(), ws, stage, "") if err != nil { t.Fatal(err) } got := staged(t, stage) if ex.Files != 5 || got["index.html"] != "

home

" { t.Fatalf("export %+v %v", ex, got) } if _, ok := got["count.txt"]; !ok { t.Fatalf("the written page is missing: %v", got) } before := size() for deadline := time.Now().Add(2 * time.Second); size() == before; { if time.Now().After(deadline) { t.Fatal("the writer was not resumed") } time.Sleep(5 * time.Millisecond) } gone := r gone.StartTicks++ h.keep(gone) if _, err := h.snapshot(context.Background(), ws, stage, ""); !errors.Is(err, errWorkBusy) { t.Fatalf("a gone sandbox: %v", err) } if _, err := os.Lstat(stage); !errors.Is(err, fs.ErrNotExist) { t.Fatalf("a refused snapshot left its stage: %v", err) } // A refused site removes the stage too. h.keep(r) os.Remove(filepath.Join(ws, "release/preview.json")) if _, err := h.snapshot(context.Background(), ws, stage, ""); !errors.Is(err, errPreviewConfig) { t.Fatalf("no release/preview.json: %v", err) } if _, err := os.Lstat(stage); !errors.Is(err, fs.ErrNotExist) { t.Fatalf("a refused snapshot left its stage: %v", err) } } func sizeOf(info os.FileInfo) int64 { if info == nil { return 0 } return info.Size() }