From 522f9ced7b90a1bbcdbac7949bb2ad7d8f8b8d4b Mon Sep 17 00:00:00 2001 From: Giuseppe Scrivano Date: Fri, 24 Apr 2026 17:06:54 +0000 Subject: [PATCH] unshare: do not cache HomeDir() when HOME is set Only cache the user.LookupId() fallback path, not the $HOME environment variable check. This allows tests that set a custom $HOME per test to work correctly, while still preserving the performance optimization for the slow NSS/LDAP lookup path. Closes: https://github.com/containers/container-libs/issues/787 Signed-off-by: Giuseppe Scrivano --- storage/pkg/unshare/unshare.go | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/storage/pkg/unshare/unshare.go b/storage/pkg/unshare/unshare.go index 00f397f350..58eba5487c 100644 --- a/storage/pkg/unshare/unshare.go +++ b/storage/pkg/unshare/unshare.go @@ -7,26 +7,18 @@ import ( "sync" ) -var ( - homeDirOnce sync.Once - homeDirErr error - homeDir string -) +var lookupHomeDir = sync.OnceValues(func() (string, error) { + usr, err := user.LookupId(fmt.Sprintf("%d", GetRootlessUID())) + if err != nil { + return "", fmt.Errorf("unable to resolve HOME directory: %w", err) + } + return usr.HomeDir, nil +}) // HomeDir returns the home directory for the current user. func HomeDir() (string, error) { - homeDirOnce.Do(func() { - home := os.Getenv("HOME") - if home == "" { - usr, err := user.LookupId(fmt.Sprintf("%d", GetRootlessUID())) - if err != nil { - homeDir, homeDirErr = "", fmt.Errorf("unable to resolve HOME directory: %w", err) - return - } - homeDir, homeDirErr = usr.HomeDir, nil - return - } - homeDir, homeDirErr = home, nil - }) - return homeDir, homeDirErr + if home := os.Getenv("HOME"); home != "" { + return home, nil + } + return lookupHomeDir() }