mxc-sdk 1.0.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! BaseContainer-fallback tier dispatcher.
//!
//! Wires Phases 0–3 (telemetry, fallback detector, AppContainer modes,
//! DACL manager) into a single entrypoint. Given an [`ExecutionRequest`], the
//! dispatcher consults [`crate::process_container_common::fallback_detector::detect`] to choose
//! between Tier 1 (BaseContainer), Tier 2 (AppContainer + BFS), or Tier 3
//! (AppContainer + DACL), constructs the appropriate runner, and applies
//! [`DaclManager`] augmentation when the chosen tier requires it.
//!
//! Filesystem-policy enforcement under T1 is delegated entirely to
//! BaseContainer's PSEC API
//! (`deniedPaths` via the process-security-environment specification); the dispatcher
//! does **not** apply host DACLs in T1. When the OS advertises native
//! deny support the OS enforces `deniedPaths` itself; when it does not,
//! a denied-paths policy never reaches T1 (the detector falls through to
//! the AppContainer tiers, which stamp the deny DACLs). So T1 has no
//! deny ACEs to apply either way.
//!
//! # Why T2 (BFS) also gets DACL deny augmentation
//!
//! `bfscfg.exe`'s BFS model expresses read-write / read-only allow lists,
//! but does **not** model a deny semantic for paths *outside* its allow
//! list (those are implicitly inaccessible, but a path that lives inside
//! an allowed parent cannot be selectively denied via BFS). To honor
//! `policy.denied_paths` on T2 we therefore add deny ACEs targeting the
//! AppContainer SID alongside the BFS configuration.
//!
//! # Drop ordering
//!
//! Callers must keep the [`DaclManager`] returned by
//! [`Dispatched::into_runner_and_guard`] alive for the entire duration of
//! the run — its [`Drop`] removes the ACEs we added to the host
//! filesystem. Dropping it before the runner finishes would yank
//! filesystem access mid-execution.
//!
//! # Performance
//!
//! Tier 1 has the lowest per-invocation cost: a single
//! `BaseContainerRunner::new()`. Tier 2 with empty `denied_paths` is also
//! near-free. The heavy paths are Tier 2 with deny-only and Tier 3, both
//! of which stamp host-DACL ACEs via [`DaclManager`].
//!
//! The DACL cost is roughly O(N) Win32 syscalls plus one state-file
//! write per path in (Tier 3: `readwrite_paths` ∪ `readonly_paths` ∪
//! `denied_paths`; Tier 2: `denied_paths`). The same number of syscalls
//! is replayed in reverse on `Drop`. At the typical N (6–12 paths) this
//! adds tens of milliseconds to both dispatch and shutdown; at larger N
//! it scales linearly and can add hundreds of milliseconds on each side.
//! SDK callers that spawn `wxc-exec` per task pay this cost on every
//! invocation. Parent-directory ACE rollup and session-scoped
//! [`DaclManager`] caching are tracked as follow-ups.
//!
//! # Known limitation
//!
//! Two concurrent runs with the *same* `container_id` derive the same
//! AppContainer SID and therefore share the same target principal for
//! ACE bookkeeping. When the second run finishes it issues
//! `REVOKE_ACCESS` for that SID, which wipes the first run's still-live
//! grants. This is out of scope for the dispatcher; callers that need
//! parallel-safe isolation must use distinct `container_id` values.
//!
//! Windows-only by virtue of `lib.rs` gating the module behind
//! `#[cfg(target_os = "windows")]`; no inner attribute is needed.

use std::path::PathBuf;
use std::sync::Arc;

use crate::mxc_common::audit::{
    sanitize_identity, AuditEvent, AuditEventName, EffectiveEnforcementLevel,
};
use crate::mxc_common::error::WxcError;
use crate::mxc_common::filesystem_dacl::{DaclError, DaclManager, RO_MASK, RW_MASK};
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainmentBackend, ExecutionRequest, ScriptResponse};
use crate::mxc_common::sandbox_process::{Runner, SandboxBackend, SandboxProcess, StdioMode};
use crate::mxc_common::script_runner::ScriptRunner;
use crate::mxc_common::validator::NetworkPolicySupport;
use crate::process_container_common::appcontainer_runner::{
    derive_sid_string, AppContainerScriptRunner, FilesystemMode,
};
use crate::process_container_common::base_container_runner::BaseContainerRunner;
use crate::process_container_common::fallback_detector::{
    self, DegradationReason, FallbackError, IsolationTier,
};
use crate::process_container_common::guarded_capture::GuardedCaptureFactory;

#[derive(Debug, Clone, Default)]
pub struct Degradation {
    pub needs_dacl_augmentation: bool,
    pub reasons: Vec<DegradationReason>,
}

fn effective_enforcement_level(
    tier: IsolationTier,
    needs_dacl_augmentation: bool,
) -> EffectiveEnforcementLevel {
    match (tier, needs_dacl_augmentation) {
        (IsolationTier::BaseContainer, false) => EffectiveEnforcementLevel::BaseContainer,
        (IsolationTier::BaseContainer, true) => {
            EffectiveEnforcementLevel::BaseContainerDaclAugmented
        }
        (IsolationTier::AppContainerBfs, false) => EffectiveEnforcementLevel::AppContainerBfs,
        (IsolationTier::AppContainerBfs, true) => {
            EffectiveEnforcementLevel::AppContainerBfsDaclAugmented
        }
        (IsolationTier::AppContainerDacl, _) => EffectiveEnforcementLevel::AppContainerDacl,
    }
}

pub(crate) fn log_enforcement_degraded(
    logger: &mut Logger,
    identity: &str,
    tier: IsolationTier,
    degradation: &Degradation,
) {
    if !fallback_detector::is_degraded(
        tier,
        degradation.needs_dacl_augmentation,
        &degradation.reasons,
    ) {
        return;
    }
    let telemetry_active = crate::mxc_common::telemetry::is_active();
    let diagnostic_active = logger.has_diagnostic_sink();
    if !telemetry_active && !diagnostic_active {
        return;
    }
    let effective_level = effective_enforcement_level(tier, degradation.needs_dacl_augmentation);
    let reason_codes = fallback_detector::reason_codes(&degradation.reasons);
    if telemetry_active {
        let redacted_identity = crate::mxc_common::policy_identity::redact_identity(identity);
        crate::mxc_common::telemetry::log_enforcement_degraded(
            &redacted_identity,
            tier.as_str(),
            degradation.needs_dacl_augmentation,
            &reason_codes,
            effective_level.as_str(),
        );
    }
    if diagnostic_active {
        let record = AuditEvent::new(AuditEventName::EnforcementDegraded)
            .str("backend", ContainmentBackend::ProcessContainer.wire_name())
            .str("identity", sanitize_identity(identity))
            .str("tier", tier.as_str())
            .str("effective_enforcement_level", effective_level.as_str())
            .bool(
                "needs_dacl_augmentation",
                degradation.needs_dacl_augmentation,
            )
            .str("degradation_reasons", &reason_codes)
            .u64("degradation_reason_count", degradation.reasons.len() as u64);
        logger.log_audit_event(&record);
    }
}

/// Result of a successful dispatch decision: a phased handle holding a
/// runner and (optionally) a `DaclManager`, with **private fields** so
/// callers cannot reorder their drops.
///
/// This is *not* a compile-time typestate — there are no
/// `PhantomData<State>` markers and `Dispatched<Ready>` /
/// `Dispatched<Spawned>` do not exist. The safety property
/// ("`DaclManager`'s `Drop` runs AFTER the runner has finished, or the
/// ACEs we applied would be revoked mid-execution") is enforced
/// dynamically by the single extraction point
/// [`Dispatched::into_runner_and_guard`]: it returns a tuple whose
/// binding order dictates drop order, and callers cannot `.take()`
/// either half independently because the fields are private.
///
/// If you need stronger guarantees (e.g. statically rejecting
/// `runner.drop()` before `dacl_manager` is taken at the FFI boundary),
/// promote the struct to a real typestate machine. Today, the
/// surface area we expose to wxc-exec / SDK doesn't need that.
pub struct Dispatched {
    runner: Box<dyn ScriptRunner>,
    dacl_manager: Option<DaclManager>,
    /// The selected tier, for telemetry.
    pub tier: IsolationTier,
    identity: String,
    /// Operator-visible warnings collected during tier selection.
    pub warnings: Vec<String>,
    pub degradation: Degradation,
}

impl Dispatched {
    /// Consume `self` and return `(runner, dacl_manager)`. Bind these
    /// in a single `let` such that the runner is dropped before the
    /// DACL guard — Rust drops local bindings in reverse declaration
    /// order, so the standard idiom is:
    ///
    /// ```ignore
    /// let (mut runner, _dacl_guard) = dispatched.into_runner_and_guard();
    /// // ... use runner ...
    /// // at end of scope: runner drops first, then _dacl_guard restores ACEs.
    /// ```
    pub fn into_runner_and_guard(self) -> (Box<dyn ScriptRunner>, Option<DaclManager>) {
        (self.runner, self.dacl_manager)
    }

    /// Read-only check used by unit tests to assert whether the chosen
    /// tier required DACL augmentation, without exposing the manager
    /// itself (which would let tests `.take()` it).
    #[cfg(test)]
    pub(crate) fn has_dacl_guard(&self) -> bool {
        self.dacl_manager.is_some()
    }

    pub fn log_enforcement_degraded(&self, logger: &mut Logger) {
        log_enforcement_degraded(logger, &self.identity, self.tier, &self.degradation);
    }
}

/// Errors that can abort dispatch before the runner executes.
#[derive(Debug)]
pub enum DispatchError {
    /// Fallback detection refused the request.
    Fallback(FallbackError),
    /// `DaclManager` failed to apply ACEs. `warnings` carries any
    /// retained-entry messages drained from the manager before the
    /// failed apply was rolled back via `restore()`. Entries that
    /// `restore()` itself could not clean up are persisted to disk and
    /// will be reaped on the next wxc-exec startup by
    /// `recover_orphaned_state`.
    Dacl {
        error: DaclError,
        warnings: Vec<String>,
    },
    /// AppContainer SID derivation failed.
    Sid(WxcError),
    /// captureDenials requires the native BaseContainer tier and cannot
    /// proceed through an AppContainer fallback.
    CaptureDenialsUnsupported { tier: IsolationTier },
    /// The selected AppContainer fallback requires guarded capture, but its
    /// prerequisites are not available.
    CaptureDenialsUnavailable { tier: IsolationTier, reason: String },
}

impl std::fmt::Display for DispatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DispatchError::Fallback(FallbackError::DaclFallbackDisabled) => write!(
                f,
                "BaseContainer is unavailable on this system and DACL fallback is disabled \
                 (fallback.allowDaclMutation=false). Run on a system with the BaseContainer \
                 API or bfscfg.exe, or set fallback.allowDaclMutation=true in your config."
            ),
            DispatchError::Fallback(FallbackError::WriteDacUnavailable { path, reason }) => {
                write!(
                    f,
                    "BaseContainer is unavailable; DACL fallback requires write-DAC permission \
                     on '{}', which the current user lacks ({reason}).",
                    path.display()
                )
            }
            DispatchError::Fallback(FallbackError::SystemRootUnresolved { reason }) => write!(
                f,
                "Could not resolve the Windows system directory while probing for bfscfg.exe \
                 ({reason}). This indicates a corrupted or unsupported OS configuration."
            ),
            DispatchError::Fallback(
                error @ (FallbackError::EnumeratePathsUnsupported
                | FallbackError::IngressUnsupported),
            ) => write!(f, "{error}"),
            DispatchError::Dacl { error, .. } => write!(f, "Failed to apply DACL ACEs: {error}"),
            DispatchError::Sid(e) => write!(f, "Failed to derive AppContainer SID: {e}"),
            DispatchError::CaptureDenialsUnsupported { tier } => write!(
                f,
                "captureDenials requires the native BaseContainer backend; \
                 the selected fallback tier '{}' does not support denial capture.",
                tier.as_str()
            ),
            DispatchError::CaptureDenialsUnavailable { tier, reason } => write!(
                f,
                "the guarded WPR captureDenials fallback required by isolation tier '{}' \
                 is unavailable: {reason}",
                tier.as_str()
            ),
        }
    }
}

impl std::error::Error for DispatchError {}

impl From<FallbackError> for DispatchError {
    fn from(e: FallbackError) -> Self {
        DispatchError::Fallback(e)
    }
}

/// The container-id → AppContainer-name mapping used by the runners. Empty
/// container_id maps to `"CLI"` (matches both AppContainerScriptRunner and
/// BaseContainerRunner internals).
fn container_name(request: &ExecutionRequest) -> String {
    if request.container_id.is_empty() {
        "CLI".to_string()
    } else {
        request.container_id.clone()
    }
}

fn paths_to_pathbufs(paths: &[String]) -> Vec<PathBuf> {
    paths.iter().map(PathBuf::from).collect()
}

/// Drop paths that already grant `needed_mask` to the well-known
/// AppContainer SIDs (`ALL APPLICATION PACKAGES`,
/// `ALL RESTRICTED APPLICATION PACKAGES`, `Everyone`). Mirrors the
/// same effective-access check that
/// [`fallback_detector::appcontainer_already_grants`] performs for
/// the `WRITE_DAC` precheck.
fn filter_paths_needing_grant(paths: Vec<PathBuf>, needed_mask: u32) -> Vec<PathBuf> {
    paths
        .into_iter()
        .filter(|p| !fallback_detector::appcontainer_already_grants(p, needed_mask))
        .collect()
}

/// Wrap a `DaclError` together with any retained-entry warnings from the
/// manager whose apply failed. Called immediately before `mgr` goes out
/// of scope (which triggers `restore()` via Drop) so we capture the
/// apply-time warnings, not whatever `restore()` itself accumulates
/// while unwinding.
fn dacl_err(mgr: &DaclManager, error: DaclError) -> DispatchError {
    DispatchError::Dacl {
        error,
        warnings: mgr.warnings().to_vec(),
    }
}

/// Build the deny-only DACL manager used by T1 and T2 when
/// `denied_paths` is non-empty. Returns `Ok(None)` when no DACL work is
/// required.
fn build_deny_only_dacl(
    sid: &str,
    denied: &[PathBuf],
) -> Result<Option<DaclManager>, DispatchError> {
    if denied.is_empty() {
        return Ok(None);
    }
    let mut mgr = DaclManager::new().map_err(|e| DispatchError::Dacl {
        error: e,
        warnings: Vec::new(),
    })?;
    if let Err(e) = mgr.add_deny_aces(sid, denied) {
        return Err(dacl_err(&mgr, e));
    }
    Ok(Some(mgr))
}

/// Build the grant + (optional) deny DACL manager used by T3. T3 always
/// returns a `DaclManager` because grants are mandatory; if grants
/// succeed and deny fails, the manager's `Drop` rolls back the grants.
fn build_t3_dacl(
    sid: &str,
    readwrite: &[PathBuf],
    readonly: &[PathBuf],
    denied: &[PathBuf],
) -> Result<DaclManager, DispatchError> {
    let mut mgr = DaclManager::new().map_err(|e| DispatchError::Dacl {
        error: e,
        warnings: Vec::new(),
    })?;
    if let Err(e) = mgr.grant_appcontainer_access(sid, readwrite, readonly) {
        return Err(dacl_err(&mgr, e));
    }
    if !denied.is_empty() {
        if let Err(e) = mgr.add_deny_aces(sid, denied) {
            return Err(dacl_err(&mgr, e));
        }
    }
    Ok(mgr)
}

/// The concrete Windows backend chosen by the fallback dispatcher, before it is
/// adapted to either the run-to-completion surface (wrapped in [`Runner`] →
/// [`ScriptRunner`], via [`dispatch_with_fallback`]) or the streaming surface
/// ([`SandboxBackend::spawn`], via [`spawn_with_fallback`]).
///
/// Keeping tier selection in one place ([`select_backend_with_fallback`]) is
/// what guarantees the two surfaces can't drift — the streaming path previously
/// reimplemented a two-tier subset and so never reached the AppContainer + DACL
/// fallback (issue #643).
enum SelectedBackend {
    BaseContainer(BaseContainerRunner),
    AppContainer(AppContainerScriptRunner),
}

impl SandboxBackend for SelectedBackend {
    fn network_policy_support(&self) -> NetworkPolicySupport {
        match self {
            SelectedBackend::BaseContainer(b) => b.network_policy_support(),
            SelectedBackend::AppContainer(a) => a.network_policy_support(),
        }
    }

    fn validate(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        match self {
            SelectedBackend::BaseContainer(b) => b.validate(request),
            SelectedBackend::AppContainer(a) => a.validate(request),
        }
    }

    fn spawn(
        &mut self,
        request: &ExecutionRequest,
        logger: &mut Logger,
        stdio: StdioMode,
    ) -> Result<Box<dyn SandboxProcess>, ScriptResponse> {
        match self {
            SelectedBackend::BaseContainer(b) => b.spawn(request, logger, stdio),
            SelectedBackend::AppContainer(a) => a.spawn(request, logger, stdio),
        }
    }

    fn diagnose_exit(&self, request: &ExecutionRequest, exit_code: i32) -> Option<String> {
        match self {
            SelectedBackend::BaseContainer(b) => b.diagnose_exit(request, exit_code),
            SelectedBackend::AppContainer(a) => a.diagnose_exit(request, exit_code),
        }
    }
}

struct BackendPlan {
    backend: SelectedBackend,
    dacl_manager: Option<DaclManager>,
    tier: IsolationTier,
    warnings: Vec<String>,
    degradation: Degradation,
}

/// Run tier selection and construct the backend + (optional) DACL guard for
/// `request`. This is the single source of truth for the tier → (backend, DACL)
/// mapping, shared by the run-to-completion ([`dispatch_with_fallback`]) and
/// streaming ([`spawn_with_fallback`]) surfaces.
///
/// `capture_factory` is the optional guarded-WPR-capture DI boundary (see
/// [`crate::process_container_common::guarded_capture`]). When `request.policy.capture_denials` is set
/// and the selected tier is not the native BaseContainer backend:
/// - available `capture_factory` → the factory is threaded onto the chosen
///   AppContainer runner via `with_guarded_capture_factory`, so the runner
///   itself performs the guarded WPR fallback capture (see
///   `appcontainer_runner`'s `validate`/`spawn`);
/// - unavailable `capture_factory` → dispatch fails before backend construction
///   or DACL mutation with [`DispatchError::CaptureDenialsUnavailable`];
/// - `capture_factory` absent → dispatch fails closed with
///   [`DispatchError::CaptureDenialsUnsupported`], preserving the legacy
///   behavior for callers that haven't opted into the fallback (e.g. callers
///   without a Windows-only `plm` dependency available).
///
/// On success the returned [`DaclManager`], when present, has **already applied
/// its ACEs** and MUST outlive the run (its `Drop` restores the host ACEs). The
/// selected [`IsolationTier`] and any tier-selection warnings are returned for
/// telemetry.
fn select_backend_with_fallback(
    request: &ExecutionRequest,
    capture_factory: Option<&Arc<dyn GuardedCaptureFactory>>,
) -> Result<BackendPlan, DispatchError> {
    // Keep the established tier fallback behavior for every schema version.
    // BaseContainerRunner uses PSEC whenever it is available and compatible.
    // Otherwise detection continues to the AppContainer tiers.
    let decision = fallback_detector::choose_backend_tier(request)?;
    let guarded_capture_required =
        request.policy.capture_denials.is_some() && decision.tier != IsolationTier::BaseContainer;
    if guarded_capture_required && capture_factory.is_none() {
        return Err(DispatchError::CaptureDenialsUnsupported {
            tier: decision.tier,
        });
    }
    let capture_factory_for_appcontainer = if guarded_capture_required {
        let factory = capture_factory.expect("guarded capture factory checked above");
        factory
            .verify_available()
            .map_err(|reason| DispatchError::CaptureDenialsUnavailable {
                tier: decision.tier,
                reason,
            })?;
        Some(factory)
    } else {
        None
    };

    let (backend, dacl_manager): (SelectedBackend, Option<DaclManager>) = match decision.tier {
        IsolationTier::BaseContainer => {
            // Tier 1 delegates filesystem-policy enforcement to
            // BaseContainer's native API. We stamp no host-DACL deny ACEs
            // here: the detector only routes a denied-paths policy to T1
            // when the OS enforces `fs_deny` natively, so there is nothing
            // for a host DACL to add.
            let runner = BaseContainerRunner::new_for_selected_request();
            (SelectedBackend::BaseContainer(runner), None)
        }
        IsolationTier::AppContainerBfs => {
            // T2 only needs deny ACEs (BFS handles the rest in-runner)
            // and only when `deniedPaths` is non-empty. Allocate the
            // path Vec and derive the SID inside that branch so the
            // common no-deny case skips both costs.
            let denied = paths_to_pathbufs(&request.policy.denied_paths);
            if denied.is_empty() {
                let runner = with_capture_factory(
                    AppContainerScriptRunner::with_filesystem_mode(FilesystemMode::Bfs),
                    capture_factory_for_appcontainer,
                );
                (SelectedBackend::AppContainer(runner), None)
            } else {
                let sid =
                    derive_sid_string(&container_name(request)).map_err(DispatchError::Sid)?;
                let mgr = build_deny_only_dacl(&sid, &denied)?;
                // Hand the derived SID string to the runner so it does
                // not re-run `ConvertSidToStringSidW` for the firewall
                // principal-id lookup.
                //
                // BFS cannot enforce `deniedPaths` itself. Marking them
                // "externally enforced" — so the runner's `validate` accepts
                // them and relies on the host deny-only DACL built above — is a
                // capture-fallback affordance, gated to `captureDenials`
                // requests. For non-capture requests we leave the runner
                // unmarked, so `deniedPaths` on the BFS tier stay unsupported
                // exactly as before this fallback existed (the runner's
                // `validate` rejects them) rather than silently broadening BFS
                // to honor `deniedPaths` via host DACLs.
                let base_runner = AppContainerScriptRunner::with_filesystem_mode_and_sid_string(
                    FilesystemMode::Bfs,
                    sid,
                );
                let base_runner = if guarded_capture_required {
                    base_runner.with_external_denied_paths()
                } else {
                    base_runner
                };

                let runner = with_capture_factory(base_runner, capture_factory_for_appcontainer);
                (SelectedBackend::AppContainer(runner), mgr)
            }
        }
        IsolationTier::AppContainerDacl => {
            // T3 always stamps grant ACEs (for readwrite/readonly paths)
            // and optionally deny ACEs. Allocate per-arm so T1/T2 don't
            // pay the cost.
            //
            // Skip per-run grant ACEs on paths where the well-known
            // AppContainer SIDs already grant the equivalent access.
            // `fallback_detector::detect` performs the same effective-
            // access check up front so it can skip the `WRITE_DAC`
            // requirement; this filter is the matching application
            // side so we don't try (and fail) to stamp a redundant
            // ACE on a system path the user doesn't own. Denied paths
            // are not filtered — DENY ACEs are about subtracting
            // access, which well-known group grants can't do.
            let readwrite = filter_paths_needing_grant(
                paths_to_pathbufs(&request.policy.readwrite_paths),
                RW_MASK,
            );
            let readonly = filter_paths_needing_grant(
                paths_to_pathbufs(&request.policy.readonly_paths),
                RO_MASK,
            );
            let denied = paths_to_pathbufs(&request.policy.denied_paths);
            let sid = derive_sid_string(&container_name(request)).map_err(DispatchError::Sid)?;
            let mgr = build_t3_dacl(&sid, &readwrite, &readonly, &denied)?;
            let runner = with_capture_factory(
                AppContainerScriptRunner::with_filesystem_mode_and_sid_string(
                    FilesystemMode::Dacl,
                    sid,
                ),
                capture_factory_for_appcontainer,
            );
            (SelectedBackend::AppContainer(runner), Some(mgr))
        }
    };

    Ok(BackendPlan {
        backend,
        dacl_manager,
        tier: decision.tier,
        warnings: decision.warnings,
        degradation: Degradation {
            needs_dacl_augmentation: decision.needs_dacl_augmentation,
            reasons: decision.reasons,
        },
    })
}

/// Chain [`AppContainerScriptRunner::with_guarded_capture_factory`] onto
/// `runner` when `capture_factory` is present, otherwise return `runner`
/// unchanged. Small helper to keep the three tier-selection arms above
/// symmetric regardless of whether `captureDenials` is in play.
fn with_capture_factory(
    runner: AppContainerScriptRunner,
    capture_factory: Option<&Arc<dyn GuardedCaptureFactory>>,
) -> AppContainerScriptRunner {
    match capture_factory {
        Some(factory) => runner.with_guarded_capture_factory(Arc::clone(factory)),
        None => runner,
    }
}

/// Build a runner with appropriate DACL augmentation for the
/// BaseContainer-preferred path. The caller is responsible for the explicit
/// (no-fallback) AppContainer path.
///
/// On success the returned [`Dispatched`] contains a runner ready to
/// execute and (when applicable) a [`DaclManager`] that has already
/// applied its ACEs. Use [`Dispatched::into_runner_and_guard`] to
/// extract both; the manager MUST stay alive through the run.
///
/// When `capture_factory` is `None`, `captureDenials` fails closed if the
/// request cannot use native BaseContainer capture.
pub fn dispatch_with_fallback(
    request: &ExecutionRequest,
    capture_factory: Option<Arc<dyn GuardedCaptureFactory>>,
) -> Result<Dispatched, DispatchError> {
    let plan = select_backend_with_fallback(request, capture_factory.as_ref())?;
    let runner: Box<dyn ScriptRunner> = Box::new(Runner::new(plan.backend));
    Ok(Dispatched {
        runner,
        dacl_manager: plan.dacl_manager,
        tier: plan.tier,
        identity: container_name(request),
        warnings: plan.warnings,
        degradation: plan.degradation,
    })
}

/// A successful streaming dispatch: a [`SandboxProcess`] handle plus the tier
/// and warnings for telemetry. The handle already owns any [`DaclManager`]
/// guard (via [`DaclGuardedProcess`]), so ACE restore outlives the child — the
/// caller only has to keep the handle alive until the run is done.
pub struct DispatchedProcess {
    /// The spawned sandboxed process, streaming stdio over pipes.
    pub process: Box<dyn SandboxProcess>,
    /// The selected tier, for telemetry.
    pub tier: IsolationTier,
    /// Operator-visible warnings collected during tier selection.
    pub warnings: Vec<String>,
}

/// Error from the streaming [`spawn_with_fallback`] path. Kept distinct from a
/// flat error so the caller can preserve fallback semantics: tier-selection /
/// DACL failures map to `backend_unavailable` (as the run-to-completion path
/// does), while a backend spawn failure preserves the backend's
/// [`FailurePhase`](crate::mxc_common::models::FailurePhase).
pub enum SpawnDispatchError {
    /// Tier selection or DACL application failed before the process spawned.
    /// Mirrors [`dispatch_with_fallback`]'s [`DispatchError`].
    Dispatch(DispatchError),
    /// The selected backend's `spawn` failed *after* a tier was already chosen
    /// (and any DACL ACEs applied then rolled back). Carries the backend's
    /// [`ScriptResponse`] so the caller can preserve its `failure_phase`, plus
    /// the selected `tier` and tier-selection `warnings` so the caller can log
    /// them on the failure path too — matching the run-to-completion path, which
    /// logs both at resolve time before the (separate, later) spawn attempt.
    ///
    /// `response` is boxed to keep this cold-path error variant small (it would
    /// otherwise trip `clippy::result_large_err` on every `spawn_with_fallback`
    /// return).
    Spawn {
        response: Box<ScriptResponse>,
        tier: IsolationTier,
        warnings: Vec<String>,
    },
}

/// Streaming counterpart of [`dispatch_with_fallback`]: select the tier, apply
/// any DACL augmentation, spawn the sandboxed process with `stdio`, and return a
/// [`SandboxProcess`] handle that owns the DACL guard so ACE restore outlives
/// the child.
///
/// This exists so the streaming (`mxc-sdk`) path gets the **same** three-tier
/// fallback as the executor binaries' run-to-completion path — including the
/// AppContainer + DACL (Tier 3) tier used when neither BaseContainer nor
/// `bfscfg.exe` (Tier 2 BFS) is available. See issue #643.
///
/// # Drop ordering
///
/// When a DACL guard is attached, the returned handle is a [`DaclGuardedProcess`]
/// whose field order drops the inner process (killing the child tree and
/// tearing down firewall / BFS enforcement) **before** the [`DaclManager`]
/// (restoring host ACEs) — the same order the run-to-completion path enforces
/// via [`Dispatched::into_runner_and_guard`].
///
pub fn spawn_with_fallback(
    request: &ExecutionRequest,
    logger: &mut Logger,
    stdio: StdioMode,
    capture_factory: Option<Arc<dyn GuardedCaptureFactory>>,
) -> Result<DispatchedProcess, SpawnDispatchError> {
    let BackendPlan {
        mut backend,
        dacl_manager,
        tier,
        warnings,
        degradation,
    } = select_backend_with_fallback(request, capture_factory.as_ref())
        .map_err(SpawnDispatchError::Dispatch)?;
    log_enforcement_degraded(logger, &container_name(request), tier, &degradation);

    // Spawn with the DACL ACEs (if any) already applied. On a spawn failure the
    // `dacl_manager` local drops here, restoring any ACEs that were stamped; we
    // hand the already-selected `tier`/`warnings` to the error so the caller can
    // still log them (the run-to-completion path logs them at resolve time,
    // before its separate spawn attempt).
    let inner = match backend.spawn(request, logger, stdio) {
        Ok(inner) => inner,
        Err(response) => {
            return Err(SpawnDispatchError::Spawn {
                response: Box::new(response),
                tier,
                warnings,
            })
        }
    };

    // Attach the guard to the handle only when there is one — T1 and T2-without-
    // deny need no DACL work, so their handle is returned unwrapped.
    let process: Box<dyn SandboxProcess> = match dacl_manager {
        Some(dacl_manager) => Box::new(DaclGuardedProcess {
            inner,
            _dacl_manager: dacl_manager,
        }),
        None => inner,
    };

    Ok(DispatchedProcess {
        process,
        tier,
        warnings,
    })
}

/// A streaming [`SandboxProcess`] paired with the [`DaclManager`] guard whose
/// `Drop` restores the host ACEs the DACL tier applied.
///
/// **Field order is load-bearing.** Rust drops struct fields in declaration
/// order, so `inner` (which kills the child tree and tears down the per-run
/// firewall / BFS enforcement) drops **before** `_dacl_manager` (which restores
/// host ACEs). This matches the run-to-completion path's `(runner, dacl_manager)`
/// drop order (see [`Dispatched::into_runner_and_guard`]): the host ACEs must
/// not be revoked until the child and its descendants are gone.
///
/// Every [`SandboxProcess`] method delegates to `inner`; the guard is otherwise
/// inert until drop.
struct DaclGuardedProcess {
    inner: Box<dyn SandboxProcess>,
    _dacl_manager: DaclManager,
}

impl SandboxProcess for DaclGuardedProcess {
    fn warnings(&self) -> Vec<String> {
        self.inner.warnings()
    }

    fn take_stdin(&mut self) -> Option<Box<dyn std::io::Write + Send>> {
        self.inner.take_stdin()
    }

    fn stdin_closer(&self) -> Option<Box<dyn crate::mxc_common::sandbox_process::StreamCloser>> {
        self.inner.stdin_closer()
    }

    fn take_native_stdio(
        &mut self,
    ) -> std::io::Result<Option<crate::mxc_common::sandbox_process::NativeStdio>> {
        self.inner.take_native_stdio()
    }

    fn take_stdout(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        self.inner.take_stdout()
    }

    fn take_stderr(&mut self) -> Option<Box<dyn std::io::Read + Send>> {
        self.inner.take_stderr()
    }

    fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
        self.inner.try_wait()
    }

    fn id(&self) -> u32 {
        self.inner.id()
    }

    fn kill(&mut self) -> std::io::Result<()> {
        self.inner.kill()
    }

    fn kill_for_timeout(&mut self) -> std::io::Result<()> {
        self.inner.kill_for_timeout()
    }

    fn wait(&mut self) -> std::io::Result<i32> {
        self.inner.wait()
    }

    fn output_metadata(&self) -> Option<&crate::mxc_common::models::SandboxOutputMetadata> {
        self.inner.output_metadata()
    }

    fn stdout_closer(&self) -> Option<Box<dyn crate::mxc_common::sandbox_process::StreamCloser>> {
        self.inner.stdout_closer()
    }

    fn stderr_closer(&self) -> Option<Box<dyn crate::mxc_common::sandbox_process::StreamCloser>> {
        self.inner.stderr_closer()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::{ContainerPolicy, ExecutionRequest, ProxyAddress, ProxyConfig};
    // `ForceTierGuard` lives in `crate::process_container_common::test_env` so the lock is
    // shared with the `fallback_detector::tests` module — otherwise
    // a dispatcher test and a fallback-detector test running on
    // different threads could each mutate `MXC_FORCE_TIER` under
    // independent locks and race.
    use crate::process_container_common::test_env::{
        BcUsableGuard, CaptureCapabilityGuard, ForceTierGuard, ENV_LOCK,
    };

    fn test_request(policy: ContainerPolicy) -> ExecutionRequest {
        ExecutionRequest {
            container_id: "MxcDispatcherTest".to_string(),
            policy,
            ..ExecutionRequest::default()
        }
    }

    fn empty_policy() -> ContainerPolicy {
        ContainerPolicy::default()
    }

    #[test]
    fn effective_enforcement_level_covers_all_tier_combinations() {
        let cases = [
            (
                IsolationTier::BaseContainer,
                false,
                EffectiveEnforcementLevel::BaseContainer,
            ),
            (
                IsolationTier::BaseContainer,
                true,
                EffectiveEnforcementLevel::BaseContainerDaclAugmented,
            ),
            (
                IsolationTier::AppContainerBfs,
                false,
                EffectiveEnforcementLevel::AppContainerBfs,
            ),
            (
                IsolationTier::AppContainerBfs,
                true,
                EffectiveEnforcementLevel::AppContainerBfsDaclAugmented,
            ),
            (
                IsolationTier::AppContainerDacl,
                false,
                EffectiveEnforcementLevel::AppContainerDacl,
            ),
            (
                IsolationTier::AppContainerDacl,
                true,
                EffectiveEnforcementLevel::AppContainerDacl,
            ),
        ];

        for (tier, needs_dacl_augmentation, expected) in cases {
            assert_eq!(
                effective_enforcement_level(tier, needs_dacl_augmentation),
                expected
            );
        }
    }

    fn policy_with_denied_temp() -> (ContainerPolicy, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut p = ContainerPolicy::default();
        p.denied_paths
            .push(dir.path().to_string_lossy().into_owned());
        (p, dir)
    }
    fn policy_with_rw_temp() -> (ContainerPolicy, tempfile::TempDir) {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut p = ContainerPolicy::default();
        p.readwrite_paths
            .push(dir.path().to_string_lossy().into_owned());
        (p, dir)
    }

    /// A fake [`GuardedCaptureFactory`] used only to exercise dispatcher
    /// tier-selection gating — its `start` is never invoked by these tests
    /// (dispatch stops at backend construction, before `spawn`).
    struct FakeGuardedCaptureFactory;

    impl GuardedCaptureFactory for FakeGuardedCaptureFactory {
        fn start(
            &self,
            _owner_pid: u32,
        ) -> Result<
            Box<dyn crate::process_container_common::guarded_capture::GuardedCaptureSession>,
            String,
        > {
            Err("not used in dispatcher selection tests".to_string())
        }
    }

    struct UnavailableGuardedCaptureFactory;

    impl GuardedCaptureFactory for UnavailableGuardedCaptureFactory {
        fn verify_available(&self) -> Result<(), String> {
            Err("plm.exe is not trusted".to_string())
        }

        fn start(
            &self,
            _owner_pid: u32,
        ) -> Result<
            Box<dyn crate::process_container_common::guarded_capture::GuardedCaptureSession>,
            String,
        > {
            panic!("unavailable factory must be rejected before start")
        }
    }

    #[test]
    fn dispatch_t1_no_denied_paths_no_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::BaseContainer);
        let req = test_request(empty_policy());
        let d = dispatch_with_fallback(&req, None).expect("T1 dispatch should succeed");
        assert!(matches!(d.tier, IsolationTier::BaseContainer));
        assert!(
            !d.has_dacl_guard(),
            "T1 with no denied_paths should not allocate DaclManager"
        );
    }
    #[test]
    fn dispatch_t1_with_denied_paths_has_no_dacl() {
        // T1 delegates filesystem-policy enforcement (including
        // `deniedPaths`) to BaseContainer's native API; the dispatcher
        // attaches no `DaclManager` on the T1 path regardless of the
        // `deniedPaths` contents.
        let _g = ForceTierGuard::set_tier(IsolationTier::BaseContainer);
        let (policy, _tmp) = policy_with_denied_temp();
        let req = test_request(policy);
        let d = dispatch_with_fallback(&req, None).expect("T1+deny dispatch should succeed");
        assert!(matches!(d.tier, IsolationTier::BaseContainer));
        assert!(
            !d.has_dacl_guard(),
            "T1 must not attach a DaclManager — BC handles deny natively"
        );
    }
    #[test]
    fn dispatch_t2_with_denied_paths_has_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerBfs);
        let (policy, _tmp) = policy_with_denied_temp();
        let req = test_request(policy);
        let d = dispatch_with_fallback(&req, None).expect("T2+deny dispatch should succeed");
        assert!(matches!(d.tier, IsolationTier::AppContainerBfs));
        assert!(d.has_dacl_guard());
    }
    #[test]
    fn dispatch_t3_always_has_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let (policy, _tmp) = policy_with_rw_temp();
        let req = test_request(policy);
        let d = dispatch_with_fallback(&req, None).expect("T3 dispatch should succeed");
        assert!(matches!(d.tier, IsolationTier::AppContainerDacl));
        assert!(
            d.has_dacl_guard(),
            "T3 always requires DaclManager (grants applied)"
        );
    }

    #[test]
    fn capture_denials_rejects_appcontainer_fallback() {
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (mut policy, _tmp) = policy_with_rw_temp();
        policy.capture_denials = Some(Default::default());
        let req = test_request(policy);

        let result = dispatch_with_fallback(&req, None);
        assert!(matches!(
            result,
            Err(DispatchError::CaptureDenialsUnsupported {
                tier: IsolationTier::AppContainerDacl
            })
        ));
    }

    #[test]
    fn capture_denials_rejects_appcontainer_fallback_without_factory() {
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (mut policy, _tmp) = policy_with_rw_temp();
        policy.capture_denials = Some(Default::default());
        let req = test_request(policy);

        let result = dispatch_with_fallback(&req, None);
        assert!(matches!(
            result,
            Err(DispatchError::CaptureDenialsUnsupported {
                tier: IsolationTier::AppContainerDacl
            })
        ));
    }

    #[test]
    fn capture_denials_selects_appcontainer_fallback_with_guarded_factory() {
        // With a guarded capture factory supplied, an AppContainer fallback
        // tier must be selected (not rejected) when `captureDenials` is set.
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (mut policy, _tmp) = policy_with_rw_temp();
        policy.capture_denials = Some(Default::default());
        let req = test_request(policy);

        let factory: Arc<dyn GuardedCaptureFactory> = Arc::new(FakeGuardedCaptureFactory);
        let dispatched = dispatch_with_fallback(&req, Some(factory))
            .expect("a guarded capture factory should let AppContainer+DACL honor captureDenials");
        assert!(matches!(dispatched.tier, IsolationTier::AppContainerDacl));
        assert!(
            dispatched.has_dacl_guard(),
            "T3 still stamps its grant ACEs when captureDenials is honored via guarded WPR"
        );
    }

    #[test]
    fn capture_denials_rejects_unavailable_guarded_factory_before_backend_setup() {
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (mut policy, _temporary_path) = policy_with_rw_temp();
        policy.capture_denials = Some(Default::default());
        let req = test_request(policy);

        let factory: Arc<dyn GuardedCaptureFactory> = Arc::new(UnavailableGuardedCaptureFactory);
        let result = dispatch_with_fallback(&req, Some(factory));

        assert!(matches!(
            result,
            Err(DispatchError::CaptureDenialsUnavailable {
                tier: IsolationTier::AppContainerDacl,
                ref reason
            }) if reason == "plm.exe is not trusted"
        ));
    }

    #[test]
    fn capture_denials_prefers_native_psec_v2_when_complete() {
        let _guard = CaptureCapabilityGuard::set(true, true);
        let mut policy = empty_policy();
        policy.capture_denials = Some(Default::default());
        let request = test_request(policy);

        let dispatched = dispatch_with_fallback(&request, None)
            .expect("complete native capture should not require guarded WPR");

        assert!(matches!(dispatched.tier, IsolationTier::BaseContainer));
    }

    #[test]
    fn capture_denials_native_capture_does_not_check_guarded_factory_availability() {
        let _guard = CaptureCapabilityGuard::set(true, true);
        let mut policy = empty_policy();
        policy.capture_denials = Some(Default::default());
        let request = test_request(policy);

        let factory: Arc<dyn GuardedCaptureFactory> = Arc::new(UnavailableGuardedCaptureFactory);
        let dispatched = dispatch_with_fallback(&request, Some(factory))
            .expect("native capture must not depend on guarded WPR prerequisites");

        assert!(matches!(dispatched.tier, IsolationTier::BaseContainer));
    }

    #[test]
    fn spawn_with_fallback_without_factory_rejects_capture() {
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (mut policy, _tmp) = policy_with_rw_temp();
        policy.capture_denials = Some(Default::default());
        let req = test_request(policy);
        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);

        let result = spawn_with_fallback(&req, &mut logger, StdioMode::Inherit, None);
        assert!(matches!(
            result,
            Err(SpawnDispatchError::Dispatch(
                DispatchError::CaptureDenialsUnsupported {
                    tier: IsolationTier::AppContainerDacl
                }
            ))
        ));
    }

    #[test]
    fn capture_denials_spawn_rejects_unavailable_guarded_factory_before_spawn() {
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (mut policy, _temporary_path) = policy_with_rw_temp();
        policy.capture_denials = Some(Default::default());
        let req = test_request(policy);
        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let factory: Arc<dyn GuardedCaptureFactory> = Arc::new(UnavailableGuardedCaptureFactory);

        let result = spawn_with_fallback(&req, &mut logger, StdioMode::Inherit, Some(factory));

        assert!(matches!(
            result,
            Err(SpawnDispatchError::Dispatch(
                DispatchError::CaptureDenialsUnavailable {
                    tier: IsolationTier::AppContainerDacl,
                    ref reason
                }
            )) if reason == "plm.exe is not trusted"
        ));
    }

    #[test]
    fn ordinary_request_keeps_appcontainer_fallback() {
        let _g = ForceTierGuard::set("appcontainer-dacl");
        let (policy, _tmp) = policy_with_rw_temp();
        let req = test_request(policy);

        let dispatched = dispatch_with_fallback(&req, None).expect("fallback should be selected");
        assert!(matches!(dispatched.tier, IsolationTier::AppContainerDacl));
        assert!(
            dispatched.has_dacl_guard(),
            "ordinary requests retain AppContainer + DACL fallback"
        );
    }

    #[test]
    fn proxy_uses_appcontainer_when_base_container_is_incompatible() {
        let _g = BcUsableGuard::set(false);
        let mut policy = empty_policy();
        policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
            builtin_test_server: false,
        };
        let req = test_request(policy);

        let plan = select_backend_with_fallback(&req, None)
            .expect("AppContainer fallback should be selected");
        let (backend, tier) = (plan.backend, plan.tier);
        assert_ne!(tier, IsolationTier::BaseContainer);
        assert!(matches!(backend, SelectedBackend::AppContainer(_)));
    }

    #[test]
    fn dispatch_fallback_disabled_errors() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let (mut policy, _tmp) = policy_with_rw_temp();
        policy.fallback.allow_dacl_mutation = false;
        let req = test_request(policy);
        let res = dispatch_with_fallback(&req, None);
        assert!(matches!(
            res,
            Err(DispatchError::Fallback(FallbackError::DaclFallbackDisabled))
        ));
    }

    #[test]
    fn dispatch_error_display_messages_non_empty() {
        let f = DispatchError::Fallback(FallbackError::DaclFallbackDisabled);
        assert!(!format!("{f}").is_empty());

        let w = DispatchError::Fallback(FallbackError::WriteDacUnavailable {
            path: PathBuf::from("C:\\foo"),
            reason: "ACCESS_DENIED".to_string(),
        });
        let s = format!("{w}");
        assert!(s.contains("C:\\foo"));
        assert!(s.contains("ACCESS_DENIED"));

        let s = DispatchError::Sid(WxcError::Initialization("bad sid".to_string()));
        assert!(format!("{s}").contains("AppContainer SID"));
    }

    /// `DispatchError::Dacl { error, warnings }` is the shape consumers
    /// (SDK envelope, error formatters) depend on. Force an actual
    /// apply failure by passing a non-existent path through
    /// `build_deny_only_dacl` — `apply_one` -> `canonicalize_local`
    /// fails with `io::Error` rooted at the missing path. The
    /// resulting `DispatchError::Dacl` must:
    ///   - be the `Dacl` variant (not `Fallback`),
    ///   - carry a `warnings: Vec<String>` (its presence/empty-or-not
    ///     is the documented contract; populated entries are added
    ///     mid-multi-path runs),
    ///   - format with a message that mentions the offending path
    ///     via its inner `DaclError`.
    #[test]
    fn dispatch_error_dacl_variant_shape_on_apply_failure() {
        use crate::process_container_common::test_env::ScopedStateDir;
        let _scope = ScopedStateDir::new();

        // Construct a path that is guaranteed not to exist. Using a
        // tempdir + unique suffix keeps the test resilient against
        // any pre-existing junk in %TEMP%.
        let nonexistent = std::env::temp_dir()
            .join(format!("mxc-dispatcher-error-shape-{}", std::process::id()))
            .join("does-not-exist");
        let err = build_deny_only_dacl("S-1-1-0", std::slice::from_ref(&nonexistent))
            .expect_err("non-existent path should fail apply");
        match err {
            DispatchError::Dacl { error, warnings } => {
                // Shape contract: warnings is Vec<String> (possibly
                // empty for a first-path apply failure). Every entry,
                // when present, is non-empty.
                for w in &warnings {
                    assert!(!w.is_empty(), "warning entries must be non-empty");
                }
                // Inner error references the offending path. The
                // canonicalize failure may surface as either
                // `DaclError::Win32` or another path-bearing variant;
                // both must serialize to a message mentioning the path.
                let s = format!("{error}");
                assert!(
                    s.contains("does-not-exist"),
                    "inner DaclError message should mention offending path: {s}"
                );
            }
            other => panic!("expected DispatchError::Dacl, got: {other:?}"),
        }
    }

    /// `filter_paths_needing_grant` is the per-path side of the
    /// `ce7713d` optimization ("skip per-run ACE when AC SID already
    /// has access"). Direct exercise: stamp an Everyone (S-1-1-0)
    /// grant on a temp dir — Everyone is in every AppContainer
    /// token's well-known-SID set — and assert
    /// `filter_paths_needing_grant` drops the path. A tempdir without
    /// any stamp must survive the filter because %TEMP%'s shadow
    /// ACLs do not grant the well-known AC SIDs `RW_MASK`.
    #[test]
    fn filter_paths_needing_grant_drops_well_known_grant() {
        use crate::process_container_common::test_env::ScopedStateDir;
        let _scope = ScopedStateDir::new();
        let td_grant = tempfile::tempdir().expect("temp dir grant");
        let td_no_grant = tempfile::tempdir().expect("temp dir no-grant");

        // Stamp an Everyone grant on td_grant via `grant_appcontainer_access`
        // and persist it for the duration of the test by holding the
        // manager. Drop at end of scope rolls it back.
        let mut mgr = crate::mxc_common::filesystem_dacl::DaclManager::new().expect("dacl mgr");
        mgr.grant_appcontainer_access(
            "S-1-1-0",
            std::slice::from_ref(&td_grant.path().to_path_buf()),
            &[],
        )
        .expect("grant");

        let input = vec![
            td_grant.path().to_path_buf(),
            td_no_grant.path().to_path_buf(),
        ];
        let kept = filter_paths_needing_grant(input, RW_MASK);
        assert!(
            !kept.iter().any(|p| p == td_grant.path()),
            "grant-stamped path should be filtered out: kept={kept:?}"
        );
        assert!(
            kept.iter().any(|p| p == td_no_grant.path()),
            "non-stamped path should survive the filter: kept={kept:?}"
        );

        // Best-effort cleanup; Drop will also run restore().
        mgr.restore().ok();
    }

    #[test]
    fn dispatch_t1_naturally_selected_when_bc_usable() {
        // Natural T1 selection (no force). Skip when the backend isn't usable.
        // Asserts only the resolved tier; it does not exec.
        //
        // Hold ENV_LOCK and clear MXC_FORCE_TIER so a concurrent
        // `ForceTierGuard` test can't leak a forced value into `detect`.
        let _lock = {
            let lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
            // SAFETY: env-var mutation in tests; serialized by ENV_LOCK.
            unsafe {
                std::env::remove_var("MXC_FORCE_TIER");
            }
            lock
        };
        if !crate::process_container_common::base_container_runner::BaseContainerRunner::is_base_container_api_present() {
            eprintln!("skipping: BaseContainer backend not usable on this machine");
            return;
        }
        let req = test_request(empty_policy());
        let d = dispatch_with_fallback(&req, None).expect("dispatch should succeed");
        assert!(matches!(d.tier, IsolationTier::BaseContainer));
    }

    #[test]
    fn dispatch_falls_back_to_t3_when_bc_unusable() {
        // The core regression: a present-but-disabled BaseContainer must not be
        // built. Forcing usable=false, dispatch resolves to Tier 3 directly so
        // the doomed BaseContainerRunner is never constructed.
        let _g = BcUsableGuard::set(false);
        let req = test_request(empty_policy());
        let d = dispatch_with_fallback(&req, None).expect("dispatch should succeed");
        assert!(matches!(d.tier, IsolationTier::AppContainerDacl));
    }

    // -------------------------------------------------------------------
    // Streaming dispatch (`select_backend_with_fallback` /
    // `spawn_with_fallback`) — issue #643.
    //
    // These assert the *shared* selector both surfaces call constructs the
    // backend variant matching the chosen tier and attaches a DaclManager
    // exactly when the tier needs host-ACE augmentation. Because the streaming
    // path (`spawn_with_fallback`) and the run-to-completion path
    // (`dispatch_with_fallback`) now both go through this one function, they
    // can no longer disagree on tier selection the way the old two-tier
    // streaming path did.
    // -------------------------------------------------------------------

    #[test]
    fn select_backend_t1_builds_base_container_no_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::BaseContainer);
        let req = test_request(empty_policy());
        let plan = select_backend_with_fallback(&req, None).expect("T1 selection should succeed");
        let (backend, dacl, tier) = (plan.backend, plan.dacl_manager, plan.tier);
        assert!(matches!(tier, IsolationTier::BaseContainer));
        assert!(
            matches!(backend, SelectedBackend::BaseContainer(_)),
            "T1 must construct the BaseContainer backend, not AppContainer"
        );
        assert!(
            dacl.is_none(),
            "T1 delegates deny to the native API; no host DACL"
        );
    }

    #[test]
    fn select_backend_t2_no_deny_builds_appcontainer_no_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerBfs);
        let req = test_request(empty_policy());
        let plan = select_backend_with_fallback(&req, None).expect("T2 selection should succeed");
        let (backend, dacl, tier) = (plan.backend, plan.dacl_manager, plan.tier);
        assert!(matches!(tier, IsolationTier::AppContainerBfs));
        assert!(matches!(backend, SelectedBackend::AppContainer(_)));
        assert!(
            dacl.is_none(),
            "T2 without deniedPaths needs no host DACL (BFS handles it in-runner)"
        );
    }

    #[test]
    fn select_backend_t2_with_deny_builds_appcontainer_with_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerBfs);
        let (policy, _tmp) = policy_with_denied_temp();
        let req = test_request(policy);
        let plan =
            select_backend_with_fallback(&req, None).expect("T2+deny selection should succeed");
        let (backend, dacl, tier) = (plan.backend, plan.dacl_manager, plan.tier);
        assert!(matches!(tier, IsolationTier::AppContainerBfs));
        assert!(matches!(backend, SelectedBackend::AppContainer(_)));
        assert!(
            dacl.is_some(),
            "T2 deniedPaths require deny ACEs via a DaclManager"
        );
    }

    #[test]
    fn select_backend_t2_non_capture_deny_still_rejects_denied_paths() {
        // Item 15 regression: on the BFS tier a *non-capture* deniedPaths
        // request must NOT be broadened to honor deniedPaths via a host DACL.
        // The selected runner is left un-marked (no `with_external_denied_paths`),
        // so its `validate` still rejects deniedPaths exactly as before the
        // guarded-capture fallback existed. (The deny DACL is still built,
        // preserving the has-DACL selection asserted above; only the runner's
        // acceptance is gated.)
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerBfs);
        let (policy, _tmp) = policy_with_denied_temp();
        let req = test_request(policy);
        let plan =
            select_backend_with_fallback(&req, None).expect("T2+deny selection should succeed");
        let (backend, tier) = (plan.backend, plan.tier);
        assert!(matches!(tier, IsolationTier::AppContainerBfs));

        let error = backend
            .validate(&req)
            .expect_err("non-capture deniedPaths on the BFS tier must be rejected");
        assert!(
            error.error_message.contains("deniedPaths"),
            "expected a deniedPaths rejection, got: {}",
            error.error_message
        );
    }

    #[test]
    fn select_backend_t3_builds_appcontainer_with_dacl() {
        let _g = ForceTierGuard::set_tier(IsolationTier::AppContainerDacl);
        let (policy, _tmp) = policy_with_rw_temp();
        let req = test_request(policy);
        let plan = select_backend_with_fallback(&req, None).expect("T3 selection should succeed");
        let (backend, dacl, tier) = (plan.backend, plan.dacl_manager, plan.tier);
        assert!(matches!(tier, IsolationTier::AppContainerDacl));
        assert!(matches!(backend, SelectedBackend::AppContainer(_)));
        assert!(
            dacl.is_some(),
            "T3 always applies grant ACEs via a DaclManager"
        );
    }

    #[test]
    fn select_backend_streaming_falls_back_to_t3_when_bc_unusable() {
        // Streaming analog of `dispatch_falls_back_to_t3_when_bc_unusable` and
        // the direct regression guard for issue #643: with BaseContainer
        // present-but-unusable and BFS not compiled in, the shared selector the
        // streaming path calls must still resolve to Tier 3 (AppContainer +
        // DACL) — where the old two-tier streaming path instead failed closed
        // with the "bfscfg.exe is not available" error.
        let _g = BcUsableGuard::set(false);
        let req = test_request(empty_policy());
        let plan = select_backend_with_fallback(&req, None).expect("selection should succeed");
        let (backend, dacl, tier) = (plan.backend, plan.dacl_manager, plan.tier);
        assert!(matches!(tier, IsolationTier::AppContainerDacl));
        assert!(matches!(backend, SelectedBackend::AppContainer(_)));
        assert!(dacl.is_some());
    }

    /// `DaclGuardedProcess` must forward every `SandboxProcess` method to the
    /// wrapped handle unchanged; the guard is inert until drop (when it restores
    /// host ACEs, after `inner` has torn the child down — enforced by field
    /// order, documented on the struct).
    #[test]
    fn dacl_guarded_process_delegates_to_inner() {
        use crate::mxc_common::sandbox_process::SandboxProcess;
        use crate::process_container_common::test_env::ScopedStateDir;
        use std::io::{Read, Write};
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        /// Minimal fake recording which delegated calls arrived and returning
        /// distinctive canned values.
        #[derive(Default)]
        struct FakeProcess {
            stdin_taken: bool,
            native_stdio_calls: Arc<AtomicUsize>,
            killed: bool,
            output_metadata: crate::mxc_common::models::SandboxOutputMetadata,
        }
        impl SandboxProcess for FakeProcess {
            fn take_stdin(&mut self) -> Option<Box<dyn Write + Send>> {
                self.stdin_taken = true;
                None
            }
            fn take_stdout(&mut self) -> Option<Box<dyn Read + Send>> {
                None
            }
            fn take_native_stdio(
                &mut self,
            ) -> std::io::Result<Option<crate::mxc_common::sandbox_process::NativeStdio>>
            {
                self.native_stdio_calls.fetch_add(1, Ordering::SeqCst);
                Ok(None)
            }
            fn take_stderr(&mut self) -> Option<Box<dyn Read + Send>> {
                None
            }
            fn try_wait(&mut self) -> std::io::Result<Option<i32>> {
                Ok(Some(7))
            }
            fn id(&self) -> u32 {
                4242
            }
            fn kill(&mut self) -> std::io::Result<()> {
                self.killed = true;
                Err(std::io::Error::other("ordinary kill"))
            }
            fn kill_for_timeout(&mut self) -> std::io::Result<()> {
                Ok(())
            }
            fn wait(&mut self) -> std::io::Result<i32> {
                Ok(7)
            }
            fn output_metadata(&self) -> Option<&crate::mxc_common::models::SandboxOutputMetadata> {
                Some(&self.output_metadata)
            }
        }

        let _scope = ScopedStateDir::new();
        // A manager with no ACEs applied: `Drop`/`restore` is a no-op, so the
        // test only exercises delegation, not real host-ACE mutation.
        let dacl_manager = DaclManager::new().expect("dacl mgr");
        let native_stdio_calls = Arc::new(AtomicUsize::new(0));
        let mut guarded = DaclGuardedProcess {
            inner: Box::new(FakeProcess {
                native_stdio_calls: Arc::clone(&native_stdio_calls),
                ..FakeProcess::default()
            }),
            _dacl_manager: dacl_manager,
        };

        assert_eq!(guarded.id(), 4242, "id() must delegate");
        assert!(
            matches!(guarded.try_wait(), Ok(Some(7))),
            "try_wait() must delegate"
        );
        assert!(matches!(guarded.wait(), Ok(7)), "wait() must delegate");
        assert!(guarded.take_stdin().is_none(), "take_stdin() must delegate");
        assert!(
            guarded.take_native_stdio().unwrap().is_none(),
            "take_native_stdio() must delegate"
        );
        assert_eq!(native_stdio_calls.load(Ordering::SeqCst), 1);
        assert!(guarded.kill().is_err(), "kill() must delegate");
        assert!(
            guarded.kill_for_timeout().is_ok(),
            "kill_for_timeout() must delegate"
        );
        assert!(
            guarded.output_metadata().is_some(),
            "output_metadata() must delegate"
        );
    }
}