bashkit 0.1.18

Awesomely fast virtual sandbox with bash and file system
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
//! Curl and wget builtins - transfer data from URLs
//!
//! Note: These builtins require the `http_client` feature and proper configuration.
//! Network access is restricted by allowlist for security.
//!
//! # Security
//!
//! - URLs must match the configured allowlist
//! - Response size is limited (default: 10MB) to prevent memory exhaustion
//! - Timeouts prevent hanging on unresponsive servers
//! - Multipart field names/filenames are sanitized to prevent header injection (issue #985)
//! - Redirects are not followed automatically (to prevent allowlist bypass)
//! - Compression decompression is size-limited to prevent zip bombs

use async_trait::async_trait;

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

/// The curl builtin - transfer data from URLs.
///
/// Usage: curl [OPTIONS] URL
///
/// Options:
///   -s, --silent       Silent mode (no progress)
///   -o FILE            Write output to FILE
///   -X METHOD          Specify request method (GET, POST, PUT, DELETE, HEAD)
///   -d DATA            Send data in request body (implies POST if no -X)
///   -H HEADER          Add header to request (format: "Name: Value")
///   -I, --head         Fetch headers only (HEAD request)
///   -f, --fail         Fail silently on HTTP errors (no output)
///   -L, --location     Follow redirects (up to 10 redirects)
///   -w FORMAT          Write output format after transfer
///   --compressed       Request compressed response and decompress
///   -u, --user U:P     Basic authentication (user:password)
///   -A, --user-agent S Custom user agent string
///   -e, --referer URL  Referer URL
///   -m, --max-time S   Maximum time in seconds for operation
///   --connect-timeout S Maximum time in seconds for connection
///   -v, --verbose      Verbose output
///
/// Note: Network access requires the 'http_client' feature and proper
/// URL allowlist configuration. Without configuration, all requests
/// will fail with an access denied error.
///
/// # Security
///
/// - Response size is limited to prevent memory exhaustion (applies to decompressed size too)
/// - Redirects require each URL to be in the allowlist
/// - Timeouts prevent hanging on slow servers
/// - --compressed decompression is size-limited to prevent zip bombs
pub struct Curl;

#[async_trait]
impl Builtin for Curl {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: curl [OPTIONS] URL\nTransfer data from or to a server.\n\n  -s, --silent\tsilent mode\n  -o FILE\twrite output to FILE\n  -X METHOD\trequest method (GET, POST, PUT, DELETE, HEAD)\n  -d, --data DATA\tsend data in request body\n  -H, --header HEADER\tadd header (\"Name: Value\")\n  -I, --head\tfetch headers only\n  -f, --fail\tfail silently on HTTP errors\n  -L, --location\tfollow redirects\n  -w, --write-out FORMAT\twrite output format after transfer\n  --compressed\trequest and decompress compressed response\n  -u, --user USER:PASS\tbasic authentication\n  -A, --user-agent STRING\tcustom user agent\n  -e, --referer URL\treferer URL\n  -m, --max-time SECONDS\tmaximum time for operation\n  --connect-timeout SECONDS\tconnection timeout\n  -F, --form FIELD\tmultipart form data\n  -v, --verbose\tverbose output\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("curl 8.7.1 (bashkit)"),
        ) {
            return Ok(r);
        }
        // Parse arguments
        let mut silent = false;
        let mut verbose = false;
        let mut output_file: Option<String> = None;
        let mut method = "GET".to_string();
        let mut data: Option<String> = None;
        let mut headers: Vec<String> = Vec::new();
        let mut head_only = false;
        let mut fail_on_error = false;
        let mut follow_redirects = false;
        let mut write_out: Option<String> = None;
        let mut compressed = false;
        let mut user_auth: Option<String> = None;
        let mut user_agent: Option<String> = None;
        let mut referer: Option<String> = None;
        let mut max_time: Option<u64> = None;
        let mut connect_timeout: Option<u64> = None;
        let mut url: Option<String> = None;
        let mut form_fields: Vec<String> = Vec::new();

        let mut i = 0;
        while i < ctx.args.len() {
            let arg = &ctx.args[i];
            match arg.as_str() {
                "-s" | "--silent" => silent = true,
                "-v" | "--verbose" => verbose = true,
                "-f" | "--fail" => fail_on_error = true,
                "-L" | "--location" => follow_redirects = true,
                "--compressed" => compressed = true,
                "-I" | "--head" => {
                    head_only = true;
                    method = "HEAD".to_string();
                }
                "-o" => {
                    i += 1;
                    if i < ctx.args.len() {
                        output_file = Some(ctx.args[i].clone());
                    }
                }
                "-X" => {
                    i += 1;
                    if i < ctx.args.len() {
                        method = ctx.args[i].clone().to_uppercase();
                    }
                }
                "-d" | "--data" => {
                    i += 1;
                    if i < ctx.args.len() {
                        data = Some(ctx.args[i].clone());
                        if method == "GET" {
                            method = "POST".to_string();
                        }
                    }
                }
                "-H" | "--header" => {
                    i += 1;
                    if i < ctx.args.len() {
                        headers.push(ctx.args[i].clone());
                    }
                }
                "-w" | "--write-out" => {
                    i += 1;
                    if i < ctx.args.len() {
                        write_out = Some(ctx.args[i].clone());
                    }
                }
                "-u" | "--user" => {
                    i += 1;
                    if i < ctx.args.len() {
                        user_auth = Some(ctx.args[i].clone());
                    }
                }
                "-A" | "--user-agent" => {
                    i += 1;
                    if i < ctx.args.len() {
                        user_agent = Some(ctx.args[i].clone());
                    }
                }
                "-e" | "--referer" => {
                    i += 1;
                    if i < ctx.args.len() {
                        referer = Some(ctx.args[i].clone());
                    }
                }
                "-m" | "--max-time" => {
                    i += 1;
                    if i < ctx.args.len() {
                        max_time = ctx.args[i].parse().ok();
                    }
                }
                "--connect-timeout" => {
                    i += 1;
                    if i < ctx.args.len() {
                        connect_timeout = ctx.args[i].parse().ok();
                    }
                }
                "-F" | "--form" => {
                    i += 1;
                    if i < ctx.args.len() {
                        form_fields.push(ctx.args[i].clone());
                        if method == "GET" {
                            method = "POST".to_string();
                        }
                    }
                }
                _ if !arg.starts_with('-') => {
                    url = Some(arg.clone());
                }
                _ => {
                    // Ignore unknown options for compatibility
                }
            }
            i += 1;
        }

        // Resolve -d @- (stdin) and -d @file (VFS file) before sending
        if let Some(ref d) = data
            && let Some(path) = d.strip_prefix('@')
        {
            if path == "-" {
                // Read from stdin
                data = Some(ctx.stdin.unwrap_or("").to_string());
            } else {
                // Read from VFS file
                let resolved = resolve_path(ctx.cwd, path);
                match ctx.fs.read_file(&resolved).await {
                    Ok(content) => {
                        data = Some(String::from_utf8_lossy(&content).into_owned());
                    }
                    Err(_) => {
                        return Ok(ExecResult::err(
                            format!(
                                "curl: Failed reading data file {}: No such file or directory\n",
                                path
                            ),
                            26,
                        ));
                    }
                }
            }
        }

        // Validate URL
        let url = match url {
            Some(u) => u,
            None => {
                return Ok(ExecResult::err("curl: no URL specified\n".to_string(), 3));
            }
        };

        // Validate multipart field names early to reject injection attempts
        // even when network is not configured (defense in depth).
        for field in &form_fields {
            if let Some(eq_pos) = field.find('=') {
                let name = &field[..eq_pos];
                if let Err(e) = sanitize_multipart_name(name, "field name") {
                    return Ok(ExecResult::err(e, 2));
                }
            }
        }

        // Check if network is configured
        #[cfg(feature = "http_client")]
        {
            if let Some(http_client) = ctx.http_client {
                return execute_curl_request(
                    http_client,
                    &url,
                    &method,
                    data.as_deref(),
                    &headers,
                    head_only,
                    silent,
                    verbose,
                    fail_on_error,
                    follow_redirects,
                    write_out.as_deref(),
                    output_file.as_deref(),
                    compressed,
                    user_auth.as_deref(),
                    user_agent.as_deref(),
                    referer.as_deref(),
                    max_time,
                    connect_timeout,
                    &form_fields,
                    &ctx,
                )
                .await;
            }
        }

        // Network not configured
        let _ = (
            silent,
            verbose,
            output_file,
            method,
            data,
            headers,
            head_only,
            fail_on_error,
            follow_redirects,
            write_out,
            compressed,
            user_auth,
            user_agent,
            referer,
            max_time,
            connect_timeout,
            form_fields,
        );

        Ok(ExecResult::err(
            format!(
                "curl: network access not configured\nURL: {}\n\
                 Note: Network builtins require the 'http_client' feature and\n\
                 URL allowlist configuration for security.\n",
                url
            ),
            1,
        ))
    }
}

/// Sanitize a multipart field name or filename to prevent header injection.
/// Rejects CR/LF characters (which could inject headers) and escapes double quotes.
fn sanitize_multipart_name(value: &str, label: &str) -> std::result::Result<String, String> {
    if value.contains('\r') || value.contains('\n') {
        return Err(format!(
            "curl: multipart {} contains illegal newline characters\n",
            label
        ));
    }
    Ok(value.replace('"', "\\\""))
}

/// Execute the actual curl request when http_client feature is enabled.
#[cfg(feature = "http_client")]
#[allow(clippy::too_many_arguments)]
async fn execute_curl_request(
    http_client: &crate::network::HttpClient,
    url: &str,
    method: &str,
    data: Option<&str>,
    headers: &[String],
    head_only: bool,
    _silent: bool,
    verbose: bool,
    fail_on_error: bool,
    follow_redirects: bool,
    write_out: Option<&str>,
    output_file: Option<&str>,
    compressed: bool,
    user_auth: Option<&str>,
    user_agent: Option<&str>,
    referer: Option<&str>,
    max_time: Option<u64>,
    connect_timeout: Option<u64>,
    form_fields: &[String],
    ctx: &Context<'_>,
) -> Result<ExecResult> {
    use crate::network::Method;

    // Parse method
    let http_method = match method {
        "GET" => Method::Get,
        "POST" => Method::Post,
        "PUT" => Method::Put,
        "DELETE" => Method::Delete,
        "HEAD" => Method::Head,
        "PATCH" => Method::Patch,
        _ => {
            return Ok(ExecResult::err(
                format!("curl: unsupported method: {}\n", method),
                1,
            ));
        }
    };

    // Parse headers and add custom ones
    let mut header_pairs: Vec<(String, String)> = Vec::new();
    for header in headers {
        if let Some(colon_pos) = header.find(':') {
            let name = header[..colon_pos].trim().to_string();
            let value = header[colon_pos + 1..].trim().to_string();
            header_pairs.push((name, value));
        }
    }

    // Add --compressed header (request gzip/deflate)
    if compressed {
        header_pairs.push(("Accept-Encoding".to_string(), "gzip, deflate".to_string()));
    }

    // Add basic auth header
    if let Some(auth) = user_auth {
        use base64::Engine;
        let encoded = base64::engine::general_purpose::STANDARD.encode(auth);
        header_pairs.push(("Authorization".to_string(), format!("Basic {}", encoded)));
    }

    // Add custom user agent
    if let Some(ua) = user_agent {
        header_pairs.push(("User-Agent".to_string(), ua.to_string()));
    }

    // Add referer
    if let Some(ref_url) = referer {
        header_pairs.push(("Referer".to_string(), ref_url.to_string()));
    }

    // Verbose output buffer
    let mut verbose_output = String::new();

    // Build multipart body if -F fields are present
    let multipart_body: Option<Vec<u8>> = if !form_fields.is_empty() {
        let boundary = format!(
            "----bashkit{:016x}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        );
        header_pairs.push((
            "Content-Type".to_string(),
            format!("multipart/form-data; boundary={}", boundary),
        ));
        let mut body = Vec::new();
        for field in form_fields {
            if let Some(eq_pos) = field.find('=') {
                let name = &field[..eq_pos];
                let value = &field[eq_pos + 1..];

                // Sanitize field name to prevent header injection
                let safe_name = match sanitize_multipart_name(name, "field name") {
                    Ok(n) => n,
                    Err(e) => return Ok(ExecResult::err(e, 2)),
                };

                body.extend_from_slice(format!("--{}\r\n", boundary).as_bytes());
                if let Some(file_path) = value.strip_prefix('@') {
                    // File upload: key=@filepath[;type=mime]
                    let (path, mime) = if let Some(semi) = file_path.find(';') {
                        let p = &file_path[..semi];
                        let rest = &file_path[semi + 1..];
                        let m = rest
                            .strip_prefix("type=")
                            .unwrap_or("application/octet-stream");
                        (p, m.to_string())
                    } else {
                        (file_path, guess_mime(file_path))
                    };
                    let resolved = resolve_path(ctx.cwd, path);
                    let file_content = ctx.fs.read_file(&resolved).await.unwrap_or_default();
                    let filename = std::path::Path::new(path)
                        .file_name()
                        .map(|n| n.to_string_lossy().to_string())
                        .unwrap_or_else(|| "file".to_string());

                    // Sanitize filename to prevent header injection
                    let safe_filename = match sanitize_multipart_name(&filename, "filename") {
                        Ok(n) => n,
                        Err(e) => return Ok(ExecResult::err(e, 2)),
                    };

                    body.extend_from_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"; filename=\"{}\"\r\n",
                            safe_name, safe_filename
                        )
                        .as_bytes(),
                    );
                    body.extend_from_slice(format!("Content-Type: {}\r\n\r\n", mime).as_bytes());
                    body.extend_from_slice(&file_content);
                } else {
                    // Text field: key=value
                    body.extend_from_slice(
                        format!(
                            "Content-Disposition: form-data; name=\"{}\"\r\n\r\n",
                            safe_name
                        )
                        .as_bytes(),
                    );
                    body.extend_from_slice(value.as_bytes());
                }
                body.extend_from_slice(b"\r\n");
            }
        }
        body.extend_from_slice(format!("--{}--\r\n", boundary).as_bytes());
        Some(body)
    } else {
        None
    };

    // Make the request
    let initial_body = if multipart_body.is_some() {
        multipart_body.as_deref().map(|b| b.to_vec())
    } else {
        data.map(|d| d.as_bytes().to_vec())
    };
    let mut current_body = initial_body;
    let mut current_method = http_method;
    let mut current_headers = header_pairs.clone();
    let mut current_url = url.to_string();
    let mut redirect_count = 0;
    const MAX_REDIRECTS: u32 = 10;

    loop {
        if verbose {
            verbose_output.push_str(&format!("> {} {} HTTP/1.1\r\n", method, current_url));
            for (name, value) in &current_headers {
                verbose_output.push_str(&format!("> {}: {}\r\n", name, value));
            }
            verbose_output.push_str(">\r\n");
        }

        let result = http_client
            .request_with_timeouts(
                current_method,
                &current_url,
                current_body.as_deref(),
                &current_headers,
                max_time,
                connect_timeout,
            )
            .await;

        match result {
            Ok(response) => {
                if verbose {
                    verbose_output.push_str(&format!("< HTTP/1.1 {}\r\n", response.status));
                    for (name, value) in &response.headers {
                        verbose_output.push_str(&format!("< {}: {}\r\n", name, value));
                    }
                    verbose_output.push_str("<\r\n");
                }

                // Handle redirects if -L flag is set
                if follow_redirects
                    && (response.status == 301
                        || response.status == 302
                        || response.status == 303
                        || response.status == 307
                        || response.status == 308)
                {
                    redirect_count += 1;
                    if redirect_count > MAX_REDIRECTS {
                        return Ok(ExecResult::err(
                            format!("curl: maximum redirects ({}) exceeded\n", MAX_REDIRECTS),
                            47,
                        ));
                    }

                    // Find Location header
                    if let Some((_, location)) = response
                        .headers
                        .iter()
                        .find(|(k, _)| k.eq_ignore_ascii_case("location"))
                    {
                        let prev_url = current_url.clone();
                        current_url = resolve_redirect_url(&prev_url, location);

                        // THREAT[TM-NET]: Strip sensitive headers on cross-origin
                        // redirect to prevent credential leakage (issue #998).
                        if !same_origin(&prev_url, &current_url) {
                            current_headers.retain(|(name, _)| {
                                !SENSITIVE_HEADERS
                                    .iter()
                                    .any(|s| name.eq_ignore_ascii_case(s))
                            });
                        }

                        // THREAT[TM-NET]: Convert POST to GET on 301/302/303
                        // per HTTP spec — drop body (issue #998).
                        if matches!(response.status, 301..=303)
                            && matches!(current_method, Method::Post)
                        {
                            current_method = Method::Get;
                            current_body = None;
                        }

                        continue;
                    }
                }

                // Check for HTTP errors if -f flag is set
                if fail_on_error && response.status >= 400 {
                    return Ok(ExecResult {
                        stdout: String::new(),
                        stderr: format!(
                            "curl: (22) The requested URL returned error: {}\n",
                            response.status
                        ),
                        exit_code: 22,
                        control_flow: crate::interpreter::ControlFlow::None,
                        ..Default::default()
                    });
                }

                // Get response body, potentially decompressing
                let body_bytes = if compressed {
                    // Check Content-Encoding header
                    let encoding = response
                        .headers
                        .iter()
                        .find(|(k, _)| k.eq_ignore_ascii_case("content-encoding"))
                        .map(|(_, v)| v.as_str());

                    match encoding {
                        Some("gzip") => {
                            decompress_gzip(&response.body, http_client.max_response_bytes())?
                        }
                        Some("deflate") => {
                            decompress_deflate(&response.body, http_client.max_response_bytes())?
                        }
                        _ => response.body.clone(),
                    }
                } else {
                    response.body.clone()
                };

                // Format output
                let output = if head_only {
                    // For -I, output headers
                    let mut header_output = format!("HTTP/1.1 {} OK\r\n", response.status);
                    for (name, value) in &response.headers {
                        header_output.push_str(&format!("{}: {}\r\n", name, value));
                    }
                    header_output.push_str("\r\n");
                    header_output
                } else {
                    String::from_utf8_lossy(&body_bytes).into_owned()
                };

                // Write to file if -o specified
                if let Some(file_path) = output_file {
                    let full_path = resolve_path(ctx.cwd, file_path);
                    if let Err(e) = ctx.fs.write_file(&full_path, output.as_bytes()).await {
                        return Ok(ExecResult::err(
                            format!("curl: failed to write to {}: {}\n", file_path, e),
                            23,
                        ));
                    }
                    // Output write-out format if specified
                    let mut stdout = verbose_output;
                    if let Some(fmt) = write_out {
                        stdout.push_str(&format_write_out(fmt, &response, output.len()));
                    }
                    return Ok(ExecResult::ok(stdout));
                }

                // Append write-out format if specified
                let mut final_output = verbose_output;
                final_output.push_str(&output);
                if let Some(fmt) = write_out {
                    final_output.push_str(&format_write_out(fmt, &response, output.len()));
                }

                return Ok(ExecResult::ok(final_output));
            }
            Err(e) => {
                let error_msg = e.to_string();

                // Determine appropriate exit code based on error type
                let exit_code = if error_msg.contains("access denied") {
                    7 // curl: couldn't connect to host
                } else if error_msg.contains("timeout") || error_msg.contains("timed out") {
                    28 // curl: operation timed out
                } else if error_msg.contains("response too large") {
                    63 // curl: maximum file size exceeded
                } else if error_msg.contains("invalid URL") {
                    3 // curl: URL malformed
                } else {
                    1 // general error
                };

                return Ok(ExecResult::err(format!("curl: {}\n", error_msg), exit_code));
            }
        }
    }
}

/// Guess MIME type from file extension
#[cfg(feature = "http_client")]
fn guess_mime(path: &str) -> String {
    match std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
    {
        Some("json") => "application/json",
        Some("xml") => "application/xml",
        Some("html" | "htm") => "text/html",
        Some("txt" | "log" | "csv") => "text/plain",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("pdf") => "application/pdf",
        Some("gz" | "tgz") => "application/gzip",
        Some("tar") => "application/x-tar",
        Some("zip") => "application/zip",
        _ => "application/octet-stream",
    }
    .to_string()
}

/// Resolve a redirect URL which may be relative.
#[cfg(feature = "http_client")]
fn resolve_redirect_url(base: &str, location: &str) -> String {
    if location.starts_with("http://") || location.starts_with("https://") {
        location.to_string()
    } else if location.starts_with('/') {
        // Absolute path - combine with base scheme, host, and port
        if let Ok(base_url) = url::Url::parse(base) {
            let host = base_url.host_str().unwrap_or("");
            if let Some(port) = base_url.port() {
                format!("{}://{}:{}{}", base_url.scheme(), host, port, location)
            } else {
                format!("{}://{}{}", base_url.scheme(), host, location)
            }
        } else {
            location.to_string()
        }
    } else {
        // Relative path
        if let Ok(base_url) = url::Url::parse(base)
            && let Ok(resolved) = base_url.join(location)
        {
            return resolved.to_string();
        }
        location.to_string()
    }
}

/// Check if two URLs have the same origin (scheme + host + port).
fn same_origin(a: &str, b: &str) -> bool {
    let (Ok(a_url), Ok(b_url)) = (url::Url::parse(a), url::Url::parse(b)) else {
        return false;
    };
    a_url.scheme() == b_url.scheme()
        && a_url.host_str() == b_url.host_str()
        && a_url.port_or_known_default() == b_url.port_or_known_default()
}

/// Sensitive headers that must not be forwarded cross-origin on redirect.
const SENSITIVE_HEADERS: &[&str] = &["authorization", "cookie", "proxy-authorization"];

/// Format the -w/--write-out output.
#[cfg(feature = "http_client")]
fn format_write_out(fmt: &str, response: &crate::network::Response, size: usize) -> String {
    let mut output = fmt.to_string();
    output = output.replace("%{http_code}", &response.status.to_string());
    output = output.replace("%{size_download}", &size.to_string());
    output = output.replace("%{content_type}", {
        response
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
            .map(|(_, v)| v.as_str())
            .unwrap_or("")
    });
    output = output.replace("\\n", "\n");
    output = output.replace("\\t", "\t");
    output
}

/// Decompress gzip data with size limit.
///
/// Returns error if decompressed size exceeds max_size (prevents zip bombs).
#[cfg(feature = "http_client")]
fn decompress_gzip(data: &[u8], max_size: usize) -> Result<Vec<u8>> {
    use flate2::read::GzDecoder;
    use std::io::Read;

    let mut decoder = GzDecoder::new(data);
    let mut decompressed = Vec::new();
    let mut buffer = [0u8; 8192];

    loop {
        match decoder.read(&mut buffer) {
            Ok(0) => break,
            Ok(n) => {
                if decompressed.len() + n > max_size {
                    return Err(crate::error::Error::Network(format!(
                        "decompressed response too large: exceeded {} bytes limit",
                        max_size
                    )));
                }
                decompressed.extend_from_slice(&buffer[..n]);
            }
            Err(e) => {
                return Err(crate::error::Error::Network(format!(
                    "gzip decompression failed: {}",
                    e
                )));
            }
        }
    }

    Ok(decompressed)
}

/// Decompress deflate data with size limit.
///
/// Returns error if decompressed size exceeds max_size (prevents zip bombs).
#[cfg(feature = "http_client")]
fn decompress_deflate(data: &[u8], max_size: usize) -> Result<Vec<u8>> {
    use flate2::read::DeflateDecoder;
    use std::io::Read;

    let mut decoder = DeflateDecoder::new(data);
    let mut decompressed = Vec::new();
    let mut buffer = [0u8; 8192];

    loop {
        match decoder.read(&mut buffer) {
            Ok(0) => break,
            Ok(n) => {
                if decompressed.len() + n > max_size {
                    return Err(crate::error::Error::Network(format!(
                        "decompressed response too large: exceeded {} bytes limit",
                        max_size
                    )));
                }
                decompressed.extend_from_slice(&buffer[..n]);
            }
            Err(e) => {
                return Err(crate::error::Error::Network(format!(
                    "deflate decompression failed: {}",
                    e
                )));
            }
        }
    }

    Ok(decompressed)
}

/// The wget builtin - download files from URLs.
///
/// Usage: wget [OPTIONS] URL
///
/// Options:
///   -q, --quiet        Quiet mode (no progress output)
///   -O FILE            Write output to FILE (use '-' for stdout)
///   --spider           Don't download, just check if URL exists
///   --header "H: V"    Add custom header
///   -U, --user-agent S Custom user agent string
///   --post-data DATA   POST data with request
///   -t, --tries N      Number of retries (ignored, for compatibility)
///   -T, --timeout S    Timeout in seconds for all operations
///   --connect-timeout S Timeout in seconds for connection
///
/// Note: Network access requires the 'http_client' feature and proper
/// URL allowlist configuration.
///
/// # Security
///
/// - Response size is limited to prevent memory exhaustion
/// - Only URLs in the allowlist can be accessed
pub struct Wget;

#[async_trait]
impl Builtin for Wget {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: wget [OPTIONS] URL\nDownload files from the web.\n\n  -q, --quiet\tquiet mode\n  -O FILE\twrite output to FILE (use '-' for stdout)\n  --spider\tdon't download, just check if URL exists\n  --header \"H: V\"\tadd custom header\n  -U, --user-agent STRING\tcustom user agent\n  --post-data DATA\tPOST data with request\n  -t, --tries NUM\tnumber of retries\n  -T, --timeout SECONDS\ttimeout for all operations\n  --connect-timeout SECONDS\tconnection timeout\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("GNU Wget 1.21 (bashkit)"),
        ) {
            return Ok(r);
        }
        // Parse arguments
        let mut quiet = false;
        let mut output_file: Option<String> = None;
        let mut spider = false;
        let mut headers: Vec<String> = Vec::new();
        let mut user_agent: Option<String> = None;
        let mut post_data: Option<String> = None;
        let mut timeout: Option<u64> = None;
        let mut connect_timeout: Option<u64> = None;
        let mut url: Option<String> = None;

        let mut i = 0;
        while i < ctx.args.len() {
            let arg = &ctx.args[i];
            match arg.as_str() {
                "-q" | "--quiet" => quiet = true,
                "--spider" => spider = true,
                "-O" => {
                    i += 1;
                    if i < ctx.args.len() {
                        output_file = Some(ctx.args[i].clone());
                    }
                }
                "--header" => {
                    i += 1;
                    if i < ctx.args.len() {
                        headers.push(ctx.args[i].clone());
                    }
                }
                "-U" | "--user-agent" => {
                    i += 1;
                    if i < ctx.args.len() {
                        user_agent = Some(ctx.args[i].clone());
                    }
                }
                "--post-data" => {
                    i += 1;
                    if i < ctx.args.len() {
                        post_data = Some(ctx.args[i].clone());
                    }
                }
                "-t" | "--tries" => {
                    // Ignore retry count (for compatibility)
                    i += 1;
                }
                "-T" | "--timeout" => {
                    i += 1;
                    if i < ctx.args.len() {
                        timeout = ctx.args[i].parse().ok();
                    }
                }
                "--connect-timeout" => {
                    i += 1;
                    if i < ctx.args.len() {
                        connect_timeout = ctx.args[i].parse().ok();
                    }
                }
                _ if !arg.starts_with('-') => {
                    url = Some(arg.clone());
                }
                _ => {
                    // Ignore unknown options
                }
            }
            i += 1;
        }

        // Validate URL
        let url = match url {
            Some(u) => u,
            None => {
                return Ok(ExecResult::err("wget: missing URL\n".to_string(), 1));
            }
        };

        // Check if network is configured
        #[cfg(feature = "http_client")]
        {
            if let Some(http_client) = ctx.http_client {
                return execute_wget_request(
                    http_client,
                    &url,
                    quiet,
                    spider,
                    output_file.as_deref(),
                    &headers,
                    user_agent.as_deref(),
                    post_data.as_deref(),
                    timeout,
                    connect_timeout,
                    &ctx,
                )
                .await;
            }
        }

        // Network not configured
        let _ = (
            quiet,
            output_file,
            spider,
            headers,
            user_agent,
            post_data,
            timeout,
            connect_timeout,
        );

        Ok(ExecResult::err(
            format!(
                "wget: network access not configured\nURL: {}\n\
                 Note: Network builtins require the 'http_client' feature and\n\
                 URL allowlist configuration for security.\n",
                url
            ),
            1,
        ))
    }
}

/// Execute the actual wget request when http_client feature is enabled.
#[cfg(feature = "http_client")]
#[allow(clippy::too_many_arguments)]
async fn execute_wget_request(
    http_client: &crate::network::HttpClient,
    url: &str,
    quiet: bool,
    spider: bool,
    output_file: Option<&str>,
    headers: &[String],
    user_agent: Option<&str>,
    post_data: Option<&str>,
    timeout: Option<u64>,
    connect_timeout: Option<u64>,
    ctx: &Context<'_>,
) -> Result<ExecResult> {
    use crate::network::Method;

    // Build header pairs
    let mut header_pairs: Vec<(String, String)> = Vec::new();
    for header in headers {
        if let Some(colon_pos) = header.find(':') {
            let name = header[..colon_pos].trim().to_string();
            let value = header[colon_pos + 1..].trim().to_string();
            header_pairs.push((name, value));
        }
    }

    // Add custom user agent
    if let Some(ua) = user_agent {
        header_pairs.push(("User-Agent".to_string(), ua.to_string()));
    }

    // Determine method and body
    let (method, body) = if spider {
        (Method::Head, None)
    } else if post_data.is_some() {
        (Method::Post, post_data.map(|d| d.as_bytes()))
    } else {
        (Method::Get, None)
    };

    let result = http_client
        .request_with_timeouts(method, url, body, &header_pairs, timeout, connect_timeout)
        .await;

    match result {
        Ok(response) => {
            // Spider mode - just check if accessible
            if spider {
                if response.status >= 200 && response.status < 400 {
                    let msg = if quiet {
                        String::new()
                    } else {
                        format!(
                            "Spider mode enabled. Check if remote file exists.\nHTTP request sent, awaiting response... {} OK\nRemote file exists.\n",
                            response.status
                        )
                    };
                    return Ok(ExecResult::ok(msg));
                } else {
                    return Ok(ExecResult::err(
                        format!(
                            "Remote file does not exist -- broken link!!!\n\
                             HTTP request sent, awaiting response... {} Error\n",
                            response.status
                        ),
                        8,
                    ));
                }
            }

            // Determine output filename
            let output_path = if let Some(file) = output_file {
                if file == "-" {
                    // Output to stdout
                    return Ok(ExecResult::ok(response.body_string()));
                }
                file.to_string()
            } else {
                // Extract filename from URL
                extract_filename_from_url(url)
            };

            // Progress output
            let mut stderr_msg = String::new();
            if !quiet {
                stderr_msg.push_str(&format!(
                    "Connecting to {}... connected.\n\
                     HTTP request sent, awaiting response... {} OK\n\
                     Length: {} [{}]\n\
                     Saving to: '{}'\n\n",
                    extract_host_from_url(url),
                    response.status,
                    response.body.len(),
                    response
                        .headers
                        .iter()
                        .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
                        .map(|(_, v)| v.as_str())
                        .unwrap_or("application/octet-stream"),
                    output_path
                ));
            }

            // Write to file
            let full_path = resolve_path(ctx.cwd, &output_path);
            if let Err(e) = ctx.fs.write_file(&full_path, &response.body).await {
                return Ok(ExecResult::err(
                    format!("wget: failed to write to {}: {}\n", output_path, e),
                    1,
                ));
            }

            if !quiet {
                stderr_msg.push_str(&format!(
                    "'{}' saved [{}/{}]\n",
                    output_path,
                    response.body.len(),
                    response.body.len()
                ));
            }

            Ok(ExecResult {
                stdout: String::new(),
                stderr: stderr_msg,
                exit_code: 0,
                control_flow: crate::interpreter::ControlFlow::None,
                ..Default::default()
            })
        }
        Err(e) => {
            let error_msg = e.to_string();

            // Determine appropriate exit code
            let exit_code = if error_msg.contains("access denied") || error_msg.contains("timeout")
            {
                4 // Network failure
            } else {
                1 // General error
            };

            Ok(ExecResult::err(format!("wget: {}\n", error_msg), exit_code))
        }
    }
}

/// Extract filename from URL for wget default output.
#[cfg(feature = "http_client")]
fn extract_filename_from_url(url: &str) -> String {
    if let Ok(parsed) = url::Url::parse(url) {
        let path = parsed.path();
        if let Some(filename) = path.rsplit('/').next()
            && !filename.is_empty()
        {
            return filename.to_string();
        }
    }
    "index.html".to_string()
}

/// Extract host from URL for wget progress output.
#[cfg(feature = "http_client")]
fn extract_host_from_url(url: &str) -> String {
    if let Ok(parsed) = url::Url::parse(url)
        && let Some(host) = parsed.host_str()
    {
        return host.to_string();
    }
    "unknown".to_string()
}

#[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 run_curl(args: &[&str]) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Curl.execute(ctx).await.unwrap()
    }

    async fn run_wget(args: &[&str]) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Wget.execute(ctx).await.unwrap()
    }

    #[tokio::test]
    async fn test_curl_no_url() {
        let result = run_curl(&[]).await;
        assert_ne!(result.exit_code, 0);
        assert!(result.stderr.contains("no URL specified"));
    }

    #[tokio::test]
    async fn test_curl_with_url_no_network() {
        let result = run_curl(&["https://example.com"]).await;
        // Should fail gracefully without network config
        assert_ne!(result.exit_code, 0);
        assert!(result.stderr.contains("network access not configured"));
    }

    #[tokio::test]
    async fn test_wget_no_url() {
        let result = run_wget(&[]).await;
        assert_ne!(result.exit_code, 0);
        assert!(result.stderr.contains("missing URL"));
    }

    #[tokio::test]
    async fn test_wget_with_url_no_network() {
        let result = run_wget(&["https://example.com"]).await;
        assert_ne!(result.exit_code, 0);
        assert!(result.stderr.contains("network access not configured"));
    }

    async fn run_curl_with_stdin_and_fs(
        args: &[&str],
        stdin: Option<&str>,
        files: &[(&str, &[u8])],
    ) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        for (path, content) in files {
            fs.write_file(std::path::Path::new(path), content)
                .await
                .unwrap();
        }
        let mut variables = HashMap::new();
        let env = HashMap::new();
        let mut cwd = PathBuf::from("/");

        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        Curl.execute(ctx).await.unwrap()
    }

    #[tokio::test]
    async fn test_curl_data_at_stdin() {
        // -d @- should read from stdin (network not configured, but data resolution
        // happens before the network check)
        let result =
            run_curl_with_stdin_and_fs(&["-d", "@-", "https://example.com"], Some("hello"), &[])
                .await;
        // Without network, we get the "network access not configured" error,
        // but the important thing is that @- was resolved (not sent literally)
        assert!(result.stderr.contains("network access not configured"));
    }

    #[tokio::test]
    async fn test_curl_data_at_file() {
        let result = run_curl_with_stdin_and_fs(
            &["-d", "@/data.json", "https://example.com"],
            None,
            &[("/data.json", b"{\"key\":\"value\"}")],
        )
        .await;
        assert!(result.stderr.contains("network access not configured"));
    }

    #[tokio::test]
    async fn test_curl_data_at_file_not_found() {
        let result =
            run_curl_with_stdin_and_fs(&["-d", "@/missing.json", "https://example.com"], None, &[])
                .await;
        assert_ne!(result.exit_code, 0);
        assert_eq!(result.exit_code, 26);
        assert!(result.stderr.contains("Failed reading data file"));
    }

    #[tokio::test]
    async fn test_curl_data_at_stdin_none() {
        // -d @- with no stdin should resolve to empty string
        let result =
            run_curl_with_stdin_and_fs(&["-d", "@-", "https://example.com"], None, &[]).await;
        // Should proceed past data resolution (get network error, not a data error)
        assert!(result.stderr.contains("network access not configured"));
    }

    #[tokio::test]
    async fn test_curl_data_literal_no_at() {
        // Regular -d without @ prefix should pass through unchanged
        let result =
            run_curl_with_stdin_and_fs(&["-d", "plain-data", "https://example.com"], None, &[])
                .await;
        assert!(result.stderr.contains("network access not configured"));
    }

    #[cfg(feature = "http_client")]
    mod network_tests {
        use super::*;

        #[test]
        fn test_extract_filename_from_url() {
            assert_eq!(
                extract_filename_from_url("https://example.com/file.txt"),
                "file.txt"
            );
            assert_eq!(
                extract_filename_from_url("https://example.com/path/to/document.pdf"),
                "document.pdf"
            );
            assert_eq!(
                extract_filename_from_url("https://example.com/"),
                "index.html"
            );
            assert_eq!(
                extract_filename_from_url("https://example.com"),
                "index.html"
            );
        }

        #[test]
        fn test_resolve_redirect_url_absolute() {
            let base = "https://example.com/original";
            assert_eq!(
                resolve_redirect_url(base, "https://other.com/new"),
                "https://other.com/new"
            );
        }

        #[test]
        fn test_resolve_redirect_url_absolute_path() {
            let base = "https://example.com/original/path";
            assert_eq!(
                resolve_redirect_url(base, "/new/path"),
                "https://example.com/new/path"
            );
        }

        #[test]
        fn test_resolve_redirect_url_relative() {
            let base = "https://example.com/original/";
            assert_eq!(
                resolve_redirect_url(base, "relative"),
                "https://example.com/original/relative"
            );
        }

        #[test]
        fn test_resolve_redirect_url_preserves_port() {
            let base = "http://localhost:8080/original";
            assert_eq!(
                resolve_redirect_url(base, "/new/path"),
                "http://localhost:8080/new/path"
            );
        }

        #[test]
        fn test_resolve_redirect_url_no_port() {
            let base = "https://example.com/original";
            assert_eq!(
                resolve_redirect_url(base, "/new"),
                "https://example.com/new"
            );
        }

        #[test]
        fn test_same_origin_true() {
            assert!(same_origin(
                "https://example.com/path1",
                "https://example.com/path2"
            ));
        }

        #[test]
        fn test_same_origin_false_different_host() {
            assert!(!same_origin(
                "https://example.com/path",
                "https://other.com/path"
            ));
        }

        #[test]
        fn test_same_origin_false_different_port() {
            assert!(!same_origin(
                "http://localhost:8080/path",
                "http://localhost:9090/path"
            ));
        }

        #[test]
        fn test_same_origin_false_different_scheme() {
            assert!(!same_origin(
                "http://example.com/path",
                "https://example.com/path"
            ));
        }

        #[test]
        fn test_sensitive_headers_stripped_cross_origin() {
            let headers = vec![
                ("Authorization".to_string(), "Bearer secret".to_string()),
                ("Content-Type".to_string(), "application/json".to_string()),
                ("Cookie".to_string(), "session=abc".to_string()),
            ];
            let mut filtered = headers.clone();
            filtered.retain(|(name, _)| {
                !SENSITIVE_HEADERS
                    .iter()
                    .any(|s| name.eq_ignore_ascii_case(s))
            });
            assert_eq!(filtered.len(), 1);
            assert_eq!(filtered[0].0, "Content-Type");
        }

        #[test]
        fn test_sanitize_multipart_name_normal() {
            let result = sanitize_multipart_name("field1", "field name").unwrap();
            assert_eq!(result, "field1");
        }

        #[test]
        fn test_sanitize_multipart_name_escapes_quotes() {
            let result = sanitize_multipart_name("fie\"ld", "field name").unwrap();
            assert_eq!(result, "fie\\\"ld");
        }

        #[test]
        fn test_sanitize_multipart_name_rejects_cr() {
            let result = sanitize_multipart_name("field\r\nInjected: header", "field name");
            assert!(result.is_err());
            assert!(result.unwrap_err().contains("illegal newline"));
        }

        #[test]
        fn test_sanitize_multipart_name_rejects_lf() {
            let result = sanitize_multipart_name("field\nInjected: header", "field name");
            assert!(result.is_err());
            assert!(result.unwrap_err().contains("illegal newline"));
        }

        #[test]
        fn test_sanitize_multipart_name_rejects_bare_cr() {
            let result = sanitize_multipart_name("field\rname", "filename");
            assert!(result.is_err());
        }

        #[tokio::test]
        async fn test_curl_multipart_field_name_with_quotes() {
            // Field name with quotes should be escaped, not cause injection
            let result = run_curl_with_stdin_and_fs(
                &["-F", "fie\"ld=value", "https://example.com"],
                None,
                &[],
            )
            .await;
            // Should reach network error (field name accepted after escaping)
            assert!(result.stderr.contains("network access not configured"));
        }

        #[tokio::test]
        async fn test_curl_multipart_field_name_with_newline_rejected() {
            // Field name with newline must be rejected
            let result = run_curl_with_stdin_and_fs(
                &["-F", "field\r\nInjected: evil=value", "https://example.com"],
                None,
                &[],
            )
            .await;
            assert_ne!(result.exit_code, 0);
            assert!(result.stderr.contains("illegal newline"));
        }

        #[tokio::test]
        async fn test_curl_multipart_normal_field_works() {
            // Normal field names should work fine
            let result = run_curl_with_stdin_and_fs(
                &["-F", "username=alice", "https://example.com"],
                None,
                &[],
            )
            .await;
            // Should reach network error (multipart built successfully)
            assert!(result.stderr.contains("network access not configured"));
        }
    }
}