| 1 | //go:build linux |
| 2 | |
| 3 | package thin |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "io/fs" |
| 13 | "net" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "path/filepath" |
| 17 | "sort" |
| 18 | "strings" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 23 | "amadan.net/oficina/equipo/internal/runner/pause" |
| 24 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 25 | "golang.org/x/sys/unix" |
| 26 | ) |
| 27 | |
| 28 | // workTree writes files (path to content) under a fresh workspace; links |
| 29 | // (path to target) are made as symlinks. |
| 30 | func workTree(t *testing.T, files, links map[string]string) string { |
| 31 | t.Helper() |
| 32 | ws := t.TempDir() |
| 33 | for rel, content := range files { |
| 34 | p := filepath.Join(ws, rel) |
| 35 | if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if err := os.WriteFile(p, []byte(content), 0o644); err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | } |
| 42 | for rel, target := range links { |
| 43 | p := filepath.Join(ws, rel) |
| 44 | if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | if err := os.Symlink(target, p); err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | } |
| 51 | return ws |
| 52 | } |
| 53 | |
| 54 | // siteFiles is a workspace whose release/preview.json names site, with |
| 55 | // files outside the output too. |
| 56 | func siteFiles() map[string]string { |
| 57 | return map[string]string{ |
| 58 | "release/preview.json": `{"output": "site"}`, |
| 59 | "site/index.html": "<h1>home</h1>", |
| 60 | "site/about/index.html": "<h1>about</h1>", |
| 61 | "site/a/b/c/d.css": "body{}", |
| 62 | "site/_headers": "/*\n X-Tree: 1\n", |
| 63 | "secret.txt": "OUTSIDE-THE-OUTPUT", |
| 64 | "other/notes.md": "OUTSIDE-THE-OUTPUT", |
| 65 | "sitemap/x.html": "OUTSIDE-THE-OUTPUT", |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // copySite runs copyWorkSite into a fresh stage and returns it. |
| 70 | func copySite(t *testing.T, ws, headers string) (previewExport, string, error) { |
| 71 | t.Helper() |
| 72 | stage := filepath.Join(t.TempDir(), "stage") |
| 73 | st, err := openSiteStage(stage) |
| 74 | if err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | defer st.close() |
| 78 | ex, err := copyWorkSite(ws, st, headers, time.Now().Add(time.Minute)) |
| 79 | return ex, stage, err |
| 80 | } |
| 81 | |
| 82 | // staged lists the stage's files (path to content) and fails on anything |
| 83 | // but regular files and directories. |
| 84 | func staged(t *testing.T, stage string) map[string]string { |
| 85 | t.Helper() |
| 86 | out := map[string]string{} |
| 87 | filepath.WalkDir(stage, func(p string, d fs.DirEntry, err error) error { |
| 88 | if err != nil { |
| 89 | t.Fatal(err) |
| 90 | } |
| 91 | info, _ := os.Lstat(p) |
| 92 | if d.IsDir() { |
| 93 | if info.Mode().Perm() != 0o700 { |
| 94 | t.Errorf("stage directory %s mode %v", p, info.Mode()) |
| 95 | } |
| 96 | return nil |
| 97 | } |
| 98 | if !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 { |
| 99 | t.Errorf("stage entry %s mode %v", p, info.Mode()) |
| 100 | } |
| 101 | raw, _ := os.ReadFile(p) |
| 102 | rel, _ := filepath.Rel(stage, p) |
| 103 | out[rel] = string(raw) |
| 104 | return nil |
| 105 | }) |
| 106 | return out |
| 107 | } |
| 108 | |
| 109 | // treeState is every entry under dir with its mode, size, mtime and |
| 110 | // content digest: what "nothing was written" compares. |
| 111 | func treeState(t *testing.T, dir string) string { |
| 112 | t.Helper() |
| 113 | var lines []string |
| 114 | filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { |
| 115 | if err != nil { |
| 116 | return nil |
| 117 | } |
| 118 | info, err := os.Lstat(p) |
| 119 | if err != nil { |
| 120 | return nil |
| 121 | } |
| 122 | sum := "" |
| 123 | if info.Mode().IsRegular() { |
| 124 | raw, _ := os.ReadFile(p) |
| 125 | h := sha256.Sum256(raw) |
| 126 | sum = hex.EncodeToString(h[:]) |
| 127 | } |
| 128 | lines = append(lines, fmt.Sprintf("%s %v %d %d %s", p, info.Mode(), info.Size(), info.ModTime().UnixNano(), sum)) |
| 129 | return nil |
| 130 | }) |
| 131 | sort.Strings(lines) |
| 132 | return strings.Join(lines, "\n") |
| 133 | } |
| 134 | |
| 135 | // Only the output directory is copied, by exportStatic's rules: the |
| 136 | // same files, the same digest as an export of the same tree from git |
| 137 | // objects, the tree's _headers replaced by the runner's; nothing outside |
| 138 | // the output is read into the stage and nothing in the workspace changes. |
| 139 | func TestWorkSiteCopiesOnlyTheOutput(t *testing.T) { |
| 140 | ws := workTree(t, siteFiles(), nil) |
| 141 | before := treeState(t, ws) |
| 142 | headers := "/*\n X-Runner: 1\n" |
| 143 | ex, stage, err := copySite(t, ws, headers) |
| 144 | if err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | got := staged(t, stage) |
| 148 | want := map[string]string{ |
| 149 | "index.html": "<h1>home</h1>", |
| 150 | "about/index.html": "<h1>about</h1>", |
| 151 | "a/b/c/d.css": "body{}", |
| 152 | "_headers": headers, |
| 153 | } |
| 154 | if len(got) != len(want) { |
| 155 | t.Fatalf("staged %v", got) |
| 156 | } |
| 157 | for k, v := range want { |
| 158 | if got[k] != v { |
| 159 | t.Fatalf("staged %s = %q, want %q", k, got[k], v) |
| 160 | } |
| 161 | } |
| 162 | for k, v := range got { |
| 163 | if strings.Contains(v, "OUTSIDE") { |
| 164 | t.Fatalf("a file outside the output was copied: %s", k) |
| 165 | } |
| 166 | } |
| 167 | if ex.Files != 4 || ex.Bytes != int64(len("<h1>home</h1><h1>about</h1>body{}")+len(headers)) { |
| 168 | t.Fatalf("export %+v", ex) |
| 169 | } |
| 170 | if after := treeState(t, ws); after != before { |
| 171 | t.Fatalf("the workspace changed:\n%s\n---\n%s", before, after) |
| 172 | } |
| 173 | |
| 174 | // The same tree exported from git objects has the same digest. |
| 175 | git, err := exec.LookPath("git") |
| 176 | if err != nil { |
| 177 | t.Skip("no git") |
| 178 | } |
| 179 | run := func(args ...string) string { |
| 180 | cmd := exec.Command(git, args...) |
| 181 | cmd.Dir = ws |
| 182 | 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"} |
| 183 | out, err := cmd.CombinedOutput() |
| 184 | if err != nil { |
| 185 | t.Fatalf("git %v: %v %s", args, err, out) |
| 186 | } |
| 187 | return strings.TrimSpace(string(out)) |
| 188 | } |
| 189 | gitDir := filepath.Join(t.TempDir(), "git") |
| 190 | run("init", "-q", "--separate-git-dir", gitDir) |
| 191 | run("add", "-A") |
| 192 | run("commit", "-q", "-m", "x") |
| 193 | sha := run("rev-parse", "HEAD") |
| 194 | os.Remove(filepath.Join(ws, ".git")) |
| 195 | cfg, err := readPreviewConfig(context.Background(), git, gitDir, sha) |
| 196 | if err != nil || cfg.Output != "site" { |
| 197 | t.Fatalf("readPreviewConfig %+v %v", cfg, err) |
| 198 | } |
| 199 | fromGit, err := exportStatic(context.Background(), git, gitDir, sha, cfg.Output, filepath.Join(t.TempDir(), "git-stage"), headers) |
| 200 | if err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | if fromGit != ex { |
| 204 | t.Fatalf("work %+v, git objects %+v", ex, fromGit) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // A link at any depth is never followed: not as release/ or its |
| 209 | // preview.json, not as the output or any directory above or below it, not |
| 210 | // as a file, whether it points inside the workspace or out of it. The |
| 211 | // copy is refused and nothing it names reaches the stage. |
| 212 | func TestWorkSiteFollowsNoLink(t *testing.T) { |
| 213 | outside := t.TempDir() |
| 214 | os.WriteFile(filepath.Join(outside, "preview.json"), []byte(`{"output": "site"}`), 0o644) |
| 215 | os.WriteFile(filepath.Join(outside, "index.html"), []byte("LINKED"), 0o644) |
| 216 | os.MkdirAll(filepath.Join(outside, "deep"), 0o755) |
| 217 | os.WriteFile(filepath.Join(outside, "deep", "index.html"), []byte("LINKED"), 0o644) |
| 218 | base := siteFiles() |
| 219 | without := func(drop ...string) map[string]string { |
| 220 | out := map[string]string{} |
| 221 | for k, v := range base { |
| 222 | out[k] = v |
| 223 | } |
| 224 | for _, d := range drop { |
| 225 | for k := range out { |
| 226 | if k == d || strings.HasPrefix(k, d+"/") { |
| 227 | delete(out, k) |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | return out |
| 232 | } |
| 233 | with := func(files map[string]string, extra map[string]string) map[string]string { |
| 234 | for k, v := range extra { |
| 235 | files[k] = v |
| 236 | } |
| 237 | return files |
| 238 | } |
| 239 | for name, c := range map[string]struct { |
| 240 | files, links map[string]string |
| 241 | }{ |
| 242 | "release is a link": {without("release"), map[string]string{"release": outside}}, |
| 243 | "preview.json is a link": {without("release/preview.json"), map[string]string{"release/preview.json": filepath.Join(outside, "preview.json")}}, |
| 244 | "the output is a link": {without("site"), map[string]string{"site": outside}}, |
| 245 | "the output is a link inside": {with(without("site"), map[string]string{"real/index.html": "LINKED"}), map[string]string{"site": "real"}}, |
| 246 | "a parent of the output": {with(without("site", "release"), map[string]string{"release/preview.json": `{"output": "web/site"}`}), map[string]string{"web": outside}}, |
| 247 | "release is a link inside": {with(without("release"), map[string]string{"conf/preview.json": `{"output": "site"}`}), map[string]string{"release": "conf"}}, |
| 248 | "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"}}, |
| 249 | "a file at the top": {base, map[string]string{"site/linked.html": filepath.Join(outside, "index.html")}}, |
| 250 | "a file inside the tree": {base, map[string]string{"site/linked.html": "index.html"}}, |
| 251 | "a directory": {base, map[string]string{"site/linked": filepath.Join(outside, "deep")}}, |
| 252 | "a file four deep": {base, map[string]string{"site/a/b/c/linked.html": filepath.Join(outside, "index.html")}}, |
| 253 | "a directory four deep": {base, map[string]string{"site/a/b/c/linked": outside}}, |
| 254 | "a dangling link": {base, map[string]string{"site/a/gone": filepath.Join(outside, "missing")}}, |
| 255 | "a link to /proc": {base, map[string]string{"site/self": "/proc/self/root"}}, |
| 256 | } { |
| 257 | ws := workTree(t, c.files, c.links) |
| 258 | _, stage, err := copySite(t, ws, "") |
| 259 | if !errors.Is(err, errPreviewConfig) { |
| 260 | t.Errorf("%s: %v", name, err) |
| 261 | } |
| 262 | for k, v := range staged(t, stage) { |
| 263 | if v == "LINKED" || strings.Contains(v, "OUTSIDE") { |
| 264 | t.Errorf("%s: %s came through a link", name, k) |
| 265 | } |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // Only regular files and directories: a FIFO (which would block an open |
| 271 | // for reading), a socket, a dot file or directory, a marker's name are |
| 272 | // all refused, and refusing does not hang. |
| 273 | func TestWorkSiteRefusesOtherEntries(t *testing.T) { |
| 274 | cases := map[string]func(ws string) error{ |
| 275 | "a fifo": func(ws string) error { return unix.Mkfifo(filepath.Join(ws, "site/pipe"), 0o644) }, |
| 276 | "a socket": func(ws string) error { |
| 277 | // sun_path is short: bind from inside the directory. |
| 278 | wd, _ := os.Getwd() |
| 279 | defer os.Chdir(wd) |
| 280 | os.Chdir(filepath.Join(ws, "site")) |
| 281 | l, err := net.Listen("unix", "sock") |
| 282 | if err == nil { |
| 283 | l.(*net.UnixListener).SetUnlinkOnClose(false) |
| 284 | l.Close() |
| 285 | } |
| 286 | return err |
| 287 | }, |
| 288 | "a dot file": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/.env"), []byte("x"), 0o644) }, |
| 289 | "an empty dot directory": func(ws string) error { return os.Mkdir(filepath.Join(ws, "site/.cache"), 0o755) }, |
| 290 | "a nested dot file": func(ws string) error { |
| 291 | return os.WriteFile(filepath.Join(ws, "site/a/.gitleaks.toml"), []byte("x"), 0o644) |
| 292 | }, |
| 293 | "the preview marker": func(ws string) error { |
| 294 | return os.WriteFile(filepath.Join(ws, "site", previewMarker), []byte("{}"), 0o644) |
| 295 | }, |
| 296 | "the site marker": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site", siteMarker), []byte("{}"), 0o644) }, |
| 297 | "a backslash": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/a\\b"), []byte("x"), 0o644) }, |
| 298 | "a newline": func(ws string) error { return os.WriteFile(filepath.Join(ws, "site/a\nb"), []byte("x"), 0o644) }, |
| 299 | } |
| 300 | for name, build := range cases { |
| 301 | ws := workTree(t, siteFiles(), nil) |
| 302 | if err := build(ws); err != nil { |
| 303 | t.Fatalf("%s: %v", name, err) |
| 304 | } |
| 305 | done := async(func() error { _, _, err := copySite(t, ws, ""); return err }) |
| 306 | select { |
| 307 | case err := <-done: |
| 308 | if !errors.Is(err, errPreviewConfig) { |
| 309 | t.Errorf("%s: %v", name, err) |
| 310 | } |
| 311 | case <-time.After(10 * time.Second): |
| 312 | t.Fatalf("%s: the copy hung", name) |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | func async(f func() error) <-chan error { |
| 318 | c := make(chan error, 1) |
| 319 | go func() { c <- f() }() |
| 320 | return c |
| 321 | } |
| 322 | |
| 323 | // release/preview.json by readPreviewConfig's rules: present, a regular |
| 324 | // file, at most 4 KiB, strictly {"output": <clean path>}; the output a |
| 325 | // directory holding at least one file. |
| 326 | func TestWorkSiteConfig(t *testing.T) { |
| 327 | for name, cfg := range map[string]*string{ |
| 328 | "missing": nil, |
| 329 | "not JSON": ptr(`{"output": `), |
| 330 | "an unknown field": ptr(`{"output": "site", "build": ["make"]}`), |
| 331 | "two values": ptr(`{"output": "site"} {"output": "site"}`), |
| 332 | "too large": ptr(`{"output": "site"}` + strings.Repeat(" ", previewMaxConfig)), |
| 333 | "outside": ptr(`{"output": "../site"}`), |
| 334 | "absolute": ptr(`{"output": "/site"}`), |
| 335 | "a dot output": ptr(`{"output": ".git"}`), |
| 336 | "unclean": ptr(`{"output": "site/"}`), |
| 337 | "a file output": ptr(`{"output": "secret.txt"}`), |
| 338 | "no such output": ptr(`{"output": "missing"}`), |
| 339 | "an empty output": ptr(`{"output": "empty"}`), |
| 340 | "only dirs": ptr(`{"output": "dirs"}`), |
| 341 | } { |
| 342 | files := siteFiles() |
| 343 | delete(files, "release/preview.json") |
| 344 | if cfg != nil { |
| 345 | files["release/preview.json"] = *cfg |
| 346 | } |
| 347 | ws := workTree(t, files, nil) |
| 348 | os.Mkdir(filepath.Join(ws, "empty"), 0o755) |
| 349 | os.MkdirAll(filepath.Join(ws, "dirs/a/b"), 0o755) |
| 350 | if _, _, err := copySite(t, ws, ""); !errors.Is(err, errPreviewConfig) { |
| 351 | t.Errorf("%s: %v", name, err) |
| 352 | } |
| 353 | } |
| 354 | // release/preview.json as a directory or a FIFO. |
| 355 | ws := workTree(t, map[string]string{"site/index.html": "x"}, nil) |
| 356 | os.MkdirAll(filepath.Join(ws, "release/preview.json"), 0o755) |
| 357 | if _, _, err := copySite(t, ws, ""); !errors.Is(err, errPreviewConfig) { |
| 358 | t.Errorf("a directory config: %v", err) |
| 359 | } |
| 360 | ws = workTree(t, map[string]string{"site/index.html": "x"}, nil) |
| 361 | os.Mkdir(filepath.Join(ws, "release"), 0o755) |
| 362 | unix.Mkfifo(filepath.Join(ws, "release/preview.json"), 0o644) |
| 363 | select { |
| 364 | case err := <-async(func() error { _, _, err := copySite(t, ws, ""); return err }): |
| 365 | if !errors.Is(err, errPreviewConfig) { |
| 366 | t.Errorf("a fifo config: %v", err) |
| 367 | } |
| 368 | case <-time.After(10 * time.Second): |
| 369 | t.Fatal("a fifo config hung the copy") |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | func ptr(s string) *string { return &s } |
| 374 | |
| 375 | // The caps of exportStatic (files, bytes, one file's size, the runner's |
| 376 | // _headers counted), and the walk's own (depth, directories), refuse with |
| 377 | // errPreviewTooLarge; at each cap exactly the copy goes through. The tree |
| 378 | // starts with one file of one byte; large files are sparse (the caps read |
| 379 | // sizes, not blocks). |
| 380 | func TestWorkSiteCaps(t *testing.T) { |
| 381 | sparse := func(ws, rel string, size int64) { |
| 382 | p := filepath.Join(ws, rel) |
| 383 | os.MkdirAll(filepath.Dir(p), 0o755) |
| 384 | f, err := os.Create(p) |
| 385 | if err != nil { |
| 386 | t.Fatal(err) |
| 387 | } |
| 388 | if err := f.Truncate(size); err != nil { |
| 389 | t.Fatal(err) |
| 390 | } |
| 391 | f.Close() |
| 392 | } |
| 393 | // bytes fills the output to n bytes beside index.html. |
| 394 | bytes := func(n int64) func(string) { |
| 395 | return func(ws string) { |
| 396 | for i := 0; n > 0; i++ { |
| 397 | size := min(n, previewMaxFile) |
| 398 | sparse(ws, fmt.Sprintf("site/v%d.bin", i), size) |
| 399 | n -= size |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | files := func(n int) func(string) { |
| 404 | return func(ws string) { |
| 405 | for i := range n { |
| 406 | os.WriteFile(filepath.Join(ws, fmt.Sprintf("site/f%d", i)), nil, 0o644) |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | dirs := func(n int) func(string) { |
| 411 | return func(ws string) { |
| 412 | for i := range n { |
| 413 | os.Mkdir(filepath.Join(ws, fmt.Sprintf("site/d%d", i)), 0o755) |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | deep := func(n int) func(string) { |
| 418 | return func(ws string) { |
| 419 | p := filepath.Join(ws, "site") |
| 420 | for range n - 1 { |
| 421 | p = filepath.Join(p, "d") |
| 422 | } |
| 423 | os.MkdirAll(p, 0o755) |
| 424 | os.WriteFile(filepath.Join(p, "x.html"), nil, 0o644) |
| 425 | } |
| 426 | } |
| 427 | const h = "/*\n" // a runner _headers of 3 bytes |
| 428 | for _, c := range []struct { |
| 429 | name string |
| 430 | build func(string) |
| 431 | headers string |
| 432 | refused bool |
| 433 | }{ |
| 434 | {"a file at the cap", func(ws string) { sparse(ws, "site/v.bin", previewMaxFile) }, "", false}, |
| 435 | {"a file too large", func(ws string) { sparse(ws, "site/v.bin", previewMaxFile+1) }, "", true}, |
| 436 | {"bytes at the cap", bytes(previewMaxBytes - 1), "", false}, |
| 437 | {"too many bytes", bytes(previewMaxBytes), "", true}, |
| 438 | {"bytes at the cap with headers", bytes(previewMaxBytes - 1 - 3), h, false}, |
| 439 | {"too many bytes with headers", bytes(previewMaxBytes - 1 - 2), h, true}, |
| 440 | {"files at the cap", files(previewMaxFiles - 1), "", false}, |
| 441 | {"too many files", files(previewMaxFiles), "", true}, |
| 442 | {"files at the cap with headers", files(previewMaxFiles - 2), h, false}, |
| 443 | {"too many files with headers", files(previewMaxFiles - 1), h, true}, |
| 444 | {"depth at the cap", deep(previewMaxDepth), "", false}, |
| 445 | {"too deep", deep(previewMaxDepth + 1), "", true}, |
| 446 | {"directories at the cap", dirs(previewMaxDirs), "", false}, |
| 447 | {"files and directories at the caps, the tree's _headers skipped", func(ws string) { |
| 448 | files(previewMaxFiles - 2)(ws) |
| 449 | dirs(previewMaxDirs)(ws) |
| 450 | os.WriteFile(filepath.Join(ws, "site/_headers"), []byte("/x\n"), 0o644) |
| 451 | }, h, false}, |
| 452 | {"too many directories", dirs(previewMaxDirs + 1), "", true}, |
| 453 | } { |
| 454 | ws := workTree(t, map[string]string{"release/preview.json": `{"output": "site"}`, "site/index.html": "x"}, nil) |
| 455 | c.build(ws) |
| 456 | _, _, err := copySite(t, ws, c.headers) |
| 457 | if c.refused && !errors.Is(err, errPreviewTooLarge) || !c.refused && err != nil { |
| 458 | t.Errorf("%s: %v", c.name, err) |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | |
| 463 | // Past its deadline the copy stops and refuses with errWorkBusy. |
| 464 | func TestWorkSiteDeadline(t *testing.T) { |
| 465 | ws := workTree(t, siteFiles(), nil) |
| 466 | st, err := openSiteStage(filepath.Join(t.TempDir(), "stage")) |
| 467 | if err != nil { |
| 468 | t.Fatal(err) |
| 469 | } |
| 470 | defer st.close() |
| 471 | if _, err := copyWorkSite(ws, st, "", time.Now().Add(-time.Millisecond)); !errors.Is(err, errWorkBusy) { |
| 472 | t.Fatalf("past the deadline: %v", err) |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | // TestSnapshotKeepsToTheCallsDeadline (branch review finding 5): the |
| 477 | // work snapshot is part of render_page's one deadline. Its pause is |
| 478 | // bounded by the time the call has left when that is under the pause's |
| 479 | // own bound, and a call already past its deadline pauses nothing: the |
| 480 | // snapshot ends with the context's error before it tries (a kept process |
| 481 | // that is gone would otherwise be refused busy by the pause). |
| 482 | func TestSnapshotKeepsToTheCallsDeadline(t *testing.T) { |
| 483 | if b, err := snapshotWithin(context.Background()); b != snapshotBound || err != nil { |
| 484 | t.Fatalf("no deadline: %v %v", b, err) |
| 485 | } |
| 486 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 487 | defer cancel() |
| 488 | if b, err := snapshotWithin(ctx); err != nil || b > time.Second || b < 500*time.Millisecond { |
| 489 | t.Fatalf("a second left: %v %v", b, err) |
| 490 | } |
| 491 | long, cancelLong := context.WithTimeout(context.Background(), time.Hour) |
| 492 | defer cancelLong() |
| 493 | if b, err := snapshotWithin(long); b != snapshotBound || err != nil { |
| 494 | t.Fatalf("an hour left: %v %v", b, err) |
| 495 | } |
| 496 | past, cancelPast := context.WithDeadline(context.Background(), time.Now().Add(-time.Millisecond)) |
| 497 | defer cancelPast() |
| 498 | if _, err := snapshotWithin(past); !errors.Is(err, context.DeadlineExceeded) { |
| 499 | t.Fatalf("past the deadline: %v", err) |
| 500 | } |
| 501 | h := &sandboxHandle{} |
| 502 | h.keep(containment.Record{ID: "ns-1", HostPID: 1 << 30, StartTicks: 99}) |
| 503 | stage := filepath.Join(t.TempDir(), "stage") |
| 504 | if _, err := h.snapshot(past, workTree(t, siteFiles(), nil), stage, ""); !errors.Is(err, context.DeadlineExceeded) { |
| 505 | t.Fatalf("a snapshot past the call's deadline: %v", err) |
| 506 | } |
| 507 | if _, err := os.Lstat(stage); !errors.Is(err, fs.ErrNotExist) { |
| 508 | t.Fatalf("a refused snapshot left its stage: %v", err) |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | // The handle keeps the sandbox's first process from the record written |
| 513 | // once it runs, not the one written before the launch; a record that |
| 514 | // cannot be written keeps nothing. |
| 515 | func TestRecordedStartKeepsTheSandbox(t *testing.T) { |
| 516 | h := &sandboxHandle{} |
| 517 | f := &recordingStarter{records: []containment.Record{{ID: "ns-1"}, {ID: "ns-1", HostPID: 4242, StartTicks: 99, NamespaceID: "pid:[7]"}}} |
| 518 | var ids []string |
| 519 | 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 { |
| 520 | t.Fatal(err) |
| 521 | } |
| 522 | if p, ok := h.current(); !ok || p != (pause.Process{PID: 4242, StartTicks: 99, Namespace: "pid:[7]"}) || len(ids) != 2 { |
| 523 | t.Fatalf("kept %+v %v (ids %v)", p, ok, ids) |
| 524 | } |
| 525 | h.drop() |
| 526 | if _, ok := h.current(); ok { |
| 527 | t.Fatal("kept after drop") |
| 528 | } |
| 529 | if _, err := h.snapshot(context.Background(), t.TempDir(), filepath.Join(t.TempDir(), "s"), ""); !errors.Is(err, errWorkBusy) { |
| 530 | t.Fatalf("a snapshot with no sandbox: %v", err) |
| 531 | } |
| 532 | h = &sandboxHandle{} |
| 533 | f = &recordingStarter{records: []containment.Record{{ID: "ns-1", HostPID: 4242, StartTicks: 99}}} |
| 534 | if _, err := recordedStartKept(context.Background(), f, provider.Launch{}, []string{"/bin/true"}, func(context.Context, string) error { return errors.New("no") }, h); err == nil { |
| 535 | t.Fatal("started without its record") |
| 536 | } |
| 537 | if _, ok := h.current(); ok { |
| 538 | t.Fatal("kept a sandbox whose record failed") |
| 539 | } |
| 540 | // The record written before the launch has no process: nothing kept. |
| 541 | h = &sandboxHandle{} |
| 542 | f = &recordingStarter{records: []containment.Record{{ID: "ns-1"}}} |
| 543 | if _, err := recordedStartKept(context.Background(), f, provider.Launch{}, []string{"/bin/true"}, func(context.Context, string) error { return nil }, h); err != nil { |
| 544 | t.Fatal(err) |
| 545 | } |
| 546 | if p, ok := h.current(); ok { |
| 547 | t.Fatalf("kept the pre-launch record %+v", p) |
| 548 | } |
| 549 | // A nil handle keeps nothing and does not panic. |
| 550 | var none *sandboxHandle |
| 551 | none.keep(containment.Record{HostPID: 1, StartTicks: 1}) |
| 552 | none.drop() |
| 553 | } |
| 554 | |
| 555 | // recordingStarter calls record with each of records in turn, as |
| 556 | // containment does before the launch and once it runs. |
| 557 | type recordingStarter struct{ records []containment.Record } |
| 558 | |
| 559 | func (f *recordingStarter) StartRecorded(ctx context.Context, _ provider.Launch, _ []string, record func(context.Context, containment.Record) error) (provider.Process, error) { |
| 560 | for _, r := range f.records { |
| 561 | if err := record(ctx, r); err != nil { |
| 562 | return nil, err |
| 563 | } |
| 564 | } |
| 565 | return nil, nil |
| 566 | } |
| 567 | |
| 568 | // stepSandbox starts script as the first process of a bubblewrap sandbox |
| 569 | // made with the step sandbox's namespace arguments, and returns it as |
| 570 | // containment records it; it is killed when the test ends. |
| 571 | func stepSandbox(t *testing.T, env []string, script string) containment.Record { |
| 572 | t.Helper() |
| 573 | bwrap, err := exec.LookPath("bwrap") |
| 574 | if err != nil { |
| 575 | t.Skip("no bwrap") |
| 576 | } |
| 577 | status, statusW, err := os.Pipe() |
| 578 | if err != nil { |
| 579 | t.Fatal(err) |
| 580 | } |
| 581 | defer status.Close() |
| 582 | args := append([]string{"--dev-bind", "/", "/", "--proc", "/proc"}, provider.NamespaceArguments()...) |
| 583 | cmd := exec.Command(bwrap, append(args, "sh", "-c", script)...) |
| 584 | cmd.Env = append([]string{"PATH=/usr/bin:/bin"}, env...) |
| 585 | cmd.ExtraFiles = []*os.File{statusW} |
| 586 | if err := cmd.Start(); err != nil { |
| 587 | t.Fatal(err) |
| 588 | } |
| 589 | statusW.Close() |
| 590 | var msg struct { |
| 591 | PID int `json:"child-pid"` |
| 592 | } |
| 593 | status.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 594 | if err := json.NewDecoder(status).Decode(&msg); err != nil || msg.PID <= 1 { |
| 595 | cmd.Process.Kill() |
| 596 | cmd.Wait() |
| 597 | t.Skipf("bwrap did not start a sandbox here: %v", err) |
| 598 | } |
| 599 | fd, err := unix.PidfdOpen(msg.PID, 0) |
| 600 | if err != nil { |
| 601 | t.Fatal(err) |
| 602 | } |
| 603 | t.Cleanup(func() { |
| 604 | unix.PidfdSendSignal(fd, unix.SIGKILL, nil, 0) |
| 605 | unix.Close(fd) |
| 606 | cmd.Process.Kill() |
| 607 | cmd.Wait() |
| 608 | }) |
| 609 | raw, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", msg.PID)) |
| 610 | if err != nil { |
| 611 | t.Fatal(err) |
| 612 | } |
| 613 | f := strings.Fields(string(raw[strings.LastIndexByte(string(raw), ')')+1:])) |
| 614 | var start uint64 |
| 615 | fmt.Sscan(f[19], &start) |
| 616 | ns, _ := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", msg.PID)) |
| 617 | return containment.Record{ID: "ns-1", HostPID: msg.PID, StartTicks: start, NamespaceID: ns} |
| 618 | } |
| 619 | |
| 620 | // A snapshot of a running step: its writer, inside a nested namespace, |
| 621 | // keeps rewriting a page of the site; the copy goes through, holds the |
| 622 | // site, and the writer goes on afterwards. (That nothing runs during the |
| 623 | // copy is the pause package's test.) A record whose process is gone is |
| 624 | // refused as busy. |
| 625 | func TestSnapshotWorkPausesTheStep(t *testing.T) { |
| 626 | if _, err := exec.LookPath("unshare"); err != nil { |
| 627 | t.Skip("no unshare") |
| 628 | } |
| 629 | ws := workTree(t, siteFiles(), nil) |
| 630 | writer := `i=0; while :; do i=$((i+1)); echo $i > "$WS/site/count.txt"; echo $i >> "$LOG"; sleep 0.001; done` |
| 631 | logPath := filepath.Join(t.TempDir(), "log") |
| 632 | r := stepSandbox(t, []string{"WS=" + ws, "LOG=" + logPath, "W=" + writer}, |
| 633 | `until unshare --user --pid --fork sh -c "$W"; do sleep 0.1; done & wait`) |
| 634 | h := &sandboxHandle{} |
| 635 | h.keep(r) |
| 636 | size := func() int64 { info, _ := os.Stat(logPath); return sizeOf(info) } |
| 637 | for deadline := time.Now().Add(10 * time.Second); size() < 64; { |
| 638 | if time.Now().After(deadline) { |
| 639 | t.Fatal("the writer never started") |
| 640 | } |
| 641 | time.Sleep(5 * time.Millisecond) |
| 642 | } |
| 643 | stage := filepath.Join(t.TempDir(), "stage") |
| 644 | ex, err := h.snapshot(context.Background(), ws, stage, "") |
| 645 | if err != nil { |
| 646 | t.Fatal(err) |
| 647 | } |
| 648 | got := staged(t, stage) |
| 649 | if ex.Files != 5 || got["index.html"] != "<h1>home</h1>" { |
| 650 | t.Fatalf("export %+v %v", ex, got) |
| 651 | } |
| 652 | if _, ok := got["count.txt"]; !ok { |
| 653 | t.Fatalf("the written page is missing: %v", got) |
| 654 | } |
| 655 | before := size() |
| 656 | for deadline := time.Now().Add(2 * time.Second); size() == before; { |
| 657 | if time.Now().After(deadline) { |
| 658 | t.Fatal("the writer was not resumed") |
| 659 | } |
| 660 | time.Sleep(5 * time.Millisecond) |
| 661 | } |
| 662 | gone := r |
| 663 | gone.StartTicks++ |
| 664 | h.keep(gone) |
| 665 | if _, err := h.snapshot(context.Background(), ws, stage, ""); !errors.Is(err, errWorkBusy) { |
| 666 | t.Fatalf("a gone sandbox: %v", err) |
| 667 | } |
| 668 | if _, err := os.Lstat(stage); !errors.Is(err, fs.ErrNotExist) { |
| 669 | t.Fatalf("a refused snapshot left its stage: %v", err) |
| 670 | } |
| 671 | // A refused site removes the stage too. |
| 672 | h.keep(r) |
| 673 | os.Remove(filepath.Join(ws, "release/preview.json")) |
| 674 | if _, err := h.snapshot(context.Background(), ws, stage, ""); !errors.Is(err, errPreviewConfig) { |
| 675 | t.Fatalf("no release/preview.json: %v", err) |
| 676 | } |
| 677 | if _, err := os.Lstat(stage); !errors.Is(err, fs.ErrNotExist) { |
| 678 | t.Fatalf("a refused snapshot left its stage: %v", err) |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | func sizeOf(info os.FileInfo) int64 { |
| 683 | if info == nil { |
| 684 | return 0 |
| 685 | } |
| 686 | return info.Size() |
| 687 | } |
| 688 | |