-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathcommands.rs
More file actions
1248 lines (1084 loc) · 33.9 KB
/
commands.rs
File metadata and controls
1248 lines (1084 loc) · 33.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::HashMap,
ffi::{OsStr, OsString},
path::PathBuf,
sync::{Mutex, OnceLock},
};
use color_eyre::{
Result,
eyre::{self, Context, bail},
};
use secrecy::{ExposeSecret, SecretString};
use subprocess::{Exec, ExitStatus, Redirection};
use thiserror::Error;
use tracing::{debug, info, warn};
use which::which;
use crate::{installable::Installable, interface::NixBuildPassthroughArgs};
static PASSWORD_CACHE: OnceLock<Mutex<HashMap<String, SecretString>>> =
OnceLock::new();
fn get_cached_password(host: &str) -> Option<SecretString> {
let cache = PASSWORD_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let guard = cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard.get(host).cloned()
}
fn cache_password(host: &str, password: SecretString) {
let cache = PASSWORD_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut guard = cache
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
guard.insert(host.to_string(), password);
}
fn ssh_wrap(
cmd: Exec,
ssh: Option<&str>,
password: Option<&SecretString>,
) -> Exec {
if let Some(ssh) = ssh {
let mut ssh_cmd = Exec::cmd("ssh")
.arg("-T")
.arg(ssh)
.arg(cmd.to_cmdline_lossy());
if let Some(pwd) = password {
ssh_cmd = ssh_cmd.stdin(format!("{}\n", pwd.expose_secret()).as_str());
}
ssh_cmd
} else {
cmd
}
}
#[allow(dead_code)] // shut up
#[derive(Debug, Clone)]
pub enum EnvAction {
/// Set an environment variable to a specific value
Set(String),
/// Preserve an environment variable from the current environment
Preserve,
/// Remove/unset an environment variable
Remove,
}
/// Strategy for choosing a privilege elevation program.
/// - `Auto`: try supported programs in fallback order.
/// - `Prefer(PathBuf)`: try the specified program, then fallback.
/// - `Force(&'static str)`: use only the specified program, error if not
/// available.
#[allow(dead_code)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ElevationStrategy {
Auto,
Prefer(PathBuf),
Force(&'static str),
}
impl ElevationStrategy {
pub fn resolve(&self) -> Result<PathBuf> {
match self {
ElevationStrategy::Auto => Self::choice(),
ElevationStrategy::Prefer(program) => {
which(program).or_else(|_| {
let auto = Self::choice()?;
warn!(
"{} not found. Using {} instead",
program.to_string_lossy(),
auto.to_string_lossy()
);
Ok(auto)
})
},
ElevationStrategy::Force(program) => Ok(program.into()),
}
}
/// Gets a path to a privilege elevation program based on what is available in
/// the system.
///
/// This funtion checks for the existence of common privilege elevation
/// program names in the `PATH` using the `which` crate and returns a Ok
/// result with the `OsString` of the path to the binary. In the case none
/// of the checked programs are found a Err result is returned.
///
/// The search is done in this order:
///
/// 1. `doas`
/// 2. `sudo`
/// 3. `run0`
/// 4. `pkexec`
///
/// The logic for choosing this order is that a person with `doas` installed
/// is more likely to be using it as their main privilege elevation program.
/// `run0` and `pkexec` are preinstalled in any `NixOS` system with polkit
/// support installed, so they have been placed lower as it's easier to
/// deactivate sudo than it is to remove `run0`/`pkexec`
///
/// # Returns
///
/// * `Result<PathBuf>` - The absolute path to the privilege elevation program
/// binary or an error if a program can't be found.
fn choice() -> Result<PathBuf> {
const STRATEGIES: [&str; 4] = ["doas", "sudo", "run0", "pkexec"];
for strategy in STRATEGIES {
if let Ok(path) = which(strategy) {
debug!(?path, "{strategy} path found");
return Ok(path);
}
}
Err(eyre::eyre!(
"No elevation strategy found. Checked: {}",
STRATEGIES.join(", ")
))
}
}
#[derive(Debug)]
pub struct Command {
dry: bool,
message: Option<String>,
command: OsString,
args: Vec<OsString>,
elevate: Option<ElevationStrategy>,
ssh: Option<String>,
show_output: bool,
env_vars: HashMap<String, EnvAction>,
}
impl Command {
pub fn new<S: AsRef<OsStr>>(command: S) -> Self {
Self {
dry: false,
message: None,
command: command.as_ref().to_os_string(),
args: vec![],
elevate: None,
ssh: None,
show_output: false,
env_vars: HashMap::new(),
}
}
/// Set whether to run the command with elevated privileges.
#[must_use]
pub fn elevate(mut self, elevate: Option<ElevationStrategy>) -> Self {
self.elevate = elevate;
self
}
/// Set whether to perform a dry run.
#[must_use]
pub fn dry(mut self, dry: bool) -> Self {
self.dry = dry;
self
}
/// Set whether to show command output.
#[must_use]
pub fn show_output(mut self, show_output: bool) -> Self {
self.show_output = show_output;
self
}
/// Set the SSH target for remote command execution.
#[must_use]
pub fn ssh(mut self, ssh: Option<String>) -> Self {
self.ssh = ssh;
self
}
/// Add a single argument to the command.
#[must_use]
pub fn arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
self.args.push(arg.as_ref().to_os_string());
self
}
/// Add multiple arguments to the command.
#[must_use]
pub fn args<I>(mut self, args: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<OsStr>,
{
for elem in args {
self.args.push(elem.as_ref().to_os_string());
}
self
}
/// Set a message to display before running the command.
#[must_use]
pub fn message<S: AsRef<str>>(mut self, message: S) -> Self {
self.message = Some(message.as_ref().to_string());
self
}
/// Preserve multiple environment variables from the current environment
#[must_use]
pub fn preserve_envs<I, K>(mut self, keys: I) -> Self
where
I: IntoIterator<Item = K>,
K: AsRef<str>,
{
for key in keys {
let key_str = key.as_ref().to_string();
self.env_vars.insert(key_str, EnvAction::Preserve);
}
self
}
/// Configure environment for Nix and NH operations
#[must_use]
pub fn with_required_env(mut self) -> Self {
// Centralized list of environment variables to preserve
// This is not a part of Nix's environment, but it might be necessary.
// nixos-rebuild preserves it, so we do too.
const PRESERVE_ENV: &[&str] = &[
"LOCALE_ARCHIVE",
// PATH needs to be preserved so that NH can invoke CLI utilities.
"PATH",
// Make sure NIX_SSHOPTS applies to nix commands that invoke ssh, such as
// `nix copy`
"NIX_SSHOPTS",
// This is relevant for Home-Manager systems
"HOME_MANAGER_BACKUP_EXT",
// Preserve other Nix-related environment variables
// TODO: is this everything we need? Previously we only preserved *some*
// variables and nh continued to work, but any missing vars might
// break functionality completely unexpectedly. This list could
// change at any moment. This better be enough. Ugh.
"NIX_CONFIG",
"NIX_PATH",
"NIX_REMOTE",
"NIX_SSL_CERT_FILE",
"NIX_USER_CONF_FILES",
];
// Always explicitly set USER if present
if let Ok(user) = std::env::var("USER") {
self
.env_vars
.insert("USER".to_string(), EnvAction::Set(user));
}
// Only propagate HOME for non-elevated commands
if self.elevate.is_none() {
if let Ok(home) = std::env::var("HOME") {
self
.env_vars
.insert("HOME".to_string(), EnvAction::Set(home));
}
}
// Preserve all variables in PRESERVE_ENV if present
for &key in PRESERVE_ENV {
if std::env::var(key).is_ok() {
self.env_vars.insert(key.to_string(), EnvAction::Preserve);
}
}
// Explicitly set NH_* variables
for (key, value) in std::env::vars() {
if key.starts_with("NH_") {
self.env_vars.insert(key, EnvAction::Set(value));
}
}
debug!(
"Configured envs: {}",
self
.env_vars
.iter()
.map(|(key, action)| {
match action {
EnvAction::Set(value) => format!("{key}={value}"),
EnvAction::Preserve => format!("{key}=<preserved>"),
EnvAction::Remove => format!("{key}=<removed>"),
}
})
.collect::<Vec<_>>()
.join(", ")
);
self
}
fn apply_env_to_exec(&self, mut cmd: Exec) -> Exec {
for (key, action) in &self.env_vars {
match action {
EnvAction::Set(value) => {
cmd = cmd.env(key, value);
},
EnvAction::Preserve => {
// Only preserve if present in current environment
if let Ok(value) = std::env::var(key) {
cmd = cmd.env(key, value);
}
},
EnvAction::Remove => {
// For remove, we'll handle this in the sudo construction
// by not including it in preserved variables
},
}
}
cmd
}
/// Creates a Exec that contains elevates the program with proper environment
/// handling.
///
/// Panics: If called when `self.elevate` is `None`
fn build_sudo_cmd(&self) -> Result<Exec> {
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 cmd = Exec::cmd(&elevation_program);
// Use NH_SUDO_ASKPASS program for sudo if present
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") {
cmd = cmd.env("SUDO_ASKPASS", askpass).arg("-A");
}
}
// NH_PRESERVE_ENV: set to "0" to disable preserving environment variables,
// "1" to force, unset defaults to force
let preserve_env = std::env::var("NH_PRESERVE_ENV")
.as_deref()
.map(|x| !matches!(x, "0"))
.unwrap_or(true);
// Insert 'env' command to explicitly pass environment variables to the
// elevated command
cmd = cmd.arg("env");
for 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,
}
}) {
cmd = cmd.arg(arg);
}
Ok(cmd)
}
/// Create a sudo command for self-elevation with proper environment handling
///
/// # Errors
///
/// Returns an error if the current executable path cannot be determined or
/// sudo command cannot be built.
pub fn self_elevate_cmd(
strategy: ElevationStrategy,
) -> Result<std::process::Command> {
// Get the current executable path
let current_exe = std::env::current_exe()
.context("Failed to get current executable path")?;
// Self-elevation with proper environment handling
let cmd_builder = Self::new(¤t_exe)
.elevate(Some(strategy))
.with_required_env();
let sudo_exec = cmd_builder.build_sudo_cmd()?;
// Add the target executable and arguments to the sudo command
let exec_with_args = sudo_exec.arg(¤t_exe);
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();
if parts.is_empty() {
bail!("Failed to build sudo command");
}
let mut std_cmd = std::process::Command::new(parts[0]);
if parts.len() > 1 {
std_cmd.args(&parts[1..]);
}
Ok(std_cmd)
}
/// Run the configured command.
///
/// # Errors
///
/// Returns an error if the command fails to execute or returns a non-zero
/// exit status.
///
/// # Panics
///
/// Panics if the command result is unexpectedly None.
pub fn run(&self) -> Result<()> {
// Prompt for sudo password if needed for remote deployment
// FIXME: this implementation only covers Sudo. I *think* doas and run0 are
// able to read from stdin, but needs to be tested and possibly
// mitigated.
let sudo_password = if self.ssh.is_some() && self.elevate.is_some() {
let host = self.ssh.as_ref().unwrap();
if let Some(cached_password) = get_cached_password(host) {
Some(cached_password)
} else {
let password =
inquire::Password::new(&format!("[sudo] password for {host}:"))
.without_confirmation()
.prompt()
.context("Failed to read sudo password")?;
let secret_password = SecretString::new(password.into());
cache_password(host, secret_password.clone());
Some(secret_password)
}
} else {
None
};
let cmd = if self.elevate.is_some() && self.ssh.is_none() {
// Local elevation
self.build_sudo_cmd()?.arg(&self.command).args(&self.args)
} else if self.elevate.is_some() && self.ssh.is_some() {
// Build elevation command
let elevation_program = self
.elevate
.as_ref()
.unwrap()
.resolve()
.context("Failed to resolve elevation program")?;
let program_name = elevation_program
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| {
eyre::eyre!("Failed to determine elevation program name")
})?;
let mut elev_cmd = Exec::cmd(&elevation_program);
// Add program-specific arguments
if program_name == "sudo" {
elev_cmd = elev_cmd.arg("--prompt=").arg("--stdin");
}
// Add env command to handle environment variables
elev_cmd = elev_cmd.arg("env");
for (key, action) in &self.env_vars {
match action {
EnvAction::Set(value) => {
elev_cmd = elev_cmd.arg(format!("{key}={value}"));
},
EnvAction::Preserve => {
if let Ok(value) = std::env::var(key) {
elev_cmd = elev_cmd.arg(format!("{key}={value}"));
}
},
_ => {},
}
}
elev_cmd.arg(&self.command).args(&self.args)
} else {
// No elevation
self.apply_env_to_exec(Exec::cmd(&self.command).args(&self.args))
};
// Configure output redirection based on show_output setting
let cmd = ssh_wrap(
if self.show_output {
cmd.stderr(Redirection::Merge)
} else {
cmd.stderr(Redirection::None).stdout(Redirection::None)
},
self.ssh.as_deref(),
sudo_password.as_ref(),
);
if let Some(m) = &self.message {
info!("{m}");
}
debug!(?cmd);
if self.dry {
return Ok(());
}
let msg = self
.message
.clone()
.unwrap_or_else(|| "Command failed".to_string());
let res = cmd.capture();
match res {
Ok(capture) => {
let status = &capture.exit_status;
if !status.success() {
let stderr = capture.stderr_str();
if stderr.trim().is_empty() {
return Err(eyre::eyre!(format!(
"{} (exit status {:?})",
msg, status
)));
}
return Err(eyre::eyre!(format!(
"{} (exit status {:?})\nstderr:\n{}",
msg, status, stderr
)));
}
Ok(())
},
Err(e) => Err(e).wrap_err(msg),
}
}
/// Run the configured command and capture its output.
///
/// # Errors
///
/// Returns an error if the command fails to execute.
pub fn run_capture(&self) -> Result<Option<String>> {
let cmd = self.apply_env_to_exec(
Exec::cmd(&self.command)
.args(&self.args)
.stderr(Redirection::None)
.stdout(Redirection::Pipe),
);
if let Some(m) = &self.message {
info!("{m}");
}
debug!(?cmd);
if self.dry {
return Ok(None);
}
Ok(Some(cmd.capture()?.stdout_str()))
}
}
#[derive(Debug)]
pub struct Build {
message: Option<String>,
installable: Installable,
extra_args: Vec<OsString>,
nom: bool,
builder: Option<String>,
}
impl Build {
#[must_use]
pub const fn new(installable: Installable) -> Self {
Self {
message: None,
installable,
extra_args: vec![],
nom: false,
builder: None,
}
}
#[must_use]
pub fn message<S: AsRef<str>>(mut self, message: S) -> Self {
self.message = Some(message.as_ref().to_string());
self
}
#[must_use]
pub fn extra_arg<S: AsRef<OsStr>>(mut self, arg: S) -> Self {
self.extra_args.push(arg.as_ref().to_os_string());
self
}
#[must_use]
pub const fn nom(mut self, yes: bool) -> Self {
self.nom = yes;
self
}
#[must_use]
pub fn builder(mut self, builder: Option<String>) -> Self {
self.builder = builder;
self
}
#[must_use]
pub fn extra_args<I>(mut self, args: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<OsStr>,
{
for elem in args {
self.extra_args.push(elem.as_ref().to_os_string());
}
self
}
#[must_use]
pub fn passthrough(self, passthrough: &NixBuildPassthroughArgs) -> Self {
self.extra_args(passthrough.generate_passthrough_args())
}
/// Run the build command.
///
/// # Errors
///
/// Returns an error if the build command fails to execute.
pub fn run(&self) -> Result<()> {
if let Some(m) = &self.message {
info!("{m}");
}
let installable_args = self.installable.to_args();
let base_command = Exec::cmd("nix")
.arg("build")
.args(&installable_args)
.args(&match &self.builder {
Some(host) => {
vec!["--builders".to_string(), format!("ssh://{host} - - - 100")]
},
None => vec![],
})
.args(&self.extra_args);
let exit = if self.nom {
let cmd = {
base_command
.args(&["--log-format", "internal-json", "--verbose"])
.stderr(Redirection::Merge)
.stdout(Redirection::Pipe)
| Exec::cmd("nom").args(&["--json"])
}
.stdout(Redirection::None);
debug!(?cmd);
cmd.join()
} else {
let cmd = base_command
.stderr(Redirection::Merge)
.stdout(Redirection::None);
debug!(?cmd);
cmd.join()
};
match exit? {
ExitStatus::Exited(0) => (),
other => bail!(ExitError(other)),
}
Ok(())
}
}
#[derive(Debug, Error)]
#[error("Command exited with status {0:?}")]
pub struct ExitError(ExitStatus);
#[cfg(test)]
mod tests {
use std::{env, ffi::OsString};
use serial_test::serial;
use super::*;
// Safely manage environment variables in tests
struct EnvGuard {
key: String,
original: Option<String>,
}
impl EnvGuard {
fn new(key: &str, value: &str) -> Self {
let original = env::var(key).ok();
unsafe {
env::set_var(key, value);
}
EnvGuard {
key: key.to_string(),
original,
}
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
unsafe {
match &self.original {
Some(val) => env::set_var(&self.key, val),
None => env::remove_var(&self.key),
}
}
}
}
#[test]
fn test_env_action_variants() {
// Test that all EnvAction variants are correctly created
let set_action = EnvAction::Set("test_value".to_string());
let preserve_action = EnvAction::Preserve;
let remove_action = EnvAction::Remove;
match set_action {
EnvAction::Set(val) => assert_eq!(val, "test_value"),
_ => panic!("Expected Set variant"),
}
assert!(matches!(preserve_action, EnvAction::Preserve));
assert!(matches!(remove_action, EnvAction::Remove));
}
#[test]
fn test_command_new() {
let cmd = Command::new("test-command");
assert_eq!(cmd.command, OsString::from("test-command"));
assert!(!cmd.dry);
assert!(cmd.message.is_none());
assert!(cmd.args.is_empty());
assert!(cmd.elevate.is_none());
assert!(cmd.ssh.is_none());
assert!(!cmd.show_output);
assert!(cmd.env_vars.is_empty());
}
#[test]
fn test_command_builder_pattern() {
let cmd = Command::new("test")
.dry(true)
.show_output(true)
.elevate(Some(ElevationStrategy::Force("sudo")))
.ssh(Some("host".to_string()))
.message("test message")
.arg("arg1")
.args(["arg2", "arg3"]);
assert!(cmd.dry);
assert!(cmd.show_output);
assert_eq!(cmd.elevate, Some(ElevationStrategy::Force("sudo")));
assert_eq!(cmd.ssh, Some("host".to_string()));
assert_eq!(cmd.message, Some("test message".to_string()));
assert_eq!(cmd.args, vec![
OsString::from("arg1"),
OsString::from("arg2"),
OsString::from("arg3")
]);
}
#[test]
fn test_preserve_envs() {
let cmd = Command::new("test").preserve_envs(["VAR1", "VAR2", "VAR3"]);
assert_eq!(cmd.env_vars.len(), 3);
assert!(matches!(
cmd.env_vars.get("VAR1"),
Some(EnvAction::Preserve)
));
assert!(matches!(
cmd.env_vars.get("VAR2"),
Some(EnvAction::Preserve)
));
assert!(matches!(
cmd.env_vars.get("VAR3"),
Some(EnvAction::Preserve)
));
}
#[test]
#[serial]
fn test_with_required_env_home_user() {
let _home_guard = EnvGuard::new("HOME", "/test/home");
let _user_guard = EnvGuard::new("USER", "testuser");
let cmd = Command::new("test").with_required_env();
// Should preserve HOME and USER as Set actions
assert!(
matches!(cmd.env_vars.get("HOME"), Some(EnvAction::Set(val)) if val == "/test/home")
);
assert!(
matches!(cmd.env_vars.get("USER"), Some(EnvAction::Set(val)) if val == "testuser")
);
// Should preserve all Nix-related variables if present
for key in [
"PATH",
"NIX_CONFIG",
"NIX_PATH",
"NIX_REMOTE",
"NIX_SSHOPTS",
"NIX_SSL_CERT_FILE",
"NIX_USER_CONF_FILES",
"LOCALE_ARCHIVE",
"HOME_MANAGER_BACKUP_EXT",
] {
if cmd.env_vars.contains_key(key) {
assert!(matches!(cmd.env_vars.get(key), Some(EnvAction::Preserve)));
}
}
}
#[test]
#[serial]
fn test_with_required_env_missing_home_user() {
// Test behavior when HOME/USER are not set
unsafe {
env::remove_var("HOME");
env::remove_var("USER");
}
let cmd = Command::new("test").with_required_env();
// Should not have HOME or USER in env_vars if they're not set
assert!(!cmd.env_vars.contains_key("HOME"));
assert!(!cmd.env_vars.contains_key("USER"));
// Should preserve Nix-related variables if present
for key in [
"PATH",
"NIX_CONFIG",
"NIX_PATH",
"NIX_REMOTE",
"NIX_SSHOPTS",
"NIX_SSL_CERT_FILE",
"NIX_USER_CONF_FILES",
"LOCALE_ARCHIVE",
"HOME_MANAGER_BACKUP_EXT",
] {
if let Some(action) = cmd.env_vars.get(key) {
assert!(matches!(action, EnvAction::Preserve));
}
}
}
#[test]
#[serial]
fn test_with_required_env_nh_vars() {
let _guard1 = EnvGuard::new("NH_TEST_VAR", "test_value");
let _guard2 = EnvGuard::new("NH_ANOTHER_VAR", "another_value");
let _guard3 = EnvGuard::new("NOT_NH_VAR", "should_not_be_included");
let cmd = Command::new("test").with_required_env();
// Should include NH_* variables as Set actions
assert!(
matches!(cmd.env_vars.get("NH_TEST_VAR"), Some(EnvAction::Set(val)) if val == "test_value")
);
assert!(
matches!(cmd.env_vars.get("NH_ANOTHER_VAR"), Some(EnvAction::Set(val)) if val == "another_value")
);
// Should not include non-NH variables
assert!(!cmd.env_vars.contains_key("NOT_NH_VAR"));
}
#[test]
#[serial]
fn test_combined_env_methods() {
let _home_guard = EnvGuard::new("HOME", "/test/home");
let _nh_guard = EnvGuard::new("NH_TEST", "nh_value");
let cmd = Command::new("test")
.with_required_env()
.preserve_envs(["EXTRA_VAR"]);
// Should have HOME from with_nix_env
assert!(
matches!(cmd.env_vars.get("HOME"), Some(EnvAction::Set(val)) if val == "/test/home")
);
// Should have NH variables from with_nh_env
assert!(
matches!(cmd.env_vars.get("NH_TEST"), Some(EnvAction::Set(val)) if val == "nh_value")
);
// Should have Nix variables preserved
assert!(matches!(
cmd.env_vars.get("PATH"),
Some(EnvAction::Preserve)
));
// Should have extra preserved variable
assert!(matches!(
cmd.env_vars.get("EXTRA_VAR"),
Some(EnvAction::Preserve)
));
}
#[test]
fn test_env_vars_override_behavior() {
let mut cmd = Command::new("test");
// First add a variable as Preserve
cmd
.env_vars
.insert("TEST_VAR".to_string(), EnvAction::Preserve);
assert!(matches!(
cmd.env_vars.get("TEST_VAR"),
Some(EnvAction::Preserve)
));
// Then override it as Set
cmd.env_vars.insert(
"TEST_VAR".to_string(),
EnvAction::Set("new_value".to_string()),
);
assert!(
matches!(cmd.env_vars.get("TEST_VAR"), Some(EnvAction::Set(val)) if val == "new_value")
);
}
#[test]
fn test_build_sudo_cmd_basic() {
let cmd =
Command::new("test").elevate(Some(ElevationStrategy::Force("sudo")));
let sudo_exec = cmd.build_sudo_cmd().unwrap();
// Platform-agnostic: 'sudo' may not be the first token if env vars are
// injected (e.g., NH_SUDO_ASKPASS). Accept any command line where
// 'sudo' is present as a token.
let cmdline = sudo_exec.to_cmdline_lossy();
assert!(cmdline.split_whitespace().any(|tok| tok == "sudo"));
}
#[test]
#[serial]
fn test_build_sudo_cmd_with_preserve_vars() {
let _preserve_env_guard = EnvGuard::new("NH_PRESERVE_ENV", "1");
let _var1_guard = EnvGuard::new("VAR1", "1");
let _var2_guard = EnvGuard::new("VAR2", "2");
let cmd = Command::new("test")
.preserve_envs(["VAR1", "VAR2"])
.elevate(Some(ElevationStrategy::Force("sudo")));
let sudo_exec = cmd.build_sudo_cmd().unwrap();
let cmdline = sudo_exec.to_cmdline_lossy();
assert!(cmdline.contains("env"));
assert!(cmdline.contains("VAR1=1"));
assert!(cmdline.contains("VAR2=2"));
}
#[test]
#[serial]
fn test_build_sudo_cmd_with_disabled_preserve_vars() {
let _preserve_env_guard = EnvGuard::new("NH_PRESERVE_ENV", "0");
let _var1_guard = EnvGuard::new("VAR1", "1");
let _var2_guard = EnvGuard::new("VAR2", "2");