//go:build linux package render import ( "bufio" "context" "fmt" "os" "os/exec" "path/filepath" "strconv" "strings" "sync/atomic" "testing" "time" "golang.org/x/sys/unix" ) // processTree starts a shell with two children and returns it once both // are running. func processTree(t *testing.T) *exec.Cmd { t.Helper() sh, err := exec.LookPath("sh") if err != nil { t.Skip("no sh") } cmd := exec.Command(sh, "-c", "sleep 30 & sleep 30 & wait") if err := cmd.Start(); err != nil { t.Fatal(err) } t.Cleanup(func() { for _, pid := range descendants(cmd.Process.Pid) { unix.Kill(pid, unix.SIGKILL) } cmd.Process.Kill() cmd.Wait() }) deadline := time.Now().Add(5 * time.Second) for len(descendants(cmd.Process.Pid)) < 2 { if time.Now().After(deadline) { t.Fatal("the shell's children did not start") } time.Sleep(10 * time.Millisecond) } return cmd } // The sum is the whole tree's: the root and every process below it. func TestTreeRSSSumsTheTree(t *testing.T) { cmd := processTree(t) page := int64(os.Getpagesize()) root := residentPages(cmd.Process.Pid) * page want := root for _, pid := range descendants(cmd.Process.Pid) { want += residentPages(pid) * page } got := treeRSS(cmd.Process.Pid) if root <= 0 || got <= root || got < want*9/10 { t.Fatalf("tree %d, root alone %d, processes summed %d", got, root, want) } if treeRSS(1<<30) != 0 { t.Fatal("a process that does not exist holds memory") } } // The watch kills over the limit, once, and not under it. func TestWatchMemory(t *testing.T) { cmd := processTree(t) sandbox := func() *Sandbox { fd, err := unix.PidfdOpen(cmd.Process.Pid, 0) if err != nil { t.Skipf("pidfd_open: %v", err) } t.Cleanup(func() { unix.Close(fd) }) return &Sandbox{pidfd: fd, done: make(chan struct{})} } s := sandbox() if s.initPID() != cmd.Process.Pid { t.Fatalf("init %d, want %d", s.initPID(), cmd.Process.Pid) } var fired atomic.Int32 // Above the root's own memory, below the tree's. limit := residentPages(cmd.Process.Pid)*int64(os.Getpagesize()) + 1 stop := watchMemory(s, limit, func() { fired.Add(1) }) deadline := time.Now().Add(2 * time.Second) for fired.Load() == 0 && time.Now().Before(deadline) { time.Sleep(10 * time.Millisecond) } time.Sleep(3 * memoryEvery) stop() if fired.Load() != 1 { t.Fatalf("over the limit: fired %d times", fired.Load()) } stop = watchMemory(sandbox(), 1<<40, func() { fired.Add(1) }) time.Sleep(3 * memoryEvery) stop() if fired.Load() != 1 { t.Fatal("fired under the limit") } } // Every process in the sandbox, the browser's included, has the call's // memory limit as its data segment's soft and hard limit. func TestSandboxHasTheMemoryLimit(t *testing.T) { cfg := testConfig(t, true) ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() s, err := Launch(ctx, cfg) if err != nil { t.Fatal(err) } defer s.Close() // The fake browser answers once it runs. s.FromBrowser.SetReadDeadline(time.Now().Add(10 * time.Second)) s.ToBrowser.WriteString("ping\x00") if reply, err := readFrame(bufio.NewReader(s.FromBrowser), 64); err != nil || string(reply) != "ping" { t.Fatalf("the browser did not start: %q %v", reply, err) } want := fmt.Sprintf("%d", MemoryLimit) var browser, sandbox bool for _, pid := range descendants(s.cmd.Process.Pid) { raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/limits") if err != nil { continue } cmdline, _ := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/cmdline") name := strings.ReplaceAll(string(cmdline), "\x00", " ") switch { case strings.HasPrefix(name, BrowserPath+" "): browser = true case strings.HasPrefix(name, binaryPath+" "+Subcommand): sandbox = true default: continue } var soft, hard string for _, line := range strings.Split(string(raw), "\n") { if rest, ok := strings.CutPrefix(line, "Max data size"); ok { if f := strings.Fields(rest); len(f) >= 2 { soft, hard = f[0], f[1] } } } if soft != want || hard != want { t.Errorf("%s: data size %s soft, %s hard, want %s", name, soft, hard, want) } } if !browser || !sandbox { t.Fatalf("browser %v, render-sandbox %v found below bubblewrap", browser, sandbox) } } // The sandbox's /tmp holds at most TmpSize: a writer filling it gets // ENOSPC near the bound. func TestSandboxTmpIsBounded(t *testing.T) { cfg := testConfig(t, false) r := runProbe(t, cfg, "fill-tmp") if r.Fill == nil || !strings.Contains(r.Fill.Err, "no space left on device") { t.Fatalf("fill %+v", r.Fill) } if r.Fill.Bytes > TmpSize || r.Fill.Bytes < TmpSize-(8<<20) { t.Fatalf("wrote %d bytes before %s, bound %d", r.Fill.Bytes, r.Fill.Err, TmpSize) } } // Render's out directory is the runner's: refused, before any sandbox // starts, unless it is absolute, clean, empty, private, this user's and // reached through no symlink. func TestRenderRefusesItsOutDir(t *testing.T) { // A launch that would start: only the out directory stops it. cfg := testConfig(t, true) used := testOut(t) must(t, os.WriteFile(filepath.Join(used, "x"), nil, 0o600)) open := testOut(t) must(t, os.Chmod(open, 0o755)) link := filepath.Join(tempDir(t), "link") must(t, os.Symlink(testOut(t), link)) file := filepath.Join(tempDir(t), "file") must(t, os.WriteFile(file, nil, 0o600)) forked := noFork(t) for name, c := range map[string]struct{ dir, why string }{ "relative": {"out", "output path"}, "unclean": {testOut(t) + "/", "output path"}, "used": {used, "not empty"}, "open": {open, "not private"}, "symlinked": {link, "symbolic links"}, "a file": {file, "not a directory"}, "missing": {filepath.Join(tempDir(t), "absent"), "no such file"}, "root's": {"/usr", "only this user can write"}, } { _, err := Render(context.Background(), cfg, c.dir, []Page{{Path: "/", Viewport: Phone}}) if err == nil || !strings.Contains(err.Error(), c.why) { t.Errorf("%s: %v, want %q", name, err, c.why) } } if *forked { t.Fatal("a sandbox started") } // A good one is held and written through. dir := testOut(t) root, err := openOut(dir) if err != nil { t.Fatal(err) } defer root.Close() must(t, root.WriteFile("page-1.png", []byte("x"), 0o600)) if _, err := os.Stat(filepath.Join(dir, "page-1.png")); err != nil { t.Fatal(err) } }