ggen_core/utils/safe_command.rs
1//! Safe command execution with validation to prevent command injection attacks
2//!
3//! This module provides the `SafeCommand` type that wraps shell commands with validation
4//! to prevent common command injection vulnerabilities. All commands are validated on
5//! construction to ensure they:
6//!
7//! - Are in the whitelist of allowed commands
8//! - Do not contain shell metacharacters in arguments (;|&><$`\n)
9//! - Do not exceed maximum command length of 4096 characters
10//! - Use validated paths for path arguments
11//!
12//! ## Security Model
13//!
14//! This module uses a multi-layered defense approach:
15//!
16//! 1. **Command Whitelist**: Only explicitly allowed commands can be executed
17//! 2. **Argument Sanitization**: Shell metacharacters are blocked in arguments
18//! 3. **Type-State Pattern**: Commands must be validated before execution
19//! 4. **Path Integration**: Path arguments use SafePath validation
20//! 5. **Length Limits**: Maximum 4096 characters to prevent buffer overflow
21//!
22//! ## Examples
23//!
24//! ```rust
25//! use crate::utils::safe_command::{SafeCommand, CommandName, CommandArg};
26//!
27//! // Valid command
28//! let cmd = SafeCommand::new("cargo")
29//! .unwrap()
30//! .arg("build")
31//! .unwrap()
32//! .arg("--release")
33//! .unwrap()
34//! .validate()
35//! .unwrap();
36//!
37//! // Invalid command (not in whitelist)
38//! assert!(SafeCommand::new("rm").is_err());
39//!
40//! // Invalid argument (shell metacharacter) is rejected
41//! let result = SafeCommand::new("cargo")
42//! .unwrap()
43//! .arg("build; rm -rf /");
44//! assert!(result.is_err());
45//! ```
46
47use crate::utils::error::{Error, Result};
48use crate::utils::safe_path::SafePath;
49use std::convert::TryFrom;
50use std::fmt;
51use std::process::Command;
52
53/// Maximum allowed command length (including all arguments)
54const MAX_COMMAND_LENGTH: usize = 4096;
55
56/// Shell metacharacters that are blocked in command arguments
57const SHELL_METACHARACTERS: &[char] = &[';', '|', '&', '>', '<', '$', '`', '\n', '\r'];
58
59/// Whitelist of allowed commands
60const ALLOWED_COMMANDS: &[&str] = &[
61 "cargo",
62 "git",
63 "npm",
64 "rustc",
65 "rustfmt",
66 "clippy-driver",
67 "timeout",
68 "make",
69 "cmake",
70 "sh", // Only when explicitly needed with validated scripts
71 "bash", // Only when explicitly needed with validated scripts
72 "ggen", // Our own CLI
73 "ls", // Added for testing
74 "echo", // Added for testing
75];
76
77/// A validated command name from the whitelist
78///
79/// This newtype ensures that only whitelisted commands can be constructed.
80#[derive(Debug, Clone, PartialEq, Eq, Hash)]
81pub struct CommandName {
82 /// Inner command name - private to prevent direct mutation
83 inner: String,
84}
85
86impl CommandName {
87 /// Create a new CommandName from a string
88 ///
89 /// # Validation Rules
90 ///
91 /// - Command must be in the whitelist
92 /// - Command name cannot be empty
93 /// - Command name cannot contain whitespace
94 ///
95 /// # Examples
96 ///
97 /// ```rust
98 /// use crate::utils::safe_command::CommandName;
99 ///
100 /// // Valid commands
101 /// assert!(CommandName::new("cargo").is_ok());
102 /// assert!(CommandName::new("git").is_ok());
103 ///
104 /// // Invalid commands
105 /// assert!(CommandName::new("rm").is_err());
106 /// assert!(CommandName::new("").is_err());
107 /// ```
108 pub fn new<S: AsRef<str>>(name: S) -> Result<Self> {
109 let name = name.as_ref();
110
111 // Check for empty
112 if name.is_empty() {
113 return Err(Error::invalid_input("Command name cannot be empty"));
114 }
115
116 // Check for whitespace
117 if name.contains(char::is_whitespace) {
118 return Err(Error::invalid_input(
119 "Command name cannot contain whitespace",
120 ));
121 }
122
123 // Check whitelist
124 if !ALLOWED_COMMANDS.contains(&name) {
125 return Err(Error::invalid_input(format!(
126 "Command '{}' is not in whitelist. Allowed commands: {:?}",
127 name, ALLOWED_COMMANDS
128 )));
129 }
130
131 Ok(Self {
132 inner: name.to_string(),
133 })
134 }
135
136 /// Get the command name as a string slice
137 #[must_use]
138 pub fn as_str(&self) -> &str {
139 &self.inner
140 }
141
142 /// Convert into the inner String
143 #[must_use]
144 pub fn into_string(self) -> String {
145 self.inner
146 }
147}
148
149impl TryFrom<&str> for CommandName {
150 type Error = Error;
151
152 fn try_from(value: &str) -> Result<Self> {
153 Self::new(value)
154 }
155}
156
157impl TryFrom<String> for CommandName {
158 type Error = Error;
159
160 fn try_from(value: String) -> Result<Self> {
161 Self::new(value)
162 }
163}
164
165impl fmt::Display for CommandName {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 write!(f, "{}", self.inner)
168 }
169}
170
171/// A validated command argument with sanitization
172///
173/// This newtype ensures that command arguments do not contain shell metacharacters
174/// that could lead to command injection attacks.
175#[derive(Debug, Clone, PartialEq, Eq, Hash)]
176pub struct CommandArg {
177 /// Inner argument - private to prevent direct mutation
178 inner: String,
179}
180
181impl CommandArg {
182 /// Create a new CommandArg from a string
183 ///
184 /// # Validation Rules
185 ///
186 /// - Argument cannot contain shell metacharacters (;|&><$`\n\r)
187 /// - Argument can be empty (for flags like --release)
188 ///
189 /// # Examples
190 ///
191 /// ```rust
192 /// use crate::utils::safe_command::CommandArg;
193 ///
194 /// // Valid arguments
195 /// assert!(CommandArg::new("build").is_ok());
196 /// assert!(CommandArg::new("--release").is_ok());
197 /// assert!(CommandArg::new("").is_ok());
198 ///
199 /// // Invalid arguments (shell metacharacters)
200 /// assert!(CommandArg::new("build; rm -rf /").is_err());
201 /// assert!(CommandArg::new("build | tee").is_err());
202 /// assert!(CommandArg::new("$(whoami)").is_err());
203 /// ```
204 pub fn new<S: AsRef<str>>(arg: S) -> Result<Self> {
205 let arg = arg.as_ref();
206
207 // Check for shell metacharacters
208 for ch in SHELL_METACHARACTERS {
209 if arg.contains(*ch) {
210 return Err(Error::invalid_input(format!(
211 "Argument contains shell metacharacter '{}': {}",
212 ch, arg
213 )));
214 }
215 }
216
217 Ok(Self {
218 inner: arg.to_string(),
219 })
220 }
221
222 /// Create a CommandArg from a SafePath
223 ///
224 /// This ensures that path arguments are validated through SafePath.
225 ///
226 /// # Examples
227 ///
228 /// ```rust
229 /// use crate::utils::safe_command::CommandArg;
230 /// use crate::utils::safe_path::SafePath;
231 ///
232 /// let path = SafePath::new("src/generated").unwrap();
233 /// let arg = CommandArg::from_path(&path);
234 /// assert_eq!(arg.as_str(), "src/generated");
235 /// ```
236 #[must_use]
237 pub fn from_path(path: &SafePath) -> Self {
238 // SafePath already validated, so we can safely convert
239 // We know it doesn't contain shell metacharacters
240 Self {
241 inner: path.as_path().display().to_string(),
242 }
243 }
244
245 /// Get the argument as a string slice
246 #[must_use]
247 pub fn as_str(&self) -> &str {
248 &self.inner
249 }
250
251 /// Convert into the inner String
252 #[must_use]
253 pub fn into_string(self) -> String {
254 self.inner
255 }
256}
257
258impl TryFrom<&str> for CommandArg {
259 type Error = Error;
260
261 fn try_from(value: &str) -> Result<Self> {
262 Self::new(value)
263 }
264}
265
266impl TryFrom<String> for CommandArg {
267 type Error = Error;
268
269 fn try_from(value: String) -> Result<Self> {
270 Self::new(value)
271 }
272}
273
274impl fmt::Display for CommandArg {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 write!(f, "{}", self.inner)
277 }
278}
279
280/// Type-state marker for unvalidated commands
281#[derive(Debug)]
282pub struct Unvalidated;
283
284/// Type-state marker for validated commands
285#[derive(Debug, Clone)]
286pub struct Validated;
287
288/// A safe command builder with type-state pattern
289///
290/// Commands must be validated before they can be executed. The type-state pattern
291/// ensures this at compile time.
292///
293/// # Type States
294///
295/// - `SafeCommand<Unvalidated>`: Command is being built, not yet validated
296/// - `SafeCommand<Validated>`: Command has been validated and can be executed
297///
298/// # Examples
299///
300/// ```rust
301/// use crate::utils::safe_command::SafeCommand;
302///
303/// // Build and validate command
304/// let cmd = SafeCommand::new("cargo")
305/// .unwrap()
306/// .arg("build")
307/// .unwrap()
308/// .arg("--release")
309/// .unwrap()
310/// .validate()
311/// .unwrap();
312///
313/// // Now cmd can be converted to std::process::Command
314/// let process_cmd = cmd.into_command();
315/// ```
316#[derive(Debug, Clone)]
317pub struct SafeCommand<State = Unvalidated> {
318 /// Validated command name
319 command: CommandName,
320 /// List of validated arguments
321 args: Vec<CommandArg>,
322 /// Type-state marker
323 _state: std::marker::PhantomData<State>,
324}
325
326impl SafeCommand<Unvalidated> {
327 /// Create a new SafeCommand with a validated command name
328 ///
329 /// # Examples
330 ///
331 /// ```rust
332 /// use crate::utils::safe_command::SafeCommand;
333 ///
334 /// let cmd = SafeCommand::new("cargo").unwrap();
335 /// assert!(SafeCommand::new("rm").is_err());
336 /// ```
337 pub fn new<S: AsRef<str>>(command: S) -> Result<Self> {
338 let command = CommandName::new(command)?;
339 Ok(Self {
340 command,
341 args: Vec::new(),
342 _state: std::marker::PhantomData,
343 })
344 }
345
346 /// Add an argument to the command
347 ///
348 /// # Examples
349 ///
350 /// ```rust
351 /// use crate::utils::safe_command::SafeCommand;
352 ///
353 /// let cmd = SafeCommand::new("cargo")
354 /// .unwrap()
355 /// .arg("build")
356 /// .unwrap()
357 /// .arg("--release")
358 /// .unwrap();
359 /// ```
360 pub fn arg<S: AsRef<str>>(mut self, arg: S) -> Result<Self> {
361 let arg = CommandArg::new(arg)?;
362 self.args.push(arg);
363 Ok(self)
364 }
365
366 /// Add a path argument to the command
367 ///
368 /// This ensures path arguments are validated through SafePath.
369 ///
370 /// # Examples
371 ///
372 /// ```rust
373 /// use crate::utils::safe_command::SafeCommand;
374 /// use crate::utils::safe_path::SafePath;
375 ///
376 /// let path = SafePath::new("src/generated").unwrap();
377 /// let cmd = SafeCommand::new("cargo")
378 /// .unwrap()
379 /// .arg("build")
380 /// .unwrap()
381 /// .arg_path(&path);
382 /// ```
383 #[must_use]
384 pub fn arg_path(mut self, path: &SafePath) -> Self {
385 let arg = CommandArg::from_path(path);
386 self.args.push(arg);
387 self
388 }
389
390 /// Add multiple arguments at once
391 ///
392 /// # Examples
393 ///
394 /// ```rust
395 /// use crate::utils::safe_command::SafeCommand;
396 ///
397 /// let cmd = SafeCommand::new("cargo")
398 /// .unwrap()
399 /// .args(&["build", "--release"])
400 /// .unwrap();
401 /// ```
402 pub fn args<I, S>(mut self, args: I) -> Result<Self>
403 where
404 I: IntoIterator<Item = S>,
405 S: AsRef<str>,
406 {
407 for arg in args {
408 let validated_arg = CommandArg::new(arg)?;
409 self.args.push(validated_arg);
410 }
411 Ok(self)
412 }
413
414 /// Validate the command and transition to Validated state
415 ///
416 /// This performs final validation including total command length check.
417 ///
418 /// # Examples
419 ///
420 /// ```rust
421 /// use crate::utils::safe_command::SafeCommand;
422 ///
423 /// let cmd = SafeCommand::new("cargo")
424 /// .unwrap()
425 /// .arg("build")
426 /// .unwrap()
427 /// .validate()
428 /// .unwrap();
429 /// ```
430 pub fn validate(self) -> Result<SafeCommand<Validated>> {
431 // Calculate total command length
432 let total_length = self.total_length();
433
434 if total_length > MAX_COMMAND_LENGTH {
435 return Err(Error::invalid_input(format!(
436 "Command length {} exceeds maximum allowed length of {}",
437 total_length, MAX_COMMAND_LENGTH
438 )));
439 }
440
441 Ok(SafeCommand {
442 command: self.command,
443 args: self.args,
444 _state: std::marker::PhantomData,
445 })
446 }
447
448 /// Calculate total command length (command + args + spaces)
449 fn total_length(&self) -> usize {
450 let mut length = self.command.as_str().len();
451
452 for arg in &self.args {
453 length += 1; // space
454 length += arg.as_str().len();
455 }
456
457 length
458 }
459}
460
461impl SafeCommand<Validated> {
462 /// Convert this SafeCommand into a std::process::Command
463 ///
464 /// This is only available for validated commands.
465 ///
466 /// # Examples
467 ///
468 /// ```rust
469 /// use crate::utils::safe_command::SafeCommand;
470 ///
471 /// let safe_cmd = SafeCommand::new("cargo")
472 /// .unwrap()
473 /// .arg("--version")
474 /// .unwrap()
475 /// .validate()
476 /// .unwrap();
477 ///
478 /// let mut cmd = safe_cmd.into_command();
479 /// // Now you can execute cmd with std::process::Command
480 /// ```
481 #[must_use]
482 pub fn into_command(self) -> Command {
483 let mut cmd = Command::new(self.command.as_str());
484
485 for arg in self.args {
486 cmd.arg(arg.as_str());
487 }
488
489 cmd
490 }
491
492 /// Get a reference to the command name
493 #[must_use]
494 pub fn command(&self) -> &CommandName {
495 &self.command
496 }
497
498 /// Get a reference to the arguments
499 #[must_use]
500 pub fn args(&self) -> &[CommandArg] {
501 &self.args
502 }
503
504 /// Get the command as a string for display purposes
505 ///
506 /// This does NOT execute the command, it just formats it as a string.
507 #[must_use]
508 pub fn to_string_debug(&self) -> String {
509 let mut result = self.command.as_str().to_string();
510
511 for arg in &self.args {
512 result.push(' ');
513 result.push_str(arg.as_str());
514 }
515
516 result
517 }
518}
519
520impl fmt::Display for SafeCommand<Validated> {
521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 write!(f, "{}", self.to_string_debug())
523 }
524}
525
526#[cfg(test)]
527mod tests {
528 use super::*;
529
530 // ============================================================================
531 // CommandName Tests
532 // ============================================================================
533
534 #[test]
535 fn test_command_name_valid() {
536 // Arrange
537 let name = "cargo";
538
539 // Act
540 let result = CommandName::new(name);
541
542 // Assert
543 assert!(result.is_ok());
544 assert_eq!(result.unwrap().as_str(), "cargo");
545 }
546
547 #[test]
548 fn test_command_name_all_whitelisted() {
549 // Arrange & Act & Assert
550 for &cmd in ALLOWED_COMMANDS {
551 let result = CommandName::new(cmd);
552 assert!(result.is_ok(), "Should allow whitelisted command: {}", cmd);
553 }
554 }
555
556 #[test]
557 fn test_command_name_not_whitelisted() {
558 // Arrange
559 let dangerous_commands = vec!["rm", "mv", "dd", "mkfs", "kill"];
560
561 // Act & Assert
562 for cmd in dangerous_commands {
563 let result = CommandName::new(cmd);
564 assert!(
565 result.is_err(),
566 "Should block non-whitelisted command: {}",
567 cmd
568 );
569 assert!(
570 result.unwrap_err().to_string().contains("not in whitelist"),
571 "Error should mention whitelist"
572 );
573 }
574 }
575
576 #[test]
577 fn test_command_name_empty() {
578 // Arrange
579 let name = "";
580
581 // Act
582 let result = CommandName::new(name);
583
584 // Assert
585 assert!(result.is_err());
586 assert!(result.unwrap_err().to_string().contains("cannot be empty"));
587 }
588
589 #[test]
590 fn test_command_name_with_whitespace() {
591 // Arrange
592 let name = "cargo build";
593
594 // Act
595 let result = CommandName::new(name);
596
597 // Assert
598 assert!(result.is_err());
599 assert!(result.unwrap_err().to_string().contains("whitespace"));
600 }
601
602 #[test]
603 fn test_command_name_try_from_str() {
604 // Arrange
605 let name = "git";
606
607 // Act
608 let result = CommandName::try_from(name);
609
610 // Assert
611 assert!(result.is_ok());
612 assert_eq!(result.unwrap().as_str(), "git");
613 }
614
615 #[test]
616 fn test_command_name_try_from_string() {
617 // Arrange
618 let name = String::from("npm");
619
620 // Act
621 let result = CommandName::try_from(name);
622
623 // Assert
624 assert!(result.is_ok());
625 assert_eq!(result.unwrap().as_str(), "npm");
626 }
627
628 #[test]
629 fn test_command_name_display() {
630 // Arrange
631 let name = CommandName::new("cargo").unwrap();
632
633 // Act
634 let display = format!("{}", name);
635
636 // Assert
637 assert_eq!(display, "cargo");
638 }
639
640 // ============================================================================
641 // CommandArg Tests
642 // ============================================================================
643
644 #[test]
645 fn test_command_arg_valid() {
646 // Arrange
647 let arg = "build";
648
649 // Act
650 let result = CommandArg::new(arg);
651
652 // Assert
653 assert!(result.is_ok());
654 assert_eq!(result.unwrap().as_str(), "build");
655 }
656
657 #[test]
658 fn test_command_arg_with_dashes() {
659 // Arrange
660 let args = vec!["--release", "-v", "--all-features"];
661
662 // Act & Assert
663 for arg in args {
664 let result = CommandArg::new(arg);
665 assert!(result.is_ok(), "Should allow arg with dashes: {}", arg);
666 }
667 }
668
669 #[test]
670 fn test_command_arg_empty() {
671 // Arrange
672 let arg = "";
673
674 // Act
675 let result = CommandArg::new(arg);
676
677 // Assert - empty args are allowed (for compatibility)
678 assert!(result.is_ok());
679 }
680
681 #[test]
682 fn test_command_arg_shell_metacharacters() {
683 // Arrange
684 let attacks = vec![
685 ("build; rm -rf /", ';'),
686 ("build | tee output", '|'),
687 ("build && rm -rf /", '&'),
688 ("build > /dev/null", '>'),
689 ("build < input", '<'),
690 ("$(whoami)", '$'),
691 ("`whoami`", '`'),
692 ("build\nrm -rf /", '\n'),
693 ("build\rrm -rf /", '\r'),
694 ];
695
696 // Act & Assert
697 for (attack, metachar) in attacks {
698 let result = CommandArg::new(attack);
699 assert!(
700 result.is_err(),
701 "Should block shell metacharacter: {}",
702 metachar
703 );
704 assert!(
705 result.unwrap_err().to_string().contains("metacharacter"),
706 "Error should mention metacharacter"
707 );
708 }
709 }
710
711 #[test]
712 fn test_command_arg_from_path() {
713 // Arrange
714 let path = SafePath::new("src/generated").unwrap();
715
716 // Act
717 let arg = CommandArg::from_path(&path);
718
719 // Assert
720 assert_eq!(arg.as_str(), "src/generated");
721 }
722
723 #[test]
724 fn test_command_arg_try_from() {
725 // Arrange
726 let arg_str = "--release";
727
728 // Act
729 let result = CommandArg::try_from(arg_str);
730
731 // Assert
732 assert!(result.is_ok());
733 assert_eq!(result.unwrap().as_str(), "--release");
734 }
735
736 // ============================================================================
737 // SafeCommand Basic Tests
738 // ============================================================================
739
740 #[test]
741 fn test_safe_command_new() {
742 // Arrange
743 let cmd = "cargo";
744
745 // Act
746 let result = SafeCommand::new(cmd);
747
748 // Assert
749 assert!(result.is_ok());
750 }
751
752 #[test]
753 fn test_safe_command_new_invalid() {
754 // Arrange
755 let cmd = "rm";
756
757 // Act
758 let result = SafeCommand::new(cmd);
759
760 // Assert
761 assert!(result.is_err());
762 assert!(result.unwrap_err().to_string().contains("not in whitelist"));
763 }
764
765 #[test]
766 fn test_safe_command_single_arg() {
767 // Arrange & Act
768 let result = SafeCommand::new("cargo").unwrap().arg("build");
769
770 // Assert
771 assert!(result.is_ok());
772 }
773
774 #[test]
775 fn test_safe_command_multiple_args() {
776 // Arrange & Act
777 let result = SafeCommand::new("cargo")
778 .unwrap()
779 .arg("build")
780 .unwrap()
781 .arg("--release")
782 .unwrap()
783 .arg("--all-features");
784
785 // Assert
786 assert!(result.is_ok());
787 }
788
789 #[test]
790 fn test_safe_command_args_bulk() {
791 // Arrange & Act
792 let result =
793 SafeCommand::new("cargo")
794 .unwrap()
795 .args(["build", "--release", "--all-features"]);
796
797 // Assert
798 assert!(result.is_ok());
799 }
800
801 #[test]
802 fn test_safe_command_arg_path() {
803 // Arrange
804 let path = SafePath::new("src/generated").unwrap();
805
806 // Act
807 let cmd = SafeCommand::new("cargo")
808 .unwrap()
809 .arg("build")
810 .unwrap()
811 .arg_path(&path);
812
813 // Assert - arg_path is infallible (uses already-validated SafePath)
814 let validated = cmd.validate();
815 assert!(validated.is_ok());
816 }
817
818 #[test]
819 fn test_safe_command_validate_success() {
820 // Arrange
821 let cmd = SafeCommand::new("cargo")
822 .unwrap()
823 .arg("build")
824 .unwrap()
825 .arg("--release")
826 .unwrap();
827
828 // Act
829 let result = cmd.validate();
830
831 // Assert
832 assert!(result.is_ok());
833 }
834
835 #[test]
836 fn test_safe_command_into_command() {
837 // Arrange
838 let safe_cmd = SafeCommand::new("cargo")
839 .unwrap()
840 .arg("--version")
841 .unwrap()
842 .validate()
843 .unwrap();
844
845 // Act
846 let process_cmd = safe_cmd.into_command();
847
848 // Assert - verify it creates a valid Command
849 // We can't easily test execution here, but we can verify it compiles
850 let _ = process_cmd;
851 }
852
853 #[test]
854 fn test_safe_command_to_string_debug() {
855 // Arrange
856 let cmd = SafeCommand::new("cargo")
857 .unwrap()
858 .arg("build")
859 .unwrap()
860 .arg("--release")
861 .unwrap()
862 .validate()
863 .unwrap();
864
865 // Act
866 let debug_string = cmd.to_string_debug();
867
868 // Assert
869 assert_eq!(debug_string, "cargo build --release");
870 }
871
872 #[test]
873 fn test_safe_command_display() {
874 // Arrange
875 let cmd = SafeCommand::new("git")
876 .unwrap()
877 .arg("status")
878 .unwrap()
879 .validate()
880 .unwrap();
881
882 // Act
883 let display = format!("{}", cmd);
884
885 // Assert
886 assert_eq!(display, "git status");
887 }
888
889 // ============================================================================
890 // SafeCommand Security Tests
891 // ============================================================================
892
893 #[test]
894 fn test_safe_command_injection_in_arg() {
895 // Arrange & Act
896 let result = SafeCommand::new("cargo").unwrap().arg("build; rm -rf /");
897
898 // Assert
899 assert!(result.is_err());
900 assert!(result.unwrap_err().to_string().contains("metacharacter"));
901 }
902
903 #[test]
904 fn test_safe_command_injection_in_multiple_args() {
905 // Arrange & Act
906 let result = SafeCommand::new("cargo")
907 .unwrap()
908 .arg("build")
909 .unwrap()
910 .arg("--release && rm -rf /");
911
912 // Assert
913 assert!(result.is_err());
914 }
915
916 #[test]
917 fn test_safe_command_max_length() {
918 // Arrange - create a command that exceeds MAX_COMMAND_LENGTH
919 let long_arg = "a".repeat(MAX_COMMAND_LENGTH);
920
921 // Act
922 let result = SafeCommand::new("cargo")
923 .unwrap()
924 .arg(&long_arg)
925 .unwrap()
926 .validate();
927
928 // Assert
929 assert!(result.is_err());
930 assert!(result.unwrap_err().to_string().contains("exceeds maximum"));
931 }
932
933 #[test]
934 fn test_safe_command_max_length_boundary() {
935 // Arrange - create a command at exactly MAX_COMMAND_LENGTH
936 // "cargo" = 5 chars
937 // " " = 1 char
938 // So we need MAX_COMMAND_LENGTH - 6 chars for the arg
939 let arg_length = MAX_COMMAND_LENGTH - 6;
940 let exact_arg = "a".repeat(arg_length);
941
942 // Act
943 let result = SafeCommand::new("cargo")
944 .unwrap()
945 .arg(&exact_arg)
946 .unwrap()
947 .validate();
948
949 // Assert - should succeed at exact boundary
950 assert!(result.is_ok());
951 }
952
953 #[test]
954 fn test_safe_command_command_and_args_accessors() {
955 // Arrange
956 let cmd = SafeCommand::new("cargo")
957 .unwrap()
958 .arg("build")
959 .unwrap()
960 .arg("--release")
961 .unwrap()
962 .validate()
963 .unwrap();
964
965 // Act
966 let command = cmd.command();
967 let args = cmd.args();
968
969 // Assert
970 assert_eq!(command.as_str(), "cargo");
971 assert_eq!(args.len(), 2);
972 assert_eq!(args[0].as_str(), "build");
973 assert_eq!(args[1].as_str(), "--release");
974 }
975
976 // ============================================================================
977 // Integration with SafePath Tests
978 // ============================================================================
979
980 #[test]
981 fn test_safe_command_with_safe_path() {
982 // Arrange
983 let path = SafePath::new("src/generated/output.rs").unwrap();
984
985 // Act
986 let cmd = SafeCommand::new("rustfmt")
987 .unwrap()
988 .arg_path(&path)
989 .validate()
990 .unwrap();
991
992 // Assert
993 let debug_string = cmd.to_string_debug();
994 assert!(debug_string.contains("src/generated/output.rs"));
995 }
996
997 #[test]
998 fn test_safe_command_multiple_paths() {
999 // Arrange
1000 let path1 = SafePath::new("src/main.rs").unwrap();
1001 let path2 = SafePath::new("src/lib.rs").unwrap();
1002
1003 // Act
1004 let cmd = SafeCommand::new("rustfmt")
1005 .unwrap()
1006 .arg_path(&path1)
1007 .arg_path(&path2)
1008 .validate()
1009 .unwrap();
1010
1011 // Assert
1012 let debug_string = cmd.to_string_debug();
1013 assert!(debug_string.contains("src/main.rs"));
1014 assert!(debug_string.contains("src/lib.rs"));
1015 }
1016
1017 // ============================================================================
1018 // Edge Cases
1019 // ============================================================================
1020
1021 #[test]
1022 fn test_safe_command_no_args() {
1023 // Arrange & Act
1024 let result = SafeCommand::new("git").unwrap().validate();
1025
1026 // Assert - command with no args should be valid
1027 assert!(result.is_ok());
1028 }
1029
1030 #[test]
1031 fn test_safe_command_many_small_args() {
1032 // Arrange - create many small args
1033 let mut cmd = SafeCommand::new("cargo").unwrap();
1034
1035 for i in 0..100 {
1036 cmd = cmd.arg(format!("arg{}", i)).unwrap();
1037 }
1038
1039 // Act
1040 let result = cmd.validate();
1041
1042 // Assert - should succeed if under max length
1043 assert!(result.is_ok());
1044 }
1045
1046 #[test]
1047 fn test_command_name_clone() {
1048 // Arrange
1049 let name = CommandName::new("cargo").unwrap();
1050
1051 // Act
1052 let cloned = name.clone();
1053
1054 // Assert
1055 assert_eq!(name, cloned);
1056 }
1057
1058 #[test]
1059 fn test_command_arg_clone() {
1060 // Arrange
1061 let arg = CommandArg::new("build").unwrap();
1062
1063 // Act
1064 let cloned = arg.clone();
1065
1066 // Assert
1067 assert_eq!(arg, cloned);
1068 }
1069
1070 #[test]
1071 fn test_safe_command_clone() {
1072 // Arrange
1073 let cmd = SafeCommand::new("cargo")
1074 .unwrap()
1075 .arg("build")
1076 .unwrap()
1077 .validate()
1078 .unwrap();
1079
1080 // Act
1081 let cloned = cmd.clone();
1082
1083 // Assert
1084 assert_eq!(cmd.to_string_debug(), cloned.to_string_debug());
1085 }
1086}