| 1 | package opencode |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/fakeopencode" |
| 20 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 21 | "amadan.net/oficina/equipo/internal/runner/egress" |
| 22 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 23 | "amadan.net/oficina/equipo/internal/runner/provider/pi" |
| 24 | "amadan.net/oficina/equipo/internal/testci" |
| 25 | ) |
| 26 | |
| 27 | // testKey is the key the tests deliver; the fake Go refuses any other. |
| 28 | const testKey = fakeopencode.TestKey |
| 29 | |
| 30 | // toolServer is the runner's end of the attempt's tool socket: Equipo's |
| 31 | // step tools over MCP, recording each call. |
| 32 | type toolServer struct { |
| 33 | path string |
| 34 | mu sync.Mutex |
| 35 | calls []string |
| 36 | } |
| 37 | |
| 38 | func (s *toolServer) called() []string { |
| 39 | s.mu.Lock() |
| 40 | defer s.mu.Unlock() |
| 41 | return append([]string(nil), s.calls...) |
| 42 | } |
| 43 | |
| 44 | func startToolServer(t *testing.T, root string, tools []string) *toolServer { |
| 45 | t.Helper() |
| 46 | dir, err := os.MkdirTemp(root, "tool-") |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | os.Chmod(dir, 0700) |
| 51 | s := &toolServer{path: filepath.Join(dir, "equipo.sock")} |
| 52 | ln, err := net.Listen("unix", s.path) |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | os.Chmod(s.path, 0600) |
| 57 | t.Cleanup(func() { ln.Close() }) |
| 58 | go func() { |
| 59 | for { |
| 60 | c, err := ln.Accept() |
| 61 | if err != nil { |
| 62 | return |
| 63 | } |
| 64 | go s.serve(c, tools) |
| 65 | } |
| 66 | }() |
| 67 | return s |
| 68 | } |
| 69 | |
| 70 | func (s *toolServer) serve(c net.Conn, tools []string) { |
| 71 | defer c.Close() |
| 72 | r := bufio.NewReader(c) |
| 73 | for { |
| 74 | line, err := r.ReadBytes('\n') |
| 75 | if err != nil { |
| 76 | return |
| 77 | } |
| 78 | var q struct { |
| 79 | ID json.RawMessage `json:"id"` |
| 80 | Method string `json:"method"` |
| 81 | Params struct { |
| 82 | Name string `json:"name"` |
| 83 | Arguments json.RawMessage `json:"arguments"` |
| 84 | } `json:"params"` |
| 85 | } |
| 86 | if json.Unmarshal(line, &q) != nil || len(q.ID) == 0 { |
| 87 | continue |
| 88 | } |
| 89 | var result any |
| 90 | switch q.Method { |
| 91 | case "initialize": |
| 92 | result = map[string]any{"protocolVersion": "2025-06-18", "capabilities": map[string]any{"tools": map[string]any{}}, "serverInfo": map[string]any{"name": "equipo", "version": "1"}} |
| 93 | case "tools/list": |
| 94 | var list []any |
| 95 | // Besides the role's tools, one no role pins: OpenCode must not |
| 96 | // run it (its permission is the deny of everything). |
| 97 | for _, name := range append(slices.Clone(tools), "merge_now") { |
| 98 | list = append(list, map[string]any{"name": name, "description": "Equipo's " + name, "inputSchema": map[string]any{"type": "object"}}) |
| 99 | } |
| 100 | result = map[string]any{"tools": list} |
| 101 | case "tools/call": |
| 102 | s.mu.Lock() |
| 103 | s.calls = append(s.calls, q.Params.Name+" "+string(q.Params.Arguments)) |
| 104 | s.mu.Unlock() |
| 105 | result = map[string]any{"content": []any{map[string]any{"type": "text", "text": "Recorded."}}} |
| 106 | default: |
| 107 | raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "error": map[string]any{"code": -32601, "message": "no"}}) |
| 108 | c.Write(append(raw, '\n')) |
| 109 | continue |
| 110 | } |
| 111 | raw, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": q.ID, "result": result}) |
| 112 | c.Write(append(raw, '\n')) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | // harness runs OpenCode (the real pinned one, or fakeopencode) in the |
| 117 | // real containment: bubblewrap, the egress relay to opencode.ai only, |
| 118 | // the key through the secret pipe, a fake Go behind the relay. |
| 119 | type harness struct { |
| 120 | t *testing.T |
| 121 | manager *containment.Manager |
| 122 | scratch string |
| 123 | install Install |
| 124 | proxy string |
| 125 | keyHome string |
| 126 | gofake *fakeopencode.Go |
| 127 | // plant, when set, writes into a launch's runtime home before it |
| 128 | // starts (a home-level configuration a switch must keep out). |
| 129 | plant func(home string) |
| 130 | } |
| 131 | |
| 132 | func copyTestBinary(t *testing.T, dir, name string) string { |
| 133 | t.Helper() |
| 134 | self, err := os.Executable() |
| 135 | if err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | raw, err := os.ReadFile(self) |
| 139 | if err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | p := filepath.Join(dir, name) |
| 143 | if err := os.MkdirAll(dir, 0755); err != nil { |
| 144 | t.Fatal(err) |
| 145 | } |
| 146 | if err := os.WriteFile(p, raw, 0755); err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | return p |
| 150 | } |
| 151 | |
| 152 | // realInstall is the pinned OpenCode this machine has |
| 153 | // (EQUIPO_OPENCODE_ROOT), or a skip, or on CI a failure. |
| 154 | func realInstall(t *testing.T) Install { |
| 155 | t.Helper() |
| 156 | root := os.Getenv("EQUIPO_OPENCODE_ROOT") |
| 157 | if root == "" { |
| 158 | testci.Absent(t, "the pinned OpenCode (EQUIPO_OPENCODE_ROOT) is absent") |
| 159 | } |
| 160 | testci.Tools(t, "opencode") |
| 161 | at, ok := At(root) |
| 162 | if !ok { |
| 163 | t.Skip("no OpenCode pins for this platform") |
| 164 | } |
| 165 | inst, ok := at.Pinned() |
| 166 | if !ok { |
| 167 | t.Skip("no OpenCode pins for this platform") |
| 168 | } |
| 169 | return inst |
| 170 | } |
| 171 | |
| 172 | // fakeInstall is fakeopencode as the binary, a copy of this test binary |
| 173 | // named opencode in a sealed tree, with its digests as the pins. |
| 174 | func fakeInstall(t *testing.T) Install { |
| 175 | t.Helper() |
| 176 | tree := filepath.Join(t.TempDir(), "opencode", "node_modules") |
| 177 | binary := copyTestBinary(t, filepath.Join(tree, "@opencode", "cli-test", "bin"), "opencode") |
| 178 | if err := provider.SealTree(tree); err != nil { |
| 179 | t.Fatal(err) |
| 180 | } |
| 181 | t.Cleanup(func() { removeTree(tree) }) |
| 182 | sum, err := provider.TreeSHA256(tree) |
| 183 | if err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | bin, err := provider.FileSHA256(binary) |
| 187 | if err != nil { |
| 188 | t.Fatal(err) |
| 189 | } |
| 190 | return Install{Tree: tree, Binary: binary, TreeSHA256: sum, BinarySHA256: bin} |
| 191 | } |
| 192 | |
| 193 | func newHarness(t *testing.T, inst Install) *harness { |
| 194 | t.Helper() |
| 195 | testci.Tools(t, "bwrap") |
| 196 | if _, err := os.Stat("/usr/bin/bwrap"); err != nil { |
| 197 | testci.Absent(t, "bubblewrap is absent") |
| 198 | } |
| 199 | if !provider.TestCAAllowed() { |
| 200 | t.Skip("needs -tags testbuild: the relay's route to the fake Go and its test authority") |
| 201 | } |
| 202 | // A short root: the tool socket's path must fit a socket address, |
| 203 | // whatever the test's name. |
| 204 | root, err := os.MkdirTemp("", "oc-") |
| 205 | if err != nil { |
| 206 | t.Fatal(err) |
| 207 | } |
| 208 | t.Cleanup(func() { removeTree(root) }) |
| 209 | scratch := filepath.Join(root, "s") |
| 210 | if err := os.Mkdir(scratch, 0700); err != nil { |
| 211 | t.Fatal(err) |
| 212 | } |
| 213 | self, err := os.Executable() |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | m, err := containment.New(containment.Config{Binary: "/usr/bin/bwrap", RunnerBinary: self, ScratchRoot: scratch}) |
| 218 | if err != nil { |
| 219 | testci.Absent(t, fmt.Sprintf("namespaces are unavailable here: %v", err)) |
| 220 | } |
| 221 | keyHome := filepath.Join(root, "opencode-go-abcdef012345") |
| 222 | if err := os.Mkdir(keyHome, 0700); err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | if err := os.WriteFile(filepath.Join(keyHome, provider.TokenFile), []byte(testKey), 0600); err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | h := &harness{t: t, manager: m, scratch: scratch, install: inst, proxy: copyTestBinary(t, filepath.Join(root, "bin"), "equipo-tool-proxy"), keyHome: keyHome} |
| 229 | h.gofake = fakeopencode.StartGo(t) |
| 230 | return h |
| 231 | } |
| 232 | |
| 233 | // run is one launch: OpenCode opened on the workspace for action, with |
| 234 | // the step tools equipo served on its tool socket. |
| 235 | type run struct { |
| 236 | launcher *Launcher |
| 237 | session provider.Session |
| 238 | process provider.Process |
| 239 | tools *toolServer |
| 240 | home string |
| 241 | events <-chan provider.Event |
| 242 | host *teeHost |
| 243 | kill context.CancelFunc |
| 244 | } |
| 245 | |
| 246 | // teeHost keeps what the process writes on stderr, and a copy of what |
| 247 | // it writes on stdout (every ACP message, for the probes). |
| 248 | type teeHost struct { |
| 249 | host provider.ProcessHost |
| 250 | mu sync.Mutex |
| 251 | err []byte |
| 252 | out bytes.Buffer |
| 253 | } |
| 254 | |
| 255 | func (h *teeHost) stderr() string { |
| 256 | h.mu.Lock() |
| 257 | defer h.mu.Unlock() |
| 258 | return string(h.err) |
| 259 | } |
| 260 | |
| 261 | func (h *teeHost) stdout() string { |
| 262 | h.mu.Lock() |
| 263 | defer h.mu.Unlock() |
| 264 | return h.out.String() |
| 265 | } |
| 266 | |
| 267 | type teeProcess struct { |
| 268 | provider.Process |
| 269 | out io.ReadCloser |
| 270 | } |
| 271 | |
| 272 | func (p teeProcess) Stdout() io.ReadCloser { return p.out } |
| 273 | |
| 274 | func (p teeProcess) Contain(ctx context.Context) error { |
| 275 | if c, ok := p.Process.(interface{ Contain(context.Context) error }); ok { |
| 276 | return c.Contain(ctx) |
| 277 | } |
| 278 | return nil |
| 279 | } |
| 280 | |
| 281 | // EgressDenials is how many connections the namespace's relay refused. |
| 282 | func (p teeProcess) EgressDenials() uint64 { |
| 283 | if d, ok := p.Process.(interface{ EgressDenials() uint64 }); ok { |
| 284 | return d.EgressDenials() |
| 285 | } |
| 286 | return 0 |
| 287 | } |
| 288 | |
| 289 | type writerFunc func([]byte) (int, error) |
| 290 | |
| 291 | func (f writerFunc) Write(b []byte) (int, error) { return f(b) } |
| 292 | |
| 293 | func (h *teeHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) { |
| 294 | p, err := h.host.Start(ctx, l, argv) |
| 295 | if err != nil { |
| 296 | return p, err |
| 297 | } |
| 298 | go func() { |
| 299 | b := make([]byte, 4096) |
| 300 | for { |
| 301 | n, err := p.Stderr().Read(b) |
| 302 | h.mu.Lock() |
| 303 | if len(h.err) < 1<<20 { |
| 304 | h.err = append(h.err, b[:n]...) |
| 305 | } |
| 306 | h.mu.Unlock() |
| 307 | if err != nil { |
| 308 | return |
| 309 | } |
| 310 | } |
| 311 | }() |
| 312 | tee := io.TeeReader(p.Stdout(), writerFunc(func(b []byte) (int, error) { |
| 313 | h.mu.Lock() |
| 314 | if h.out.Len() < 8<<20 { |
| 315 | h.out.Write(b) |
| 316 | } |
| 317 | h.mu.Unlock() |
| 318 | return len(b), nil |
| 319 | })) |
| 320 | return teeProcess{Process: p, out: io.NopCloser(tee)}, nil |
| 321 | } |
| 322 | |
| 323 | func (h *harness) open(work, action string, equipo []string) *run { |
| 324 | return h.openWith(work, action, equipo, "", "") |
| 325 | } |
| 326 | |
| 327 | // openKept resumes session id from the database kept in dir. |
| 328 | func (h *harness) openKept(work, action string, equipo []string, id, dir string) *run { |
| 329 | return h.openWith(work, action, equipo, id, dir) |
| 330 | } |
| 331 | |
| 332 | func (h *harness) openWith(work, action string, equipo []string, resume, kept string) *run { |
| 333 | r, err := h.tryOpen(work, action, equipo, resume, kept) |
| 334 | if err != nil { |
| 335 | h.t.Fatal(err) |
| 336 | } |
| 337 | return r |
| 338 | } |
| 339 | |
| 340 | func (h *harness) tryOpen(work, action string, equipo []string, resume, kept string) (*run, error) { |
| 341 | t := h.t |
| 342 | t.Helper() |
| 343 | 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}) |
| 344 | if err != nil { |
| 345 | t.Fatal(err) |
| 346 | } |
| 347 | if kept != "" { |
| 348 | if _, err := RestoreSession(kept, resume, in.Home); err != nil { |
| 349 | t.Fatal(err) |
| 350 | } |
| 351 | } |
| 352 | if h.plant != nil { |
| 353 | h.plant(in.Home) |
| 354 | } |
| 355 | policy, err := provider.BuildOpenCodePolicy(in) |
| 356 | if err != nil { |
| 357 | t.Fatal(err) |
| 358 | } |
| 359 | tools := startToolServer(t, h.scratch, equipo) |
| 360 | host := &teeHost{host: h.manager} |
| 361 | l, _ := New(host) |
| 362 | 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} |
| 363 | // The context Open gets is the attempt's lifetime: cancelling it |
| 364 | // kills the namespace. |
| 365 | ctx, kill := context.WithCancel(context.Background()) |
| 366 | sess, err := l.Open(ctx, launch) |
| 367 | if err != nil { |
| 368 | kill() |
| 369 | cleanup() |
| 370 | time.Sleep(200 * time.Millisecond) |
| 371 | return nil, fmt.Errorf("open: %v\n%s", err, host.stderr()) |
| 372 | } |
| 373 | proc, _ := l.Process(sess) |
| 374 | events, _ := l.Events(context.Background(), sess) |
| 375 | r := &run{launcher: l, session: sess, process: proc, tools: tools, home: in.Home, events: events, host: host, kill: kill} |
| 376 | t.Cleanup(func() { |
| 377 | r.stop(t) |
| 378 | kill() |
| 379 | cleanup() |
| 380 | }) |
| 381 | return r, nil |
| 382 | } |
| 383 | |
| 384 | func egressHosts(t *testing.T) []string { |
| 385 | p, err := egress.ProviderPolicy(provider.NetworkContract{Provider: "opencode-go", Harness: "opencode"}, false) |
| 386 | if err != nil { |
| 387 | t.Fatal(err) |
| 388 | } |
| 389 | return p.Hosts |
| 390 | } |
| 391 | |
| 392 | func eventKinds(evs []provider.Event) string { |
| 393 | var k []string |
| 394 | for _, e := range evs { |
| 395 | k = append(k, e.Kind) |
| 396 | } |
| 397 | return strings.Join(k, ",") |
| 398 | } |
| 399 | |
| 400 | // prompt sends one prompt and collects its events to its end, answering |
| 401 | // every ask with answer. |
| 402 | func (r *run) prompt(t *testing.T, text, answer string) []provider.Event { |
| 403 | t.Helper() |
| 404 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) |
| 405 | defer cancel() |
| 406 | if err := r.launcher.StartTurn(ctx, r.session, provider.Turn{ID: pi.NewSessionID(), Prompt: text}); err != nil { |
| 407 | t.Fatalf("prompt: %v\n%s", err, r.host.stderr()) |
| 408 | } |
| 409 | var out []provider.Event |
| 410 | for { |
| 411 | select { |
| 412 | case <-ctx.Done(): |
| 413 | t.Fatalf("no end; events %v\n%s", eventKinds(out), r.host.stderr()) |
| 414 | case e, ok := <-r.events: |
| 415 | if !ok { |
| 416 | t.Fatalf("OpenCode ended; events %v\n%s", eventKinds(out), r.host.stderr()) |
| 417 | } |
| 418 | out = append(out, e) |
| 419 | if e.Kind == KindAsk { |
| 420 | if err := r.launcher.Respond(ctx, r.session, provider.Answer{RequestID: e.RequestID, Behavior: answer}); err != nil { |
| 421 | t.Fatal(err) |
| 422 | } |
| 423 | } |
| 424 | if e.Kind == KindDone { |
| 425 | return out |
| 426 | } |
| 427 | } |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | // stop closes OpenCode's stdin, kills the namespace and waits for its |
| 432 | // proof. |
| 433 | func (r *run) stop(t *testing.T) error { |
| 434 | if r.process == nil { |
| 435 | return nil |
| 436 | } |
| 437 | r.launcher.Close(context.Background(), r.session) |
| 438 | r.kill() |
| 439 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 440 | defer cancel() |
| 441 | if c, ok := r.process.(interface{ Contain(context.Context) error }); ok { |
| 442 | c.Contain(ctx) |
| 443 | } |
| 444 | _, err := r.process.Wait(ctx) |
| 445 | r.process = nil |
| 446 | return err |
| 447 | } |
| 448 | |
| 449 | func doneOf(t *testing.T, evs []provider.Event) pi.Done { |
| 450 | t.Helper() |
| 451 | var d pi.Done |
| 452 | if len(evs) == 0 || evs[len(evs)-1].Kind != KindDone || json.Unmarshal(evs[len(evs)-1].Payload, &d) != nil { |
| 453 | t.Fatalf("no done: %v", eventKinds(evs)) |
| 454 | } |
| 455 | return d |
| 456 | } |
| 457 | |
| 458 | func tallyOf(evs []provider.Event) *Tally { |
| 459 | t := &Tally{} |
| 460 | for _, e := range evs { |
| 461 | t.Add(e) |
| 462 | } |
| 463 | return t |
| 464 | } |
| 465 | |
| 466 | // fakeopencode in the real containment: a Review run reaches its one |
| 467 | // Equipo tool through the tool socket, reports its usage and ends; the |
| 468 | // session is kept, and a question resumes it in a new process. |
| 469 | func TestOpenCodeFakeReviewInNamespace(t *testing.T) { |
| 470 | h := newHarness(t, fakeInstall(t)) |
| 471 | work := t.TempDir() |
| 472 | r := h.open(work, "inspect", []string{"submit_review", "ask_person"}) |
| 473 | evs := r.prompt(t, "[Equipo: review] Review this.", "deny") |
| 474 | tally := tallyOf(evs) |
| 475 | row := tally.Row() |
| 476 | if !row.Complete || row.Model != "glm-5.3" || *row.InputTokens != 120 || *row.CachedInputTokens != 80 || *row.OutputTokens != 14 { |
| 477 | t.Fatalf("usage %+v; events %v", row, eventKinds(evs)) |
| 478 | } |
| 479 | calls := r.tools.called() |
| 480 | if len(calls) != 1 || !strings.HasPrefix(calls[0], "submit_review ") { |
| 481 | t.Fatalf("tool calls %v", calls) |
| 482 | } |
| 483 | if d := doneOf(t, evs); d.Status != pi.StatusCompleted { |
| 484 | t.Fatalf("done %+v", d) |
| 485 | } |
| 486 | if err := r.stop(t); err != nil { |
| 487 | t.Fatalf("exit not proven: %v", err) |
| 488 | } |
| 489 | kept := filepath.Join(t.TempDir(), "kept") |
| 490 | if n, err := KeepSession(r.home, r.session.ID, kept, 0); err != nil || n == 0 || !HasSession(kept, r.session.ID) { |
| 491 | t.Fatalf("session not kept: %d %v", n, err) |
| 492 | } |
| 493 | again := h.openKept(t.TempDir(), "answer", []string{"git_log"}, r.session.ID, kept) |
| 494 | evs = again.prompt(t, "[Equipo: question] What did you check?", "deny") |
| 495 | text := "" |
| 496 | for _, e := range evs { |
| 497 | if e.Kind == KindDelta { |
| 498 | var d pi.Delta |
| 499 | json.Unmarshal(e.Payload, &d) |
| 500 | text += d.Text |
| 501 | } |
| 502 | } |
| 503 | if !strings.Contains(text, "message 3") { |
| 504 | t.Fatalf("the resumed session lost its history (or replayed it as this turn's): %q", text) |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | // The kept database is copied without following a link: a run that |
| 509 | // replaced it with a link to another file keeps nothing. |
| 510 | func TestKeepSessionRefusesLinks(t *testing.T) { |
| 511 | home := t.TempDir() |
| 512 | data := filepath.Join(home, ".local", "share", "opencode") |
| 513 | os.MkdirAll(data, 0700) |
| 514 | secret := filepath.Join(t.TempDir(), "secret") |
| 515 | os.WriteFile(secret, []byte("the key"), 0600) |
| 516 | os.Symlink(secret, filepath.Join(data, "opencode.db")) |
| 517 | kept := t.TempDir() |
| 518 | if _, err := KeepSession(home, "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa", kept, 0); err == nil || HasSession(kept, "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa") { |
| 519 | t.Fatalf("a link was kept: %v", err) |
| 520 | } |
| 521 | os.Remove(filepath.Join(data, "opencode.db")) |
| 522 | os.WriteFile(filepath.Join(data, "opencode.db"), []byte("db"), 0600) |
| 523 | os.Symlink(secret, filepath.Join(data, "opencode.db-wal")) |
| 524 | if _, err := KeepSession(home, "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa", kept, 0); err == nil { |
| 525 | t.Fatal("a linked journal was kept") |
| 526 | } |
| 527 | if _, err := KeepSession(home, "../ses_x", kept, 0); err == nil { |
| 528 | t.Fatal("a session id that is a path was kept") |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | // Security round finding 1: the kept database is copied through the |
| 533 | // runtime home's own directories, never a link in any of them: a run |
| 534 | // that replaced .local, .local/share or .local/share/opencode with a link |
| 535 | // to a host directory keeps nothing from it. |
| 536 | func TestKeepSessionRefusesLinkedDirectories(t *testing.T) { |
| 537 | const id = "ses_aaaaaaaaaaaaaaaaaaaaaaaaaa" |
| 538 | host := t.TempDir() |
| 539 | os.WriteFile(filepath.Join(host, "opencode.db"), []byte("a host database"), 0600) |
| 540 | os.MkdirAll(filepath.Join(host, "share", "opencode"), 0700) |
| 541 | os.WriteFile(filepath.Join(host, "share", "opencode", "opencode.db"), []byte("a host database"), 0600) |
| 542 | os.MkdirAll(filepath.Join(host, "local", "share", "opencode"), 0700) |
| 543 | os.WriteFile(filepath.Join(host, "local", "share", "opencode", "opencode.db"), []byte("a host database"), 0600) |
| 544 | for name, plant := range map[string]func(home string){ |
| 545 | "opencode": func(home string) { |
| 546 | os.MkdirAll(filepath.Join(home, ".local", "share"), 0700) |
| 547 | os.Symlink(host, filepath.Join(home, ".local", "share", "opencode")) |
| 548 | }, |
| 549 | "share": func(home string) { |
| 550 | os.MkdirAll(filepath.Join(home, ".local"), 0700) |
| 551 | os.Symlink(filepath.Join(host, "share"), filepath.Join(home, ".local", "share")) |
| 552 | }, |
| 553 | ".local": func(home string) { os.Symlink(filepath.Join(host, "local"), filepath.Join(home, ".local")) }, |
| 554 | } { |
| 555 | home := t.TempDir() |
| 556 | plant(home) |
| 557 | kept := t.TempDir() |
| 558 | if _, err := KeepSession(home, id, kept, 0); err == nil || HasSession(kept, id) { |
| 559 | t.Errorf("%s linked: kept a host database (%v)", name, err) |
| 560 | } |
| 561 | } |
| 562 | // Restoring follows no link in the kept directory either. |
| 563 | kept := t.TempDir() |
| 564 | os.MkdirAll(filepath.Join(kept, "opencode"), 0700) |
| 565 | os.Symlink(filepath.Join(host, "share", "opencode"), filepath.Join(kept, "opencode", id)) |
| 566 | if _, err := RestoreSession(kept, id, t.TempDir()); err == nil { |
| 567 | t.Error("restored through a linked kept directory") |
| 568 | } |
| 569 | } |
| 570 | |