#![cfg_attr(docsrs, feature(doc_cfg))]
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::ffi::c_void;
use std::fmt::{Debug, Display};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::str::FromStr;
#[allow(non_snake_case, non_camel_case_types, dead_code, clippy::all)]
mod bindings;
#[allow(non_upper_case_globals)]
pub mod well_known;
pub mod authority;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct WellKnownSidType(i32);
const SID_REVISION: u8 = 1;
const SID_MAX_SUB_AUTHORITIES: u8 = 15;
const SID_HEADER_WORDS: usize = 2;
const ERROR_INVALID_SID: u32 = 0x0539;
const MAX_AUTHORITY: u64 = 0xFFFF_FFFF_FFFF;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Error {
TooManySubAuthorities,
AuthorityOutOfRange,
InvalidSid,
Windows(u32),
}
impl Error {
#[must_use]
pub const fn win32_code(&self) -> u32 {
match self {
Error::TooManySubAuthorities | Error::AuthorityOutOfRange | Error::InvalidSid => {
ERROR_INVALID_SID
}
Error::Windows(code) => *code,
}
}
fn from_last_win32_error() -> Self {
Error::Windows(unsafe { bindings::GetLastError() })
}
}
impl std::error::Error for Error {}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::TooManySubAuthorities => write!(f, "a SID holds at most 15 sub-authorities"),
Error::AuthorityOutOfRange => {
write!(f, "the identifier authority does not fit in 48 bits")
}
Error::InvalidSid => write!(f, "not a valid SID"),
Error::Windows(code) => {
Display::fmt(&std::io::Error::from_raw_os_error(*code as i32), f)
}
}
}
}
impl From<Error> for std::io::Error {
fn from(error: Error) -> Self {
std::io::Error::from_raw_os_error(error.win32_code() as i32)
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub trait AsSidPtr {
fn as_sid_ptr(&self) -> *const c_void;
}
pub trait AsWellKnownSidType {
fn as_well_known_sid_type(&self) -> WellKnownSidType;
}
impl AsWellKnownSidType for WellKnownSidType {
fn as_well_known_sid_type(&self) -> WellKnownSidType {
*self
}
}
impl AsSidPtr for *const c_void {
fn as_sid_ptr(&self) -> *const c_void {
*self
}
}
impl AsSidPtr for *mut c_void {
fn as_sid_ptr(&self) -> *const c_void {
*self
}
}
mod sealed {
pub trait Sealed {}
}
pub trait IntoAuthority: sealed::Sealed {
fn try_into_authority(self) -> Result<[u8; 6]>;
}
impl sealed::Sealed for [u8; 6] {}
impl IntoAuthority for [u8; 6] {
fn try_into_authority(self) -> Result<[u8; 6]> {
Ok(self)
}
}
macro_rules! impl_into_authority {
($($t:ty)*) => {$(
impl sealed::Sealed for $t {}
impl IntoAuthority for $t {
#[allow(clippy::useless_conversion)] fn try_into_authority(self) -> Result<[u8; 6]> {
match u64::try_from(self) {
Ok(value) if value <= MAX_AUTHORITY => {
Ok(value.to_be_bytes()[2..].try_into().unwrap())
}
_ => Err(Error::AuthorityOutOfRange),
}
}
}
)*};
}
impl_into_authority!(u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize);
#[repr(C)]
pub struct Sid {
revision: u8,
sub_authority_count: u8,
identifier_authority: [u8; 6],
sub_authority: [u32],
}
impl Sid {
fn from_words_unchecked(words: &[u32]) -> &Sid {
debug_assert!(
words.len() >= SID_HEADER_WORDS,
"a SID has at least the two header words"
);
let sub_count = words.len() - SID_HEADER_WORDS;
let ptr = std::ptr::slice_from_raw_parts(words.as_ptr(), sub_count) as *const Sid;
unsafe { &*ptr }
}
fn from_words_unchecked_mut(words: &mut [u32]) -> &mut Sid {
debug_assert!(
words.len() >= SID_HEADER_WORDS,
"a SID has at least the two header words"
);
let sub_count = words.len() - SID_HEADER_WORDS;
let ptr = std::ptr::slice_from_raw_parts_mut(words.as_mut_ptr(), sub_count) as *mut Sid;
unsafe { &mut *ptr }
}
#[inline]
fn logical_sub_count(&self) -> usize {
(self.sub_authority_count as usize).min(self.sub_authority.len())
}
#[inline]
fn words(&self) -> &[u32] {
unsafe {
std::slice::from_raw_parts(
self as *const Sid as *const u32,
SID_HEADER_WORDS + self.logical_sub_count(),
)
}
}
#[inline]
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
let words = self.words();
unsafe { std::slice::from_raw_parts(words.as_ptr() as *const u8, size_of_val(words)) }
}
#[cfg(test)]
fn buffer_bytes(&self) -> &[u8] {
let word_len = SID_HEADER_WORDS + self.sub_authority.len();
unsafe {
std::slice::from_raw_parts(self as *const Sid as *const u8, word_len * size_of::<u32>())
}
}
#[must_use]
pub fn as_ptr(&self) -> *const c_void {
self as *const Sid as *const c_void
}
pub unsafe fn from_psid<'a>(psid: impl AsSidPtr) -> Result<&'a Sid> {
let psid = psid.as_sid_ptr();
let p = psid as *const u8;
let (revision, sub_count) = unsafe { (*p, *p.add(1)) };
if revision != SID_REVISION || sub_count > SID_MAX_SUB_AUTHORITIES {
return Err(Error::InvalidSid);
}
debug_assert!(
(psid as usize).is_multiple_of(align_of::<u32>()),
"SID pointer is not 4-byte aligned",
);
let word_len = SID_HEADER_WORDS + sub_count as usize;
let words = unsafe { std::slice::from_raw_parts(psid as *const u32, word_len) };
Ok(Sid::from_words_unchecked(words))
}
#[inline]
#[must_use]
pub fn revision(&self) -> u8 {
self.revision
}
#[inline]
#[must_use]
pub fn sub_authority_count(&self) -> u8 {
self.sub_authority_count
}
#[inline]
#[must_use]
pub fn authority(&self) -> u64 {
let [a0, a1, a2, a3, a4, a5] = self.identifier_authority;
u64::from_be_bytes([0, 0, a0, a1, a2, a3, a4, a5])
}
#[inline]
#[must_use]
pub fn authority_bytes(&self) -> [u8; 6] {
self.identifier_authority
}
#[inline]
#[must_use]
pub fn sub_authority(&self, idx: u8) -> Option<u32> {
self.sub_authorities().get(idx as usize).copied()
}
#[inline]
#[must_use]
pub fn rid(&self) -> Option<u32> {
self.sub_authorities().last().copied()
}
#[inline]
#[must_use]
pub fn sub_authorities(&self) -> &[u32] {
&self.sub_authority[..self.logical_sub_count()]
}
#[inline]
#[must_use]
pub fn equal_prefix(&self, other: &Sid) -> bool {
self.revision == other.revision
&& self.identifier_authority == other.identifier_authority
&& self.sub_authority_count == other.sub_authority_count
&& match (
self.sub_authorities().split_last(),
other.sub_authorities().split_last(),
) {
(Some((_, prefix1)), Some((_, prefix2))) => prefix1 == prefix2,
(None, None) => true,
_ => false,
}
}
#[inline]
pub fn equal_domain(&self, other: &Sid) -> Result<bool> {
let mut equal = 0;
if unsafe {
bindings::EqualDomainSid(
self.as_ptr().cast_mut(),
other.as_ptr().cast_mut(),
&mut equal,
)
} == 0
{
return Err(Error::from_last_win32_error());
}
Ok(equal != 0)
}
#[inline]
pub fn account_domain_sid(&self) -> Result<SidBuf> {
unsafe {
let mut len = 0u32;
if bindings::GetWindowsAccountDomainSid(
self.as_ptr().cast_mut(),
std::ptr::null_mut(),
&mut len,
) == 0
{
let error = Error::from_last_win32_error();
if error.win32_code() != bindings::ERROR_INSUFFICIENT_BUFFER {
return Err(error);
}
}
let mut domain_sid = SidBuf::with_capacity(len as usize);
if bindings::GetWindowsAccountDomainSid(
self.as_ptr().cast_mut(),
domain_sid.as_mut_ptr(),
&mut len,
) == 0
{
return Err(Error::from_last_win32_error());
}
Ok(domain_sid)
}
}
#[inline]
#[must_use]
pub fn is_well_known(&self, well_known_type: impl AsWellKnownSidType) -> bool {
let well_known_type = well_known_type.as_well_known_sid_type();
unsafe { bindings::IsWellKnownSid(self.as_ptr().cast_mut(), well_known_type.0) != 0 }
}
}
impl ToOwned for Sid {
type Owned = SidBuf;
fn to_owned(&self) -> SidBuf {
SidBuf::from_boxed_words(self.words().to_vec().into_boxed_slice())
}
}
impl Eq for Sid {}
impl PartialEq for Sid {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl Hash for Sid {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.as_bytes());
}
}
impl PartialOrd for Sid {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Sid {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.authority()
.cmp(&other.authority())
.then_with(|| self.sub_authorities().cmp(other.sub_authorities()))
}
}
impl Display for Sid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("S-1-")?;
let authority = self.authority();
if authority <= 0xFFFFFFFF {
write!(f, "{}", authority)?;
} else {
write!(f, "0x{:012X}", authority)?;
}
for sa in self.sub_authorities() {
write!(f, "-{}", sa)?;
}
Ok(())
}
}
impl Debug for Sid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "\"{}\"", self)
}
}
pub struct SidBuf {
sid: Box<Sid>,
}
impl Clone for SidBuf {
fn clone(&self) -> Self {
(**self).to_owned()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SidParseError {
kind: SidParseErrorKind,
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum SidParseErrorKind {
Invalid,
InteriorNul,
Windows(u32),
}
impl SidParseError {
fn invalid() -> Self {
Self {
kind: SidParseErrorKind::Invalid,
}
}
}
impl std::error::Error for SidParseError {}
impl Display for SidParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.kind {
SidParseErrorKind::Invalid => write!(f, "invalid SID string"),
SidParseErrorKind::InteriorNul => {
write!(f, "SID string contains an interior NUL byte")
}
SidParseErrorKind::Windows(code) => {
write!(
f,
"invalid SID string: {}",
std::io::Error::from_raw_os_error(code as i32)
)
}
}
}
}
impl From<SidParseError> for Error {
fn from(_: SidParseError) -> Error {
Error::InvalidSid
}
}
impl FromStr for SidBuf {
type Err = SidParseError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
let mut parts = s.split('-');
match parts.next() {
Some(p) if p.eq_ignore_ascii_case("S") => {}
_ => return Err(SidParseError::invalid()),
}
if parts.next() != Some("1") {
return Err(SidParseError::invalid());
}
let authority_str = parts.next().ok_or_else(SidParseError::invalid)?;
let authority = match authority_str
.strip_prefix("0x")
.or_else(|| authority_str.strip_prefix("0X"))
{
Some(hex) if !hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit()) => {
u64::from_str_radix(hex, 16).map_err(|_| SidParseError::invalid())?
}
Some(_) => return Err(SidParseError::invalid()),
None if !authority_str.is_empty()
&& authority_str.bytes().all(|b| b.is_ascii_digit()) =>
{
authority_str
.parse::<u64>()
.map_err(|_| SidParseError::invalid())?
}
None => return Err(SidParseError::invalid()),
};
let sub_authorities = parts
.map(|p| {
if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
return Err(SidParseError::invalid());
}
p.parse::<u32>().map_err(|_| SidParseError::invalid())
})
.collect::<std::result::Result<Vec<u32>, _>>()?;
SidBuf::new(authority, &sub_authorities).map_err(|_| SidParseError::invalid())
}
}
impl SidBuf {
fn from_boxed_words(words: Box<[u32]>) -> SidBuf {
debug_assert!(
words.len() >= SID_HEADER_WORDS,
"a SID has at least the two header words"
);
let sub_count = words.len() - SID_HEADER_WORDS;
let data = Box::into_raw(words).cast::<u32>();
let ptr = std::ptr::slice_from_raw_parts_mut(data, sub_count) as *mut Sid;
SidBuf {
sid: unsafe { Box::from_raw(ptr) },
}
}
pub fn new(identifier_authority: impl IntoAuthority, sub_authorities: &[u32]) -> Result<Self> {
let identifier_authority = identifier_authority.try_into_authority()?;
let count = sub_authorities.len();
if count > SID_MAX_SUB_AUTHORITIES as usize {
return Err(Error::TooManySubAuthorities);
}
let mut words = vec![0u32; SID_HEADER_WORDS + count].into_boxed_slice();
let sid = Sid::from_words_unchecked_mut(&mut words);
sid.revision = SID_REVISION;
sid.sub_authority_count = count as u8;
sid.identifier_authority = identifier_authority;
sid.sub_authority.copy_from_slice(sub_authorities);
Ok(Self::from_boxed_words(words))
}
pub fn from_bytes(bytes: &[u8]) -> Result<SidBuf> {
let header_len = SID_HEADER_WORDS * size_of::<u32>();
if bytes.len() < header_len || bytes[0] != SID_REVISION {
return Err(Error::InvalidSid);
}
let count = bytes[1] as usize;
if count > SID_MAX_SUB_AUTHORITIES as usize
|| bytes.len() != header_len + count * size_of::<u32>()
{
return Err(Error::InvalidSid);
}
let identifier_authority: [u8; 6] = bytes[2..header_len].try_into().unwrap();
let sub_authorities = bytes[header_len..]
.chunks_exact(size_of::<u32>())
.map(|chunk| u32::from_le_bytes(chunk.try_into().unwrap()))
.collect::<Vec<_>>();
SidBuf::new(identifier_authority, &sub_authorities)
}
#[must_use]
pub fn with_capacity(len: usize) -> SidBuf {
let word_len = len.div_ceil(size_of::<u32>()).max(SID_HEADER_WORDS + 1);
let mut words = vec![0u32; word_len].into_boxed_slice();
let sid = Sid::from_words_unchecked_mut(&mut words);
sid.revision = SID_REVISION;
sid.sub_authority_count = 1;
SidBuf::from_boxed_words(words)
}
#[must_use]
pub unsafe fn as_mut_ptr(&mut self) -> *mut c_void {
let sid: &mut Sid = &mut self.sid;
sid as *mut Sid as *mut c_void
}
pub fn well_known(
well_known_type: impl AsWellKnownSidType,
domain_sid: Option<&Sid>,
) -> Result<SidBuf> {
unsafe {
let well_known_type = well_known_type.as_well_known_sid_type();
let domain_psid = domain_sid
.map(|sid| sid.as_ptr().cast_mut())
.unwrap_or(std::ptr::null_mut());
let mut len = 0u32;
if bindings::CreateWellKnownSid(
well_known_type.0,
domain_psid,
std::ptr::null_mut(),
&mut len,
) == 0
{
let error = Error::from_last_win32_error();
if error.win32_code() != bindings::ERROR_INSUFFICIENT_BUFFER {
return Err(error);
}
}
let word_len = (len as usize)
.div_ceil(size_of::<u32>())
.max(SID_HEADER_WORDS);
let mut words: Box<[u32]> = vec![0u32; word_len].into_boxed_slice();
if bindings::CreateWellKnownSid(
well_known_type.0,
domain_psid,
words.as_mut_ptr().cast(),
&mut len,
) == 0
{
return Err(Error::from_last_win32_error());
}
Ok(SidBuf::from_boxed_words(words))
}
}
pub fn from_string_sid(s: &str) -> std::result::Result<SidBuf, SidParseError> {
let s = std::ffi::CString::new(s).map_err(|_| SidParseError {
kind: SidParseErrorKind::InteriorNul,
})?;
unsafe {
let mut sid = std::ptr::null_mut();
if bindings::ConvertStringSidToSidA(s.as_ptr().cast(), &mut sid) == 0 {
return Err(SidParseError {
kind: SidParseErrorKind::Windows(bindings::GetLastError()),
});
}
let res = SidBuf::from_psid(sid).map_err(|_| SidParseError::invalid());
bindings::LocalFree(sid);
res
}
}
pub unsafe fn from_psid(psid: impl AsSidPtr) -> Result<Self> {
let src = unsafe { Sid::from_psid(psid) }?;
Ok(src.to_owned())
}
}
impl Deref for SidBuf {
type Target = Sid;
#[inline]
fn deref(&self) -> &Sid {
&self.sid
}
}
impl Borrow<Sid> for SidBuf {
#[inline]
fn borrow(&self) -> &Sid {
self
}
}
impl AsRef<Sid> for SidBuf {
#[inline]
fn as_ref(&self) -> &Sid {
self
}
}
impl Eq for SidBuf {}
impl PartialEq for SidBuf {
#[inline]
fn eq(&self, other: &Self) -> bool {
(**self).eq(&**other)
}
}
impl Hash for SidBuf {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl PartialOrd for SidBuf {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for SidBuf {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
(**self).cmp(&**other)
}
}
impl Display for SidBuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&**self, f)
}
}
impl Debug for SidBuf {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&**self, f)
}
}
impl Default for SidBuf {
fn default() -> Self {
SidBuf::new(authority::SECURITY_NULL_SID_AUTHORITY, &[0]).unwrap()
}
}
impl PartialEq<SidBuf> for Sid {
#[inline]
fn eq(&self, other: &SidBuf) -> bool {
self == &**other
}
}
impl PartialEq<Sid> for SidBuf {
#[inline]
fn eq(&self, other: &Sid) -> bool {
&**self == other
}
}
impl PartialEq<&Sid> for SidBuf {
#[inline]
fn eq(&self, other: &&Sid) -> bool {
&**self == *other
}
}
impl PartialEq<SidBuf> for &Sid {
#[inline]
fn eq(&self, other: &SidBuf) -> bool {
*self == &**other
}
}
#[cfg(test)]
mod tests {
use super::authority::*;
use super::well_known::*;
use super::*;
fn nt_sid(sub_authorities: &[u32]) -> SidBuf {
SidBuf::new(SECURITY_NT_AUTHORITY, sub_authorities).unwrap()
}
#[test]
fn from_psid_rejects_invalid_headers() {
for header in [[0, 0], [SID_REVISION, SID_MAX_SUB_AUTHORITIES + 1]] {
let words = [u32::from_ne_bytes([header[0], header[1], 0, 0]), 0];
let psid = words.as_ptr() as *const c_void;
assert!(unsafe { Sid::from_psid(psid) }.is_err());
assert!(unsafe { SidBuf::from_psid(psid) }.is_err());
}
}
#[test]
fn new_enforces_the_sub_authority_limit() {
assert_eq!(
SidBuf::new([0; 6], &[7; 15]).unwrap().sub_authority_count(),
15
);
assert_eq!(
SidBuf::new([0; 6], &[0; 16]).unwrap_err(),
Error::TooManySubAuthorities
);
}
#[test]
fn from_bytes_copies_aligned_and_unaligned_sids() {
let expected = nt_sid(&[32, 544]);
let bytes = expected.as_bytes();
assert_eq!(SidBuf::from_bytes(bytes).unwrap(), expected);
let mut unaligned = vec![0xFF];
unaligned.extend_from_slice(bytes);
assert_eq!(SidBuf::from_bytes(&unaligned[1..]).unwrap(), expected);
}
#[test]
fn from_bytes_validates_the_complete_structure() {
let no_sub_authorities = [SID_REVISION, 0, 0, 0, 0, 0, 0, 5];
assert_eq!(
SidBuf::from_bytes(&no_sub_authorities)
.unwrap()
.sub_authorities(),
&[]
);
let mut too_many_sub_authorities =
vec![0; SID_HEADER_WORDS * size_of::<u32>() + 16 * size_of::<u32>()];
too_many_sub_authorities[0] = SID_REVISION;
too_many_sub_authorities[1] = SID_MAX_SUB_AUTHORITIES + 1;
for bytes in [
&[][..],
&[0, 0, 0, 0, 0, 0, 0, 0],
&[SID_REVISION, 1, 0, 0, 0, 0, 0, 5],
&[SID_REVISION, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0],
&too_many_sub_authorities,
] {
assert_eq!(SidBuf::from_bytes(bytes).unwrap_err(), Error::InvalidSid);
}
}
#[test]
fn rid_returns_the_final_sub_authority() {
assert_eq!(nt_sid(&[21, 1, 2, 3, 1000]).rid(), Some(1000));
assert_eq!(SidBuf::new(5, &[]).unwrap().rid(), None);
}
#[test]
fn new_accepts_every_authority_form() {
let from_const = SidBuf::new(SECURITY_NT_AUTHORITY, &[18]).unwrap();
let from_array = SidBuf::new([0, 0, 0, 0, 0, 5], &[18]).unwrap();
let from_literal = SidBuf::new(5, &[18]).unwrap();
let from_u8 = SidBuf::new(5u8, &[18]).unwrap();
let from_u64 = SidBuf::new(5u64, &[18]).unwrap();
let from_usize = SidBuf::new(5usize, &[18]).unwrap();
let from_i128 = SidBuf::new(5i128, &[18]).unwrap();
for sid in [
from_array,
from_literal,
from_u8,
from_u64,
from_usize,
from_i128,
] {
assert_eq!(sid, from_const);
}
}
#[test]
fn new_enforces_the_authority_range() {
assert_eq!(
SidBuf::new(MAX_AUTHORITY, &[]).unwrap().authority(),
MAX_AUTHORITY
);
for result in [
SidBuf::new(-1, &[]),
SidBuf::new(1u64 << 48, &[]),
SidBuf::new(u128::MAX, &[]),
SidBuf::new(i64::MIN, &[]),
] {
assert_eq!(result.unwrap_err(), Error::AuthorityOutOfRange);
}
}
#[test]
fn authority_getters_round_trip_through_new() {
let sid = nt_sid(&[32, 544]);
assert_eq!(sid.authority(), 5);
assert_eq!(sid.authority_bytes(), SECURITY_NT_AUTHORITY);
assert_eq!(
SidBuf::new(sid.authority(), sid.sub_authorities()).unwrap(),
sid
);
let large = SidBuf::new(1u64 << 32, &[1]).unwrap();
assert_eq!(large.authority_bytes(), [0, 1, 0, 0, 0, 0]);
assert_eq!(
SidBuf::new(large.authority_bytes(), large.sub_authorities()).unwrap(),
large
);
}
#[test]
fn errors_map_to_win32_codes() {
assert_eq!(Error::TooManySubAuthorities.win32_code(), ERROR_INVALID_SID);
assert_eq!(Error::AuthorityOutOfRange.win32_code(), ERROR_INVALID_SID);
assert_eq!(Error::InvalidSid.win32_code(), ERROR_INVALID_SID);
assert_eq!(Error::Windows(5).win32_code(), 5);
let io_error: std::io::Error = Error::Windows(5).into();
assert_eq!(io_error.raw_os_error(), Some(5));
assert_eq!(Error::from(SidParseError::invalid()), Error::InvalidSid);
for error in [Error::TooManySubAuthorities, Error::Windows(5)] {
assert!(!error.to_string().is_empty());
}
}
#[test]
fn well_known_sids_construct() {
for (kind, expected) in [
(WinNullSid, "S-1-0-0"),
(WinLocalSystemSid, "S-1-5-18"),
(WinBuiltinAdministratorsSid, "S-1-5-32-544"),
] {
assert_eq!(
SidBuf::well_known(kind, None).unwrap().to_string(),
expected
);
}
}
#[test]
fn new_builds_the_expected_sid() {
let sid = nt_sid(&[32, 544]);
assert_eq!(
sid.as_bytes(),
&[
0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x20, 0x00, 0x00, 0x00, 0x20, 0x02, 0x00, 0x00, ]
);
assert_eq!(sid.revision(), SID_REVISION);
assert_eq!(sid.sub_authority_count(), 2);
assert_eq!(sid.authority(), 5);
assert_eq!(sid.sub_authority(0), Some(32));
assert_eq!(sid.sub_authority(1), Some(544));
assert_eq!(sid.sub_authority(2), None);
assert_eq!(sid.sub_authorities(), [32, 544]);
}
#[test]
fn from_psid_borrows_or_copies_as_requested() {
let copied = {
let src = nt_sid(&[18]);
let borrowed = unsafe { Sid::from_psid(src.as_ptr()) }.expect("valid SID");
let copied = unsafe { SidBuf::from_psid(src.as_ptr()) }.expect("valid SID");
assert_eq!(borrowed, &*src);
assert_eq!(copied, src);
copied
};
assert_eq!(copied.to_string(), "S-1-5-18");
}
#[test]
fn with_capacity_separates_logical_length_from_buffer_length() {
for (requested, allocated) in [(0, 12), (12, 12), (13, 16), (200, 200)] {
let sid = SidBuf::with_capacity(requested);
assert_eq!(sid.buffer_bytes().len(), allocated);
assert_eq!(sid.as_bytes().len(), 12);
assert_eq!(sid, SidBuf::default());
}
}
#[test]
fn as_mut_ptr_lets_a_caller_fill_the_buffer() {
let admins = nt_sid(&[32, 544]);
let mut buf = SidBuf::with_capacity(admins.as_bytes().len());
unsafe {
let dst = buf.as_mut_ptr() as *mut u8;
std::ptr::copy_nonoverlapping(admins.as_bytes().as_ptr(), dst, admins.as_bytes().len());
}
assert_eq!(buf, admins);
}
#[test]
fn value_traits_ignore_spare_buffer_capacity() {
use std::collections::hash_map::DefaultHasher;
let oversized = SidBuf::with_capacity(200);
let null_sid = SidBuf::default();
assert_eq!(oversized, null_sid);
assert_eq!(oversized.as_bytes(), null_sid.as_bytes());
assert_eq!(oversized.cmp(&null_sid), Ordering::Equal);
let mut oversized_hash = DefaultHasher::new();
oversized.hash(&mut oversized_hash);
let mut null_hash = DefaultHasher::new();
null_sid.hash(&mut null_hash);
assert_eq!(oversized_hash.finish(), null_hash.finish());
}
#[test]
fn owned_and_borrowed_views_agree() {
let owned = nt_sid(&[18]);
let via_deref: &Sid = &owned;
let via_borrow: &Sid = owned.borrow();
let via_as_ref: &Sid = owned.as_ref();
assert_eq!(via_deref, via_borrow);
assert_eq!(via_deref, via_as_ref);
assert_eq!(via_deref.to_owned(), owned);
assert_eq!(*via_deref, owned);
assert_eq!(owned, *via_deref);
assert_eq!(via_deref, owned);
assert_eq!(owned, via_deref);
let different = nt_sid(&[19]);
assert_ne!(via_deref, different);
assert_ne!(different, via_deref);
}
#[test]
fn display_and_debug_render_canonical_strings() {
let cases = [
(SidBuf::default(), "S-1-0-0"),
(nt_sid(&[18]), "S-1-5-18"),
(nt_sid(&[32, 544]), "S-1-5-32-544"),
(
SidBuf::new([0, 0, 0xFF, 0xFF, 0xFF, 0xFF], &[1]).unwrap(),
"S-1-4294967295-1",
),
(
SidBuf::new([0, 1, 0, 0, 0, 0], &[1, 2]).unwrap(),
"S-1-0x000100000000-1-2",
),
];
for (sid, expected) in cases {
assert_eq!(sid.to_string(), expected);
assert_eq!(format!("{sid:?}"), format!("{expected:?}"));
assert_eq!(format!("{:?}", &*sid), format!("{expected:?}"));
}
}
#[test]
fn from_str_parses_and_round_trips_display() {
for s in [
"S-1-0-0",
"S-1-5-18",
"S-1-5-32-544",
"S-1-0x000100000000-1-2",
] {
let sid: SidBuf = s.parse().unwrap();
assert_eq!(sid.to_string(), s);
}
assert_eq!(
"s-1-4294967296-1".parse::<SidBuf>().unwrap(),
"S-1-0x000100000000-1".parse::<SidBuf>().unwrap(),
);
assert_eq!(
"S-1-5".parse::<SidBuf>().unwrap().sub_authorities(),
&[] as &[u32]
);
}
#[test]
fn from_str_rejects_malformed_input() {
for s in [
"", "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", ] {
assert!(s.parse::<SidBuf>().is_err(), "parsing should reject {s:?}");
}
}
#[test]
fn equality_and_ordering_follow_sid_fields_numerically() {
let a = nt_sid(&[18]);
let b = nt_sid(&[18]);
let c = nt_sid(&[19]);
assert_eq!(a, b);
assert_ne!(a, c);
assert!(a < nt_sid(&[32, 544]));
assert!(nt_sid(&[1]) < nt_sid(&[256]));
assert!(nt_sid(&[21, 1]) < nt_sid(&[21, 1, 1]));
let lower_authority = SidBuf::new(4, &[u32::MAX, u32::MAX]).unwrap();
let higher_authority = SidBuf::new(5, &[0]).unwrap();
assert!(lower_authority < higher_authority);
}
#[test]
fn equal_prefix_ignores_only_the_last_sub_authority() {
let first = nt_sid(&[21, 1, 2, 3, 1000]);
let same_prefix = nt_sid(&[21, 1, 2, 3, 2000]);
let different_prefix = nt_sid(&[21, 1, 2, 4, 1000]);
let different_count = nt_sid(&[21, 1, 2, 3]);
let different_authority = SidBuf::new([0, 0, 0, 0, 0, 4], &[21, 1, 2, 3, 2000]).unwrap();
assert!(first.equal_prefix(&same_prefix));
assert!(!first.equal_prefix(&different_prefix));
assert!(!first.equal_prefix(&different_count));
assert!(!first.equal_prefix(&different_authority));
let no_sub_authorities = SidBuf::new(SECURITY_NT_AUTHORITY, &[]).unwrap();
assert!(no_sub_authorities.equal_prefix(&no_sub_authorities));
}
#[test]
fn windows_domain_helpers_compare_and_extract_domains() {
let first = nt_sid(&[21, 1, 2, 3, 1000]);
let same_domain = nt_sid(&[21, 1, 2, 3, 2000]);
let different_domain = nt_sid(&[21, 1, 2, 4, 1000]);
let expected_domain = nt_sid(&[21, 1, 2, 3]);
assert!(first.equal_domain(&same_domain).unwrap());
assert!(!first.equal_domain(&different_domain).unwrap());
assert_eq!(first.account_domain_sid().unwrap(), expected_domain);
}
#[test]
fn well_known_sid_helper_classifies_sids() {
let local_system = nt_sid(&[18]);
assert!(local_system.is_well_known(WinLocalSystemSid));
assert!(!local_system.is_well_known(WinWorldSid));
}
#[test]
fn borrowed_sid_looks_up_owned_key() {
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(nt_sid(&[18]), "LocalSystem");
let key = nt_sid(&[18]);
let probe: &Sid = &key;
assert_eq!(map.get(probe), Some(&"LocalSystem"));
}
#[test]
fn from_string_sid_supports_numeric_and_aliases() {
let ba = nt_sid(&[32, 544]);
assert_eq!(SidBuf::from_string_sid("BA").unwrap(), ba);
assert_eq!(SidBuf::from_string_sid("S-1-5-32-544").unwrap(), ba);
}
#[test]
fn from_string_sid_fails_on_bad_input() {
assert!(matches!(
SidBuf::from_string_sid("").unwrap_err().kind,
SidParseErrorKind::Windows(_)
));
assert!(SidBuf::from_string_sid("not-a-sid").is_err());
assert!(matches!(
SidBuf::from_string_sid("BA\0").unwrap_err().kind,
SidParseErrorKind::InteriorNul
));
}
}