Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resolve homedir of sudo user #1412

Merged
merged 4 commits into from
May 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions clab/authz_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (c *CLab) CreateAuthzKeysFile() error {

log.Debugf("extracted %d keys from ssh-agent", len(keys))
for _, k := range keys {
b.WriteString(k + "\n")
addKeyToBuffer(b, k)
}

for _, fn := range all {
Expand Down Expand Up @@ -79,8 +79,7 @@ func addKeyToBuffer(b *bytes.Buffer, key string) {
return
}

key = elems[0] + " " + elems[1]
if !strings.Contains(b.String(), key) {
if !strings.Contains(b.String(), elems[1]) {
b.WriteString(key + "\n")
}
}
Expand Down
19 changes: 17 additions & 2 deletions utils/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"

Expand Down Expand Up @@ -169,10 +170,24 @@ func ReadFileContent(file string) ([]byte, error) {
}

// ExpandHome expands `~` char in the path to home path of a current user in provided path p.
// When sudo is used, it expands to home dir of a sudo user.
func ExpandHome(p string) string {
userPath, _ := os.UserHomeDir()
// current user home dir, used when sudo is not used
// or when errors occur during sudo user lookup
curUserHomeDir, _ := os.UserHomeDir()

p = strings.Replace(p, "~", userPath, 1)
userId, isSet := os.LookupEnv("SUDO_UID")
if !isSet {
return curUserHomeDir
}

// lookup user to figure out Home Directory
u, err := user.LookupId(userId)
if err != nil {
return curUserHomeDir
}

p = strings.Replace(p, "~", u.HomeDir, 1)
hellt marked this conversation as resolved.
Show resolved Hide resolved

return p
}
Expand Down