Mac slice F task 10: token check, sign-in, home guard, taint gate
A Mac worker's Claude credential, built for darwin and tested on Linux with the pinned-CLI stand-in (test build) and recorded fixtures: - mac/creds (new): the home guard (ownership, mode bits and ACLs from lstat and ls -led, never an access test) and the Keychain watch around a sign-in (attributes-only listings, durable before-list, delete only the attempt's own item by service, account and path, hold until a listing shows it gone); the darwin pty. - thin/maccreds.go (new): the guards (taint first, then the home guard) at every store and use; the darwin token check (check-only policy, token on fd 3, workspace under scratch, socket under toolRoot, one OpTokenCheck turn); auth status by descriptor; the sign-in terminal in an OpSignIn turn; the store in OpTokenStore; EngineeringStatus tainted or home_open. - Hooks in tokencheck.go (shared readCheck), signin.go, token.go, connector.go, mac.go; mac.Command.TTY; mac.PinnedForTest (test build only); the fake CLI reads its token from a descriptor. - Copy drafts runner.mac.home_open, home_open_folder, keychain_item (pending). Budgets re-measured: thin 31384/27420, equipo 24014. The thin glue was written before its tests; RED was taken against the glue reverted to the pre-task behaviour (recorded in the report), and every guard has a mutation that a named test kills.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
26 files changed,
+2,947
−16
.rastrillo/budgets.txt+2 −2docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json+15 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+3 −0internal/equipo/copy.go+5 −2internal/fakeclaude/fake.go+15 −1internal/runner/mac/claude_testbuild.go+3 −0internal/runner/mac/creds/guard.go+300 −0internal/runner/mac/creds/guard_test.go+239 −0internal/runner/mac/creds/keychain.go+485 −0internal/runner/mac/creds/keychain_test.go+305 −0internal/runner/mac/creds/pty_darwin.go+46 −0internal/runner/mac/creds/pty_linux.go+11 −0internal/runner/mac/creds/testdata/dump-keychain-constructed-2026-11-29-docs-t1.txt+45 −0internal/runner/mac/creds/testdata/ls-led-constructed-2026-11-29-docs-t1.txt+22 −0internal/runner/mac/creds/testdata/ls-led-users-2026-11-28-tito-studio.txt+21 −0internal/runner/mac/launch.go+7 −2internal/runner/thin/claude.go+3 −0internal/runner/thin/connector.go+9 −0internal/runner/thin/mac.go+15 −0internal/runner/thin/maccreds.go+561 −0internal/runner/thin/maccreds_test.go+763 −0internal/runner/thin/signin.go+22 −1internal/runner/thin/token.go+22 −1internal/runner/thin/token_test.go+4 −2internal/runner/thin/tokencheck.go+19 −5internal/runner/thin/toolproxy_linux_test.go+5 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 516edda5..9d6ceb08 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,7 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| -size internal/equipo 24011 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes; measured 24011. |
| +size internal/equipo 24014 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, Mac waits, probe and proof codes, Mac credential copy; measured 24014. |
| size internal/wire 8604 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), Mac waits, 37 Mac Engineering, probe and proof codes; measured 8604. |
| size internal/equipotest - 12683 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures and Rastrillo asset contract; measured 0/12683 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| @@ -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 30740 26650 Protocols 31 to 35, merge credential, publication guards, kept work, scans, Mac pin, paths, bases, endpoint, Mac turns; measured 30740/26650. |
| +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. |
| 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/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json| index 23f6aa6a..8270d5c7 100644 |
| --- a/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json |
| +++ b/docs/superpowers/plans/2026-11-28-mac-slice-f-copy.json |
| @@ -83,5 +83,20 @@ |
| "key": "runner.unproven.record_incomplete", |
| "where": "Machines page, a Mac's card: a note when an attempt there can never be proven over (its turn record was incomplete; wire.UnprovenRecordIncomplete). The step stays unfinished, with no Retry.", |
| "draft": "Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished." |
| + }, |
| + { |
| + "key": "runner.mac.home_open", |
| + "where": "Machines page, a Mac whose home guard fails on its home folder (Engineering status home_open, reason home_mode); %[1]s is the Mac's runner user", |
| + "draft": "Other people on this Mac can open %[1]s's home folder, so Equipo won't keep Claude there. Run chmod 700 ~ as %[1]s, then try again." |
| + }, |
| + { |
| + "key": "runner.mac.home_open_folder", |
| + "where": "Machines page, a Mac whose home guard fails on another folder (Engineering status home_open, any other reason); %[1]s is the Mac's runner user", |
| + "draft": "Other people on this Mac can reach a folder where %[1]s keeps Claude, so Equipo won't keep Claude there. The runner's log names the folder and what to change." |
| + }, |
| + { |
| + "key": "runner.mac.keychain_item", |
| + "where": "Machines page, a Mac holding a Keychain item a sign-in left, or one with Claude Code's name it found there; %[1]s is the item's service name, %[2]s the Mac's runner user", |
| + "draft": "This Mac's Keychain has an item named %[1]s, so Equipo won't keep Claude there. Remove it in Keychain Access as %[2]s, then try again." |
| } |
| ] |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 2dc7624f..1cca79ee 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -7022,6 +7022,9 @@ records remain unchanged. |
| | `work.reason.workspace_too_large` | the project is too large to send to the Mac | Copy specialist | COPY REVIEW PENDING | |
| | `runner.probe_detail.turn_busy` | The Mac was busy with other work, so this was not checked. | Copy specialist | COPY REVIEW PENDING | |
| | `runner.unproven.record_incomplete` | Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished. | Copy specialist | COPY REVIEW PENDING | |
| +| `runner.mac.home_open` | Other people on this Mac can open %[1]s's home folder, so Equipo won't keep Claude there. Run chmod 700 ~ as %[1]s, then try again. | Copy specialist | COPY REVIEW PENDING | |
| +| `runner.mac.home_open_folder` | Other people on this Mac can reach a folder where %[1]s keeps Claude, so Equipo won't keep Claude there. The runner's log names the folder and what to change. | Copy specialist | COPY REVIEW PENDING | |
| +| `runner.mac.keychain_item` | This Mac's Keychain has an item named %[1]s, so Equipo won't keep Claude there. Remove it in Keychain Access as %[2]s, then try again. | Copy specialist | COPY REVIEW PENDING | |
| ## Task 21 |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 86fd3603..dcc48d28 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -2109,8 +2109,11 @@ var pageCopy = map[string]string{ |
| "runner.verdict.skipped": "Not run", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "runner.verdict.unavailable": "Unavailable", |
| - "runner.unproven.record_incomplete": "Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished.", // COPY REVIEW PENDING |
| - "runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING |
| + "runner.unproven.record_incomplete": "Equipo could not prove that an earlier step on this Mac stopped completely, so that step stays unfinished.", // COPY REVIEW PENDING |
| + "runner.probe_detail.turn_busy": "The Mac was busy with other work, so this was not checked.", // COPY REVIEW PENDING |
| + "runner.mac.home_open": "Other people on this Mac can open %[1]s's home folder, so Equipo won't keep Claude there. Run chmod 700 ~ as %[1]s, then try again.", // COPY REVIEW PENDING |
| + "runner.mac.home_open_folder": "Other people on this Mac can reach a folder where %[1]s keeps Claude, so Equipo won't keep Claude there. The runner's log names the folder and what to change.", // COPY REVIEW PENDING |
| + "runner.mac.keychain_item": "This Mac's Keychain has an item named %[1]s, so Equipo won't keep Claude there. Remove it in Keychain Access as %[2]s, then try again.", // COPY REVIEW PENDING |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "runner.origin": "Equipo address:", |
| // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index 00357891..6d92641d 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -150,6 +150,17 @@ const Version = "2.1.312" |
| // Main runs the fake with argv after the program name. |
| func Main(args []string, stdin io.Reader, stdout, stderr io.Writer) int { |
| + // The token by descriptor, as the pinned CLI reads it (task 1, S4): |
| + // /dev/fd/<n>, trimmed, when CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR |
| + // names one; the fake then holds it as if it were in its environment. |
| + if n := os.Getenv(tokenFDEnv); n != "" && os.Getenv(tokenEnv) == "" { |
| + raw, err := os.ReadFile("/dev/fd/" + n) |
| + if err != nil || len(raw) == 0 { |
| + fmt.Fprintln(stderr, "no token on descriptor "+n) |
| + return 3 |
| + } |
| + os.Setenv(tokenEnv, strings.TrimSpace(string(raw))) |
| + } |
| if tok := os.Getenv(tokenEnv); tok != "" { |
| for _, a := range args { |
| if strings.Contains(a, tok) { |
| @@ -1434,7 +1445,10 @@ var reviewAuthWord = regexp.MustCompile(`\breviewauth:([^\s|]+@[^\s|]+[a-z])`) |
| // stepLimitWord is steplimit:<email>, for an Engineering step only. |
| var stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`) |
| -const tokenEnv = "CLAUDE_CODE_OAUTH_TOKEN" |
| +const ( |
| + tokenEnv = "CLAUDE_CODE_OAUTH_TOKEN" |
| + tokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" |
| +) |
| // CheckPrompt is the runner's token check, word for word (thin's |
| // tokenCheckPrompt). |
diff --git a/internal/runner/mac/claude_testbuild.go b/internal/runner/mac/claude_testbuild.go| index f0f585f9..a00910e3 100644 |
| --- a/internal/runner/mac/claude_testbuild.go |
| +++ b/internal/runner/mac/claude_testbuild.go |
| @@ -21,3 +21,6 @@ func claudeStandIn(getenv func(string) string) ClaudeFetch { |
| } |
| return func(context.Context, string) (io.ReadCloser, error) { return os.Open(path) } |
| } |
| + |
| +// PinnedForTest is c pinned to pin (a test build's own CLI stand-in). |
| +func PinnedForTest(c ClaudeCLI, pin string) ClaudeCLI { c.pin = pin; return c } |
diff --git a/internal/runner/mac/creds/guard.go b/internal/runner/mac/creds/guard.go| new file mode 100644 |
| index 00000000..af5ce49e |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/guard.go |
| @@ -0,0 +1,300 @@ |
| +// Package creds is a Mac worker's Claude credential guards (Mac runners |
| +// spec §8.3, §8.7; slice F task 10): the home guard, which decides from |
| +// ownership, mode bits and ACLs whether anyone else could reach the |
| +// folders a connection lives in, and the Keychain watch around a |
| +// sign-in. It reads facts through seams (ls -led and lstat, security |
| +// dump-keychain), so everything here is tested with recorded outputs. |
| +package creds |
| + |
| +import ( |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| +) |
| + |
| +// ACE is one access control entry as ls -le prints it: |
| +// " 0: user:vicky inherited allow read,write". |
| +type ACE struct { |
| + Index int |
| + Who string |
| + Inherited bool |
| + Allow bool |
| + Rights []string |
| +} |
| + |
| +// Fact is what the guard knows of one path: its kind ('d' a directory, |
| +// 'l' a link, '-' a file), its permission bits, its owner (the name ls |
| +// prints and the uid lstat reads, -1 unknown) and its ACL entries. |
| +type Fact struct { |
| + Path string |
| + Kind byte |
| + Perm fs.FileMode |
| + Owner string |
| + UID int |
| + ACL []ACE |
| + Missing bool |
| +} |
| + |
| +var ( |
| + lsHeader = regexp.MustCompile(`^([-dlbcps])([-rwxsStT]{9})([@+]?)\s+\d+\s+(\S+)\s+(\S+)\s+\d+\s+\S+\s+\S+\s+\S+\s+(.+)$`) |
| + lsEntry = regexp.MustCompile(`^\s*(\d+): (\S+) (inherited )?(allow|deny) ([a-z_]+(?:,[a-z_]+)*)$`) |
| +) |
| + |
| +// ErrUnreadable: ls output the guard cannot read for sure. It decides |
| +// nothing from it. |
| +var ErrUnreadable = errors.New("creds: ls output not understood") |
| + |
| +// ParseLS reads `ls -led` output: each path's line and the ACL entries |
| +// under it. A line it does not understand, or a "+" with no entry, is |
| +// ErrUnreadable. |
| +func ParseLS(out string) ([]Fact, error) { |
| + var facts []Fact |
| + plus := false |
| + end := func() error { |
| + if len(facts) > 0 && plus && len(facts[len(facts)-1].ACL) == 0 { |
| + return ErrUnreadable |
| + } |
| + return nil |
| + } |
| + for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") { |
| + if line == "" { |
| + continue |
| + } |
| + if m := lsEntry.FindStringSubmatch(line); m != nil { |
| + if len(facts) == 0 { |
| + return nil, ErrUnreadable |
| + } |
| + f := &facts[len(facts)-1] |
| + n, _ := strconv.Atoi(m[1]) |
| + if n != len(f.ACL) { |
| + return nil, ErrUnreadable |
| + } |
| + f.ACL = append(f.ACL, ACE{Index: n, Who: m[2], Inherited: m[3] != "", Allow: m[4] == "allow", Rights: strings.Split(m[5], ",")}) |
| + continue |
| + } |
| + m := lsHeader.FindStringSubmatch(line) |
| + if m == nil { |
| + return nil, ErrUnreadable |
| + } |
| + if err := end(); err != nil { |
| + return nil, err |
| + } |
| + path := m[6] |
| + if m[1] == "l" { |
| + path, _, _ = strings.Cut(path, " -> ") |
| + } |
| + facts = append(facts, Fact{Path: path, Kind: m[1][0], Perm: permOf(m[2]), Owner: m[4], UID: -1}) |
| + plus = m[3] == "+" |
| + } |
| + if err := end(); err != nil { |
| + return nil, err |
| + } |
| + return facts, nil |
| +} |
| + |
| +// permOf is the 0777 bits of an ls mode string ("rwxr-x---"): s and t |
| +// carry x, S and T do not. |
| +func permOf(s string) fs.FileMode { |
| + var p fs.FileMode |
| + for i, c := range s { |
| + if c != '-' && c != 'S' && c != 'T' { |
| + p |= 1 << (8 - i) |
| + } |
| + } |
| + return p |
| +} |
| + |
| +// Read is path's fact: the kind, mode and owner lstat reads (never |
| +// following a link), and, when ls is set, the ACL `ls -led` prints, its |
| +// mode and owner required to agree. ls nil (off a Mac) reads no ACL. |
| +func Read(path string, ls func(string) (string, error)) (Fact, error) { |
| + info, err := os.Lstat(path) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return Fact{Path: path, Missing: true, UID: -1}, nil |
| + } |
| + if err != nil { |
| + return Fact{}, err |
| + } |
| + f := Fact{Path: path, Kind: '-', Perm: info.Mode().Perm(), UID: -1} |
| + switch { |
| + case info.Mode()&fs.ModeSymlink != 0: |
| + f.Kind = 'l' |
| + case info.IsDir(): |
| + f.Kind = 'd' |
| + case !info.Mode().IsRegular(): |
| + f.Kind = '?' |
| + } |
| + if st, ok := info.Sys().(*syscall.Stat_t); ok { |
| + f.UID = int(st.Uid) |
| + } |
| + if ls == nil { |
| + return f, nil |
| + } |
| + out, err := ls(path) |
| + if err != nil { |
| + return Fact{}, err |
| + } |
| + facts, err := ParseLS(out) |
| + if err != nil || len(facts) != 1 || facts[0].Path != path || facts[0].Kind != f.Kind || facts[0].Perm != f.Perm { |
| + return Fact{}, ErrUnreadable |
| + } |
| + f.Owner, f.ACL = facts[0].Owner, facts[0].ACL |
| + return f, nil |
| +} |
| + |
| +// Problem codes: what is wrong, in the capability string rules (the |
| +// Engineering status's reason). |
| +const ( |
| + CodeHomeMode = "home_mode" |
| + CodeMode = "mode" |
| + CodeACL = "acl" |
| + CodeOwner = "owner" |
| + CodeOutside = "outside" |
| + CodeLink = "link" |
| + CodeMissing = "missing" |
| + CodeUnknown = "unknown" |
| +) |
| + |
| +// Input is what the guard checks: the runner user (name and uid), its |
| +// home, and the roots that must be private inside it (the state dir, |
| +// the config dir, the accounts root). |
| +type Input struct { |
| + User string |
| + UID int |
| + Home string |
| + Roots []string |
| +} |
| + |
| +// Problem is one thing to change: the path, the code, and the command |
| +// that changes it, run as the runner user unless it says otherwise. |
| +type Problem struct { |
| + Path, Code, Fix string |
| +} |
| + |
| +// Result is the guard's verdict: no problem passes. |
| +type Result struct { |
| + Problems []Problem |
| +} |
| + |
| +// OK: nobody else can list, traverse, read or replace any root. |
| +func (r Result) OK() bool { return len(r.Problems) == 0 } |
| + |
| +// Reason is the first problem's code, "" when it passes. |
| +func (r Result) Reason() string { |
| + if r.OK() { |
| + return "" |
| + } |
| + return r.Problems[0].Code |
| +} |
| + |
| +// Fix is every change to make, in order, one per line. |
| +func (r Result) Fix() string { |
| + var out []string |
| + for _, p := range r.Problems { |
| + if !slices.Contains(out, p.Fix) { |
| + out = append(out, p.Fix) |
| + } |
| + } |
| + return strings.Join(out, "\n") |
| +} |
| + |
| +// Check decides from ownership, mode bits and ACLs alone, through read, |
| +// never by opening anything as this user (which cannot see what another |
| +// user sees). It passes only when the home and every root are real |
| +// directories inside the home, owned by the user, with no group or other |
| +// bit and no ACL entry allowing anyone else anything (inherited or not), |
| +// and every directory between the home and a root is a real directory |
| +// the user owns, with no group or other write bit and no such entry. |
| +func Check(in Input, read func(string) (Fact, error)) Result { |
| + var r Result |
| + home := filepath.Clean(in.Home) |
| + add := func(p, code, fix string) { |
| + r.Problems = append(r.Problems, Problem{Path: p, Code: code, Fix: fix}) |
| + } |
| + if !filepath.IsAbs(in.Home) || home == "/" || in.User == "" || in.UID < 0 { |
| + 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 |
| + } |
| + seen[p] = true |
| + at := tilde(home, p) |
| + f, err := read(p) |
| + switch { |
| + case err != nil: |
| + add(p, CodeUnknown, at+" could not be checked") |
| + return false |
| + case f.Missing: |
| + add(p, CodeMissing, "mkdir -m 700 "+at) |
| + return false |
| + case f.Kind == 'l': |
| + add(p, CodeLink, "replace the link "+at+" with a folder") |
| + return false |
| + case f.Kind != 'd': |
| + add(p, CodeLink, "replace "+at+" with a folder") |
| + return false |
| + } |
| + if f.UID != in.UID || f.Owner != "" && f.Owner != in.User && f.Owner != strconv.Itoa(in.UID) { |
| + add(p, CodeOwner, "sudo chown "+in.User+" "+at+" (an administrator)") |
| + } |
| + switch { |
| + case root && f.Perm&0o077 != 0 && p == home: |
| + add(p, CodeHomeMode, "chmod 700 ~") |
| + case root && f.Perm&0o077 != 0: |
| + add(p, CodeMode, "chmod 700 "+at) |
| + case !root && f.Perm&0o022 != 0: |
| + add(p, CodeMode, "chmod go-w "+at) |
| + } |
| + // Highest index first, so each removal leaves the next one's |
| + // number as printed. |
| + for i := len(f.ACL) - 1; i >= 0; i-- { |
| + if e := f.ACL[i]; e.Allow && e.Who != "user:"+in.User { |
| + add(p, CodeACL, "chmod -a# "+strconv.Itoa(e.Index)+" "+at) |
| + } |
| + } |
| + return true |
| + } |
| + look(home, true) |
| + for _, root := range in.Roots { |
| + p := filepath.Clean(root) |
| + if !filepath.IsAbs(root) || !within(home, p) { |
| + add(p, CodeOutside, "keep "+p+" inside ~") |
| + continue |
| + } |
| + rel, _ := strings.CutPrefix(p, home) |
| + 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) |
| + } |
| + if ok && p != home { |
| + look(p, true) |
| + } |
| + } |
| + return r |
| +} |
| + |
| +// tilde is p with the home written ~. |
| +func tilde(home, p string) string { |
| + if p == home { |
| + return "~" |
| + } |
| + if rel, ok := strings.CutPrefix(p, home+"/"); ok { |
| + return "~/" + rel |
| + } |
| + return p |
| +} |
| + |
| +// within: p is home or below it (both clean and absolute). |
| +func within(home, p string) bool { |
| + return p == home || strings.HasPrefix(p, home+"/") |
| +} |
diff --git a/internal/runner/mac/creds/guard_test.go b/internal/runner/mac/creds/guard_test.go| new file mode 100644 |
| index 00000000..35b93b8a |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/guard_test.go |
| @@ -0,0 +1,239 @@ |
| +package creds |
| + |
| +import ( |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// The fixtures, each named for its date and machine: |
| +// - ls-led-users-2026-11-28-tito-studio.txt is recorded: `ls -led |
| +// /Users/*` on tito-studio as paulca, 2026-11-28 17:55Z (task 1, R2). |
| +// - ls-led-constructed-2026-11-29-docs-t1.txt is constructed on docs-t1 |
| +// in the recording's format, for the ACL cases no recording shows. |
| + |
| +// uids are the Studio's (R2: paulequipo is 506). |
| +var uids = map[string]int{"paulequipo": 506, "paulca": 502, "vicky": 507, "root": 0, "billhorsman": 501, "ci": 503, "drbparsons": 504, "murraysum": 505} |
| + |
| +// facts reads a fixture into the guard's reader, each owner's uid as the |
| +// Studio has it. |
| +func facts(t *testing.T, names ...string) map[string]Fact { |
| + t.Helper() |
| + out := map[string]Fact{} |
| + for _, name := range names { |
| + raw, err := os.ReadFile(filepath.Join("testdata", name)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + list, err := ParseLS(string(raw)) |
| + if err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + for _, f := range list { |
| + f.UID = uids[f.Owner] |
| + out[f.Path] = f |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func reader(m map[string]Fact) func(string) (Fact, error) { |
| + return func(p string) (Fact, error) { |
| + f, ok := m[p] |
| + if !ok { |
| + return Fact{Path: p, Missing: true, UID: -1}, nil |
| + } |
| + return f, nil |
| + } |
| +} |
| + |
| +// private is a 0700 directory of paulequipo's with no ACL. |
| +func private(p string) Fact { |
| + return Fact{Path: p, Kind: 'd', Perm: 0700, Owner: "paulequipo", UID: 506} |
| +} |
| + |
| +const home = "/Users/paulequipo" |
| + |
| +// studio is the Studio's runner layout, every folder private: the state |
| +// dir, the config dir and the accounts root, and the folders between. |
| +func studio() map[string]Fact { |
| + m := map[string]Fact{} |
| + for _, p := range []string{home, home + "/.local", home + "/.local/share", home + "/.local/share/equipo-runner", home + "/.local/share/equipo-runner/state", home + "/.config", home + "/.config/equipo-runner", home + "/.local/share/equipo", home + "/.local/share/equipo/accounts"} { |
| + m[p] = private(p) |
| + } |
| + return m |
| +} |
| + |
| +var studioIn = Input{User: "paulequipo", UID: 506, Home: home, Roots: []string{home + "/.local/share/equipo-runner/state", home + "/.config/equipo-runner", home + "/.local/share/equipo/accounts"}} |
| + |
| +// codes is each problem as path=code. |
| +func codes(r Result) []string { |
| + var out []string |
| + for _, p := range r.Problems { |
| + out = append(out, p.Path+"="+p.Code) |
| + } |
| + return out |
| +} |
| + |
| +// TestHomeGuard: the guard passes only a private layout, and names what |
| +// to change for each way another user could reach it. |
| +func TestHomeGuard(t *testing.T) { |
| + t.Run("0700 passes", func(t *testing.T) { |
| + r := Check(studioIn, reader(studio())) |
| + if !r.OK() || r.Reason() != "" || r.Fix() != "" { |
| + t.Fatalf("a private layout failed: %v", codes(r)) |
| + } |
| + }) |
| + t.Run("an allow entry for the user itself passes", func(t *testing.T) { |
| + m := studio() |
| + f := facts(t, "ls-led-constructed-2026-11-29-docs-t1.txt")[home+"/.self"] |
| + f.Path = home |
| + m[home] = f |
| + if r := Check(studioIn, reader(m)); !r.OK() { |
| + t.Fatalf("the user's own entry and a deny failed it: %v", codes(r)) |
| + } |
| + }) |
| + // The Studio's own home today (recorded, R2): drwxr-x---+ group |
| + // staff, and every person is in staff. It must fail, naming chmod 700 ~. |
| + t.Run("the Studio's paulequipo today", func(t *testing.T) { |
| + m := studio() |
| + m[home] = facts(t, "ls-led-users-2026-11-28-tito-studio.txt")[home] |
| + r := Check(studioIn, reader(m)) |
| + if r.OK() || r.Reason() != CodeHomeMode || r.Fix() != "chmod 700 ~" || len(r.Problems) != 1 { |
| + t.Fatalf("paulequipo's recorded home: %v %q", codes(r), r.Fix()) |
| + } |
| + }) |
| + t.Run("every recorded home fails for its own user", func(t *testing.T) { |
| + for path, f := range facts(t, "ls-led-users-2026-11-28-tito-studio.txt") { |
| + if f.Owner == "root" { |
| + continue |
| + } |
| + r := Check(Input{User: f.Owner, UID: f.UID, Home: path}, reader(map[string]Fact{path: f})) |
| + if r.Reason() != CodeHomeMode { |
| + t.Fatalf("%s: %v", path, codes(r)) |
| + } |
| + } |
| + }) |
| + // Each case changes one folder of the private layout to the fixture's |
| + // folder of that name; the guard must fail with code, naming fix. |
| + cases := []struct { |
| + name, at, fixture, code, fix string |
| + }{ |
| + {"0750 on a root", home + "/.config/equipo-runner", ".g750", CodeMode, "chmod 700 ~/.config/equipo-runner"}, |
| + {"0750 on the home", home, ".g750", CodeHomeMode, "chmod 700 ~"}, |
| + {"group read alone on the home", home, ".g740", CodeHomeMode, "chmod 700 ~"}, |
| + {"group read alone on a root", home + "/.local/share/equipo/accounts", ".g740", CodeMode, "chmod 700 ~/.local/share/equipo/accounts"}, |
| + {"other read alone on a root", home + "/.local/share/equipo-runner/state", ".o704", CodeMode, "chmod 700 ~/.local/share/equipo-runner/state"}, |
| + {"an ACL grant to everyone", home, ".everyone", CodeACL, "chmod -a# 0 ~"}, |
| + {"an ACL grant to one user", home + "/.local/share/equipo/accounts", ".vicky", CodeACL, "chmod -a# 0 ~/.local/share/equipo/accounts"}, |
| + {"a write grant", home + "/.local/share/equipo-runner/state", ".write", CodeACL, "chmod -a# 0 ~/.local/share/equipo-runner/state"}, |
| + {"a writesecurity grant", home + "/.config/equipo-runner", ".writesecurity", CodeACL, "chmod -a# 0 ~/.config/equipo-runner"}, |
| + {"a chown grant to a group", home + "/.config/equipo-runner", ".chown", CodeACL, "chmod -a# 0 ~/.config/equipo-runner"}, |
| + {"an inherited grant", home + "/.local/share/equipo/accounts", ".inherited", CodeACL, "chmod -a# 1 ~/.local/share/equipo/accounts"}, |
| + {"an ACL grant on an ancestor", home + "/.local/share", ".vicky", CodeACL, "chmod -a# 0 ~/.local/share"}, |
| + {"a symlinked ancestor", home + "/.local", ".link", CodeLink, "replace the link ~/.local with a folder"}, |
| + {"a symlinked root", home + "/.config/equipo-runner", ".link", CodeLink, "replace the link ~/.config/equipo-runner with a folder"}, |
| + {"an ancestor owned by another user", home + "/.local/share", ".vickys", CodeOwner, "sudo chown paulequipo ~/.local/share (an administrator)"}, |
| + {"a root owned by another user", home + "/.local/share/equipo/accounts", ".vickys", CodeOwner, "sudo chown paulequipo ~/.local/share/equipo/accounts (an administrator)"}, |
| + } |
| + constructed := facts(t, "ls-led-constructed-2026-11-29-docs-t1.txt") |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + m := studio() |
| + f := constructed[home+"/"+c.fixture] |
| + f.Path = c.at |
| + m[c.at] = f |
| + r := Check(studioIn, reader(m)) |
| + if r.OK() || !slices.Contains(codes(r), c.at+"="+c.code) || !strings.Contains(r.Fix(), c.fix) { |
| + t.Fatalf("%s: %v %q", c.name, codes(r), r.Fix()) |
| + } |
| + }) |
| + } |
| + t.Run("an ancestor readable by others but not writable passes", func(t *testing.T) { |
| + m := studio() |
| + f := m[home+"/.config"] |
| + f.Perm = 0755 |
| + m[home+"/.config"] = f |
| + if r := Check(studioIn, reader(m)); !r.OK() { |
| + t.Fatalf("a 0755 ancestor failed: %v", codes(r)) |
| + } |
| + }) |
| + t.Run("an ancestor writable by its group fails", func(t *testing.T) { |
| + m := studio() |
| + f := m[home+"/.config"] |
| + f.Perm = 0770 |
| + m[home+"/.config"] = f |
| + r := Check(studioIn, reader(m)) |
| + if !slices.Contains(codes(r), home+"/.config="+CodeMode) || !strings.Contains(r.Fix(), "chmod go-w ~/.config") { |
| + t.Fatalf("a group-writable ancestor: %v %q", 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") |
| + m := studio() |
| + m["/Users/Shared/equipo"] = private("/Users/Shared/equipo") |
| + r := Check(in, reader(m)) |
| + if !slices.Contains(codes(r), "/Users/Shared/equipo="+CodeOutside) { |
| + t.Fatalf("a root outside the home: %v", codes(r)) |
| + } |
| + }) |
| + t.Run("a root that escapes through ..", func(t *testing.T) { |
| + in := studioIn |
| + in.Roots = []string{home + "/../vicky/equipo"} |
| + if r := Check(in, reader(studio())); r.Reason() != CodeOutside { |
| + t.Fatalf("a root through ..: %v", codes(r)) |
| + } |
| + }) |
| + t.Run("a missing root", func(t *testing.T) { |
| + m := studio() |
| + delete(m, home+"/.local/share/equipo/accounts") |
| + r := Check(studioIn, reader(m)) |
| + if r.Reason() != CodeMissing || !strings.Contains(r.Fix(), "mkdir -m 700 ~/.local/share/equipo/accounts") { |
| + t.Fatalf("a missing root: %v %q", codes(r), r.Fix()) |
| + } |
| + }) |
| + t.Run("an unreadable fact decides nothing", func(t *testing.T) { |
| + r := Check(studioIn, func(p string) (Fact, error) { |
| + if p == home+"/.config" { |
| + return Fact{}, ErrUnreadable |
| + } |
| + return reader(studio())(p) |
| + }) |
| + if r.OK() || !slices.Contains(codes(r), home+"/.config="+CodeUnknown) { |
| + t.Fatalf("an unreadable ancestor: %v", codes(r)) |
| + } |
| + }) |
| + t.Run("a uid that is not the user's", func(t *testing.T) { |
| + m := studio() |
| + f := m[home] |
| + f.UID = 507 |
| + m[home] = f |
| + if r := Check(studioIn, reader(m)); r.Reason() != CodeOwner { |
| + t.Fatalf("the home's uid is another's: %v", codes(r)) |
| + } |
| + }) |
| +} |
| + |
| +// TestParseLSRefusesWhatItCannotRead: a line it does not understand, or |
| +// a "+" with no entries, or entries out of order, is ErrUnreadable. |
| +func TestParseLSRefusesWhatItCannotRead(t *testing.T) { |
| + for _, out := range []string{ |
| + "drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo\n", |
| + "drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo\n 0: user:vicky maybe read\n", |
| + "drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo\n 1: user:vicky allow read\n", |
| + "total 0\n", |
| + " 0: user:vicky allow read\n", |
| + } { |
| + if _, err := ParseLS(out); !errors.Is(err, ErrUnreadable) { |
| + t.Fatalf("read %q: %v", out, err) |
| + } |
| + } |
| + f, err := ParseLS("drwxr-x---+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paul equipo\n 0: group:everyone deny delete\n") |
| + if err != nil || len(f) != 1 || f[0].Path != "/Users/paul equipo" || f[0].Perm != 0750 || len(f[0].ACL) != 1 || f[0].ACL[0].Allow { |
| + t.Fatalf("a path with a space: %+v %v", f, err) |
| + } |
| +} |
diff --git a/internal/runner/mac/creds/keychain.go b/internal/runner/mac/creds/keychain.go| new file mode 100644 |
| index 00000000..07739a78 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/keychain.go |
| @@ -0,0 +1,485 @@ |
| +package creds |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "strings" |
| + "sync" |
| +) |
| + |
| +// The Keychain watch around a sign-in (spec §8.3; slice F task 10). The |
| +// pinned CLI is kept off the Keychain first: the sign-in runs with |
| +// CLAUDE_CONFIG_DIR set to a directory of its own, so any credential it |
| +// stores is named for that directory (task 1, S4). Then it is checked: |
| +// before the CLI starts, the generic-password items of the runner user's |
| +// Keychains are listed by their attributes only (no secret is read) and |
| +// the list is written durably; after its end is proven they are listed |
| +// again. An item that appeared is deleted only when it is positively the |
| +// attempt's own: in the runner user's login Keychain, named by path, |
| +// with the service the CLI derives for the attempt's config dir and an |
| +// account the CLI derives for this user. Anything else that appeared is |
| +// never touched. Either way the connection is refused, and the Mac holds |
| +// a credential (Held) until a listing shows every such item gone. An |
| +// 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. |
| +type Item struct { |
| + Keychain string `json:"keychain"` |
| + Service string `json:"service"` |
| + Account string `json:"account"` |
| + Unread string `json:"unread,omitempty"` |
| +} |
| + |
| +func (i Item) key() string { |
| + if i.Unread != "" { |
| + return "?" + i.Unread |
| + } |
| + return i.Keychain + "\x00" + i.Service + "\x00" + i.Account |
| +} |
| + |
| +// ServiceFor is the Keychain service the pinned CLI stores its |
| +// credential under when CLAUDE_CONFIG_DIR is dir: "Claude Code" (the |
| +// build's OAUTH_FILE_SUFFIX is empty), "-credentials", then "-" and the |
| +// first eight hex digits of SHA-256 of dir (task 1, S4). |
| +func ServiceFor(dir string) string { |
| + sum := sha256.Sum256([]byte(dir)) |
| + return "Claude Code-credentials-" + hex.EncodeToString(sum[:])[:8] |
| +} |
| + |
| +// Accounts are the accounts the CLI derives for user: its name, or |
| +// claude-code-user when the name has characters it does not keep. |
| +func Accounts(user string) []string { |
| + if user == "claude-code-user" { |
| + return []string{user} |
| + } |
| + return []string{user, "claude-code-user"} |
| +} |
| + |
| +// cliService: a service the pinned CLI names its items with. |
| +func cliService(s string) bool { return s == "Claude Code" || strings.HasPrefix(s, "Claude Code-") } |
| + |
| +var ( |
| + dumpAttr = regexp.MustCompile(`^\s+"(svce|acct)"<blob>=(.*)$`) |
| + 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. |
| +func ParseDump(out string) ([]Item, error) { |
| + var items []Item |
| + var cur *dumpItem |
| + flush := func() { |
| + if cur != nil && cur.class == `"genp"` { |
| + 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}} |
| + continue |
| + } |
| + if cur == nil { |
| + if strings.TrimSpace(line) == "" { |
| + continue |
| + } |
| + 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 |
| + } |
| + } |
| + } |
| + flush() |
| + return items, nil |
| +} |
| + |
| +type dumpItem struct { |
| + keychain, class, service, account string |
| + hasService, hasAccount, bad bool |
| + lines []string |
| +} |
| + |
| +func (d *dumpItem) item() Item { |
| + if d.bad || !d.hasService || !d.hasAccount || !filepath.IsAbs(d.keychain) { |
| + return Item{Unread: strings.Join(d.lines, "\n")} |
| + } |
| + return Item{Keychain: d.keychain, Service: d.service, Account: d.account} |
| +} |
| + |
| +// blobValue is a dump's value: <NULL>, "text" with no escape in it, or |
| +// 0x<hex> (the bytes, whatever the quoted rendering after it says). |
| +func blobValue(v string) (string, bool) { |
| + v = strings.TrimSpace(v) |
| + switch { |
| + case v == "<NULL>": |
| + return "", true |
| + case len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' && !strings.ContainsAny(v[1:len(v)-1], "\\\""): |
| + return v[1 : len(v)-1], true |
| + } |
| + if m := dumpHex.FindStringSubmatch(v); m != nil { |
| + raw, err := hex.DecodeString(m[1]) |
| + if err == nil && !bytes.ContainsAny(raw, "\x00\n\r") { |
| + return string(raw), true |
| + } |
| + } |
| + return "", false |
| +} |
| + |
| +// ErrExisting refuses a connection while a Keychain item with the CLI's |
| +// 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. |
| +type Keychain struct { |
| + Dir, Login, User string |
| + List func(context.Context) ([]Item, error) |
| + Delete func(context.Context, Item) error |
| + |
| + // op runs one watch operation at a time (a sign-in's second look and |
| + // the hourly settling may meet on a record). |
| + op sync.Mutex |
| + mu sync.Mutex |
| + live map[string]bool |
| +} |
| + |
| +// record is one watch on disk: Before until the attempt's end is |
| +// checked; then Left, what a listing still showed. |
| +type record struct { |
| + Marker string `json:"marker"` |
| + ConfigDir string `json:"config_dir"` |
| + Before []Item `json:"before"` |
| + Checked bool `json:"checked"` |
| + Left []Item `json:"left,omitempty"` |
| +} |
| + |
| +// existingRecord names the record of CLI items found already there. |
| +const existingRecord = "existing" |
| + |
| +// Outcome is what a sign-in's second look found: Clean, nothing new; |
| +// otherwise what was deleted (the attempt's own) and what is left. |
| +type Outcome struct { |
| + Clean bool |
| + Deleted, Left []Item |
| +} |
| + |
| +var recordName = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`) |
| + |
| +// Before lists the Keychains and writes the list durably as marker's |
| +// watch, with dir the CLAUDE_CONFIG_DIR the CLI will run with, before |
| +// anything starts. An item with the CLI's service name already there |
| +// refuses the attempt (ErrExisting) and holds. |
| +func (k *Keychain) Before(ctx context.Context, marker, dir string) error { |
| + k.op.Lock() |
| + defer k.op.Unlock() |
| + if !recordName.MatchString(marker) || marker == existingRecord || !filepath.IsAbs(dir) { |
| + return ErrUnreadable |
| + } |
| + list, err := k.List(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + if err := k.refuseExisting(list); err != nil { |
| + return err |
| + } |
| + if err := k.save(record{Marker: marker, ConfigDir: dir, Before: list}); err != nil { |
| + return err |
| + } |
| + k.mu.Lock() |
| + if k.live == nil { |
| + k.live = map[string]bool{} |
| + } |
| + k.live[marker] = true |
| + k.mu.Unlock() |
| + return nil |
| +} |
| + |
| +// refuseExisting records the CLI's items in list, if any, as found |
| +// there: ErrExisting. |
| +func (k *Keychain) refuseExisting(list []Item) error { |
| + var found []Item |
| + for _, i := range list { |
| + if i.Unread == "" && cliService(i.Service) { |
| + found = append(found, i) |
| + } |
| + } |
| + if len(found) == 0 { |
| + return nil |
| + } |
| + if err := k.save(record{Marker: existingRecord, Checked: true, Left: found}); err != nil { |
| + return err |
| + } |
| + return ErrExisting |
| +} |
| + |
| +// After lists again once marker's CLI is proven gone: what appeared is |
| +// deleted when it is the attempt's own, and a second listing decides |
| +// what is left. Outcome.Clean only when nothing appeared. |
| +func (k *Keychain) After(ctx context.Context, marker string) (Outcome, error) { |
| + k.op.Lock() |
| + defer k.op.Unlock() |
| + defer func() { |
| + k.mu.Lock() |
| + delete(k.live, marker) |
| + k.mu.Unlock() |
| + }() |
| + rec, err := k.load(marker) |
| + if err != nil { |
| + return Outcome{}, err |
| + } |
| + list, err := k.List(ctx) |
| + if err != nil { |
| + return Outcome{}, err |
| + } |
| + rec.Left, rec.Checked = appeared(rec.Before, list), true |
| + if len(rec.Left) == 0 { |
| + return Outcome{Clean: true}, k.remove(marker) |
| + } |
| + out := Outcome{Left: rec.Left} |
| + out.Deleted, err = k.recheck(ctx, []*record{&rec}) |
| + out.Left = rec.Left |
| + return out, err |
| +} |
| + |
| +// appeared is what list has that before did not. |
| +func appeared(before, list []Item) []Item { |
| + had := map[string]bool{} |
| + for _, i := range before { |
| + had[i.key()] = true |
| + } |
| + var out []Item |
| + for _, i := range list { |
| + if !had[i.key()] { |
| + out = append(out, i) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// 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) |
| +} |
| + |
| +// recheck deletes each record's own items left, lists again, keeps of |
| +// each record what that listing still shows, and writes it (a record |
| +// with nothing left goes). It returns what it deleted. |
| +func (k *Keychain) recheck(ctx context.Context, recs []*record) ([]Item, error) { |
| + var deleted []Item |
| + for _, rec := range recs { |
| + for _, i := range rec.Left { |
| + if k.own(*rec, i) && k.Delete(ctx, i) == nil { |
| + deleted = append(deleted, i) |
| + } |
| + } |
| + } |
| + list, err := k.List(ctx) |
| + if err != nil { |
| + return deleted, err |
| + } |
| + shown := map[string]bool{} |
| + for _, i := range list { |
| + shown[i.key()] = true |
| + } |
| + var errs []error |
| + for _, rec := range recs { |
| + rec.Left = slices.DeleteFunc(rec.Left, func(i Item) bool { return !shown[i.key()] }) |
| + if len(rec.Left) == 0 { |
| + errs = append(errs, k.remove(rec.Marker)) |
| + } else { |
| + errs = append(errs, k.save(*rec)) |
| + } |
| + } |
| + return deleted, errors.Join(errs...) |
| +} |
| + |
| +// Existing refuses a new connection (ErrExisting, recorded and held) |
| +// while an item with the CLI's service name is in a Keychain. |
| +func (k *Keychain) Existing(ctx context.Context) error { |
| + k.op.Lock() |
| + defer k.op.Unlock() |
| + list, err := k.List(ctx) |
| + if err != nil { |
| + return err |
| + } |
| + return k.refuseExisting(list) |
| +} |
| + |
| +// Settle looks again at every record: what is left is deleted again |
| +// when it is an attempt's own, and a record goes once a listing shows |
| +// none of it. A watch whose attempt never got its second look (the |
| +// runner stopped) is checked only at a restart and once gone(marker) |
| +// proves its CLI ended; it is never touched while its attempt runs here. |
| +func (k *Keychain) Settle(ctx context.Context, restart bool, gone func(string) bool) error { |
| + k.op.Lock() |
| + defer k.op.Unlock() |
| + names, err := k.names() |
| + if err != nil || len(names) == 0 { |
| + return err |
| + } |
| + var recs []*record |
| + var list []Item |
| + for _, name := range names { |
| + rec, err := k.load(name) |
| + if err != nil { |
| + return err |
| + } |
| + if !rec.Checked { |
| + k.mu.Lock() |
| + live := k.live[name] |
| + k.mu.Unlock() |
| + if !restart || live || gone == nil || !gone(name) { |
| + continue |
| + } |
| + if list == nil { |
| + if list, err = k.List(ctx); err != nil { |
| + return err |
| + } |
| + } |
| + rec.Left, rec.Checked = appeared(rec.Before, list), true |
| + } |
| + recs = append(recs, &rec) |
| + } |
| + if len(recs) == 0 { |
| + return nil |
| + } |
| + _, err = k.recheck(ctx, recs) |
| + return err |
| +} |
| + |
| +// Held: a watch or a residue is on record, so the Mac may hold a |
| +// credential in a Keychain. A records directory that cannot be read |
| +// holds. |
| +func (k *Keychain) Held() bool { |
| + names, err := k.names() |
| + return err != nil || len(names) > 0 |
| +} |
| + |
| +// Residue is the service of every item on record for the person to |
| +// remove ("" for one whose attributes could not be read), sorted. |
| +func (k *Keychain) Residue() []string { |
| + names, _ := k.names() |
| + var out []string |
| + for _, name := range names { |
| + rec, err := k.load(name) |
| + if err != nil { |
| + continue |
| + } |
| + for _, i := range rec.Left { |
| + if !slices.Contains(out, i.Service) { |
| + out = append(out, i.Service) |
| + } |
| + } |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| + |
| +// names are the records on disk. |
| +func (k *Keychain) names() ([]string, error) { |
| + entries, err := os.ReadDir(k.Dir) |
| + if errors.Is(err, fs.ErrNotExist) { |
| + return nil, nil |
| + } |
| + if err != nil { |
| + return nil, err |
| + } |
| + var out []string |
| + for _, e := range entries { |
| + if name, ok := strings.CutSuffix(e.Name(), ".json"); ok && recordName.MatchString(name) { |
| + out = append(out, name) |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +func (k *Keychain) load(name string) (record, error) { |
| + var rec record |
| + raw, err := os.ReadFile(filepath.Join(k.Dir, name+".json")) |
| + if err == nil { |
| + err = json.Unmarshal(raw, &rec) |
| + } |
| + if err == nil && rec.Marker != name { |
| + err = ErrUnreadable |
| + } |
| + return rec, err |
| +} |
| + |
| +// save writes rec durably: a new file synced, renamed over the old one, |
| +// the directory synced. |
| +func (k *Keychain) save(rec record) error { |
| + if err := os.MkdirAll(k.Dir, 0o700); err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(rec) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := os.CreateTemp(k.Dir, ".record-") |
| + if err != nil { |
| + return err |
| + } |
| + _, err = f.Write(raw) |
| + if e := f.Sync(); err == nil { |
| + err = e |
| + } |
| + if e := f.Close(); err == nil { |
| + err = e |
| + } |
| + if err == nil { |
| + err = os.Rename(f.Name(), filepath.Join(k.Dir, rec.Marker+".json")) |
| + } |
| + if err != nil { |
| + os.Remove(f.Name()) |
| + return err |
| + } |
| + return syncDir(k.Dir) |
| +} |
| + |
| +func (k *Keychain) remove(name string) error { |
| + if err := os.Remove(filepath.Join(k.Dir, name+".json")); err != nil && !errors.Is(err, fs.ErrNotExist) { |
| + return err |
| + } |
| + return syncDir(k.Dir) |
| +} |
| + |
| +func syncDir(dir string) error { |
| + d, err := os.Open(dir) |
| + if err != nil { |
| + return err |
| + } |
| + defer d.Close() |
| + return d.Sync() |
| +} |
diff --git a/internal/runner/mac/creds/keychain_test.go b/internal/runner/mac/creds/keychain_test.go| new file mode 100644 |
| index 00000000..22d03be8 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/keychain_test.go |
| @@ -0,0 +1,305 @@ |
| +package creds |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "sync" |
| + "testing" |
| +) |
| + |
| +// dump-keychain-constructed-2026-11-29-docs-t1.txt is constructed on |
| +// docs-t1 in the documented `security dump-keychain` format (no -d). No |
| +// Mac's Keychain was read for it. |
| + |
| +const login = "/Users/paulequipo/Library/Keychains/login.keychain-db" |
| + |
| +// fakeKeychain is the runner user's Keychains: List as dump-keychain |
| +// would list them, Delete as delete-generic-password would delete one. |
| +type fakeKeychain struct { |
| + mu sync.Mutex |
| + items []Item |
| + // lists counts listings; deleted records each deletion asked for. |
| + lists int |
| + deleted []Item |
| + // fail makes every deletion fail; stale keeps a deleted item in the |
| + // next listing (it goes from the one after). |
| + fail, stale bool |
| + ghost []Item |
| +} |
| + |
| +func (f *fakeKeychain) add(i ...Item) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.items = append(f.items, i...) |
| +} |
| + |
| +func (f *fakeKeychain) list(context.Context) ([]Item, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.lists++ |
| + out := append(slices.Clone(f.items), f.ghost...) |
| + f.ghost = nil |
| + return out, nil |
| +} |
| + |
| +func (f *fakeKeychain) delete(_ context.Context, i Item) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.deleted = append(f.deleted, i) |
| + if f.fail { |
| + return errors.New("security: The specified item could not be found in the keychain.") |
| + } |
| + n := slices.Index(f.items, i) |
| + if n < 0 { |
| + return errors.New("security: The specified item could not be found in the keychain.") |
| + } |
| + f.items = slices.Delete(f.items, n, n+1) |
| + if f.stale { |
| + f.ghost = append(f.ghost, i) |
| + } |
| + return nil |
| +} |
| + |
| +func (f *fakeKeychain) has(i Item) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return slices.Contains(f.items, i) |
| +} |
| + |
| +func newWatch(t *testing.T, f *fakeKeychain) *Keychain { |
| + t.Helper() |
| + return &Keychain{Dir: filepath.Join(t.TempDir(), "keychain"), Login: login, User: "paulequipo", List: f.list, Delete: f.delete} |
| +} |
| + |
| +const configDir = "/Users/paulequipo/.local/share/equipo-runner/scratch/homes/signin-1" |
| + |
| +func own() Item { |
| + return Item{Keychain: login, Service: ServiceFor(configDir), Account: "paulequipo"} |
| +} |
| + |
| +func TestParseDump(t *testing.T) { |
| + raw, err := os.ReadFile(filepath.Join("testdata", "dump-keychain-constructed-2026-11-29-docs-t1.txt")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + items, err := ParseDump(string(raw)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := []Item{ |
| + {Keychain: login, Service: "Wi-Fi", Account: "paulequipo"}, |
| + {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"}, |
| + } |
| + if !slices.Equal(items, want) { |
| + t.Fatalf("generic passwords:\n%+v\nwant\n%+v", items, want) |
| + } |
| + // 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 == "" { |
| + t.Fatalf("an unreadable account: %+v %v", odd, err) |
| + } |
| + if _, err := ParseDump("class: \"genp\"\n"); err == nil { |
| + t.Fatal("an item with no keychain line was read") |
| + } |
| +} |
| + |
| +func TestServiceFor(t *testing.T) { |
| + // sha256("/Users/paulequipo/.local/share/equipo-runner/scratch/homes/signin-1"), first 8 hex. |
| + if got := ServiceFor(configDir); len(got) != len("Claude Code-credentials-")+8 || got[:24] != "Claude Code-credentials-" { |
| + t.Fatalf("service %q", got) |
| + } |
| + if ServiceFor(configDir) == ServiceFor(configDir+"x") { |
| + t.Fatal("two config dirs share a service") |
| + } |
| +} |
| + |
| +// TestKeychainWatch: what a sign-in adds is deleted only when it is |
| +// positively its own, everything else is left, and the hold stays until |
| +// a listing shows every item it found gone. |
| +func TestKeychainWatch(t *testing.T) { |
| + ctx := context.Background() |
| + wifi := Item{Keychain: login, Service: "Wi-Fi", Account: "paulequipo"} |
| + t.Run("nothing new is clean and releases", func(t *testing.T) { |
| + f := &fakeKeychain{items: []Item{wifi}} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !k.Held() { |
| + t.Fatal("not held while the sign-in runs") |
| + } |
| + out, err := k.After(ctx, "signin-1") |
| + if err != nil || !out.Clean || k.Held() || len(f.deleted) != 0 { |
| + t.Fatalf("clean: %+v %v held=%v deleted=%v", out, err, k.Held(), f.deleted) |
| + } |
| + }) |
| + t.Run("the before list is durable before anything starts", func(t *testing.T) { |
| + f := &fakeKeychain{items: []Item{wifi}} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); err != nil { |
| + t.Fatal(err) |
| + } |
| + again := &Keychain{Dir: k.Dir, Login: login, User: "paulequipo", List: f.list, Delete: f.delete} |
| + if !again.Held() { |
| + t.Fatal("a restart does not see the watch") |
| + } |
| + }) |
| + t.Run("its own item is deleted by its exact attributes", func(t *testing.T) { |
| + f := &fakeKeychain{items: []Item{wifi}, stale: true} |
| + 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(f.deleted, []Item{own()}) { |
| + t.Fatalf("own item: %+v %v deleted=%+v", out, err, f.deleted) |
| + } |
| + // The second listing still showed it: held, until one does not. |
| + if !k.Held() || !slices.Equal(k.Residue(), []string{own().Service}) { |
| + t.Fatalf("released before a listing showed it gone: %v", k.Residue()) |
| + } |
| + if err := k.Settle(ctx, false, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if k.Held() || f.has(wifi) == false { |
| + t.Fatalf("held=%v after a listing showed it gone; wifi kept=%v", k.Held(), f.has(wifi)) |
| + } |
| + }) |
| + t.Run("claude-code-user is the CLI's account too", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + i := own() |
| + i.Account = "claude-code-user" |
| + f.add(i) |
| + if out, _ := k.After(ctx, "signin-1"); out.Clean || f.has(i) || k.Held() { |
| + t.Fatalf("claude-code-user item: %+v kept=%v held=%v", out, f.has(i), k.Held()) |
| + } |
| + }) |
| + t.Run("a failed delete keeps the hold", func(t *testing.T) { |
| + f := &fakeKeychain{fail: true} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(own()) |
| + out, err := k.After(ctx, "signin-1") |
| + if out.Clean || !k.Held() || !f.has(own()) || !slices.Contains(out.Left, own()) { |
| + t.Fatalf("failed delete: %+v %v held=%v", out, err, k.Held()) |
| + } |
| + // Settling tries again; once it works and a listing shows it gone, |
| + // the hold goes. |
| + f.fail = false |
| + if err := k.Settle(ctx, false, nil); err != nil || k.Held() || f.has(own()) { |
| + t.Fatalf("retry: %v held=%v", err, k.Held()) |
| + } |
| + }) |
| + t.Run("an unrelated item at the same time is left, and holds", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + other := Item{Keychain: login, Service: "Other App", Account: "paulequipo"} |
| + f.add(own(), other) |
| + out, _ := k.After(ctx, "signin-1") |
| + if out.Clean || f.has(own()) || !f.has(other) || slices.Contains(f.deleted, other) { |
| + t.Fatalf("unrelated: %+v deleted=%+v", out, f.deleted) |
| + } |
| + if !k.Held() || !slices.Equal(k.Residue(), []string{"Other App"}) { |
| + t.Fatalf("the unrelated item does not hold: %v", k.Residue()) |
| + } |
| + _ = k.Settle(ctx, false, nil) |
| + if !k.Held() || slices.Contains(f.deleted, other) { |
| + t.Fatal("settling touched it or let it go") |
| + } |
| + f.mu.Lock() |
| + f.items = nil |
| + f.mu.Unlock() |
| + if _ = k.Settle(ctx, false, nil); k.Held() { |
| + t.Fatal("held after the person removed it") |
| + } |
| + }) |
| + t.Run("matching attributes in another keychain are left", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + 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() { |
| + t.Fatalf("another keychain: %+v deleted=%+v held=%v", out, f.deleted, k.Held()) |
| + } |
| + }) |
| + t.Run("another config dir's service or another account is left", func(t *testing.T) { |
| + for _, i := range []Item{ |
| + {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"}, |
| + } { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(i) |
| + if out, _ := k.After(ctx, "signin-1"); out.Clean || len(f.deleted) != 0 || !k.Held() { |
| + t.Fatalf("%+v: %+v deleted=%+v", i, out, f.deleted) |
| + } |
| + } |
| + }) |
| + t.Run("an item there before is never touched", func(t *testing.T) { |
| + f := &fakeKeychain{items: []Item{wifi}} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(own()) |
| + _, _ = k.After(ctx, "signin-1") |
| + if !f.has(wifi) || slices.Contains(f.deleted, wifi) { |
| + t.Fatal("an item from before was touched") |
| + } |
| + }) |
| + t.Run("a Claude Code item there before refuses and holds", func(t *testing.T) { |
| + left := Item{Keychain: login, Service: "Claude Code-credentials", Account: "paulequipo"} |
| + f := &fakeKeychain{items: []Item{left}} |
| + k := newWatch(t, f) |
| + if err := k.Before(ctx, "signin-1", configDir); !errors.Is(err, ErrExisting) { |
| + t.Fatalf("before: %v", err) |
| + } |
| + if !k.Held() || !slices.Equal(k.Residue(), []string{"Claude Code-credentials"}) || len(f.deleted) != 0 { |
| + t.Fatalf("existing: held=%v %v deleted=%v", k.Held(), k.Residue(), f.deleted) |
| + } |
| + if err := k.Existing(ctx); !errors.Is(err, ErrExisting) { |
| + t.Fatalf("a pasted token's store: %v", err) |
| + } |
| + _ = k.Settle(ctx, true, func(string) bool { return true }) |
| + if len(f.deleted) != 0 || !f.has(left) { |
| + t.Fatal("settling deleted an item from before") |
| + } |
| + }) |
| + t.Run("a restart settles a watch its runner never finished", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(own()) |
| + restarted := &Keychain{Dir: k.Dir, Login: login, User: "paulequipo", List: f.list, Delete: f.delete} |
| + // Not before its CLI is proven gone. |
| + if _ = restarted.Settle(ctx, true, func(string) bool { return false }); !restarted.Held() || !f.has(own()) { |
| + t.Fatal("settled before its CLI was proven gone") |
| + } |
| + if err := restarted.Settle(ctx, true, func(m string) bool { return m == "signin-1" }); err != nil || restarted.Held() || f.has(own()) { |
| + t.Fatalf("restart: %v held=%v", err, restarted.Held()) |
| + } |
| + }) |
| + t.Run("a running watch is never settled", func(t *testing.T) { |
| + f := &fakeKeychain{} |
| + k := newWatch(t, f) |
| + _ = k.Before(ctx, "signin-1", configDir) |
| + f.add(own()) |
| + _ = k.Settle(ctx, true, func(string) bool { return true }) |
| + _ = k.Settle(ctx, false, func(string) bool { return true }) |
| + if !f.has(own()) || !k.Held() { |
| + t.Fatal("a watch still running here was settled") |
| + } |
| + }) |
| +} |
diff --git a/internal/runner/mac/creds/pty_darwin.go b/internal/runner/mac/creds/pty_darwin.go| new file mode 100644 |
| index 00000000..e2f9d908 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/pty_darwin.go |
| @@ -0,0 +1,46 @@ |
| +package creds |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "os" |
| + "unsafe" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// OpenTerminal opens a pseudo-terminal pair for a sign-in's CLI, wide |
| +// enough that it never wraps a line: /dev/ptmx, then grantpt, unlockpt |
| +// and ptsname as ioctls (no cgo). |
| +func OpenTerminal() (master, tty *os.File, err error) { |
| + master, err = os.OpenFile("/dev/ptmx", os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + fd := master.Fd() |
| + for _, op := range []uintptr{unix.TIOCPTYGRANT, unix.TIOCPTYUNLK} { |
| + if _, _, e := unix.Syscall(unix.SYS_IOCTL, fd, op, 0); e != 0 { |
| + master.Close() |
| + return nil, nil, e |
| + } |
| + } |
| + // The pointer is converted in the call itself (unsafe.Pointer rule 4). |
| + var name [128]byte |
| + if _, _, e := unix.Syscall(unix.SYS_IOCTL, fd, unix.TIOCPTYGNAME, uintptr(unsafe.Pointer(&name[0]))); e != 0 { |
| + master.Close() |
| + return nil, nil, e |
| + } |
| + n := bytes.IndexByte(name[:], 0) |
| + if n <= 0 { |
| + master.Close() |
| + return nil, nil, errors.New("creds: no terminal name") |
| + } |
| + tty, err = os.OpenFile(string(name[:n]), os.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + master.Close() |
| + return nil, nil, err |
| + } |
| + ws := unix.Winsize{Row: 50, Col: 1000} |
| + _ = unix.IoctlSetWinsize(int(tty.Fd()), unix.TIOCSWINSZ, &ws) |
| + return master, tty, nil |
| +} |
diff --git a/internal/runner/mac/creds/pty_linux.go b/internal/runner/mac/creds/pty_linux.go| new file mode 100644 |
| index 00000000..9c6be16a |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/pty_linux.go |
| @@ -0,0 +1,11 @@ |
| +package creds |
| + |
| +import ( |
| + "os" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| +) |
| + |
| +// OpenTerminal is the Linux pseudo-terminal pair (the test build's fake |
| +// Mac worker and the tests): containment's. |
| +func OpenTerminal() (master, tty *os.File, err error) { return containment.OpenTerminal() } |
diff --git a/internal/runner/mac/creds/testdata/dump-keychain-constructed-2026-11-29-docs-t1.txt b/internal/runner/mac/creds/testdata/dump-keychain-constructed-2026-11-29-docs-t1.txt| new file mode 100644 |
| index 00000000..5918b272 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/testdata/dump-keychain-constructed-2026-11-29-docs-t1.txt |
| @@ -0,0 +1,45 @@ |
| +keychain: "/Users/paulequipo/Library/Keychains/login.keychain-db" |
| +version: 512 |
| +class: "genp" |
| +attributes: |
| + 0x00000007 <blob>="Wi-Fi" |
| + 0x00000008 <blob>=<NULL> |
| + "acct"<blob>="paulequipo" |
| + "cdat"<timedate>=0x32303236313131303130303030305A00 "20261110100000Z\000" |
| + "crtr"<uint32>=<NULL> |
| + "cusi"<sint32>=<NULL> |
| + "desc"<blob>=<NULL> |
| + "gena"<blob>=<NULL> |
| + "icmt"<blob>=<NULL> |
| + "invi"<sint32>=<NULL> |
| + "mdat"<timedate>=0x32303236313131303130303030305A00 "20261110100000Z\000" |
| + "nega"<sint32>=<NULL> |
| + "prot"<blob>=<NULL> |
| + "scrp"<sint32>=<NULL> |
| + "svce"<blob>="Wi-Fi" |
| + "type"<uint32>=<NULL> |
| +keychain: "/Users/paulequipo/Library/Keychains/login.keychain-db" |
| +version: 512 |
| +class: "inet" |
| +attributes: |
| + "acct"<blob>="paul" |
| + "srvr"<blob>="example.com" |
| + "svce"<blob>=<NULL> |
| +keychain: "/Users/paulequipo/Library/Keychains/login.keychain-db" |
| +version: 512 |
| +class: "genp" |
| +attributes: |
| + 0x00000007 <blob>="Claude Code-credentials-1a2b3c4d" |
| + "acct"<blob>=0x7061756C657175697066 "paulequipf" |
| + "svce"<blob>=0x436C6175646520436F64652D63726564656E7469616C732D3161326233633464 "Claude Code-credentials-1a2b3c4d" |
| +keychain: "/Library/Keychains/System.keychain" |
| +version: 512 |
| +class: "genp" |
| +attributes: |
| + "acct"<blob>="com.apple.network.eap.system.item.wlan.ssid.home" |
| + "svce"<blob>="AirPort" |
| +keychain: "/Users/paulequipo/Library/Keychains/login.keychain-db" |
| +version: 512 |
| +class: 0x80001000 |
| +attributes: |
| + "alis"<blob>="Apple Development" |
diff --git a/internal/runner/mac/creds/testdata/ls-led-constructed-2026-11-29-docs-t1.txt b/internal/runner/mac/creds/testdata/ls-led-constructed-2026-11-29-docs-t1.txt| new file mode 100644 |
| index 00000000..37607060 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/testdata/ls-led-constructed-2026-11-29-docs-t1.txt |
| @@ -0,0 +1,22 @@ |
| +drwx------ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo |
| +drwxr-x--- 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.g750 |
| +drwxr----- 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.g740 |
| +drwx---r-- 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.o704 |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.everyone |
| + 0: group:everyone allow list,search |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.vicky |
| + 0: user:vicky allow read |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.write |
| + 0: user:vicky allow write |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.writesecurity |
| + 0: user:vicky allow writesecurity |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.chown |
| + 0: group:staff allow chown |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.inherited |
| + 0: group:everyone deny delete |
| + 1: user:vicky inherited allow list,search,file_inherit,directory_inherit |
| +drwx------+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo/.self |
| + 0: user:paulequipo allow list,search,add_file,delete_child |
| + 1: group:everyone deny delete |
| +lrwxr-xr-x 1 paulequipo staff 24 28 Nov 15:22 /Users/paulequipo/.link -> /Volumes/Shared/equipo |
| +drwx------ 19 vicky staff 608 28 Nov 15:22 /Users/paulequipo/.vickys |
diff --git a/internal/runner/mac/creds/testdata/ls-led-users-2026-11-28-tito-studio.txt b/internal/runner/mac/creds/testdata/ls-led-users-2026-11-28-tito-studio.txt| new file mode 100644 |
| index 00000000..f6eef836 |
| --- /dev/null |
| +++ b/internal/runner/mac/creds/testdata/ls-led-users-2026-11-28-tito-studio.txt |
| @@ -0,0 +1,21 @@ |
| +drwxr-x---+ 51 billhorsman staff 1632 28 Nov 17:35 /Users/billhorsman |
| + 0: user:paulequipo deny list,search,readattr,readextattr,readsecurity |
| + 1: group:everyone deny delete |
| +drwxr-x---+ 16 ci staff 512 11 Nov 17:48 /Users/ci |
| + 0: user:paulequipo deny list,search,readattr,readextattr,readsecurity |
| + 1: group:everyone deny delete |
| +drwxr-x---+ 37 drbparsons staff 1184 28 Nov 17:54 /Users/drbparsons |
| + 0: user:paulequipo deny list,search,readattr,readextattr,readsecurity |
| + 1: group:everyone deny delete |
| +drwxr-x---+ 28 murraysum staff 896 6 Oct 13:27 /Users/murraysum |
| + 0: user:paulequipo deny list,search,readattr,readextattr,readsecurity |
| + 1: group:everyone deny delete |
| +drwxr-x---+ 45 paulca staff 1440 28 Nov 15:05 /Users/paulca |
| + 0: user:paulequipo deny list,search,readattr,readextattr,readsecurity |
| + 1: group:everyone deny delete |
| +drwxr-x---+ 19 paulequipo staff 608 28 Nov 15:22 /Users/paulequipo |
| + 0: group:everyone deny delete |
| +drwxrwxrwt 8 root wheel 256 9 Nov 10:37 /Users/Shared |
| +drwxr-x---+ 41 vicky staff 1312 28 Nov 17:29 /Users/vicky |
| + 0: user:paulequipo deny list,search,readattr,readextattr,readsecurity |
| + 1: group:everyone deny delete |
diff --git a/internal/runner/mac/launch.go b/internal/runner/mac/launch.go| index bbac89c8..ec4f6de6 100644 |
| --- a/internal/runner/mac/launch.go |
| +++ b/internal/runner/mac/launch.go |
| @@ -58,13 +58,15 @@ type Executor struct { |
| // Command is what to start: Argv with Env as its whole environment, in |
| // Dir, Files as descriptors 3 and on. With Pipes the run offers its |
| // stdin, stdout and stderr; otherwise Stdout and Stderr receive the |
| -// output and stdin is empty. |
| +// output and stdin is empty. TTY (a sign-in's) is the leader's stdin, |
| +// stdout, stderr and controlling terminal instead. |
| type Command struct { |
| Argv, Env []string |
| Dir string |
| Files []*os.File |
| Pipes bool |
| Stdout, Stderr io.Writer |
| + TTY *os.File |
| } |
| func (x *Executor) procs() Procs { |
| @@ -178,7 +180,10 @@ func (x *Executor) Start(ctx context.Context, c Command, marker string, record f |
| // stop kills what is left. |
| cmd.WaitDelay = time.Second |
| } |
| - cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: c.TTY != nil} |
| + if c.TTY != nil { |
| + cmd.Stdin, cmd.Stdout, cmd.Stderr = c.TTY, c.TTY, c.TTY |
| + } |
| if err := cmd.Start(); err != nil { |
| return fail(err) |
| } |
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go| index 97109d04..10f99246 100644 |
| --- a/internal/runner/thin/claude.go |
| +++ b/internal/runner/thin/claude.go |
| @@ -81,6 +81,9 @@ type ClaudeOptions struct { |
| // (profile.go); nil reads none. A release runner's is |
| // AnthropicProfile (OptionsFromEnv). |
| Profile *ProfileReader |
| + // Mac is a Mac worker's credential operations (maccreds.go): its |
| + // token check runs the darwin launch, nil on Linux. |
| + Mac *macCreds |
| } |
| // ToolCaller runs one tool call for a person's turn attempt. |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index 8161b30b..31fbe8b0 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -61,6 +61,10 @@ type Connector struct { |
| // Manager contains a sign-in's `claude setup-token` (nil: Claude's |
| // sign-in by a link is unavailable). |
| Manager *containment.Manager |
| + // Mac is a Mac worker's credential operations (maccreds.go): its |
| + // guards before a token is stored or used, its darwin sign-in and |
| + // auth status, nil on Linux. |
| + Mac *macCreds |
| // terminal starts setup-token for an attempt (contained, signin.go; |
| // tests replace it); gone proves an attempt's namespace gone at |
| @@ -188,6 +192,11 @@ func (c *Connector) Start(ctx context.Context) error { |
| c.removeHome(l.home) |
| c.finish(l.id, wire.ConnectionReport{Connection: l.id, Person: l.person, Provider: l.provider, State: wire.ConnError, Reason: "runner_offline"}) |
| } |
| + if c.Mac != nil { |
| + // A Mac's Keychain watches its sign-ins left: settled once their |
| + // CLIs are proven gone (maccreds.go). |
| + c.Mac.settle(ctx, true) |
| + } |
| // An attempt saved and then cancelled, stopped before it was signed |
| // out: owed now. Then every cleanup still owed. |
| if _, err = c.State.db.ExecContext(ctx, "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) SELECT id, person, local_id, 0, ? FROM connect_attempts WHERE state='done' AND cancelled=1 AND local_id<>'' ON CONFLICT(connection) DO NOTHING", now()); err != nil { |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index bdd48665..8868ff1b 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -438,6 +438,9 @@ type macHost struct { |
| capsLogged atomic.Bool |
| // turns lets one gate at a time run (mac.Turns). |
| turns *mac.Turns |
| + // creds is the Claude credential's guards and operations |
| + // (maccreds.go). |
| + creds *macCreds |
| // fetchClaude fetches the pinned Claude Code (mac.OfficialClaude). |
| fetchClaude mac.ClaudeFetch |
| // warmMu guards warmed, the Xcode (version and build) whose plugin |
| @@ -738,6 +741,7 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| h.probes.fingerprint = func() string { return toolFingerprint(h.paths.InstallDir, h.tools) } |
| h.taint = loadTaint(filepath.Join(c.StateDir, "tainted")) |
| h.checks = &macChecks{probes: h.probes, taint: h.taint, srt: h.tools.SRT, sandboxed: gate(h.tools.SRT, wire.SandboxSeatbelt), unproven: gate(h.tools.SRT, wire.SandboxNone), bare: gate("", wire.SandboxNone)} |
| + h.creds = h.newCreds(c) |
| h.caps = func(ctx context.Context) wire.Capabilities { |
| // The first gathering is the one the first hello waits on: each |
| // command at info. Later ones (hourly, each check's gate) at debug. |
| @@ -753,6 +757,7 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| caps.Probes = probes |
| } |
| caps.Tainted = h.taint.Tainted() |
| + h.credentialCaps(ctx, &caps) |
| if h.turns.Incomplete() { |
| caps.Unproven = wire.UnprovenRecordIncomplete |
| } |
| @@ -761,6 +766,16 @@ func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| return h, nil |
| } |
| +// credentialCaps says why the Mac can take no Claude connection, if its |
| +// guards say so (maccreds.go), and looks again for a Keychain item it |
| +// found. |
| +func (h *macHost) credentialCaps(ctx context.Context, caps *wire.Capabilities) { |
| + caps.Engineering = h.creds.status() |
| + if h.creds.Held() { |
| + h.creds.settle(ctx, false) |
| + } |
| +} |
| + |
| // simShutdownLimit bounds `simctl shutdown all` before a T cleanup. |
| // It shuts every booted simulator down one after another, each taking |
| // seconds to tens of seconds, so QueryLimit (30 s) would cut a Mac with |
diff --git a/internal/runner/thin/maccreds.go b/internal/runner/thin/maccreds.go| new file mode 100644 |
| index 00000000..7252e57b |
| --- /dev/null |
| +++ b/internal/runner/thin/maccreds.go |
| @@ -0,0 +1,561 @@ |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "log/slog" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "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/runner/provider/claude" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A Mac worker's Claude credential (Mac runners spec §8.3, §8.7; slice F |
| +// task 10). Until slice F a Mac held only its runner identity; now it |
| +// can hold a long-lived token, on a machine other people use. So: |
| +// |
| +// - The guards. A tainted runner (D2: a check once ran outside its |
| +// sandbox, in its own state or by the instance's word) takes no model |
| +// connection, and the home guard (creds.Check) must pass: nobody |
| +// else can reach the home, the state dir, the config dir or the |
| +// accounts root. Both are checked again when a token is stored and |
| +// before every use, never once for good. |
| +// - Every operation that puts the token in a process, or writes it, |
| +// holds the Mac's one turn for its whole life (mac.Turns): the token |
| +// check, the auth status read, the sign-in while its terminal is |
| +// open, the store. |
| +// - The token goes to the pinned CLI by descriptor only (fd 3, |
| +// CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR): never in an environment, |
| +// which a sandboxed command can read through KERN_PROCARGS2 (task 1, |
| +// R4, S4). |
| +// - The sign-in (`claude setup-token` on a pseudo-terminal, as on Linux) |
| +// runs with CLAUDE_CONFIG_DIR of its own, so any Keychain item it |
| +// makes is named for it, and the Keychain is watched around it |
| +// (creds.Keychain): an item it left refuses the connection, and the |
| +// Mac holds a credential until a listing shows it gone. |
| + |
| +var ( |
| + // errTainted refuses a model connection on a tainted runner. |
| + errTainted = errors.New("this runner is tainted, so it takes no model connection") |
| + // errKeychain refuses a sign-in that left a Keychain item, or whose |
| + // Keychain could not be listed again. |
| + errKeychain = errors.New("the sign-in left an item in a Keychain") |
| + // errMacRefused refuses to keep a token (the guards, or a Keychain |
| + // item with Claude Code's name). |
| + errMacRefused = errors.New("the Mac refused to keep the token") |
| +) |
| + |
| +// homeOpen refuses a credential while the home guard fails. It names |
| +// what to change. |
| +type homeOpen struct{ r creds.Result } |
| + |
| +func (e *homeOpen) Error() string { |
| + return "other users could reach the runner's folders; as the runner user: " + strings.ReplaceAll(e.r.Fix(), "\n", "; ") |
| +} |
| + |
| +// tokenStoreWait bounds how long keeping a token waits for the Mac's |
| +// turn. A longer wait fails the delivery, which the instance sends again. |
| +var tokenStoreWait = time.Minute |
| + |
| +// authStatusLimit bounds the CLI's auth status read, as on Linux. |
| +const authStatusLimit = 30 * time.Second |
| + |
| +// macTokenFDEnv names the token's descriptor to the CLI. |
| +const macTokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" |
| + |
| +// macCreds is a Mac worker's credential operations. |
| +type macCreds struct { |
| + turns *mac.Turns |
| + exec *mac.Executor |
| + cli mac.ClaudeCLI |
| + paths mac.Paths |
| + // configDir is the runner's config dir (runner.env, the bindings); |
| + // runner its binary (the CLI's MCP server); scratch its scratch root. |
| + configDir, runner, scratch string |
| + taint *macTaint |
| + keychain *creds.Keychain |
| + // fact reads one path's kind, mode, owner and ACL (ls -led and lstat |
| + // on a Mac). |
| + fact func(string) (creds.Fact, error) |
| + // user and uid are the runner user (id -un, id -u at start). |
| + user string |
| + uid int |
| + log *slog.Logger |
| +} |
| + |
| +// newCreds is h's credential operations for c. |
| +func (h *macHost) newCreds(c runner.Config) *macCreds { |
| + m := &macCreds{turns: h.turns, exec: &mac.Executor{Turns: h.turns}, cli: h.tools.Claude, paths: h.paths, configDir: macConfigDir(c, h.paths.Home), |
| + runner: c.Executable, scratch: c.ScratchRoot, taint: h.taint, uid: -1, log: h.log} |
| + ctx, cancel := context.WithTimeout(context.Background(), mac.QueryLimit) |
| + defer cancel() |
| + if a, err := mac.ReadAccount(ctx, h.run); err == nil { |
| + m.user, m.uid = a.Name, a.UID |
| + } |
| + m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) } |
| + if runtime.GOOS == "darwin" { |
| + m.fact = func(p string) (creds.Fact, error) { |
| + return creds.Read(p, func(p string) (string, error) { |
| + ctx, cancel := context.WithTimeout(context.Background(), mac.QueryLimit) |
| + defer cancel() |
| + return h.run(ctx, "/bin/ls", "-led", "--", p) |
| + }) |
| + } |
| + } |
| + m.keychain = &creds.Keychain{Dir: filepath.Join(c.StateDir, "keychain"), Login: filepath.Join(h.paths.Home, "Library", "Keychains", "login.keychain-db"), User: m.user, List: h.keychainList, Delete: h.keychainDelete} |
| + return m |
| +} |
| + |
| +// macConfigDir is the runner's config dir: the bindings file's, or the |
| +// installer's ~/.config/equipo-runner. |
| +func macConfigDir(c runner.Config, home string) string { |
| + if c.AccountBindingsPath != "" { |
| + return filepath.Dir(c.AccountBindingsPath) |
| + } |
| + 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" { |
| + return nil, nil |
| + } |
| + ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| + defer cancel() |
| + out, err := h.run(ctx, "/usr/bin/security", "dump-keychain") |
| + if err != nil { |
| + return nil, err |
| + } |
| + return creds.ParseDump(out) |
| +} |
| + |
| +// 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 != "" { |
| + 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) |
| + return err |
| +} |
| + |
| +// guard is the home guard now: the home and the three roots, each made |
| +// (0700) if it is missing, then read and decided. |
| +func (m *macCreds) guard() creds.Result { |
| + roots := []string{m.paths.StateDir, m.configDir, m.paths.AccountsRoot} |
| + for _, r := range roots { |
| + if r != "" && strings.HasPrefix(filepath.Clean(r), filepath.Clean(m.paths.Home)+"/") { |
| + _ = os.MkdirAll(r, 0o700) |
| + } |
| + } |
| + return creds.Check(creds.Input{User: m.user, UID: m.uid, Home: m.paths.Home, Roots: roots}, m.fact) |
| +} |
| + |
| +// Gate is the guards, now: errTainted, or *homeOpen naming what to |
| +// change, or nil. Every store and every use of a token passes it first. |
| +func (m *macCreds) Gate() error { |
| + if m.taint.Tainted() { |
| + return errTainted |
| + } |
| + if r := m.guard(); !r.OK() { |
| + if m.log != nil { |
| + m.log.Warn("other users could reach the runner's folders; no model connection is kept or used", "reason", r.Reason(), "change", strings.ReplaceAll(r.Fix(), "\n", "; ")) |
| + } |
| + return &homeOpen{r} |
| + } |
| + return nil |
| +} |
| + |
| +// status is the guards' Engineering status: tainted (it lasts, so it is |
| +// said first), or home_open with the guard's first code; nil when both |
| +// pass. |
| +func (m *macCreds) status() *wire.EngineeringStatus { |
| + if m.taint.Tainted() { |
| + return &wire.EngineeringStatus{State: wire.EngineeringTainted} |
| + } |
| + if r := m.guard(); !r.OK() { |
| + return &wire.EngineeringStatus{State: wire.EngineeringHomeOpen, Reason: r.Reason()} |
| + } |
| + return nil |
| +} |
| + |
| +// Held: a Keychain item a sign-in may have left is on record (the |
| +// Keychain half of the credential hold; task 11 adds the files'). |
| +func (m *macCreds) Held() bool { return m.keychain.Held() } |
| + |
| +// store is a token store's turn (OpTokenStore) and its guards; give |
| +// ends it. errMacRefused (joined with why) refuses the token; any other |
| +// error is a wait that ran out, and the delivery is tried again. |
| +func (m *macCreds) store(ctx context.Context) (give func(), err error) { |
| + wait, cancel := context.WithTimeout(ctx, tokenStoreWait) |
| + defer cancel() |
| + _, give, err = m.turns.Hold(wait, mac.OpTokenStore) |
| + if err != nil { |
| + return nil, err |
| + } |
| + err = m.Gate() |
| + if err == nil { |
| + err = m.keychain.Existing(ctx) |
| + } |
| + if err != nil { |
| + give() |
| + return nil, errors.Join(errMacRefused, err) |
| + } |
| + return give, nil |
| +} |
| + |
| +// 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)) }) |
| + if err != nil && m.log != nil { |
| + m.log.Warn("keychain not settled", "err", err) |
| + } |
| + if left := m.keychain.Residue(); len(left) > 0 && m.log != nil { |
| + m.log.Warn("a Keychain item holds this Mac as having a credential; remove it in Keychain Access", "services", strings.Join(left, ", ")) |
| + } |
| +} |
| + |
| +// 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. |
| +func (m *macCreds) place(prefix string) (dir, marker string, err error) { |
| + root := filepath.Join(m.scratch, "homes") |
| + if err = os.MkdirAll(root, 0o700); err != nil { |
| + return "", "", err |
| + } |
| + if dir, err = os.MkdirTemp(root, prefix); err != nil { |
| + return "", "", err |
| + } |
| + return dir, filepath.Base(dir), nil |
| +} |
| + |
| +// env is a launch's whole environment: its own config dir (both names |
| +// the CLI reads it by, so its Keychain service is named for it), the |
| +// runner user's home, the CLI's PATH and locale, no updater and no |
| +// nonessential traffic, the marker, and with a token only the number |
| +// of the descriptor it is on. |
| +func (m *macCreds) env(dir, marker string, token bool, extra ...string) []string { |
| + env := []string{"HOME=" + m.paths.Home, "USER=" + m.user, "CLAUDE_CONFIG_DIR=" + dir, "CLAUDE_SECURESTORAGE_CONFIG_DIR=" + dir, "TMPDIR=" + dir, |
| + "PATH=" + claude.DarwinPath, "LANG=" + claude.DarwinLang, "DISABLE_AUTOUPDATER=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", claude.DarwinMarkerEnv + "=" + marker} |
| + if token { |
| + env = append(env, macTokenFDEnv+"="+strconv.Itoa(claude.DarwinTokenFD)) |
| + } |
| + return append(env, extra...) |
| +} |
| + |
| +// start starts the pinned CLI with args (ClaudeCLI.Launch: hashed, then |
| +// checked again just before) through the executor, in dir, as c says, |
| +// with token (if any) in a pipe that is descriptor 3. ctx must hold the |
| +// turn. |
| +func (m *macCreds) start(ctx context.Context, dir, marker string, c mac.Command, token []byte, record func(string) error, args ...string) (*mac.Run, error) { |
| + c.Dir = dir |
| + if token != nil { |
| + if len(token) == 0 || len(token) > mac.MaxToken || bytes.ContainsAny(token, "\x00\r\n") { |
| + return nil, provider.ErrPolicy |
| + } |
| + read, write, err := os.Pipe() |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer read.Close() |
| + _, err = write.Write(token) |
| + if cerr := write.Close(); err == nil { |
| + err = cerr |
| + } |
| + if err != nil { |
| + return nil, provider.ErrPolicy |
| + } |
| + c.Files = []*os.File{read} |
| + } |
| + var run *mac.Run |
| + err := m.cli.Launch(ctx, func(ctx context.Context, argv []string) error { |
| + c.Argv = argv |
| + r, err := m.exec.Start(ctx, c, marker, record) |
| + run = r |
| + return err |
| + }, args...) |
| + return run, err |
| +} |
| + |
| +// capped keeps the first 64 KiB written to it. |
| +type capped struct{ b bytes.Buffer } |
| + |
| +func (c *capped) Write(p []byte) (int, error) { |
| + if room := 64<<10 - c.b.Len(); room > 0 { |
| + c.b.Write(p[:min(len(p), room)]) |
| + } |
| + return len(p), nil |
| +} |
| + |
| +// authStatus is a token home's `claude auth status --json` on a Mac |
| +// (Linux's provider.RefreshLogin), the token by descriptor, in the |
| +// check's turn: the email, if the CLI names one. It proves nothing about |
| +// the token. ClaudeOptions.Refresh and Conns.Refresh on a Mac. |
| +func (m *macCreds) authStatus(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| + if b.Provider != wire.ProviderClaude || !b.Token { |
| + return provider.Identity{}, provider.ErrLoginUnavailable |
| + } |
| + ctx, give, err := m.turns.Hold(ctx, mac.OpTokenCheck) |
| + if err != nil { |
| + return provider.Identity{}, err |
| + } |
| + defer give() |
| + if err := m.Gate(); err != nil { |
| + return provider.Identity{}, err |
| + } |
| + raw, err := provider.ReadToken(b.Home) |
| + if err != nil { |
| + return provider.Identity{}, provider.ErrLoginRequired |
| + } |
| + defer clear(raw) |
| + ctx, cancel := context.WithTimeout(ctx, authStatusLimit) |
| + defer cancel() |
| + dir, marker, err := m.place("status-") |
| + if err != nil { |
| + return provider.Identity{}, err |
| + } |
| + defer os.RemoveAll(dir) |
| + 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 { |
| + return provider.Identity{}, err |
| + } |
| + select { |
| + case <-run.Exited(): |
| + case <-run.Aborted(): |
| + case <-ctx.Done(): |
| + } |
| + proven := run.Stop() |
| + run.Finish(context.WithoutCancel(ctx)) |
| + switch { |
| + case !proven: |
| + return provider.Identity{}, mac.ErrUnproven |
| + case ctx.Err() != nil: |
| + return provider.Identity{}, ctx.Err() |
| + } |
| + id, _, err := provider.ClaudeTokenIdentity(out.b.Bytes(), b.ID) |
| + if err != nil || run.ExitErr() != nil { |
| + return provider.Identity{}, provider.ErrLoginRequired |
| + } |
| + return id, nil |
| +} |
| + |
| +// checkToken is the token check on a Mac (tokencheck.go's, the same |
| +// prompt, outcomes and limit): the darwin launch's check-only policy (no |
| +// native tool, no Equipo tool, an empty read-only workspace under the |
| +// scratch root, no network for any shell), the token by descriptor, the |
| +// whole check in one turn (OpTokenCheck). A crash leaves the turn's |
| +// record, and the next turn settles what it left. |
| +func (m *macCreds) checkToken(ctx context.Context, o ClaudeOptions, b runner.AccountBinding) (_ []wire.Usage, _ *connect.Limit, named bool, err error) { |
| + if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken { |
| + return nil, nil, false, provider.ErrPolicy |
| + } |
| + tctx, give, err := m.turns.Hold(ctx, mac.OpTokenCheck) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + defer give() |
| + if err = m.Gate(); err != nil { |
| + return nil, nil, false, err |
| + } |
| + parent := tctx |
| + ctx, cancel := context.WithTimeout(tctx, tokenCheckLimit) |
| + defer cancel() |
| + direct, err := o.Runner.DirectBinding(b) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + lease, err := provider.OpenRuntimeCopy(ctx, direct, m.authStatus, o.LockWait) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + defer lease.Close() |
| + binding := lease.Binding() |
| + scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + defer os.RemoveAll(scratch) |
| + // The empty workspace: under the scratch root, never SessionRoot (the |
| + // §4.2 list denies it). |
| + work, err := os.MkdirTemp(o.Runner.ScratchRoot, "check-") |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + defer os.RemoveAll(work) |
| + root, err := toolRoot(o.Runner) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + tool, err := openToolSocket(context.Background(), root, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true }) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + defer tool.Close() |
| + sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| + session := uuid() |
| + in := mac.EngineeringInput{Paths: m.paths, Action: claude.DarwinCheck, Model: firstNonEmpty(b.Model, firstNonEmpty(o.Runner.ClaudeModel, DefaultModels[wire.ProviderClaude])), |
| + Worktree: work, Scratch: scratch, Runner: m.runner, ToolRoot: root, Socket: tool.Path, |
| + ConfigDir: binding.Home, CredentialHome: b.ProviderHome, RuntimeRoot: direct.RuntimeRoot, Attempt: "check-" + filepath.Base(work), SessionID: session} |
| + policy, err := mac.EngineeringPolicy(m.cli, in) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + if err = lease.CheckCopy(ctx); err != nil { |
| + return nil, nil, false, err |
| + } |
| + launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy} |
| + env, err := provider.LaunchSecretEnv(launch) |
| + if err != nil { |
| + return nil, nil, false, err |
| + } |
| + token := []byte(env[provider.OAuthTokenEnv]) |
| + // The account profile, once the provider answered, as on Linux. |
| + defer func() { |
| + if err == nil && o.Profile != nil { |
| + named = o.readProfile(parent, b, token) |
| + } |
| + clear(token) |
| + }() |
| + 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 { |
| + 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()) }() |
| + stop := context.AfterFunc(ctx, kill) |
| + defer func() { |
| + stop() |
| + kill() |
| + <-exited |
| + }() |
| + rows, seen, err := readCheck(ctx, proc, session, b) |
| + return rows, seen, false, err |
| +} |
| + |
| +// macSetupToken is a Mac's sign-in terminal for attempt (Connector's |
| +// terminal): its run's record goes on the attempt's row. |
| +func (c *Connector) macSetupToken(ctx context.Context, attempt string) (connect.Terminal, error) { |
| + return c.Mac.terminal(ctx, func(id string) error { |
| + _, err := c.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE connect_attempts SET namespace=? WHERE id=?", id, attempt) |
| + return err |
| + }) |
| +} |
| + |
| +// terminal starts `claude setup-token` on a pseudo-terminal in the |
| +// Mac's turn (OpSignIn), held until Stop: the guards, then its own |
| +// config dir, then the Keychain listed and written down (before |
| +// anything starts), then the CLI. |
| +func (m *macCreds) terminal(ctx context.Context, record func(string) error) (connect.Terminal, error) { |
| + u, err := m.turns.Take(ctx, mac.OpSignIn) |
| + if err != nil { |
| + return nil, err |
| + } |
| + kept := false |
| + defer func() { |
| + if !kept { |
| + u.Give() |
| + } |
| + }() |
| + if err = m.Gate(); err != nil { |
| + return nil, err |
| + } |
| + dir, marker, err := m.place("signin-") |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err = m.keychain.Before(ctx, marker, dir); err != nil { |
| + os.RemoveAll(dir) |
| + return nil, err |
| + } |
| + // What did not start (or whose end is proven) gets its second look now. |
| + unstarted := func() { |
| + _, _ = m.keychain.After(context.WithoutCancel(ctx), marker) |
| + os.RemoveAll(dir) |
| + } |
| + pty, tty, err := creds.OpenTerminal() |
| + if err != nil { |
| + unstarted() |
| + return nil, err |
| + } |
| + env := m.env(dir, marker, false, "TERM=xterm-256color", "BROWSER="+provider.SignInBrowser) |
| + run, err := m.start(u.Context(ctx), dir, marker, mac.Command{Env: env, TTY: tty}, nil, record, "setup-token") |
| + tty.Close() |
| + if err != nil { |
| + pty.Close() |
| + if !errors.Is(err, mac.ErrUnproven) { |
| + unstarted() |
| + } |
| + return nil, err |
| + } |
| + kept = true |
| + return &macTerminal{m: m, turn: u, run: run, pty: pty, marker: marker, dir: dir}, nil |
| +} |
| + |
| +// macTerminal is a sign-in's terminal on a Mac. |
| +type macTerminal struct { |
| + m *macCreds |
| + turn *mac.Turn |
| + run *mac.Run |
| + pty *os.File |
| + marker, dir string |
| + once sync.Once |
| + err error |
| +} |
| + |
| +func (t *macTerminal) Read(p []byte) (int, error) { return t.pty.Read(p) } |
| +func (t *macTerminal) Write(p []byte) (int, error) { return t.pty.Write(p) } |
| +func (t *macTerminal) Done() <-chan struct{} { return t.run.Exited() } |
| + |
| +// Stop stops the CLI and proves its end (its group and what it left), |
| +// then looks at the Keychain again and gives the turn back. errUnproven: |
| +// its end is not proven (the watch stays, held, for the restart); |
| +// errKeychain: the sign-in left an item, so the connection is refused. |
| +func (t *macTerminal) Stop() error { |
| + t.once.Do(func() { |
| + defer t.turn.Give() |
| + proven := t.run.Stop() |
| + t.run.Finish(context.Background()) |
| + t.pty.Close() |
| + if !proven { |
| + t.err = errUnproven |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*mac.QueryLimit) |
| + defer cancel() |
| + out, err := t.m.keychain.After(ctx, 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_test.go b/internal/runner/thin/maccreds_test.go| new file mode 100644 |
| index 00000000..726b7977 |
| --- /dev/null |
| +++ b/internal/runner/thin/maccreds_test.go |
| @@ -0,0 +1,763 @@ |
| +//go:build testbuild |
| + |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/fakeclaude" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "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/runner/provider/claude" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// A Mac's Claude credential (maccreds.go) on Linux: the pinned "CLI" is |
| +// a shell script pinned by its own digest, provisioned and hashed before |
| +// every start exactly as the real one is (ClaudeCLI.Launch), which |
| +// records its argv, environment and directory and then runs the fake |
| +// CLI; the executor and the turns are package mac's own; the Keychain is |
| +// a fake listing. Test build only: mac.PinnedForTest exists only there. |
| + |
| +// 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. |
| +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 |
| +exec "$d/bin/claude" "$@" |
| +` |
| + |
| +// keychainFake is the runner user's Keychains as security lists them. |
| +type keychainFake struct { |
| + mu sync.Mutex |
| + items []creds.Item |
| + lists int |
| + deleted []creds.Item |
| + fail bool |
| + // stale keeps a deleted item in the next listing. |
| + stale bool |
| + ghost []creds.Item |
| + // started, when set, says whether the CLI has started; startedAt is |
| + // what it said at the first listing. |
| + started func() bool |
| + startedAt []bool |
| +} |
| + |
| +func (f *keychainFake) list(context.Context) ([]creds.Item, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.lists++ |
| + if f.started != nil { |
| + f.startedAt = append(f.startedAt, f.started()) |
| + } |
| + out := append(slices.Clone(f.items), f.ghost...) |
| + f.ghost = nil |
| + return out, nil |
| +} |
| + |
| +func (f *keychainFake) delete(_ context.Context, i creds.Item) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.deleted = append(f.deleted, i) |
| + n := slices.Index(f.items, i) |
| + if f.fail || n < 0 { |
| + return errors.New("security: The specified item could not be found in the keychain.") |
| + } |
| + f.items = slices.Delete(f.items, n, n+1) |
| + if f.stale { |
| + f.ghost = append(f.ghost, i) |
| + } |
| + return nil |
| +} |
| + |
| +func (f *keychainFake) add(i ...creds.Item) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.items = append(f.items, i...) |
| +} |
| + |
| +func (f *keychainFake) has(i creds.Item) bool { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return slices.Contains(f.items, i) |
| +} |
| + |
| +func (f *keychainFake) set(fail bool) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.fail = fail |
| +} |
| + |
| +// darwinRig is a token rig with a Mac's credential operations over it. |
| +type darwinRig struct { |
| + *tokenRig |
| + m *macCreds |
| + kc *keychainFake |
| + opts ClaudeOptions |
| + user string |
| + mu sync.Mutex |
| + // checks is what each real check (Conns.Verify) returned. |
| + checks []checkSeen |
| +} |
| + |
| +type checkSeen struct { |
| + check TokenCheck |
| + err error |
| +} |
| + |
| +// shortDir is a private directory with a short path: a tool socket's |
| +// path must fit sun_path. |
| +func shortDir(t *testing.T) string { |
| + t.Helper() |
| + dir, err := os.MkdirTemp("", "dk") |
| + if err == nil { |
| + dir, err = filepath.EvalSymlinks(dir) |
| + } |
| + if err == nil { |
| + err = os.Chmod(dir, 0o700) |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { os.RemoveAll(dir) }) |
| + return dir |
| +} |
| + |
| +func newDarwinRig(t *testing.T) *darwinRig { return darwinRigAt(t, shortDir(t)) } |
| + |
| +// darwinRigAt is the rig in dir (the home); a second rig in the same |
| +// dir is the same runner after a restart. |
| +func darwinRigAt(t *testing.T, dir string) *darwinRig { |
| + t.Helper() |
| + r := &darwinRig{tokenRig: newTokenRigAt(t, dir), kc: &keychainFake{}} |
| + r.cfg.StateDir = filepath.Join(dir, "state") |
| + proxy := filepath.Join(dir, "bin", "equipo-tool-proxy") |
| + if _, err := os.Lstat(proxy); err != nil { |
| + self, _ := os.Executable() |
| + if err := os.Symlink(self, proxy); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + r.cfg.Executable = proxy |
| + install := filepath.Join(dir, "lib") |
| + if err := os.MkdirAll(install, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + script := fmt.Sprintf(launchScript, dir) |
| + sum := sha256.Sum256([]byte(script)) |
| + cli := mac.PinnedForTest(mac.NewClaudeCLI(dir, install), hex.EncodeToString(sum[:])) |
| + if err := cli.Provision(context.Background(), func(context.Context, string) (io.ReadCloser, error) { |
| + return io.NopCloser(strings.NewReader(script)), nil |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + out, err := exec.Command("/usr/bin/id", "-un").Output() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.user = strings.TrimSpace(string(out)) |
| + turns := mac.NewTurns(filepath.Join(r.cfg.StateDir, "mac-gate.lock")) |
| + m := &macCreds{turns: turns, exec: &mac.Executor{Turns: turns, Settle: 10 * time.Second}, cli: cli, |
| + paths: mac.Paths{Home: dir, StateDir: r.cfg.StateDir, AccountsRoot: r.root, SessionRoot: filepath.Join(dir, "sessions"), InstallDir: install}, |
| + configDir: filepath.Join(dir, "config"), runner: proxy, scratch: r.cfg.ScratchRoot, taint: loadTaint(filepath.Join(r.cfg.StateDir, "tainted")), |
| + user: r.user, uid: os.Getuid(), log: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| + m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) } |
| + m.keychain = &creds.Keychain{Dir: filepath.Join(r.cfg.StateDir, "keychain"), Login: filepath.Join(dir, "Library", "Keychains", "login.keychain-db"), User: r.user, List: r.kc.list, Delete: r.kc.delete} |
| + r.m = m |
| + r.opts = ClaudeOptions{Runner: r.cfg, State: r.state, Mac: m, LockWait: 5 * time.Second} |
| + r.conns.Runner = r.cfg |
| + r.conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { |
| + c, err := r.opts.CheckToken(ctx, b) |
| + r.mu.Lock() |
| + r.checks = append(r.checks, checkSeen{c, err}) |
| + r.mu.Unlock() |
| + return err |
| + } |
| + return r |
| +} |
| + |
| +// connector is a Mac worker's connector: no terminal of its own, the |
| +// Mac's credential operations. |
| +func (r *darwinRig) connector() *Connector { |
| + keys := r.keys |
| + limit := time.Hour |
| + if r.limit > 0 { |
| + limit = r.limit |
| + } |
| + c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: limit, Logger: slog.New(slog.NewTextHandler(&r.logs, nil)), Mac: r.m} |
| + c.spawn = func(f func()) { f() } |
| + if err := c.Start(r.ctx); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +// launches is every start of the pinned CLI so far: argv, environment |
| +// and directory, by pid. |
| +type launched struct { |
| + pid int |
| + argv, cwd string |
| + env map[string]string |
| +} |
| + |
| +func (r *darwinRig) launches() []launched { |
| + var out []launched |
| + matches, _ := filepath.Glob(filepath.Join(r.dir, "bin", "launch.*.argv")) |
| + for _, path := range matches { |
| + pid, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "launch."), ".argv")) |
| + argv, _ := os.ReadFile(path) |
| + cwd, _ := os.ReadFile(strings.TrimSuffix(path, ".argv") + ".cwd") |
| + l := launched{pid: pid, argv: strings.TrimSpace(string(argv)), cwd: strings.TrimSpace(string(cwd)), env: map[string]string{}} |
| + raw, _ := os.ReadFile(strings.TrimSuffix(path, ".argv") + ".env") |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + if k, v, ok := strings.Cut(line, "="); ok { |
| + l.env[k] = v |
| + } |
| + } |
| + out = append(out, l) |
| + } |
| + return out |
| +} |
| + |
| +// onlyIn fails if token is in any file under the rig's directory but |
| +// home's token file ("" for none), or in the runner's log. |
| +func (r *darwinRig) onlyIn(token, home string) { |
| + r.t.Helper() |
| + _ = filepath.WalkDir(r.dir, func(path string, d os.DirEntry, err error) error { |
| + if err != nil || d.IsDir() || path == filepath.Join(home, provider.TokenFile) || filepath.Dir(path) == filepath.Join(r.dir, "bin") && d.Name() == "claude" { |
| + return nil |
| + } |
| + if raw, _ := os.ReadFile(path); strings.Contains(string(raw), token) { |
| + r.t.Fatalf("the token is in %s", path) |
| + } |
| + return nil |
| + }) |
| + if strings.Contains(r.logs.String(), token) { |
| + r.t.Fatal("the token is in the runner's log") |
| + } |
| +} |
| + |
| +// lastCheck is the last real check's result. |
| +func (r *darwinRig) lastCheck() checkSeen { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if len(r.checks) == 0 { |
| + r.t.Fatal("no check ran") |
| + } |
| + return r.checks[len(r.checks)-1] |
| +} |
| + |
| +// turnFree: nothing holds the Mac's turn. |
| +func (r *darwinRig) turnFree() bool { |
| + u, ok := r.m.turns.TryTake(mac.OpWarm) |
| + if ok { |
| + u.Give() |
| + } |
| + return ok |
| +} |
| + |
| +// paste connects a pasted token on c and waits for the attempt's end. |
| +func (r *darwinRig) paste(c *Connector, id, token string) (string, wire.ConnectionReport) { |
| + r.t.Helper() |
| + home := r.connect(c, id) |
| + if !r.deliver(c, "f-"+id, r.sealed(id, token, nil)) { |
| + r.t.Fatalf("delivery failed: %v", r.errs) |
| + } |
| + return home, r.ended(id) |
| +} |
| + |
| +func pidAlive(pid int) bool { |
| + if syscall.Kill(pid, 0) != nil { |
| + return false |
| + } |
| + raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") |
| + return err == nil && !strings.Contains(string(raw), ") Z ") |
| +} |
| + |
| +func waitPid(t *testing.T, path string) int { |
| + t.Helper() |
| + for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { |
| + if raw, err := os.ReadFile(path); err == nil { |
| + if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil { |
| + return pid |
| + } |
| + } |
| + } |
| + t.Fatal("the hung CLI never started") |
| + return 0 |
| +} |
| + |
| +// TestDarwinTokenCheck: the token check on a Mac, through the darwin |
| +// launch with its check-only policy and the token by descriptor, gives |
| +// Linux's outcomes, and a crash is settled by the next turn. |
| +func TestDarwinTokenCheck(t *testing.T) { |
| + t.Run("success", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + c := r.connector() |
| + token := fakeclaude.Token("a@example.com") |
| + home, _ := r.paste(c, "c1", token) |
| + r.healthy("c1", home, token, "a@example.com") |
| + if got := r.lastCheck(); got.err != nil || len(got.check.Rows) == 0 { |
| + t.Fatalf("check %+v", got) |
| + } |
| + var check, status bool |
| + for _, l := range r.launches() { |
| + if v, ok := l.env["CLAUDE_CODE_OAUTH_TOKEN"]; ok { |
| + t.Fatalf("the token was in the CLI's environment (%d chars)", len(v)) |
| + } |
| + if l.env[macTokenFDEnv] != "3" || !strings.HasPrefix(l.env["CLAUDE_CONFIG_DIR"], filepath.Join(r.cfg.ScratchRoot, "homes")+"/") || l.env["PATH"] != claude.DarwinPath { |
| + t.Fatalf("launch %d: %v", l.pid, l.env) |
| + } |
| + switch { |
| + case l.argv == "auth status --json": |
| + status = true |
| + case strings.HasPrefix(l.argv, "-p "): |
| + check = true |
| + if !strings.Contains(l.argv, "--tools ") || !strings.HasPrefix(l.env[claude.DarwinMarkerEnv], "check-") || !strings.HasPrefix(l.cwd, r.cfg.ScratchRoot+"/check-") { |
| + t.Fatalf("the check's launch: %q in %s, %v", l.argv, l.cwd, l.env) |
| + } |
| + } |
| + } |
| + if !check || !status { |
| + t.Fatalf("launches %+v", r.launches()) |
| + } |
| + r.onlyIn(token, home) |
| + if !r.turnFree() { |
| + t.Fatal("the check kept the Mac's turn") |
| + } |
| + }) |
| + t.Run("signed out", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + _, end := r.paste(r.connector(), "c1", "sk-ant-oat01-fake-zz-ok") |
| + if end.State != wire.ConnError || end.Reason != "provider_refused" || !errors.Is(r.lastCheck().err, provider.ErrLoginRequired) { |
| + t.Fatalf("end %+v check %+v", end, r.lastCheck()) |
| + } |
| + }) |
| + t.Run("limited", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + token := fakeclaude.Token("spent-a@example.com") |
| + home, _ := r.paste(r.connector(), "c1", token) |
| + r.healthy("c1", home, token, "spent-a@example.com") |
| + if got := r.lastCheck(); got.err != nil || got.check.Seen == nil || !got.check.Seen.Limited { |
| + t.Fatalf("a spent account's check %+v", got) |
| + } |
| + }) |
| + t.Run("cancelled", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| + b, ok := r.binding(filepath.Base(home)) |
| + if !ok { |
| + t.Fatal("no binding") |
| + } |
| + if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan error, 1) |
| + go func() { _, err := r.opts.CheckToken(ctx, b); done <- err }() |
| + pid := waitPid(t, filepath.Join(r.dir, "hang.pid")) |
| + cancel() |
| + select { |
| + case err := <-done: |
| + if err == nil { |
| + t.Fatal("a cancelled check answered") |
| + } |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("the cancelled check never returned") |
| + } |
| + if pidAlive(pid) || !r.turnFree() { |
| + t.Fatalf("after the cancel: CLI alive=%v, turn free=%v", pidAlive(pid), r.turnFree()) |
| + } |
| + }) |
| + t.Run("a crash then recovery", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| + local := filepath.Base(home) |
| + if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Another runner process starts a check on the same Mac and dies |
| + // (SIGKILL) while its CLI runs. |
| + 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 !pidAlive(pid) { |
| + t.Fatal("the dead runner's CLI did not outlive it (nothing to recover)") |
| + } |
| + os.Remove(filepath.Join(r.dir, "hang")) |
| + b, _ := r.binding(local) |
| + if _, err := r.opts.CheckToken(context.Background(), b); err != nil { |
| + t.Fatalf("the check after the crash: %v", err) |
| + } |
| + if pidAlive(pid) { |
| + t.Fatal("the next turn left the dead runner's CLI running") |
| + } |
| + }) |
| +} |
| + |
| +// TestDarwinTokenCheckCrashHelper is the runner process that dies in |
| +// TestDarwinTokenCheck: it runs one check and is killed during it. |
| +func TestDarwinTokenCheckCrashHelper(t *testing.T) { |
| + dir := os.Getenv("EQUIPO_DARWIN_CRASH_DIR") |
| + if dir == "" { |
| + t.Skip("run by TestDarwinTokenCheck") |
| + } |
| + r := darwinRigAt(t, dir) |
| + b, ok := r.binding(os.Getenv("EQUIPO_DARWIN_CRASH_LOCAL")) |
| + if !ok { |
| + t.Fatal("no binding") |
| + } |
| + _, _ = r.opts.CheckToken(context.Background(), b) |
| + t.Fatal("the hung check returned") |
| +} |
| + |
| +// own is the item a sign-in's CLI would store for its config dir. |
| +func (r *darwinRig) own(dir string) creds.Item { |
| + return creds.Item{Keychain: r.m.keychain.Login, Service: creds.ServiceFor(dir), Account: r.user} |
| +} |
| + |
| +// signInDir is the running sign-in's CLAUDE_CONFIG_DIR. |
| +func (r *darwinRig) signInDir() string { |
| + r.t.Helper() |
| + for _, l := range r.launches() { |
| + if l.argv == "setup-token" { |
| + return l.env["CLAUDE_CONFIG_DIR"] |
| + } |
| + } |
| + r.t.Fatal("no sign-in launched") |
| + return "" |
| +} |
| + |
| +// codeIn types the right code for email into the sign-in's card. |
| +func (r *darwinRig) codeIn(c *Connector, id, link, email string) { |
| + r.t.Helper() |
| + if !r.deliver(c, "f-code-"+id, r.sealedCode(id, codeFor(link, email), 1, nil)) { |
| + r.t.Fatalf("code delivery: %v", r.errs) |
| + } |
| +} |
| + |
| +// TestDarwinSignIn: the sign-in on a Mac, in its turn, with its own |
| +// config dir and the Keychain watched around it. |
| +func TestDarwinSignIn(t *testing.T) { |
| + t.Run("code delivered", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + wifi := creds.Item{Keychain: r.m.keychain.Login, Service: "Wi-Fi", Account: r.user} |
| + r.kc.add(wifi) |
| + r.kc.started = func() bool { |
| + m, _ := filepath.Glob(filepath.Join(r.dir, "bin", "launch.*.argv")) |
| + return len(m) > 0 |
| + } |
| + c := r.connector() |
| + link, home := r.signIn(c, "s1") |
| + if !r.m.Held() || len(r.kc.startedAt) == 0 || r.kc.startedAt[0] { |
| + t.Fatalf("the Keychain was not listed and held before the CLI started: %v", r.kc.startedAt) |
| + } |
| + if r.turnFree() { |
| + t.Fatal("the sign-in's terminal is open outside the Mac's turn") |
| + } |
| + dir := r.signInDir() |
| + for _, l := range r.launches() { |
| + if l.argv != "setup-token" { |
| + continue |
| + } |
| + if !strings.HasPrefix(dir, filepath.Join(r.cfg.ScratchRoot, "homes")+"/signin-") || l.env["CLAUDE_SECURESTORAGE_CONFIG_DIR"] != dir || l.env["HOME"] != r.dir || l.env["PATH"] != claude.DarwinPath || l.env[claude.DarwinMarkerEnv] != filepath.Base(dir) || l.env["BROWSER"] != provider.SignInBrowser { |
| + t.Fatalf("the sign-in's environment: %v", l.env) |
| + } |
| + if _, ok := l.env["CLAUDE_CODE_OAUTH_TOKEN"]; ok { |
| + t.Fatal("a token in the sign-in's environment") |
| + } |
| + } |
| + r.codeIn(c, "s1", link, "a@example.com") |
| + token := fakeclaude.Token("a@example.com") |
| + r.healthy("s1", home, token, "a@example.com") |
| + if r.m.Held() || !r.kc.has(wifi) || len(r.kc.deleted) != 0 { |
| + t.Fatalf("held=%v after a clean sign-in; deleted %v", r.m.Held(), r.kc.deleted) |
| + } |
| + if _, err := os.Lstat(dir); !os.IsNotExist(err) { |
| + t.Fatalf("the sign-in's config dir was left: %v", err) |
| + } |
| + if !r.turnFree() { |
| + t.Fatal("the turn was kept") |
| + } |
| + r.onlyIn(token, home) |
| + }) |
| + t.Run("timeout", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + r.limit = 2 * time.Second |
| + c := r.connector() |
| + r.signIn(c, "s1") |
| + if end := r.ended("s1"); end.Reason != "timed_out" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + r.gone() |
| + if r.m.Held() || !r.turnFree() { |
| + t.Fatalf("after the time limit: held=%v turn free=%v", r.m.Held(), r.turnFree()) |
| + } |
| + }) |
| + t.Run("cancel", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + 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) |
| + } |
| + if end := r.ended("s1"); end.Reason != "cancelled" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + r.gone() |
| + if r.m.Held() || !r.turnFree() { |
| + t.Fatalf("after the cancel: held=%v turn free=%v", r.m.Held(), r.turnFree()) |
| + } |
| + }) |
| + t.Run("a Keychain item created means refused, deleted by its exact attributes, held until a second listing shows it gone", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + r.kc.stale = true |
| + c := r.connector() |
| + link, home := r.signIn(c, "s1") |
| + item := r.own(r.signInDir()) |
| + r.kc.add(item) |
| + r.codeIn(c, "s1", link, "a@example.com") |
| + end := r.ended("s1") |
| + if end.State != wire.ConnError || end.Reason != "provider_refused" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if _, ok := r.binding(filepath.Base(home)); ok || exists(home) { |
| + t.Fatal("a refused sign-in kept its connection") |
| + } |
| + if !slices.Equal(r.kc.deleted, []creds.Item{item}) || r.kc.has(item) { |
| + t.Fatalf("deleted %+v", r.kc.deleted) |
| + } |
| + if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{item.Service}) { |
| + t.Fatal("released before a listing showed the item gone") |
| + } |
| + r.m.settle(r.ctx, false) |
| + if r.m.Held() { |
| + t.Fatal("held after a listing showed it gone") |
| + } |
| + }) |
| + t.Run("a pre-existing item is untouched and refuses", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + left := creds.Item{Keychain: r.m.keychain.Login, Service: "Claude Code-credentials", Account: r.user} |
| + r.kc.add(left) |
| + c := r.connector() |
| + if err := c.Accept(r.ctx, "f-connect-s1", wire.ConnectCommand{Connection: "s1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if end := r.ended("s1"); end.Reason != "provider_refused" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if len(r.pids()) != 0 || !r.kc.has(left) || len(r.kc.deleted) != 0 { |
| + t.Fatalf("pids %v deleted %v", r.pids(), r.kc.deleted) |
| + } |
| + if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{"Claude Code-credentials"}) { |
| + t.Fatal("not held, or not named") |
| + } |
| + // A pasted token is refused too, before anything is written. |
| + _, end := r.paste(c, "c2", fakeclaude.Token("a@example.com")) |
| + if end.Reason != "provider_refused" || r.seals("c2") != 0 { |
| + t.Fatalf("a pasted token with a Claude Code item there: %+v", end) |
| + } |
| + }) |
| + t.Run("a failed delete keeps the flag", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + r.kc.set(true) |
| + c := r.connector() |
| + link, _ := r.signIn(c, "s1") |
| + item := r.own(r.signInDir()) |
| + r.kc.add(item) |
| + r.codeIn(c, "s1", link, "a@example.com") |
| + if end := r.ended("s1"); end.Reason != "provider_refused" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if !r.kc.has(item) || !r.m.Held() { |
| + t.Fatal("a failed delete released the hold") |
| + } |
| + r.m.settle(r.ctx, false) |
| + if !r.m.Held() { |
| + t.Fatal("released while the item is still there") |
| + } |
| + }) |
| + t.Run("an unrelated item created at the same time is left, the hold kept", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + c := r.connector() |
| + link, _ := r.signIn(c, "s1") |
| + item := r.own(r.signInDir()) |
| + other := creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user} |
| + r.kc.add(item, other) |
| + r.codeIn(c, "s1", link, "a@example.com") |
| + if end := r.ended("s1"); end.Reason != "provider_refused" { |
| + t.Fatalf("end %+v", end) |
| + } |
| + if r.kc.has(item) || !r.kc.has(other) || slices.Contains(r.kc.deleted, other) { |
| + t.Fatalf("deleted %+v", r.kc.deleted) |
| + } |
| + if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{"Other App"}) { |
| + t.Fatal("the unrelated item does not hold") |
| + } |
| + }) |
| + t.Run("matching attributes in another keychain are left", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + c := r.connector() |
| + link, _ := r.signIn(c, "s1") |
| + elsewhere := r.own(r.signInDir()) |
| + 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) |
| + } |
| + 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()) |
| + } |
| + }) |
| + t.Run("restart", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + // A watch the runner never finished: its list written, its CLI |
| + // gone with the process, an item of its own made meanwhile. |
| + crashed := filepath.Join(r.cfg.ScratchRoot, "homes", "signin-crashed") |
| + if err := r.m.keychain.Before(r.ctx, "signin-crashed", crashed); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.kc.set(true) |
| + c := r.connector() |
| + link, _ := r.signIn(c, "s1") |
| + item := r.own(r.signInDir()) |
| + r.kc.add(item) |
| + r.codeIn(c, "s1", link, "a@example.com") |
| + r.ended("s1") |
| + left := r.own(crashed) |
| + r.kc.add(left) |
| + // The same runner after a restart: the hold is on disk, and the |
| + // restart settles both now that deleting works. |
| + again := darwinRigAt(t, r.dir) |
| + again.kc = r.kc |
| + again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete |
| + if !again.m.Held() { |
| + t.Fatal("the hold did not survive the restart") |
| + } |
| + r.kc.set(false) |
| + again.connector() |
| + if again.m.Held() || r.kc.has(item) || r.kc.has(left) { |
| + t.Fatalf("after the restart: held=%v %v", again.m.Held(), again.m.keychain.Residue()) |
| + } |
| + }) |
| +} |
| + |
| +// TestTaintBlocksConnections: a tainted runner (its own state, or the |
| +// instance's word) stores no token, starts no sign-in, uses no token, |
| +// and its Engineering status says tainted. |
| +func TestTaintBlocksConnections(t *testing.T) { |
| + t.Run("in its own state", func(t *testing.T) { |
| + dir := shortDir(t) |
| + if err := os.MkdirAll(filepath.Join(dir, "state"), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "state", "tainted"), []byte("2026-11-11T00:00:00Z\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := darwinRigAt(t, dir) |
| + c := r.connector() |
| + token := fakeclaude.Token("a@example.com") |
| + _, end := r.paste(c, "c1", token) |
| + if end.State != wire.ConnError || end.Reason != "provider_refused" || r.seals("c1") != 0 || len(r.launches()) != 0 { |
| + t.Fatalf("a tainted runner kept a token: %+v seals=%d launches=%d", end, r.seals("c1"), len(r.launches())) |
| + } |
| + r.onlyIn(token, "") |
| + if err := c.Accept(r.ctx, "f-connect-s1", wire.ConnectCommand{Connection: "s1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if end := r.ended("s1"); end.Reason != "provider_refused" || len(r.pids()) != 0 { |
| + t.Fatalf("a tainted runner signed in: %+v", end) |
| + } |
| + if s := r.m.status(); s == nil || s.State != wire.EngineeringTainted { |
| + t.Fatalf("status %+v", s) |
| + } |
| + }) |
| + t.Run("by the instance, after a connection was made", func(t *testing.T) { |
| + r := newDarwinRig(t) |
| + home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| + b, _ := r.binding(filepath.Base(home)) |
| + before := len(r.launches()) |
| + r.m.taint.Set() |
| + if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errTainted) || len(r.launches()) != before { |
| + t.Fatalf("a tainted runner used its token: %v", err) |
| + } |
| + if s := r.m.status(); s == nil || s.State != wire.EngineeringTainted { |
| + t.Fatalf("status %+v", s) |
| + } |
| + }) |
| +} |
| + |
| +// TestHomeGuardChangedBetweenStoreAndUse: the home guard is read again |
| +// before every use: a home opened after the token was stored stops its |
| +// use, and closing it again lets it go on. |
| +func TestHomeGuardChangedBetweenStoreAndUse(t *testing.T) { |
| + r := newDarwinRig(t) |
| + c := r.connector() |
| + home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com")) |
| + b, ok := r.binding(filepath.Base(home)) |
| + if !ok || r.m.status() != nil { |
| + t.Fatalf("not connected, or not ready: %+v", r.m.status()) |
| + } |
| + if err := os.Chmod(r.dir, 0o750); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := len(r.launches()) |
| + var open *homeOpen |
| + if _, err := r.opts.CheckToken(r.ctx, b); !errors.As(err, &open) || open.r.Fix() != "chmod 700 ~" || len(r.launches()) != before { |
| + t.Fatalf("a check with the home open: %v", err) |
| + } |
| + if s := r.m.status(); s == nil || s.State != wire.EngineeringHomeOpen || s.Reason != creds.CodeHomeMode { |
| + t.Fatalf("status %+v", s) |
| + } |
| + // Nor is a new token stored. |
| + if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 { |
| + t.Fatalf("stored with the home open: %+v", end) |
| + } |
| + if err := os.Chmod(r.dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.opts.CheckToken(r.ctx, b); err != nil { |
| + t.Fatalf("closed again: %v", err) |
| + } |
| +} |
| + |
| +// TestMacCapsSayTainted: the hello's Engineering status comes from the |
| +// guards. |
| +func TestMacCapsSayTainted(t *testing.T) { |
| + r := newDarwinRig(t) |
| + h := &macHost{creds: r.m, taint: r.m.taint} |
| + r.m.taint.Set() |
| + caps := wire.Capabilities{} |
| + h.credentialCaps(r.ctx, &caps) |
| + if caps.Engineering == nil || caps.Engineering.State != wire.EngineeringTainted || wire.ValidCapabilities(caps) != nil { |
| + t.Fatalf("caps %+v", caps.Engineering) |
| + } |
| +} |
diff --git a/internal/runner/thin/signin.go b/internal/runner/thin/signin.go| index 876c43b8..0b8c812f 100644 |
| --- a/internal/runner/thin/signin.go |
| +++ b/internal/runner/thin/signin.go |
| @@ -122,6 +122,13 @@ func (c *Connector) runSignIn(ctx context.Context, cmd wire.ConnectCommand, base |
| } |
| token, reason, err := c.signIn(ctx, cmd, base, home) |
| lock.Close() |
| + if errors.Is(err, errKeychain) { |
| + // A Mac's sign-in left a Keychain item: refused, and the Mac holds |
| + // a credential until it is gone (maccreds.go). |
| + c.log("connect sign-in", err) |
| + c.failToken(cmd, base, home, firstNonEmpty(reason, "provider_refused")) |
| + return |
| + } |
| if err != nil { |
| // Its CLI could not be proven gone: the home stays, and the |
| // attempt runs on until the next start's recovery proves it. |
| @@ -178,7 +185,11 @@ func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wi |
| var attempt int64 |
| wrong, reason := false, "provider_refused" |
| start := c.terminal |
| - if start == nil { |
| + switch { |
| + case start != nil: |
| + case c.Mac != nil: |
| + start = c.macSetupToken |
| + default: |
| start = c.containedSetupToken |
| } |
| for launch := 0; launch < maxLaunches; launch++ { |
| @@ -194,6 +205,9 @@ func (c *Connector) signIn(ctx context.Context, cmd wire.ConnectCommand, base wi |
| stop := func() error { |
| if err := cli.Close(); err != nil { |
| c.log("connect sign-in stop", err) |
| + if errors.Is(err, errKeychain) { |
| + return errKeychain |
| + } |
| return errUnproven |
| } |
| return nil |
| @@ -352,6 +366,13 @@ func (c *Connector) namespaceGone(ctx context.Context, id string) error { |
| if c.gone != nil { |
| return c.gone(ctx, id) |
| } |
| + if c.Mac != nil { |
| + // A Mac's: its run's end proven (mac.Executor.Verify). |
| + if c.Mac.exec.Verify(id) { |
| + return nil |
| + } |
| + return errUnproven |
| + } |
| if c.Manager == nil { |
| return errUnproven |
| } |
diff --git a/internal/runner/thin/token.go b/internal/runner/thin/token.go| index 30cb677f..3699f16d 100644 |
| --- a/internal/runner/thin/token.go |
| +++ b/internal/runner/thin/token.go |
| @@ -232,7 +232,14 @@ func (c *Connector) madeToken(ctx context.Context, cmd wire.ConnectCommand, base |
| // `auth status --json`, the token in the CLI's environment: the |
| // email, if it names one. It proves nothing about the token. |
| options := provider.LoginOptions{ClaudePath: c.Runner.ClaudePath, CodexPath: c.Runner.CodexPath} |
| - observed, err := provider.RefreshLogin(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}, options) |
| + refresh := func(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| + return provider.RefreshLogin(ctx, b, options) |
| + } |
| + if c.Mac != nil { |
| + // A Mac's: the token by descriptor, in its turn. |
| + refresh = c.Mac.authStatus |
| + } |
| + observed, err := refresh(ctx, provider.Binding{ID: id, Home: home, Provider: wire.ProviderClaude, Token: true}) |
| if ctx.Err() != nil { |
| failed(home, reasonOf(ctx.Err())) |
| return |
| @@ -550,6 +557,11 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC |
| c.refused("not_waiting") |
| return nil |
| } |
| + if errors.Is(err, errMacRefused) { |
| + // The Mac's guards refused it: nothing was written. |
| + c.log("connect token", err) |
| + return refuse("provider_refused") |
| + } |
| if err != nil { |
| // Anything else is retried on the resend. |
| return err |
| @@ -566,6 +578,15 @@ func (c *Connector) Secret(ctx context.Context, frameID string, cmd wire.SecretC |
| // to the token file, the directory synced. Not committed, nothing of it |
| // stays. errNotWaiting: the attempt was not waiting for it (a cancel won). |
| func (c *Connector) keep(ctx context.Context, id, kind string, dir *os.File, secret []byte, record func(*sql.Tx) error) error { |
| + if c.Mac != nil { |
| + // A Mac keeps a token in its turn, and only while its guards pass. |
| + give, err := c.Mac.store(ctx) |
| + if err != nil { |
| + clear(secret) |
| + return err |
| + } |
| + defer give() |
| + } |
| err := stage(dir, secret) |
| clear(secret) |
| if err != nil { |
diff --git a/internal/runner/thin/token_test.go b/internal/runner/thin/token_test.go| index 2989f302..bf515568 100644 |
| --- a/internal/runner/thin/token_test.go |
| +++ b/internal/runner/thin/token_test.go |
| @@ -68,8 +68,10 @@ type tokenRig struct { |
| refuse atomic.Pointer[error] |
| } |
| -func newTokenRig(t *testing.T) *tokenRig { |
| - dir := t.TempDir() |
| +func newTokenRig(t *testing.T) *tokenRig { return newTokenRigAt(t, t.TempDir()) } |
| + |
| +// newTokenRigAt is the rig in dir. |
| +func newTokenRigAt(t *testing.T, dir string) *tokenRig { |
| r := &tokenRig{t: t, dir: dir, root: filepath.Join(dir, "accounts")} |
| for _, d := range []string{r.root, filepath.Join(dir, "config"), filepath.Join(dir, "state"), filepath.Join(dir, "bin"), filepath.Join(dir, "scratch")} { |
| if err := os.MkdirAll(d, 0700); err != nil { |
diff --git a/internal/runner/thin/tokencheck.go b/internal/runner/thin/tokencheck.go| index 33a2a9e5..c5e08cac 100644 |
| --- a/internal/runner/thin/tokencheck.go |
| +++ b/internal/runner/thin/tokencheck.go |
| @@ -53,6 +53,10 @@ func (o ClaudeOptions) CheckToken(ctx context.Context, b runner.AccountBinding) |
| func (o ClaudeOptions) checkToken(ctx context.Context, b runner.AccountBinding) (_ []wire.Usage, _ *connect.Limit, named bool, err error) { |
| o.defaults() |
| + if o.Mac != nil { |
| + // A Mac: the darwin launch, token by descriptor (maccreds.go). |
| + return o.Mac.checkToken(ctx, o, b) |
| + } |
| if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken || o.Manager == nil { |
| return nil, nil, false, provider.ErrPolicy |
| } |
| @@ -138,13 +142,23 @@ func (o ClaudeOptions) checkToken(ctx context.Context, b runner.AccountBinding) |
| } |
| (&coordBase{o: o}).forget(proc.ID()) |
| }() |
| + rows, seen, err := readCheck(ctx, proc, session, b) |
| + return rows, seen, false, err |
| +} |
| + |
| +// readCheck sends the check's one prompt to proc and reads its stream to |
| +// the result, bounded by ctx: the usage rows and the last rate limit the |
| +// provider reported. nil: the provider answered (a quota refusal |
| +// answers too); ErrLoginRequired: it refused the token; errCheckFailed |
| +// (or ctx's error): no answer, which proves nothing about the token. |
| +func readCheck(ctx context.Context, proc provider.Process, session string, b runner.AccountBinding) ([]wire.Usage, *connect.Limit, error) { |
| go func() { _, _ = io.Copy(io.Discard, io.LimitReader(proc.Stderr(), 1<<20)) }() |
| raw, err := claude.UserContent(session, tokenCheckPrompt, nil) |
| if err == nil { |
| _, err = proc.Stdin().Write(raw) |
| } |
| if err != nil { |
| - return nil, nil, false, firstErr(ctx.Err(), errCheckFailed) |
| + return nil, nil, firstErr(ctx.Err(), errCheckFailed) |
| } |
| scan := bufio.NewScanner(proc.Stdout()) |
| scan.Buffer(make([]byte, 0, 64<<10), claude.MaxFrameBytes) |
| @@ -182,15 +196,15 @@ func (o ClaudeOptions) checkToken(ctx context.Context, b runner.AccountBinding) |
| rows := usageRows(connect.ClaudeRows(ev.Payload), b, 1, outcome) |
| switch { |
| case signal == connect.FailAuth: |
| - return rows, nil, false, provider.ErrLoginRequired |
| + return rows, nil, provider.ErrLoginRequired |
| case outcome == wire.OutcomeReplied, signal == connect.FailQuota, seen != nil && seen.Limited: |
| // A rejected rate limit is the provider's answer too. |
| - return rows, seen, false, nil |
| + return rows, seen, nil |
| } |
| - return rows, seen, false, errCheckFailed |
| + return rows, seen, errCheckFailed |
| } |
| } |
| - return nil, nil, false, firstErr(ctx.Err(), errCheckFailed) |
| + return nil, nil, firstErr(ctx.Err(), errCheckFailed) |
| } |
| // ReportCheck queues a check's usage for the instance (durable). |
diff --git a/internal/runner/thin/toolproxy_linux_test.go b/internal/runner/thin/toolproxy_linux_test.go| index 692d7158..47ab820e 100644 |
| --- a/internal/runner/thin/toolproxy_linux_test.go |
| +++ b/internal/runner/thin/toolproxy_linux_test.go |
| @@ -4,12 +4,17 @@ import ( |
| "context" |
| "os" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| "amadan.net/oficina/equipo/internal/toolproxy" |
| ) |
| // serveToolProxy is the tool proxy the Pi step tests run from a copy of |
| // this binary (Linux only, as the tool proxy is). |
| func serveToolProxy(args []string) int { |
| + if len(args) == 4 && args[1] == provider.DarwinToolProxyCommand { |
| + // The darwin MCP config's command line (provider.DarwinToolMCP). |
| + args = append(args[:1], args[2:]...) |
| + } |
| if len(args) != 3 || args[1] != "--socket" || toolproxy.Serve(context.Background(), os.Stdin, os.Stdout, args[2]) != nil { |
| return 1 |
| } |