| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 16 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 17 | "amadan.net/oficina/equipo/internal/testci" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 20 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 21 | ) |
| 22 | |
| 23 | func directToolFixture(t *testing.T) ToolBinding { |
| 24 | t.Helper() |
| 25 | j, _, s, _ := directFixture(t, "codex") |
| 26 | mustJournal(t, j.BeginTurn(context.Background(), s, directTurn())) |
| 27 | mustJournal(t, j.consumeTurn(context.Background(), s.AttemptKey, s.ID, "hello")) |
| 28 | return ToolBinding{Journal: j, Session: s, TurnID: "turn", InstanceID: "instance", TaskID: "task", Attempt: 1, Fence: 7, Tools: []string{"ask_person", "submit_candidate", "submit_review", "submit_reproduction"}, LeaseDeadline: time.Now().Add(time.Minute), Agent: provider.Agent{Provider: "codex", ServerID: "direct", AgentID: s.AttemptKey, ProviderSessionID: s.ID}, Isolation: team.IsolationSnapshot{Status: "confined"}, Copy: ToolCopy{Accepted: "accepted", Rejected: "rejected"}, Current: func(context.Context) error { return nil }} |
| 29 | } |
| 30 | func TestDirectToolScope(t *testing.T) { |
| 31 | b := directToolFixture(t) |
| 32 | p, e := OpenToolProxy(context.Background(), b) |
| 33 | mustJournal(t, e) |
| 34 | defer p.Close() |
| 35 | binary := filepath.Join(t.TempDir(), "equipo-tool-proxy") |
| 36 | build := exec.Command("go", "build", "-o", binary, "../../cmd/equipo-tool-proxy") |
| 37 | build.Env = append(os.Environ(), "CGO_ENABLED=0") |
| 38 | testci.GoCommand(t, build) |
| 39 | if out, e := build.CombinedOutput(); e != nil { |
| 40 | t.Fatalf("build: %v %s", e, out) |
| 41 | } |
| 42 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 43 | defer cancel() |
| 44 | cmd := exec.CommandContext(ctx, binary, "--socket", p.SocketPath) |
| 45 | cmd.Env = []string{"PATH=/usr/bin:/bin"} |
| 46 | in, e := cmd.StdinPipe() |
| 47 | mustJournal(t, e) |
| 48 | out, e := cmd.StdoutPipe() |
| 49 | mustJournal(t, e) |
| 50 | mustJournal(t, cmd.Start()) |
| 51 | t.Cleanup(func() { |
| 52 | if cmd.ProcessState == nil { |
| 53 | cmd.Process.Kill() |
| 54 | cmd.Wait() |
| 55 | } |
| 56 | }) |
| 57 | enc := json.NewEncoder(in) |
| 58 | scan := bufio.NewScanner(out) |
| 59 | rpc := func(id int, method string, params any) map[string]any { |
| 60 | t.Helper() |
| 61 | mustJournal(t, enc.Encode(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})) |
| 62 | if !scan.Scan() { |
| 63 | t.Fatal("no helper reply", scan.Err()) |
| 64 | } |
| 65 | var v map[string]any |
| 66 | mustJournal(t, json.Unmarshal(scan.Bytes(), &v)) |
| 67 | return v |
| 68 | } |
| 69 | if rpc(1, "initialize", map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{}, "clientInfo": map[string]any{}})["error"] != nil { |
| 70 | t.Fatal("initialize") |
| 71 | } |
| 72 | tools := fmt.Sprint(rpc(2, "tools/list", map[string]any{})) |
| 73 | if strings.Contains(tools, "publish") || strings.Contains(tools, "attest") { |
| 74 | t.Fatal(tools) |
| 75 | } |
| 76 | args := []string{`{"request_id":"a","question":"Which?"}`, `{"request_id":"b","commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`, `{"request_id":"c","candidate":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","decision":"approve","findings":[]}`, `{"request_id":"d","expected_symptom":"fails","files":[{"path":"x_test.go","bytes":"eA=="}],"test_names":[{"package":"./x","name":"TestX"}]}`} |
| 77 | for i, name := range b.Tools { |
| 78 | if v := rpc(3+i, "tools/call", map[string]any{"name": name, "arguments": json.RawMessage(args[i])}); v["error"] != nil { |
| 79 | t.Fatal(name, v) |
| 80 | } |
| 81 | rows, e := b.Journal.ToolSubmissions(ctx, 10) |
| 82 | mustJournal(t, e) |
| 83 | if len(rows) != 1 || rows[0].Fence != 7 || rows[0].Agent.ProviderSessionID != b.Session.ID { |
| 84 | t.Fatal(rows) |
| 85 | } |
| 86 | mustJournal(t, b.Journal.AckTool(ctx, rows[0])) |
| 87 | } |
| 88 | for i, name := range []string{"read_file", "publish", "attest_check", "ask_person"} { |
| 89 | a := json.RawMessage(`{"request_id":"evil","path":"/etc/passwd"}`) |
| 90 | if v := rpc(20+i, "tools/call", map[string]any{"name": name, "arguments": a}); v["error"] == nil { |
| 91 | t.Fatal("host authority", name) |
| 92 | } |
| 93 | } |
| 94 | in.Close() |
| 95 | mustJournal(t, cmd.Wait()) |
| 96 | } |
| 97 | func TestToolProxyCannotExposeSecrets(t *testing.T) { |
| 98 | b := directToolFixture(t) |
| 99 | p, e := OpenToolProxy(context.Background(), b) |
| 100 | mustJournal(t, e) |
| 101 | want := `{"mcpServers":{"equipo":{"type":"stdio","command":"/opt/equipo-tool-proxy","args":["--socket","/tool/equipo.sock"]}}}` |
| 102 | if string(p.MCP()) != want { |
| 103 | t.Fatal("unexpected tool proxy MCP configuration") |
| 104 | } |
| 105 | if strings.Contains(string(p.MCP()), b.Journal.path) || strings.Contains(string(p.MCP()), "capability") { |
| 106 | t.Fatal("host secret exposed") |
| 107 | } |
| 108 | // A long host address is dialled through the verified parent fd by the helper. |
| 109 | if len(p.SocketPath) <= 107 { |
| 110 | t.Log("fixture address is short; separate long-path case covers fd binding") |
| 111 | } |
| 112 | mustJournal(t, p.Close()) |
| 113 | mustJournal(t, p.Close()) |
| 114 | if _, e := os.Stat(p.SocketPath); !os.IsNotExist(e) { |
| 115 | t.Fatal("proxy survived close", e) |
| 116 | } |
| 117 | } |
| 118 | func TestToolProxyLongPath(t *testing.T) { |
| 119 | b := directToolFixture(t) |
| 120 | path := filepath.Join(t.TempDir(), strings.Repeat("long", 30), "journal.db") |
| 121 | j, e := OpenJournal(context.Background(), path) |
| 122 | mustJournal(t, e) |
| 123 | defer j.Close() |
| 124 | // Proxy storage location is independent of the authenticated attempt journal. |
| 125 | p, e := openToolProxy(context.Background(), b, filepath.Dir(path)) |
| 126 | mustJournal(t, e) |
| 127 | defer p.Close() |
| 128 | var out strings.Builder |
| 129 | input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" |
| 130 | mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath)) |
| 131 | if !strings.Contains(out.String(), "serverInfo") { |
| 132 | t.Fatal(out.String()) |
| 133 | } |
| 134 | } |
| 135 | func TestCodexApprovalResponseBroker(t *testing.T) { |
| 136 | for _, change := range []string{"ok", "fence", "attempt", "tool", "arguments", "lost-lease", "execute-revalidate"} { |
| 137 | t.Run(change, func(t *testing.T) { |
| 138 | b := directToolFixture(t) |
| 139 | current := true |
| 140 | b.Current = func(context.Context) error { |
| 141 | if !current { |
| 142 | return runnerproto.ErrInvalid |
| 143 | } |
| 144 | return nil |
| 145 | } |
| 146 | p, e := OpenToolProxy(context.Background(), b) |
| 147 | mustJournal(t, e) |
| 148 | defer p.Close() |
| 149 | q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "ask_person", RequestID: "r", Arguments: json.RawMessage(`{"question":"Which?"}`)} |
| 150 | switch change { |
| 151 | case "fence": |
| 152 | q.Fence++ |
| 153 | case "attempt": |
| 154 | q.Attempt++ |
| 155 | case "tool": |
| 156 | q.Name = "publish" |
| 157 | case "arguments": |
| 158 | q.Arguments = json.RawMessage(`{"question":"Which?","command":"cat /etc/passwd"}`) |
| 159 | case "lost-lease": |
| 160 | current = false |
| 161 | } |
| 162 | e = p.ValidateApproval(context.Background(), q) |
| 163 | if change == "ok" || change == "execute-revalidate" { |
| 164 | mustJournal(t, e) |
| 165 | } else if e == nil { |
| 166 | t.Fatal("invalid approval", change) |
| 167 | } |
| 168 | if change == "execute-revalidate" { |
| 169 | current = false |
| 170 | if p.submit(context.Background(), q.Name, q.RequestID, q.Arguments) == nil { |
| 171 | t.Fatal("execution did not revalidate") |
| 172 | } |
| 173 | } |
| 174 | }) |
| 175 | } |
| 176 | } |
| 177 | func TestDirectStaleAnswer(t *testing.T) { |
| 178 | for _, change := range []string{"cancel", "restart", "replaced-turn", "revoked-member", "replayed-changed-payload"} { |
| 179 | t.Run(change, func(t *testing.T) { |
| 180 | b := directToolFixture(t) |
| 181 | c := &answerClient{} |
| 182 | current := true |
| 183 | r := QuestionRelay{Journal: b.Journal, Client: c, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { |
| 184 | if !current { |
| 185 | return time.Time{}, runnerproto.ErrInvalid |
| 186 | } |
| 187 | return b.LeaseDeadline, nil |
| 188 | }} |
| 189 | q := runnerproto.Question{ID: "q", TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: "r", Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline, RawRequest: json.RawMessage(`{"id":"r","kind":"person","question":"Which?"}`)} |
| 190 | a := runnerproto.QuestionAnswer{Behavior: "deny"} |
| 191 | switch change { |
| 192 | case "cancel": |
| 193 | mustJournal(t, b.Journal.interruptDirect(context.Background(), b.Session.AttemptKey, false)) |
| 194 | case "restart": |
| 195 | _, e := b.Journal.RecoverDirect(context.Background()) |
| 196 | mustJournal(t, e) |
| 197 | case "replaced-turn": |
| 198 | r.TurnID = "other" |
| 199 | case "revoked-member": |
| 200 | current = false |
| 201 | case "replayed-changed-payload": |
| 202 | mustJournal(t, r.Deliver(context.Background(), q, a)) |
| 203 | q.RawRequest = json.RawMessage(`{"id":"r","kind":"person","question":"Changed?"}`) |
| 204 | } |
| 205 | before := len(c.responses) |
| 206 | if r.Deliver(context.Background(), q, a) == nil || len(c.responses) != before { |
| 207 | t.Fatal("stale answer delivered", change) |
| 208 | } |
| 209 | }) |
| 210 | } |
| 211 | } |
| 212 | func TestDirectStaleAnswerCancelIsAttemptScoped(t *testing.T) { |
| 213 | b := directToolFixture(t) |
| 214 | ctx := context.Background() |
| 215 | var launchRaw, recordRaw []byte |
| 216 | mustJournal(t, b.Journal.db.QueryRow("SELECT launch,record FROM direct_attempts WHERE attempt='attempt'").Scan(&launchRaw, &recordRaw)) |
| 217 | var launch provider.Launch |
| 218 | var record containment.Record |
| 219 | mustJournal(t, json.Unmarshal(launchRaw, &launch)) |
| 220 | mustJournal(t, json.Unmarshal(recordRaw, &record)) |
| 221 | launch.AttemptKey = "B" |
| 222 | record.AttemptKey = "B" |
| 223 | record.ID = strings.Repeat("b", 32) |
| 224 | mustJournal(t, b.Journal.recordDirectLaunch(ctx, launch, record)) |
| 225 | sessionB := b.Session |
| 226 | sessionB.AttemptKey = "B" |
| 227 | sessionB.ID = "session-B" |
| 228 | turnB := provider.Turn{ID: "turn", AdmissionID: "admission-B", Prompt: "hello"} |
| 229 | mustJournal(t, b.Journal.BeginTurn(ctx, sessionB, turnB)) |
| 230 | mustJournal(t, b.Journal.consumeTurn(ctx, "B", sessionB.ID, "hello")) |
| 231 | for _, a := range []string{"attempt", "B"} { |
| 232 | _, e := b.Journal.db.ExecContext(ctx, "INSERT INTO journal_answers VALUES(?,?,'pending')", a, "hash") |
| 233 | mustJournal(t, e) |
| 234 | _, e = b.Journal.db.ExecContext(ctx, "INSERT INTO direct_answer_scopes(answer_key,attempt,turn) VALUES(?,?,?)", a, a, "turn") |
| 235 | mustJournal(t, e) |
| 236 | } |
| 237 | mustJournal(t, b.Journal.interruptDirect(ctx, "attempt", false)) |
| 238 | mustJournal(t, b.Journal.currentDirectTurn(ctx, sessionB, "turn")) |
| 239 | var state string |
| 240 | mustJournal(t, b.Journal.db.QueryRow("SELECT state FROM journal_answers WHERE answer_key='B'").Scan(&state)) |
| 241 | if state != "pending" { |
| 242 | t.Fatal("attempt B answer invalidated by A", state) |
| 243 | } |
| 244 | mustJournal(t, b.Journal.db.QueryRow("SELECT state FROM journal_answers WHERE answer_key='attempt'").Scan(&state)) |
| 245 | if state != "invalid" { |
| 246 | t.Fatal("A answer survived", state) |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | func TestDirectToolAnswerCapture(t *testing.T) { |
| 251 | j, l, s, p := directFixture(t, "codex") |
| 252 | ctx := context.Background() |
| 253 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 254 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 255 | input := &captureInput{journal: j, launch: l, input: p.Stdin(), ctx: ctx, fail: func(error) {}} |
| 256 | wire := []byte("{\"id\":7,\"result\":{\"decision\":\"decline\"}}\n") |
| 257 | if _, e := input.Write(wire); e == nil { |
| 258 | t.Fatal("ordinary stdin accepted uncorrelated reply") |
| 259 | } |
| 260 | if _, e := input.WriteAnswer(ctx, s, "turn", wire); e != nil { |
| 261 | t.Fatal("correlated answer rejected", e) |
| 262 | } |
| 263 | before := p.input.Len() |
| 264 | if _, e := input.WriteAnswer(ctx, s, "turn", wire); e == nil || p.input.Len() != before { |
| 265 | t.Fatal("answer replay transmitted") |
| 266 | } |
| 267 | for _, raw := range []string{"{\"id\":8,\"method\":\"turn/start\",\"params\":{}}\n", "{\"id\":8,\"result\":{\"decision\":{\"acceptWithExecpolicyAmendment\":{}}}}\n"} { |
| 268 | if _, e := input.WriteAnswer(ctx, s, "turn", []byte(raw)); e == nil { |
| 269 | t.Fatal("hidden turn or policy amendment", raw) |
| 270 | } |
| 271 | } |
| 272 | mustJournal(t, j.interruptDirect(ctx, s.AttemptKey, false)) |
| 273 | if _, e := input.WriteAnswer(ctx, s, "turn", []byte("{\"id\":8,\"result\":{\"decision\":\"decline\"}}\n")); e == nil { |
| 274 | t.Fatal("cancelled answer sent") |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | type directAnswerLauncher struct { |
| 279 | provider.Launcher |
| 280 | answers []provider.Answer |
| 281 | } |
| 282 | |
| 283 | func (l *directAnswerLauncher) Respond(ctx context.Context, s provider.Session, a provider.Answer) error { |
| 284 | l.answers = append(l.answers, a) |
| 285 | return nil |
| 286 | } |
| 287 | func TestCodexApprovalResponseRouting(t *testing.T) { |
| 288 | b := directToolFixture(t) |
| 289 | p, e := OpenToolProxy(context.Background(), b) |
| 290 | mustJournal(t, e) |
| 291 | defer p.Close() |
| 292 | l := &directAnswerLauncher{} |
| 293 | relay := DirectQuestionRelay{Binding: b, Proxy: p, Launcher: l, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }} |
| 294 | for i, method := range []string{"mcpServer/elicitation/request", "item/commandExecution/requestApproval", "item/fileChange/requestApproval"} { |
| 295 | ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: fmt.Sprint(i), Payload: json.RawMessage(fmt.Sprintf(`{"id":%d,"method":%q,"params":{"threadId":"session","turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Which?"}}}`, i, method))} |
| 296 | ev = pinnedRunnerMCP(ev) |
| 297 | asked := 0 |
| 298 | mustJournal(t, relay.Handle(context.Background(), ev, func(ctx context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { |
| 299 | asked++ |
| 300 | if q.Validate() != nil || q.RawRequest == nil { |
| 301 | t.Fatal(q) |
| 302 | } |
| 303 | return runnerproto.QuestionAnswer{Behavior: "deny"}, nil |
| 304 | })) |
| 305 | if i == 0 { |
| 306 | if asked != 0 || l.answers[i].Behavior != "allow" || l.answers[i].Authorize == nil { |
| 307 | t.Fatal("Equipo MCP not validated", asked, l.answers) |
| 308 | } |
| 309 | } else if asked != 1 || l.answers[i].Behavior != "deny" { |
| 310 | t.Fatal("non-Equipo approval not relayed", asked, l.answers) |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | |
| 315 | func TestToolProxyLifecycle(t *testing.T) { |
| 316 | for _, cause := range []string{"cancel", "lease", "restart", "pending", "invalid"} { |
| 317 | t.Run(cause, func(t *testing.T) { |
| 318 | b := directToolFixture(t) |
| 319 | ctx, cancel := context.WithCancel(context.Background()) |
| 320 | defer cancel() |
| 321 | saved := b.Session |
| 322 | if cause == "pending" { |
| 323 | b.Session = provider.Session{} |
| 324 | b.TurnID = "" |
| 325 | } |
| 326 | p, e := OpenToolProxy(ctx, b) |
| 327 | mustJournal(t, e) |
| 328 | defer p.Close() |
| 329 | if cause == "pending" { |
| 330 | if p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)) == nil { |
| 331 | t.Fatal("unbound attempt accepted") |
| 332 | } |
| 333 | mustJournal(t, p.BindTurn(saved, "turn")) |
| 334 | mustJournal(t, p.submit(ctx, "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`))) |
| 335 | return |
| 336 | } |
| 337 | switch cause { |
| 338 | case "cancel": |
| 339 | cancel() |
| 340 | case "invalid": |
| 341 | p.broker.Invalidate() |
| 342 | case "lease": |
| 343 | p.broker.mu.Lock() |
| 344 | p.broker.binding.LeaseDeadline = time.Now().Add(-time.Second) |
| 345 | p.broker.mu.Unlock() |
| 346 | case "restart": |
| 347 | _, e = b.Journal.RecoverDirect(ctx) |
| 348 | mustJournal(t, e) |
| 349 | } |
| 350 | deadline := time.Now().Add(2 * time.Second) |
| 351 | for time.Now().Before(deadline) { |
| 352 | if _, e = os.Stat(p.SocketPath); os.IsNotExist(e) { |
| 353 | return |
| 354 | } |
| 355 | time.Sleep(10 * time.Millisecond) |
| 356 | } |
| 357 | t.Fatal("invalid endpoint remained live", cause) |
| 358 | }) |
| 359 | } |
| 360 | } |
| 361 | func TestCodexApprovalResponseChangedOriginal(t *testing.T) { |
| 362 | b := directToolFixture(t) |
| 363 | p, e := OpenToolProxy(context.Background(), b) |
| 364 | mustJournal(t, e) |
| 365 | defer p.Close() |
| 366 | l := &directAnswerLauncher{} |
| 367 | relay := DirectQuestionRelay{Binding: b, Proxy: p, Launcher: l} |
| 368 | ev := provider.Event{Kind: "request", SessionID: b.Session.ID, TurnID: b.TurnID, RequestID: "7", Payload: json.RawMessage(`{"id":7,"method":"mcpServer/elicitation/request","params":{"threadId":"session","turnId":"provider-turn","server":"equipo","tool":"ask_person","arguments":{"request_id":"r","question":"Original?"}}}`)} |
| 369 | ev = pinnedRunnerMCP(ev) |
| 370 | mustJournal(t, relay.Handle(context.Background(), ev, nil)) |
| 371 | changed := ev |
| 372 | changed.Payload = json.RawMessage(strings.Replace(string(ev.Payload), "Original?", "Changed?", 1)) |
| 373 | changed.ToolCall = json.RawMessage(strings.Replace(string(ev.ToolCall), "Original?", "Changed?", 1)) |
| 374 | if l.answers[0].Authorize(context.Background(), changed) == nil { |
| 375 | t.Fatal("changed arguments approved") |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | func TestToolProxyCannotExposeSecretsHostileFrames(t *testing.T) { |
| 380 | b := directToolFixture(t) |
| 381 | p, e := OpenToolProxy(context.Background(), b) |
| 382 | mustJournal(t, e) |
| 383 | defer p.Close() |
| 384 | for _, params := range []string{`{"name":"read_file","arguments":{"path":"/etc/passwd"}}`, `{"name":"publish","arguments":{"request_id":"r"}}`, `{"name":"ask_person","arguments":{"request_id":"r","question":"Hi?","fence":8}}`, `{"name":"ask_person","arguments":{"request_id":"r","question":"Hi?"},"capability":"steal"}`} { |
| 385 | var out strings.Builder |
| 386 | input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":` + params + "}\n" |
| 387 | mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath)) |
| 388 | if !strings.Contains(out.String(), `"error"`) || strings.Contains(out.String(), p.broker.capability.Secret) || strings.Contains(out.String(), b.Journal.path) { |
| 389 | t.Fatal("host authority leaked", out.String()) |
| 390 | } |
| 391 | } |
| 392 | } |
| 393 | func TestDirectStaleAnswerTurnAssociation(t *testing.T) { |
| 394 | b := directToolFixture(t) |
| 395 | ctx := context.Background() |
| 396 | c := &answerClient{} |
| 397 | r := QuestionRelay{Journal: b.Journal, Client: c, Agent: b.Agent, DirectSession: b.Session, TurnID: b.TurnID, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return b.LeaseDeadline, nil }} |
| 398 | q := runnerproto.Question{ID: "q", TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, ServerID: b.Agent.ServerID, AgentID: b.Agent.AgentID, SessionID: b.Session.ID, PermissionID: "same-id", Kind: "person", Revision: 1, ExpiresAt: b.LeaseDeadline, RawRequest: json.RawMessage(`{"id":"same-id","kind":"person","question":"Hi?"}`)} |
| 399 | mustJournal(t, r.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "deny"})) |
| 400 | _, e := b.Journal.db.Exec("UPDATE direct_turns SET state='completed'") |
| 401 | mustJournal(t, e) |
| 402 | turn := provider.Turn{ID: "next", AdmissionID: "next", Prompt: "next"} |
| 403 | mustJournal(t, b.Journal.BeginTurn(ctx, b.Session, turn)) |
| 404 | mustJournal(t, b.Journal.consumeTurn(ctx, b.Session.AttemptKey, b.Session.ID, "next")) |
| 405 | r.TurnID = "next" |
| 406 | if r.Deliver(ctx, q, runnerproto.QuestionAnswer{Behavior: "deny"}) == nil { |
| 407 | t.Fatal("previous turn answer reused in replacement turn") |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | func pinnedRunnerMCP(ev provider.Event) provider.Event { |
| 412 | var v map[string]any |
| 413 | _ = json.Unmarshal(ev.Payload, &v) |
| 414 | if v["method"] != "mcpServer/elicitation/request" { |
| 415 | return ev |
| 416 | } |
| 417 | p := v["params"].(map[string]any) |
| 418 | ev.ToolCall, _ = json.Marshal(map[string]any{"method": "item/started", "params": map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "item": map[string]any{"id": "item", "type": "mcpToolCall", "server": "equipo", "tool": p["tool"], "arguments": p["arguments"], "status": "inProgress"}}}) |
| 419 | v["params"] = map[string]any{"threadId": p["threadId"], "turnId": p["turnId"], "serverName": "equipo", "mode": "form", "message": "fixture", "requestedSchema": map[string]any{"type": "object", "properties": map[string]any{}}, "_meta": map[string]any{"codex_approval_kind": "mcp_tool_call", "tool_params": p["arguments"]}} |
| 420 | ev.Payload, _ = json.Marshal(v) |
| 421 | return ev |
| 422 | } |
| 423 | |
| 424 | func TestDirectToolScopedAskAnswer(t *testing.T) { |
| 425 | b := directToolFixture(t) |
| 426 | asked := 0 |
| 427 | b.Ask = func(ctx context.Context, bound ToolBinding, id string, args json.RawMessage) (json.RawMessage, error) { |
| 428 | relay := DirectQuestionRelay{Binding: bound, Current: func(context.Context, runnerproto.Question) (time.Time, error) { return bound.LeaseDeadline, nil }} |
| 429 | return relay.Ask(ctx, id, args, func(_ context.Context, q runnerproto.Question) (runnerproto.QuestionAnswer, error) { |
| 430 | asked++ |
| 431 | if q.Kind != "person" || q.SessionID != bound.Session.ID { |
| 432 | t.Fatal(q) |
| 433 | } |
| 434 | return runnerproto.QuestionAnswer{Behavior: "allow", UpdatedInput: json.RawMessage(`{"answers":{"answer":"blue"}}`)}, nil |
| 435 | }) |
| 436 | } |
| 437 | p, e := OpenToolProxy(context.Background(), b) |
| 438 | mustJournal(t, e) |
| 439 | defer p.Close() |
| 440 | input := `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{}}}` + "\n" + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask_person","arguments":{"request_id":"ask-1","question":"Which colour?"}}}` + "\n" |
| 441 | var out strings.Builder |
| 442 | mustJournal(t, ServeToolProxy(context.Background(), strings.NewReader(input), &out, p.SocketPath)) |
| 443 | if !strings.Contains(out.String(), "blue") || asked != 1 { |
| 444 | t.Fatal("scoped answer not returned", out.String(), asked) |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | func TestToolProxyBindBeforeDispatch(t *testing.T) { |
| 449 | b := directToolFixture(t) |
| 450 | saved := b.Session |
| 451 | _, e := b.Journal.db.Exec("UPDATE direct_turns SET state='completed'") |
| 452 | mustJournal(t, e) |
| 453 | b.Session = provider.Session{} |
| 454 | b.TurnID = "" |
| 455 | p, e := OpenToolProxy(context.Background(), b) |
| 456 | mustJournal(t, e) |
| 457 | defer p.Close() |
| 458 | mustJournal(t, p.BindTurn(saved, "next")) |
| 459 | turn := provider.Turn{ID: "next", AdmissionID: "next", Prompt: "next"} |
| 460 | mustJournal(t, b.Journal.BeginTurn(context.Background(), saved, turn)) |
| 461 | mustJournal(t, b.Journal.consumeTurn(context.Background(), saved.AttemptKey, saved.ID, "next")) |
| 462 | mustJournal(t, p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`))) |
| 463 | } |
| 464 | |
| 465 | func TestCodexApprovalResponseIdempotency(t *testing.T) { |
| 466 | b := directToolFixture(t) |
| 467 | p, e := OpenToolProxy(context.Background(), b) |
| 468 | mustJournal(t, e) |
| 469 | defer p.Close() |
| 470 | ctx := context.Background() |
| 471 | args := json.RawMessage(`{"question":"Original?"}`) |
| 472 | mustJournal(t, p.submit(ctx, "ask_person", "r", args)) |
| 473 | q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "ask_person", RequestID: "r", Arguments: args} |
| 474 | mustJournal(t, p.ValidateApproval(ctx, q)) |
| 475 | q.Arguments = json.RawMessage(`{"question":"Changed?"}`) |
| 476 | if p.ValidateApproval(ctx, q) == nil { |
| 477 | t.Fatal("changed replay arguments approved") |
| 478 | } |
| 479 | } |
| 480 | func TestToolProxyBindingIdentity(t *testing.T) { |
| 481 | for _, field := range []string{"account", "model", "provider", "session"} { |
| 482 | t.Run(field, func(t *testing.T) { |
| 483 | b := directToolFixture(t) |
| 484 | switch field { |
| 485 | case "account": |
| 486 | b.Session.AccountID = "other" |
| 487 | case "model": |
| 488 | b.Session.Model = "other" |
| 489 | case "provider": |
| 490 | b.Session.Provider = "claude" |
| 491 | b.Agent.Provider = "claude" |
| 492 | case "session": |
| 493 | b.Agent.ProviderSessionID = "other" |
| 494 | } |
| 495 | p, e := OpenToolProxy(context.Background(), b) |
| 496 | mustJournal(t, e) |
| 497 | defer p.Close() |
| 498 | if p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`)) == nil { |
| 499 | t.Fatal("mismatched bound identity", field) |
| 500 | } |
| 501 | }) |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | func TestCodexApprovalResponseToolAllowlist(t *testing.T) { |
| 506 | b := directToolFixture(t) |
| 507 | b.Tools = []string{"ask_person"} |
| 508 | p, e := OpenToolProxy(context.Background(), b) |
| 509 | mustJournal(t, e) |
| 510 | defer p.Close() |
| 511 | q := ToolSubmission{InstanceID: b.InstanceID, TaskID: b.TaskID, Attempt: b.Attempt, Fence: b.Fence, Agent: b.Agent, Name: "submit_candidate", RequestID: "r", Arguments: json.RawMessage(`{"commit":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}`)} |
| 512 | if p.ValidateApproval(context.Background(), q) == nil { |
| 513 | t.Fatal("valid but unscoped tool approved") |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | func TestToolProxyRenewedLease(t *testing.T) { |
| 518 | b := directToolFixture(t) |
| 519 | b.LeaseDeadline = time.Now().Add(150 * time.Millisecond) |
| 520 | p, e := OpenToolProxy(context.Background(), b) |
| 521 | mustJournal(t, e) |
| 522 | defer p.Close() |
| 523 | mustJournal(t, p.RenewLease(context.Background(), time.Now().Add(time.Second))) |
| 524 | time.Sleep(200 * time.Millisecond) |
| 525 | mustJournal(t, p.submit(context.Background(), "ask_person", "r", json.RawMessage(`{"question":"Hi?"}`))) |
| 526 | mustJournal(t, p.Close()) |
| 527 | if p.RenewLease(context.Background(), time.Now().Add(time.Minute)) == nil { |
| 528 | t.Fatal("closed lease revived") |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | func TestDirectAnswerProtocolError(t *testing.T) { |
| 533 | j, l, s, p := directFixture(t, "codex") |
| 534 | ctx := context.Background() |
| 535 | mustJournal(t, j.BeginTurn(ctx, s, directTurn())) |
| 536 | mustJournal(t, j.consumeTurn(ctx, s.AttemptKey, s.ID, "hello")) |
| 537 | c := &captureInput{journal: j, launch: l, process: p, input: p.Stdin(), ctx: ctx} |
| 538 | raw := []byte("{\"id\":7,\"error\":{\"code\":-32000,\"message\":\"provider_policy_rejected\"}}\n") |
| 539 | if _, err := c.WriteAnswer(ctx, s, "turn", raw); err != nil { |
| 540 | t.Fatal("protocol refusal cannot pass durable capture", err) |
| 541 | } |
| 542 | } |
| 543 | |