sprit-mutilagent 0.3.2

A robust command-line toolkit for managing multiple AI coding agents in isolated tmux sessions with comprehensive workspace management and health monitoring
Documentation
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
//! Security and validation utilities for the Sprite multi-agent workflow toolkit.
//!
//! This module provides functions for path validation, input sanitization,
//! and security checks needed for safe agent operations.

use crate::error::{SecurityViolationType, SpriteError};
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Maximum allowed path length to prevent path traversal attacks
#[allow(dead_code)]
const MAX_PATH_LENGTH: usize = 4096;

/// List of dangerous characters that should not be in file paths
#[allow(dead_code)]
const DANGEROUS_CHARS: &[char] = &[
    '\0', '<', '>', '|', '"', ';', '&', '$', '`', '(', ')', '[', ']', '{', '}',
];

/// Validate that a path is safe for agent operations.
#[allow(dead_code)]
pub fn validate_agent_path(path: &Path) -> Result<()> {
    // Check path length
    let path_str = path.to_string_lossy();
    if path_str.len() > MAX_PATH_LENGTH {
        return Err(SpriteError::security(
            format!(
                "Path too long: {} characters (max: {})",
                path_str.len(),
                MAX_PATH_LENGTH
            ),
            SecurityViolationType::InvalidPath,
        )
        .into());
    }

    // Check for dangerous characters
    for char in DANGEROUS_CHARS.iter() {
        if path_str.contains(*char) {
            return Err(SpriteError::security(
                format!("Path contains dangerous character '{}': {}", char, path_str),
                SecurityViolationType::InvalidPath,
            )
            .into());
        }
    }

    // Check for path traversal attempts
    if path_str.contains("..") {
        return Err(SpriteError::security(
            format!("Path traversal detected: {}", path_str),
            SecurityViolationType::PathTraversal,
        )
        .into());
    }

    // Check if path is absolute (should be relative to workspace)
    if path.is_absolute() {
        return Err(SpriteError::security(
            format!("Absolute paths not allowed: {}", path_str),
            SecurityViolationType::InvalidPath,
        )
        .into());
    }

    Ok(())
}

/// Validate that a directory path is safe and within allowed bounds.
#[allow(dead_code)]
pub fn validate_directory_path(path: &Path, base_dir: &Path) -> Result<()> {
    // First check that the original path doesn't contain dangerous patterns
    let path_str = path.to_string_lossy();

    // Check path length
    if path_str.len() > MAX_PATH_LENGTH {
        return Err(SpriteError::security(
            format!(
                "Path too long: {} characters (max: {})",
                path_str.len(),
                MAX_PATH_LENGTH
            ),
            SecurityViolationType::InvalidPath,
        )
        .into());
    }

    // Check for dangerous characters
    for char in DANGEROUS_CHARS.iter() {
        if path_str.contains(*char) {
            return Err(SpriteError::security(
                format!("Path contains dangerous character '{}': {}", char, path_str),
                SecurityViolationType::InvalidPath,
            )
            .into());
        }
    }

    // Check for path traversal attempts in the original path
    if path_str.contains("..") {
        return Err(SpriteError::security(
            format!("Path traversal detected: {}", path_str),
            SecurityViolationType::PathTraversal,
        )
        .into());
    }

    // Canonicalize both paths to resolve relative components
    let canonical_path = std::fs::canonicalize(path)
        .with_context(|| format!("Failed to canonicalize path: {}", path.display()))?;

    let canonical_base = std::fs::canonicalize(base_dir).with_context(|| {
        format!(
            "Failed to canonicalize base directory: {}",
            base_dir.display()
        )
    })?;

    // Check that the path is within the base directory
    if !canonical_path.starts_with(&canonical_base) {
        return Err(SpriteError::security(
            format!(
                "Path '{}' is outside of allowed base directory '{}'",
                canonical_path.display(),
                canonical_base.display()
            ),
            SecurityViolationType::PathTraversal,
        )
        .into());
    }

    Ok(())
}

/// Validate agent name for security and proper formatting.
#[allow(dead_code)]
pub fn validate_agent_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(SpriteError::security(
            "Agent name cannot be empty",
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    if name.len() > 64 {
        return Err(SpriteError::security(
            format!("Agent name too long: {} characters (max: 64)", name.len()),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Check for valid characters (alphanumeric, hyphen, underscore)
    if !name
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        return Err(SpriteError::security(
            format!("Agent name contains invalid characters: {}", name),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Name should not start with a hyphen or underscore
    if let Some(first_char) = name.chars().next() {
        if first_char == '-' || first_char == '_' {
            return Err(SpriteError::security(
                format!("Agent name cannot start with '{}': {}", first_char, name),
                SecurityViolationType::InvalidInput,
            )
            .into());
        }
    }

    // Name should not be a reserved system name
    let reserved_names = &[
        "root", "admin", "system", "daemon", "nobody", "www-data", "sprite", "control", "master",
        "main", "default",
    ];

    if reserved_names.contains(&name.to_lowercase().as_str()) {
        return Err(SpriteError::security(
            format!("Agent name '{}' is reserved and cannot be used", name),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    Ok(())
}

/// Validate session name for security and proper formatting.
#[allow(dead_code)]
pub fn validate_session_name(name: &str) -> Result<()> {
    // Use same validation as agent names for consistency
    validate_agent_name(name)?;

    // Additional session-specific validation could be added here
    if name.to_lowercase().contains("control") {
        return Err(SpriteError::security(
            format!("Session name containing 'control' is reserved: {}", name),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    Ok(())
}

/// Validate tmux session name for compatibility with tmux requirements.
#[allow(dead_code)]
pub fn validate_tmux_session_name(name: &str) -> Result<()> {
    validate_session_name(name)?;

    // Tmux has additional restrictions on session names
    if name.len() > 32 {
        return Err(SpriteError::security(
            format!(
                "Tmux session name too long: {} characters (max: 32)",
                name.len()
            ),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Tmux doesn't allow certain characters in session names
    if name.contains('.') || name.contains('@') || name.contains(':') {
        return Err(SpriteError::security(
            format!("Tmux session name contains invalid characters: {}", name),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    Ok(())
}

/// Validate git branch name for compatibility with git requirements.
#[allow(dead_code)]
pub fn validate_git_branch_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(SpriteError::security(
            "Git branch name cannot be empty",
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Git branch name restrictions
    if name.len() > 255 {
        return Err(SpriteError::security(
            format!(
                "Git branch name too long: {} characters (max: 255)",
                name.len()
            ),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Cannot start with a dot or slash
    if let Some(first_char) = name.chars().next() {
        if first_char == '.' || first_char == '/' {
            return Err(SpriteError::security(
                format!(
                    "Git branch name cannot start with '{}': {}",
                    first_char, name
                ),
                SecurityViolationType::InvalidInput,
            )
            .into());
        }
    }

    // Cannot end with a slash
    if let Some(last_char) = name.chars().last() {
        if last_char == '/' {
            return Err(SpriteError::security(
                format!("Git branch name cannot end with '{}': {}", last_char, name),
                SecurityViolationType::InvalidInput,
            )
            .into());
        }
    }

    // Cannot contain consecutive slashes
    if name.contains("//") {
        return Err(SpriteError::security(
            format!(
                "Git branch name cannot contain consecutive slashes: {}",
                name
            ),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Cannot contain certain characters
    let invalid_patterns = &["..", "~", "^", ":", "?", "*", "[", " ", "\t", "\n", "\r"];
    for invalid in invalid_patterns {
        if name.contains(invalid) {
            return Err(SpriteError::security(
                format!(
                    "Git branch name contains invalid sequence '{}': {}",
                    invalid, name
                ),
                SecurityViolationType::InvalidInput,
            )
            .into());
        }
    }

    // Cannot be a special git reference
    let reserved_refs = &[
        "HEAD",
        "ORIG_HEAD",
        "FETCH_HEAD",
        "MERGE_HEAD",
        "main",
        "master",
        "develop",
        "release",
        "hotfix",
    ];

    if reserved_refs.contains(&name) {
        return Err(SpriteError::security(
            format!("Git branch name '{}' is reserved", name),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    Ok(())
}

/// Sanitize a string input to remove potentially dangerous content.
#[allow(dead_code)]
pub fn sanitize_input(input: &str) -> String {
    input
        .chars()
        .map(|c| {
            // Convert newlines and carriage returns to spaces
            if c == '\n' || c == '\r' {
                ' '
            } else if c.is_ascii_graphic() || c == ' ' || c == '\t' {
                c
            } else {
                // Filter out dangerous characters
                '\0'
            }
        })
        .filter(|c| *c != '\0')
        .collect::<String>()
        .trim()
        .to_string()
}

/// Validate that a command is safe to execute.
#[allow(dead_code)]
pub fn validate_command(command: &str) -> Result<()> {
    if command.is_empty() {
        return Err(SpriteError::security(
            "Command cannot be empty",
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Check for dangerous command patterns
    let dangerous_patterns = &[
        "rm -rf /",
        "sudo rm",
        "chmod 777",
        "chown root",
        "dd if=",
        "mkfs",
        "format",
        "fdisk",
        "shutdown",
        "reboot",
        "iptables",
        "ufw",
        "firewall",
        "passwd",
        "su -",
        "sudo su",
        "curl | sh",
        "wget | sh",
        "eval $(curl",
        "eval $(wget",
        "> /dev/",
        "< /dev/",
        "&& rm",
        "; rm",
        "|| rm",
    ];

    let lower_command = command.to_lowercase();
    for pattern in dangerous_patterns.iter() {
        if lower_command.contains(&pattern.to_lowercase()) {
            return Err(SpriteError::security(
                format!(
                    "Command contains dangerous pattern '{}': {}",
                    pattern, command
                ),
                SecurityViolationType::UnsafeCommand,
            )
            .into());
        }
    }

    // Check for shell injection attempts
    if lower_command.contains("$(") || lower_command.contains("`") || lower_command.contains("${") {
        return Err(SpriteError::security(
            format!("Command contains potential shell injection: {}", command),
            SecurityViolationType::UnsafeCommand,
        )
        .into());
    }

    Ok(())
}

/// Validate that a URL is safe and uses allowed protocols.
#[allow(dead_code)]
pub fn validate_url(url: &str) -> Result<()> {
    if url.is_empty() {
        return Err(SpriteError::security(
            "URL cannot be empty",
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Check URL length
    if url.len() > 2048 {
        return Err(SpriteError::security(
            format!("URL too long: {} characters (max: 2048)", url.len()),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Check for allowed protocols
    let allowed_protocols = &["http://", "https://", "git://", "ssh://"];
    let has_allowed_protocol = allowed_protocols
        .iter()
        .any(|protocol| url.to_lowercase().starts_with(protocol));

    // Also check for SCP-style git URLs (user@host:path/repo.git)
    let is_scp_style = url.contains('@')
        && url.contains(':')
        && !url.starts_with("http://")
        && !url.starts_with("https://")
        && !url.starts_with("git://")
        && !url.starts_with("ssh://")
        && !url.contains("://");

    if !has_allowed_protocol && !is_scp_style {
        return Err(SpriteError::security(
            format!(
                "URL must use allowed protocol (http, https, git, ssh) or SCP-style git URL: {}",
                url
            ),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    // Check for dangerous URL patterns
    if url.contains("file://") || url.contains("ftp://") || url.contains("data:") {
        return Err(SpriteError::security(
            format!("URL uses disallowed protocol: {}", url),
            SecurityViolationType::InvalidInput,
        )
        .into());
    }

    Ok(())
}

/// Validate file permissions to ensure they're not too permissive.
#[allow(dead_code)]
pub fn validate_file_permissions(path: &Path) -> Result<()> {
    if !path.exists() {
        return Err(SpriteError::security(
            format!("File does not exist: {}", path.display()),
            SecurityViolationType::InvalidPath,
        )
        .into());
    }

    let metadata = std::fs::metadata(path)
        .with_context(|| format!("Failed to read file metadata: {}", path.display()))?;

    let permissions = metadata.permissions();

    // Check if file is readable/writable by others (security risk)
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = permissions.mode();

        // Check if readable or writable by others
        if mode & 0o044 != 0 {
            return Err(SpriteError::security(
                format!(
                    "File has overly permissive permissions (readable by others): {}",
                    path.display()
                ),
                SecurityViolationType::InsecurePermissions,
            )
            .into());
        }
    }

    Ok(())
}

/// Create a secure temporary directory with appropriate permissions.
#[allow(dead_code)]
pub fn create_secure_temp_dir(prefix: &str) -> Result<PathBuf> {
    let temp_dir = std::env::temp_dir();
    let secure_name = format!("{}_{}", sanitize_input(prefix), uuid::Uuid::new_v4());
    let temp_path = temp_dir.join(secure_name);

    std::fs::create_dir(&temp_path).with_context(|| {
        format!(
            "Failed to create temporary directory: {}",
            temp_path.display()
        )
    })?;

    // Set secure permissions (only owner can read/write/execute)
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let metadata = std::fs::metadata(&temp_path)?;
        let mut permissions = metadata.permissions();
        permissions.set_mode(0o700);
        std::fs::set_permissions(&temp_path, permissions)?;
    }

    Ok(temp_path)
}

/// Check if running in a secure environment.
#[allow(dead_code)]
pub fn check_environment_security() -> Result<()> {
    // Check if running as root (not recommended)
    #[cfg(unix)]
    {
        if unsafe { libc::getuid() } == 0 {
            return Err(SpriteError::security(
                "Running as root is not recommended for security reasons",
                SecurityViolationType::InsecureEnvironment,
            )
            .into());
        }
    }

    // Check if HOME directory is writable by others
    if let Ok(home) = std::env::var("HOME") {
        let home_path = Path::new(&home);
        if let Ok(metadata) = std::fs::metadata(home_path) {
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = metadata.permissions().mode();
                if mode & 0o022 != 0 {
                    return Err(SpriteError::security(
                        format!(
                            "Home directory has overly permissive permissions: {:o}",
                            mode
                        ),
                        SecurityViolationType::InsecureEnvironment,
                    )
                    .into());
                }
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_validate_agent_name() {
        assert!(validate_agent_name("agent-1").is_ok());
        assert!(validate_agent_name("agent_test").is_ok());

        assert!(validate_agent_name("").is_err());
        assert!(validate_agent_name("agent name").is_err());
        assert!(validate_agent_name("-agent").is_err());
        assert!(validate_agent_name("root").is_err());
        assert!(validate_agent_name(&"a".repeat(65)).is_err());
    }

    #[test]
    fn test_validate_agent_path() {
        assert!(validate_agent_path(Path::new("valid/path")).is_ok());
        assert!(validate_agent_path(Path::new("valid-file.txt")).is_ok());

        assert!(validate_agent_path(Path::new("../dangerous")).is_err());
        assert!(validate_agent_path(Path::new("/absolute/path")).is_err());
        assert!(validate_agent_path(Path::new("path/with<danger")).is_err());
    }

    #[test]
    fn test_validate_command() {
        assert!(validate_command("ls -la").is_ok());
        assert!(validate_command("cargo build").is_ok());

        assert!(validate_command("rm -rf /").is_err());
        assert!(validate_command("curl | sh").is_err());
        assert!(validate_command("eval $(curl url)").is_err());
    }

    #[test]
    fn test_validate_url() {
        assert!(validate_url("https://github.com/user/repo").is_ok());
        assert!(validate_url("git@github.com:user/repo.git").is_ok());

        assert!(validate_url("file:///etc/passwd").is_err());
        assert!(validate_url("ftp://example.com").is_err());
        assert!(validate_url("").is_err());
    }

    #[test]
    fn test_sanitize_input() {
        assert_eq!(sanitize_input("hello world"), "hello world");
        assert_eq!(sanitize_input("hello\x00world"), "helloworld");
        assert_eq!(sanitize_input("  trimmed  "), "trimmed");
        assert_eq!(sanitize_input("multiple\nlines"), "multiple lines");
    }

    #[test]
    fn test_validate_directory_path() {
        let temp_dir = TempDir::new().unwrap();
        let base_dir = temp_dir.path();

        // Create a subdirectory for testing
        let sub_dir = base_dir.join("test");
        std::fs::create_dir(&sub_dir).unwrap();

        assert!(validate_directory_path(&sub_dir, base_dir).is_ok());

        // Test path outside base directory (should fail)
        let outside_path = temp_dir.path().parent().unwrap().join("outside");
        assert!(validate_directory_path(&outside_path, base_dir).is_err());
    }

    #[test]
    fn test_create_secure_temp_dir() {
        let temp_dir = create_secure_temp_dir("test").unwrap();
        assert!(temp_dir.exists());
        assert!(temp_dir.is_dir());

        // Check permissions
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let metadata = std::fs::metadata(&temp_dir).unwrap();
            let mode = metadata.permissions().mode();
            assert_eq!(mode & 0o777, 0o700);
        }
    }
}