From a2906b03d4a84c0f8c8345ded8b0c1b5af77a9ab Mon Sep 17 00:00:00 2001 From: Jacob Callahan Date: Sat, 12 Oct 2024 17:03:18 -0400 Subject: [PATCH] Allow users to use ~ in their key paths for real this time Previously, it was observed that using a tilde to represent a user's home directory wasn't resolving correctly. With this change, we're explicitly expanding the path to fully resolve the location. Fixes #21 --- Cargo.toml | 1 + src/connection.rs | 7 +++++-- tests/test_connection.py | 12 ++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fe5fe71..4b01865 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ crate-type = ["cdylib"] [dependencies] openssl = { version = "0.10", features = ["vendored"] } pyo3 = "0.22" +shellexpand = "2.1" # ssh2 = "0.9" # temporary until ssh2#312 makes it into a release. probably 0.9.5 ssh2 = { git = "https://github.com/alexcrichton/ssh2-rs", branch = "master" } diff --git a/src/connection.rs b/src/connection.rs index f3c22ac..0346d90 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -252,15 +252,18 @@ impl Connection { let private_key = private_key.unwrap_or(""); // if private_key is set, use it to authenticate if !private_key.is_empty() { + // If a user uses a tilde to represent the home directory, + // replace it with the actual home directory + let private_key = shellexpand::tilde(private_key).into_owned(); // if a password is set, use it to decrypt the private key if !password.is_empty() { session - .userauth_pubkey_file(username, None, Path::new(private_key), Some(password)) + .userauth_pubkey_file(username, None, Path::new(&private_key), Some(password)) .map_err(|e| PyErr::new::(format!("{}", e)))?; } else { // otherwise, try using the private key without a passphrase session - .userauth_pubkey_file(username, None, Path::new(private_key), None) + .userauth_pubkey_file(username, None, Path::new(&private_key), None) .map_err(|e| PyErr::new::(format!("{}", e)))?; } } else if !password.is_empty() { diff --git a/tests/test_connection.py b/tests/test_connection.py index 1c67e3f..23ac25c 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -26,6 +26,18 @@ def test_key_auth(): assert Connection(host="localhost", port=8022, private_key="tests/data/test_key") +def test_key_in_user_home(): + """Test that we can establish a connection with a key in the user's home directory.""" + # temporarily copy the key to the user's home directory + key_path = Path("tests/data/test_key") + new_path = Path.home() / ".ssh" / "test_key" + key_path.rename(new_path) + try: + assert Connection(host="localhost", port=8022, private_key="~/.ssh/test_key") + finally: + new_path.rename(key_path) + + def test_key_with_password_auth(): """Test that we can establish a connection with key-based authentication and a password.""" assert Connection(