oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package provider
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "crypto/sha256"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "io"
12 "os"
13 "os/user"
14 "path/filepath"
15 "strconv"
16 "strings"
17 "sync"
18 "time"
19
20 "golang.org/x/sys/unix"
21)
22
23const IdentityFile = "equipo-identity.json"
24const (
25 ErrAccountBusy Error = "provider_account_busy"
26 ErrAccountMaintenance Error = "provider_account_maintenance"
27 ErrPreflightRequired Error = "provider_preflight_required"
28 ErrRefreshPending Error = "provider_refresh_pending"
29 ErrContainment Error = "provider_account_containment"
30 ErrPolicy Error = "provider_policy_rejected"
31)
32
33// HomeRules describes forbidden credential sources. Tests inject owned fake
34// directories; production also compares directory inodes to catch bind aliases.
35type HomeRules struct {
36 InteractiveHomes []string
37 unavailable bool
38}
39
40func DefaultHomeRules() HomeRules {
41 return homeRules(user.LookupId, os.Getenv)
42}
43func homeRules(lookup func(string) (*user.User, error), getenv func(string) string) HomeRules {
44 u, e := lookup(strconv.Itoa(os.Geteuid()))
45 if e != nil || u == nil || !cleanPath(u.HomeDir) {
46 return HomeRules{unavailable: true}
47 }
48 homes := []string{filepath.Join(u.HomeDir, ".claude"), filepath.Join(u.HomeDir, ".codex")}
49 for _, key := range []string{"CODEX_HOME", "CLAUDE_CONFIG_DIR"} {
50 if path := getenv(key); path != "" {
51 path, e = filepath.Abs(path)
52 if e != nil {
53 return HomeRules{unavailable: true}
54 }
55 homes = append(homes, path)
56 if real, e := filepath.EvalSymlinks(path); e == nil {
57 homes = append(homes, real)
58 }
59 }
60 }
61 return HomeRules{InteractiveHomes: homes}
62}
63func withinPath(path, root string) bool { return path == root || strings.HasPrefix(path, root+"/") }
64func cleanPath(path string) bool {
65 return filepath.IsAbs(path) && filepath.Clean(path) == path && path != "/"
66}
67func (r HomeRules) RefusesPath(path string) bool {
68 if r.unavailable || !cleanPath(path) {
69 return true
70 }
71 if strings.Contains(path+"/", "/.paseo/zerosub/homes/") {
72 return true
73 }
74 for _, home := range r.InteractiveHomes {
75 if withinPath(path, home) {
76 return true
77 }
78 }
79 return false
80}
81func (r HomeRules) refusedInode(info os.FileInfo) bool {
82 for _, home := range r.InteractiveHomes {
83 if other, e := os.Stat(home); e == nil && os.SameFile(info, other) {
84 return true
85 }
86 }
87 return false
88}
89func pinDirectory(path string) (*os.File, error) {
90 if !cleanPath(path) {
91 return nil, ErrPolicy
92 }
93 fd, e := openNoLinks(path, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC)
94 if e != nil {
95 return nil, ErrPolicy
96 }
97 return os.NewFile(uintptr(fd), path), nil
98}
99func privateDirectory(f *os.File) bool {
100 info, e := f.Stat()
101 return e == nil && info.IsDir() && info.Mode().Perm() == 0700
102}
103
104// AccountLease holds a directory flock until Close, including across preflight,
105// all turns. Claude's identity is trust-on-first-use: Paul
106// confirms CLI-observed metadata at enrolment. It is not remote attestation.
107type AccountLease struct {
108 goMu sync.Mutex
109 goPins map[Mount]goPin
110 goClosed bool
111 mu sync.Mutex
112 sourceFreshUntil time.Time
113 source Binding
114 rules HomeRules
115 dir *os.File
116 runtime string
117 config string
118 configInfo os.FileInfo
119 policy *Policy
120 runtimeInfo os.FileInfo
121 generation [32]byte
122 ready, active, closed bool
123 checking bool
124 // detached copies released the source lock after staging (copy.go).
125 detached bool
126 contained bool
127 runtimeGeneration [32]byte
128 claudeIdentity []byte
129 // token is a token home's credential, held for the launch
130 // environment only (LaunchSecretEnv); never staged in the copy.
131 token []byte
132}
133
134func OpenAccount(ctx context.Context, b Binding) (*AccountLease, error) {
135 return openAccount(ctx, b, DefaultHomeRules())
136}
137
138// OpenAccountRefreshing runs the official CLI in the locked source home before
139// making a runtime copy. The lock remains held through the attempt.
140func OpenAccountRefreshing(ctx context.Context, b Binding, refresh func(context.Context, Binding) (Identity, error)) (*AccountLease, error) {
141 return openAccountRefreshing(ctx, b, DefaultHomeRules(), refresh)
142}
143func openAccount(ctx context.Context, b Binding, r HomeRules) (*AccountLease, error) {
144 return openAccountRefreshing(ctx, b, r, nil)
145}
146func openAccountRefreshing(ctx context.Context, b Binding, r HomeRules, refresh func(context.Context, Binding) (Identity, error)) (_ *AccountLease, err error) {
147 if e := ctx.Err(); e != nil {
148 return nil, e
149 }
150 if ValidateContract(Version, b.Provider) != nil || b.ID == "" || b.AccountID == "" || b.Expected.AccountID != b.AccountID || b.Expected.HomeID == "" || b.Expected.ProviderVersion == "" || r.RefusesPath(b.Home) {
151 return nil, ErrIdentity
152 }
153 // Resolve before opening any login file. Also inspect mount roots for aliases
154 // of forbidden trees; inode comparison below handles explicit interactive homes.
155 real, e := filepath.EvalSymlinks(b.Home)
156 if e != nil || real != b.Home || r.RefusesPath(real) || refusedMountAlias(b.Home, r) {
157 return nil, ErrPolicy
158 }
159 dir, e := pinDirectory(b.Home)
160 if e != nil {
161 return nil, e
162 }
163 defer func() {
164 if err != nil {
165 // As in Close: a concurrent fork can hold this descriptor until
166 // exec, and the lock with it, so a caller's next try would find
167 // the home busy. Release the lock before closing our copy.
168 unix.Flock(int(dir.Fd()), unix.LOCK_UN)
169 dir.Close()
170 }
171 }()
172 if !privateDirectory(dir) {
173 return nil, ErrPolicy
174 }
175 for parent := b.Home; parent != "/"; parent = filepath.Dir(parent) {
176 info, e := os.Stat(parent)
177 if e != nil || r.refusedInode(info) {
178 return nil, ErrPolicy
179 }
180 }
181 if e = unix.Flock(int(dir.Fd()), unix.LOCK_EX|unix.LOCK_NB); e != nil {
182 return nil, ErrAccountBusy
183 }
184 l := &AccountLease{source: b, dir: dir, rules: r}
185 _, _, e = l.snapshot()
186 if e != nil {
187 return nil, e
188 }
189 if r.RefusesPath(b.RuntimeRoot) || !cleanPath(b.RuntimeRoot) || withinPath(b.RuntimeRoot, b.Home) || withinPath(b.Home, b.RuntimeRoot) {
190 return nil, ErrPolicy
191 }
192 if refresh != nil {
193 id, err := refresh(ctx, b)
194 if err != nil {
195 return nil, err
196 }
197 if !observedIdentityMatches(b, id) {
198 return nil, ErrIdentity
199 }
200 if _, _, err = l.snapshot(); err != nil {
201 return nil, err
202 }
203 l.sourceFreshUntil = time.Now().Add(25 * time.Minute)
204 }
205 root, e := makePrivateRoot(b.RuntimeRoot)
206 if e != nil {
207 return nil, e
208 }
209 defer root.Close()
210 if !privateDirectory(root) {
211 return nil, ErrPolicy
212 }
213 l.runtime, e = os.MkdirTemp(b.RuntimeRoot, "account-")
214 if e != nil {
215 return nil, ErrPolicy
216 }
217 l.runtimeInfo, e = os.Stat(l.runtime)
218 if e != nil {
219 os.RemoveAll(l.runtime)
220 return nil, ErrPolicy
221 }
222 if e = l.stage(); e != nil {
223 os.RemoveAll(l.runtime)
224 return nil, e
225 }
226 l.config, e = os.MkdirTemp(b.RuntimeRoot, "config-")
227 if e != nil {
228 os.RemoveAll(l.runtime)
229 return nil, ErrPolicy
230 }
231 l.configInfo, e = os.Stat(l.config)
232 if e != nil {
233 os.RemoveAll(l.config)
234 os.RemoveAll(l.runtime)
235 return nil, ErrPolicy
236 }
237 return l, nil
238}
239
240// mountinfo's root field retains the original tree when a directory is bind
241// mounted elsewhere. No credential file is consulted to reject these aliases.
242func refusedMountAlias(path string, r HomeRules) bool {
243 data, e := os.ReadFile("/proc/self/mountinfo")
244 if e != nil {
245 return true
246 }
247 decode := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`)
248 for _, line := range strings.Split(string(data), "\n") {
249 fields := strings.Fields(line)
250 if len(fields) < 6 {
251 continue
252 }
253 root, mount := decode.Replace(fields[3]), decode.Replace(fields[4])
254 if withinPath(path, mount) {
255 rel, e := filepath.Rel(mount, path)
256 if e != nil || r.RefusesPath(filepath.Join(root, rel)) {
257 return true
258 }
259 }
260 }
261 return false
262}
263func credentialName(provider string) string {
264 if provider == "claude" {
265 return ".credentials.json"
266 }
267 return "auth.json"
268}
269func readPrivate(dir *os.File, name string) ([]byte, error) {
270 fd, e := unix.Openat(int(dir.Fd()), name, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK, 0)
271 if e != nil {
272 return nil, ErrAccountMaintenance
273 }
274 f := os.NewFile(uintptr(fd), name)
275 defer f.Close()
276 var st unix.Stat_t
277 if unix.Fstat(fd, &st) != nil || st.Nlink != 1 || st.Uid != uint32(os.Geteuid()) {
278 return nil, ErrPolicy
279 }
280 info, e := f.Stat()
281 if e != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > 1<<20 {
282 return nil, ErrPolicy
283 }
284 raw, e := io.ReadAll(io.LimitReader(f, (1<<20)+1))
285 if e != nil || len(raw) == 0 || len(raw) > 1<<20 {
286 return nil, ErrAccountMaintenance
287 }
288 return raw, nil
289}
290func (l *AccountLease) sourceUnchanged() bool {
291 f, e := pinDirectory(l.source.Home)
292 if e != nil {
293 return false
294 }
295 defer f.Close()
296 a, e := f.Stat()
297 if e != nil {
298 return false
299 }
300 b, e := l.dir.Stat()
301 return e == nil && os.SameFile(a, b) && privateDirectory(f)
302}
303func (l *AccountLease) snapshot() ([]byte, [32]byte, error) {
304 var zero [32]byte
305 if !l.sourceUnchanged() {
306 return nil, zero, accountContainment("source_directory")
307 }
308 metadata, e := readPrivate(l.dir, IdentityFile)
309 if e != nil {
310 return nil, zero, accountContainment("source_identity_file")
311 }
312 metadata, e = canonical(metadata)
313 if e != nil {
314 return nil, zero, ErrIdentity
315 }
316 var id Identity
317 dec := json.NewDecoder(bytes.NewReader(metadata))
318 dec.DisallowUnknownFields()
319 if dec.Decode(&id) != nil || dec.Decode(new(any)) != io.EOF || id != l.source.Expected {
320 return nil, zero, ErrIdentity
321 }
322 raw, e := readPrivate(l.dir, l.credentialFile())
323 if e != nil {
324 return nil, zero, accountContainment("source_credential")
325 }
326 if l.source.Token && (l.source.Provider != "claude" || !ValidToken(raw)) {
327 return nil, zero, accountContainment("source_credential")
328 }
329 if credentialsExpired(raw, time.Now()) {
330 return nil, zero, ErrAccountMaintenance
331 }
332 // This digest stays in memory. Stat identity detects atomic replacement
333 // even when the replacement contains identical credential bytes.
334 var stat unix.Stat_t
335 if unix.Fstatat(int(l.dir.Fd()), l.credentialFile(), &stat, unix.AT_SYMLINK_NOFOLLOW) != nil {
336 return nil, zero, ErrAccountMaintenance
337 }
338 state, _ := json.Marshal(struct {
339 Dev, Ino uint64
340 Mtime, Ctime unix.Timespec
341 }{uint64(stat.Dev), stat.Ino, stat.Mtim, stat.Ctim})
342 var native []byte
343 if l.source.Provider == "claude" {
344 native, e = claudeAccountMetadata(l.dir)
345 if e != nil {
346 return nil, zero, ErrIdentity
347 }
348 }
349 digest := sha256.Sum256(bytes.Join([][]byte{metadata, raw, state, native}, nil))
350 return raw, digest, nil
351}
352
353// credentialFile is the source home's credential: the CLI's own login
354// file, or a token home's token.
355func (l *AccountLease) credentialFile() string {
356 if l.source.Token {
357 return TokenFile
358 }
359 return credentialName(l.source.Provider)
360}
361func (l *AccountLease) runtimeDir() (*os.File, error) {
362 f, e := pinDirectory(l.runtime)
363 if e != nil {
364 return nil, accountContainment("runtime_directory")
365 }
366 info, e := f.Stat()
367 if e != nil || !os.SameFile(info, l.runtimeInfo) || !privateDirectory(f) {
368 f.Close()
369 return nil, accountContainment("runtime_directory")
370 }
371 return f, nil
372}
373func (l *AccountLease) configDir() (*os.File, error) {
374 f, e := pinDirectory(l.config)
375 if e != nil {
376 return nil, ErrPolicy
377 }
378 info, e := f.Stat()
379 if e != nil || !os.SameFile(info, l.configInfo) || !privateDirectory(f) {
380 f.Close()
381 return nil, ErrPolicy
382 }
383 return f, nil
384}
385func atomicPrivate(dir *os.File, name string, raw []byte) error {
386 var random [16]byte
387 if _, e := rand.Read(random[:]); e != nil {
388 return ErrAccountMaintenance
389 }
390 temp := ".equipo-" + hex.EncodeToString(random[:])
391 fd, e := unix.Openat(int(dir.Fd()), temp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600)
392 if e != nil {
393 return ErrAccountMaintenance
394 }
395 defer unix.Unlinkat(int(dir.Fd()), temp, 0)
396 f := os.NewFile(uintptr(fd), temp)
397 _, e = f.Write(raw)
398 if e == nil {
399 e = f.Sync()
400 }
401 closeErr := f.Close()
402 if e != nil || closeErr != nil {
403 return ErrAccountMaintenance
404 }
405 if unix.Renameat(int(dir.Fd()), temp, int(dir.Fd()), name) != nil || dir.Sync() != nil {
406 return ErrAccountMaintenance
407 }
408 return nil
409}
410func (l *AccountLease) stage() error {
411 raw, _, e := l.snapshot()
412 if e != nil {
413 return e
414 }
415 dir, e := l.runtimeDir()
416 if e != nil {
417 return e
418 }
419 defer dir.Close()
420 if l.source.Token {
421 return l.stageToken(dir, raw)
422 }
423 name := credentialName(l.source.Provider)
424 var stat unix.Stat_t
425 if e = unix.Fstatat(int(dir.Fd()), name, &stat, unix.AT_SYMLINK_NOFOLLOW); e == nil && stat.Mode&unix.S_IFMT != unix.S_IFREG {
426 return ErrContainment
427 }
428 if e != nil && e != unix.ENOENT {
429 return ErrContainment
430 }
431 if e = atomicPrivate(dir, name, raw); e != nil {
432 return e
433 }
434 metadata, _ := json.Marshal(l.source.Expected)
435 if e = atomicPrivate(dir, IdentityFile, metadata); e != nil {
436 return e
437 }
438 if l.source.Provider == "claude" {
439 native, e := claudeAccountMetadata(l.dir)
440 if e != nil {
441 return e
442 }
443 if e = atomicPrivate(dir, ".claude.json", native); e != nil {
444 return e
445 }
446 l.claudeIdentity = bytes.Clone(native)
447 }
448 l.runtimeGeneration = sha256.Sum256(raw)
449 return nil
450}
451func (l *AccountLease) runtimeSnapshot() ([]byte, error) {
452 dir, e := l.runtimeDir()
453 if e != nil {
454 return nil, e
455 }
456 defer dir.Close()
457 metadata, e := readPrivate(dir, IdentityFile)
458 if e != nil {
459 return nil, accountContainment("runtime_identity_file")
460 }
461 metadata, e = canonical(metadata)
462 var id Identity
463 if e != nil || json.Unmarshal(metadata, &id) != nil || id != l.source.Expected {
464 return nil, accountContainment("runtime_identity_changed")
465 }
466 if l.source.Provider == "claude" {
467 native, e := claudeAccountMetadata(dir)
468 if e != nil || !bytes.Equal(native, l.claudeIdentity) {
469 return nil, accountContainment("runtime_claude_identity")
470 }
471 }
472 if l.source.Token {
473 if e = tokenRuntimeClean(dir); e != nil {
474 return nil, e
475 }
476 return tokenRuntimeMarker, nil
477 }
478 raw, e := readPrivate(dir, credentialName(l.source.Provider))
479 if e != nil {
480 return nil, accountContainment("runtime_credential")
481 }
482 return raw, nil
483}
484func (l *AccountLease) binding() Binding {
485 b := l.source
486 b.CredentialHome = b.Home
487 b.Home = l.runtime
488 b.DedicatedHome = true
489 b.provenance = l
490 return b
491}
492func (l *AccountLease) Binding() Binding { l.mu.Lock(); defer l.mu.Unlock(); return l.binding() }
493func (l *AccountLease) Identity() Identity { return l.source.Expected }
494func (b Binding) VerifiedDedicatedHome() bool {
495 l := b.provenance
496 if l == nil {
497 return false
498 }
499 l.mu.Lock()
500 defer l.mu.Unlock()
501 return !l.closed && !l.contained && b == l.binding() && l.sourceUnchanged()
502}
503func (l *AccountLease) latch(err error) {
504 if errors.Is(err, ErrContainment) || errors.Is(err, ErrIdentity) {
505 l.contained = true
506 }
507}
508func (l *AccountLease) validate(ctx context.Context) (err error) {
509 if !l.sourceFreshUntil.IsZero() && !time.Now().Before(l.sourceFreshUntil) {
510 return ErrPreflightRequired
511 }
512 defer func() { l.latch(err) }()
513 if l.detached {
514 // The source may be refreshed by others once the lock is released;
515 // only the staged copy must stay exactly as staged.
516 if l.contained {
517 return accountContainment("latched")
518 }
519 if e := ctx.Err(); e != nil {
520 return e
521 }
522 if l.closed {
523 return ErrAccountMaintenance
524 }
525 raw, e := l.runtimeSnapshot()
526 if e != nil {
527 return e
528 }
529 if sha256.Sum256(raw) != l.runtimeGeneration {
530 return ErrRefreshPending
531 }
532 return nil
533 }
534 if l.contained {
535 return accountContainment("latched")
536 }
537 if e := ctx.Err(); e != nil {
538 return e
539 }
540 if l.closed || l.checking {
541 return ErrAccountMaintenance
542 }
543 _, generation, e := l.snapshot()
544 if e != nil {
545 l.ready = false
546 if l.active {
547 return accountContainment("active_source_snapshot")
548 }
549 return e
550 }
551 if generation != l.generation && l.active {
552 l.ready = false
553 return accountContainment("active_source_changed")
554 }
555 runtimeRaw, runtimeErr := l.runtimeSnapshot()
556 if runtimeErr != nil {
557 l.ready = false
558 return runtimeErr
559 }
560 if sha256.Sum256(runtimeRaw) != l.runtimeGeneration {
561 l.ready = false
562 return ErrRefreshPending
563 }
564 if generation != l.generation {
565 l.ready = false
566 return ErrPreflightRequired
567 }
568 if !l.ready {
569 return ErrPreflightRequired
570 }
571 return nil
572}
573func (l *AccountLease) Validate(ctx context.Context) error {
574 l.mu.Lock()
575 defer l.mu.Unlock()
576 return l.validate(ctx)
577}
578
579// Preflight restages only the selected login and checks CLI-observed identity.
580// Call it again after ErrPreflightRequired, before binding a new turn or resume.
581// A failed check leaves the account waiting for maintenance, never in failover.
582func (l *AccountLease) Preflight(ctx context.Context, probe func(context.Context, Binding) (Identity, error)) error {
583 return l.check(ctx, probe, false)
584}
585
586// CommitRefresh accepts a login atomically replaced by the harness in its
587// private runtime home. The adapter must observe the same identity without
588// prompting. A successful commit still requires Preflight before another turn.
589func (l *AccountLease) CommitRefresh(ctx context.Context, probe func(context.Context, Binding) (Identity, error)) error {
590 if !l.sourceFreshUntil.IsZero() || l.source.Token {
591 return ErrPolicy
592 }
593 return l.check(ctx, probe, true)
594}
595func (l *AccountLease) check(ctx context.Context, probe func(context.Context, Binding) (Identity, error), refresh bool) error {
596 l.mu.Lock()
597 if e := ctx.Err(); e != nil {
598 l.mu.Unlock()
599 return e
600 }
601 if l.contained {
602 l.mu.Unlock()
603 return ErrContainment
604 }
605 if l.closed || l.active || l.checking || probe == nil {
606 l.mu.Unlock()
607 return ErrAccountMaintenance
608 }
609 l.ready = false
610 _, before, e := l.snapshot()
611 if e != nil {
612 l.latch(e)
613 l.mu.Unlock()
614 return e
615 }
616 runtimeCurrent, runtimeErr := l.runtimeSnapshot()
617 if runtimeErr != nil {
618 l.contained = true
619 l.mu.Unlock()
620 return runtimeErr
621 }
622 if !refresh && sha256.Sum256(runtimeCurrent) != l.runtimeGeneration {
623 l.mu.Unlock()
624 return ErrRefreshPending
625 }
626 if !refresh {
627 e = l.stage()
628 if e != nil {
629 l.latch(e)
630 l.mu.Unlock()
631 return e
632 }
633 }
634 runtimeBefore, e := l.runtimeSnapshot()
635 if e != nil {
636 l.latch(e)
637 l.mu.Unlock()
638 return e
639 }
640 l.checking = true
641 b := l.binding()
642 l.mu.Unlock()
643 id, probeErr := probe(ctx, b)
644 l.mu.Lock()
645 defer l.mu.Unlock()
646 l.checking = false
647 if l.closed {
648 return ErrAccountMaintenance
649 }
650 if e = ctx.Err(); e != nil {
651 return e
652 }
653 if probeErr != nil {
654 return probeErr
655 }
656 if !observedIdentityMatches(l.source, id) {
657 l.contained = true
658 return ErrIdentity
659 }
660 _, after, e := l.snapshot()
661 if e != nil {
662 l.latch(e)
663 return e
664 }
665 if before != after {
666 return ErrPreflightRequired
667 }
668 runtimeAfter, e := l.runtimeSnapshot()
669 if e != nil {
670 l.latch(e)
671 return e
672 }
673 if !bytes.Equal(runtimeBefore, runtimeAfter) {
674 return ErrPreflightRequired
675 }
676 if refresh {
677 if before != l.generation {
678 return ErrPreflightRequired
679 }
680 if e = atomicPrivate(l.dir, credentialName(l.source.Provider), runtimeAfter); e != nil {
681 return e
682 }
683 l.runtimeGeneration = sha256.Sum256(runtimeAfter)
684 return nil
685 }
686 l.generation = after
687 l.runtimeGeneration = sha256.Sum256(runtimeAfter)
688 l.ready = true
689 return nil
690}
691func (l *AccountLease) BeginTurn(ctx context.Context) error {
692 l.mu.Lock()
693 defer l.mu.Unlock()
694 if l.active {
695 return ErrAccountBusy
696 }
697 if e := l.validate(ctx); e != nil {
698 return e
699 }
700 if e := l.validatePolicy(); e != nil {
701 return e
702 }
703 l.active = true
704 return nil
705}
706
707// ValidatePolicy rechecks policy sources before a turn or session resume.
708func (l *AccountLease) ValidatePolicy(ctx context.Context) error {
709 l.mu.Lock()
710 defer l.mu.Unlock()
711 if e := l.validate(ctx); e != nil {
712 return e
713 }
714 return l.validatePolicy()
715}
716func (l *AccountLease) validatePolicy() error {
717 if err := l.validateRuntimeEntries(); err != nil {
718 return err
719 }
720 if l.policy == nil {
721 return nil
722 }
723 return l.policy.ValidateSources(l.binding())
724}
725func (l *AccountLease) EndTurn(ctx context.Context) error {
726 l.mu.Lock()
727 defer l.mu.Unlock()
728 e := l.validate(ctx)
729 l.active = false
730 return e
731}
732func (l *AccountLease) Close() error {
733 l.mu.Lock()
734 defer l.mu.Unlock()
735 if l.closed {
736 return nil
737 }
738 l.closed = true
739 l.goMu.Lock()
740 l.goClosed = true
741 for _, pin := range l.goPins {
742 pin.file.Close()
743 }
744 l.goPins = nil
745 l.goMu.Unlock()
746 l.ready = false
747 clear(l.token)
748 l.token = nil
749 // Do not follow a runtime path replaced by someone else during cleanup.
750 info, e := os.Lstat(l.runtime)
751 var cleanup error
752 if e == nil && os.SameFile(info, l.runtimeInfo) {
753 cleanup = os.RemoveAll(l.runtime)
754 } else {
755 cleanup = ErrContainment
756 }
757 info, e = os.Lstat(l.config)
758 if e == nil && os.SameFile(info, l.configInfo) {
759 cleanup = errors.Join(cleanup, os.RemoveAll(l.config))
760 } else {
761 cleanup = errors.Join(cleanup, ErrContainment)
762 }
763 // A concurrent fork can retain this descriptor until exec, even with
764 // close-on-exec set. Release the lock before closing our copy.
765 unlock := unix.Flock(int(l.dir.Fd()), unix.LOCK_UN)
766 return errors.Join(cleanup, unlock, l.dir.Close())
767}
768
769func (l *AccountLease) validateLaunch() error {
770 l.mu.Lock()
771 defer l.mu.Unlock()
772 if l.closed {
773 return ErrAccountMaintenance
774 }
775 if l.checking {
776 _, _, e := l.snapshot()
777 return e
778 }
779 return l.validate(context.Background())
780}
781
782func makePrivateRoot(path string) (*os.File, error) {
783 missing := []string{}
784 parent := path
785 for {
786 _, e := os.Lstat(parent)
787 if e == nil {
788 break
789 }
790 if !os.IsNotExist(e) || parent == "/" {
791 return nil, ErrPolicy
792 }
793 missing = append(missing, filepath.Base(parent))
794 parent = filepath.Dir(parent)
795 }
796 dir, e := pinDirectory(parent)
797 if e != nil {
798 return nil, e
799 }
800 for i := len(missing) - 1; i >= 0; i-- {
801 if e = unix.Mkdirat(int(dir.Fd()), missing[i], 0700); e != nil && e != unix.EEXIST {
802 dir.Close()
803 return nil, ErrPolicy
804 }
805 fd, e := unix.Openat(int(dir.Fd()), missing[i], unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
806 dir.Close()
807 if e != nil {
808 return nil, ErrPolicy
809 }
810 dir = os.NewFile(uintptr(fd), path)
811 }
812 if !privateDirectory(dir) {
813 dir.Close()
814 return nil, ErrPolicy
815 }
816 return dir, nil
817}
818
819// AccountLease returns only the lease that created this exact runtime binding.
820func (b Binding) AccountLease() (*AccountLease, error) {
821 if !b.VerifiedDedicatedHome() {
822 return nil, ErrIdentity
823 }
824 return b.provenance, nil
825}
826
827func observedIdentityMatches(b Binding, observed Identity) bool {
828 if (b.Provider == "claude" || b.Provider == "codex") && observed.HomeID == "" {
829 return observed.AccountID == b.Expected.AccountID && observed.ProviderVersion == b.Expected.ProviderVersion
830 }
831 return observed == b.Expected
832}
833
834// Claude reads account metadata from its native config during auth status.
835// Import only identifiers, never user settings, trust entries, hooks or plugins.
836func claudeAccountMetadata(dir *os.File) ([]byte, error) {
837 var stat unix.Stat_t
838 if e := unix.Fstatat(int(dir.Fd()), ".claude.json", &stat, unix.AT_SYMLINK_NOFOLLOW); e == unix.ENOENT {
839 return []byte(`{}`), nil
840 } else if e != nil {
841 return nil, ErrIdentity
842 }
843 raw, e := readPrivate(dir, ".claude.json")
844 if e != nil {
845 return nil, e
846 }
847 raw, e = canonical(raw)
848 if e != nil {
849 return nil, e
850 }
851 var config map[string]json.RawMessage
852 if json.Unmarshal(raw, &config) != nil {
853 return nil, ErrIdentity
854 }
855 account, ok := config["oauthAccount"]
856 if !ok {
857 return []byte(`{}`), nil
858 }
859 var fields map[string]json.RawMessage
860 if json.Unmarshal(account, &fields) != nil || fields == nil {
861 return nil, ErrIdentity
862 }
863 selected := map[string]string{}
864 for _, key := range []string{"emailAddress", "accountUuid", "organizationUuid"} {
865 if raw, ok := fields[key]; ok {
866 var v string
867 if json.Unmarshal(raw, &v) != nil {
868 return nil, ErrIdentity
869 }
870 selected[key] = v
871 }
872 }
873 if selected["emailAddress"] == "" {
874 return nil, ErrIdentity
875 }
876 return json.Marshal(map[string]any{"oauthAccount": selected, "hasCompletedOnboarding": true})
877}
878
879// PreflightFingerprint identifies the current source generation without granting authority.
880func (l *AccountLease) PreflightFingerprint(ctx context.Context) (string, error) {
881 l.mu.Lock()
882 defer l.mu.Unlock()
883 if err := ctx.Err(); err != nil {
884 return "", err
885 }
886 if l.closed || l.contained {
887 return "", ErrContainment
888 }
889 _, generation, err := l.snapshot()
890 if err != nil {
891 return "", err
892 }
893 info, err := l.dir.Stat()
894 if err != nil {
895 return "", err
896 }
897 raw, _ := json.Marshal([]any{l.source, hex.EncodeToString(generation[:]), info.Sys()})
898 sum := sha256.Sum256(raw)
899 return hex.EncodeToString(sum[:]), nil
900}
901
902// containmentError is ErrContainment with its category, always a literal.
903type containmentError struct{ reason string }
904
905func (e containmentError) Error() string { return string(ErrContainment) + ": " + e.reason }
906func (e containmentError) Unwrap() error { return ErrContainment }
907func accountContainment(reason string) error { return containmentError{reason} }
908
909// ContainmentReason is a containment refusal's category, safe to log; "" otherwise.
910func ContainmentReason(err error) string { var c containmentError; errors.As(err, &c); return c.reason }
911