Skip to main content

safe_sid/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! Safe borrowed and owned wrappers for Windows security identifiers (SIDs).
4//!
5//! A SID identifies a user, group, logon session, or other security principal.
6//! This crate represents one with the same in-memory layout used by Windows:
7//!
8//! - [`Sid`] is a dynamically sized, borrowed SID, analogous to `str`.
9//! - [`SidBuf`] owns a SID, analogous to [`String`].
10//!
11//! `SidBuf` dereferences to `Sid`, and both types implement equality, ordering,
12//! hashing, and formatting. This makes owned SIDs suitable as map and set keys
13//! while still allowing lookup with a borrowed `&Sid`.
14//!
15//! # Creating SIDs
16//!
17//! Build a SID from its identifier authority and its sub-authorities. The
18//! authority can be one of the constants in [`authority`], its raw six-byte
19//! form, or a plain integer:
20//!
21//! ```
22//! use safe_sid::SidBuf;
23//! use safe_sid::authority::SECURITY_NT_AUTHORITY;
24//!
25//! // S-1-5-32-544 is the BUILTIN\Administrators SID.
26//! let administrators = SidBuf::new(SECURITY_NT_AUTHORITY, &[32, 544])?;
27//! assert_eq!(administrators.to_string(), "S-1-5-32-544");
28//! # Ok::<(), safe_sid::Error>(())
29//! ```
30//!
31//! Or ask Windows to create a [well-known SID](well_known):
32//!
33//! ```
34//! use safe_sid::SidBuf;
35//! use safe_sid::well_known::WinLocalSystemSid;
36//!
37//! let local_system = SidBuf::well_known(WinLocalSystemSid, None)?;
38//! assert_eq!(local_system.to_string(), "S-1-5-18");
39//! # Ok::<(), safe_sid::Error>(())
40//! ```
41//!
42//! Numeric SID strings can be parsed without calling Windows:
43//!
44//! ```
45//! use safe_sid::SidBuf;
46//!
47//! let sid: SidBuf = "S-1-5-18".parse()?;
48//! assert_eq!(sid.authority(), 5);
49//! assert_eq!(sid.sub_authorities(), [18]);
50//! # Ok::<(), safe_sid::SidParseError>(())
51//! ```
52//!
53//! [`SidBuf::from_string_sid`] additionally accepts Windows aliases such
54//! as `BA` (BUILTIN\Administrators).
55//!
56//! # Windows API interoperability
57//!
58//! This crate does not depend on the `windows` crate. [`Sid::as_ptr`] and
59//! [`Sid::from_psid`] use raw `c_void` pointers so applications can choose
60//! their own Windows bindings and versions.
61//!
62//! A borrowed SID can be passed to an API for the duration of the call:
63//!
64//! ```
65//! use safe_sid::SidBuf;
66//! use windows::Win32::Security::{GetLengthSid, PSID};
67//!
68//! let sid: SidBuf = "S-1-5-18".parse().unwrap();
69//! // The API must not retain or mutate the borrowed pointer.
70//! let byte_len = unsafe { GetLengthSid(PSID(sid.as_ptr().cast_mut())) };
71//! assert_eq!(byte_len as usize, sid.as_bytes().len());
72//! ```
73//!
74//! Use [`SidBuf::with_capacity`] and [`SidBuf::as_mut_ptr`] for APIs that fill
75//! a caller-supplied SID buffer. The usual Windows two-call pattern is:
76//!
77//! 1. Call the API with no buffer to obtain the required byte count.
78//! 2. Allocate that many bytes with [`SidBuf::with_capacity`].
79//! 3. Pass [`SidBuf::as_mut_ptr`] to the API.
80//! 4. Read the buffer only after the API has successfully written a valid SID.
81//!
82//! See [`SidBuf::as_mut_ptr`] for a complete buffer-filling example.
83
84use std::borrow::Borrow;
85use std::cmp::Ordering;
86use std::ffi::c_void;
87use std::fmt::{Debug, Display};
88use std::hash::{Hash, Hasher};
89use std::ops::Deref;
90use std::str::FromStr;
91
92#[allow(non_snake_case, non_camel_case_types, dead_code, clippy::all)]
93mod bindings;
94
95#[allow(non_upper_case_globals)]
96/// Constants for the SID types accepted by [`SidBuf::well_known`] and
97/// [`Sid::is_well_known`].
98///
99/// The names and values correspond to Windows'
100/// `WELL_KNOWN_SID_TYPE` enumeration.
101pub mod well_known;
102
103/// Constants for the identifier authorities defined by Windows, for use with
104/// [`SidBuf::new`].
105///
106/// The names and values correspond to Windows'
107/// `SECURITY_*_AUTHORITY` constants.
108pub mod authority;
109
110/// A Windows well-known SID type.
111///
112/// Values of this type are exposed as the named constants in [`well_known`],
113/// such as [`well_known::WinLocalSystemSid`]. The integer accepted by the
114/// underlying Windows APIs is intentionally not part of this crate's public
115/// API, so arbitrary integers cannot be used as well-known SID types.
116#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
117#[repr(transparent)]
118pub struct WellKnownSidType(i32);
119
120const SID_REVISION: u8 = 1;
121const SID_MAX_SUB_AUTHORITIES: u8 = 15;
122const SID_HEADER_WORDS: usize = 2;
123const ERROR_INVALID_SID: u32 = 0x0539;
124const MAX_AUTHORITY: u64 = 0xFFFF_FFFF_FFFF;
125
126/// An error reported while creating, validating, or querying a SID.
127///
128/// Failures detected by this crate are reported as descriptive variants, while
129/// failures reported by a Windows API carry the Win32 error code in
130/// [`Error::Windows`]. [`Error::win32_code`] maps any variant to a Win32 error
131/// code, and the [`From`] conversion to [`std::io::Error`] does the same for
132/// I/O-based error handling.
133///
134/// This type is owned by `safe-sid`, so it remains stable independently of the
135/// version of `windows-core` used by an application. String parsing reports
136/// [`SidParseError`] instead, which converts into this type via [`From`].
137#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
138#[non_exhaustive]
139pub enum Error {
140    /// More than 15 sub-authorities were supplied.
141    TooManySubAuthorities,
142    /// An integer identifier authority does not fit in 48 bits.
143    AuthorityOutOfRange,
144    /// The bytes, string, or pointer do not describe a valid SID.
145    InvalidSid,
146    /// A Windows API call failed with this Win32 error code.
147    Windows(u32),
148}
149
150impl Error {
151    /// Returns the Win32 error code equivalent of this error.
152    ///
153    /// Failures detected by this crate map to `ERROR_INVALID_SID`. Failures
154    /// reported by Windows return their original code.
155    #[must_use]
156    pub const fn win32_code(&self) -> u32 {
157        match self {
158            Error::TooManySubAuthorities | Error::AuthorityOutOfRange | Error::InvalidSid => {
159                ERROR_INVALID_SID
160            }
161            Error::Windows(code) => *code,
162        }
163    }
164
165    /// Captures the calling thread's last Win32 error code.
166    fn from_last_win32_error() -> Self {
167        // SAFETY: GetLastError has no preconditions.
168        Error::Windows(unsafe { bindings::GetLastError() })
169    }
170}
171
172impl std::error::Error for Error {}
173
174impl Display for Error {
175    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176        match self {
177            Error::TooManySubAuthorities => write!(f, "a SID holds at most 15 sub-authorities"),
178            Error::AuthorityOutOfRange => {
179                write!(f, "the identifier authority does not fit in 48 bits")
180            }
181            Error::InvalidSid => write!(f, "not a valid SID"),
182            Error::Windows(code) => {
183                Display::fmt(&std::io::Error::from_raw_os_error(*code as i32), f)
184            }
185        }
186    }
187}
188
189impl From<Error> for std::io::Error {
190    fn from(error: Error) -> Self {
191        std::io::Error::from_raw_os_error(error.win32_code() as i32)
192    }
193}
194
195/// A result returned by fallible `safe-sid` operations.
196pub type Result<T> = std::result::Result<T, Error>;
197
198/// Converts a supported pointer wrapper to the raw pointer used by SID APIs.
199///
200/// This trait lets [`Sid::from_psid`] and [`SidBuf::from_psid`] work with raw
201/// `c_void` pointers and user-defined pointer wrappers without depending on a
202/// particular Windows bindings crate.
203pub trait AsSidPtr {
204    /// Returns the wrapped SID pointer.
205    fn as_sid_ptr(&self) -> *const c_void;
206}
207
208/// Converts a well-known SID type to the value expected by Windows.
209///
210/// The crate's constants, such as [`well_known::WinLocalSystemSid`], implement
211/// this trait.
212pub trait AsWellKnownSidType {
213    /// Returns the wrapped well-known SID type.
214    fn as_well_known_sid_type(&self) -> WellKnownSidType;
215}
216
217impl AsWellKnownSidType for WellKnownSidType {
218    fn as_well_known_sid_type(&self) -> WellKnownSidType {
219        *self
220    }
221}
222
223impl AsSidPtr for *const c_void {
224    fn as_sid_ptr(&self) -> *const c_void {
225        *self
226    }
227}
228
229impl AsSidPtr for *mut c_void {
230    fn as_sid_ptr(&self) -> *const c_void {
231        *self
232    }
233}
234
235mod sealed {
236    /// Prevents implementations of [`IntoAuthority`](super::IntoAuthority)
237    /// outside of this crate.
238    pub trait Sealed {}
239}
240
241/// Converts a value into a SID's six-byte identifier authority.
242///
243/// This trait is implemented for `[u8; 6]`, the authority's raw big-endian
244/// form used by the constants in [`authority`], and for every primitive
245/// integer type. Integer values must fit in 48 bits.
246///
247/// The trait is sealed and cannot be implemented outside of `safe-sid`.
248pub trait IntoAuthority: sealed::Sealed {
249    /// Returns the value as a big-endian six-byte identifier authority.
250    ///
251    /// # Errors
252    ///
253    /// Returns [`Error::AuthorityOutOfRange`] if the value cannot be
254    /// represented in 48 bits.
255    fn try_into_authority(self) -> Result<[u8; 6]>;
256}
257
258impl sealed::Sealed for [u8; 6] {}
259
260impl IntoAuthority for [u8; 6] {
261    fn try_into_authority(self) -> Result<[u8; 6]> {
262        Ok(self)
263    }
264}
265
266macro_rules! impl_into_authority {
267    ($($t:ty)*) => {$(
268        impl sealed::Sealed for $t {}
269
270        impl IntoAuthority for $t {
271            #[allow(clippy::useless_conversion)] // the u64 expansion converts u64 to u64
272            fn try_into_authority(self) -> Result<[u8; 6]> {
273                match u64::try_from(self) {
274                    Ok(value) if value <= MAX_AUTHORITY => {
275                        Ok(value.to_be_bytes()[2..].try_into().unwrap())
276                    }
277                    _ => Err(Error::AuthorityOutOfRange),
278                }
279            }
280        }
281    )*};
282}
283
284// i32 is required in this list: with multiple integer impls, an unsuffixed
285// literal in `SidBuf::new(5, ...)` resolves through the compiler's i32
286// fallback, so removing i32 breaks such calls. The list deliberately covers
287// every primitive integer type so it never needs to grow, which keeps that
288// fallback (and therefore inference) stable.
289impl_into_authority!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);
290
291/// A borrowed SID.
292///
293/// `Sid` is byte-compatible with the Windows `SID` structure but represented as
294/// a dynamically sized type. It is normally obtained by dereferencing a
295/// [`SidBuf`] or, when borrowing memory owned elsewhere, by calling
296/// [`Sid::from_psid`].
297///
298/// Use [`ToOwned::to_owned`] to copy a borrowed SID into a [`SidBuf`].
299#[repr(C)]
300pub struct Sid {
301    revision: u8,
302    sub_authority_count: u8,
303    identifier_authority: [u8; 6],
304    sub_authority: [u32],
305}
306
307impl Sid {
308    /// Reinterpret already-validated SID words as a `&Sid`.
309    ///
310    /// `words` must be the two header words followed by the sub-authority words.
311    fn from_words_unchecked(words: &[u32]) -> &Sid {
312        debug_assert!(
313            words.len() >= SID_HEADER_WORDS,
314            "a SID has at least the two header words"
315        );
316        let sub_count = words.len() - SID_HEADER_WORDS;
317        let ptr = std::ptr::slice_from_raw_parts(words.as_ptr(), sub_count) as *const Sid;
318        // SAFETY: ptr is 4-byte aligned, see SidBuf::from_boxed_words for explanation on length validity
319        unsafe { &*ptr }
320    }
321
322    /// See [`Sid::from_words_unchecked`].
323    fn from_words_unchecked_mut(words: &mut [u32]) -> &mut Sid {
324        debug_assert!(
325            words.len() >= SID_HEADER_WORDS,
326            "a SID has at least the two header words"
327        );
328        let sub_count = words.len() - SID_HEADER_WORDS;
329        let ptr = std::ptr::slice_from_raw_parts_mut(words.as_mut_ptr(), sub_count) as *mut Sid;
330        // SAFETY: ptr is 4-byte aligned, see SidBuf::from_boxed_words for explanation on length validity
331        unsafe { &mut *ptr }
332    }
333
334    /// Returns the number of sub-authorities that fit in the backing buffer.
335    #[inline]
336    fn logical_sub_count(&self) -> usize {
337        (self.sub_authority_count as usize).min(self.sub_authority.len())
338    }
339
340    /// The SID's words, independent of any extra buffer capacity
341    /// (see [`with_capacity`](SidBuf::with_capacity)).
342    #[inline]
343    fn words(&self) -> &[u32] {
344        // SAFETY: logical_sub_count() is limited to our actual buffer size, so
345        // even if sub_authority_count is oversized, the returned slice cannot
346        // allow out-of-bounds reads.
347        unsafe {
348            std::slice::from_raw_parts(
349                self as *const Sid as *const u32,
350                SID_HEADER_WORDS + self.logical_sub_count(),
351            )
352        }
353    }
354
355    /// Returns the logical SID as raw bytes.
356    ///
357    /// The slice contains the eight-byte header followed by four bytes for each
358    /// sub-authority. Spare capacity in a [`SidBuf::with_capacity`] allocation
359    /// is not included.
360    #[inline]
361    #[must_use]
362    pub fn as_bytes(&self) -> &[u8] {
363        let words = self.words();
364        // SAFETY: [u32] has a stronger alignment requirement than [u8], size is computed accurately
365        unsafe { std::slice::from_raw_parts(words.as_ptr() as *const u8, size_of_val(words)) }
366    }
367
368    /// The entire backing allocation, including any capacity beyond the logical SID.
369    /// Exposed for testing to validate allocations.
370    #[cfg(test)]
371    fn buffer_bytes(&self) -> &[u8] {
372        let word_len = SID_HEADER_WORDS + self.sub_authority.len();
373        // SAFETY: we know we have a 2 word header and sub_authority gives the allocated length,
374        // so this is an accurate representation of the bytes that can be accessed
375        unsafe {
376            std::slice::from_raw_parts(self as *const Sid as *const u8, word_len * size_of::<u32>())
377        }
378    }
379
380    /// Returns a raw pointer to this SID for use with Windows APIs.
381    ///
382    /// The pointer remains valid only while `self` is alive and has not been
383    /// mutably borrowed. The called API must not mutate the SID through it.
384    #[must_use]
385    pub fn as_ptr(&self) -> *const c_void {
386        self as *const Sid as *const c_void
387    }
388
389    /// Borrows a raw `PSID` as `&'a Sid`, validating its structure.
390    ///
391    /// # Safety
392    ///
393    /// `psid` must be non-null and point to a readable, 4-byte-aligned SID that
394    /// remains valid for `'a`. Its sub-authority count must accurately describe
395    /// the allocation. SIDs allocated by Windows meet these requirements.
396    ///
397    /// # Errors
398    ///
399    /// Returns [`Error::InvalidSid`] if the revision or sub-authority count is
400    /// outside the range allowed by Windows.
401    pub unsafe fn from_psid<'a>(psid: impl AsSidPtr) -> Result<&'a Sid> {
402        let psid = psid.as_sid_ptr();
403
404        // SAFETY: the safety rules stated to the caller apply here
405        let p = psid as *const u8;
406        let (revision, sub_count) = unsafe { (*p, *p.add(1)) };
407        if revision != SID_REVISION || sub_count > SID_MAX_SUB_AUTHORITIES {
408            return Err(Error::InvalidSid);
409        }
410
411        // Validate 4-byte alignment in debug mode
412        debug_assert!(
413            (psid as usize).is_multiple_of(align_of::<u32>()),
414            "SID pointer is not 4-byte aligned",
415        );
416
417        // Header + sub-authorities
418        let word_len = SID_HEADER_WORDS + sub_count as usize;
419
420        // SAFETY: the safety rules stated to the caller apply here
421        let words = unsafe { std::slice::from_raw_parts(psid as *const u32, word_len) };
422        Ok(Sid::from_words_unchecked(words))
423    }
424
425    /// Returns the SID revision.
426    ///
427    /// Valid Windows SIDs currently have revision 1.
428    #[inline]
429    #[must_use]
430    pub fn revision(&self) -> u8 {
431        self.revision
432    }
433
434    /// Returns the number of sub-authorities recorded in the SID header.
435    #[inline]
436    #[must_use]
437    pub fn sub_authority_count(&self) -> u8 {
438        self.sub_authority_count
439    }
440
441    /// Returns the 48-bit identifier authority as an integer.
442    #[inline]
443    #[must_use]
444    pub fn authority(&self) -> u64 {
445        let [a0, a1, a2, a3, a4, a5] = self.identifier_authority;
446        u64::from_be_bytes([0, 0, a0, a1, a2, a3, a4, a5])
447    }
448
449    /// Returns the identifier authority in its big-endian six-byte form.
450    ///
451    /// This is the representation used by the constants in [`authority`] and
452    /// accepted by [`SidBuf::new`].
453    #[inline]
454    #[must_use]
455    pub fn authority_bytes(&self) -> [u8; 6] {
456        self.identifier_authority
457    }
458
459    /// Returns the sub-authority at `idx`, or `None` if it is out of bounds.
460    #[inline]
461    #[must_use]
462    pub fn sub_authority(&self, idx: u8) -> Option<u32> {
463        self.sub_authorities().get(idx as usize).copied()
464    }
465
466    /// Returns the SID's relative identifier (RID).
467    ///
468    /// A RID is the final sub-authority. Returns `None` when the SID has no
469    /// sub-authorities.
470    #[inline]
471    #[must_use]
472    pub fn rid(&self) -> Option<u32> {
473        self.sub_authorities().last().copied()
474    }
475
476    /// Returns all of the SID's sub-authorities.
477    #[inline]
478    #[must_use]
479    pub fn sub_authorities(&self) -> &[u32] {
480        &self.sub_authority[..self.logical_sub_count()]
481    }
482
483    /// Tests whether this SID and `other` have equal prefixes.
484    ///
485    /// A SID prefix contains the revision, identifier authority, sub-authority
486    /// count, and every sub-authority except the last.
487    #[inline]
488    #[must_use]
489    pub fn equal_prefix(&self, other: &Sid) -> bool {
490        self.revision == other.revision
491            && self.identifier_authority == other.identifier_authority
492            && self.sub_authority_count == other.sub_authority_count
493            && match (
494                self.sub_authorities().split_last(),
495                other.sub_authorities().split_last(),
496            ) {
497                (Some((_, prefix1)), Some((_, prefix2))) => prefix1 == prefix2,
498                (None, None) => true,
499                _ => false,
500            }
501    }
502
503    /// Tests whether this SID and `other` belong to the same Windows account
504    /// domain.
505    ///
506    /// Calls the Windows `EqualDomainSid` function.
507    ///
508    /// Both SIDs must be account-domain SIDs or BUILTIN SIDs.
509    ///
510    /// # Errors
511    ///
512    /// Returns the error reported by `EqualDomainSid`.
513    #[inline]
514    pub fn equal_domain(&self, other: &Sid) -> Result<bool> {
515        let mut equal = 0;
516        // SAFETY: both pointers refer to valid SIDs and equal is a valid output pointer
517        if unsafe {
518            bindings::EqualDomainSid(
519                self.as_ptr().cast_mut(),
520                other.as_ptr().cast_mut(),
521                &mut equal,
522            )
523        } == 0
524        {
525            return Err(Error::from_last_win32_error());
526        }
527        Ok(equal != 0)
528    }
529
530    /// Returns the Windows account-domain SID containing this SID.
531    ///
532    /// Calls the Windows `GetWindowsAccountDomainSid` function.
533    ///
534    /// # Errors
535    ///
536    /// Returns the error reported by `GetWindowsAccountDomainSid`.
537    #[inline]
538    pub fn account_domain_sid(&self) -> Result<SidBuf> {
539        unsafe {
540            let mut len = 0u32;
541            if bindings::GetWindowsAccountDomainSid(
542                self.as_ptr().cast_mut(),
543                std::ptr::null_mut(),
544                &mut len,
545            ) == 0
546            {
547                let error = Error::from_last_win32_error();
548                if error.win32_code() != bindings::ERROR_INSUFFICIENT_BUFFER {
549                    return Err(error);
550                }
551            }
552
553            let mut domain_sid = SidBuf::with_capacity(len as usize);
554            if bindings::GetWindowsAccountDomainSid(
555                self.as_ptr().cast_mut(),
556                domain_sid.as_mut_ptr(),
557                &mut len,
558            ) == 0
559            {
560                return Err(Error::from_last_win32_error());
561            }
562            Ok(domain_sid)
563        }
564    }
565
566    /// Tests whether this SID has the specified well-known SID type.
567    ///
568    /// Calls the Windows `IsWellKnownSid` function.
569    #[inline]
570    #[must_use]
571    pub fn is_well_known(&self, well_known_type: impl AsWellKnownSidType) -> bool {
572        let well_known_type = well_known_type.as_well_known_sid_type();
573        // SAFETY: self supplies a valid SID pointer
574        unsafe { bindings::IsWellKnownSid(self.as_ptr().cast_mut(), well_known_type.0) != 0 }
575    }
576}
577
578impl ToOwned for Sid {
579    type Owned = SidBuf;
580    fn to_owned(&self) -> SidBuf {
581        SidBuf::from_boxed_words(self.words().to_vec().into_boxed_slice())
582    }
583}
584
585impl Eq for Sid {}
586
587impl PartialEq for Sid {
588    #[inline]
589    fn eq(&self, other: &Self) -> bool {
590        self.as_bytes() == other.as_bytes()
591    }
592}
593
594impl Hash for Sid {
595    fn hash<H: Hasher>(&self, state: &mut H) {
596        state.write(self.as_bytes());
597    }
598}
599
600impl PartialOrd for Sid {
601    #[inline]
602    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
603        Some(self.cmp(other))
604    }
605}
606
607impl Ord for Sid {
608    #[inline]
609    fn cmp(&self, other: &Self) -> Ordering {
610        self.authority()
611            .cmp(&other.authority())
612            .then_with(|| self.sub_authorities().cmp(other.sub_authorities()))
613    }
614}
615
616impl Display for Sid {
617    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
618        f.write_str("S-1-")?;
619        let authority = self.authority();
620        if authority <= 0xFFFFFFFF {
621            write!(f, "{}", authority)?;
622        } else {
623            // 12 byte hex display for authorities that don't fit in 8 bytes
624            write!(f, "0x{:012X}", authority)?;
625        }
626
627        for sa in self.sub_authorities() {
628            write!(f, "-{}", sa)?;
629        }
630
631        Ok(())
632    }
633}
634
635impl Debug for Sid {
636    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
637        write!(f, "\"{}\"", self)
638    }
639}
640
641/// An owned copy of a SID's bytes.
642///
643/// `SidBuf` dereferences to [`Sid`], so all borrowed-SID operations are
644/// available directly on an owned value. Clone a `SidBuf` to duplicate its
645/// bytes, or borrow it as `&Sid` without allocating.
646pub struct SidBuf {
647    sid: Box<Sid>,
648}
649
650impl Clone for SidBuf {
651    fn clone(&self) -> Self {
652        (**self).to_owned()
653    }
654}
655
656/// The error returned when a string is not a valid SID.
657///
658/// Both [`SidBuf::from_str`](FromStr::from_str) and
659/// [`SidBuf::from_string_sid`] report this error; see those functions for the
660/// formats they accept. The [`From`] conversion to [`Error`] lets `?`
661/// propagate a parse failure from a function returning [`Result`].
662#[derive(Clone, Debug, Eq, PartialEq)]
663pub struct SidParseError {
664    kind: SidParseErrorKind,
665}
666
667/// The private detail behind [`SidParseError`], following the pattern of
668/// [`std::num::ParseIntError`]. Kept private so the cases can be refined
669/// without a breaking change; visible through `Debug` output only.
670#[derive(Clone, Debug, Eq, PartialEq)]
671enum SidParseErrorKind {
672    /// The string does not match the SID grammar.
673    Invalid,
674    /// The string contains an interior NUL byte, so it cannot be passed to
675    /// Windows.
676    InteriorNul,
677    /// `ConvertStringSidToSid` rejected the string with this Win32 error code.
678    Windows(u32),
679}
680
681impl SidParseError {
682    fn invalid() -> Self {
683        Self {
684            kind: SidParseErrorKind::Invalid,
685        }
686    }
687}
688
689impl std::error::Error for SidParseError {}
690
691impl Display for SidParseError {
692    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
693        match self.kind {
694            SidParseErrorKind::Invalid => write!(f, "invalid SID string"),
695            SidParseErrorKind::InteriorNul => {
696                write!(f, "SID string contains an interior NUL byte")
697            }
698            SidParseErrorKind::Windows(code) => {
699                write!(
700                    f,
701                    "invalid SID string: {}",
702                    std::io::Error::from_raw_os_error(code as i32)
703                )
704            }
705        }
706    }
707}
708
709impl From<SidParseError> for Error {
710    fn from(_: SidParseError) -> Error {
711        Error::InvalidSid
712    }
713}
714
715/// Parses a numeric SID string such as `S-1-5-32-544`.
716///
717/// The format is `S-1-<authority>` followed by zero to fifteen `-<sub-authority>`
718/// components: the literal `S` (case-insensitive), the revision `1`, an
719/// identifier authority of at most 48 bits in decimal or `0x`/`0X`-prefixed
720/// hexadecimal, and decimal sub-authorities. Parsing is pure Rust and never
721/// calls Windows; use [`SidBuf::from_string_sid`] for Windows-defined
722/// aliases such as `BA`.
723///
724/// Every string produced by the [`Display`] implementation parses back to an
725/// equal SID. The parser also accepts equivalent spellings that [`Display`]
726/// never produces: a lowercase `s`, leading zeros, and hexadecimal
727/// authorities small enough to be displayed in decimal. Signs, whitespace,
728/// empty components, and non-ASCII digits are rejected.
729///
730/// # Examples
731///
732/// ```
733/// use safe_sid::SidBuf;
734///
735/// let sid: SidBuf = "S-1-5-32-544".parse()?;
736/// assert_eq!(sid.authority(), 5);
737/// assert_eq!(sid.sub_authorities(), [32, 544]);
738///
739/// assert!("S-1-5-".parse::<SidBuf>().is_err());
740/// assert!("BA".parse::<SidBuf>().is_err()); // aliases need from_string_sid
741/// # Ok::<(), safe_sid::SidParseError>(())
742/// ```
743impl FromStr for SidBuf {
744    type Err = SidParseError;
745
746    /// Parses a numeric SID string.
747    ///
748    /// # Errors
749    ///
750    /// Returns [`SidParseError`] if the string does not match the format
751    /// described [above](#impl-FromStr-for-SidBuf).
752    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
753        let mut parts = s.split('-');
754
755        // Leading "S", case-insensitive
756        match parts.next() {
757            Some(p) if p.eq_ignore_ascii_case("S") => {}
758            _ => return Err(SidParseError::invalid()),
759        }
760
761        // Revision (only 1 is allowed)
762        if parts.next() != Some("1") {
763            return Err(SidParseError::invalid());
764        }
765
766        // Identifier authority: decimal or 0x-prefixed hex, 48 bits max
767        let authority_str = parts.next().ok_or_else(SidParseError::invalid)?;
768        let authority = match authority_str
769            .strip_prefix("0x")
770            .or_else(|| authority_str.strip_prefix("0X"))
771        {
772            Some(hex) if !hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit()) => {
773                u64::from_str_radix(hex, 16).map_err(|_| SidParseError::invalid())?
774            }
775            Some(_) => return Err(SidParseError::invalid()),
776            None if !authority_str.is_empty()
777                && authority_str.bytes().all(|b| b.is_ascii_digit()) =>
778            {
779                authority_str
780                    .parse::<u64>()
781                    .map_err(|_| SidParseError::invalid())?
782            }
783            None => return Err(SidParseError::invalid()),
784        };
785        // Remaining fields are decimal sub-authorities
786        let sub_authorities = parts
787            .map(|p| {
788                if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
789                    return Err(SidParseError::invalid());
790                }
791                p.parse::<u32>().map_err(|_| SidParseError::invalid())
792            })
793            .collect::<std::result::Result<Vec<u32>, _>>()?;
794
795        // new() rejects authorities over 48 bits and more than 15 sub-authorities
796        SidBuf::new(authority, &sub_authorities).map_err(|_| SidParseError::invalid())
797    }
798}
799
800impl SidBuf {
801    /// Takes ownership of already-validated SID data as a `Box<Sid>`.
802    ///
803    /// `words` must be the two header words followed by the sub-authority words.
804    fn from_boxed_words(words: Box<[u32]>) -> SidBuf {
805        debug_assert!(
806            words.len() >= SID_HEADER_WORDS,
807            "a SID has at least the two header words"
808        );
809        let sub_count = words.len() - SID_HEADER_WORDS;
810        // A DST pointer tracks only the trailing slice length. The input box is
811        // entirely an array, while Sid has two header words before its slice,
812        // so the pointer metadata excludes those header words.
813        let data = Box::into_raw(words).cast::<u32>();
814        let ptr = std::ptr::slice_from_raw_parts_mut(data, sub_count) as *mut Sid;
815        // SAFETY: We are reboxing a pointer with the same alignment as the one it was detached from
816        SidBuf {
817            sid: unsafe { Box::from_raw(ptr) },
818        }
819    }
820
821    /// Builds a SID from its identifier authority and sub-authorities.
822    ///
823    /// The authority may be one of the constants in [`authority`], the raw
824    /// big-endian `[u8; 6]` form, or any primitive integer that fits in
825    /// 48 bits.
826    ///
827    /// # Errors
828    ///
829    /// Returns [`Error::TooManySubAuthorities`] if more than 15 sub-authorities
830    /// are given, or [`Error::AuthorityOutOfRange`] if the authority cannot be
831    /// represented in 48 bits.
832    ///
833    pub fn new(identifier_authority: impl IntoAuthority, sub_authorities: &[u32]) -> Result<Self> {
834        let identifier_authority = identifier_authority.try_into_authority()?;
835        let count = sub_authorities.len();
836        if count > SID_MAX_SUB_AUTHORITIES as usize {
837            return Err(Error::TooManySubAuthorities);
838        }
839
840        let mut words = vec![0u32; SID_HEADER_WORDS + count].into_boxed_slice();
841        let sid = Sid::from_words_unchecked_mut(&mut words);
842        sid.revision = SID_REVISION;
843        sid.sub_authority_count = count as u8;
844        sid.identifier_authority = identifier_authority;
845        sid.sub_authority.copy_from_slice(sub_authorities);
846
847        Ok(Self::from_boxed_words(words))
848    }
849
850    /// Copies a SID from its raw byte representation.
851    ///
852    /// The input does not need to be aligned. Its length must exactly match the
853    /// sub-authority count recorded in the SID header; trailing capacity is not
854    /// accepted.
855    ///
856    /// # Errors
857    ///
858    /// Returns [`Error::InvalidSid`] if the input is too short, has an
859    /// unsupported revision or sub-authority count, or does not have the exact
860    /// length required by its header.
861    ///
862    /// # Examples
863    ///
864    /// ```
865    /// use safe_sid::SidBuf;
866    ///
867    /// let bytes = [
868    ///     1, 2, 0, 0, 0, 0, 0, 5, // revision, count, NT authority
869    ///     32, 0, 0, 0,             // BUILTIN
870    ///     32, 2, 0, 0,             // Administrators
871    /// ];
872    /// let administrators = SidBuf::from_bytes(&bytes)?;
873    /// assert_eq!(administrators.to_string(), "S-1-5-32-544");
874    /// # Ok::<(), safe_sid::Error>(())
875    /// ```
876    pub fn from_bytes(bytes: &[u8]) -> Result<SidBuf> {
877        let header_len = SID_HEADER_WORDS * size_of::<u32>();
878        if bytes.len() < header_len || bytes[0] != SID_REVISION {
879            return Err(Error::InvalidSid);
880        }
881
882        let count = bytes[1] as usize;
883        if count > SID_MAX_SUB_AUTHORITIES as usize
884            || bytes.len() != header_len + count * size_of::<u32>()
885        {
886            return Err(Error::InvalidSid);
887        }
888
889        let identifier_authority: [u8; 6] = bytes[2..header_len].try_into().unwrap();
890        let sub_authorities = bytes[header_len..]
891            .chunks_exact(size_of::<u32>())
892            .map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap()))
893            .collect::<Vec<_>>();
894
895        SidBuf::new(identifier_authority, &sub_authorities)
896    }
897
898    /// Allocates a `SidBuf` of `len` bytes for a Windows API to fill.
899    ///
900    /// The buffer initially contains the null SID (`S-1-0-0`). `len` is the
901    /// total requested size of the SID structure in bytes. It is rounded up to
902    /// the next four-byte boundary, with a minimum allocation of 12 bytes.
903    ///
904    /// Extra capacity is not exposed by [`Sid::as_bytes`]; the logical length is
905    /// determined by [`Sid::sub_authority_count`].
906    #[must_use]
907    pub fn with_capacity(len: usize) -> SidBuf {
908        let word_len = len.div_ceil(size_of::<u32>()).max(SID_HEADER_WORDS + 1);
909
910        let mut words = vec![0u32; word_len].into_boxed_slice();
911        let sid = Sid::from_words_unchecked_mut(&mut words);
912        sid.revision = SID_REVISION;
913        sid.sub_authority_count = 1;
914
915        SidBuf::from_boxed_words(words)
916    }
917
918    /// Returns a mutable pointer to this SID's bytes for a Windows API to fill.
919    ///
920    /// This is intended for the second call of Windows APIs that first report a
921    /// required buffer length. Allocate that length with
922    /// [`SidBuf::with_capacity`], then pass this pointer to the API.
923    ///
924    /// # Safety
925    ///
926    /// Writing through the pointer can leave the buffer holding bytes that are
927    /// not a valid SID. The caller must not write past the length supplied to
928    /// [`SidBuf::with_capacity`] and must leave a valid SID behind before
929    /// accessing the buffer through `&Sid`. Dropping the buffer remains safe
930    /// even if the API fails or writes malformed data.
931    ///
932    /// # Examples
933    ///
934    /// This example uses the standard two-call pattern to look up an account
935    /// name. The first call obtains the two buffer lengths, and the second fills
936    /// the allocated SID and domain-name buffers.
937    ///
938    /// ```no_run
939    /// use safe_sid::SidBuf;
940    /// use std::ffi::CStr;
941    /// use windows::Win32::Security::{LookupAccountNameA, PSID, SID_NAME_USE};
942    /// use windows::core::{HRESULT, PCSTR, PSTR, Result};
943    ///
944    /// fn lookup_account_name(name: &CStr) -> Result<SidBuf> {
945    ///     let mut sid_use = SID_NAME_USE::default();
946    ///     let mut sid_len = 0u32;
947    ///     let mut domain_len = 0u32;
948    ///
949    ///     unsafe {
950    ///         if let Err(error) = LookupAccountNameA(
951    ///             PCSTR::null(),
952    ///             PCSTR(name.as_ptr().cast()),
953    ///             None,
954    ///             &mut sid_len,
955    ///             None,
956    ///             &mut domain_len,
957    ///             &mut sid_use,
958    ///         ) && error.code() != HRESULT::from_win32(122) // ERROR_INSUFFICIENT_BUFFER
959    ///         {
960    ///             return Err(error);
961    ///         }
962    ///
963    ///         let mut sid = SidBuf::with_capacity(sid_len as usize);
964    ///         let mut domain = vec![0u8; domain_len as usize];
965    ///         LookupAccountNameA(
966    ///             PCSTR::null(),
967    ///             PCSTR(name.as_ptr().cast()),
968    ///             Some(PSID(sid.as_mut_ptr())),
969    ///             &mut sid_len,
970    ///             Some(PSTR(domain.as_mut_ptr())),
971    ///             &mut domain_len,
972    ///             &mut sid_use,
973    ///         )?;
974    ///         Ok(sid)
975    ///     }
976    /// }
977    ///
978    /// # let _ = lookup_account_name;
979    /// ```
980    #[must_use]
981    pub unsafe fn as_mut_ptr(&mut self) -> *mut c_void {
982        let sid: &mut Sid = &mut self.sid;
983        sid as *mut Sid as *mut c_void
984    }
985
986    /// Builds a well-known SID with `CreateWellKnownSid`.
987    ///
988    /// `domain_sid` is required for well-known types whose value depends on a
989    /// Windows domain and should otherwise be `None`.
990    ///
991    /// # Errors
992    ///
993    /// Returns the error reported by `CreateWellKnownSid`.
994    ///
995    pub fn well_known(
996        well_known_type: impl AsWellKnownSidType,
997        domain_sid: Option<&Sid>,
998    ) -> Result<SidBuf> {
999        unsafe {
1000            let well_known_type = well_known_type.as_well_known_sid_type();
1001            let domain_psid = domain_sid
1002                .map(|sid| sid.as_ptr().cast_mut())
1003                .unwrap_or(std::ptr::null_mut());
1004            let mut len = 0u32;
1005            if bindings::CreateWellKnownSid(
1006                well_known_type.0,
1007                domain_psid,
1008                std::ptr::null_mut(),
1009                &mut len,
1010            ) == 0
1011            {
1012                let error = Error::from_last_win32_error();
1013                if error.win32_code() != bindings::ERROR_INSUFFICIENT_BUFFER {
1014                    return Err(error);
1015                }
1016            }
1017
1018            let word_len = (len as usize)
1019                .div_ceil(size_of::<u32>())
1020                .max(SID_HEADER_WORDS);
1021            let mut words: Box<[u32]> = vec![0u32; word_len].into_boxed_slice();
1022            if bindings::CreateWellKnownSid(
1023                well_known_type.0,
1024                domain_psid,
1025                words.as_mut_ptr().cast(),
1026                &mut len,
1027            ) == 0
1028            {
1029                return Err(Error::from_last_win32_error());
1030            }
1031
1032            Ok(SidBuf::from_boxed_words(words))
1033        }
1034    }
1035
1036    /// Converts a string SID to a SID with `ConvertStringSidToSidA`.
1037    ///
1038    /// Unlike [`FromStr`], this accepts string constants such as `BA` and `AU`
1039    /// in addition to numeric SIDs. Windows performs the parsing and may clamp
1040    /// overflowing numeric components instead of rejecting them.
1041    ///
1042    /// String SIDs and their constants are ASCII. This method converts the
1043    /// input to a C string before passing it to the ANSI Windows API.
1044    ///
1045    /// # Errors
1046    ///
1047    /// Returns [`SidParseError`] if `s` contains an interior NUL byte or is
1048    /// rejected by `ConvertStringSidToSidA`.
1049    ///
1050    pub fn from_string_sid(s: &str) -> std::result::Result<SidBuf, SidParseError> {
1051        let s = std::ffi::CString::new(s).map_err(|_| SidParseError {
1052            kind: SidParseErrorKind::InteriorNul,
1053        })?;
1054
1055        unsafe {
1056            let mut sid = std::ptr::null_mut();
1057            if bindings::ConvertStringSidToSidA(s.as_ptr().cast(), &mut sid) == 0 {
1058                return Err(SidParseError {
1059                    kind: SidParseErrorKind::Windows(bindings::GetLastError()),
1060                });
1061            }
1062            let res = SidBuf::from_psid(sid).map_err(|_| SidParseError::invalid());
1063            bindings::LocalFree(sid);
1064            res
1065        }
1066    }
1067
1068    /// Validates and copies the SID pointed to by `psid` into an owned buffer.
1069    ///
1070    /// # Errors
1071    ///
1072    /// Returns [`Error::InvalidSid`] if the pointer does not reference a valid
1073    /// SID.
1074    ///
1075    /// # Safety
1076    ///
1077    /// `psid` must be non-null and point to a readable, 4-byte-aligned SID for
1078    /// the duration of this call. Its sub-authority count must accurately
1079    /// describe the allocation. The data is copied, so the pointer need not
1080    /// remain valid after this function returns.
1081    pub unsafe fn from_psid(psid: impl AsSidPtr) -> Result<Self> {
1082        // SAFETY: safety requirements noted to the caller in the doc comment
1083        let src = unsafe { Sid::from_psid(psid) }?;
1084        Ok(src.to_owned())
1085    }
1086}
1087
1088impl Deref for SidBuf {
1089    type Target = Sid;
1090    #[inline]
1091    fn deref(&self) -> &Sid {
1092        &self.sid
1093    }
1094}
1095
1096impl Borrow<Sid> for SidBuf {
1097    #[inline]
1098    fn borrow(&self) -> &Sid {
1099        self
1100    }
1101}
1102
1103impl AsRef<Sid> for SidBuf {
1104    #[inline]
1105    fn as_ref(&self) -> &Sid {
1106        self
1107    }
1108}
1109
1110impl Eq for SidBuf {}
1111
1112impl PartialEq for SidBuf {
1113    #[inline]
1114    fn eq(&self, other: &Self) -> bool {
1115        (**self).eq(&**other)
1116    }
1117}
1118
1119impl Hash for SidBuf {
1120    fn hash<H: Hasher>(&self, state: &mut H) {
1121        (**self).hash(state);
1122    }
1123}
1124
1125impl PartialOrd for SidBuf {
1126    #[inline]
1127    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1128        Some(self.cmp(other))
1129    }
1130}
1131
1132impl Ord for SidBuf {
1133    #[inline]
1134    fn cmp(&self, other: &Self) -> Ordering {
1135        (**self).cmp(&**other)
1136    }
1137}
1138
1139impl Display for SidBuf {
1140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1141        Display::fmt(&**self, f)
1142    }
1143}
1144
1145impl Debug for SidBuf {
1146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1147        Debug::fmt(&**self, f)
1148    }
1149}
1150
1151impl Default for SidBuf {
1152    fn default() -> Self {
1153        SidBuf::new(authority::SECURITY_NULL_SID_AUTHORITY, &[0]).unwrap()
1154    }
1155}
1156
1157impl PartialEq<SidBuf> for Sid {
1158    #[inline]
1159    fn eq(&self, other: &SidBuf) -> bool {
1160        self == &**other
1161    }
1162}
1163
1164impl PartialEq<Sid> for SidBuf {
1165    #[inline]
1166    fn eq(&self, other: &Sid) -> bool {
1167        &**self == other
1168    }
1169}
1170
1171impl PartialEq<&Sid> for SidBuf {
1172    #[inline]
1173    fn eq(&self, other: &&Sid) -> bool {
1174        &**self == *other
1175    }
1176}
1177
1178impl PartialEq<SidBuf> for &Sid {
1179    #[inline]
1180    fn eq(&self, other: &SidBuf) -> bool {
1181        *self == &**other
1182    }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187    use super::authority::*;
1188    use super::well_known::*;
1189    use super::*;
1190
1191    fn nt_sid(sub_authorities: &[u32]) -> SidBuf {
1192        SidBuf::new(SECURITY_NT_AUTHORITY, sub_authorities).unwrap()
1193    }
1194
1195    #[test]
1196    fn from_psid_rejects_invalid_headers() {
1197        for header in [[0, 0], [SID_REVISION, SID_MAX_SUB_AUTHORITIES + 1]] {
1198            let words = [u32::from_ne_bytes([header[0], header[1], 0, 0]), 0];
1199            let psid = words.as_ptr() as *const c_void;
1200
1201            assert!(unsafe { Sid::from_psid(psid) }.is_err());
1202            assert!(unsafe { SidBuf::from_psid(psid) }.is_err());
1203        }
1204    }
1205
1206    #[test]
1207    fn new_enforces_the_sub_authority_limit() {
1208        assert_eq!(
1209            SidBuf::new([0; 6], &[7; 15]).unwrap().sub_authority_count(),
1210            15
1211        );
1212        assert_eq!(
1213            SidBuf::new([0; 6], &[0; 16]).unwrap_err(),
1214            Error::TooManySubAuthorities
1215        );
1216    }
1217
1218    #[test]
1219    fn from_bytes_copies_aligned_and_unaligned_sids() {
1220        let expected = nt_sid(&[32, 544]);
1221        let bytes = expected.as_bytes();
1222
1223        assert_eq!(SidBuf::from_bytes(bytes).unwrap(), expected);
1224
1225        let mut unaligned = vec![0xFF];
1226        unaligned.extend_from_slice(bytes);
1227        assert_eq!(SidBuf::from_bytes(&unaligned[1..]).unwrap(), expected);
1228    }
1229
1230    #[test]
1231    fn from_bytes_validates_the_complete_structure() {
1232        let no_sub_authorities = [SID_REVISION, 0, 0, 0, 0, 0, 0, 5];
1233        assert_eq!(
1234            SidBuf::from_bytes(&no_sub_authorities)
1235                .unwrap()
1236                .sub_authorities(),
1237            &[]
1238        );
1239
1240        let mut too_many_sub_authorities =
1241            vec![0; SID_HEADER_WORDS * size_of::<u32>() + 16 * size_of::<u32>()];
1242        too_many_sub_authorities[0] = SID_REVISION;
1243        too_many_sub_authorities[1] = SID_MAX_SUB_AUTHORITIES + 1;
1244
1245        for bytes in [
1246            &[][..],
1247            &[0, 0, 0, 0, 0, 0, 0, 0],
1248            &[SID_REVISION, 1, 0, 0, 0, 0, 0, 5],
1249            &[SID_REVISION, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0],
1250            &too_many_sub_authorities,
1251        ] {
1252            assert_eq!(SidBuf::from_bytes(bytes).unwrap_err(), Error::InvalidSid);
1253        }
1254    }
1255
1256    #[test]
1257    fn rid_returns_the_final_sub_authority() {
1258        assert_eq!(nt_sid(&[21, 1, 2, 3, 1000]).rid(), Some(1000));
1259        assert_eq!(SidBuf::new(5, &[]).unwrap().rid(), None);
1260    }
1261
1262    #[test]
1263    fn new_accepts_every_authority_form() {
1264        let from_const = SidBuf::new(SECURITY_NT_AUTHORITY, &[18]).unwrap();
1265        // Each of these forms must keep compiling: the unsuffixed literal
1266        // resolves through the i32 fallback and the unsuffixed array through
1267        // the sole [u8; 6] impl
1268        let from_array = SidBuf::new([0, 0, 0, 0, 0, 5], &[18]).unwrap();
1269        let from_literal = SidBuf::new(5, &[18]).unwrap();
1270        let from_u8 = SidBuf::new(5u8, &[18]).unwrap();
1271        let from_u64 = SidBuf::new(5u64, &[18]).unwrap();
1272        let from_usize = SidBuf::new(5usize, &[18]).unwrap();
1273        let from_i128 = SidBuf::new(5i128, &[18]).unwrap();
1274
1275        for sid in [
1276            from_array,
1277            from_literal,
1278            from_u8,
1279            from_u64,
1280            from_usize,
1281            from_i128,
1282        ] {
1283            assert_eq!(sid, from_const);
1284        }
1285    }
1286
1287    #[test]
1288    fn new_enforces_the_authority_range() {
1289        assert_eq!(
1290            SidBuf::new(MAX_AUTHORITY, &[]).unwrap().authority(),
1291            MAX_AUTHORITY
1292        );
1293
1294        for result in [
1295            SidBuf::new(-1, &[]),
1296            SidBuf::new(1u64 << 48, &[]),
1297            SidBuf::new(u128::MAX, &[]),
1298            SidBuf::new(i64::MIN, &[]),
1299        ] {
1300            assert_eq!(result.unwrap_err(), Error::AuthorityOutOfRange);
1301        }
1302    }
1303
1304    #[test]
1305    fn authority_getters_round_trip_through_new() {
1306        let sid = nt_sid(&[32, 544]);
1307        assert_eq!(sid.authority(), 5);
1308        assert_eq!(sid.authority_bytes(), SECURITY_NT_AUTHORITY);
1309        assert_eq!(
1310            SidBuf::new(sid.authority(), sid.sub_authorities()).unwrap(),
1311            sid
1312        );
1313
1314        let large = SidBuf::new(1u64 << 32, &[1]).unwrap();
1315        assert_eq!(large.authority_bytes(), [0, 1, 0, 0, 0, 0]);
1316        assert_eq!(
1317            SidBuf::new(large.authority_bytes(), large.sub_authorities()).unwrap(),
1318            large
1319        );
1320    }
1321
1322    #[test]
1323    fn errors_map_to_win32_codes() {
1324        assert_eq!(Error::TooManySubAuthorities.win32_code(), ERROR_INVALID_SID);
1325        assert_eq!(Error::AuthorityOutOfRange.win32_code(), ERROR_INVALID_SID);
1326        assert_eq!(Error::InvalidSid.win32_code(), ERROR_INVALID_SID);
1327        assert_eq!(Error::Windows(5).win32_code(), 5);
1328
1329        let io_error: std::io::Error = Error::Windows(5).into();
1330        assert_eq!(io_error.raw_os_error(), Some(5));
1331
1332        assert_eq!(Error::from(SidParseError::invalid()), Error::InvalidSid);
1333
1334        for error in [Error::TooManySubAuthorities, Error::Windows(5)] {
1335            assert!(!error.to_string().is_empty());
1336        }
1337    }
1338
1339    #[test]
1340    fn well_known_sids_construct() {
1341        for (kind, expected) in [
1342            (WinNullSid, "S-1-0-0"),
1343            (WinLocalSystemSid, "S-1-5-18"),
1344            (WinBuiltinAdministratorsSid, "S-1-5-32-544"),
1345        ] {
1346            assert_eq!(
1347                SidBuf::well_known(kind, None).unwrap().to_string(),
1348                expected
1349            );
1350        }
1351    }
1352
1353    #[test]
1354    fn new_builds_the_expected_sid() {
1355        let sid = nt_sid(&[32, 544]);
1356
1357        assert_eq!(
1358            sid.as_bytes(),
1359            &[
1360                0x01, // revision
1361                0x02, // sub-authority count
1362                0x00, 0x00, 0x00, 0x00, 0x00, 0x05, // authority, big-endian
1363                0x20, 0x00, 0x00, 0x00, // sub-authority #1, little-endian
1364                0x20, 0x02, 0x00, 0x00, // sub-authority #2, little-endian
1365            ]
1366        );
1367        assert_eq!(sid.revision(), SID_REVISION);
1368        assert_eq!(sid.sub_authority_count(), 2);
1369        assert_eq!(sid.authority(), 5);
1370        assert_eq!(sid.sub_authority(0), Some(32));
1371        assert_eq!(sid.sub_authority(1), Some(544));
1372        assert_eq!(sid.sub_authority(2), None);
1373        assert_eq!(sid.sub_authorities(), [32, 544]);
1374    }
1375
1376    #[test]
1377    fn from_psid_borrows_or_copies_as_requested() {
1378        let copied = {
1379            let src = nt_sid(&[18]);
1380            let borrowed = unsafe { Sid::from_psid(src.as_ptr()) }.expect("valid SID");
1381            let copied = unsafe { SidBuf::from_psid(src.as_ptr()) }.expect("valid SID");
1382
1383            assert_eq!(borrowed, &*src);
1384            assert_eq!(copied, src);
1385            copied
1386        };
1387
1388        assert_eq!(copied.to_string(), "S-1-5-18");
1389    }
1390
1391    #[test]
1392    fn with_capacity_separates_logical_length_from_buffer_length() {
1393        for (requested, allocated) in [(0, 12), (12, 12), (13, 16), (200, 200)] {
1394            let sid = SidBuf::with_capacity(requested);
1395
1396            assert_eq!(sid.buffer_bytes().len(), allocated);
1397            assert_eq!(sid.as_bytes().len(), 12);
1398            assert_eq!(sid, SidBuf::default());
1399        }
1400    }
1401
1402    #[test]
1403    fn as_mut_ptr_lets_a_caller_fill_the_buffer() {
1404        // Size a buffer for S-1-5-32-544, then fill it through the raw pointer the
1405        // way a Windows API would write into a caller-supplied buffer
1406        let admins = nt_sid(&[32, 544]);
1407        let mut buf = SidBuf::with_capacity(admins.as_bytes().len());
1408
1409        unsafe {
1410            let dst = buf.as_mut_ptr() as *mut u8;
1411            std::ptr::copy_nonoverlapping(admins.as_bytes().as_ptr(), dst, admins.as_bytes().len());
1412        }
1413
1414        assert_eq!(buf, admins);
1415    }
1416
1417    #[test]
1418    fn value_traits_ignore_spare_buffer_capacity() {
1419        use std::collections::hash_map::DefaultHasher;
1420
1421        let oversized = SidBuf::with_capacity(200);
1422        let null_sid = SidBuf::default();
1423
1424        assert_eq!(oversized, null_sid);
1425        assert_eq!(oversized.as_bytes(), null_sid.as_bytes());
1426        assert_eq!(oversized.cmp(&null_sid), Ordering::Equal);
1427
1428        let mut oversized_hash = DefaultHasher::new();
1429        oversized.hash(&mut oversized_hash);
1430        let mut null_hash = DefaultHasher::new();
1431        null_sid.hash(&mut null_hash);
1432        assert_eq!(oversized_hash.finish(), null_hash.finish());
1433    }
1434
1435    #[test]
1436    fn owned_and_borrowed_views_agree() {
1437        let owned = nt_sid(&[18]);
1438        let via_deref: &Sid = &owned;
1439        let via_borrow: &Sid = owned.borrow();
1440        let via_as_ref: &Sid = owned.as_ref();
1441
1442        assert_eq!(via_deref, via_borrow);
1443        assert_eq!(via_deref, via_as_ref);
1444        assert_eq!(via_deref.to_owned(), owned);
1445        assert_eq!(*via_deref, owned);
1446        assert_eq!(owned, *via_deref);
1447        assert_eq!(via_deref, owned);
1448        assert_eq!(owned, via_deref);
1449
1450        let different = nt_sid(&[19]);
1451        assert_ne!(via_deref, different);
1452        assert_ne!(different, via_deref);
1453    }
1454
1455    #[test]
1456    fn display_and_debug_render_canonical_strings() {
1457        let cases = [
1458            (SidBuf::default(), "S-1-0-0"),
1459            (nt_sid(&[18]), "S-1-5-18"),
1460            (nt_sid(&[32, 544]), "S-1-5-32-544"),
1461            (
1462                SidBuf::new([0, 0, 0xFF, 0xFF, 0xFF, 0xFF], &[1]).unwrap(),
1463                "S-1-4294967295-1",
1464            ),
1465            (
1466                SidBuf::new([0, 1, 0, 0, 0, 0], &[1, 2]).unwrap(),
1467                "S-1-0x000100000000-1-2",
1468            ),
1469        ];
1470
1471        for (sid, expected) in cases {
1472            assert_eq!(sid.to_string(), expected);
1473            assert_eq!(format!("{sid:?}"), format!("{expected:?}"));
1474            assert_eq!(format!("{:?}", &*sid), format!("{expected:?}"));
1475        }
1476    }
1477
1478    #[test]
1479    fn from_str_parses_and_round_trips_display() {
1480        // Display and parse are inverse of each-other for our SID, so ensure that they round-trip
1481        for s in [
1482            "S-1-0-0",
1483            "S-1-5-18",
1484            "S-1-5-32-544",
1485            "S-1-0x000100000000-1-2",
1486        ] {
1487            let sid: SidBuf = s.parse().unwrap();
1488            assert_eq!(sid.to_string(), s);
1489        }
1490
1491        // Validate that both decimal and hex forms of the same SID are equal
1492        assert_eq!(
1493            "s-1-4294967296-1".parse::<SidBuf>().unwrap(),
1494            "S-1-0x000100000000-1".parse::<SidBuf>().unwrap(),
1495        );
1496
1497        // A SID can have zero sub-authorities
1498        assert_eq!(
1499            "S-1-5".parse::<SidBuf>().unwrap().sub_authorities(),
1500            &[] as &[u32]
1501        );
1502    }
1503
1504    #[test]
1505    fn from_str_rejects_malformed_input() {
1506        for s in [
1507            "",                                             // empty
1508            "X-1-5-18",                                     // wrong prefix
1509            "S-2-5-18",                                     // unsupported revision
1510            "S-1",                                          // missing authority
1511            "S-1-5-",                                       // trailing separator
1512            "S-1-+5-18",                                    // signed decimal authority
1513            "S-1-0x+5-18",                                  // signed hexadecimal authority
1514            "S-1-5-+18",                                    // signed sub-authority
1515            "S-1-5-4294967296",                             // sub-authority overflows u32
1516            "S-1-0x1000000000000-1",                        // authority overflows 48 bits
1517            "S-1-5-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16", // more than 15 sub-authorities
1518        ] {
1519            assert!(s.parse::<SidBuf>().is_err(), "parsing should reject {s:?}");
1520        }
1521    }
1522
1523    #[test]
1524    fn equality_and_ordering_follow_sid_fields_numerically() {
1525        let a = nt_sid(&[18]);
1526        let b = nt_sid(&[18]);
1527        let c = nt_sid(&[19]);
1528        assert_eq!(a, b);
1529        assert_ne!(a, c);
1530
1531        assert!(a < nt_sid(&[32, 544]));
1532        assert!(nt_sid(&[1]) < nt_sid(&[256]));
1533        assert!(nt_sid(&[21, 1]) < nt_sid(&[21, 1, 1]));
1534
1535        let lower_authority = SidBuf::new(4, &[u32::MAX, u32::MAX]).unwrap();
1536        let higher_authority = SidBuf::new(5, &[0]).unwrap();
1537        assert!(lower_authority < higher_authority);
1538    }
1539
1540    #[test]
1541    fn equal_prefix_ignores_only_the_last_sub_authority() {
1542        let first = nt_sid(&[21, 1, 2, 3, 1000]);
1543        let same_prefix = nt_sid(&[21, 1, 2, 3, 2000]);
1544        let different_prefix = nt_sid(&[21, 1, 2, 4, 1000]);
1545        let different_count = nt_sid(&[21, 1, 2, 3]);
1546        let different_authority = SidBuf::new([0, 0, 0, 0, 0, 4], &[21, 1, 2, 3, 2000]).unwrap();
1547
1548        assert!(first.equal_prefix(&same_prefix));
1549        assert!(!first.equal_prefix(&different_prefix));
1550        assert!(!first.equal_prefix(&different_count));
1551        assert!(!first.equal_prefix(&different_authority));
1552
1553        let no_sub_authorities = SidBuf::new(SECURITY_NT_AUTHORITY, &[]).unwrap();
1554        assert!(no_sub_authorities.equal_prefix(&no_sub_authorities));
1555    }
1556
1557    #[test]
1558    fn windows_domain_helpers_compare_and_extract_domains() {
1559        let first = nt_sid(&[21, 1, 2, 3, 1000]);
1560        let same_domain = nt_sid(&[21, 1, 2, 3, 2000]);
1561        let different_domain = nt_sid(&[21, 1, 2, 4, 1000]);
1562        let expected_domain = nt_sid(&[21, 1, 2, 3]);
1563
1564        assert!(first.equal_domain(&same_domain).unwrap());
1565        assert!(!first.equal_domain(&different_domain).unwrap());
1566        assert_eq!(first.account_domain_sid().unwrap(), expected_domain);
1567    }
1568
1569    #[test]
1570    fn well_known_sid_helper_classifies_sids() {
1571        let local_system = nt_sid(&[18]);
1572        assert!(local_system.is_well_known(WinLocalSystemSid));
1573        assert!(!local_system.is_well_known(WinWorldSid));
1574    }
1575
1576    #[test]
1577    fn borrowed_sid_looks_up_owned_key() {
1578        use std::collections::HashMap;
1579
1580        let mut map = HashMap::new();
1581        map.insert(nt_sid(&[18]), "LocalSystem");
1582
1583        let key = nt_sid(&[18]);
1584        let probe: &Sid = &key;
1585        assert_eq!(map.get(probe), Some(&"LocalSystem"));
1586    }
1587
1588    #[test]
1589    fn from_string_sid_supports_numeric_and_aliases() {
1590        let ba = nt_sid(&[32, 544]);
1591        assert_eq!(SidBuf::from_string_sid("BA").unwrap(), ba);
1592        assert_eq!(SidBuf::from_string_sid("S-1-5-32-544").unwrap(), ba);
1593    }
1594
1595    #[test]
1596    fn from_string_sid_fails_on_bad_input() {
1597        assert!(matches!(
1598            SidBuf::from_string_sid("").unwrap_err().kind,
1599            SidParseErrorKind::Windows(_)
1600        ));
1601        assert!(SidBuf::from_string_sid("not-a-sid").is_err());
1602        assert!(matches!(
1603            SidBuf::from_string_sid("BA\0").unwrap_err().kind,
1604            SidParseErrorKind::InteriorNul
1605        ));
1606    }
1607}