package opencode import ( "bufio" "context" "encoding/json" "errors" "io" "os" "path/filepath" "runtime" "strconv" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) // An OpenCode that stops reading its stdin cannot hold the runner: a // write gives up when its context ends, and the next waits its turn // without blocking the client. func TestClientWritesAreCancellable(t *testing.T) { stdinR, stdinW := io.Pipe() // nobody reads stdinR defer stdinR.Close() stdoutR, stdoutW := io.Pipe() defer stdoutW.Close() c := NewClient(stdoutR, stdinW) for range 2 { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) start := time.Now() err := c.Send(ctx, map[string]string{"method": "session/cancel"}) cancel() if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second { t.Fatalf("a write to a stdin nobody reads: %v after %v", err, time.Since(start)) } } } // The client keeps at most its byte budget of unread messages (OpenCode // waits for the rest), and a message over the size limit ends the // stream. func TestClientQueueIsBounded(t *testing.T) { stdoutR, stdoutW := io.Pipe() c := newClientLimits(stdoutR, io.Discard, 1000, 300) go func() { for range 20 { stdoutW.Write([]byte(`{"jsonrpc":"2.0","method":"session/update","params":{"x":"` + strings.Repeat("y", 60) + `"}}` + "\n")) } stdoutW.Write([]byte(strings.Repeat("z", 2000) + "\n")) stdoutW.Close() }() time.Sleep(200 * time.Millisecond) if q := c.queuedBytes(); q > 300+120 { t.Fatalf("%d bytes queued against a budget of 300", q) } n := 0 for m := range c.Messages { n++ c.Release(len(m)) } if n != 20 || !c.Closed() { t.Fatalf("%d messages, closed %v", n, c.Closed()) } } // stuckProcess is an OpenCode that answers initialize and session/new, // reads the prompt and asks a permission, then never reads its stdin // again. type stuckProcess struct { stdinR *io.PipeReader stdinW *io.PipeWriter stdoutR *io.PipeReader stdoutW *io.PipeWriter } func (p *stuckProcess) Stdin() io.WriteCloser { return p.stdinW } func (p *stuckProcess) Stdout() io.ReadCloser { return p.stdoutR } func (p *stuckProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("")) } func (p *stuckProcess) ID() string { return "stuck" } func (p *stuckProcess) Wait(ctx context.Context) (provider.Exit, error) { <-ctx.Done() return provider.Exit{}, ctx.Err() } type stuckHost struct{ p *stuckProcess } func (h stuckHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { go func() { r := bufio.NewReader(h.p.stdinR) answers := []string{ `{"protocolVersion":1,"agentInfo":{"name":"OpenCode","version":"` + Version + `"}}`, `{"sessionId":"ses_stuckstuckstuck","configOptions":[{"id":"model","currentValue":"equipo/glm-5.3"}]}`, } for _, a := range answers { line, err := r.ReadBytes('\n') if err != nil { return } var m struct { ID json.RawMessage `json:"id"` } json.Unmarshal(line, &m) h.p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":` + string(m.ID) + `,"result":` + a + "}\n")) } // The prompt is read; a permission request, then silence: stdin is // never read again. if _, err := r.ReadBytes('\n'); err != nil { return } 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")) }() return h.p, nil } // Interrupt is bounded by its context even when OpenCode reads nothing: // the run's end is the namespace's kill, never OpenCode's answer. func TestLauncherInterruptIsBounded(t *testing.T) { in := opencodePolicyFixture(t) p := &stuckProcess{} p.stdinR, p.stdinW = io.Pipe() p.stdoutR, p.stdoutW = io.Pipe() defer p.stdoutW.Close() l, _ := New(stuckHost{p}) sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) if err != nil { t.Fatal(err) } events, _ := l.Events(context.Background(), sess) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); err != nil { t.Fatal(err) } select { case e := <-events: if e.Kind != KindAsk { t.Fatalf("event %s", e.Kind) } case <-ctx.Done(): t.Fatal("no ask") } ictx, stop := context.WithTimeout(context.Background(), 200*time.Millisecond) defer stop() start := time.Now() if err := l.Interrupt(ictx, sess); err == nil || time.Since(start) > 2*time.Second { t.Fatalf("interrupt: %v after %v", err, time.Since(start)) } } // opencodePolicyFixture is a certified OpenCode policy on the fake // install (for the launcher's own checks; nothing is attested). func opencodePolicyFixture(t *testing.T) provider.Policy { t.Helper() inst := fakeInstall(t) root := t.TempDir() work := filepath.Join(root, "work") if err := os.Mkdir(work, 0700); err != nil { t.Fatal(err) } stand := copyTestBinary(t, filepath.Join(root, "bin"), "equipo-tool-proxy") 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"}}) if err != nil { t.Fatal(err) } t.Cleanup(cleanup) p, err := provider.BuildOpenCodePolicy(in) if err != nil { t.Fatal(err) } return p } // Security round finding 7: shutting the client down ends its reader even // with its queue full and nobody reading, and frees a write blocked on a // stdin nobody reads; nothing is sent after it. func TestClientShutdownWithFullQueues(t *testing.T) { // A small byte budget fills first; a large one lets the channel fill. for _, budget := range []int{300, 1 << 20} { t.Run(strconv.Itoa(budget), func(t *testing.T) { clientShutdown(t, budget) }) } } func clientShutdown(t *testing.T, budget int) { before := runtime.NumGoroutine() stdoutR, stdoutW := io.Pipe() stdinR, stdinW := io.Pipe() // nobody reads stdinR defer stdinR.Close() c := newClientLimits(stdoutR, stdinW, 1000, budget) go func() { for { if _, err := stdoutW.Write([]byte(`{"jsonrpc":"2.0","method":"session/update","params":{"x":"` + strings.Repeat("y", 60) + `"}}` + "\n")); err != nil { return } } }() time.Sleep(100 * time.Millisecond) blocked := make(chan error, 1) go func() { blocked <- c.Send(context.Background(), map[string]string{"method": "session/cancel"}) }() time.Sleep(100 * time.Millisecond) c.Shutdown() select { case err := <-blocked: if err == nil { t.Fatal("a blocked write reported success") } case <-time.After(2 * time.Second): t.Fatal("a blocked write outlived the shutdown") } if budget < 1<<20 { deadline := time.After(2 * time.Second) for range c.Messages { select { case <-deadline: t.Fatal("the reader outlived the shutdown") default: } } } // With the large budget nobody ever reads: the reader, blocked on its // full channel, must end by itself (the goroutine count below). if err := c.Send(context.Background(), map[string]string{"method": "x"}); !errors.Is(err, ErrClosed) { t.Fatalf("a send after the shutdown: %v", err) } stdoutW.Close() // The reader, the writer (blocked on the stdin nobody reads) and the // test's own producer are all gone. for end := time.Now().Add(2 * time.Second); runtime.NumGoroutine() > before; { if time.Now().After(end) { t.Fatalf("goroutines %d, before %d", runtime.NumGoroutine(), before) } time.Sleep(10 * time.Millisecond) } } // Security round finding 5: the client's writes are one goroutine and a // bounded queue: many writes to a stdin nobody reads start no goroutine // each, and a queue that is full refuses at once (TrySend). func TestClientWritesAreBounded(t *testing.T) { stdinR, stdinW := io.Pipe() // nobody reads stdinR defer stdinR.Close() stdoutR, stdoutW := io.Pipe() defer stdoutW.Close() c := NewClient(stdoutR, stdinW) defer c.Shutdown() before := runtime.NumGoroutine() refused := 0 for range 10_000 { if !c.TrySend(map[string]string{"method": "x"}) { refused++ } } for range 50 { ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) c.Send(ctx, map[string]string{"method": "y"}) cancel() } time.Sleep(50 * time.Millisecond) if n := runtime.NumGoroutine(); n > before+5 || refused < 10_000-maxPendingWrites-1 { t.Fatalf("goroutines %d then %d, %d refused", before, n, refused) } } // Security round finding 5: unsupported requests are refused through the // bounded writer, never a goroutine each; pending permission requests are // capped; nothing grows with what OpenCode sends while its stdin is not // read. func TestLauncherRequestsAreBounded(t *testing.T) { in := opencodePolicyFixture(t) p := &stuckProcess{} p.stdinR, p.stdinW = io.Pipe() p.stdoutR, p.stdoutW = io.Pipe() defer p.stdoutW.Close() l, _ := New(stuckHost{p}) sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) if err != nil { t.Fatal(err) } defer l.Close(context.Background(), sess) events, _ := l.Events(context.Background(), sess) go func() { for range events { } }() ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); err != nil { t.Fatal(err) } before := runtime.NumGoroutine() for i := range 5000 { p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":` + strconv.Itoa(1000+i) + `,"method":"fs/read_text_file","params":{"path":"/etc/passwd"}}` + "\n")) 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")) } time.Sleep(200 * time.Millisecond) s, _ := l.state(sess) s.mu.Lock() asks := len(s.asks) s.mu.Unlock() if n := runtime.NumGoroutine(); n > before+10 || asks > maxPendingAsks { t.Fatalf("goroutines %d then %d; %d pending asks", before, n, asks) } } // Security round finding 7: closing the session ends its reader even // when nobody reads its events and OpenCode keeps sending. func TestLauncherCloseFreesTheReader(t *testing.T) { in := opencodePolicyFixture(t) p := &stuckProcess{} p.stdinR, p.stdinW = io.Pipe() p.stdoutR, p.stdoutW = io.Pipe() defer p.stdoutW.Close() l, _ := New(stuckHost{p}) sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) if err != nil { t.Fatal(err) } events, _ := l.Events(context.Background(), sess) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); err != nil { t.Fatal(err) } go func() { for { 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 { return } } }() time.Sleep(200 * time.Millisecond) // events and queue fill; nobody reads l.Close(context.Background(), sess) time.Sleep(300 * time.Millisecond) // Nobody read before: the reader stopped at Close, so what is left is // at most what its channel held, then the channel is closed. n := 0 deadline := time.After(3 * time.Second) for { select { case _, ok := <-events: if !ok { if n > cap(events) { t.Fatalf("%d events after Close: the reader went on", n) } return } n++ case <-deadline: t.Fatal("the reader outlived Close") } } } // switchingHost is an OpenCode whose session's model option changes to // another model (a config_option_update) before it answers session/new, // then counts every byte written to it after that. type switchingHost struct { p *stuckProcess after chan int } func (h switchingHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { go func() { r := bufio.NewReader(h.p.stdinR) answers := []string{ `{"protocolVersion":1,"agentInfo":{"name":"OpenCode","version":"` + Version + `"}}`, `{"sessionId":"ses_switchswitchsw","configOptions":[{"id":"model","currentValue":"equipo/glm-5.3"}]}`, } for i, a := range answers { line, err := r.ReadBytes('\n') if err != nil { return } var m struct { ID json.RawMessage `json:"id"` } json.Unmarshal(line, &m) if i == 1 { 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")) } h.p.stdoutW.Write([]byte(`{"jsonrpc":"2.0","id":` + string(m.ID) + `,"result":` + a + "}\n")) } n := 0 buf := make([]byte, 4096) for { k, err := h.p.stdinR.Read(buf) n += k if err != nil { h.after <- n return } } }() return h.p, nil } // Security round #9 (ยง16.5): once OpenCode says the session's model is // another than the one Equipo fixed, no prompt is sent: StartTurn refuses // with ErrIdentity and writes nothing. func TestLauncherRefusesAChangedModel(t *testing.T) { in := opencodePolicyFixture(t) p := &stuckProcess{} p.stdinR, p.stdinW = io.Pipe() p.stdoutR, p.stdoutW = io.Pipe() defer p.stdoutW.Close() h := switchingHost{p: p, after: make(chan int, 1)} l, _ := New(h) sess, err := l.Open(context.Background(), provider.Launch{AttemptKey: "a", Selection: provider.Selection{Provider: "opencode-go", Model: "glm-5.3"}, Policy: in}) if err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := l.StartTurn(ctx, sess, provider.Turn{ID: "t", Prompt: "hello"}); !errors.Is(err, provider.ErrIdentity) { t.Fatalf("a prompt to a session whose model changed: %v", err) } time.Sleep(100 * time.Millisecond) p.stdinW.Close() if n := <-h.after; n != 0 { t.Fatalf("%d bytes written after the model changed", n) } }