hotl-platform 0.24.0

Internal component of hotl - no semver promise; pin exact or don't depend. Platform seams: one capability trait per concern, one adapter per platform.
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
//! A one-ACE, `SE_DACL_PROTECTED` DACL applied at create.
//!
//! Three traps, in the order they bite:
//!
//! 1. The DACL has exactly one ACE — the current user's SID, `FILE_ALL_ACCESS`,
//!    no inheritance.
//! 2. **`SE_DACL_PROTECTED` is the whole ballgame.** Without it, ACEs inherited
//!    from `%LOCALAPPDATA%` (typically `Administrators`, sometimes `Users`) are
//!    *merged* with ours and the result is not `0700` — it is `0700` plus
//!    whatever the parent grants. Every "chmod on Windows" snippet gets this
//!    wrong.
//! 3. **Apply at create**, via `SECURITY_ATTRIBUTES` on `CreateDirectoryW` /
//!    `CreateFileW`. A create-then-harden window on the session log is a real
//!    read window.
//!
//! No policy lives here (rule 6): this module decides nothing about *which*
//! principal to grant, only how to express "the current user, and nobody else"
//! in Win32.

use super::{EffectiveAccess, PrivateFs, Writes};
use std::ffi::c_void;
use std::fs::File;
use std::io;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::FromRawHandle;
use std::path::Path;
use std::ptr;

use windows_sys::Win32::Foundation::{
    CloseHandle, LocalFree, GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE,
};
use windows_sys::Win32::Security::Authorization::{
    GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW, EXPLICIT_ACCESS_W,
    NO_MULTIPLE_TRUSTEE, SET_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_SID, TRUSTEE_IS_UNKNOWN, TRUSTEE_W,
};
use windows_sys::Win32::Security::{
    AclSizeInformation, EqualSid, GetAce, GetAclInformation, GetTokenInformation,
    InitializeSecurityDescriptor, LookupAccountSidW, SetSecurityDescriptorControl,
    SetSecurityDescriptorDacl, TokenUser, ACCESS_ALLOWED_ACE, ACL, ACL_SIZE_INFORMATION,
    DACL_SECURITY_INFORMATION, NO_INHERITANCE, PROTECTED_DACL_SECURITY_INFORMATION,
    PSECURITY_DESCRIPTOR, PSID, SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR,
    SECURITY_DESCRIPTOR_CONTROL, SE_DACL_PROTECTED, TOKEN_QUERY, TOKEN_USER,
};
use windows_sys::Win32::Storage::FileSystem::{
    CreateDirectoryW, CreateFileW, CREATE_ALWAYS, CREATE_NEW, FILE_ALL_ACCESS,
    FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE,
    FILE_SHARE_MODE, FILE_SHARE_READ, FILE_WRITE_DATA,
};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

/// The ACE type that grants. Anything else in a DACL cannot widen a read.
const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;

/// What a **second** opener may do while we hold the file open for writing.
///
/// Share mode is not an access control — the DACL already decided *who* can
/// open this file, and it is only ever the owner. Share mode decides whether
/// the owner's own other handles may coexist, and a mode of `0` says no,
/// including to hotl itself.
///
/// That is not hypothetical: the session log is append-only and is read
/// **while it is being written** — by `replay` for resume and fork, by
/// `list_sessions`, and by `hotl attach` following a live session. Denying
/// `FILE_SHARE_READ` turns every one of those into
/// `ERROR_SHARING_VIOLATION`, which has no Unix counterpart at all, where an
/// open file is freely readable.
///
/// `FILE_SHARE_DELETE` for the same reason: on Unix an `unlink` of an open
/// file always succeeds, and without this flag retention could not prune a log
/// any handle still held. Deliberately **not** `FILE_SHARE_WRITE` — the log has
/// exactly one writer by design, and a second one is a real hazard rather than
/// a compatibility gap.
const SHARE_WHILE_WRITING: FILE_SHARE_MODE = FILE_SHARE_READ | FILE_SHARE_DELETE;

#[derive(Debug, Clone, Copy, Default)]
pub struct WindowsPrivateFs;

impl WindowsPrivateFs {
    pub const fn new() -> Self {
        Self
    }
}

impl crate::sealed::Sealed for WindowsPrivateFs {}

impl PrivateFs for WindowsPrivateFs {
    fn create_dir(&self, path: &Path) -> io::Result<()> {
        let sid = current_user_sid()?;
        let acl = one_ace_dacl(sid.as_psid(), FILE_ALL_ACCESS)?;
        let mut sd = protected_descriptor(&acl)?;
        let sa = SECURITY_ATTRIBUTES {
            nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: sd.as_mut_ptr(),
            bInheritHandle: 0,
        };
        let wide = wide(path);
        // SAFETY: `wide` is NUL-terminated and outlives the call; `sa` points at
        // a descriptor whose DACL is owned by `acl` for the same scope.
        if unsafe { CreateDirectoryW(wide.as_ptr(), &sa) } == 0 {
            let err = io::Error::last_os_error();
            if err.kind() == io::ErrorKind::AlreadyExists {
                // A pre-existing directory keeps whatever it had — there is no
                // umask to have narrowed it — so tighten rather than accept it.
                return self.harden_existing(path);
            }
            return Err(err);
        }
        Ok(())
    }

    fn create_file_new(&self, path: &Path, writes: Writes) -> io::Result<File> {
        let sid = current_user_sid()?;
        let acl = one_ace_dacl(sid.as_psid(), FILE_ALL_ACCESS)?;
        let mut sd = protected_descriptor(&acl)?;
        let sa = SECURITY_ATTRIBUTES {
            nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: sd.as_mut_ptr(),
            bInheritHandle: 0,
        };
        let wide = wide(path);
        // `FILE_GENERIC_WRITE` minus `FILE_WRITE_DATA` is Windows' `O_APPEND`:
        // what is left includes `FILE_APPEND_DATA`, and without write-data the
        // handle *cannot* address any offset but the end.
        let access = match writes {
            Writes::FromStart => GENERIC_READ | GENERIC_WRITE,
            Writes::Append => FILE_GENERIC_WRITE & !FILE_WRITE_DATA,
        };
        // `CREATE_NEW` is the `O_EXCL`. SAFETY: as above.
        let handle = unsafe {
            CreateFileW(
                wide.as_ptr(),
                access,
                SHARE_WHILE_WRITING,
                &sa,
                CREATE_NEW,
                FILE_ATTRIBUTE_NORMAL,
                ptr::null_mut(),
            )
        };
        if handle == INVALID_HANDLE_VALUE {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: a fresh handle from `CreateFileW`, owned by nothing else.
        Ok(unsafe { File::from_raw_handle(handle as _) })
    }

    fn create_file_truncate(&self, path: &Path) -> io::Result<File> {
        let sid = current_user_sid()?;
        let acl = one_ace_dacl(sid.as_psid(), FILE_ALL_ACCESS)?;
        let mut sd = protected_descriptor(&acl)?;
        let sa = SECURITY_ATTRIBUTES {
            nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: sd.as_mut_ptr(),
            bInheritHandle: 0,
        };
        let wide = wide(path);
        // SAFETY: NUL-terminated path; `sa` is live for the call and its DACL
        // is owned by `acl` for the same scope.
        let handle = unsafe {
            CreateFileW(
                wide.as_ptr(),
                GENERIC_READ | GENERIC_WRITE,
                SHARE_WHILE_WRITING,
                &sa,
                CREATE_ALWAYS,
                FILE_ATTRIBUTE_NORMAL,
                ptr::null_mut(),
            )
        };
        if handle == INVALID_HANDLE_VALUE {
            return Err(io::Error::last_os_error());
        }
        // `CREATE_ALWAYS` ignores `sa` when the file already existed, so narrow
        // it now — the window the trait doc names.
        self.harden_existing(path)?;
        // SAFETY: a fresh handle from `CreateFileW`, owned by nothing else.
        Ok(unsafe { File::from_raw_handle(handle as _) })
    }

    fn harden_existing(&self, path: &Path) -> io::Result<()> {
        let sid = current_user_sid()?;
        let acl = one_ace_dacl(sid.as_psid(), FILE_ALL_ACCESS)?;
        let mut wide = wide(path);
        // `PROTECTED_DACL_SECURITY_INFORMATION` is `SE_DACL_PROTECTED`'s
        // equivalent on this call: it detaches the object from the parent's
        // inheritable ACEs rather than merging with them.
        // SAFETY: NUL-terminated path, a live ACL, and null for every field the
        // information flags say we are not setting.
        let rc = unsafe {
            SetNamedSecurityInfoW(
                wide.as_mut_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
                ptr::null_mut(),
                ptr::null_mut(),
                acl.as_ptr(),
                ptr::null_mut(),
            )
        };
        if rc != 0 {
            return Err(io::Error::from_raw_os_error(rc as i32));
        }
        Ok(())
    }

    fn effective_access(&self, path: &Path) -> io::Result<EffectiveAccess> {
        let me = current_user_sid()?;
        let mut wide = wide(path);
        let mut dacl: *mut ACL = ptr::null_mut();
        let mut sd: PSECURITY_DESCRIPTOR = ptr::null_mut();
        // SAFETY: out-params are live for the call; `sd` is freed below and is
        // what owns the memory `dacl` points into.
        let rc = unsafe {
            GetNamedSecurityInfoW(
                wide.as_mut_ptr(),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION,
                ptr::null_mut(),
                ptr::null_mut(),
                &mut dacl,
                ptr::null_mut(),
                &mut sd,
            )
        };
        if rc != 0 {
            return Err(io::Error::from_raw_os_error(rc as i32));
        }
        let owned = LocalOwned(sd);
        let other_readers = read_grants_other_than(dacl, &me)?;
        drop(owned);
        Ok(EffectiveAccess {
            owner_only: other_readers.is_empty(),
            other_readers,
        })
    }
}

/// Every principal but `me` that the DACL grants any read bit to.
///
/// A null DACL is the dangerous case and is reported as such rather than as
/// "no entries": a NULL DACL grants everything to everyone.
fn read_grants_other_than(dacl: *const ACL, me: &OwnedSid) -> io::Result<Vec<String>> {
    if dacl.is_null() {
        return Ok(vec!["everyone (the object has a NULL DACL)".to_string()]);
    }
    let mut info = ACL_SIZE_INFORMATION {
        AceCount: 0,
        AclBytesInUse: 0,
        AclBytesFree: 0,
    };
    // SAFETY: `dacl` is non-null and came from the OS; `info` matches the class.
    if unsafe {
        GetAclInformation(
            dacl,
            (&raw mut info).cast(),
            size_of::<ACL_SIZE_INFORMATION>() as u32,
            AclSizeInformation,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }

    let mut out = Vec::new();
    for i in 0..info.AceCount {
        let mut ace: *mut c_void = ptr::null_mut();
        // SAFETY: `i` is below the count the OS just reported.
        if unsafe { GetAce(dacl, i, &mut ace) } == 0 {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: `ace` points at an ACE header; the type byte is its first
        // field and is valid for every ACE variant.
        let header = unsafe { *(ace as *const u8) };
        if header != ACCESS_ALLOWED_ACE_TYPE {
            continue; // deny and audit ACEs cannot widen a read
        }
        // SAFETY: the type byte says this is an ACCESS_ALLOWED_ACE, whose
        // `SidStart` is the first `DWORD` of an inline SID.
        let allowed = unsafe { &*(ace as *const ACCESS_ALLOWED_ACE) };
        if allowed.Mask & FILE_GENERIC_READ == 0 {
            continue;
        }
        let sid = (&raw const allowed.SidStart) as PSID;
        // SAFETY: both SIDs are valid for the length the OS gave them.
        if unsafe { EqualSid(sid, me.as_psid()) } != 0 {
            continue;
        }
        out.push(account_name(sid));
    }
    Ok(out)
}

/// A human-readable name for a SID, falling back to a marker rather than
/// dropping the entry — an unresolvable SID still reads the file.
fn account_name(sid: PSID) -> String {
    let mut name = [0u16; 256];
    let mut domain = [0u16; 256];
    let mut name_len = name.len() as u32;
    let mut domain_len = domain.len() as u32;
    let mut kind = 0i32;
    // SAFETY: both buffers are live and their lengths are passed by pointer.
    let ok = unsafe {
        LookupAccountSidW(
            ptr::null(),
            sid,
            name.as_mut_ptr(),
            &mut name_len,
            domain.as_mut_ptr(),
            &mut domain_len,
            &mut kind,
        )
    };
    if ok == 0 {
        return "an unresolvable SID".to_string();
    }
    String::from_utf16_lossy(&name[..name_len as usize])
}

/// An owned `TOKEN_USER` blob, kept alive because the `PSID` points into it.
struct OwnedSid(Vec<u8>);

impl OwnedSid {
    fn as_psid(&self) -> PSID {
        // SAFETY: the buffer holds a `TOKEN_USER` whose first field is the SID
        // pointer the OS wrote.
        unsafe { (*(self.0.as_ptr() as *const TOKEN_USER)).User.Sid }
    }
}

fn current_user_sid() -> io::Result<OwnedSid> {
    let mut token: HANDLE = ptr::null_mut();
    // SAFETY: a pseudo-handle for our own process and a live out-param.
    if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == 0 {
        return Err(io::Error::last_os_error());
    }
    let mut needed = 0u32;
    // SAFETY: the deliberate zero-length probe call that reports the size.
    unsafe { GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut needed) };
    let mut buf = vec![0u8; needed as usize];
    // SAFETY: `buf` is exactly the size the OS just asked for.
    let ok = unsafe {
        GetTokenInformation(
            token,
            TokenUser,
            buf.as_mut_ptr().cast(),
            needed,
            &mut needed,
        )
    };
    // SAFETY: a handle we opened and no longer need, on both paths.
    unsafe { CloseHandle(token) };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(OwnedSid(buf))
}

/// A DACL with exactly one allow ACE, built by `SetEntriesInAclW` so the ACE
/// order is canonical. Never hand-assemble ACE order.
struct OwnedAcl(*mut ACL);

impl OwnedAcl {
    fn as_ptr(&self) -> *const ACL {
        self.0
    }
}

impl Drop for OwnedAcl {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: `SetEntriesInAclW` allocates with `LocalAlloc`.
            unsafe { LocalFree(self.0.cast()) };
        }
    }
}

fn one_ace_dacl(sid: PSID, access: u32) -> io::Result<OwnedAcl> {
    let ea = EXPLICIT_ACCESS_W {
        grfAccessPermissions: access,
        grfAccessMode: SET_ACCESS,
        grfInheritance: NO_INHERITANCE,
        Trustee: TRUSTEE_W {
            pMultipleTrustee: ptr::null_mut(),
            MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
            TrusteeForm: TRUSTEE_IS_SID,
            TrusteeType: TRUSTEE_IS_UNKNOWN,
            ptstrName: sid.cast(),
        },
    };
    let mut acl: *mut ACL = ptr::null_mut();
    // SAFETY: one live entry, a null "existing ACL" meaning "build from
    // scratch", and a live out-param.
    let rc = unsafe { SetEntriesInAclW(1, &ea, ptr::null(), &mut acl) };
    if rc != 0 {
        return Err(io::Error::from_raw_os_error(rc as i32));
    }
    Ok(OwnedAcl(acl))
}

/// An absolute security descriptor carrying `acl` as its DACL, with
/// `SE_DACL_PROTECTED` set so no inherited ACE is merged in.
struct Descriptor(Box<SECURITY_DESCRIPTOR>);

impl Descriptor {
    fn as_mut_ptr(&mut self) -> *mut c_void {
        (&raw mut *self.0).cast()
    }
}

fn protected_descriptor(acl: &OwnedAcl) -> io::Result<Descriptor> {
    // SAFETY: zeroed is a valid starting state for the struct
    // `InitializeSecurityDescriptor` is about to fill in.
    let mut sd: Box<SECURITY_DESCRIPTOR> = Box::new(unsafe { std::mem::zeroed() });
    let ptr = (&raw mut *sd).cast();
    // SAFETY: a live, correctly sized descriptor.
    if unsafe { InitializeSecurityDescriptor(ptr, 1) } == 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `acl` outlives every use of this descriptor at both call sites.
    if unsafe { SetSecurityDescriptorDacl(ptr, 1, acl.as_ptr() as *mut ACL, 0) } == 0 {
        return Err(io::Error::last_os_error());
    }
    // Trap 2. Without this the parent's inheritable ACEs are merged in and the
    // object is not owner-only.
    // SAFETY: setting one control bit on a descriptor we just initialized.
    if unsafe {
        SetSecurityDescriptorControl(
            ptr,
            SE_DACL_PROTECTED as SECURITY_DESCRIPTOR_CONTROL,
            SE_DACL_PROTECTED as SECURITY_DESCRIPTOR_CONTROL,
        )
    } == 0
    {
        return Err(io::Error::last_os_error());
    }
    Ok(Descriptor(sd))
}

/// An owner-only `SECURITY_ATTRIBUTES`, for the Win32 create calls outside this
/// module that take one.
///
/// The named-pipe server's DACL is the same authorization boundary a `0600`
/// mode is for a unix socket, so it is built by the same code rather than by a
/// second hand-rolled descriptor that could drift from this one.
pub(crate) struct OwnerOnlyAttributes {
    // Declaration order is drop order, and it is load-bearing: `sa` points into
    // `sd`, which points into `acl`.
    sa: Box<SECURITY_ATTRIBUTES>,
    _sd: Descriptor,
    _acl: OwnedAcl,
}

impl OwnerOnlyAttributes {
    pub(crate) fn as_ptr(&mut self) -> *mut c_void {
        (&raw mut *self.sa).cast()
    }
}

pub(crate) fn owner_only_attributes() -> io::Result<OwnerOnlyAttributes> {
    let sid = current_user_sid()?;
    let acl = one_ace_dacl(sid.as_psid(), FILE_ALL_ACCESS)?;
    let mut sd = protected_descriptor(&acl)?;
    let sa = Box::new(SECURITY_ATTRIBUTES {
        nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
        lpSecurityDescriptor: sd.as_mut_ptr(),
        bInheritHandle: 0,
    });
    Ok(OwnerOnlyAttributes {
        sa,
        _sd: sd,
        _acl: acl,
    })
}

/// `LocalFree` on drop, for the descriptors `GetNamedSecurityInfoW` allocates.
struct LocalOwned(*mut c_void);

impl Drop for LocalOwned {
    fn drop(&mut self) {
        if !self.0.is_null() {
            // SAFETY: allocated by the OS with `LocalAlloc`.
            unsafe { LocalFree(self.0) };
        }
    }
}

fn wide(path: &Path) -> Vec<u16> {
    path.as_os_str().encode_wide().chain(Some(0)).collect()
}

/// Whether the object's DACL is detached from its parent's inheritable ACEs.
///
/// Windows-only, and not part of the [`PrivateFs`] contract, because Unix has
/// no counterpart: there is nothing to inherit from and nothing to protect
/// against. The test below is the one assertion with no Unix twin.
#[cfg(test)]
pub(crate) fn dacl_is_protected(path: &Path) -> io::Result<bool> {
    use windows_sys::Win32::Security::GetSecurityDescriptorControl;
    let mut wide = wide(path);
    let mut sd: PSECURITY_DESCRIPTOR = ptr::null_mut();
    let mut dacl: *mut ACL = ptr::null_mut();
    // SAFETY: live out-params; `sd` owns the memory and is freed below.
    let rc = unsafe {
        GetNamedSecurityInfoW(
            wide.as_mut_ptr(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            &mut dacl,
            ptr::null_mut(),
            &mut sd,
        )
    };
    if rc != 0 {
        return Err(io::Error::from_raw_os_error(rc as i32));
    }
    let owned = LocalOwned(sd);
    let mut control: SECURITY_DESCRIPTOR_CONTROL = 0;
    let mut revision = 0u32;
    // SAFETY: `sd` is a valid descriptor for the duration of `owned`.
    let ok = unsafe { GetSecurityDescriptorControl(sd, &mut control, &mut revision) };
    drop(owned);
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok(control & (SE_DACL_PROTECTED as SECURITY_DESCRIPTOR_CONTROL) != 0)
}

/// Re-attach the object to its parent's inheritable ACEs — the test's way of
/// loosening something so `harden_existing` has work to do.
#[cfg(test)]
pub(crate) fn allow_inheritance(path: &Path) -> io::Result<()> {
    let mut wide = wide(path);
    // No `PROTECTED_DACL_SECURITY_INFORMATION`, and a null DACL pointer with
    // `UNPROTECTED` semantics: inheritable ACEs flow back in.
    // SAFETY: NUL-terminated path; nulls for everything not being set.
    let rc = unsafe {
        SetNamedSecurityInfoW(
            wide.as_mut_ptr(),
            SE_FILE_OBJECT,
            DACL_SECURITY_INFORMATION
                | windows_sys::Win32::Security::UNPROTECTED_DACL_SECURITY_INFORMATION,
            ptr::null_mut(),
            ptr::null_mut(),
            ptr::null(),
            ptr::null_mut(),
        )
    };
    if rc != 0 {
        return Err(io::Error::from_raw_os_error(rc as i32));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The Windows-only assertion with no Unix counterpart: the object is
    /// `SE_DACL_PROTECTED`, not merely correct-looking. Verify no inherited ACE
    /// survived, because a merged-in `Administrators` ACE would leave the DACL
    /// *looking* right while granting a second reader.
    #[test]
    fn a_private_object_is_detached_from_inherited_aces() {
        let scratch = std::env::temp_dir().join(format!("hotl-dacl-{}", std::process::id()));
        crate::PRIVATE_FS.create_dir(&scratch).unwrap();
        assert!(dacl_is_protected(&scratch).unwrap());

        let file = scratch.join("secret");
        drop(
            crate::PRIVATE_FS
                .create_file_new(&file, crate::privatefs::Writes::FromStart)
                .unwrap(),
        );
        assert!(dacl_is_protected(&file).unwrap());

        // And the re-hardening path restores it after inheritance is let back
        // in.
        allow_inheritance(&file).unwrap();
        crate::PRIVATE_FS.harden_existing(&file).unwrap();
        assert!(dacl_is_protected(&file).unwrap());

        let _ = std::fs::remove_dir_all(&scratch);
    }
}