| 1 | package opencode |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 18 | ) |
| 19 | |
| 20 | // An OpenCode that stops reading its stdin cannot hold the runner: a |
| 21 | // write gives up when its context ends, and the next waits its turn |
| 22 | // without blocking the client. |
| 23 | func TestClientWritesAreCancellable(t *testing.T) { |
| 24 | stdinR, stdinW := io.Pipe() // nobody reads stdinR |
| 25 | defer stdinR.Close() |
| 26 | stdoutR, stdoutW := io.Pipe() |
| 27 | defer stdoutW.Close() |
| 28 | c := NewClient(stdoutR, stdinW) |
| 29 | for range 2 { |
| 30 | ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 31 | start := time.Now() |
| 32 | err := c.Send(ctx, map[string]string{"method": "session/cancel"}) |
| 33 | cancel() |
| 34 | if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second { |
| 35 | t.Fatalf("a write to a stdin nobody reads: %v after %v", err, time.Since(start)) |
| 36 | } |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // The client keeps at most its byte budget of unread messages (OpenCode |
| 41 | // waits for the rest), and a message over the size limit ends the |
| 42 | // stream. |
| 43 | func TestClientQueueIsBounded(t *testing.T) { |
| 44 | stdoutR, stdoutW := io.Pipe() |
| 45 | c := newClientLimits(stdoutR, io.Discard, 1000, 300) |
| 46 | go func() { |
| 47 | for range 20 { |
| 48 | stdoutW.Write([]byte(`{"jsonrpc":"2.0","method":"session/update","params":{"x":"` + strings.Repeat("y", 60) + `"}}` + "\n")) |
| 49 | } |
| 50 | stdoutW.Write([]byte(strings.Repeat("z", 2000) + "\n")) |
| 51 | stdoutW.Close() |
| 52 | }() |
| 53 | time.Sleep(200 * time.Millisecond) |
| 54 | if q := c.queuedBytes(); q > 300+120 { |
| 55 | t.Fatalf("%d bytes queued against a budget of 300", q) |
| 56 | } |
| 57 | n := 0 |
| 58 | for m := range c.Messages { |
| 59 | n++ |
| 60 | c.Release(len(m)) |
| 61 | } |
| 62 | if n != 20 || !c.Closed() { |
| 63 | t.Fatalf("%d messages, closed %v", n, c.Closed()) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // stuckProcess is an OpenCode that answers initialize and session/new, |
| 68 | // reads the prompt and asks a permission, then never reads its stdin |
| 69 | // again. |
| 70 | type stuckProcess struct { |
| 71 | stdinR *io.PipeReader |
| 72 | stdinW *io.PipeWriter |
| 73 | stdoutR *io.PipeReader |
| 74 | stdoutW *io.PipeWriter |
| 75 | } |
| 76 | |
| 77 | func (p *stuckProcess) Stdin() io.WriteCloser { return p.stdinW } |
| 78 | func (p *stuckProcess) Stdout() io.ReadCloser { return p.stdoutR } |
| 79 | func (p *stuckProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("")) } |
| 80 | func (p *stuckProcess) ID() string { return "stuck" } |
| 81 | func (p *stuckProcess) Wait(ctx context.Context) (provider.Exit, error) { |
| 82 | <-ctx.Done() |
| 83 | return provider.Exit{}, ctx.Err() |
| 84 | } |
| 85 | |
| 86 | type stuckHost struct{ p *stuckProcess } |
| 87 | |
| 88 | func (h stuckHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { |
| 89 | go func() { |
| 90 | r := bufio.NewReader(h.p.stdinR) |
| 91 | answers := []string{ |
| 92 | `{"protocolVersion":1,"agentInfo":{"name":"OpenCode","version":"` + Version + `"}}`, |
| 93 | `{"sessionId":"ses_stuckstuckstuck","configOptions":[{"id":"model","currentValue":"equipo/glm-5.3"}]}`, |
| 94 | } |
| 95 | for _, a := range answers { |
| 96 | line, err := r.ReadBytes('\n') |
| 97 | if err != nil { |
| 98 | return |
| 99 | } |
| 100 | var m struct { |
| 101 | ID json.RawMessage `json:"id"` |
| 102 | } |
| 103 | json.Unmarshal(line, &m) |
| 104 | h.p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":` + string(m.ID) + `,"result":` + a + "}\n")) |
| 105 | } |
| 106 | // The prompt is read; a permission request, then silence: stdin is |
| 107 | // never read again. |
| 108 | if _, err := r.ReadBytes('\n'); err != nil { |
| 109 | return |
| 110 | } |
| 111 | h.p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":0,"method":"session/request_permission","params":{"sessionId":"ses_stuckstuckstuck","toolCall":{"toolCallId":"c1","name":"shell"},"options":[{"optionId":"reject","kind":"reject_once"}]}}` + "\n")) |
| 112 | }() |
| 113 | return h.p, nil |
| 114 | } |
| 115 | |
| 116 | // Interrupt is bounded by its context even when OpenCode reads nothing: |
| 117 | // the run's end is the namespace's kill, never OpenCode's answer. |
| 118 | func TestLauncherInterruptIsBounded(t *testing.T) { |
| 119 | in := opencodePolicyFixture(t) |
| 120 | p := &stuckProcess{} |
| 121 | p.stdinR, p.stdinW = io.Pipe() |
| 122 | p.stdoutR, p.stdoutW = io.Pipe() |
| 123 | defer p.stdoutW.Close() |
| 124 | l, _ := New(stuckHost{p}) |
| 125 | sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) |
| 126 | if err != nil { |
| 127 | t.Fatal(err) |
| 128 | } |
| 129 | events, _ := l.Events(context.Background(), sess) |
| 130 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 131 | defer cancel() |
| 132 | if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); err != nil { |
| 133 | t.Fatal(err) |
| 134 | } |
| 135 | select { |
| 136 | case e := <-events: |
| 137 | if e.Kind != KindAsk { |
| 138 | t.Fatalf("event %s", e.Kind) |
| 139 | } |
| 140 | case <-ctx.Done(): |
| 141 | t.Fatal("no ask") |
| 142 | } |
| 143 | ictx, stop := context.WithTimeout(context.Background(), 200*time.Millisecond) |
| 144 | defer stop() |
| 145 | start := time.Now() |
| 146 | if err := l.Interrupt(ictx, sess); err == nil || time.Since(start) > 2*time.Second { |
| 147 | t.Fatalf("interrupt: %v after %v", err, time.Since(start)) |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | // opencodePolicyFixture is a certified OpenCode policy on the fake |
| 152 | // install (for the launcher's own checks; nothing is attested). |
| 153 | func opencodePolicyFixture(t *testing.T) provider.Policy { |
| 154 | t.Helper() |
| 155 | inst := fakeInstall(t) |
| 156 | root := t.TempDir() |
| 157 | work := filepath.Join(root, "work") |
| 158 | if err := os.Mkdir(work, 0700); err != nil { |
| 159 | t.Fatal(err) |
| 160 | } |
| 161 | stand := copyTestBinary(t, filepath.Join(root, "bin"), "equipo-tool-proxy") |
| 162 | in, cleanup, err := Prepare(filepath.Join(root, "s"), Run{Install: inst, Bwrap: stand, ToolProxy: stand, Workspace: work, Action: "inspect", Provider: "opencode-go", Model: "glm-5.3", Equipo: []string{"submit_review"}, EgressHosts: []string{"opencode.ai"}}) |
| 163 | if err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | t.Cleanup(cleanup) |
| 167 | p, err := provider.BuildOpenCodePolicy(in) |
| 168 | if err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | return p |
| 172 | } |
| 173 | |
| 174 | // Security round finding 7: shutting the client down ends its reader even |
| 175 | // with its queue full and nobody reading, and frees a write blocked on a |
| 176 | // stdin nobody reads; nothing is sent after it. |
| 177 | func TestClientShutdownWithFullQueues(t *testing.T) { |
| 178 | // A small byte budget fills first; a large one lets the channel fill. |
| 179 | for _, budget := range []int{300, 1 << 20} { |
| 180 | t.Run(strconv.Itoa(budget), func(t *testing.T) { clientShutdown(t, budget) }) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func clientShutdown(t *testing.T, budget int) { |
| 185 | before := runtime.NumGoroutine() |
| 186 | stdoutR, stdoutW := io.Pipe() |
| 187 | stdinR, stdinW := io.Pipe() // nobody reads stdinR |
| 188 | defer stdinR.Close() |
| 189 | c := newClientLimits(stdoutR, stdinW, 1000, budget) |
| 190 | go func() { |
| 191 | for { |
| 192 | if _, err := stdoutW.Write([]byte(`{"jsonrpc":"2.0","method":"session/update","params":{"x":"` + strings.Repeat("y", 60) + `"}}` + "\n")); err != nil { |
| 193 | return |
| 194 | } |
| 195 | } |
| 196 | }() |
| 197 | time.Sleep(100 * time.Millisecond) |
| 198 | blocked := make(chan error, 1) |
| 199 | go func() { blocked <- c.Send(context.Background(), map[string]string{"method": "session/cancel"}) }() |
| 200 | time.Sleep(100 * time.Millisecond) |
| 201 | c.Shutdown() |
| 202 | select { |
| 203 | case err := <-blocked: |
| 204 | if err == nil { |
| 205 | t.Fatal("a blocked write reported success") |
| 206 | } |
| 207 | case <-time.After(2 * time.Second): |
| 208 | t.Fatal("a blocked write outlived the shutdown") |
| 209 | } |
| 210 | if budget < 1<<20 { |
| 211 | deadline := time.After(2 * time.Second) |
| 212 | for range c.Messages { |
| 213 | select { |
| 214 | case <-deadline: |
| 215 | t.Fatal("the reader outlived the shutdown") |
| 216 | default: |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | // With the large budget nobody ever reads: the reader, blocked on its |
| 221 | // full channel, must end by itself (the goroutine count below). |
| 222 | if err := c.Send(context.Background(), map[string]string{"method": "x"}); !errors.Is(err, ErrClosed) { |
| 223 | t.Fatalf("a send after the shutdown: %v", err) |
| 224 | } |
| 225 | stdoutW.Close() |
| 226 | // The reader, the writer (blocked on the stdin nobody reads) and the |
| 227 | // test's own producer are all gone. |
| 228 | for end := time.Now().Add(2 * time.Second); runtime.NumGoroutine() > before; { |
| 229 | if time.Now().After(end) { |
| 230 | t.Fatalf("goroutines %d, before %d", runtime.NumGoroutine(), before) |
| 231 | } |
| 232 | time.Sleep(10 * time.Millisecond) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // Security round finding 5: the client's writes are one goroutine and a |
| 237 | // bounded queue: many writes to a stdin nobody reads start no goroutine |
| 238 | // each, and a queue that is full refuses at once (TrySend). |
| 239 | func TestClientWritesAreBounded(t *testing.T) { |
| 240 | stdinR, stdinW := io.Pipe() // nobody reads stdinR |
| 241 | defer stdinR.Close() |
| 242 | stdoutR, stdoutW := io.Pipe() |
| 243 | defer stdoutW.Close() |
| 244 | c := NewClient(stdoutR, stdinW) |
| 245 | defer c.Shutdown() |
| 246 | before := runtime.NumGoroutine() |
| 247 | refused := 0 |
| 248 | for range 10_000 { |
| 249 | if !c.TrySend(map[string]string{"method": "x"}) { |
| 250 | refused++ |
| 251 | } |
| 252 | } |
| 253 | for range 50 { |
| 254 | ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) |
| 255 | c.Send(ctx, map[string]string{"method": "y"}) |
| 256 | cancel() |
| 257 | } |
| 258 | time.Sleep(50 * time.Millisecond) |
| 259 | if n := runtime.NumGoroutine(); n > before+5 || refused < 10_000-maxPendingWrites-1 { |
| 260 | t.Fatalf("goroutines %d then %d, %d refused", before, n, refused) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | // Security round finding 5: unsupported requests are refused through the |
| 265 | // bounded writer, never a goroutine each; pending permission requests are |
| 266 | // capped; nothing grows with what OpenCode sends while its stdin is not |
| 267 | // read. |
| 268 | func TestLauncherRequestsAreBounded(t *testing.T) { |
| 269 | in := opencodePolicyFixture(t) |
| 270 | p := &stuckProcess{} |
| 271 | p.stdinR, p.stdinW = io.Pipe() |
| 272 | p.stdoutR, p.stdoutW = io.Pipe() |
| 273 | defer p.stdoutW.Close() |
| 274 | l, _ := New(stuckHost{p}) |
| 275 | sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) |
| 276 | if err != nil { |
| 277 | t.Fatal(err) |
| 278 | } |
| 279 | defer l.Close(context.Background(), sess) |
| 280 | events, _ := l.Events(context.Background(), sess) |
| 281 | go func() { |
| 282 | for range events { |
| 283 | } |
| 284 | }() |
| 285 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 286 | defer cancel() |
| 287 | if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); err != nil { |
| 288 | t.Fatal(err) |
| 289 | } |
| 290 | before := runtime.NumGoroutine() |
| 291 | for i := range 5000 { |
| 292 | p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":` + strconv.Itoa(1000+i) + `,"method":"fs/read_text_file","params":{"path":"/etc/passwd"}}` + "\n")) |
| 293 | p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":"p` + strconv.Itoa(i) + `","method":"session/request_permission","params":{"sessionId":"ses_stuckstuckstuck","toolCall":{"toolCallId":"c` + strconv.Itoa(i) + `","name":"shell"},"options":[{"optionId":"reject","kind":"reject_once"}]}}` + "\n")) |
| 294 | } |
| 295 | time.Sleep(200 * time.Millisecond) |
| 296 | s, _ := l.state(sess) |
| 297 | s.mu.Lock() |
| 298 | asks := len(s.asks) |
| 299 | s.mu.Unlock() |
| 300 | if n := runtime.NumGoroutine(); n > before+10 || asks > maxPendingAsks { |
| 301 | t.Fatalf("goroutines %d then %d; %d pending asks", before, n, asks) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // Security round finding 7: closing the session ends its reader even |
| 306 | // when nobody reads its events and OpenCode keeps sending. |
| 307 | func TestLauncherCloseFreesTheReader(t *testing.T) { |
| 308 | in := opencodePolicyFixture(t) |
| 309 | p := &stuckProcess{} |
| 310 | p.stdinR, p.stdinW = io.Pipe() |
| 311 | p.stdoutR, p.stdoutW = io.Pipe() |
| 312 | defer p.stdoutW.Close() |
| 313 | l, _ := New(stuckHost{p}) |
| 314 | sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) |
| 315 | if err != nil { |
| 316 | t.Fatal(err) |
| 317 | } |
| 318 | events, _ := l.Events(context.Background(), sess) |
| 319 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 320 | defer cancel() |
| 321 | if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); err != nil { |
| 322 | t.Fatal(err) |
| 323 | } |
| 324 | go func() { |
| 325 | for { |
| 326 | if _, err := p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_stuckstuckstuck","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"x"}}}}` + "\n")); err != nil { |
| 327 | return |
| 328 | } |
| 329 | } |
| 330 | }() |
| 331 | time.Sleep(200 * time.Millisecond) // events and queue fill; nobody reads |
| 332 | l.Close(context.Background(), sess) |
| 333 | time.Sleep(300 * time.Millisecond) |
| 334 | // Nobody read before: the reader stopped at Close, so what is left is |
| 335 | // at most what its channel held, then the channel is closed. |
| 336 | n := 0 |
| 337 | deadline := time.After(3 * time.Second) |
| 338 | for { |
| 339 | select { |
| 340 | case _, ok := <-events: |
| 341 | if !ok { |
| 342 | if n > cap(events) { |
| 343 | t.Fatalf("%d events after Close: the reader went on", n) |
| 344 | } |
| 345 | return |
| 346 | } |
| 347 | n++ |
| 348 | case <-deadline: |
| 349 | t.Fatal("the reader outlived Close") |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | // switchingHost is an OpenCode whose session's model option changes to |
| 355 | // another model (a config_option_update) before it answers session/new, |
| 356 | // then counts every byte written to it after that. |
| 357 | type switchingHost struct { |
| 358 | p *stuckProcess |
| 359 | after chan int |
| 360 | } |
| 361 | |
| 362 | func (h switchingHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { |
| 363 | go func() { |
| 364 | r := bufio.NewReader(h.p.stdinR) |
| 365 | answers := []string{ |
| 366 | `{"protocolVersion":1,"agentInfo":{"name":"OpenCode","version":"` + Version + `"}}`, |
| 367 | `{"sessionId":"ses_switchswitchsw","configOptions":[{"id":"model","currentValue":"equipo/glm-5.3"}]}`, |
| 368 | } |
| 369 | for i, a := range answers { |
| 370 | line, err := r.ReadBytes('\n') |
| 371 | if err != nil { |
| 372 | return |
| 373 | } |
| 374 | var m struct { |
| 375 | ID json.RawMessage `json:"id"` |
| 376 | } |
| 377 | json.Unmarshal(line, &m) |
| 378 | if i == 1 { |
| 379 | h.p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_switchswitchsw","update":{"sessionUpdate":"config_option_update","configOptions":[{"id":"model","currentValue":"equipo/kimi-k3"}]}}}` + "\n")) |
| 380 | } |
| 381 | h.p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":` + string(m.ID) + `,"result":` + a + "}\n")) |
| 382 | } |
| 383 | n := 0 |
| 384 | buf := make([]byte, 4096) |
| 385 | for { |
| 386 | k, err := h.p.stdinR.Read(buf) |
| 387 | n += k |
| 388 | if err != nil { |
| 389 | h.after <- n |
| 390 | return |
| 391 | } |
| 392 | } |
| 393 | }() |
| 394 | return h.p, nil |
| 395 | } |
| 396 | |
| 397 | // Security round #9 (§16.5): once OpenCode says the session's model is |
| 398 | // another than the one Equipo fixed, no prompt is sent: StartTurn refuses |
| 399 | // with ErrIdentity and writes nothing. |
| 400 | func TestLauncherRefusesAChangedModel(t *testing.T) { |
| 401 | in := opencodePolicyFixture(t) |
| 402 | p := &stuckProcess{} |
| 403 | p.stdinR, p.stdinW = io.Pipe() |
| 404 | p.stdoutR, p.stdoutW = io.Pipe() |
| 405 | defer p.stdoutW.Close() |
| 406 | h := switchingHost{p: p, after: make(chan int, 1)} |
| 407 | l, _ := New(h) |
| 408 | sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) |
| 409 | if err != nil { |
| 410 | t.Fatal(err) |
| 411 | } |
| 412 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| 413 | defer cancel() |
| 414 | if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); !errors.Is(err, provider.ErrIdentity) { |
| 415 | t.Fatalf("a prompt to a session whose model changed: %v", err) |
| 416 | } |
| 417 | time.Sleep(100 * time.Millisecond) |
| 418 | p.stdinW.Close() |
| 419 | if n := <-h.after; n != 0 { |
| 420 | t.Fatalf("%d bytes written after the model changed", n) |
| 421 | } |
| 422 | } |
| 423 | |