package codex import ( "bufio" "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "reflect" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) type fakeProcess struct { exitCode int in *io.PipeWriter out *io.PipeReader done chan struct{} } func (p *fakeProcess) Stdin() io.WriteCloser { return p.in } func (p *fakeProcess) Stdout() io.ReadCloser { return p.out } func (p *fakeProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("diagnostic")) } func (p *fakeProcess) ID() string { return "fake" } func (p *fakeProcess) Wait(ctx context.Context) (provider.Exit, error) { select { case <-p.done: return provider.Exit{Code: p.exitCode}, nil case <-ctx.Done(): return provider.Exit{}, ctx.Err() } } type fakeHost struct { sessionID string startupFrames []json.RawMessage startupSessionOnly bool startupMethod string mu sync.Mutex mode string calls []string requests []json.RawMessage launches []provider.Launch processes []*fakeProcess } func (h *fakeHost) set(mode string) { h.mu.Lock(); h.mode = mode; h.mu.Unlock() } func (h *fakeHost) count(method string) int { h.mu.Lock() defer h.mu.Unlock() n := 0 for _, m := range h.calls { if m == method { n++ } } return n } func (h *fakeHost) Start(ctx context.Context, l provider.Launch, args []string) (provider.Process, error) { if _, e := provider.AttestLaunch(l, args); e != nil { return nil, e } in, writer := io.Pipe() reader, out := io.Pipe() p := &fakeProcess{in: writer, out: reader, done: make(chan struct{})} h.mu.Lock() h.launches = append(h.launches, l) h.processes = append(h.processes, p) h.mu.Unlock() go func() { <-ctx.Done(); in.CloseWithError(ctx.Err()); out.CloseWithError(ctx.Err()) }() go func() { defer close(p.done) defer in.Close() defer out.Close() // Simulate an app-server writing only its constructed home. os.WriteFile(filepath.Join(l.Binding.Home, "history.jsonl"), []byte("# private fake config\n"), 0600) scan := bufio.NewScanner(in) scan.Buffer(make([]byte, 4096), MaxFrameBytes) send := func(v any) { raw, _ := json.Marshal(v) if h.sessionID != "" { raw = bytes.ReplaceAll(raw, []byte("thread-1"), []byte(h.sessionID)) } out.Write(append(raw, '\n')) } turn := 0 startupSent := false for scan.Scan() { var req struct { ID json.RawMessage Method string Params map[string]json.RawMessage } if json.Unmarshal(scan.Bytes(), &req) != nil { return } h.mu.Lock() mode := h.mode h.calls = append(h.calls, req.Method) h.requests = append(h.requests, bytes.Clone(scan.Bytes())) h.mu.Unlock() noticeMethod := h.startupMethod if noticeMethod == "" { noticeMethod = "initialized" } if !startupSent && req.Method == noticeMethod && (!h.startupSessionOnly || !strings.HasPrefix(l.AttemptKey, "codex-preflight-")) { startupSent = true frames := h.startupFrames if frames == nil && mode != "account-event" { frames = []json.RawMessage{json.RawMessage(startupAccountFrame)} } send(json.RawMessage(startupRemoteFrame)) for _, frame := range frames { send(frame) } } if req.Method == "initialized" { continue } var result any = map[string]any{} switch req.Method { case "initialize": version := Version if mode == "version" { version = "0.164.0" } result = recordedReply(tFixturePath, 1) if mode == "version" { result.(map[string]any)["userAgent"] = "equipo/" + version + " (Linux)" } send(recordedNotification()) case "account/read": email := "account@example.invalid" if mode == "identity" { email = "other@example.invalid" } result = map[string]any{"account": map[string]any{"type": "chatgpt", "email": email, "planType": "pro"}, "requiresOpenaiAuth": true} case "config/read": if mode == "resume-race" { os.WriteFile(filepath.Join(l.Binding.CredentialHome, "auth.json"), []byte(`{"fake":"changed"}`), 0600) } var config map[string]any json.Unmarshal(l.Policy.Settings, &config) if mode == "profile" { config["permissions"].(map[string]any)["equipo"].(map[string]any)["filesystem"].(map[string]any)["/egress"] = "read" } if mode == "config-extra" { config["hooks"] = map[string]any{"enabled": true} } if mode == "apps" { config["features"].(map[string]any)["apps"] = true } if mode == "mcp" { config["mcp_servers"] = map[string]any{"inherited": map[string]any{"command": "evil"}} } if mode == "extra-mcp" { config["mcp_servers"].(map[string]any)["other"] = map[string]any{"command": "other"} } if mode == "network" { config["permissions"].(map[string]any)["equipo"].(map[string]any)["network"].(map[string]any)["enabled"] = true } result = recordedConfig(config) if mode == "origin" { result.(map[string]any)["origins"].(map[string]any)["model"] = map[string]any{"name": map[string]any{"type": "enterpriseManaged"}, "version": "fake"} } case "thread/start", "thread/resume": if req.Method == "thread/resume" && strings.HasPrefix(mode, "resume-usage") { raw, _ := os.ReadFile("testdata/probe.jsonl") var snapshot map[string]any for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) { var frame map[string]any json.Unmarshal(line, &frame) if frame["method"] == "thread/tokenUsage/updated" { snapshot = frame } } if mode == "resume-usage-changed" { snapshot["params"].(map[string]any)["tokenUsage"].(map[string]any)["total"].(map[string]any)["inputTokens"] = 99999 } send(snapshot) } if mode == "unpersisted" && req.Method == "thread/resume" && turn == 0 { send(map[string]any{"id": req.ID, "error": map[string]any{"code": -32600, "message": "no rollout found for thread id thread-1"}}) continue } if mode == "turn-race" { os.WriteFile(filepath.Join(l.Binding.CredentialHome, "auth.json"), []byte(`{"fake":"changed"}`), 0600) } profile := "equipo" if mode == "active-profile" { profile = "other" } approval := "on-request" reviewer := "user" if mode == "approval" { approval = "never" } if mode == "reviewer" { reviewer = "guardian_subagent" } result = map[string]any{"thread": map[string]any{"id": "thread-1"}, "model": "gpt-6-luna", "modelProvider": "openai", "cwd": "/workspace", "approvalPolicy": approval, "approvalsReviewer": reviewer, "activePermissionProfile": map[string]any{"id": profile, "extends": nil}, "runtimeWorkspaceRoots": []string{"/workspace"}, "sandbox": map[string]any{"type": "workspaceWrite", "networkAccess": false}} case "turn/start": if mode == "exit" { p.exitCode = 7 } turn++ tid := "turn-" + string(rune('0'+turn)) if mode == "account-event" { send(map[string]any{"method": "account/updated", "params": map[string]any{"authMode": "chatgpt", "planType": "pro"}}) } if mode == "source-active" { os.WriteFile(filepath.Join(l.Binding.CredentialHome, "auth.json"), []byte(`{"fake":"changed-active"}`), 0600) } send(map[string]any{"method": "turn/started", "params": map[string]any{"threadId": "thread-1", "turn": map[string]any{"id": tid, "status": "inProgress"}}}) result = map[string]any{"turn": map[string]any{"id": tid, "status": "inProgress"}} send(map[string]any{"id": req.ID, "result": result}) if mode == "eof" { return } if mode == "hang" { continue } raw, _ := os.ReadFile("testdata/probe.jsonl") for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) { if mode == "session-event" { line = bytes.ReplaceAll(line, []byte("thread-1"), []byte("wrong-thread")) } if mode == "turn-event" { line = bytes.ReplaceAll(line, []byte("turn-1"), []byte("wrong-turn")) } if h.sessionID != "" { line = bytes.ReplaceAll(line, []byte("thread-1"), []byte(h.sessionID)) } out.Write(append(bytes.ReplaceAll(line, []byte("turn-1"), []byte(tid)), '\n')) } continue } send(map[string]any{"id": req.ID, "result": result}) } }() return p, nil } type fakeCapture struct{} func (fakeCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) { frames := make(chan provider.Frame) done := make(chan error, 1) go func() { defer p.Stdout().Close() scan := bufio.NewScanner(p.Stdout()) scan.Buffer(make([]byte, 4096), MaxFrameBytes+1) var seq int64 for scan.Scan() { seq++ select { case frames <- provider.Frame{Sequence: seq, Bytes: bytes.Clone(scan.Bytes())}: case <-ctx.Done(): close(frames) done <- ctx.Err() close(done) return } } close(frames) done <- scan.Err() close(done) }() return &provider.Capture{Input: p.Stdin(), Frames: frames, Done: done}, nil } type fixture struct { l *Launcher host *fakeHost lease *provider.AccountLease launch provider.Launch inputs provider.PolicyInputs interactive string } func fixtureFor(t *testing.T) *fixture { t.Helper() root := t.TempDir() source := filepath.Join(root, "dedicated") os.Mkdir(source, 0700) id := provider.Identity{AccountID: "account@example.invalid", HomeID: "equipo-home", ProviderVersion: Version} raw, _ := json.Marshal(id) os.WriteFile(filepath.Join(source, provider.IdentityFile), raw, 0600) os.WriteFile(filepath.Join(source, "auth.json"), []byte(`{"fake":"login"}`), 0600) lease, e := provider.OpenAccount(context.Background(), provider.Binding{ID: "binding", Home: source, AccountID: id.AccountID, Provider: "codex", Expected: id, RuntimeRoot: filepath.Join(root, "homes")}) if e != nil { t.Fatal(e) } t.Cleanup(func() { lease.Close() }) work, scratch := filepath.Join(root, "workspace"), filepath.Join(root, "scratch") os.Mkdir(work, 0700) os.Mkdir(scratch, 0700) files := []provider.Mount{} for _, name := range []string{"codex", "codex-code-mode-host", "equipo-tool-proxy"} { p := filepath.Join(root, name) os.WriteFile(p, []byte(name), 0700) files = append(files, provider.Mount{Source: p, Target: "/opt/" + name, ReadOnly: true}) } in := provider.PolicyInputs{RuntimeFiles: files, Workspace: work, Scratch: scratch, AuthHost: "auth.openai.com", EgressHosts: []string{"chatgpt.com", "auth.openai.com"}, LauncherVersion: "2", BwrapVersion: "0.11.0", DeniedPaths: []string{"/alias/login", "/private/state"}} in, e = PolicyInputs(lease.Binding(), in, "gpt-6-luna") if e != nil { t.Fatal(e) } policy, e := provider.BuildPolicy(lease.Binding(), in) if e != nil { t.Fatal(e) } host := &fakeHost{} l, e := New(host, fakeCapture{}) if e != nil { t.Fatal(e) } for name, dst := range map[string]*string{"codex": &l.digest, "codex-code-mode-host": &l.hostDigest} { sum := sha256.Sum256([]byte(name)) *dst = hex.EncodeToString(sum[:]) } interactive := filepath.Join(root, "interactive") os.Mkdir(interactive, 0700) os.WriteFile(filepath.Join(interactive, "config.toml"), []byte("# keep byte-identical\nmodel = \"interactive\"\n"), 0600) t.Cleanup(func() { host.mu.Lock() defer host.mu.Unlock() for _, p := range host.processes { p.in.Close() p.out.Close() select { case <-p.done: case <-time.After(time.Second): t.Error("fake server leaked") } } }) return &fixture{l, host, lease, provider.Launch{AttemptKey: "attempt", Workspace: work, Binding: lease.Binding(), Policy: policy, Selection: provider.Selection{ConnectionID: "connection", Provider: "codex", Family: "gpt", Model: "gpt-6-luna", AccountID: id.AccountID}}, in, interactive} } func openFixture(t *testing.T, f *fixture) (provider.Session, <-chan provider.Event) { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) t.Cleanup(cancel) s, e := f.l.Open(ctx, f.launch) if e != nil { t.Fatal(e) } t.Cleanup(func() { f.l.Close(context.Background(), s) }) events, e := f.l.Events(ctx, s) if e != nil { t.Fatal(e) } return s, events } func terminal(t *testing.T, ch <-chan provider.Event) provider.Event { t.Helper() for { select { case ev, ok := <-ch: if !ok { t.Fatal("missing terminal") } if ev.Kind == "turn.completed" || ev.Kind == "turn.failed" { return ev } case <-time.After(2 * time.Second): t.Fatal("terminal timeout") } } } func TestCodexAppServerPolicy(t *testing.T) { t.Parallel() f := fixtureFor(t) before, _ := os.ReadFile(filepath.Join(f.interactive, "config.toml")) s, events := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "local-1", AdmissionID: "a1", Prompt: "hello"}); e != nil { t.Fatal(e) } if ev := terminal(t, events); ev.Kind != "turn.completed" || ev.TurnID != "local-1" { t.Fatal(ev) } if e := f.l.Close(context.Background(), s); e != nil { t.Fatal(e) } f.launch.AttemptKey = "resume" f.launch.ResumeSessionID = s.ID s2, events2 := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s2, provider.Turn{ID: "local-2", AdmissionID: "a2", Prompt: "again"}); e != nil { t.Fatal(e) } terminal(t, events2) after, _ := os.ReadFile(filepath.Join(f.interactive, "config.toml")) if !bytes.Equal(before, after) { t.Fatal("interactive config changed") } if f.host.count("thread/resume") != 2 { t.Fatal("resume not used") } f.host.mu.Lock() defer f.host.mu.Unlock() for _, launch := range f.host.launches { in, _, e := policyInputs(launch.Policy) if e != nil { t.Fatal(e) } if len(in.Argv) < 5 || !reflect.DeepEqual(in.Argv[:5], []string{"/opt/codex", "app-server", "--strict-config", "--listen", "stdio://"}) { t.Fatal("strict app-server launch missing", in.Argv) } if len(launch.Policy.Manifest) == 0 || !bytes.Contains(launch.Policy.Manifest, []byte(`"ThreadPolicy"`)) || !bytes.Contains(launch.Policy.ThreadPolicy, []byte(`"approvalsReviewer":"user"`)) { t.Fatal("RPC policy missing from manifest") } } for i, method := range f.host.calls { var req struct{ Params map[string]any } json.Unmarshal(f.host.requests[i], &req) switch method { case "initialize": if req.Params["capabilities"].(map[string]any)["experimentalApi"] != true { t.Fatal("experimental API missing") } case "thread/start", "thread/resume": for k, v := range map[string]any{"approvalPolicy": "on-request", "approvalsReviewer": "user", "permissions": "equipo"} { if req.Params[k] != v { t.Fatal(method, k, req.Params) } } case "turn/start": for _, k := range []string{"permissions", "sandboxPolicy", "approvalPolicy", "approvalsReviewer"} { if _, ok := req.Params[k]; ok { t.Fatal("turn override", k) } } } } } func TestCodexNoLegacyPolicyOverride(t *testing.T) { t.Parallel() for _, change := range []string{"strict", "ignore", "sandbox", "sandboxPolicy", "deny-home", "deny-egress", "deny-tool", "deny-alias", "code-host", "digest", "approval", "reviewer", "turn", "hash", "version"} { t.Run(change, func(t *testing.T) { f := fixtureFor(t) in := f.inputs switch change { case "strict": in.Argv = append([]string{}, in.Argv...) for i, a := range in.Argv { if a == "--strict-config" { in.Argv = append(in.Argv[:i], in.Argv[i+1:]...) break } } case "ignore": in.Argv = append(in.Argv, "--ignore-user-config") case "code-host": in.RuntimeFiles = in.RuntimeFiles[:1] case "digest": os.WriteFile(in.RuntimeFiles[1].Source, []byte("wrong binary"), 0700) case "version": in.ProviderVersion = "0.164.0" case "turn": in.TurnPolicy = json.RawMessage(`{"permissions":"other"}`) case "hash": f.launch.Policy.Hash = "wrong" default: var settings map[string]any json.Unmarshal(in.Settings, &settings) if strings.HasPrefix(change, "deny-") { path := map[string]string{"deny-home": f.launch.Binding.CredentialHome, "deny-egress": "/egress", "deny-tool": "/tool", "deny-alias": "/alias/login"}[change] delete(settings["permissions"].(map[string]any)["equipo"].(map[string]any)["filesystem"].(map[string]any), path) in.Settings, _ = json.Marshal(settings) } else { var tp map[string]any json.Unmarshal(in.ThreadPolicy, &tp) key := change value := "read-only" if change == "approval" { key = "approvalPolicy" value = "never" } if change == "reviewer" { key = "approvalsReviewer" value = "guardian_subagent" } tp[key] = value in.ThreadPolicy, _ = json.Marshal(tp) } } if change != "hash" { p, e := provider.BuildPolicy(f.launch.Binding, in) if e != nil { return } f.launch.Policy = p } if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("unsafe policy accepted", change) } if f.host.count("turn/start") != 0 { t.Fatal("spent before rejection") } }) } } func TestCodexUnexpectedPolicyChange(t *testing.T) { t.Parallel() for _, mode := range []string{"profile", "network", "origin", "identity", "active-profile", "approval", "reviewer", "version", "config-extra", "apps", "mcp"} { t.Run("startup-"+mode, func(t *testing.T) { t.Parallel() f := fixtureFor(t) f.host.set(mode) if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("bad readback accepted") } if f.host.count("turn/start") != 0 { t.Fatal("prompt sent") } }) } for _, mode := range []string{"profile", "active-profile", "approval", "reviewer", "origin", "identity", "source-file", "source-active", "account-event", "session-event", "turn-event", "eof"} { t.Run("between-"+mode, func(t *testing.T) { t.Parallel() f := fixtureFor(t) s, ch := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "initial", AdmissionID: "initial", Prompt: "ready"}); e != nil { t.Fatal(e) } terminal(t, ch) f.host.set(mode) if mode == "source-file" { os.WriteFile(f.inputs.RuntimeFiles[1].Source, []byte("tampered"), 0700) } e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "local-1", AdmissionID: "a1", Prompt: "hello"}) if mode == "source-active" || mode == "account-event" || mode == "session-event" || mode == "turn-event" || mode == "eof" { if e == nil && terminal(t, ch).Kind != "turn.failed" { t.Fatal("active change completed") } } else if e == nil { t.Fatal("changed policy accepted") } count := f.host.count("turn/start") if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "local-2", AdmissionID: "a2", Prompt: "again"}); e == nil { t.Fatal("contained step resumed") } if count != f.host.count("turn/start") { t.Fatal("contained step wrote prompt") } }) } } func TestCodexRefreshAndAdmission(t *testing.T) { t.Parallel() f := fixtureFor(t) s, ch := openFixture(t, f) turn := provider.Turn{ID: "l1", AdmissionID: "a1", Prompt: "hello"} if e := f.l.StartTurn(context.Background(), s, turn); e != nil { t.Fatal(e) } terminal(t, ch) checks := f.host.count("account/read") os.WriteFile(filepath.Join(f.launch.Binding.Home, "auth.json"), []byte(`{"fake":"refreshed"}`), 0600) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "l2", AdmissionID: "a2", Prompt: "again"}); !errors.Is(e, provider.ErrAccountMaintenance) { t.Fatal("runtime refresh did not require sign-in", e) } if f.host.count("account/read") != checks { t.Fatal("refresh ran an identity probe") } raw, _ := os.ReadFile(filepath.Join(f.launch.Binding.CredentialHome, "auth.json")) if string(raw) == `{"fake":"refreshed"}` { t.Fatal("runtime credentials committed") } if e := f.l.StartTurn(context.Background(), s, turn); e == nil { t.Fatal("admission replayed") } if e := f.l.Respond(context.Background(), s, provider.Answer{Behavior: "allow"}); e == nil { t.Fatal("automatic approval") } } func TestCodexPolicyHashIncludesRPC(t *testing.T) { t.Parallel() f := fixtureFor(t) for _, field := range []string{"thread", "turn"} { in := f.inputs if field == "thread" { in.ThreadPolicy = json.RawMessage(`{"permissions":"other"}`) } else { in.TurnPolicy = json.RawMessage(`{"effort":"high"}`) } p, e := provider.BuildPolicy(f.launch.Binding, in) if e != nil { t.Fatal(e) } if p.Hash == f.launch.Policy.Hash || p.ManifestHash == f.launch.Policy.ManifestHash { t.Fatal("RPC policy omitted from hash") } } } func TestCodexIdentityWithoutHomeEcho(t *testing.T) { t.Parallel() f := fixtureFor(t) id, e := f.l.Preflight(context.Background(), f.launch.Binding, f.launch.Policy) if e != nil { t.Fatal(e) } if id.HomeID != "" || id.AccountID != f.launch.Binding.Expected.AccountID { t.Fatal("invented identity", id) } if e = f.lease.ValidatePolicy(context.Background()); e != nil { t.Fatal(e) } f.host.set("identity") _, e = f.l.Preflight(context.Background(), f.launch.Binding, f.launch.Policy) if !errors.Is(e, provider.ErrIdentity) { t.Fatal(e) } } func TestCodexConstructor(t *testing.T) { t.Parallel() if _, e := New(nil, fakeCapture{}); e == nil { t.Fatal("nil host") } if _, e := New(&fakeHost{}, nil); e == nil { t.Fatal("nil capture") } } func TestCodexThreadConfigPinned(t *testing.T) { t.Parallel() f := fixtureFor(t) s, ch := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "l", AdmissionID: "a", Prompt: "hello"}); e != nil { t.Fatal(e) } terminal(t, ch) f.host.mu.Lock() defer f.host.mu.Unlock() for i, method := range f.host.calls { if method != "thread/start" && method != "thread/resume" { continue } var req struct{ Params map[string]json.RawMessage } json.Unmarshal(f.host.requests[i], &req) if !sameJSON(req.Params["config"], f.launch.Policy.Settings) { t.Fatal("saved thread can retain a different profile definition", method) } } } func TestCodexLifecycle(t *testing.T) { t.Parallel() t.Run("attach-and-identity", func(t *testing.T) { f := fixtureFor(t) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() s, e := f.l.Open(ctx, f.launch) if e != nil { t.Fatal(e) } defer f.l.Close(context.Background(), s) if e = f.l.StartTurn(ctx, s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil { t.Fatal("turn without event capture") } bad := s bad.AccountID = "other" if _, e = f.l.Events(ctx, bad); e == nil { t.Fatal("forged session accepted") } if _, e = f.l.Events(ctx, s); e != nil { t.Fatal(e) } if _, e = f.l.Events(ctx, s); e == nil { t.Fatal("duplicate consumer") } }) t.Run("interrupt", func(t *testing.T) { f := fixtureFor(t) s, ch := openFixture(t, f) f.host.set("hang") if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil { t.Fatal(e) } f.l.Interrupt(context.Background(), s) if terminal(t, ch).Kind != "turn.failed" { t.Fatal("interruption reported completion") } if f.host.count("turn/interrupt") != 1 { t.Fatal("missing graceful interrupt") } if e := f.l.Close(context.Background(), s); e == nil { t.Fatal("uncertain attempt clean") } f.launch.AttemptKey = "resume" f.launch.ResumeSessionID = s.ID if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("uncertain resume") } }) t.Run("attempt-context", func(t *testing.T) { f := fixtureFor(t) ctx, cancel := context.WithCancel(context.Background()) s, e := f.l.Open(ctx, f.launch) if e != nil { t.Fatal(e) } ch, _ := f.l.Events(ctx, s) cancel() if terminal(t, ch).Kind != "turn.failed" { t.Fatal("attempt lifetime ignored") } f.l.Close(context.Background(), s) }) t.Run("per-turn-tamper", func(t *testing.T) { f := fixtureFor(t) s, _ := openFixture(t, f) state, _ := f.l.state(s) state.launch.Policy.TurnPolicy = json.RawMessage(`{"approvalPolicy":"never"}`) count := len(f.host.calls) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil { t.Fatal("per-turn override accepted") } if len(f.host.calls) != count { t.Fatal("override reached stdin") } }) } func TestCodexGeneratedSchema(t *testing.T) { t.Parallel() f := fixtureFor(t) for _, name := range []string{"ThreadStartParams", "ThreadResumeParams", "TurnStartParams"} { raw, e := os.ReadFile("testdata/schema-" + name + ".json") if e != nil { t.Fatal(e) } var schema struct{ Properties map[string]json.RawMessage } if e = json.Unmarshal(raw, &schema); e != nil { t.Fatal(e) } policy := f.launch.Policy.ThreadPolicy if name == "TurnStartParams" { policy = f.launch.Policy.TurnPolicy } var fields map[string]json.RawMessage json.Unmarshal(policy, &fields) if name == "ThreadResumeParams" { fields = threadParams(policy, "thread/resume", "fixture") } for key := range fields { if _, ok := schema.Properties[key]; !ok { t.Fatal("field absent from pinned schema", name, key) } } } } func TestCodexPolicyShape(t *testing.T) { if Version != "0.165.0" || ExecutableSHA256 != "c06a67fd8ac76508dc78bd99ce20c9f317b8d568beda59485f3f4134df9962d5" || CodeModeHostSHA256 != "522935d4392ec9674fab60b239b5495992c6a93e4deb65113a216b6f5451ccd4" { t.Fatal("pinned runtime changed") } t.Parallel() f := fixtureFor(t) var config map[string]any json.Unmarshal(f.inputs.Settings, &config) for key, want := range map[string]any{"approval_policy": "on-request", "approvals_reviewer": "user", "default_permissions": "equipo", "model": "gpt-6-luna", "model_provider": "openai"} { if config[key] != want { t.Fatal(key, config[key]) } } profiles, ok := config["permissions"].(map[string]any) if !ok || len(profiles) != 1 { t.Fatal("named profile missing") } profile, ok := profiles["equipo"].(map[string]any) if !ok { t.Fatal("equipo profile missing") } fs := profile["filesystem"].(map[string]any) for _, path := range []string{f.launch.Binding.CredentialHome, f.launch.Binding.Home, "/home/runner", "/egress", "/tool", "/config", "/proc", "/alias/login", "/private/state"} { if fs[path] != "deny" { t.Fatal("missing deny", path) } } if fs["/workspace"] != "write" || profile["network"].(map[string]any)["enabled"] != false { t.Fatal("workspace/network profile changed") } features := config["features"].(map[string]any) for _, key := range []string{"apps", "multi_agent", "remote_control"} { if features[key] != false { t.Fatal("feature enabled", key) } } if servers := config["mcp_servers"].(map[string]any); len(servers) != 1 || servers["equipo"] == nil { t.Fatal("inherited MCP") } } func TestCodexResumeRechecksLease(t *testing.T) { t.Parallel() f := fixtureFor(t) s, _ := openFixture(t, f) f.host.set("resume-race") before := f.host.count("thread/resume") if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil { t.Fatal("resume accepted stale lease") } if f.host.count("thread/resume") != before { t.Fatal("thread/resume sent after source changed") } } func TestCodexTurnRechecksLease(t *testing.T) { t.Parallel() f := fixtureFor(t) s, events := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "initial", AdmissionID: "initial", Prompt: "ready"}); e != nil { t.Fatal(e) } terminal(t, events) f.host.set("turn-race") if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e == nil { t.Fatal("turn accepted stale lease") } if f.host.count("turn/start") != 1 { t.Fatal("turn/start sent after source changed") } } func TestCodexRefreshRejectsChangedIdentity(t *testing.T) { t.Parallel() f := fixtureFor(t) s, ch := openFixture(t, f) if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil { t.Fatal(e) } terminal(t, ch) os.WriteFile(filepath.Join(f.launch.Binding.Home, "auth.json"), []byte(`{"fake":"other login"}`), 0600) f.host.set("identity") if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t2", AdmissionID: "a2", Prompt: "again"}); e == nil { t.Fatal("wrong identity refreshed") } if e := f.lease.Validate(context.Background()); !errors.Is(e, provider.ErrRefreshPending) { t.Fatal("runtime login did not remain pending sign-in", e) } raw, _ := os.ReadFile(filepath.Join(f.launch.Binding.CredentialHome, "auth.json")) if bytes.Contains(raw, []byte("other login")) { t.Fatal("wrong identity committed") } } func TestCodexProcessExit(t *testing.T) { t.Parallel() f := fixtureFor(t) s, ch := openFixture(t, f) f.host.set("exit") if e := f.l.StartTurn(context.Background(), s, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil { t.Fatal(e) } terminal(t, ch) if e := f.l.Close(context.Background(), s); e == nil { t.Fatal("nonzero exit accepted") } f.launch.AttemptKey = "resume" f.launch.ResumeSessionID = s.ID if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("nonzero exit authorized resume") } } type brokenCapture struct{ invalid bool } func (f brokenCapture) Open(context.Context, provider.Process, provider.Launch) (*provider.Capture, error) { if f.invalid { return &provider.Capture{}, nil } return nil, io.ErrUnexpectedEOF } func TestCodexCaptureRequired(t *testing.T) { t.Parallel() for _, invalid := range []bool{false, true} { f := fixtureFor(t) f.l.captures = brokenCapture{invalid: invalid} if _, e := f.l.Open(context.Background(), f.launch); e == nil { t.Fatal("missing capture accepted") } if f.host.count("turn/start") != 0 { t.Fatal("prompt bypassed capture") } } } func TestCodexClosedTurnCannotRestart(t *testing.T) { t.Parallel() f := fixtureFor(t) session, ch := openFixture(t, f) if e := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "t", AdmissionID: "a", Prompt: "hello"}); e != nil { t.Fatal(e) } terminal(t, ch) if e := f.l.Close(context.Background(), session); e != nil { t.Fatal(e) } s, _ := f.l.state(session) if e := s.beginTurn(context.Background(), provider.Turn{ID: "late", AdmissionID: "late-admission", Prompt: "late"}); e == nil { t.Fatal("close raced with begin and reopened the lease") } if e := f.lease.BeginTurn(context.Background()); e != nil { t.Fatal("closed session left lease active", e) } f.lease.EndTurn(context.Background()) } func TestCodexTypedNilConstructor(t *testing.T) { var host *fakeHost var capture *fakeCapture if _, e := New(host, fakeCapture{}); e == nil { t.Fatal("typed nil host accepted") } if _, e := New(&fakeHost{}, capture); e == nil { t.Fatal("typed nil capture accepted") } } type directGuardCapture struct { inner provider.CaptureFactory fail bool bound, turns int } type directGuardInput struct { io.WriteCloser owner *directGuardCapture } func (c *directGuardCapture) Open(ctx context.Context, p provider.Process, l provider.Launch) (*provider.Capture, error) { cap, e := c.inner.Open(ctx, p, l) if e == nil { cap.Input = &directGuardInput{cap.Input, c} } return cap, e } func (w *directGuardInput) BindSession(context.Context, provider.Session) error { w.owner.bound++ return nil } func (w *directGuardInput) BeginTurn(context.Context, provider.Session, provider.Turn) error { w.owner.turns++ if w.owner.fail { return io.ErrClosedPipe } return nil } func TestDirectJournalAdapterBarrier(t *testing.T) { for _, fail := range []bool{false, true} { t.Run(fmt.Sprint(fail), func(t *testing.T) { f := fixtureFor(t) guard := &directGuardCapture{inner: f.l.captures, fail: fail} f.l.captures = guard session, ch := openFixture(t, f) if guard.bound != 1 { t.Fatal("session not durably bound") } err := f.l.StartTurn(context.Background(), session, provider.Turn{ID: "direct-turn", AdmissionID: "direct-admission", Prompt: "hello"}) if fail { if err == nil { t.Fatal("failed journal barrier ignored") } if f.host.count("turn/start") != 0 { t.Fatal("failed barrier sent input") } } else { if err != nil { t.Fatal(err) } event := terminal(t, ch) if event.Sequence <= 0 { t.Fatal("capture sequence lost before projection") } } if guard.turns != 1 { t.Fatal("journal turn barrier not called") } }) } } func TestRefreshWithoutCertifiedHostFailsClosed(t *testing.T) { f := fixtureFor(t) in, _, err := policyInputs(f.launch.Policy) if err != nil { t.Fatal(err) } in.AuthHost = "" in.EgressHosts = []string{"chatgpt.com"} f.launch.Policy, err = provider.BuildPolicy(f.launch.Binding, in) if err != nil { t.Fatal(err) } s, _ := openFixture(t, f) if err = os.WriteFile(filepath.Join(f.launch.Binding.Home, "auth.json"), []byte(`{"fake":"refreshed"}`), 0600); err != nil { t.Fatal(err) } t.Setenv("EQUIPO_AUTH_HOST", "auth.openai.com") if err = f.l.StartTurn(context.Background(), s, provider.Turn{ID: "no-refresh", AdmissionID: "no-refresh", Prompt: "never sent"}); !errors.Is(err, provider.ErrAccountMaintenance) { t.Fatalf("uncertified refresh: %v", err) } }