Skip to content

Commit

Permalink
Merge pull request #1412 from steiler/sudoUserSSHPubKeys
Browse files Browse the repository at this point in the history
resolve homedir of sudo user
  • Loading branch information
hellt committed May 30, 2023
2 parents f624faa + 5c6fe6b commit 06505dc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
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)

return p
}
Expand Down

0 comments on commit 06505dc

Please sign in to comment.