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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ hostname = "0.4.1"
humantime = "2.3.0"
inquire = { default-features = false, version = "0.9.1", features = [ "crossterm" ] }
nix = { default-features = false, features = [ "fs", "user" ], version = "0.30.1" }
yansi = "1.0.1"
regex = "1.11.3"
reqwest = { default-features = false, features = [
"rustls-tls-native-roots",
Expand All @@ -57,6 +56,7 @@ thiserror = "2.0.17"
tracing = "0.1.41"
tracing-subscriber = { features = [ "env-filter", "registry", "std" ], version = "0.3.20" }
which = "8.0.0"
yansi = "1.0.1"

[target.'cfg(target_os="macos")'.dependencies]
system-configuration = "0.6.1"
Expand Down
80 changes: 66 additions & 14 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,14 @@ impl Command {
}
}

// INFO: Setting HOME to "" for macos
// ref: https://github.com/NixOS/nix/blob/d5d7ca01b3dcf48f43819012c580cfb57cb08e47/src/libutil/unix/users.cc#L52
if self.elevate.is_some() && cfg!(target_os = "macos") {
self
.env_vars
.insert("HOME".to_string(), EnvAction::Set("".to_string()));
}

// Preserve all variables in PRESERVE_ENV if present
for &key in PRESERVE_ENV {
if std::env::var(key).is_ok() {
Expand Down Expand Up @@ -405,6 +413,52 @@ impl Command {
Ok(cmd)
}

fn build_sudo_parts(&self) -> Result<Vec<String>> {
let elevation_program = self
.elevate
.as_ref()
.ok_or_else(|| eyre::eyre!("Command not found for elevation"))?
.resolve()
.context("Failed to resolve elevation program")?;

let mut parts = vec![elevation_program.to_string_lossy().to_string()];

let program_name = elevation_program
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| {
eyre::eyre!("Failed to determine elevation program name")
})?;
if program_name == "sudo" {
if let Ok(_askpass) = std::env::var("NH_SUDO_ASKPASS") {
parts.push("-A".to_string());
}
}

let preserve_env = std::env::var("NH_PRESERVE_ENV")
.as_deref()
.map(|x| !matches!(x, "0"))
.unwrap_or(true);

parts.push("env".to_string());
for env_arg in self.env_vars.iter().filter_map(|(key, action)| {
match action {
EnvAction::Set(value) => Some(format!("{key}={value}")),
EnvAction::Preserve if preserve_env => {
match std::env::var(key) {
Ok(value) => Some(format!("{key}={value}")),
Err(_) => None,
}
},
_ => None,
}
}) {
parts.push(env_arg);
}

Ok(parts)
}

/// Create a sudo command for self-elevation with proper environment handling
///
/// # Errors
Expand All @@ -423,26 +477,24 @@ impl Command {
.elevate(Some(strategy))
.with_required_env();

let sudo_exec = cmd_builder.build_sudo_cmd()?;
let mut sudo_parts = cmd_builder.build_sudo_parts()?;

// Add the target executable and arguments to the sudo command
let exec_with_args = sudo_exec.arg(&current_exe);
// Add the target executable and arguments
sudo_parts.push(current_exe.to_string_lossy().to_string());
let args: Vec<String> = std::env::args().skip(1).collect();
let final_exec = exec_with_args.args(&args);

// Convert Exec to std::process::Command by parsing the command line
let cmdline = final_exec.to_cmdline_lossy();
let parts: Vec<&str> = cmdline.split_whitespace().collect();
sudo_parts.extend(args);

if parts.is_empty() {
bail!("Failed to build sudo command");
let mut std_cmd = std::process::Command::new(&sudo_parts[0]);
if sudo_parts.len() > 1 {
std_cmd.args(&sudo_parts[1..]);
}

let mut std_cmd = std::process::Command::new(parts[0]);
if parts.len() > 1 {
std_cmd.args(&parts[1..]);
// check if using SUDO_ASKPASS
if sudo_parts[1] == "-A" {
if let Ok(askpass) = std::env::var("NH_SUDO_ASKPASS") {
std_cmd.env("SUDO_ASKPASS", askpass);
}
}

Ok(std_cmd)
}

Expand Down