oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build testbuild
2
3package thin
4
5import (
6 "context"
7 "errors"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strconv"
12 "strings"
13 "syscall"
14 "testing"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/fakeclaude"
18 "amadan.net/oficina/equipo/internal/runner/mac"
19 "amadan.net/oficina/equipo/internal/runner/mac/creds"
20 "amadan.net/oficina/equipo/internal/runner/provider"
21 "amadan.net/oficina/equipo/internal/wire"
22 "golang.org/x/sys/unix"
23)
24
25// Task 10 fix round 1 (Astra round 1): the Keychain watch around the
26// token check and auth status (#3), the termination proof of a check
27// (#4), and direct tests of every guard the thin wiring added (#6).
28
29// connected is a rig with one healthy pasted-token connection: its
30// binding and token-home binding.
31func connected(t *testing.T, r *darwinRig, token string) (b, home string) {
32 t.Helper()
33 h, end := r.paste(r.connector(), "c1", token)
34 if end.State != wire.ConnHealthy {
35 t.Fatalf("not connected: %+v", end)
36 }
37 return filepath.Base(h), h
38}
39
40// statusBinding is the token home as auth status reads it.
41func statusBinding(local, home string) provider.Binding {
42 return provider.Binding{ID: local, Home: home, Provider: wire.ProviderClaude, Token: true}
43}
44
45// lingering steers the next launch whose first argument is arg to leave
46// a child that ignores SIGTERM; its end then cannot be proven within a
47// short Settle. The child is killed at the test's end.
48func (r *darwinRig) lingering(t *testing.T, arg string) {
49 t.Helper()
50 r.m.exec.Settle, r.m.exec.Grace = 500*time.Millisecond, time.Minute
51 if err := os.WriteFile(filepath.Join(r.dir, "linger"), []byte(arg), 0o600); err != nil {
52 t.Fatal(err)
53 }
54 t.Cleanup(func() {
55 if raw, err := os.ReadFile(filepath.Join(r.dir, "linger.pid")); err == nil {
56 if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil {
57 _ = syscall.Kill(pid, syscall.SIGKILL)
58 }
59 }
60 })
61}
62
63// TestDarwinCheckKeychainWatch (#3): the token check and auth status are
64// watched as the sign-in is: an item a launch leaves refuses it, its own
65// is deleted, anything else holds; a cancelled check is looked at too,
66// and a crash is settled at the restart.
67func TestDarwinCheckKeychainWatch(t *testing.T) {
68 t.Run("the check's own item refuses it and is deleted", func(t *testing.T) {
69 r := newDarwinRig(t)
70 local, _ := connected(t, r, fakeclaude.Token("a@example.com"))
71 r.creating("-p ", r.own)
72 b, _ := r.binding(local)
73 _, err := r.opts.CheckToken(r.ctx, b)
74 if !errors.Is(err, errKeychain) || len(r.kc.deleted) != 1 || r.m.Held() {
75 t.Fatalf("check: %v deleted %+v held=%v", err, r.kc.deleted, r.m.Held())
76 }
77 if !strings.HasPrefix(r.kc.deleted[0].Service, "Claude Code-credentials-") || r.kc.deleted[0].Keychain != r.m.keychain.Login {
78 t.Fatalf("deleted %+v", r.kc.deleted)
79 }
80 })
81 t.Run("an unrelated item during the check holds", func(t *testing.T) {
82 r := newDarwinRig(t)
83 local, _ := connected(t, r, fakeclaude.Token("a@example.com"))
84 r.creating("-p ", func(string) creds.Item {
85 return creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user}
86 })
87 b, _ := r.binding(local)
88 if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errKeychain) || len(r.kc.deleted) != 0 || !r.m.Held() {
89 t.Fatalf("check: %v deleted %+v held=%v", err, r.kc.deleted, r.m.Held())
90 }
91 })
92 t.Run("auth status's own item refuses the connection", func(t *testing.T) {
93 r := newDarwinRig(t)
94 r.creating("auth status", r.own)
95 _, end := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com"))
96 if end.Reason != "provider_refused" || len(r.kc.deleted) != 1 || r.m.Held() {
97 t.Fatalf("end %+v deleted %+v held=%v", end, r.kc.deleted, r.m.Held())
98 }
99 })
100 t.Run("auth status called alone is watched", func(t *testing.T) {
101 r := newDarwinRig(t)
102 local, home := connected(t, r, fakeclaude.Token("a@example.com"))
103 r.creating("auth status", r.own)
104 if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, errKeychain) || len(r.kc.deleted) != 1 {
105 t.Fatalf("auth status: %v deleted %+v", err, r.kc.deleted)
106 }
107 })
108 t.Run("a cancelled check is looked at", func(t *testing.T) {
109 r := newDarwinRig(t)
110 local, _ := connected(t, r, fakeclaude.Token("a@example.com"))
111 r.creating("-p ", r.own)
112 if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil {
113 t.Fatal(err)
114 }
115 b, _ := r.binding(local)
116 ctx, cancel := context.WithCancel(r.ctx)
117 done := make(chan error, 1)
118 go func() { _, err := r.opts.CheckToken(ctx, b); done <- err }()
119 waitPid(t, filepath.Join(r.dir, "hang.pid"))
120 cancel()
121 <-done
122 if len(r.kc.deleted) != 1 || r.m.Held() {
123 t.Fatalf("after the cancel: deleted %+v held=%v", r.kc.deleted, r.m.Held())
124 }
125 })
126 t.Run("a crashed check's watch is held until a reboot", func(t *testing.T) {
127 r := newDarwinRig(t)
128 local, _ := connected(t, r, fakeclaude.Token("a@example.com"))
129 if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil {
130 t.Fatal(err)
131 }
132 helper := exec.Command(os.Args[0], "-test.run=^TestDarwinTokenCheckCrashHelper$", "-test.count=1")
133 helper.Env = append(os.Environ(), "EQUIPO_DARWIN_CRASH_DIR="+r.dir, "EQUIPO_DARWIN_CRASH_LOCAL="+local)
134 if err := helper.Start(); err != nil {
135 t.Fatal(err)
136 }
137 pid := waitPid(t, filepath.Join(r.dir, "hang.pid"))
138 _ = helper.Process.Kill()
139 _ = helper.Wait()
140 if !r.m.Held() {
141 t.Fatal("the dead runner's check left no watch")
142 }
143 // What its CLI stored meanwhile (its launch is on disk already).
144 r.creating("-p ", r.own)
145 r.kc.mu.Lock()
146 delete(r.kc.created, pid)
147 r.kc.mu.Unlock()
148 // The restart cannot prove it over (fix round 2): held.
149 r.connector()
150 if !r.m.Held() || len(r.kc.deleted) != 0 {
151 t.Fatalf("after a restart without a reboot: held=%v deleted %+v", r.m.Held(), r.kc.deleted)
152 }
153 r.rebooted(t, pid)
154 r.connector()
155 if r.m.Held() || len(r.kc.deleted) != 1 {
156 t.Fatalf("after a reboot: held=%v deleted %+v", r.m.Held(), r.kc.deleted)
157 }
158 })
159}
160
161// TestDarwinCheckUnprovenIsNotSuccess (#4): a check that answered but
162// whose end cannot be proven fails with mac.ErrUnproven: the profile is
163// not read, and the watch and the turn's record stay for recovery.
164func TestDarwinCheckUnprovenIsNotSuccess(t *testing.T) {
165 r := newDarwinRig(t)
166 local, _ := connected(t, r, fakeclaude.Token(""))
167 b, _ := r.binding(local)
168 clock := time.Now()
169 fake := newFakeProfile(t, "")
170 fake.answer(200, "a@example.com")
171 r.opts.Profile = fake.reader(&clock)
172 r.lingering(t, "-p")
173 _, err := r.opts.CheckToken(r.ctx, b)
174 if !errors.Is(err, mac.ErrUnproven) {
175 t.Fatalf("an unproven check: %v", err)
176 }
177 if fake.count() != 0 {
178 t.Fatal("the profile was read after an unproven check")
179 }
180 if !r.m.Held() {
181 t.Fatal("the check's watch was dropped with its end unproven")
182 }
183 if _, err := os.Stat(filepath.Join(r.cfg.StateDir, "mac-gate.lock.turn")); err != nil {
184 t.Fatalf("the turn's record was dropped: %v", err)
185 }
186 // Control: once a restart proves it over, the check reads the
187 // profile.
188 os.Remove(filepath.Join(r.dir, "linger"))
189 again := darwinRigAt(t, r.dir)
190 again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete
191 again.opts.Profile = fake.reader(&clock)
192 again.connector()
193 if _, err := again.opts.CheckToken(again.ctx, b); err != nil || fake.count() != 1 {
194 t.Fatalf("a proven check: %v, %d profile reads", err, fake.count())
195 }
196 t.Run("auth status", func(t *testing.T) {
197 r := newDarwinRig(t)
198 local, home := connected(t, r, fakeclaude.Token("a@example.com"))
199 r.lingering(t, "auth")
200 if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, mac.ErrUnproven) || !r.m.Held() || len(unprovenOf(r.m)) != 1 {
201 t.Fatalf("an unproven auth status: %v held=%v unproven=%v", err, r.m.Held(), unprovenOf(r.m))
202 }
203 })
204}
205
206// TestDarwinAuthStatusGates (#6): auth status, which madeToken calls on
207// its own, refuses a tainted runner and an open home before it starts
208// anything.
209func TestDarwinAuthStatusGates(t *testing.T) {
210 t.Run("tainted", func(t *testing.T) {
211 r := newDarwinRig(t)
212 local, home := connected(t, r, fakeclaude.Token("a@example.com"))
213 before := len(r.launches())
214 r.m.taint.Set()
215 if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, errTainted) || len(r.launches()) != before {
216 t.Fatalf("a tainted auth status: %v", err)
217 }
218 })
219 t.Run("home open", func(t *testing.T) {
220 r := newDarwinRig(t)
221 local, home := connected(t, r, fakeclaude.Token("a@example.com"))
222 before := len(r.launches())
223 if err := os.Chmod(r.dir, 0o750); err != nil {
224 t.Fatal(err)
225 }
226 var open *homeOpen
227 if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.As(err, &open) || len(r.launches()) != before {
228 t.Fatalf("auth status with the home open: %v", err)
229 }
230 })
231 t.Run("not a token", func(t *testing.T) {
232 r := newDarwinRig(t)
233 if _, err := r.m.authStatus(r.ctx, provider.Binding{ID: "x", Home: r.root, Provider: wire.ProviderClaude}); !errors.Is(err, provider.ErrLoginUnavailable) {
234 t.Fatalf("a subscription home: %v", err)
235 }
236 })
237}
238
239// TestDarwinCheckRefusesBeforeTheLease (#6): the check's own gate
240// refuses before the account's lease is opened: with the account busy,
241// a tainted runner still says tainted at once.
242func TestDarwinCheckRefusesBeforeTheLease(t *testing.T) {
243 r := newDarwinRig(t)
244 local, home := connected(t, r, fakeclaude.Token("a@example.com"))
245 b, _ := r.binding(local)
246 lock, err := os.Open(home)
247 if err != nil {
248 t.Fatal(err)
249 }
250 defer lock.Close()
251 if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil {
252 t.Fatal(err)
253 }
254 r.m.taint.Set()
255 start := time.Now()
256 if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errTainted) || time.Since(start) > 2*time.Second {
257 t.Fatalf("a tainted check with the account busy: %v after %s", err, time.Since(start))
258 }
259}
260
261// TestDarwinStoreWaitsForTheTurn (#6): a token is stored only in the
262// Mac's turn: while another operation holds it, the delivery waits, then
263// fails to be sent again, and nothing is written.
264func TestDarwinStoreWaitsForTheTurn(t *testing.T) {
265 r := newDarwinRig(t)
266 was := tokenStoreWait
267 tokenStoreWait = 300 * time.Millisecond
268 defer func() { tokenStoreWait = was }()
269 c := r.connector()
270 r.connect(c, "c1")
271 u, ok := r.m.turns.TryTake(mac.OpWarm)
272 if !ok {
273 t.Fatal("the turn is busy")
274 }
275 cmd := r.sealed("c1", fakeclaude.Token("a@example.com"), nil)
276 if r.deliver(c, "f-c1", cmd) || r.seals("c1") != 0 {
277 t.Fatal("stored while another operation held the turn")
278 }
279 u.Give()
280 if !r.deliver(c, "f-c1", cmd) || r.ended("c1").State != wire.ConnHealthy {
281 t.Fatal("the resend after the turn was free did not connect")
282 }
283}
284
285// TestDarwinSignInUnprovenKeepsTheWatch (#6): a sign-in whose CLI's end
286// cannot be proven keeps its watch (and its attempt, for the restart).
287func TestDarwinSignInUnprovenKeepsTheWatch(t *testing.T) {
288 r := newDarwinRig(t)
289 r.lingering(t, "setup-token")
290 c := r.connector()
291 r.signIn(c, "s1")
292 if err := c.Cancel(r.ctx, "f-cancel-s1", wire.CancelConnectCommand{Connection: "s1", Person: connPerson}); err != nil {
293 t.Fatal(err)
294 }
295 r.waitFor(func() bool { return r.turnFree() }, "the sign-in to stop")
296 var state string
297 _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id='s1'").Scan(&state)
298 if !r.m.Held() || state != "running" || len(unprovenOf(r.m)) != 1 {
299 t.Fatalf("an unproven sign-in: held=%v state=%s", r.m.Held(), state)
300 }
301}
302
303// TestDarwinSignInRecoveredAtRestart (#6): a sign-in left running by a
304// dead runner has its CLI killed by its record at the restart, then
305// ends runner_offline.
306func TestDarwinSignInRecoveredAtRestart(t *testing.T) {
307 r := newDarwinRig(t)
308 marker := "signin-left"
309 cmd := exec.Command("/bin/sleep", "600")
310 cmd.Env = []string{"EQUIPO_ATTEMPT=" + marker}
311 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
312 if err := cmd.Start(); err != nil {
313 t.Fatal(err)
314 }
315 go func() { _ = cmd.Wait() }()
316 defer func() { _ = cmd.Process.Kill() }()
317 if _, err := r.state.db.Exec("INSERT INTO connect_attempts(id, person, provider, state, kind, namespace, created_at) VALUES(?,?,?,?,?,?,?)", "s1", connPerson, wire.ProviderClaude, "running", wire.KindSubscription, mac.RecordID(cmd.Process.Pid, marker), now()); err != nil {
318 t.Fatal(err)
319 }
320 r.connector()
321 if end := r.ended("s1"); end.Reason != "runner_offline" {
322 t.Fatalf("end %+v", end)
323 }
324 r.waitFor(func() bool { return !pidAlive(cmd.Process.Pid) }, "the left CLI to be gone")
325}
326
327// TestDarwinStartRefusesABadToken (#6): the descriptor carries only a
328// token that fits one: no NUL, CR or LF, not empty, bounded.
329func TestDarwinStartRefusesABadToken(t *testing.T) {
330 r := newDarwinRig(t)
331 u, err := r.m.turns.Take(r.ctx, mac.OpTokenCheck)
332 if err != nil {
333 t.Fatal(err)
334 }
335 defer u.Give()
336 dir, marker, err := r.m.place("status-")
337 if err != nil {
338 t.Fatal(err)
339 }
340 for _, tok := range [][]byte{{}, []byte("sk-ant\nx"), []byte("sk\x00"), make([]byte, mac.MaxToken+1)} {
341 if _, err := r.m.start(u.Context(r.ctx), dir, marker, mac.Command{Env: r.m.env(dir, marker, true)}, tok, func(string) error { return nil }, "auth", "status", "--json"); !errors.Is(err, provider.ErrPolicy) {
342 t.Fatalf("token %q: %v", tok, err)
343 }
344 }
345 if len(r.launches()) != 0 {
346 t.Fatal("a bad token started the CLI")
347 }
348}
349
350// TestMacCapsSettleTheKeychain (#6): the hourly capability gathering
351// looks again for what the Keychain watch found, and lets go once it is
352// gone.
353func TestMacCapsSettleTheKeychain(t *testing.T) {
354 r := newDarwinRig(t)
355 h := &macHost{creds: r.m, taint: r.m.taint}
356 other := creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user}
357 if err := r.m.keychain.Before(r.ctx, "signin-1", filepath.Join(r.cfg.ScratchRoot, "homes", "signin-1")); err != nil {
358 t.Fatal(err)
359 }
360 r.kc.add(other)
361 if _, err := r.m.keychain.After(r.ctx, "signin-1"); err != nil || !r.m.Held() {
362 t.Fatalf("not held: %v", err)
363 }
364 r.kc.mu.Lock()
365 r.kc.items = nil
366 r.kc.mu.Unlock()
367 caps := wire.Capabilities{}
368 h.credentialCaps(r.ctx, &caps)
369 if r.m.Held() {
370 t.Fatal("the gathering did not look again")
371 }
372}
373
374// TestMacKeychainListsLoginByPath (#2): the runner lists its login
375// keychain by its path, and refuses to decide when it is not there.
376func TestMacKeychainListsLoginByPath(t *testing.T) {
377 dir := shortDir(t)
378 args := filepath.Join(dir, "args")
379 security := filepath.Join(dir, "security")
380 login := filepath.Join(dir, "login.keychain-db")
381 script := "#!/bin/sh\necho \"$@\" > " + args + "\nprintf 'keychain: \"%s\"\\nclass: \"genp\"\\nattributes:\\n \"acct\"<blob>=\"u\"\\n \"svce\"<blob>=\"Other App\"\\n' \"$2\"\n"
382 if err := os.WriteFile(security, []byte(script), 0o700); err != nil {
383 t.Fatal(err)
384 }
385 was, wasOn := macSecurity, macKeychains
386 macSecurity, macKeychains = security, true
387 defer func() { macSecurity, macKeychains = was, wasOn }()
388 h := &macHost{}
389 if _, err := h.keychainList(context.Background(), login); err == nil {
390 t.Fatal("listed a login keychain that is not there")
391 }
392 if err := os.WriteFile(login, nil, 0o600); err != nil {
393 t.Fatal(err)
394 }
395 items, err := h.keychainList(context.Background(), login)
396 raw, _ := os.ReadFile(args)
397 if err != nil || strings.TrimSpace(string(raw)) != "dump-keychain "+login || len(items) != 1 || items[0].Keychain != login {
398 t.Fatalf("listed %q: %+v %v", raw, items, err)
399 }
400}
401