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 "errors"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "syscall"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/fakeclaude"
17 "amadan.net/oficina/equipo/internal/runner/mac"
18 "amadan.net/oficina/equipo/internal/runner/mac/creds"
19 "amadan.net/oficina/equipo/internal/runner/mac/proc"
20 "amadan.net/oficina/equipo/internal/wire"
21)
22
23// Task 10 fix round 2 (Astra round 2): a watch clears only once its
24// launch's end is proven (Executor.Verify) or the Mac has booted since
25// the watch began; until then the Mac keeps its Claude connections
26// closed and says so.
27
28// rebooted is a reboot of the Mac (creds.BootForTest): another boot
29// identity, begun now, later than every watch so far. No process
30// outlives a boot, so each pid in gone is ended first.
31func (r *darwinRig) rebooted(t *testing.T, gone ...int) {
32 t.Helper()
33 for _, pid := range gone {
34 _ = syscall.Kill(pid, syscall.SIGKILL)
35 }
36 now, err := creds.Boot()
37 if err != nil {
38 t.Fatal(err)
39 }
40 creds.BootForTest(func() (proc.Boot, error) { return proc.Boot{ID: now.ID + "-next", Time: time.Now()}, nil })
41 t.Cleanup(func() { creds.BootForTest(nil) })
42}
43
44// clockForward steps the Mac's clock forward with no reboot: the same
45// boot identity, its boot time read as now (kern.boottime moves when the
46// clock is stepped).
47func (r *darwinRig) clockForward(t *testing.T) {
48 t.Helper()
49 now, err := creds.Boot()
50 if err != nil {
51 t.Fatal(err)
52 }
53 creds.BootForTest(func() (proc.Boot, error) { return proc.Boot{ID: now.ID, Time: time.Now()}, nil })
54 t.Cleanup(func() { creds.BootForTest(nil) })
55}
56
57// crashCheck starts a check in a second runner process and SIGKILLs it
58// while the check's CLI runs (steered by the hang file); it returns the
59// hung CLI's pid.
60func (r *darwinRig) crashCheck(t *testing.T, local string) int {
61 t.Helper()
62 if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil {
63 t.Fatal(err)
64 }
65 helper := exec.Command(os.Args[0], "-test.run=^TestDarwinTokenCheckCrashHelper$", "-test.count=1")
66 helper.Env = append(os.Environ(), "EQUIPO_DARWIN_CRASH_DIR="+r.dir, "EQUIPO_DARWIN_CRASH_LOCAL="+local)
67 if err := helper.Start(); err != nil {
68 t.Fatal(err)
69 }
70 pid := waitPid(t, filepath.Join(r.dir, "hang.pid"))
71 _ = helper.Process.Kill()
72 _ = helper.Wait()
73 os.Remove(filepath.Join(r.dir, "hang"))
74 return pid
75}
76
77// TestDarwinCrashedWatchHeldUntilReboot: a runner dies during a check,
78// and something of that launch the runner cannot see survives (an
79// unmarked process in a session of its own: on a Mac, say, a descendant
80// that changed its real uid, which no turn's sweep reaches; started here
81// by the test, since a test cannot change uid). It writes a credential
82// into the Keychain a moment later. The restart
83// cannot prove the launch ended, so the hold stays (and the Mac's
84// connections stay closed) through the late write; once the Mac has
85// booted since, the watch's second look finds the item and deletes it.
86func TestDarwinCrashedWatchHeldUntilReboot(t *testing.T) {
87 r := newDarwinRig(t)
88 local, _ := connected(t, r, fakeclaude.Token("a@example.com"))
89 var item creds.Item
90 r.kc.appear = func() []creds.Item {
91 if _, err := os.Stat(filepath.Join(r.dir, "wrote")); err != nil {
92 return nil
93 }
94 raw, _ := os.ReadFile(filepath.Join(r.dir, "hang.pid"))
95 for _, l := range r.launches() {
96 if strconv.Itoa(l.pid) == strings.TrimSpace(string(raw)) {
97 item = r.own(l.env["CLAUDE_CONFIG_DIR"])
98 return []creds.Item{item}
99 }
100 }
101 return nil
102 }
103 hung := r.crashCheck(t, local)
104 survivor := exec.Command("/bin/sh", "-c", "sleep 1; touch "+filepath.Join(r.dir, "wrote"))
105 survivor.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
106 if err := survivor.Start(); err != nil {
107 t.Fatal(err)
108 }
109 defer func() { _ = survivor.Wait() }()
110 r.connector()
111 if !r.m.Held() || len(unprovenOf(r.m)) != 1 {
112 t.Fatalf("the restart let go of a launch it could not prove ended: held=%v unproven=%v", r.m.Held(), unprovenOf(r.m))
113 }
114 b, _ := r.binding(local)
115 if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errCredentialUnproven) {
116 t.Fatalf("a check with an unproven launch on record: %v", err)
117 }
118 r.waitFor(func() bool { _, err := os.Stat(filepath.Join(r.dir, "wrote")); return err == nil }, "the survivor's late write")
119 // The write lands in the Keychain (the fake stores it at a listing).
120 _, _ = r.kc.list(r.ctx, r.m.keychain.Login)
121 r.m.settle(r.ctx, true)
122 if !r.m.Held() || item == (creds.Item{}) || !r.kc.has(item) {
123 t.Fatalf("after the late write: held=%v item %+v", r.m.Held(), item)
124 }
125 // The boot time earlier than the watch: still held.
126 r.m.settle(r.ctx, true)
127 if !r.m.Held() {
128 t.Fatal("released with the Mac booted before the watch began")
129 }
130 r.rebooted(t, hung)
131 r.m.settle(r.ctx, true)
132 if r.kc.has(item) || len(unprovenOf(r.m)) != 0 {
133 t.Fatalf("after a reboot: item kept=%v unproven=%v", r.kc.has(item), unprovenOf(r.m))
134 }
135 r.m.settle(r.ctx, false)
136 if r.m.Held() {
137 t.Fatal("held after a reboot and a listing showing the item gone")
138 }
139}
140
141// TestDarwinUnprovenClosesConnections: an unproven credential launch in
142// this process closes the Mac's connections and says why
143// (credential_unproven); a restart opens them again once Verify proves
144// the launch over (its leftover killed by its record).
145func TestDarwinUnprovenClosesConnections(t *testing.T) {
146 r := newDarwinRig(t)
147 c := r.connector()
148 home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com"))
149 b, _ := r.binding(filepath.Base(home))
150 r.lingering(t, "-p")
151 if _, err := r.opts.CheckToken(r.ctx, b); err == nil {
152 t.Fatal("an unproven check passed")
153 }
154 os.Remove(filepath.Join(r.dir, "linger"))
155 if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errCredentialUnproven) {
156 t.Fatalf("a check after an unproven one: %v", err)
157 }
158 if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 {
159 t.Fatalf("a token stored after an unproven launch: %+v", end)
160 }
161 h := &macHost{creds: r.m, taint: r.m.taint, turns: r.m.turns}
162 caps := wire.Capabilities{}
163 h.credentialCaps(r.ctx, &caps)
164 if caps.Unproven != wire.UnprovenCredential || wire.ValidCapabilities(caps) != nil {
165 t.Fatalf("caps %+v", caps)
166 }
167 // The restart proves it over: the leftover carries its record.
168 again := darwinRigAt(t, r.dir)
169 again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete
170 again.connector()
171 if _, err := again.opts.CheckToken(again.ctx, b); err != nil {
172 t.Fatalf("after the restart proved it over: %v", err)
173 }
174}
175
176// unprovenOf is m's unproven watches ("?" for an error).
177func unprovenOf(m *macCreds) []string {
178 left, err := m.keychain.Unproven()
179 if err != nil {
180 return []string{"?"}
181 }
182 return left
183}
184
185// TestDarwinUnreadableWatchesStayClosed (fix round 3, #1): with an
186// unproven launch on record and the watch records unreadable, no token
187// is stored and the Mac still says credential_unproven.
188func TestDarwinUnreadableWatchesStayClosed(t *testing.T) {
189 r := newDarwinRig(t)
190 c := r.connector()
191 home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com"))
192 b, _ := r.binding(filepath.Base(home))
193 r.lingering(t, "-p")
194 if _, err := r.opts.CheckToken(r.ctx, b); err == nil {
195 t.Fatal("an unproven check passed")
196 }
197 if err := os.Chmod(r.m.keychain.Dir, 0); err != nil {
198 t.Fatal(err)
199 }
200 defer os.Chmod(r.m.keychain.Dir, 0o700)
201 if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 {
202 t.Fatalf("a token stored with the watch records unreadable: %+v seals=%d", end, r.seals("c2"))
203 }
204 h := &macHost{creds: r.m, taint: r.m.taint, turns: r.m.turns}
205 caps := wire.Capabilities{}
206 h.credentialCaps(r.ctx, &caps)
207 if caps.Unproven != wire.UnprovenCredential {
208 t.Fatalf("caps %+v", caps.Unproven)
209 }
210}
211
212// TestDarwinClearanceVerifiesTheRecordedRun (fix round 3, #2): a watch
213// whose launch's recorded group is still alive, with nothing in it
214// carrying the marker (a child that scrubbed its environment), and the
215// Mac booted before the watch began, is not cleared: Verify judges the
216// recorded run, group and all, not the marker alone. Once the group is
217// gone it clears.
218func TestDarwinClearanceVerifiesTheRecordedRun(t *testing.T) {
219 r := newDarwinRig(t)
220 marker := "status-scrubbed"
221 if err := r.m.keychain.Before(r.ctx, marker, filepath.Join(r.cfg.ScratchRoot, "homes", marker)); err != nil {
222 t.Fatal(err)
223 }
224 group := exec.Command("/bin/sleep", "60")
225 group.Env = []string{}
226 group.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
227 if err := group.Start(); err != nil {
228 t.Fatal(err)
229 }
230 waited := make(chan struct{})
231 go func() { _ = group.Wait(); close(waited) }()
232 defer func() { _ = group.Process.Kill(); <-waited }()
233 if err := r.m.keychain.Ran(marker, mac.RecordID(group.Process.Pid, marker)); err != nil {
234 t.Fatal(err)
235 }
236 r.m.keychain.Abandon(marker)
237 if boot, err := creds.Boot(); err != nil || !boot.Time.Before(time.Now()) {
238 t.Fatalf("boot %v %v", boot, err)
239 }
240 r.m.settle(r.ctx, true)
241 if !r.m.Held() || len(unprovenOf(r.m)) != 1 || !pidAlive(group.Process.Pid) {
242 t.Fatalf("cleared with its recorded group alive: held=%v unproven=%v", r.m.Held(), unprovenOf(r.m))
243 }
244 _ = group.Process.Kill()
245 <-waited
246 r.m.settle(r.ctx, true)
247 if r.m.Held() || len(unprovenOf(r.m)) != 0 {
248 t.Fatalf("held once its group is gone: %v", unprovenOf(r.m))
249 }
250}
251