package opencode import ( "bufio" "bytes" "context" "encoding/json" "fmt" "io" "net" "os" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/fakeopencode" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/pi" "amadan.net/oficina/equipo/internal/testci" ) // testKey is the key the tests deliver; the fake Go refuses any other. const testKey = fakeopencode.TestKey // toolServer is the runner's end of the attempt's tool socket: Equipo's // step tools over MCP, recording each call. type toolServer struct { path string mu sync.Mutex calls []string } func (s *toolServer) called() []string { s.mu.Lock() defer s.mu.Unlock() return append([]string(nil), s.calls...) } func startToolServer(t *testing.T, root string, tools []string) *toolServer { t.Helper() dir, err := os.MkdirTemp(root, "tool-") if err != nil { t.Fatal(err) } os.Chmod(dir, 0700) s := &toolServer{path: filepath.Join(dir, "equipo.sock")} ln, err := net.Listen("unix", s.path) if err != nil { t.Fatal(err) } os.Chmod(s.path, 0600) t.Cleanup(func() { ln.Close() }) go func() { for { c, err := ln.Accept() if err != nil { return } go s.serve(c, tools) } }() return s } func (s *toolServer) serve(c net.Conn, tools []string) { defer c.Close() r := bufio.NewReader(c) for { line, err := r.ReadBytes('\n') if err != nil { return } var q struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params struct { Name string `json:"name"` Arguments json.RawMessage `json:"arguments"` } `json:"params"` } if json.Unmarshal(line, &q) != nil || len(q.ID) == 0 { continue } var result any switch q.Method { case "initialize": result = map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo", "version": "1"}} case "tools/list": var list []any // Besides the role's tools, one no role pins: OpenCode must not // run it (its permission is the deny of everything). for _, name := range append(slices.Clone(tools), "merge_now") { list = append(list, map[string]any{"name": name, "description": "Equipo's " + name, "inputSchema": map[string]any{"type": "object"}}) } result = map[string]any{"tools": list} case "tools/call": s.mu.Lock() s.calls = append(s.calls, q.Params.Name+" "+string(q.Params.Arguments)) s.mu.Unlock() result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "Recorded."}}} default: raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "error": map[string]any{"code": -32601, "message": "no"}}) c.Write(append(raw, '\n')) continue } raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "result": result}) c.Write(append(raw, '\n')) } } // harness runs OpenCode (the real pinned one, or fakeopencode) in the // real containment: bubblewrap, the egress relay to opencode.ai only, // the key through the secret pipe, a fake Go behind the relay. type harness struct { t *testing.T manager *containment.Manager scratch string install Install proxy string keyHome string gofake *fakeopencode.Go // plant, when set, writes into a launch's runtime home before it // starts (a home-level configuration a switch must keep out). plant func(home string) } func copyTestBinary(t *testing.T, dir, name string) string { t.Helper() self, err := os.Executable() if err != nil { t.Fatal(err) } raw, err := os.ReadFile(self) if err != nil { t.Fatal(err) } p := filepath.Join(dir, name) if err := os.MkdirAll(dir, 0755); err != nil { t.Fatal(err) } if err := os.WriteFile(p, raw, 0755); err != nil { t.Fatal(err) } return p } // realInstall is the pinned OpenCode this machine has // (EQUIPO_OPENCODE_ROOT), or a skip, or on CI a failure. func realInstall(t *testing.T) Install { t.Helper() root := os.Getenv("EQUIPO_OPENCODE_ROOT") if root == "" { testci.Absent(t, "the pinned OpenCode (EQUIPO_OPENCODE_ROOT) is absent") } testci.Tools(t, "opencode") at, ok := At(root) if !ok { t.Skip("no OpenCode pins for this platform") } inst, ok := at.Pinned() if !ok { t.Skip("no OpenCode pins for this platform") } return inst } // fakeInstall is fakeopencode as the binary, a copy of this test binary // named opencode in a sealed tree, with its digests as the pins. func fakeInstall(t *testing.T) Install { t.Helper() tree := filepath.Join(t.TempDir(), "opencode", "node_modules") binary := copyTestBinary(t, filepath.Join(tree, "@opencode", "cli-test", "bin"), "opencode") if err := provider.SealTree(tree); err != nil { t.Fatal(err) } t.Cleanup(func() { removeTree(tree) }) sum, err := provider.TreeSHA256(tree) if err != nil { t.Fatal(err) } bin, err := provider.FileSHA256(binary) if err != nil { t.Fatal(err) } return Install{Tree: tree, Binary: binary, TreeSHA256: sum, BinarySHA256: bin} } func newHarness(t *testing.T, inst Install) *harness { t.Helper() testci.Tools(t, "bwrap") if _, err := os.Stat("/usr/bin/bwrap"); err != nil { testci.Absent(t, "bubblewrap is absent") } if !provider.TestCAAllowed() { t.Skip("needs -tags testbuild: the relay's route to the fake Go and its test authority") } // A short root: the tool socket's path must fit a socket address, // whatever the test's name. root, err := os.MkdirTemp("", "oc-") if err != nil { t.Fatal(err) } t.Cleanup(func() { removeTree(root) }) scratch := filepath.Join(root, "s") if err := os.Mkdir(scratch, 0700); err != nil { t.Fatal(err) } self, err := os.Executable() if err != nil { t.Fatal(err) } m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch}) if err != nil { testci.Absent(t, fmt.Sprintf("namespaces are unavailable here: %v", err)) } keyHome := filepath.Join(root, "opencode-go-abcdef012345") if err := os.Mkdir(keyHome, 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(testKey), 0600); err != nil { t.Fatal(err) } h := &harness{t: t, manager: m, scratch: scratch, install: inst, proxy: copyTestBinary(t, filepath.Join(root, "bin"), "equipo-tool-proxy"), keyHome: keyHome} h.gofake = fakeopencode.StartGo(t) return h } // run is one launch: OpenCode opened on the workspace for action, with // the step tools equipo served on its tool socket. type run struct { launcher *Launcher session provider.Session process provider.Process tools *toolServer home string events <-chan provider.Event host *teeHost kill context.CancelFunc } // teeHost keeps what the process writes on stderr, and a copy of what // it writes on stdout (every ACP message, for the probes). type teeHost struct { host provider.ProcessHost mu sync.Mutex err []byte out bytes.Buffer } func (h *teeHost) stderr() string { h.mu.Lock() defer h.mu.Unlock() return string(h.err) } func (h *teeHost) stdout() string { h.mu.Lock() defer h.mu.Unlock() return h.out.String() } type teeProcess struct { provider.Process out io.ReadCloser } func (p teeProcess) Stdout() io.ReadCloser { return p.out } func (p teeProcess) Contain(ctx context.Context) error { if c, ok := p.Process.(interface{ Contain(context.Context) error }); ok { return c.Contain(ctx) } return nil } // EgressDenials is how many connections the namespace's relay refused. func (p teeProcess) EgressDenials() uint64 { if d, ok := p.Process.(interface{ EgressDenials() uint64 }); ok { return d.EgressDenials() } return 0 } type writerFunc func([]byte) (int, error) func (f writerFunc) Write(b []byte) (int, error) { return f(b) } func (h *teeHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { p, err := h.host.Start(ctx, l, argv) if err != nil { return p, err } go func() { b := make([]byte, 4096) for { n, err := p.Stderr().Read(b) h.mu.Lock() if len(h.err) < 1<<20 { h.err = append(h.err, b[:n]...) } h.mu.Unlock() if err != nil { return } } }() tee := io.TeeReader(p.Stdout(), writerFunc(func(b []byte) (int, error) { h.mu.Lock() if h.out.Len() < 8<<20 { h.out.Write(b) } h.mu.Unlock() return len(b), nil })) return teeProcess{Process: p, out: io.NopCloser(tee)}, nil } func (h *harness) open(work, action string, equipo []string) *run { return h.openWith(work, action, equipo, "", "") } // openKept resumes session id from the database kept in dir. func (h *harness) openKept(work, action string, equipo []string, id, dir string) *run { return h.openWith(work, action, equipo, id, dir) } func (h *harness) openWith(work, action string, equipo []string, resume, kept string) *run { r, err := h.tryOpen(work, action, equipo, resume, kept) if err != nil { h.t.Fatal(err) } return r } func (h *harness) tryOpen(work, action string, equipo []string, resume, kept string) (*run, error) { t := h.t t.Helper() in, cleanup, err := Prepare(h.scratch, Run{Install: h.install, Bwrap: "/usr/bin/bwrap", ToolProxy: h.proxy, Workspace: work, Action: action, Provider: "opencode-go", Model: "glm-5.3", Equipo: equipo, Resume: resume, EgressHosts: egressHosts(t), ExtraCA: h.gofake.CA}) if err != nil { t.Fatal(err) } if kept != "" { if _, err := RestoreSession(kept, resume, in.Home); err != nil { t.Fatal(err) } } if h.plant != nil { h.plant(in.Home) } policy, err := provider.BuildOpenCodePolicy(in) if err != nil { t.Fatal(err) } tools := startToolServer(t, h.scratch, equipo) host := &teeHost{host: h.manager} l, _ := New(host) launch := provider.Launch{ToolSocket: tools.path, AttemptKey: "test/" + pi.NewSessionID(), Workspace: work, ResumeSessionID: resume, Selection: provider.Selection{ConnectionID: "opencode-go-abcdef012345", Provider: "opencode-go", Model: "glm-5.3", Family: Family("glm-5.3")}, Binding: provider.OpenCodeBinding("opencode-go-abcdef012345", in.Home, h.keyHome), Policy: policy} // The context Open gets is the attempt's lifetime: cancelling it // kills the namespace. ctx, kill := context.WithCancel(context.Background()) sess, err := l.Open(ctx, launch) if err != nil { kill() cleanup() time.Sleep(200 * time.Millisecond) return nil, fmt.Errorf("open: %v\n%s", err, host.stderr()) } proc, _ := l.Process(sess) events, _ := l.Events(context.Background(), sess) r := &run{launcher: l, session: sess, process: proc, tools: tools, home: in.Home, events: events, host: host, kill: kill} t.Cleanup(func() { r.stop(t) kill() cleanup() }) return r, nil } func egressHosts(t *testing.T) []string { p, err := egress.ProviderPolicy(provider.NetworkContract{Provider: "opencode-go", Harness: "opencode"}, false) if err != nil { t.Fatal(err) } return p.Hosts } func eventKinds(evs []provider.Event) string { var k []string for _, e := range evs { k = append(k, e.Kind) } return strings.Join(k, ",") } // prompt sends one prompt and collects its events to its end, answering // every ask with answer. func (r *run) prompt(t *testing.T, text, answer string) []provider.Event { t.Helper() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) defer cancel() if err := r.launcher.StartTurn(ctx, r.session, provider.Turn{ID: pi.NewSessionID(), Prompt: text}); err != nil { t.Fatalf("prompt: %v\n%s", err, r.host.stderr()) } var out []provider.Event for { select { case <-ctx.Done(): t.Fatalf("no end; events %v\n%s", eventKinds(out), r.host.stderr()) case e, ok := <-r.events: if !ok { t.Fatalf("OpenCode ended; events %v\n%s", eventKinds(out), r.host.stderr()) } out = append(out, e) if e.Kind == KindAsk { if err := r.launcher.Respond(ctx, r.session, provider.Answer{RequestID: e.RequestID, Behavior: answer}); err != nil { t.Fatal(err) } } if e.Kind == KindDone { return out } } } } // stop closes OpenCode's stdin, kills the namespace and waits for its // proof. func (r *run) stop(t *testing.T) error { if r.process == nil { return nil } r.launcher.Close(context.Background(), r.session) r.kill() ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if c, ok := r.process.(interface{ Contain(context.Context) error }); ok { c.Contain(ctx) } _, err := r.process.Wait(ctx) r.process = nil return err } func doneOf(t *testing.T, evs []provider.Event) pi.Done { t.Helper() var d pi.Done if len(evs) == 0 || evs[len(evs)-1].Kind != KindDone || json.Unmarshal(evs[len(evs)-1].Payload, &d) != nil { t.Fatalf("no done: %v", eventKinds(evs)) } return d } func tallyOf(evs []provider.Event) *Tally { t := &Tally{} for _, e := range evs { t.Add(e) } return t } // fakeopencode in the real containment: a Review run reaches its one // Equipo tool through the tool socket, reports its usage and ends; the // session is kept, and a question resumes it in a new process. func TestOpenCodeFakeReviewInNamespace(t *testing.T) { h := newHarness(t, fakeInstall(t)) work := t.TempDir() r := h.open(work, "inspect", []string{"submit_review", "ask_person"}) evs := r.prompt(t, "[Equipo: review] Review this.", "deny") tally := tallyOf(evs) row := tally.Row() if !row.Complete || row.Model != "glm-5.3" || *row.InputTokens != 120 || *row.CachedInputTokens != 80 || *row.OutputTokens != 14 { t.Fatalf("usage %+v; events %v", row, eventKinds(evs)) } calls := r.tools.called() if len(calls) != 1 || !strings.HasPrefix(calls[0], "submit_review ") { t.Fatalf("tool calls %v", calls) } if d := doneOf(t, evs); d.Status != pi.StatusCompleted { t.Fatalf("done %+v", d) } if err := r.stop(t); err != nil { t.Fatalf("exit not proven: %v", err) } kept := filepath.Join(t.TempDir(), "kept") if n, err := KeepSession(r.home, r.session.ID, kept, 0); err != nil || n == 0 || !HasSession(kept, r.session.ID) { t.Fatalf("session not kept: %d %v", n, err) } again := h.openKept(t.TempDir(), "answer", []string{"git_log"}, r.session.ID, kept) evs = again.prompt(t, "[Equipo: question] What did you check?", "deny") text := "" for _, e := range evs { if e.Kind == KindDelta { var d pi.Delta json.Unmarshal(e.Payload, &d) text += d.Text } } if !strings.Contains(text, "message 3") { t.Fatalf("the resumed session lost its history (or replayed it as this turn's): %q", text) } } // The kept database is copied without following a link: a run that // replaced it with a link to another file keeps nothing. func TestKeepSessionRefusesLinks(t *testing.T) { home := t.TempDir() data := filepath.Join(home, ".local", "share", "opencode") os.MkdirAll(data, 0700) secret := filepath.Join(t.TempDir(), "secret") os.WriteFile(secret, []byte("the key"), 0600) os.Symlink(secret, filepath.Join(data, "opencode.db")) kept := t.TempDir() if _, err := KeepSession(home, "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa", kept, 0); err == nil || HasSession(kept, "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa") { t.Fatalf("a link was kept: %v", err) } os.Remove(filepath.Join(data, "opencode.db")) os.WriteFile(filepath.Join(data, "opencode.db"), []byte("db"), 0600) os.Symlink(secret, filepath.Join(data, "opencode.db-wal")) if _, err := KeepSession(home, "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa", kept, 0); err == nil { t.Fatal("a linked journal was kept") } if _, err := KeepSession(home, "../ses_x", kept, 0); err == nil { t.Fatal("a session id that is a path was kept") } } // Security round finding 1: the kept database is copied through the // runtime home's own directories, never a link in any of them: a run // that replaced .local, .local/share or .local/share/opencode with a link // to a host directory keeps nothing from it. func TestKeepSessionRefusesLinkedDirectories(t *testing.T) { const id = "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa" host := t.TempDir() os.WriteFile(filepath.Join(host, "opencode.db"), []byte("a host database"), 0600) os.MkdirAll(filepath.Join(host, "share", "opencode"), 0700) os.WriteFile(filepath.Join(host, "share", "opencode", "opencode.db"), []byte("a host database"), 0600) os.MkdirAll(filepath.Join(host, "local", "share", "opencode"), 0700) os.WriteFile(filepath.Join(host, "local", "share", "opencode", "opencode.db"), []byte("a host database"), 0600) for name, plant := range map[string]func(home string){ "opencode": func(home string) { os.MkdirAll(filepath.Join(home, ".local", "share"), 0700) os.Symlink(host, filepath.Join(home, ".local", "share", "opencode")) }, "share": func(home string) { os.MkdirAll(filepath.Join(home, ".local"), 0700) os.Symlink(filepath.Join(host, "share"), filepath.Join(home, ".local", "share")) }, ".local": func(home string) { os.Symlink(filepath.Join(host, "local"), filepath.Join(home, ".local")) }, } { home := t.TempDir() plant(home) kept := t.TempDir() if _, err := KeepSession(home, id, kept, 0); err == nil || HasSession(kept, id) { t.Errorf("%s linked: kept a host database (%v)", name, err) } } // Restoring follows no link in the kept directory either. kept := t.TempDir() os.MkdirAll(filepath.Join(kept, "opencode"), 0700) os.Symlink(filepath.Join(host, "share", "opencode"), filepath.Join(kept, "opencode", id)) if _, err := RestoreSession(kept, id, t.TempDir()); err == nil { t.Error("restored through a linked kept directory") } }