package thin import ( "context" "encoding/json" gitleakscmd "github.com/zricethezav/gitleaks/v8/cmd" "log/slog" "net" "net/http" "os" "os/exec" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/fakeopencode" "amadan.net/oficina/equipo/internal/fakepi" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/testci" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/wiretest" "amadan.net/rastrillo/rastrillo/budget" "github.com/coder/websocket" ) func TestMain(m *testing.M) { switch filepath.Base(os.Args[0]) { case "scanner", "gitleaks": gitleakscmd.Execute() return case "claude": os.Exit(fakeclaude.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) case "node": // fakepi, started as Node with the Pi CLI's path first. os.Exit(fakepi.Main(os.Args[2:], os.Stdin, os.Stdout, os.Stderr)) case "opencode": // fakeopencode, started as the pinned binary. os.Exit(fakeopencode.Main(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) case "equipo-tool-proxy": os.Exit(serveToolProxy(os.Args)) } if len(os.Args) > 1 && os.Args[1] == "__namespace" { os.Exit(containment.NamespaceMain(os.Args[2:])) } if testHelper != nil { if code, ok := testHelper(); ok { os.Exit(code) } } // The fake carlos binaries answer no version verb: a current release // stands in, and the guard's own tests set theirs. readCarlosVersion = func(context.Context, string) string { return "v0.43.3" } code := budget.Main(m) if scannerBuild.binary != "" { _ = os.RemoveAll(filepath.Dir(scannerBuild.binary)) } os.Exit(code) } // testHelper, when a test build's file sets it, may run this binary as // one of its helper processes instead of the tests (ok). var testHelper func() (code int, ok bool) // stubCoordinator streams two deltas and replies, or waits to be cancelled. type stubCoordinator struct { mu sync.Mutex turns []TurnInput } func (s *stubCoordinator) Turn(ctx context.Context, in TurnInput, emit func(string)) TurnResult { s.mu.Lock() s.turns = append(s.turns, in) s.mu.Unlock() if strings.Contains(in.Text, "wait") { <-ctx.Done() return TurnResult{Reason: "cancelled"} } emit("Hel") emit("lo.") return TurnResult{Text: "Hello.", Usage: []wire.Usage{{InputTokens: i64(1), OutputTokens: i64(2), Complete: true}}} } func (s *stubCoordinator) Close() {} func i64(v int64) *int64 { return &v } // testEnrolledRole is the role startLink's runner was enrolled with. var testEnrolledRole = wire.RolePrimary // testTaskEnded is startLink's Link.TaskEnded (nil: none). var testTaskEnded func(context.Context, string) // fakeInstance is the instance end of the stream, driven from fixtures. type fakeInstance struct { t *testing.T url string conns chan *websocket.Conn } func newFakeInstance(t *testing.T) *fakeInstance { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } f := &fakeInstance{t: t, url: "http://" + l.Addr().String(), conns: make(chan *websocket.Conn, 4)} srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != wire.StreamPath || r.Header.Get("Authorization") != "Bearer token" { http.Error(w, "forbidden", http.StatusForbidden) return } c, err := websocket.Accept(w, r, nil) if err != nil { return } f.conns <- c <-r.Context().Done() })} go srv.Serve(l) t.Cleanup(func() { srv.Close() }) return f } func read(t *testing.T, c *websocket.Conn, kind string) (wire.Frame, []byte) { t.Helper() for { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) _, raw, err := c.Read(ctx) cancel() if err != nil { t.Fatalf("waiting for %s: %v", kind, err) } f, _, err := wire.ParseFrame(raw) if err != nil { t.Fatal(err) } if f.Type == kind { if kind == wire.FrameHello { // A protocol 2 hello carries the slice 4 hello's fields and // the protocol 2 ones; at protocol 1 it is the slice 4 hello. old, err := wire.Encode(f, wire.Protocol1) if err != nil { t.Fatal(err) } check, _ := json.Marshal(old) if err = wiretest.SameShape(wiretest.Fixture("frames/hello.json"), check); err != nil { t.Fatalf("hello frame: %v\n%s", err, raw) } return f, raw } if err = wiretest.SameShape(wiretest.Fixture("frames/"+kind+".json"), raw); err != nil { t.Fatalf("%s frame: %v\n%s", kind, err, raw) } return f, raw } if f.Type == wire.FrameLease { // The fake instance confirms the lease, as the real one does // for the current connection. ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) rawAck, _ := json.Marshal(ack) write(t, c, rawAck) continue } if f.Type != wire.FrameHello && f.Type != wire.FrameDelta && f.Type != wire.FrameAck { t.Fatalf("waiting for %s, got %s", kind, raw) } } } func write(t *testing.T, c *websocket.Conn, raw []byte) { t.Helper() if err := c.Write(context.Background(), websocket.MessageText, raw); err != nil { t.Fatal(err) } } func startLink(t *testing.T, origin string, coord Coordinator, seed ...func(*State)) (*Link, *State, context.CancelFunc, chan error) { t.Helper() return startLinkWith(t, origin, coord, nil, seed...) } // startLinkWith is startLink with hello, when set, as the runner's hello, // in place before the link first dials. func startLinkWith(t *testing.T, origin string, coord Coordinator, hello func() wire.Hello, seed ...func(*State)) (*Link, *State, context.CancelFunc, chan error) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) state, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } for _, f := range seed { f(state) } t.Cleanup(func() { state.Close() }) sessions := filepath.Join(t.TempDir(), "sessions") if err := os.MkdirAll(sessions, 0700); err != nil { t.Fatal(err) } link := &Link{Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)), Origin: origin, Token: "token", State: state, Role: testEnrolledRole, Files: &Files{State: state, SessionRoot: sessions}, Hello: func() wire.Hello { return wire.Hello{Repos: []string{"amadan.net/oficina/sample"}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{{LocalID: "claude-a", Person: "owner@example.com", Provider: "claude", Kind: "subscription", Label: "owner@example.com", State: "healthy"}}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}} }} if hello != nil { link.Hello = hello } link.TaskEnded = testTaskEnded engine := &Engine{State: state, Emit: link.Delta, Notify: link.Notify, Authorize: link.Confirm, Open: func(string, string, runner.AccountBinding) (Coordinator, error) { return coord, nil }} link.Engine = engine if err = engine.Start(ctx); err != nil { t.Fatal(err) } done := make(chan error, 1) go func() { done <- link.Run(ctx) }() t.Cleanup(func() { cancel(); engine.Wait() }) return link, state, cancel, done } // The runner end of the contract: it speaks the recorded frames and // accepts the instance's recorded frames. func TestRunnerContract(t *testing.T) { inst := newFakeInstance(t) coord := &stubCoordinator{} _, state, _, _ := startLink(t, inst.url, coord) c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome.json")) read(t, c, wire.FrameSync) write(t, c, wiretest.Fixture("frames/message.json")) ack, raw := read(t, c, wire.FrameAck) var a wire.Ack json.Unmarshal(ack.Data, &a) if a.ID != "c7" { t.Fatalf("ack %s", raw) } delta, _ := read(t, c, wire.FrameDelta) var d wire.DeltaReport json.Unmarshal(delta.Data, &d) reply, _ := read(t, c, wire.FrameReply) var r wire.Reply json.Unmarshal(reply.Data, &r) if d.TurnID != "t_0001" || d.Offset != 0 || !strings.HasPrefix("Hello.", d.Text) || r.Text != "Hello." || r.TurnID != "t_0001" || r.Attempt != 1 { t.Fatalf("delta %+v reply %+v", d, r) } if got := coord.turns[0]; got.Text != "hello" || len(got.Tail) != 2 || got.Person != "owner@example.com" { t.Fatalf("turn input %+v", got) } // A resent message frame is acked again and not run twice. write(t, c, wiretest.Fixture("frames/message.json")) read(t, c, wire.FrameAck) ackFrame, _ := wire.NewFrame("i-ack", wire.FrameAck, wire.Ack{ID: reply.ID}) rawAck, _ := json.Marshal(ackFrame) write(t, c, rawAck) deadline := time.Now().Add(5 * time.Second) for { s, _ := state.Sync(context.Background()) if len(s.Runs) == 0 { break } if time.Now().After(deadline) { t.Fatalf("run not finished after ack: %+v", s.Runs) } time.Sleep(20 * time.Millisecond) } if len(coord.turns) != 1 { t.Fatalf("turn ran %d times", len(coord.turns)) } // Drain: the runner reconnects and presents its generation. write(t, c, wiretest.Fixture("frames/drain.json")) c2 := <-inst.conns _, raw = read(t, c2, wire.FrameHello) var h wire.Frame json.Unmarshal(raw, &h) var hello wire.Hello json.Unmarshal(h.Data, &hello) if hello.Generation != 3 { t.Fatalf("reconnect generation %d, want the granted 3", hello.Generation) } } func TestRunnerCancelAndSupersede(t *testing.T) { testci.Quarantine(t) inst := newFakeInstance(t) coord := &stubCoordinator{} _, _, _, done := startLink(t, inst.url, coord) c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome.json")) read(t, c, wire.FrameSync) msg, _ := wire.NewFrame("c9", wire.FrameMessage, wire.MessageCommand{Person: "owner@example.com", TurnID: "t_wait", Attempt: 1, Text: "wait for it", Tail: []wire.TailMessage{}}) raw, _ := json.Marshal(msg) write(t, c, raw) read(t, c, wire.FrameAck) cancelFrame, _ := wire.NewFrame("c10", wire.FrameCancel, wire.CancelCommand{Person: "owner@example.com", TurnID: "t_wait", Attempt: 1}) raw, _ = json.Marshal(cancelFrame) write(t, c, raw) read(t, c, wire.FrameAck) turn, raw := read(t, c, wire.FrameTurn) var report wire.TurnReport json.Unmarshal(turn.Data, &report) if report.State != wire.TurnCancelled || report.TurnID != "t_wait" || report.Attempt != 1 { t.Fatalf("cancel report %s", raw) } c.Close(wire.CloseSuperseded, "superseded") select { case err := <-done: if err != ErrSuperseded { t.Fatalf("link ended with %v", err) } case <-time.After(10 * time.Second): t.Fatal("superseded runner kept running") } } // Recovery: a run the previous process held becomes attempt 2, once. func TestRunnerRecovery(t *testing.T) { ctx := context.Background() dir := t.TempDir() state, err := OpenState(ctx, dir) if err != nil { t.Fatal(err) } defer state.Close() if err = state.Accept(ctx, "c1", wire.MessageCommand{Person: "p", TurnID: "t1", Attempt: 1, Text: "x"}); err != nil { t.Fatal(err) } for i, want := range []wire.TurnReport{{TurnID: "t1", Attempt: 2, State: wire.TurnRunning}, {TurnID: "t1", Attempt: 2, State: wire.TurnFailed, Reason: "runner_restarted"}} { if err = state.Recover(ctx); err != nil { t.Fatal(err) } frames, _, _ := state.Unacked(ctx, 0) var got wire.TurnReport json.Unmarshal(frames[len(frames)-1].Data, &got) if got != want { t.Fatalf("recovery %d: %+v, want %+v", i, got, want) } } } // login runs the official sign-in into a new dedicated home and records // the observed email in the bindings for the runner's person. func TestLogin(t *testing.T) { root := t.TempDir() self, _ := os.Executable() bin := filepath.Join(root, "bin") os.Mkdir(bin, 0700) raw, _ := os.ReadFile(self) claudePath := filepath.Join(bin, "claude") if err := os.WriteFile(claudePath, raw, 0755); err != nil { t.Fatal(err) } state := filepath.Join(root, "state") os.Mkdir(state, 0700) credential, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "t", Person: "owner@example.com"}}) os.WriteFile(filepath.Join(state, "credentials.json"), credential, 0600) config := filepath.Join(root, "config") os.Mkdir(config, 0700) c := runner.Config{StateDir: state, ClaudePath: claudePath, AccountBindingsPath: filepath.Join(config, "bindings.json")} var out strings.Builder // The official CLI is interactive; the fake signs in as this email. command := func(ctx context.Context, binary string, args []string, dir string, env []string) error { cmd := exec.CommandContext(ctx, binary, args...) cmd.Dir, cmd.Env = dir, append(env, "FAKE_LOGIN_EMAIL=owner@example.com") return cmd.Run() } err := Login(context.Background(), c, "claude", LoginOptions{Root: filepath.Join(root, "accounts"), Output: &out, Command: command}) if err != nil { t.Fatal(err) } if !strings.Contains(out.String(), "owner@example.com") || !strings.Contains(out.String(), "claude-1") { t.Fatalf("output %q", out.String()) } bs, err := runner.LoadBindings(c.AccountBindingsPath) if err != nil || len(bs) != 1 || bs[0].ID != "claude-1" || bs[0].PersonID != "owner@example.com" || bs[0].AccountID != "owner@example.com" || bs[0].ProviderHome != filepath.Join(root, "accounts", "claude-1") { t.Fatalf("bindings %+v %v", bs, err) } // A second login gets the next home. if err = Login(context.Background(), c, "claude", LoginOptions{Root: filepath.Join(root, "accounts"), Output: &out, Command: command}); err == nil { t.Fatal("the same account was bound twice") } if _, err = os.Stat(filepath.Join(root, "accounts", "claude-2")); err != nil { t.Fatalf("second home: %v", err) } } func (s *stubCoordinator) count() int { s.mu.Lock(); defer s.mu.Unlock(); return len(s.turns) } // A run held from a previous process is not executed until the instance // confirms this connection's lease. func TestRunnerExecutesOnlyWithConfirmedLease(t *testing.T) { inst := newFakeInstance(t) coord := &stubCoordinator{} startLink(t, inst.url, coord, func(s *State) { if err := s.Accept(context.Background(), "c1", wire.MessageCommand{Person: "owner@example.com", TurnID: "t_held", Attempt: 1, Text: "hi", Tail: []wire.TailMessage{}}); err != nil { t.Fatal(err) } }) c := <-inst.conns time.Sleep(300 * time.Millisecond) if coord.count() != 0 { t.Fatal("executed before any connection") } read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome.json")) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() for { _, raw, err := c.Read(ctx) if err != nil { t.Fatalf("no lease check: %v", err) } f, _, _ := wire.ParseFrame(raw) if f.Type == wire.FrameLease { if coord.count() != 0 { t.Fatal("executed before the lease was confirmed") } time.Sleep(200 * time.Millisecond) if coord.count() != 0 { t.Fatal("executed without the lease ack") } ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) rawAck, _ := json.Marshal(ack) write(t, c, rawAck) break } } read(t, c, wire.FrameReply) if coord.count() != 1 { t.Fatalf("turns run %d", coord.count()) } } // A cancel that arrives before its message holds the turn cancelled: the // late message is never executed and termination is reported. func TestRunnerCancelBeforeMessage(t *testing.T) { inst := newFakeInstance(t) coord := &stubCoordinator{} startLink(t, inst.url, coord) c := <-inst.conns read(t, c, wire.FrameHello) write(t, c, wiretest.Fixture("frames/welcome.json")) read(t, c, wire.FrameSync) cancelFrame, _ := wire.NewFrame("c20", wire.FrameCancel, wire.CancelCommand{Person: "owner@example.com", TurnID: "t_late", Attempt: 1}) raw, _ := json.Marshal(cancelFrame) write(t, c, raw) msg, _ := wire.NewFrame("c21", wire.FrameMessage, wire.MessageCommand{Person: "owner@example.com", TurnID: "t_late", Attempt: 1, Text: "hi", Tail: []wire.TailMessage{}}) raw, _ = json.Marshal(msg) write(t, c, raw) f, _ := read(t, c, wire.FrameTurn) var report wire.TurnReport json.Unmarshal(f.Data, &report) if report.State != wire.TurnCancelled || report.TurnID != "t_late" || coord.count() != 0 { t.Fatalf("report %+v after %d turns", report, coord.count()) } } // Only the ack of a terminal report finishes a run; recovery keeps a // durable cancel and reports it instead of retrying. func TestRunnerRecoveryAcksAndCancels(t *testing.T) { ctx := context.Background() s, err := OpenState(ctx, t.TempDir()) if err != nil { t.Fatal(err) } defer s.Close() s.Accept(ctx, "c1", wire.MessageCommand{Person: "p", TurnID: "t1", Attempt: 1, Text: "x"}) if err = s.Recover(ctx); err != nil { t.Fatal(err) } frames, _, _ := s.Unacked(ctx, 0) announcement := frames[len(frames)-1].ID // The retried attempt replies before the announcement's ack arrives. held, _, _ := s.next(ctx, "p", wire.LaneCoordinator) if err = s.Report(ctx, held, &wire.Reply{TurnID: "t1", Attempt: held.Attempt, Text: "done"}, nil, nil); err != nil { t.Fatal(err) } if err = s.Acked(ctx, announcement); err != nil { t.Fatal(err) } if sync, _ := s.Sync(ctx); len(sync.Runs) != 1 || sync.Runs[0].State != runReported { t.Fatalf("acked recovery announcement finished the run before its reply was acked: %+v", sync.Runs) } s.Accept(ctx, "c2", wire.MessageCommand{Person: "p", TurnID: "t2", Attempt: 1, Text: "y"}) if _, err = s.RequestCancel(ctx, "c3", wire.CancelCommand{Person: "p", TurnID: "t2", Attempt: 1}); err != nil { t.Fatal(err) } if err = s.Recover(ctx); err != nil { t.Fatal(err) } frames, _, _ = s.Unacked(ctx, 0) var last wire.TurnReport for _, f := range frames { var r wire.TurnReport if json.Unmarshal(f.Data, &r) == nil && r.TurnID == "t2" { last = r } } if last.State != wire.TurnCancelled { t.Fatalf("recovery resurrected a cancelled turn: %+v", last) } if r, ok, _ := s.next(ctx, "p", wire.LaneCoordinator); ok && r.TurnID == "t2" { t.Fatal("cancelled turn still runnable") } } func TestSweepOrphans(t *testing.T) { root := t.TempDir() c := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state")} keep := []string{filepath.Join(c.ScratchRoot, "homes", "unrelated"), filepath.Join(c.StateDir, "private")} gone := []string{filepath.Join(c.ScratchRoot, "homes", "account-1"), filepath.Join(c.ScratchRoot, "homes", "config-1"), filepath.Join(c.ScratchRoot, "policy-1"), filepath.Join(c.WorkspaceRoot, "converse-1"), filepath.Join(c.StateDir, "coord-tool-1"), filepath.Join(c.ScratchRoot, "t", "123456")} for _, d := range append(append([]string{}, keep...), gone...) { os.MkdirAll(d, 0700) } if err := sweepOrphans(c); err != nil { t.Fatal(err) } for _, d := range gone { if _, err := os.Stat(d); err == nil { t.Fatalf("%s survived", d) } } for _, d := range keep { if _, err := os.Stat(d); err != nil { t.Fatalf("%s removed", d) } } } // Roots shared with another runner's state directory are refused before // anything is swept; a root held by a running runner is refused too. func TestPrepareRootsRefusesSharedRoots(t *testing.T) { root := t.TempDir() mine := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state-a")} other := mine other.StateDir = filepath.Join(root, "state-b") release, err := prepareRoots(other) if err != nil { t.Fatal(err) } live := filepath.Join(other.ScratchRoot, "homes", "account-live") os.MkdirAll(live, 0700) if _, err = prepareRoots(other); err != ErrRootShared { t.Fatalf("second claim while held: %v", err) } release() if _, err = prepareRoots(mine); err != ErrRootShared { t.Fatalf("roots of another state directory accepted: %v", err) } if _, err = os.Stat(live); err != nil { t.Fatal("another runner's credential copy was swept") } again, err := prepareRoots(other) if err != nil { t.Fatalf("owner could not reclaim its roots: %v", err) } again() } // Startup takes ownership before recovery: a second runner sharing the // first one's roots is refused before any recovery or sweep runs, and the // first runner's namespace record and scratch survive. func TestStartupRefusesSharedRootsBeforeRecovery(t *testing.T) { root := t.TempDir() first := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state-a")} second := first second.StateDir = filepath.Join(root, "state-b") release, err := startup(context.Background(), first, nil, func(context.Context) error { return nil }) if err != nil { t.Fatal(err) } defer release() live := []string{filepath.Join(first.ScratchRoot, "attempt-0123456789abcdef0123456789abcdef"), filepath.Join(first.ScratchRoot, "homes", "account-live"), filepath.Join(first.ScratchRoot, "policy-live")} for _, d := range live { os.MkdirAll(d, 0700) } record := filepath.Join(first.ScratchRoot, "0123456789abcdef0123456789abcdef.json") os.WriteFile(record, []byte("{}"), 0600) recovered := false if _, err = startup(context.Background(), second, nil, func(context.Context) error { recovered = true; return nil }); err != ErrRootShared { t.Fatalf("second runner on shared roots: %v", err) } if recovered { t.Fatal("recovery ran before root ownership was checked") } for _, p := range append(live, record) { if _, err := os.Stat(p); err != nil { t.Fatalf("the first runner's %s was touched", filepath.Base(p)) } } }