//go:build linux
package render
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"debug/elf"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"net"
"net/netip"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"time"
"golang.org/x/sys/unix"
"amadan.net/oficina/equipo/internal/release"
"amadan.net/oficina/equipo/internal/testci"
"amadan.net/oficina/equipo/internal/wire"
)
// usableBwrap is bubblewrap, when it can make namespaces here, and this
// test binary, which must be static to run inside a sandbox with no
// host /usr.
func usableBwrap(t *testing.T) (bwrap, self string) {
t.Helper()
testci.Tools(t, "bwrap")
bwrap, err := exec.LookPath("bwrap")
if err != nil {
testci.Absent(t, "bwrap is not installed")
}
if out, err := exec.Command(bwrap, "--unshare-all", "--ro-bind", "/", "/", "true").CombinedOutput(); err != nil {
testci.Absent(t, "bwrap cannot create namespaces here: "+strings.TrimSpace(string(out)))
}
if self, err = os.Executable(); err != nil {
t.Fatal(err)
}
if self, err = filepath.EvalSymlinks(self); err != nil {
t.Fatal(err)
}
f, err := elf.Open(self)
if err != nil {
t.Fatal(err)
}
defer f.Close()
for _, p := range f.Progs {
if p.Type == elf.PT_INTERP {
t.Skip("the test binary is dynamically linked; run with CGO_ENABLED=0 as make does")
}
}
return bwrap, self
}
func tempDir(t *testing.T) string {
t.Helper()
dir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
// t.TempDir's mode follows the umask; the tree's directory must not
// be group writable.
must(t, os.Chmod(dir, 0o700))
return dir
}
// testTree writes a renderer tree that verifies, with the layout the
// launch binds (usr, etc/fonts) and, when browser is not "", that file
// as the browser. It returns the tree and its pin.
func testTree(t *testing.T, browser string) (dir, pin string) {
t.Helper()
dir = filepath.Join(tempDir(t), "tree")
return dir, writeTree(t, dir, browser)
}
// writeTree writes testTree's tree at dir and returns its pin.
func writeTree(t *testing.T, dir, browser string) (pin string) {
t.Helper()
entries := []string{"dir etc", "dir etc/fonts", "dir usr", "dir usr/lib", "dir usr/lib/chromium"}
must(t, os.Mkdir(dir, 0o755))
for _, e := range entries {
must(t, os.Mkdir(filepath.Join(dir, strings.TrimPrefix(e, "dir ")), 0o755))
}
if browser != "" {
raw, err := os.ReadFile(browser)
must(t, err)
rel := strings.TrimPrefix(BrowserPath, "/")
must(t, os.WriteFile(filepath.Join(dir, rel), raw, 0o755))
sum := sha256.Sum256(raw)
entries = append(entries, fmt.Sprintf("file %s %x 0755", rel, sum))
}
manifest := strings.Join(entries, "\n") + "\n"
must(t, os.WriteFile(filepath.Join(dir, "MANIFEST"), []byte(manifest), 0o644))
sum := sha256.Sum256([]byte(manifest))
pin = hex.EncodeToString(sum[:])
if err := release.VerifyRenderer(dir, pin); err != nil {
t.Fatalf("test tree: %v", err)
}
return pin
}
func testSite(t *testing.T) string {
t.Helper()
dir := filepath.Join(tempDir(t), "site")
must(t, os.Mkdir(dir, 0o755))
must(t, os.WriteFile(filepath.Join(dir, "index.html"), []byte("
shop"), 0o644))
return dir
}
func testOut(t *testing.T) string {
t.Helper()
dir := filepath.Join(tempDir(t), "out")
must(t, os.Mkdir(dir, 0o700))
return dir
}
func must(t *testing.T, errs ...error) {
t.Helper()
for _, err := range errs {
if err != nil && !errors.Is(err, os.ErrExist) {
t.Fatal(err)
}
}
}
func testConfig(t *testing.T, browser bool) LaunchConfig {
t.Helper()
bwrap, self := usableBwrap(t)
b := ""
if browser {
b = self
}
tree, pin := testTree(t, b)
return LaunchConfig{Bwrap: bwrap, Binary: self, Tree: tree, Pin: pin, Site: testSite(t)}
}
// runProbe runs the probe as the sandbox's first process and returns
// the report it sends on the browser's pipe.
func runProbe(t *testing.T, cfg LaunchConfig, args ...string) probeReport {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
s, err := start(ctx, cfg, append([]string{"render-probe"}, args...)...)
if err != nil {
t.Fatal(err)
}
raw, rerr := readFrame(bufio.NewReader(s.FromBrowser), 64<<20)
if _, err = s.Wait(); err != nil {
t.Fatalf("probe: %v: %s", err, s.stderr.Bytes())
}
s.Close()
if rerr != nil {
t.Fatalf("probe report: %v: %s", rerr, s.stderr.Bytes())
}
var r probeReport
if err = json.Unmarshal(raw, &r); err != nil {
t.Fatal(err)
}
return r
}
// The policy is the spike's, exactly: no --share-net, nothing from the
// host but the descriptors it binds, and the environment cleared.
func TestBwrapArgs(t *testing.T) {
want := "--unshare-all --unshare-user --die-with-parent --new-session --clearenv --cap-drop ALL" +
" --info-fd 10 --ro-bind-fd 6 /usr --symlink usr/lib /lib --symlink usr/lib64 /lib64 --symlink usr/bin /bin" +
" --ro-bind-fd 7 /etc/fonts --ro-bind-fd 8 /runner --ro-bind-fd 9 /site" +
" --size 536870912 --tmpfs /tmp --proc /proc --dev /dev --remount-ro / --chdir / -- /runner render-sandbox"
got := bwrapArgs(Subcommand)
if strings.Join(got, " ") != want {
t.Fatalf("bwrap args\n got %s\nwant %s", strings.Join(got, " "), want)
}
for _, a := range got {
if strings.HasPrefix(a, "--share") || a == "--setenv" || a == "--bind" || a == "--ro-bind" || a == "--dev-bind" {
t.Errorf("bwrap arg %s", a)
}
}
}
// tailnetAddr is one of this host's tailnet addresses (100.64.0.0/10),
// if it has one.
func tailnetAddr() (netip.Addr, bool) {
cgnat := netip.MustParsePrefix("100.64.0.0/10")
addrs, _ := net.InterfaceAddrs()
for _, a := range addrs {
if p, err := netip.ParsePrefix(a.String()); err == nil && cgnat.Contains(p.Addr()) {
return p.Addr(), true
}
}
return netip.Addr{}, false
}
// listen opens a listener on the host that accepts and closes.
func listen(t *testing.T, addr string) string {
t.Helper()
ln, err := net.Listen("tcp", addr)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
c.Close()
}
}()
return ln.Addr().String()
}
// From inside, only the sandbox's own loopback answers: a public IP, the
// host's tailnet address and a listener on the host's 127.0.0.1 are
// unreachable, and no name resolves.
func TestSandboxReachesNoNetwork(t *testing.T) {
cfg := testConfig(t, false)
targets := map[string]string{
"public IPv4": "1.1.1.1:443",
"public IPv6": "[2606:4700:4700::1111]:443",
"host loopback": listen(t, "127.0.0.1:0"),
}
if addr, ok := tailnetAddr(); ok {
targets["host tailnet"] = listen(t, netip.AddrPortFrom(addr, 0).String())
} else {
t.Log("this host has no tailnet address; that case is not run")
}
var args []string
for _, a := range targets {
args = append(args, "dial="+a)
}
r := runProbe(t, cfg, args...)
if r.Loopback != "" {
t.Fatalf("the sandbox's own loopback does not work: %s", r.Loopback)
}
if !slices.Equal(r.Interfaces, []string{"lo"}) {
t.Errorf("interfaces %q", r.Interfaces)
}
for name, a := range targets {
if e, ok := r.Dials[a]; !ok || e == "" {
t.Errorf("%s %s: reached from inside (%q)", name, a, e)
}
}
if r.Lookup == "" {
t.Error("a public name resolved from inside")
}
}
// A descriptor the runner left inheritable never reaches the sandbox:
// its first process holds 0, 1, 2, the browser's pipe and the status
// pipe, and the runner's own descriptor stays open.
func TestSandboxSeesNoParentDescriptor(t *testing.T) {
cfg := testConfig(t, false)
secret := filepath.Join(tempDir(t), "forge.json")
must(t, os.WriteFile(secret, []byte(`{"token":"secret"}`), 0o600))
opened, err := os.Open(secret)
if err != nil {
t.Fatal(err)
}
defer opened.Close()
// Above the descriptors the launch hands bubblewrap (3 to 10), which
// would replace it in the child, and without close-on-exec, as F_DUPFD
// leaves it.
fd, err := unix.FcntlInt(opened.Fd(), unix.F_DUPFD, 20)
if err != nil {
t.Fatal(err)
}
f := os.NewFile(uintptr(fd), secret)
defer f.Close()
if flags, err := unix.FcntlInt(f.Fd(), unix.F_GETFD, 0); err != nil || flags&unix.FD_CLOEXEC != 0 {
t.Fatalf("the descriptor is not inheritable: %d %v", flags, err)
}
r := runProbe(t, cfg)
if want := []int{0, 1, 2, fdBrowserIn, fdBrowserOut, fdStatus}; !slices.Equal(r.FDs, want) {
t.Fatalf("descriptors inside %v, want %v (the runner's file is %d)", r.FDs, want, f.Fd())
}
if _, err = f.Stat(); err != nil {
t.Fatalf("the runner's own descriptor: %v", err)
}
}
// The sandbox's first process starts with an empty environment: nothing
// from the runner's. Bubblewrap itself sets PWD after --chdir.
func TestSandboxEnvironmentIsEmpty(t *testing.T) {
cfg := testConfig(t, false)
t.Setenv("EQUIPO_RUNNER_TOKEN", "secret")
t.Setenv("HOME", "/home/runner")
r := runProbe(t, cfg)
if len(r.Env) > 1 || len(r.Env) == 1 && r.Env[0] != "PWD=/" {
t.Fatalf("environment %q", r.Env)
}
}
// /site, the tree, the binary and the root are read only, and there is
// no /out: /tmp, which ends with the sandbox, is the only place it
// writes.
func TestSandboxSiteIsReadOnly(t *testing.T) {
cfg := testConfig(t, false)
r := runProbe(t, cfg)
for op, e := range r.Writes {
writable := op == "create /tmp/new"
switch {
case writable && e != "":
t.Errorf("%s: %s", op, e)
case !writable && !strings.Contains(e, "read-only file system"):
t.Errorf("%s: %q, want read-only file system", op, e)
}
}
if len(r.Writes) != 11 {
t.Errorf("writes %v", r.Writes)
}
if raw, err := os.ReadFile(filepath.Join(cfg.Site, "index.html")); err != nil || string(raw) != "shop" {
t.Errorf("the site changed: %q %v", raw, err)
}
if _, err := os.Stat(filepath.Join(cfg.Site, "new")); err == nil {
t.Error("the sandbox created a file in the site")
}
}
// Nothing of the host but what the launch binds is visible: no home,
// runner state or credentials.
func TestSandboxHoldsNoRunnerState(t *testing.T) {
cfg := testConfig(t, false)
r := runProbe(t, cfg)
allowed := map[string]bool{"/": true, "/bin": true, "/lib": true, "/lib64": true, "/etc": true, "/etc/fonts": true, binaryPath: true, "/site": true, "/site/index.html": true, "/tmp": true, "/usr": true, "/proc": true, "/dev": true}
for _, p := range r.Paths {
if !allowed[p] {
t.Errorf("the sandbox shows %s", p)
}
}
if !slices.Contains(r.Paths, "/site/index.html") {
t.Errorf("paths %q", r.Paths)
}
}
// A page whose server redirects to an external host gets the redirect,
// and following it fails to resolve or connect: reported, not followed.
func TestSandboxRedirectIsReportedNotFollowed(t *testing.T) {
cfg := testConfig(t, false)
targets := []string{"http://cdn.example.com/app.js", "http://1.1.1.1/", "http://[2606:4700:4700::1111]/"}
var args []string
for _, u := range targets {
args = append(args, "redirect="+u)
}
r := runProbe(t, cfg, args...)
for _, u := range targets {
got, ok := r.Redirects[u]
if !ok || got.Location != u {
t.Errorf("%s: the redirect was not seen: %+v", u, got)
continue
}
if got.Status != 0 || !got.Blocked {
t.Errorf("%s: followed: %+v", u, got)
}
}
}
// Launch runs the real subcommand: the site served on the sandbox's
// 127.0.0.1, the browser started with its pipe on 3 and 4 and nothing
// else, HOME=/tmp its whole environment, and its exit reported.
func TestLaunchStartsTheBrowser(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()
if !siteURL.MatchString(s.Site) {
t.Fatalf("site %q", s.Site)
}
from := bufio.NewReader(s.FromBrowser)
ask := func(msg string) string {
t.Helper()
if _, err := s.ToBrowser.WriteString(msg + "\x00"); err != nil {
t.Fatal(err)
}
reply, err := from.ReadString(0)
if err != nil {
t.Fatalf("%s: %v", msg, err)
}
return strings.TrimSuffix(reply, "\x00")
}
if got := ask("ping"); got != "ping" {
t.Fatalf("echo %q", got)
}
if got := ask("get " + s.Site + "index.html"); got != "200 shop" {
t.Fatalf("site %q", got)
}
if got := ask("get " + s.Site + "../../usr/lib/chromium/chromium-headless-shell"); strings.HasPrefix(got, "200") {
t.Fatalf("the site server left /site: %.40q", got)
}
if got := ask("post " + s.Site + "index.html"); got != "405" {
t.Fatalf("post %q", got)
}
raw := []byte(ask("report"))
s.ToBrowser.WriteString("exit 7\x00")
exit, err := s.Wait()
if err != nil || exit != (BrowserExit{Known: true, Code: 7}) {
t.Fatalf("exit %+v, %v: %s", exit, err, s.stderr.Bytes())
}
if _, err = from.ReadByte(); err == nil {
t.Fatal("the browser's pipe is still open")
}
var b browserReport
if err = json.Unmarshal(raw, &b); err != nil {
t.Fatal(err)
}
if !slices.Equal(b.Args, browserArgs()) {
t.Errorf("browser args %q", b.Args)
}
if !slices.Equal(b.Env, []string{"HOME=/tmp"}) {
t.Errorf("browser environment %q", b.Env)
}
if !slices.Equal(b.FDs, []int{0, 1, 2, fdBrowserIn, fdBrowserOut}) {
t.Errorf("browser descriptors %v", b.FDs)
}
if b.Dir != "/tmp" {
t.Errorf("browser directory %q", b.Dir)
}
}
// Closing a sandbox kills everything in it, a browser that would never
// end on its own included.
func TestCloseKillsTheSandbox(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)
}
s.ToBrowser.WriteString("hang\x00")
if reply, err := bufio.NewReader(s.FromBrowser).ReadString(0); err != nil || reply != "hanging\x00" {
t.Fatalf("hang: %q %v", reply, err)
}
inside := descendants(s.cmd.Process.Pid)
if len(inside) < 2 {
t.Fatalf("processes in the sandbox: %v", inside)
}
// Should the kill fail, the test still leaves nothing running.
t.Cleanup(func() {
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
})
done := make(chan struct{})
go func() { s.Close(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("Close did not end the sandbox promptly")
}
if _, err = s.Wait(); err == nil {
t.Fatal("a killed sandbox reported success")
}
// Every process that was in the sandbox (bubblewrap's, the
// subcommand, the browser) ends: the kernel kills the rest of a PID
// namespace when its first process dies, a moment after bubblewrap.
deadline := time.Now().Add(5 * time.Second)
for _, n := range inside {
for alive(n) && time.Now().Before(deadline) {
time.Sleep(20 * time.Millisecond)
}
if alive(n) {
raw, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "status"))
t.Errorf("process %d outlived the sandbox: %.200s", n, raw)
}
}
}
// alive is a process that exists and is not a zombie.
func alive(pid int) bool {
raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "status"))
return err == nil && !strings.Contains(string(raw), "State:\tZ")
}
// A tree without the browser: render-sandbox reports it and Launch fails.
func TestLaunchReportsABrowserThatCannotStart(t *testing.T) {
cfg := testConfig(t, false)
_, err := Launch(context.Background(), cfg)
if err == nil || !strings.Contains(err.Error(), "failed ("+reasonBrowser+")") {
t.Fatalf("Launch: %v", err)
}
}
// Only a tree that has just verified is mounted: a changed, missing or
// unpinned tree is the renderer's health and nothing starts.
func TestLaunchRefusesAnUnverifiedTree(t *testing.T) {
for name, c := range map[string]struct {
change func(cfg *LaunchConfig)
health string
}{
"tampered": {func(cfg *LaunchConfig) {
os.WriteFile(filepath.Join(cfg.Tree, "usr", "lib", "extra"), []byte("x"), 0o644)
}, wire.ToolMismatch},
"missing": {func(cfg *LaunchConfig) { cfg.Tree = filepath.Join(filepath.Dir(cfg.Tree), "absent") }, wire.ToolMissing},
"unpinned": {func(cfg *LaunchConfig) { cfg.Pin = "" }, wire.ToolUnpinned},
"other pin": {func(cfg *LaunchConfig) { cfg.Pin = strings.Repeat("a", 64) }, wire.ToolMismatch},
} {
t.Run(name, func(t *testing.T) {
cfg := testConfig(t, false)
c.change(&cfg)
forked := noFork(t)
_, err := Launch(context.Background(), cfg)
var re *release.RendererError
if !errors.As(err, &re) || re.Health != c.health {
t.Fatalf("Launch: %v, want %s", err, c.health)
}
if *forked {
t.Fatal("something ran")
}
})
}
}
// noFork records whether the launcher forked, until the test ends.
func noFork(t *testing.T) *bool {
t.Helper()
forked := new(bool)
testBeforeFork = func() { *forked = true }
t.Cleanup(func() { testBeforeFork = nil })
return forked
}
func TestLaunchRefusesItsInputs(t *testing.T) {
base := testConfig(t, false)
shared := testSite(t)
must(t, os.Chmod(shared, 0o775))
siteLink := filepath.Join(tempDir(t), "site-link")
must(t, os.Symlink(testSite(t), siteLink))
for name, c := range map[string]struct {
change func(*LaunchConfig)
why string
}{
"relative bwrap": {func(c *LaunchConfig) { c.Bwrap = "bwrap" }, "launch path"},
"relative binary": {func(c *LaunchConfig) { c.Binary = "runner" }, "launch path"},
"missing binary": {func(c *LaunchConfig) { c.Binary = "/nonexistent/runner" }, "no such file"},
"relative site": {func(c *LaunchConfig) { c.Site = "site" }, "launch path"},
"shared site": {func(c *LaunchConfig) { c.Site = shared }, "only this user can write"},
"root's site": {func(c *LaunchConfig) { c.Site = "/usr" }, "only this user can write"},
"symlinked site": {func(c *LaunchConfig) { c.Site = siteLink }, "symbolic links"},
"unclean tree": {func(c *LaunchConfig) { c.Tree += "/" }, "launch path"},
} {
cfg := base
c.change(&cfg)
s, err := Launch(context.Background(), cfg)
if err == nil {
s.Close()
}
if err == nil || !strings.Contains(err.Error(), c.why) {
t.Errorf("%s: %v, want %q", name, err, c.why)
}
}
}
// The status pipe is read strictly: the first line must be ready with a
// loopback site or failed, lines are bounded, and anything else ends the
// reading.
func TestReadStatus(t *testing.T) {
for name, c := range map[string]struct {
lines string
ready string
exit BrowserExit
}{
"ready then exit": {`{"event":"ready","site":"http://127.0.0.1:4100/"}` + "\n" + `{"event":"exit","code":3}` + "\n", "ready", BrowserExit{Known: true, Code: 3}},
"failed": {`{"event":"failed","reason":"site"}` + "\n", "failed", BrowserExit{}},
"another host": {`{"event":"ready","site":"http://10.0.0.1:4100/"}` + "\n", "", BrowserExit{}},
"a path": {`{"event":"ready","site":"http://127.0.0.1:4100/x"}` + "\n", "", BrowserExit{}},
"exit first": {`{"event":"exit","code":3}` + "\n", "", BrowserExit{}},
"not JSON": {"ready\n" + `{"event":"ready","site":"http://127.0.0.1:4100/"}` + "\n", "", BrowserExit{}},
"a long line": {`{"event":"failed","reason":"` + strings.Repeat("x", 2000) + `"}` + "\n", "", BrowserExit{}},
"a second ready": {`{"event":"ready","site":"http://127.0.0.1:4100/"}` + "\n" + `{"event":"ready","site":"http://127.0.0.1:4101/"}` + "\n" + `{"event":"exit","code":3}` + "\n", "ready", BrowserExit{}},
} {
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
go func() { w.WriteString(c.lines); w.Close() }()
s := &Sandbox{ready: make(chan status, 1)}
done := make(chan struct{})
s.readStatus(r, done)
r.Close()
got := ""
select {
case st := <-s.ready:
got = st.Event
default:
}
if got != c.ready || s.exit != c.exit {
t.Errorf("%s: ready %q exit %+v", name, got, s.exit)
}
}
}
// render-sandbox's first step leaves exactly 0 to 5 open, 3 to 5
// close-on-exec, whatever else it was started with; the /proc fallback
// closes as close_range does.
func TestSandboxDescriptors(t *testing.T) {
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, mode := range []string{"", "each"} {
var extra []*os.File
for i := 0; i < 5; i++ {
f, err := os.Open(os.DevNull)
if err != nil {
t.Fatal(err)
}
defer f.Close()
extra = append(extra, f)
}
cmd := exec.Command(self, "render-fds")
if mode != "" {
cmd.Args = append(cmd.Args, mode)
}
cmd.ExtraFiles = extra
out, err := cmd.Output()
if err != nil {
t.Fatalf("%q: %v", mode, err)
}
var r fdsReport
if err = json.Unmarshal(out, &r); err != nil {
t.Fatalf("%q: %v: %s", mode, err, out)
}
if r.Err != "" || !slices.Equal(r.FDs, []int{0, 1, 2, 3, 4, 5}) {
t.Errorf("%q: %+v", mode, r)
}
if mode == "" && (!r.CloExec[3] || !r.CloExec[4] || !r.CloExec[5]) {
t.Errorf("not close-on-exec: %+v", r)
}
}
}
// A descriptor another goroutine opens without close-on-exec just before
// the launcher forks is inherited by the process the launcher starts,
// and never reaches bubblewrap or the sandbox: render-exec closes it.
func TestSandboxSeesNothingOpenedAtFork(t *testing.T) {
cfg := testConfig(t, false)
var leaked int = -1
testBeforeFork = func() {
f, err := os.Open(os.DevNull)
if err != nil {
return
}
leaked, _ = unix.FcntlInt(f.Fd(), unix.F_DUPFD, 30)
f.Close()
}
defer func() { testBeforeFork = nil }()
r := runProbe(t, cfg)
if leaked < 30 {
t.Fatalf("the test's descriptor: %d", leaked)
}
defer unix.Close(leaked)
if flags, err := unix.FcntlInt(uintptr(leaked), unix.F_GETFD, 0); err != nil || flags&unix.FD_CLOEXEC != 0 {
t.Fatalf("the test's descriptor is not inheritable: %d %v", flags, err)
}
if want := []int{0, 1, 2, fdBrowserIn, fdBrowserOut, fdStatus}; !slices.Equal(r.FDs, want) {
t.Fatalf("descriptors inside %v, want %v (opened at fork: %d)", r.FDs, want, leaked)
}
}
// The tree mounted is the tree verified: replacing the tree, its usr,
// its etc or its etc/fonts between the verification and the mount is
// refused, and nothing runs.
func TestLaunchRefusesATreeReplacedAfterVerification(t *testing.T) {
for _, part := range []string{"", "usr", "etc", "etc/fonts"} {
t.Run("replace "+part, func(t *testing.T) {
cfg := testConfig(t, false)
testAfterVerify = func() {
p := filepath.Join(cfg.Tree, part)
must(t, os.Rename(p, p+".verified"))
// The impostor: a copy of the tree layout, with a socket
// and an unverified browser in reach.
must(t, os.MkdirAll(filepath.Join(p, "lib/chromium"), 0o755), os.MkdirAll(filepath.Join(p, "fonts"), 0o755), os.MkdirAll(filepath.Join(p, "usr"), 0o755), os.MkdirAll(filepath.Join(p, "etc/fonts"), 0o755))
must(t, os.WriteFile(filepath.Join(p, "lib/chromium/chromium-headless-shell"), []byte("#!/bin/sh\n"), 0o755))
}
defer func() { testAfterVerify = nil }()
forked := noFork(t)
_, err := Launch(context.Background(), cfg)
var re *release.RendererError
if !errors.As(err, &re) || re.Health != wire.ToolMismatch || !strings.Contains(re.Reason, "changed while it was verified") {
t.Fatalf("Launch: %v", err)
}
if *forked {
t.Fatal("something ran")
}
})
}
}
// The tree is verified through the descriptor of its directory that the
// launch holds, not its path: with an ancestor renamed during the
// verification and a good tree put at the old path, the tree checked is
// still the one that will be mounted (here a tampered one), and it is
// refused.
func TestLaunchVerifiesTheTreeItMounts(t *testing.T) {
cfg := testConfig(t, false)
g := filepath.Join(tempDir(t), "g")
must(t, os.MkdirAll(filepath.Join(g, "p"), 0o700))
cfg.Tree = filepath.Join(g, "p", "tree")
writeTree(t, cfg.Tree, "")
testBeforeVerify = func() {
must(t, os.WriteFile(filepath.Join(cfg.Tree, "usr", "lib", "extra"), []byte("x"), 0o644))
must(t, os.Rename(g, g+".moved"))
must(t, os.MkdirAll(filepath.Join(g, "p"), 0o700))
writeTree(t, cfg.Tree, "")
}
defer func() { testBeforeVerify = nil }()
s, err := Launch(context.Background(), cfg)
if err == nil {
s.Close()
}
var re *release.RendererError
if !errors.As(err, &re) || re.Health != wire.ToolMismatch || re.Path != "usr/lib/extra" {
t.Fatalf("Launch: %v", err)
}
}
// The tree's directory must be this user's or root's and nobody else's
// to write: otherwise another user could swap the tree.
func TestLaunchRefusesATreeOthersCanMove(t *testing.T) {
cfg := testConfig(t, false)
must(t, os.Chmod(filepath.Dir(cfg.Tree), 0o777))
_, err := Launch(context.Background(), cfg)
var re *release.RendererError
if !errors.As(err, &re) || re.Health != wire.ToolMismatch || !strings.Contains(re.Reason, "another user") {
t.Fatalf("Launch: %v", err)
}
}
// When Close returns, every process of the sandbox has ended, even one
// that started its own session and kept writing to the browser's pipe,
// which the test still reads after Close. Three rounds: a Close that does not wait returns while
// that writer still runs in most rounds, not all.
func TestCloseReturnsOnlyWhenEverythingEnded(t *testing.T) {
for round := 0; round < 3; round++ {
closeAWriter(t)
}
}
func closeAWriter(t *testing.T) {
t.Helper()
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)
}
// The test's own reader of the browser's pipe outlives Close, so
// the pipe stays open to a writer that survives it.
ticks := dupReader(t, s.FromBrowser)
defer ticks.Close()
s.ToBrowser.WriteString("spawn\x00")
var seen []byte
ticks.SetReadDeadline(time.Now().Add(10 * time.Second))
for !bytes.Contains(seen, []byte("spawned\x00")) || !bytes.Contains(seen, []byte(".")) {
buf := make([]byte, 4096)
n, err := ticks.Read(buf)
if err != nil {
t.Fatalf("spawn: %q %v", seen, err)
}
seen = append(seen, buf[:n]...)
}
inside := descendants(s.cmd.Process.Pid)
t.Cleanup(func() {
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
})
if err = s.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
// What was written before Close is taken at once; after it, nothing.
drain(ticks, time.Millisecond)
for _, n := range inside {
if alive(n) {
raw, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "status"))
t.Fatalf("process %d still runs after Close: %.120s", n, raw)
}
}
time.Sleep(100 * time.Millisecond)
if n := drain(ticks, 20*time.Millisecond); n != 0 {
t.Fatalf("the browser's pipe was still written after Close: %d bytes", n)
}
}
// dupReader is a second reader of f's pipe, with its own deadlines.
func dupReader(t *testing.T, f *os.File) *os.File {
t.Helper()
rc, err := f.SyscallConn()
if err != nil {
t.Fatal(err)
}
fd := -1
if cerr := rc.Control(func(raw uintptr) { fd, err = unix.FcntlInt(raw, unix.F_DUPFD_CLOEXEC, 0) }); cerr != nil || err != nil {
t.Fatal(cerr, err)
}
must(t, unix.SetNonblock(fd, true))
return os.NewFile(uintptr(fd), "ticks")
}
// drain reads what r holds, for at most d, and returns how much.
func drain(r *os.File, d time.Duration) int {
r.SetReadDeadline(time.Now().Add(d))
total := 0
buf := make([]byte, 64<<10)
for {
n, err := r.Read(buf)
total += n
if err != nil {
return total
}
}
}
// The real browser, from a tree scripts/build-renderer-tree.py kept
// (--tree), starts in the sandbox with its own sandbox on and answers on
// its pipe. Building a tree downloads about 164 MB, so this runs only
// when EQUIPO_RENDERER_TREE names one.
func TestLaunchRealBrowser(t *testing.T) {
tree := os.Getenv("EQUIPO_RENDERER_TREE")
if tree == "" {
t.Skip("set EQUIPO_RENDERER_TREE to a tree built by scripts/build-renderer-tree.py --tree to run the real browser")
}
bwrap, self := usableBwrap(t)
manifest, err := os.ReadFile(filepath.Join(tree, "MANIFEST"))
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(manifest)
var stderr bounded
stderr.max = 64 << 10
cfg := LaunchConfig{Bwrap: bwrap, Binary: self, Tree: tree, Pin: hex.EncodeToString(sum[:]), Site: testSite(t), Stderr: &stderr}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
s, err := Launch(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer s.Close()
from := bufio.NewReader(s.FromBrowser)
call := func(id int, method string) map[string]any {
t.Helper()
msg, _ := json.Marshal(map[string]any{"id": id, "method": method})
if _, err := s.ToBrowser.Write(append(msg, 0)); err != nil {
t.Fatal(err)
}
for {
raw, err := from.ReadBytes(0)
if err != nil {
t.Fatalf("%s: %v", method, err)
}
var reply map[string]any
if err = json.Unmarshal(raw[:len(raw)-1], &reply); err != nil {
t.Fatalf("%s: %v", method, err)
}
if reply["id"] == float64(id) {
return reply
}
}
}
version := call(1, "Browser.getVersion")
result, _ := version["result"].(map[string]any)
if product, _ := result["product"].(string); !strings.HasPrefix(product, "HeadlessChrome/") {
t.Fatalf("version %v", version)
}
// Chromium's own sandbox is on: a renderer below bubblewrap runs
// under its seccomp filter with no new privileges.
deadline := time.Now().Add(10 * time.Second)
for !sandboxedRenderer(s.cmd.Process.Pid) {
if time.Now().After(deadline) {
t.Fatal("no renderer under Chromium's own sandbox")
}
time.Sleep(100 * time.Millisecond)
}
call(2, "Browser.close")
exit, err := s.Wait()
if err != nil || exit != (BrowserExit{Known: true}) {
t.Fatalf("exit %+v, %v", exit, err)
}
t.Logf("browser: %v; stderr:\n%s", result["product"], stderr.Bytes())
}
// descendants lists the processes below pid, read from the host's /proc.
func descendants(pid int) []int {
parent := map[int]int{}
entries, _ := os.ReadDir("/proc")
for _, e := range entries {
n, err := strconv.Atoi(e.Name())
if err != nil {
continue
}
raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "status"))
if err != nil {
continue
}
for _, line := range strings.Split(string(raw), "\n") {
if v, ok := strings.CutPrefix(line, "PPid:"); ok {
parent[n], _ = strconv.Atoi(strings.TrimSpace(v))
}
}
}
var below []int
for n := range parent {
for p, i := parent[n], 0; i < 64 && p > 1; p, i = parent[p], i+1 {
if p == pid {
below = append(below, n)
break
}
}
}
return below
}
// sandboxedRenderer is a process below pid whose command line is a
// Chromium renderer's and that runs with a seccomp filter (Seccomp 2)
// and NoNewPrivs 1, read from the host's /proc.
func sandboxedRenderer(pid int) bool {
for _, n := range descendants(pid) {
cmdline, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "cmdline"))
if !strings.Contains(string(cmdline), "--type=renderer") {
continue
}
raw, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "status"))
st := string(raw)
if strings.Contains(st, "\nSeccomp:\t2\n") && strings.Contains(st, "\nNoNewPrivs:\t1\n") {
return true
}
}
return false
}
// identify's rules, each observation alone: only a process whose parent
// is the unreaped monitor is held, only no process at the PID is the
// init gone, and everything else is unknown, its pidfd closed.
func TestIdentify(t *testing.T) {
defer func() { pidfdOpen, readParent = unix.PidfdOpen, parentOf }()
const pid, monitor = 4242, 4241
for name, c := range map[string]struct {
openErr error
parent int
parentErr error
pid int
want initState
}{
"parent is the monitor": {parent: monitor, want: initHeld},
"no process at the PID (pidfd)": {openErr: unix.ESRCH, want: initGone},
"no process at the PID (/proc)": {parentErr: os.ErrNotExist, want: initGone},
"process gone while read": {parentErr: unix.ESRCH, want: initGone},
"no pidfd: descriptors exhausted": {openErr: unix.EMFILE, want: initUnknown},
"no pidfd: not permitted": {openErr: unix.EPERM, want: initUnknown},
"parent unreadable": {parentErr: unix.EIO, want: initUnknown},
"another parent (monitor gone)": {parent: 1, want: initUnknown},
"no PID": {pid: -1, want: initUnknown},
"PID 1": {pid: 1, want: initUnknown},
} {
var opened = -1
pidfdOpen = func(int, int) (int, error) {
if c.openErr != nil {
return -1, c.openErr
}
f, err := os.Open(os.DevNull)
if err != nil {
t.Fatal(err)
}
opened, _ = unix.Dup(int(f.Fd()))
f.Close()
return opened, nil
}
readParent = func(int) (int, error) { return c.parent, c.parentErr }
p := pid
if c.pid != 0 {
p = c.pid
}
fd, state := identify(p, monitor)
if state != c.want {
t.Errorf("%s: state %d, want %d", name, state, c.want)
}
switch {
case state == initHeld && fd != opened:
t.Errorf("%s: fd %d, want %d", name, fd, opened)
case state != initHeld && fd != -1:
t.Errorf("%s: fd %d", name, fd)
case state != initHeld && opened >= 0:
if _, err := unix.FcntlInt(uintptr(opened), unix.F_GETFD, 0); err == nil {
t.Errorf("%s: the pidfd was left open", name)
unix.Close(opened)
}
}
if state == initHeld {
unix.Close(fd)
}
}
}
// failClosed launches a real sandbox with a fault injected and checks
// Launch fails with ErrNotEnded and returns no sandbox; whatever ran is
// killed at the end of the test.
func failClosed(t *testing.T) {
t.Helper()
cfg := testConfig(t, true)
var inside []int
testBeforeIdentity = func(monitor int) { inside = descendants(monitor) }
defer func() { testBeforeIdentity = nil }()
t.Cleanup(func() {
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
})
s, err := Launch(context.Background(), cfg)
if s != nil || !errors.Is(err, ErrNotEnded) {
if s != nil {
s.Close()
}
t.Fatalf("Launch: %v, want ErrNotEnded", err)
}
}
// Without a pidfd on the init (descriptors exhausted) the end of the
// sandbox cannot be shown: Launch fails closed.
func TestLaunchFailsClosedWithoutAPidfd(t *testing.T) {
pidfdOpen = func(int, int) (int, error) { return -1, unix.EMFILE }
defer func() { pidfdOpen = unix.PidfdOpen }()
failClosed(t)
}
// Without the init's parent the pidfd may be anyone's: fail closed.
func TestLaunchFailsClosedWhenTheParentIsUnreadable(t *testing.T) {
readParent = func(int) (int, error) { return 0, unix.EIO }
defer func() { readParent = parentOf }()
failClosed(t)
}
// bubblewrap's monitor exits before the init is identified: the init,
// moved to another parent, cannot be told from a process that took its
// PID. The kernel's answers are fixed here (a pidfd, parent 1), so the
// case runs every time; really, the init may also be gone already.
func TestLaunchFailsClosedWhenTheMonitorLeftFirst(t *testing.T) {
cfg := testConfig(t, true)
var inside []int
testBeforeIdentity = func(monitor int) {
inside = descendants(monitor)
killAndAwaitZombie(t, monitor)
}
readParent = func(int) (int, error) { return 1, nil }
pidfdOpen = func(int, int) (int, error) { return unix.PidfdOpen(os.Getpid(), 0) }
defer func() { testBeforeIdentity, readParent, pidfdOpen = nil, parentOf, unix.PidfdOpen }()
t.Cleanup(func() {
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
})
s, err := Launch(context.Background(), cfg)
if s != nil || !errors.Is(err, ErrNotEnded) {
t.Fatalf("Launch: %v, want ErrNotEnded", err)
}
}
// The same with the kernel's real answer, which depends on timing: the
// init may still run (moved to another parent) or be gone. Either way
// Launch never returns a sandbox, and unless it says ErrNotEnded nothing
// of the sandbox runs when it returns.
func TestLaunchNeverClaimsAnUnprovenEnd(t *testing.T) {
for round := 0; round < 5; round++ {
cfg := testConfig(t, true)
var inside []int
testBeforeIdentity = func(monitor int) {
inside = descendants(monitor)
killAndAwaitZombie(t, monitor)
}
s, err := Launch(context.Background(), cfg)
testBeforeIdentity = nil
if s != nil || err == nil {
t.Fatalf("Launch: %v", err)
}
if !errors.Is(err, ErrNotEnded) {
for _, n := range inside {
if alive(n) {
t.Fatalf("no ErrNotEnded, but process %d runs: %v", n, err)
}
}
}
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
}
}
// killAndAwaitZombie kills this process's child pid and waits until it
// has exited (a zombie, not yet reaped).
func killAndAwaitZombie(t *testing.T, pid int) {
t.Helper()
unix.Kill(pid, unix.SIGKILL)
for i := 0; i < 500; i++ {
raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
if j := strings.LastIndexByte(string(raw), ')'); err == nil && j > 0 && j+2 < len(raw) && raw[j+2] == 'Z' {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("bubblewrap %d did not exit", pid)
}
// A request already cancelled starts nothing, before even the tree is
// read.
func TestLaunchAlreadyCancelled(t *testing.T) {
cfg := testConfig(t, true)
forked := false
testBeforeFork = func() { forked = true }
defer func() { testBeforeFork = nil }()
ctx, cancel := context.WithCancel(context.Background())
cancel()
s, err := Launch(ctx, cfg)
if s != nil || !errors.Is(err, context.Canceled) || errors.Is(err, ErrNotEnded) || forked {
t.Fatalf("Launch: %v (forked %v)", err, forked)
}
}
// stallingBwrap is a bubblewrap that starts and never writes its info.
func stallingBwrap(t *testing.T, cfg *LaunchConfig) (started string) {
t.Helper()
_, self := usableBwrap(t)
dir := tempDir(t)
must(t, os.Symlink(self, filepath.Join(dir, "fake-bwrap-stall")))
cfg.Bwrap = filepath.Join(dir, "fake-bwrap-stall")
return filepath.Join(dir, "started")
}
// Cancelled just before the fork: nothing starts.
func TestLaunchCancelledAtFork(t *testing.T) {
cfg := testConfig(t, true)
started := stallingBwrap(t, &cfg)
ctx, cancel := context.WithCancel(context.Background())
testBeforeFork = cancel
defer func() { testBeforeFork = nil }()
s, err := Launch(ctx, cfg)
if s != nil || !errors.Is(err, context.Canceled) || errors.Is(err, ErrNotEnded) {
t.Fatalf("Launch: %v", err)
}
time.Sleep(200 * time.Millisecond)
if _, err = os.Stat(started); err == nil {
t.Fatal("bubblewrap started")
}
}
// awaitStarted waits for the stalling bubblewrap to say it runs and
// returns its PID.
func awaitStarted(t *testing.T, started string) int {
t.Helper()
for i := 0; i < 1000; i++ {
if raw, err := os.ReadFile(started); err == nil && len(raw) > 0 {
pid, err := strconv.Atoi(string(raw))
if err != nil {
t.Fatal(err)
}
return pid
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("bubblewrap did not start")
return 0
}
// Cancelled while bubblewrap has not said which process is the init:
// Launch returns at once, having killed bubblewrap, and says the end
// could not be shown.
func TestLaunchCancelledWhileAwaitingInfo(t *testing.T) {
cfg := testConfig(t, true)
started := stallingBwrap(t, &cfg)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var pid int
go func() {
pid = awaitStarted(t, started)
cancel()
}()
begun := time.Now()
s, err := Launch(ctx, cfg)
if s != nil || !errors.Is(err, context.Canceled) || !errors.Is(err, ErrNotEnded) {
t.Fatalf("Launch: %v", err)
}
if took := time.Since(begun); took > 3*time.Second {
t.Fatalf("Launch took %v after the cancel", took)
}
if alive(pid) {
t.Fatalf("bubblewrap %d still runs", pid)
}
}
// The same when the start timeout passes instead.
func TestLaunchTimesOutAwaitingInfo(t *testing.T) {
cfg := testConfig(t, true)
started := stallingBwrap(t, &cfg)
cfg.StartTimeout = 300 * time.Millisecond
s, err := Launch(context.Background(), cfg)
if s != nil || !errors.Is(err, os.ErrDeadlineExceeded) || !errors.Is(err, ErrNotEnded) {
t.Fatalf("Launch: %v", err)
}
if pid := awaitStarted(t, started); alive(pid) {
t.Fatalf("bubblewrap %d still runs", pid)
}
}
// Cancelled once the init can be held: it is killed and shown to have
// ended, so Launch reports the cancel and not ErrNotEnded, returns no
// sandbox even when its ready came first, and nothing of the sandbox runs
// when it returns. Ten rounds: which of ready and the cancel Launch sees
// first is up to the scheduler.
func TestLaunchCancelledOnceTheInitIsHeld(t *testing.T) {
for round := 0; round < 10; round++ {
cancelOnceHeld(t)
}
}
func cancelOnceHeld(t *testing.T) {
t.Helper()
cfg := testConfig(t, true)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var inside []int
testBeforeIdentity = func(monitor int) {
inside = descendants(monitor)
cancel()
}
defer func() { testBeforeIdentity = nil }()
t.Cleanup(func() {
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
})
s, err := Launch(ctx, cfg)
if s != nil || !errors.Is(err, context.Canceled) || errors.Is(err, ErrNotEnded) {
if s != nil {
s.Close()
}
t.Fatalf("Launch: %v", err)
}
if len(inside) == 0 {
t.Fatal("no process was seen in the sandbox")
}
for _, n := range inside {
if alive(n) {
t.Fatalf("process %d runs after Launch returned", n)
}
}
}
// A sandbox outlives no cancel: once ctx is done its init is killed, and
// Wait returns with every process ended.
func TestContextEndsTheSandbox(t *testing.T) {
cfg := testConfig(t, true)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := Launch(ctx, cfg)
if err != nil {
t.Fatal(err)
}
defer s.Close()
s.ToBrowser.WriteString("hang\x00")
if reply, err := bufio.NewReader(s.FromBrowser).ReadString(0); err != nil || reply != "hanging\x00" {
t.Fatalf("hang: %q %v", reply, err)
}
inside := descendants(s.cmd.Process.Pid)
t.Cleanup(func() {
for _, n := range inside {
unix.Kill(n, unix.SIGKILL)
}
})
cancel()
done := make(chan error, 1)
go func() { _, err := s.Wait(); done <- err }()
select {
case err = <-done:
case <-time.After(5 * time.Second):
t.Fatal("the sandbox outlived its context")
}
if errors.Is(err, ErrNotEnded) {
t.Fatalf("Wait: %v", err)
}
for _, n := range inside {
if alive(n) {
t.Fatalf("process %d runs after Wait", n)
}
}
}