//go:build testbuild package thin import ( "context" "crypto/ed25519" "crypto/rand" "database/sql" "encoding/base64" "encoding/json" "log/slog" "net" "net/http" "os" "path/filepath" "slices" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" "github.com/coder/websocket" ) // A Mac worker's own Claude connections (Mac runners slice F, task 11): // the worker opens Conns over its own accounts root, says its // connections and seal key in hello once the welcome says 37, takes the // instance's connect, cancel, sign-out and preference commands, keeps // only Claude token connections (pasted, or made by its own sign-in), and // holds the Mac as having a model credential for as long as anything of // one may be there. // machineKey writes the runner's enrolment key into its state, as // enrolment does, and makes the rig seal to it. func (r *darwinRig) machineKey() { r.t.Helper() _, key, err := ed25519.GenerateKey(rand.Reader) if err != nil { r.t.Fatal(err) } raw, _ := json.Marshal(base64.RawURLEncoding.EncodeToString(key)) if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "machine-key.json"), raw, 0o600); err != nil { r.t.Fatal(err) } if r.keys, err = sealbox.FromEd25519(key); err != nil { r.t.Fatal(err) } } // workerOptions are a worker's options in these tests. func (r *darwinRig) workerOptions(protocol int) Options { return Options{Version: "v-test", Logger: slog.New(slog.NewTextHandler(&r.logs, nil)), Claude: ClaudeOptions{LockWait: 5 * time.Second}, ConnectLimit: time.Hour, Protocol: protocol} } // worker is the Mac worker's own connections over the rig, as runWorker // opens them, started. func (r *darwinRig) worker() *workerConns { r.t.Helper() r.machineKey() w := openWorkerConns(r.cfg, r.workerOptions(0), r.state, runnerproto.RunnerCredential{RunnerID: tokenRunner, Person: connPerson}, r.m, nil, nil) w.connector.spawn = func(f func()) { f() } if err := w.start(r.ctx); err != nil { r.t.Fatal(err) } return w } // workerInstance is an instance's runner stream for one worker // connection at a time: it welcomes at a protocol, acks every durable // frame the worker sends, and hands the frames over in order. type workerInstance struct { t *testing.T origin string conns chan *websocket.Conn ws *websocket.Conn frames chan workerFrame seq int } type workerFrame struct { f wire.Frame body any } func newWorkerInstance(t *testing.T) *workerInstance { t.Helper() l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } i := &workerInstance{t: t, origin: "http://" + l.Addr().String(), conns: make(chan *websocket.Conn, 4), frames: make(chan workerFrame, 256)} srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ws, err := websocket.Accept(w, r, nil) if err != nil { return } ws.SetReadLimit(wire.MaxFrameBytes) i.conns <- ws <-r.Context().Done() })} go srv.Serve(l) t.Cleanup(func() { srv.Close() }) return i } // welcome takes the worker's connection, its first hello, and welcomes // it at protocol; it returns that first hello. func (i *workerInstance) welcome(protocol int) wire.Hello { i.t.Helper() select { case i.ws = <-i.conns: case <-time.After(20 * time.Second): i.t.Fatal("the worker never connected") } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() _, raw, err := i.ws.Read(ctx) f, body, perr := wire.ParseFrame(raw) if err != nil || perr != nil || f.Type != wire.FrameHello { i.t.Fatalf("no hello: %v %v %s", err, perr, raw) } i.send(wire.FrameWelcome, wire.Welcome{Generation: 1, RunnerID: tokenRunner, Protocol: protocol, Role: wire.RoleWorker}) go func(ws *websocket.Conn) { for { _, raw, err := ws.Read(context.Background()) if err != nil { return } f, body, err := wire.ParseFrame(raw) if err != nil { continue } if f.Durable() { ack, _ := wire.NewFrame("i-ack-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) out, _ := json.Marshal(ack) _ = ws.Write(context.Background(), websocket.MessageText, out) } i.frames <- workerFrame{f, body} } }(i.ws) return *body.(*wire.Hello) } // send writes one frame to the worker. func (i *workerInstance) send(kind string, body any) { i.t.Helper() i.seq++ f, err := wire.NewFrame("i-"+kind+"-"+itoa(int64(i.seq)), kind, body) if err != nil { i.t.Fatal(err) } raw, _ := json.Marshal(f) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := i.ws.Write(ctx, websocket.MessageText, raw); err != nil { i.t.Fatal(err) } } // next is the first frame of kind for which ok says yes. func (i *workerInstance) next(kind string, ok func(any) bool) any { i.t.Helper() deadline := time.After(45 * time.Second) for { select { case w := <-i.frames: if w.f.Type == kind && (ok == nil || ok(w.body)) { return w.body } case <-deadline: i.t.Fatalf("no %s", kind) } } } // runWorker runs the Mac worker over the rig (its credential operations, // the fake gate and capabilities) against inst, offering protocol (0: // the current one); stop ends it. func (r *darwinRig) runWorker(inst *workerInstance, protocol int) (stop func()) { r.t.Helper() c := r.cfg c.Origin, c.WorkspaceRoot, c.MachineLabel = inst.origin, filepath.Join(r.dir, "work"), "Tito Studio" ctx, cancel := context.WithCancel(r.ctx) done := make(chan error, 1) go func() { done <- runWorker(ctx, c, r.workerOptions(protocol), wire.Platform{OS: "darwin", Arch: "arm64"}, workerSetup{probe: fake.probe(""), gate: fake.gate("", ""), creds: r.m}) }() return func() { r.t.Helper() cancel() select { case err := <-done: if err != nil { r.t.Fatalf("worker ended: %v", err) } case <-time.After(30 * time.Second): r.t.Fatal("the worker did not stop") } } } // workerCredential is the worker's enrolment credential in its state. func (r *darwinRig) workerCredential() { r.t.Helper() raw, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "bearer-worker-test", Role: wire.RoleWorker, RunnerID: tokenRunner, Person: connPerson}}) if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "credentials.json"), raw, 0o600); err != nil { r.t.Fatal(err) } } // TestWorkerHelloConnections: at 37 a worker takes a connect and its // sealed token through its link, and its hello (and sync) carry the // connection and its seal key; the same worker welcomed at 35 says none // and no seal key. The first hello, sent before any welcome, says none // either way. func TestWorkerHelloConnections(t *testing.T) { r := newDarwinRig(t) r.machineKey() r.workerCredential() key := r.keys.PublicString() inst := newWorkerInstance(t) stop := r.runWorker(inst, 0) first := inst.welcome(wire.ProtocolMacEngineering) if len(first.Connections) != 0 || first.SealKey != "" || first.Inventory { t.Fatalf("the first hello, before the welcome: %+v %q inventory=%v", first.Connections, first.SealKey, first.Inventory) } inst.next(wire.FrameHello, func(b any) bool { return b.(*wire.Hello).SealKey == key }) inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) inst.next(wire.FrameConnection, func(b any) bool { v := b.(*wire.ConnectionReport) return v.Connection == "cn_w1" && v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptToken }) token := fakeclaude.Token("w@example.com") inst.send(wire.FrameSecret, r.sealed("cn_w1", token, nil)) end := inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).State != wire.ConnConnecting }).(*wire.ConnectionReport) if end.State != wire.ConnHealthy || end.LocalID == "" { t.Fatalf("the worker's connection: %+v\n%s", end, r.logs.String()) } h := inst.next(wire.FrameHello, func(b any) bool { return len(b.(*wire.Hello).Connections) == 1 }).(*wire.Hello) if c := h.Connections[0]; c.LocalID != end.LocalID || c.Kind != wire.KindToken || c.Person != connPerson || h.SealKey != key { t.Fatalf("hello at 37: %+v %q", h.Connections, h.SealKey) } if !h.Inventory { t.Fatal("the hello after the welcome does not say it is the whole inventory") } if h.Capabilities == nil || !h.Capabilities.ModelHold { t.Fatalf("a worker holding a token said it holds none: %+v", h.Capabilities) } // The person's preference, addressed to this runner, is kept here. inst.send(wire.FramePreference, wire.PreferenceCommand{Person: connPerson, Provider: wire.ProviderClaude, Revision: 3}) r.waitFor(func() bool { var raw string _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&raw) return raw != "" }, "the preference kept") // A cancel ends an attempt on this runner. inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w2", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).Connection == "cn_w2" }) inst.send(wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: "cn_w2", Person: connPerson}) inst.next(wire.FrameConnection, func(b any) bool { v := b.(*wire.ConnectionReport) return v.Connection == "cn_w2" && v.State == wire.ConnError && v.Reason == "cancelled" }) // A sign-out addressed to this runner signs its connection out. inst.send(wire.FrameDisconnect, wire.DisconnectCommand{Connection: "cn_w1", Person: connPerson, LocalID: end.LocalID, RunnerID: tokenRunner}) inst.next(wire.FrameConnection, func(b any) bool { v := b.(*wire.ConnectionReport) return v.Connection == "cn_w1" && v.State == wire.ConnSignedOut }) inst.next(wire.FrameHello, func(b any) bool { return len(b.(*wire.Hello).Connections) == 0 }) // Another for the 35 run: held, so its absence below 37 means something. inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w3", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).Connection == "cn_w3" }) inst.send(wire.FrameSecret, r.sealed("cn_w3", fakeclaude.Token("w3@example.com"), nil)) inst.next(wire.FrameConnection, func(b any) bool { v := b.(*wire.ConnectionReport) return v.Connection == "cn_w3" && v.State == wire.ConnHealthy }) stop() again := newWorkerInstance(t) stop = r.runWorker(again, 0) first = again.welcome(wire.ProtocolChangeDiffs) sync := again.next(wire.FrameSync, nil).(*wire.Sync) h = again.next(wire.FrameHello, nil).(*wire.Hello) if len(first.Connections) != 0 || len(sync.Connections) != 0 || len(h.Connections) != 0 || h.SealKey != "" || first.SealKey != "" { t.Fatalf("at 35: first %+v, sync %+v, hello %+v %q", first.Connections, sync.Connections, h.Connections, h.SealKey) } if h.Capabilities != nil && (h.Capabilities.ModelHold || len(h.Capabilities.HoldingItems) > 0) || h.Inventory { t.Fatalf("the hold or the inventory said below 37: %+v inventory=%v", h.Capabilities, h.Inventory) } // Below 37 a worker acts on no connection command, acks none, and // replays nothing of its connections (fix round 1, #3). local := filepath.Base(r.homeOf(t, "cn_w3")) launches := len(r.launches()) var prefer string _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&prefer) if err := r.state.tx(r.ctx, func(t *sql.Tx) error { return r.state.enqueue(t, wire.FrameConnection, "", wire.ConnectionReport{Connection: "cn_w3", Person: connPerson, LocalID: local, Provider: wire.ProviderClaude, State: wire.ConnSignedOut}) }); err != nil { t.Fatal(err) } if err := r.state.ReportCheck(r.ctx, []wire.Usage{{Provider: wire.ProviderClaude, Connection: local, Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true}}); err != nil { t.Fatal(err) } again.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w4", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) again.send(wire.FrameSecret, r.sealed("cn_w4", fakeclaude.Token("w4@example.com"), nil)) again.send(wire.FrameCheck, wire.CheckCommand{Connection: "cn_w3", Person: connPerson, LocalID: local}) again.send(wire.FramePreference, wire.PreferenceCommand{Person: connPerson, Provider: wire.ProviderCodex, Revision: 9}) again.send(wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: "cn_w3", Person: connPerson}) again.send(wire.FrameDisconnect, wire.DisconnectCommand{Connection: "cn_w3", Person: connPerson, LocalID: local, RunnerID: tokenRunner}) again.quiet(3*time.Second, func(w workerFrame) bool { switch w.f.Type { case wire.FrameConnection, wire.FrameUsage, wire.FrameAck: return true } return false }) var attempts int _ = r.state.db.QueryRow("SELECT count(*) FROM connect_attempts WHERE id='cn_w4'").Scan(&attempts) var now string _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&now) if _, ok := r.conns.Binding(local); !ok || attempts != 0 || r.seals("cn_w4") != 0 || len(r.launches()) != launches || now != prefer { t.Fatalf("below 37: bound=%v attempts=%d seals=%d launches %d->%d preference %q->%q", ok, attempts, r.seals("cn_w4"), launches, len(r.launches()), prefer, now) } stop() } // homeOf is the home an attempt made. func (r *darwinRig) homeOf(t *testing.T, id string) string { t.Helper() var home string if err := r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home); err != nil || home == "" { t.Fatalf("no home for %s: %v", id, err) } return home } // quiet fails if, within d, the worker sends a frame bad says is one it // must not send. func (i *workerInstance) quiet(d time.Duration, bad func(workerFrame) bool) { i.t.Helper() deadline := time.After(d) for { select { case w := <-i.frames: if bad(w) { raw, _ := json.Marshal(w.body) i.t.Fatalf("below 37 the worker sent %s: %s", w.f.Type, raw) } case <-deadline: return } } } // TestWorkerTokenConnectionStored: a pasted token on a worker rests in a // 0600 file in a 0700 home inside a 0700 accounts root; with the home // guard failing nothing is stored. func TestWorkerTokenConnectionStored(t *testing.T) { r := newDarwinRig(t) w := r.worker() token := fakeclaude.Token("a@example.com") home, end := r.paste(w.connector, "c1", token) if end.State != wire.ConnHealthy { t.Fatalf("not connected: %+v\n%s", end, r.logs.String()) } for path, want := range map[string]os.FileMode{r.root: 0o700, home: 0o700, filepath.Join(home, provider.TokenFile): 0o600} { info, err := os.Lstat(path) if err != nil || info.Mode().Perm() != want { t.Fatalf("%s: %v %v, want %v", path, err, info.Mode().Perm(), want) } } if b, ok := w.conns.Binding(filepath.Base(home)); !ok || b.Kind != wire.KindToken || b.PersonID != connPerson { t.Fatalf("binding %+v %v", b, ok) } r.onlyIn(token, home) // The home guard fails: refused, nothing written. if err := os.Chmod(r.dir, 0o750); err != nil { t.Fatal(err) } t.Cleanup(func() { os.Chmod(r.dir, 0o700) }) home2, end := r.paste(w.connector, "c2", fakeclaude.Token("b@example.com")) if end.State != wire.ConnError || end.Reason != "provider_refused" || r.seals("c2") != 0 || exists(filepath.Join(home2, provider.TokenFile)) || exists(filepath.Join(home2, provider.TokenStaging)) { t.Fatalf("stored with the home guard failing: %+v seals=%d", end, r.seals("c2")) } } // TestWorkerRefusesOtherConnectionKinds: a worker keeps only Claude // token connections. Codex, an API key and an endpoint are refused, each // with the stated reason and nothing made in the accounts root; Claude's // sign-in and a pasted token both start. func TestWorkerRefusesOtherConnectionKinds(t *testing.T) { r := newDarwinRig(t) w := r.worker() budget := &wire.Budget{Day: 5_000_000, Month: 50_000_000, Currency: "USD", Revision: 1} for i, cmd := range []wire.ConnectCommand{ {Provider: wire.ProviderCodex, Kind: wire.KindSubscription}, {Provider: wire.ProviderCodex, Kind: wire.KindToken}, {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: budget}, {Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingSubscription, Budget: budget}, {Provider: "local", Kind: "endpoint"}, } { cmd.Connection, cmd.Person = "x"+itoa(int64(i)), connPerson if err := w.connector.Accept(r.ctx, "f-"+cmd.Connection, cmd); err != nil { t.Fatal(err) } if end := r.ended(cmd.Connection); end.State != wire.ConnError || end.Reason != wire.ReasonMacClaudeOnly { t.Fatalf("%s %s: %+v", cmd.Provider, cmd.Kind, end) } if entries, _ := os.ReadDir(r.root); len(entries) != 0 { t.Fatalf("%s %s left %d entries in the accounts root", cmd.Provider, cmd.Kind, len(entries)) } } if !wire.ConnectReasons[wire.ReasonMacClaudeOnly] { t.Fatal("the reason is not one an instance accepts") } r.connect(w.connector, "t1") link, _ := r.signIn(w.connector, "s1") if link == "" { t.Fatal("no sign-in") } } // TestWorkerCredentialHoldDurable: the worker holds the Mac as having a // model credential from the moment an attempt starts, through a refused // sign-in that left a Keychain item, and across a restart, until the // connection's files are gone and the Keychain is clean; the hello says // so, with the item's service. func TestWorkerCredentialHoldDurable(t *testing.T) { r := newDarwinRig(t) w := r.worker() if w.held(r.ctx) { t.Fatal("held with nothing there") } r.kc.set(true) // deletes fail: the item the sign-in leaves stays link, home := r.signIn(w.connector, "s1") if !w.held(r.ctx) { t.Fatal("not held while connecting") } item := r.own(r.signInDir()) r.kc.add(item) r.codeIn(w.connector, "s1", link, "a@example.com") if end := r.ended("s1"); end.Reason != "provider_refused" { t.Fatalf("end %+v", end) } if exists(home) { t.Fatal("the refused attempt's home stayed") } if entries, _ := os.ReadDir(r.root); len(entries) != 0 || !w.held(r.ctx) { t.Fatalf("files gone, item left: held=%v", w.held(r.ctx)) } h := wire.Hello{Capabilities: &wire.Capabilities{}} w.hello(wire.ProtocolMacEngineering, &h) if !h.Capabilities.ModelHold || !slices.Equal(h.Capabilities.HoldingItems, []string{item.Service}) || wire.ValidCapabilities(*h.Capabilities) != nil { t.Fatalf("hello %+v", h.Capabilities) } // A restart: the same state, held still. again := darwinRigAt(t, r.dir) again.kc = r.kc again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete again.kc.r = again w2 := openWorkerConns(again.cfg, again.workerOptions(0), again.state, runnerproto.RunnerCredential{RunnerID: tokenRunner, Person: connPerson}, again.m, nil, nil) if !w2.held(again.ctx) { t.Fatal("the hold did not survive the restart") } // The item goes (deletes work again); the restart's settling clears it. r.kc.set(false) w2.connector.spawn = func(f func()) { f() } if err := w2.start(again.ctx); err != nil { t.Fatal(err) } if w2.held(again.ctx) || r.kc.has(item) { t.Fatalf("still held once the files and the item are gone: %v", again.m.keychain.Residue()) } h = wire.Hello{Capabilities: &wire.Capabilities{}} w2.hello(wire.ProtocolMacEngineering, &h) if h.Capabilities.ModelHold || len(h.Capabilities.HoldingItems) != 0 { t.Fatalf("hello %+v", h.Capabilities) } // An attempt running, or a sign-out owed, holds by itself, before // anything of it is on disk. for _, q := range []string{ "INSERT INTO connect_attempts(id, person, provider, state, created_at) VALUES('x1', 'p', 'claude', 'running', '2026-11-29T00:00:00Z')", "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) VALUES('x2', 'p', 'claude-8', 1, '2026-11-29T00:00:00Z')", } { if _, err := again.state.db.Exec(q); err != nil { t.Fatal(err) } if !w2.held(again.ctx) { t.Fatalf("not held by %s", q) } if _, err := again.state.db.Exec("DELETE FROM connect_attempts WHERE id='x1'; DELETE FROM connect_cleanups WHERE connection='x2'"); err != nil { t.Fatal(err) } } if w2.held(again.ctx) { t.Fatal("held once they were gone") } // A file in the accounts root holds by itself. if err := os.Mkdir(filepath.Join(again.root, "claude-9"), 0o700); err != nil { t.Fatal(err) } if !w2.held(again.ctx) { t.Fatal("a home in the accounts root does not hold") } } // TestWorkerSignOutOnlyItsOwn: a disconnect addressed to another runner // removes nothing here, even for a local id this runner holds. func TestWorkerSignOutOnlyItsOwn(t *testing.T) { r := newDarwinRig(t) w := r.worker() home, end := r.paste(w.connector, "c1", fakeclaude.Token("a@example.com")) if end.State != wire.ConnHealthy { t.Fatalf("not connected: %+v", end) } local := filepath.Base(home) if err := w.connector.Disconnect(r.ctx, "f-out-1", wire.DisconnectCommand{Connection: "c1", Person: connPerson, LocalID: local, RunnerID: "run_primary"}); err != nil { t.Fatal(err) } if _, ok := w.conns.Binding(local); !ok || !exists(home) { t.Fatal("another runner's sign-out removed this runner's connection") } if err := w.connector.Disconnect(r.ctx, "f-out-2", wire.DisconnectCommand{Connection: "c1", Person: connPerson, LocalID: local, RunnerID: tokenRunner}); err != nil { t.Fatal(err) } if _, ok := w.conns.Binding(local); ok || exists(home) { t.Fatal("its own sign-out left the connection") } } // TestWorkerProfileAtStartGated: on a Mac the start's profile reads use // a token only while the Mac's guards pass: a tainted Mac reads none; an // untainted one reads as Linux does. func TestWorkerProfileAtStartGated(t *testing.T) { r := newProfileRig(t) m := &macCreds{taint: loadTaint(filepath.Join(r.dir, "state", "tainted"))} m.taint.Set() r.o.Mac = m if named := r.start(); named != 0 || r.fake.count() != 0 { t.Fatalf("a tainted Mac read %d profiles", r.fake.count()) } }