1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3use 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)]
96pub mod well_known;
102
103pub mod authority;
109
110#[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#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
138#[non_exhaustive]
139pub enum Error {
140 TooManySubAuthorities,
142 AuthorityOutOfRange,
144 InvalidSid,
146 Windows(u32),
148}
149
150impl Error {
151 #[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 fn from_last_win32_error() -> Self {
167 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
195pub type Result<T> = std::result::Result<T, Error>;
197
198pub trait AsSidPtr {
204 fn as_sid_ptr(&self) -> *const c_void;
206}
207
208pub trait AsWellKnownSidType {
213 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 pub trait Sealed {}
239}
240
241pub trait IntoAuthority: sealed::Sealed {
249 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)] 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
284impl_into_authority!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);
290
291#[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 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 unsafe { &*ptr }
320 }
321
322 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 unsafe { &mut *ptr }
332 }
333
334 #[inline]
336 fn logical_sub_count(&self) -> usize {
337 (self.sub_authority_count as usize).min(self.sub_authority.len())
338 }
339
340 #[inline]
343 fn words(&self) -> &[u32] {
344 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 #[inline]
361 #[must_use]
362 pub fn as_bytes(&self) -> &[u8] {
363 let words = self.words();
364 unsafe { std::slice::from_raw_parts(words.as_ptr() as *const u8, size_of_val(words)) }
366 }
367
368 #[cfg(test)]
371 fn buffer_bytes(&self) -> &[u8] {
372 let word_len = SID_HEADER_WORDS + self.sub_authority.len();
373 unsafe {
376 std::slice::from_raw_parts(self as *const Sid as *const u8, word_len * size_of::<u32>())
377 }
378 }
379
380 #[must_use]
385 pub fn as_ptr(&self) -> *const c_void {
386 self as *const Sid as *const c_void
387 }
388
389 pub unsafe fn from_psid<'a>(psid: impl AsSidPtr) -> Result<&'a Sid> {
402 let psid = psid.as_sid_ptr();
403
404 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 debug_assert!(
413 (psid as usize).is_multiple_of(align_of::<u32>()),
414 "SID pointer is not 4-byte aligned",
415 );
416
417 let word_len = SID_HEADER_WORDS + sub_count as usize;
419
420 let words = unsafe { std::slice::from_raw_parts(psid as *const u32, word_len) };
422 Ok(Sid::from_words_unchecked(words))
423 }
424
425 #[inline]
429 #[must_use]
430 pub fn revision(&self) -> u8 {
431 self.revision
432 }
433
434 #[inline]
436 #[must_use]
437 pub fn sub_authority_count(&self) -> u8 {
438 self.sub_authority_count
439 }
440
441 #[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 #[inline]
454 #[must_use]
455 pub fn authority_bytes(&self) -> [u8; 6] {
456 self.identifier_authority
457 }
458
459 #[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 #[inline]
471 #[must_use]
472 pub fn rid(&self) -> Option<u32> {
473 self.sub_authorities().last().copied()
474 }
475
476 #[inline]
478 #[must_use]
479 pub fn sub_authorities(&self) -> &[u32] {
480 &self.sub_authority[..self.logical_sub_count()]
481 }
482
483 #[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 #[inline]
514 pub fn equal_domain(&self, other: &Sid) -> Result<bool> {
515 let mut equal = 0;
516 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 #[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 #[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 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 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
641pub 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#[derive(Clone, Debug, Eq, PartialEq)]
663pub struct SidParseError {
664 kind: SidParseErrorKind,
665}
666
667#[derive(Clone, Debug, Eq, PartialEq)]
671enum SidParseErrorKind {
672 Invalid,
674 InteriorNul,
677 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
715impl FromStr for SidBuf {
744 type Err = SidParseError;
745
746 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
753 let mut parts = s.split('-');
754
755 match parts.next() {
757 Some(p) if p.eq_ignore_ascii_case("S") => {}
758 _ => return Err(SidParseError::invalid()),
759 }
760
761 if parts.next() != Some("1") {
763 return Err(SidParseError::invalid());
764 }
765
766 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 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 SidBuf::new(authority, &sub_authorities).map_err(|_| SidParseError::invalid())
797 }
798}
799
800impl SidBuf {
801 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 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 SidBuf {
817 sid: unsafe { Box::from_raw(ptr) },
818 }
819 }
820
821 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 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 #[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 #[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 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 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 pub unsafe fn from_psid(psid: impl AsSidPtr) -> Result<Self> {
1082 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 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, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, ]
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 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 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 assert_eq!(
1493 "s-1-4294967296-1".parse::<SidBuf>().unwrap(),
1494 "S-1-0x000100000000-1".parse::<SidBuf>().unwrap(),
1495 );
1496
1497 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 "", "X-1-5-18", "S-2-5-18", "S-1", "S-1-5-", "S-1-+5-18", "S-1-0x+5-18", "S-1-5-+18", "S-1-5-4294967296", "S-1-0x1000000000000-1", "S-1-5-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16", ] {
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}