mxc-sdk 1.2.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use super::*;
use crate::core_modules::process_security_environment_policy_result::experimental_process_security_environment_policy_result as layout;
use crate::mxc_common::policy_failures::{PolicyFailureDetail, MAX_RESULTS};
use std::cell::{Cell, RefCell};
use windows::Win32::Foundation::{E_FAIL, S_OK};
use windows::Win32::System::Com::CoTaskMemAlloc;

#[path = "policy_preparation_backend_tests.rs"]
mod preparation;

const POLICY_DENIED: HRESULT = HRESULT(0x800704ecu32 as i32);
const POLICY_DENIED_MESSAGE: &str = concat!(
    "failed to create the process security environment: ",
    "CreateProcessSecurityEnvironment failed (HRESULT = 0x800704EC). ",
    "Windows blocked creation of the requested sandbox because of an IT-managed policy rule ",
    "(ERROR_ACCESS_DISABLED_BY_POLICY, 1260). Review the requested sandbox permissions or ",
    "contact your system administrator.",
);
/// An unrelated caller flag that policy-result capture must preserve.
const CALLER_FLAG: u32 = 0x40;

struct FakeState {
    status: HRESULT,
    handle: bool,
    support_status: HRESULT,
    support_flags: u64,
    getter_status: HRESULT,
    report: PolicyFailureResult,
    payload_override: Option<Vec<u8>>,
    reported_size: Option<u32>,
    flags: Vec<u32>,
    specifications: Vec<Vec<u8>>,
    calls: Vec<&'static str>,
    threads: Vec<std::thread::ThreadId>,
    frees: usize,
    closes: usize,
    capture_sources: crate::learning_mode_windows::LearningModeTraceSources,
}

impl Default for FakeState {
    fn default() -> Self {
        Self {
            status: POLICY_DENIED,
            handle: false,
            support_status: S_OK,
            support_flags: EXPERIMENTAL_PSE_SUPPORT_POLICY_RESULT,
            getter_status: S_OK,
            report: PolicyFailureResult {
                outcome: PolicyFailureResult::OUTCOME_BLOCKED,
                details: vec![PolicyFailureDetail {
                    failure_class: PolicyFailureDetail::CLASS_FILESYSTEM,
                    failure_reason: PolicyFailureDetail::REASON_ACCESS_EXCEEDS_CEILING,
                    required_action: PolicyFailureDetail::ACTION_RESTRICT_FILESYSTEM_ACCESS,
                    resource_kind: PolicyFailureDetail::RESOURCE_KIND_PATH,
                    value_kind: PolicyFailureDetail::VALUE_KIND_ACCESS,
                    flags: PolicyFailureDetail::FLAG_HAS_ACTIONABLE_DETAILS
                        | PolicyFailureDetail::FLAG_RESOURCE_COMPLETE,
                    requested_value: PolicyFailureDetail::ACCESS_READ_WRITE,
                    required_value: PolicyFailureDetail::ACCESS_READ_ONLY,
                    resource: Some(r"C:\work".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            },
            payload_override: None,
            reported_size: None,
            flags: Vec::new(),
            specifications: Vec::new(),
            calls: Vec::new(),
            threads: Vec::new(),
            frees: 0,
            closes: 0,
            capture_sources: crate::learning_mode_windows::LearningModeTraceSources::AccessOnly,
        }
    }
}

thread_local! {
    static STATE: RefCell<FakeState> = RefCell::new(FakeState::default());
    static INJECTED_API: Cell<Option<SecurityEnvironmentApi>> = const { Cell::new(None) };
}

pub(super) fn injected_api() -> Option<SecurityEnvironmentApi> {
    INJECTED_API.with(Cell::get)
}

pub(super) fn injected_capture_trace_sources(
) -> Option<crate::learning_mode_windows::LearningModeTraceSources> {
    injected_api().map(|_| STATE.with(|state| state.borrow().capture_sources))
}

pub(super) fn record_injected_creation_effect(effect: &'static str) {
    if injected_api().is_some() {
        STATE.with(|state| state.borrow_mut().calls.push(effect));
    }
}

pub(super) fn policy_buffer_freed(_: *mut u8) {
    STATE.with(|state| state.borrow_mut().frees += 1);
}

fn reset() -> SecurityEnvironmentApi {
    STATE.with(|state| *state.borrow_mut() = FakeState::default());
    let mut api = SecurityEnvironmentApi::from_raw_parts(create, query, close);
    api.get_last_policy_result = Some(get_result);
    api
}

unsafe extern "system" fn query(flags: *mut u64) -> HRESULT {
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.calls.push("support");
        // SAFETY: the tested API passes valid output storage.
        unsafe { *flags = state.support_flags };
        state.support_status
    })
}

unsafe extern "system" fn create(
    specification: *const c_void,
    size: u32,
    flags: u32,
    output: *mut HANDLE,
) -> HRESULT {
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.calls.push("create");
        state.threads.push(std::thread::current().id());
        state.flags.push(flags);
        // SAFETY: the tested API supplies the complete input buffer.
        state.specifications.push(unsafe {
            std::slice::from_raw_parts(specification.cast::<u8>(), size as usize).to_vec()
        });
        if state.handle {
            // SAFETY: fake output storage is provided by the tested API.
            unsafe { *output = HANDLE(0x1000usize as *mut c_void) };
        }
        state.status
    })
}

struct ApiScope(Option<SecurityEnvironmentApi>);

impl Drop for ApiScope {
    fn drop(&mut self) {
        INJECTED_API.with(|slot| slot.set(self.0));
    }
}

unsafe extern "system" fn version(_: u32, available: *mut u8, minor: *mut u32) -> HRESULT {
    // SAFETY: native version-query outputs are valid for this fake.
    unsafe {
        *available = 1;
        *minor = 3;
    }
    S_OK
}

struct UnusedCapture;

impl crate::process_container_common::base_container_runner::CaptureSessionFactory
    for UnusedCapture
{
    fn trace_sources(
        &self,
    ) -> Result<crate::learning_mode_windows::LearningModeTraceSources, LearningModeError> {
        Ok(crate::learning_mode_windows::LearningModeTraceSources::AccessOnly)
    }

    fn begin(
        &self,
        _: &[u8],
        _: u32,
    ) -> Result<
        Box<dyn crate::process_container_common::base_container_runner::CaptureSessionOps>,
        CreationError,
    > {
        Err(LearningModeError::HResultCall {
            function: "unexpected test capture",
            code: E_FAIL.0,
        }
        .into())
    }
}

fn launch_fixed_fixture(
    launch: crate::process_container_common::base_container_runner::BaseProcessLaunch<'_>,
) -> windows_core::Result<()> {
    use windows::Win32::System::Threading::{
        CreateProcessW, CREATE_NO_WINDOW, EXTENDED_STARTUPINFO_PRESENT, PROCESS_CREATION_FLAGS,
        STARTUPINFOW,
    };
    use windows_core::{PCWSTR, PWSTR};
    assert_eq!(launch.startup.environment_for_test().0 as usize, 0x1000);
    assert_ne!(launch.creation_flags.0 & CREATE_NO_WINDOW.0, 0);
    assert_eq!(
        String::from_utf16(launch.command_line)
            .unwrap()
            .trim_end_matches('\0'),
        "cmd.exe /d /c echo mxc-policy-child",
    );
    STATE.with(|state| state.borrow_mut().calls.push("launch"));
    let mut startup = launch.startup.startup_info().StartupInfo;
    startup.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
    // The native environment is fake. Execute only the fixed trusted fixture,
    // without the fake PSEC attribute, retaining pipes/suspension/job cleanup.
    unsafe {
        CreateProcessW(
            PCWSTR::null(),
            Some(PWSTR(launch.command_line.as_mut_ptr())),
            None,
            None,
            launch.inherit_handles,
            PROCESS_CREATION_FLAGS(launch.creation_flags.0 & !EXTENDED_STARTUPINFO_PRESENT.0),
            launch
                .environment
                .map(|block| block.as_ptr().cast::<c_void>()),
            PCWSTR(launch.working_directory.as_ptr()),
            &startup,
            launch.process_information,
        )
    }
}

#[test]
fn merged_output_uses_independent_inheritable_handles_at_launch() {
    use crate::mxc_common::logger::{Logger, Mode};
    use crate::mxc_common::sandbox_process::{SandboxBackend, StdioMode};
    use crate::process_container_common::base_container_runner::{
        BaseContainerRunner, BaseProcessLaunch,
    };
    use crate::process_container_common::test_env::CaptureCapabilityGuard;
    use std::sync::Arc;
    use windows::Win32::Foundation::{GetHandleInformation, HANDLE_FLAG_INHERIT};

    fn launch(launch: BaseProcessLaunch<'_>) -> windows_core::Result<()> {
        let startup = &launch.startup.startup_info().StartupInfo;
        assert_ne!(startup.hStdOutput, startup.hStdError);
        for handle in [startup.hStdOutput, startup.hStdError] {
            let mut flags = 0;
            // SAFETY: The runner owns both output handles throughout launch.
            unsafe { GetHandleInformation(handle, &mut flags) }?;
            assert_ne!(flags & HANDLE_FLAG_INHERIT.0, 0);
        }
        launch_fixed_fixture(launch)
    }

    let _host = CaptureCapabilityGuard::set(true, true);
    let mut api = reset();
    api.version_support = Some(version);
    let _scope = ApiScope(INJECTED_API.with(|slot| slot.replace(Some(api))));
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.status = S_OK;
        state.handle = true;
    });
    let request = parsed_request(
        r#"{"version":"1.0.0","containment":"processcontainer",
            "process":{"commandLine":"cmd.exe /d /c echo mxc-policy-child","timeout":5000}}"#,
    );
    let mut runner = BaseContainerRunner::with_capture_factory(Arc::new(UnusedCapture))
        .with_process_launcher(launch);
    let mut process = runner
        .spawn(
            &request,
            &mut Logger::new(Mode::Buffer),
            StdioMode::MergedPipes,
        )
        .expect("spawn merged output fixture");
    assert!(process.take_stderr().is_none());
    assert_eq!(process.wait().expect("wait for fixture"), 0);
}

fn parsed_request(json: &str) -> crate::mxc_common::models::ExecutionRequest {
    use crate::mxc_common::logger::{Logger, Mode};
    use crate::mxc_common::state_aware_request::MxcRequest;
    match crate::mxc_common::config_parser::load_mxc_request_from_json(
        json,
        &mut Logger::new(Mode::Buffer),
    )
    .unwrap()
    {
        MxcRequest::OneShot(request) => request,
        MxcRequest::StateAware(_) => panic!("expected a create-and-run request"),
    }
}

fn prepare_candidate(
    original: &str,
    failures: &PolicyFailures,
) -> crate::v1::dev::PreparedPolicyRequest {
    fn resource_calls(state: &FakeState) -> Vec<&'static str> {
        state
            .calls
            .iter()
            .copied()
            .filter(|call| matches!(*call, "create" | "get" | "launch" | "close"))
            .collect()
    }
    let before = STATE.with(|state| {
        let state = state.borrow();
        (
            state.specifications.len(),
            resource_calls(&state),
            state.frees,
            state.closes,
        )
    });
    let prepared = crate::v1::dev::prepare_policy_json(original, failures, Default::default())
        .expect("prepare without creation or workload execution");
    STATE.with(|state| {
        let state = state.borrow();
        assert_eq!(state.specifications.len(), before.0);
        assert_eq!(resource_calls(&state), before.1);
        assert_eq!(state.frees, before.2);
        assert_eq!(state.closes, before.3);
    });
    assert_eq!(
        crate::v1::dev::PreparedPolicyRequest::from_json(&prepared.to_json().unwrap()).unwrap(),
        prepared,
    );
    prepared
}

#[test]
fn policy_preparation_app_loop_merges_observations_then_accepts_strict_creation() {
    use crate::mxc_common::logger::{Logger, Mode};
    use crate::mxc_common::sandbox_process::{SandboxBackend, StdioMode};
    use crate::process_container_common::base_container_runner::BaseContainerRunner;
    use crate::process_container_common::test_env::CaptureCapabilityGuard;
    use crate::v1::dev::PolicyChangeOperation;
    use std::io::Read;
    use std::sync::Arc;

    let _host = CaptureCapabilityGuard::set(true, true);
    let mut api = reset();
    api.version_support = Some(version);
    let _scope = ApiScope(INJECTED_API.with(|slot| slot.replace(Some(api))));
    let directory = tempfile::tempdir().unwrap();
    let original = serde_json::json!({
        "version": "1.0.0",
        "containerId": "policy-preparation-fixture",
        "containment": "processcontainer",
        "process": {
            "commandLine": "cmd.exe /d /c echo mxc-policy-child",
            "cwd": directory.path(), "timeout": 5000,
        },
        "processContainer": { "capabilities": ["registryRead", "registryWrite"] },
    })
    .to_string();
    let mut selected = original.clone();
    let mut runner = BaseContainerRunner::with_capture_factory(Arc::new(UnusedCapture))
        .with_process_launcher(launch_fixed_fixture);
    let mut failures = PolicyFailures::default();
    for (index, capability) in ["registryRead", "registryWrite"].into_iter().enumerate() {
        STATE.with(|state| {
            let mut state = state.borrow_mut();
            state.report.details = vec![PolicyFailureDetail {
                failure_class: PolicyFailureDetail::CLASS_FILESYSTEM,
                failure_reason: PolicyFailureDetail::REASON_CAPABILITY_NOT_ALLOWED,
                required_action: PolicyFailureDetail::ACTION_REMOVE_CAPABILITY,
                resource_kind: PolicyFailureDetail::RESOURCE_KIND_CAPABILITY,
                flags: PolicyFailureDetail::FLAG_HAS_ACTIONABLE_DETAILS
                    | PolicyFailureDetail::FLAG_RESOURCE_COMPLETE,
                resource: Some(capability.to_string()),
                ..Default::default()
            }];
        });
        let request = parsed_request(&selected);
        let error = match runner.spawn(&request, &mut Logger::new(Mode::Buffer), StdioMode::Pipes) {
            Err(error) => error,
            Ok(_) => panic!("a refusal must not launch a workload"),
        };
        let error = crate::mxc_engine::Error::from(error.into_mxc_error());
        let next = PolicyFailures::from_error(&error).unwrap().unwrap();
        assert_eq!(
            next.results.len(),
            1,
            "strict creation returns only its own observation"
        );
        assert_eq!(
            error.native_code.as_deref(),
            Some(PolicyFailures::NATIVE_CODE_POLICY_BLOCKED)
        );
        failures = failures.merged_with(&next).unwrap();
        assert_eq!(failures.results.len(), index + 1);
        STATE.with(|state| {
            let state = state.borrow();
            assert_eq!(state.specifications.len(), index + 1);
            assert!(!state.calls.contains(&"launch"));
        });
        let prepared = prepare_candidate(&original, &failures);
        assert_eq!(prepared.changes.len(), 1);
        let change = &prepared.changes[0];
        assert_eq!(change.operation, PolicyChangeOperation::Replace);
        assert_eq!(change.path, "/processContainer/capabilities");
        assert_eq!(
            change.before,
            serde_json::json!(["registryRead", "registryWrite"])
        );
        assert_eq!(
            change.after,
            if index == 0 {
                serde_json::json!(["registryWrite"])
            } else {
                serde_json::json!([])
            },
        );
        selected = prepared.request_json; // The caller explicitly accepts the checked capability removals.
    }
    let request = parsed_request(&selected);
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.status = S_OK;
        state.handle = true;
    });
    let mut process = runner
        .spawn(&request, &mut Logger::new(Mode::Buffer), StdioMode::Pipes)
        .expect("submit the accepted candidate through ordinary strict creation");
    let mut stdout = String::new();
    process
        .take_stdout()
        .unwrap()
        .read_to_string(&mut stdout)
        .unwrap();
    assert_eq!(stdout.trim(), "mxc-policy-child");
    assert_eq!(process.wait().unwrap(), 0);
    assert!(process.warnings().is_empty());
    drop(process);
    STATE.with(|state| {
        let state = state.borrow();
        assert_eq!(state.specifications.len(), 3);
        assert_eq!(
            state.calls.iter().filter(|call| **call == "launch").count(),
            1
        );
        assert_eq!(state.closes, 1);
        assert_eq!(state.frees, 2);
        use crate::core_modules::process_security_environment_spec::process_security_environment_layout as psec;
        for (index, bytes) in state.specifications.iter().enumerate() {
            let spec = psec::root_as_process_security_environment(bytes).unwrap();
            let expected = ["registryRead,registryWrite", "registryWrite"].get(index);
            assert_eq!(spec.capabilities(), expected.copied());
        }
    });
}

unsafe extern "system" fn close(_: HANDLE) {
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.calls.push("close");
        state.closes += 1;
    });
}

unsafe extern "system" fn get_result(
    version: u32,
    size: *mut u32,
    output: *mut *mut u8,
) -> HRESULT {
    assert_eq!(version, POLICY_RESULT_VERSION);
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.calls.push("get");
        state.threads.push(std::thread::current().id());
        let native = PolicyResult::from(&state.report);
        let mut builder = flatbuffers::FlatBufferBuilder::new();
        let root = native.pack(&mut builder);
        layout::finish_policy_result_buffer(&mut builder, root);
        let bytes = state
            .payload_override
            .as_deref()
            .unwrap_or(builder.finished_data());
        // SAFETY: this fake implements the native owned-allocation contract.
        let allocation = unsafe { CoTaskMemAlloc(bytes.len()) }.cast::<u8>();
        assert!(!allocation.is_null());
        unsafe {
            std::ptr::copy_nonoverlapping(bytes.as_ptr(), allocation, bytes.len());
            *output = allocation;
            *size = state.reported_size.unwrap_or(bytes.len() as u32);
        }
        state.getter_status
    })
}

#[test]
fn policy_failures_native_invalid_payloads_stop_and_free_without_text_specifics() {
    for fault in [
        "identifier",
        "table",
        "version",
        "resourceFlags",
        "byteLimit",
        "resourceLimit",
        "zeroSize",
    ] {
        let api = reset();
        STATE.with(|state| {
            let mut state = state.borrow_mut();
            match fault {
                "identifier" => state.payload_override = Some(vec![0; 8]),
                "table" => {
                    let mut bytes = vec![0; 8];
                    bytes[4..].copy_from_slice(b"PSEP");
                    state.payload_override = Some(bytes);
                }
                "version" => {
                    state.report.minimum_reader_version =
                        PolicyFailureResult::MINIMUM_READER_VERSION + 1
                }
                "resourceFlags" => {
                    state.report.details[0].flags = PolicyFailureDetail::FLAG_HAS_ACTIONABLE_DETAILS
                }
                "byteLimit" => state.reported_size = Some(MAX_RESULT_BYTES as u32 + 1),
                "resourceLimit" => state.report.details[0].resource = Some("A".repeat(32_768)),
                "zeroSize" => state.reported_size = Some(0),
                _ => unreachable!(),
            }
        });
        let failure = api
            .create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
            .unwrap_err();
        let error = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
        assert!(
            PolicyFailures::from_error(&error).unwrap().is_none(),
            "{fault}"
        );
        assert!(
            error
                .details
                .as_deref()
                .unwrap()
                .get("policyResultUnavailable")
                .is_some(),
            "{fault}"
        );
        assert_eq!(
            error.native_code.as_deref(),
            Some(PolicyFailures::NATIVE_CODE_POLICY_BLOCKED)
        );
        assert_eq!(error.message, POLICY_DENIED_MESSAGE, "{fault}");
        STATE.with(|state| assert_eq!(state.borrow().frees, 1, "{fault}"));
    }
}

#[test]
fn policy_failures_native_maximum_byte_count_remains_usable() {
    let api = reset();
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        let native = PolicyResult::from(&state.report);
        let mut builder = flatbuffers::FlatBufferBuilder::new();
        let root = native.pack(&mut builder);
        layout::finish_policy_result_buffer(&mut builder, root);
        let mut bytes = builder.finished_data().to_vec();
        bytes.resize(MAX_RESULT_BYTES, 0);
        state.payload_override = Some(bytes);
    });
    let failure = api
        .create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
        .unwrap_err();
    let error = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
    assert_eq!(
        PolicyFailures::from_error(&error)
            .unwrap()
            .unwrap()
            .results
            .len(),
        1
    );
    STATE.with(|state| assert_eq!(state.borrow().frees, 1));
}

#[test]
fn policy_failures_from_malformed_error_details_use_one_canonical_error() {
    let api = reset();
    let failure = api
        .create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
        .unwrap_err();
    let valid = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
    let stored = valid.details.as_deref().unwrap()["policyFailures"].clone();
    let mut wrong_version = stored.clone();
    wrong_version["formatVersion"] = 2.into();
    let mut over_limit = stored.clone();
    let result = stored["results"][0].clone();
    over_limit["results"] = vec![result; MAX_RESULTS + 2].into();
    for (case, policy_failures) in [
        ("formatVersion", wrong_version),
        ("resultLimit", over_limit),
        ("shape", serde_json::json!([])),
    ] {
        let mut error = valid.clone();
        error.details = Some(Box::new(
            serde_json::json!({ "policyFailures": policy_failures }),
        ));
        let malformed = PolicyFailures::from_error(&error).unwrap_err();
        assert_eq!(
            malformed.code,
            crate::mxc_engine::ErrorCode::BackendError,
            "{case}"
        );
        assert_eq!(
            malformed.message, "native policy failures are malformed",
            "{case}"
        );
    }
}

#[test]
fn policy_failures_caller_merge_keeps_a_complete_terminal_batch() {
    let api = reset();
    let mut prior = PolicyFailures::default();
    for index in 0..MAX_RESULTS {
        let mut result = STATE.with(|state| state.borrow().report.clone());
        result.details[0].resource = Some(format!(r"C:\history\{index}"));
        prior.append(result);
    }
    prior.validate().unwrap();
    let failure = api
        .create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
        .unwrap_err();
    let error = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
    assert!(error
        .details
        .as_deref()
        .unwrap()
        .get("policyFeedbackError")
        .is_none());
    assert_eq!(
        error.native_code.as_deref(),
        Some(PolicyFailures::NATIVE_CODE_POLICY_BLOCKED)
    );
    assert_eq!(
        error.operation.as_deref(),
        Some("CreateProcessSecurityEnvironment")
    );
    let current = PolicyFailures::from_error(&error).unwrap().unwrap();
    assert_eq!(current.results.len(), 1);
    let complete = prior.merged_with(&current).unwrap();
    assert_eq!(complete.results.len(), MAX_RESULTS + 1);
    assert_eq!(&complete.results[..MAX_RESULTS], &prior.results);
    assert_eq!(
        PolicyFailures::from_json(&complete.to_json().unwrap()).unwrap(),
        complete
    );
    assert!(complete.validate().is_err());
    STATE.with(|state| assert_eq!(state.borrow().frees, 1));
}

#[test]
fn policy_preparation_capture_removal_is_authorable_and_strictly_submitted() {
    use crate::core_modules::process_security_environment_spec::process_security_environment_layout as psec;
    use crate::mxc_common::logger::{Logger, Mode};
    use crate::mxc_common::sandbox_process::{SandboxBackend, StdioMode};
    use crate::process_container_common::base_container_runner::BaseContainerRunner;
    use crate::process_container_common::test_env::CaptureCapabilityGuard;
    use std::{io::Read, sync::Arc};

    let _host = CaptureCapabilityGuard::set(true, true);
    let mut api = reset();
    api.version_support = Some(version);
    let _scope = ApiScope(INJECTED_API.with(|slot| slot.replace(Some(api))));
    STATE.with(|state| {
        let mut state = state.borrow_mut();
        state.status = S_OK;
        state.handle = true;
    });
    let mut failures = PolicyFailures::default();
    for capability in ["learningModeLogging", "permissiveLearningMode"] {
        failures.append(PolicyFailureResult {
            outcome: PolicyFailureResult::OUTCOME_BLOCKED,
            details: vec![PolicyFailureDetail {
                failure_class: PolicyFailureDetail::CLASS_ENFORCEMENT_MODE,
                failure_reason: PolicyFailureDetail::REASON_CAPABILITY_NOT_ALLOWED,
                required_action: PolicyFailureDetail::ACTION_REMOVE_CAPABILITY,
                resource_kind: PolicyFailureDetail::RESOURCE_KIND_CAPABILITY,
                flags: PolicyFailureDetail::FLAG_HAS_ACTIONABLE_DETAILS
                    | PolicyFailureDetail::FLAG_RESOURCE_COMPLETE,
                resource: Some(capability.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        });
    }
    let directory = tempfile::tempdir().unwrap();
    let original = serde_json::json!({
        "version": "1.1.0-alpha",
        "containment": "process",
        "process": {
            "commandLine": "cmd.exe /d /c echo mxc-policy-child",
            "cwd": directory.path(), "timeout": 5000,
        },
        "processContainer": {
            "learningMode": true,
            "captureDenials": {
                "mode": "allow", "retainEtl": true,
                "outputPath": directory.path().join("capture.json"),
            }
        }
    })
    .to_string();
    let prepared = prepare_candidate(&original, &failures);
    let candidate: serde_json::Value = serde_json::from_str(&prepared.request_json).unwrap();
    assert_eq!(candidate["version"], "1.1.0-alpha");
    assert_eq!(candidate["processContainer"]["learningMode"], false);
    assert!(candidate["processContainer"]
        .get("captureDenials")
        .is_none());
    assert!(candidate["processContainer"].get("capabilities").is_none());
    assert!(prepared.changes.iter().any(|change| {
        change.path == "/processContainer/captureDenials"
            && change.operation == crate::v1::dev::PolicyChangeOperation::Remove
            && change.before.is_object()
            && change.after.is_null()
    }));
    let request = parsed_request(&prepared.request_json);
    let mut runner = BaseContainerRunner::with_capture_factory(Arc::new(UnusedCapture))
        .with_process_launcher(launch_fixed_fixture);
    let mut process = runner
        .spawn(&request, &mut Logger::new(Mode::Buffer), StdioMode::Pipes)
        .unwrap();
    let mut stdout = String::new();
    process
        .take_stdout()
        .unwrap()
        .read_to_string(&mut stdout)
        .unwrap();
    assert_eq!(stdout.trim(), "mxc-policy-child");
    assert_eq!(process.wait().unwrap(), 0);
    drop(process);
    assert_eq!(
        parsed_request(&original)
            .policy
            .capture_denials
            .unwrap()
            .mode,
        crate::mxc_common::models::CaptureDenialsMode::Allow
    );
    STATE.with(|state| {
        let state = state.borrow();
        assert_eq!(state.specifications.len(), 1);
        let specification =
            psec::root_as_process_security_environment(&state.specifications[0]).unwrap();
        assert_eq!(specification.capabilities(), None);
        assert_eq!(
            state.calls.iter().filter(|call| **call == "launch").count(),
            1
        );
        assert_eq!(state.closes, 1);
    });
}

#[test]
fn policy_failures_native_capture_preserves_data_status_and_cleanup_not_prose() {
    let api = reset();
    STATE.with(|state| state.borrow_mut().handle = true);
    let error = api
        .create_with_diagnostics(b"spec", CALLER_FLAG)
        .unwrap_err();
    let rendered = format!("{error:?}");
    for resource in [r"C:\work", r"C:\\work"] {
        assert!(!rendered.contains(resource), "{rendered}");
    }
    assert!(rendered.contains("<redacted>"), "{rendered}");
    let error = crate::mxc_engine::Error::from(error.response(false).into_mxc_error());
    let failures = PolicyFailures::from_error(&error).unwrap().unwrap();
    assert_eq!(
        error.operation.as_deref(),
        Some("CreateProcessSecurityEnvironment")
    );
    assert_eq!(
        error.native_code.as_deref(),
        Some(PolicyFailures::NATIVE_CODE_POLICY_BLOCKED)
    );
    assert_eq!(error.message, POLICY_DENIED_MESSAGE);
    assert_eq!(
        failures.results[0].details[0].resource.as_deref(),
        Some(r"C:\work")
    );
    STATE.with(|state| {
        let state = state.borrow();
        assert_eq!(
            state.calls.iter().filter(|call| **call == "create").count(),
            1
        );
        assert!(
            state.calls.iter().position(|call| *call == "get").unwrap()
                < state
                    .calls
                    .iter()
                    .position(|call| *call == "close")
                    .unwrap()
        );
        assert_eq!(
            state.flags,
            [CALLER_FLAG | EXPERIMENTAL_PROCESS_SECURITY_ENVIRONMENT_FLAG_CAPTURE_POLICY_RESULT]
        );
        assert_eq!(state.frees, 1);
        assert_eq!(state.closes, 1);
        assert!(state
            .threads
            .iter()
            .all(|id| *id == std::thread::current().id()));
    });
}

#[test]
fn policy_failures_malformed_native_resource_is_unavailable_and_cannot_prepare() {
    let _host =
        crate::process_container_common::test_env::PolicyCapabilityGuard::set(true, true, true);
    for path_count in [false, true] {
        let mut api = reset();
        api.version_support = Some(version);
        let _scope = ApiScope(INJECTED_API.with(|slot| slot.replace(Some(api))));
        STATE.with(|state| {
            let mut state = state.borrow_mut();
            state.handle = true;
            let mut native = PolicyResult::from(&state.report);
            let detail = &mut native.details.as_mut().unwrap()[0];
            detail.resource = Some(vec![0xd800]);
            if path_count {
                detail.failure_reason = layout::FailureReason::RequestPathLimit;
                detail.required_action = layout::RequiredAction::ReducePathCount;
                detail.resource_kind = layout::ResourceKind::None;
                detail.value_kind = layout::ValueKind::PathCount;
            }
            let mut builder = flatbuffers::FlatBufferBuilder::new();
            let root = native.pack(&mut builder);
            layout::finish_policy_result_buffer(&mut builder, root);
            state.payload_override = Some(builder.finished_data().to_vec());
        });
        let error = api
            .create_with_diagnostics(b"spec", CALLER_FLAG)
            .unwrap_err();
        let error = crate::mxc_engine::Error::from(error.response(false).into_mxc_error());
        let captured = PolicyFailures::from_error(&error).unwrap().unwrap();
        let restored = PolicyFailures::from_json(&captured.to_json().unwrap()).unwrap();
        assert_eq!(restored, captured);
        let detail = &restored.results[0].details[0];
        assert!(detail.resource.is_none());
        assert_eq!(
            detail.flags,
            PolicyFailureDetail::FLAG_HAS_ACTIONABLE_DETAILS
                | PolicyFailureDetail::FLAG_RESOURCE_UNAVAILABLE
        );
        let request = r#"{"version":"1.0.0","process":{"commandLine":"must-not-run"}}"#;
        let error = crate::v1::dev::prepare_policy_json(request, &restored, Default::default())
            .unwrap_err();
        assert_eq!(error.code, crate::v1::ErrorCode::PolicyValidation);
        STATE.with(|state| {
            let state = state.borrow();
            assert_eq!(state.specifications.len(), 1);
            assert!(!state.calls.contains(&"launch"));
            assert_eq!(state.frees, 1);
            assert_eq!(state.closes, 1);
        });
    }
}

#[test]
fn policy_failures_are_not_queried_after_success_or_unrelated_failure() {
    for status in [S_OK, E_FAIL] {
        let api = reset();
        STATE.with(|state| {
            let mut state = state.borrow_mut();
            state.status = status;
            state.handle = status.is_ok();
        });
        drop(api.create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE));
        STATE.with(|state| {
            let state = state.borrow();
            assert!(!state.calls.contains(&"get"));
            assert_eq!(state.frees, 0);
            assert_eq!(state.closes, usize::from(status.is_ok()));
        });
    }
}

#[test]
fn policy_failures_getter_failure_frees_outputs_and_reports_unavailability() {
    let api = reset();
    STATE.with(|state| state.borrow_mut().getter_status = E_FAIL);
    let failure = api
        .create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
        .unwrap_err();
    let error = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
    assert!(PolicyFailures::from_error(&error).unwrap().is_none());
    assert!(error
        .details
        .as_deref()
        .unwrap()
        .get("policyResultUnavailable")
        .is_some());
    assert_eq!(
        error.native_code.as_deref(),
        Some(PolicyFailures::NATIVE_CODE_POLICY_BLOCKED)
    );
    STATE.with(|state| assert_eq!(state.borrow().frees, 1));
}

#[test]
fn policy_failures_missing_getter_reports_unavailability_only_as_structured_data() {
    let mut api = reset();
    api.get_last_policy_result = None;
    let failure = api
        .create_with_diagnostics(b"spec", PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE)
        .unwrap_err();
    let error = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
    assert!(PolicyFailures::from_error(&error).unwrap().is_none());
    assert!(error
        .details
        .as_deref()
        .unwrap()
        .get("policyResultUnavailable")
        .is_some());
    assert_eq!(error.message, POLICY_DENIED_MESSAGE);
    STATE.with(|state| {
        let state = state.borrow();
        assert_eq!(state.flags, [PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE]);
        assert!(!state.calls.contains(&"get"));
    });
}

#[test]
fn policy_failures_unadvertised_or_failed_support_preserves_strict_creation() {
    let no_support = 0;
    let other_support = !EXPERIMENTAL_PSE_SUPPORT_POLICY_RESULT;
    for (support_status, support_flags) in [
        (S_OK, no_support),
        (S_OK, other_support),
        (E_FAIL, EXPERIMENTAL_PSE_SUPPORT_POLICY_RESULT),
    ] {
        let api = reset();
        STATE.with(|state| {
            let mut state = state.borrow_mut();
            state.support_status = support_status;
            state.support_flags = support_flags;
        });
        let failure = api
            .create_with_diagnostics(b"spec", CALLER_FLAG)
            .unwrap_err();
        STATE.with(|state| {
            let state = state.borrow();
            assert_eq!(state.flags, [CALLER_FLAG]);
            assert_eq!(state.calls, ["support", "create"]);
            assert_eq!(state.frees, 0);
        });
        let error = crate::mxc_engine::Error::from(failure.response(false).into_mxc_error());
        assert_eq!(
            error.native_code.as_deref(),
            Some(PolicyFailures::NATIVE_CODE_POLICY_BLOCKED)
        );
        assert_eq!(
            error.operation.as_deref(),
            Some("CreateProcessSecurityEnvironment")
        );
        assert!(PolicyFailures::from_error(&error).unwrap().is_none());
        assert!(error.details.as_deref().unwrap()["policyResultUnavailable"]
            .as_str()
            .is_some_and(|reason| !reason.is_empty()));
        assert_eq!(error.message, POLICY_DENIED_MESSAGE);
    }
}