//go:build testbuild package thin import ( "errors" "os" "os/exec" "path/filepath" "strconv" "strings" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/creds" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/wire" ) // Task 10 fix round 2 (Astra round 2): a watch clears only once its // launch's end is proven (Executor.Verify) or the Mac has booted since // the watch began; until then the Mac keeps its Claude connections // closed and says so. // rebooted is a reboot of the Mac (creds.BootForTest): another boot // identity, begun now, later than every watch so far. No process // outlives a boot, so each pid in gone is ended first. func (r *darwinRig) rebooted(t *testing.T, gone ...int) { t.Helper() for _, pid := range gone { _ = syscall.Kill(pid, syscall.SIGKILL) } now, err := creds.Boot() if err != nil { t.Fatal(err) } creds.BootForTest(func() (proc.Boot, error) { return proc.Boot{ID: now.ID + "-next", Time: time.Now()}, nil }) t.Cleanup(func() { creds.BootForTest(nil) }) } // clockForward steps the Mac's clock forward with no reboot: the same // boot identity, its boot time read as now (kern.boottime moves when the // clock is stepped). func (r *darwinRig) clockForward(t *testing.T) { t.Helper() now, err := creds.Boot() if err != nil { t.Fatal(err) } creds.BootForTest(func() (proc.Boot, error) { return proc.Boot{ID: now.ID, Time: time.Now()}, nil }) t.Cleanup(func() { creds.BootForTest(nil) }) } // crashCheck starts a check in a second runner process and SIGKILLs it // while the check's CLI runs (steered by the hang file); it returns the // hung CLI's pid. func (r *darwinRig) crashCheck(t *testing.T, local string) int { t.Helper() if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { t.Fatal(err) } helper := exec.Command(os.Args[0], "-test.run=^TestDarwinTokenCheckCrashHelper$", "-test.count=1") helper.Env = append(os.Environ(), "EQUIPO_DARWIN_CRASH_DIR="+r.dir, "EQUIPO_DARWIN_CRASH_LOCAL="+local) if err := helper.Start(); err != nil { t.Fatal(err) } pid := waitPid(t, filepath.Join(r.dir, "hang.pid")) _ = helper.Process.Kill() _ = helper.Wait() os.Remove(filepath.Join(r.dir, "hang")) return pid } // TestDarwinCrashedWatchHeldUntilReboot: a runner dies during a check, // and something of that launch the runner cannot see survives (an // unmarked process in a session of its own: on a Mac, say, a descendant // that changed its real uid, which no turn's sweep reaches; started here // by the test, since a test cannot change uid). It writes a credential // into the Keychain a moment later. The restart // cannot prove the launch ended, so the hold stays (and the Mac's // connections stay closed) through the late write; once the Mac has // booted since, the watch's second look finds the item and deletes it. func TestDarwinCrashedWatchHeldUntilReboot(t *testing.T) { r := newDarwinRig(t) local, _ := connected(t, r, fakeclaude.Token("a@example.com")) var item creds.Item r.kc.appear = func() []creds.Item { if _, err := os.Stat(filepath.Join(r.dir, "wrote")); err != nil { return nil } raw, _ := os.ReadFile(filepath.Join(r.dir, "hang.pid")) for _, l := range r.launches() { if strconv.Itoa(l.pid) == strings.TrimSpace(string(raw)) { item = r.own(l.env["CLAUDE_CONFIG_DIR"]) return []creds.Item{item} } } return nil } hung := r.crashCheck(t, local) survivor := exec.Command("/bin/sh", "-c", "sleep 1; touch "+filepath.Join(r.dir, "wrote")) survivor.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := survivor.Start(); err != nil { t.Fatal(err) } defer func() { _ = survivor.Wait() }() r.connector() if !r.m.Held() || len(unprovenOf(r.m)) != 1 { t.Fatalf("the restart let go of a launch it could not prove ended: held=%v unproven=%v", r.m.Held(), unprovenOf(r.m)) } b, _ := r.binding(local) if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errCredentialUnproven) { t.Fatalf("a check with an unproven launch on record: %v", err) } r.waitFor(func() bool { _, err := os.Stat(filepath.Join(r.dir, "wrote")); return err == nil }, "the survivor's late write") // The write lands in the Keychain (the fake stores it at a listing). _, _ = r.kc.list(r.ctx, r.m.keychain.Login) r.m.settle(r.ctx, true) if !r.m.Held() || item == (creds.Item{}) || !r.kc.has(item) { t.Fatalf("after the late write: held=%v item %+v", r.m.Held(), item) } // The boot time earlier than the watch: still held. r.m.settle(r.ctx, true) if !r.m.Held() { t.Fatal("released with the Mac booted before the watch began") } r.rebooted(t, hung) r.m.settle(r.ctx, true) if r.kc.has(item) || len(unprovenOf(r.m)) != 0 { t.Fatalf("after a reboot: item kept=%v unproven=%v", r.kc.has(item), unprovenOf(r.m)) } r.m.settle(r.ctx, false) if r.m.Held() { t.Fatal("held after a reboot and a listing showing the item gone") } } // TestDarwinUnprovenClosesConnections: an unproven credential launch in // this process closes the Mac's connections and says why // (credential_unproven); a restart opens them again once Verify proves // the launch over (its leftover killed by its record). func TestDarwinUnprovenClosesConnections(t *testing.T) { r := newDarwinRig(t) c := r.connector() home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com")) b, _ := r.binding(filepath.Base(home)) r.lingering(t, "-p") if _, err := r.opts.CheckToken(r.ctx, b); err == nil { t.Fatal("an unproven check passed") } os.Remove(filepath.Join(r.dir, "linger")) if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errCredentialUnproven) { t.Fatalf("a check after an unproven one: %v", err) } if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 { t.Fatalf("a token stored after an unproven launch: %+v", end) } h := &macHost{creds: r.m, taint: r.m.taint, turns: r.m.turns} caps := wire.Capabilities{} h.credentialCaps(r.ctx, &caps) if caps.Unproven != wire.UnprovenCredential || wire.ValidCapabilities(caps) != nil { t.Fatalf("caps %+v", caps) } // The restart proves it over: the leftover carries its record. again := darwinRigAt(t, r.dir) again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete again.connector() if _, err := again.opts.CheckToken(again.ctx, b); err != nil { t.Fatalf("after the restart proved it over: %v", err) } } // unprovenOf is m's unproven watches ("?" for an error). func unprovenOf(m *macCreds) []string { left, err := m.keychain.Unproven() if err != nil { return []string{"?"} } return left } // TestDarwinUnreadableWatchesStayClosed (fix round 3, #1): with an // unproven launch on record and the watch records unreadable, no token // is stored and the Mac still says credential_unproven. func TestDarwinUnreadableWatchesStayClosed(t *testing.T) { r := newDarwinRig(t) c := r.connector() home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com")) b, _ := r.binding(filepath.Base(home)) r.lingering(t, "-p") if _, err := r.opts.CheckToken(r.ctx, b); err == nil { t.Fatal("an unproven check passed") } if err := os.Chmod(r.m.keychain.Dir, 0); err != nil { t.Fatal(err) } defer os.Chmod(r.m.keychain.Dir, 0o700) if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 { t.Fatalf("a token stored with the watch records unreadable: %+v seals=%d", end, r.seals("c2")) } h := &macHost{creds: r.m, taint: r.m.taint, turns: r.m.turns} caps := wire.Capabilities{} h.credentialCaps(r.ctx, &caps) if caps.Unproven != wire.UnprovenCredential { t.Fatalf("caps %+v", caps.Unproven) } } // TestDarwinClearanceVerifiesTheRecordedRun (fix round 3, #2): a watch // whose launch's recorded group is still alive, with nothing in it // carrying the marker (a child that scrubbed its environment), and the // Mac booted before the watch began, is not cleared: Verify judges the // recorded run, group and all, not the marker alone. Once the group is // gone it clears. func TestDarwinClearanceVerifiesTheRecordedRun(t *testing.T) { r := newDarwinRig(t) marker := "status-scrubbed" if err := r.m.keychain.Before(r.ctx, marker, filepath.Join(r.cfg.ScratchRoot, "homes", marker)); err != nil { t.Fatal(err) } group := exec.Command("/bin/sleep", "60") group.Env = []string{} group.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := group.Start(); err != nil { t.Fatal(err) } waited := make(chan struct{}) go func() { _ = group.Wait(); close(waited) }() defer func() { _ = group.Process.Kill(); <-waited }() if err := r.m.keychain.Ran(marker, mac.RecordID(group.Process.Pid, marker)); err != nil { t.Fatal(err) } r.m.keychain.Abandon(marker) if boot, err := creds.Boot(); err != nil || !boot.Time.Before(time.Now()) { t.Fatalf("boot %v %v", boot, err) } r.m.settle(r.ctx, true) if !r.m.Held() || len(unprovenOf(r.m)) != 1 || !pidAlive(group.Process.Pid) { t.Fatalf("cleared with its recorded group alive: held=%v unproven=%v", r.m.Held(), unprovenOf(r.m)) } _ = group.Process.Kill() <-waited r.m.settle(r.ctx, true) if r.m.Held() || len(unprovenOf(r.m)) != 0 { t.Fatalf("held once its group is gone: %v", unprovenOf(r.m)) } }