1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3use std::borrow::Borrow;
94use std::cmp::Ordering;
95use std::ffi::c_void;
96use std::fmt::{Debug, Display};
97use std::hash::{Hash, Hasher};
98use std::ops::Deref;
99use std::str::FromStr;
100use windows_core::{Error, HRESULT, Result};
101
102#[allow(
103 non_snake_case,
104 non_upper_case_globals,
105 non_camel_case_types,
106 dead_code,
107 clippy::all
108)]
109mod bindings {
110 include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
111}
112
113#[allow(
114 non_snake_case,
115 non_upper_case_globals,
116 non_camel_case_types,
117 dead_code,
118 clippy::all
119)]
120pub mod well_known {
126 include!(concat!(env!("OUT_DIR"), "/well_known.rs"));
127}
128
129#[doc(no_inline)]
130pub use well_known::*;
131
132#[cfg(feature = "windows-full")]
133use windows::Win32::Security::{PSID, WELL_KNOWN_SID_TYPE as WINDOWS_WELL_KNOWN_SID_TYPE};
134
135const SID_REVISION: u8 = 1;
136const SID_MAX_SUB_AUTHORITIES: u8 = 15;
137const SID_HEADER_WORDS: usize = 2;
138
139fn invalid_sid_err() -> Error {
141 Error::from_hresult(HRESULT::from_win32(0x0539))
142}
143
144pub trait AsSidPtr {
150 fn as_sid_ptr(&self) -> *const c_void;
152}
153
154pub trait AsWellKnownSidType {
160 fn as_well_known_sid_type(&self) -> WELL_KNOWN_SID_TYPE;
162}
163
164impl AsWellKnownSidType for WELL_KNOWN_SID_TYPE {
165 fn as_well_known_sid_type(&self) -> WELL_KNOWN_SID_TYPE {
166 *self
167 }
168}
169
170#[cfg(feature = "windows-full")]
171impl AsWellKnownSidType for WINDOWS_WELL_KNOWN_SID_TYPE {
172 fn as_well_known_sid_type(&self) -> WELL_KNOWN_SID_TYPE {
173 self.0
174 }
175}
176
177#[cfg(feature = "windows-full")]
178impl AsSidPtr for PSID {
179 fn as_sid_ptr(&self) -> *const c_void {
180 self.0
181 }
182}
183
184impl AsSidPtr for *const c_void {
185 fn as_sid_ptr(&self) -> *const c_void {
186 *self
187 }
188}
189
190impl AsSidPtr for *mut c_void {
191 fn as_sid_ptr(&self) -> *const c_void {
192 *self
193 }
194}
195
196#[repr(C)]
205pub struct Sid {
206 revision: u8,
207 sub_authority_count: u8,
208 identifier_authority: [u8; 6],
209 sub_authority: [u32],
210}
211
212impl Sid {
213 fn from_words_unchecked(words: &[u32]) -> &Sid {
217 debug_assert!(
218 words.len() >= SID_HEADER_WORDS,
219 "a SID has at least the two header words"
220 );
221 let sub_count = words.len() - SID_HEADER_WORDS;
222 let ptr = std::ptr::slice_from_raw_parts(words.as_ptr(), sub_count) as *const Sid;
223 unsafe { &*ptr }
225 }
226
227 fn from_words_unchecked_mut(words: &mut [u32]) -> &mut Sid {
229 debug_assert!(
230 words.len() >= SID_HEADER_WORDS,
231 "a SID has at least the two header words"
232 );
233 let sub_count = words.len() - SID_HEADER_WORDS;
234 let ptr = std::ptr::slice_from_raw_parts_mut(words.as_mut_ptr(), sub_count) as *mut Sid;
235 unsafe { &mut *ptr }
237 }
238
239 #[inline]
242 fn logical_sub_count(&self) -> usize {
243 (self.sub_authority_count as usize).min(self.sub_authority.len())
244 }
245
246 #[inline]
249 fn words(&self) -> &[u32] {
250 unsafe {
254 std::slice::from_raw_parts(
255 self as *const Sid as *const u32,
256 SID_HEADER_WORDS + self.logical_sub_count(),
257 )
258 }
259 }
260
261 #[inline]
267 pub fn as_bytes(&self) -> &[u8] {
268 let words = self.words();
269 unsafe { std::slice::from_raw_parts(words.as_ptr() as *const u8, size_of_val(words)) }
271 }
272
273 #[cfg(test)]
276 fn buffer_bytes(&self) -> &[u8] {
277 let word_len = SID_HEADER_WORDS + self.sub_authority.len();
278 unsafe {
281 std::slice::from_raw_parts(self as *const Sid as *const u8, word_len * size_of::<u32>())
282 }
283 }
284
285 #[cfg(feature = "windows-full")]
293 #[inline]
294 pub unsafe fn as_psid(&self) -> PSID {
295 PSID(self as *const Sid as *mut _)
296 }
297
298 pub fn as_ptr(&self) -> *const c_void {
303 self as *const Sid as *const c_void
304 }
305
306 pub unsafe fn from_psid<'a>(psid: impl AsSidPtr) -> Result<&'a Sid> {
322 let psid = psid.as_sid_ptr();
323
324 let p = psid as *const u8;
326 let (revision, sub_count) = unsafe { (*p, *p.add(1)) };
327 if revision != SID_REVISION || sub_count > SID_MAX_SUB_AUTHORITIES {
328 return Err(invalid_sid_err());
329 }
330
331 debug_assert!(
333 (psid as usize).is_multiple_of(align_of::<u32>()),
334 "SID pointer is not 4-byte aligned",
335 );
336
337 let word_len = SID_HEADER_WORDS + sub_count as usize;
339
340 let words = unsafe { std::slice::from_raw_parts(psid as *const u32, word_len) };
342 Ok(Sid::from_words_unchecked(words))
343 }
344
345 #[inline]
349 pub fn revision(&self) -> u8 {
350 self.revision
351 }
352
353 #[inline]
355 pub fn sub_authority_count(&self) -> u8 {
356 self.sub_authority_count
357 }
358
359 #[inline]
361 pub fn authority(&self) -> u64 {
362 let [a0, a1, a2, a3, a4, a5] = self.identifier_authority;
363 u64::from_be_bytes([0, 0, a0, a1, a2, a3, a4, a5])
364 }
365
366 #[inline]
368 pub fn sub_authority(&self, idx: u8) -> Option<u32> {
369 self.sub_authorities().get(idx as usize).copied()
370 }
371
372 #[inline]
374 pub fn sub_authorities(&self) -> &[u32] {
375 &self.sub_authority[..self.logical_sub_count()]
376 }
377
378 #[inline]
383 pub fn equal_prefix(&self, other: &Sid) -> bool {
384 self.revision == other.revision
385 && self.identifier_authority == other.identifier_authority
386 && self.sub_authority_count == other.sub_authority_count
387 && match (
388 self.sub_authorities().split_last(),
389 other.sub_authorities().split_last(),
390 ) {
391 (Some((_, prefix1)), Some((_, prefix2))) => prefix1 == prefix2,
392 (None, None) => true,
393 _ => false,
394 }
395 }
396
397 #[inline]
407 pub fn equal_domain(&self, other: &Sid) -> Result<bool> {
408 let mut equal = 0;
409 if unsafe {
411 bindings::EqualDomainSid(
412 self.as_ptr().cast_mut(),
413 other.as_ptr().cast_mut(),
414 &mut equal,
415 )
416 } == 0
417 {
418 return Err(Error::from_thread());
419 }
420 Ok(equal != 0)
421 }
422
423 #[inline]
431 pub fn account_domain_sid(&self) -> Result<SidBuf> {
432 unsafe {
433 let mut len = 0u32;
434 if bindings::GetWindowsAccountDomainSid(
435 self.as_ptr().cast_mut(),
436 std::ptr::null_mut(),
437 &mut len,
438 ) == 0
439 {
440 let error = Error::from_thread();
441 if error.code() != HRESULT::from_win32(bindings::ERROR_INSUFFICIENT_BUFFER) {
442 return Err(error);
443 }
444 }
445
446 let mut domain_sid = SidBuf::with_capacity(len as usize);
447 if bindings::GetWindowsAccountDomainSid(
448 self.as_ptr().cast_mut(),
449 domain_sid.as_mut_ptr(),
450 &mut len,
451 ) == 0
452 {
453 return Err(Error::from_thread());
454 }
455 Ok(domain_sid)
456 }
457 }
458
459 #[inline]
463 pub fn is_well_known(&self, well_known_type: impl AsWellKnownSidType) -> bool {
464 unsafe {
466 bindings::IsWellKnownSid(
467 self.as_ptr().cast_mut(),
468 well_known_type.as_well_known_sid_type(),
469 ) != 0
470 }
471 }
472}
473
474impl ToOwned for Sid {
475 type Owned = SidBuf;
476 fn to_owned(&self) -> SidBuf {
477 SidBuf::from_boxed_words(self.words().to_vec().into_boxed_slice())
478 }
479}
480
481impl Eq for Sid {}
482
483impl PartialEq for Sid {
484 #[inline]
485 fn eq(&self, other: &Self) -> bool {
486 self.as_bytes() == other.as_bytes()
487 }
488}
489
490impl Hash for Sid {
491 fn hash<H: Hasher>(&self, state: &mut H) {
492 state.write(self.as_bytes());
493 }
494}
495
496impl PartialOrd for Sid {
497 #[inline]
498 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
499 Some(self.cmp(other))
500 }
501}
502
503impl Ord for Sid {
504 #[inline]
505 fn cmp(&self, other: &Self) -> Ordering {
506 self.as_bytes().cmp(other.as_bytes())
507 }
508}
509
510impl Display for Sid {
511 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512 f.write_str("S-1-")?;
513 let authority = self.authority();
514 if authority <= 0xFFFFFFFF {
515 write!(f, "{}", authority)?;
516 } else {
517 write!(f, "0x{:012X}", authority)?;
519 }
520
521 for sa in self.sub_authorities() {
522 write!(f, "-{}", sa)?;
523 }
524
525 Ok(())
526 }
527}
528
529impl Debug for Sid {
530 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
531 write!(f, "\"{}\"", self)
532 }
533}
534
535pub struct SidBuf {
554 sid: Box<Sid>,
555}
556
557impl Clone for SidBuf {
558 fn clone(&self) -> Self {
559 (**self).to_owned()
560 }
561}
562
563#[derive(Debug)]
564pub struct ParseError;
568
569impl std::error::Error for ParseError {}
570impl Display for ParseError {
571 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
572 write!(f, "invalid SID string")
573 }
574}
575
576impl FromStr for SidBuf {
577 type Err = ParseError;
578
579 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
580 let mut parts = s.split('-');
581
582 match parts.next() {
584 Some(p) if p.eq_ignore_ascii_case("S") => {}
585 _ => return Err(ParseError),
586 }
587
588 if parts.next() != Some("1") {
590 return Err(ParseError);
591 }
592
593 let authority_str = parts.next().ok_or(ParseError)?;
595 let authority = match authority_str
596 .strip_prefix("0x")
597 .or_else(|| authority_str.strip_prefix("0X"))
598 {
599 Some(hex) => u64::from_str_radix(hex, 16).map_err(|_| ParseError)?,
600 None => authority_str.parse::<u64>().map_err(|_| ParseError)?,
601 };
602 if authority > 0xFFFF_FFFF_FFFF {
603 return Err(ParseError);
604 }
605 let identifier_authority: [u8; 6] = authority.to_be_bytes()[2..].try_into().unwrap();
606
607 let sub_authorities = parts
609 .map(|p| p.parse::<u32>())
610 .collect::<std::result::Result<Vec<u32>, _>>()
611 .map_err(|_| ParseError)?;
612
613 SidBuf::new(identifier_authority, &sub_authorities).map_err(|_| ParseError)
614 }
615}
616
617impl SidBuf {
618 fn from_boxed_words(words: Box<[u32]>) -> SidBuf {
622 debug_assert!(
623 words.len() >= SID_HEADER_WORDS,
624 "a SID has at least the two header words"
625 );
626 let sub_count = words.len() - SID_HEADER_WORDS;
627 let data = Box::into_raw(words).cast::<u32>();
631 let ptr = std::ptr::slice_from_raw_parts_mut(data, sub_count) as *mut Sid;
632 SidBuf {
634 sid: unsafe { Box::from_raw(ptr) },
635 }
636 }
637
638 pub fn new(identifier_authority: [u8; 6], sub_authorities: &[u32]) -> Result<Self> {
652 let count = sub_authorities.len();
653 if count > SID_MAX_SUB_AUTHORITIES as usize {
654 return Err(invalid_sid_err());
655 }
656
657 let mut words = vec![0u32; SID_HEADER_WORDS + count].into_boxed_slice();
658 let sid = Sid::from_words_unchecked_mut(&mut words);
659 sid.revision = SID_REVISION;
660 sid.sub_authority_count = count as u8;
661 sid.identifier_authority = identifier_authority;
662 sid.sub_authority.copy_from_slice(sub_authorities);
663
664 Ok(Self::from_boxed_words(words))
665 }
666
667 pub fn with_capacity(len: usize) -> SidBuf {
676 let word_len = len.div_ceil(size_of::<u32>()).max(SID_HEADER_WORDS + 1);
677
678 let mut words = vec![0u32; word_len].into_boxed_slice();
679 let sid = Sid::from_words_unchecked_mut(&mut words);
680 sid.revision = SID_REVISION;
681 sid.sub_authority_count = 1;
682
683 SidBuf::from_boxed_words(words)
684 }
685
686 pub unsafe fn as_mut_ptr(&mut self) -> *mut c_void {
753 let sid: &mut Sid = &mut self.sid;
754 sid as *mut Sid as *mut c_void
755 }
756
757 pub fn well_known(
776 well_known_type: impl AsWellKnownSidType,
777 domain_sid: Option<&Sid>,
778 ) -> Result<SidBuf> {
779 unsafe {
780 let well_known_type = well_known_type.as_well_known_sid_type();
781 let domain_psid = domain_sid
782 .map(|sid| sid.as_ptr().cast_mut())
783 .unwrap_or(std::ptr::null_mut());
784 let mut len = 0u32;
785 if bindings::CreateWellKnownSid(
786 well_known_type,
787 domain_psid,
788 std::ptr::null_mut(),
789 &mut len,
790 ) == 0
791 {
792 let error = Error::from_thread();
793 if error.code() != HRESULT::from_win32(bindings::ERROR_INSUFFICIENT_BUFFER) {
794 return Err(error);
795 }
796 }
797
798 let word_len = (len as usize).div_ceil(size_of::<u32>());
799 let mut words: Box<[u32]> = vec![0u32; word_len].into_boxed_slice();
800 if bindings::CreateWellKnownSid(
801 well_known_type,
802 domain_psid,
803 words.as_mut_ptr().cast(),
804 &mut len,
805 ) == 0
806 {
807 return Err(Error::from_thread());
808 }
809
810 Ok(SidBuf::from_boxed_words(words))
811 }
812 }
813
814 pub fn from_cstr_with_alias(s: &std::ffi::CStr) -> Result<SidBuf> {
834 unsafe {
835 let mut sid = std::ptr::null_mut();
836 if bindings::ConvertStringSidToSidA(s.as_ptr().cast(), &mut sid) == 0 {
837 return Err(Error::from_thread());
838 }
839 let res = SidBuf::from_psid(sid);
840 bindings::LocalFree(sid);
841 res
842 }
843 }
844
845 pub unsafe fn from_psid(psid: impl AsSidPtr) -> Result<Self> {
869 let src = unsafe { Sid::from_psid(psid) }?;
871 Ok(src.to_owned())
872 }
873}
874
875impl Deref for SidBuf {
876 type Target = Sid;
877 #[inline]
878 fn deref(&self) -> &Sid {
879 &self.sid
880 }
881}
882
883impl Borrow<Sid> for SidBuf {
884 #[inline]
885 fn borrow(&self) -> &Sid {
886 self
887 }
888}
889
890impl AsRef<Sid> for SidBuf {
891 #[inline]
892 fn as_ref(&self) -> &Sid {
893 self
894 }
895}
896
897impl Eq for SidBuf {}
898
899impl PartialEq for SidBuf {
900 #[inline]
901 fn eq(&self, other: &Self) -> bool {
902 (**self).eq(&**other)
903 }
904}
905
906impl Hash for SidBuf {
907 fn hash<H: Hasher>(&self, state: &mut H) {
908 (**self).hash(state);
909 }
910}
911
912impl PartialOrd for SidBuf {
913 #[inline]
914 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
915 Some(self.cmp(other))
916 }
917}
918
919impl Ord for SidBuf {
920 #[inline]
921 fn cmp(&self, other: &Self) -> Ordering {
922 (**self).cmp(&**other)
923 }
924}
925
926impl Display for SidBuf {
927 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928 Display::fmt(&**self, f)
929 }
930}
931
932impl Debug for SidBuf {
933 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
934 Debug::fmt(&**self, f)
935 }
936}
937
938impl Default for SidBuf {
939 fn default() -> Self {
940 SidBuf::new([0, 0, 0, 0, 0, 0], &[0]).unwrap()
941 }
942}
943
944impl PartialEq<SidBuf> for Sid {
945 #[inline]
946 fn eq(&self, other: &SidBuf) -> bool {
947 self == &**other
948 }
949}
950
951impl PartialEq<Sid> for SidBuf {
952 #[inline]
953 fn eq(&self, other: &Sid) -> bool {
954 &**self == other
955 }
956}
957
958#[cfg(test)]
959mod tests {
960 use super::*;
961
962 const NT_AUTHORITY: [u8; 6] = [0, 0, 0, 0, 0, 5];
963
964 fn nt_sid(sub_authorities: &[u32]) -> SidBuf {
965 SidBuf::new(NT_AUTHORITY, sub_authorities).unwrap()
966 }
967
968 #[test]
969 fn from_psid_rejects_invalid_headers() {
970 for header in [[0, 0], [SID_REVISION, SID_MAX_SUB_AUTHORITIES + 1]] {
971 let words = [u32::from_ne_bytes([header[0], header[1], 0, 0]), 0];
972 let psid = words.as_ptr() as *const c_void;
973
974 assert!(unsafe { Sid::from_psid(psid) }.is_err());
975 assert!(unsafe { SidBuf::from_psid(psid) }.is_err());
976 }
977 }
978
979 #[test]
980 fn new_enforces_the_sub_authority_limit() {
981 assert_eq!(
982 SidBuf::new([0; 6], &[7; 15]).unwrap().sub_authority_count(),
983 15
984 );
985 assert!(SidBuf::new([0; 6], &[0; 16]).is_err());
986 }
987
988 #[test]
989 fn well_known_sids_construct() {
990 for (kind, expected) in [
991 (WinNullSid, "S-1-0-0"),
992 (WinLocalSystemSid, "S-1-5-18"),
993 (WinBuiltinAdministratorsSid, "S-1-5-32-544"),
994 ] {
995 assert_eq!(
996 SidBuf::well_known(kind, None).unwrap().to_string(),
997 expected
998 );
999 }
1000 }
1001
1002 #[test]
1003 fn new_builds_the_expected_sid() {
1004 let sid = nt_sid(&[32, 544]);
1005
1006 assert_eq!(
1007 sid.as_bytes(),
1008 &[
1009 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, ]
1015 );
1016 assert_eq!(sid.revision(), SID_REVISION);
1017 assert_eq!(sid.sub_authority_count(), 2);
1018 assert_eq!(sid.authority(), 5);
1019 assert_eq!(sid.sub_authority(0), Some(32));
1020 assert_eq!(sid.sub_authority(1), Some(544));
1021 assert_eq!(sid.sub_authority(2), None);
1022 assert_eq!(sid.sub_authorities(), [32, 544]);
1023 }
1024
1025 #[test]
1026 fn from_psid_borrows_or_copies_as_requested() {
1027 let copied = {
1028 let src = nt_sid(&[18]);
1029 let borrowed = unsafe { Sid::from_psid(src.as_ptr()) }.expect("valid SID");
1030 let copied = unsafe { SidBuf::from_psid(src.as_ptr()) }.expect("valid SID");
1031
1032 assert_eq!(borrowed, &*src);
1033 assert_eq!(copied, src);
1034 copied
1035 };
1036
1037 assert_eq!(copied.to_string(), "S-1-5-18");
1038 }
1039
1040 #[cfg(feature = "windows-full")]
1041 #[test]
1042 fn windows_psid_interoperates_when_enabled() {
1043 let source = nt_sid(&[18]);
1044 let psid = unsafe { source.as_psid() };
1045
1046 assert_eq!(unsafe { Sid::from_psid(psid) }.unwrap(), &*source);
1047 }
1048
1049 #[cfg(feature = "windows-full")]
1050 #[test]
1051 fn windows_well_known_sid_types_interoperate_when_enabled() {
1052 use windows::Win32::Security::WinLocalSystemSid as WindowsWinLocalSystemSid;
1053
1054 let local_system = SidBuf::well_known(WindowsWinLocalSystemSid, None).unwrap();
1055
1056 assert!(local_system.is_well_known(WindowsWinLocalSystemSid));
1057 }
1058
1059 #[test]
1060 fn with_capacity_separates_logical_length_from_buffer_length() {
1061 for (requested, allocated) in [(0, 12), (12, 12), (13, 16), (200, 200)] {
1062 let sid = SidBuf::with_capacity(requested);
1063
1064 assert_eq!(sid.buffer_bytes().len(), allocated);
1065 assert_eq!(sid.as_bytes().len(), 12);
1066 assert_eq!(sid, SidBuf::default());
1067 }
1068 }
1069
1070 #[test]
1071 fn as_mut_ptr_lets_a_caller_fill_the_buffer() {
1072 let admins = nt_sid(&[32, 544]);
1075 let mut buf = SidBuf::with_capacity(admins.as_bytes().len());
1076
1077 unsafe {
1078 let dst = buf.as_mut_ptr() as *mut u8;
1079 std::ptr::copy_nonoverlapping(admins.as_bytes().as_ptr(), dst, admins.as_bytes().len());
1080 }
1081
1082 assert_eq!(buf, admins);
1083 }
1084
1085 #[test]
1086 fn value_traits_ignore_spare_buffer_capacity() {
1087 use std::collections::hash_map::DefaultHasher;
1088
1089 let oversized = SidBuf::with_capacity(200);
1090 let null_sid = SidBuf::default();
1091
1092 assert_eq!(oversized, null_sid);
1093 assert_eq!(oversized.as_bytes(), null_sid.as_bytes());
1094 assert_eq!(oversized.cmp(&null_sid), Ordering::Equal);
1095
1096 let mut oversized_hash = DefaultHasher::new();
1097 oversized.hash(&mut oversized_hash);
1098 let mut null_hash = DefaultHasher::new();
1099 null_sid.hash(&mut null_hash);
1100 assert_eq!(oversized_hash.finish(), null_hash.finish());
1101 }
1102
1103 #[test]
1104 fn owned_and_borrowed_views_agree() {
1105 let owned = nt_sid(&[18]);
1106 let via_deref: &Sid = &owned;
1107 let via_borrow: &Sid = owned.borrow();
1108 let via_as_ref: &Sid = owned.as_ref();
1109
1110 assert_eq!(via_deref, via_borrow);
1111 assert_eq!(via_deref, via_as_ref);
1112 assert_eq!(via_deref.to_owned(), owned);
1113 assert_eq!(*via_deref, owned);
1114 assert_eq!(owned, *via_deref);
1115 }
1116
1117 #[test]
1118 fn display_and_debug_render_canonical_strings() {
1119 let cases = [
1120 (SidBuf::default(), "S-1-0-0"),
1121 (nt_sid(&[18]), "S-1-5-18"),
1122 (nt_sid(&[32, 544]), "S-1-5-32-544"),
1123 (
1124 SidBuf::new([0, 0, 0xFF, 0xFF, 0xFF, 0xFF], &[1]).unwrap(),
1125 "S-1-4294967295-1",
1126 ),
1127 (
1128 SidBuf::new([0, 1, 0, 0, 0, 0], &[1, 2]).unwrap(),
1129 "S-1-0x000100000000-1-2",
1130 ),
1131 ];
1132
1133 for (sid, expected) in cases {
1134 assert_eq!(sid.to_string(), expected);
1135 assert_eq!(format!("{sid:?}"), format!("{expected:?}"));
1136 assert_eq!(format!("{:?}", &*sid), format!("{expected:?}"));
1137 }
1138 }
1139
1140 #[test]
1141 fn from_str_parses_and_round_trips_display() {
1142 for s in [
1144 "S-1-0-0",
1145 "S-1-5-18",
1146 "S-1-5-32-544",
1147 "S-1-0x000100000000-1-2",
1148 ] {
1149 let sid: SidBuf = s.parse().unwrap();
1150 assert_eq!(sid.to_string(), s);
1151 }
1152
1153 assert_eq!(
1155 "s-1-4294967296-1".parse::<SidBuf>().unwrap(),
1156 "S-1-0x000100000000-1".parse::<SidBuf>().unwrap(),
1157 );
1158
1159 assert_eq!(
1161 "S-1-5".parse::<SidBuf>().unwrap().sub_authorities(),
1162 &[] as &[u32]
1163 );
1164 }
1165
1166 #[test]
1167 fn from_str_rejects_malformed_input() {
1168 for s in [
1169 "", "X-1-5-18", "S-2-5-18", "S-1", "S-1-5-", "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", ] {
1178 assert!(s.parse::<SidBuf>().is_err(), "parsing should reject {s:?}");
1179 }
1180 }
1181
1182 #[test]
1183 fn equality_and_ordering_follow_sid_bytes() {
1184 let a = nt_sid(&[18]);
1185 let b = nt_sid(&[18]);
1186 let c = nt_sid(&[19]);
1187 assert_eq!(a, b);
1188 assert_ne!(a, c);
1189
1190 assert!(a < nt_sid(&[32, 544]));
1191 }
1192
1193 #[test]
1194 fn equal_prefix_ignores_only_the_last_sub_authority() {
1195 let first = nt_sid(&[21, 1, 2, 3, 1000]);
1196 let same_prefix = nt_sid(&[21, 1, 2, 3, 2000]);
1197 let different_prefix = nt_sid(&[21, 1, 2, 4, 1000]);
1198 let different_count = nt_sid(&[21, 1, 2, 3]);
1199 let different_authority = SidBuf::new([0, 0, 0, 0, 0, 4], &[21, 1, 2, 3, 2000]).unwrap();
1200
1201 assert!(first.equal_prefix(&same_prefix));
1202 assert!(!first.equal_prefix(&different_prefix));
1203 assert!(!first.equal_prefix(&different_count));
1204 assert!(!first.equal_prefix(&different_authority));
1205
1206 let no_sub_authorities = SidBuf::new(NT_AUTHORITY, &[]).unwrap();
1207 assert!(no_sub_authorities.equal_prefix(&no_sub_authorities));
1208 }
1209
1210 #[test]
1211 fn windows_domain_helpers_compare_and_extract_domains() {
1212 let first = nt_sid(&[21, 1, 2, 3, 1000]);
1213 let same_domain = nt_sid(&[21, 1, 2, 3, 2000]);
1214 let different_domain = nt_sid(&[21, 1, 2, 4, 1000]);
1215 let expected_domain = nt_sid(&[21, 1, 2, 3]);
1216
1217 assert!(first.equal_domain(&same_domain).unwrap());
1218 assert!(!first.equal_domain(&different_domain).unwrap());
1219 assert_eq!(first.account_domain_sid().unwrap(), expected_domain);
1220 }
1221
1222 #[test]
1223 fn well_known_sid_helper_classifies_sids() {
1224 let local_system = nt_sid(&[18]);
1225 assert!(local_system.is_well_known(WinLocalSystemSid));
1226 assert!(!local_system.is_well_known(WinWorldSid));
1227 }
1228
1229 #[test]
1230 fn borrowed_sid_looks_up_owned_key() {
1231 use std::collections::HashMap;
1232
1233 let mut map = HashMap::new();
1234 map.insert(nt_sid(&[18]), "LocalSystem");
1235
1236 let key = nt_sid(&[18]);
1237 let probe: &Sid = &key;
1238 assert_eq!(map.get(probe), Some(&"LocalSystem"));
1239 }
1240
1241 #[test]
1242 fn from_cstr_supports_numeric_and_aliases() {
1243 let ba = nt_sid(&[32, 544]);
1244 assert_eq!(SidBuf::from_cstr_with_alias(c"BA").unwrap(), ba);
1245 assert_eq!(SidBuf::from_cstr_with_alias(c"S-1-5-32-544").unwrap(), ba);
1246 }
1247
1248 #[test]
1249 fn from_cstr_fails_on_bad_input() {
1250 assert!(SidBuf::from_cstr_with_alias(c"").is_err());
1251 assert!(SidBuf::from_cstr_with_alias(c"not-a-sid").is_err());
1252 }
1253}