From cd535929916994fdd210d4b0ea181c8752118c63 Mon Sep 17 00:00:00 2001 From: Daniel J Walsh Date: Wed, 4 Sep 2024 06:20:22 -0400 Subject: [PATCH] Treat XDG_CONFIG_HOME and $HOME/.config the same way Currently we handle XDG_CONFIG_HOME and the fallback $HOME/.config differently. We create the later if it does not exist and verify that it is owned by the current user. This patch makes XDG_CONFIG_HOME follow the same pattern. Signed-off-by: Daniel J Walsh --- pkg/homedir/homedir_unix.go | 40 +++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/pkg/homedir/homedir_unix.go b/pkg/homedir/homedir_unix.go index 45be87659e..13dc1496e7 100644 --- a/pkg/homedir/homedir_unix.go +++ b/pkg/homedir/homedir_unix.go @@ -101,11 +101,24 @@ func isWriteableOnlyByOwner(perm os.FileMode) bool { return (perm & 0o722) == 0o700 } -// GetConfigHome returns XDG_CONFIG_HOME. -// GetConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. -// +// ConfigHome returns XDG_CONFIG_HOME. +// ConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. +// Verifies ownership of config directory matches the current process or +// returns error. // See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html func GetConfigHome() (string, error) { + rootlessConfigHomeDir, rootlessConfigHomeDirError = ConfigHome() + if rootlessConfigHomeDirError == nil { + _ = os.MkdirAll(rootlessConfigHomeDir, 0o700) + } + + return rootlessConfigHomeDir, rootlessConfigHomeDirError +} + +// ConfigHome returns XDG_CONFIG_HOME. (Deprecated) +// ConfigHome returns $HOME/.config and nil error if XDG_CONFIG_HOME is not set. +// See also https://standards.freedesktop.org/basedir-spec/latest/ar01s03.html +func ConfigHome() (string, error) { rootlessConfigHomeDirOnce.Do(func() { cfgHomeDir := os.Getenv("XDG_CONFIG_HOME") if cfgHomeDir == "" { @@ -115,18 +128,15 @@ func GetConfigHome() (string, error) { rootlessConfigHomeDirError = fmt.Errorf("cannot resolve %s: %w", home, err) return } - tmpDir := filepath.Join(resolvedHome, ".config") - _ = os.MkdirAll(tmpDir, 0o700) - st, err := os.Stat(tmpDir) - if err != nil { - rootlessConfigHomeDirError = err - return - } else if int(st.Sys().(*syscall.Stat_t).Uid) == os.Geteuid() { - cfgHomeDir = tmpDir - } else { - rootlessConfigHomeDirError = fmt.Errorf("path %q exists and it is not owned by the current user", tmpDir) - return - } + cfgHomeDir = filepath.Join(resolvedHome, ".config") + } + st, err := os.Stat(cfgHomeDir) + if err != nil { + rootlessConfigHomeDirError = err + return + } else if int(st.Sys().(*syscall.Stat_t).Uid) != os.Geteuid() { + rootlessConfigHomeDirError = fmt.Errorf("path %q exists and it is not owned by the current user", tmpDir) + return } rootlessConfigHomeDir = cfgHomeDir })