From d0a251916f5749a6411978ddd02f9fe856cf2c8c Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Mon, 24 Apr 2023 13:44:35 -0400 Subject: [PATCH] fix: expand file path Recognize tile `~` symbol and environment variables in path. Fixes: 472a463d0e8d ("ref: change api to expose ssh.PublicKey and authorizd_key") Signed-off-by: Ayman Bagabas --- keygen.go | 16 +++++++++++++++- keygen_test.go | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/keygen.go b/keygen.go index d406380..37b5ce3 100644 --- a/keygen.go +++ b/keygen.go @@ -154,7 +154,7 @@ func WithEllipticCurve(curve elliptic.Curve) Option { func New(path string, opts ...Option) (*SSHKeyPair, error) { var err error s := &SSHKeyPair{ - path: path, + path: expandPath(path), rsaBitSize: rsaDefaultBits, ec: elliptic.P384(), keyType: Ed25519, @@ -501,6 +501,20 @@ func fileExists(path string) bool { return true } +// expandPath resolves the tilde `~` and any environment variables in path. +func expandPath(path string) string { + if len(path) > 0 && path[0] == '~' { + userdir, err := os.UserHomeDir() + if err != nil { + return path + } + + path = filepath.Join(userdir, path[1:]) + } + + return os.ExpandEnv(path) +} + // attaches a user@host suffix to a serialized public key. returns the original // pubkey if we can't get the username or host. func pubKeyMemo() string { diff --git a/keygen_test.go b/keygen_test.go index 2ae8367..8188a95 100644 --- a/keygen_test.go +++ b/keygen_test.go @@ -336,3 +336,24 @@ func TestKeynameSuffix(t *testing.T) { }) } } + +func TestExpandPath(t *testing.T) { + tmpdir := t.TempDir() + os.Setenv("TEMP", tmpdir) + defer os.Unsetenv("TEMP") + + // Test environment variable expansion + if fp := expandPath(filepath.Join("$TEMP", "testkey")); fp != filepath.Join(tmpdir, "testkey") { + t.Errorf("error expanding path: %s", fp) + } + + // Test tilde expansion + homedir, err := os.UserHomeDir() + if err != nil { + t.Fatalf("error getting user home directory: %v", err) + } + + if fp := expandPath(filepath.Join("~", "testkey")); fp != filepath.Join(homedir, "testkey") { + t.Errorf("error expanding path: %s", fp) + } +}