subc-os 0.1.14

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
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
//! One-time Windows handoff. No pipe handle is inherited by the child.

use super::{Cached, LaunchNonce, LaunchNonceError, LaunchNonceSource};
use std::{
    ffi::OsStr,
    io,
    os::windows::{
        ffi::OsStrExt,
        io::{AsRawHandle, FromRawHandle, OwnedHandle},
    },
    ptr::{null, null_mut},
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc, OnceLock,
    },
    time::{Duration, Instant},
};
use windows_sys::Win32::{
    Foundation::{
        LocalFree, ERROR_ACCESS_DENIED, ERROR_BROKEN_PIPE, ERROR_IO_PENDING, ERROR_PIPE_BUSY,
        ERROR_PIPE_CONNECTED, ERROR_PIPE_NOT_CONNECTED, ERROR_SEM_TIMEOUT, GENERIC_READ, HANDLE,
        INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT,
    },
    Security::Cryptography::{BCryptGenRandom, BCRYPT_USE_SYSTEM_PREFERRED_RNG},
    Security::{
        Authorization::{
            ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
        },
        GetTokenInformation, TokenUser, SECURITY_ATTRIBUTES, TOKEN_QUERY, TOKEN_USER,
    },
    Storage::FileSystem::{
        CreateFileW, FlushFileBuffers, ReadFile, WriteFile, FILE_FLAG_FIRST_PIPE_INSTANCE,
        FILE_FLAG_OVERLAPPED, OPEN_EXISTING, PIPE_ACCESS_OUTBOUND, SECURITY_IDENTIFICATION,
        SECURITY_SQOS_PRESENT,
    },
    System::{
        Pipes::{
            ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, GetNamedPipeClientProcessId,
            PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_WAIT,
        },
        Threading::{
            CreateEventW, GetCurrentProcess, OpenProcess, OpenProcessToken, WaitForSingleObject,
            PROCESS_SYNCHRONIZE,
        },
        IO::{CancelIoEx, CancelSynchronousIo, GetOverlappedResult, OVERLAPPED},
    },
};

const OPEN_WINDOW: Duration = Duration::from_millis(500);
const READ_WINDOW: Duration = Duration::from_secs(2);
const POLL: Duration = Duration::from_millis(5);
const MAX_NONCE_BYTES: usize = 4096;
const CLIENT_ACCESS: u32 = 0x80100100;

fn wide(text: &OsStr) -> Vec<u16> {
    text.encode_wide().chain(Some(0)).collect()
}

fn owned(handle: HANDLE) -> io::Result<OwnedHandle> {
    if handle.is_null() || handle == INVALID_HANDLE_VALUE {
        Err(io::Error::last_os_error())
    } else {
        // SAFETY: each caller supplies a newly created, uniquely owned handle.
        Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
    }
}

/// Owns the named-pipe server created before the daemon starts the module.
/// While its handle stays open, another process cannot create an instance with
/// the same name. Dropping it closes that handle and releases the pipe name.
pub struct LaunchNoncePipeHandoff {
    pipe: OwnedHandle,
    name: String,
    nonce: Vec<u8>,
}

impl LaunchNoncePipeHandoff {
    pub fn new(nonce: &str) -> io::Result<Self> {
        Self::with_names(nonce, random_name)
    }

    fn with_names(nonce: &str, mut next: impl FnMut() -> io::Result<String>) -> io::Result<Self> {
        if nonce.is_empty() || nonce.len() > MAX_NONCE_BYTES {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid launch nonce length",
            ));
        }
        let security = user_security_descriptor()?;
        let attrs = SECURITY_ATTRIBUTES {
            nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: security.0,
            bInheritHandle: 0,
        };
        // A pre-existing pipe makes first-instance creation fail; retry with a
        // fresh random name rather than connecting to another process's server.
        for _ in 0..16 {
            let name = next()?;
            let path = wide(OsStr::new(&name));
            // SAFETY: path and the protected security descriptor remain live for the call.
            let result = owned(unsafe {
                CreateNamedPipeW(
                    path.as_ptr(),
                    PIPE_ACCESS_OUTBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
                    PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
                    1,
                    MAX_NONCE_BYTES as u32,
                    0,
                    0,
                    &attrs,
                )
            });
            match result {
                Ok(pipe) => {
                    return Ok(Self {
                        pipe,
                        name,
                        nonce: nonce.as_bytes().to_vec(),
                    })
                }
                Err(error) if matches!(error.raw_os_error(), Some(code) if code == ERROR_ACCESS_DENIED as i32 || code == ERROR_PIPE_BUSY as i32) => {
                    continue
                }
                Err(error) => return Err(error),
            }
        }
        Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "could not reserve a fresh launch nonce pipe",
        ))
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    /// Pin the child's kernel object before starting the serving thread. The
    /// caller still owns its child, so its PID cannot be recycled during this call.
    pub fn serve(self, pid: u32, deadline: Duration) -> io::Result<LaunchNoncePipeDelivery> {
        // SAFETY: OpenProcess returns a fresh handle; no inheritable rights are requested.
        let process = owned(unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) })?;
        let consumed = Arc::new(OnceLock::new());
        let cancelled = Arc::new(AtomicBool::new(false));
        let delivery = LaunchNoncePipeDelivery {
            consumed: consumed.clone(),
            cancelled: cancelled.clone(),
        };
        let deadline = Instant::now() + deadline;
        std::thread::Builder::new()
            .name("launch-nonce-pipe".into())
            .spawn(move || {
                let _ = self.deliver(pid, &process, deadline, &cancelled, &consumed);
            })?;
        Ok(delivery)
    }

    fn deliver(
        self,
        pid: u32,
        process: &OwnedHandle,
        deadline: Instant,
        cancelled: &AtomicBool,
        consumed: &Arc<OnceLock<()>>,
    ) -> io::Result<()> {
        let handle = self.pipe.as_raw_handle();
        loop {
            // SAFETY: the process handle is pinned and was opened for synchronization.
            if Instant::now() >= deadline
                || cancelled.load(Ordering::Acquire)
                || unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } == WAIT_OBJECT_0
            {
                return Err(timeout());
            }
            let mut operation = Operation::new(handle)?;
            // SAFETY: operation pins its event/OVERLAPPED until completion or cancellation.
            let connected = unsafe { ConnectNamedPipe(handle, &mut operation.overlapped) };
            if connected == 0 {
                let error = io::Error::last_os_error();
                match error.raw_os_error() {
                    Some(code) if code == ERROR_PIPE_CONNECTED as i32 => {}
                    Some(code) if code == ERROR_IO_PENDING as i32 => {
                        operation.pending = true;
                        operation.wait(deadline, Some(process), Some(cancelled))?;
                    }
                    _ => return Err(error),
                }
            }
            drop(operation);
            let mut client_pid = 0;
            // SAFETY: connected server handle and valid writable output pointer.
            let matches = unsafe { GetNamedPipeClientProcessId(handle, &mut client_pid) } != 0
                && client_pid == pid;
            if !matches {
                // Disconnect a client whose PID is not the direct child, but
                // keep the server handle so nobody can re-create this name.
                // SAFETY: handle is our server instance.
                unsafe { DisconnectNamedPipe(handle) };
                if Instant::now() >= deadline || cancelled.load(Ordering::Acquire) {
                    return Err(timeout());
                }
                continue;
            }
            let mut operation = Operation::new(handle)?;
            // SAFETY: nonce and OVERLAPPED remain alive through wait and cancellation.
            let result = unsafe {
                WriteFile(
                    handle,
                    self.nonce.as_ptr(),
                    self.nonce.len() as u32,
                    null_mut(),
                    &mut operation.overlapped,
                )
            };
            if result == 0 {
                if io::Error::last_os_error().raw_os_error() != Some(ERROR_IO_PENDING as i32) {
                    return Err(io::Error::last_os_error());
                }
                operation.pending = true;
            }
            // Overlapped byte counts come from GetOverlappedResult, including
            // operations that completed before WriteFile returned.
            let written = operation.wait(deadline, Some(process), Some(cancelled))?;
            if written as usize != self.nonce.len() {
                return Err(io::Error::other("short launch nonce pipe write"));
            }
            drop(operation);
            return flush_delivery(self.pipe, process, deadline, cancelled, consumed.clone());
        }
    }
}

/// Records whether the process started for this spawn read every nonce byte.
/// The daemon sets this only after the pipe flush completes; it does not trust
/// the source field sent by the module in its registration message.
/// Dropping this guard asks the serving thread to stop waiting and close the
/// pipe, including when a replacement process is discarded before promotion.
pub struct LaunchNoncePipeDelivery {
    consumed: Arc<OnceLock<()>>,
    cancelled: Arc<AtomicBool>,
}

impl LaunchNoncePipeDelivery {
    pub fn consumed(&self) -> Arc<OnceLock<()>> {
        self.consumed.clone()
    }
}

impl Drop for LaunchNoncePipeDelivery {
    fn drop(&mut self) {
        self.cancelled.store(true, Ordering::Release);
    }
}

fn flush_delivery(
    pipe: OwnedHandle,
    process: &OwnedHandle,
    deadline: Instant,
    cancelled: &AtomicBool,
    consumed: Arc<OnceLock<()>>,
) -> io::Result<()> {
    // Write completion only means Windows buffered the nonce. Flush waits for
    // the client to drain it before disconnect/close can discard unread bytes:
    // https://learn.microsoft.com/en-us/windows/win32/ipc/named-pipe-operations.
    // FlushFileBuffers is synchronous even on an overlapped handle. Give it a
    // dedicated thread so cancellation cannot target unrelated daemon I/O.
    let flush = std::thread::Builder::new()
        .name("launch-nonce-flush".into())
        .spawn(move || {
            // SAFETY: this thread uniquely owns the live server pipe handle.
            let result = if unsafe { FlushFileBuffers(pipe.as_raw_handle()) } == 0 {
                Err(io::Error::last_os_error())
            } else {
                // Record the completed read before disconnecting sends EOF.
                // The module can register as soon as it receives EOF, so the
                // daemon's list/status and supervisor.provenance responses must
                // already report pipe rather than the offered environment copy.
                let _ = consumed.set(());
                Ok(())
            };
            // SAFETY: the flush has finished; no asynchronous operation still
            // uses the handle. A failed flush deliberately abandons delivery.
            unsafe { DisconnectNamedPipe(pipe.as_raw_handle()) };
            result
        })?;

    let mut wait_error = None;
    while !flush.is_finished() {
        // SAFETY: JoinHandle owns a live thread handle until join below.
        match unsafe { WaitForSingleObject(flush.as_raw_handle(), POLL.as_millis() as u32) } {
            WAIT_OBJECT_0 => break,
            WAIT_TIMEOUT => {}
            _ => {
                wait_error = Some(io::Error::last_os_error());
                std::thread::sleep(POLL);
            }
        }
        // SAFETY: process stays live through this borrowed synchronize handle.
        if wait_error.is_some()
            || Instant::now() >= deadline
            || cancelled.load(Ordering::Acquire)
            || unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } == WAIT_OBJECT_0
        {
            // Repeat cancellation until the worker exits: it might not have
            // entered FlushFileBuffers when the first request was made.
            // SAFETY: this is the dedicated flush thread, not a reusable pool
            // thread; its only blocking I/O is on the launch pipe.
            unsafe { CancelSynchronousIo(flush.as_raw_handle()) };
        }
    }
    let result = flush
        .join()
        .map_err(|_| io::Error::other("launch nonce flush thread panicked"))?;
    match wait_error {
        Some(error) => Err(error),
        None => result,
    }
}

fn random_name() -> io::Result<String> {
    let mut bytes = [0u8; 16];
    // SAFETY: valid output buffer; the system RNG needs no provider handle.
    let status = unsafe {
        BCryptGenRandom(
            null_mut(),
            bytes.as_mut_ptr(),
            bytes.len() as u32,
            BCRYPT_USE_SYSTEM_PREFERRED_RNG,
        )
    };
    if status != 0 {
        return Err(io::Error::other(
            "Windows RNG could not generate a launch pipe name",
        ));
    }
    let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
    Ok(format!(r"\\.\pipe\subc-launch-{hex}"))
}

struct LocalAllocation(*mut std::ffi::c_void);
impl Drop for LocalAllocation {
    fn drop(&mut self) {
        // SAFETY: these allocations were returned by LocalAlloc-backed Windows APIs.
        unsafe { LocalFree(self.0) };
    }
}

fn user_security_descriptor() -> io::Result<LocalAllocation> {
    let mut token = null_mut();
    // SAFETY: current process pseudo-handle is valid; output points to initialized storage.
    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
        return Err(io::Error::last_os_error());
    }
    let token = owned(token)?;
    let mut needed = 0;
    // SAFETY: a null buffer requests the required TOKEN_USER size.
    unsafe { GetTokenInformation(token.as_raw_handle(), TokenUser, null_mut(), 0, &mut needed) };
    // usize storage provides alignment for TOKEN_USER and its SID.
    let mut buffer = vec![0usize; (needed as usize).div_ceil(size_of::<usize>())];
    // SAFETY: buffer is aligned and covers the size Windows requested.
    if unsafe {
        GetTokenInformation(
            token.as_raw_handle(),
            TokenUser,
            buffer.as_mut_ptr().cast(),
            needed,
            &mut needed,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: successful TokenUser query initialized the TOKEN_USER header.
    let user = unsafe { &*buffer.as_ptr().cast::<TOKEN_USER>() };
    let mut sid = null_mut();
    // SAFETY: SID points inside the still-live token buffer.
    if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut sid) } == 0 {
        return Err(io::Error::last_os_error());
    }
    let sid_allocation = LocalAllocation(sid.cast());
    let mut length = 0;
    // SAFETY: ConvertSidToStringSidW returns a null-terminated UTF-16 string.
    while unsafe { *sid.add(length) } != 0 {
        length += 1;
    }
    // SAFETY: length covers only the initialized SID string.
    let sid_text = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(sid, length) });
    drop(sid_allocation);
    // libuv's read-only fallback also requests FILE_WRITE_ATTRIBUTES to set
    // its own handle's read mode: https://github.com/nodejs/node/blob/main/deps/uv/src/win/pipe.c#L139-L194.
    // Grant that bit, GENERIC_READ and SYNCHRONIZE only. GENERIC_WRITE includes
    // FILE_CREATE_PIPE_INSTANCE and must never be granted to clients.
    let sddl = wide(OsStr::new(&format!(
        "D:P(A;;0x{CLIENT_ACCESS:08x};;;{sid_text})"
    )));
    let mut descriptor = null_mut();
    // SAFETY: null-terminated SDDL and valid output pointer; revision 1 is SDDL_REVISION_1.
    if unsafe {
        ConvertStringSecurityDescriptorToSecurityDescriptorW(
            sddl.as_ptr(),
            1,
            &mut descriptor,
            null_mut(),
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(LocalAllocation(descriptor))
}

// OVERLAPPED operations must be cancelled and joined before their buffers or
// event are freed, even when the child exits or the deadline expires.
struct Operation {
    handle: HANDLE,
    overlapped: OVERLAPPED,
    _event: OwnedHandle,
    pending: bool,
}

impl Operation {
    fn new(handle: HANDLE) -> io::Result<Self> {
        // SAFETY: unnamed, manual-reset event; no handle inheritance.
        let event = owned(unsafe { CreateEventW(null(), 1, 0, null()) })?;
        let overlapped = OVERLAPPED {
            hEvent: event.as_raw_handle(),
            ..Default::default()
        };
        Ok(Self {
            handle,
            overlapped,
            _event: event,
            pending: false,
        })
    }

    fn wait(
        &mut self,
        deadline: Instant,
        process: Option<&OwnedHandle>,
        cancelled: Option<&AtomicBool>,
    ) -> io::Result<u32> {
        loop {
            if Instant::now() >= deadline
                || cancelled.is_some_and(|flag| flag.load(Ordering::Acquire))
            {
                return Err(timeout());
            }
            // SAFETY: the borrowed OwnedHandle stays live through this wait and
            // was opened with the synchronization right required by the kernel.
            if process.is_some_and(|process| unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } == WAIT_OBJECT_0) {
                return Err(io::Error::new(io::ErrorKind::BrokenPipe, "launch nonce child exited"));
            }
            // SAFETY: event belongs to this operation and remains live.
            match unsafe { WaitForSingleObject(self.overlapped.hEvent, POLL.as_millis() as u32) } {
                WAIT_OBJECT_0 => {
                    self.pending = false;
                    let mut transferred = 0;
                    // SAFETY: the signaled event means the OVERLAPPED has completed.
                    if unsafe {
                        GetOverlappedResult(self.handle, &self.overlapped, &mut transferred, 0)
                    } == 0
                    {
                        return Err(io::Error::last_os_error());
                    }
                    return Ok(transferred);
                }
                WAIT_TIMEOUT => {}
                _ => return Err(io::Error::last_os_error()),
            }
        }
    }
}

impl Drop for Operation {
    fn drop(&mut self) {
        // ERROR_PIPE_CONNECTED and immediate EOF do not submit an operation.
        // Their events need not be signaled, so joining them could wait forever.
        if !self.pending {
            return;
        }
        // SAFETY: cancellation names only this operation; joining it keeps all
        // caller buffers alive until Windows has stopped using their pointers.
        unsafe {
            CancelIoEx(self.handle, &self.overlapped);
            let mut transferred = 0;
            GetOverlappedResult(self.handle, &self.overlapped, &mut transferred, 1);
        }
    }
}

fn timeout() -> io::Error {
    io::Error::from_raw_os_error(ERROR_SEM_TIMEOUT as i32)
}

pub(super) fn read_pipe(name: &OsStr) -> Cached {
    read_open_pipe(open_pipe(name)?)
}

fn open_pipe(name: &OsStr) -> Result<OwnedHandle, LaunchNonceError> {
    let path = wide(name);
    if path.len() <= 1 || path[..path.len() - 1].contains(&0) {
        return Err(LaunchNonceError::PipeNotOpen { errno: 123 });
    }
    let open_deadline = Instant::now() + OPEN_WINDOW;
    loop {
        // SAFETY: valid name, no inheritance, read-only access. Identification
        // security quality of service lets the server inspect identity but not
        // impersonate this process's token, even if the server is counterfeit.
        let result = owned(unsafe {
            CreateFileW(
                path.as_ptr(),
                GENERIC_READ,
                0,
                null(),
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
                null_mut(),
            )
        });
        match result {
            Ok(pipe) => return Ok(pipe),
            Err(error)
                if error.raw_os_error() == Some(ERROR_PIPE_BUSY as i32)
                    && Instant::now() < open_deadline =>
            {
                std::thread::sleep(POLL)
            }
            Err(error) => {
                return Err(LaunchNonceError::PipeNotOpen {
                    errno: error.raw_os_error().unwrap_or(0),
                })
            }
        }
    }
}

fn read_open_pipe(pipe: OwnedHandle) -> Cached {
    let deadline = Instant::now() + READ_WINDOW;
    let mut bytes = Vec::new();
    loop {
        let mut chunk = [0u8; 256];
        let mut operation = Operation::new(pipe.as_raw_handle()).map_err(pipe_unreadable)?;
        // SAFETY: chunk/OVERLAPPED stay live through completion and cancellation.
        let result = unsafe {
            ReadFile(
                pipe.as_raw_handle(),
                chunk.as_mut_ptr(),
                chunk.len() as u32,
                null_mut(),
                &mut operation.overlapped,
            )
        };
        if result == 0 {
            let error = io::Error::last_os_error();
            if pipe_eof(&error) {
                break;
            }
            if error.raw_os_error() != Some(ERROR_IO_PENDING as i32) {
                return Err(pipe_unreadable(error));
            }
            operation.pending = true;
        }
        let read = match operation.wait(deadline, None, None) {
            Ok(count) => count,
            Err(error) if pipe_eof(&error) => break,
            Err(error) => return Err(pipe_unreadable(error)),
        };
        if read == 0 {
            break;
        }
        bytes.extend_from_slice(&chunk[..read as usize]);
        if bytes.len() > MAX_NONCE_BYTES {
            return Err(LaunchNonceError::PipeUnreadable { errno: None });
        }
    }
    if bytes.is_empty() {
        return Err(LaunchNonceError::PipeEmpty);
    }
    let value = String::from_utf8(bytes).map_err(|_| LaunchNonceError::PipeNotUtf8)?;
    Ok(Some(LaunchNonce {
        value,
        source: LaunchNonceSource::Pipe,
    }))
}

fn pipe_eof(error: &io::Error) -> bool {
    matches!(error.raw_os_error(), Some(code) if code == ERROR_BROKEN_PIPE as i32 || code == ERROR_PIPE_NOT_CONNECTED as i32)
}

fn pipe_unreadable(error: io::Error) -> LaunchNonceError {
    LaunchNonceError::PipeUnreadable {
        errno: error.raw_os_error(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::launch_nonce::{
        launch_nonce, LaunchNonceCell, LAUNCH_NONCE_ENV, LAUNCH_NONCE_PIPE_ENV,
        LAUNCH_NONCE_PIPE_FALLBACK_ENV,
    };
    use std::process::{Command, Stdio};

    #[test]
    fn windows_launch_pipe_dacl_grants_exact_client_access() {
        use windows_sys::Win32::Foundation::{GetHandleInformation, HANDLE_FLAG_INHERIT};
        use windows_sys::Win32::Security::{
            Authorization::{GetSecurityInfo, SE_KERNEL_OBJECT},
            GetAce, GetSecurityDescriptorControl, ACCESS_ALLOWED_ACE, DACL_SECURITY_INFORMATION,
            SE_DACL_PROTECTED,
        };
        let pipe = LaunchNoncePipeHandoff::new("secret").unwrap();
        let mut flags = 0;
        // SAFETY: the server handle is live and flags is a valid output pointer.
        assert_ne!(
            unsafe { GetHandleInformation(pipe.pipe.as_raw_handle(), &mut flags) },
            0
        );
        assert_eq!(flags & HANDLE_FLAG_INHERIT, 0);
        let mut dacl = null_mut();
        let mut descriptor = null_mut();
        // SAFETY: the server handle is live, and all outputs name initialized storage.
        assert_eq!(
            unsafe {
                GetSecurityInfo(
                    pipe.pipe.as_raw_handle(),
                    SE_KERNEL_OBJECT,
                    DACL_SECURITY_INFORMATION,
                    null_mut(),
                    null_mut(),
                    &mut dacl,
                    null_mut(),
                    &mut descriptor,
                )
            },
            0
        );
        let _descriptor = LocalAllocation(descriptor);
        assert!(!dacl.is_null());
        // SAFETY: GetSecurityInfo returned a valid DACL.
        assert_eq!(unsafe { (*dacl).AceCount }, 1);
        let mut ace = null_mut();
        // SAFETY: DACL has exactly one ACE and ace is a valid output pointer.
        assert_ne!(unsafe { GetAce(dacl, 0, &mut ace) }, 0);
        // SAFETY: the only ACE was created as an ACCESS_ALLOWED_ACE.
        let mask = unsafe { (*ace.cast::<ACCESS_ALLOWED_ACE>()).Mask };
        // Windows may store GENERIC_READ verbatim or expand its pipe rights.
        assert!(
            mask == 0x80100100 || mask == 0x00120189,
            "unexpected client access mask: {mask:#x}"
        );
        assert_eq!(mask & (0x40000000 | 0x4), 0);
        let mut control = 0;
        let mut revision = 0;
        // SAFETY: descriptor is live and output pointers are valid.
        assert_ne!(
            unsafe { GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) },
            0
        );
        assert_ne!(control & SE_DACL_PROTECTED, 0);
    }

    #[test]
    fn windows_pipe_child_fixture() {
        if std::env::var_os("SUBC_PIPE_TEST_CHILD").is_none() {
            return;
        }
        std::thread::sleep(Duration::from_millis(250));
        let nonce = launch_nonce()
            .expect("child pipe read")
            .expect("child nonce");
        assert_eq!(nonce.source(), LaunchNonceSource::Pipe);
        assert_eq!(launch_nonce().unwrap(), Some(nonce.clone()));
        assert_eq!(std::env::var(LAUNCH_NONCE_ENV).unwrap(), "environment-copy");
        println!("child-pipe:{}", nonce.value());
    }

    fn spawn_reader(pipe: &LaunchNoncePipeHandoff) -> std::process::Child {
        Command::new(std::env::current_exe().unwrap())
            .args([
                "launch_nonce::windows::tests::windows_pipe_child_fixture",
                "--exact",
                "--nocapture",
            ])
            .env("SUBC_PIPE_TEST_CHILD", "1")
            .env(LAUNCH_NONCE_PIPE_ENV, pipe.name())
            .env(LAUNCH_NONCE_ENV, "environment-copy")
            .env_remove(LAUNCH_NONCE_PIPE_FALLBACK_ENV)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap()
    }

    fn assert_child_reads(mut child: std::process::Child, evidence: &OnceLock<()>) {
        let deadline = Instant::now() + Duration::from_secs(10);
        while child.try_wait().unwrap().is_none() {
            if Instant::now() >= deadline {
                let _ = child.kill();
                let _ = child.wait();
                panic!("child did not finish its bounded pipe handoff");
            }
            std::thread::sleep(POLL);
        }
        let output = child.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("child-pipe:test-secret"),
            "{}",
            String::from_utf8_lossy(&output.stdout)
        );
        assert!(evidence.get().is_some(), "server records pipe consumption");
    }

    #[test]
    fn windows_supervisor_child_reads_secret_through_pipe() {
        let pipe = LaunchNoncePipeHandoff::new("test-secret").unwrap();
        let child = spawn_reader(&pipe);
        let delivery = pipe.serve(child.id(), Duration::from_secs(5)).unwrap();
        assert_child_reads(child, &delivery.consumed());
    }

    #[test]
    fn windows_wrong_pid_gets_nothing_and_real_child_still_reads() {
        let pipe = LaunchNoncePipeHandoff::new("test-secret").unwrap();
        let name = pipe.name().to_owned();
        let child = spawn_reader(&pipe);
        let delivery = pipe.serve(child.id(), Duration::from_secs(5)).unwrap();
        assert_eq!(
            read_pipe(OsStr::new(&name)),
            Err(LaunchNonceError::PipeEmpty)
        );
        assert_child_reads(child, &delivery.consumed());
    }

    #[test]
    fn windows_name_collision_picks_fresh_pipe() {
        let occupied = LaunchNoncePipeHandoff::new("occupied").unwrap();
        let mut calls = 0;
        let pipe = LaunchNoncePipeHandoff::with_names("test-secret", || {
            calls += 1;
            if calls == 1 {
                Ok(occupied.name().to_owned())
            } else {
                random_name()
            }
        })
        .unwrap();
        assert_eq!(calls, 2);
        assert_ne!(pipe.name(), occupied.name());
        let child = spawn_reader(&pipe);
        let delivery = pipe.serve(child.id(), Duration::from_secs(5)).unwrap();
        assert_child_reads(child, &delivery.consumed());
    }

    #[test]
    fn windows_gone_pipe_never_falls_back_and_caches_failure() {
        let name = LaunchNoncePipeHandoff::new("secret")
            .unwrap()
            .name()
            .to_owned();
        let cell = LaunchNonceCell::new();
        let result = cell.get(|key| match key {
            LAUNCH_NONCE_PIPE_ENV => Some(name.clone().into()),
            LAUNCH_NONCE_ENV => panic!("must not look up environment fallback"),
            _ => None,
        });
        assert!(matches!(result, Err(LaunchNonceError::PipeNotOpen { .. })));
        assert_eq!(cell.get(|_| panic!("must use cached failure")), result);
    }

    #[test]
    fn windows_phase_one_gone_pipe_uses_and_caches_the_environment_source() {
        let name = LaunchNoncePipeHandoff::new("secret")
            .unwrap()
            .name()
            .to_owned();
        let cell = LaunchNonceCell::new();
        let result = cell
            .get(|key| match key {
                LAUNCH_NONCE_PIPE_ENV => Some(name.clone().into()),
                LAUNCH_NONCE_PIPE_FALLBACK_ENV => Some("env".into()),
                LAUNCH_NONCE_ENV => Some("environment-secret".into()),
                _ => None,
            })
            .unwrap()
            .unwrap();
        assert_eq!(result.value(), "environment-secret");
        assert_eq!(result.source(), LaunchNonceSource::Env);
        assert_eq!(
            cell.get(|_| panic!("must use cached fallback")),
            Ok(Some(result))
        );
    }
}

#[cfg(test)]
mod buffered_delivery_tests {
    use super::*;
    use crate::launch_nonce::{
        launch_nonce, LAUNCH_NONCE_ENV, LAUNCH_NONCE_PIPE_ENV, LAUNCH_NONCE_PIPE_FALLBACK_ENV,
    };
    use cortexkit_test_support::ScratchDir;
    use std::{
        path::{Path, PathBuf},
        process::{Child, Command, Stdio},
    };
    use windows_sys::Win32::System::Pipes::PeekNamedPipe;

    struct Gates(ScratchDir);
    impl Gates {
        fn new() -> Self {
            Self(ScratchDir::new("subc-pipe-gates"))
        }
        fn path(&self, name: &str) -> PathBuf {
            self.0.join(name)
        }
    }

    fn wait_for(path: &Path) {
        let deadline = Instant::now() + Duration::from_secs(5);
        while !path.exists() {
            assert!(
                Instant::now() < deadline,
                "pipe child did not reach {}",
                path.display()
            );
            std::thread::sleep(POLL);
        }
    }

    #[test]
    fn windows_buffered_pipe_child_fixture() {
        let Some(root) = std::env::var_os("SUBC_PIPE_GATES") else {
            return;
        };
        let root = PathBuf::from(root);
        let name = std::env::var_os(LAUNCH_NONCE_PIPE_ENV).unwrap();
        let pipe = open_pipe(&name).unwrap();
        std::fs::write(root.join("connected"), b"ready").unwrap();
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let mut available = 0;
            // SAFETY: this is the live read-only client handle, and only the
            // byte-count output is requested; no credential bytes leave it.
            assert_ne!(
                unsafe {
                    PeekNamedPipe(
                        pipe.as_raw_handle(),
                        null_mut(),
                        0,
                        null_mut(),
                        &mut available,
                        null_mut(),
                    )
                },
                0
            );
            if available != 0 {
                break;
            }
            assert!(Instant::now() < deadline, "server never buffered the nonce");
            std::thread::sleep(POLL);
        }
        std::fs::write(root.join("buffered"), b"ready").unwrap();
        while !root.join("read").exists() {
            let mut available = 0;
            // SAFETY: same live client handle and byte-count-only query as above.
            if unsafe {
                PeekNamedPipe(
                    pipe.as_raw_handle(),
                    null_mut(),
                    0,
                    null_mut(),
                    &mut available,
                    null_mut(),
                )
            } == 0
            {
                assert!(
                    pipe_eof(&io::Error::last_os_error()),
                    "unexpected pipe failure"
                );
                drop(pipe);
                let nonce = launch_nonce().unwrap().unwrap();
                assert_eq!(nonce.source(), LaunchNonceSource::Env);
                println!("child-env:{}", nonce.value());
                std::fs::write(root.join("closed"), b"ready").unwrap();
                return;
            }
            assert!(Instant::now() < deadline, "reader gate was not opened");
            std::thread::sleep(POLL);
        }
        let nonce = read_open_pipe(pipe).unwrap().unwrap();
        assert_eq!(nonce.source(), LaunchNonceSource::Pipe);
        println!("child-pipe:{}", nonce.value());
    }

    fn spawn_buffered_reader(
        pipe: &LaunchNoncePipeHandoff,
        gates: &Gates,
        fallback: bool,
    ) -> Child {
        let mut command = Command::new(std::env::current_exe().unwrap());
        command
            .args(["launch_nonce::windows::buffered_delivery_tests::windows_buffered_pipe_child_fixture", "--exact", "--nocapture"])
            .env("SUBC_PIPE_GATES", gates.0.path())
            .env(LAUNCH_NONCE_PIPE_ENV, pipe.name())
            .env_remove(LAUNCH_NONCE_PIPE_FALLBACK_ENV)
            .env_remove(LAUNCH_NONCE_ENV)
            .stdout(Stdio::piped()).stderr(Stdio::piped());
        if fallback {
            command
                .env(LAUNCH_NONCE_PIPE_FALLBACK_ENV, "env")
                .env(LAUNCH_NONCE_ENV, "test-secret");
        }
        command.spawn().unwrap()
    }

    #[test]
    fn windows_client_connected_first_is_drained_before_consumption_and_eof() {
        let gates = Gates::new();
        let pipe = LaunchNoncePipeHandoff::new("test-secret").unwrap();
        let mut child = spawn_buffered_reader(&pipe, &gates, false);
        wait_for(&gates.path("connected"));
        let delivery = pipe.serve(child.id(), Duration::from_secs(5)).unwrap();
        wait_for(&gates.path("buffered"));
        assert!(
            delivery.consumed().get().is_none(),
            "buffering bytes is not client consumption"
        );
        std::fs::write(gates.path("read"), b"ready").unwrap();
        let deadline = Instant::now() + Duration::from_secs(5);
        while child.try_wait().unwrap().is_none() {
            if Instant::now() >= deadline {
                let _ = child.kill();
                panic!("connected-first reader did not reach EOF");
            }
            std::thread::sleep(POLL);
        }
        let output = child.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(String::from_utf8_lossy(&output.stdout).contains("child-pipe:test-secret"));
        assert!(delivery.consumed().get().is_some());
    }

    #[test]
    fn windows_flush_deadline_closes_pipe_without_reporting_consumption() {
        let gates = Gates::new();
        let pipe = LaunchNoncePipeHandoff::new("test-secret").unwrap();
        let child = spawn_buffered_reader(&pipe, &gates, true);
        wait_for(&gates.path("connected"));
        let delivery = pipe.serve(child.id(), Duration::from_secs(1)).unwrap();
        wait_for(&gates.path("buffered"));
        wait_for(&gates.path("closed"));
        assert!(delivery.consumed().get().is_none());
        let output = child.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(String::from_utf8_lossy(&output.stdout).contains("child-env:test-secret"));
    }
}

#[cfg(all(test, windows))]
mod lifecycle_tests {
    use super::*;
    use std::process::{Command, Stdio};

    #[test]
    fn windows_pipe_idle_child_fixture() {
        if std::env::var_os("SUBC_PIPE_IDLE_CHILD").is_some() {
            std::thread::sleep(Duration::from_secs(1));
        }
    }

    fn idle_child() -> std::process::Child {
        Command::new(std::env::current_exe().unwrap())
            .args([
                "launch_nonce::windows::lifecycle_tests::windows_pipe_idle_child_fixture",
                "--exact",
            ])
            .env("SUBC_PIPE_IDLE_CHILD", "1")
            .stdout(Stdio::null())
            .spawn()
            .unwrap()
    }

    #[test]
    fn windows_registration_deadline_closes_unconsumed_pipe() {
        let pipe = LaunchNoncePipeHandoff::new("secret").unwrap();
        let name = pipe.name().to_owned();
        let mut child = idle_child();
        let delivery = pipe.serve(child.id(), Duration::from_millis(30)).unwrap();
        std::thread::sleep(Duration::from_millis(100));
        assert!(matches!(
            read_pipe(OsStr::new(&name)),
            Err(LaunchNonceError::PipeNotOpen { .. })
        ));
        assert!(delivery.consumed().get().is_none());
        child.kill().unwrap();
        child.wait().unwrap();
    }

    #[test]
    fn windows_child_exit_closes_unconsumed_pipe() {
        let pipe = LaunchNoncePipeHandoff::new("secret").unwrap();
        let name = pipe.name().to_owned();
        let mut child = idle_child();
        let delivery = pipe.serve(child.id(), Duration::from_secs(5)).unwrap();
        child.kill().unwrap();
        child.wait().unwrap();
        std::thread::sleep(Duration::from_millis(100));
        assert!(matches!(
            read_pipe(OsStr::new(&name)),
            Err(LaunchNonceError::PipeNotOpen { .. })
        ));
        assert!(delivery.consumed().get().is_none());
    }
}