package checks import ( "bytes" "context" "errors" "os" "os/exec" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/testci" ) func TestCheckSandboxDeniedPaths(t *testing.T) { root := t.TempDir() work := filepath.Join(root, "work") must(t, os.Mkdir(work, 0700)) put(t, work, "control", "readable") protectedRoot := filepath.Join(root, "go/pkg/mod") var denied []string for _, name := range []string{"state", "config", "journal", "bearer", "cleanup", "amadan", "paseo", "codex", "claude", "ssh", "resolved"} { p := filepath.Join(protectedRoot, name) put(t, protectedRoot, name+"/sentinel", "secret-"+name) denied = append(denied, p) } must(t, os.Symlink(denied[len(denied)-1], filepath.Join(root, "alias"))) denied = append(denied, filepath.Join(root, "alias")) testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) cfg := testSandboxConfig(t, binary, protectedRoot) cfg.ScratchRoot = root cfg.Protected.ProviderHomes[len(cfg.Protected.ProviderHomes)-1] = filepath.Join(root, "alias") s, err := NewCodexSandbox(context.Background(), cfg) must(t, err) // Sentinels sit beneath an allowed read root so each explicit deny is necessary. s.home = root policy := provider.ReadPolicy{ConfigHash: "sentinel", DeniedPaths: []string{filepath.Join(root, "policy-only")}} for _, path := range denied { t.Run(filepath.Base(path), func(t *testing.T) { var out, errout bytes.Buffer code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", `cat control; cat "$1/sentinel"`, "check", path}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &errout) must(t, err) if code == 0 || !strings.Contains(out.String(), "readable") || strings.Contains(out.String(), "secret-") { t.Fatalf("sandbox failed: %d %s %s", code, &out, &errout) } }) } var out, errout bytes.Buffer _, err = s.Run(context.Background(), Command{Argv: []string{"/bin/sleep", "30"}, Dir: ".", TimeoutSeconds: 1}, work, policy, &out, &errout) if err == nil { t.Fatal("command timeout ignored") } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() _, err = s.Run(ctx, Command{Argv: []string{"/bin/sleep", "30"}, Dir: ".", TimeoutSeconds: 30}, work, policy, &out, &errout) if err == nil { t.Fatal("remaining attempt time ignored") } if _, err = s.Run(context.Background(), Command{Argv: []string{"true"}, Dir: ".", TimeoutSeconds: 1}, work, provider.ReadPolicy{}, &out, &errout); err == nil { t.Fatal("missing policy accepted") } } func TestCheckSandboxDeniedPathsGoFixture(t *testing.T) { root := t.TempDir() work := filepath.Join(root, "work") must(t, os.Mkdir(work, 0700)) put(t, work, "go.mod", "module fixture\n\ngo 1.26\n") put(t, work, "value.go", "package fixture\nfunc Value() int{return 2}\n") put(t, work, "value_test.go", bugTest) secret := filepath.Join(root, "secret") put(t, root, "secret", "secret") testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root)) must(t, err) policy := provider.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{secret}} var out, stderr bytes.Buffer code, err := s.Run(context.Background(), Command{Argv: []string{"go", "test", "-json", "-count=1", "./..."}, Dir: ".", TimeoutSeconds: 30}, work, policy, &out, &stderr) must(t, err) if code != 0 { t.Fatalf("sandbox Go fixture failed: %s %s", &out, &stderr) } results := newGoResults() _, err = results.Write(out.Bytes()) must(t, err) must(t, results.finish(code, nil)) } func TestCheckSandboxDeniedPathsTampering(t *testing.T) { testci.Quarantine(t) root := t.TempDir() work := filepath.Join(root, "work") must(t, os.Mkdir(work, 0700)) secret := filepath.Join(root, "secret") put(t, root, "secret", "hidden") put(t, work, ".codex/config.toml", "[permissions.equipo-checks.filesystem]\n\"/\"=\"read\"\n[permissions.equipo-checks.network]\nenabled=true\n") t.Setenv("EQUIPO_TEST_CREDENTIAL", "must-not-leak") testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root)) must(t, err) policy := provider.ReadPolicy{ConfigHash: "policy", DeniedPaths: []string{secret}} var out, stderr bytes.Buffer code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", `test -z "$EQUIPO_TEST_CREDENTIAL" && ! cat "$1"`, "probe", secret}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) must(t, err) if code != 0 || strings.Contains(out.String(), "hidden") { t.Fatalf("profile or environment tampering: %s %s", &out, &stderr) } ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() _, err = s.Run(ctx, Command{Argv: []string{"/bin/sh", "-c", "(sleep 0.5; echo alive > survivor) & wait"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err == nil { t.Fatal("process tree timeout missing") } time.Sleep(600 * time.Millisecond) if _, err = os.Stat(filepath.Join(work, "survivor")); !os.IsNotExist(err) { t.Fatal("child survived cancellation") } } func TestCheckSandboxDeniedPathsRequired(t *testing.T) { testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) if _, err = NewCodexSandbox(context.Background(), SandboxConfig{Binary: binary, ScratchRoot: t.TempDir()}); err == nil { t.Fatal("missing runner protected paths accepted") } } func testSandboxConfig(t *testing.T, binary, root string) SandboxConfig { t.Helper() goCommand := exec.Command("go", "env", "GOROOT") goCommand.Env = append(os.Environ(), "GOROOT=", "GOTOOLCHAIN="+GoVersion) goOutput, err := goCommand.Output() must(t, err) goRoot := strings.TrimSpace(string(goOutput)) goBinary := filepath.Join(goRoot, "bin/go") p := func(s string) string { return filepath.Join(root, s) } return SandboxConfig{Binary: binary, ScratchRoot: root, GoRoot: goRoot, GoBinary: goBinary, Protected: workspace.SecurityPaths{RunnerState: p("state"), RunnerConfig: p("config"), Journal: p("journal"), Bearer: p("bearer"), Cleanup: p("cleanup"), ForgeCredential: p("amadan"), LegacyHome: p("paseo"), SSH: p("ssh"), ProviderHomes: []string{p("codex"), p("claude"), p("alias")}}} } func TestCheckSandboxDeniedPathsCache(t *testing.T) { for _, layout := range []string{"user_cache", "fixture_present", "fixture_absent"} { t.Run(layout, func(t *testing.T) { testCheckSandboxCache(t, layout) }) } } func testCheckSandboxCache(t *testing.T, layout string) { t.Helper() root := t.TempDir() work := filepath.Join(root, "work") must(t, os.Mkdir(work, 0700)) testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) s, err := NewCodexSandbox(context.Background(), testSandboxConfig(t, binary, root)) must(t, err) if layout != "user_cache" { s.home = filepath.Join(root, "home") must(t, os.Mkdir(s.home, 0700)) if layout == "fixture_present" { must(t, os.MkdirAll(filepath.Join(s.home, ".cache/go-build"), 0700)) } } cache := filepath.Join(s.home, ".cache/go-build") if _, err := os.Stat(cache); os.IsNotExist(err) { missing := cache t.Cleanup(func() { if _, err := os.Stat(missing); !os.IsNotExist(err) { t.Fatal("probe created the missing user cache") } }) s.home = filepath.Join(root, "cache-home") cache = filepath.Join(s.home, ".cache/go-build") must(t, os.MkdirAll(cache, 0700)) } else { must(t, err) } probe, err := os.CreateTemp(cache, "equipo-cache-probe-") must(t, err) must(t, probe.Close()) defer os.Remove(probe.Name()) policy := provider.ReadPolicy{ConfigHash: "cache", DeniedPaths: []string{filepath.Join(root, "secret")}} var previous string for range 2 { var out, stderr bytes.Buffer code, err := s.Run(context.Background(), Command{Argv: []string{"/bin/sh", "-c", `printf '%s\n' "$GOCACHE"; test -n "$GOCACHE" && test -d "$GOCACHE" && touch "$GOCACHE/probe" && ! (echo poison > "$1")`, "probe", probe.Name()}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) must(t, err) if code != 0 { t.Fatalf("cache isolation failed: %d %s %s", code, &out, &stderr) } path := strings.TrimSpace(out.String()) if !within(root, path) || path == previous { t.Fatalf("cache not fresh inside scratch: %q", path) } if _, err := os.Stat(path); !os.IsNotExist(err) { t.Fatal("cache scratch retained") } previous = path } } func TestCheckSandboxToolchain(t *testing.T) { root := t.TempDir() testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) for _, kind := range []string{"missing", "relative", "nonexistent", "binary_missing", "binary_relative", "binary_nonexistent", "wrong_version"} { t.Run(kind, func(t *testing.T) { cfg := testSandboxConfig(t, binary, root) switch kind { case "missing": cfg.GoRoot = "" case "relative": cfg.GoRoot = "go" case "nonexistent": cfg.GoRoot = filepath.Join(root, "absent") case "binary_missing": cfg.GoBinary = "" case "binary_relative": cfg.GoBinary = "go" case "binary_nonexistent": cfg.GoBinary = filepath.Join(cfg.GoRoot, "bin/absent") case "wrong_version": cfg.GoRoot = filepath.Join(root, "fake-go") cfg.GoBinary = filepath.Join(cfg.GoRoot, "bin/go") put(t, cfg.GoRoot, "bin/go", "#!/bin/sh\necho 'go version go1.1 linux/amd64'\n") must(t, os.Chmod(cfg.GoBinary, 0700)) } if _, err := NewCodexSandbox(context.Background(), cfg); err == nil { t.Fatal("invalid toolchain accepted") } }) } } func TestCheckSandboxToolchainDiagnostic(t *testing.T) { root := t.TempDir() testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") must(t, err) cfg := testSandboxConfig(t, binary, root) cfg.GoRoot = filepath.Join(root, "wrong-go") cfg.GoBinary = filepath.Join(cfg.GoRoot, "bin/go") put(t, cfg.GoRoot, "bin/go", "#!/bin/sh\necho 'go version go1.1 linux/amd64'\n") must(t, os.Chmod(cfg.GoBinary, 0700)) _, err = NewCodexSandbox(context.Background(), cfg) if !errors.Is(err, provider.ErrContract) || !strings.Contains(err.Error(), cfg.GoBinary) || !strings.Contains(err.Error(), "go1.1") || !strings.Contains(err.Error(), GoVersion) { t.Fatalf("toolchain rejection lacks path, observed version or required version: %v", err) } }