package checks_test import ( "bytes" "context" "errors" "os" "os/exec" "path/filepath" "runtime" "strconv" "strings" "testing" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/checks" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" ) type checkHost struct { provider.ProcessHost launches []provider.Launch args [][]string } func (h *checkHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { h.launches = append(h.launches, l) h.args = append(h.args, argv) return h.ProcessHost.Start(ctx, l, argv) } func namespaceCheck(t *testing.T, configure ...func(*checks.SandboxConfig)) (*checks.CodexSandbox, string, string, provider.ReadPolicy, *checkHost) { t.Helper() root := t.TempDir() if err := os.Chmod(root, 0700); err != nil { t.Fatal(err) } scratch, work, mods := filepath.Join(root, "ns"), filepath.Join(root, "work"), filepath.Join(root, "modules") for _, p := range []string{scratch, work, mods} { if err := os.Mkdir(p, 0700); err != nil { t.Fatal(err) } } testci.Tools(t, "codex", "bwrap", "python3", "sh") binary, err := exec.LookPath("codex") if err != nil { t.Fatal(err) } goCommand := exec.Command("go", "env", "GOROOT") goCommand.Env = append(os.Environ(), "GOROOT=", "GOTOOLCHAIN="+checks.GoVersion) goOutput, err := goCommand.Output() if err != nil { t.Fatalf("resolve check toolchain: %v", err) } goRoot := strings.TrimSpace(string(goOutput)) helper, err := os.Executable() if err != nil { t.Fatal(err) } m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: helper, ScratchRoot: scratch}) if err != nil { t.Fatal(err) } j, err := runner.OpenJournal(context.Background(), filepath.Join(root, "journal.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { j.Close() }) if _, err = j.ReconcileDirect(context.Background(), m); err != nil { t.Fatal(err) } p := filepath.Join(root, "private") protected := workspace.SecurityPaths{RunnerState: p, RunnerConfig: p, Journal: p, Bearer: p, Cleanup: p, ForgeCredential: p, LegacyHome: p, SSH: p, ProviderHomes: []string{p}} host := &checkHost{ProcessHost: runner.NewDirectHost(j, m)} cfg := checks.SandboxConfig{Binary: binary, ScratchRoot: scratch, GoBinary: filepath.Join(goRoot, "bin/go"), GoRoot: goRoot, Protected: protected, Host: host, RunnerBinary: helper, Bwrap: "/usr/bin/bwrap", ModuleCache: mods} for _, apply := range configure { apply(&cfg) } s, err := checks.NewCodexSandbox(context.Background(), cfg) if err != nil { t.Fatal(err) } return s, work, scratch, provider.ReadPolicy{ConfigHash: "checks", DeniedPaths: []string{p}}, host } func TestCheckNamespaceContainment(t *testing.T) { s, work, scratch, policy, _ := namespaceCheck(t) var out, stderr bytes.Buffer code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", `import os,time if os.fork()==0: os.setsid() time.sleep(1) open('/workspace/escaped','w').write('bad') os._exit(0) print('parent done',flush=True)`}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err != nil || code != 0 { t.Fatalf("check: %d %v %s", code, err, &stderr) } if !strings.Contains(out.String(), "parent done") { t.Fatal("command did not run") } if _, err := os.Stat(filepath.Join(work, "escaped")); !os.IsNotExist(err) { t.Fatal("detached child escaped") } files, err := os.ReadDir(scratch) if err != nil { t.Fatal(err) } for _, f := range files { if f.IsDir() && strings.HasPrefix(f.Name(), "attempt-") { t.Fatal("attempt scratch survived containment") } } } func TestCheckCacheIsolation(t *testing.T) { s, work, scratch, policy, tracker := namespaceCheck(t) home, err := os.UserHomeDir() if err != nil { t.Fatal(err) } for i := 0; i < 2; i++ { var out, stderr bytes.Buffer code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", `import os assert not os.path.exists(os.environ['GOCACHE']+'/prior') open(os.environ['GOCACHE']+'/prior','w').write('owned') try: open(os.environ['GOMODCACHE']+'/poison','w').write('bad') except OSError: pass else: raise Exception('module cache writable') assert not os.path.exists('` + filepath.Join(home, ".cache/go-build") + `') assert os.environ['GOCACHE'].startswith('/tmp/') assert os.environ['GOTMPDIR'].startswith('/tmp/') print('isolated')`}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err != nil || code != 0 || !strings.Contains(out.String(), "isolated") { t.Fatalf("cache check %d: %d %v %s %s", i, code, err, &out, &stderr) } } if len(tracker.launches) != 2 || tracker.launches[0].AttemptKey == tracker.launches[1].AttemptKey { t.Fatal("checks shared a namespace identity") } for i, launch := range tracker.launches { args := strings.Join(tracker.args[i], " ") if !strings.Contains(args, `"/opt/go-mod"="read"`) { t.Fatal("module-cache inner write protection missing") } if !strings.Contains(args, `"`+filepath.Join(home, ".cache/go-build")+`"="deny"`) { t.Fatal("host build cache exclusion missing") } for _, mount := range launch.Policy.Mounts { if mount.Source == filepath.Join(home, ".cache/go-build") { t.Fatal("host build cache mounted") } if mount.Target == "/opt/go-mod" && (!mount.ReadOnly || mount.Source != filepath.Join(filepath.Dir(work), "modules")) { t.Fatal("module cache mount changed") } } } files, err := os.ReadDir(scratch) if err != nil { t.Fatal(err) } for _, f := range files { if f.IsDir() && strings.HasPrefix(f.Name(), "attempt-") { t.Fatal("check cache left behind") } } } func TestCheckNamespaceDeniedMountAliases(t *testing.T) { s, work, _, policy, _ := namespaceCheck(t) secret := filepath.Join(filepath.Dir(work), "modules", "private") if err := os.WriteFile(secret, []byte("denied-sentinel"), 0600); err != nil { t.Fatal(err) } policy.DeniedPaths = append(policy.DeniedPaths, secret) var out, stderr bytes.Buffer code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", "/opt/go-mod/private"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err != nil { t.Fatal(err) } if code == 0 || strings.Contains(out.String(), "denied-sentinel") { t.Fatal("module mount alias bypassed denied path") } } func TestCheckCacheRejectsBroadHome(t *testing.T) { home, err := os.UserHomeDir() if err != nil { t.Fatal(err) } for _, root := range []string{home, "/home", "/", "/tmp"} { _, err = provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: t.TempDir(), Binary: "/usr/bin/true", RunnerBinary: "/usr/bin/true", Bwrap: "/usr/bin/bwrap", GoRoot: t.TempDir(), ModuleCache: root, Argv: []string{"/opt/codex"}}) if err == nil { t.Fatalf("broad home accepted as module cache: %s", root) } } } func TestCheckCacheRejectsNamespaceScratch(t *testing.T) { s, work, _, policy, _ := namespaceCheck(t, func(cfg *checks.SandboxConfig) { cfg.ModuleCache = cfg.ScratchRoot }) var out, stderr bytes.Buffer if _, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/true"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr); err == nil { t.Fatal("namespace scratch accepted as module cache") } } func TestCheckNamespaceGoRootInsideModuleCache(t *testing.T) { var goRoot string s, work, _, policy, tracker := namespaceCheck(t, func(cfg *checks.SandboxConfig) { goRoot = filepath.Join(cfg.ModuleCache, "golang.org/toolchain@v0.0.1-"+checks.GoVersion+"."+runtime.GOOS+"-"+runtime.GOARCH) if err := os.CopyFS(goRoot, os.DirFS(cfg.GoRoot)); err != nil { t.Fatal(err) } cfg.GoRoot, cfg.GoBinary = goRoot, filepath.Join(goRoot, "bin/go") }) home, err := os.UserHomeDir() if err != nil { t.Fatal(err) } script := `import os,subprocess assert not os.path.exists(` + strconv.Quote(filepath.Join(home, ".cache/go-build")) + `) assert os.environ['GOTOOLCHAIN']=='local' assert os.environ['MAKEFLAGS']=='GOTOOLCHAIN=local' for path in ['/opt/go/VERSION', '/opt/go-mod/` + filepath.ToSlash(filepath.Join("golang.org", filepath.Base(goRoot))) + `/VERSION']: assert os.path.isfile(path), path try: fd=os.open(path,os.O_WRONLY) except OSError: pass else: os.close(fd) raise Exception('runtime alias writable: '+path) assert os.statvfs('/opt/go-mod').f_flag & os.ST_RDONLY subprocess.run(['/opt/go/bin/go','test','./...'],check=True) print('nested runtime isolated')` for name, data := range map[string]string{"go.mod": "module nestedfixture\n\ngo 1.26.0\n", "nested_test.go": "package nestedfixture\nimport \"testing\"\nfunc TestNested(t *testing.T) {}\n"} { if err := os.WriteFile(filepath.Join(work, name), []byte(data), 0600); err != nil { t.Fatal(err) } } var out, stderr bytes.Buffer code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", script}, Dir: ".", TimeoutSeconds: 120}, work, policy, &out, &stderr) if err != nil || code != 0 || !strings.Contains(out.String(), "nested runtime isolated") { t.Fatalf("nested runtime: code=%d error=%v stdout=%s stderr=%s", code, err, &out, &stderr) } for _, mount := range tracker.launches[0].Policy.Mounts { if !mount.ReadOnly || mount.Source == filepath.Join(home, ".cache/go-build") { t.Fatalf("unsafe mount: %+v", mount) } } policy.DeniedPaths = append(policy.DeniedPaths, filepath.Join(goRoot, "VERSION")) for _, alias := range []string{"/opt/go/VERSION", "/opt/go-mod/" + filepath.ToSlash(filepath.Join("golang.org", filepath.Base(goRoot))) + "/VERSION"} { out.Reset() stderr.Reset() code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", alias}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err != nil || code == 0 || out.Len() != 0 { t.Fatalf("denied runtime alias %q: code=%d error=%v stdout=%s stderr=%s", alias, code, err, &out, &stderr) } } } func TestCheckCacheRejectsSymlinkPathDiagnostic(t *testing.T) { root := t.TempDir() real := filepath.Join(root, "real") alias := filepath.Join(root, "alias") if err := os.Mkdir(real, 0700); err != nil { t.Fatal(err) } if err := os.Symlink(real, alias); err != nil { t.Fatal(err) } _, err := provider.BuildCheckPolicy(provider.CheckPolicyInputs{Workspace: root, GoRoot: real, ModuleCache: alias, Binary: "/usr/bin/true", RunnerBinary: "/usr/bin/true", Bwrap: "/usr/bin/bwrap"}) if !errors.Is(err, provider.ErrPolicy) || !strings.Contains(err.Error(), alias) { t.Fatalf("refused module cache must retain policy class and identify path %q: %v", alias, err) } } func TestCheckNamespaceHostTmp(t *testing.T) { root, err := os.MkdirTemp("/tmp", "equipo-check-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(root) }) t.Setenv("TMPDIR", root) s, work, _, policy, _ := namespaceCheck(t) policy.DeniedPaths = append(policy.DeniedPaths, filepath.Join(policy.DeniedPaths[0], "config")) var out, stderr bytes.Buffer code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/python3", "-c", "import os; assert not os.path.exists(" + strconv.Quote(root) + "); print('check ran')"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err != nil || code != 0 || !strings.Contains(out.String(), "check ran") { t.Fatalf("host /tmp check: code=%d err=%v stdout=%s stderr=%s", code, err, &out, &stderr) } } func TestCheckNamespaceDeniedHostAliases(t *testing.T) { for _, kind := range []string{"ancestor", "symlink"} { t.Run(kind, func(t *testing.T) { var mods string s, work, _, policy, _ := namespaceCheck(t, func(cfg *checks.SandboxConfig) { cfg.ModuleCache = filepath.Join(cfg.ModuleCache, "nested") if err := os.Mkdir(cfg.ModuleCache, 0700); err != nil { t.Fatal(err) } mods = cfg.ModuleCache }) if err := os.WriteFile(filepath.Join(mods, "secret"), []byte("denied-sentinel"), 0600); err != nil { t.Fatal(err) } denied := filepath.Dir(mods) if kind == "symlink" { denied = filepath.Join(filepath.Dir(work), "alias") if err := os.Symlink(filepath.Join(mods, "secret"), denied); err != nil { t.Fatal(err) } } policy.DeniedPaths = append(policy.DeniedPaths, denied) var out, stderr bytes.Buffer code, err := s.Run(context.Background(), checks.Command{Argv: []string{"/usr/bin/cat", "/opt/go-mod/secret"}, Dir: ".", TimeoutSeconds: 10}, work, policy, &out, &stderr) if err != nil { t.Fatal(err) } if code == 0 || strings.Contains(out.String(), "denied-sentinel") { t.Fatalf("%s deny bypassed: %s", kind, &out) } }) } }