ggen_core/security/
command.rs1use crate::utils::error::{Error, Result};
9use std::path::Path;
10use std::process::{Command, Output};
11
12#[derive(Debug, thiserror::Error)]
14pub enum CommandError {
15 #[error("Invalid command: {0}")]
16 InvalidCommand(String),
17
18 #[error("Command not allowed: {0}")]
19 NotAllowed(String),
20
21 #[error("Command execution failed: {0}")]
22 ExecutionFailed(String),
23
24 #[error("Invalid argument: {0}")]
25 InvalidArgument(String),
26
27 #[error("Command output invalid UTF-8")]
28 InvalidUtf8,
29}
30
31impl From<CommandError> for Error {
32 fn from(err: CommandError) -> Self {
33 Error::new(&err.to_string())
34 }
35}
36
37#[derive(Clone)]
66pub struct SafeCommand {
67 program: String,
68 args: Vec<String>,
69 current_dir: Option<String>,
70}
71
72impl SafeCommand {
73 const ALLOWED_COMMANDS: &'static [&'static str] = &[
75 "git", "cargo", "npm", "node", "rustc", "rustup", "ls", "echo",
76 ];
77
78 const DANGEROUS_CHARS: &'static [char] = &[
80 ';', '|', '&', '$', '`', '\n', '\r', '<', '>', '(', ')', '{', '}',
81 ];
82
83 pub fn new(program: &str) -> Result<Self> {
91 if program.is_empty() {
93 return Err(CommandError::InvalidCommand("Empty command".to_string()).into());
94 }
95
96 if program.chars().any(|c| Self::DANGEROUS_CHARS.contains(&c)) {
98 return Err(CommandError::InvalidCommand(format!(
99 "Command contains dangerous characters: {}",
100 program
101 ))
102 .into());
103 }
104
105 if !Self::ALLOWED_COMMANDS.contains(&program) {
107 return Err(CommandError::NotAllowed(format!(
108 "Command '{}' is not in allowed list",
109 program
110 ))
111 .into());
112 }
113
114 Ok(Self {
115 program: program.to_string(),
116 args: Vec::new(),
117 current_dir: None,
118 })
119 }
120
121 pub fn arg(mut self, arg: &str) -> Result<Self> {
128 if arg.chars().any(|c| Self::DANGEROUS_CHARS.contains(&c)) {
130 return Err(CommandError::InvalidArgument(format!(
131 "Argument contains dangerous characters: {}",
132 arg
133 ))
134 .into());
135 }
136
137 self.args.push(arg.to_string());
138 Ok(self)
139 }
140
141 pub fn args<I, S>(mut self, args: I) -> Result<Self>
143 where
144 I: IntoIterator<Item = S>,
145 S: AsRef<str>,
146 {
147 for arg in args {
148 self = self.arg(arg.as_ref())?;
149 }
150 Ok(self)
151 }
152
153 pub fn current_dir(mut self, dir: &Path) -> Result<Self> {
160 if !dir.exists() {
162 return Err(Error::new(&format!(
163 "Directory does not exist: {}",
164 dir.display()
165 )));
166 }
167
168 if !dir.is_dir() {
169 return Err(Error::new(&format!(
170 "Path is not a directory: {}",
171 dir.display()
172 )));
173 }
174
175 self.current_dir = Some(dir.to_string_lossy().to_string());
177 Ok(self)
178 }
179
180 pub fn execute(self) -> Result<Output> {
188 let mut cmd = Command::new(&self.program);
189
190 for arg in &self.args {
192 cmd.arg(arg);
193 }
194
195 if let Some(dir) = &self.current_dir {
197 cmd.current_dir(dir);
198 }
199
200 let output = cmd
202 .output()
203 .map_err(|e| CommandError::ExecutionFailed(format!("{}: {}", self.program, e)))?;
204
205 Ok(output)
206 }
207
208 pub fn execute_stdout(self) -> Result<String> {
215 let program = self.program.clone();
216 let output = self.execute()?;
217
218 if !output.status.success() {
219 let stderr = String::from_utf8_lossy(&output.stderr);
220 return Err(CommandError::ExecutionFailed(format!("{}: {}", program, stderr)).into());
221 }
222
223 String::from_utf8(output.stdout).map_err(|_| CommandError::InvalidUtf8.into())
224 }
225}
226
227pub struct CommandExecutor;
229
230impl CommandExecutor {
231 pub fn git(args: &[&str]) -> Result<Output> {
233 let mut cmd = SafeCommand::new("git")?;
234 for arg in args {
235 cmd = cmd.arg(arg)?;
236 }
237 cmd.execute()
238 }
239
240 pub fn cargo(args: &[&str]) -> Result<Output> {
242 let mut cmd = SafeCommand::new("cargo")?;
243 for arg in args {
244 cmd = cmd.arg(arg)?;
245 }
246 cmd.execute()
247 }
248
249 pub fn npm(args: &[&str]) -> Result<Output> {
251 let mut cmd = SafeCommand::new("npm")?;
252 for arg in args {
253 cmd = cmd.arg(arg)?;
254 }
255 cmd.execute()
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 #[test]
264 fn test_safe_command_new_validates_whitelist() {
265 assert!(SafeCommand::new("git").is_ok());
267 assert!(SafeCommand::new("cargo").is_ok());
268
269 assert!(SafeCommand::new("rm").is_err());
271 assert!(SafeCommand::new("sh").is_err());
272 }
273
274 #[test]
275 fn test_safe_command_rejects_dangerous_chars() {
276 assert!(SafeCommand::new("git; rm -rf /").is_err());
278 assert!(SafeCommand::new("git | cat").is_err());
279 assert!(SafeCommand::new("git && ls").is_err());
280
281 let cmd1 = SafeCommand::new("git").unwrap();
283 assert!(cmd1.arg("init; rm -rf /").is_err());
284
285 let cmd2 = SafeCommand::new("git").unwrap();
286 assert!(cmd2.arg("init | cat").is_err());
287 }
288
289 #[test]
290 fn test_safe_command_arg_validation() {
291 let cmd = SafeCommand::new("git").unwrap();
292
293 assert!(cmd.clone().arg("init").is_ok());
295 assert!(cmd.clone().arg("status").is_ok());
296
297 assert!(cmd.clone().arg("init; ls").is_err());
299 assert!(cmd.clone().arg("$(whoami)").is_err());
300 assert!(cmd.clone().arg("`whoami`").is_err());
301 }
302
303 #[test]
304 fn test_command_injection_prevention() {
305 let result = SafeCommand::new("git")
307 .unwrap()
308 .arg("init")
309 .unwrap()
310 .arg("; rm -rf /");
311
312 assert!(result.is_err());
313
314 let result = SafeCommand::new("git; whoami");
316 assert!(result.is_err());
317 }
318
319 #[test]
320 fn test_executor_git() {
321 let result = CommandExecutor::git(&["--version"]);
323 let _ = result;
325 }
326}