ggen-utils 26.5.5

Shared utilities for ggen
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
//! Comprehensive security tests for SafeCommand
//!
//! Tests all edge cases and attack vectors:
//! - Command injection variations
//! - Shell metacharacter attacks
//! - Path traversal in arguments
//! - Command length attacks
//! - Whitelist bypass attempts

use ggen_utils::safe_command::{CommandArg, CommandName, SafeCommand};
use ggen_utils::safe_path::SafePath;

// ============================================================================
// Command Injection Attack Tests
// ============================================================================

#[test]
fn test_command_injection_semicolon() {
    // Arrange
    let attacks = vec![
        "build; rm -rf /",
        "build ; rm -rf /",
        "build  ;  rm -rf /",
        "; rm -rf /",
    ];

    // Act & Assert
    for attack in attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(
            result.is_err(),
            "Should block semicolon injection: {}",
            attack
        );
        assert!(
            result.unwrap_err().to_string().contains("metacharacter"),
            "Error should mention metacharacter"
        );
    }
}

#[test]
fn test_command_injection_pipe() {
    // Arrange
    let attacks = vec![
        "build | tee output",
        "build|tee output",
        "build || echo hacked",
        "| cat /etc/passwd",
    ];

    // Act & Assert
    for attack in attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(result.is_err(), "Should block pipe injection: {}", attack);
    }
}

#[test]
fn test_command_injection_ampersand() {
    // Arrange
    let attacks = vec![
        "build & rm -rf /",
        "build&rm -rf /",
        "build && rm -rf /",
        "build&&rm -rf /",
        "& rm -rf /",
    ];

    // Act & Assert
    for attack in attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(
            result.is_err(),
            "Should block ampersand injection: {}",
            attack
        );
    }
}

#[test]
fn test_command_injection_redirection() {
    // Arrange
    let attacks = vec![
        "build > /etc/passwd",
        "build>> /etc/passwd",
        "build < /etc/passwd",
        "build 2>&1",
        "> /etc/passwd",
        "< /etc/passwd",
    ];

    // Act & Assert
    for attack in attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(
            result.is_err(),
            "Should block redirection injection: {}",
            attack
        );
    }
}

#[test]
fn test_command_injection_command_substitution() {
    // Arrange
    let attacks = vec![
        "$(whoami)",
        "$(rm -rf /)",
        "`whoami`",
        "`rm -rf /`",
        "build $(whoami)",
        "build `whoami`",
    ];

    // Act & Assert
    for attack in attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(
            result.is_err(),
            "Should block command substitution: {}",
            attack
        );
    }
}

#[test]
fn test_command_injection_newline() {
    // Arrange
    let attacks = vec![
        "build\nrm -rf /",
        "build\n\nrm -rf /",
        "\nrm -rf /",
        "build\rrm -rf /",
        "build\r\nrm -rf /",
    ];

    // Act & Assert
    for attack in attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(
            result.is_err(),
            "Should block newline injection: {:?}",
            attack
        );
    }
}

// ============================================================================
// Whitelist Bypass Tests
// ============================================================================

#[test]
fn test_whitelist_dangerous_commands() {
    // Arrange
    let dangerous = vec![
        "rm", "rmdir", "dd", "mkfs", "kill", "killall", "pkill", "sudo", "su", "chmod", "chown",
        "curl", "wget", "nc", "netcat", "telnet", "ssh", "scp", "rsync", "tar", "zip", "unzip",
        "7z",
    ];

    // Act & Assert
    for cmd in dangerous {
        let result = SafeCommand::new(cmd);
        assert!(result.is_err(), "Should block dangerous command: {}", cmd);
        assert!(
            result.unwrap_err().to_string().contains("not in whitelist"),
            "Error should mention whitelist for: {}",
            cmd
        );
    }
}

#[test]
fn test_whitelist_case_sensitivity() {
    // Arrange - uppercase versions of allowed commands
    let uppercase_attempts = vec!["CARGO", "GIT", "NPM", "Cargo", "Git", "Npm"];

    // Act & Assert
    for cmd in uppercase_attempts {
        let result = SafeCommand::new(cmd);
        assert!(result.is_err(), "Should be case-sensitive, block: {}", cmd);
    }
}

#[test]
fn test_whitelist_with_path() {
    // Arrange - attempts to use full paths
    let path_attempts = vec![
        "/usr/bin/cargo",
        "/bin/git",
        "./cargo",
        "../cargo",
        "~/cargo",
    ];

    // Act & Assert
    for cmd in path_attempts {
        let result = SafeCommand::new(cmd);
        assert!(
            result.is_err(),
            "Should block path-qualified commands: {}",
            cmd
        );
    }
}

#[test]
fn test_whitelist_with_whitespace() {
    // Arrange
    let whitespace_attempts = vec![
        "cargo ", " cargo", " cargo ", "car go", "cargo\t", "\tcargo",
    ];

    // Act & Assert
    for cmd in whitespace_attempts {
        let result = CommandName::new(cmd);
        assert!(
            result.is_err(),
            "Should block command with whitespace: {:?}",
            cmd
        );
    }
}

// ============================================================================
// Path Traversal in Arguments Tests
// ============================================================================

#[test]
fn test_path_argument_safe_path_validated() {
    // Arrange
    let safe_path = SafePath::new("src/generated").unwrap();

    // Act
    let cmd = SafeCommand::new("cargo")
        .unwrap()
        .arg_path(&safe_path)
        .validate();

    // Assert
    assert!(cmd.is_ok(), "SafePath arguments should be validated");
}

#[test]
fn test_path_argument_parent_dir_blocked() {
    // Arrange - try to pass parent dir as string argument
    let attacks = vec![
        "../../../etc/passwd",
        "../../etc/passwd",
        "../etc/passwd",
        "subdir/../../etc/passwd",
    ];

    // Act & Assert
    for attack in attacks {
        // Parent dirs don't contain shell metacharacters, so they pass CommandArg validation
        // But they should be blocked if user tries to create SafePath from them
        let result = SafePath::new(attack);
        assert!(
            result.is_err(),
            "SafePath should block path traversal: {}",
            attack
        );
    }
}

#[test]
fn test_safe_path_integration() {
    // Arrange
    let valid_path = SafePath::new("src/main.rs").unwrap();
    let invalid_path_str = "../../../etc/passwd";

    // Act - valid path
    let valid_cmd = SafeCommand::new("rustfmt")
        .unwrap()
        .arg_path(&valid_path)
        .validate();

    // Act - invalid path (can't create SafePath)
    let invalid_path = SafePath::new(invalid_path_str);

    // Assert
    assert!(valid_cmd.is_ok(), "Valid SafePath should work");
    assert!(invalid_path.is_err(), "Invalid path should be blocked");
}

// ============================================================================
// Length Attack Tests
// ============================================================================

#[test]
fn test_max_length_single_arg() {
    // Arrange - create argument that exceeds MAX_COMMAND_LENGTH (4096)
    let long_arg = "a".repeat(5000);

    // Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg(&long_arg)
        .unwrap()
        .validate();

    // Assert
    assert!(result.is_err(), "Should block command exceeding max length");
    assert!(
        result.unwrap_err().to_string().contains("exceeds maximum"),
        "Error should mention max length"
    );
}

#[test]
fn test_max_length_many_args() {
    // Arrange - create many args that together exceed MAX_COMMAND_LENGTH
    let mut cmd = SafeCommand::new("cargo").unwrap();

    // Add 500 args of 10 chars each = 5000 chars total (exceeds 4096)
    for i in 0..500 {
        cmd = cmd.arg(format!("arg_{:05}", i)).unwrap();
    }

    // Act
    let result = cmd.validate();

    // Assert
    assert!(result.is_err(), "Should block total length exceeding max");
}

#[test]
fn test_max_length_boundary() {
    // Arrange - create command at exactly MAX_COMMAND_LENGTH
    // "cargo" = 5 chars
    // " " + "build" = 1 + 5 = 6 chars
    // " " + arg = 1 + arg_len
    // Total = 5 + 6 + 1 + arg_len = 12 + arg_len
    // For total = 4096: arg_len = 4096 - 12 = 4084
    let boundary_arg = "a".repeat(4084);

    // Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("build")
        .unwrap()
        .arg(&boundary_arg)
        .unwrap()
        .validate();

    // Assert - should succeed at exact boundary
    assert!(
        result.is_ok(),
        "Should allow command at max length boundary"
    );
}

#[test]
fn test_max_length_just_over_boundary() {
    // Arrange - create command just over MAX_COMMAND_LENGTH
    let over_boundary_arg = "a".repeat(4086);

    // Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("build")
        .unwrap()
        .arg(&over_boundary_arg)
        .unwrap()
        .validate();

    // Assert
    assert!(result.is_err(), "Should block command just over max length");
}

// ============================================================================
// Combined Attack Tests
// ============================================================================

#[test]
fn test_combined_attack_injection_and_path() {
    // Arrange - combine command injection with path traversal
    let combined_attacks = vec![
        "../../etc/passwd; rm -rf /",
        "../../../etc/passwd | cat",
        "../../etc/passwd && whoami",
    ];

    // Act & Assert
    for attack in combined_attacks {
        let result = SafeCommand::new("cargo").unwrap().arg(attack);
        assert!(result.is_err(), "Should block combined attack: {}", attack);
    }
}

#[test]
fn test_combined_attack_multiple_stages() {
    // Arrange - try injection in different args
    let result1 = SafeCommand::new("cargo")
        .unwrap()
        .arg("build")
        .unwrap()
        .arg("--release");

    let result2 = result1.unwrap().arg("; rm -rf /");

    // Act & Assert
    assert!(result2.is_err(), "Should block injection in any arg");
}

// ============================================================================
// Encoding Attack Tests
// ============================================================================

#[test]
fn test_unicode_shell_metacharacters() {
    // Arrange - Unicode look-alikes (should be blocked if they match)
    // Note: Rust char matching is exact, so these won't match ASCII metacharacters
    // But we test to ensure no unexpected behavior
    let unicode_attacks = vec![
        "build|cat /etc/passwd", // Full-width pipe
        "buildï¼›rm -rf /",        // Full-width semicolon
        "build&rm -rf /",        // Full-width ampersand
    ];

    // Act & Assert
    for attack in unicode_attacks {
        // These won't be blocked by our ASCII metachar check, but they're also
        // not valid shell syntax, so they're safe in practice
        let result = CommandArg::new(attack);
        // If it passes (which it will), it's safe because shells don't interpret
        // full-width Unicode chars as metacharacters
        let _ = result;
    }
}

#[test]
fn test_null_byte_in_command() {
    // Arrange
    let null_attacks = vec!["cargo\0", "\0cargo", "car\0go"];

    // Act & Assert
    for attack in null_attacks {
        // Rust strings can contain null bytes, but they won't work as commands
        // Our whitelist check will catch these because they won't match exactly
        let result = CommandName::new(attack);
        assert!(
            result.is_err(),
            "Should block command with null byte: {:?}",
            attack
        );
    }
}

#[test]
fn test_null_byte_in_arg() {
    // Arrange
    let null_attacks = vec!["build\0", "\0", "build\0--release"];

    // Act & Assert
    for attack in null_attacks {
        // Null bytes are not in our metacharacter list, but they're dangerous
        // We should add them to be extra safe
        let result = CommandArg::new(attack);
        // Currently these would pass, but they're safe because std::process::Command
        // will reject them. We could add explicit null byte check for defense-in-depth.
        let _ = result;
    }
}

// ============================================================================
// Batch Validation Tests
// ============================================================================

#[test]
fn test_args_bulk_all_valid() {
    // Arrange
    let args = vec!["build", "--release", "--all-features"];

    // Act
    let result = SafeCommand::new("cargo").unwrap().args(&args);

    // Assert
    assert!(result.is_ok(), "All valid args should pass");
}

#[test]
fn test_args_bulk_one_invalid() {
    // Arrange
    let args = vec!["build", "--release; rm -rf /", "--all-features"];

    // Act
    let result = SafeCommand::new("cargo").unwrap().args(&args);

    // Assert
    assert!(result.is_err(), "Should fail on first invalid arg");
}

#[test]
fn test_args_bulk_empty_vec() {
    // Arrange
    let args: Vec<&str> = vec![];

    // Act
    let result = SafeCommand::new("cargo").unwrap().args(&args);

    // Assert
    assert!(result.is_ok(), "Empty args vec should be allowed");
}

// ============================================================================
// Real-World Usage Tests
// ============================================================================

#[test]
fn test_cargo_make_command() {
    // Arrange & Act
    let cmd = SafeCommand::new("cargo")
        .unwrap()
        .arg("make")
        .unwrap()
        .arg("test")
        .unwrap()
        .validate();

    // Assert
    assert!(cmd.is_ok());
    assert_eq!(cmd.unwrap().to_string_debug(), "cargo make test");
}

#[test]
fn test_git_status_command() {
    // Arrange & Act
    let cmd = SafeCommand::new("git")
        .unwrap()
        .arg("status")
        .unwrap()
        .validate();

    // Assert
    assert!(cmd.is_ok());
    assert_eq!(cmd.unwrap().to_string_debug(), "git status");
}

#[test]
fn test_timeout_wrapper() {
    // Arrange & Act
    let cmd = SafeCommand::new("timeout")
        .unwrap()
        .arg("5s")
        .unwrap()
        .arg("cargo")
        .unwrap()
        .arg("build")
        .unwrap()
        .validate();

    // Assert
    assert!(cmd.is_ok());
    assert_eq!(cmd.unwrap().to_string_debug(), "timeout 5s cargo build");
}

#[test]
fn test_rustfmt_with_path() {
    // Arrange
    let path = SafePath::new("src/generated/output.rs").unwrap();

    // Act
    let cmd = SafeCommand::new("rustfmt")
        .unwrap()
        .arg_path(&path)
        .validate();

    // Assert
    assert!(cmd.is_ok());
    let cmd_str = cmd.unwrap().to_string_debug();
    assert!(cmd_str.contains("rustfmt"));
    assert!(cmd_str.contains("src/generated/output.rs"));
}

// ============================================================================
// Edge Cases
// ============================================================================

#[test]
fn test_command_with_no_args() {
    // Arrange & Act
    let cmd = SafeCommand::new("git").unwrap().validate();

    // Assert
    assert!(cmd.is_ok(), "Command with no args should be valid");
}

#[test]
fn test_command_with_many_short_args() {
    // Arrange
    let mut cmd = SafeCommand::new("cargo").unwrap();

    // Add 1000 short args
    for i in 0..1000 {
        cmd = cmd.arg(format!("a{}", i)).unwrap();
    }

    // Act
    let result = cmd.validate();

    // Assert - will likely exceed max length
    // This is expected and should be blocked
    assert!(result.is_err(), "Many args should exceed max length");
}

#[test]
fn test_arg_with_equals_sign() {
    // Arrange & Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("--config=release")
        .unwrap()
        .validate();

    // Assert - equals sign is safe
    assert!(result.is_ok(), "Equals sign should be allowed in args");
}

#[test]
fn test_arg_with_colon() {
    // Arrange & Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("package:name")
        .unwrap()
        .validate();

    // Assert - colon is safe
    assert!(result.is_ok(), "Colon should be allowed in args");
}

#[test]
fn test_arg_with_slash() {
    // Arrange & Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("path/to/file")
        .unwrap()
        .validate();

    // Assert - slash is safe (for paths)
    assert!(result.is_ok(), "Slash should be allowed in args");
}

#[test]
fn test_arg_with_dot() {
    // Arrange & Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("file.rs")
        .unwrap()
        .validate();

    // Assert - dot is safe
    assert!(result.is_ok(), "Dot should be allowed in args");
}

#[test]
fn test_arg_with_underscore_and_dash() {
    // Arrange & Act
    let result = SafeCommand::new("cargo")
        .unwrap()
        .arg("my-package_name")
        .unwrap()
        .validate();

    // Assert
    assert!(
        result.is_ok(),
        "Underscore and dash should be allowed in args"
    );
}