bashkit 0.1.14

Virtual bash interpreter for multi-tenant environments
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
//! Archive builtins - tar, gzip, gunzip
//!
//! # Zip Bomb Protection
//!
//! All decompression operations check output size against filesystem limits
//! to prevent zip bomb attacks. Decompression is aborted early if the
//! output would exceed limits.

// Uses expect() for verified safe unwraps (e.g., strip_suffix after ends_with check)
#![allow(clippy::unwrap_used)]

use async_trait::async_trait;
use flate2::Compression;
use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use std::io::{Read, Write};
use std::path::Path;

use super::{Builtin, Context, resolve_path};
use crate::error::Result;
use crate::interpreter::ExecResult;

/// Maximum decompression ratio to detect zip bombs.
/// A ratio over 100:1 is suspicious.
const MAX_DECOMPRESSION_RATIO: usize = 100;

/// Read from a decoder with size limits to prevent zip bombs.
///
/// Returns an error if the decompressed size exceeds the limit or
/// if the decompression ratio is suspiciously high.
fn read_with_limit<R: Read>(
    mut reader: R,
    compressed_size: usize,
    max_size: u64,
) -> std::io::Result<Vec<u8>> {
    let mut output = Vec::new();
    let mut buffer = [0u8; 8192];

    loop {
        let n = reader.read(&mut buffer)?;
        if n == 0 {
            break;
        }

        output.extend_from_slice(&buffer[..n]);

        // Check absolute size limit
        if output.len() as u64 > max_size {
            return Err(std::io::Error::other(format!(
                "decompressed size exceeds {} byte limit (zip bomb protection)",
                max_size
            )));
        }

        // Check decompression ratio (zip bomb detection)
        if compressed_size > 0 && output.len() > compressed_size * MAX_DECOMPRESSION_RATIO {
            return Err(std::io::Error::other(format!(
                "decompression ratio exceeds {}:1 (zip bomb protection)",
                MAX_DECOMPRESSION_RATIO
            )));
        }
    }

    Ok(output)
}

/// The tar builtin - create and extract tar archives.
///
/// Usage: tar [-c|-x|-t] [-v] [-f ARCHIVE] [FILE...]
///
/// Options:
///   -c   Create archive
///   -x   Extract archive
///   -t   List archive contents
///   -v   Verbose output
///   -f   Archive file name
///   -z   Filter through gzip (for .tar.gz)
pub struct Tar;

#[async_trait]
impl Builtin for Tar {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        let mut create = false;
        let mut extract = false;
        let mut list = false;
        let mut verbose = false;
        let mut gzip = false;
        let mut to_stdout = false;
        let mut archive_file: Option<String> = None;
        let mut change_dir: Option<String> = None;
        let mut files: Vec<String> = Vec::new();

        // Parse arguments
        let mut i = 0;
        while i < ctx.args.len() {
            let arg = &ctx.args[i];
            if arg.starts_with('-') && !arg.starts_with("--") {
                // Track whether 'f' or 'C' consumed the next arg
                let mut consumed_next = false;
                for c in arg[1..].chars() {
                    match c {
                        'c' => create = true,
                        'x' => extract = true,
                        't' => list = true,
                        'v' => verbose = true,
                        'z' => gzip = true,
                        'O' => to_stdout = true,
                        'f' => {
                            i += 1;
                            consumed_next = true;
                            if i >= ctx.args.len() {
                                return Ok(ExecResult::err(
                                    "tar: option requires an argument -- 'f'\n".to_string(),
                                    2,
                                ));
                            }
                            archive_file = Some(ctx.args[i].clone());
                        }
                        'C' => {
                            i += 1;
                            consumed_next = true;
                            if i >= ctx.args.len() {
                                return Ok(ExecResult::err(
                                    "tar: option requires an argument -- 'C'\n".to_string(),
                                    2,
                                ));
                            }
                            change_dir = Some(ctx.args[i].clone());
                        }
                        _ => {
                            return Ok(ExecResult::err(
                                format!("tar: invalid option -- '{}'\n", c),
                                2,
                            ));
                        }
                    }
                    if consumed_next {
                        break;
                    }
                }
            } else {
                files.push(arg.clone());
            }
            i += 1;
        }

        // Check for exactly one of -c, -x, -t
        let mode_count = [create, extract, list].iter().filter(|&&x| x).count();
        if mode_count == 0 {
            return Ok(ExecResult::err(
                "tar: You must specify one of -c, -x, or -t\n".to_string(),
                2,
            ));
        }
        if mode_count > 1 {
            return Ok(ExecResult::err(
                "tar: You may not specify more than one of -c, -x, -t\n".to_string(),
                2,
            ));
        }

        let archive_name = archive_file.unwrap_or_else(|| "-".to_string());

        if create {
            if files.is_empty() {
                return Ok(ExecResult::err(
                    "tar: Cowardly refusing to create an empty archive\n".to_string(),
                    2,
                ));
            }
            create_tar(&ctx, &archive_name, &files, verbose, gzip).await
        } else if extract {
            extract_tar(
                &ctx,
                &archive_name,
                verbose,
                gzip,
                change_dir.as_deref(),
                to_stdout,
            )
            .await
        } else {
            list_tar(&ctx, &archive_name, verbose, gzip).await
        }
    }
}

/// Simple tar header (512 bytes)
const TAR_BLOCK_SIZE: usize = 512;

/// Create a tar archive
async fn create_tar(
    ctx: &Context<'_>,
    archive_name: &str,
    files: &[String],
    verbose: bool,
    gzip: bool,
) -> Result<ExecResult> {
    let mut output_data: Vec<u8> = Vec::new();
    let mut verbose_output = String::new();

    for file in files {
        let path = resolve_path(ctx.cwd, file);

        if !ctx.fs.exists(&path).await.unwrap_or(false) {
            return Ok(ExecResult::err(
                format!("tar: {}: Cannot stat: No such file or directory\n", file),
                2,
            ));
        }

        let metadata = ctx.fs.stat(&path).await?;

        if metadata.file_type.is_dir() {
            // Add directory recursively
            add_directory_to_tar(
                ctx,
                &path,
                file,
                &mut output_data,
                &mut verbose_output,
                verbose,
            )
            .await?;
        } else {
            // Add single file
            add_file_to_tar(
                ctx,
                &path,
                file,
                &mut output_data,
                &mut verbose_output,
                verbose,
            )
            .await?;
        }
    }

    // Add two zero blocks at end
    output_data.extend_from_slice(&[0u8; TAR_BLOCK_SIZE * 2]);

    // Compress if -z
    let final_data = if gzip {
        let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
        encoder.write_all(&output_data).map_err(|e| {
            crate::error::Error::Execution(format!("tar: gzip compression failed: {}", e))
        })?;
        encoder.finish().map_err(|e| {
            crate::error::Error::Execution(format!("tar: gzip compression failed: {}", e))
        })?
    } else {
        output_data
    };

    // Write to file or stdout
    if archive_name == "-" {
        // Convert to lossy string for stdout
        return Ok(ExecResult {
            stdout: String::from_utf8_lossy(&final_data).to_string(),
            stderr: verbose_output,
            exit_code: 0,
            control_flow: crate::interpreter::ControlFlow::None,
            ..Default::default()
        });
    }

    let archive_path = resolve_path(ctx.cwd, archive_name);
    ctx.fs.write_file(&archive_path, &final_data).await?;

    Ok(ExecResult {
        stdout: String::new(),
        stderr: verbose_output,
        exit_code: 0,
        control_flow: crate::interpreter::ControlFlow::None,
        ..Default::default()
    })
}

/// Add a file to tar archive
async fn add_file_to_tar(
    ctx: &Context<'_>,
    path: &Path,
    name: &str,
    output: &mut Vec<u8>,
    verbose_output: &mut String,
    verbose: bool,
) -> Result<()> {
    let metadata = ctx.fs.stat(path).await?;
    let content = ctx.fs.read_file(path).await?;

    if verbose {
        verbose_output.push_str(name);
        verbose_output.push('\n');
    }

    // Create tar header
    let mut header = [0u8; TAR_BLOCK_SIZE];

    // Name (100 bytes)
    let name_bytes = name.as_bytes();
    let name_len = name_bytes.len().min(100);
    header[..name_len].copy_from_slice(&name_bytes[..name_len]);

    // Mode (8 bytes, octal)
    write_octal(&mut header[100..108], metadata.mode as u64, 7);

    // UID (8 bytes)
    write_octal(&mut header[108..116], 1000, 7);

    // GID (8 bytes)
    write_octal(&mut header[116..124], 1000, 7);

    // Size (12 bytes, octal)
    write_octal(&mut header[124..136], content.len() as u64, 11);

    // Mtime (12 bytes, octal)
    let mtime = metadata
        .modified
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    write_octal(&mut header[136..148], mtime, 11);

    // Checksum placeholder (8 bytes of spaces)
    header[148..156].copy_from_slice(b"        ");

    // Type flag
    header[156] = b'0'; // Regular file

    // Magic
    header[257..263].copy_from_slice(b"ustar ");

    // Version
    header[263..265].copy_from_slice(b" \0");

    // Calculate and write checksum
    let checksum: u32 = header.iter().map(|&b| b as u32).sum();
    write_octal(&mut header[148..156], checksum as u64, 7);

    output.extend_from_slice(&header);

    // Write file content with padding
    output.extend_from_slice(&content);
    let padding = (TAR_BLOCK_SIZE - (content.len() % TAR_BLOCK_SIZE)) % TAR_BLOCK_SIZE;
    output.extend(std::iter::repeat_n(0u8, padding));

    Ok(())
}

/// Add a directory to tar archive recursively
fn add_directory_to_tar<'a>(
    ctx: &'a Context<'_>,
    path: &'a Path,
    name: &'a str,
    output: &'a mut Vec<u8>,
    verbose_output: &'a mut String,
    verbose: bool,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> {
    Box::pin(async move {
        // Add directory entry
        if verbose {
            verbose_output.push_str(name);
            verbose_output.push_str("/\n");
        }

        let metadata = ctx.fs.stat(path).await?;

        // Create tar header for directory
        let mut header = [0u8; TAR_BLOCK_SIZE];

        // Name with trailing slash
        let dir_name = format!("{}/", name);
        let name_bytes = dir_name.as_bytes();
        let name_len = name_bytes.len().min(100);
        header[..name_len].copy_from_slice(&name_bytes[..name_len]);

        // Mode
        write_octal(&mut header[100..108], metadata.mode as u64, 7);

        // UID/GID
        write_octal(&mut header[108..116], 1000, 7);
        write_octal(&mut header[116..124], 1000, 7);

        // Size (0 for directory)
        write_octal(&mut header[124..136], 0, 11);

        // Mtime
        let mtime = metadata
            .modified
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        write_octal(&mut header[136..148], mtime, 11);

        // Checksum placeholder
        header[148..156].copy_from_slice(b"        ");

        // Type flag for directory
        header[156] = b'5';

        // Magic
        header[257..263].copy_from_slice(b"ustar ");
        header[263..265].copy_from_slice(b" \0");

        // Calculate checksum
        let checksum: u32 = header.iter().map(|&b| b as u32).sum();
        write_octal(&mut header[148..156], checksum as u64, 7);

        output.extend_from_slice(&header);

        // Add directory contents
        let entries = ctx.fs.read_dir(path).await?;
        for entry in entries {
            let child_path = path.join(&entry.name);
            let child_name = format!("{}/{}", name, entry.name);

            if entry.metadata.file_type.is_dir() {
                add_directory_to_tar(
                    ctx,
                    &child_path,
                    &child_name,
                    output,
                    verbose_output,
                    verbose,
                )
                .await?;
            } else {
                add_file_to_tar(
                    ctx,
                    &child_path,
                    &child_name,
                    output,
                    verbose_output,
                    verbose,
                )
                .await?;
            }
        }

        Ok(())
    })
}

/// Write octal value to tar header field
fn write_octal(buf: &mut [u8], value: u64, width: usize) {
    let s = format!("{:0>width$o}", value, width = width);
    let bytes = s.as_bytes();
    let len = bytes.len().min(buf.len() - 1);
    buf[..len].copy_from_slice(&bytes[bytes.len() - len..]);
    buf[len] = 0;
}

/// Extract a tar archive
async fn extract_tar(
    ctx: &Context<'_>,
    archive_name: &str,
    verbose: bool,
    gzip: bool,
    change_dir: Option<&str>,
    to_stdout: bool,
) -> Result<ExecResult> {
    // Resolve extraction base directory (-C flag)
    let extract_base = if let Some(dir) = change_dir {
        resolve_path(ctx.cwd, dir)
    } else {
        ctx.cwd.clone()
    };
    let data = if archive_name == "-" {
        ctx.stdin.map(|s| s.as_bytes().to_vec()).unwrap_or_default()
    } else {
        let archive_path = resolve_path(ctx.cwd, archive_name);
        if !ctx.fs.exists(&archive_path).await.unwrap_or(false) {
            return Ok(ExecResult::err(
                format!(
                    "tar: {}: Cannot open: No such file or directory\n",
                    archive_name
                ),
                2,
            ));
        }
        ctx.fs.read_file(&archive_path).await?
    };

    // Get filesystem limits for zip bomb protection
    let limits = ctx.fs.limits();
    let max_size = limits.max_total_bytes;

    // Decompress if -z, with size limits
    let tar_data = if gzip {
        let compressed_size = data.len();
        let decoder = GzDecoder::new(data.as_slice());
        read_with_limit(decoder, compressed_size, max_size)
            .map_err(|e| crate::error::Error::Execution(format!("tar: {}", e)))?
    } else {
        data
    };

    let mut verbose_output = String::new();
    let mut stdout_output = String::new();
    let mut offset = 0;

    // Ensure extract_base directory exists when -C is used
    if change_dir.is_some() {
        ctx.fs.mkdir(&extract_base, true).await?;
    }

    while offset + TAR_BLOCK_SIZE <= tar_data.len() {
        let header = &tar_data[offset..offset + TAR_BLOCK_SIZE];

        // Check for end of archive (two zero blocks)
        if header.iter().all(|&b| b == 0) {
            break;
        }

        // Parse name
        let name_end = header[..100].iter().position(|&b| b == 0).unwrap_or(100);
        let name = String::from_utf8_lossy(&header[..name_end]).to_string();

        if name.is_empty() {
            break;
        }

        // Parse size
        let size = parse_octal(&header[124..136]);

        // Parse type
        let type_flag = header[156];

        if verbose {
            verbose_output.push_str(&name);
            verbose_output.push('\n');
        }

        offset += TAR_BLOCK_SIZE;

        // Path traversal protection: reject entries with ".." components or absolute paths
        if !to_stdout
            && (name.contains("..")
                || name.starts_with('/')
                || !resolve_path(&extract_base, &name).starts_with(&extract_base))
        {
            return Ok(ExecResult::err(
                format!("tar: {}: path traversal blocked\n", name),
                2,
            ));
        }

        match type_flag {
            b'5' | b'\0' if name.ends_with('/') => {
                // Directory
                if !to_stdout {
                    let dir_path = resolve_path(&extract_base, &name);
                    ctx.fs.mkdir(&dir_path, true).await?;
                }
            }
            b'0' | b'\0' => {
                // Regular file
                let content_blocks = size.div_ceil(TAR_BLOCK_SIZE);
                let content_end = offset + content_blocks * TAR_BLOCK_SIZE;

                if content_end > tar_data.len() {
                    return Ok(ExecResult::err(
                        format!("tar: {}: Unexpected end of archive\n", name),
                        2,
                    ));
                }

                let content = &tar_data[offset..offset + size];

                if to_stdout {
                    // -O: write content to stdout
                    stdout_output.push_str(&String::from_utf8_lossy(content));
                } else {
                    let file_path = resolve_path(&extract_base, &name);

                    // Ensure parent directory exists
                    if let Some(parent) = file_path.parent() {
                        ctx.fs.mkdir(parent, true).await?;
                    }

                    ctx.fs.write_file(&file_path, content).await?;
                }
                offset = content_end;
            }
            _ => {
                // Skip unknown types
                let content_blocks = size.div_ceil(TAR_BLOCK_SIZE);
                offset += content_blocks * TAR_BLOCK_SIZE;
            }
        }
    }

    Ok(ExecResult {
        stdout: stdout_output,
        stderr: verbose_output,
        exit_code: 0,
        control_flow: crate::interpreter::ControlFlow::None,
        ..Default::default()
    })
}

/// List tar archive contents
async fn list_tar(
    ctx: &Context<'_>,
    archive_name: &str,
    verbose: bool,
    gzip: bool,
) -> Result<ExecResult> {
    let data = if archive_name == "-" {
        ctx.stdin.map(|s| s.as_bytes().to_vec()).unwrap_or_default()
    } else {
        let archive_path = resolve_path(ctx.cwd, archive_name);
        if !ctx.fs.exists(&archive_path).await.unwrap_or(false) {
            return Ok(ExecResult::err(
                format!(
                    "tar: {}: Cannot open: No such file or directory\n",
                    archive_name
                ),
                2,
            ));
        }
        ctx.fs.read_file(&archive_path).await?
    };

    // Get filesystem limits for zip bomb protection
    let limits = ctx.fs.limits();
    let max_size = limits.max_total_bytes;

    // Decompress if -z, with size limits
    let tar_data = if gzip {
        let compressed_size = data.len();
        let decoder = GzDecoder::new(data.as_slice());
        read_with_limit(decoder, compressed_size, max_size)
            .map_err(|e| crate::error::Error::Execution(format!("tar: {}", e)))?
    } else {
        data
    };

    let mut output = String::new();
    let mut offset = 0;

    while offset + TAR_BLOCK_SIZE <= tar_data.len() {
        let header = &tar_data[offset..offset + TAR_BLOCK_SIZE];

        // Check for end of archive
        if header.iter().all(|&b| b == 0) {
            break;
        }

        // Parse name
        let name_end = header[..100].iter().position(|&b| b == 0).unwrap_or(100);
        let name = String::from_utf8_lossy(&header[..name_end]).to_string();

        if name.is_empty() {
            break;
        }

        // Parse size
        let size = parse_octal(&header[124..136]);

        if verbose {
            // Parse mode
            let mode = parse_octal(&header[100..108]) as u32;
            let size_val = parse_octal(&header[124..136]);

            let type_flag = header[156];
            let type_char = match type_flag {
                b'5' => 'd',
                b'2' => 'l',
                _ => '-',
            };

            output.push_str(&format!(
                "{}{}{}{}{}{}{}{}{}{} {:>8} {}\n",
                type_char,
                if mode & 0o400 != 0 { 'r' } else { '-' },
                if mode & 0o200 != 0 { 'w' } else { '-' },
                if mode & 0o100 != 0 { 'x' } else { '-' },
                if mode & 0o040 != 0 { 'r' } else { '-' },
                if mode & 0o020 != 0 { 'w' } else { '-' },
                if mode & 0o010 != 0 { 'x' } else { '-' },
                if mode & 0o004 != 0 { 'r' } else { '-' },
                if mode & 0o002 != 0 { 'w' } else { '-' },
                if mode & 0o001 != 0 { 'x' } else { '-' },
                size_val,
                name
            ));
        } else {
            output.push_str(&name);
            output.push('\n');
        }

        offset += TAR_BLOCK_SIZE;

        // Skip content blocks
        let content_blocks = size.div_ceil(TAR_BLOCK_SIZE);
        offset += content_blocks * TAR_BLOCK_SIZE;
    }

    Ok(ExecResult::ok(output))
}

/// Parse octal value from tar header field
fn parse_octal(buf: &[u8]) -> usize {
    let s: String = buf
        .iter()
        .take_while(|&&b| b != 0 && b != b' ')
        .map(|&b| b as char)
        .collect();
    usize::from_str_radix(s.trim(), 8).unwrap_or(0)
}

/// The gzip builtin - compress files.
///
/// Usage: gzip [-d] [-k] [-f] [FILE...]
///
/// Options:
///   -d   Decompress (same as gunzip)
///   -k   Keep original file
///   -f   Force overwrite
pub struct Gzip;

#[async_trait]
impl Builtin for Gzip {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        let mut decompress = false;
        let mut keep = false;
        let mut force = false;
        let mut files: Vec<String> = Vec::new();

        for arg in ctx.args {
            if arg.starts_with('-') && arg.len() > 1 {
                for c in arg[1..].chars() {
                    match c {
                        'd' => decompress = true,
                        'k' => keep = true,
                        'f' => force = true,
                        _ => {
                            return Ok(ExecResult::err(
                                format!("gzip: invalid option -- '{}'\n", c),
                                1,
                            ));
                        }
                    }
                }
            } else {
                files.push(arg.clone());
            }
        }

        // Get filesystem limits for zip bomb protection
        let limits = ctx.fs.limits();
        let max_size = limits.max_file_size;

        // If no files, read from stdin
        if files.is_empty() {
            if let Some(stdin) = ctx.stdin {
                if decompress {
                    let compressed_size = stdin.len();
                    let decoder = GzDecoder::new(stdin.as_bytes());
                    match read_with_limit(decoder, compressed_size, max_size) {
                        Ok(output) => {
                            return Ok(ExecResult::ok(
                                String::from_utf8_lossy(&output).to_string(),
                            ));
                        }
                        Err(e) => return Ok(ExecResult::err(format!("gzip: stdin: {}\n", e), 1)),
                    }
                } else {
                    let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
                    encoder.write_all(stdin.as_bytes()).map_err(|e| {
                        crate::error::Error::Execution(format!("gzip: compression failed: {}", e))
                    })?;
                    let compressed = encoder.finish().map_err(|e| {
                        crate::error::Error::Execution(format!("gzip: compression failed: {}", e))
                    })?;
                    return Ok(ExecResult::ok(
                        String::from_utf8_lossy(&compressed).to_string(),
                    ));
                }
            }
            return Ok(ExecResult::ok(String::new()));
        }

        for file in &files {
            let path = resolve_path(ctx.cwd, file);

            if !ctx.fs.exists(&path).await.unwrap_or(false) {
                return Ok(ExecResult::err(
                    format!("gzip: {}: No such file or directory\n", file),
                    1,
                ));
            }

            let metadata = ctx.fs.stat(&path).await?;
            if metadata.file_type.is_dir() {
                return Ok(ExecResult::err(
                    format!("gzip: {}: Is a directory\n", file),
                    1,
                ));
            }

            if decompress {
                // Decompress
                if !file.ends_with(".gz") {
                    return Ok(ExecResult::err(
                        format!("gzip: {}: unknown suffix -- ignored\n", file),
                        1,
                    ));
                }

                let output_name = file.strip_suffix(".gz").unwrap();
                let output_path = resolve_path(ctx.cwd, output_name);

                if ctx.fs.exists(&output_path).await.unwrap_or(false) && !force {
                    return Ok(ExecResult::err(
                        format!("gzip: {}: already exists\n", output_name),
                        1,
                    ));
                }

                let data = ctx.fs.read_file(&path).await?;
                let compressed_size = data.len();
                let decoder = GzDecoder::new(data.as_slice());
                let output = read_with_limit(decoder, compressed_size, max_size).map_err(|e| {
                    crate::error::Error::Execution(format!("gzip: {}: {}", file, e))
                })?;

                ctx.fs.write_file(&output_path, &output).await?;

                if !keep {
                    ctx.fs.remove(&path, false).await?;
                }
            } else {
                // Compress
                if file.ends_with(".gz") {
                    return Ok(ExecResult::err(
                        format!("gzip: {}: already has .gz suffix\n", file),
                        1,
                    ));
                }

                let output_name = format!("{}.gz", file);
                let output_path = resolve_path(ctx.cwd, &output_name);

                if ctx.fs.exists(&output_path).await.unwrap_or(false) && !force {
                    return Ok(ExecResult::err(
                        format!("gzip: {}: already exists\n", output_name),
                        1,
                    ));
                }

                let data = ctx.fs.read_file(&path).await?;
                let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
                encoder.write_all(&data).map_err(|e| {
                    crate::error::Error::Execution(format!("gzip: {}: {}", file, e))
                })?;
                let compressed = encoder.finish().map_err(|e| {
                    crate::error::Error::Execution(format!("gzip: {}: {}", file, e))
                })?;

                ctx.fs.write_file(&output_path, &compressed).await?;

                if !keep {
                    ctx.fs.remove(&path, false).await?;
                }
            }
        }

        Ok(ExecResult::ok(String::new()))
    }
}

/// The gunzip builtin - decompress files.
///
/// Usage: gunzip [-k] [-f] [FILE...]
///
/// Options:
///   -k   Keep original file
///   -f   Force overwrite
pub struct Gunzip;

#[async_trait]
impl Builtin for Gunzip {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        // gunzip is equivalent to gzip -d
        let mut modified_args: Vec<String> = vec!["-d".to_string()];
        modified_args.extend(ctx.args.iter().cloned());

        let new_ctx = Context {
            args: &modified_args,
            env: ctx.env,
            variables: ctx.variables,
            cwd: ctx.cwd,
            fs: ctx.fs,
            stdin: ctx.stdin,
            #[cfg(feature = "http_client")]
            http_client: ctx.http_client,
            #[cfg(feature = "git")]
            git_client: ctx.git_client,
            shell: ctx.shell,
        };

        Gzip.execute(new_ctx).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    use crate::fs::{FileSystem, InMemoryFs};

    async fn create_test_ctx() -> (Arc<InMemoryFs>, PathBuf, HashMap<String, String>) {
        let fs = Arc::new(InMemoryFs::new());
        let cwd = PathBuf::from("/home/user");
        let variables = HashMap::new();

        fs.mkdir(&cwd, true).await.unwrap();

        (fs, cwd, variables)
    }

    // ==================== tar tests ====================

    #[tokio::test]
    async fn test_tar_create_and_list() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Create a test file
        fs.write_file(&cwd.join("test.txt"), b"Hello, world!")
            .await
            .unwrap();

        // Create archive
        let args = vec![
            "-cf".to_string(),
            "archive.tar".to_string(),
            "test.txt".to_string(),
        ];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(fs.exists(&cwd.join("archive.tar")).await.unwrap());

        // List archive
        let args = vec!["-tf".to_string(), "archive.tar".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.contains("test.txt"));
    }

    #[tokio::test]
    async fn test_tar_create_and_extract() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Create a test file
        fs.write_file(&cwd.join("original.txt"), b"Test content")
            .await
            .unwrap();

        // Create archive
        let args = vec![
            "-cf".to_string(),
            "archive.tar".to_string(),
            "original.txt".to_string(),
        ];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);

        // Remove original
        fs.remove(&cwd.join("original.txt"), false).await.unwrap();
        assert!(!fs.exists(&cwd.join("original.txt")).await.unwrap());

        // Extract
        let args = vec!["-xf".to_string(), "archive.tar".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);

        // Verify extracted file
        assert!(fs.exists(&cwd.join("original.txt")).await.unwrap());
        let content = fs.read_file(&cwd.join("original.txt")).await.unwrap();
        assert_eq!(content, b"Test content");
    }

    #[tokio::test]
    async fn test_tar_verbose() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        fs.write_file(&cwd.join("test.txt"), b"content")
            .await
            .unwrap();

        let args = vec![
            "-cvf".to_string(),
            "archive.tar".to_string(),
            "test.txt".to_string(),
        ];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(result.stderr.contains("test.txt"));
    }

    #[tokio::test]
    async fn test_tar_missing_mode() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        let args = vec!["-f".to_string(), "archive.tar".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 2);
        assert!(result.stderr.contains("must specify"));
    }

    #[tokio::test]
    async fn test_tar_nonexistent_file() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        let args = vec![
            "-cf".to_string(),
            "archive.tar".to_string(),
            "nonexistent".to_string(),
        ];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 2);
        assert!(result.stderr.contains("No such file"));
    }

    #[tokio::test]
    async fn test_tar_directory() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        fs.mkdir(&cwd.join("testdir"), false).await.unwrap();
        fs.write_file(&cwd.join("testdir/file.txt"), b"content")
            .await
            .unwrap();

        // Create archive with directory
        let args = vec![
            "-cf".to_string(),
            "archive.tar".to_string(),
            "testdir".to_string(),
        ];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);

        // List to verify
        let args = vec!["-tf".to_string(), "archive.tar".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(result.stdout.contains("testdir/"));
        assert!(result.stdout.contains("testdir/file.txt"));
    }

    // ==================== gzip tests ====================

    #[tokio::test]
    async fn test_gzip_compress() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        fs.write_file(&cwd.join("test.txt"), b"Hello, world!")
            .await
            .unwrap();

        let args = vec!["test.txt".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(fs.exists(&cwd.join("test.txt.gz")).await.unwrap());
        assert!(!fs.exists(&cwd.join("test.txt")).await.unwrap());
    }

    #[tokio::test]
    async fn test_gzip_decompress() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Create and compress
        fs.write_file(&cwd.join("test.txt"), b"Hello, world!")
            .await
            .unwrap();

        let args = vec!["test.txt".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        Gzip.execute(ctx).await.unwrap();

        // Decompress
        let args = vec!["-d".to_string(), "test.txt.gz".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(fs.exists(&cwd.join("test.txt")).await.unwrap());

        let content = fs.read_file(&cwd.join("test.txt")).await.unwrap();
        assert_eq!(content, b"Hello, world!");
    }

    #[tokio::test]
    async fn test_gzip_keep() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        fs.write_file(&cwd.join("test.txt"), b"content")
            .await
            .unwrap();

        let args = vec!["-k".to_string(), "test.txt".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(fs.exists(&cwd.join("test.txt")).await.unwrap());
        assert!(fs.exists(&cwd.join("test.txt.gz")).await.unwrap());
    }

    #[tokio::test]
    async fn test_gzip_nonexistent() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        let args = vec!["nonexistent".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("No such file"));
    }

    #[tokio::test]
    async fn test_gzip_already_gz() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        fs.write_file(&cwd.join("test.gz"), b"content")
            .await
            .unwrap();

        let args = vec!["test.gz".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("already has .gz"));
    }

    #[tokio::test]
    async fn test_gzip_directory() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        fs.mkdir(&cwd.join("testdir"), false).await.unwrap();

        let args = vec!["testdir".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("Is a directory"));
    }

    // ==================== gunzip tests ====================

    #[tokio::test]
    async fn test_gunzip_basic() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Create and compress
        fs.write_file(&cwd.join("test.txt"), b"content")
            .await
            .unwrap();

        let args = vec!["test.txt".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };
        Gzip.execute(ctx).await.unwrap();

        // Decompress with gunzip
        let args = vec!["test.txt.gz".to_string()];
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs: fs.clone(),
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            shell: None,
        };

        let result = Gunzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
        assert!(fs.exists(&cwd.join("test.txt")).await.unwrap());
    }

    // ==================== zip bomb protection tests ====================

    #[test]
    fn test_read_with_limit_normal() {
        let data = b"hello world";
        let result = read_with_limit(data.as_slice(), data.len(), 1000);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), data);
    }

    #[test]
    fn test_read_with_limit_exceeds_max() {
        let data = vec![0u8; 1000];
        let result = read_with_limit(data.as_slice(), data.len(), 500);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("exceeds") || err.contains("limit"));
    }

    #[test]
    fn test_read_with_limit_high_ratio() {
        // Simulate a high decompression ratio scenario
        // We can't easily create a real gzip bomb, but we test the ratio check
        let data = vec![0u8; 10100]; // 101x the "compressed" size
        let result = read_with_limit(data.as_slice(), 100, u64::MAX);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("ratio") || err.contains("bomb"));
    }

    #[tokio::test]
    async fn test_gzip_respects_file_size_limit() {
        use crate::fs::FsLimits;

        // Create FS with small file size limit
        let limits = FsLimits::new().max_file_size(100);
        let fs = Arc::new(crate::fs::InMemoryFs::with_limits(limits));
        let mut cwd = PathBuf::from("/tmp");
        let mut variables = HashMap::new();
        let env = HashMap::new();

        // Create a small file
        fs.write_file(&cwd.join("small.txt"), b"small content")
            .await
            .unwrap();

        // Compress it
        let args = vec!["small.txt".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);

        let result = Gzip.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_fs_limits_enforced_on_extract() {
        use crate::fs::FsLimits;

        // Create FS with small limits
        let limits = FsLimits::new().max_total_bytes(1000).max_file_size(500);
        let fs = Arc::new(crate::fs::InMemoryFs::with_limits(limits));
        let cwd = PathBuf::from("/tmp");

        // Create a file that will exceed limits when extracted
        let large_content = vec![b'x'; 600];
        fs.write_file(&cwd.join("large.txt"), &large_content)
            .await
            .expect_err("Should fail due to file size limit");
    }

    // ==================== path traversal tests ====================

    /// Build a minimal tar archive with a single file entry.
    /// Used to craft malicious archives for security testing.
    fn build_tar_with_entry(name: &str, content: &[u8]) -> Vec<u8> {
        let mut output = Vec::new();
        let mut header = [0u8; 512];

        // Name
        let name_bytes = name.as_bytes();
        let name_len = name_bytes.len().min(100);
        header[..name_len].copy_from_slice(&name_bytes[..name_len]);

        // Mode
        let mode = b"0000644\0";
        header[100..108].copy_from_slice(mode);

        // UID/GID
        header[108..116].copy_from_slice(b"0001000\0");
        header[116..124].copy_from_slice(b"0001000\0");

        // Size (octal)
        let size_str = format!("{:011o}\0", content.len());
        header[124..136].copy_from_slice(size_str.as_bytes());

        // Mtime
        header[136..148].copy_from_slice(b"00000000000\0");

        // Checksum placeholder (spaces)
        header[148..156].copy_from_slice(b"        ");

        // Type flag: regular file
        header[156] = b'0';

        // Magic
        header[257..263].copy_from_slice(b"ustar ");
        header[263..265].copy_from_slice(b" \0");

        // Calculate checksum
        let checksum: u32 = header.iter().map(|&b| b as u32).sum();
        let cksum_str = format!("{:06o}\0 ", checksum);
        header[148..156].copy_from_slice(cksum_str.as_bytes());

        output.extend_from_slice(&header);
        output.extend_from_slice(content);
        let padding = (512 - (content.len() % 512)) % 512;
        output.extend(std::iter::repeat_n(0u8, padding));
        // End-of-archive marker (two zero blocks)
        output.extend_from_slice(&[0u8; 1024]);
        output
    }

    #[tokio::test]
    async fn test_tar_extract_path_traversal_dotdot_blocked() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Craft a malicious tar with ../../../etc/passwd entry
        let malicious_tar = build_tar_with_entry("../../../etc/passwd", b"root:x:0:0");
        fs.write_file(&cwd.join("evil.tar"), &malicious_tar)
            .await
            .unwrap();

        let args = vec!["-xf".to_string(), "evil.tar".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);

        let result = Tar.execute(ctx).await.unwrap();

        // Should be blocked
        assert_eq!(result.exit_code, 2);
        assert!(result.stderr.contains("path traversal blocked"));

        // /etc/passwd must NOT exist
        assert!(!fs.exists(&PathBuf::from("/etc/passwd")).await.unwrap());
    }

    #[tokio::test]
    async fn test_tar_extract_path_traversal_absolute_blocked() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Craft a malicious tar with absolute path entry
        let malicious_tar = build_tar_with_entry("/etc/shadow", b"root:!:19000");
        fs.write_file(&cwd.join("evil.tar"), &malicious_tar)
            .await
            .unwrap();

        let args = vec!["-xf".to_string(), "evil.tar".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);

        let result = Tar.execute(ctx).await.unwrap();

        // Should be blocked
        assert_eq!(result.exit_code, 2);
        assert!(result.stderr.contains("path traversal blocked"));

        // /etc/shadow must NOT exist
        assert!(!fs.exists(&PathBuf::from("/etc/shadow")).await.unwrap());
    }

    #[tokio::test]
    async fn test_tar_extract_path_traversal_dir_dotdot_blocked() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Craft malicious tar with directory entry using ..
        let mut output = Vec::new();
        let mut header = [0u8; 512];
        let name = b"../../etc/";
        header[..name.len()].copy_from_slice(name);
        header[100..108].copy_from_slice(b"0000755\0");
        header[108..116].copy_from_slice(b"0001000\0");
        header[116..124].copy_from_slice(b"0001000\0");
        header[124..136].copy_from_slice(b"00000000000\0");
        header[136..148].copy_from_slice(b"00000000000\0");
        header[148..156].copy_from_slice(b"        ");
        header[156] = b'5'; // directory
        header[257..263].copy_from_slice(b"ustar ");
        header[263..265].copy_from_slice(b" \0");
        let checksum: u32 = header.iter().map(|&b| b as u32).sum();
        let cksum_str = format!("{:06o}\0 ", checksum);
        header[148..156].copy_from_slice(cksum_str.as_bytes());
        output.extend_from_slice(&header);
        output.extend_from_slice(&[0u8; 1024]);

        fs.write_file(&cwd.join("evil_dir.tar"), &output)
            .await
            .unwrap();

        let args = vec!["-xf".to_string(), "evil_dir.tar".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);

        let result = Tar.execute(ctx).await.unwrap();

        assert_eq!(result.exit_code, 2);
        assert!(result.stderr.contains("path traversal blocked"));
    }

    #[tokio::test]
    async fn test_tar_extract_safe_paths_still_work() {
        let (fs, mut cwd, mut variables) = create_test_ctx().await;
        let env = HashMap::new();

        // Normal tar with safe relative path should still work
        let safe_tar = build_tar_with_entry("subdir/file.txt", b"safe content");
        fs.write_file(&cwd.join("safe.tar"), &safe_tar)
            .await
            .unwrap();

        let args = vec!["-xf".to_string(), "safe.tar".to_string()];
        let ctx = Context::new_for_test(&args, &env, &mut variables, &mut cwd, fs.clone(), None);

        let result = Tar.execute(ctx).await.unwrap();
        assert_eq!(result.exit_code, 0);

        let content = fs.read_file(&cwd.join("subdir/file.txt")).await.unwrap();
        assert_eq!(content, b"safe content");
    }
}