package creds import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io/fs" "os" "path/filepath" "regexp" "slices" "strconv" "strings" "sync" "time" ) // 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, known by its stable attributes only: the // Keychain file, the service, the account and the creation date as the // dump prints it (never its other attributes, which change). An // attribute the dump writes in a way it does not know is kept as "?" // and its raw text, and the item is Unread: it is never anyone's own, // and it is gone only once a listing shows none with that identity. type Item struct { Keychain string `json:"keychain"` Service string `json:"service"` Account string `json:"account"` Created string `json:"created,omitempty"` Unread bool `json:"unread,omitempty"` } // key is the item's identity as listed: every stable attribute. An item // made again under the same names is a new one. func (i Item) key() string { return strconv.FormatBool(i.Unread) + "\x00" + i.Keychain + "\x00" + i.Service + "\x00" + i.Account + "\x00" + i.Created } // name is what shows the item still there: its Keychain, service and // account (a readable item's are unique in its Keychain), and for an // Unread one its creation date too. func (i Item) name() string { if i.Unread { return i.key() } return "false\x00" + i.Keychain + "\x00" + i.Service + "\x00" + i.Account } // cliItem: an item that may be the CLI's: its service names it so, or // the service could not be read. func (i Item) cliItem() bool { return cliService(i.Service) || i.Unread && strings.HasPrefix(i.Service, "?") } // ServiceFor is the Keychain service the pinned CLI stores its // 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|cdat)"<(?:blob|timedate)>=(.*)$`) dumpHex = regexp.MustCompile(`^0x([0-9A-Fa-f]*)(?:\s+".*")?$`) ) // ParseDump reads `security dump-keychain` (no -d: attributes only) and // returns its generic passwords, each by its stable attributes. An item // with an attribute written in a way it does not know, or with no class // line, is returned Unread. func ParseDump(out string) ([]Item, error) { var items []Item var cur *dumpItem flush := func() { if cur != nil && (cur.class == `"genp"` || cur.class == "") { items = append(items, cur.item()) } } for _, line := range strings.Split(out, "\n") { if v, ok := strings.CutPrefix(line, "keychain: "); ok { flush() cur = &dumpItem{} cur.keychain = cur.value(v) continue } if cur == nil { if strings.TrimSpace(line) == "" { continue } return nil, ErrUnreadable } if v, ok := strings.CutPrefix(line, "class: "); ok { cur.class = strings.TrimSpace(v) continue } m := dumpAttr.FindStringSubmatch(line) switch { case m == nil: case m[1] == "svce": cur.service, cur.hasService = cur.value(m[2]), true case m[1] == "acct": cur.account, cur.hasAccount = cur.value(m[2]), true default: cur.created = strings.TrimSpace(m[2]) } } flush() return items, nil } type dumpItem struct { keychain, class, service, account, created string hasService, hasAccount, bad bool } // value is an attribute's value, or "?" and its raw text (and the item // Unread) when it cannot be read for sure. func (d *dumpItem) value(v string) string { if s, ok := blobValue(v); ok { return s } d.bad = true return "?" + strings.TrimSpace(v) } func (d *dumpItem) item() Item { i := Item{Keychain: d.keychain, Service: d.service, Account: d.account, Created: d.created} if !d.hasService { i.Service = "?" } if !d.hasAccount { i.Account = "?" } i.Unread = d.bad || d.class == "" || !d.hasService || !d.hasAccount || !filepath.IsAbs(d.keychain) return i } // blobValue is a dump's value: , "text" with no escape in it, or // 0x (the bytes, whatever the quoted rendering after it says). func blobValue(v string) (string, bool) { v = strings.TrimSpace(v) switch { case v == "": 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 login Keychain. Dir holds its // durable records (in the state dir); Login is the login Keychain's // path; User the runner user. List lists the generic passwords of the // Keychain at a path (security dump-keychain ), attributes only; // Delete deletes one by service, account and Keychain path. type Keychain struct { Dir, Login, User string List func(ctx context.Context, keychain string) ([]Item, error) Delete func(context.Context, Item) error // Acked, if set, is told of each watch Settle proved over, once its // record is durably checked or gone (the proof is no longer needed). Acked func(Watch) // 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"` // Started is when the watch began (before its launch started); Run // is its launch's process record (mac.RecordID) once it started. Started time.Time `json:"started"` Run string `json:"run,omitempty"` ConfigDir string `json:"config_dir"` Before []Item `json:"before"` Checked bool `json:"checked"` Left []Item `json:"left,omitempty"` } // list is the runner user's login Keychain, listed by its path whatever // the search list says (the CLI writes to the default Keychain, which // for this user is the login one): its items only. A listing that fails // is an error, and nothing is decided from it. func (k *Keychain) list(ctx context.Context) ([]Item, error) { all, err := k.List(ctx, k.Login) if err != nil { return nil, err } var out []Item for _, i := range all { if i.Keychain == k.Login || i.Unread && !filepath.IsAbs(i.Keychain) { out = append(out, i) } } return out, nil } // Watch is a watch still waiting for its second look, as Settle asks // whether its launch has ended: its marker, its launch's process record // ("" when it never started) and when the watch began. type Watch struct { Marker, Run string Started time.Time } // Ran records marker's launch's process record (mac.RecordID) on its // watch, durably, as soon as it is known. func (k *Keychain) Ran(marker, run string) error { k.op.Lock() defer k.op.Unlock() rec, err := k.load(marker) if err != nil { return err } rec.Run = run return k.save(rec) } // Abandon gives a watch up in this process: its launch's end could not // be proven, so it stays unchecked, held and Unproven, for a restart. func (k *Keychain) Abandon(marker string) { k.mu.Lock() delete(k.live, marker) k.mu.Unlock() } // Unproven are the watches whose launch's end is not proven and that no // launch here still runs: each keeps the Mac's connections closed. An // error (the records cannot be listed) must close them too. func (k *Keychain) Unproven() ([]string, error) { names, err := k.names() if err != nil { return nil, err } var out []string for _, name := range names { rec, err := k.load(name) k.mu.Lock() live := k.live[name] k.mu.Unlock() if err != nil || !rec.Checked && !live { out = append(out, name) } } return out, nil } // 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, Started: time.Now()}); 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.cliItem() { 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.name()] = true } var errs []error for _, rec := range recs { rec.Left = slices.DeleteFunc(rec.Left, func(i Item) bool { return !shown[i.name()] }) if len(rec.Left) == 0 { errs = append(errs, k.remove(rec.Marker)) } else { 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(Watch) 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 var proven []Watch 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() w := Watch{Marker: rec.Marker, Run: rec.Run, Started: rec.Started} if !restart || live || gone == nil || !gone(w) { continue } if list == nil { if list, err = k.list(ctx); err != nil { return err } } rec.Left, rec.Checked = appeared(rec.Before, list), true proven = append(proven, w) } recs = append(recs, &rec) } if len(recs) == 0 { return nil } _, err = k.recheck(ctx, recs) for _, w := range proven { // Only a record on disk as checked, or gone, no longer needs it. if rec, lerr := k.load(w.Marker); k.Acked != nil && (errors.Is(lerr, fs.ErrNotExist) || lerr == nil && rec.Checked) { k.Acked(w) } } 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 { name := i.Service if strings.HasPrefix(name, "?") { name = "" } if !slices.Contains(out, name) { out = append(out, name) } } } 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() }