From 1ba67f76e17de1979d70efa1abb28b0ed9cfd62b Mon Sep 17 00:00:00 2001 From: Dominik Schulz Date: Wed, 28 Dec 2022 14:03:02 +0100 Subject: [PATCH] Do not rewrite ~ (#2496) * Do not rewrite ~ Fixes #2083 RELEASE_NOTES=[ENHANCEMENT] Do not rewrite ~. Signed-off-by: Dominik Schulz * Honor GOPASS_HOMEDIR Signed-off-by: Dominik Schulz Signed-off-by: Dominik Schulz --- pkg/fsutil/fsutil.go | 15 +++++---------- pkg/fsutil/fsutil_test.go | 23 ++++++++++++----------- 2 files changed, 17 insertions(+), 21 deletions(-) diff --git a/pkg/fsutil/fsutil.go b/pkg/fsutil/fsutil.go index e4abce220d..4ada434dde 100644 --- a/pkg/fsutil/fsutil.go +++ b/pkg/fsutil/fsutil.go @@ -7,7 +7,6 @@ import ( "io" "math/rand" "os" - "os/user" "path/filepath" "regexp" "strings" @@ -26,20 +25,16 @@ func CleanFilename(in string) string { // CleanPath resolves common aliases in a path and cleans it as much as possible. func CleanPath(path string) string { - // http://stackoverflow.com/questions/17609732/expand-tilde-to-home-directory - // TODO(GH-2083): We should consider if we really want to rewrite ~ + // Only replace ~ if GOPASS_HOMEDIR is set. In that case we do expect any reference + // to the users homedir to be replaced by the value of GOPASS_HOMEDIR. This is mainly + // for testing and experiments. In all other cases we do want to leave ~ as-is. if len(path) > 1 && path[:2] == "~/" { - usr, _ := user.Current() - dir := usr.HomeDir - if hd := os.Getenv("GOPASS_HOMEDIR"); hd != "" { - dir = hd + return filepath.Clean(hd + path[2:]) } - - path = strings.Replace(path, "~/", dir+"/", 1) } - if p, err := filepath.Abs(path); err == nil { + if p, err := filepath.Abs(path); err == nil && !strings.HasPrefix(path, "~") { return p } diff --git a/pkg/fsutil/fsutil_test.go b/pkg/fsutil/fsutil_test.go index 81db28aa93..9b184a1867 100644 --- a/pkg/fsutil/fsutil_test.go +++ b/pkg/fsutil/fsutil_test.go @@ -4,8 +4,9 @@ import ( "crypto/rand" "io/ioutil" "os" - "os/user" "path/filepath" + "runtime" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -34,21 +35,21 @@ func TestCleanPath(t *testing.T) { "/home/user/../bob/.password-store": "/home/bob/.password-store", "/home/user//.password-store": "/home/user/.password-store", tempdir + "/foo.gpg": tempdir + "/foo.gpg", - } - - usr, err := user.Current() - if err == nil { - hd := usr.HomeDir - if gph := os.Getenv("GOPASS_HOMEDIR"); gph != "" { - hd = gph - } - - m["~/.password-store"] = hd + "/.password-store" + "~/.password-store": "~/.password-store", } for in, out := range m { got := CleanPath(in) + if strings.HasPrefix(out, "~") { + // skip these tests on windows + if runtime.GOOS == "windows" { + continue + } + assert.Equal(t, out, got) + + continue + } // filepath.Abs turns /home/bob into C:\home\bob on Windows absOut, err := filepath.Abs(out) assert.NoError(t, err)