Skip to content

Commit

Permalink
fix: expand file path
Browse files Browse the repository at this point in the history
Recognize tile `~` symbol and environment variables in path.

Fixes: 472a463 ("ref: change api to expose ssh.PublicKey and authorizd_key")

Signed-off-by: Ayman Bagabas <[email protected]>
  • Loading branch information
aymanbagabas committed Apr 24, 2023
1 parent ba5b374 commit d0a2519
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
16 changes: 15 additions & 1 deletion keygen.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down
21 changes: 21 additions & 0 deletions keygen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit d0a2519

Please sign in to comment.