package provider import ( "bytes" "context" "crypto/rand" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "os" "os/user" "path/filepath" "strconv" "strings" "sync" "time" "golang.org/x/sys/unix" ) const IdentityFile = "equipo-identity.json" const ( ErrAccountBusy Error = "provider_account_busy" ErrAccountMaintenance Error = "provider_account_maintenance" ErrPreflightRequired Error = "provider_preflight_required" ErrRefreshPending Error = "provider_refresh_pending" ErrContainment Error = "provider_account_containment" ErrPolicy Error = "provider_policy_rejected" ) // HomeRules describes forbidden credential sources. Tests inject owned fake // directories; production also compares directory inodes to catch bind aliases. type HomeRules struct { InteractiveHomes []string unavailable bool } func DefaultHomeRules() HomeRules { return homeRules(user.LookupId, os.Getenv) } func homeRules(lookup func(string) (*user.User, error), getenv func(string) string) HomeRules { u, e := lookup(strconv.Itoa(os.Geteuid())) if e != nil || u == nil || !cleanPath(u.HomeDir) { return HomeRules{unavailable: true} } homes := []string{filepath.Join(u.HomeDir, ".claude"), filepath.Join(u.HomeDir, ".codex")} for _, key := range []string{"CODEX_HOME", "CLAUDE_CONFIG_DIR"} { if path := getenv(key); path != "" { path, e = filepath.Abs(path) if e != nil { return HomeRules{unavailable: true} } homes = append(homes, path) if real, e := filepath.EvalSymlinks(path); e == nil { homes = append(homes, real) } } } return HomeRules{InteractiveHomes: homes} } func withinPath(path, root string) bool { return path == root || strings.HasPrefix(path, root+"/") } func cleanPath(path string) bool { return filepath.IsAbs(path) && filepath.Clean(path) == path && path != "/" } func (r HomeRules) RefusesPath(path string) bool { if r.unavailable || !cleanPath(path) { return true } if strings.Contains(path+"/", "/.paseo/zerosub/homes/") { return true } for _, home := range r.InteractiveHomes { if withinPath(path, home) { return true } } return false } func (r HomeRules) refusedInode(info os.FileInfo) bool { for _, home := range r.InteractiveHomes { if other, e := os.Stat(home); e == nil && os.SameFile(info, other) { return true } } return false } func pinDirectory(path string) (*os.File, error) { if !cleanPath(path) { return nil, ErrPolicy } fd, e := openNoLinks(path, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC) if e != nil { return nil, ErrPolicy } return os.NewFile(uintptr(fd), path), nil } func privateDirectory(f *os.File) bool { info, e := f.Stat() return e == nil && info.IsDir() && info.Mode().Perm() == 0700 } // AccountLease holds a directory flock until Close, including across preflight, // all turns. Claude's identity is trust-on-first-use: Paul // confirms CLI-observed metadata at enrolment. It is not remote attestation. type AccountLease struct { goMu sync.Mutex goPins map[Mount]goPin goClosed bool mu sync.Mutex sourceFreshUntil time.Time source Binding rules HomeRules dir *os.File runtime string config string configInfo os.FileInfo policy *Policy runtimeInfo os.FileInfo generation [32]byte ready, active, closed bool checking bool // detached copies released the source lock after staging (copy.go). detached bool contained bool runtimeGeneration [32]byte claudeIdentity []byte // token is a token home's credential, held for the launch // environment only (LaunchSecretEnv); never staged in the copy. token []byte } func OpenAccount(ctx context.Context, b Binding) (*AccountLease, error) { return openAccount(ctx, b, DefaultHomeRules()) } // OpenAccountRefreshing runs the official CLI in the locked source home before // making a runtime copy. The lock remains held through the attempt. func OpenAccountRefreshing(ctx context.Context, b Binding, refresh func(context.Context, Binding) (Identity, error)) (*AccountLease, error) { return openAccountRefreshing(ctx, b, DefaultHomeRules(), refresh) } func openAccount(ctx context.Context, b Binding, r HomeRules) (*AccountLease, error) { return openAccountRefreshing(ctx, b, r, nil) } func openAccountRefreshing(ctx context.Context, b Binding, r HomeRules, refresh func(context.Context, Binding) (Identity, error)) (_ *AccountLease, err error) { if e := ctx.Err(); e != nil { return nil, e } 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) { return nil, ErrIdentity } // Resolve before opening any login file. Also inspect mount roots for aliases // of forbidden trees; inode comparison below handles explicit interactive homes. real, e := filepath.EvalSymlinks(b.Home) if e != nil || real != b.Home || r.RefusesPath(real) || refusedMountAlias(b.Home, r) { return nil, ErrPolicy } dir, e := pinDirectory(b.Home) if e != nil { return nil, e } defer func() { if err != nil { // As in Close: a concurrent fork can hold this descriptor until // exec, and the lock with it, so a caller's next try would find // the home busy. Release the lock before closing our copy. unix.Flock(int(dir.Fd()), unix.LOCK_UN) dir.Close() } }() if !privateDirectory(dir) { return nil, ErrPolicy } for parent := b.Home; parent != "/"; parent = filepath.Dir(parent) { info, e := os.Stat(parent) if e != nil || r.refusedInode(info) { return nil, ErrPolicy } } if e = unix.Flock(int(dir.Fd()), unix.LOCK_EX|unix.LOCK_NB); e != nil { return nil, ErrAccountBusy } l := &AccountLease{source: b, dir: dir, rules: r} _, _, e = l.snapshot() if e != nil { return nil, e } if r.RefusesPath(b.RuntimeRoot) || !cleanPath(b.RuntimeRoot) || withinPath(b.RuntimeRoot, b.Home) || withinPath(b.Home, b.RuntimeRoot) { return nil, ErrPolicy } if refresh != nil { id, err := refresh(ctx, b) if err != nil { return nil, err } if !observedIdentityMatches(b, id) { return nil, ErrIdentity } if _, _, err = l.snapshot(); err != nil { return nil, err } l.sourceFreshUntil = time.Now().Add(25 * time.Minute) } root, e := makePrivateRoot(b.RuntimeRoot) if e != nil { return nil, e } defer root.Close() if !privateDirectory(root) { return nil, ErrPolicy } l.runtime, e = os.MkdirTemp(b.RuntimeRoot, "account-") if e != nil { return nil, ErrPolicy } l.runtimeInfo, e = os.Stat(l.runtime) if e != nil { os.RemoveAll(l.runtime) return nil, ErrPolicy } if e = l.stage(); e != nil { os.RemoveAll(l.runtime) return nil, e } l.config, e = os.MkdirTemp(b.RuntimeRoot, "config-") if e != nil { os.RemoveAll(l.runtime) return nil, ErrPolicy } l.configInfo, e = os.Stat(l.config) if e != nil { os.RemoveAll(l.config) os.RemoveAll(l.runtime) return nil, ErrPolicy } return l, nil } // mountinfo's root field retains the original tree when a directory is bind // mounted elsewhere. No credential file is consulted to reject these aliases. func refusedMountAlias(path string, r HomeRules) bool { data, e := os.ReadFile("/proc/self/mountinfo") if e != nil { return true } decode := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`) for _, line := range strings.Split(string(data), "\n") { fields := strings.Fields(line) if len(fields) < 6 { continue } root, mount := decode.Replace(fields[3]), decode.Replace(fields[4]) if withinPath(path, mount) { rel, e := filepath.Rel(mount, path) if e != nil || r.RefusesPath(filepath.Join(root, rel)) { return true } } } return false } func credentialName(provider string) string { if provider == "claude" { return ".credentials.json" } return "auth.json" } func readPrivate(dir *os.File, name string) ([]byte, error) { fd, e := unix.Openat(int(dir.Fd()), name, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC|unix.O_NONBLOCK, 0) if e != nil { return nil, ErrAccountMaintenance } f := os.NewFile(uintptr(fd), name) defer f.Close() var st unix.Stat_t if unix.Fstat(fd, &st) != nil || st.Nlink != 1 || st.Uid != uint32(os.Geteuid()) { return nil, ErrPolicy } info, e := f.Stat() if e != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 || info.Size() > 1<<20 { return nil, ErrPolicy } raw, e := io.ReadAll(io.LimitReader(f, (1<<20)+1)) if e != nil || len(raw) == 0 || len(raw) > 1<<20 { return nil, ErrAccountMaintenance } return raw, nil } func (l *AccountLease) sourceUnchanged() bool { f, e := pinDirectory(l.source.Home) if e != nil { return false } defer f.Close() a, e := f.Stat() if e != nil { return false } b, e := l.dir.Stat() return e == nil && os.SameFile(a, b) && privateDirectory(f) } func (l *AccountLease) snapshot() ([]byte, [32]byte, error) { var zero [32]byte if !l.sourceUnchanged() { return nil, zero, accountContainment("source_directory") } metadata, e := readPrivate(l.dir, IdentityFile) if e != nil { return nil, zero, accountContainment("source_identity_file") } metadata, e = canonical(metadata) if e != nil { return nil, zero, ErrIdentity } var id Identity dec := json.NewDecoder(bytes.NewReader(metadata)) dec.DisallowUnknownFields() if dec.Decode(&id) != nil || dec.Decode(new(any)) != io.EOF || id != l.source.Expected { return nil, zero, ErrIdentity } raw, e := readPrivate(l.dir, l.credentialFile()) if e != nil { return nil, zero, accountContainment("source_credential") } if l.source.Token && (l.source.Provider != "claude" || !ValidToken(raw)) { return nil, zero, accountContainment("source_credential") } if credentialsExpired(raw, time.Now()) { return nil, zero, ErrAccountMaintenance } // This digest stays in memory. Stat identity detects atomic replacement // even when the replacement contains identical credential bytes. var stat unix.Stat_t if unix.Fstatat(int(l.dir.Fd()), l.credentialFile(), &stat, unix.AT_SYMLINK_NOFOLLOW) != nil { return nil, zero, ErrAccountMaintenance } state, _ := json.Marshal(struct { Dev, Ino uint64 Mtime, Ctime unix.Timespec }{uint64(stat.Dev), stat.Ino, stat.Mtim, stat.Ctim}) var native []byte if l.source.Provider == "claude" { native, e = claudeAccountMetadata(l.dir) if e != nil { return nil, zero, ErrIdentity } } digest := sha256.Sum256(bytes.Join([][]byte{metadata, raw, state, native}, nil)) return raw, digest, nil } // credentialFile is the source home's credential: the CLI's own login // file, or a token home's token. func (l *AccountLease) credentialFile() string { if l.source.Token { return TokenFile } return credentialName(l.source.Provider) } func (l *AccountLease) runtimeDir() (*os.File, error) { f, e := pinDirectory(l.runtime) if e != nil { return nil, accountContainment("runtime_directory") } info, e := f.Stat() if e != nil || !os.SameFile(info, l.runtimeInfo) || !privateDirectory(f) { f.Close() return nil, accountContainment("runtime_directory") } return f, nil } func (l *AccountLease) configDir() (*os.File, error) { f, e := pinDirectory(l.config) if e != nil { return nil, ErrPolicy } info, e := f.Stat() if e != nil || !os.SameFile(info, l.configInfo) || !privateDirectory(f) { f.Close() return nil, ErrPolicy } return f, nil } func atomicPrivate(dir *os.File, name string, raw []byte) error { var random [16]byte if _, e := rand.Read(random[:]); e != nil { return ErrAccountMaintenance } temp := ".equipo-" + hex.EncodeToString(random[:]) fd, e := unix.Openat(int(dir.Fd()), temp, unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) if e != nil { return ErrAccountMaintenance } defer unix.Unlinkat(int(dir.Fd()), temp, 0) f := os.NewFile(uintptr(fd), temp) _, e = f.Write(raw) if e == nil { e = f.Sync() } closeErr := f.Close() if e != nil || closeErr != nil { return ErrAccountMaintenance } if unix.Renameat(int(dir.Fd()), temp, int(dir.Fd()), name) != nil || dir.Sync() != nil { return ErrAccountMaintenance } return nil } func (l *AccountLease) stage() error { raw, _, e := l.snapshot() if e != nil { return e } dir, e := l.runtimeDir() if e != nil { return e } defer dir.Close() if l.source.Token { return l.stageToken(dir, raw) } name := credentialName(l.source.Provider) var stat unix.Stat_t if e = unix.Fstatat(int(dir.Fd()), name, &stat, unix.AT_SYMLINK_NOFOLLOW); e == nil && stat.Mode&unix.S_IFMT != unix.S_IFREG { return ErrContainment } if e != nil && e != unix.ENOENT { return ErrContainment } if e = atomicPrivate(dir, name, raw); e != nil { return e } metadata, _ := json.Marshal(l.source.Expected) if e = atomicPrivate(dir, IdentityFile, metadata); e != nil { return e } if l.source.Provider == "claude" { native, e := claudeAccountMetadata(l.dir) if e != nil { return e } if e = atomicPrivate(dir, ".claude.json", native); e != nil { return e } l.claudeIdentity = bytes.Clone(native) } l.runtimeGeneration = sha256.Sum256(raw) return nil } func (l *AccountLease) runtimeSnapshot() ([]byte, error) { dir, e := l.runtimeDir() if e != nil { return nil, e } defer dir.Close() metadata, e := readPrivate(dir, IdentityFile) if e != nil { return nil, accountContainment("runtime_identity_file") } metadata, e = canonical(metadata) var id Identity if e != nil || json.Unmarshal(metadata, &id) != nil || id != l.source.Expected { return nil, accountContainment("runtime_identity_changed") } if l.source.Provider == "claude" { native, e := claudeAccountMetadata(dir) if e != nil || !bytes.Equal(native, l.claudeIdentity) { return nil, accountContainment("runtime_claude_identity") } } if l.source.Token { if e = tokenRuntimeClean(dir); e != nil { return nil, e } return tokenRuntimeMarker, nil } raw, e := readPrivate(dir, credentialName(l.source.Provider)) if e != nil { return nil, accountContainment("runtime_credential") } return raw, nil } func (l *AccountLease) binding() Binding { b := l.source b.CredentialHome = b.Home b.Home = l.runtime b.DedicatedHome = true b.provenance = l return b } func (l *AccountLease) Binding() Binding { l.mu.Lock(); defer l.mu.Unlock(); return l.binding() } func (l *AccountLease) Identity() Identity { return l.source.Expected } func (b Binding) VerifiedDedicatedHome() bool { l := b.provenance if l == nil { return false } l.mu.Lock() defer l.mu.Unlock() return !l.closed && !l.contained && b == l.binding() && l.sourceUnchanged() } func (l *AccountLease) latch(err error) { if errors.Is(err, ErrContainment) || errors.Is(err, ErrIdentity) { l.contained = true } } func (l *AccountLease) validate(ctx context.Context) (err error) { if !l.sourceFreshUntil.IsZero() && !time.Now().Before(l.sourceFreshUntil) { return ErrPreflightRequired } defer func() { l.latch(err) }() if l.detached { // The source may be refreshed by others once the lock is released; // only the staged copy must stay exactly as staged. if l.contained { return accountContainment("latched") } if e := ctx.Err(); e != nil { return e } if l.closed { return ErrAccountMaintenance } raw, e := l.runtimeSnapshot() if e != nil { return e } if sha256.Sum256(raw) != l.runtimeGeneration { return ErrRefreshPending } return nil } if l.contained { return accountContainment("latched") } if e := ctx.Err(); e != nil { return e } if l.closed || l.checking { return ErrAccountMaintenance } _, generation, e := l.snapshot() if e != nil { l.ready = false if l.active { return accountContainment("active_source_snapshot") } return e } if generation != l.generation && l.active { l.ready = false return accountContainment("active_source_changed") } runtimeRaw, runtimeErr := l.runtimeSnapshot() if runtimeErr != nil { l.ready = false return runtimeErr } if sha256.Sum256(runtimeRaw) != l.runtimeGeneration { l.ready = false return ErrRefreshPending } if generation != l.generation { l.ready = false return ErrPreflightRequired } if !l.ready { return ErrPreflightRequired } return nil } func (l *AccountLease) Validate(ctx context.Context) error { l.mu.Lock() defer l.mu.Unlock() return l.validate(ctx) } // Preflight restages only the selected login and checks CLI-observed identity. // Call it again after ErrPreflightRequired, before binding a new turn or resume. // A failed check leaves the account waiting for maintenance, never in failover. func (l *AccountLease) Preflight(ctx context.Context, probe func(context.Context, Binding) (Identity, error)) error { return l.check(ctx, probe, false) } // CommitRefresh accepts a login atomically replaced by the harness in its // private runtime home. The adapter must observe the same identity without // prompting. A successful commit still requires Preflight before another turn. func (l *AccountLease) CommitRefresh(ctx context.Context, probe func(context.Context, Binding) (Identity, error)) error { if !l.sourceFreshUntil.IsZero() || l.source.Token { return ErrPolicy } return l.check(ctx, probe, true) } func (l *AccountLease) check(ctx context.Context, probe func(context.Context, Binding) (Identity, error), refresh bool) error { l.mu.Lock() if e := ctx.Err(); e != nil { l.mu.Unlock() return e } if l.contained { l.mu.Unlock() return ErrContainment } if l.closed || l.active || l.checking || probe == nil { l.mu.Unlock() return ErrAccountMaintenance } l.ready = false _, before, e := l.snapshot() if e != nil { l.latch(e) l.mu.Unlock() return e } runtimeCurrent, runtimeErr := l.runtimeSnapshot() if runtimeErr != nil { l.contained = true l.mu.Unlock() return runtimeErr } if !refresh && sha256.Sum256(runtimeCurrent) != l.runtimeGeneration { l.mu.Unlock() return ErrRefreshPending } if !refresh { e = l.stage() if e != nil { l.latch(e) l.mu.Unlock() return e } } runtimeBefore, e := l.runtimeSnapshot() if e != nil { l.latch(e) l.mu.Unlock() return e } l.checking = true b := l.binding() l.mu.Unlock() id, probeErr := probe(ctx, b) l.mu.Lock() defer l.mu.Unlock() l.checking = false if l.closed { return ErrAccountMaintenance } if e = ctx.Err(); e != nil { return e } if probeErr != nil { return probeErr } if !observedIdentityMatches(l.source, id) { l.contained = true return ErrIdentity } _, after, e := l.snapshot() if e != nil { l.latch(e) return e } if before != after { return ErrPreflightRequired } runtimeAfter, e := l.runtimeSnapshot() if e != nil { l.latch(e) return e } if !bytes.Equal(runtimeBefore, runtimeAfter) { return ErrPreflightRequired } if refresh { if before != l.generation { return ErrPreflightRequired } if e = atomicPrivate(l.dir, credentialName(l.source.Provider), runtimeAfter); e != nil { return e } l.runtimeGeneration = sha256.Sum256(runtimeAfter) return nil } l.generation = after l.runtimeGeneration = sha256.Sum256(runtimeAfter) l.ready = true return nil } func (l *AccountLease) BeginTurn(ctx context.Context) error { l.mu.Lock() defer l.mu.Unlock() if l.active { return ErrAccountBusy } if e := l.validate(ctx); e != nil { return e } if e := l.validatePolicy(); e != nil { return e } l.active = true return nil } // ValidatePolicy rechecks policy sources before a turn or session resume. func (l *AccountLease) ValidatePolicy(ctx context.Context) error { l.mu.Lock() defer l.mu.Unlock() if e := l.validate(ctx); e != nil { return e } return l.validatePolicy() } func (l *AccountLease) validatePolicy() error { if err := l.validateRuntimeEntries(); err != nil { return err } if l.policy == nil { return nil } return l.policy.ValidateSources(l.binding()) } func (l *AccountLease) EndTurn(ctx context.Context) error { l.mu.Lock() defer l.mu.Unlock() e := l.validate(ctx) l.active = false return e } func (l *AccountLease) Close() error { l.mu.Lock() defer l.mu.Unlock() if l.closed { return nil } l.closed = true l.goMu.Lock() l.goClosed = true for _, pin := range l.goPins { pin.file.Close() } l.goPins = nil l.goMu.Unlock() l.ready = false clear(l.token) l.token = nil // Do not follow a runtime path replaced by someone else during cleanup. info, e := os.Lstat(l.runtime) var cleanup error if e == nil && os.SameFile(info, l.runtimeInfo) { cleanup = os.RemoveAll(l.runtime) } else { cleanup = ErrContainment } info, e = os.Lstat(l.config) if e == nil && os.SameFile(info, l.configInfo) { cleanup = errors.Join(cleanup, os.RemoveAll(l.config)) } else { cleanup = errors.Join(cleanup, ErrContainment) } // A concurrent fork can retain this descriptor until exec, even with // close-on-exec set. Release the lock before closing our copy. unlock := unix.Flock(int(l.dir.Fd()), unix.LOCK_UN) return errors.Join(cleanup, unlock, l.dir.Close()) } func (l *AccountLease) validateLaunch() error { l.mu.Lock() defer l.mu.Unlock() if l.closed { return ErrAccountMaintenance } if l.checking { _, _, e := l.snapshot() return e } return l.validate(context.Background()) } func makePrivateRoot(path string) (*os.File, error) { missing := []string{} parent := path for { _, e := os.Lstat(parent) if e == nil { break } if !os.IsNotExist(e) || parent == "/" { return nil, ErrPolicy } missing = append(missing, filepath.Base(parent)) parent = filepath.Dir(parent) } dir, e := pinDirectory(parent) if e != nil { return nil, e } for i := len(missing) - 1; i >= 0; i-- { if e = unix.Mkdirat(int(dir.Fd()), missing[i], 0700); e != nil && e != unix.EEXIST { dir.Close() return nil, ErrPolicy } fd, e := unix.Openat(int(dir.Fd()), missing[i], unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) dir.Close() if e != nil { return nil, ErrPolicy } dir = os.NewFile(uintptr(fd), path) } if !privateDirectory(dir) { dir.Close() return nil, ErrPolicy } return dir, nil } // AccountLease returns only the lease that created this exact runtime binding. func (b Binding) AccountLease() (*AccountLease, error) { if !b.VerifiedDedicatedHome() { return nil, ErrIdentity } return b.provenance, nil } func observedIdentityMatches(b Binding, observed Identity) bool { if (b.Provider == "claude" || b.Provider == "codex") && observed.HomeID == "" { return observed.AccountID == b.Expected.AccountID && observed.ProviderVersion == b.Expected.ProviderVersion } return observed == b.Expected } // Claude reads account metadata from its native config during auth status. // Import only identifiers, never user settings, trust entries, hooks or plugins. func claudeAccountMetadata(dir *os.File) ([]byte, error) { var stat unix.Stat_t if e := unix.Fstatat(int(dir.Fd()), ".claude.json", &stat, unix.AT_SYMLINK_NOFOLLOW); e == unix.ENOENT { return []byte(`{}`), nil } else if e != nil { return nil, ErrIdentity } raw, e := readPrivate(dir, ".claude.json") if e != nil { return nil, e } raw, e = canonical(raw) if e != nil { return nil, e } var config map[string]json.RawMessage if json.Unmarshal(raw, &config) != nil { return nil, ErrIdentity } account, ok := config["oauthAccount"] if !ok { return []byte(`{}`), nil } var fields map[string]json.RawMessage if json.Unmarshal(account, &fields) != nil || fields == nil { return nil, ErrIdentity } selected := map[string]string{} for _, key := range []string{"emailAddress", "accountUuid", "organizationUuid"} { if raw, ok := fields[key]; ok { var v string if json.Unmarshal(raw, &v) != nil { return nil, ErrIdentity } selected[key] = v } } if selected["emailAddress"] == "" { return nil, ErrIdentity } return json.Marshal(map[string]any{"oauthAccount": selected, "hasCompletedOnboarding": true}) } // PreflightFingerprint identifies the current source generation without granting authority. func (l *AccountLease) PreflightFingerprint(ctx context.Context) (string, error) { l.mu.Lock() defer l.mu.Unlock() if err := ctx.Err(); err != nil { return "", err } if l.closed || l.contained { return "", ErrContainment } _, generation, err := l.snapshot() if err != nil { return "", err } info, err := l.dir.Stat() if err != nil { return "", err } raw, _ := json.Marshal([]any{l.source, hex.EncodeToString(generation[:]), info.Sys()}) sum := sha256.Sum256(raw) return hex.EncodeToString(sum[:]), nil } // containmentError is ErrContainment with its category, always a literal. type containmentError struct{ reason string } func (e containmentError) Error() string { return string(ErrContainment) + ": " + e.reason } func (e containmentError) Unwrap() error { return ErrContainment } func accountContainment(reason string) error { return containmentError{reason} } // ContainmentReason is a containment refusal's category, safe to log; "" otherwise. func ContainmentReason(err error) string { var c containmentError; errors.As(err, &c); return c.reason }