| 1 | //go:build linux |
| 2 | |
| 3 | package render |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "bytes" |
| 8 | "context" |
| 9 | "crypto/sha256" |
| 10 | "debug/elf" |
| 11 | "encoding/hex" |
| 12 | "encoding/json" |
| 13 | "errors" |
| 14 | "fmt" |
| 15 | "net" |
| 16 | "net/netip" |
| 17 | "os" |
| 18 | "os/exec" |
| 19 | "path/filepath" |
| 20 | "slices" |
| 21 | "strconv" |
| 22 | "strings" |
| 23 | "testing" |
| 24 | "time" |
| 25 | |
| 26 | "golang.org/x/sys/unix" |
| 27 | |
| 28 | "amadan.net/oficina/equipo/internal/release" |
| 29 | "amadan.net/oficina/equipo/internal/testci" |
| 30 | "amadan.net/oficina/equipo/internal/wire" |
| 31 | ) |
| 32 | |
| 33 | // usableBwrap is bubblewrap, when it can make namespaces here, and this |
| 34 | // test binary, which must be static to run inside a sandbox with no |
| 35 | // host /usr. |
| 36 | func usableBwrap(t *testing.T) (bwrap, self string) { |
| 37 | t.Helper() |
| 38 | testci.Tools(t, "bwrap") |
| 39 | bwrap, err := exec.LookPath("bwrap") |
| 40 | if err != nil { |
| 41 | testci.Absent(t, "bwrap is not installed") |
| 42 | } |
| 43 | if out, err := exec.Command(bwrap, "--unshare-all", "--ro-bind", "/", "/", "true").CombinedOutput(); err != nil { |
| 44 | testci.Absent(t, "bwrap cannot create namespaces here: "+strings.TrimSpace(string(out))) |
| 45 | } |
| 46 | if self, err = os.Executable(); err != nil { |
| 47 | t.Fatal(err) |
| 48 | } |
| 49 | if self, err = filepath.EvalSymlinks(self); err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | f, err := elf.Open(self) |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | defer f.Close() |
| 57 | for _, p := range f.Progs { |
| 58 | if p.Type == elf.PT_INTERP { |
| 59 | t.Skip("the test binary is dynamically linked; run with CGO_ENABLED=0 as make does") |
| 60 | } |
| 61 | } |
| 62 | return bwrap, self |
| 63 | } |
| 64 | |
| 65 | func tempDir(t *testing.T) string { |
| 66 | t.Helper() |
| 67 | dir, err := filepath.EvalSymlinks(t.TempDir()) |
| 68 | if err != nil { |
| 69 | t.Fatal(err) |
| 70 | } |
| 71 | // t.TempDir's mode follows the umask; the tree's directory must not |
| 72 | // be group writable. |
| 73 | must(t, os.Chmod(dir, 0o700)) |
| 74 | return dir |
| 75 | } |
| 76 | |
| 77 | // testTree writes a renderer tree that verifies, with the layout the |
| 78 | // launch binds (usr, etc/fonts) and, when browser is not "", that file |
| 79 | // as the browser. It returns the tree and its pin. |
| 80 | func testTree(t *testing.T, browser string) (dir, pin string) { |
| 81 | t.Helper() |
| 82 | dir = filepath.Join(tempDir(t), "tree") |
| 83 | return dir, writeTree(t, dir, browser) |
| 84 | } |
| 85 | |
| 86 | // writeTree writes testTree's tree at dir and returns its pin. |
| 87 | func writeTree(t *testing.T, dir, browser string) (pin string) { |
| 88 | t.Helper() |
| 89 | entries := []string{"dir etc", "dir etc/fonts", "dir usr", "dir usr/lib", "dir usr/lib/chromium"} |
| 90 | must(t, os.Mkdir(dir, 0o755)) |
| 91 | for _, e := range entries { |
| 92 | must(t, os.Mkdir(filepath.Join(dir, strings.TrimPrefix(e, "dir ")), 0o755)) |
| 93 | } |
| 94 | if browser != "" { |
| 95 | raw, err := os.ReadFile(browser) |
| 96 | must(t, err) |
| 97 | rel := strings.TrimPrefix(BrowserPath, "/") |
| 98 | must(t, os.WriteFile(filepath.Join(dir, rel), raw, 0o755)) |
| 99 | sum := sha256.Sum256(raw) |
| 100 | entries = append(entries, fmt.Sprintf("file %s %x 0755", rel, sum)) |
| 101 | } |
| 102 | manifest := strings.Join(entries, "\n") + "\n" |
| 103 | must(t, os.WriteFile(filepath.Join(dir, "MANIFEST"), []byte(manifest), 0o644)) |
| 104 | sum := sha256.Sum256([]byte(manifest)) |
| 105 | pin = hex.EncodeToString(sum[:]) |
| 106 | if err := release.VerifyRenderer(dir, pin); err != nil { |
| 107 | t.Fatalf("test tree: %v", err) |
| 108 | } |
| 109 | return pin |
| 110 | } |
| 111 | |
| 112 | func testSite(t *testing.T) string { |
| 113 | t.Helper() |
| 114 | dir := filepath.Join(tempDir(t), "site") |
| 115 | must(t, os.Mkdir(dir, 0o755)) |
| 116 | must(t, os.WriteFile(filepath.Join(dir, "index.html"), []byte("<title>shop</title>"), 0o644)) |
| 117 | return dir |
| 118 | } |
| 119 | |
| 120 | func testOut(t *testing.T) string { |
| 121 | t.Helper() |
| 122 | dir := filepath.Join(tempDir(t), "out") |
| 123 | must(t, os.Mkdir(dir, 0o700)) |
| 124 | return dir |
| 125 | } |
| 126 | |
| 127 | func must(t *testing.T, errs ...error) { |
| 128 | t.Helper() |
| 129 | for _, err := range errs { |
| 130 | if err != nil && !errors.Is(err, os.ErrExist) { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func testConfig(t *testing.T, browser bool) LaunchConfig { |
| 137 | t.Helper() |
| 138 | bwrap, self := usableBwrap(t) |
| 139 | b := "" |
| 140 | if browser { |
| 141 | b = self |
| 142 | } |
| 143 | tree, pin := testTree(t, b) |
| 144 | return LaunchConfig{Bwrap: bwrap, Binary: self, Tree: tree, Pin: pin, Site: testSite(t)} |
| 145 | } |
| 146 | |
| 147 | // runProbe runs the probe as the sandbox's first process and returns |
| 148 | // the report it sends on the browser's pipe. |
| 149 | func runProbe(t *testing.T, cfg LaunchConfig, args ...string) probeReport { |
| 150 | t.Helper() |
| 151 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 152 | defer cancel() |
| 153 | s, err := start(ctx, cfg, append([]string{"render-probe"}, args...)...) |
| 154 | if err != nil { |
| 155 | t.Fatal(err) |
| 156 | } |
| 157 | raw, rerr := readFrame(bufio.NewReader(s.FromBrowser), 64<<20) |
| 158 | if _, err = s.Wait(); err != nil { |
| 159 | t.Fatalf("probe: %v: %s", err, s.stderr.Bytes()) |
| 160 | } |
| 161 | s.Close() |
| 162 | if rerr != nil { |
| 163 | t.Fatalf("probe report: %v: %s", rerr, s.stderr.Bytes()) |
| 164 | } |
| 165 | var r probeReport |
| 166 | if err = json.Unmarshal(raw, &r); err != nil { |
| 167 | t.Fatal(err) |
| 168 | } |
| 169 | return r |
| 170 | } |
| 171 | |
| 172 | // The policy is the spike's, exactly: no --share-net, nothing from the |
| 173 | // host but the descriptors it binds, and the environment cleared. |
| 174 | func TestBwrapArgs(t *testing.T) { |
| 175 | want := "--unshare-all --unshare-user --die-with-parent --new-session --clearenv --cap-drop ALL" + |
| 176 | " --info-fd 10 --ro-bind-fd 6 /usr --symlink usr/lib /lib --symlink usr/lib64 /lib64 --symlink usr/bin /bin" + |
| 177 | " --ro-bind-fd 7 /etc/fonts --ro-bind-fd 8 /runner --ro-bind-fd 9 /site" + |
| 178 | " --size 536870912 --tmpfs /tmp --proc /proc --dev /dev --remount-ro / --chdir / -- /runner render-sandbox" |
| 179 | got := bwrapArgs(Subcommand) |
| 180 | if strings.Join(got, " ") != want { |
| 181 | t.Fatalf("bwrap args\n got %s\nwant %s", strings.Join(got, " "), want) |
| 182 | } |
| 183 | for _, a := range got { |
| 184 | if strings.HasPrefix(a, "--share") || a == "--setenv" || a == "--bind" || a == "--ro-bind" || a == "--dev-bind" { |
| 185 | t.Errorf("bwrap arg %s", a) |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | // tailnetAddr is one of this host's tailnet addresses (100.64.0.0/10), |
| 191 | // if it has one. |
| 192 | func tailnetAddr() (netip.Addr, bool) { |
| 193 | cgnat := netip.MustParsePrefix("100.64.0.0/10") |
| 194 | addrs, _ := net.InterfaceAddrs() |
| 195 | for _, a := range addrs { |
| 196 | if p, err := netip.ParsePrefix(a.String()); err == nil && cgnat.Contains(p.Addr()) { |
| 197 | return p.Addr(), true |
| 198 | } |
| 199 | } |
| 200 | return netip.Addr{}, false |
| 201 | } |
| 202 | |
| 203 | // listen opens a listener on the host that accepts and closes. |
| 204 | func listen(t *testing.T, addr string) string { |
| 205 | t.Helper() |
| 206 | ln, err := net.Listen("tcp", addr) |
| 207 | if err != nil { |
| 208 | t.Fatal(err) |
| 209 | } |
| 210 | t.Cleanup(func() { ln.Close() }) |
| 211 | go func() { |
| 212 | for { |
| 213 | c, err := ln.Accept() |
| 214 | if err != nil { |
| 215 | return |
| 216 | } |
| 217 | c.Close() |
| 218 | } |
| 219 | }() |
| 220 | return ln.Addr().String() |
| 221 | } |
| 222 | |
| 223 | // From inside, only the sandbox's own loopback answers: a public IP, the |
| 224 | // host's tailnet address and a listener on the host's 127.0.0.1 are |
| 225 | // unreachable, and no name resolves. |
| 226 | func TestSandboxReachesNoNetwork(t *testing.T) { |
| 227 | cfg := testConfig(t, false) |
| 228 | targets := map[string]string{ |
| 229 | "public IPv4": "1.1.1.1:443", |
| 230 | "public IPv6": "[2606:4700:4700::1111]:443", |
| 231 | "host loopback": listen(t, "127.0.0.1:0"), |
| 232 | } |
| 233 | if addr, ok := tailnetAddr(); ok { |
| 234 | targets["host tailnet"] = listen(t, netip.AddrPortFrom(addr, 0).String()) |
| 235 | } else { |
| 236 | t.Log("this host has no tailnet address; that case is not run") |
| 237 | } |
| 238 | var args []string |
| 239 | for _, a := range targets { |
| 240 | args = append(args, "dial="+a) |
| 241 | } |
| 242 | r := runProbe(t, cfg, args...) |
| 243 | if r.Loopback != "" { |
| 244 | t.Fatalf("the sandbox's own loopback does not work: %s", r.Loopback) |
| 245 | } |
| 246 | if !slices.Equal(r.Interfaces, []string{"lo"}) { |
| 247 | t.Errorf("interfaces %q", r.Interfaces) |
| 248 | } |
| 249 | for name, a := range targets { |
| 250 | if e, ok := r.Dials[a]; !ok || e == "" { |
| 251 | t.Errorf("%s %s: reached from inside (%q)", name, a, e) |
| 252 | } |
| 253 | } |
| 254 | if r.Lookup == "" { |
| 255 | t.Error("a public name resolved from inside") |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // A descriptor the runner left inheritable never reaches the sandbox: |
| 260 | // its first process holds 0, 1, 2, the browser's pipe and the status |
| 261 | // pipe, and the runner's own descriptor stays open. |
| 262 | func TestSandboxSeesNoParentDescriptor(t *testing.T) { |
| 263 | cfg := testConfig(t, false) |
| 264 | secret := filepath.Join(tempDir(t), "forge.json") |
| 265 | must(t, os.WriteFile(secret, []byte(`{"token":"secret"}`), 0o600)) |
| 266 | opened, err := os.Open(secret) |
| 267 | if err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | defer opened.Close() |
| 271 | // Above the descriptors the launch hands bubblewrap (3 to 10), which |
| 272 | // would replace it in the child, and without close-on-exec, as F_DUPFD |
| 273 | // leaves it. |
| 274 | fd, err := unix.FcntlInt(opened.Fd(), unix.F_DUPFD, 20) |
| 275 | if err != nil { |
| 276 | t.Fatal(err) |
| 277 | } |
| 278 | f := os.NewFile(uintptr(fd), secret) |
| 279 | defer f.Close() |
| 280 | if flags, err := unix.FcntlInt(f.Fd(), unix.F_GETFD, 0); err != nil || flags&unix.FD_CLOEXEC != 0 { |
| 281 | t.Fatalf("the descriptor is not inheritable: %d %v", flags, err) |
| 282 | } |
| 283 | r := runProbe(t, cfg) |
| 284 | if want := []int{0, 1, 2, fdBrowserIn, fdBrowserOut, fdStatus}; !slices.Equal(r.FDs, want) { |
| 285 | t.Fatalf("descriptors inside %v, want %v (the runner's file is %d)", r.FDs, want, f.Fd()) |
| 286 | } |
| 287 | if _, err = f.Stat(); err != nil { |
| 288 | t.Fatalf("the runner's own descriptor: %v", err) |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | // The sandbox's first process starts with an empty environment: nothing |
| 293 | // from the runner's. Bubblewrap itself sets PWD after --chdir. |
| 294 | func TestSandboxEnvironmentIsEmpty(t *testing.T) { |
| 295 | cfg := testConfig(t, false) |
| 296 | t.Setenv("EQUIPO_RUNNER_TOKEN", "secret") |
| 297 | t.Setenv("HOME", "/home/runner") |
| 298 | r := runProbe(t, cfg) |
| 299 | if len(r.Env) > 1 || len(r.Env) == 1 && r.Env[0] != "PWD=/" { |
| 300 | t.Fatalf("environment %q", r.Env) |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // /site, the tree, the binary and the root are read only, and there is |
| 305 | // no /out: /tmp, which ends with the sandbox, is the only place it |
| 306 | // writes. |
| 307 | func TestSandboxSiteIsReadOnly(t *testing.T) { |
| 308 | cfg := testConfig(t, false) |
| 309 | r := runProbe(t, cfg) |
| 310 | for op, e := range r.Writes { |
| 311 | writable := op == "create /tmp/new" |
| 312 | switch { |
| 313 | case writable && e != "": |
| 314 | t.Errorf("%s: %s", op, e) |
| 315 | case !writable && !strings.Contains(e, "read-only file system"): |
| 316 | t.Errorf("%s: %q, want read-only file system", op, e) |
| 317 | } |
| 318 | } |
| 319 | if len(r.Writes) != 11 { |
| 320 | t.Errorf("writes %v", r.Writes) |
| 321 | } |
| 322 | if raw, err := os.ReadFile(filepath.Join(cfg.Site, "index.html")); err != nil || string(raw) != "<title>shop</title>" { |
| 323 | t.Errorf("the site changed: %q %v", raw, err) |
| 324 | } |
| 325 | if _, err := os.Stat(filepath.Join(cfg.Site, "new")); err == nil { |
| 326 | t.Error("the sandbox created a file in the site") |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | // Nothing of the host but what the launch binds is visible: no home, |
| 331 | // runner state or credentials. |
| 332 | func TestSandboxHoldsNoRunnerState(t *testing.T) { |
| 333 | cfg := testConfig(t, false) |
| 334 | r := runProbe(t, cfg) |
| 335 | 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} |
| 336 | for _, p := range r.Paths { |
| 337 | if !allowed[p] { |
| 338 | t.Errorf("the sandbox shows %s", p) |
| 339 | } |
| 340 | } |
| 341 | if !slices.Contains(r.Paths, "/site/index.html") { |
| 342 | t.Errorf("paths %q", r.Paths) |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | // A page whose server redirects to an external host gets the redirect, |
| 347 | // and following it fails to resolve or connect: reported, not followed. |
| 348 | func TestSandboxRedirectIsReportedNotFollowed(t *testing.T) { |
| 349 | cfg := testConfig(t, false) |
| 350 | targets := []string{"http://cdn.example.com/app.js", "http://1.1.1.1/", "http://[2606:4700:4700::1111]/"} |
| 351 | var args []string |
| 352 | for _, u := range targets { |
| 353 | args = append(args, "redirect="+u) |
| 354 | } |
| 355 | r := runProbe(t, cfg, args...) |
| 356 | for _, u := range targets { |
| 357 | got, ok := r.Redirects[u] |
| 358 | if !ok || got.Location != u { |
| 359 | t.Errorf("%s: the redirect was not seen: %+v", u, got) |
| 360 | continue |
| 361 | } |
| 362 | if got.Status != 0 || !got.Blocked { |
| 363 | t.Errorf("%s: followed: %+v", u, got) |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | // Launch runs the real subcommand: the site served on the sandbox's |
| 369 | // 127.0.0.1, the browser started with its pipe on 3 and 4 and nothing |
| 370 | // else, HOME=/tmp its whole environment, and its exit reported. |
| 371 | func TestLaunchStartsTheBrowser(t *testing.T) { |
| 372 | cfg := testConfig(t, true) |
| 373 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 374 | defer cancel() |
| 375 | s, err := Launch(ctx, cfg) |
| 376 | if err != nil { |
| 377 | t.Fatal(err) |
| 378 | } |
| 379 | defer s.Close() |
| 380 | if !siteURL.MatchString(s.Site) { |
| 381 | t.Fatalf("site %q", s.Site) |
| 382 | } |
| 383 | from := bufio.NewReader(s.FromBrowser) |
| 384 | ask := func(msg string) string { |
| 385 | t.Helper() |
| 386 | if _, err := s.ToBrowser.WriteString(msg + "\x00"); err != nil { |
| 387 | t.Fatal(err) |
| 388 | } |
| 389 | reply, err := from.ReadString(0) |
| 390 | if err != nil { |
| 391 | t.Fatalf("%s: %v", msg, err) |
| 392 | } |
| 393 | return strings.TrimSuffix(reply, "\x00") |
| 394 | } |
| 395 | if got := ask("ping"); got != "ping" { |
| 396 | t.Fatalf("echo %q", got) |
| 397 | } |
| 398 | if got := ask("get " + s.Site + "index.html"); got != "200 <title>shop</title>" { |
| 399 | t.Fatalf("site %q", got) |
| 400 | } |
| 401 | if got := ask("get " + s.Site + "../../usr/lib/chromium/chromium-headless-shell"); strings.HasPrefix(got, "200") { |
| 402 | t.Fatalf("the site server left /site: %.40q", got) |
| 403 | } |
| 404 | if got := ask("post " + s.Site + "index.html"); got != "405" { |
| 405 | t.Fatalf("post %q", got) |
| 406 | } |
| 407 | raw := []byte(ask("report")) |
| 408 | s.ToBrowser.WriteString("exit 7\x00") |
| 409 | exit, err := s.Wait() |
| 410 | if err != nil || exit != (BrowserExit{Known: true, Code: 7}) { |
| 411 | t.Fatalf("exit %+v, %v: %s", exit, err, s.stderr.Bytes()) |
| 412 | } |
| 413 | if _, err = from.ReadByte(); err == nil { |
| 414 | t.Fatal("the browser's pipe is still open") |
| 415 | } |
| 416 | var b browserReport |
| 417 | if err = json.Unmarshal(raw, &b); err != nil { |
| 418 | t.Fatal(err) |
| 419 | } |
| 420 | if !slices.Equal(b.Args, browserArgs()) { |
| 421 | t.Errorf("browser args %q", b.Args) |
| 422 | } |
| 423 | if !slices.Equal(b.Env, []string{"HOME=/tmp"}) { |
| 424 | t.Errorf("browser environment %q", b.Env) |
| 425 | } |
| 426 | if !slices.Equal(b.FDs, []int{0, 1, 2, fdBrowserIn, fdBrowserOut}) { |
| 427 | t.Errorf("browser descriptors %v", b.FDs) |
| 428 | } |
| 429 | if b.Dir != "/tmp" { |
| 430 | t.Errorf("browser directory %q", b.Dir) |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | // Closing a sandbox kills everything in it, a browser that would never |
| 435 | // end on its own included. |
| 436 | func TestCloseKillsTheSandbox(t *testing.T) { |
| 437 | cfg := testConfig(t, true) |
| 438 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 439 | defer cancel() |
| 440 | s, err := Launch(ctx, cfg) |
| 441 | if err != nil { |
| 442 | t.Fatal(err) |
| 443 | } |
| 444 | s.ToBrowser.WriteString("hang\x00") |
| 445 | if reply, err := bufio.NewReader(s.FromBrowser).ReadString(0); err != nil || reply != "hanging\x00" { |
| 446 | t.Fatalf("hang: %q %v", reply, err) |
| 447 | } |
| 448 | inside := descendants(s.cmd.Process.Pid) |
| 449 | if len(inside) < 2 { |
| 450 | t.Fatalf("processes in the sandbox: %v", inside) |
| 451 | } |
| 452 | // Should the kill fail, the test still leaves nothing running. |
| 453 | t.Cleanup(func() { |
| 454 | for _, n := range inside { |
| 455 | unix.Kill(n, unix.SIGKILL) |
| 456 | } |
| 457 | }) |
| 458 | done := make(chan struct{}) |
| 459 | go func() { s.Close(); close(done) }() |
| 460 | select { |
| 461 | case <-done: |
| 462 | case <-time.After(5 * time.Second): |
| 463 | t.Fatal("Close did not end the sandbox promptly") |
| 464 | } |
| 465 | if _, err = s.Wait(); err == nil { |
| 466 | t.Fatal("a killed sandbox reported success") |
| 467 | } |
| 468 | // Every process that was in the sandbox (bubblewrap's, the |
| 469 | // subcommand, the browser) ends: the kernel kills the rest of a PID |
| 470 | // namespace when its first process dies, a moment after bubblewrap. |
| 471 | deadline := time.Now().Add(5 * time.Second) |
| 472 | for _, n := range inside { |
| 473 | for alive(n) && time.Now().Before(deadline) { |
| 474 | time.Sleep(20 * time.Millisecond) |
| 475 | } |
| 476 | if alive(n) { |
| 477 | raw, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "status")) |
| 478 | t.Errorf("process %d outlived the sandbox: %.200s", n, raw) |
| 479 | } |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | // alive is a process that exists and is not a zombie. |
| 484 | func alive(pid int) bool { |
| 485 | raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "status")) |
| 486 | return err == nil && !strings.Contains(string(raw), "State:\tZ") |
| 487 | } |
| 488 | |
| 489 | // A tree without the browser: render-sandbox reports it and Launch fails. |
| 490 | func TestLaunchReportsABrowserThatCannotStart(t *testing.T) { |
| 491 | cfg := testConfig(t, false) |
| 492 | _, err := Launch(context.Background(), cfg) |
| 493 | if err == nil || !strings.Contains(err.Error(), "failed ("+reasonBrowser+")") { |
| 494 | t.Fatalf("Launch: %v", err) |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | // Only a tree that has just verified is mounted: a changed, missing or |
| 499 | // unpinned tree is the renderer's health and nothing starts. |
| 500 | func TestLaunchRefusesAnUnverifiedTree(t *testing.T) { |
| 501 | for name, c := range map[string]struct { |
| 502 | change func(cfg *LaunchConfig) |
| 503 | health string |
| 504 | }{ |
| 505 | "tampered": {func(cfg *LaunchConfig) { |
| 506 | os.WriteFile(filepath.Join(cfg.Tree, "usr", "lib", "extra"), []byte("x"), 0o644) |
| 507 | }, wire.ToolMismatch}, |
| 508 | "missing": {func(cfg *LaunchConfig) { cfg.Tree = filepath.Join(filepath.Dir(cfg.Tree), "absent") }, wire.ToolMissing}, |
| 509 | "unpinned": {func(cfg *LaunchConfig) { cfg.Pin = "" }, wire.ToolUnpinned}, |
| 510 | "other pin": {func(cfg *LaunchConfig) { cfg.Pin = strings.Repeat("a", 64) }, wire.ToolMismatch}, |
| 511 | } { |
| 512 | t.Run(name, func(t *testing.T) { |
| 513 | cfg := testConfig(t, false) |
| 514 | c.change(&cfg) |
| 515 | forked := noFork(t) |
| 516 | _, err := Launch(context.Background(), cfg) |
| 517 | var re *release.RendererError |
| 518 | if !errors.As(err, &re) || re.Health != c.health { |
| 519 | t.Fatalf("Launch: %v, want %s", err, c.health) |
| 520 | } |
| 521 | if *forked { |
| 522 | t.Fatal("something ran") |
| 523 | } |
| 524 | }) |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | // noFork records whether the launcher forked, until the test ends. |
| 529 | func noFork(t *testing.T) *bool { |
| 530 | t.Helper() |
| 531 | forked := new(bool) |
| 532 | testBeforeFork = func() { *forked = true } |
| 533 | t.Cleanup(func() { testBeforeFork = nil }) |
| 534 | return forked |
| 535 | } |
| 536 | |
| 537 | func TestLaunchRefusesItsInputs(t *testing.T) { |
| 538 | base := testConfig(t, false) |
| 539 | shared := testSite(t) |
| 540 | must(t, os.Chmod(shared, 0o775)) |
| 541 | siteLink := filepath.Join(tempDir(t), "site-link") |
| 542 | must(t, os.Symlink(testSite(t), siteLink)) |
| 543 | for name, c := range map[string]struct { |
| 544 | change func(*LaunchConfig) |
| 545 | why string |
| 546 | }{ |
| 547 | "relative bwrap": {func(c *LaunchConfig) { c.Bwrap = "bwrap" }, "launch path"}, |
| 548 | "relative binary": {func(c *LaunchConfig) { c.Binary = "runner" }, "launch path"}, |
| 549 | "missing binary": {func(c *LaunchConfig) { c.Binary = "/nonexistent/runner" }, "no such file"}, |
| 550 | "relative site": {func(c *LaunchConfig) { c.Site = "site" }, "launch path"}, |
| 551 | "shared site": {func(c *LaunchConfig) { c.Site = shared }, "only this user can write"}, |
| 552 | "root's site": {func(c *LaunchConfig) { c.Site = "/usr" }, "only this user can write"}, |
| 553 | "symlinked site": {func(c *LaunchConfig) { c.Site = siteLink }, "symbolic links"}, |
| 554 | "unclean tree": {func(c *LaunchConfig) { c.Tree += "/" }, "launch path"}, |
| 555 | } { |
| 556 | cfg := base |
| 557 | c.change(&cfg) |
| 558 | s, err := Launch(context.Background(), cfg) |
| 559 | if err == nil { |
| 560 | s.Close() |
| 561 | } |
| 562 | if err == nil || !strings.Contains(err.Error(), c.why) { |
| 563 | t.Errorf("%s: %v, want %q", name, err, c.why) |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | // The status pipe is read strictly: the first line must be ready with a |
| 569 | // loopback site or failed, lines are bounded, and anything else ends the |
| 570 | // reading. |
| 571 | func TestReadStatus(t *testing.T) { |
| 572 | for name, c := range map[string]struct { |
| 573 | lines string |
| 574 | ready string |
| 575 | exit BrowserExit |
| 576 | }{ |
| 577 | "ready then exit": {`{"event":"ready","site":"http://127.0.0.1:4100/"}` + "\n" + `{"event":"exit","code":3}` + "\n", "ready", BrowserExit{Known: true, Code: 3}}, |
| 578 | "failed": {`{"event":"failed","reason":"site"}` + "\n", "failed", BrowserExit{}}, |
| 579 | "another host": {`{"event":"ready","site":"http://10.0.0.1:4100/"}` + "\n", "", BrowserExit{}}, |
| 580 | "a path": {`{"event":"ready","site":"http://127.0.0.1:4100/x"}` + "\n", "", BrowserExit{}}, |
| 581 | "exit first": {`{"event":"exit","code":3}` + "\n", "", BrowserExit{}}, |
| 582 | "not JSON": {"ready\n" + `{"event":"ready","site":"http://127.0.0.1:4100/"}` + "\n", "", BrowserExit{}}, |
| 583 | "a long line": {`{"event":"failed","reason":"` + strings.Repeat("x", 2000) + `"}` + "\n", "", BrowserExit{}}, |
| 584 | "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{}}, |
| 585 | } { |
| 586 | r, w, err := os.Pipe() |
| 587 | if err != nil { |
| 588 | t.Fatal(err) |
| 589 | } |
| 590 | go func() { w.WriteString(c.lines); w.Close() }() |
| 591 | s := &Sandbox{ready: make(chan status, 1)} |
| 592 | done := make(chan struct{}) |
| 593 | s.readStatus(r, done) |
| 594 | r.Close() |
| 595 | got := "" |
| 596 | select { |
| 597 | case st := <-s.ready: |
| 598 | got = st.Event |
| 599 | default: |
| 600 | } |
| 601 | if got != c.ready || s.exit != c.exit { |
| 602 | t.Errorf("%s: ready %q exit %+v", name, got, s.exit) |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | |
| 607 | // render-sandbox's first step leaves exactly 0 to 5 open, 3 to 5 |
| 608 | // close-on-exec, whatever else it was started with; the /proc fallback |
| 609 | // closes as close_range does. |
| 610 | func TestSandboxDescriptors(t *testing.T) { |
| 611 | self, err := os.Executable() |
| 612 | if err != nil { |
| 613 | t.Fatal(err) |
| 614 | } |
| 615 | for _, mode := range []string{"", "each"} { |
| 616 | var extra []*os.File |
| 617 | for i := 0; i < 5; i++ { |
| 618 | f, err := os.Open(os.DevNull) |
| 619 | if err != nil { |
| 620 | t.Fatal(err) |
| 621 | } |
| 622 | defer f.Close() |
| 623 | extra = append(extra, f) |
| 624 | } |
| 625 | cmd := exec.Command(self, "render-fds") |
| 626 | if mode != "" { |
| 627 | cmd.Args = append(cmd.Args, mode) |
| 628 | } |
| 629 | cmd.ExtraFiles = extra |
| 630 | out, err := cmd.Output() |
| 631 | if err != nil { |
| 632 | t.Fatalf("%q: %v", mode, err) |
| 633 | } |
| 634 | var r fdsReport |
| 635 | if err = json.Unmarshal(out, &r); err != nil { |
| 636 | t.Fatalf("%q: %v: %s", mode, err, out) |
| 637 | } |
| 638 | if r.Err != "" || !slices.Equal(r.FDs, []int{0, 1, 2, 3, 4, 5}) { |
| 639 | t.Errorf("%q: %+v", mode, r) |
| 640 | } |
| 641 | if mode == "" && (!r.CloExec[3] || !r.CloExec[4] || !r.CloExec[5]) { |
| 642 | t.Errorf("not close-on-exec: %+v", r) |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | // A descriptor another goroutine opens without close-on-exec just before |
| 648 | // the launcher forks is inherited by the process the launcher starts, |
| 649 | // and never reaches bubblewrap or the sandbox: render-exec closes it. |
| 650 | func TestSandboxSeesNothingOpenedAtFork(t *testing.T) { |
| 651 | cfg := testConfig(t, false) |
| 652 | var leaked int = -1 |
| 653 | testBeforeFork = func() { |
| 654 | f, err := os.Open(os.DevNull) |
| 655 | if err != nil { |
| 656 | return |
| 657 | } |
| 658 | leaked, _ = unix.FcntlInt(f.Fd(), unix.F_DUPFD, 30) |
| 659 | f.Close() |
| 660 | } |
| 661 | defer func() { testBeforeFork = nil }() |
| 662 | r := runProbe(t, cfg) |
| 663 | if leaked < 30 { |
| 664 | t.Fatalf("the test's descriptor: %d", leaked) |
| 665 | } |
| 666 | defer unix.Close(leaked) |
| 667 | if flags, err := unix.FcntlInt(uintptr(leaked), unix.F_GETFD, 0); err != nil || flags&unix.FD_CLOEXEC != 0 { |
| 668 | t.Fatalf("the test's descriptor is not inheritable: %d %v", flags, err) |
| 669 | } |
| 670 | if want := []int{0, 1, 2, fdBrowserIn, fdBrowserOut, fdStatus}; !slices.Equal(r.FDs, want) { |
| 671 | t.Fatalf("descriptors inside %v, want %v (opened at fork: %d)", r.FDs, want, leaked) |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | // The tree mounted is the tree verified: replacing the tree, its usr, |
| 676 | // its etc or its etc/fonts between the verification and the mount is |
| 677 | // refused, and nothing runs. |
| 678 | func TestLaunchRefusesATreeReplacedAfterVerification(t *testing.T) { |
| 679 | for _, part := range []string{"", "usr", "etc", "etc/fonts"} { |
| 680 | t.Run("replace "+part, func(t *testing.T) { |
| 681 | cfg := testConfig(t, false) |
| 682 | testAfterVerify = func() { |
| 683 | p := filepath.Join(cfg.Tree, part) |
| 684 | must(t, os.Rename(p, p+".verified")) |
| 685 | // The impostor: a copy of the tree layout, with a socket |
| 686 | // and an unverified browser in reach. |
| 687 | 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)) |
| 688 | must(t, os.WriteFile(filepath.Join(p, "lib/chromium/chromium-headless-shell"), []byte("#!/bin/sh\n"), 0o755)) |
| 689 | } |
| 690 | defer func() { testAfterVerify = nil }() |
| 691 | forked := noFork(t) |
| 692 | _, err := Launch(context.Background(), cfg) |
| 693 | var re *release.RendererError |
| 694 | if !errors.As(err, &re) || re.Health != wire.ToolMismatch || !strings.Contains(re.Reason, "changed while it was verified") { |
| 695 | t.Fatalf("Launch: %v", err) |
| 696 | } |
| 697 | if *forked { |
| 698 | t.Fatal("something ran") |
| 699 | } |
| 700 | }) |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | // The tree is verified through the descriptor of its directory that the |
| 705 | // launch holds, not its path: with an ancestor renamed during the |
| 706 | // verification and a good tree put at the old path, the tree checked is |
| 707 | // still the one that will be mounted (here a tampered one), and it is |
| 708 | // refused. |
| 709 | func TestLaunchVerifiesTheTreeItMounts(t *testing.T) { |
| 710 | cfg := testConfig(t, false) |
| 711 | g := filepath.Join(tempDir(t), "g") |
| 712 | must(t, os.MkdirAll(filepath.Join(g, "p"), 0o700)) |
| 713 | cfg.Tree = filepath.Join(g, "p", "tree") |
| 714 | writeTree(t, cfg.Tree, "") |
| 715 | testBeforeVerify = func() { |
| 716 | must(t, os.WriteFile(filepath.Join(cfg.Tree, "usr", "lib", "extra"), []byte("x"), 0o644)) |
| 717 | must(t, os.Rename(g, g+".moved")) |
| 718 | must(t, os.MkdirAll(filepath.Join(g, "p"), 0o700)) |
| 719 | writeTree(t, cfg.Tree, "") |
| 720 | } |
| 721 | defer func() { testBeforeVerify = nil }() |
| 722 | s, err := Launch(context.Background(), cfg) |
| 723 | if err == nil { |
| 724 | s.Close() |
| 725 | } |
| 726 | var re *release.RendererError |
| 727 | if !errors.As(err, &re) || re.Health != wire.ToolMismatch || re.Path != "usr/lib/extra" { |
| 728 | t.Fatalf("Launch: %v", err) |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | // The tree's directory must be this user's or root's and nobody else's |
| 733 | // to write: otherwise another user could swap the tree. |
| 734 | func TestLaunchRefusesATreeOthersCanMove(t *testing.T) { |
| 735 | cfg := testConfig(t, false) |
| 736 | must(t, os.Chmod(filepath.Dir(cfg.Tree), 0o777)) |
| 737 | _, err := Launch(context.Background(), cfg) |
| 738 | var re *release.RendererError |
| 739 | if !errors.As(err, &re) || re.Health != wire.ToolMismatch || !strings.Contains(re.Reason, "another user") { |
| 740 | t.Fatalf("Launch: %v", err) |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | // When Close returns, every process of the sandbox has ended, even one |
| 745 | // that started its own session and kept writing to the browser's pipe, |
| 746 | // which the test still reads after Close. Three rounds: a Close that does not wait returns while |
| 747 | // that writer still runs in most rounds, not all. |
| 748 | func TestCloseReturnsOnlyWhenEverythingEnded(t *testing.T) { |
| 749 | for round := 0; round < 3; round++ { |
| 750 | closeAWriter(t) |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | func closeAWriter(t *testing.T) { |
| 755 | t.Helper() |
| 756 | cfg := testConfig(t, true) |
| 757 | ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| 758 | defer cancel() |
| 759 | s, err := Launch(ctx, cfg) |
| 760 | if err != nil { |
| 761 | t.Fatal(err) |
| 762 | } |
| 763 | // The test's own reader of the browser's pipe outlives Close, so |
| 764 | // the pipe stays open to a writer that survives it. |
| 765 | ticks := dupReader(t, s.FromBrowser) |
| 766 | defer ticks.Close() |
| 767 | s.ToBrowser.WriteString("spawn\x00") |
| 768 | var seen []byte |
| 769 | ticks.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 770 | for !bytes.Contains(seen, []byte("spawned\x00")) || !bytes.Contains(seen, []byte(".")) { |
| 771 | buf := make([]byte, 4096) |
| 772 | n, err := ticks.Read(buf) |
| 773 | if err != nil { |
| 774 | t.Fatalf("spawn: %q %v", seen, err) |
| 775 | } |
| 776 | seen = append(seen, buf[:n]...) |
| 777 | } |
| 778 | inside := descendants(s.cmd.Process.Pid) |
| 779 | t.Cleanup(func() { |
| 780 | for _, n := range inside { |
| 781 | unix.Kill(n, unix.SIGKILL) |
| 782 | } |
| 783 | }) |
| 784 | if err = s.Close(); err != nil { |
| 785 | t.Fatalf("Close: %v", err) |
| 786 | } |
| 787 | // What was written before Close is taken at once; after it, nothing. |
| 788 | drain(ticks, time.Millisecond) |
| 789 | for _, n := range inside { |
| 790 | if alive(n) { |
| 791 | raw, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "status")) |
| 792 | t.Fatalf("process %d still runs after Close: %.120s", n, raw) |
| 793 | } |
| 794 | } |
| 795 | time.Sleep(100 * time.Millisecond) |
| 796 | if n := drain(ticks, 20*time.Millisecond); n != 0 { |
| 797 | t.Fatalf("the browser's pipe was still written after Close: %d bytes", n) |
| 798 | } |
| 799 | } |
| 800 | |
| 801 | // dupReader is a second reader of f's pipe, with its own deadlines. |
| 802 | func dupReader(t *testing.T, f *os.File) *os.File { |
| 803 | t.Helper() |
| 804 | rc, err := f.SyscallConn() |
| 805 | if err != nil { |
| 806 | t.Fatal(err) |
| 807 | } |
| 808 | fd := -1 |
| 809 | if cerr := rc.Control(func(raw uintptr) { fd, err = unix.FcntlInt(raw, unix.F_DUPFD_CLOEXEC, 0) }); cerr != nil || err != nil { |
| 810 | t.Fatal(cerr, err) |
| 811 | } |
| 812 | must(t, unix.SetNonblock(fd, true)) |
| 813 | return os.NewFile(uintptr(fd), "ticks") |
| 814 | } |
| 815 | |
| 816 | // drain reads what r holds, for at most d, and returns how much. |
| 817 | func drain(r *os.File, d time.Duration) int { |
| 818 | r.SetReadDeadline(time.Now().Add(d)) |
| 819 | total := 0 |
| 820 | buf := make([]byte, 64<<10) |
| 821 | for { |
| 822 | n, err := r.Read(buf) |
| 823 | total += n |
| 824 | if err != nil { |
| 825 | return total |
| 826 | } |
| 827 | } |
| 828 | } |
| 829 | |
| 830 | // The real browser, from a tree scripts/build-renderer-tree.py kept |
| 831 | // (--tree), starts in the sandbox with its own sandbox on and answers on |
| 832 | // its pipe. Building a tree downloads about 164 MB, so this runs only |
| 833 | // when EQUIPO_RENDERER_TREE names one. |
| 834 | func TestLaunchRealBrowser(t *testing.T) { |
| 835 | tree := os.Getenv("EQUIPO_RENDERER_TREE") |
| 836 | if tree == "" { |
| 837 | t.Skip("set EQUIPO_RENDERER_TREE to a tree built by scripts/build-renderer-tree.py --tree to run the real browser") |
| 838 | } |
| 839 | bwrap, self := usableBwrap(t) |
| 840 | manifest, err := os.ReadFile(filepath.Join(tree, "MANIFEST")) |
| 841 | if err != nil { |
| 842 | t.Fatal(err) |
| 843 | } |
| 844 | sum := sha256.Sum256(manifest) |
| 845 | var stderr bounded |
| 846 | stderr.max = 64 << 10 |
| 847 | cfg := LaunchConfig{Bwrap: bwrap, Binary: self, Tree: tree, Pin: hex.EncodeToString(sum[:]), Site: testSite(t), Stderr: &stderr} |
| 848 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) |
| 849 | defer cancel() |
| 850 | s, err := Launch(ctx, cfg) |
| 851 | if err != nil { |
| 852 | t.Fatal(err) |
| 853 | } |
| 854 | defer s.Close() |
| 855 | from := bufio.NewReader(s.FromBrowser) |
| 856 | call := func(id int, method string) map[string]any { |
| 857 | t.Helper() |
| 858 | msg, _ := json.Marshal(map[string]any{"id": id, "method": method}) |
| 859 | if _, err := s.ToBrowser.Write(append(msg, 0)); err != nil { |
| 860 | t.Fatal(err) |
| 861 | } |
| 862 | for { |
| 863 | raw, err := from.ReadBytes(0) |
| 864 | if err != nil { |
| 865 | t.Fatalf("%s: %v", method, err) |
| 866 | } |
| 867 | var reply map[string]any |
| 868 | if err = json.Unmarshal(raw[:len(raw)-1], &reply); err != nil { |
| 869 | t.Fatalf("%s: %v", method, err) |
| 870 | } |
| 871 | if reply["id"] == float64(id) { |
| 872 | return reply |
| 873 | } |
| 874 | } |
| 875 | } |
| 876 | version := call(1, "Browser.getVersion") |
| 877 | result, _ := version["result"].(map[string]any) |
| 878 | if product, _ := result["product"].(string); !strings.HasPrefix(product, "HeadlessChrome/") { |
| 879 | t.Fatalf("version %v", version) |
| 880 | } |
| 881 | // Chromium's own sandbox is on: a renderer below bubblewrap runs |
| 882 | // under its seccomp filter with no new privileges. |
| 883 | deadline := time.Now().Add(10 * time.Second) |
| 884 | for !sandboxedRenderer(s.cmd.Process.Pid) { |
| 885 | if time.Now().After(deadline) { |
| 886 | t.Fatal("no renderer under Chromium's own sandbox") |
| 887 | } |
| 888 | time.Sleep(100 * time.Millisecond) |
| 889 | } |
| 890 | call(2, "Browser.close") |
| 891 | exit, err := s.Wait() |
| 892 | if err != nil || exit != (BrowserExit{Known: true}) { |
| 893 | t.Fatalf("exit %+v, %v", exit, err) |
| 894 | } |
| 895 | t.Logf("browser: %v; stderr:\n%s", result["product"], stderr.Bytes()) |
| 896 | } |
| 897 | |
| 898 | // descendants lists the processes below pid, read from the host's /proc. |
| 899 | func descendants(pid int) []int { |
| 900 | parent := map[int]int{} |
| 901 | entries, _ := os.ReadDir("/proc") |
| 902 | for _, e := range entries { |
| 903 | n, err := strconv.Atoi(e.Name()) |
| 904 | if err != nil { |
| 905 | continue |
| 906 | } |
| 907 | raw, err := os.ReadFile(filepath.Join("/proc", e.Name(), "status")) |
| 908 | if err != nil { |
| 909 | continue |
| 910 | } |
| 911 | for _, line := range strings.Split(string(raw), "\n") { |
| 912 | if v, ok := strings.CutPrefix(line, "PPid:"); ok { |
| 913 | parent[n], _ = strconv.Atoi(strings.TrimSpace(v)) |
| 914 | } |
| 915 | } |
| 916 | } |
| 917 | var below []int |
| 918 | for n := range parent { |
| 919 | for p, i := parent[n], 0; i < 64 && p > 1; p, i = parent[p], i+1 { |
| 920 | if p == pid { |
| 921 | below = append(below, n) |
| 922 | break |
| 923 | } |
| 924 | } |
| 925 | } |
| 926 | return below |
| 927 | } |
| 928 | |
| 929 | // sandboxedRenderer is a process below pid whose command line is a |
| 930 | // Chromium renderer's and that runs with a seccomp filter (Seccomp 2) |
| 931 | // and NoNewPrivs 1, read from the host's /proc. |
| 932 | func sandboxedRenderer(pid int) bool { |
| 933 | for _, n := range descendants(pid) { |
| 934 | cmdline, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "cmdline")) |
| 935 | if !strings.Contains(string(cmdline), "--type=renderer") { |
| 936 | continue |
| 937 | } |
| 938 | raw, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(n), "status")) |
| 939 | st := string(raw) |
| 940 | if strings.Contains(st, "\nSeccomp:\t2\n") && strings.Contains(st, "\nNoNewPrivs:\t1\n") { |
| 941 | return true |
| 942 | } |
| 943 | } |
| 944 | return false |
| 945 | } |
| 946 | |
| 947 | // identify's rules, each observation alone: only a process whose parent |
| 948 | // is the unreaped monitor is held, only no process at the PID is the |
| 949 | // init gone, and everything else is unknown, its pidfd closed. |
| 950 | func TestIdentify(t *testing.T) { |
| 951 | defer func() { pidfdOpen, readParent = unix.PidfdOpen, parentOf }() |
| 952 | const pid, monitor = 4242, 4241 |
| 953 | for name, c := range map[string]struct { |
| 954 | openErr error |
| 955 | parent int |
| 956 | parentErr error |
| 957 | pid int |
| 958 | want initState |
| 959 | }{ |
| 960 | "parent is the monitor": {parent: monitor, want: initHeld}, |
| 961 | "no process at the PID (pidfd)": {openErr: unix.ESRCH, want: initGone}, |
| 962 | "no process at the PID (/proc)": {parentErr: os.ErrNotExist, want: initGone}, |
| 963 | "process gone while read": {parentErr: unix.ESRCH, want: initGone}, |
| 964 | "no pidfd: descriptors exhausted": {openErr: unix.EMFILE, want: initUnknown}, |
| 965 | "no pidfd: not permitted": {openErr: unix.EPERM, want: initUnknown}, |
| 966 | "parent unreadable": {parentErr: unix.EIO, want: initUnknown}, |
| 967 | "another parent (monitor gone)": {parent: 1, want: initUnknown}, |
| 968 | "no PID": {pid: -1, want: initUnknown}, |
| 969 | "PID 1": {pid: 1, want: initUnknown}, |
| 970 | } { |
| 971 | var opened = -1 |
| 972 | pidfdOpen = func(int, int) (int, error) { |
| 973 | if c.openErr != nil { |
| 974 | return -1, c.openErr |
| 975 | } |
| 976 | f, err := os.Open(os.DevNull) |
| 977 | if err != nil { |
| 978 | t.Fatal(err) |
| 979 | } |
| 980 | opened, _ = unix.Dup(int(f.Fd())) |
| 981 | f.Close() |
| 982 | return opened, nil |
| 983 | } |
| 984 | readParent = func(int) (int, error) { return c.parent, c.parentErr } |
| 985 | p := pid |
| 986 | if c.pid != 0 { |
| 987 | p = c.pid |
| 988 | } |
| 989 | fd, state := identify(p, monitor) |
| 990 | if state != c.want { |
| 991 | t.Errorf("%s: state %d, want %d", name, state, c.want) |
| 992 | } |
| 993 | switch { |
| 994 | case state == initHeld && fd != opened: |
| 995 | t.Errorf("%s: fd %d, want %d", name, fd, opened) |
| 996 | case state != initHeld && fd != -1: |
| 997 | t.Errorf("%s: fd %d", name, fd) |
| 998 | case state != initHeld && opened >= 0: |
| 999 | if _, err := unix.FcntlInt(uintptr(opened), unix.F_GETFD, 0); err == nil { |
| 1000 | t.Errorf("%s: the pidfd was left open", name) |
| 1001 | unix.Close(opened) |
| 1002 | } |
| 1003 | } |
| 1004 | if state == initHeld { |
| 1005 | unix.Close(fd) |
| 1006 | } |
| 1007 | } |
| 1008 | } |
| 1009 | |
| 1010 | // failClosed launches a real sandbox with a fault injected and checks |
| 1011 | // Launch fails with ErrNotEnded and returns no sandbox; whatever ran is |
| 1012 | // killed at the end of the test. |
| 1013 | func failClosed(t *testing.T) { |
| 1014 | t.Helper() |
| 1015 | cfg := testConfig(t, true) |
| 1016 | var inside []int |
| 1017 | testBeforeIdentity = func(monitor int) { inside = descendants(monitor) } |
| 1018 | defer func() { testBeforeIdentity = nil }() |
| 1019 | t.Cleanup(func() { |
| 1020 | for _, n := range inside { |
| 1021 | unix.Kill(n, unix.SIGKILL) |
| 1022 | } |
| 1023 | }) |
| 1024 | s, err := Launch(context.Background(), cfg) |
| 1025 | if s != nil || !errors.Is(err, ErrNotEnded) { |
| 1026 | if s != nil { |
| 1027 | s.Close() |
| 1028 | } |
| 1029 | t.Fatalf("Launch: %v, want ErrNotEnded", err) |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | // Without a pidfd on the init (descriptors exhausted) the end of the |
| 1034 | // sandbox cannot be shown: Launch fails closed. |
| 1035 | func TestLaunchFailsClosedWithoutAPidfd(t *testing.T) { |
| 1036 | pidfdOpen = func(int, int) (int, error) { return -1, unix.EMFILE } |
| 1037 | defer func() { pidfdOpen = unix.PidfdOpen }() |
| 1038 | failClosed(t) |
| 1039 | } |
| 1040 | |
| 1041 | // Without the init's parent the pidfd may be anyone's: fail closed. |
| 1042 | func TestLaunchFailsClosedWhenTheParentIsUnreadable(t *testing.T) { |
| 1043 | readParent = func(int) (int, error) { return 0, unix.EIO } |
| 1044 | defer func() { readParent = parentOf }() |
| 1045 | failClosed(t) |
| 1046 | } |
| 1047 | |
| 1048 | // bubblewrap's monitor exits before the init is identified: the init, |
| 1049 | // moved to another parent, cannot be told from a process that took its |
| 1050 | // PID. The kernel's answers are fixed here (a pidfd, parent 1), so the |
| 1051 | // case runs every time; really, the init may also be gone already. |
| 1052 | func TestLaunchFailsClosedWhenTheMonitorLeftFirst(t *testing.T) { |
| 1053 | cfg := testConfig(t, true) |
| 1054 | var inside []int |
| 1055 | testBeforeIdentity = func(monitor int) { |
| 1056 | inside = descendants(monitor) |
| 1057 | killAndAwaitZombie(t, monitor) |
| 1058 | } |
| 1059 | readParent = func(int) (int, error) { return 1, nil } |
| 1060 | pidfdOpen = func(int, int) (int, error) { return unix.PidfdOpen(os.Getpid(), 0) } |
| 1061 | defer func() { testBeforeIdentity, readParent, pidfdOpen = nil, parentOf, unix.PidfdOpen }() |
| 1062 | t.Cleanup(func() { |
| 1063 | for _, n := range inside { |
| 1064 | unix.Kill(n, unix.SIGKILL) |
| 1065 | } |
| 1066 | }) |
| 1067 | s, err := Launch(context.Background(), cfg) |
| 1068 | if s != nil || !errors.Is(err, ErrNotEnded) { |
| 1069 | t.Fatalf("Launch: %v, want ErrNotEnded", err) |
| 1070 | } |
| 1071 | } |
| 1072 | |
| 1073 | // The same with the kernel's real answer, which depends on timing: the |
| 1074 | // init may still run (moved to another parent) or be gone. Either way |
| 1075 | // Launch never returns a sandbox, and unless it says ErrNotEnded nothing |
| 1076 | // of the sandbox runs when it returns. |
| 1077 | func TestLaunchNeverClaimsAnUnprovenEnd(t *testing.T) { |
| 1078 | for round := 0; round < 5; round++ { |
| 1079 | cfg := testConfig(t, true) |
| 1080 | var inside []int |
| 1081 | testBeforeIdentity = func(monitor int) { |
| 1082 | inside = descendants(monitor) |
| 1083 | killAndAwaitZombie(t, monitor) |
| 1084 | } |
| 1085 | s, err := Launch(context.Background(), cfg) |
| 1086 | testBeforeIdentity = nil |
| 1087 | if s != nil || err == nil { |
| 1088 | t.Fatalf("Launch: %v", err) |
| 1089 | } |
| 1090 | if !errors.Is(err, ErrNotEnded) { |
| 1091 | for _, n := range inside { |
| 1092 | if alive(n) { |
| 1093 | t.Fatalf("no ErrNotEnded, but process %d runs: %v", n, err) |
| 1094 | } |
| 1095 | } |
| 1096 | } |
| 1097 | for _, n := range inside { |
| 1098 | unix.Kill(n, unix.SIGKILL) |
| 1099 | } |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | // killAndAwaitZombie kills this process's child pid and waits until it |
| 1104 | // has exited (a zombie, not yet reaped). |
| 1105 | func killAndAwaitZombie(t *testing.T, pid int) { |
| 1106 | t.Helper() |
| 1107 | unix.Kill(pid, unix.SIGKILL) |
| 1108 | for i := 0; i < 500; i++ { |
| 1109 | raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) |
| 1110 | if j := strings.LastIndexByte(string(raw), ')'); err == nil && j > 0 && j+2 < len(raw) && raw[j+2] == 'Z' { |
| 1111 | return |
| 1112 | } |
| 1113 | time.Sleep(10 * time.Millisecond) |
| 1114 | } |
| 1115 | t.Fatalf("bubblewrap %d did not exit", pid) |
| 1116 | } |
| 1117 | |
| 1118 | // A request already cancelled starts nothing, before even the tree is |
| 1119 | // read. |
| 1120 | func TestLaunchAlreadyCancelled(t *testing.T) { |
| 1121 | cfg := testConfig(t, true) |
| 1122 | forked := false |
| 1123 | testBeforeFork = func() { forked = true } |
| 1124 | defer func() { testBeforeFork = nil }() |
| 1125 | ctx, cancel := context.WithCancel(context.Background()) |
| 1126 | cancel() |
| 1127 | s, err := Launch(ctx, cfg) |
| 1128 | if s != nil || !errors.Is(err, context.Canceled) || errors.Is(err, ErrNotEnded) || forked { |
| 1129 | t.Fatalf("Launch: %v (forked %v)", err, forked) |
| 1130 | } |
| 1131 | } |
| 1132 | |
| 1133 | // stallingBwrap is a bubblewrap that starts and never writes its info. |
| 1134 | func stallingBwrap(t *testing.T, cfg *LaunchConfig) (started string) { |
| 1135 | t.Helper() |
| 1136 | _, self := usableBwrap(t) |
| 1137 | dir := tempDir(t) |
| 1138 | must(t, os.Symlink(self, filepath.Join(dir, "fake-bwrap-stall"))) |
| 1139 | cfg.Bwrap = filepath.Join(dir, "fake-bwrap-stall") |
| 1140 | return filepath.Join(dir, "started") |
| 1141 | } |
| 1142 | |
| 1143 | // Cancelled just before the fork: nothing starts. |
| 1144 | func TestLaunchCancelledAtFork(t *testing.T) { |
| 1145 | cfg := testConfig(t, true) |
| 1146 | started := stallingBwrap(t, &cfg) |
| 1147 | ctx, cancel := context.WithCancel(context.Background()) |
| 1148 | testBeforeFork = cancel |
| 1149 | defer func() { testBeforeFork = nil }() |
| 1150 | s, err := Launch(ctx, cfg) |
| 1151 | if s != nil || !errors.Is(err, context.Canceled) || errors.Is(err, ErrNotEnded) { |
| 1152 | t.Fatalf("Launch: %v", err) |
| 1153 | } |
| 1154 | time.Sleep(200 * time.Millisecond) |
| 1155 | if _, err = os.Stat(started); err == nil { |
| 1156 | t.Fatal("bubblewrap started") |
| 1157 | } |
| 1158 | } |
| 1159 | |
| 1160 | // awaitStarted waits for the stalling bubblewrap to say it runs and |
| 1161 | // returns its PID. |
| 1162 | func awaitStarted(t *testing.T, started string) int { |
| 1163 | t.Helper() |
| 1164 | for i := 0; i < 1000; i++ { |
| 1165 | if raw, err := os.ReadFile(started); err == nil && len(raw) > 0 { |
| 1166 | pid, err := strconv.Atoi(string(raw)) |
| 1167 | if err != nil { |
| 1168 | t.Fatal(err) |
| 1169 | } |
| 1170 | return pid |
| 1171 | } |
| 1172 | time.Sleep(10 * time.Millisecond) |
| 1173 | } |
| 1174 | t.Fatal("bubblewrap did not start") |
| 1175 | return 0 |
| 1176 | } |
| 1177 | |
| 1178 | // Cancelled while bubblewrap has not said which process is the init: |
| 1179 | // Launch returns at once, having killed bubblewrap, and says the end |
| 1180 | // could not be shown. |
| 1181 | func TestLaunchCancelledWhileAwaitingInfo(t *testing.T) { |
| 1182 | cfg := testConfig(t, true) |
| 1183 | started := stallingBwrap(t, &cfg) |
| 1184 | ctx, cancel := context.WithCancel(context.Background()) |
| 1185 | defer cancel() |
| 1186 | var pid int |
| 1187 | go func() { |
| 1188 | pid = awaitStarted(t, started) |
| 1189 | cancel() |
| 1190 | }() |
| 1191 | begun := time.Now() |
| 1192 | s, err := Launch(ctx, cfg) |
| 1193 | if s != nil || !errors.Is(err, context.Canceled) || !errors.Is(err, ErrNotEnded) { |
| 1194 | t.Fatalf("Launch: %v", err) |
| 1195 | } |
| 1196 | if took := time.Since(begun); took > 3*time.Second { |
| 1197 | t.Fatalf("Launch took %v after the cancel", took) |
| 1198 | } |
| 1199 | if alive(pid) { |
| 1200 | t.Fatalf("bubblewrap %d still runs", pid) |
| 1201 | } |
| 1202 | } |
| 1203 | |
| 1204 | // The same when the start timeout passes instead. |
| 1205 | func TestLaunchTimesOutAwaitingInfo(t *testing.T) { |
| 1206 | cfg := testConfig(t, true) |
| 1207 | started := stallingBwrap(t, &cfg) |
| 1208 | cfg.StartTimeout = 300 * time.Millisecond |
| 1209 | s, err := Launch(context.Background(), cfg) |
| 1210 | if s != nil || !errors.Is(err, os.ErrDeadlineExceeded) || !errors.Is(err, ErrNotEnded) { |
| 1211 | t.Fatalf("Launch: %v", err) |
| 1212 | } |
| 1213 | if pid := awaitStarted(t, started); alive(pid) { |
| 1214 | t.Fatalf("bubblewrap %d still runs", pid) |
| 1215 | } |
| 1216 | } |
| 1217 | |
| 1218 | // Cancelled once the init can be held: it is killed and shown to have |
| 1219 | // ended, so Launch reports the cancel and not ErrNotEnded, returns no |
| 1220 | // sandbox even when its ready came first, and nothing of the sandbox runs |
| 1221 | // when it returns. Ten rounds: which of ready and the cancel Launch sees |
| 1222 | // first is up to the scheduler. |
| 1223 | func TestLaunchCancelledOnceTheInitIsHeld(t *testing.T) { |
| 1224 | for round := 0; round < 10; round++ { |
| 1225 | cancelOnceHeld(t) |
| 1226 | } |
| 1227 | } |
| 1228 | |
| 1229 | func cancelOnceHeld(t *testing.T) { |
| 1230 | t.Helper() |
| 1231 | cfg := testConfig(t, true) |
| 1232 | ctx, cancel := context.WithCancel(context.Background()) |
| 1233 | defer cancel() |
| 1234 | var inside []int |
| 1235 | testBeforeIdentity = func(monitor int) { |
| 1236 | inside = descendants(monitor) |
| 1237 | cancel() |
| 1238 | } |
| 1239 | defer func() { testBeforeIdentity = nil }() |
| 1240 | t.Cleanup(func() { |
| 1241 | for _, n := range inside { |
| 1242 | unix.Kill(n, unix.SIGKILL) |
| 1243 | } |
| 1244 | }) |
| 1245 | s, err := Launch(ctx, cfg) |
| 1246 | if s != nil || !errors.Is(err, context.Canceled) || errors.Is(err, ErrNotEnded) { |
| 1247 | if s != nil { |
| 1248 | s.Close() |
| 1249 | } |
| 1250 | t.Fatalf("Launch: %v", err) |
| 1251 | } |
| 1252 | if len(inside) == 0 { |
| 1253 | t.Fatal("no process was seen in the sandbox") |
| 1254 | } |
| 1255 | for _, n := range inside { |
| 1256 | if alive(n) { |
| 1257 | t.Fatalf("process %d runs after Launch returned", n) |
| 1258 | } |
| 1259 | } |
| 1260 | } |
| 1261 | |
| 1262 | // A sandbox outlives no cancel: once ctx is done its init is killed, and |
| 1263 | // Wait returns with every process ended. |
| 1264 | func TestContextEndsTheSandbox(t *testing.T) { |
| 1265 | cfg := testConfig(t, true) |
| 1266 | ctx, cancel := context.WithCancel(context.Background()) |
| 1267 | defer cancel() |
| 1268 | s, err := Launch(ctx, cfg) |
| 1269 | if err != nil { |
| 1270 | t.Fatal(err) |
| 1271 | } |
| 1272 | defer s.Close() |
| 1273 | s.ToBrowser.WriteString("hang\x00") |
| 1274 | if reply, err := bufio.NewReader(s.FromBrowser).ReadString(0); err != nil || reply != "hanging\x00" { |
| 1275 | t.Fatalf("hang: %q %v", reply, err) |
| 1276 | } |
| 1277 | inside := descendants(s.cmd.Process.Pid) |
| 1278 | t.Cleanup(func() { |
| 1279 | for _, n := range inside { |
| 1280 | unix.Kill(n, unix.SIGKILL) |
| 1281 | } |
| 1282 | }) |
| 1283 | cancel() |
| 1284 | done := make(chan error, 1) |
| 1285 | go func() { _, err := s.Wait(); done <- err }() |
| 1286 | select { |
| 1287 | case err = <-done: |
| 1288 | case <-time.After(5 * time.Second): |
| 1289 | t.Fatal("the sandbox outlived its context") |
| 1290 | } |
| 1291 | if errors.Is(err, ErrNotEnded) { |
| 1292 | t.Fatalf("Wait: %v", err) |
| 1293 | } |
| 1294 | for _, n := range inside { |
| 1295 | if alive(n) { |
| 1296 | t.Fatalf("process %d runs after Wait", n) |
| 1297 | } |
| 1298 | } |
| 1299 | } |
| 1300 | |