package codex import ( "context" "crypto/sha256" "encoding/hex" "errors" "io" "io/fs" "os" "os/exec" "path/filepath" "runtime" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/testci" ) // The transport runs the real CLI without an egress relay. Open, policy // attestation, account staging and RPC handling are the production code. type offlineCodexHost struct{ t *testing.T } type offlineCodexProcess struct { in io.WriteCloser out io.ReadCloser done chan struct{} exit provider.Exit } func (p *offlineCodexProcess) ID() string { return "offline-replay" } func (p *offlineCodexProcess) Stdin() io.WriteCloser { return p.in } func (p *offlineCodexProcess) Stdout() io.ReadCloser { return p.out } func (p *offlineCodexProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("")) } func (p *offlineCodexProcess) Wait(ctx context.Context) (provider.Exit, error) { select { case <-p.done: return p.exit, nil case <-ctx.Done(): return provider.Exit{}, ctx.Err() } } func (h offlineCodexHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { if _, err := provider.AttestLaunch(l, argv); err != nil { return nil, err } args := []string{"--unshare-all", "--die-with-parent", "--new-session", "--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin", "--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--bind", l.Binding.Home, "/home/runner", "--bind", l.Workspace, "/workspace"} for _, m := range l.Policy.Mounts { args = append(args, "--ro-bind", m.Source, m.Target) } args = append(args, "--chdir", "/workspace", "--clearenv", "--setenv", "PATH", "/usr/bin:/bin:/opt", "--setenv", "HOME", "/home/runner", "--setenv", "CODEX_HOME", "/home/runner", "--setenv", "TMPDIR", "/tmp", "--setenv", "LANG", "C.UTF-8") args = append(args, argv...) cmd := exec.CommandContext(ctx, "bwrap", args...) p := &offlineCodexProcess{done: make(chan struct{})} var err error if p.in, err = cmd.StdinPipe(); err != nil { return nil, err } if p.out, err = cmd.StdoutPipe(); err != nil { p.in.Close() return nil, err } if err = cmd.Start(); err != nil { p.in.Close() p.out.Close() return nil, err } go func() { _ = cmd.Wait(); p.exit.Code = cmd.ProcessState.ExitCode(); close(p.done) }() h.t.Cleanup(func() { _ = cmd.Process.Kill(); <-p.done; p.in.Close(); p.out.Close() }) return p, nil } func TestCodexEmptyHomeReplay(t *testing.T) { testci.Tools(t, "try-bin", "bwrap", "python3") home, err := os.UserHomeDir() if err != nil { t.Fatal(err) } bin := filepath.Join(home, ".local/share/equipo/try/bin") // The official build for this machine: the certified pins on amd64. executable, codeModeHost, ok := ReleasePins(runtime.GOARCH) if !ok { t.Fatalf("no pinned Codex 0.165.0 build for %s", runtime.GOARCH) } for name, want := range map[string]string{"codex": executable, "codex-code-mode-host": codeModeHost} { f, err := os.Open(filepath.Join(bin, name)) if os.IsNotExist(err) { testci.Absent(t, "pinned Codex 0.165.0 binaries absent; empty-home replay requires the local pinned installation") } if err != nil { t.Fatal(err) } sum := sha256.New() _, err = io.Copy(sum, f) f.Close() if err != nil { t.Fatal(err) } if hex.EncodeToString(sum.Sum(nil)) != want { t.Fatalf("pinned %s digest differs", name) } } for _, action := range []string{"implement", "coordinate"} { t.Run(action, func(t *testing.T) { f := fixtureFor(t) // This source is a newly-created test fixture, containing no login. source := filepath.Join(filepath.Dir(f.interactive), "dedicated", "auth.json") if err := os.WriteFile(source, []byte(`{"auth_mode":"apikey"}`), 0600); err != nil { t.Fatal(err) } in := f.inputs in.Action = action profile, _ := provider.Profile(action) in.Tools = profile.MCPTools() for i := range in.RuntimeFiles { if in.RuntimeFiles[i].Target != "/opt/equipo-tool-proxy" { in.RuntimeFiles[i].Source = filepath.Join(bin, filepath.Base(in.RuntimeFiles[i].Target)) } } // No thread starts, so the tool proxy is never invoked. in, err = PolicyInputs(f.lease.Binding(), in, f.launch.Selection.Model) if err != nil { t.Fatal(err) } f.launch.Policy, err = provider.BuildPolicy(f.lease.Binding(), in) if err != nil { t.Fatal(err) } f.l, err = New(offlineCodexHost{t}, fakeCapture{}) if err != nil { t.Fatal(err) } f.l.digest, f.l.hostDigest = executable, codeModeHost ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = f.l.Open(ctx, f.launch) if !errors.Is(err, provider.ErrIdentity) || errors.Is(err, provider.ErrContainment) { t.Fatalf("expected missing account from real Open, got %v", err) } t.Logf("real %s Open: %v", action, err) // Missing account returns before config/read in Open. Check the same // production policy on a second unauthenticated process, without a turn. err = f.lease.Preflight(ctx, func(ctx context.Context, b provider.Binding) (provider.Identity, error) { probeCtx, stop := context.WithCancel(ctx) defer stop() launch := f.launch launch.Binding = b proc, _, rpc, e := f.l.start(probeCtx, launch, func(provider.Frame) error { return nil }) defer func() { if rpc != nil { rpc.close() } stop() waitProcess(proc) if rpc != nil { <-rpc.done } }() if e != nil { return provider.Identity{}, e } if e = initialize(probeCtx, rpc); e != nil { return provider.Identity{}, e } if e = readConfig(probeCtx, rpc, launch.Policy); e != nil { return provider.Identity{}, e } return readIdentity(probeCtx, rpc) }) if !errors.Is(err, provider.ErrIdentity) { t.Fatalf("readback probe: %v", err) } for _, name := range []string{"skills", ".tmp/plugins.sha", ".tmp/plugins"} { if _, err = os.Lstat(filepath.Join(f.lease.Binding().Home, name)); !os.IsNotExist(err) { t.Fatalf("disabled startup artifact %s: %v", name, err) } } // Only make the fixture ready after all real processes have exited, so // ValidatePolicy can check their actual startup files. No CLI uses this // synthetic identity and no credentials or successful Open are fabricated. if err = f.lease.Preflight(ctx, func(context.Context, provider.Binding) (provider.Identity, error) { return f.lease.Identity(), nil }); err != nil { t.Fatal(err) } filepath.WalkDir(f.lease.Binding().Home, func(path string, d fs.DirEntry, e error) error { if e == nil && strings.Contains(path, "arg0") { r, _ := filepath.Rel(f.lease.Binding().Home, path) t.Logf("runtime: %s %s", r, d.Type()) } return e }) if err = f.lease.ValidatePolicy(ctx); err != nil { t.Fatalf("real runtime tree rejected: %v", err) } }) } }