1use crate::error::{SecurityViolationType, SpriteError};
7use anyhow::{Context, Result};
8use std::path::{Path, PathBuf};
9
10#[allow(dead_code)]
12const MAX_PATH_LENGTH: usize = 4096;
13
14#[allow(dead_code)]
16const DANGEROUS_CHARS: &[char] = &[
17 '\0', '<', '>', '|', '"', ';', '&', '$', '`', '(', ')', '[', ']', '{', '}',
18];
19
20#[allow(dead_code)]
22pub fn validate_agent_path(path: &Path) -> Result<()> {
23 let path_str = path.to_string_lossy();
25 if path_str.len() > MAX_PATH_LENGTH {
26 return Err(SpriteError::security(
27 format!(
28 "Path too long: {} characters (max: {})",
29 path_str.len(),
30 MAX_PATH_LENGTH
31 ),
32 SecurityViolationType::InvalidPath,
33 )
34 .into());
35 }
36
37 for char in DANGEROUS_CHARS.iter() {
39 if path_str.contains(*char) {
40 return Err(SpriteError::security(
41 format!("Path contains dangerous character '{}': {}", char, path_str),
42 SecurityViolationType::InvalidPath,
43 )
44 .into());
45 }
46 }
47
48 if path_str.contains("..") {
50 return Err(SpriteError::security(
51 format!("Path traversal detected: {}", path_str),
52 SecurityViolationType::PathTraversal,
53 )
54 .into());
55 }
56
57 if path.is_absolute() {
59 return Err(SpriteError::security(
60 format!("Absolute paths not allowed: {}", path_str),
61 SecurityViolationType::InvalidPath,
62 )
63 .into());
64 }
65
66 Ok(())
67}
68
69#[allow(dead_code)]
71pub fn validate_directory_path(path: &Path, base_dir: &Path) -> Result<()> {
72 let path_str = path.to_string_lossy();
74
75 if path_str.len() > MAX_PATH_LENGTH {
77 return Err(SpriteError::security(
78 format!(
79 "Path too long: {} characters (max: {})",
80 path_str.len(),
81 MAX_PATH_LENGTH
82 ),
83 SecurityViolationType::InvalidPath,
84 )
85 .into());
86 }
87
88 for char in DANGEROUS_CHARS.iter() {
90 if path_str.contains(*char) {
91 return Err(SpriteError::security(
92 format!("Path contains dangerous character '{}': {}", char, path_str),
93 SecurityViolationType::InvalidPath,
94 )
95 .into());
96 }
97 }
98
99 if path_str.contains("..") {
101 return Err(SpriteError::security(
102 format!("Path traversal detected: {}", path_str),
103 SecurityViolationType::PathTraversal,
104 )
105 .into());
106 }
107
108 let canonical_path = std::fs::canonicalize(path)
110 .with_context(|| format!("Failed to canonicalize path: {}", path.display()))?;
111
112 let canonical_base = std::fs::canonicalize(base_dir).with_context(|| {
113 format!(
114 "Failed to canonicalize base directory: {}",
115 base_dir.display()
116 )
117 })?;
118
119 if !canonical_path.starts_with(&canonical_base) {
121 return Err(SpriteError::security(
122 format!(
123 "Path '{}' is outside of allowed base directory '{}'",
124 canonical_path.display(),
125 canonical_base.display()
126 ),
127 SecurityViolationType::PathTraversal,
128 )
129 .into());
130 }
131
132 Ok(())
133}
134
135#[allow(dead_code)]
137pub fn validate_agent_name(name: &str) -> Result<()> {
138 if name.is_empty() {
139 return Err(SpriteError::security(
140 "Agent name cannot be empty",
141 SecurityViolationType::InvalidInput,
142 )
143 .into());
144 }
145
146 if name.len() > 64 {
147 return Err(SpriteError::security(
148 format!("Agent name too long: {} characters (max: 64)", name.len()),
149 SecurityViolationType::InvalidInput,
150 )
151 .into());
152 }
153
154 if !name
156 .chars()
157 .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
158 {
159 return Err(SpriteError::security(
160 format!("Agent name contains invalid characters: {}", name),
161 SecurityViolationType::InvalidInput,
162 )
163 .into());
164 }
165
166 if let Some(first_char) = name.chars().next() {
168 if first_char == '-' || first_char == '_' {
169 return Err(SpriteError::security(
170 format!("Agent name cannot start with '{}': {}", first_char, name),
171 SecurityViolationType::InvalidInput,
172 )
173 .into());
174 }
175 }
176
177 let reserved_names = &[
179 "root", "admin", "system", "daemon", "nobody", "www-data", "sprite", "control", "master",
180 "main", "default",
181 ];
182
183 if reserved_names.contains(&name.to_lowercase().as_str()) {
184 return Err(SpriteError::security(
185 format!("Agent name '{}' is reserved and cannot be used", name),
186 SecurityViolationType::InvalidInput,
187 )
188 .into());
189 }
190
191 Ok(())
192}
193
194#[allow(dead_code)]
196pub fn validate_session_name(name: &str) -> Result<()> {
197 validate_agent_name(name)?;
199
200 if name.to_lowercase().contains("control") {
202 return Err(SpriteError::security(
203 format!("Session name containing 'control' is reserved: {}", name),
204 SecurityViolationType::InvalidInput,
205 )
206 .into());
207 }
208
209 Ok(())
210}
211
212#[allow(dead_code)]
214pub fn validate_tmux_session_name(name: &str) -> Result<()> {
215 validate_session_name(name)?;
216
217 if name.len() > 32 {
219 return Err(SpriteError::security(
220 format!(
221 "Tmux session name too long: {} characters (max: 32)",
222 name.len()
223 ),
224 SecurityViolationType::InvalidInput,
225 )
226 .into());
227 }
228
229 if name.contains('.') || name.contains('@') || name.contains(':') {
231 return Err(SpriteError::security(
232 format!("Tmux session name contains invalid characters: {}", name),
233 SecurityViolationType::InvalidInput,
234 )
235 .into());
236 }
237
238 Ok(())
239}
240
241#[allow(dead_code)]
243pub fn validate_git_branch_name(name: &str) -> Result<()> {
244 if name.is_empty() {
245 return Err(SpriteError::security(
246 "Git branch name cannot be empty",
247 SecurityViolationType::InvalidInput,
248 )
249 .into());
250 }
251
252 if name.len() > 255 {
254 return Err(SpriteError::security(
255 format!(
256 "Git branch name too long: {} characters (max: 255)",
257 name.len()
258 ),
259 SecurityViolationType::InvalidInput,
260 )
261 .into());
262 }
263
264 if let Some(first_char) = name.chars().next() {
266 if first_char == '.' || first_char == '/' {
267 return Err(SpriteError::security(
268 format!(
269 "Git branch name cannot start with '{}': {}",
270 first_char, name
271 ),
272 SecurityViolationType::InvalidInput,
273 )
274 .into());
275 }
276 }
277
278 if let Some(last_char) = name.chars().last() {
280 if last_char == '/' {
281 return Err(SpriteError::security(
282 format!("Git branch name cannot end with '{}': {}", last_char, name),
283 SecurityViolationType::InvalidInput,
284 )
285 .into());
286 }
287 }
288
289 if name.contains("//") {
291 return Err(SpriteError::security(
292 format!(
293 "Git branch name cannot contain consecutive slashes: {}",
294 name
295 ),
296 SecurityViolationType::InvalidInput,
297 )
298 .into());
299 }
300
301 let invalid_patterns = &["..", "~", "^", ":", "?", "*", "[", " ", "\t", "\n", "\r"];
303 for invalid in invalid_patterns {
304 if name.contains(invalid) {
305 return Err(SpriteError::security(
306 format!(
307 "Git branch name contains invalid sequence '{}': {}",
308 invalid, name
309 ),
310 SecurityViolationType::InvalidInput,
311 )
312 .into());
313 }
314 }
315
316 let reserved_refs = &[
318 "HEAD",
319 "ORIG_HEAD",
320 "FETCH_HEAD",
321 "MERGE_HEAD",
322 "main",
323 "master",
324 "develop",
325 "release",
326 "hotfix",
327 ];
328
329 if reserved_refs.contains(&name) {
330 return Err(SpriteError::security(
331 format!("Git branch name '{}' is reserved", name),
332 SecurityViolationType::InvalidInput,
333 )
334 .into());
335 }
336
337 Ok(())
338}
339
340#[allow(dead_code)]
342pub fn sanitize_input(input: &str) -> String {
343 input
344 .chars()
345 .map(|c| {
346 if c == '\n' || c == '\r' {
348 ' '
349 } else if c.is_ascii_graphic() || c == ' ' || c == '\t' {
350 c
351 } else {
352 '\0'
354 }
355 })
356 .filter(|c| *c != '\0')
357 .collect::<String>()
358 .trim()
359 .to_string()
360}
361
362#[allow(dead_code)]
364pub fn validate_command(command: &str) -> Result<()> {
365 if command.is_empty() {
366 return Err(SpriteError::security(
367 "Command cannot be empty",
368 SecurityViolationType::InvalidInput,
369 )
370 .into());
371 }
372
373 let dangerous_patterns = &[
375 "rm -rf /",
376 "sudo rm",
377 "chmod 777",
378 "chown root",
379 "dd if=",
380 "mkfs",
381 "format",
382 "fdisk",
383 "shutdown",
384 "reboot",
385 "iptables",
386 "ufw",
387 "firewall",
388 "passwd",
389 "su -",
390 "sudo su",
391 "curl | sh",
392 "wget | sh",
393 "eval $(curl",
394 "eval $(wget",
395 "> /dev/",
396 "< /dev/",
397 "&& rm",
398 "; rm",
399 "|| rm",
400 ];
401
402 let lower_command = command.to_lowercase();
403 for pattern in dangerous_patterns.iter() {
404 if lower_command.contains(&pattern.to_lowercase()) {
405 return Err(SpriteError::security(
406 format!(
407 "Command contains dangerous pattern '{}': {}",
408 pattern, command
409 ),
410 SecurityViolationType::UnsafeCommand,
411 )
412 .into());
413 }
414 }
415
416 if lower_command.contains("$(") || lower_command.contains("`") || lower_command.contains("${") {
418 return Err(SpriteError::security(
419 format!("Command contains potential shell injection: {}", command),
420 SecurityViolationType::UnsafeCommand,
421 )
422 .into());
423 }
424
425 Ok(())
426}
427
428#[allow(dead_code)]
430pub fn validate_url(url: &str) -> Result<()> {
431 if url.is_empty() {
432 return Err(SpriteError::security(
433 "URL cannot be empty",
434 SecurityViolationType::InvalidInput,
435 )
436 .into());
437 }
438
439 if url.len() > 2048 {
441 return Err(SpriteError::security(
442 format!("URL too long: {} characters (max: 2048)", url.len()),
443 SecurityViolationType::InvalidInput,
444 )
445 .into());
446 }
447
448 let allowed_protocols = &["http://", "https://", "git://", "ssh://"];
450 let has_allowed_protocol = allowed_protocols
451 .iter()
452 .any(|protocol| url.to_lowercase().starts_with(protocol));
453
454 let is_scp_style = url.contains('@')
456 && url.contains(':')
457 && !url.starts_with("http://")
458 && !url.starts_with("https://")
459 && !url.starts_with("git://")
460 && !url.starts_with("ssh://")
461 && !url.contains("://");
462
463 if !has_allowed_protocol && !is_scp_style {
464 return Err(SpriteError::security(
465 format!(
466 "URL must use allowed protocol (http, https, git, ssh) or SCP-style git URL: {}",
467 url
468 ),
469 SecurityViolationType::InvalidInput,
470 )
471 .into());
472 }
473
474 if url.contains("file://") || url.contains("ftp://") || url.contains("data:") {
476 return Err(SpriteError::security(
477 format!("URL uses disallowed protocol: {}", url),
478 SecurityViolationType::InvalidInput,
479 )
480 .into());
481 }
482
483 Ok(())
484}
485
486#[allow(dead_code)]
488pub fn validate_file_permissions(path: &Path) -> Result<()> {
489 if !path.exists() {
490 return Err(SpriteError::security(
491 format!("File does not exist: {}", path.display()),
492 SecurityViolationType::InvalidPath,
493 )
494 .into());
495 }
496
497 let metadata = std::fs::metadata(path)
498 .with_context(|| format!("Failed to read file metadata: {}", path.display()))?;
499
500 let permissions = metadata.permissions();
501
502 #[cfg(unix)]
504 {
505 use std::os::unix::fs::PermissionsExt;
506 let mode = permissions.mode();
507
508 if mode & 0o044 != 0 {
510 return Err(SpriteError::security(
511 format!(
512 "File has overly permissive permissions (readable by others): {}",
513 path.display()
514 ),
515 SecurityViolationType::InsecurePermissions,
516 )
517 .into());
518 }
519 }
520
521 Ok(())
522}
523
524#[allow(dead_code)]
526pub fn create_secure_temp_dir(prefix: &str) -> Result<PathBuf> {
527 let temp_dir = std::env::temp_dir();
528 let secure_name = format!("{}_{}", sanitize_input(prefix), uuid::Uuid::new_v4());
529 let temp_path = temp_dir.join(secure_name);
530
531 std::fs::create_dir(&temp_path).with_context(|| {
532 format!(
533 "Failed to create temporary directory: {}",
534 temp_path.display()
535 )
536 })?;
537
538 #[cfg(unix)]
540 {
541 use std::os::unix::fs::PermissionsExt;
542 let metadata = std::fs::metadata(&temp_path)?;
543 let mut permissions = metadata.permissions();
544 permissions.set_mode(0o700);
545 std::fs::set_permissions(&temp_path, permissions)?;
546 }
547
548 Ok(temp_path)
549}
550
551#[allow(dead_code)]
553pub fn check_environment_security() -> Result<()> {
554 #[cfg(unix)]
556 {
557 if unsafe { libc::getuid() } == 0 {
558 return Err(SpriteError::security(
559 "Running as root is not recommended for security reasons",
560 SecurityViolationType::InsecureEnvironment,
561 )
562 .into());
563 }
564 }
565
566 if let Ok(home) = std::env::var("HOME") {
568 let home_path = Path::new(&home);
569 if let Ok(metadata) = std::fs::metadata(home_path) {
570 #[cfg(unix)]
571 {
572 use std::os::unix::fs::PermissionsExt;
573 let mode = metadata.permissions().mode();
574 if mode & 0o022 != 0 {
575 return Err(SpriteError::security(
576 format!(
577 "Home directory has overly permissive permissions: {:o}",
578 mode
579 ),
580 SecurityViolationType::InsecureEnvironment,
581 )
582 .into());
583 }
584 }
585 }
586 }
587
588 Ok(())
589}
590
591#[cfg(test)]
592mod tests {
593 use super::*;
594 use tempfile::TempDir;
595
596 #[test]
597 fn test_validate_agent_name() {
598 assert!(validate_agent_name("agent-1").is_ok());
599 assert!(validate_agent_name("agent_test").is_ok());
600
601 assert!(validate_agent_name("").is_err());
602 assert!(validate_agent_name("agent name").is_err());
603 assert!(validate_agent_name("-agent").is_err());
604 assert!(validate_agent_name("root").is_err());
605 assert!(validate_agent_name(&"a".repeat(65)).is_err());
606 }
607
608 #[test]
609 fn test_validate_agent_path() {
610 assert!(validate_agent_path(Path::new("valid/path")).is_ok());
611 assert!(validate_agent_path(Path::new("valid-file.txt")).is_ok());
612
613 assert!(validate_agent_path(Path::new("../dangerous")).is_err());
614 assert!(validate_agent_path(Path::new("/absolute/path")).is_err());
615 assert!(validate_agent_path(Path::new("path/with<danger")).is_err());
616 }
617
618 #[test]
619 fn test_validate_command() {
620 assert!(validate_command("ls -la").is_ok());
621 assert!(validate_command("cargo build").is_ok());
622
623 assert!(validate_command("rm -rf /").is_err());
624 assert!(validate_command("curl | sh").is_err());
625 assert!(validate_command("eval $(curl url)").is_err());
626 }
627
628 #[test]
629 fn test_validate_url() {
630 assert!(validate_url("https://github.com/user/repo").is_ok());
631 assert!(validate_url("git@github.com:user/repo.git").is_ok());
632
633 assert!(validate_url("file:///etc/passwd").is_err());
634 assert!(validate_url("ftp://example.com").is_err());
635 assert!(validate_url("").is_err());
636 }
637
638 #[test]
639 fn test_sanitize_input() {
640 assert_eq!(sanitize_input("hello world"), "hello world");
641 assert_eq!(sanitize_input("hello\x00world"), "helloworld");
642 assert_eq!(sanitize_input(" trimmed "), "trimmed");
643 assert_eq!(sanitize_input("multiple\nlines"), "multiple lines");
644 }
645
646 #[test]
647 fn test_validate_directory_path() {
648 let temp_dir = TempDir::new().unwrap();
649 let base_dir = temp_dir.path();
650
651 let sub_dir = base_dir.join("test");
653 std::fs::create_dir(&sub_dir).unwrap();
654
655 assert!(validate_directory_path(&sub_dir, base_dir).is_ok());
656
657 let outside_path = temp_dir.path().parent().unwrap().join("outside");
659 assert!(validate_directory_path(&outside_path, base_dir).is_err());
660 }
661
662 #[test]
663 fn test_create_secure_temp_dir() {
664 let temp_dir = create_secure_temp_dir("test").unwrap();
665 assert!(temp_dir.exists());
666 assert!(temp_dir.is_dir());
667
668 #[cfg(unix)]
670 {
671 use std::os::unix::fs::PermissionsExt;
672 let metadata = std::fs::metadata(&temp_dir).unwrap();
673 let mode = metadata.permissions().mode();
674 assert_eq!(mode & 0o777, 0o700);
675 }
676 }
677}