funera-core 0.3.0

Core LLM agent engine — ReAct loop, providers, tools, skills, middleware, security
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
//! Windows sandbox implementation using write-restricted tokens + environment blocking.
//!
//! Based on OpenAI Codex's "unprivileged sandbox" approach:
//! - File-write isolation: Write-Restricted Token + synthetic SID + ACLs
//! - Network isolation: environment variable poisoning (advisory)
//!
//! No administrator privileges required.

use std::path::PathBuf;
use std::time::Duration;

use super::sandbox::SandboxPolicy;
use anyhow::anyhow;

// ── Win32 constants not yet included in the windows crate feature set ──
/// SE_GROUP_LOGON_ID (0xC0000000): bitmask for logon-session SIDs.
const SE_GROUP_LOGON_ID: u32 = 0xC0000000;

use windows::Win32::Foundation::{
    BOOL, CloseHandle, ERROR_BROKEN_PIPE, HANDLE, HANDLE_FLAG_INHERIT, HANDLE_FLAGS, WAIT_OBJECT_0,
};
use windows::Win32::Security::{
    AllocateAndInitializeSid, CreateRestrictedToken, DISABLE_MAX_PRIVILEGE, FreeSid,
    GetTokenInformation, PSID, SANDBOX_INERT, SECURITY_ATTRIBUTES, SID_AND_ATTRIBUTES,
    TOKEN_ACCESS_MASK, TOKEN_DUPLICATE, TOKEN_GROUPS, TOKEN_QUERY, TokenGroups,
};
use windows::Win32::System::Console::{
    CONSOLE_MODE, GetConsoleMode, GetStdHandle, STD_INPUT_HANDLE, SetConsoleMode,
};
use windows::Win32::System::Pipes::CreatePipe;
use windows::Win32::System::Threading::{
    CREATE_NO_WINDOW, CREATE_UNICODE_ENVIRONMENT, CreateProcessAsUserW, GetCurrentProcess,
    GetExitCodeProcess, OpenProcessToken, PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOW,
    TerminateProcess, WaitForSingleObject,
};
use windows::core::PWSTR;

const WRITE_RESTRICTED: u32 = 0x0000_0008;
const SECURITY_NT_AUTHORITY: [u8; 6] = [0, 0, 0, 0, 0, 5];

/// A write-restricted token + synthetic SID based sandbox for Windows.
///
/// # Safety
///
/// `WindowsSandbox` holds a raw PSID pointer. It is Send+Sync because:
/// - The PSID is allocated once during construction and only freed on Drop.
/// - `execute()` takes `&self` and does not mutate shared state.
/// - The ACL operations on the filesystem are serialized per-process.
pub struct WindowsSandbox {
    sid: PSID,
    read_write_paths: Vec<PathBuf>,
    block_network: bool,
}

// SAFETY: PSID is a `*mut c_void` wrapper. The pointer is non-null after
// construction, read-only during `execute()`, and freed only on Drop.
unsafe impl Send for WindowsSandbox {}
unsafe impl Sync for WindowsSandbox {}

impl WindowsSandbox {
    pub fn new(policy: &SandboxPolicy) -> anyhow::Result<Self> {
        let sid = create_sandbox_sid().map_err(|e| anyhow!("failed to create sandbox SID: {e}"))?;
        match apply_write_acls(sid, &policy.read_write_paths) {
            Ok(()) => Ok(Self {
                sid,
                read_write_paths: policy.read_write_paths.clone(),
                block_network: policy.block_network,
            }),
            Err(e) => {
                // SAFETY: `sid` was successfully allocated above;
                // FreeSid must be called exactly once to avoid a leak.
                unsafe { FreeSid(sid) };
                Err(anyhow!("failed to apply write ACLs: {e}"))
            }
        }
    }

    pub async fn execute(
        &self,
        shell: &str,
        shell_flag: &str,
        command: &str,
        workdir: Option<&str>,
        timeout: Duration,
    ) -> anyhow::Result<(String, String, i32)> {
        match try_full_sandbox(
            self.sid,
            shell,
            shell_flag,
            command,
            workdir,
            timeout,
            self.block_network,
        ) {
            Ok(result) => return Ok(result),
            Err(e) => {
                // SAFETY: log.warn is safe; the sandbox creation (e.g.
                // CreateRestrictedToken / CreateProcessAsUserW failing
                // due to missing admin privileges) is expected on some
                // Windows configurations. We degrade to network-only.
                tracing::warn!(
                    "sandbox creation failed, falling back to network-only isolation: {e}"
                );
            }
        }
        execute_fallback(
            shell,
            shell_flag,
            command,
            workdir,
            timeout,
            self.block_network,
        )
        .await
    }
}

impl Drop for WindowsSandbox {
    fn drop(&mut self) {
        remove_write_acls(self.sid, &self.read_write_paths);
        if !self.sid.0.is_null() {
            // SAFETY: `self.sid` was allocated in `new()`. We check for
            // null to guard against a zeroed/uninitialized value. FreeSid
            // must be called exactly once per allocated PSID.
            unsafe { FreeSid(self.sid) };
        }
    }
}

async fn execute_fallback(
    shell: &str,
    shell_flag: &str,
    command: &str,
    workdir: Option<&str>,
    timeout: Duration,
    block_network: bool,
) -> anyhow::Result<(String, String, i32)> {
    use std::process::Stdio;
    use tokio::process::Command as TokioCommand;
    use tokio::time::timeout as tokio_timeout;

    let mut cmd = TokioCommand::new(shell);
    cmd.arg(shell_flag).arg(command);
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    cmd.stdin(Stdio::null());

    if block_network {
        cmd.env("HTTPS_PROXY", "http://127.0.0.1:9");
        cmd.env("HTTP_PROXY", "http://127.0.0.1:9");
        cmd.env("ALL_PROXY", "http://127.0.0.1:9");
        cmd.env("GIT_HTTPS_PROXY", "http://127.0.0.1:9");
        cmd.env("NO_PROXY", "localhost,127.0.0.1,::1");
    }

    if let Some(dir) = workdir {
        cmd.current_dir(dir);
    }

    let output = tokio_timeout(timeout, cmd.output())
        .await
        .map_err(|_| anyhow!("command timed out"))?
        .map_err(|e| anyhow!("command failed: {e}"))?;

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

    Ok((stdout, stderr, exit_code))
}

fn create_sandbox_sid() -> Result<PSID, windows::core::Error> {
    let pid = std::process::id();
    // SAFETY: AllocateAndInitializeSid writes the PSID on success.
    // The zeroed initial value is overwritten before being returned.
    unsafe {
        let mut sid: PSID = std::mem::zeroed();
        AllocateAndInitializeSid(
            &windows::Win32::Security::SID_IDENTIFIER_AUTHORITY {
                Value: SECURITY_NT_AUTHORITY,
            },
            5u8,
            21u32,
            (pid >> 16) & 0xFFFF,
            pid & 0xFFFF,
            0xF1_E001u32,
            0x0005_B001u32,
            0,
            0,
            0,
            &mut sid,
        )?;
        Ok(sid)
    }
}

fn apply_write_acls(_sid: PSID, paths: &[PathBuf]) -> anyhow::Result<()> {
    for path in paths {
        if !path.exists() {
            continue;
        }
        let path_str = path.to_string_lossy();
        let sid_str = sid_to_string_fallback(_sid)?;
        let grant_cmd = format!("icacls \"{path_str}\" /grant \"*{sid_str}\":(OI)(CI)(RX,W,D) /Q");
        let _ = std::process::Command::new("cmd")
            .args(["/c", &grant_cmd])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .stdin(std::process::Stdio::null())
            .status();

        for protected in &[".git", ".funera", ".agents"] {
            let subdir = path.join(protected);
            if subdir.exists() {
                let deny_cmd = format!(
                    "icacls \"{}\" /deny \"*{sid_str}\":(OI)(CI)(W,D) /Q",
                    subdir.to_string_lossy()
                );
                let _ = std::process::Command::new("cmd")
                    .args(["/c", &deny_cmd])
                    .stdout(std::process::Stdio::null())
                    .stderr(std::process::Stdio::null())
                    .stdin(std::process::Stdio::null())
                    .status();
            }
        }
    }
    Ok(())
}

fn remove_write_acls(_sid: PSID, paths: &[PathBuf]) {
    for path in paths {
        if !path.exists() {
            continue;
        }
        let Ok(sid_str) = sid_to_string_fallback(_sid) else {
            continue;
        };
        let path_str = path.to_string_lossy();
        let remove_cmd = format!("icacls \"{path_str}\" /remove \"*{sid_str}\" /Q");
        let _ = std::process::Command::new("cmd")
            .args(["/c", &remove_cmd])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .stdin(std::process::Stdio::null())
            .status();
    }
}

fn sid_to_string_fallback(sid: PSID) -> anyhow::Result<String> {
    unsafe {
        let mut str_ptr: PWSTR = PWSTR::null();
        if windows::Win32::Security::Authorization::ConvertSidToStringSidW(sid, &mut str_ptr)
            .is_ok()
        {
            // SAFETY: ConvertSidToStringSidW guarantees null-terminated output
            // on success. We cap at 2048 to prevent runaway from corruption.
            let ptr: *const u16 = str_ptr.as_ptr();
            let len = (0..).take(2048).take_while(|&i| *ptr.add(i) != 0).count();
            let result = String::from_utf16_lossy(std::slice::from_raw_parts(ptr, len));
            windows::Win32::Foundation::LocalFree(windows::Win32::Foundation::HLOCAL(
                str_ptr.0 as *mut std::ffi::c_void,
            ));
            return Ok(result);
        }
    }
    Ok(format!("S-1-5-21-{}-funera-sandbox", std::process::id()))
}

fn create_write_restricted_token(sandbox_sid: PSID) -> anyhow::Result<HANDLE> {
    let mut token: HANDLE = HANDLE::default();
    // SAFETY: OpenProcessToken opens the current process token. The
    // token handle is closed in the cleanup block below (line 298).
    unsafe {
        OpenProcessToken(
            GetCurrentProcess(),
            TOKEN_ACCESS_MASK(TOKEN_QUERY.0 | TOKEN_DUPLICATE.0),
            &mut token,
        )
        .map_err(|e| anyhow!("OpenProcessToken failed: {e}"))?;
    }

    let logon_sid = get_logon_sid(token).inspect_err(|_e| {
        // SAFETY: CloseHandle closes the process token. Required
        // before propagating the error to avoid a handle leak.
        unsafe { CloseHandle(token).ok() };
    })?;
    let everyone = make_everyone_sid().inspect_err(|_e| {
        // SAFETY: Cleanup on error — free the already-allocated SID
        // and close the process token before returning.
        unsafe {
            FreeSid(logon_sid);
            CloseHandle(token).ok()
        };
    })?;

    let restricted_sids = [
        SID_AND_ATTRIBUTES {
            Sid: logon_sid,
            Attributes: 0,
        },
        SID_AND_ATTRIBUTES {
            Sid: everyone,
            Attributes: 0,
        },
        SID_AND_ATTRIBUTES {
            Sid: sandbox_sid,
            Attributes: 0,
        },
    ];

    let flags = windows::Win32::Security::CREATE_RESTRICTED_TOKEN_FLAGS(
        WRITE_RESTRICTED | DISABLE_MAX_PRIVILEGE.0 | SANDBOX_INERT.0,
    );

    let mut restricted: HANDLE = HANDLE::default();
    // SAFETY: CreateRestrictedToken takes the existing token and returns
    // a new restricted token handle. It reads the SID_AND_ATTRIBUTES
    // array synchronously — all pointers are valid for the call duration.
    let result = unsafe {
        CreateRestrictedToken(
            token,
            flags,
            None,
            None,
            Some(&restricted_sids),
            &mut restricted,
        )
    };

    // SAFETY: Always free the intermediate SIDs and close the process
    // token — the restricted token (if created) is returned to the caller.
    unsafe {
        FreeSid(everyone);
        FreeSid(logon_sid);
        CloseHandle(token).ok()
    };
    result.map_err(|e| anyhow!("CreateRestrictedToken failed: {e}"))?;
    Ok(restricted)
}

fn make_everyone_sid() -> anyhow::Result<PSID> {
    // SAFETY: AllocateAndInitializeSid allocates a new SID and writes
    // into &mut sid. The zeroed initial value is overwritten on success.
    unsafe {
        let mut sid: PSID = std::mem::zeroed();
        AllocateAndInitializeSid(
            &windows::Win32::Security::SECURITY_WORLD_SID_AUTHORITY,
            1u8,
            0u32,
            0,
            0,
            0,
            0,
            0,
            0,
            0,
            &mut sid,
        )
        .map_err(|e| anyhow!("failed to create Everyone SID: {e}"))?;
        Ok(sid)
    }
}

fn get_logon_sid(token: HANDLE) -> anyhow::Result<PSID> {
    use windows::Win32::Security::Authorization::{ConvertSidToStringSidW, ConvertStringSidToSidW};
    // SAFETY: GetTokenInformation writes a TOKEN_GROUPS struct into
    // the Vec buffer. The raw pointer cast is valid per Win32 ABI
    // because TOKEN_GROUPS is a C struct with BYTE alignment.
    // The loop walks at most GroupCount entries, preventing OOB.
    unsafe {
        let mut size: u32 = 0;
        let _ = GetTokenInformation(token, TokenGroups, None, 0, &mut size);
        let mut buf: Vec<u8> = vec![0u8; size as usize];
        GetTokenInformation(
            token,
            TokenGroups,
            Some(buf.as_mut_ptr() as *mut _),
            size,
            &mut size,
        )
        .map_err(|e| anyhow!("GetTokenInformation(TokenGroups) failed: {e}"))?;

        let groups = &*(buf.as_ptr() as *const TOKEN_GROUPS);
        let groups_ptr = groups.Groups.as_ptr();
        for i in 0..groups.GroupCount as usize {
            let entry = &*groups_ptr.add(i);
            if (entry.Attributes & SE_GROUP_LOGON_ID) == SE_GROUP_LOGON_ID {
                let mut sid_str: PWSTR = PWSTR::null();
                ConvertSidToStringSidW(entry.Sid, &mut sid_str)
                    .map_err(|e| anyhow!("ConvertSidToStringSidW failed: {e}"))?;
                let mut dup_sid: PSID = std::mem::zeroed();
                if ConvertStringSidToSidW(sid_str, &mut dup_sid).is_ok() {
                    windows::Win32::Foundation::LocalFree(windows::Win32::Foundation::HLOCAL(
                        sid_str.0 as *mut std::ffi::c_void,
                    ));
                    return Ok(dup_sid);
                }
                windows::Win32::Foundation::LocalFree(windows::Win32::Foundation::HLOCAL(
                    sid_str.0 as *mut std::ffi::c_void,
                ));
            }
        }
    }
    make_everyone_sid()
}

fn try_full_sandbox(
    sid: PSID,
    shell: &str,
    shell_flag: &str,
    command: &str,
    workdir: Option<&str>,
    timeout: Duration,
    block_network: bool,
) -> anyhow::Result<(String, String, i32)> {
    let token = create_write_restricted_token(sid)?;
    let result = launch_restricted(
        token,
        shell,
        shell_flag,
        command,
        workdir,
        timeout,
        block_network,
    );
    // SAFETY: CloseHandle must be called once per HANDLE. token was
    // obtained from create_write_restricted_token and is not used
    // after this point.
    unsafe { CloseHandle(token).ok() };
    result
}

fn launch_restricted(
    token: HANDLE,
    shell: &str,
    shell_flag: &str,
    command: &str,
    workdir: Option<&str>,
    timeout: Duration,
    block_network: bool,
) -> anyhow::Result<(String, String, i32)> {
    let env_block = if block_network {
        Some(build_net_blocked_env_block())
    } else {
        None
    };

    let sa = SECURITY_ATTRIBUTES {
        nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: std::ptr::null_mut(),
        bInheritHandle: BOOL::from(true),
    };

    // ── create pipes with a drop-guard so early-exits never leak handles ──
    let mut stdout_read = HANDLE::default();
    let mut stdout_write = HANDLE::default();
    // SAFETY: CreatePipe allocates kernel pipe objects. The handles are
    // wrapped in PipeGuard which closes them on any early-exit path.
    unsafe {
        CreatePipe(&mut stdout_read, &mut stdout_write, Some(&sa), 0)?;
    }

    let mut stderr_read = HANDLE::default();
    let mut stderr_write = HANDLE::default();
    // SAFETY: Same as above — second pipe pair for stderr.
    unsafe {
        CreatePipe(&mut stderr_read, &mut stderr_write, Some(&sa), 0)?;
    }

    // Drop-guard: if we return early, this guard closes all four handles.
    let mut guard = PipeGuard {
        stdout_read,
        stdout_write,
        stderr_read,
        stderr_write,
        committed: false,
    };

    // SAFETY: SetHandleInformation marks the read-ends as non-inheritable
    // so only the child process inherits the write-ends. The handles are
    // valid from CreatePipe above. If this fails, PipeGuard cleans up.
    unsafe {
        windows::Win32::Foundation::SetHandleInformation(
            stdout_read,
            HANDLE_FLAG_INHERIT.0,
            HANDLE_FLAGS::default(),
        )?;
        windows::Win32::Foundation::SetHandleInformation(
            stderr_read,
            HANDLE_FLAG_INHERIT.0,
            HANDLE_FLAGS::default(),
        )?;
    }

    let full_cmd = format!("{} {} {}", shell, shell_flag, command);
    let mut cmd_wide: Vec<u16> = full_cmd.encode_utf16().collect();
    cmd_wide.push(0);

    let workdir_wide: Option<Vec<u16>> = workdir.map(|d| {
        let mut w: Vec<u16> = d.encode_utf16().collect();
        w.push(0);
        w
    });

    let mut stdin_read = HANDLE::default();
    let mut stdin_write = HANDLE::default();
    // SAFETY: CreatePipe allocates a kernel pipe object for stdin.
    // The write-end is closed immediately so the child reads EOF.
    unsafe {
        CreatePipe(&mut stdin_read, &mut stdin_write, Some(&sa), 0)?;
    }
    unsafe { CloseHandle(stdin_write).ok() };

    // Save console input mode to restore after child exits.
    // Windows: GetStdHandle(STD_INPUT_HANDLE) from within a child
    // process always returns the real console handle regardless of
    // STARTF_USESTDHANDLES, so child processes can modify
    // ENABLE_VIRTUAL_TERMINAL_INPUT etc.
    let stdin_handle = unsafe { GetStdHandle(STD_INPUT_HANDLE)? };
    let mut saved_mode = CONSOLE_MODE(0);
    let mode_saved = unsafe { GetConsoleMode(stdin_handle, &mut saved_mode) }.is_ok();

    // SAFETY: zeroed() is safe for STARTUPINFOW — all fields are
    // explicitly set below before the struct is passed to the API.
    let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() };
    si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
    si.hStdOutput = stdout_write;
    si.hStdError = stderr_write;
    si.hStdInput = stdin_read;
    si.dwFlags = STARTF_USESTDHANDLES;

    // SAFETY: zeroed() is safe for PROCESS_INFORMATION — the fields
    // are filled by CreateProcessAsUserW on success.
    let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };

    // SAFETY: CreateProcessAsUserW launches a child process with a
    // restricted token. The cmd_wide buffer is on the stack and
    // outlives the call (call reads synchronously). env_block and
    // workdir_wide are also stack-local. If this fails, PipeGuard
    // closes the pipe handles.
    let result = unsafe {
        CreateProcessAsUserW(
            token,
            None,
            PWSTR::from_raw(cmd_wide.as_mut_ptr()),
            None,
            None,
            BOOL::from(true),
            CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
            env_block
                .as_ref()
                .map(|e| Some(e.as_ptr() as *const std::ffi::c_void))
                .unwrap_or(None),
            workdir_wide
                .as_ref()
                .map(|w| windows::core::PCWSTR::from_raw(w.as_ptr()))
                .unwrap_or(windows::core::PCWSTR::null()),
            &si,
            &mut pi,
        )
    };

    // The child now has handles to the write-ends; we can close ours.
    guard.close_write_ends();
    // stdin_read was inherited by the child; close parent's copy.
    unsafe { CloseHandle(stdin_read).ok() };

    if result.is_err() {
        return Err(anyhow!("CreateProcessAsUserW failed: {result:?}"));
    }

    // Commit – from now on guard.drop() does nothing.
    guard.committed = true;

    let timeout_ms = timeout.as_millis().min(u32::MAX as u128) as u32;
    // SAFETY: WaitForSingleObject blocks until the child process exits
    // or the timeout expires. The process handle is valid from the
    // CreateProcessAsUserW call above.
    let wait_result = unsafe { WaitForSingleObject(pi.hProcess, timeout_ms) };

    let stdout_str = read_pipe(stdout_read);
    let stderr_str = read_pipe(stderr_read);
    // SAFETY: Read-ends are no longer needed; close them now. They
    // remain open until this explicit CloseHandle because the guard
    // is committed (committed=true) and skips them in Drop.
    unsafe {
        CloseHandle(stdout_read).ok();
        CloseHandle(stderr_read).ok();
    }

    let exit_code = if wait_result == WAIT_OBJECT_0 {
        let mut code: u32 = 0;
        // SAFETY: GetExitCodeProcess reads the exit code from a
        // terminated process. The process handle is valid.
        unsafe {
            if GetExitCodeProcess(pi.hProcess, &mut code).is_err() {
                1
            } else {
                code as i32
            }
        }
    } else {
        // SAFETY: TerminateProcess forcibly kills the child on timeout.
        unsafe { TerminateProcess(pi.hProcess, 1).ok() };
        1
    };

    // SAFETY: Close the process and thread handles obtained from
    // CreateProcessAsUserW. Both are valid if we reach here.
    unsafe {
        CloseHandle(pi.hProcess).ok();
        CloseHandle(pi.hThread).ok();
    }
    // Restore console input mode in case the child modified it.
    if mode_saved {
        unsafe { SetConsoleMode(stdin_handle, saved_mode).ok() };
    }
    Ok((stdout_str, stderr_str, exit_code))
}

/// RAII guard: closes all four pipe handles unless [`committed`] or
/// [`close_write_ends`] has been called first.
struct PipeGuard {
    stdout_read: HANDLE,
    stdout_write: HANDLE,
    stderr_read: HANDLE,
    stderr_write: HANDLE,
    committed: bool,
}

impl PipeGuard {
    fn close_write_ends(&mut self) {
        // SAFETY: CloseHandle on a valid HANDLE is safe. The write-ends
        // are closed to allow the child to signal EOF on the pipes. We
        // null the handles afterwards to prevent double-close in Drop.
        unsafe {
            CloseHandle(self.stdout_write).ok();
            CloseHandle(self.stderr_write).ok();
        }
        self.stdout_write = HANDLE::default();
        self.stderr_write = HANDLE::default();
    }
}

impl Drop for PipeGuard {
    fn drop(&mut self) {
        if self.committed {
            return;
        }
        // SAFETY: On early-exit (committed=false), all four pipe handles
        // are still open and must be closed to avoid leaking kernel objects.
        // Null handles (HANDLE::default()) passed to CloseHandle are ignored.
        unsafe {
            CloseHandle(self.stdout_read).ok();
            CloseHandle(self.stdout_write).ok();
            CloseHandle(self.stderr_read).ok();
            CloseHandle(self.stderr_write).ok();
        }
    }
}

fn read_pipe(pipe: HANDLE) -> String {
    let mut result: Vec<u8> = Vec::new();
    let mut buf = vec![0u8; 4096];
    loop {
        let mut bytes_read: u32 = 0;
        // SAFETY: ReadFile reads up to 4096 bytes into the stack buffer.
        // pipe must be a valid, readable HANDLE. The caller is responsible
        // for closing the handle after this function returns.
        match unsafe {
            windows::Win32::Storage::FileSystem::ReadFile(
                pipe,
                Some(&mut buf),
                Some(&mut bytes_read),
                None,
            )
        } {
            Ok(_) if bytes_read > 0 => result.extend_from_slice(&buf[..bytes_read as usize]),
            Ok(_) => break,
            Err(e) => {
                if e.code() == ERROR_BROKEN_PIPE.to_hresult() {
                    break;
                }
                break;
            }
        }
    }
    String::from_utf8_lossy(&result).to_string()
}

fn build_net_blocked_env_block() -> Vec<u16> {
    let mut result: Vec<u16> = Vec::new();
    for (key, value) in std::env::vars() {
        let upper = key.to_uppercase();
        if [
            "HTTPS_PROXY",
            "HTTP_PROXY",
            "ALL_PROXY",
            "GIT_HTTPS_PROXY",
            "NO_PROXY",
        ]
        .contains(&upper.as_str())
        {
            continue;
        }
        result.extend(format!("{key}={value}").encode_utf16());
        result.push(0);
    }
    for (k, v) in &[
        ("HTTPS_PROXY", "http://127.0.0.1:9"),
        ("HTTP_PROXY", "http://127.0.0.1:9"),
        ("ALL_PROXY", "http://127.0.0.1:9"),
        ("GIT_HTTPS_PROXY", "http://127.0.0.1:9"),
        ("NO_PROXY", "localhost,127.0.0.1,::1"),
    ] {
        result.extend(format!("{k}={v}").encode_utf16());
        result.push(0);
    }
    result.push(0);
    result
}

// ── tests ──────────────────────────────────────────────────────────

#[cfg(all(test, feature = "sandbox", target_os = "windows"))]
mod tests {
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::Duration;

    use super::*;
    use crate::security::sandbox::SandboxPolicy;

    static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn unique_temp_dir() -> PathBuf {
        let id = TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let base = std::env::temp_dir().join(format!("funera_sandbox_win_test_{}", id));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).expect("create temp dir");
        base
    }

    fn cleanup_temp_dir(dir: &PathBuf) {
        let _ = std::fs::remove_dir_all(dir);
    }

    // ══════════════════════════════════════════════════════════════════
    //  GROUP A — pure functions (0 unsafe, fully testable)
    // ══════════════════════════════════════════════════════════════════

    #[test]
    fn test_env_block_has_poison_proxy_vars() {
        unsafe {
            std::env::set_var("HTTPS_PROXY", "http://real-proxy:8080");
            std::env::set_var("MY_VAR", "hello");
        }

        let block = build_net_blocked_env_block();
        let raw = String::from_utf16_lossy(&block);

        assert!(
            !raw.contains("http://real-proxy:8080"),
            "original HTTPS_PROXY must be removed"
        );
        assert!(
            raw.contains("HTTPS_PROXY=http://127.0.0.1:9"),
            "missing poison HTTPS_PROXY"
        );
        assert!(
            raw.contains("HTTP_PROXY=http://127.0.0.1:9"),
            "missing poison HTTP_PROXY"
        );
        assert!(
            raw.contains("ALL_PROXY=http://127.0.0.1:9"),
            "missing poison ALL_PROXY"
        );
        assert!(
            raw.contains("GIT_HTTPS_PROXY=http://127.0.0.1:9"),
            "missing poison GIT_HTTPS_PROXY"
        );
        assert!(
            raw.contains("MY_VAR=hello"),
            "non-proxy vars must be preserved"
        );

        unsafe {
            std::env::remove_var("HTTPS_PROXY");
            std::env::remove_var("MY_VAR");
        }
    }

    #[test]
    fn test_env_block_double_null_terminated() {
        let block = build_net_blocked_env_block();
        assert!(block.len() >= 2, "block must have at least 2 bytes");
        assert_eq!(block[block.len() - 1], 0, "last byte is null");
        assert_eq!(block[block.len() - 2], 0, "second-to-last byte is null");
    }

    #[test]
    fn test_fallback_without_network_block() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(execute_fallback(
            "cmd",
            "/c",
            "echo no_net_block_test",
            None,
            Duration::from_secs(10),
            false,
        ));
        assert!(
            result.is_ok(),
            "fallback command failed: {:?}",
            result.err()
        );
        let (stdout, _, exit_code) = result.unwrap();
        assert!(stdout.contains("no_net_block_test"), "stdout: {stdout}");
        assert_eq!(exit_code, 0, "exit code: {exit_code}");
    }

    #[test]
    fn test_fallback_with_workdir() {
        let dir = std::env::temp_dir();
        let dir_str = dir.to_string_lossy().to_string();
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(execute_fallback(
            "cmd",
            "/c",
            "cd",
            Some(&dir_str),
            Duration::from_secs(10),
            false,
        ));
        assert!(result.is_ok(), "fallback with workdir: {:?}", result.err());
        let (stdout, _, _) = result.unwrap();
        assert!(!stdout.is_empty(), "cd should produce output");
    }

    #[test]
    fn test_fallback_timeout() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(execute_fallback(
            "cmd",
            "/c",
            "timeout /t 30 /nobreak",
            None,
            Duration::from_millis(10),
            false,
        ));
        assert!(result.is_err(), "should timeout");
    }

    #[test]
    fn test_fallback_with_network_blocked() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result = rt.block_on(execute_fallback(
            "cmd",
            "/c",
            "echo net_block_ok",
            None,
            Duration::from_secs(10),
            true,
        ));
        assert!(result.is_ok());
        let (stdout, _, _) = result.unwrap();
        assert!(stdout.contains("net_block_ok"), "stdout: {stdout}");
    }

    #[test]
    fn test_read_pipe_with_data() {
        let mut read_end = HANDLE::default();
        let mut write_end = HANDLE::default();
        let sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: std::ptr::null_mut(),
            bInheritHandle: BOOL::from(true),
        };
        unsafe {
            CreatePipe(&mut read_end, &mut write_end, Some(&sa), 0).unwrap();
        }

        let msg = b"hello pipe";
        let mut written: u32 = 0;
        unsafe {
            windows::Win32::Storage::FileSystem::WriteFile(
                write_end,
                Some(msg),
                Some(&mut written),
                None,
            )
            .expect("WriteFile failed");
            CloseHandle(write_end).ok();
        }

        let output = read_pipe(read_end);
        assert_eq!(output, "hello pipe");
        unsafe { CloseHandle(read_end).ok() };
    }

    #[test]
    fn test_read_pipe_empty() {
        let mut read_end = HANDLE::default();
        let mut write_end = HANDLE::default();
        let sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: std::ptr::null_mut(),
            bInheritHandle: BOOL::from(true),
        };
        unsafe {
            CreatePipe(&mut read_end, &mut write_end, Some(&sa), 0).unwrap();
        }
        unsafe { CloseHandle(write_end).ok() };

        let output = read_pipe(read_end);
        assert_eq!(output, "");
        unsafe { CloseHandle(read_end).ok() };
    }

    // ══════════════════════════════════════════════════════════════════
    //  GROUP B — SID functions (unsafe, both branches testable)
    // ══════════════════════════════════════════════════════════════════

    #[test]
    fn test_create_sandbox_sid_is_valid() {
        let sid = create_sandbox_sid().expect("create sandbox sid");
        assert!(!sid.0.is_null(), "sid must not be null");
        let sid_str = sid_to_string_fallback(sid).expect("sid to string");
        assert!(
            sid_str.starts_with("S-1-5-21-"),
            "unexpected sid format: {sid_str}"
        );
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_make_everyone_sid_is_valid() {
        let sid = make_everyone_sid().expect("create everyone sid");
        assert!(!sid.0.is_null(), "everyone sid must not be null");
        let sid_str = sid_to_string_fallback(sid).expect("everyone to string");
        assert!(
            sid_str.contains("S-1-1-"),
            "unexpected everyone sid: {sid_str}"
        );
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_sid_to_string_valid_sid() {
        let sid = create_sandbox_sid().expect("create sid");
        let result = sid_to_string_fallback(sid).expect("sid to string");
        assert!(result.starts_with("S-1-"), "expected SID format: {result}");
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_sid_to_string_fallback_on_invalid_sid() {
        let invalid_sid = PSID(std::ptr::null_mut());
        let result = sid_to_string_fallback(invalid_sid).expect("fallback should always succeed");
        assert!(
            result.contains("funera-sandbox"),
            "expected fallback format: {result}"
        );
    }

    #[test]
    fn test_sid_free_works() {
        let sid = make_everyone_sid().expect("create everyone sid");
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_get_logon_sid_found() {
        let mut token: HANDLE = HANDLE::default();
        unsafe {
            OpenProcessToken(
                GetCurrentProcess(),
                TOKEN_ACCESS_MASK(TOKEN_QUERY.0 | TOKEN_DUPLICATE.0),
                &mut token,
            )
            .expect("OpenProcessToken");
        }
        let sid = get_logon_sid(token).expect("get logon sid");
        assert!(!sid.0.is_null(), "logon sid must not be null");
        unsafe {
            FreeSid(sid);
            CloseHandle(token).ok()
        };
    }

    #[test]
    fn test_get_logon_sid_always_returns_valid() {
        let mut token: HANDLE = HANDLE::default();
        unsafe {
            OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token)
                .expect("OpenProcessToken");
        }
        let sid = get_logon_sid(token).expect("get logon sid");
        assert!(!sid.0.is_null(), "must return a valid fallback SID");
        unsafe {
            FreeSid(sid);
            CloseHandle(token).ok()
        };
    }

    // ══════════════════════════════════════════════════════════════════
    //  GROUP C — token functions & sandbox lifecycle
    // ══════════════════════════════════════════════════════════════════
    //
    // Note: try_full_sandbox / create_write_restricted_token /
    // launch_restricted are only testable when the process has
    // SE_ASSIGNPRIMARYTOKEN_NAME privilege (typically admin mode).
    // On non-admin builds, WindowsSandbox::execute gracefully falls
    // back to execute_fallback, which is tested directly in Group A.
    // The end-to-end tests below validate that the fallback works
    // correctly.

    #[test]
    fn test_write_restricted_token_created() {
        let sandbox_sid = create_sandbox_sid().expect("create sandbox sid");
        let token = create_write_restricted_token(sandbox_sid).expect("create restricted token");
        assert_ne!(token.0, std::ptr::null_mut(), "token must not be null");
        unsafe {
            CloseHandle(token).ok();
            FreeSid(sandbox_sid)
        };
    }

    // ══════════════════════════════════════════════════════════════════
    //  GROUP D — process launch (unsafe heavy)
    // ══════════════════════════════════════════════════════════════════

    #[test]
    fn test_pipe_guard_drops_on_early_exit() {
        let sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: std::ptr::null_mut(),
            bInheritHandle: BOOL::from(true),
        };
        let mut r0 = HANDLE::default();
        let mut w0 = HANDLE::default();
        let mut r1 = HANDLE::default();
        let mut w1 = HANDLE::default();
        unsafe {
            CreatePipe(&mut r0, &mut w0, Some(&sa), 0).unwrap();
            CreatePipe(&mut r1, &mut w1, Some(&sa), 0).unwrap();
        }
        {
            let _guard = PipeGuard {
                stdout_read: r0,
                stdout_write: w0,
                stderr_read: r1,
                stderr_write: w1,
                committed: false,
            };
        }
        // r0/r1/w0/w1 are now copies of the handles that guard closed.
        // Reading from them should fail.
        let mut buf = [0u8; 4];
        let mut read: u32 = 0;
        let result = unsafe {
            windows::Win32::Storage::FileSystem::ReadFile(r0, Some(&mut buf), Some(&mut read), None)
        };
        assert!(result.is_err(), "read should fail after guard drop");
    }

    #[test]
    fn test_pipe_guard_committed_does_not_close_reads() {
        let mut r0 = HANDLE::default();
        let mut w0 = HANDLE::default();
        let sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: std::ptr::null_mut(),
            bInheritHandle: BOOL::from(true),
        };
        unsafe {
            CreatePipe(&mut r0, &mut w0, Some(&sa), 0).unwrap();
        }

        {
            let mut guard = PipeGuard {
                stdout_read: r0,
                stdout_write: w0,
                stderr_read: HANDLE::default(),
                stderr_write: HANDLE::default(),
                committed: false,
            };
            guard.close_write_ends();
            guard.committed = true;
        }
        assert_ne!(r0.0, std::ptr::null_mut(), "read handle should be non-null");
        unsafe { CloseHandle(r0).ok() };
    }

    #[test]
    fn test_pipe_guard_close_write_ends_nullifies() {
        let mut r0 = HANDLE::default();
        let mut w0 = HANDLE::default();
        let sa = SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: std::ptr::null_mut(),
            bInheritHandle: BOOL::from(true),
        };
        unsafe {
            CreatePipe(&mut r0, &mut w0, Some(&sa), 0).unwrap();
        }

        let mut guard = PipeGuard {
            stdout_read: r0,
            stdout_write: w0,
            stderr_read: HANDLE::default(),
            stderr_write: HANDLE::default(),
            committed: false,
        };
        guard.close_write_ends();
        assert_eq!(
            guard.stdout_write.0,
            std::ptr::null_mut(),
            "write end should be null"
        );
        assert_eq!(
            guard.stderr_write.0,
            std::ptr::null_mut(),
            "stderr write end should be null"
        );
        unsafe { CloseHandle(guard.stdout_read).ok() };
    }

    #[test]
    fn test_pipe_guard_drop_null_handles_noop() {
        let guard = PipeGuard {
            stdout_read: HANDLE::default(),
            stdout_write: HANDLE::default(),
            stderr_read: HANDLE::default(),
            stderr_write: HANDLE::default(),
            committed: false,
        };
        drop(guard);
    }

    #[test]
    fn test_sandbox_execute_echo_builtin() {
        let policy = SandboxPolicy {
            enabled: true,
            read_write_paths: vec![],
            ..Default::default()
        };
        let sandbox = WindowsSandbox::new(&policy).expect("create sandbox");
        let rt = tokio::runtime::Runtime::new().unwrap();
        let (stdout, _, code) = rt
            .block_on(sandbox.execute(
                "cmd",
                "/c",
                "echo win_sandbox_ok",
                None,
                Duration::from_secs(10),
            ))
            .expect("sandbox execute");
        assert!(stdout.contains("win_sandbox_ok"), "stdout: {stdout}");
        assert_eq!(code, 0, "exit code: {code}");
    }

    #[test]
    fn test_sandbox_execute_exit_code() {
        let policy = SandboxPolicy::default();
        let sandbox = WindowsSandbox::new(&policy).expect("create sandbox");
        let rt = tokio::runtime::Runtime::new().unwrap();
        let (_, _, code) = rt
            .block_on(sandbox.execute("cmd", "/c", "exit 99", None, Duration::from_secs(10)))
            .expect("sandbox execute");
        assert_eq!(code, 99, "expected exit code 99, got {code}");
    }

    #[test]
    fn test_sandbox_execute_does_not_panic() {
        let policy = SandboxPolicy::default();
        let sandbox = WindowsSandbox::new(&policy).expect("create sandbox");
        let rt = tokio::runtime::Runtime::new().unwrap();
        let result =
            rt.block_on(sandbox.execute("cmd", "/c", "echo hello", None, Duration::from_secs(10)));
        // On non-admin, try_full_sandbox fails → execute_fallback runs.
        // Either way the result should not panic.
        assert!(result.is_ok(), "expected ok but got: {:?}", result.err());
        let (stdout, _, _) = result.unwrap();
        assert!(stdout.contains("hello"), "stdout: {stdout}");
    }

    #[test]
    fn test_sandbox_execute_with_workdir() {
        let tmpdir = unique_temp_dir();
        let dir_str = tmpdir.to_string_lossy().to_string();
        let policy = SandboxPolicy {
            enabled: true,
            read_write_paths: vec![tmpdir.clone()],
            ..Default::default()
        };
        let sandbox = WindowsSandbox::new(&policy).expect("create sandbox");
        let rt = tokio::runtime::Runtime::new().unwrap();
        let (stdout, _, code) = rt
            .block_on(sandbox.execute("cmd", "/c", "cd", Some(&dir_str), Duration::from_secs(10)))
            .expect("sandbox execute with workdir");
        assert_eq!(code, 0, "exit code: {code}");
        assert!(
            stdout.contains(&dir_str.replace('/', "\\")) || stdout.contains(&dir_str),
            "expected workdir {dir_str} in output: {stdout}"
        );
        cleanup_temp_dir(&tmpdir);
    }

    #[test]
    fn test_console_mode_restored_after_sandbox_execute() {
        let stdin_handle = unsafe { GetStdHandle(STD_INPUT_HANDLE).expect("GetStdHandle") };
        let mut mode_before = CONSOLE_MODE(0);
        let have_console = unsafe { GetConsoleMode(stdin_handle, &mut mode_before) }.is_ok();
        if !have_console {
            return;
        }

        let policy = SandboxPolicy {
            enabled: true,
            block_network: true,
            ..Default::default()
        };
        let sandbox = WindowsSandbox::new(&policy).expect("create sandbox");
        let rt = tokio::runtime::Runtime::new().unwrap();
        let (_, _, code) = rt
            .block_on(sandbox.execute("cmd", "/c", "echo test", None, Duration::from_secs(10)))
            .expect("sandbox execute");
        assert_eq!(code, 0);

        let mut mode_after = CONSOLE_MODE(0);
        let got_mode = unsafe { GetConsoleMode(stdin_handle, &mut mode_after) }.is_ok();
        assert!(got_mode, "failed to read console mode after sandbox");
        assert_eq!(
            mode_before.0, mode_after.0,
            "console mode changed: before=0x{:x}, after=0x{:x}",
            mode_before.0, mode_after.0,
        );
    }

    // ══════════════════════════════════════════════════════════════════
    //  GROUP E — ACL functions
    // ══════════════════════════════════════════════════════════════════

    #[test]
    fn test_apply_acls_empty_paths() {
        let sid = create_sandbox_sid().expect("create sid");
        assert!(
            apply_write_acls(sid, &[]).is_ok(),
            "empty paths should succeed"
        );
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_apply_acls_skips_missing_dir() {
        let sid = create_sandbox_sid().expect("create sid");
        let missing = std::env::temp_dir().join("funera_nonexistent_should_not_exist_xxxx");
        assert!(!missing.exists(), "path should not exist");
        assert!(
            apply_write_acls(sid, &[missing]).is_ok(),
            "missing path should be skipped"
        );
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_apply_acls_on_existing_dir_roundtrip() {
        let tmpdir = unique_temp_dir();
        let sid = create_sandbox_sid().expect("create sid");

        // apply should not crash
        assert!(
            apply_write_acls(sid, std::slice::from_ref(&tmpdir)).is_ok(),
            "apply ACE"
        );

        // remove should not crash
        remove_write_acls(sid, std::slice::from_ref(&tmpdir));

        cleanup_temp_dir(&tmpdir);
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_apply_acls_protected_subdir_gets_deny() {
        let tmpdir = unique_temp_dir();
        let git_dir = tmpdir.join(".git");
        std::fs::create_dir_all(&git_dir).expect("create .git");
        let sid = create_sandbox_sid().expect("create sid");

        assert!(
            apply_write_acls(sid, std::slice::from_ref(&tmpdir)).is_ok(),
            "apply ACE"
        );

        cleanup_temp_dir(&tmpdir);
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_apply_acls_skips_missing_protected_subdir() {
        let tmpdir = unique_temp_dir();
        let sid = create_sandbox_sid().expect("create sid");
        assert!(
            apply_write_acls(sid, std::slice::from_ref(&tmpdir)).is_ok(),
            "missing protected subdirs should not cause errors"
        );
        cleanup_temp_dir(&tmpdir);
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_remove_acls_on_missing_path_is_noop() {
        let sid = create_sandbox_sid().expect("create sid");
        let missing = std::env::temp_dir().join("funera_remove_missing_xxxxx");
        remove_write_acls(sid, &[missing]);
        unsafe { FreeSid(sid) };
    }

    #[test]
    fn test_remove_acls_empty_paths_noop() {
        let sid = create_sandbox_sid().expect("create sid");
        remove_write_acls(sid, &[]);
        unsafe { FreeSid(sid) };
    }

    // ══════════════════════════════════════════════════════════════════
    //  GROUP F — constructor / lifecycle
    // ══════════════════════════════════════════════════════════════════

    #[test]
    fn test_new_empty_paths() {
        let policy = SandboxPolicy {
            enabled: true,
            read_write_paths: vec![],
            ..Default::default()
        };
        let sandbox = WindowsSandbox::new(&policy).expect("new with empty paths");
        assert!(!sandbox.sid.0.is_null(), "sid must be allocated");
    }

    #[test]
    fn test_new_with_writable_paths() {
        let tmpdir = unique_temp_dir();
        let policy = SandboxPolicy {
            enabled: true,
            read_write_paths: vec![tmpdir.clone()],
            ..Default::default()
        };
        let sandbox = WindowsSandbox::new(&policy).expect("new with writable paths");
        assert!(!sandbox.sid.0.is_null(), "sid must be allocated");
        cleanup_temp_dir(&tmpdir);
    }

    #[test]
    fn test_sandbox_drop_works() {
        let policy = SandboxPolicy::default();
        {
            let sandbox = WindowsSandbox::new(&policy).expect("create");
            assert!(!sandbox.sid.0.is_null(), "sid non-null");
        }
    }
}