Private/SID/Test-OrphanedSID.ps1

#Requires -Version 5.1

<#
.SYNOPSIS
    SID Orphaned Detection and Cache Management Module for Find-UnknownSID Solution
 
.DESCRIPTION
    This module provides comprehensive SID orphaned detection and cache management
    functionality for the Find-UnknownSID enterprise solution. It focuses exclusively
    on identifying orphaned SIDs and managing validation cache for performance.
 
    This module follows the single-responsibility principle by focusing exclusively
    on orphaned SID detection and cache management. It depends on the Test-SIDFormat
    module for basic validation before performing Active Directory lookups.
 
    BUSINESS VALUE:
    - Enables accurate identification of orphaned SIDs for security cleanup
    - Reduces false positives through comprehensive validation methods
    - Improves security posture by identifying unused access rights
    - Supports compliance requirements for access review and cleanup
 
    TECHNICAL FEATURES:
    - Multiple validation methods (Get-ADObject, SecurityIdentifier translation)
    - Performance caching to avoid repeated AD queries
    - Handles deleted objects and various object types
    - Comprehensive error handling with correlation tracking
    - Cache management for memory optimization
 
.NOTES
    Author: Jeffrey Stuhr
    Blog: https://www.techbyjeff.net
    LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
    Last Updated: 2025-07-04
    Version: 1.0.0
    PowerShell Version: 5.1+ (Windows), 7.x+ (Cross-platform)
 
    MODULE DESIGN:
    This module implements the single-responsibility principle by focusing
    exclusively on orphaned SID detection and cache management. It provides
    comprehensive Active Directory integration while maintaining high cohesion.
 
    TROUBLESHOOTING:
    - For orphaned detection issues: .\Troubleshooting\Security\Orphaned-SID-Issues.md
 
    DEPENDENCIES:
    - Requires Test-SIDFormat.ps1 for SID format validation
    - Requires Logging.ps1 for Write-StructuredLog function
    - Requires ADRetry.ps1 for Invoke-ADOperationWithRetry function
    - Uses script-scoped $script:SIDValidationCache variable for caching
#>


# Initialize cache at module level
if (-not $script:SIDValidationCache) {
    $script:SIDValidationCache = @{}
}
# Lookup counters feed CacheHitRatio in Get-SIDValidationCacheStat
if ($null -eq $script:SIDValidationCacheLookups) {
    $script:SIDValidationCacheLookups = 0
    $script:SIDValidationCacheHits = 0
}

function Test-OrphanedSID {
    <#
    .SYNOPSIS
        Tests whether a SID is orphaned (no longer exists in Active Directory)
 
    .DESCRIPTION
        Performs comprehensive testing to determine if a SID is orphaned by checking
        multiple AD lookup methods and utilizing caching for performance. This function
        is essential for identifying SIDs that should be removed from ACLs during
        security cleanup operations.
 
        OUTCOMES:
        - Orphaned: every lookup completed and none found the SID, or it was found only
          among deleted objects
        - Exists: a lookup found a live principal with the SID
        - Unverified: nothing found the SID, but at least one lookup failed for a reason
          other than "not found" (timeout, access denied, unreachable domain controller).
          ErrorMessage names each failure. Unverified SIDs are never removed and are not
          cached, so a later call performs the lookups again.
 
        UNREACHABLE DIRECTORY SERVER:
        Each directory lookup against a server that does not answer waits for the AD Web
        Services connect timeout, about 42 seconds. Once one lookup fails with
        ADServerDownException, the remaining directory lookups for this SID would fail the
        same way, so they are skipped and listed in ErrorMessage as skipped. The SID is
        Unverified, exactly as if each had been tried. SecurityIdentifier.Translate still runs:
        it goes through LSA rather than AD Web Services, and a name it returns proves the SID
        exists.
 
        BUSINESS VALUE:
        - Enables accurate identification of orphaned SIDs for security cleanup
        - Reduces false positives through comprehensive validation methods
        - Improves security posture by identifying unused access rights
        - Supports compliance requirements for access review and cleanup
 
        TECHNICAL FEATURES:
        - Multiple validation methods (Get-ADObject, SecurityIdentifier translation, type-specific lookups)
        - Performance caching to avoid repeated AD queries
        - Handles deleted objects and various object types
        - Comprehensive error handling with correlation tracking
        - Integration with retry logic for AD operations
 
    .PARAMETER SID
        [String] (Mandatory: Yes, Pipeline: ByValue)
 
        The Security Identifier to test for orphaned status.
 
        VALIDATION RULES:
        - Must be a valid SID string format
        - Supports domain SIDs, well-known SIDs, and service SIDs
 
        BUSINESS CONTEXT:
        SIDs from ACL entries that may no longer have corresponding AD objects.
        Used during security audits and cleanup operations.
 
        EXAMPLES:
        - Domain user: "S-1-5-21-1234567890-1234567890-1234567890-1001"
        - Built-in account: "S-1-5-32-544"
        - Service SID: "S-1-5-80-123456789-123456789-123456789-123456789-123456789"
 
    .PARAMETER MaxRetries
        [Int] (Mandatory: No; 0-10, default 3)
 
        Retries after the first attempt for each directory lookup whose failure looks transient
        (a timeout, a busy or unavailable server). The public commands' -MaxRetries arrives here.
        A server that cannot be contacted is not retried; see UNREACHABLE DIRECTORY SERVER.
 
    .PARAMETER CorrelationId
        [String] (Mandatory: No)
 
        Correlation ID for tracking this operation across logs and troubleshooting.
        Defaults to auto-generated GUID if not provided.
 
    .EXAMPLE
        PS> Test-OrphanedSID -SID "S-1-5-21-1234567890-1234567890-1234567890-1001"
 
        DESCRIPTION: Basic orphaned SID test for domain user
        OUTPUT: SIDLookupResult whose Status is Orphaned, Exists or Unverified
        USE CASE: Security audit to identify unused ACL entries
 
    .EXAMPLE
        PS> @('S-1-5-21-123-456-789-1001', 'S-1-5-32-544') | Test-OrphanedSID
 
        DESCRIPTION: Pipeline processing of multiple SIDs
        OUTPUT: One SIDLookupResult for each SID
        USE CASE: Bulk validation during ACL cleanup operations
 
    .EXAMPLE
        PS> $lookup = Test-OrphanedSID -SID "S-1-5-21-123-456-789-1001" -CorrelationId $correlationId
        PS> if ($lookup.Status -eq 'Unverified') { $lookup.ErrorMessage }
 
        DESCRIPTION: Orphaned test with correlation tracking, reading why a SID could not be verified
        OUTPUT: The lookup failures, such as an unreachable domain controller
        USE CASE: Enterprise audit operations requiring full traceability
 
    .INPUTS
        [String] - SID string values via pipeline
 
    .OUTPUTS
        [SIDLookupResult] - PSCustomObject with SID, Status (Orphaned, Exists, Unverified),
        IsOrphaned and ErrorMessage
 
    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
        Last Updated: 2025-07-04
        Version: 1.0.0
 
        PERFORMANCE CHARACTERISTICS:
        - Uses caching to improve performance for repeated queries
        - Multiple fallback methods ensure comprehensive validation
        - Typical execution time: 50-200ms for uncached, <5ms for cached
 
        TROUBLESHOOTING:
        - For validation errors: .\Troubleshooting\Security\Orphaned-SID-Issues.md
 
    .LINK
        Test-SIDFormat
        Clear-SIDValidationCache
        Get-SIDValidationCacheStat
        .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    [OutputType('SIDLookupResult')]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$SID,

        [Parameter()]
        [ValidateRange(0, 10)]
        [int]$MaxRetries = 3,

        [Parameter()]
        [string]$CorrelationId = [System.Guid]::NewGuid().ToString()
    )

    begin {
        # Initialize cache if it doesn't exist
        if (-not $script:SIDValidationCache) {
            $script:SIDValidationCache = @{}
        }
    }

    process {
        # A lookup that throws anything other than "not found" proves nothing about the SID. Each such
        # failure is collected here; with any present, the SID is Unverified rather than Orphaned.
        $lookupFailures = [System.Collections.Generic.List[string]]::new()
        # Once a directory lookup finds the server unreachable, the rest would wait out the same ~42 s
        # connect timeout and fail the same way (#82). They are skipped and named in the failure text.
        $serverDown = $false
        # Invoke-ADOperationWithRetry counts attempts, the first included
        $lookupAttempts = $MaxRetries + 1
        $skippedLookups = [System.Collections.Generic.List[string]]::new()

        try {
            Write-StructuredLog "Testing SID for orphaned status: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId

            # Validate SID format first using Test-SIDFormat module
            if (-not (Test-SIDFormat -SID $SID -CorrelationId $CorrelationId)) {
                Write-StructuredLog "SID format invalid - cannot be verified: $SID" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                return New-SIDLookupResult -SID $SID -Status 'Unverified' -ErrorMessage 'The SID is not in a valid format, so no lookup was made'
            }

            # Check cache first for performance. Only Orphaned and Exists are ever cached.
            $script:SIDValidationCacheLookups++
            if ($script:SIDValidationCache.ContainsKey($SID)) {
                $script:SIDValidationCacheHits++
                Write-StructuredLog "SID validation cache hit for $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                return $script:SIDValidationCache[$SID]
            }

            # Method 1: Try Get-ADObject with SID (most reliable)
            try {
                $adObject = Invoke-ADOperationWithRetry -ScriptBlock {
                    Get-ADObject -Filter "objectSid -eq '$SID'" -ErrorAction Stop
                } -MaxRetries $lookupAttempts -OperationName 'Get-ADObject-BySID' -ObjectContext $SID -CorrelationId $CorrelationId

                if ($adObject) {
                    Write-StructuredLog "SID found in AD via Get-ADObject: $($adObject.DistinguishedName)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                    $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                    return $script:SIDValidationCache[$SID]
                }
            }
            catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                Write-StructuredLog "SID not found via Get-ADObject: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
            }
            catch {
                $lookupFailures.Add("Get-ADObject: $($_.Exception.Message)")
                if (Test-ADServerDownError -ErrorRecord $_) { $serverDown = $true }
                Write-StructuredLog "Get-ADObject lookup failed for SID $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
            }

            # Method 1a: Check for deleted objects specifically. -IncludeDeletedObjects returns live
            # objects as well as tombstones, so this step is reached with a live match whenever
            # Method 1 failed rather than came back empty; isDeleted tells the two apart.
            if ($serverDown) {
                $skippedLookups.Add('Get-ADObject -IncludeDeletedObjects')
            } else {
                try {
                    $matchedObjects = @(Invoke-ADOperationWithRetry -ScriptBlock {
                            Get-ADObject -Filter "objectSid -eq '$SID'" -IncludeDeletedObjects -Properties isDeleted -ErrorAction Stop
                        } -MaxRetries $lookupAttempts -OperationName 'Get-ADObject-Deleted-BySID' -ObjectContext $SID -CorrelationId $CorrelationId)

                    $liveObject = $matchedObjects | Where-Object { $_ -and $_.isDeleted -ne $true } | Select-Object -First 1
                    $deletedObject = $matchedObjects | Where-Object { $_ -and $_.isDeleted -eq $true } | Select-Object -First 1

                    if ($liveObject) {
                        Write-StructuredLog "SID found as a live object by the deleted-objects lookup: $($liveObject.DistinguishedName)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                        return $script:SIDValidationCache[$SID]
                    }

                    if ($deletedObject) {
                        # A tombstone is positive evidence of deletion, so it settles the question even when
                        # an earlier lookup failed
                        Write-StructuredLog "SID found in deleted objects: $($deletedObject.DistinguishedName) - treating as orphaned" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Orphaned'
                        return $script:SIDValidationCache[$SID]
                    }
                }
                catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                    Write-StructuredLog "SID not found in deleted objects: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
                catch {
                    $lookupFailures.Add("Get-ADObject -IncludeDeletedObjects: $($_.Exception.Message)")
                    if (Test-ADServerDownError -ErrorRecord $_) { $serverDown = $true }
                    Write-StructuredLog "Deleted objects lookup failed for SID $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
            }

            # Method 2: Try direct SecurityIdentifier translation
            try {
                $securityIdentifier = [System.Security.Principal.SecurityIdentifier]::new($SID)
                $ntAccount = $securityIdentifier.Translate([System.Security.Principal.NTAccount])

                if ($ntAccount -and $ntAccount.Value -and -not $ntAccount.Value.StartsWith('S-1-')) {
                    Write-StructuredLog "SID successfully translated to account name: $($ntAccount.Value)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                    $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                    return $script:SIDValidationCache[$SID]
                }
            }
            catch [System.Security.Principal.IdentityNotMappedException] {
                Write-StructuredLog "SID could not be translated - likely orphaned: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
            }
            catch {
                $lookupFailures.Add("SecurityIdentifier.Translate: $($_.Exception.Message)")
                Write-StructuredLog "SecurityIdentifier translation failed for $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
            }

            # Method 3: Try specific object type lookups
            $objectTypes = @(
                @{ CmdLet = 'Get-ADUser'; Filter = "SID -eq '$SID'" },
                @{ CmdLet = 'Get-ADGroup'; Filter = "SID -eq '$SID'" },
                @{ CmdLet = 'Get-ADComputer'; Filter = "SID -eq '$SID'" }
            )

            foreach ($objectType in $objectTypes) {
                if ($serverDown) {
                    $skippedLookups.Add($objectType.CmdLet)
                    continue
                }
                try {
                    $result = Invoke-ADOperationWithRetry -ScriptBlock {
                        & $objectType.CmdLet -Filter $objectType.Filter -ErrorAction Stop
                    } -MaxRetries $lookupAttempts -OperationName $objectType.CmdLet -ObjectContext $SID -CorrelationId $CorrelationId

                    if ($result) {
                        Write-StructuredLog "SID found via $($objectType.CmdLet): $($result.DistinguishedName)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                        return $script:SIDValidationCache[$SID]
                    }
                }
                catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                    # Expected for orphaned SIDs, continue to next type
                    continue
                }
                catch {
                    $lookupFailures.Add("$($objectType.CmdLet): $($_.Exception.Message)")
                    if (Test-ADServerDownError -ErrorRecord $_) { $serverDown = $true }
                    Write-StructuredLog "$($objectType.CmdLet) lookup failed for $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
            }

            # Nothing found the SID, but a lookup that failed might have. Unverified is not cached, so
            # a transient failure does not decide the answer for every later object in the run.
            if ($lookupFailures.Count -gt 0) {
                $countText = "$($lookupFailures.Count) lookup(s) failed"
                if ($skippedLookups.Count -gt 0) {
                    $countText += ", $($skippedLookups.Count) not attempted"
                    $lookupFailures.Add("Not attempted because the directory server could not be contacted: $($skippedLookups -join ', ')")
                }
                $failureText = $lookupFailures -join '; '
                Write-StructuredLog "SID could not be verified - $($countText): $SID ($failureText)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                return New-SIDLookupResult -SID $SID -Status 'Unverified' -ErrorMessage $failureText
            }

            # Every lookup completed and none found the SID
            Write-StructuredLog "SID could not be resolved - marking as orphaned: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
            $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Orphaned'
            return $script:SIDValidationCache[$SID]

        }
        catch {
            # An unexpected failure proves nothing about the SID. Reporting it orphaned would put a live
            # principal's access in the removal path, so it is Unverified and is not cached.
            Write-StructuredLog "Error testing SID for orphaned status $SID : $($_.Exception.Message)" -Level Error -Component 'SIDDetection' -CorrelationId $CorrelationId
            return New-SIDLookupResult -SID $SID -Status 'Unverified' -ErrorMessage $_.Exception.Message
        }
    }
}


function New-SIDLookupResult {
    <#
    .SYNOPSIS
        Creates the result Test-OrphanedSID returns for one SID
 
    .DESCRIPTION
        Private factory for the three outcomes of an orphaned-SID check:
 
        - Orphaned: every lookup completed and none found the SID, or the SID was found only among
          deleted objects. Safe to report and to remove.
        - Exists: a lookup found a live principal with the SID.
        - Unverified: no lookup found the SID, but at least one failed for a reason other than
          "not found" (timeout, access denied, unreachable domain controller), so the SID may still
          belong to a live principal. Reported for re-checking, never removed.
 
    .PARAMETER SID
        The SID string that was tested.
 
    .PARAMETER Status
        Orphaned, Exists or Unverified.
 
    .PARAMETER ErrorMessage
        For Unverified, the failures that prevented a verdict. Empty otherwise.
 
    .OUTPUTS
        [PSCustomObject] with PSTypeName SIDLookupResult and properties SID, Status, IsOrphaned and
        ErrorMessage.
 
    .NOTES
        TROUBLESHOOTING:
        - For unverified SIDs: .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    [OutputType('SIDLookupResult')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',
        Justification = 'Factory function: builds an object and changes no state')]
    param(
        [Parameter(Mandatory)]
        [string]$SID,

        [Parameter(Mandatory)]
        [ValidateSet('Orphaned', 'Exists', 'Unverified')]
        [string]$Status,

        [Parameter()]
        [string]$ErrorMessage
    )

    [PSCustomObject]@{
        PSTypeName   = 'SIDLookupResult'
        SID          = $SID
        Status       = $Status
        IsOrphaned   = ($Status -eq 'Orphaned')
        ErrorMessage = $ErrorMessage
    }
}


function Clear-SIDValidationCache {
    <#
    .SYNOPSIS
        Clears the SID validation cache to free memory and reset validation state
 
    .DESCRIPTION
        Removes all entries from the SID validation cache, which is used to store
        results of orphaned SID tests for performance optimization. This function
        is useful for freeing memory or forcing re-validation of SIDs.
 
        BUSINESS VALUE:
        - Manages memory usage during long-running operations
        - Allows fresh validation when AD state may have changed
        - Supports testing and troubleshooting scenarios
        - Enables cleanup after batch operations
 
        TECHNICAL FEATURES:
        - Safe cache clearing with null checking
        - Verbose output showing entries cleared
        - No side effects on other operations
 
    .EXAMPLE
        PS> Clear-SIDValidationCache
 
        DESCRIPTION: Clear all cached SID validation results
        OUTPUT: Verbose message showing entries cleared
        USE CASE: Memory management during large operations
 
    .EXAMPLE
        PS> Clear-SIDValidationCache; Test-OrphanedSID -SID $sid
 
        DESCRIPTION: Force fresh validation by clearing cache first
        OUTPUT: Cache cleared, then fresh SID validation
        USE CASE: Troubleshooting when cached results may be stale
 
    .INPUTS
        None
 
    .OUTPUTS
        None (cache clearing operation)
 
    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
        Last Updated: 2025-07-04
        Version: 1.0.0
 
        PERFORMANCE CHARACTERISTICS:
        - Instant operation regardless of cache size
        - No impact on other module functions
 
        TROUBLESHOOTING:
        - For cache issues: .\Troubleshooting\Security\Orphaned-SID-Issues.md
        - For memory problems: .\Troubleshooting\Performance\Memory-Management-Issues.md
 
    .LINK
        Get-SIDValidationCacheStat
        Test-OrphanedSID
        .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$CorrelationId = [System.Guid]::NewGuid().ToString()
    )

    if ($script:SIDValidationCache) {
        $count = $script:SIDValidationCache.Count
        $script:SIDValidationCache.Clear()
        $script:SIDValidationCacheLookups = 0
        $script:SIDValidationCacheHits = 0
        Write-StructuredLog "Cleared SID validation cache ($count entries)" -Level Information -Component 'SIDDetection' -CorrelationId $CorrelationId
    } else {
        Write-StructuredLog "SID validation cache was already empty" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
    }
}


function Get-SIDValidationCacheStat {
    <#
    .SYNOPSIS
        Retrieves statistics about the current SID validation cache
 
    .DESCRIPTION
        Provides detailed statistics about the SID validation cache including
        total entries, orphaned SIDs count, and valid SIDs count. This function
        is useful for monitoring cache utilization and performance analysis.
 
        BUSINESS VALUE:
        - Enables performance monitoring and optimization
        - Provides visibility into validation patterns
        - Supports capacity planning for large operations
        - Assists with troubleshooting cache-related issues
 
        TECHNICAL FEATURES:
        - Safe statistics gathering with null checking
        - Detailed breakdown of cache contents
        - No impact on cache performance
 
    .EXAMPLE
        PS> Get-SIDValidationCacheStat
 
        DESCRIPTION: Get current cache statistics
        OUTPUT: Object with TotalEntries, OrphanedSIDs, ValidSIDs counts
        USE CASE: Performance monitoring during operations
 
    .EXAMPLE
        PS> $stats = Get-SIDValidationCacheStat; Write-Host "Cache efficiency: $($stats.ValidSIDs/$stats.TotalEntries*100)%"
 
        DESCRIPTION: Calculate cache efficiency ratio
        OUTPUT: Cache hit efficiency percentage
        USE CASE: Performance analysis and optimization
 
    .INPUTS
        None
 
    .OUTPUTS
        [PSCustomObject] with properties:
        - TotalEntries: Total number of cached SID validations
        - OrphanedSIDs: Number of SIDs identified as orphaned
        - ValidSIDs: Number of SIDs identified as valid
        - CacheHitRatio: Percentage of cache utilization
 
    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
        Last Updated: 2025-07-04
        Version: 1.0.0
 
        PERFORMANCE CHARACTERISTICS:
        - Very fast operation (simple counting)
        - No impact on cache contents or performance
 
        TROUBLESHOOTING:
        - For cache analysis: .\Troubleshooting\Security\Orphaned-SID-Issues.md
        - For performance tuning: .\Troubleshooting\Performance\Performance-Tuning.md
 
    .LINK
        Clear-SIDValidationCache
        Test-OrphanedSID
        .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    if ($script:SIDValidationCache) {
        $totalEntries = $script:SIDValidationCache.Count
        # The cache holds SIDLookupResult objects; Unverified results are never cached
        $orphanedCount = @($script:SIDValidationCache.Values | Where-Object { $_.Status -eq 'Orphaned' }).Count
        $validCount = @($script:SIDValidationCache.Values | Where-Object { $_.Status -eq 'Exists' }).Count

        return [PSCustomObject]@{
            PSTypeName = 'SIDValidationCacheStats'
            TotalEntries = $totalEntries
            OrphanedSIDs = $orphanedCount
            ValidSIDs = $validCount
            CacheHitRatio = if ($script:SIDValidationCacheLookups -gt 0) { [Math]::Round($script:SIDValidationCacheHits / $script:SIDValidationCacheLookups * 100, 2) } else { 0 }
            LastUpdated = Get-Date
        }
    }
    else {
        return [PSCustomObject]@{
            PSTypeName = 'SIDValidationCacheStats'
            TotalEntries = 0
            OrphanedSIDs = 0
            ValidSIDs = 0
            CacheHitRatio = 0
            LastUpdated = Get-Date
        }
    }
}

function Test-ADServerDownError {
    <#
    .SYNOPSIS
        Tells whether an error means the directory server could not be contacted.
 
    .DESCRIPTION
        Test-OrphanedSID runs up to five directory lookups for one SID. When the server that
        answers them is down, each waits for the AD Web Services connect timeout, about 42
        seconds, and fails with Microsoft.ActiveDirectory.Management.ADServerDownException
        ("Unable to contact the server"). This identifies that failure so the remaining lookups
        can be skipped.
 
        The exception chain is walked and compared by type name, so the function works when the
        ActiveDirectory module is not loaded and the type does not exist, as in unit tests.
 
    .PARAMETER ErrorRecord
        The error caught from a directory lookup.
 
    .OUTPUTS
        [bool] True when the error, or an exception inside it, is ADServerDownException.
 
    .EXAMPLE
        PS> try { Get-ADObject -Server dc01 -Filter * } catch { Test-ADServerDownError -ErrorRecord $_ }
 
        DESCRIPTION: Classifies a lookup failure
        OUTPUT: True when dc01 could not be contacted
 
    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
    #>

    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.ErrorRecord]$ErrorRecord
    )

    $exception = $ErrorRecord.Exception
    while ($exception) {
        if ($exception.GetType().FullName -eq 'Microsoft.ActiveDirectory.Management.ADServerDownException') {
            return $true
        }
        $exception = $exception.InnerException
    }
    return $false
}