package checks import ( "context" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" "sort" "strings" "sync" "syscall" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/workspace" ) const CodexVersion = "codex-cli 0.165.0" const GoVersion = "go1.26.11" type SandboxConfig struct { Host provider.ProcessHost RunnerBinary, Bwrap, ModuleCache string Binary, ScratchRoot string GoRoot, GoBinary string Protected workspace.SecurityPaths } type CodexSandbox struct { containMu sync.Mutex uncontained map[string]bool direct SandboxConfig binary, version, scratch, home string protected []string goRoot, goBinary, goVersion string } func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, error) { paths := append(cfg.Protected.Credentials(), cfg.Protected.ProviderHomes...) if len(cfg.Protected.ProviderHomes) == 0 { return nil, provider.ErrPolicy } for _, p := range paths { if _, err := canonicalPath(p); err != nil { return nil, err } } if !filepath.IsAbs(cfg.Binary) || !filepath.IsAbs(cfg.ScratchRoot) { return nil, provider.ErrContract } binary, err := filepath.EvalSymlinks(cfg.Binary) if err != nil { return nil, err } home, err := os.UserHomeDir() if err != nil { return nil, err } cmd := exec.CommandContext(ctx, binary, "--version") cmd.Env = []string{"PATH=/usr/bin:/bin"} b, err := cmd.Output() if err != nil || strings.TrimSpace(string(b)) != CodexVersion { return nil, fmt.Errorf("%w: Codex binary %q returned %q, want %q (probe: %v)", provider.ErrContract, binary, strings.TrimSpace(string(b)), CodexVersion, err) } if !filepath.IsAbs(cfg.GoRoot) || !filepath.IsAbs(cfg.GoBinary) { return nil, fmt.Errorf("%w: Go root %q and binary %q must be absolute", provider.ErrContract, cfg.GoRoot, cfg.GoBinary) } goRoot, err := filepath.EvalSymlinks(cfg.GoRoot) if err != nil { return nil, err } info, err := os.Stat(goRoot) if err != nil || !info.IsDir() { return nil, fmt.Errorf("%w: Go root %q is not a directory (stat: %v)", provider.ErrContract, goRoot, err) } goBinary, err := filepath.EvalSymlinks(cfg.GoBinary) if err != nil || goBinary != filepath.Join(goRoot, "bin/go") { return nil, fmt.Errorf("%w: Go binary %q resolves to %q, want %q (resolve: %v)", provider.ErrContract, cfg.GoBinary, goBinary, filepath.Join(goRoot, "bin/go"), err) } probe, err := os.MkdirTemp(cfg.ScratchRoot, "go-probe-") if err != nil { return nil, err } defer os.RemoveAll(probe) xdg, err := telemetryOffConfig(probe) if err != nil { return nil, err } cmd = exec.CommandContext(ctx, goBinary, "version") cmd.Env = []string{"PATH=/usr/bin:/bin", "GOROOT=" + goRoot, "GOTOOLCHAIN=local", "GOENV=off", "GOTELEMETRY=off", "XDG_CONFIG_HOME=" + xdg} b, err = cmd.Output() if err != nil || strings.TrimSpace(string(b)) != "go version "+GoVersion+" "+runtime.GOOS+"/"+runtime.GOARCH { return nil, fmt.Errorf("%w: Go binary %q with GOROOT %q returned %q, want %q (probe: %v)", provider.ErrContract, goBinary, goRoot, strings.TrimSpace(string(b)), "go version "+GoVersion+" "+runtime.GOOS+"/"+runtime.GOARCH, err) } return &CodexSandbox{direct: cfg, binary: binary, version: CodexVersion, scratch: cfg.ScratchRoot, home: home, protected: paths, goRoot: goRoot, goBinary: goBinary, goVersion: GoVersion}, nil } func canonicalPath(path string) (string, error) { if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[\x00") { return "", provider.ErrPolicy } p, err := filepath.EvalSymlinks(path) if err == nil { return p, nil } if !os.IsNotExist(err) { return "", err } parent := filepath.Dir(path) if parent == path { return "", err } p, err = canonicalPath(parent) if err != nil { return "", err } return filepath.Join(p, filepath.Base(path)), nil } func within(root, path string) bool { return root == path || strings.HasPrefix(path, root+string(filepath.Separator)) } func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy provider.ReadPolicy, stdout, stderr io.Writer) (code int, resultErr error) { if policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 || len(c.Argv) == 0 || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 1200 { return -1, provider.ErrPolicy } resolved, err := canonicalPath(work) if err != nil || resolved != work { return -1, provider.ErrPolicy } if err = safeDir(work, c.Dir); err != nil { return -1, err } denies := map[string]bool{} for _, p := range append(append([]string(nil), s.protected...), policy.DeniedPaths...) { r, err := canonicalPath(p) if err != nil || within(p, work) || within(r, work) { return -1, provider.ErrPolicy } denies[p] = true denies[r] = true } if s.direct.Host != nil { return s.runNamespace(ctx, c, work, policy, stdout, stderr) } control, err := os.MkdirTemp(s.scratch, "sandbox-") if err != nil { return -1, err } defer os.RemoveAll(control) // A fresh config home prevents user/project profiles and login state entering the command. cfgHome := filepath.Join(control, "codex") xdg, err := telemetryOffConfig(control) if err != nil { return -1, err } temp, err := os.MkdirTemp(work, ".equipo-check-") if err != nil { return -1, err } defer os.RemoveAll(temp) cache := filepath.Join(temp, "go-build") goTemp := filepath.Join(temp, "go-tmp") for _, path := range []string{cache, goTemp} { if err := os.Mkdir(path, 0700); err != nil { return -1, err } } if err = os.Mkdir(cfgHome, 0700); err != nil { return -1, err } roots := map[string]string{xdg: "read", ":minimal": "read", s.binary: "read", s.goRoot: "read", work: "write", filepath.Join(s.home, ".cache/go-build"): "deny", filepath.Join(s.home, "go/pkg/mod"): "read"} for _, p := range []string{s.goRoot, filepath.Join(s.home, "go/pkg/mod"), filepath.Join(s.home, ".cache/go-build")} { r, err := canonicalPath(p) if err != nil { return -1, err } roots[r] = roots[p] } denies[cfgHome] = true for p := range denies { covered := false for parent := range denies { if parent != p && within(parent, p) { covered = true break } } if !covered { roots[p] = "deny" } } keys := make([]string, 0, len(roots)) for k := range roots { keys = append(keys, k) } sort.Strings(keys) var entries []string for _, k := range keys { key, _ := json.Marshal(k) v, _ := json.Marshal(roots[k]) entries = append(entries, string(key)+"="+string(v)) } args := []string{"sandbox", "-P", "equipo-checks", "-C", filepath.Join(work, c.Dir), "-c", "permissions.equipo-checks.filesystem={" + strings.Join(entries, ",") + "}", "-c", "permissions.equipo-checks.network.enabled=false", "--"} argv := append([]string(nil), c.Argv...) if argv[0] == "go" { argv[0] = s.goBinary } args = append(args, argv...) ctx, cancel := context.WithTimeout(ctx, time.Duration(c.TimeoutSeconds)*time.Second) defer cancel() cmd := exec.CommandContext(ctx, s.binary, args...) cmd.Dir = control cmd.Env = []string{"PATH=" + filepath.Join(s.goRoot, "bin") + ":/usr/bin:/bin", "HOME=" + s.home, "CODEX_HOME=" + cfgHome, "TMPDIR=" + temp, "GOCACHE=" + cache, "GOTMPDIR=" + goTemp, "GOROOT=" + s.goRoot, "CGO_ENABLED=0", "GOTOOLCHAIN=local", "MAKEFLAGS=GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=", "GOTELEMETRY=off", "XDG_CONFIG_HOME=" + xdg, "GOPROXY=off", "GOSUMDB=off", "LANG=C", "LC_ALL=C"} for key, value := range workspace.GitEnvironment() { if strings.HasPrefix(key, "GIT_") { cmd.Env = append(cmd.Env, key+"="+value) } } cmd.Stdout = stdout cmd.Stderr = stderr cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} cmd.WaitDelay = time.Second cmd.Cancel = func() error { if cmd.Process == nil { return nil } return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } if err = cmd.Start(); err != nil { return -1, provider.ErrContract } defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) err = cmd.Wait() if ctx.Err() != nil { return -1, ctx.Err() } if err == nil { return 0, nil } var exit *exec.ExitError if errors.As(err, &exit) { return exit.ExitCode(), nil } return -1, provider.ErrContract } func telemetryOffConfig(root string) (string, error) { xdg := filepath.Join(root, "xdg") dir := filepath.Join(xdg, "go", "telemetry") if err := os.MkdirAll(dir, 0700); err != nil { return "", err } if err := os.WriteFile(filepath.Join(dir, "mode"), []byte("off\n"), 0600); err != nil { return "", err } return xdg, nil }