oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package creds
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "io/fs"
11 "os"
12 "path/filepath"
13 "regexp"
14 "slices"
15 "strconv"
16 "strings"
17 "sync"
18 "time"
19)
20
21// The Keychain watch around a sign-in (spec §8.3; slice F task 10). The
22// pinned CLI is kept off the Keychain first: the sign-in runs with
23// CLAUDE_CONFIG_DIR set to a directory of its own, so any credential it
24// stores is named for that directory (task 1, S4). Then it is checked:
25// before the CLI starts, the generic-password items of the runner user's
26// Keychains are listed by their attributes only (no secret is read) and
27// the list is written durably; after its end is proven they are listed
28// again. An item that appeared is deleted only when it is positively the
29// attempt's own: in the runner user's login Keychain, named by path,
30// with the service the CLI derives for the attempt's config dir and an
31// account the CLI derives for this user. Anything else that appeared is
32// never touched. Either way the connection is refused, and the Mac holds
33// a credential (Held) until a listing shows every such item gone. An
34// item there before is never touched; one with the CLI's service name
35// refuses the connection and holds too.
36
37// Item is a generic password, known by its stable attributes only: the
38// Keychain file, the service, the account and the creation date as the
39// dump prints it (never its other attributes, which change). An
40// attribute the dump writes in a way it does not know is kept as "?"
41// and its raw text, and the item is Unread: it is never anyone's own,
42// and it is gone only once a listing shows none with that identity.
43type Item struct {
44 Keychain string `json:"keychain"`
45 Service string `json:"service"`
46 Account string `json:"account"`
47 Created string `json:"created,omitempty"`
48 Unread bool `json:"unread,omitempty"`
49}
50
51// key is the item's identity as listed: every stable attribute. An item
52// made again under the same names is a new one.
53func (i Item) key() string {
54 return strconv.FormatBool(i.Unread) + "\x00" + i.Keychain + "\x00" + i.Service + "\x00" + i.Account + "\x00" + i.Created
55}
56
57// name is what shows the item still there: its Keychain, service and
58// account (a readable item's are unique in its Keychain), and for an
59// Unread one its creation date too.
60func (i Item) name() string {
61 if i.Unread {
62 return i.key()
63 }
64 return "false\x00" + i.Keychain + "\x00" + i.Service + "\x00" + i.Account
65}
66
67// cliItem: an item that may be the CLI's: its service names it so, or
68// the service could not be read.
69func (i Item) cliItem() bool {
70 return cliService(i.Service) || i.Unread && strings.HasPrefix(i.Service, "?")
71}
72
73// ServiceFor is the Keychain service the pinned CLI stores its
74// credential under when CLAUDE_CONFIG_DIR is dir: "Claude Code" (the
75// build's OAUTH_FILE_SUFFIX is empty), "-credentials", then "-" and the
76// first eight hex digits of SHA-256 of dir (task 1, S4).
77func ServiceFor(dir string) string {
78 sum := sha256.Sum256([]byte(dir))
79 return "Claude Code-credentials-" + hex.EncodeToString(sum[:])[:8]
80}
81
82// Accounts are the accounts the CLI derives for user: its name, or
83// claude-code-user when the name has characters it does not keep.
84func Accounts(user string) []string {
85 if user == "claude-code-user" {
86 return []string{user}
87 }
88 return []string{user, "claude-code-user"}
89}
90
91// cliService: a service the pinned CLI names its items with.
92func cliService(s string) bool { return s == "Claude Code" || strings.HasPrefix(s, "Claude Code-") }
93
94var (
95 dumpAttr = regexp.MustCompile(`^\s+"(svce|acct|cdat)"<(?:blob|timedate)>=(.*)$`)
96 dumpHex = regexp.MustCompile(`^0x([0-9A-Fa-f]*)(?:\s+".*")?$`)
97)
98
99// ParseDump reads `security dump-keychain` (no -d: attributes only) and
100// returns its generic passwords, each by its stable attributes. An item
101// with an attribute written in a way it does not know, or with no class
102// line, is returned Unread.
103func ParseDump(out string) ([]Item, error) {
104 var items []Item
105 var cur *dumpItem
106 flush := func() {
107 if cur != nil && (cur.class == `"genp"` || cur.class == "") {
108 items = append(items, cur.item())
109 }
110 }
111 for _, line := range strings.Split(out, "\n") {
112 if v, ok := strings.CutPrefix(line, "keychain: "); ok {
113 flush()
114 cur = &dumpItem{}
115 cur.keychain = cur.value(v)
116 continue
117 }
118 if cur == nil {
119 if strings.TrimSpace(line) == "" {
120 continue
121 }
122 return nil, ErrUnreadable
123 }
124 if v, ok := strings.CutPrefix(line, "class: "); ok {
125 cur.class = strings.TrimSpace(v)
126 continue
127 }
128 m := dumpAttr.FindStringSubmatch(line)
129 switch {
130 case m == nil:
131 case m[1] == "svce":
132 cur.service, cur.hasService = cur.value(m[2]), true
133 case m[1] == "acct":
134 cur.account, cur.hasAccount = cur.value(m[2]), true
135 default:
136 cur.created = strings.TrimSpace(m[2])
137 }
138 }
139 flush()
140 return items, nil
141}
142
143type dumpItem struct {
144 keychain, class, service, account, created string
145 hasService, hasAccount, bad bool
146}
147
148// value is an attribute's value, or "?" and its raw text (and the item
149// Unread) when it cannot be read for sure.
150func (d *dumpItem) value(v string) string {
151 if s, ok := blobValue(v); ok {
152 return s
153 }
154 d.bad = true
155 return "?" + strings.TrimSpace(v)
156}
157
158func (d *dumpItem) item() Item {
159 i := Item{Keychain: d.keychain, Service: d.service, Account: d.account, Created: d.created}
160 if !d.hasService {
161 i.Service = "?"
162 }
163 if !d.hasAccount {
164 i.Account = "?"
165 }
166 i.Unread = d.bad || d.class == "" || !d.hasService || !d.hasAccount || !filepath.IsAbs(d.keychain)
167 return i
168}
169
170// blobValue is a dump's value: <NULL>, "text" with no escape in it, or
171// 0x<hex> (the bytes, whatever the quoted rendering after it says).
172func blobValue(v string) (string, bool) {
173 v = strings.TrimSpace(v)
174 switch {
175 case v == "<NULL>":
176 return "", true
177 case len(v) >= 2 && v[0] == '"' && v[len(v)-1] == '"' && !strings.ContainsAny(v[1:len(v)-1], "\\\""):
178 return v[1 : len(v)-1], true
179 }
180 if m := dumpHex.FindStringSubmatch(v); m != nil {
181 raw, err := hex.DecodeString(m[1])
182 if err == nil && !bytes.ContainsAny(raw, "\x00\n\r") {
183 return string(raw), true
184 }
185 }
186 return "", false
187}
188
189// ErrExisting refuses a connection while a Keychain item with the CLI's
190// service name is there (Residue names it).
191var ErrExisting = errors.New("creds: a Keychain item with Claude Code's name is already there")
192
193// Keychain watches the runner user's login Keychain. Dir holds its
194// durable records (in the state dir); Login is the login Keychain's
195// path; User the runner user. List lists the generic passwords of the
196// Keychain at a path (security dump-keychain <path>), attributes only;
197// Delete deletes one by service, account and Keychain path.
198type Keychain struct {
199 Dir, Login, User string
200 List func(ctx context.Context, keychain string) ([]Item, error)
201 Delete func(context.Context, Item) error
202 // Acked, if set, is told of each watch Settle proved over, once its
203 // record is durably checked or gone (the proof is no longer needed).
204 Acked func(Watch)
205
206 // op runs one watch operation at a time (a sign-in's second look and
207 // the hourly settling may meet on a record).
208 op sync.Mutex
209 mu sync.Mutex
210 live map[string]bool
211}
212
213// record is one watch on disk: Before until the attempt's end is
214// checked; then Left, what a listing still showed.
215type record struct {
216 Marker string `json:"marker"`
217 // Started is when the watch began (before its launch started); Run
218 // is its launch's process record (mac.RecordID) once it started.
219 Started time.Time `json:"started"`
220 Run string `json:"run,omitempty"`
221 ConfigDir string `json:"config_dir"`
222 Before []Item `json:"before"`
223 Checked bool `json:"checked"`
224 Left []Item `json:"left,omitempty"`
225}
226
227// list is the runner user's login Keychain, listed by its path whatever
228// the search list says (the CLI writes to the default Keychain, which
229// for this user is the login one): its items only. A listing that fails
230// is an error, and nothing is decided from it.
231func (k *Keychain) list(ctx context.Context) ([]Item, error) {
232 all, err := k.List(ctx, k.Login)
233 if err != nil {
234 return nil, err
235 }
236 var out []Item
237 for _, i := range all {
238 if i.Keychain == k.Login || i.Unread && !filepath.IsAbs(i.Keychain) {
239 out = append(out, i)
240 }
241 }
242 return out, nil
243}
244
245// Watch is a watch still waiting for its second look, as Settle asks
246// whether its launch has ended: its marker, its launch's process record
247// ("" when it never started) and when the watch began.
248type Watch struct {
249 Marker, Run string
250 Started time.Time
251}
252
253// Ran records marker's launch's process record (mac.RecordID) on its
254// watch, durably, as soon as it is known.
255func (k *Keychain) Ran(marker, run string) error {
256 k.op.Lock()
257 defer k.op.Unlock()
258 rec, err := k.load(marker)
259 if err != nil {
260 return err
261 }
262 rec.Run = run
263 return k.save(rec)
264}
265
266// Abandon gives a watch up in this process: its launch's end could not
267// be proven, so it stays unchecked, held and Unproven, for a restart.
268func (k *Keychain) Abandon(marker string) {
269 k.mu.Lock()
270 delete(k.live, marker)
271 k.mu.Unlock()
272}
273
274// Unproven are the watches whose launch's end is not proven and that no
275// launch here still runs: each keeps the Mac's connections closed. An
276// error (the records cannot be listed) must close them too.
277func (k *Keychain) Unproven() ([]string, error) {
278 names, err := k.names()
279 if err != nil {
280 return nil, err
281 }
282 var out []string
283 for _, name := range names {
284 rec, err := k.load(name)
285 k.mu.Lock()
286 live := k.live[name]
287 k.mu.Unlock()
288 if err != nil || !rec.Checked && !live {
289 out = append(out, name)
290 }
291 }
292 return out, nil
293}
294
295// existingRecord names the record of CLI items found already there.
296const existingRecord = "existing"
297
298// Outcome is what a sign-in's second look found: Clean, nothing new;
299// otherwise what was deleted (the attempt's own) and what is left.
300type Outcome struct {
301 Clean bool
302 Deleted, Left []Item
303}
304
305var recordName = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
306
307// Before lists the Keychains and writes the list durably as marker's
308// watch, with dir the CLAUDE_CONFIG_DIR the CLI will run with, before
309// anything starts. An item with the CLI's service name already there
310// refuses the attempt (ErrExisting) and holds.
311func (k *Keychain) Before(ctx context.Context, marker, dir string) error {
312 k.op.Lock()
313 defer k.op.Unlock()
314 if !recordName.MatchString(marker) || marker == existingRecord || !filepath.IsAbs(dir) {
315 return ErrUnreadable
316 }
317 list, err := k.list(ctx)
318 if err != nil {
319 return err
320 }
321 if err := k.refuseExisting(list); err != nil {
322 return err
323 }
324 if err := k.save(record{Marker: marker, ConfigDir: dir, Before: list, Started: time.Now()}); err != nil {
325 return err
326 }
327 k.mu.Lock()
328 if k.live == nil {
329 k.live = map[string]bool{}
330 }
331 k.live[marker] = true
332 k.mu.Unlock()
333 return nil
334}
335
336// refuseExisting records the CLI's items in list, if any, as found
337// there: ErrExisting.
338func (k *Keychain) refuseExisting(list []Item) error {
339 var found []Item
340 for _, i := range list {
341 if i.cliItem() {
342 found = append(found, i)
343 }
344 }
345 if len(found) == 0 {
346 return nil
347 }
348 if err := k.save(record{Marker: existingRecord, Checked: true, Left: found}); err != nil {
349 return err
350 }
351 return ErrExisting
352}
353
354// After lists again once marker's CLI is proven gone: what appeared is
355// deleted when it is the attempt's own, and a second listing decides
356// what is left. Outcome.Clean only when nothing appeared.
357func (k *Keychain) After(ctx context.Context, marker string) (Outcome, error) {
358 k.op.Lock()
359 defer k.op.Unlock()
360 defer func() {
361 k.mu.Lock()
362 delete(k.live, marker)
363 k.mu.Unlock()
364 }()
365 rec, err := k.load(marker)
366 if err != nil {
367 return Outcome{}, err
368 }
369 list, err := k.list(ctx)
370 if err != nil {
371 return Outcome{}, err
372 }
373 rec.Left, rec.Checked = appeared(rec.Before, list), true
374 if len(rec.Left) == 0 {
375 return Outcome{Clean: true}, k.remove(marker)
376 }
377 out := Outcome{Left: rec.Left}
378 out.Deleted, err = k.recheck(ctx, []*record{&rec})
379 out.Left = rec.Left
380 return out, err
381}
382
383// appeared is what list has that before did not.
384func appeared(before, list []Item) []Item {
385 had := map[string]bool{}
386 for _, i := range before {
387 had[i.key()] = true
388 }
389 var out []Item
390 for _, i := range list {
391 if !had[i.key()] {
392 out = append(out, i)
393 }
394 }
395 return out
396}
397
398// own: i is positively rec's attempt's: in the login Keychain, named
399// for its config dir, with an account the CLI derives for this user.
400func (k *Keychain) own(rec record, i Item) bool {
401 return rec.ConfigDir != "" && !i.Unread && i.Keychain == k.Login && i.Service == ServiceFor(rec.ConfigDir) && slices.Contains(Accounts(k.User), i.Account)
402}
403
404// recheck deletes each record's own items left, lists again, keeps of
405// each record what that listing still shows, and writes it (a record
406// with nothing left goes). It returns what it deleted.
407func (k *Keychain) recheck(ctx context.Context, recs []*record) ([]Item, error) {
408 var deleted []Item
409 for _, rec := range recs {
410 for _, i := range rec.Left {
411 if k.own(*rec, i) && k.Delete(ctx, i) == nil {
412 deleted = append(deleted, i)
413 }
414 }
415 }
416 list, err := k.list(ctx)
417 if err != nil {
418 return deleted, err
419 }
420 shown := map[string]bool{}
421 for _, i := range list {
422 shown[i.name()] = true
423 }
424 var errs []error
425 for _, rec := range recs {
426 rec.Left = slices.DeleteFunc(rec.Left, func(i Item) bool { return !shown[i.name()] })
427 if len(rec.Left) == 0 {
428 errs = append(errs, k.remove(rec.Marker))
429 } else {
430 errs = append(errs, k.save(*rec))
431 }
432 }
433 return deleted, errors.Join(errs...)
434}
435
436// Existing refuses a new connection (ErrExisting, recorded and held)
437// while an item with the CLI's service name is in a Keychain.
438func (k *Keychain) Existing(ctx context.Context) error {
439 k.op.Lock()
440 defer k.op.Unlock()
441 list, err := k.list(ctx)
442 if err != nil {
443 return err
444 }
445 return k.refuseExisting(list)
446}
447
448// Settle looks again at every record: what is left is deleted again
449// when it is an attempt's own, and a record goes once a listing shows
450// none of it. A watch whose attempt never got its second look (the
451// runner stopped) is checked only at a restart and once gone(marker)
452// proves its CLI ended; it is never touched while its attempt runs here.
453func (k *Keychain) Settle(ctx context.Context, restart bool, gone func(Watch) bool) error {
454 k.op.Lock()
455 defer k.op.Unlock()
456 names, err := k.names()
457 if err != nil || len(names) == 0 {
458 return err
459 }
460 var recs []*record
461 var list []Item
462 var proven []Watch
463 for _, name := range names {
464 rec, err := k.load(name)
465 if err != nil {
466 return err
467 }
468 if !rec.Checked {
469 k.mu.Lock()
470 live := k.live[name]
471 k.mu.Unlock()
472 w := Watch{Marker: rec.Marker, Run: rec.Run, Started: rec.Started}
473 if !restart || live || gone == nil || !gone(w) {
474 continue
475 }
476 if list == nil {
477 if list, err = k.list(ctx); err != nil {
478 return err
479 }
480 }
481 rec.Left, rec.Checked = appeared(rec.Before, list), true
482 proven = append(proven, w)
483 }
484 recs = append(recs, &rec)
485 }
486 if len(recs) == 0 {
487 return nil
488 }
489 _, err = k.recheck(ctx, recs)
490 for _, w := range proven {
491 // Only a record on disk as checked, or gone, no longer needs it.
492 if rec, lerr := k.load(w.Marker); k.Acked != nil && (errors.Is(lerr, fs.ErrNotExist) || lerr == nil && rec.Checked) {
493 k.Acked(w)
494 }
495 }
496 return err
497}
498
499// Held: a watch or a residue is on record, so the Mac may hold a
500// credential in a Keychain. A records directory that cannot be read
501// holds.
502func (k *Keychain) Held() bool {
503 names, err := k.names()
504 return err != nil || len(names) > 0
505}
506
507// Residue is the service of every item on record for the person to
508// remove ("" for one whose attributes could not be read), sorted.
509func (k *Keychain) Residue() []string {
510 names, _ := k.names()
511 var out []string
512 for _, name := range names {
513 rec, err := k.load(name)
514 if err != nil {
515 continue
516 }
517 for _, i := range rec.Left {
518 name := i.Service
519 if strings.HasPrefix(name, "?") {
520 name = ""
521 }
522 if !slices.Contains(out, name) {
523 out = append(out, name)
524 }
525 }
526 }
527 slices.Sort(out)
528 return out
529}
530
531// names are the records on disk.
532func (k *Keychain) names() ([]string, error) {
533 entries, err := os.ReadDir(k.Dir)
534 if errors.Is(err, fs.ErrNotExist) {
535 return nil, nil
536 }
537 if err != nil {
538 return nil, err
539 }
540 var out []string
541 for _, e := range entries {
542 if name, ok := strings.CutSuffix(e.Name(), ".json"); ok && recordName.MatchString(name) {
543 out = append(out, name)
544 }
545 }
546 return out, nil
547}
548
549func (k *Keychain) load(name string) (record, error) {
550 var rec record
551 raw, err := os.ReadFile(filepath.Join(k.Dir, name+".json"))
552 if err == nil {
553 err = json.Unmarshal(raw, &rec)
554 }
555 if err == nil && rec.Marker != name {
556 err = ErrUnreadable
557 }
558 return rec, err
559}
560
561// save writes rec durably: a new file synced, renamed over the old one,
562// the directory synced.
563func (k *Keychain) save(rec record) error {
564 if err := os.MkdirAll(k.Dir, 0o700); err != nil {
565 return err
566 }
567 raw, err := json.Marshal(rec)
568 if err != nil {
569 return err
570 }
571 f, err := os.CreateTemp(k.Dir, ".record-")
572 if err != nil {
573 return err
574 }
575 _, err = f.Write(raw)
576 if e := f.Sync(); err == nil {
577 err = e
578 }
579 if e := f.Close(); err == nil {
580 err = e
581 }
582 if err == nil {
583 err = os.Rename(f.Name(), filepath.Join(k.Dir, rec.Marker+".json"))
584 }
585 if err != nil {
586 os.Remove(f.Name())
587 return err
588 }
589 return syncDir(k.Dir)
590}
591
592func (k *Keychain) remove(name string) error {
593 if err := os.Remove(filepath.Join(k.Dir, name+".json")); err != nil && !errors.Is(err, fs.ErrNotExist) {
594 return err
595 }
596 return syncDir(k.Dir)
597}
598
599func syncDir(dir string) error {
600 d, err := os.Open(dir)
601 if err != nil {
602 return err
603 }
604 defer d.Close()
605 return d.Sync()
606}
607