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
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
mod common;
mod system_integration;

#[macro_use]
mod platform_test_macro;

#[cfg(target_os = "linux")]
mod tests {
    use super::*;
    use crate::system_integration::{JailTestPlatform, httpjail_cmd};

    /// Linux-specific platform implementation
    struct LinuxPlatform;

    impl system_integration::JailTestPlatform for LinuxPlatform {
        fn require_privileges() {
            // Check if running as root
            let uid = unsafe { libc::geteuid() };
            if uid != 0 {
                eprintln!("\n⚠️  Test requires root privileges.");
                eprintln!("   Run with: sudo cargo test --test linux_integration");
                eprintln!("   Or in GitHub Actions, tests run with sudo automatically\n");
                panic!("Test skipped: requires root privileges");
            }
        }

        fn platform_name() -> &'static str {
            "Linux"
        }

        fn supports_https_interception() -> bool {
            true // Linux with network namespaces supports transparent TLS interception
        }
    }

    // Generate all the shared platform tests
    platform_tests!(LinuxPlatform);

    // Linux-specific tests below
    use serial_test::serial;

    #[test]
    fn test_root_dry_run_enforces_restricted_policy() {
        LinuxPlatform::require_privileges();
        assert_eq!(
            httpjail::jail::get_canary_dir(),
            std::path::PathBuf::from("/var/lib/httpjail/canaries")
        );
        let mut inline = httpjail_cmd();
        let rejected = inline
            .args([
                "--sh",
                "/usr/bin/id -u",
                "--test",
                "https://example.invalid/",
            ])
            .output()
            .unwrap();
        assert!(!rejected.status.success());
        assert!(String::from_utf8_lossy(&rejected.stderr).contains("one trusted executable"));

        let mut trusted = httpjail_cmd();
        let output = trusted
            .args(["--sh", "/usr/bin/id", "--test", "https://example.invalid/"])
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(String::from_utf8_lossy(&output.stdout).contains("uid=65534"));
    }

    #[test]
    fn test_public_ca_is_readable_without_exposing_key() {
        LinuxPlatform::require_privileges();
        let mut cmd = httpjail_cmd();
        let run = cmd
            .args(["--js", "false", "--", "/usr/bin/true"])
            .output()
            .unwrap();
        assert!(
            run.status.success(),
            "{}",
            String::from_utf8_lossy(&run.stderr)
        );

        let cert = httpjail::tls::CertificateManager::get_ca_cert_path().unwrap();
        let uid = std::env::var("SUDO_UID").unwrap();
        let gid = std::env::var("SUDO_GID").unwrap();
        let read = |path: &std::path::Path| {
            std::process::Command::new("/usr/bin/setpriv")
                .args([
                    "--no-new-privs",
                    &format!("--reuid={uid}"),
                    &format!("--regid={gid}"),
                    "--clear-groups",
                    "--",
                    "/usr/bin/cat",
                ])
                .arg(path)
                .output()
                .unwrap()
        };
        let cert_read = read(cert.as_std_path());
        assert!(cert_read.status.success());
        assert!(String::from_utf8_lossy(&cert_read.stdout).contains("BEGIN CERTIFICATE"));
        let key = cert.with_file_name("ca-key.pem");
        assert!(!read(key.as_std_path()).status.success());
    }

    #[test]
    fn test_root_request_log_cannot_append_protected_file() {
        LinuxPlatform::require_privileges();
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("protected");
        std::fs::write(&target, "unchanged").unwrap();
        let mut cmd = httpjail_cmd();
        let output = cmd
            .args(["--js", "false", "--request-log"])
            .arg(&target)
            .args(["--test", "https://example.invalid/\nINJECTED"])
            .output()
            .unwrap();
        assert!(!output.status.success());
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "unchanged");
    }

    #[test]
    #[ignore]
    fn pid_namespace_probe_helper() {
        assert_eq!(unsafe { libc::getpid() }, 1);
        assert!(
            std::fs::read_to_string("/proc/1/comm")
                .unwrap()
                .starts_with("linux_integrat")
        );
    }

    #[test]
    fn test_native_jail_has_private_pid_namespace() {
        LinuxPlatform::require_privileges();
        let mut cmd = httpjail_cmd();
        cmd.args(["--js", "false", "--"])
            .arg(std::env::current_exe().unwrap())
            .args(["--ignored", "--exact", "tests::pid_namespace_probe_helper"]);
        let output = cmd.output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "PID namespace probe failed: {stdout} {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    #[ignore]
    fn unix_socket_probe_helper() {
        let path = std::env::var("HTTPJAIL_TEST_UNIX_SOCKET").unwrap();
        let error = std::os::unix::net::UnixStream::connect(path).unwrap_err();
        assert_eq!(error.raw_os_error(), Some(libc::EPERM));
        // Local stream socketpairs are needed by threaded DNS resolvers.
        let (a, _b) = std::os::unix::net::UnixStream::pair().unwrap();
        drop(a);
        let mut pair = [-1_i32; 2];
        let result =
            unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_DGRAM, 0, pair.as_mut_ptr()) };
        assert_eq!(result, -1);
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::EPERM)
        );
        // io_uring can create sockets without calling socket(2), so its
        // submission syscalls must also be denied in this namespace.
        let result = unsafe { libc::syscall(libc::SYS_io_uring_setup, 1, std::ptr::null::<u8>()) };
        assert_eq!(result, -1);
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::EPERM)
        );
        let vsock = unsafe { libc::socket(libc::AF_VSOCK, libc::SOCK_STREAM, 0) };
        assert_eq!(vsock, -1);
        assert_eq!(
            std::io::Error::last_os_error().raw_os_error(),
            Some(libc::EPERM)
        );
    }

    #[test]
    fn test_native_jail_blocks_host_unix_sockets() {
        LinuxPlatform::require_privileges();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("host.sock");
        let _listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
        let mut cmd = httpjail_cmd();
        cmd.args(["--js", "false", "--"])
            .arg(std::env::current_exe().unwrap())
            .args(["--ignored", "--exact", "tests::unix_socket_probe_helper"])
            .env("HTTPJAIL_TEST_UNIX_SOCKET", &path);
        let output = cmd.output().unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed"),
            "Unix socket probe failed: {stdout} {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn test_strong_jail_rejects_user_writable_policy_program() {
        LinuxPlatform::require_privileges();
        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("policy.sh");
        std::fs::write(&script, "#!/bin/sh\nexit 0\n").unwrap();
        let mut cmd = httpjail_cmd();
        cmd.arg("--sh").arg(&script).args(["--", "true"]);
        let output = cmd.output().unwrap();
        assert!(!output.status.success());
        assert!(
            String::from_utf8_lossy(&output.stderr).contains("root-owned, non-writable"),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn test_direct_root_strong_jail_refused() {
        LinuxPlatform::require_privileges();
        let output = std::process::Command::new(env!("CARGO_BIN_EXE_httpjail"))
            .env_remove("SUDO_UID")
            .env_remove("SUDO_GID")
            .args(["--js", "false", "--", "true"])
            .output()
            .unwrap();
        assert!(!output.status.success());
        assert!(
            String::from_utf8_lossy(&output.stderr).contains("requires sudo from a non-root user"),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn test_strong_jail_clears_groups_and_blocks_setuid() {
        LinuxPlatform::require_privileges();
        let mut groups = httpjail_cmd();
        groups.args(["--js", "true", "--", "id", "-G"]);
        let output = groups.output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        let expected = std::env::var("SUDO_GID").expect("run as sudo from non-root user");
        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);

        let mut sudo = httpjail_cmd();
        sudo.args(["--js", "true", "--", "sudo", "-n", "id", "-u"]);
        let output = sudo.output().unwrap();
        assert!(
            !output.status.success(),
            "jailed process regained root via sudo"
        );
    }

    /// Linux-specific test: verify namespace cleanup
    #[test]
    #[serial]
    fn test_namespace_cleanup() {
        LinuxPlatform::require_privileges();

        // Get initial namespace count
        let output = std::process::Command::new("ip")
            .args(["netns", "list"])
            .output()
            .expect("Failed to list namespaces");

        let initial_namespaces = String::from_utf8_lossy(&output.stdout);
        let initial_count = initial_namespaces
            .lines()
            .filter(|line| line.contains("httpjail_"))
            .count();

        // Run httpjail
        let mut cmd = httpjail_cmd();
        cmd.arg("--js")
            .arg("true")
            .arg("--")
            .arg("echo")
            .arg("test");

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

        // Check namespace was cleaned up
        let output = std::process::Command::new("ip")
            .args(["netns", "list"])
            .output()
            .expect("Failed to list namespaces");

        let final_namespaces = String::from_utf8_lossy(&output.stdout);
        let final_count = final_namespaces
            .lines()
            .filter(|line| line.contains("httpjail_"))
            .count();

        assert_eq!(
            initial_count, final_count,
            "Namespace not cleaned up properly. Initial: {}, Final: {}",
            initial_count, final_count
        );
    }

    /// Comprehensive test to verify all resources are cleaned up after jail execution
    #[test]
    #[serial]
    #[cfg(feature = "isolated-cleanup-tests")]
    fn test_comprehensive_resource_cleanup() {
        LinuxPlatform::require_privileges();

        // 1. Get initial state of all resources

        // Network namespaces
        let initial_namespaces = std::process::Command::new("ip")
            .args(["netns", "list"])
            .output()
            .expect("Failed to list namespaces")
            .stdout;
        let initial_ns_count = String::from_utf8_lossy(&initial_namespaces)
            .lines()
            .filter(|line| line.contains("httpjail_"))
            .count();

        // Virtual ethernet pairs
        let initial_links = std::process::Command::new("ip")
            .args(["link", "show"])
            .output()
            .expect("Failed to list network links")
            .stdout;
        let initial_veth_count = String::from_utf8_lossy(&initial_links)
            .lines()
            .filter(|line| line.contains("vh_") || line.contains("vn_"))
            .count();

        // NFTables tables
        let initial_nft_tables = std::process::Command::new("nft")
            .args(["list", "tables"])
            .output()
            .expect("Failed to list nftables")
            .stdout;
        let initial_nft_count = String::from_utf8_lossy(&initial_nft_tables)
            .lines()
            .filter(|line| line.contains("httpjail_"))
            .count();

        // Namespace config directories
        let initial_netns_dirs = std::fs::read_dir("/etc/netns")
            .map(|entries| {
                entries
                    .filter_map(|e| e.ok())
                    .filter(|e| e.file_name().to_string_lossy().contains("httpjail_"))
                    .count()
            })
            .unwrap_or(0);

        // 2. Run httpjail command
        let mut cmd = httpjail_cmd();
        cmd.arg("--js")
            .arg("true")
            .arg("--")
            .arg("echo")
            .arg("test");

        let output = cmd.output().expect("Failed to execute httpjail");
        assert!(output.status.success(), "httpjail command failed");

        // 3. Check all resources were cleaned up

        // Network namespaces
        let final_namespaces = std::process::Command::new("ip")
            .args(["netns", "list"])
            .output()
            .expect("Failed to list namespaces")
            .stdout;
        let final_ns_count = String::from_utf8_lossy(&final_namespaces)
            .lines()
            .filter(|line| line.contains("httpjail_"))
            .count();
        assert_eq!(
            initial_ns_count, final_ns_count,
            "Network namespace not cleaned up. Initial: {}, Final: {}",
            initial_ns_count, final_ns_count
        );

        // Virtual ethernet pairs
        let final_links = std::process::Command::new("ip")
            .args(["link", "show"])
            .output()
            .expect("Failed to list network links")
            .stdout;
        let final_veth_count = String::from_utf8_lossy(&final_links)
            .lines()
            .filter(|line| line.contains("vh_") || line.contains("vn_"))
            .count();
        assert_eq!(
            initial_veth_count, final_veth_count,
            "Virtual ethernet pairs not cleaned up. Initial: {}, Final: {}",
            initial_veth_count, final_veth_count
        );

        // NFTables tables
        let final_nft_tables = std::process::Command::new("nft")
            .args(["list", "tables"])
            .output()
            .expect("Failed to list nftables")
            .stdout;
        let final_nft_count = String::from_utf8_lossy(&final_nft_tables)
            .lines()
            .filter(|line| line.contains("httpjail_"))
            .count();
        assert_eq!(
            initial_nft_count, final_nft_count,
            "NFTables not cleaned up. Initial: {}, Final: {}",
            initial_nft_count, final_nft_count
        );

        // Namespace config directories
        let final_netns_dirs = std::fs::read_dir("/etc/netns")
            .map(|entries| {
                entries
                    .filter_map(|e| e.ok())
                    .filter(|e| e.file_name().to_string_lossy().contains("httpjail_"))
                    .count()
            })
            .unwrap_or(0);
        assert_eq!(
            initial_netns_dirs, final_netns_dirs,
            "Namespace config directories not cleaned up. Initial: {}, Final: {}",
            initial_netns_dirs, final_netns_dirs
        );
    }

    /// Test cleanup after abnormal termination (SIGINT)
    #[test]
    #[serial]
    #[cfg(feature = "isolated-cleanup-tests")]
    fn test_cleanup_after_sigint() {
        LinuxPlatform::require_privileges();

        use std::thread;
        use std::time::Duration;

        // Get initial resource counts
        let initial_ns_count = std::process::Command::new("ip")
            .args(["netns", "list"])
            .output()
            .map(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .filter(|l| l.contains("httpjail_"))
                    .count()
            })
            .unwrap_or(0);

        // Start httpjail with a long-running command using std::process::Command directly
        let httpjail_path = assert_cmd::cargo::cargo_bin("httpjail");
        let mut child = std::process::Command::new(&httpjail_path)
            .arg("--js")
            .arg("true")
            .arg("--")
            .arg("sleep")
            .arg("60")
            .env("HTTPJAIL_SKIP_KEYCHAIN_INSTALL", "1") // Skip automatic keychain installation during tests
            .spawn()
            .expect("Failed to spawn httpjail");

        // Give it time to set up resources
        thread::sleep(Duration::from_millis(500));

        // Send SIGINT (which ctrlc handles)
        unsafe {
            libc::kill(child.id() as i32, libc::SIGINT);
        }

        // Wait for process to exit
        let _ = child.wait();

        // Give cleanup a moment to complete
        thread::sleep(Duration::from_millis(500));

        // Check resources were cleaned up
        let final_ns_count = std::process::Command::new("ip")
            .args(["netns", "list"])
            .output()
            .map(|o| {
                String::from_utf8_lossy(&o.stdout)
                    .lines()
                    .filter(|l| l.contains("httpjail_"))
                    .count()
            })
            .unwrap_or(0);

        assert_eq!(
            initial_ns_count, final_ns_count,
            "Resources not cleaned up after SIGINT. Initial namespaces: {}, Final: {}",
            initial_ns_count, final_ns_count
        );
    }

    /// Verify outbound TCP connections to non-HTTP ports are blocked inside the jail
    ///
    /// Uses portquiz.net which listens on all TCP ports and returns an HTTP response,
    /// allowing us to test egress on non-standard ports reliably.
    #[test]
    fn test_outbound_tcp_non_http_blocked() {
        LinuxPlatform::require_privileges();

        // Attempt to connect to portquiz.net on port 81 (non-standard HTTP port)
        // Expectation: connection is blocked by namespace egress filter
        let mut cmd = httpjail_cmd();
        cmd.arg("--js").arg("true") // allow all requests through proxy
            .arg("--")
            .arg("sh")
            .arg("-c")
            .arg("curl -s -o /dev/null -w '%{http_code}' --connect-timeout 5 --max-time 8 http://portquiz.net:81 && echo CONNECTED || echo 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);

        eprintln!("[Linux] outbound TCP test stdout: {}", stdout);
        if !stderr.is_empty() {
            eprintln!("[Linux] outbound TCP test stderr: {}", stderr);
        }

        assert!(
            stdout.contains("BLOCKED"),
            "Non-HTTP outbound TCP should be blocked. stdout: {}, stderr: {}",
            stdout.trim(),
            stderr.trim()
        );
    }

    #[test]
    #[ignore]
    fn ipv6_host_probe_helper() {
        let Some(host) = std::env::var("HTTPJAIL_TEST_HOST_IPV6").ok() else {
            return;
        };
        let iface =
            std::ffi::CString::new(std::env::var("HTTPJAIL_TEST_GUEST_IFACE").unwrap()).unwrap();
        let index = unsafe { libc::if_nametoindex(iface.as_ptr()) };
        assert_ne!(index, 0);
        let ip = host.parse::<std::net::Ipv6Addr>().unwrap();
        let port = std::env::var("HTTPJAIL_TEST_HOST_PORT")
            .unwrap()
            .parse::<u16>()
            .unwrap();
        let target = std::net::SocketAddr::V6(std::net::SocketAddrV6::new(ip, port, 0, index));
        let connection =
            std::net::TcpStream::connect_timeout(&target, std::time::Duration::from_millis(300));
        let expected = std::env::var_os("HTTPJAIL_TEST_ALLOW_IPV6").is_some();
        assert_eq!(
            connection.is_ok(),
            expected,
            "Unexpected IPv6 host-veth reachability: {connection:?}"
        );
    }

    #[test]
    fn test_namespace_blocks_host_ipv6_link_local() {
        LinuxPlatform::require_privileges();
        let listener = std::net::TcpListener::bind("[::]:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let mut jail = std::process::Command::new(env!("CARGO_BIN_EXE_httpjail"));
        jail.env("HTTPJAIL_SKIP_KEYCHAIN_INSTALL", "1").args([
            "--timeout",
            "15",
            "--js",
            "false",
            "--",
            "sleep",
            "5",
        ]);
        let mut child = jail.spawn().unwrap();
        let canary_dir = httpjail::jail::get_canary_dir();
        let id = (0..60)
            .find_map(|_| {
                let match_id = std::fs::read_dir(&canary_dir).ok().and_then(|entries| {
                    entries.flatten().find_map(|entry| {
                        (std::fs::read_to_string(entry.path()).ok()?.trim()
                            == child.id().to_string())
                        .then(|| entry.file_name().to_string_lossy().into_owned())
                    })
                });
                if match_id.is_none() {
                    std::thread::sleep(std::time::Duration::from_millis(50));
                }
                match_id
            })
            .expect("jail canary did not appear");
        let host_iface = format!("vh_{id}");
        let namespace = format!("httpjail_{id}");
        let address = (0..60)
            .find_map(|_| {
                let output = std::process::Command::new("ip")
                    .args([
                        "-6",
                        "-o",
                        "addr",
                        "show",
                        "dev",
                        &host_iface,
                        "scope",
                        "link",
                    ])
                    .output()
                    .ok()?;
                let ip = String::from_utf8_lossy(&output.stdout)
                    .split_whitespace()
                    .find_map(|part| {
                        part.strip_suffix("/64")
                            .filter(|ip| ip.starts_with("fe80::"))
                    })
                    .map(str::to_owned);
                let ready = std::process::Command::new("ip")
                    .args([
                        "netns",
                        "exec",
                        &namespace,
                        "nft",
                        "list",
                        "table",
                        "ip6",
                        "httpjail6",
                    ])
                    .output()
                    .is_ok_and(|output| output.status.success());
                if ip.is_none() || !ready {
                    std::thread::sleep(std::time::Duration::from_millis(50));
                }
                ip.filter(|_| ready)
            })
            .expect("IPv6 veth and output filter did not become ready");
        // Some hosts disable automatic guest veth IPv6 addresses. Give this
        // disposable namespace its own link-local source for the control probe.
        let guest_iface = format!("vn_{id}");
        let enable = std::process::Command::new("/usr/sbin/ip")
            .args(["netns", "exec", &namespace, "/usr/sbin/sysctl", "-w"])
            .arg(format!("net.ipv6.conf.{guest_iface}.disable_ipv6=0"))
            .output()
            .unwrap();
        assert!(
            enable.status.success(),
            "{}",
            String::from_utf8_lossy(&enable.stderr)
        );
        let add = std::process::Command::new("/usr/sbin/ip")
            .args([
                "netns",
                "exec",
                &namespace,
                "/usr/sbin/ip",
                "-6",
                "addr",
                "add",
                "fe80::2/64",
                "dev",
                &guest_iface,
                "nodad",
            ])
            .output()
            .unwrap();
        assert!(
            add.status.success(),
            "{}",
            String::from_utf8_lossy(&add.stderr)
        );
        let probe = std::process::Command::new("ip")
            .args(["netns", "exec", &format!("httpjail_{id}")])
            .arg(std::env::current_exe().unwrap())
            .args(["--ignored", "--exact", "tests::ipv6_host_probe_helper"])
            .env("HTTPJAIL_TEST_HOST_IPV6", &address)
            .env("HTTPJAIL_TEST_GUEST_IFACE", format!("vn_{id}"))
            .env("HTTPJAIL_TEST_HOST_PORT", port.to_string())
            .output()
            .unwrap();
        // Control: only inside this disposable jail namespace, remove the IPv6
        // output table and confirm the same host service becomes reachable.
        let removal = std::process::Command::new("ip")
            .args([
                "netns",
                "exec",
                &namespace,
                "nft",
                "delete",
                "table",
                "ip6",
                "httpjail6",
            ])
            .output()
            .unwrap();
        assert!(
            removal.status.success(),
            "{}",
            String::from_utf8_lossy(&removal.stderr)
        );
        let control = std::process::Command::new("ip")
            .args(["netns", "exec", &namespace])
            .arg(std::env::current_exe().unwrap())
            .args(["--ignored", "--exact", "tests::ipv6_host_probe_helper"])
            .env("HTTPJAIL_TEST_HOST_IPV6", &address)
            .env("HTTPJAIL_TEST_GUEST_IFACE", format!("vn_{id}"))
            .env("HTTPJAIL_TEST_HOST_PORT", port.to_string())
            .env("HTTPJAIL_TEST_ALLOW_IPV6", "1")
            .output()
            .unwrap();
        let _ = child.wait();
        let stdout = String::from_utf8_lossy(&probe.stdout);
        assert!(
            probe.status.success() && stdout.contains("1 passed"),
            "IPv6 probe did not run or failed: {stdout} {}",
            String::from_utf8_lossy(&probe.stderr)
        );
        if !control.status.success() {
            eprintln!(
                "Host IPv6 networking also blocks the control probe; only the jail table and blocked probe were verified: {}",
                String::from_utf8_lossy(&control.stderr)
            );
            return;
        }
        assert!(String::from_utf8_lossy(&control.stdout).contains("1 passed"));
    }

    /// Docker bridge traffic to the host gateway must not bypass HTTP rules.
    #[test]
    fn test_docker_cannot_reach_host_gateway_service() {
        LinuxPlatform::require_privileges();
        let listener = std::net::TcpListener::bind(("0.0.0.0", 0)).unwrap();
        listener.set_nonblocking(true).unwrap();
        let port = listener.local_addr().unwrap().port();
        let mut cmd = httpjail_cmd();
        cmd.args(["--js", "false", "--docker-run", "--", "--rm", "alpine:latest", "sh", "-c"])
            .arg(format!(
                r#"gw=$(ip route | awk '$1=="default" {{print $3; exit}}'); wget -q -T 2 -O - http://$gw:{port}/ >/dev/null 2>&1 && echo REACHED || echo BLOCKED"#
            ));
        let output = cmd.output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("BLOCKED"),
            "Docker container reached a host gateway service"
        );
        assert!(
            listener.accept().is_err(),
            "Host listener received a Docker request"
        );
    }

    /// Test Docker container execution with --docker-run
    #[test]
    fn test_docker_run_basic() {
        LinuxPlatform::require_privileges();

        // Check if Docker is available
        let docker_check = std::process::Command::new("docker")
            .arg("--version")
            .output();

        if docker_check.is_err() || !docker_check.unwrap().status.success() {
            eprintln!("Skipping Docker test: Docker not available");
            return;
        }

        // Run a simple Docker container with httpjail
        let mut cmd = httpjail_cmd();
        cmd.arg("--js")
            .arg("true") // Allow all traffic
            .arg("--docker-run")
            .arg("--")
            .arg("--rm") // Remove container after exit
            .arg("alpine:latest")
            .arg("echo")
            .arg("Hello from Docker");

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

        eprintln!("[Docker test] stdout: {}", stdout);
        if !stderr.is_empty() {
            eprintln!("[Docker test] stderr: {}", stderr);
        }

        assert!(
            output.status.success(),
            "Docker container should run successfully. Exit code: {:?}",
            output.status.code()
        );

        assert!(
            stdout.contains("Hello from Docker"),
            "Expected output not found. stdout: {}",
            stdout
        );
    }

    /// Test Docker container with network restrictions
    #[test]
    fn test_docker_run_with_network_restrictions() {
        LinuxPlatform::require_privileges();

        // Check if Docker is available
        let docker_check = std::process::Command::new("docker")
            .arg("--version")
            .output();

        if docker_check.is_err() || !docker_check.unwrap().status.success() {
            eprintln!("Skipping Docker test: Docker not available");
            return;
        }

        // Try to access a blocked domain from within Docker container
        let mut cmd = httpjail_cmd();
        cmd.arg("--js")
            .arg("host === 'example.com'") // Only allow example.com
            .arg("--docker-run")
            .arg("--")
            .arg("--rm")
            .arg("alpine:latest")
            .arg("sh")
            .arg("-c")
            .arg("wget -q -O- --timeout=2 https://httpbingo.org/get 2>&1 || echo 'BLOCKED'");

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

        eprintln!("[Docker network restriction test] stdout: {}", stdout);
        if !stderr.is_empty() {
            eprintln!("[Docker network restriction test] stderr: {}", stderr);
        }

        assert!(
            stdout.contains("BLOCKED") || stderr.contains("403"),
            "Network request should be blocked. stdout: {}, stderr: {}",
            stdout,
            stderr
        );
    }

    /// Test Docker container with HTTPS/TLS interception
    #[test]
    fn test_docker_run_with_tls() {
        LinuxPlatform::require_privileges();

        // Check if Docker is available
        let docker_check = std::process::Command::new("docker")
            .arg("--version")
            .output();

        if docker_check.is_err() || !docker_check.unwrap().status.success() {
            eprintln!("Skipping Docker test: Docker not available");
            return;
        }

        // Test HTTPS access to ifconfig.me
        let mut cmd = httpjail_cmd();
        cmd.arg("--js")
            .arg("true") // Allow all traffic
            .arg("--docker-run")
            .arg("--")
            .arg("--rm")
            .arg("alpine:latest")
            .arg("sh")
            .arg("-c")
            .arg("wget -q -O- --timeout=5 https://ifconfig.me/ip 2>&1 | head -1");

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

        eprintln!("[Docker TLS test] stdout: {}", stdout);
        if !stderr.is_empty() {
            eprintln!("[Docker TLS test] stderr: {}", stderr);
        }

        // Should get an IP address back (the Docker container's external IP)
        assert!(
            output.status.success(),
            "HTTPS request should succeed. Exit code: {:?}",
            output.status.code()
        );

        // Basic check that we got an IP-like response
        let response = stdout.trim();
        assert!(
            !response.is_empty() && response.chars().any(|c| c == '.' || c.is_numeric()),
            "Should receive IP address from ifconfig.me, got: {}",
            response
        );
    }

    /// Test Docker container with HTTPS/TLS blocking
    #[test]
    fn test_docker_run_with_tls_blocked() {
        LinuxPlatform::require_privileges();

        // Check if Docker is available
        let docker_check = std::process::Command::new("docker")
            .arg("--version")
            .output();

        if docker_check.is_err() || !docker_check.unwrap().status.success() {
            eprintln!("Skipping Docker test: Docker not available");
            return;
        }

        // Test HTTPS blocking
        let mut cmd = httpjail_cmd();
        cmd.arg("--js")
            .arg("false") // Block all traffic
            .arg("--docker-run")
            .arg("--")
            .arg("--rm")
            .arg("alpine:latest")
            .arg("sh")
            .arg("-c")
            .arg("wget -q -O- --timeout=3 https://ifconfig.me/ip 2>&1 || echo 'BLOCKED'");

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

        eprintln!("[Docker TLS blocked test] stdout: {}", stdout);
        if !stderr.is_empty() {
            eprintln!("[Docker TLS blocked test] stderr: {}", stderr);
        }

        assert!(
            stdout.contains("BLOCKED") || stderr.contains("403") || stderr.contains("certificate"),
            "HTTPS request should be blocked. stdout: {}, stderr: {}",
            stdout,
            stderr
        );
    }
}