package provider import ( "context" "crypto/sha256" "encoding/json" "errors" "time" "golang.org/x/sys/unix" ) // CopyLifetime is how long a runtime credential copy may be used after the // source home was refreshed. A copy never writes back and cannot reach // refresh hosts, so a process lives at most one copy. const CopyLifetime = 25 * time.Minute // OpenRuntimeCopy refreshes the source home with the official CLI under // the source lock, stages a runtime copy and releases the lock. The lock is // held only for refresh and staging: copies cannot refresh, so maintenance // cannot race them. A busy source is retried until wait passes. func OpenRuntimeCopy(ctx context.Context, b Binding, refresh func(context.Context, Binding) (Identity, error), wait time.Duration) (*AccountLease, error) { if refresh == nil { return nil, ErrPolicy } deadline := time.Now().Add(wait) for { l, err := openAccountRefreshing(ctx, b, DefaultHomeRules(), refresh) if err == nil { if err = l.detach(); err != nil { l.Close() return nil, err } return l, nil } if !errors.Is(err, ErrAccountBusy) || time.Now().After(deadline) { return nil, err } select { case <-ctx.Done(): return nil, ctx.Err() case <-time.After(500 * time.Millisecond): } } } func (l *AccountLease) detach() error { l.mu.Lock() defer l.mu.Unlock() raw, generation, err := l.snapshot() if err != nil { return err } until := l.sourceFreshUntil if expires := credentialsExpireAt(raw); !expires.IsZero() && expires.Before(until) { until = expires } l.sourceFreshUntil = until l.generation = generation l.detached = true l.ready = true return unix.Flock(int(l.dir.Fd()), unix.LOCK_UN) } // FreshUntil is when this runtime copy must stop being used. func (l *AccountLease) FreshUntil() time.Time { l.mu.Lock() defer l.mu.Unlock() return l.sourceFreshUntil } // CheckCopy is the check before each turn on a detached copy: still fresh, // the runtime credential unchanged, only expected runtime entries, and the // policy's generated and pinned files unchanged. func (l *AccountLease) CheckCopy(ctx context.Context) error { l.mu.Lock() defer l.mu.Unlock() if !l.detached || l.closed { return ErrAccountMaintenance } if err := ctx.Err(); err != nil { return err } if l.contained { return accountContainment("latched") } if !time.Now().Before(l.sourceFreshUntil) { return ErrPreflightRequired } raw, err := l.runtimeSnapshot() if err != nil { l.latch(err) return err } if sha256.Sum256(raw) != l.runtimeGeneration { return ErrRefreshPending } if err = l.validatePolicy(); err != nil { l.latch(err) return err } return nil } func credentialsExpireAt(raw []byte) time.Time { var v struct { Claude struct { ExpiresAt int64 `json:"expiresAt"` } `json:"claudeAiOauth"` } if json.Unmarshal(raw, &v) != nil || v.Claude.ExpiresAt <= 0 { return time.Time{} } return time.UnixMilli(v.Claude.ExpiresAt) }