win-custody 0.1.6

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

use std::cmp::Ordering;
use std::ffi::{OsStr, OsString};
use std::io;
use std::marker::PhantomData;
use std::mem::size_of;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle, RawHandle};
use std::path::{Path, PathBuf};
use std::ptr::{null, null_mut};

use windows_sys::Win32::Foundation::{
    DuplicateHandle, SetHandleInformation, DUPLICATE_SAME_ACCESS, ERROR_BROKEN_PIPE, HANDLE,
    HANDLE_FLAG_INHERIT,
};
use windows_sys::Win32::Globalization::{
    CompareStringOrdinal, CSTR_EQUAL, CSTR_GREATER_THAN, CSTR_LESS_THAN,
};
use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
use windows_sys::Win32::Security::SECURITY_CAPABILITIES;
use windows_sys::Win32::Storage::FileSystem::{
    CreateFileW, ReadFile, FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
    FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING,
};
use windows_sys::Win32::System::Pipes::CreatePipe;
use windows_sys::Win32::System::Threading::{
    CreateProcessAsUserW, CreateProcessW, DeleteProcThreadAttributeList,
    InitializeProcThreadAttributeList, ResumeThread, TerminateProcess, UpdateProcThreadAttribute,
    CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, EXTENDED_STARTUPINFO_PRESENT,
    LPPROC_THREAD_ATTRIBUTE_LIST, PROCESS_INFORMATION, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
    PROC_THREAD_ATTRIBUTE_JOB_LIST, PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
    STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW,
};

use crate::app_container::AppContainerProfile;
use crate::handle::{current_process, owned_from_creation};
use crate::job::Job;
use crate::process::{Process, ProcessAccess};
use crate::session::current_session_id;
use crate::token::PrimaryToken;
use crate::wide::wide_null;

/// Flags the launch manages itself; a caller cannot turn them on or off
/// through [`Launch::creation_flags`].
const MANAGED_FLAGS: u32 =
    CREATE_SUSPENDED | EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT;

/// A child process to create, and everything it is allowed to receive.
///
/// Unlike [`std::process::Command`], a launch never lets the child inherit a
/// handle it was not explicitly given: the standard handles and the handles
/// passed to [`Launch::inherit`] form a `PROC_THREAD_ATTRIBUTE_HANDLE_LIST`,
/// and every other inheritable handle in this process stays private.
///
/// The executable is not searched on `PATH`; pass a full path.
///
/// # Standard handles
///
/// If none of [`stdin`](Self::stdin), [`stdout`](Self::stdout) and
/// [`stderr`](Self::stderr) is set, the child starts without standard handles.
/// If any is set, the unset ones are connected to the `NUL` device.
///
/// # Environment
///
/// The child inherits this process's environment unless
/// [`env`](Self::env), [`env_remove`](Self::env_remove) or
/// [`env_clear`](Self::env_clear) is used, in which case it receives a
/// sorted Unicode block built from those changes. A child started with
/// [`as_user`](Self::as_user) still inherits *this* process's environment by
/// default, not the target user's.
#[derive(Debug)]
pub struct Launch<'a> {
    executable: PathBuf,
    arguments: Vec<OsString>,
    /// Private duplicates of the handles the child inherits. They are made
    /// inheritable only for the duration of the creating call.
    inherited: Vec<OwnedHandle>,
    stdin: Option<BorrowedHandle<'a>>,
    stdout: Option<BorrowedHandle<'a>>,
    stderr: Option<BorrowedHandle<'a>>,
    current_dir: Option<PathBuf>,
    environment: EnvironmentPlan,
    create_no_window: bool,
    extra_flags: u32,
    token: Option<&'a PrimaryToken>,
    desktop: Option<OsString>,
    app_container: Option<&'a AppContainerProfile>,
}

impl<'a> Launch<'a> {
    /// A launch of `executable` with no arguments, no inherited handles, no
    /// console window, and this process's environment.
    pub fn new(executable: impl Into<PathBuf>) -> Self {
        Self {
            executable: executable.into(),
            arguments: Vec::new(),
            inherited: Vec::new(),
            stdin: None,
            stdout: None,
            stderr: None,
            current_dir: None,
            environment: EnvironmentPlan::default(),
            create_no_window: true,
            extra_flags: 0,
            token: None,
            desktop: None,
            app_container: None,
        }
    }

    /// Appends one argument. It reaches the child exactly as given, quoted
    /// the way `CommandLineToArgvW` parses command lines.
    pub fn arg(&mut self, argument: impl AsRef<OsStr>) -> &mut Self {
        self.arguments.push(argument.as_ref().to_owned());
        self
    }

    /// Appends several arguments.
    pub fn args<I, S>(&mut self, arguments: I) -> &mut Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<OsStr>,
    {
        self.arguments.extend(
            arguments
                .into_iter()
                .map(|argument| argument.as_ref().to_owned()),
        );
        self
    }

    /// Lets the child inherit a copy of `handle` and returns the handle value
    /// the child will see, for passing on its command line or in its
    /// environment.
    ///
    /// The copy is private to this launch and only becomes inheritable while
    /// the child is being created. Other code in this process that creates
    /// processes with blanket inheritance during that call (for example
    /// [`std::process::Command`]) can still inherit it, as with any
    /// inheritable handle; spawn from one place if that matters.
    pub fn inherit(&mut self, handle: &impl AsHandle) -> io::Result<usize> {
        let copy = duplicate(handle.as_handle(), false)?;
        let value = copy.as_raw_handle() as usize;
        self.inherited.push(copy);
        Ok(value)
    }

    /// The child's standard input.
    pub fn stdin<H: AsHandle + ?Sized>(&mut self, handle: &'a H) -> &mut Self {
        self.stdin = Some(handle.as_handle());
        self
    }

    /// The child's standard output.
    pub fn stdout<H: AsHandle + ?Sized>(&mut self, handle: &'a H) -> &mut Self {
        self.stdout = Some(handle.as_handle());
        self
    }

    /// The child's standard error.
    pub fn stderr<H: AsHandle + ?Sized>(&mut self, handle: &'a H) -> &mut Self {
        self.stderr = Some(handle.as_handle());
        self
    }

    /// The child's working directory. Defaults to this process's.
    pub fn current_dir(&mut self, directory: impl Into<PathBuf>) -> &mut Self {
        self.current_dir = Some(directory.into());
        self
    }

    /// Sets an environment variable for the child. Names are compared without
    /// regard to case, as Windows does.
    pub fn env(&mut self, name: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
        self.environment
            .changes
            .push((name.as_ref().to_owned(), Some(value.as_ref().to_owned())));
        self
    }

    /// Removes an environment variable from the child's environment.
    pub fn env_remove(&mut self, name: impl AsRef<OsStr>) -> &mut Self {
        self.environment
            .changes
            .push((name.as_ref().to_owned(), None));
        self
    }

    /// Starts the child's environment empty instead of from this process's.
    /// Variables set with [`env`](Self::env) are still applied.
    pub fn env_clear(&mut self) -> &mut Self {
        self.environment.clear = true;
        self.environment.changes.clear();
        self
    }

    /// Whether a console child gets no console window (`CREATE_NO_WINDOW`).
    /// Defaults to `true`.
    pub fn create_no_window(&mut self, enabled: bool) -> &mut Self {
        self.create_no_window = enabled;
        self
    }

    /// Additional `CreateProcess` creation flags, such as a priority class or
    /// `CREATE_NEW_PROCESS_GROUP`. `CREATE_SUSPENDED`,
    /// `EXTENDED_STARTUPINFO_PRESENT` and `CREATE_UNICODE_ENVIRONMENT` are
    /// managed by the launch and ignored here.
    pub fn creation_flags(&mut self, flags: u32) -> &mut Self {
        self.extra_flags = flags & !MANAGED_FLAGS;
        self
    }

    /// Creates the child with `token` through `CreateProcessAsUserW`, so it
    /// runs as that token's user in that token's session.
    ///
    /// The caller needs `SeIncreaseQuotaPrivilege`, and
    /// `SeAssignPrimaryTokenPrivilege` unless the token is derived from its
    /// own; services running as LocalSystem hold both. Windows does not let a
    /// child in another session inherit handles, so a launch into another
    /// session must not set standard handles or call
    /// [`inherit`](Self::inherit). This cannot be combined with
    /// [`app_container`](Self::app_container); the `spawn_*` methods fail with
    /// [`io::ErrorKind::InvalidInput`] when both are configured.
    pub fn as_user(&mut self, token: &'a PrimaryToken) -> &mut Self {
        self.token = Some(token);
        self
    }

    /// The window station and desktop the child starts on, such as
    /// `winsta0\default`.
    pub fn desktop(&mut self, name: impl AsRef<OsStr>) -> &mut Self {
        self.desktop = Some(name.as_ref().to_owned());
        self
    }

    /// Creates the child in `profile`'s AppContainer with exactly its
    /// configured capabilities. This attribute is combined with the explicit
    /// inherited-handle list when both are present. This cannot be combined
    /// with [`as_user`](Self::as_user); the `spawn_*` methods fail with
    /// [`io::ErrorKind::InvalidInput`] when both are configured.
    pub fn app_container(&mut self, profile: &'a AppContainerProfile) -> &mut Self {
        self.app_container = Some(profile);
        self
    }

    /// Creates the child suspended. Nothing in it runs until
    /// [`SuspendedChild::resume`].
    ///
    /// This does not put the child in a job. To do that, create it with
    /// [`spawn_suspended_in_job`](Self::spawn_suspended_in_job) instead of
    /// calling [`Job::assign`] on the result: a child assigned after it was
    /// created is outside the job until the assignment returns, and if this
    /// process is killed in between, the child stays behind, suspended.
    pub fn spawn_suspended(&mut self) -> io::Result<SuspendedChild> {
        self.create_suspended(None)
    }

    /// Creates the child suspended and already a member of `job`, through
    /// `PROC_THREAD_ATTRIBUTE_JOB_LIST`. Windows creates the process inside
    /// the job, so the child never exists outside it: with
    /// [`JobLimits::kill_on_close`](crate::JobLimits::kill_on_close) it dies
    /// with this process even when this process is killed before the call
    /// returns, and the job's limits apply to it from the start.
    ///
    /// If the job refuses the child, for example because its active-process
    /// limit is reached, the call fails and no process is created. The call
    /// needs Windows 10 or Windows Server 2016; on an older system it fails
    /// instead of assigning the child to the job after creating it.
    pub fn spawn_suspended_in_job(&mut self, job: &Job) -> io::Result<SuspendedChild> {
        self.create_suspended(Some(job))
    }

    /// Creates the child inside `job` and lets it run. What that guarantees,
    /// and when it fails, is described at
    /// [`spawn_suspended_in_job`](Self::spawn_suspended_in_job).
    pub fn spawn_in_job(&mut self, job: &Job) -> io::Result<Process> {
        self.spawn_suspended_in_job(job)?.resume()
    }

    /// Creates the child and lets it run.
    pub fn spawn(&mut self) -> io::Result<Process> {
        self.spawn_suspended()?.resume()
    }

    fn create_suspended(&mut self, job: Option<&Job>) -> io::Result<SuspendedChild> {
        if self.token.is_some() && self.app_container.is_some() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "an AppContainer launch cannot use as_user: the profile belongs to the calling user, not the token's user",
            ));
        }

        let application = wide_null(&self.executable)?;
        let mut command_line = command_line(&self.executable, &self.arguments)?;
        let current_dir = self.current_dir.as_ref().map(wide_null).transpose()?;
        let environment = self.environment.block()?;
        let mut desktop = self.desktop.as_ref().map(wide_null).transpose()?;

        let standard = if self.stdin.is_some() || self.stdout.is_some() || self.stderr.is_some() {
            Some([
                standard_slot(self.stdin)?,
                standard_slot(self.stdout)?,
                standard_slot(self.stderr)?,
            ])
        } else {
            None
        };
        let mut handles: Vec<HANDLE> = Vec::new();
        if let Some(standard) = &standard {
            handles.extend(standard.iter().map(AsRawHandle::as_raw_handle));
        }
        handles.extend(self.inherited.iter().map(AsRawHandle::as_raw_handle));

        if let Some(token) = self.token {
            if !handles.is_empty() && token.session_id()? != current_session_id()? {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "a child in another session cannot inherit handles",
                ));
            }
        }

        let mut attributes = if handles.is_empty() && self.app_container.is_none() && job.is_none()
        {
            None
        } else {
            Some(AttributeList::with_attributes(
                &handles,
                self.app_container,
                job,
            )?)
        };
        let inheritable = InheritableWindow::open(&self.inherited)?;

        let mut startup = STARTUPINFOEXW::default();
        let mut flags = self.extra_flags | CREATE_SUSPENDED;
        if let Some(list) = attributes.as_mut() {
            startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
            startup.lpAttributeList = list.as_mut_ptr();
            flags |= EXTENDED_STARTUPINFO_PRESENT;
        } else {
            startup.StartupInfo.cb = size_of::<STARTUPINFOW>() as u32;
        }
        if let Some([input, output, error]) = &standard {
            startup.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
            startup.StartupInfo.hStdInput = input.as_raw_handle();
            startup.StartupInfo.hStdOutput = output.as_raw_handle();
            startup.StartupInfo.hStdError = error.as_raw_handle();
        }
        if let Some(desktop) = desktop.as_mut() {
            startup.StartupInfo.lpDesktop = desktop.as_mut_ptr();
        }
        if self.create_no_window {
            flags |= CREATE_NO_WINDOW;
        }
        if environment.is_some() {
            flags |= CREATE_UNICODE_ENVIRONMENT;
        }
        let environment_pointer = environment
            .as_ref()
            .map_or(null(), |block| block.as_ptr().cast());
        let directory_pointer = current_dir
            .as_ref()
            .map_or(null(), |directory| directory.as_ptr());
        let inherit_handles = i32::from(!handles.is_empty());

        let mut information = PROCESS_INFORMATION::default();
        let created = match self.token {
            // SAFETY: `application`, `directory_pointer` (when non-null) and
            // the writable `command_line` are NUL-terminated buffers that
            // outlive the call; the environment pointer, when non-null, is a
            // double-NUL-terminated UTF-16 block flagged with
            // CREATE_UNICODE_ENVIRONMENT; `startup` carries live standard
            // handles and, when present, an initialized attribute list whose
            // handles are all inheritable for this call; `information` is a
            // local out structure. The attribute list owns its handle array,
            // its boxed job handle and its boxed security-capabilities value;
            // the profile borrow keeps all referenced SIDs live, and the job
            // borrow keeps the job handle open, through process creation.
            None => unsafe {
                CreateProcessW(
                    application.as_ptr(),
                    command_line.as_mut_ptr(),
                    null(),
                    null(),
                    inherit_handles,
                    flags,
                    environment_pointer,
                    directory_pointer,
                    &startup.StartupInfo,
                    &mut information,
                )
            },
            // SAFETY: as above, including attribute-list ownership of handles,
            // any boxed job handle with its borrowed job, and any boxed
            // security capabilities with their borrowed profile; the token is
            // a live primary token borrowed for this launch.
            Some(token) => unsafe {
                CreateProcessAsUserW(
                    token.as_raw_handle(),
                    application.as_ptr(),
                    command_line.as_mut_ptr(),
                    null(),
                    null(),
                    inherit_handles,
                    flags,
                    environment_pointer,
                    directory_pointer,
                    &startup.StartupInfo,
                    &mut information,
                )
            },
        };
        // Read the error before cleanup makes further Win32 calls.
        let failure = (created == 0).then(io::Error::last_os_error);
        drop(inheritable);
        drop(attributes);
        drop(standard);
        if let Some(error) = failure {
            return Err(error);
        }

        // Both handles are owned from here, so neither can leak if the other
        // turns out to be unusable.
        let process = owned_from_creation(information.hProcess);
        let thread = owned_from_creation(information.hThread);
        match (process, thread) {
            (Ok(process), Ok(thread)) => Ok(SuspendedChild {
                process: Some(Process::from_owned(process, ProcessAccess::AsCreated)),
                thread: Some(thread),
                pid: information.dwProcessId,
            }),
            (Ok(process), Err(error)) => {
                // SAFETY: the process handle is live and carries the
                // termination right CreateProcess granted; no pointers.
                unsafe { TerminateProcess(process.as_raw_handle(), 1) };
                Err(error)
            }
            (Err(error), _) => Err(error),
        }
    }
}

/// A child created suspended. Dropping it without calling
/// [`resume`](Self::resume) terminates it, so a launch that fails half-way
/// never leaves a frozen process behind.
#[derive(Debug)]
pub struct SuspendedChild {
    process: Option<Process>,
    thread: Option<OwnedHandle>,
    pid: u32,
}

impl SuspendedChild {
    /// The child's process ID.
    pub fn pid(&self) -> u32 {
        self.pid
    }

    /// The child's process handle, for identity checks and other preparation
    /// before it runs. To put the child in a job, create it there with
    /// [`Launch::spawn_suspended_in_job`].
    pub fn process(&self) -> &Process {
        self.process.as_ref().expect("present until consumed")
    }

    /// Starts the child's initial thread and hands over the process handle.
    /// If the thread cannot be resumed, the child is terminated.
    pub fn resume(mut self) -> io::Result<Process> {
        let thread = self.thread.take().expect("present until consumed");
        // SAFETY: the thread handle is live and owned; the call takes no
        // pointers.
        if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
            return Err(io::Error::last_os_error());
        }
        Ok(self.process.take().expect("present until consumed"))
    }

    /// Terminates the child without ever letting it run.
    pub fn terminate(mut self, exit_code: u32) -> io::Result<()> {
        self.process
            .take()
            .expect("present until consumed")
            .terminate(exit_code)
    }
}

impl Drop for SuspendedChild {
    fn drop(&mut self) {
        if let Some(process) = self.process.take() {
            let _ = process.terminate(1);
        }
    }
}

/// An anonymous pipe as `(read, write)`. Neither end is inheritable; give an
/// end to a child with [`Launch::stdout`], [`Launch::stdin`] or
/// [`Launch::inherit`].
pub fn anonymous_pipe() -> io::Result<(OwnedHandle, OwnedHandle)> {
    let mut read = null_mut();
    let mut write = null_mut();
    // SAFETY: both out pointers are locals; null security attributes create
    // non-inheritable ends.
    if unsafe { CreatePipe(&mut read, &mut write, null(), 0) } == 0 {
        return Err(io::Error::last_os_error());
    }
    let read = owned_from_creation(read);
    let write = owned_from_creation(write);
    Ok((read?, write?))
}

/// A read/write handle to the `NUL` device, which discards writes and reads
/// as end-of-file.
pub fn null_device() -> io::Result<OwnedHandle> {
    open_null(false)
}

/// Reads `handle` to end-of-stream, keeping at most `maximum + 1` bytes so a
/// caller can tell "exactly the bound" from "over the bound". A broken pipe
/// counts as end-of-stream.
pub fn read_to_end_bounded(handle: &impl AsHandle, maximum: usize) -> io::Result<Vec<u8>> {
    let raw = handle.as_handle().as_raw_handle();
    let mut output = Vec::new();
    let mut buffer = [0_u8; 4096];
    loop {
        let mut bytes_read = 0;
        // SAFETY: the handle is live for the call; `buffer` is writable for
        // its full length, which is what the length argument states.
        let read = unsafe {
            ReadFile(
                raw,
                buffer.as_mut_ptr(),
                buffer.len() as u32,
                &mut bytes_read,
                null_mut(),
            )
        };
        if read == 0 {
            let error = io::Error::last_os_error();
            if error.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
                break;
            }
            return Err(error);
        }
        if bytes_read == 0 {
            break;
        }
        let remaining = maximum.saturating_add(1).saturating_sub(output.len());
        output.extend_from_slice(&buffer[..(bytes_read as usize).min(remaining)]);
    }
    Ok(output)
}

/// An inheritable copy of a standard handle for one launch, or the `NUL`
/// device when the slot was left unset.
fn standard_slot(handle: Option<BorrowedHandle<'_>>) -> io::Result<OwnedHandle> {
    match handle {
        Some(handle) => duplicate(handle, true),
        None => open_null(true),
    }
}

fn duplicate(handle: BorrowedHandle<'_>, inheritable: bool) -> io::Result<OwnedHandle> {
    let mut copy = null_mut();
    // SAFETY: the source handle is live for the call, both process arguments
    // are the current-process pseudo-handle, and `copy` is a local out value.
    let duplicated = unsafe {
        DuplicateHandle(
            current_process(),
            handle.as_raw_handle(),
            current_process(),
            &mut copy,
            0,
            i32::from(inheritable),
            DUPLICATE_SAME_ACCESS,
        )
    };
    if duplicated == 0 {
        return Err(io::Error::last_os_error());
    }
    owned_from_creation(copy)
}

fn open_null(inheritable: bool) -> io::Result<OwnedHandle> {
    let security = SECURITY_ATTRIBUTES {
        nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: null_mut(),
        bInheritHandle: i32::from(inheritable),
    };
    let name = wide_null("NUL")?;
    // SAFETY: `name` is NUL-terminated and the attribute block outlives the
    // call; no template handle is passed.
    let handle = unsafe {
        CreateFileW(
            name.as_ptr(),
            FILE_GENERIC_READ | FILE_GENERIC_WRITE,
            FILE_SHARE_READ | FILE_SHARE_WRITE,
            &security,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            null_mut(),
        )
    };
    owned_from_creation(handle)
}

/// Makes the launch's private handle copies inheritable, and makes them
/// private again when dropped.
struct InheritableWindow<'h> {
    handles: &'h [OwnedHandle],
    opened: usize,
}

impl<'h> InheritableWindow<'h> {
    fn open(handles: &'h [OwnedHandle]) -> io::Result<Self> {
        let mut window = Self { handles, opened: 0 };
        for handle in handles {
            set_inheritable(handle.as_raw_handle(), true)?;
            window.opened += 1;
        }
        Ok(window)
    }
}

impl Drop for InheritableWindow<'_> {
    fn drop(&mut self) {
        for handle in &self.handles[..self.opened] {
            let _ = set_inheritable(handle.as_raw_handle(), false);
        }
    }
}

fn set_inheritable(handle: RawHandle, inheritable: bool) -> io::Result<()> {
    let value = if inheritable { HANDLE_FLAG_INHERIT } else { 0 };
    // SAFETY: the handle is owned by the launch and live; the mask and value
    // are integers.
    if unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, value) } == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(())
}

/// A process-thread attribute list owning every value to which its
/// handle-list, job-list and security-capabilities attributes point. Storage is
/// allocated to the size Windows reports and the initialized list is deleted
/// when dropped.
struct AttributeList<'a> {
    storage: Vec<usize>,
    initialized: bool,
    /// The list stores a pointer to the handle array, so the array lives here.
    _handles: Vec<HANDLE>,
    /// Boxed so the job-list attribute points to a stable address.
    _job: Option<Box<HANDLE>>,
    /// Boxed so the security-capabilities attribute points to a stable address.
    _security_capabilities: Option<Box<SECURITY_CAPABILITIES>>,
    /// Keeps alive the profile with every SID the boxed capabilities refer to,
    /// and the job whose handle the boxed job handle names.
    _borrows: PhantomData<(&'a AppContainerProfile, &'a Job)>,
}

impl<'a> AttributeList<'a> {
    fn with_attributes(
        handles: &[HANDLE],
        app_container: Option<&'a AppContainerProfile>,
        job: Option<&'a Job>,
    ) -> io::Result<Self> {
        let mut count = u32::from(!handles.is_empty());
        count += u32::from(app_container.is_some());
        count += u32::from(job.is_some());
        let mut bytes = 0_usize;
        // SAFETY: a null list with a size probe is the documented way to ask
        // for the required byte count; the out pointer is a local.
        unsafe { InitializeProcThreadAttributeList(null_mut(), count, 0, &mut bytes) };
        if bytes == 0 {
            return Err(io::Error::last_os_error());
        }
        let mut list = Self {
            storage: vec![0_usize; bytes.div_ceil(size_of::<usize>())],
            initialized: false,
            _handles: handles.to_vec(),
            _job: job.map(|job| Box::new(job.as_raw_handle())),
            _security_capabilities: app_container
                .map(AppContainerProfile::security_capabilities)
                .map(Box::new),
            _borrows: PhantomData,
        };
        // SAFETY: `storage` is at least `bytes` long and word-aligned, and the
        // list is deleted in `Drop` only after this initialization succeeds.
        let initialized =
            unsafe { InitializeProcThreadAttributeList(list.as_mut_ptr(), count, 0, &mut bytes) };
        if initialized == 0 {
            return Err(io::Error::last_os_error());
        }
        list.initialized = true;
        if !list._handles.is_empty() {
            let pointer = list._handles.as_ptr();
            let length = std::mem::size_of_val(list._handles.as_slice());
            // SAFETY: the list is initialized; the handle array is owned by
            // the list and stays in the same allocation for this call.
            let updated = unsafe {
                UpdateProcThreadAttribute(
                    list.as_mut_ptr(),
                    0,
                    PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
                    pointer.cast(),
                    length,
                    null_mut(),
                    null(),
                )
            };
            if updated == 0 {
                return Err(io::Error::last_os_error());
            }
        }
        let job = list._job.as_deref().map(|handle| handle as *const HANDLE);
        if let Some(job) = job {
            // SAFETY: the list is initialized; it points to the boxed job
            // handle owned by `list`, and the job borrow keeps that handle
            // open until after CreateProcess and attribute-list deletion.
            let updated = unsafe {
                UpdateProcThreadAttribute(
                    list.as_mut_ptr(),
                    0,
                    PROC_THREAD_ATTRIBUTE_JOB_LIST as usize,
                    job.cast(),
                    size_of::<HANDLE>(),
                    null_mut(),
                    null(),
                )
            };
            if updated == 0 {
                return Err(io::Error::last_os_error());
            }
        }
        let capabilities = list
            ._security_capabilities
            .as_deref_mut()
            .map(|value| value as *mut SECURITY_CAPABILITIES);
        if let Some(capabilities) = capabilities {
            // SAFETY: the initialized list points to the boxed value owned by
            // `list`; its profile borrow keeps every referenced SID and SID
            // array live until after CreateProcess and attribute-list deletion.
            let updated = unsafe {
                UpdateProcThreadAttribute(
                    list.as_mut_ptr(),
                    0,
                    PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES as usize,
                    capabilities.cast(),
                    size_of::<SECURITY_CAPABILITIES>(),
                    null_mut(),
                    null(),
                )
            };
            if updated == 0 {
                return Err(io::Error::last_os_error());
            }
        }
        Ok(list)
    }

    fn as_mut_ptr(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
        self.storage.as_mut_ptr().cast()
    }
}

impl Drop for AttributeList<'_> {
    fn drop(&mut self) {
        if self.initialized {
            // SAFETY: the list was initialized in `with_attributes`, has not
            // been deleted, and all pointed-to handle and security-capabilities
            // storage remains owned by `self` until this drop completes.
            unsafe { DeleteProcThreadAttributeList(self.as_mut_ptr()) };
        }
    }
}

/// Environment changes requested for a launch.
#[derive(Debug, Default)]
struct EnvironmentPlan {
    clear: bool,
    /// In call order; `None` removes the variable.
    changes: Vec<(OsString, Option<OsString>)>,
}

impl EnvironmentPlan {
    /// The Unicode environment block, or `None` to inherit this process's.
    fn block(&self) -> io::Result<Option<Vec<u16>>> {
        if !self.clear && self.changes.is_empty() {
            return Ok(None);
        }
        let mut entries: Vec<(Vec<u16>, Vec<u16>)> = Vec::new();
        if !self.clear {
            for (name, value) in std::env::vars_os() {
                upsert(
                    &mut entries,
                    name.encode_wide().collect(),
                    value.encode_wide().collect(),
                );
            }
        }
        for (name, value) in &self.changes {
            let name: Vec<u16> = name.encode_wide().collect();
            if name.is_empty() || name.contains(&0) || name.contains(&u16::from(b'=')) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "environment names must be non-empty and contain neither '=' nor NUL",
                ));
            }
            match value {
                Some(value) => {
                    let value: Vec<u16> = value.encode_wide().collect();
                    if value.contains(&0) {
                        return Err(io::Error::new(
                            io::ErrorKind::InvalidInput,
                            "environment values must not contain NUL",
                        ));
                    }
                    upsert(&mut entries, name, value);
                }
                None => entries.retain(|(existing, _)| {
                    compare_environment_names(existing, &name) != Ordering::Equal
                }),
            }
        }
        // CreateProcess requires the block sorted by name, without regard to
        // case.
        entries.sort_by(|left, right| compare_environment_names(&left.0, &right.0));
        let mut block = Vec::new();
        for (name, value) in entries {
            block.extend(name);
            block.push(u16::from(b'='));
            block.extend(value);
            block.push(0);
        }
        if block.is_empty() {
            // An empty Unicode block is two NUL units.
            block.push(0);
        }
        block.push(0);
        Ok(Some(block))
    }
}

fn upsert(entries: &mut Vec<(Vec<u16>, Vec<u16>)>, name: Vec<u16>, value: Vec<u16>) {
    entries.retain(|(existing, _)| compare_environment_names(existing, &name) != Ordering::Equal);
    entries.push((name, value));
}

fn compare_environment_names(left: &[u16], right: &[u16]) -> Ordering {
    let (Ok(left_length), Ok(right_length)) =
        (i32::try_from(left.len()), i32::try_from(right.len()))
    else {
        return left.cmp(right);
    };
    // SAFETY: both slices are live and their exact lengths are passed, so no
    // terminator is read; the comparison ignores case ordinally.
    let result = unsafe {
        CompareStringOrdinal(left.as_ptr(), left_length, right.as_ptr(), right_length, 1)
    };
    match result {
        CSTR_LESS_THAN => Ordering::Less,
        CSTR_EQUAL => Ordering::Equal,
        CSTR_GREATER_THAN => Ordering::Greater,
        _ => left.cmp(right),
    }
}

/// The full command line: the executable, always quoted, followed by the
/// arguments, quoted only where `CommandLineToArgvW` needs it.
fn command_line(executable: &Path, arguments: &[OsString]) -> io::Result<Vec<u16>> {
    let executable: Vec<u16> = executable.as_os_str().encode_wide().collect();
    if executable.contains(&0) || executable.contains(&u16::from(b'"')) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "the executable path contains a NUL or a quote",
        ));
    }
    // The program name is parsed without backslash escapes, so it is wrapped
    // in quotes verbatim.
    let mut line = vec![u16::from(b'"')];
    line.extend(executable);
    line.push(u16::from(b'"'));
    for argument in arguments {
        line.push(u16::from(b' '));
        append_argument(&mut line, argument)?;
    }
    line.push(0);
    Ok(line)
}

/// The arguments alone, NUL-terminated, for `ShellExecuteExW`'s parameters.
pub(crate) fn command_line_tail(arguments: &[OsString]) -> io::Result<Vec<u16>> {
    let mut line = Vec::new();
    for (index, argument) in arguments.iter().enumerate() {
        if index != 0 {
            line.push(u16::from(b' '));
        }
        append_argument(&mut line, argument)?;
    }
    line.push(0);
    Ok(line)
}

fn append_argument(line: &mut Vec<u16>, argument: &OsStr) -> io::Result<()> {
    let units: Vec<u16> = argument.encode_wide().collect();
    if units.contains(&0) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "an argument contains a NUL",
        ));
    }
    let quote = u16::from(b'"');
    let backslash = u16::from(b'\\');
    let needs_quotes = units.is_empty()
        || units
            .iter()
            .any(|unit| matches!(*unit, 0x09..=0x0d | 0x20 | 0x22));
    if !needs_quotes {
        line.extend(units);
        return Ok(());
    }
    line.push(quote);
    let mut backslashes = 0_usize;
    for unit in units {
        if unit == backslash {
            backslashes += 1;
        } else if unit == quote {
            line.extend(std::iter::repeat(backslash).take(backslashes * 2 + 1));
            line.push(unit);
            backslashes = 0;
        } else {
            line.extend(std::iter::repeat(backslash).take(backslashes));
            line.push(unit);
            backslashes = 0;
        }
    }
    line.extend(std::iter::repeat(backslash).take(backslashes * 2));
    line.push(quote);
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::fs::File;
    use std::io::{Read, Write};
    use std::os::windows::ffi::OsStringExt;
    use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle};
    use std::path::Path;
    use std::time::{Duration, Instant};

    use windows_sys::Win32::Foundation::{ERROR_NOT_ENOUGH_QUOTA, GENERIC_READ, GENERIC_WRITE};
    use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
    use windows_sys::Win32::System::JobObjects::IsProcessInJob;

    use super::{
        anonymous_pipe, command_line, command_line_tail, null_device, read_to_end_bounded, Launch,
    };
    use crate::handle::WaitOutcome;
    use crate::job::{Job, JobLimits};
    use crate::pipe::{PipeDirection, PipeServer, PipeWait};
    use crate::process::ProcessAccess;
    use crate::security::{
        current_user_sid_string, ObjectSecurityDescriptor, OwnedSid, SecurityDescriptor,
    };
    use crate::{AppContainerAccess, AppContainerProfile, PrimaryToken};

    fn cmd() -> std::path::PathBuf {
        let root = std::env::var_os("SystemRoot").expect("SystemRoot is set");
        Path::new(&root).join("System32").join("cmd.exe")
    }

    struct ProfileGuard(Option<AppContainerProfile>);

    impl ProfileGuard {
        fn new(suffix: &str) -> Self {
            let name = format!("win-custody-test-{}-{suffix}", std::process::id());
            assert!(name.encode_utf16().count() <= 64);
            Self(Some(
                AppContainerProfile::create_or_open(
                    &name,
                    "Win Custody test",
                    "Win Custody AppContainer launch test",
                )
                .unwrap(),
            ))
        }

        fn with_capabilities(suffix: &str, capabilities: &[&str]) -> Self {
            let name = format!("win-custody-test-{}-{suffix}", std::process::id());
            assert!(name.encode_utf16().count() <= 64);
            Self(Some(
                AppContainerProfile::create_or_open_with_capabilities(
                    &name,
                    "Win Custody test",
                    "Win Custody AppContainer launch test",
                    capabilities,
                )
                .unwrap(),
            ))
        }

        fn profile(&self) -> &AppContainerProfile {
            self.0.as_ref().expect("profile present until guard drop")
        }
    }

    impl Drop for ProfileGuard {
        fn drop(&mut self) {
            if let Some(profile) = self.0.take() {
                let _ = profile.delete();
            }
        }
    }

    fn rendered(arguments: &[&str]) -> String {
        let arguments: Vec<OsString> = arguments.iter().map(OsString::from).collect();
        let units = command_line(Path::new(r"C:\a b\x.exe"), &arguments).unwrap();
        String::from_utf16(&units[..units.len() - 1]).unwrap()
    }

    #[test]
    fn arguments_are_quoted_only_where_the_child_parser_needs_it() {
        assert_eq!(rendered(&[]), r#""C:\a b\x.exe""#);
        assert_eq!(rendered(&["plain"]), r#""C:\a b\x.exe" plain"#);
        assert_eq!(rendered(&[""]), r#""C:\a b\x.exe" """#);
        assert_eq!(rendered(&["two words"]), r#""C:\a b\x.exe" "two words""#);
        assert_eq!(
            rendered(&["with \"quote\""]),
            r#""C:\a b\x.exe" "with \"quote\"""#
        );
        assert_eq!(
            rendered(&[r"trailing\ x\"]),
            r#""C:\a b\x.exe" "trailing\ x\\""#
        );
        assert_eq!(rendered(&[r"no\space\"]), r#""C:\a b\x.exe" no\space\"#);
    }

    #[test]
    fn unpaired_surrogates_survive_quoting() {
        let value = OsString::from_wide(&[0xd800, u16::from(b' '), u16::from(b'x')]);
        let units = command_line_tail(&[value]).unwrap();
        assert_eq!(
            units,
            [
                u16::from(b'"'),
                0xd800,
                u16::from(b' '),
                u16::from(b'x'),
                u16::from(b'"'),
                0
            ]
        );
    }

    #[test]
    fn nuls_and_quotes_in_the_program_name_are_rejected() {
        assert!(command_line(Path::new("a\"b.exe"), &[]).is_err());
        assert!(command_line(Path::new("a.exe"), &[OsString::from("a\0b")]).is_err());
    }

    #[test]
    fn a_child_in_a_kill_on_close_job_reports_its_exit_code() {
        let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
        let child = Launch::new(cmd())
            .args(["/d", "/c", "exit 7"])
            .spawn_in_job(&job)
            .unwrap();
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(child.exit_code().unwrap(), Some(7));
    }

    #[test]
    fn an_appcontainer_child_is_created_in_its_job_and_keeps_captured_stdio() {
        let profile = ProfileGuard::new("grant");
        assert!(profile
            .profile()
            .sid_string()
            .unwrap()
            .starts_with("S-1-15-2-"));
        let directory = tempfile::tempdir().unwrap();
        profile
            .profile()
            .grant_path(directory.path(), AppContainerAccess::ReadWrite)
            .unwrap();
        let job = Job::create(&JobLimits::new().kill_on_close(true).active_processes(1)).unwrap();
        let (read, write) = anonymous_pipe().unwrap();
        let child = Launch::new(cmd())
            .args([
                "/d",
                "/c",
                "echo appcontainer-ok > marker.txt & type marker.txt",
            ])
            .current_dir(directory.path())
            .app_container(profile.profile())
            .stdout(&write)
            .spawn_in_job(&job)
            .unwrap();
        assert!(child.is_app_container().unwrap());
        assert!(!child.has_capability("internetClient").unwrap());
        drop(write);
        let output = read_to_end_bounded(&read, 4096).unwrap();
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(String::from_utf8_lossy(&output).trim(), "appcontainer-ok");
        assert_eq!(
            std::fs::read_to_string(directory.path().join("marker.txt"))
                .unwrap()
                .trim(),
            "appcontainer-ok"
        );
    }

    #[test]
    fn an_appcontainer_child_cannot_write_outside_a_granted_directory() {
        let profile = ProfileGuard::new("confine");
        let granted = tempfile::tempdir().unwrap();
        let ungranted = tempfile::tempdir().unwrap();
        profile
            .profile()
            .grant_path(granted.path(), AppContainerAccess::ReadWrite)
            .unwrap();
        let marker = ungranted.path().join("forbidden-marker.txt");
        assert_eq!(granted.path().parent(), ungranted.path().parent());
        let ungranted_name = ungranted
            .path()
            .file_name()
            .and_then(|name| name.to_str())
            .expect("tempfile directory names are Unicode");
        assert!(!ungranted_name.chars().any(char::is_whitespace));
        let command = format!(r"echo x > ..\{ungranted_name}\forbidden-marker.txt");

        let control = Launch::new(cmd())
            .args(["/d", "/c", &command])
            .current_dir(granted.path())
            .spawn()
            .unwrap();
        assert_eq!(
            control.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(control.exit_code().unwrap(), Some(0));
        assert!(marker.exists());
        std::fs::remove_file(&marker).unwrap();

        // The first marker proves cmd ran inside the container, so a failure to
        // start cannot pass for confinement.
        let contained_command = format!("echo ok > ran-marker.txt & {command}");
        let child = Launch::new(cmd())
            .args(["/d", "/c", &contained_command])
            .current_dir(granted.path())
            .app_container(profile.profile())
            .spawn()
            .unwrap();
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert!(granted.path().join("ran-marker.txt").exists());
        assert_ne!(child.exit_code().unwrap(), Some(0));
        assert!(!marker.exists());
    }

    #[test]
    fn an_appcontainer_child_token_contains_its_configured_capability() {
        let profile = ProfileGuard::with_capabilities("capability", &["internetClient"]);
        let child = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .app_container(profile.profile())
            .spawn_suspended()
            .unwrap();
        assert!(child.process().has_capability("internetClient").unwrap());
        assert!(!child
            .process()
            .has_capability("internetClientServer")
            .unwrap());
        child.process().terminate(0).unwrap();
        assert_eq!(
            child.process().wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
    }

    #[test]
    fn ensuring_path_access_writes_only_missing_rights() {
        let profile = ProfileGuard::new("ensure");
        let directory = tempfile::tempdir().unwrap();
        assert!(profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());
        assert!(!profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());
        assert!(profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadWriteExecute)
            .unwrap());
    }

    #[test]
    fn all_application_packages_access_avoids_writing_the_dacl() {
        let profile = ProfileGuard::new("packages-access");
        let directory = tempfile::tempdir().unwrap();
        let current_user = current_user_sid_string().unwrap();
        let descriptor = SecurityDescriptor::from_sddl(&format!(
            "D:P(A;OICI;FA;;;{current_user})(A;OICI;GRGX;;;AC)"
        ))
        .unwrap();
        descriptor.apply_to_tree(directory.path(), true).unwrap();
        let current_user = OwnedSid::from_string(&current_user).unwrap();
        let packages = OwnedSid::from_string("AC").unwrap();
        let before = ObjectSecurityDescriptor::query_file(directory.path()).unwrap();
        let before: Vec<_> = before
            .dacl()
            .unwrap()
            .allowed_aces()
            .map(|ace| {
                (
                    ace.flags(),
                    ace.mask(),
                    ace.trustee_matches(&current_user),
                    ace.trustee_matches(&packages),
                )
            })
            .collect();

        assert!(!profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());

        let profile_sid = OwnedSid::from_string(&profile.profile().sid_string().unwrap()).unwrap();
        let after = ObjectSecurityDescriptor::query_file(directory.path()).unwrap();
        let dacl = after.dacl().unwrap();
        assert!(!dacl
            .allowed_aces()
            .any(|ace| ace.trustee_matches(&profile_sid)));
        let after: Vec<_> = dacl
            .allowed_aces()
            .map(|ace| {
                (
                    ace.flags(),
                    ace.mask(),
                    ace.trustee_matches(&current_user),
                    ace.trustee_matches(&packages),
                )
            })
            .collect();
        assert_eq!(after, before);
    }

    #[test]
    fn a_profile_deny_precedes_the_package_allow() {
        let profile = ProfileGuard::new("denied-execute");
        let directory = tempfile::tempdir().unwrap();
        let current_user = current_user_sid_string().unwrap();
        let profile_sid = profile.profile().sid_string().unwrap();
        let descriptor = SecurityDescriptor::from_sddl(&format!(
            "D:P(A;OICI;FA;;;{current_user})(D;OICI;GX;;;{profile_sid})(A;OICI;GRGX;;;AC)"
        ))
        .unwrap();
        descriptor.apply_to_tree(directory.path(), true).unwrap();

        assert!(profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());
    }

    #[test]
    fn an_inherit_only_package_rule_does_not_grant_the_directory_access() {
        let profile = ProfileGuard::new("inherit-only");
        let directory = tempfile::tempdir().unwrap();
        let current_user = current_user_sid_string().unwrap();
        let descriptor = SecurityDescriptor::from_sddl(&format!(
            "D:P(A;OICI;FA;;;{current_user})(A;OICIIO;GRGX;;;AC)"
        ))
        .unwrap();
        descriptor.apply_to_tree(directory.path(), true).unwrap();

        assert!(profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());
    }

    #[test]
    fn repeated_path_access_checks_finish_without_authz_delay() {
        let profile = ProfileGuard::new("ensure-timing");
        let directory = tempfile::tempdir().unwrap();
        assert!(profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());

        let started = Instant::now();
        for _ in 0..20 {
            assert!(!profile
                .profile()
                .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
                .unwrap());
        }
        let elapsed = started.elapsed();
        eprintln!("20 repeated ensure_path_access calls took {elapsed:?}");
        assert!(elapsed < Duration::from_secs(2), "elapsed: {elapsed:?}");
    }

    #[test]
    fn read_execute_grant_includes_file_execute_rights() {
        let profile = ProfileGuard::new("execute-rights");
        let directory = tempfile::tempdir().unwrap();
        profile
            .profile()
            .grant_path(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap();
        let rights = profile
            .profile()
            .effective_path_rights(directory.path())
            .unwrap();
        assert_eq!(rights & FILE_GENERIC_EXECUTE, FILE_GENERIC_EXECUTE);
    }

    const APPCONTAINER_SELF_CHECK: &str = "WIN_CUSTODY_TEST_SELF_CHECK";

    #[test]
    #[ignore = "run by appcontainer_capability_is_visible_inside_the_child"]
    fn appcontainer_process_reports_its_capability() {
        if std::env::var_os(APPCONTAINER_SELF_CHECK) != Some(OsString::from("1")) {
            return;
        }
        let process =
            crate::Process::open(std::process::id(), ProcessAccess::QueryLimited).unwrap();
        assert!(process.is_app_container().unwrap());
        assert!(process.has_capability("internetClient").unwrap());
        assert!(!process.has_capability("internetClientServer").unwrap());
    }

    #[test]
    fn appcontainer_capability_is_visible_inside_the_child() {
        let profile = ProfileGuard::with_capabilities("self-check", &["internetClient"]);
        let current =
            crate::Process::open(std::process::id(), ProcessAccess::QueryLimited).unwrap();
        assert!(!current.has_capability("internetClient").unwrap());
        let directory = tempfile::tempdir().unwrap();
        let executable = directory.path().join("win-custody-self-check.exe");
        std::fs::copy(std::env::current_exe().unwrap(), &executable).unwrap();
        assert!(profile
            .profile()
            .ensure_path_access(directory.path(), AppContainerAccess::ReadExecute)
            .unwrap());
        let child = Launch::new(&executable)
            .args([
                "--exact",
                "launch::tests::appcontainer_process_reports_its_capability",
                "--ignored",
            ])
            .env(APPCONTAINER_SELF_CHECK, "1")
            .app_container(profile.profile())
            .spawn_suspended()
            .unwrap();
        assert!(child.process().has_capability("internetClient").unwrap());
        let child = child.resume().unwrap();
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(child.exit_code().unwrap(), Some(0));
    }

    #[test]
    fn as_user_and_appcontainer_are_rejected_before_launch_conversion() {
        let profile = ProfileGuard::new("as-user");
        let token = PrimaryToken::duplicate_current_process().unwrap();
        let error = Launch::new(Path::new("contains\0nul.exe"))
            .as_user(&token)
            .app_container(profile.profile())
            .spawn()
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
        assert_eq!(
            error.to_string(),
            "an AppContainer launch cannot use as_user: the profile belongs to the calling user, not the token's user"
        );
    }

    #[test]
    fn appcontainer_launch_composes_with_a_low_integrity_named_pipe() {
        let profile = ProfileGuard::new("pipe");
        let pipe_name = format!(r"\\.\pipe\win-custody-appcontainer-{}", std::process::id());
        let descriptor = SecurityDescriptor::from_sddl(&format!(
            "D:P(A;;0x{:08X};;;{})(A;;0x{:08X};;;{})S:(ML;;NW;;;LW)",
            GENERIC_READ | GENERIC_WRITE,
            current_user_sid_string().unwrap(),
            GENERIC_READ | GENERIC_WRITE,
            profile.profile().sid_string().unwrap(),
        ))
        .unwrap();
        let server = PipeServer::create(&pipe_name, PipeDirection::Inbound, &descriptor).unwrap();
        let command = format!("echo appcontainer-pipe>{pipe_name}");
        let child = Launch::new(cmd())
            .args(["/d", "/c", &command])
            .app_container(profile.profile())
            .spawn()
            .unwrap();
        server
            .connect(&PipeWait::within(Duration::from_secs(30)).with_peer(&child))
            .unwrap();
        assert_eq!(server.client_process_id().unwrap(), child.pid().unwrap());
        let mut payload = [0_u8; 128];
        let read = server
            .read(
                &mut payload,
                &PipeWait::within(Duration::from_secs(30)).with_peer(&child),
            )
            .unwrap();
        assert_eq!(
            String::from_utf8_lossy(&payload[..read]).trim(),
            "appcontainer-pipe"
        );
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(child.exit_code().unwrap(), Some(0));
    }

    #[test]
    fn closing_the_job_kills_the_child() {
        let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
        let child = Launch::new(cmd())
            .args(["/d", "/c", "ping -n 60 127.0.0.1 >NUL"])
            .spawn_in_job(&job)
            .unwrap();
        assert_eq!(
            child.wait(Some(Duration::from_millis(200))).unwrap(),
            WaitOutcome::TimedOut
        );
        drop(job);
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
    }

    /// Turns `supervisor_process_for_the_killed_parent_test` from a no-op into
    /// the supervisor. Its value is the inherited handle on which the
    /// supervisor reports its child's process ID.
    const SUPERVISOR_REPORT: &str = "WIN_CUSTODY_TEST_SUPERVISOR_REPORT";

    /// Terminates a process the test could not prove dead, so a failing
    /// assertion never leaves a suspended process behind.
    struct TerminateOnDrop(crate::Process);

    impl Drop for TerminateOnDrop {
        fn drop(&mut self) {
            let _ = self.0.terminate(1);
        }
    }

    /// Not a test of its own.
    /// `a_child_created_in_a_job_dies_when_its_parent_is_killed` runs this test
    /// binary again with [`SUPERVISOR_REPORT`] set, and that process is the
    /// parent that gets killed.
    #[test]
    fn supervisor_process_for_the_killed_parent_test() {
        let Some(report) = std::env::var_os(SUPERVISOR_REPORT) else {
            return;
        };
        let report: usize = report.to_str().unwrap().parse().unwrap();
        // SAFETY: the controlling test passed this value for a pipe write end
        // it let this process inherit, and nothing else here owns it.
        let mut report = unsafe { File::from_raw_handle(report as RawHandle) };
        let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
        let child = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .spawn_suspended_in_job(&job)
            .unwrap();
        report.write_all(&child.pid().to_le_bytes()).unwrap();
        // The controlling test kills this process here, while the child is
        // still suspended. If it never does, returning drops the child, which
        // terminates it.
        std::thread::sleep(Duration::from_secs(120));
    }

    fn is_in_job(process: &crate::Process, job: &Job) -> bool {
        let mut member = 0;
        // SAFETY: both handles are live for the call and `member` is a local
        // out value.
        let queried =
            unsafe { IsProcessInJob(process.as_raw_handle(), job.as_raw_handle(), &mut member) };
        assert_ne!(queried, 0, "{}", std::io::Error::last_os_error());
        member != 0
    }

    #[test]
    fn a_child_created_in_a_job_is_a_member_while_still_suspended() {
        let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
        let outside = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .spawn_suspended()
            .unwrap();
        assert!(!is_in_job(outside.process(), &job));
        let inside = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .spawn_suspended_in_job(&job)
            .unwrap();
        assert!(is_in_job(inside.process(), &job));
    }

    #[test]
    fn a_full_job_refuses_the_child_instead_of_letting_it_exist_outside() {
        let job = Job::create(&JobLimits::new().kill_on_close(true).active_processes(1)).unwrap();
        let _first = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .spawn_suspended_in_job(&job)
            .unwrap();
        let error = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .spawn_suspended_in_job(&job)
            .unwrap_err();
        assert_eq!(error.raw_os_error(), Some(ERROR_NOT_ENOUGH_QUOTA as i32));
    }

    #[test]
    fn a_child_created_in_a_job_still_receives_its_standard_output() {
        let job = Job::create(&JobLimits::new().kill_on_close(true)).unwrap();
        let (read, write) = anonymous_pipe().unwrap();
        let child = Launch::new(cmd())
            .args(["/d", "/c", "echo in-the-job"])
            .stdout(&write)
            .spawn_in_job(&job)
            .unwrap();
        drop(write);
        let output = read_to_end_bounded(&read, 4096).unwrap();
        assert_eq!(
            child.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(String::from_utf8_lossy(&output).trim(), "in-the-job");
    }

    #[test]
    fn a_child_created_in_a_job_dies_when_its_parent_is_killed() {
        let (read, write) = anonymous_pipe().unwrap();
        let input = null_device().unwrap();
        let supervisor = {
            let mut launch = Launch::new(std::env::current_exe().unwrap());
            launch
                .args([
                    "--exact",
                    "launch::tests::supervisor_process_for_the_killed_parent_test",
                ])
                .stdin(&input);
            let report = launch.inherit(&write).unwrap();
            launch.env(SUPERVISOR_REPORT, report.to_string());
            TerminateOnDrop(launch.spawn().unwrap())
        };
        drop(write);
        let mut pid = [0_u8; 4];
        File::from(read)
            .read_exact(&mut pid)
            .expect("the supervisor reports its child before it waits");
        // Opened while the supervisor still holds the child, so the process
        // ID cannot have been reused.
        let child = TerminateOnDrop(
            crate::Process::open(u32::from_le_bytes(pid), ProcessAccess::Terminate).unwrap(),
        );
        assert_eq!(
            child.0.wait(Some(Duration::from_millis(200))).unwrap(),
            WaitOutcome::TimedOut
        );

        // TerminateProcess runs none of the supervisor's destructors, so only
        // the kernel closing its job handle can end the child.
        supervisor.0.terminate(1).unwrap();
        assert_eq!(
            supervisor.0.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(
            child.0.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
    }

    #[test]
    fn standard_output_and_environment_reach_the_child() {
        let (read, write) = anonymous_pipe().unwrap();
        let child = Launch::new(cmd())
            .args(["/d", "/c", "echo %WIN_CUSTODY_PROBE%"])
            .env("WIN_CUSTODY_PROBE", "custody-ok")
            .stdout(&write)
            .spawn()
            .unwrap();
        drop(write);
        let output = read_to_end_bounded(&read, 4096).unwrap();
        child.wait(Some(Duration::from_secs(30))).unwrap();
        assert_eq!(String::from_utf8_lossy(&output).trim(), "custody-ok");
    }

    #[test]
    fn a_removed_variable_is_absent_in_the_child() {
        std::env::set_var("WIN_CUSTODY_REMOVED", "present");
        let (read, write) = anonymous_pipe().unwrap();
        let child = Launch::new(cmd())
            .args([
                "/d",
                "/c",
                "if defined WIN_CUSTODY_REMOVED (echo yes) else (echo no)",
            ])
            .env_remove("win_custody_removed")
            .stdout(&write)
            .spawn()
            .unwrap();
        drop(write);
        let output = read_to_end_bounded(&read, 4096).unwrap();
        child.wait(Some(Duration::from_secs(30))).unwrap();
        assert_eq!(String::from_utf8_lossy(&output).trim(), "no");
    }

    #[test]
    fn a_dropped_suspended_child_is_terminated() {
        let child = Launch::new(cmd())
            .args(["/d", "/c", "exit 0"])
            .spawn_suspended()
            .unwrap();
        let process = crate::process::Process::open(
            child.pid(),
            crate::process::ProcessAccess::QueryLimitedAndSynchronize,
        )
        .unwrap();
        drop(child);
        assert_eq!(
            process.wait(Some(Duration::from_secs(30))).unwrap(),
            WaitOutcome::Signaled
        );
        assert_eq!(process.exit_code().unwrap(), Some(1));
    }

    #[test]
    fn output_beyond_the_bound_is_cut_at_one_extra_byte() {
        let (read, write) = anonymous_pipe().unwrap();
        let child = Launch::new(cmd())
            .args(["/d", "/c", "echo 0123456789"])
            .stdout(&write)
            .spawn()
            .unwrap();
        drop(write);
        let output = read_to_end_bounded(&read, 4).unwrap();
        child.wait(Some(Duration::from_secs(30))).unwrap();
        assert_eq!(output, b"01234");
    }
}