Mac slice F task 10 fix 1: keychain identity, login path, watched checks
Astra round 1 (6 Important), with the controller's rulings: 1. Keychain items are known by stable attributes only (keychain, service, account, cdat). An unreadable CLI-named or service-less item refuses a preflight. A hold goes only once a listing positively shows the identity absent; an unreadable listing decides nothing. 2. The login keychain is listed by path (security dump-keychain <login>), whatever the search list says, and it fails closed when the file is missing or the listing fails. Other keychains are ignored. 3. The token check and auth status get the sign-in's durable Keychain watch, including on cancel and at restart. A crashed launch counts as ended when Verify proves it, or when its dead turn is settled and nothing carries its marker. 4. The check keeps proc.Wait's error. A valid answer whose end is not proven is mac.ErrUnproven: no profile read, and the watch and the turn record are kept. 5. The home guard precomputes its protected roots, so the root rule applies however a root is reached. 6. Recorded exception (controller ruling, as for task 9): the original thin wiring was written before its tests. Every guard it added was broken and its named test seen to fail, then restored: T1 taint gate, T2 home gate, T3 check gate, T4 auth status gate, T5 sign-in gate, T6 store gate, T7 store Keychain check, T8 Secret refusal, T9 keep via the Mac, T10-T13 turns (check, auth status, sign-in, store), T14 token by descriptor, T15 token shape, T16 before-list first, T17 unproven sign-in keeps watch, T18-T20 Keychain refusal path, T21 namespace proof, T22 settle at Start, T23 madeToken auth status, T24 Mac terminal, T25 check dispatch, T26-T29 status and caps. All 29 were killed. Fix guards F1-F17 were all killed but F9b, a redundant marker check after Verify, which kills marked processes. Direct auth status tests cover its taint and permission gates. The thin budget was re-measured at 31450/27864.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+860
−107
.rastrillo/budgets.txt+1 −1internal/runner/mac/creds/guard.go+28 −11internal/runner/mac/creds/guard_test.go+16 −0internal/runner/mac/creds/keychain.go+102 −48internal/runner/mac/creds/keychain_test.go+164 −8internal/runner/thin/maccreds.go+97 −31internal/runner/thin/maccreds_fix1_test.go+391 −0internal/runner/thin/maccreds_test.go+61 −8
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 9d6ceb08..452db203 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 31384 27420 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials; measured 31384/27420. |
| +size internal/runner/thin 31450 27864 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns, Mac credentials; measured 31450/27864. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
diff --git a/internal/runner/mac/creds/guard.go b/internal/runner/mac/creds/guard.go| index af5ce49e..efd821ab 100644 |
| --- a/internal/runner/mac/creds/guard.go |
| +++ b/internal/runner/mac/creds/guard.go |
| @@ -221,16 +221,32 @@ func Check(in Input, read func(string) (Fact, error)) Result { |
| add(in.Home, CodeUnknown, "the runner user's home could not be checked") |
| return r |
| } |
| - seen := map[string]bool{} |
| - look := func(p string, root bool) bool { |
| - if seen[p] { |
| - return true |
| + // The protected set first: a root is held to the root rule however |
| + // it is reached, as another root's ancestor or as itself. Facts are |
| + // read once; each path's problems are said once. |
| + protected := map[string]bool{home: true} |
| + for _, root := range in.Roots { |
| + if p := filepath.Clean(root); filepath.IsAbs(root) && within(home, p) { |
| + protected[p] = true |
| + } |
| + } |
| + facts := map[string]Fact{} |
| + errs := map[string]error{} |
| + usable := map[string]bool{} |
| + done := map[string]bool{} |
| + look := func(p string) bool { |
| + if done[p] { |
| + return usable[p] |
| + } |
| + done[p] = true |
| + f, ok := facts[p] |
| + if !ok { |
| + f, errs[p] = read(p) |
| + facts[p] = f |
| } |
| - seen[p] = true |
| - at := tilde(home, p) |
| - f, err := read(p) |
| + root, at := protected[p], tilde(home, p) |
| switch { |
| - case err != nil: |
| + case errs[p] != nil: |
| add(p, CodeUnknown, at+" could not be checked") |
| return false |
| case f.Missing: |
| @@ -261,9 +277,10 @@ func Check(in Input, read func(string) (Fact, error)) Result { |
| add(p, CodeACL, "chmod -a# "+strconv.Itoa(e.Index)+" "+at) |
| } |
| } |
| + usable[p] = true |
| return true |
| } |
| - look(home, true) |
| + look(home) |
| for _, root := range in.Roots { |
| p := filepath.Clean(root) |
| if !filepath.IsAbs(root) || !within(home, p) { |
| @@ -274,10 +291,10 @@ func Check(in Input, read func(string) (Fact, error)) Result { |
| parts := strings.Split(strings.Trim(rel, "/"), "/") |
| ok := true |
| for i := 1; i < len(parts) && ok; i++ { |
| - ok = look(filepath.Join(append([]string{home}, parts[:i]...)...), false) |
| + ok = look(filepath.Join(append([]string{home}, parts[:i]...)...)) |
| } |
| if ok && p != home { |
| - look(p, true) |
| + look(p) |
| } |
| } |
| return r |
diff --git a/internal/runner/mac/creds/guard_test.go b/internal/runner/mac/creds/guard_test.go| index 35b93b8a..a4e8f99c 100644 |
| --- a/internal/runner/mac/creds/guard_test.go |
| +++ b/internal/runner/mac/creds/guard_test.go |
| @@ -171,6 +171,22 @@ func TestHomeGuard(t *testing.T) { |
| t.Fatalf("a group-writable ancestor: %v %q", codes(r), r.Fix()) |
| } |
| }) |
| + // Fix round 1, #5: a protected root is held to the root rule however |
| + // it is reached, first as another root's ancestor or not. |
| + t.Run("nested roots, both orders", func(t *testing.T) { |
| + m := studio() |
| + cfg, state := home+"/.config/equipo-runner", home+"/.config/equipo-runner/state" |
| + m[state] = private(state) |
| + f := m[cfg] |
| + f.Perm = 0o755 |
| + m[cfg] = f |
| + for _, roots := range [][]string{{state, cfg}, {cfg, state}} { |
| + r := Check(Input{User: "paulequipo", UID: 506, Home: home, Roots: roots}, reader(m)) |
| + if !slices.Contains(codes(r), cfg+"="+CodeMode) || !strings.Contains(r.Fix(), "chmod 700 ~/.config/equipo-runner") { |
| + t.Fatalf("roots %v: %v %q", roots, codes(r), r.Fix()) |
| + } |
| + } |
| + }) |
| t.Run("a root outside the home", func(t *testing.T) { |
| in := studioIn |
| in.Roots = append(slices.Clone(in.Roots), "/Users/Shared/equipo") |
diff --git a/internal/runner/mac/creds/keychain.go b/internal/runner/mac/creds/keychain.go| index 07739a78..39d2977b 100644 |
| --- a/internal/runner/mac/creds/keychain.go |
| +++ b/internal/runner/mac/creds/keychain.go |
| @@ -12,6 +12,7 @@ import ( |
| "path/filepath" |
| "regexp" |
| "slices" |
| + "strconv" |
| "strings" |
| "sync" |
| ) |
| @@ -32,21 +33,40 @@ import ( |
| // item there before is never touched; one with the CLI's service name |
| // refuses the connection and holds too. |
| -// Item is a generic password's attributes: the Keychain file, the |
| -// service and the account. Unread is set for an item whose attributes |
| -// could not be read for sure; it is never anyone's own. |
| +// Item is a generic password, known by its stable attributes only: the |
| +// Keychain file, the service, the account and the creation date as the |
| +// dump prints it (never its other attributes, which change). An |
| +// attribute the dump writes in a way it does not know is kept as "?" |
| +// and its raw text, and the item is Unread: it is never anyone's own, |
| +// and it is gone only once a listing shows none with that identity. |
| type Item struct { |
| Keychain string `json:"keychain"` |
| Service string `json:"service"` |
| Account string `json:"account"` |
| - Unread string `json:"unread,omitempty"` |
| + Created string `json:"created,omitempty"` |
| + Unread bool `json:"unread,omitempty"` |
| } |
| +// key is the item's identity as listed: every stable attribute. An item |
| +// made again under the same names is a new one. |
| func (i Item) key() string { |
| - if i.Unread != "" { |
| - return "?" + i.Unread |
| + return strconv.FormatBool(i.Unread) + "\x00" + i.Keychain + "\x00" + i.Service + "\x00" + i.Account + "\x00" + i.Created |
| +} |
| + |
| +// name is what shows the item still there: its Keychain, service and |
| +// account (a readable item's are unique in its Keychain), and for an |
| +// Unread one its creation date too. |
| +func (i Item) name() string { |
| + if i.Unread { |
| + return i.key() |
| } |
| - return i.Keychain + "\x00" + i.Service + "\x00" + i.Account |
| + return "false\x00" + i.Keychain + "\x00" + i.Service + "\x00" + i.Account |
| +} |
| + |
| +// cliItem: an item that may be the CLI's: its service names it so, or |
| +// the service could not be read. |
| +func (i Item) cliItem() bool { |
| + return cliService(i.Service) || i.Unread && strings.HasPrefix(i.Service, "?") |
| } |
| // ServiceFor is the Keychain service the pinned CLI stores its |
| @@ -71,27 +91,27 @@ func Accounts(user string) []string { |
| func cliService(s string) bool { return s == "Claude Code" || strings.HasPrefix(s, "Claude Code-") } |
| var ( |
| - dumpAttr = regexp.MustCompile(`^\s+"(svce|acct)"<blob>=(.*)$`) |
| + dumpAttr = regexp.MustCompile(`^\s+"(svce|acct|cdat)"<(?:blob|timedate)>=(.*)$`) |
| dumpHex = regexp.MustCompile(`^0x([0-9A-Fa-f]*)(?:\s+".*")?$`) |
| ) |
| // ParseDump reads `security dump-keychain` (no -d: attributes only) and |
| -// returns its generic passwords. An item whose Keychain, service or |
| -// account is written in a way it does not know is returned Unread, its |
| -// lines kept to tell it from others. |
| +// returns its generic passwords, each by its stable attributes. An item |
| +// with an attribute written in a way it does not know, or with no class |
| +// line, is returned Unread. |
| func ParseDump(out string) ([]Item, error) { |
| var items []Item |
| var cur *dumpItem |
| flush := func() { |
| - if cur != nil && cur.class == `"genp"` { |
| + if cur != nil && (cur.class == `"genp"` || cur.class == "") { |
| items = append(items, cur.item()) |
| } |
| } |
| for _, line := range strings.Split(out, "\n") { |
| if v, ok := strings.CutPrefix(line, "keychain: "); ok { |
| flush() |
| - path, ok := blobValue(v) |
| - cur = &dumpItem{keychain: path, bad: !ok, lines: []string{line}} |
| + cur = &dumpItem{} |
| + cur.keychain = cur.value(v) |
| continue |
| } |
| if cur == nil { |
| @@ -100,21 +120,19 @@ func ParseDump(out string) ([]Item, error) { |
| } |
| return nil, ErrUnreadable |
| } |
| - cur.lines = append(cur.lines, line) |
| if v, ok := strings.CutPrefix(line, "class: "); ok { |
| cur.class = strings.TrimSpace(v) |
| continue |
| } |
| - if m := dumpAttr.FindStringSubmatch(line); m != nil { |
| - v, ok := blobValue(m[2]) |
| - if !ok { |
| - cur.bad = true |
| - } |
| - if m[1] == "svce" { |
| - cur.service, cur.hasService = v, true |
| - } else { |
| - cur.account, cur.hasAccount = v, true |
| - } |
| + m := dumpAttr.FindStringSubmatch(line) |
| + switch { |
| + case m == nil: |
| + case m[1] == "svce": |
| + cur.service, cur.hasService = cur.value(m[2]), true |
| + case m[1] == "acct": |
| + cur.account, cur.hasAccount = cur.value(m[2]), true |
| + default: |
| + cur.created = strings.TrimSpace(m[2]) |
| } |
| } |
| flush() |
| @@ -122,16 +140,30 @@ func ParseDump(out string) ([]Item, error) { |
| } |
| type dumpItem struct { |
| - keychain, class, service, account string |
| - hasService, hasAccount, bad bool |
| - lines []string |
| + keychain, class, service, account, created string |
| + hasService, hasAccount, bad bool |
| +} |
| + |
| +// value is an attribute's value, or "?" and its raw text (and the item |
| +// Unread) when it cannot be read for sure. |
| +func (d *dumpItem) value(v string) string { |
| + if s, ok := blobValue(v); ok { |
| + return s |
| + } |
| + d.bad = true |
| + return "?" + strings.TrimSpace(v) |
| } |
| func (d *dumpItem) item() Item { |
| - if d.bad || !d.hasService || !d.hasAccount || !filepath.IsAbs(d.keychain) { |
| - return Item{Unread: strings.Join(d.lines, "\n")} |
| + i := Item{Keychain: d.keychain, Service: d.service, Account: d.account, Created: d.created} |
| + if !d.hasService { |
| + i.Service = "?" |
| } |
| - return Item{Keychain: d.keychain, Service: d.service, Account: d.account} |
| + if !d.hasAccount { |
| + i.Account = "?" |
| + } |
| + i.Unread = d.bad || d.class == "" || !d.hasService || !d.hasAccount || !filepath.IsAbs(d.keychain) |
| + return i |
| } |
| // blobValue is a dump's value: <NULL>, "text" with no escape in it, or |
| @@ -157,14 +189,14 @@ func blobValue(v string) (string, bool) { |
| // service name is there (Residue names it). |
| var ErrExisting = errors.New("creds: a Keychain item with Claude Code's name is already there") |
| -// Keychain watches the runner user's Keychains. Dir holds its durable |
| -// records (in the state dir); Login is the user's login Keychain's path; |
| -// User the runner user. List lists every generic password of the user's |
| -// Keychain search list, attributes only; Delete deletes one by service, |
| -// account and Keychain path. |
| +// Keychain watches the runner user's login Keychain. Dir holds its |
| +// durable records (in the state dir); Login is the login Keychain's |
| +// path; User the runner user. List lists the generic passwords of the |
| +// Keychain at a path (security dump-keychain <path>), attributes only; |
| +// Delete deletes one by service, account and Keychain path. |
| type Keychain struct { |
| Dir, Login, User string |
| - List func(context.Context) ([]Item, error) |
| + List func(ctx context.Context, keychain string) ([]Item, error) |
| Delete func(context.Context, Item) error |
| // op runs one watch operation at a time (a sign-in's second look and |
| @@ -184,6 +216,24 @@ type record struct { |
| Left []Item `json:"left,omitempty"` |
| } |
| +// list is the runner user's login Keychain, listed by its path whatever |
| +// the search list says (the CLI writes to the default Keychain, which |
| +// for this user is the login one): its items only. A listing that fails |
| +// is an error, and nothing is decided from it. |
| +func (k *Keychain) list(ctx context.Context) ([]Item, error) { |
| + all, err := k.List(ctx, k.Login) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var out []Item |
| + for _, i := range all { |
| + if i.Keychain == k.Login || i.Unread && !filepath.IsAbs(i.Keychain) { |
| + out = append(out, i) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| // existingRecord names the record of CLI items found already there. |
| const existingRecord = "existing" |
| @@ -206,7 +256,7 @@ func (k *Keychain) Before(ctx context.Context, marker, dir string) error { |
| if !recordName.MatchString(marker) || marker == existingRecord || !filepath.IsAbs(dir) { |
| return ErrUnreadable |
| } |
| - list, err := k.List(ctx) |
| + list, err := k.list(ctx) |
| if err != nil { |
| return err |
| } |
| @@ -230,7 +280,7 @@ func (k *Keychain) Before(ctx context.Context, marker, dir string) error { |
| func (k *Keychain) refuseExisting(list []Item) error { |
| var found []Item |
| for _, i := range list { |
| - if i.Unread == "" && cliService(i.Service) { |
| + if i.cliItem() { |
| found = append(found, i) |
| } |
| } |
| @@ -258,7 +308,7 @@ func (k *Keychain) After(ctx context.Context, marker string) (Outcome, error) { |
| if err != nil { |
| return Outcome{}, err |
| } |
| - list, err := k.List(ctx) |
| + list, err := k.list(ctx) |
| if err != nil { |
| return Outcome{}, err |
| } |
| @@ -290,7 +340,7 @@ func appeared(before, list []Item) []Item { |
| // own: i is positively rec's attempt's: in the login Keychain, named |
| // for its config dir, with an account the CLI derives for this user. |
| func (k *Keychain) own(rec record, i Item) bool { |
| - return rec.ConfigDir != "" && i.Unread == "" && i.Keychain == k.Login && i.Service == ServiceFor(rec.ConfigDir) && slices.Contains(Accounts(k.User), i.Account) |
| + return rec.ConfigDir != "" && !i.Unread && i.Keychain == k.Login && i.Service == ServiceFor(rec.ConfigDir) && slices.Contains(Accounts(k.User), i.Account) |
| } |
| // recheck deletes each record's own items left, lists again, keeps of |
| @@ -305,17 +355,17 @@ func (k *Keychain) recheck(ctx context.Context, recs []*record) ([]Item, error) |
| } |
| } |
| } |
| - list, err := k.List(ctx) |
| + list, err := k.list(ctx) |
| if err != nil { |
| return deleted, err |
| } |
| shown := map[string]bool{} |
| for _, i := range list { |
| - shown[i.key()] = true |
| + shown[i.name()] = true |
| } |
| var errs []error |
| for _, rec := range recs { |
| - rec.Left = slices.DeleteFunc(rec.Left, func(i Item) bool { return !shown[i.key()] }) |
| + rec.Left = slices.DeleteFunc(rec.Left, func(i Item) bool { return !shown[i.name()] }) |
| if len(rec.Left) == 0 { |
| errs = append(errs, k.remove(rec.Marker)) |
| } else { |
| @@ -330,7 +380,7 @@ func (k *Keychain) recheck(ctx context.Context, recs []*record) ([]Item, error) |
| func (k *Keychain) Existing(ctx context.Context) error { |
| k.op.Lock() |
| defer k.op.Unlock() |
| - list, err := k.List(ctx) |
| + list, err := k.list(ctx) |
| if err != nil { |
| return err |
| } |
| @@ -364,7 +414,7 @@ func (k *Keychain) Settle(ctx context.Context, restart bool, gone func(string) b |
| continue |
| } |
| if list == nil { |
| - if list, err = k.List(ctx); err != nil { |
| + if list, err = k.list(ctx); err != nil { |
| return err |
| } |
| } |
| @@ -398,8 +448,12 @@ func (k *Keychain) Residue() []string { |
| continue |
| } |
| for _, i := range rec.Left { |
| - if !slices.Contains(out, i.Service) { |
| - out = append(out, i.Service) |
| + name := i.Service |
| + if strings.HasPrefix(name, "?") { |
| + name = "" |
| + } |
| + if !slices.Contains(out, name) { |
| + out = append(out, name) |
| } |
| } |
| } |
diff --git a/internal/runner/mac/creds/keychain_test.go b/internal/runner/mac/creds/keychain_test.go| index 22d03be8..33eb84b4 100644 |
| --- a/internal/runner/mac/creds/keychain_test.go |
| +++ b/internal/runner/mac/creds/keychain_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "os" |
| "path/filepath" |
| "slices" |
| + "strings" |
| "sync" |
| "testing" |
| ) |
| @@ -28,6 +29,13 @@ type fakeKeychain struct { |
| // next listing (it goes from the one after). |
| fail, stale bool |
| ghost []Item |
| + // asked is every keychain listed; search is the user's search list |
| + // (what a listing without a path would show); broken fails the |
| + // listings; dump, when set, is listed instead, as security prints it. |
| + asked []string |
| + search []string |
| + broken bool |
| + dump string |
| } |
| func (f *fakeKeychain) add(i ...Item) { |
| @@ -36,11 +44,25 @@ func (f *fakeKeychain) add(i ...Item) { |
| f.items = append(f.items, i...) |
| } |
| -func (f *fakeKeychain) list(context.Context) ([]Item, error) { |
| +func (f *fakeKeychain) list(_ context.Context, keychain string) ([]Item, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.lists++ |
| - out := append(slices.Clone(f.items), f.ghost...) |
| + f.asked = append(f.asked, keychain) |
| + if f.broken { |
| + return nil, errors.New("security: could not list") |
| + } |
| + if f.dump != "" { |
| + return ParseDump(f.dump) |
| + } |
| + var out []Item |
| + for _, i := range append(slices.Clone(f.items), f.ghost...) { |
| + // dump-keychain <path> lists that keychain, in the search list |
| + // or not; without a path, only the search list's. |
| + if keychain == i.Keychain || keychain == "" && slices.Contains(f.search, i.Keychain) { |
| + out = append(out, i) |
| + } |
| + } |
| f.ghost = nil |
| return out, nil |
| } |
| @@ -90,7 +112,7 @@ func TestParseDump(t *testing.T) { |
| t.Fatal(err) |
| } |
| want := []Item{ |
| - {Keychain: login, Service: "Wi-Fi", Account: "paulequipo"}, |
| + {Keychain: login, Service: "Wi-Fi", Account: "paulequipo", Created: `0x32303236313131303130303030305A00 "20261110100000Z\000"`}, |
| {Keychain: login, Service: "Claude Code-credentials-1a2b3c4d", Account: "paulequipf"}, |
| {Keychain: "/Library/Keychains/System.keychain", Service: "AirPort", Account: "com.apple.network.eap.system.item.wlan.ssid.home"}, |
| } |
| @@ -99,7 +121,7 @@ func TestParseDump(t *testing.T) { |
| } |
| // What it cannot read for sure is never an item anyone owns. |
| odd, err := ParseDump("keychain: \"" + login + "\"\nclass: \"genp\"\nattributes:\n \"svce\"<blob>=\"Claude Code-credentials-1a2b3c4d\"\n \"acct\"<blob>=<weird>\n") |
| - if err != nil || len(odd) != 1 || odd[0].Unread == "" { |
| + if err != nil || len(odd) != 1 || !odd[0].Unread { |
| t.Fatalf("an unreadable account: %+v %v", odd, err) |
| } |
| if _, err := ParseDump("class: \"genp\"\n"); err == nil { |
| @@ -221,15 +243,17 @@ func TestKeychainWatch(t *testing.T) { |
| t.Fatal("held after the person removed it") |
| } |
| }) |
| - t.Run("matching attributes in another keychain are left", func(t *testing.T) { |
| - f := &fakeKeychain{} |
| + // Only the login keychain is watched (fix round 1, #2): the CLI writes |
| + // to the default one, and nothing elsewhere is ever touched. |
| + t.Run("matching attributes in another keychain are left alone", func(t *testing.T) { |
| + f := &fakeKeychain{search: []string{"/Users/paulequipo/Library/Keychains/other.keychain-db"}} |
| k := newWatch(t, f) |
| _ = k.Before(ctx, "signin-1", configDir) |
| elsewhere := own() |
| elsewhere.Keychain = "/Users/paulequipo/Library/Keychains/other.keychain-db" |
| f.add(elsewhere) |
| out, _ := k.After(ctx, "signin-1") |
| - if out.Clean || !f.has(elsewhere) || len(f.deleted) != 0 || !k.Held() { |
| + if !out.Clean || !f.has(elsewhere) || len(f.deleted) != 0 { |
| t.Fatalf("another keychain: %+v deleted=%+v held=%v", out, f.deleted, k.Held()) |
| } |
| }) |
| @@ -238,7 +262,7 @@ func TestKeychainWatch(t *testing.T) { |
| {Keychain: login, Service: ServiceFor(configDir + "-2"), Account: "paulequipo"}, |
| {Keychain: login, Service: ServiceFor(configDir), Account: "vicky"}, |
| {Keychain: login, Service: "Claude Code-credentials", Account: "paulequipo"}, |
| - {Unread: "raw"}, |
| + {Keychain: login, Service: "raw", Unread: true}, |
| } { |
| f := &fakeKeychain{} |
| k := newWatch(t, f) |
| @@ -303,3 +327,135 @@ func TestKeychainWatch(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +// dumpOf is a login keychain dump holding one generic password, its |
| +// attributes as given (svce and acct values exactly as security prints |
| +// them) and mdat. |
| +func dumpOf(keychain, svce, acct, mdat string) string { |
| + return "keychain: \"" + keychain + "\"\nversion: 512\nclass: \"genp\"\nattributes:\n" + |
| + " \"acct\"<blob>=" + acct + "\n" + |
| + " \"cdat\"<timedate>=0x32303236313132393130303030305A00 \"20261129100000Z\\000\"\n" + |
| + " \"mdat\"<timedate>=" + mdat + "\n" + |
| + " \"svce\"<blob>=" + svce + "\n" |
| +} |
| + |
| +// TestKeychainAmbiguousItems (fix round 1, #1): an item whose attributes |
| +// cannot all be read is known by its stable attributes only (keychain, |
| +// class, service, account, creation date), never by the whole dump; one |
| +// with the CLI's service name, or with no readable service, refuses a |
| +// preflight; and its hold goes only once a listing shows it absent. |
| +func TestKeychainAmbiguousItems(t *testing.T) { |
| + ctx := context.Background() |
| + t.Run("a metadata change keeps the identity and the hold", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.dump = dumpOf(login, "\"Other App\"", "<weird>", "0x31") |
| + out, err := k.After(ctx, "signin-1") |
| + if err != nil || out.Clean || len(out.Left) != 1 || !out.Left[0].Unread || !k.Held() { |
| + t.Fatalf("an unreadable new item: %+v %v held=%v", out, err, k.Held()) |
| + } |
| + f.dump = dumpOf(login, "\"Other App\"", "<weird>", "0x32") |
| + if err := k.Settle(ctx, false, nil); err != nil || !k.Held() { |
| + t.Fatalf("a metadata change released the hold: %v held=%v", err, k.Held()) |
| + } |
| + f.dump = "" |
| + if err := k.Settle(ctx, false, nil); err != nil || k.Held() { |
| + t.Fatalf("held once the item is gone: %v", err) |
| + } |
| + }) |
| + t.Run("parsing keeps only stable attributes", func(t *testing.T) { |
| + a, err1 := ParseDump(dumpOf(login, "\"Other App\"", "<weird>", "0x31")) |
| + b, err2 := ParseDump(dumpOf(login, "\"Other App\"", "<weird>", "0x32")) |
| + if err1 != nil || err2 != nil || len(a) != 1 || !slices.Equal(a, b) || strings.Contains(a[0].Account+a[0].Service, "mdat") || a[0].Created == "" { |
| + t.Fatalf("%+v %+v", a, b) |
| + } |
| + }) |
| + t.Run("an unreadable item with the CLI's service there before refuses", func(t *testing.T) { |
| + f := &fakeKeychain{dump: dumpOf(login, "\"Claude Code-credentials-1a2b3c4d\"", "<weird>", "0x31")} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); !errors.Is(err, ErrExisting) || !k.Held() { |
| + t.Fatalf("before: %v held=%v", err, k.Held()) |
| + } |
| + if err := k.Existing(ctx); !errors.Is(err, ErrExisting) { |
| + t.Fatalf("a store: %v", err) |
| + } |
| + }) |
| + t.Run("an item with no readable service there before refuses", func(t *testing.T) { |
| + f := &fakeKeychain{dump: dumpOf(login, "<weird>", "\"paulequipo\"", "0x31")} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); !errors.Is(err, ErrExisting) || !k.Held() { |
| + t.Fatalf("before: %v held=%v", err, k.Held()) |
| + } |
| + }) |
| + t.Run("an unreadable listing keeps the hold", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(own()) |
| + f.broken = true |
| + if _, err := k.After(ctx, "signin-1"); err == nil || !k.Held() { |
| + t.Fatalf("after an unreadable listing: %v held=%v", err, k.Held()) |
| + } |
| + _ = k.Settle(ctx, true, func(string) bool { return true }) |
| + if !k.Held() { |
| + t.Fatal("settling with an unreadable listing released the hold") |
| + } |
| + f.broken = false |
| + if err := k.Settle(ctx, true, func(string) bool { return true }); err != nil || k.Held() || f.has(own()) { |
| + t.Fatalf("once it lists: %v held=%v", err, k.Held()) |
| + } |
| + }) |
| + t.Run("a recheck that cannot list keeps a residue's hold", func(t *testing.T) { |
| + f := &fakeKeychain{fail: true} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(own()) |
| + if _, err := k.After(ctx, "signin-1"); err != nil || !k.Held() { |
| + t.Fatalf("a failed delete: %v held=%v", err, k.Held()) |
| + } |
| + f.fail, f.broken = false, true |
| + if err := k.Settle(ctx, false, nil); err == nil || !k.Held() { |
| + t.Fatalf("a recheck with no listing: %v held=%v", err, k.Held()) |
| + } |
| + }) |
| + t.Run("a preflight that cannot list refuses", func(t *testing.T) { |
| + f := &fakeKeychain{broken: true} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); err == nil { |
| + t.Fatal("a sign-in started with no listing") |
| + } |
| + if err := k.Existing(ctx); err == nil { |
| + t.Fatal("a store went ahead with no listing") |
| + } |
| + }) |
| +} |
| + |
| +// TestKeychainLoginByPath (fix round 1, #2): the login keychain is |
| +// listed by its path, whatever the search list says, and items of other |
| +// keychains are not the watch's. |
| +func TestKeychainLoginByPath(t *testing.T) { |
| + ctx := context.Background() |
| + f := &fakeKeychain{search: []string{"/Library/Keychains/System.keychain"}} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.add(own()) |
| + out, err := k.After(ctx, "signin-1") |
| + if err != nil || out.Clean || !slices.Equal(out.Deleted, []Item{own()}) || f.has(own()) { |
| + t.Fatalf("an item in a login keychain left out of the search list: %+v %v", out, err) |
| + } |
| + for _, kc := range f.asked { |
| + if kc != login { |
| + t.Fatalf("listed %q, not the login keychain by path", kc) |
| + } |
| + } |
| + // What a dump of it says of another keychain is not the watch's. |
| + f.dump = dumpOf("/Library/Keychains/System.keychain", "\"Claude Code-credentials\"", "\"paulequipo\"", "0x31") |
| + if err := k.Before(ctx, "signin-2", configDir); err != nil { |
| + t.Fatalf("another keychain's item refused the sign-in: %v", err) |
| + } |
| +} |
diff --git a/internal/runner/thin/maccreds.go b/internal/runner/thin/maccreds.go| index 7252e57b..f59455f0 100644 |
| --- a/internal/runner/thin/maccreds.go |
| +++ b/internal/runner/thin/maccreds.go |
| @@ -129,16 +129,28 @@ func macConfigDir(c runner.Config, home string) string { |
| return filepath.Join(home, ".config", "equipo-runner") |
| } |
| -// keychainList is every generic password of the runner user's Keychain |
| -// search list, by attributes only (no -d: no secret is read). Off a Mac |
| -// there is none. |
| -func (h *macHost) keychainList(ctx context.Context) ([]creds.Item, error) { |
| - if runtime.GOOS != "darwin" { |
| +// macSecurity is security(1); macKeychains: this host has Keychains |
| +// (tests stand in for both). |
| +var ( |
| + macSecurity = "/usr/bin/security" |
| + macKeychains = runtime.GOOS == "darwin" |
| +) |
| + |
| +// keychainList is every generic password of the Keychain at keychain |
| +// (the runner user's login Keychain, named by its path whatever the |
| +// search list says), by attributes only (no -d: no secret is read). A |
| +// Keychain file that is not there, or a listing that fails, is an |
| +// error: nothing is decided from it. Off a Mac there is none. |
| +func (h *macHost) keychainList(ctx context.Context, keychain string) ([]creds.Item, error) { |
| + if !macKeychains { |
| return nil, nil |
| } |
| + if info, err := os.Lstat(keychain); err != nil || !info.Mode().IsRegular() { |
| + return nil, errKeychain |
| + } |
| ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| defer cancel() |
| - out, err := h.run(ctx, "/usr/bin/security", "dump-keychain") |
| + out, err := h.run(ctx, macSecurity, "dump-keychain", keychain) |
| if err != nil { |
| return nil, err |
| } |
| @@ -148,12 +160,12 @@ func (h *macHost) keychainList(ctx context.Context) ([]creds.Item, error) { |
| // keychainDelete deletes one generic password by service, account and |
| // Keychain path. |
| func (h *macHost) keychainDelete(ctx context.Context, i creds.Item) error { |
| - if runtime.GOOS != "darwin" || i.Unread != "" { |
| + if !macKeychains || i.Unread { |
| return errKeychain |
| } |
| ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| defer cancel() |
| - _, err := h.run(ctx, "/usr/bin/security", "delete-generic-password", "-s", i.Service, "-a", i.Account, i.Keychain) |
| + _, err := h.run(ctx, macSecurity, "delete-generic-password", "-s", i.Service, "-a", i.Account, i.Keychain) |
| return err |
| } |
| @@ -222,10 +234,27 @@ func (m *macCreds) store(ctx context.Context) (give func(), err error) { |
| return give, nil |
| } |
| +// after is a launch's second look at the Keychain once its end is |
| +// proven: errKeychain when it left an item (its own is deleted; the Mac |
| +// holds until a listing shows every such item gone) or the Keychain |
| +// could not be listed again. |
| +func (m *macCreds) after(marker string) error { |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*mac.QueryLimit) |
| + defer cancel() |
| + out, err := m.keychain.After(ctx, marker) |
| + if err == nil && out.Clean { |
| + return nil |
| + } |
| + if m.log != nil { |
| + m.log.Warn("a launch left a Keychain item, or the Keychain could not be listed; refused", "marker", marker, "deleted", len(out.Deleted), "left", len(out.Left), "err", err) |
| + } |
| + return errKeychain |
| +} |
| + |
| // settle is the Keychain watch's settling: at a restart, every watch |
| // whose CLI is proven gone; otherwise only what was found left. |
| func (m *macCreds) settle(ctx context.Context, restart bool) { |
| - err := m.keychain.Settle(ctx, restart, func(marker string) bool { return m.exec.Verify(mac.RecordID(0, marker)) }) |
| + err := m.keychain.Settle(ctx, restart, m.ended) |
| if err != nil && m.log != nil { |
| m.log.Warn("keychain not settled", "err", err) |
| } |
| @@ -234,6 +263,24 @@ func (m *macCreds) settle(ctx context.Context, restart bool) { |
| } |
| } |
| +// ended: nothing of marker's launch can write a Keychain item any more. |
| +// Proven over (Executor.Verify), or, for a launch whose turn record was |
| +// never completed (the runner died: task 9 never proves such an attempt |
| +// over), its turn settled (a turn can be taken, so what it left of the |
| +// runner user's was killed) and nothing carrying its marker left. |
| +func (m *macCreds) ended(marker string) bool { |
| + if m.exec.Verify(mac.RecordID(0, marker)) { |
| + return true |
| + } |
| + u, ok := m.turns.TryTake(mac.OpRecover) |
| + if !ok { |
| + return false |
| + } |
| + u.Give() |
| + left, err := mac.Marked(marker) |
| + return err == nil && len(left) == 0 |
| +} |
| + |
| // place makes a launch's own CLAUDE_CONFIG_DIR under the runtime root |
| // (<scratch>/homes, which no sandboxed command reaches); its name is the |
| // launch's marker. |
| @@ -333,10 +380,20 @@ func (m *macCreds) authStatus(ctx context.Context, b provider.Binding) (provider |
| if err != nil { |
| return provider.Identity{}, err |
| } |
| - defer os.RemoveAll(dir) |
| + // Watched as a sign-in is: the list on record before the CLI starts, |
| + // the second look once its end is proven (a crash leaves the watch |
| + // for the restart). |
| + if err = m.keychain.Before(ctx, marker, dir); err != nil { |
| + os.RemoveAll(dir) |
| + return provider.Identity{}, err |
| + } |
| out := &capped{} |
| run, err := m.start(ctx, dir, marker, mac.Command{Env: m.env(dir, marker, true), Stdout: out}, raw, func(string) error { return nil }, "auth", "status", "--json") |
| if err != nil { |
| + if !errors.Is(err, mac.ErrUnproven) { |
| + err = errors.Join(err, m.after(marker)) |
| + os.RemoveAll(dir) |
| + } |
| return provider.Identity{}, err |
| } |
| select { |
| @@ -346,9 +403,15 @@ func (m *macCreds) authStatus(ctx context.Context, b provider.Binding) (provider |
| } |
| proven := run.Stop() |
| run.Finish(context.WithoutCancel(ctx)) |
| - switch { |
| - case !proven: |
| + if !proven { |
| + // Not success: the watch and the turn's record stay. |
| return provider.Identity{}, mac.ErrUnproven |
| + } |
| + kerr := m.after(marker) |
| + os.RemoveAll(dir) |
| + switch { |
| + case kerr != nil: |
| + return provider.Identity{}, kerr |
| case ctx.Err() != nil: |
| return provider.Identity{}, ctx.Err() |
| } |
| @@ -436,25 +499,36 @@ func (m *macCreds) checkToken(ctx context.Context, o ClaudeOptions, b runner.Acc |
| } |
| clear(token) |
| }() |
| + // Watched as a sign-in is, the runtime copy its config dir. |
| + if err = m.keychain.Before(ctx, in.Attempt, in.ConfigDir); err != nil { |
| + return nil, nil, false, err |
| + } |
| pctx, kill := context.WithCancel(context.WithoutCancel(tctx)) |
| defer kill() |
| s := &mac.Starter{Exec: m.exec, CLI: m.cli, Input: in, Token: bytes.Clone(token)} |
| proc, err := s.StartRecorded(pctx, launch, claude.DarwinArgv(policy), func(context.Context, containment.Record) error { return nil }) |
| if err != nil { |
| + if !errors.Is(err, mac.ErrUnproven) { |
| + err = errors.Join(err, m.after(in.Attempt)) |
| + } |
| return nil, nil, false, err |
| } |
| - // Stopped at the limit (which ends the reads) and at the end; its end |
| - // is proven, or its turn's record stays for the next turn, before the |
| - // runtime copy goes. |
| - exited := make(chan struct{}) |
| - go func() { defer close(exited); _, _ = proc.Wait(context.Background()) }() |
| + // Stopped at the limit (which ends the reads) and at the end. Only a |
| + // proven end, then a clean second look at the Keychain, lets an |
| + // answer count: unproven, the watch and the turn's record stay for |
| + // recovery, and the profile is not read. |
| + waited := make(chan error, 1) |
| + go func() { _, err := proc.Wait(context.Background()); waited <- err }() |
| stop := context.AfterFunc(ctx, kill) |
| - defer func() { |
| - stop() |
| - kill() |
| - <-exited |
| - }() |
| rows, seen, err := readCheck(ctx, proc, session, b) |
| + stop() |
| + kill() |
| + if werr := <-waited; werr != nil { |
| + return rows, nil, false, errors.Join(mac.ErrUnproven, werr) |
| + } |
| + if kerr := m.after(in.Attempt); kerr != nil { |
| + return rows, nil, false, kerr |
| + } |
| return rows, seen, false, err |
| } |
| @@ -546,16 +620,8 @@ func (t *macTerminal) Stop() error { |
| t.err = errUnproven |
| return |
| } |
| - ctx, cancel := context.WithTimeout(context.Background(), 3*mac.QueryLimit) |
| - defer cancel() |
| - out, err := t.m.keychain.After(ctx, t.marker) |
| + t.err = t.m.after(t.marker) |
| os.RemoveAll(t.dir) |
| - if err != nil || !out.Clean { |
| - t.err = errKeychain |
| - if t.m.log != nil { |
| - t.m.log.Warn("the sign-in left a Keychain item, so its connection is refused", "deleted", len(out.Deleted), "left", len(out.Left), "err", err) |
| - } |
| - } |
| }) |
| return t.err |
| } |
diff --git a/internal/runner/thin/maccreds_fix1_test.go b/internal/runner/thin/maccreds_fix1_test.go| new file mode 100644 |
| index 00000000..d8a8e350 |
| --- /dev/null |
| +++ b/internal/runner/thin/maccreds_fix1_test.go |
| @@ -0,0 +1,391 @@ |
| +//go:build testbuild |
| + |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "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/provider" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// Task 10 fix round 1 (Astra round 1): the Keychain watch around the |
| +// token check and auth status (#3), the termination proof of a check |
| +// (#4), and direct tests of every guard the thin wiring added (#6). |
| + |
| +// connected is a rig with one healthy pasted-token connection: its |
| +// binding and token-home binding. |
| +func connected(t *testing.T, r *darwinRig, token string) (b, home string) { |
| + t.Helper() |
| + h, end := r.paste(r.connector(), "c1", token) |
| + if end.State != wire.ConnHealthy { |
| + t.Fatalf("not connected: %+v", end) |
| + } |
| + return filepath.Base(h), h |
| +} |
| + |
| +// statusBinding is the token home as auth status reads it. |
| +func statusBinding(local, home string) provider.Binding { |
| + return provider.Binding{ID: local, Home: home, Provider: wire.ProviderClaude, Token: true} |
| +} |
| + |
| +// lingering steers the next launch whose first argument is arg to leave |
| +// a child that ignores SIGTERM; its end then cannot be proven within a |
| +// short Settle. The child is killed at the test's end. |
| +func (r *darwinRig) lingering(t *testing.T, arg string) { |
| + t.Helper() |
| + r.m.exec.Settle, r.m.exec.Grace = 500*time.Millisecond, time.Minute |
| + if err := os.WriteFile(filepath.Join(r.dir, "linger"), []byte(arg), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { |
| + if raw, err := os.ReadFile(filepath.Join(r.dir, "linger.pid")); err == nil { |
| + if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + } |
| + }) |
| +} |
| + |
| +// TestDarwinCheckKeychainWatch (#3): the token check and auth status are |
| +// watched as the sign-in is: an item a launch leaves refuses it, its own |
| +// is deleted, anything else holds; a cancelled check is looked at too, |
| +// and a crash is settled at the restart. |
| +func TestDarwinCheckKeychainWatch(t *testing.T) { |
| + t.Run("the check's own item refuses it and is deleted", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, _ := connected(t, r, fakeclaude.Token("a@example.com")) |
| + r.creating("-p ", r.own) |
| + b, _ := r.binding(local) |
| + _, err := r.opts.CheckToken(r.ctx, b) |
| + if !errors.Is(err, errKeychain) || len(r.kc.deleted) != 1 || r.m.Held() { |
| + t.Fatalf("check: %v deleted %+v held=%v", err, r.kc.deleted, r.m.Held()) |
| + } |
| + if !strings.HasPrefix(r.kc.deleted[0].Service, "Claude Code-credentials-") || r.kc.deleted[0].Keychain != r.m.keychain.Login { |
| + t.Fatalf("deleted %+v", r.kc.deleted) |
| + } |
| + }) |
| + t.Run("an unrelated item during the check holds", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, _ := connected(t, r, fakeclaude.Token("a@example.com")) |
| + r.creating("-p ", func(string) creds.Item { |
| + return creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user} |
| + }) |
| + b, _ := r.binding(local) |
| + if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errKeychain) || len(r.kc.deleted) != 0 || !r.m.Held() { |
| + t.Fatalf("check: %v deleted %+v held=%v", err, r.kc.deleted, r.m.Held()) |
| + } |
| + }) |
| + t.Run("auth status's own item refuses the connection", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + r.creating("auth status", r.own) |
| + _, end := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| + if end.Reason != "provider_refused" || len(r.kc.deleted) != 1 || r.m.Held() { |
| + t.Fatalf("end %+v deleted %+v held=%v", end, r.kc.deleted, r.m.Held()) |
| + } |
| + }) |
| + t.Run("auth status called alone is watched", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, home := connected(t, r, fakeclaude.Token("a@example.com")) |
| + r.creating("auth status", r.own) |
| + if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, errKeychain) || len(r.kc.deleted) != 1 { |
| + t.Fatalf("auth status: %v deleted %+v", err, r.kc.deleted) |
| + } |
| + }) |
| + t.Run("a cancelled check is looked at", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, _ := connected(t, r, fakeclaude.Token("a@example.com")) |
| + r.creating("-p ", r.own) |
| + if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + b, _ := r.binding(local) |
| + ctx, cancel := context.WithCancel(r.ctx) |
| + done := make(chan error, 1) |
| + go func() { _, err := r.opts.CheckToken(ctx, b); done <- err }() |
| + waitPid(t, filepath.Join(r.dir, "hang.pid")) |
| + cancel() |
| + <-done |
| + if len(r.kc.deleted) != 1 || r.m.Held() { |
| + t.Fatalf("after the cancel: deleted %+v held=%v", r.kc.deleted, r.m.Held()) |
| + } |
| + }) |
| + t.Run("a crashed check's watch is settled at the restart", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, _ := connected(t, r, fakeclaude.Token("a@example.com")) |
| + 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() |
| + if !r.m.Held() { |
| + t.Fatal("the dead runner's check left no watch") |
| + } |
| + // What its CLI stored meanwhile (its launch is on disk already). |
| + r.creating("-p ", r.own) |
| + r.kc.mu.Lock() |
| + delete(r.kc.created, pid) |
| + r.kc.mu.Unlock() |
| + r.connector() |
| + |
| + if r.m.Held() || len(r.kc.deleted) != 1 || pidAlive(pid) { |
| + t.Fatalf("after the restart: held=%v deleted %+v CLI alive=%v", r.m.Held(), r.kc.deleted, pidAlive(pid)) |
| + } |
| + }) |
| +} |
| + |
| +// TestDarwinCheckUnprovenIsNotSuccess (#4): a check that answered but |
| +// whose end cannot be proven fails with mac.ErrUnproven: the profile is |
| +// not read, and the watch and the turn's record stay for recovery. |
| +func TestDarwinCheckUnprovenIsNotSuccess(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, _ := connected(t, r, fakeclaude.Token("")) |
| + b, _ := r.binding(local) |
| + clock := time.Now() |
| + fake := newFakeProfile(t, "") |
| + fake.answer(200, "a@example.com") |
| + r.opts.Profile = fake.reader(&clock) |
| + r.lingering(t, "-p") |
| + _, err := r.opts.CheckToken(r.ctx, b) |
| + if !errors.Is(err, mac.ErrUnproven) { |
| + t.Fatalf("an unproven check: %v", err) |
| + } |
| + if fake.count() != 0 { |
| + t.Fatal("the profile was read after an unproven check") |
| + } |
| + if !r.m.Held() { |
| + t.Fatal("the check's watch was dropped with its end unproven") |
| + } |
| + if _, err := os.Stat(filepath.Join(r.cfg.StateDir, "mac-gate.lock.turn")); err != nil { |
| + t.Fatalf("the turn's record was dropped: %v", err) |
| + } |
| + // Control: proven, the same check reads the profile. |
| + os.Remove(filepath.Join(r.dir, "linger")) |
| + r.m.exec.Settle = 10 * time.Second |
| + if _, err := r.opts.CheckToken(r.ctx, b); err != nil || fake.count() != 1 { |
| + t.Fatalf("a proven check: %v, %d profile reads", err, fake.count()) |
| + } |
| + t.Run("auth status", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, home := connected(t, r, fakeclaude.Token("a@example.com")) |
| + r.lingering(t, "auth") |
| + if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, mac.ErrUnproven) || !r.m.Held() { |
| + t.Fatalf("an unproven auth status: %v held=%v", err, r.m.Held()) |
| + } |
| + }) |
| +} |
| + |
| +// TestDarwinAuthStatusGates (#6): auth status, which madeToken calls on |
| +// its own, refuses a tainted runner and an open home before it starts |
| +// anything. |
| +func TestDarwinAuthStatusGates(t *testing.T) { |
| + t.Run("tainted", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, home := connected(t, r, fakeclaude.Token("a@example.com")) |
| + before := len(r.launches()) |
| + r.m.taint.Set() |
| + if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, errTainted) || len(r.launches()) != before { |
| + t.Fatalf("a tainted auth status: %v", err) |
| + } |
| + }) |
| + t.Run("home open", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, home := connected(t, r, fakeclaude.Token("a@example.com")) |
| + before := len(r.launches()) |
| + if err := os.Chmod(r.dir, 0o750); err != nil { |
| + t.Fatal(err) |
| + } |
| + var open *homeOpen |
| + if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.As(err, &open) || len(r.launches()) != before { |
| + t.Fatalf("auth status with the home open: %v", err) |
| + } |
| + }) |
| + t.Run("not a token", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + if _, err := r.m.authStatus(r.ctx, provider.Binding{ID: "x", Home: r.root, Provider: wire.ProviderClaude}); !errors.Is(err, provider.ErrLoginUnavailable) { |
| + t.Fatalf("a subscription home: %v", err) |
| + } |
| + }) |
| +} |
| + |
| +// TestDarwinCheckRefusesBeforeTheLease (#6): the check's own gate |
| +// refuses before the account's lease is opened: with the account busy, |
| +// a tainted runner still says tainted at once. |
| +func TestDarwinCheckRefusesBeforeTheLease(t *testing.T) { |
| + r := newDarwinRig(t) |
| + local, home := connected(t, r, fakeclaude.Token("a@example.com")) |
| + b, _ := r.binding(local) |
| + lock, err := os.Open(home) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer lock.Close() |
| + if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.m.taint.Set() |
| + start := time.Now() |
| + if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errTainted) || time.Since(start) > 2*time.Second { |
| + t.Fatalf("a tainted check with the account busy: %v after %s", err, time.Since(start)) |
| + } |
| +} |
| + |
| +// TestDarwinStoreWaitsForTheTurn (#6): a token is stored only in the |
| +// Mac's turn: while another operation holds it, the delivery waits, then |
| +// fails to be sent again, and nothing is written. |
| +func TestDarwinStoreWaitsForTheTurn(t *testing.T) { |
| + r := newDarwinRig(t) |
| + was := tokenStoreWait |
| + tokenStoreWait = 300 * time.Millisecond |
| + defer func() { tokenStoreWait = was }() |
| + c := r.connector() |
| + r.connect(c, "c1") |
| + u, ok := r.m.turns.TryTake(mac.OpWarm) |
| + if !ok { |
| + t.Fatal("the turn is busy") |
| + } |
| + cmd := r.sealed("c1", fakeclaude.Token("a@example.com"), nil) |
| + if r.deliver(c, "f-c1", cmd) || r.seals("c1") != 0 { |
| + t.Fatal("stored while another operation held the turn") |
| + } |
| + u.Give() |
| + if !r.deliver(c, "f-c1", cmd) || r.ended("c1").State != wire.ConnHealthy { |
| + t.Fatal("the resend after the turn was free did not connect") |
| + } |
| +} |
| + |
| +// TestDarwinSignInUnprovenKeepsTheWatch (#6): a sign-in whose CLI's end |
| +// cannot be proven keeps its watch (and its attempt, for the restart). |
| +func TestDarwinSignInUnprovenKeepsTheWatch(t *testing.T) { |
| + r := newDarwinRig(t) |
| + r.lingering(t, "setup-token") |
| + c := r.connector() |
| + r.signIn(c, "s1") |
| + if err := c.Cancel(r.ctx, "f-cancel-s1", wire.CancelConnectCommand{Connection: "s1", Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.waitFor(func() bool { return r.turnFree() }, "the sign-in to stop") |
| + var state string |
| + _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id='s1'").Scan(&state) |
| + if !r.m.Held() || state != "running" { |
| + t.Fatalf("an unproven sign-in: held=%v state=%s", r.m.Held(), state) |
| + } |
| +} |
| + |
| +// TestDarwinSignInRecoveredAtRestart (#6): a sign-in left running by a |
| +// dead runner has its CLI killed by its record at the restart, then |
| +// ends runner_offline. |
| +func TestDarwinSignInRecoveredAtRestart(t *testing.T) { |
| + r := newDarwinRig(t) |
| + marker := "signin-left" |
| + cmd := exec.Command("/bin/sleep", "600") |
| + cmd.Env = []string{"EQUIPO_ATTEMPT=" + marker} |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| + if err := cmd.Start(); err != nil { |
| + t.Fatal(err) |
| + } |
| + go func() { _ = cmd.Wait() }() |
| + defer func() { _ = cmd.Process.Kill() }() |
| + 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 { |
| + t.Fatal(err) |
| + } |
| + r.connector() |
| + if end := r.ended("s1"); end.Reason != "runner_offline" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + r.waitFor(func() bool { return !pidAlive(cmd.Process.Pid) }, "the left CLI to be gone") |
| +} |
| + |
| +// TestDarwinStartRefusesABadToken (#6): the descriptor carries only a |
| +// token that fits one: no NUL, CR or LF, not empty, bounded. |
| +func TestDarwinStartRefusesABadToken(t *testing.T) { |
| + r := newDarwinRig(t) |
| + u, err := r.m.turns.Take(r.ctx, mac.OpTokenCheck) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer u.Give() |
| + dir, marker, err := r.m.place("status-") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, tok := range [][]byte{{}, []byte("sk-ant\nx"), []byte("sk\x00"), make([]byte, mac.MaxToken+1)} { |
| + 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) { |
| + t.Fatalf("token %q: %v", tok, err) |
| + } |
| + } |
| + if len(r.launches()) != 0 { |
| + t.Fatal("a bad token started the CLI") |
| + } |
| +} |
| + |
| +// TestMacCapsSettleTheKeychain (#6): the hourly capability gathering |
| +// looks again for what the Keychain watch found, and lets go once it is |
| +// gone. |
| +func TestMacCapsSettleTheKeychain(t *testing.T) { |
| + r := newDarwinRig(t) |
| + h := &macHost{creds: r.m, taint: r.m.taint} |
| + other := creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user} |
| + if err := r.m.keychain.Before(r.ctx, "signin-1", filepath.Join(r.cfg.ScratchRoot, "homes", "signin-1")); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.kc.add(other) |
| + if _, err := r.m.keychain.After(r.ctx, "signin-1"); err != nil || !r.m.Held() { |
| + t.Fatalf("not held: %v", err) |
| + } |
| + r.kc.mu.Lock() |
| + r.kc.items = nil |
| + r.kc.mu.Unlock() |
| + caps := wire.Capabilities{} |
| + h.credentialCaps(r.ctx, &caps) |
| + if r.m.Held() { |
| + t.Fatal("the gathering did not look again") |
| + } |
| +} |
| + |
| +// TestMacKeychainListsLoginByPath (#2): the runner lists its login |
| +// keychain by its path, and refuses to decide when it is not there. |
| +func TestMacKeychainListsLoginByPath(t *testing.T) { |
| + dir := shortDir(t) |
| + args := filepath.Join(dir, "args") |
| + security := filepath.Join(dir, "security") |
| + login := filepath.Join(dir, "login.keychain-db") |
| + script := "#!/bin/sh\necho \"$@\" > " + args + "\nprintf 'keychain: \"%s\"\\nclass: \"genp\"\\nattributes:\\n \"acct\"<blob>=\"u\"\\n \"svce\"<blob>=\"Other App\"\\n' \"$2\"\n" |
| + if err := os.WriteFile(security, []byte(script), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + was, wasOn := macSecurity, macKeychains |
| + macSecurity, macKeychains = security, true |
| + defer func() { macSecurity, macKeychains = was, wasOn }() |
| + h := &macHost{} |
| + if _, err := h.keychainList(context.Background(), login); err == nil { |
| + t.Fatal("listed a login keychain that is not there") |
| + } |
| + if err := os.WriteFile(login, nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + items, err := h.keychainList(context.Background(), login) |
| + raw, _ := os.ReadFile(args) |
| + if err != nil || strings.TrimSpace(string(raw)) != "dump-keychain "+login || len(items) != 1 || items[0].Keychain != login { |
| + t.Fatalf("listed %q: %+v %v", raw, items, err) |
| + } |
| +} |
diff --git a/internal/runner/thin/maccreds_test.go b/internal/runner/thin/maccreds_test.go| index 726b7977..adb7d250 100644 |
| --- a/internal/runner/thin/maccreds_test.go |
| +++ b/internal/runner/thin/maccreds_test.go |
| @@ -39,13 +39,16 @@ import ( |
| // launchScript is the pinned stand-in: %[1]s is the rig's directory. |
| // With <dir>/hang it never answers a check (-p): it says its pid and |
| -// sleeps, as a hung CLI would. |
| +// sleeps, as a hung CLI would. With <dir>/linger naming its first |
| +// argument it leaves a child that ignores SIGTERM, so its end cannot be |
| +// proven within a short Settle. |
| const launchScript = `#!/bin/sh |
| d=%[1]s |
| env > "$d/bin/launch.$$.env" |
| pwd > "$d/bin/launch.$$.cwd" |
| echo "$*" > "$d/bin/launch.$$.argv" |
| if [ "$1" = "-p" ] && [ -e "$d/hang" ]; then echo $$ > "$d/hang.pid"; exec /bin/sleep 600; fi |
| +if [ -e "$d/linger" ] && [ "$1" = "$(cat "$d/linger")" ]; then (trap "" TERM HUP; exec /bin/sleep 5) & echo $! > "$d/linger.pid"; fi |
| exec "$d/bin/claude" "$@" |
| ` |
| @@ -63,20 +66,62 @@ type keychainFake struct { |
| // what it said at the first listing. |
| started func() bool |
| startedAt []bool |
| + // asked is each keychain listed. create, when set, is what a CLI |
| + // launch stored in the login keychain (it runs once per launch, at |
| + // the first listing after it). |
| + asked []string |
| + create func(launched) []creds.Item |
| + created map[int]bool |
| + r *darwinRig |
| } |
| -func (f *keychainFake) list(context.Context) ([]creds.Item, error) { |
| +func (f *keychainFake) list(_ context.Context, keychain string) ([]creds.Item, error) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| f.lists++ |
| + f.asked = append(f.asked, keychain) |
| if f.started != nil { |
| f.startedAt = append(f.startedAt, f.started()) |
| } |
| - out := append(slices.Clone(f.items), f.ghost...) |
| + if f.create != nil { |
| + if f.created == nil { |
| + f.created = map[int]bool{} |
| + } |
| + for _, l := range f.r.launches() { |
| + if !f.created[l.pid] { |
| + f.created[l.pid] = true |
| + f.items = append(f.items, f.create(l)...) |
| + } |
| + } |
| + } |
| + var out []creds.Item |
| + for _, i := range append(slices.Clone(f.items), f.ghost...) { |
| + if i.Keychain == keychain { |
| + out = append(out, i) |
| + } |
| + } |
| f.ghost = nil |
| return out, nil |
| } |
| +// creating makes each later launch whose argv starts with prefix store |
| +// item(its CLAUDE_CONFIG_DIR), as a CLI writing to the Keychain would. |
| +func (r *darwinRig) creating(prefix string, item func(dir string) creds.Item) { |
| + f := r.kc |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.created = map[int]bool{} |
| + for _, l := range r.launches() { |
| + f.created[l.pid] = true |
| + } |
| + f.create = func(l launched) []creds.Item { |
| + if !strings.HasPrefix(l.argv, prefix) { |
| + return nil |
| + } |
| + return []creds.Item{item(l.env["CLAUDE_CONFIG_DIR"])} |
| + } |
| +} |
| + |
| func (f *keychainFake) delete(_ context.Context, i creds.Item) error { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| @@ -152,7 +197,10 @@ func newDarwinRig(t *testing.T) *darwinRig { return darwinRigAt(t, shortDir(t)) |
| func darwinRigAt(t *testing.T, dir string) *darwinRig { |
| t.Helper() |
| r := &darwinRig{tokenRig: newTokenRigAt(t, dir), kc: &keychainFake{}} |
| + r.kc.r = r |
| r.cfg.StateDir = filepath.Join(dir, "state") |
| + // A Mac has no Linux CLI path: only the pinned CLI, by Launch. |
| + r.cfg.ClaudePath = "" |
| proxy := filepath.Join(dir, "bin", "equipo-tool-proxy") |
| if _, err := os.Lstat(proxy); err != nil { |
| self, _ := os.Executable() |
| @@ -622,7 +670,9 @@ func TestDarwinSignIn(t *testing.T) { |
| t.Fatal("the unrelated item does not hold") |
| } |
| }) |
| - t.Run("matching attributes in another keychain are left", func(t *testing.T) { |
| + // Only the login keychain is the watch's (fix round 1, #2): one |
| + // elsewhere is never touched. |
| + t.Run("matching attributes in another keychain are left alone", func(t *testing.T) { |
| r := newDarwinRig(t) |
| c := r.connector() |
| link, _ := r.signIn(c, "s1") |
| @@ -630,11 +680,14 @@ func TestDarwinSignIn(t *testing.T) { |
| elsewhere.Keychain = filepath.Join(r.dir, "Library", "Keychains", "other.keychain-db") |
| r.kc.add(elsewhere) |
| r.codeIn(c, "s1", link, "a@example.com") |
| - if end := r.ended("s1"); end.Reason != "provider_refused" { |
| - t.Fatalf("end %+v", end) |
| + r.ended("s1") |
| + if !r.kc.has(elsewhere) || len(r.kc.deleted) != 0 { |
| + t.Fatalf("deleted %+v", r.kc.deleted) |
| } |
| - if !r.kc.has(elsewhere) || len(r.kc.deleted) != 0 || !r.m.Held() { |
| - t.Fatalf("deleted %+v held=%v", r.kc.deleted, r.m.Held()) |
| + for _, kc := range r.kc.asked { |
| + if kc != r.m.keychain.Login { |
| + t.Fatalf("listed %q", kc) |
| + } |
| } |
| }) |
| t.Run("restart", func(t *testing.T) { |