Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ pub mod models;
#[cfg(test)]
pub mod models_tests;
pub mod notebooks;
pub mod path_vars;
#[cfg(test)]
pub mod path_vars_tests;
pub mod paths; // Added
#[cfg(test)]
pub mod paths_tests;
Expand Down
139 changes: 139 additions & 0 deletions src-tauri/src/path_vars.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
//! Expansion of environment variables and `~` inside user-entered paths.
//!
//! Users type SSH key paths like `%USERPROFILE%\ssh_keys\id_ed25519`,
//! `$HOME/.ssh/id_rsa` or `~/.ssh/id_rsa`, and expect them to work. Expansion
//! happens at *use* time, never when the path is saved: the stored value keeps
//! the variable in it, which is what lets the same profile work on a
//! colleague's machine — and matters doubly for the SSH profiles shared
//! through [`crate::team_share`].
//!
//! Every syntax is accepted on every platform, and `HOME`/`USERPROFILE` both
//! resolve to the home directory wherever the app runs, so a path written on
//! Windows still resolves on macOS and Linux.
//!
//! A name that resolves to nothing is left exactly as typed rather than
//! replaced with an empty string: the user then sees the unresolved variable
//! in the error instead of a silently broken path.

/// Expand `%VAR%`, `${VAR}`, `$VAR` and a leading `~` using the process
/// environment.
pub fn expand(raw: &str) -> String {
let home = home_dir();
expand_with(
raw,
|name| match name {
// Cross-platform aliases: the home directory answers to both
// spellings everywhere, so a shared profile survives the trip.
"HOME" | "USERPROFILE" => home.clone().or_else(|| std::env::var(name).ok()),
_ => std::env::var(name).ok(),
},
home.as_deref(),
)
}

/// The user's home directory, whichever variable the platform sets.
fn home_dir() -> Option<String> {
std::env::var("HOME")
.ok()
.or_else(|| std::env::var("USERPROFILE").ok())
.filter(|value| !value.is_empty())
}

/// Pure core of [`expand`]: `lookup` resolves a variable name, `home` is what
/// a leading `~` stands for. Both are injected so this is testable without
/// touching the real environment.
pub fn expand_with<F>(raw: &str, lookup: F, home: Option<&str>) -> String
where
F: Fn(&str) -> Option<String>,
{
let chars: Vec<char> = raw.chars().collect();
let mut out = String::with_capacity(raw.len());
let mut i = 0;

// A leading `~` only counts when it stands for the whole first segment,
// so `~user/x` (another account's home, which we cannot resolve) and a
// file literally named `~note.txt` are left alone.
if let Some(home) = home {
if chars.first() == Some(&'~')
// `map_or` rather than `is_none_or`: the latter needs Rust 1.82
// and the crate declares 1.77.2.
&& chars.get(1).map_or(true, |c| *c == '/' || *c == '\\')
{
out.push_str(home);
i = 1;
}
}

while i < chars.len() {
let consumed = match chars[i] {
'%' => expand_percent(&chars, i, &lookup, &mut out),
'$' => expand_dollar(&chars, i, &lookup, &mut out),
_ => None,
};
match consumed {
Some(next) => i = next,
None => {
out.push(chars[i]);
i += 1;
}
}
}
out
}

/// `%NAME%`. Returns the index just past the closing `%` when it expanded.
fn expand_percent<F>(chars: &[char], start: usize, lookup: &F, out: &mut String) -> Option<usize>
where
F: Fn(&str) -> Option<String>,
{
let end = find(chars, start + 1, '%')?;
let name: String = chars[start + 1..end].iter().collect();
if !is_var_name(&name) {
return None;
}
out.push_str(&lookup(&name)?);
Some(end + 1)
}

/// `${NAME}` or `$NAME`.
fn expand_dollar<F>(chars: &[char], start: usize, lookup: &F, out: &mut String) -> Option<usize>
where
F: Fn(&str) -> Option<String>,
{
if chars.get(start + 1) == Some(&'{') {
let end = find(chars, start + 2, '}')?;
let name: String = chars[start + 2..end].iter().collect();
if !is_var_name(&name) {
return None;
}
out.push_str(&lookup(&name)?);
return Some(end + 1);
}

let mut end = start + 1;
while end < chars.len() && is_name_char(chars[end], end == start + 1) {
end += 1;
}
if end == start + 1 {
return None;
}
let name: String = chars[start + 1..end].iter().collect();
out.push_str(&lookup(&name)?);
Some(end)
}

fn find(chars: &[char], from: usize, needle: char) -> Option<usize> {
(from..chars.len()).find(|i| chars[*i] == needle)
}

fn is_name_char(c: char, first: bool) -> bool {
c == '_' || c.is_ascii_alphabetic() || (!first && c.is_ascii_digit())
}

fn is_var_name(name: &str) -> bool {
let mut chars = name.chars();
match chars.next() {
Some(c) if is_name_char(c, true) => chars.all(|c| is_name_char(c, false)),
_ => false,
}
}
108 changes: 108 additions & 0 deletions src-tauri/src/path_vars_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use crate::path_vars::{expand, expand_with};

const HOME: &str = "/home/matteo";
const WIN_HOME: &str = "C:\\Users\\Matteo";

fn env(name: &str) -> Option<String> {
match name {
"HOME" => Some(HOME.to_string()),
"USERPROFILE" => Some(WIN_HOME.to_string()),
"SSH_DIR" => Some("/etc/keys".to_string()),
"EMPTY" => Some(String::new()),
_ => None,
}
}

fn expanded(raw: &str) -> String {
expand_with(raw, env, Some(HOME))
}

#[test]
fn windows_percent_syntax_resolves() {
assert_eq!(
expand_with("%USERPROFILE%\\ssh_keys\\id_ed25519.ppk", env, Some(WIN_HOME)),
"C:\\Users\\Matteo\\ssh_keys\\id_ed25519.ppk"
);
}

#[test]
fn unix_dollar_syntax_resolves() {
assert_eq!(expanded("$HOME/.ssh/id_rsa"), "/home/matteo/.ssh/id_rsa");
}

#[test]
fn braced_syntax_resolves() {
assert_eq!(expanded("${HOME}/.ssh/id_rsa"), "/home/matteo/.ssh/id_rsa");
}

#[test]
fn a_leading_tilde_resolves() {
assert_eq!(expanded("~/.ssh/id_rsa"), "/home/matteo/.ssh/id_rsa");
assert_eq!(expanded("~\\.ssh\\id_rsa"), "/home/matteo\\.ssh\\id_rsa");
assert_eq!(expanded("~"), "/home/matteo");
}

#[test]
fn a_tilde_that_is_not_the_first_segment_is_left_alone() {
// Another account's home is not something we can resolve, and a file may
// legitimately start with a tilde.
assert_eq!(expanded("~other/.ssh/id_rsa"), "~other/.ssh/id_rsa");
assert_eq!(expanded("/keys/~backup.pem"), "/keys/~backup.pem");
}

#[test]
fn several_variables_in_one_path_resolve() {
assert_eq!(expanded("$SSH_DIR/${HOME}/key"), "/etc/keys//home/matteo/key");
}

#[test]
fn an_unknown_variable_is_left_verbatim() {
// Better a visibly unresolved path in the error than a silently wrong one.
assert_eq!(expanded("%NOPE%\\key"), "%NOPE%\\key");
assert_eq!(expanded("$NOPE/key"), "$NOPE/key");
assert_eq!(expanded("${NOPE}/key"), "${NOPE}/key");
}

#[test]
fn a_variable_resolving_to_empty_is_honoured() {
assert_eq!(expanded("$EMPTY/key"), "/key");
}

#[test]
fn a_path_without_variables_is_untouched() {
assert_eq!(expanded("/absolute/path/id_rsa"), "/absolute/path/id_rsa");
assert_eq!(
expanded("C:\\Users\\Matteo\\key.ppk"),
"C:\\Users\\Matteo\\key.ppk"
);
assert_eq!(expanded(""), "");
}

#[test]
fn stray_markers_are_not_mistaken_for_variables() {
assert_eq!(expanded("100%/keys"), "100%/keys");
assert_eq!(expanded("%%"), "%%");
assert_eq!(expanded("cost$/key"), "cost$/key");
assert_eq!(expanded("$"), "$");
assert_eq!(expanded("${unclosed/key"), "${unclosed/key");
}

#[test]
fn a_name_may_not_start_with_a_digit() {
assert_eq!(expanded("$1HOME/key"), "$1HOME/key");
}

#[test]
fn no_home_leaves_a_tilde_alone() {
assert_eq!(expand_with("~/.ssh/id_rsa", env, None), "~/.ssh/id_rsa");
}

#[test]
fn both_home_spellings_resolve_on_this_platform() {
// The point of the aliasing: a profile written on Windows must still
// resolve on macOS and Linux, and the other way round.
let from_windows = expand("%USERPROFILE%/keys/id_rsa");
let from_unix = expand("$HOME/keys/id_rsa");
assert_eq!(from_windows, from_unix);
assert!(!from_windows.contains("USERPROFILE"));
}
12 changes: 12 additions & 0 deletions src-tauri/src/ssh_tunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,13 @@ impl SshTunnel {
tcp_host: Option<&str>,
tcp_port: Option<u16>,
) -> Result<Self, String> {
// Resolve `%USERPROFILE%`, `$HOME`, `${HOME}` and `~` now rather than
// when the path was saved, so the stored profile stays portable across
// machines and platforms. Done here rather than in `new` so the
// proxy-fronted path gets it too.
let expanded_key_file = ssh_key_file.map(crate::path_vars::expand);
let ssh_key_file = expanded_key_file.as_deref();

let use_system_ssh = should_use_system_ssh(ssh_password, ssh_key_file);
let connect_host = tcp_host.unwrap_or(ssh_host);
let connect_port = tcp_port.unwrap_or(ssh_port);
Expand Down Expand Up @@ -619,6 +626,11 @@ pub fn test_ssh_connection(
ssh_key_passphrase: Option<&str>,
ssh_allow_passphrase_prompt: bool,
) -> Result<String, String> {
// Expanded once here so both backends read the same file, and so "Test
// connection" behaves exactly like opening the tunnel.
let expanded_key_file = ssh_key_file.map(crate::path_vars::expand);
let ssh_key_file = expanded_key_file.as_deref();

let use_system_ssh = should_use_system_ssh(ssh_password, ssh_key_file);
eprintln!(
"[SSH Test] Testing connection to {}:{} as {} (UseSystemSSH={}, AllowPrompt={})",
Expand Down
17 changes: 11 additions & 6 deletions src/components/ssh/SshConnectionsManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -501,12 +501,17 @@ export function SshConnectionsManager({

{formData.auth_type === "ssh_key" && (
<>
<SshInput
label={t("newConnection.sshKeyFile")}
value={formData.key_file}
onChange={(val) => updateField("key_file", val)}
placeholder={t("newConnection.sshKeyFilePlaceholder")}
/>
<div className="flex flex-col">
<SshInput
label={t("newConnection.sshKeyFile")}
value={formData.key_file}
onChange={(val) => updateField("key_file", val)}
placeholder={t("newConnection.sshKeyFilePlaceholder")}
/>
<span className="text-xs text-muted mt-1">
{t("newConnection.sshKeyFileVarsHint")}
</span>
</div>

<div className="flex flex-col">
<SshInput
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1281,7 +1281,8 @@
"defaultDatabase": "Default database",
"defaultDatabaseHint": "New query tabs use this database. If you remove it from the selection, the next selected database becomes the default.",
"selectDatabasesHint": "Select the databases to include in this connection.",
"loadDatabasesHint": "Click Load Databases to fetch available databases."
"loadDatabasesHint": "Click Load Databases to fetch available databases.",
"sshKeyFileVarsHint": "Environment variables are resolved when connecting: %USERPROFILE%\\keys\\id_ed25519, $HOME/.ssh/id_rsa, ~/.ssh/id_rsa. Use ~ to keep the path working on every machine."
},
"sshConnections": {
"title": "SSH Connections",
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -1277,7 +1277,8 @@
"defaultDatabase": "Database predefinito",
"defaultDatabaseHint": "Le nuove schede di query usano questo database. Se lo rimuovi dalla selezione, il successivo database selezionato diventa quello predefinito.",
"selectDatabasesHint": "Seleziona i database da includere in questa connessione.",
"loadDatabasesHint": "Premi Carica database per recuperare i database disponibili."
"loadDatabasesHint": "Premi Carica database per recuperare i database disponibili.",
"sshKeyFileVarsHint": "Le variabili di ambiente vengono risolte alla connessione: %USERPROFILE%\\keys\\id_ed25519, $HOME/.ssh/id_rsa, ~/.ssh/id_rsa. Usa ~ per un percorso che funziona su ogni macchina."
},
"sshConnections": {
"title": "Connessioni SSH",
Expand Down