| 1 | //go:build testbuild |
| 2 | |
| 3 | package thin |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/ed25519" |
| 8 | "crypto/rand" |
| 9 | "database/sql" |
| 10 | "encoding/base64" |
| 11 | "encoding/json" |
| 12 | "log/slog" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "slices" |
| 18 | "testing" |
| 19 | "time" |
| 20 | |
| 21 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 22 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 23 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 24 | "amadan.net/oficina/equipo/internal/sealbox" |
| 25 | "amadan.net/oficina/equipo/internal/wire" |
| 26 | "github.com/coder/websocket" |
| 27 | ) |
| 28 | |
| 29 | // A Mac worker's own Claude connections (Mac runners slice F, task 11): |
| 30 | // the worker opens Conns over its own accounts root, says its |
| 31 | // connections and seal key in hello once the welcome says 37, takes the |
| 32 | // instance's connect, cancel, sign-out and preference commands, keeps |
| 33 | // only Claude token connections (pasted, or made by its own sign-in), and |
| 34 | // holds the Mac as having a model credential for as long as anything of |
| 35 | // one may be there. |
| 36 | |
| 37 | // machineKey writes the runner's enrolment key into its state, as |
| 38 | // enrolment does, and makes the rig seal to it. |
| 39 | func (r *darwinRig) machineKey() { |
| 40 | r.t.Helper() |
| 41 | _, key, err := ed25519.GenerateKey(rand.Reader) |
| 42 | if err != nil { |
| 43 | r.t.Fatal(err) |
| 44 | } |
| 45 | raw, _ := json.Marshal(base64.RawURLEncoding.EncodeToString(key)) |
| 46 | if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "machine-key.json"), raw, 0o600); err != nil { |
| 47 | r.t.Fatal(err) |
| 48 | } |
| 49 | if r.keys, err = sealbox.FromEd25519(key); err != nil { |
| 50 | r.t.Fatal(err) |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // workerOptions are a worker's options in these tests. |
| 55 | func (r *darwinRig) workerOptions(protocol int) Options { |
| 56 | return Options{Version: "v-test", Logger: slog.New(slog.NewTextHandler(&r.logs, nil)), Claude: ClaudeOptions{LockWait: 5 * time.Second}, ConnectLimit: time.Hour, Protocol: protocol} |
| 57 | } |
| 58 | |
| 59 | // worker is the Mac worker's own connections over the rig, as runWorker |
| 60 | // opens them, started. |
| 61 | func (r *darwinRig) worker() *workerConns { |
| 62 | r.t.Helper() |
| 63 | r.machineKey() |
| 64 | w := openWorkerConns(r.cfg, r.workerOptions(0), r.state, runnerproto.RunnerCredential{RunnerID: tokenRunner, Person: connPerson}, r.m, nil, nil) |
| 65 | w.connector.spawn = func(f func()) { f() } |
| 66 | if err := w.start(r.ctx); err != nil { |
| 67 | r.t.Fatal(err) |
| 68 | } |
| 69 | return w |
| 70 | } |
| 71 | |
| 72 | // workerInstance is an instance's runner stream for one worker |
| 73 | // connection at a time: it welcomes at a protocol, acks every durable |
| 74 | // frame the worker sends, and hands the frames over in order. |
| 75 | type workerInstance struct { |
| 76 | t *testing.T |
| 77 | origin string |
| 78 | conns chan *websocket.Conn |
| 79 | ws *websocket.Conn |
| 80 | frames chan workerFrame |
| 81 | seq int |
| 82 | } |
| 83 | |
| 84 | type workerFrame struct { |
| 85 | f wire.Frame |
| 86 | body any |
| 87 | } |
| 88 | |
| 89 | func newWorkerInstance(t *testing.T) *workerInstance { |
| 90 | t.Helper() |
| 91 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 92 | if err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | i := &workerInstance{t: t, origin: "http://" + l.Addr().String(), conns: make(chan *websocket.Conn, 4), frames: make(chan workerFrame, 256)} |
| 96 | srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 97 | ws, err := websocket.Accept(w, r, nil) |
| 98 | if err != nil { |
| 99 | return |
| 100 | } |
| 101 | ws.SetReadLimit(wire.MaxFrameBytes) |
| 102 | i.conns <- ws |
| 103 | <-r.Context().Done() |
| 104 | })} |
| 105 | go srv.Serve(l) |
| 106 | t.Cleanup(func() { srv.Close() }) |
| 107 | return i |
| 108 | } |
| 109 | |
| 110 | // welcome takes the worker's connection, its first hello, and welcomes |
| 111 | // it at protocol; it returns that first hello. |
| 112 | func (i *workerInstance) welcome(protocol int) wire.Hello { |
| 113 | i.t.Helper() |
| 114 | select { |
| 115 | case i.ws = <-i.conns: |
| 116 | case <-time.After(20 * time.Second): |
| 117 | i.t.Fatal("the worker never connected") |
| 118 | } |
| 119 | ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) |
| 120 | defer cancel() |
| 121 | _, raw, err := i.ws.Read(ctx) |
| 122 | f, body, perr := wire.ParseFrame(raw) |
| 123 | if err != nil || perr != nil || f.Type != wire.FrameHello { |
| 124 | i.t.Fatalf("no hello: %v %v %s", err, perr, raw) |
| 125 | } |
| 126 | i.send(wire.FrameWelcome, wire.Welcome{Generation: 1, RunnerID: tokenRunner, Protocol: protocol, Role: wire.RoleWorker}) |
| 127 | go func(ws *websocket.Conn) { |
| 128 | for { |
| 129 | _, raw, err := ws.Read(context.Background()) |
| 130 | if err != nil { |
| 131 | return |
| 132 | } |
| 133 | f, body, err := wire.ParseFrame(raw) |
| 134 | if err != nil { |
| 135 | continue |
| 136 | } |
| 137 | if f.Durable() { |
| 138 | ack, _ := wire.NewFrame("i-ack-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 139 | out, _ := json.Marshal(ack) |
| 140 | _ = ws.Write(context.Background(), websocket.MessageText, out) |
| 141 | } |
| 142 | i.frames <- workerFrame{f, body} |
| 143 | } |
| 144 | }(i.ws) |
| 145 | return *body.(*wire.Hello) |
| 146 | } |
| 147 | |
| 148 | // send writes one frame to the worker. |
| 149 | func (i *workerInstance) send(kind string, body any) { |
| 150 | i.t.Helper() |
| 151 | i.seq++ |
| 152 | f, err := wire.NewFrame("i-"+kind+"-"+itoa(int64(i.seq)), kind, body) |
| 153 | if err != nil { |
| 154 | i.t.Fatal(err) |
| 155 | } |
| 156 | raw, _ := json.Marshal(f) |
| 157 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 158 | defer cancel() |
| 159 | if err := i.ws.Write(ctx, websocket.MessageText, raw); err != nil { |
| 160 | i.t.Fatal(err) |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // next is the first frame of kind for which ok says yes. |
| 165 | func (i *workerInstance) next(kind string, ok func(any) bool) any { |
| 166 | i.t.Helper() |
| 167 | deadline := time.After(45 * time.Second) |
| 168 | for { |
| 169 | select { |
| 170 | case w := <-i.frames: |
| 171 | if w.f.Type == kind && (ok == nil || ok(w.body)) { |
| 172 | return w.body |
| 173 | } |
| 174 | case <-deadline: |
| 175 | i.t.Fatalf("no %s", kind) |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | // runWorker runs the Mac worker over the rig (its credential operations, |
| 181 | // the fake gate and capabilities) against inst, offering protocol (0: |
| 182 | // the current one); stop ends it. |
| 183 | func (r *darwinRig) runWorker(inst *workerInstance, protocol int) (stop func()) { |
| 184 | r.t.Helper() |
| 185 | c := r.cfg |
| 186 | c.Origin, c.WorkspaceRoot, c.MachineLabel = inst.origin, filepath.Join(r.dir, "work"), "Tito Studio" |
| 187 | ctx, cancel := context.WithCancel(r.ctx) |
| 188 | done := make(chan error, 1) |
| 189 | go func() { |
| 190 | done <- runWorker(ctx, c, r.workerOptions(protocol), wire.Platform{OS: "darwin", Arch: "arm64"}, workerSetup{probe: fake.probe(""), gate: fake.gate("", ""), creds: r.m}) |
| 191 | }() |
| 192 | return func() { |
| 193 | r.t.Helper() |
| 194 | cancel() |
| 195 | select { |
| 196 | case err := <-done: |
| 197 | if err != nil { |
| 198 | r.t.Fatalf("worker ended: %v", err) |
| 199 | } |
| 200 | case <-time.After(30 * time.Second): |
| 201 | r.t.Fatal("the worker did not stop") |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // workerCredential is the worker's enrolment credential in its state. |
| 207 | func (r *darwinRig) workerCredential() { |
| 208 | r.t.Helper() |
| 209 | raw, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: "bearer-worker-test", Role: wire.RoleWorker, RunnerID: tokenRunner, Person: connPerson}}) |
| 210 | if err := os.WriteFile(filepath.Join(r.cfg.StateDir, "credentials.json"), raw, 0o600); err != nil { |
| 211 | r.t.Fatal(err) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // TestWorkerHelloConnections: at 37 a worker takes a connect and its |
| 216 | // sealed token through its link, and its hello (and sync) carry the |
| 217 | // connection and its seal key; the same worker welcomed at 35 says none |
| 218 | // and no seal key. The first hello, sent before any welcome, says none |
| 219 | // either way. |
| 220 | func TestWorkerHelloConnections(t *testing.T) { |
| 221 | r := newDarwinRig(t) |
| 222 | r.machineKey() |
| 223 | r.workerCredential() |
| 224 | key := r.keys.PublicString() |
| 225 | |
| 226 | inst := newWorkerInstance(t) |
| 227 | stop := r.runWorker(inst, 0) |
| 228 | first := inst.welcome(wire.ProtocolMacEngineering) |
| 229 | if len(first.Connections) != 0 || first.SealKey != "" || first.Inventory { |
| 230 | t.Fatalf("the first hello, before the welcome: %+v %q inventory=%v", first.Connections, first.SealKey, first.Inventory) |
| 231 | } |
| 232 | inst.next(wire.FrameHello, func(b any) bool { return b.(*wire.Hello).SealKey == key }) |
| 233 | inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| 234 | inst.next(wire.FrameConnection, func(b any) bool { |
| 235 | v := b.(*wire.ConnectionReport) |
| 236 | return v.Connection == "cn_w1" && v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptToken |
| 237 | }) |
| 238 | token := fakeclaude.Token("w@example.com") |
| 239 | inst.send(wire.FrameSecret, r.sealed("cn_w1", token, nil)) |
| 240 | end := inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).State != wire.ConnConnecting }).(*wire.ConnectionReport) |
| 241 | if end.State != wire.ConnHealthy || end.LocalID == "" { |
| 242 | t.Fatalf("the worker's connection: %+v\n%s", end, r.logs.String()) |
| 243 | } |
| 244 | h := inst.next(wire.FrameHello, func(b any) bool { return len(b.(*wire.Hello).Connections) == 1 }).(*wire.Hello) |
| 245 | if c := h.Connections[0]; c.LocalID != end.LocalID || c.Kind != wire.KindToken || c.Person != connPerson || h.SealKey != key { |
| 246 | t.Fatalf("hello at 37: %+v %q", h.Connections, h.SealKey) |
| 247 | } |
| 248 | if !h.Inventory { |
| 249 | t.Fatal("the hello after the welcome does not say it is the whole inventory") |
| 250 | } |
| 251 | if h.Capabilities == nil || !h.Capabilities.ModelHold { |
| 252 | t.Fatalf("a worker holding a token said it holds none: %+v", h.Capabilities) |
| 253 | } |
| 254 | // The person's preference, addressed to this runner, is kept here. |
| 255 | inst.send(wire.FramePreference, wire.PreferenceCommand{Person: connPerson, Provider: wire.ProviderClaude, Revision: 3}) |
| 256 | r.waitFor(func() bool { |
| 257 | var raw string |
| 258 | _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&raw) |
| 259 | return raw != "" |
| 260 | }, "the preference kept") |
| 261 | // A cancel ends an attempt on this runner. |
| 262 | inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w2", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| 263 | inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).Connection == "cn_w2" }) |
| 264 | inst.send(wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: "cn_w2", Person: connPerson}) |
| 265 | inst.next(wire.FrameConnection, func(b any) bool { |
| 266 | v := b.(*wire.ConnectionReport) |
| 267 | return v.Connection == "cn_w2" && v.State == wire.ConnError && v.Reason == "cancelled" |
| 268 | }) |
| 269 | // A sign-out addressed to this runner signs its connection out. |
| 270 | inst.send(wire.FrameDisconnect, wire.DisconnectCommand{Connection: "cn_w1", Person: connPerson, LocalID: end.LocalID, RunnerID: tokenRunner}) |
| 271 | inst.next(wire.FrameConnection, func(b any) bool { |
| 272 | v := b.(*wire.ConnectionReport) |
| 273 | return v.Connection == "cn_w1" && v.State == wire.ConnSignedOut |
| 274 | }) |
| 275 | inst.next(wire.FrameHello, func(b any) bool { return len(b.(*wire.Hello).Connections) == 0 }) |
| 276 | // Another for the 35 run: held, so its absence below 37 means something. |
| 277 | inst.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w3", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| 278 | inst.next(wire.FrameConnection, func(b any) bool { return b.(*wire.ConnectionReport).Connection == "cn_w3" }) |
| 279 | inst.send(wire.FrameSecret, r.sealed("cn_w3", fakeclaude.Token("w3@example.com"), nil)) |
| 280 | inst.next(wire.FrameConnection, func(b any) bool { |
| 281 | v := b.(*wire.ConnectionReport) |
| 282 | return v.Connection == "cn_w3" && v.State == wire.ConnHealthy |
| 283 | }) |
| 284 | stop() |
| 285 | |
| 286 | again := newWorkerInstance(t) |
| 287 | stop = r.runWorker(again, 0) |
| 288 | first = again.welcome(wire.ProtocolChangeDiffs) |
| 289 | sync := again.next(wire.FrameSync, nil).(*wire.Sync) |
| 290 | h = again.next(wire.FrameHello, nil).(*wire.Hello) |
| 291 | if len(first.Connections) != 0 || len(sync.Connections) != 0 || len(h.Connections) != 0 || h.SealKey != "" || first.SealKey != "" { |
| 292 | t.Fatalf("at 35: first %+v, sync %+v, hello %+v %q", first.Connections, sync.Connections, h.Connections, h.SealKey) |
| 293 | } |
| 294 | if h.Capabilities != nil && (h.Capabilities.ModelHold || len(h.Capabilities.HoldingItems) > 0) || h.Inventory { |
| 295 | t.Fatalf("the hold or the inventory said below 37: %+v inventory=%v", h.Capabilities, h.Inventory) |
| 296 | } |
| 297 | // Below 37 a worker acts on no connection command, acks none, and |
| 298 | // replays nothing of its connections (fix round 1, #3). |
| 299 | local := filepath.Base(r.homeOf(t, "cn_w3")) |
| 300 | launches := len(r.launches()) |
| 301 | var prefer string |
| 302 | _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&prefer) |
| 303 | if err := r.state.tx(r.ctx, func(t *sql.Tx) error { |
| 304 | return r.state.enqueue(t, wire.FrameConnection, "", wire.ConnectionReport{Connection: "cn_w3", Person: connPerson, LocalID: local, Provider: wire.ProviderClaude, State: wire.ConnSignedOut}) |
| 305 | }); err != nil { |
| 306 | t.Fatal(err) |
| 307 | } |
| 308 | 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 { |
| 309 | t.Fatal(err) |
| 310 | } |
| 311 | again.send(wire.FrameConnect, wire.ConnectCommand{Connection: "cn_w4", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}) |
| 312 | again.send(wire.FrameSecret, r.sealed("cn_w4", fakeclaude.Token("w4@example.com"), nil)) |
| 313 | again.send(wire.FrameCheck, wire.CheckCommand{Connection: "cn_w3", Person: connPerson, LocalID: local}) |
| 314 | again.send(wire.FramePreference, wire.PreferenceCommand{Person: connPerson, Provider: wire.ProviderCodex, Revision: 9}) |
| 315 | again.send(wire.FrameCancelConnect, wire.CancelConnectCommand{Connection: "cn_w3", Person: connPerson}) |
| 316 | again.send(wire.FrameDisconnect, wire.DisconnectCommand{Connection: "cn_w3", Person: connPerson, LocalID: local, RunnerID: tokenRunner}) |
| 317 | again.quiet(3*time.Second, func(w workerFrame) bool { |
| 318 | switch w.f.Type { |
| 319 | case wire.FrameConnection, wire.FrameUsage, wire.FrameAck: |
| 320 | return true |
| 321 | } |
| 322 | return false |
| 323 | }) |
| 324 | var attempts int |
| 325 | _ = r.state.db.QueryRow("SELECT count(*) FROM connect_attempts WHERE id='cn_w4'").Scan(&attempts) |
| 326 | var now string |
| 327 | _ = r.state.db.QueryRow("SELECT value FROM meta WHERE key=?", "prefer:"+connPerson).Scan(&now) |
| 328 | if _, ok := r.conns.Binding(local); !ok || attempts != 0 || r.seals("cn_w4") != 0 || len(r.launches()) != launches || now != prefer { |
| 329 | 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) |
| 330 | } |
| 331 | stop() |
| 332 | } |
| 333 | |
| 334 | // homeOf is the home an attempt made. |
| 335 | func (r *darwinRig) homeOf(t *testing.T, id string) string { |
| 336 | t.Helper() |
| 337 | var home string |
| 338 | if err := r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home); err != nil || home == "" { |
| 339 | t.Fatalf("no home for %s: %v", id, err) |
| 340 | } |
| 341 | return home |
| 342 | } |
| 343 | |
| 344 | // quiet fails if, within d, the worker sends a frame bad says is one it |
| 345 | // must not send. |
| 346 | func (i *workerInstance) quiet(d time.Duration, bad func(workerFrame) bool) { |
| 347 | i.t.Helper() |
| 348 | deadline := time.After(d) |
| 349 | for { |
| 350 | select { |
| 351 | case w := <-i.frames: |
| 352 | if bad(w) { |
| 353 | raw, _ := json.Marshal(w.body) |
| 354 | i.t.Fatalf("below 37 the worker sent %s: %s", w.f.Type, raw) |
| 355 | } |
| 356 | case <-deadline: |
| 357 | return |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | // TestWorkerTokenConnectionStored: a pasted token on a worker rests in a |
| 363 | // 0600 file in a 0700 home inside a 0700 accounts root; with the home |
| 364 | // guard failing nothing is stored. |
| 365 | func TestWorkerTokenConnectionStored(t *testing.T) { |
| 366 | r := newDarwinRig(t) |
| 367 | w := r.worker() |
| 368 | token := fakeclaude.Token("a@example.com") |
| 369 | home, end := r.paste(w.connector, "c1", token) |
| 370 | if end.State != wire.ConnHealthy { |
| 371 | t.Fatalf("not connected: %+v\n%s", end, r.logs.String()) |
| 372 | } |
| 373 | for path, want := range map[string]os.FileMode{r.root: 0o700, home: 0o700, filepath.Join(home, provider.TokenFile): 0o600} { |
| 374 | info, err := os.Lstat(path) |
| 375 | if err != nil || info.Mode().Perm() != want { |
| 376 | t.Fatalf("%s: %v %v, want %v", path, err, info.Mode().Perm(), want) |
| 377 | } |
| 378 | } |
| 379 | if b, ok := w.conns.Binding(filepath.Base(home)); !ok || b.Kind != wire.KindToken || b.PersonID != connPerson { |
| 380 | t.Fatalf("binding %+v %v", b, ok) |
| 381 | } |
| 382 | r.onlyIn(token, home) |
| 383 | // The home guard fails: refused, nothing written. |
| 384 | if err := os.Chmod(r.dir, 0o750); err != nil { |
| 385 | t.Fatal(err) |
| 386 | } |
| 387 | t.Cleanup(func() { os.Chmod(r.dir, 0o700) }) |
| 388 | home2, end := r.paste(w.connector, "c2", fakeclaude.Token("b@example.com")) |
| 389 | 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)) { |
| 390 | t.Fatalf("stored with the home guard failing: %+v seals=%d", end, r.seals("c2")) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | // TestWorkerRefusesOtherConnectionKinds: a worker keeps only Claude |
| 395 | // token connections. Codex, an API key and an endpoint are refused, each |
| 396 | // with the stated reason and nothing made in the accounts root; Claude's |
| 397 | // sign-in and a pasted token both start. |
| 398 | func TestWorkerRefusesOtherConnectionKinds(t *testing.T) { |
| 399 | r := newDarwinRig(t) |
| 400 | w := r.worker() |
| 401 | budget := &wire.Budget{Day: 5_000_000, Month: 50_000_000, Currency: "USD", Revision: 1} |
| 402 | for i, cmd := range []wire.ConnectCommand{ |
| 403 | {Provider: wire.ProviderCodex, Kind: wire.KindSubscription}, |
| 404 | {Provider: wire.ProviderCodex, Kind: wire.KindToken}, |
| 405 | {Provider: wire.ProviderTensorX, Kind: wire.KindAPIKey, Billing: wire.BillingMetered, Budget: budget}, |
| 406 | {Provider: wire.ProviderOpenCodeGo, Kind: wire.KindAPIKey, Billing: wire.BillingSubscription, Budget: budget}, |
| 407 | {Provider: "local", Kind: "endpoint"}, |
| 408 | } { |
| 409 | cmd.Connection, cmd.Person = "x"+itoa(int64(i)), connPerson |
| 410 | if err := w.connector.Accept(r.ctx, "f-"+cmd.Connection, cmd); err != nil { |
| 411 | t.Fatal(err) |
| 412 | } |
| 413 | if end := r.ended(cmd.Connection); end.State != wire.ConnError || end.Reason != wire.ReasonMacClaudeOnly { |
| 414 | t.Fatalf("%s %s: %+v", cmd.Provider, cmd.Kind, end) |
| 415 | } |
| 416 | if entries, _ := os.ReadDir(r.root); len(entries) != 0 { |
| 417 | t.Fatalf("%s %s left %d entries in the accounts root", cmd.Provider, cmd.Kind, len(entries)) |
| 418 | } |
| 419 | } |
| 420 | if !wire.ConnectReasons[wire.ReasonMacClaudeOnly] { |
| 421 | t.Fatal("the reason is not one an instance accepts") |
| 422 | } |
| 423 | r.connect(w.connector, "t1") |
| 424 | link, _ := r.signIn(w.connector, "s1") |
| 425 | if link == "" { |
| 426 | t.Fatal("no sign-in") |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | // TestWorkerCredentialHoldDurable: the worker holds the Mac as having a |
| 431 | // model credential from the moment an attempt starts, through a refused |
| 432 | // sign-in that left a Keychain item, and across a restart, until the |
| 433 | // connection's files are gone and the Keychain is clean; the hello says |
| 434 | // so, with the item's service. |
| 435 | func TestWorkerCredentialHoldDurable(t *testing.T) { |
| 436 | r := newDarwinRig(t) |
| 437 | w := r.worker() |
| 438 | if w.held(r.ctx) { |
| 439 | t.Fatal("held with nothing there") |
| 440 | } |
| 441 | r.kc.set(true) // deletes fail: the item the sign-in leaves stays |
| 442 | link, home := r.signIn(w.connector, "s1") |
| 443 | if !w.held(r.ctx) { |
| 444 | t.Fatal("not held while connecting") |
| 445 | } |
| 446 | item := r.own(r.signInDir()) |
| 447 | r.kc.add(item) |
| 448 | r.codeIn(w.connector, "s1", link, "a@example.com") |
| 449 | if end := r.ended("s1"); end.Reason != "provider_refused" { |
| 450 | t.Fatalf("end %+v", end) |
| 451 | } |
| 452 | if exists(home) { |
| 453 | t.Fatal("the refused attempt's home stayed") |
| 454 | } |
| 455 | if entries, _ := os.ReadDir(r.root); len(entries) != 0 || !w.held(r.ctx) { |
| 456 | t.Fatalf("files gone, item left: held=%v", w.held(r.ctx)) |
| 457 | } |
| 458 | h := wire.Hello{Capabilities: &wire.Capabilities{}} |
| 459 | w.hello(wire.ProtocolMacEngineering, &h) |
| 460 | if !h.Capabilities.ModelHold || !slices.Equal(h.Capabilities.HoldingItems, []string{item.Service}) || wire.ValidCapabilities(*h.Capabilities) != nil { |
| 461 | t.Fatalf("hello %+v", h.Capabilities) |
| 462 | } |
| 463 | |
| 464 | // A restart: the same state, held still. |
| 465 | again := darwinRigAt(t, r.dir) |
| 466 | again.kc = r.kc |
| 467 | again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete |
| 468 | again.kc.r = again |
| 469 | w2 := openWorkerConns(again.cfg, again.workerOptions(0), again.state, runnerproto.RunnerCredential{RunnerID: tokenRunner, Person: connPerson}, again.m, nil, nil) |
| 470 | if !w2.held(again.ctx) { |
| 471 | t.Fatal("the hold did not survive the restart") |
| 472 | } |
| 473 | // The item goes (deletes work again); the restart's settling clears it. |
| 474 | r.kc.set(false) |
| 475 | w2.connector.spawn = func(f func()) { f() } |
| 476 | if err := w2.start(again.ctx); err != nil { |
| 477 | t.Fatal(err) |
| 478 | } |
| 479 | if w2.held(again.ctx) || r.kc.has(item) { |
| 480 | t.Fatalf("still held once the files and the item are gone: %v", again.m.keychain.Residue()) |
| 481 | } |
| 482 | h = wire.Hello{Capabilities: &wire.Capabilities{}} |
| 483 | w2.hello(wire.ProtocolMacEngineering, &h) |
| 484 | if h.Capabilities.ModelHold || len(h.Capabilities.HoldingItems) != 0 { |
| 485 | t.Fatalf("hello %+v", h.Capabilities) |
| 486 | } |
| 487 | // An attempt running, or a sign-out owed, holds by itself, before |
| 488 | // anything of it is on disk. |
| 489 | for _, q := range []string{ |
| 490 | "INSERT INTO connect_attempts(id, person, provider, state, created_at) VALUES('x1', 'p', 'claude', 'running', '2026-11-29T00:00:00Z')", |
| 491 | "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) VALUES('x2', 'p', 'claude-8', 1, '2026-11-29T00:00:00Z')", |
| 492 | } { |
| 493 | if _, err := again.state.db.Exec(q); err != nil { |
| 494 | t.Fatal(err) |
| 495 | } |
| 496 | if !w2.held(again.ctx) { |
| 497 | t.Fatalf("not held by %s", q) |
| 498 | } |
| 499 | if _, err := again.state.db.Exec("DELETE FROM connect_attempts WHERE id='x1'; DELETE FROM connect_cleanups WHERE connection='x2'"); err != nil { |
| 500 | t.Fatal(err) |
| 501 | } |
| 502 | } |
| 503 | if w2.held(again.ctx) { |
| 504 | t.Fatal("held once they were gone") |
| 505 | } |
| 506 | // A file in the accounts root holds by itself. |
| 507 | if err := os.Mkdir(filepath.Join(again.root, "claude-9"), 0o700); err != nil { |
| 508 | t.Fatal(err) |
| 509 | } |
| 510 | if !w2.held(again.ctx) { |
| 511 | t.Fatal("a home in the accounts root does not hold") |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | // TestWorkerSignOutOnlyItsOwn: a disconnect addressed to another runner |
| 516 | // removes nothing here, even for a local id this runner holds. |
| 517 | func TestWorkerSignOutOnlyItsOwn(t *testing.T) { |
| 518 | r := newDarwinRig(t) |
| 519 | w := r.worker() |
| 520 | home, end := r.paste(w.connector, "c1", fakeclaude.Token("a@example.com")) |
| 521 | if end.State != wire.ConnHealthy { |
| 522 | t.Fatalf("not connected: %+v", end) |
| 523 | } |
| 524 | local := filepath.Base(home) |
| 525 | if err := w.connector.Disconnect(r.ctx, "f-out-1", wire.DisconnectCommand{Connection: "c1", Person: connPerson, LocalID: local, RunnerID: "run_primary"}); err != nil { |
| 526 | t.Fatal(err) |
| 527 | } |
| 528 | if _, ok := w.conns.Binding(local); !ok || !exists(home) { |
| 529 | t.Fatal("another runner's sign-out removed this runner's connection") |
| 530 | } |
| 531 | if err := w.connector.Disconnect(r.ctx, "f-out-2", wire.DisconnectCommand{Connection: "c1", Person: connPerson, LocalID: local, RunnerID: tokenRunner}); err != nil { |
| 532 | t.Fatal(err) |
| 533 | } |
| 534 | if _, ok := w.conns.Binding(local); ok || exists(home) { |
| 535 | t.Fatal("its own sign-out left the connection") |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | // TestWorkerProfileAtStartGated: on a Mac the start's profile reads use |
| 540 | // a token only while the Mac's guards pass: a tainted Mac reads none; an |
| 541 | // untainted one reads as Linux does. |
| 542 | func TestWorkerProfileAtStartGated(t *testing.T) { |
| 543 | r := newProfileRig(t) |
| 544 | m := &macCreds{taint: loadTaint(filepath.Join(r.dir, "state", "tainted"))} |
| 545 | m.taint.Set() |
| 546 | r.o.Mac = m |
| 547 | if named := r.start(); named != 0 || r.fake.count() != 0 { |
| 548 | t.Fatalf("a tainted Mac read %d profiles", r.fake.count()) |
| 549 | } |
| 550 | } |
| 551 | |