harn-vm 0.10.132

Async bytecode virtual machine for the Harn programming language
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
//! Tests for the linux sandbox backend, split out of `linux.rs` to keep
//! that file under the source-length ratchet. Same module path as before
//! (`super::*` still resolves to `linux.rs`), so nothing about scope moved.

use super::*;
use crate::stdlib::sandbox::{effective_fallback, handler_sandbox_test_guard};

const WRITE_BITS: u64 = LANDLOCK_ACCESS_FS_WRITE_FILE
    | LANDLOCK_ACCESS_FS_REMOVE_DIR
    | LANDLOCK_ACCESS_FS_REMOVE_FILE
    | LANDLOCK_ACCESS_FS_MAKE_CHAR
    | LANDLOCK_ACCESS_FS_MAKE_DIR
    | LANDLOCK_ACCESS_FS_MAKE_REG
    | LANDLOCK_ACCESS_FS_MAKE_SOCK
    | LANDLOCK_ACCESS_FS_MAKE_FIFO
    | LANDLOCK_ACCESS_FS_MAKE_BLOCK
    | LANDLOCK_ACCESS_FS_MAKE_SYM
    | LANDLOCK_ACCESS_FS_REFER
    | LANDLOCK_ACCESS_FS_TRUNCATE;

/// Declares that this host is expected to enforce Landlock, so a live-boundary
/// test that cannot exercise the boundary must fail rather than skip.
///
/// CI sets this on the runner class that has Landlock. Everywhere else the
/// tests skip and say why, because a missing kernel feature is not a product
/// defect and reporting it as one wastes the reader's time on a Landlock hunt
/// in a kernel that has none.
const REQUIRE_LIVE_LANDLOCK_ENV: &str = "HARN_REQUIRE_LANDLOCK_TESTS";

/// Whether a live Landlock boundary will actually be applied on this host.
///
/// Two different absences, kept apart because they are acted on differently:
/// the kernel has no Landlock at all, or it has it and the fallback selector
/// turned enforcement off for this thread. Both mean the same thing to a
/// negative control -- nothing was confined -- and neither is a product defect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LiveLandlock {
    Enforcing,
    AbsentOnHost,
    DisabledBySelector,
}

impl LiveLandlock {
    fn probe() -> Self {
        if landlock_abi_version() == 0 {
            return Self::AbsentOnHost;
        }
        // A worktree-profile run consults the selector, and `off` produces no
        // ruleset even where the kernel supports one.
        if matches!(
            effective_fallback(SandboxProfile::Worktree),
            SandboxFallback::Off
        ) {
            return Self::DisabledBySelector;
        }
        Self::Enforcing
    }

    fn reason(self) -> &'static str {
        match self {
            Self::Enforcing => "Landlock is enforcing",
            Self::AbsentOnHost => {
                "Landlock unavailable on this host, sandbox boundary not exercised"
            }
            Self::DisabledBySelector => {
                "Landlock disabled by the fallback selector, sandbox boundary not exercised"
            }
        }
    }
}

/// The active security-module list, for a skip message that names the class.
///
/// A skip that only says "no Landlock" leaves the reader unable to tell which
/// runner class they are looking at. The kernel publishes the answer.
fn active_lsm_list() -> String {
    std::fs::read_to_string("/sys/kernel/security/lsm")
        .map(|text| text.trim().to_string())
        .unwrap_or_else(|error| format!("<unreadable: {error}>"))
}

/// What a live-Landlock test must do, given what the host can actually enforce.
#[derive(Debug, Clone, PartialEq, Eq)]
enum LandlockGate {
    Proceed,
    Skip(String),
    Fail(String),
}

/// Whether the environment declares that this host must enforce Landlock.
///
/// Read from the real process environment on purpose. The shared test env seam
/// is per-thread and structurally hides the process environment under
/// `cfg(test)`, which is right for selectors a test injects and wrong for a
/// declaration the CI job makes about its own runner.
fn live_landlock_required() -> bool {
    std::env::var(REQUIRE_LIVE_LANDLOCK_ENV)
        .map(|value| {
            let value = value.trim().to_ascii_lowercase();
            !matches!(value.as_str(), "" | "0" | "false" | "off" | "no")
        })
        .unwrap_or(false)
}

/// The gate's whole decision, as a pure function of what was measured.
///
/// Separated from the probe so the two directions can be asserted without
/// touching a kernel or a process environment.
fn landlock_gate(state: LiveLandlock, required: bool, test: &str, lsm: &str) -> LandlockGate {
    if state == LiveLandlock::Enforcing {
        return LandlockGate::Proceed;
    }
    if required {
        return LandlockGate::Fail(format!(
            "[{test}] {}; {REQUIRE_LIVE_LANDLOCK_ENV} declares this host must enforce it. active security modules: {lsm}",
            state.reason()
        ));
    }
    LandlockGate::Skip(format!(
        "[{test}] SKIPPED: {}. active security modules: {lsm}",
        state.reason()
    ))
}

/// The one gate every live-Landlock test opens with.
///
/// Returns false when the caller must return early. Panics with the named
/// reason when the environment declares enforcement required, so a runner class
/// that is supposed to confine cannot quietly stop confining -- which is the
/// vacuous pass this replaces: the positive half of a boundary test succeeds
/// identically whether the boundary permits the write or was never applied, so
/// only the negative half notices, and it reported the absence as a product
/// defect (harn#8215).
#[must_use]
fn live_landlock_available(test: &str) -> bool {
    let lsm = active_lsm_list();
    match landlock_gate(LiveLandlock::probe(), live_landlock_required(), test, &lsm) {
        LandlockGate::Proceed => {
            // Printed on the PROCEEDING path too, not only on a skip. The
            // kernel can answer the ABI query and still not apply an effective
            // ruleset -- a container that permits the version probe and blocks
            // the rest reads as enforcing here, the boundary assertion fails,
            // and the report looks like a product defect again. One line per
            // run makes that host state visible in the log whether the test
            // passes, skips, or reds.
            eprintln!(
                "[{test}] Landlock ABI {} reported enforcing. active security modules: {lsm}",
                landlock_abi_version()
            );
            true
        }
        LandlockGate::Skip(reason) => {
            eprintln!("{reason}");
            false
        }
        LandlockGate::Fail(reason) => panic!("{reason}"),
    }
}

fn linux_policy_with_workspace_ops(ops: &[&str]) -> CapabilityPolicy {
    CapabilityPolicy {
        tools: Vec::new(),
        capabilities: std::collections::BTreeMap::from([(
            "workspace".to_string(),
            ops.iter().map(|op| op.to_string()).collect(),
        )]),
        workspace_roots: vec!["/ws".to_string()],
        read_only_roots: Vec::new(),
        side_effect_level: Some("read_only".to_string()),
        recursion_limit: None,
        tool_arg_constraints: Vec::new(),
        tool_annotations: std::collections::BTreeMap::new(),
        sandbox_profile: SandboxProfile::Worktree,
        process_sandbox: Default::default(),
        process_network_proxy: None,
    }
}

#[test]
fn managed_proxy_fails_closed_without_proxy_only_network_namespace() {
    let mut policy = linux_policy_with_workspace_ops(&["read_text"]);
    policy.side_effect_level = Some("network".to_string());
    policy.process_network_proxy = Some(crate::orchestration::ProcessNetworkProxy {
        http_port: 3128,
        socks_port: 1080,
    });

    let error = match profile_setup("ignored", &policy, SandboxProfile::Worktree) {
        Ok(_) => panic!("managed proxy must not widen to unrestricted Linux sockets"),
        Err(error) => error,
    };
    assert!(
        error
            .to_string()
            .contains("requires a proxy-only Linux network namespace"),
        "{error}"
    );
}

#[test]
fn no_network_excludes_addressable_sockets_but_allows_local_socketpair() {
    // At a sub-network ceiling, the egress-capable socket syscalls are
    // not allowlisted, but `socketpair` (anonymous, unaddressable local IPC) stays
    // allowed so Cargo's socketpair-backed jobserver can spawn rustc.
    let policy = linux_policy_with_workspace_ops(&["read_text"]);
    assert_eq!(
        policy.side_effect_level.as_deref(),
        Some("read_only"),
        "fixture must be below the network ceiling",
    );
    let allowed = allowed_syscalls(&policy);

    assert!(
        !allowed.contains(&libc::SYS_socket),
        "addressable socket() must not be allowlisted without network",
    );
    assert!(
        !allowed.contains(&libc::SYS_connect),
        "connect() must not be allowlisted without network",
    );
    assert!(
        allowed.contains(&libc::SYS_socketpair),
        "socketpair() (local IPC) must be allowlisted — Cargo's jobserver needs it",
    );
    // The socketpair-backed jobserver also drives its pair with the
    // send/recv family. They open no egress while socket/connect/bind
    // stay absent from the allowlist.
    for call in [
        libc::SYS_recvfrom,
        libc::SYS_recvmsg,
        libc::SYS_sendmsg,
        libc::SYS_sendto,
    ] {
        assert!(
                allowed.contains(&call),
                "send/recv syscall {call} must be allowlisted — local socketpair IPC (Cargo jobserver) needs it",
            );
    }
    // The egress-capable openers stay absent: no addressable socket can be
    // created or routed, so the inherited-fd send/recv calls cannot reach the network.
    for call in [
        libc::SYS_socket,
        libc::SYS_connect,
        libc::SYS_bind,
        libc::SYS_listen,
        libc::SYS_accept,
        libc::SYS_accept4,
    ] {
        assert!(
            !allowed.contains(&call),
            "egress opener {call} must stay absent without network",
        );
    }
}

#[test]
fn network_ceiling_allows_all_socket_syscalls() {
    // When network side effects are permitted, none of the socket family
    // is removed from the allowlist (socketpair included).
    let mut policy = linux_policy_with_workspace_ops(&["read_text"]);
    policy.side_effect_level = Some("network".to_string());
    let allowed = allowed_syscalls(&policy);
    for call in [
        libc::SYS_socket,
        libc::SYS_socketpair,
        libc::SYS_connect,
        libc::SYS_bind,
    ] {
        assert!(
            allowed.contains(&call),
            "network ceiling must allowlist socket-family syscall {call}",
        );
    }
}

#[test]
fn filesystem_metadata_syscalls_include_fchmodat2() {
    let policy = linux_policy_with_workspace_ops(&["read_text", "write_text"]);
    let allowed = allowed_syscalls(&policy);

    assert!(
        allowed.contains(&SYS_FCHMODAT2),
        "modern tools use fchmodat2 to preserve symlink metadata",
    );
}

#[test]
fn sandboxed_tar_extracts_symlinks_without_widening_the_write_root() {
    // The negative half below is the only assertion that can tell an enforced
    // boundary from no boundary at all, so it must not run where nothing will
    // be confined (harn#8215).
    if !live_landlock_available("sandboxed-tar") {
        return;
    }
    let workspace = tempfile::tempdir().expect("workspace");
    let source = workspace.path().join("archive-source");
    let extract = workspace.path().join("extract");
    std::fs::create_dir(&source).expect("archive source");
    std::fs::create_dir(&extract).expect("extract root");
    std::fs::write(source.join("harn"), "fixture binary").expect("fixture binary");
    std::os::unix::fs::symlink("harn", source.join("harn-dap")).expect("fixture symlink");
    let archive = workspace.path().join("harn.tar.gz");
    let create = Command::new("tar")
        .args(["-czf"])
        .arg(&archive)
        .arg("-C")
        .arg(&source)
        .arg(".")
        .output()
        .expect("create archive");
    assert!(
        create.status.success(),
        "create archive: {}",
        String::from_utf8_lossy(&create.stderr),
    );

    let mut policy = linux_policy_with_workspace_ops(&["read_text", "write_text"]);
    policy.workspace_roots = vec![workspace.path().display().to_string()];
    policy.side_effect_level = Some("process_exec".to_string());
    let run_tar = |destination: &Path| {
        let args = vec![
            "-xzf".to_string(),
            archive.display().to_string(),
            "-C".to_string(),
            destination.display().to_string(),
        ];
        let mut command = Command::new("tar");
        command.args(&args).current_dir(workspace.path());
        let preparation = Backend::prepare_std_command(
            "tar",
            &args,
            &mut command,
            &policy,
            SandboxProfile::Worktree,
        )
        .expect("prepare sandboxed tar");
        assert!(matches!(preparation, PrepareOutcome::Direct));
        command.output().expect("run sandboxed tar")
    };

    let extracted = run_tar(&extract);
    assert!(
        extracted.status.success(),
        "extract archive: {}",
        String::from_utf8_lossy(&extracted.stderr),
    );
    assert_eq!(
        std::fs::read_link(extract.join("harn-dap")).expect("extracted symlink"),
        Path::new("harn"),
    );

    // The refusal below is produced by Landlock and by nothing else. A kernel
    // without it reports filesystem isolation as disabled and cannot refuse
    // the write, so asserting there blames the backend for the runner. Skip
    // the boundary half the same way the other live-Landlock cases do; the
    // extraction assertions above still ran.
    if landlock_abi_version() == 0 {
        eprintln!("[fchmodat2-boundary] SKIPPED: no Landlock on this kernel");
        return;
    }
    let outside = tempfile::tempdir().expect("outside workspace");
    let refused = run_tar(outside.path());
    assert!(
        !refused.status.success(),
        "fchmodat2 must not weaken the Landlock write boundary",
    );
    assert!(
        !outside.path().join("harn").exists(),
        "an out-of-scope extraction must write nothing",
    );
}

#[test]
fn network_ceiling_grants_exact_name_service_files_without_opening_run() {
    let mut policy = linux_policy_with_workspace_ops(&["read_text"]);
    assert!(network_name_service_read_roots(&policy).is_empty());

    policy.side_effect_level = Some("network".to_string());
    let roots = network_name_service_read_roots(&policy);
    assert_eq!(
        roots,
        [
            "/etc/resolv.conf",
            "/etc/hosts",
            "/etc/nsswitch.conf",
            "/etc/gai.conf",
            "/etc/host.conf",
        ]
        .into_iter()
        .map(PathBuf::from)
        .collect::<Vec<_>>(),
    );
    assert!(
        roots.iter().all(|root| !root.starts_with("/run")),
        "the repair must grant canonical resolver files, never the mutable /run tree",
    );
}

#[test]
fn process_network_ceiling_controls_real_child_socket() {
    let workspace = tempfile::tempdir().expect("workspace");
    let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("loopback listener");
    let address = listener.local_addr().expect("listener address");
    let args = vec![
        "-c".to_string(),
        format!("exec 3<>/dev/tcp/127.0.0.1/{}", address.port()),
    ];

    let run_probe = |policy: &CapabilityPolicy| {
        let mut command = Command::new("/bin/bash");
        command.args(&args).current_dir(workspace.path());
        let preparation = Backend::prepare_std_command(
            "/bin/bash",
            &args,
            &mut command,
            policy,
            SandboxProfile::Worktree,
        )
        .expect("prepare sandboxed child");
        assert!(matches!(preparation, PrepareOutcome::Direct));
        command.output().expect("run sandboxed child")
    };

    let mut denied = linux_policy_with_workspace_ops(&["read_text"]);
    denied.workspace_roots = vec![workspace.path().display().to_string()];
    denied.side_effect_level = Some("process_exec".to_string());
    let denied_output = run_probe(&denied);
    assert!(
        !denied_output.status.success(),
        "the default process-exec ceiling must deny an addressable child socket",
    );

    let mut allowed = denied;
    allowed.side_effect_level = Some("network".to_string());
    let allowed_output = run_probe(&allowed);
    assert!(
        allowed_output.status.success(),
        "the network ceiling must permit the child loopback socket: {}",
        String::from_utf8_lossy(&allowed_output.stderr),
    );
    listener
        .set_nonblocking(true)
        .expect("set listener nonblocking");
    listener
        .accept()
        .expect("the listener must observe the allowed child connection");
}

#[test]
fn seccomp_filter_is_default_deny_allowlist() {
    let filter = compile_seccomp_program(&[libc::SYS_read, libc::SYS_write])
        .expect("compile the probe filter");
    assert_eq!(
        filter.last().map(|entry| entry.k),
        Some(libc::SECCOMP_RET_ERRNO | libc::EPERM as u32),
        "seccomp fallthrough must deny unknown syscalls",
    );
    assert!(
        filter
            .iter()
            .any(|entry| entry.k == libc::SECCOMP_RET_ALLOW),
        "allowlisted syscalls must jump to an allow action",
    );
}

/// The filter must reject foreign ABIs before it ever looks at a syscall
/// number. `msync` stands in for the general hazard: we allow number 26,
/// and i386 number 26 is `ptrace` — which
/// `allowlist_excludes_process_introspection_and_io_uring` asserts we
/// withhold. Without the arch gate that exclusion is reachable anyway,
/// through `int $0x80`.
#[test]
fn seccomp_filter_validates_architecture_before_syscall_number() {
    let filter = compile_seccomp_program(&[libc::SYS_msync]).expect("compile the probe filter");

    let arch_load = filter.first().expect("filter must not be empty");
    assert_eq!(
        arch_load.code,
        (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16,
        "the first instruction must be an absolute word load",
    );
    assert_eq!(
        arch_load.k, 4,
        "the first load must read seccomp_data.arch (offset 4), not .nr (offset 0)",
    );

    assert_eq!(
        filter.get(2).map(|entry| entry.k),
        Some(libc::SECCOMP_RET_KILL_PROCESS),
        "an architecture mismatch must kill the process, never return EPERM: \
             EPERM would let a caller probe the whole syscall space for free",
    );

    // Only after the arch gate may the program consult the syscall number.
    assert_eq!(
        filter.get(3).map(|entry| (entry.code, entry.k)),
        Some(((libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16, 0)),
        "the syscall number load must follow the architecture check",
    );
}

#[test]
fn allowlist_excludes_process_introspection_and_io_uring() {
    let policy = linux_policy_with_workspace_ops(&["read_text", "write_text"]);
    let allowed = allowed_syscalls(&policy);
    for call in [
        libc::SYS_ptrace,
        libc::SYS_process_vm_readv,
        libc::SYS_process_vm_writev,
        libc::SYS_io_uring_setup,
        libc::SYS_io_uring_enter,
        libc::SYS_io_uring_register,
    ] {
        assert!(
            !allowed.contains(&call),
            "dangerous syscall {call} must stay outside the seccomp allowlist",
        );
    }
}

#[test]
fn read_only_access_grants_read_and_execute_but_never_write() {
    let access = read_only_access();
    assert_ne!(access & LANDLOCK_ACCESS_FS_READ_FILE, 0, "read file");
    assert_ne!(access & LANDLOCK_ACCESS_FS_READ_DIR, 0, "read dir");
    assert_ne!(access & LANDLOCK_ACCESS_FS_EXECUTE, 0, "execute");
    assert_eq!(
        access & WRITE_BITS,
        0,
        "read-only access must not carry any write/create/remove right",
    );
}

#[test]
fn read_only_access_is_independent_of_workspace_write_capability() {
    // Even when the policy otherwise allows workspace writes, the
    // read-only access bits are unchanged: a read-only root gets
    // read+execute only.
    let writable = linux_policy_with_workspace_ops(&["read_text", "write_text", "delete"]);
    assert_ne!(
        workspace_access(&writable) & LANDLOCK_ACCESS_FS_WRITE_FILE,
        0,
        "writable workspace root should carry write",
    );
    assert_eq!(
        read_only_access() & WRITE_BITS,
        0,
        "read-only roots stay unwritable regardless of workspace write capability",
    );
}

#[test]
fn package_manager_config_roots_are_read_only() {
    let temp_home = tempfile::tempdir().expect("temp home");
    std::fs::write(
        temp_home.path().join(".npmrc"),
        "registry=https://registry.example\n",
    )
    .expect("write npmrc");
    let roots = super::super::package_manager_config_read_roots_for_home(temp_home.path());

    assert!(
        roots.iter().any(|path| path.ends_with(".npmrc")),
        "npmrc should be part of the package-manager preset"
    );
    assert!(
        roots
            .iter()
            .any(|path| path.ends_with(".cargo/config.toml")),
        "cargo config should be part of the package-manager preset"
    );
    assert!(
        roots.iter().all(|path| path.starts_with(temp_home.path())),
        "package-manager roots must stay under HOME"
    );
    assert_eq!(
        read_only_access() & WRITE_BITS,
        0,
        "package-manager Landlock rules use read-only access bits"
    );
}

#[test]
fn developer_toolchain_roots_are_read_only() {
    let temp_home = tempfile::tempdir().expect("temp home");
    let roots = super::super::developer_toolchain_read_roots_for_home(temp_home.path());

    assert!(
        roots.iter().any(|path| path.ends_with(".local/share/uv")),
        "uv runtimes should be part of the developer-toolchain preset"
    );
    assert!(
        roots.iter().any(|path| path.ends_with(".rustup")),
        "rustup should be part of the developer-toolchain preset"
    );
    assert!(
        roots.iter().all(|path| path.starts_with(temp_home.path())),
        "developer-toolchain roots must stay under HOME"
    );
    assert_eq!(
        read_only_access() & WRITE_BITS,
        0,
        "developer-toolchain Landlock rules use read-only access bits"
    );
}

#[test]
fn developer_toolchains_admit_linux_vendor_installations() {
    let enabled = CapabilityPolicy {
        process_sandbox: crate::orchestration::ProcessSandboxPolicy {
            presets: Some(vec![ProcessSandboxPreset::DeveloperToolchains]),
            ..Default::default()
        },
        ..Default::default()
    };
    assert_eq!(
        developer_toolchain_system_read_roots(&enabled),
        vec![PathBuf::from("/opt")]
    );

    let disabled = CapabilityPolicy {
        process_sandbox: crate::orchestration::ProcessSandboxPolicy {
            presets: Some(Vec::new()),
            ..Default::default()
        },
        ..Default::default()
    };
    assert!(developer_toolchain_system_read_roots(&disabled).is_empty());
}

#[test]
fn standard_device_rules_allow_common_device_files_only() {
    let rules = standard_device_rules();
    assert_eq!(rules.len(), 4);
    assert!(rules.iter().any(
        |(path, access)| path.as_path() == std::path::Path::new("/dev/null")
            && access & LANDLOCK_ACCESS_FS_READ_FILE != 0
            && access & LANDLOCK_ACCESS_FS_WRITE_FILE != 0
            && access & LANDLOCK_ACCESS_FS_IOCTL_DEV == 0
    ));
    for device in ["/dev/zero", "/dev/random", "/dev/urandom"] {
        let Some((_, access)) = rules
            .iter()
            .find(|(path, _)| path.as_path() == std::path::Path::new(device))
        else {
            panic!("missing standard device rule for {device}");
        };
        assert_ne!(
            *access & LANDLOCK_ACCESS_FS_READ_FILE,
            0,
            "{device} should be readable"
        );
        assert_eq!(
            *access & LANDLOCK_ACCESS_FS_WRITE_FILE,
            0,
            "{device} must not be writable"
        );
        assert_eq!(
            *access & LANDLOCK_ACCESS_FS_IOCTL_DEV,
            0,
            "{device} must not receive device ioctl access"
        );
    }
}

#[test]
fn directory_only_access_excludes_file_applicable_rights() {
    // The file-applicable rights must never be classified as
    // directory-only, otherwise `push_rule` would strip a read/exec
    // grant from a regular-file rule and silently under-scope it.
    for right in [
        LANDLOCK_ACCESS_FS_READ_FILE,
        LANDLOCK_ACCESS_FS_WRITE_FILE,
        LANDLOCK_ACCESS_FS_EXECUTE,
        LANDLOCK_ACCESS_FS_TRUNCATE,
        LANDLOCK_ACCESS_FS_IOCTL_DEV,
    ] {
        assert_eq!(
            DIRECTORY_ONLY_ACCESS_FS & right,
            0,
            "file-applicable right {right:#x} must not be directory-only",
        );
    }
    // READ_DIR is the right that triggers the EINVAL on regular files.
    assert_ne!(
        DIRECTORY_ONLY_ACCESS_FS & LANDLOCK_ACCESS_FS_READ_DIR,
        0,
        "READ_DIR must be classified as directory-only",
    );
}

#[test]
fn read_only_access_on_a_regular_file_drops_directory_only_bits() {
    // A read-only preset root that resolves to a *file* (e.g.
    // `~/.gitconfig`) must end up with only file-applicable rights;
    // the `READ_DIR` bit in `read_only_access()` would otherwise make
    // `landlock_add_rule` return EINVAL.
    let masked = read_only_access() & !DIRECTORY_ONLY_ACCESS_FS;
    assert_eq!(
        masked & LANDLOCK_ACCESS_FS_READ_DIR,
        0,
        "READ_DIR must be stripped for non-directory rules",
    );
    assert_ne!(
        masked & LANDLOCK_ACCESS_FS_READ_FILE,
        0,
        "READ_FILE must survive for non-directory rules",
    );
    assert_ne!(
        masked & LANDLOCK_ACCESS_FS_EXECUTE,
        0,
        "EXECUTE must survive for non-directory rules",
    );
}

#[test]
fn landlock_handled_access_tracks_device_ioctl_abi() {
    assert_eq!(
        landlock_handled_access(4) & LANDLOCK_ACCESS_FS_IOCTL_DEV,
        0,
        "ABI 4 kernels do not support device ioctl mediation",
    );
    assert_ne!(
        landlock_handled_access(5) & LANDLOCK_ACCESS_FS_IOCTL_DEV,
        0,
        "ABI 5+ kernels should explicitly mediate device ioctls",
    );
}

#[test]
fn proc_runtime_reads_require_restricted_yama_scope() {
    for safe in ["1", "2\n", "3"] {
        assert!(yama_scope_contains_process_reads(safe), "scope {safe}");
    }
    for unsafe_or_unknown in ["0", "", "disabled", "256"] {
        assert!(
            !yama_scope_contains_process_reads(unsafe_or_unknown),
            "scope {unsafe_or_unknown} must not grant procfs reads",
        );
    }
}

// ---- complement enumeration: how a denial is expressed without a deny rule

/// Landlock is allow-only. A denial is therefore enforced by NOT granting,
/// which means a grant containing a denied subtree must be replaced by the
/// siblings that do not lead to it. These assert the substitution, because
/// on this backend there is no deny rule to look for in a rendered profile:
/// the ABSENCE of a grant IS the enforcement, and absence is exactly what a
/// careless test reads as success.
fn tree(root: &std::path::Path, names: &[&str]) {
    for name in names {
        std::fs::create_dir_all(root.join(name)).expect("tree");
    }
}

/// Measurement, not assertion: prints what the product-default denylist
/// actually costs on THIS host, so the cap is chosen from numbers instead
/// of intuition. Run with `--nocapture`.
///
/// It asserts only that the expansion succeeded and stayed under the cap,
/// because the point is the reported figure, and a machine-specific count
/// is not something to freeze into an assertion.
#[test]
fn report_default_denylist_expansion_cost() {
    let Some(home) = crate::user_dirs::home_dir() else {
        eprintln!("[landlock-cost] no home dir on this host; nothing to measure");
        return;
    };
    let denied: Vec<PathBuf> = crate::orchestration::default_read_deny_home_paths()
        .iter()
        .map(|relative| home.join(relative))
        .collect();
    let home = home.canonicalize().unwrap_or(home);

    // No wall-clock read here on purpose: the cap is a function of the RULE
    // COUNT, not of how long the walk took, and the test harness already
    // reports per-test duration. Reading `Instant` would put a host clock
    // read in a production file for a test-only number.
    let granted = expand_around_denied(&home, &denied).expect("expand around home");

    let entries = std::fs::read_dir(&home).map(|dir| dir.count()).unwrap_or(0);
    eprintln!(
        "[landlock-cost] home={} home_entries={} denied={} expanded_rules={} cap={}",
        home.display(),
        entries,
        denied.len(),
        granted.len(),
        MAX_DENY_EXPANSION_RULES,
    );
    assert!(
        granted.len() <= MAX_DENY_EXPANSION_RULES,
        "the product default must not trip the cap on a real home: {} rules",
        granted.len()
    );
    // Non-null control. A cap check against a nearly empty directory passes for
    // the wrong reason, so refuse to report a measurement that cannot have come
    // from a real home. This is the difference between a measured number and a
    // measured nothing, and it already fired once: a sibling test's `HOME`
    // window made this read `/tmp/.tmpLZc8Wo` with 3 entries and 3 rules, which
    // printed and passed while measuring nothing.
    assert!(
        entries >= 10,
        "[landlock-cost] measured '{}' with only {entries} entries, which is not a real home; \
         the cap check would pass vacuously. Something rewrote HOME under this test.",
        home.display()
    );
}

#[test]
fn a_root_with_no_denial_inside_it_is_granted_whole() {
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    tree(&root, &["a", "b"]);
    // Genuinely outside `root`. A path like `root.join("elsewhere")` would
    // be INSIDE it and would exercise the subtraction instead, which is the
    // opposite of what this test claims to check.
    let unrelated = tempfile::TempDir::new().expect("unrelated");
    let unrelated = unrelated.path().canonicalize().expect("canonical");

    let granted = expand_around_denied(&root, &[unrelated]).expect("expand");

    assert_eq!(
        granted,
        vec![root],
        "a denial that is not inside the root must cost nothing and leave it intact"
    );
}

#[test]
fn a_denied_child_is_replaced_by_its_siblings_and_never_granted() {
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    tree(&root, &["projects", "documents", ".ssh"]);
    let denied = root.join(".ssh");

    let granted = expand_around_denied(&root, std::slice::from_ref(&denied)).expect("expand");

    assert!(
        !granted.contains(&root),
        "the root itself must NOT be granted; granting it would include the denied \
             subtree, which is the whole failure this function exists to prevent: {granted:?}"
    );
    assert!(
        !granted.iter().any(|path| path.starts_with(&denied)),
        "no grant may lead into the denied subtree: {granted:?}"
    );
    assert!(
        granted.contains(&root.join("projects")) && granted.contains(&root.join("documents")),
        "the siblings must still be reachable, or the subtraction has silently removed \
             access the policy granted: {granted:?}"
    );
}

#[test]
fn a_nested_denial_keeps_siblings_at_every_level() {
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    tree(&root, &["keep-me", ".config/gh", ".config/keep-this"]);
    let denied = root.join(".config/gh");

    let granted = expand_around_denied(&root, std::slice::from_ref(&denied)).expect("expand");

    assert!(
        granted.contains(&root.join("keep-me")),
        "a sibling at the top level must survive: {granted:?}"
    );
    assert!(
        granted.contains(&root.join(".config/keep-this")),
        "a sibling INSIDE the denied path's parent must survive, which is what makes this \
             a subtraction rather than denying the whole parent: {granted:?}"
    );
    assert!(
        !granted.contains(&denied) && !granted.contains(&root.join(".config")),
        "neither the denial nor any ancestor that contains it may be granted: {granted:?}"
    );
}

#[test]
fn a_root_that_is_itself_denied_grants_nothing() {
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    tree(&root, &["inside"]);

    let granted = expand_around_denied(&root, std::slice::from_ref(&root)).expect("expand");

    assert!(
        granted.is_empty(),
        "a root that IS the denial must grant nothing at all: {granted:?}"
    );
}

/// An unreadable ancestor must not be GRANTED, which is the only unsafe
/// outcome here. Ending the walk grants nothing beneath it, which is
/// strictly narrower than continuing.
///
/// This used to refuse the spawn. That was over-strict in the one direction
/// that matters operationally: under the hardened conformance profile
/// `$HOME` is `/root`, unreadable to the runtime, so every spawn failed
/// while no authority was gained by failing.
#[test]
fn an_unreadable_ancestor_grants_nothing_beneath_it_and_never_itself() {
    use std::os::unix::fs::PermissionsExt;
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    tree(&root, &["locked/.ssh", "visible/keep"]);
    let locked = root.join("locked");
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).expect("lock dir");

    let result = expand_around_denied(&root, &[locked.join(".ssh")]);

    // Restore before asserting so a failure cannot leave an unremovable dir.
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).expect("unlock");
    let granted = result.expect("an unreadable ancestor must not refuse the spawn");

    assert!(
        !granted
            .iter()
            .any(|path| path == &locked || locked.starts_with(path)),
        "granting the unreadable ancestor (or anything above it) would expose the \
             subtree we could not enumerate around: {granted:?}"
    );
    // Control: expansion still happened. Without this the assertion above
    // would also pass on an empty result produced by giving up entirely,
    // which would be a silent loss of every legitimate grant.
    assert!(
        granted.contains(&root.join("visible")),
        "a sibling outside the unreadable subtree must still be granted: {granted:?}"
    );
}

/// The live Landlock falsifier.
///
/// Every other test here checks the SUBSTITUTION — which paths we decided to
/// grant. On this backend that is not the same claim as "the denied file is
/// refused", because the enforcement is the absence of a grant, and absence
/// is exactly what a careless test reads as success. So this spawns a real
/// confined child and reads two files that differ only in whether a denial
/// covers them.
///
/// Structure mirrors the macOS live test:
/// * control: the sibling inside the same granted root is readable, so a
///   refusal cannot be explained by an absent grant;
/// * claim: the denied file is refused;
/// * revert: with `read_deny_roots` cleared the same file is readable,
///   which is what proves the refusal was the denylist.
#[test]
fn a_live_landlock_child_is_refused_a_denied_file_and_allowed_its_sibling() {
    if !live_landlock_available("landlock-live") {
        return;
    }
    let home = tempfile::TempDir::new().expect("temp home");
    let home_path = home.path().canonicalize().expect("canonical home");

    let secrets = home_path.join("secrets");
    std::fs::create_dir_all(&secrets).expect("secrets dir");
    let denied_file = secrets.join("id_ed25519");
    std::fs::write(&denied_file, "NOT-A-REAL-KEY\n").expect("dummy key");
    let allowed_file = home_path.join("readable.txt");
    std::fs::write(&allowed_file, "READABLE\n").expect("control file");

    let read_under = |deny: &[String], target: &std::path::Path| -> std::io::Result<bool> {
        let policy = CapabilityPolicy {
            workspace_roots: vec![home_path.display().to_string()],
            sandbox_profile: SandboxProfile::Worktree,
            process_sandbox: crate::orchestration::ProcessSandboxPolicy {
                read_deny_roots: deny.to_vec(),
                ..Default::default()
            },
            ..CapabilityPolicy::default()
        };
        crate::orchestration::push_execution_policy(policy);
        let output = crate::stdlib::sandbox::command_output(
            "/bin/cat",
            &[target.display().to_string()],
            &crate::stdlib::sandbox::ProcessCommandConfig::default(),
        );
        // Pop before returning. Each arm must run under its OWN policy, and
        // a leaked push would leave the last arm's denial on the stack for
        // whatever runs next on this thread.
        crate::orchestration::pop_execution_policy();
        Ok(matches!(output, Ok(out) if out.status.success()))
    };

    let deny = vec![secrets.display().to_string()];

    // Control first: the grant works, so a later refusal is attributable.
    let control = read_under(&deny, &allowed_file).expect("control read");
    assert!(
        control,
        "the control file inside the same workspace root must be readable, or the denial \
             below proves nothing"
    );

    let denied = read_under(&deny, &denied_file).expect("denied read");
    assert!(
        !denied,
        "a denied file must be refused even though its parent root is granted; it was read"
    );

    // Revert the fix: same policy, same files, denial removed.
    let ungated = read_under(&[], &denied_file).expect("ungated read");
    assert!(
        ungated,
        "with the denial removed the same file must become readable, which is what proves \
             the refusal was the denylist and not an unrelated accident"
    );
    eprintln!("[landlock-live] denied refused, sibling readable, revert readable");
}

/// The defect the cost measurement caught on a real host: a denied path whose
/// ancestor does not exist must cost nothing, not refuse the spawn.
///
/// `~/.kube/config` is on the default denylist and `~/.kube` is absent on
/// most machines. Treating a missing directory as "cannot enumerate" made
/// `expand_around_denied` fail closed for every spawn on any such host,
/// which would have taken the eval fleet down while looking like a working
/// security feature.
#[test]
fn a_denial_under_a_missing_directory_costs_nothing() {
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    tree(&root, &["present"]);

    let granted = expand_around_denied(&root, &[root.join("absent/config")])
        .expect("a denial under a missing directory must not refuse the spawn");

    assert!(
        granted.contains(&root.join("present")),
        "the siblings must still be granted: {granted:?}"
    );
}

/// The relaxation above is bounded: only NotFound and PermissionDenied end
/// the walk. Any OTHER enumeration error still refuses the spawn, because
/// "any error means nothing to exclude" is exactly the widening this term
/// must never acquire.
///
/// A file where a directory is expected reproduces that third shape
/// (`NotADirectory`) without needing an exotic filesystem.
#[test]
fn an_unexpected_enumeration_error_still_refuses_the_spawn() {
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    std::fs::write(root.join("notadir"), b"x").expect("write file");

    let result = expand_around_denied(&root, &[root.join("notadir/inner/secret")]);

    assert!(
        result.is_err(),
        "an enumeration error that is neither missing nor forbidden must fail closed, \
             got {result:?}"
    );
}

/// An optional preset root that EXISTS but cannot be opened must be skipped,
/// not fatal.
///
/// This took down every confined command when the runtime's `$HOME` was not
/// its own: `HOME=/root` under a non-root uid makes `~/.asdf` (and friends)
/// exist, unreadable, and previously fatal. Reproduced on Linux before the fix.
#[test]
fn an_unreadable_optional_root_is_skipped_and_a_required_one_still_fails() {
    use std::os::unix::fs::PermissionsExt;
    let temp = tempfile::TempDir::new().expect("temp");
    let root = temp.path().canonicalize().expect("canonical");
    let locked = root.join("locked");
    std::fs::create_dir_all(&locked).expect("mkdir");
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).expect("lock");

    let mut profile = LandlockProfile {
        ruleset_fd: -1,
        rules: Vec::new(),
        handled_access_fs: 0,
        read_deny_roots: Vec::new(),
    };
    let optional = push_rule_exact(
        &mut profile,
        locked.clone(),
        LANDLOCK_ACCESS_FS_READ_FILE,
        true,
    );
    let required = push_rule_exact(
        &mut profile,
        locked.clone(),
        LANDLOCK_ACCESS_FS_READ_FILE,
        false,
    );

    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).expect("unlock");

    assert!(
        optional.is_ok(),
        "an unreadable OPTIONAL root must be skipped, not refuse the spawn: {optional:?}"
    );
    assert!(
        required.is_err(),
        "an unreadable REQUIRED root must still fail closed; something asked for it by name"
    );
}

/// The `/root`-under-hardened control, beside the `~/.kube` one.
///
/// Third instance of one class. Each time, a path the setup could not read
/// refused the whole spawn instead of ending that branch:
///
/// | shape | before | now |
/// |--------------------------------------|---------------|------------------|
/// | denial under a MISSING dir (`~/.kube`) | refused spawn | ends the walk    |
/// | denial under an UNLISTABLE dir (`$HOME`)| refused spawn | ends the walk    |
/// | optional root that cannot be OPENED    | refused spawn | skipped, logged  |
///
/// The live shape: a runtime whose `$HOME` is not its own (`HOME=/root` under a
/// non-root uid) has preset roots such as `~/.asdf` that exist and cannot be
/// opened. Every confined command died. This spawns a real child under exactly
/// that arrangement and requires it to run.
#[test]
fn a_confined_child_still_spawns_when_a_preset_root_exists_but_cannot_be_read() {
    use std::os::unix::fs::PermissionsExt;
    if !live_landlock_available("unreadable-root") {
        return;
    }
    let _env_lock = crate::runtime_paths::test_env_lock()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());

    let home = tempfile::TempDir::new().expect("temp home");
    let home_path = home.path().canonicalize().expect("canonical");
    // `.asdf` is a real DeveloperToolchains preset root, so this reproduces the
    // production shape rather than a synthetic one.
    let unreadable = home_path.join(".asdf");
    std::fs::create_dir_all(unreadable.join("shims")).expect("mkdir");
    std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o000)).expect("lock");

    let previous_home = std::env::var_os("HOME");
    std::env::set_var("HOME", &home_path);

    let policy = CapabilityPolicy {
        workspace_roots: vec![home_path.display().to_string()],
        sandbox_profile: SandboxProfile::Worktree,
        ..CapabilityPolicy::default()
    };
    crate::orchestration::push_execution_policy(policy);
    let output = crate::stdlib::sandbox::command_output(
        "/bin/echo",
        &["UNREADABLE-ROOT-PROBE-ALIVE".to_string()],
        &crate::stdlib::sandbox::ProcessCommandConfig::default(),
    );
    crate::orchestration::pop_execution_policy();

    std::fs::set_permissions(&unreadable, std::fs::Permissions::from_mode(0o755)).expect("unlock");
    match previous_home {
        Some(value) => std::env::set_var("HOME", value),
        None => std::env::remove_var("HOME"),
    }

    let output = output.expect(
        "an unreadable preset root must not refuse the spawn; this is the /root-under-hardened \
         control and its failure is the exact outage it exists to catch",
    );
    assert!(
        output.status.success(),
        "the confined child must run: {output:?}"
    );
    assert!(
        String::from_utf8_lossy(&output.stdout).contains("UNREADABLE-ROOT-PROBE-ALIVE"),
        "the child must actually have executed, not merely exited zero"
    );
    eprintln!("[unreadable-root] confined child ran with an unreadable preset root present");
}

/// FALSIFIER 1. With nothing enforcing and no declaration, the gate stands down
/// and says why. It must never report a missing kernel feature as a boundary
/// failure, which is what harn#8215 recorded.
#[test]
fn an_unenforced_host_skips_with_the_named_reason_when_nothing_requires_it() {
    for state in [LiveLandlock::AbsentOnHost, LiveLandlock::DisabledBySelector] {
        let decision = landlock_gate(state, false, "probe", "capability,yama");
        let LandlockGate::Skip(reason) = decision else {
            panic!("an unenforced host must skip, not {decision:?}");
        };
        assert!(
            reason.contains("sandbox boundary not exercised"),
            "the skip names what did not happen: {reason}"
        );
        assert!(
            reason.contains("capability,yama"),
            "the skip names the host's security modules so the class is identifiable: {reason}"
        );
    }
}

/// FALSIFIER 2. Same host, but the environment declares it must enforce. The
/// gate reds, and the message says which declaration was broken. This is what
/// stops a runner class silently ceasing to confine.
#[test]
fn a_host_declared_to_enforce_reds_when_it_does_not() {
    let decision = landlock_gate(LiveLandlock::AbsentOnHost, true, "probe", "capability,yama");
    let LandlockGate::Fail(reason) = decision else {
        panic!("a declared-enforcing host must fail, not {decision:?}");
    };
    assert!(
        reason.contains("Landlock unavailable on this host, sandbox boundary not exercised"),
        "the failure names the absence verbatim: {reason}"
    );
    assert!(
        reason.contains(REQUIRE_LIVE_LANDLOCK_ENV),
        "the failure names the declaration it answers to: {reason}"
    );
}

/// DIRECTION CONTROL for both. An enforcing host proceeds whatever the
/// declaration says, so the gate can never turn a real boundary test off.
#[test]
fn an_enforcing_host_always_proceeds() {
    for required in [true, false] {
        assert_eq!(
            landlock_gate(LiveLandlock::Enforcing, required, "probe", "landlock"),
            LandlockGate::Proceed,
            "an enforcing host runs the boundary test, required={required}"
        );
    }
}

/// The probe reads the real mechanism, not just the kernel.
///
/// Landlock can be present and still not applied, because the worktree profile
/// consults the fallback selector and `off` produces no ruleset. A gate keyed
/// on the kernel alone would call that host enforcing and hand the negative
/// control an unconfined child, which is the same vacuous pass by another route.
#[test]
fn the_selector_can_disable_enforcement_on_a_landlock_capable_kernel() {
    if landlock_abi_version() == 0 {
        eprintln!(
            "[selector-probe] SKIPPED: no Landlock on this kernel, so the selector cannot be \
             the deciding factor. active security modules: {}",
            active_lsm_list()
        );
        return;
    }
    let guard = handler_sandbox_test_guard();
    guard.set("off");
    assert_eq!(
        LiveLandlock::probe(),
        LiveLandlock::DisabledBySelector,
        "a disabled selector must not read as an enforcing host"
    );
    // Direction control: the default selector leaves the same kernel enforcing.
    drop(guard);
    let _restored = handler_sandbox_test_guard();
    assert_eq!(
        LiveLandlock::probe(),
        LiveLandlock::Enforcing,
        "the default selector enforces on a Landlock-capable kernel"
    );
}