| 1 | package checks |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "runtime" |
| 13 | "sort" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "syscall" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 20 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 21 | ) |
| 22 | |
| 23 | const CodexVersion = "codex-cli 0.165.0" |
| 24 | const GoVersion = "go1.26.11" |
| 25 | |
| 26 | type SandboxConfig struct { |
| 27 | Host provider.ProcessHost |
| 28 | RunnerBinary, Bwrap, ModuleCache string |
| 29 | Binary, ScratchRoot string |
| 30 | GoRoot, GoBinary string |
| 31 | Protected workspace.SecurityPaths |
| 32 | } |
| 33 | type CodexSandbox struct { |
| 34 | containMu sync.Mutex |
| 35 | uncontained map[string]bool |
| 36 | direct SandboxConfig |
| 37 | binary, version, scratch, home string |
| 38 | protected []string |
| 39 | goRoot, goBinary, goVersion string |
| 40 | } |
| 41 | |
| 42 | func NewCodexSandbox(ctx context.Context, cfg SandboxConfig) (*CodexSandbox, error) { |
| 43 | paths := append(cfg.Protected.Credentials(), cfg.Protected.ProviderHomes...) |
| 44 | if len(cfg.Protected.ProviderHomes) == 0 { |
| 45 | return nil, provider.ErrPolicy |
| 46 | } |
| 47 | for _, p := range paths { |
| 48 | if _, err := canonicalPath(p); err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | } |
| 52 | if !filepath.IsAbs(cfg.Binary) || !filepath.IsAbs(cfg.ScratchRoot) { |
| 53 | return nil, provider.ErrContract |
| 54 | } |
| 55 | binary, err := filepath.EvalSymlinks(cfg.Binary) |
| 56 | if err != nil { |
| 57 | return nil, err |
| 58 | } |
| 59 | home, err := os.UserHomeDir() |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | cmd := exec.CommandContext(ctx, binary, "--version") |
| 64 | cmd.Env = []string{"PATH=/usr/bin:/bin"} |
| 65 | b, err := cmd.Output() |
| 66 | if err != nil || strings.TrimSpace(string(b)) != CodexVersion { |
| 67 | return nil, fmt.Errorf("%w: Codex binary %q returned %q, want %q (probe: %v)", provider.ErrContract, binary, strings.TrimSpace(string(b)), CodexVersion, err) |
| 68 | } |
| 69 | if !filepath.IsAbs(cfg.GoRoot) || !filepath.IsAbs(cfg.GoBinary) { |
| 70 | return nil, fmt.Errorf("%w: Go root %q and binary %q must be absolute", provider.ErrContract, cfg.GoRoot, cfg.GoBinary) |
| 71 | } |
| 72 | goRoot, err := filepath.EvalSymlinks(cfg.GoRoot) |
| 73 | if err != nil { |
| 74 | return nil, err |
| 75 | } |
| 76 | info, err := os.Stat(goRoot) |
| 77 | if err != nil || !info.IsDir() { |
| 78 | return nil, fmt.Errorf("%w: Go root %q is not a directory (stat: %v)", provider.ErrContract, goRoot, err) |
| 79 | } |
| 80 | goBinary, err := filepath.EvalSymlinks(cfg.GoBinary) |
| 81 | if err != nil || goBinary != filepath.Join(goRoot, "bin/go") { |
| 82 | 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) |
| 83 | } |
| 84 | probe, err := os.MkdirTemp(cfg.ScratchRoot, "go-probe-") |
| 85 | if err != nil { |
| 86 | return nil, err |
| 87 | } |
| 88 | defer os.RemoveAll(probe) |
| 89 | xdg, err := telemetryOffConfig(probe) |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | cmd = exec.CommandContext(ctx, goBinary, "version") |
| 94 | cmd.Env = []string{"PATH=/usr/bin:/bin", "GOROOT=" + goRoot, "GOTOOLCHAIN=local", "GOENV=off", "GOTELEMETRY=off", "XDG_CONFIG_HOME=" + xdg} |
| 95 | b, err = cmd.Output() |
| 96 | if err != nil || strings.TrimSpace(string(b)) != "go version "+GoVersion+" "+runtime.GOOS+"/"+runtime.GOARCH { |
| 97 | 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) |
| 98 | } |
| 99 | return &CodexSandbox{direct: cfg, binary: binary, version: CodexVersion, scratch: cfg.ScratchRoot, home: home, protected: paths, goRoot: goRoot, goBinary: goBinary, goVersion: GoVersion}, nil |
| 100 | } |
| 101 | func canonicalPath(path string) (string, error) { |
| 102 | if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[\x00") { |
| 103 | return "", provider.ErrPolicy |
| 104 | } |
| 105 | p, err := filepath.EvalSymlinks(path) |
| 106 | if err == nil { |
| 107 | return p, nil |
| 108 | } |
| 109 | if !os.IsNotExist(err) { |
| 110 | return "", err |
| 111 | } |
| 112 | parent := filepath.Dir(path) |
| 113 | if parent == path { |
| 114 | return "", err |
| 115 | } |
| 116 | p, err = canonicalPath(parent) |
| 117 | if err != nil { |
| 118 | return "", err |
| 119 | } |
| 120 | return filepath.Join(p, filepath.Base(path)), nil |
| 121 | } |
| 122 | func within(root, path string) bool { |
| 123 | return root == path || strings.HasPrefix(path, root+string(filepath.Separator)) |
| 124 | } |
| 125 | func (s *CodexSandbox) Run(ctx context.Context, c Command, work string, policy provider.ReadPolicy, stdout, stderr io.Writer) (code int, resultErr error) { |
| 126 | if policy.ConfigHash == "" || len(policy.DeniedPaths) == 0 || len(c.Argv) == 0 || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 1200 { |
| 127 | return -1, provider.ErrPolicy |
| 128 | } |
| 129 | resolved, err := canonicalPath(work) |
| 130 | if err != nil || resolved != work { |
| 131 | return -1, provider.ErrPolicy |
| 132 | } |
| 133 | if err = safeDir(work, c.Dir); err != nil { |
| 134 | return -1, err |
| 135 | } |
| 136 | denies := map[string]bool{} |
| 137 | for _, p := range append(append([]string(nil), s.protected...), policy.DeniedPaths...) { |
| 138 | r, err := canonicalPath(p) |
| 139 | if err != nil || within(p, work) || within(r, work) { |
| 140 | return -1, provider.ErrPolicy |
| 141 | } |
| 142 | denies[p] = true |
| 143 | denies[r] = true |
| 144 | } |
| 145 | if s.direct.Host != nil { |
| 146 | return s.runNamespace(ctx, c, work, policy, stdout, stderr) |
| 147 | } |
| 148 | control, err := os.MkdirTemp(s.scratch, "sandbox-") |
| 149 | if err != nil { |
| 150 | return -1, err |
| 151 | } |
| 152 | defer os.RemoveAll(control) |
| 153 | // A fresh config home prevents user/project profiles and login state entering the command. |
| 154 | cfgHome := filepath.Join(control, "codex") |
| 155 | xdg, err := telemetryOffConfig(control) |
| 156 | if err != nil { |
| 157 | return -1, err |
| 158 | } |
| 159 | temp, err := os.MkdirTemp(work, ".equipo-check-") |
| 160 | if err != nil { |
| 161 | return -1, err |
| 162 | } |
| 163 | defer os.RemoveAll(temp) |
| 164 | cache := filepath.Join(temp, "go-build") |
| 165 | goTemp := filepath.Join(temp, "go-tmp") |
| 166 | for _, path := range []string{cache, goTemp} { |
| 167 | if err := os.Mkdir(path, 0700); err != nil { |
| 168 | return -1, err |
| 169 | } |
| 170 | } |
| 171 | if err = os.Mkdir(cfgHome, 0700); err != nil { |
| 172 | return -1, err |
| 173 | } |
| 174 | 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"} |
| 175 | for _, p := range []string{s.goRoot, filepath.Join(s.home, "go/pkg/mod"), filepath.Join(s.home, ".cache/go-build")} { |
| 176 | r, err := canonicalPath(p) |
| 177 | if err != nil { |
| 178 | return -1, err |
| 179 | } |
| 180 | roots[r] = roots[p] |
| 181 | } |
| 182 | denies[cfgHome] = true |
| 183 | for p := range denies { |
| 184 | covered := false |
| 185 | for parent := range denies { |
| 186 | if parent != p && within(parent, p) { |
| 187 | covered = true |
| 188 | break |
| 189 | } |
| 190 | } |
| 191 | if !covered { |
| 192 | roots[p] = "deny" |
| 193 | } |
| 194 | } |
| 195 | keys := make([]string, 0, len(roots)) |
| 196 | for k := range roots { |
| 197 | keys = append(keys, k) |
| 198 | } |
| 199 | sort.Strings(keys) |
| 200 | var entries []string |
| 201 | for _, k := range keys { |
| 202 | key, _ := json.Marshal(k) |
| 203 | v, _ := json.Marshal(roots[k]) |
| 204 | entries = append(entries, string(key)+"="+string(v)) |
| 205 | } |
| 206 | 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", "--"} |
| 207 | argv := append([]string(nil), c.Argv...) |
| 208 | if argv[0] == "go" { |
| 209 | argv[0] = s.goBinary |
| 210 | } |
| 211 | args = append(args, argv...) |
| 212 | ctx, cancel := context.WithTimeout(ctx, time.Duration(c.TimeoutSeconds)*time.Second) |
| 213 | defer cancel() |
| 214 | cmd := exec.CommandContext(ctx, s.binary, args...) |
| 215 | cmd.Dir = control |
| 216 | 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"} |
| 217 | for key, value := range workspace.GitEnvironment() { |
| 218 | if strings.HasPrefix(key, "GIT_") { |
| 219 | cmd.Env = append(cmd.Env, key+"="+value) |
| 220 | } |
| 221 | } |
| 222 | cmd.Stdout = stdout |
| 223 | cmd.Stderr = stderr |
| 224 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| 225 | cmd.WaitDelay = time.Second |
| 226 | cmd.Cancel = func() error { |
| 227 | if cmd.Process == nil { |
| 228 | return nil |
| 229 | } |
| 230 | return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) |
| 231 | } |
| 232 | if err = cmd.Start(); err != nil { |
| 233 | return -1, provider.ErrContract |
| 234 | } |
| 235 | defer syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) |
| 236 | err = cmd.Wait() |
| 237 | if ctx.Err() != nil { |
| 238 | return -1, ctx.Err() |
| 239 | } |
| 240 | if err == nil { |
| 241 | return 0, nil |
| 242 | } |
| 243 | var exit *exec.ExitError |
| 244 | if errors.As(err, &exit) { |
| 245 | return exit.ExitCode(), nil |
| 246 | } |
| 247 | return -1, provider.ErrContract |
| 248 | } |
| 249 | |
| 250 | func telemetryOffConfig(root string) (string, error) { |
| 251 | xdg := filepath.Join(root, "xdg") |
| 252 | dir := filepath.Join(xdg, "go", "telemetry") |
| 253 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 254 | return "", err |
| 255 | } |
| 256 | if err := os.WriteFile(filepath.Join(dir, "mode"), []byte("off\n"), 0600); err != nil { |
| 257 | return "", err |
| 258 | } |
| 259 | return xdg, nil |
| 260 | } |
| 261 | |