Private/AzStackHci.Layer7.Helpers.ps1

# ////////////////////////////////////////////////////////////////////////////
# Strict Mode v1 (PS 5.1 safe) - surfaces reads of uninitialised variables at runtime.
Set-StrictMode -Version 1.0

# Helper function to extract CRL Distribution Point and OCSP responder URLs from
# a leaf X509Certificate2. Used when the CRL/OCSP revocation check is offline, so
# callers can surface the specific dependency URLs to the user and optionally
# append dedicated test rows for them.
#
# Returns @{ CRL = @(<http urls>); OCSP = @(<http urls>) } (empty arrays if the
# certificate has no such extensions). Non-http scheme entries (e.g. ldap://)
# are filtered out as they are not applicable for Azure Local.
#
# This is a private helper for Test-Layer7Connectivity / Get-Layer7CertificateDetails.
Function Get-CertRevocationEndpoints {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
    )

    $result = @{ CRL = @(); OCSP = @() }

    try {
        foreach ($ext in $Certificate.Extensions) {
            if (-not $ext -or -not $ext.Oid) { continue }
            $oid = $ext.Oid.Value
            if ($oid -ne $script:CRL_DP_OID -and $oid -ne $script:AIA_OID) { continue }

            # Format(true) expands the ASN.1 into a human-readable multi-line string
            # containing 'URL=http://...' or 'URL=ldap://...' lines.
            $formatted = $ext.Format($true)
            $urlMatches = [regex]::Matches($formatted, 'URL\s*=\s*(\S+)', 'IgnoreCase')
            foreach ($m in $urlMatches) {
                $candidate = ($m.Groups[1].Value).Trim().TrimEnd(',', ';', ')', ']')
                if ([string]::IsNullOrWhiteSpace($candidate)) { continue }
                if ($candidate -notmatch '^https?://') { continue }  # skip ldap://, etc.
                if ($oid -eq $script:CRL_DP_OID) {
                    if ($result.CRL -notcontains $candidate) { $result.CRL += $candidate }
                } else {
                    if ($result.OCSP -notcontains $candidate) { $result.OCSP += $candidate }
                }
            }
        }
    } catch {
        Write-Debug "Get-CertRevocationEndpoints: error parsing extensions - $($_.Exception.Message)"
    }

    return $result
}


# ////////////////////////////////////////////////////////////////////////////
# Helper function to get certificate details for an endpoint
#
# Certificate chain validation flow:
# 1. If HTTPS: calls Get-AzSHciSslCertificateChain to retrieve the full X509 chain (leaf, intermediate, root)
# 2. Validates the leaf certificate using Test-Certificate -Policy SSL
# 3. Then validates the leaf certificate against the specific DNS name
# 4. If either validation fails: marks as SSL Inspection detected (sets $script:SSLInspectionDetected)
# 5. Extracts Subject, Issuer, and Thumbprint for all three chain levels
# 6. If HTTP (port 80): skips all cert checks and fills fields with "Port 80 - SSL not required"
# 7. If cert retrieval fails: fills fields with "Error retrieving certificates"
#
# This is a private helper function for Test-Layer7Connectivity
Function Get-Layer7CertificateDetails {
    param (
        [Parameter(Mandatory=$true)]
        [string]$url,
        [Parameter(Mandatory=$true)]
        [string]$Layer7Status,
        [Parameter(Mandatory=$false)]
        [string]$ReturnLayer7Response = ""
    )

    # Initialize return hashtable
    $CertDetails = @{
        Layer7Status = $Layer7Status
        ReturnLayer7Response = $ReturnLayer7Response
        ReturnCertIssuer = ""
        ReturnCertSubject = ""
        ReturnCertThumbprint = ""
        ReturnCertIntIssuer = ""
        ReturnCertIntSubject = ""
        ReturnCertIntThumbprint = ""
        ReturnCertRootIssuer = ""
        ReturnCertRootSubject = ""
        ReturnCertRootThumbprint = ""
    }

    # Initialised here so the HTTP (port 80) path - which skips the HTTPS cert-retrieval
    # branch - never leaves these variables undefined when they are read below
    # ('if ($Certificates)' / 'elseif ($NoCertificatesRequired)') under Set-StrictMode -Version 1.0.
    $Certificates = $null
    $NoCertificatesRequired = $false

    try {

    # Check if the URL is HTTPS
    if($url -match "https://"){
        # Get the certificate chain for the URL
        # The function will check for SSL inspection, and return the certificate issuer
        # The function will return the certificate issuer, thumbprint, and subject.
        # NOTE: function renamed in v0.6.6 from Get-SslCertificateChain to avoid a name
        # collision with AzStackHci.EnvironmentChecker (10.2509+) which exports a function
        # of the same name with a different parameter set.
        $Certificates = Get-AzSHciSslCertificateChain -url $url -AllowAutoRedirect $false -ErrorAction SilentlyContinue
        # Retry once if cert retrieval failed (intermittent backend pool server issues can cause TLS handshake timeouts)
        if(-not $Certificates){
            Write-Debug "Certificate retrieval failed for '$url', retrying once..."
            $Certificates = Get-AzSHciSslCertificateChain -url $url -AllowAutoRedirect $false -ErrorAction SilentlyContinue
        }
    } else {
        # No certificate required for HTTP (port 80)
        $NoCertificatesRequired = $true
        Write-Verbose "Port 80: SSL certificate checks not required."
    }

    # Get Certificate details
    if($Certificates){
        # Get the certificate chain elements array with bounds safety
        $chainCerts = $Certificates.ChainElements.Certificate
        [int]$chainCount = if ($chainCerts) { @($chainCerts).Count } else { 0 }

        # Check if the certificate chain is not null
        if($chainCount -gt 0){
            Write-Verbose "Certificates Chain found with $chainCount parts"
        } else {
            # No certificate found
            Write-HostAzS "Error: No SSL Certificates found" -ForegroundColor Red
        }
        
        # Leaf certificate (index 0) - only access if chain has at least 1 element
        if($chainCount -ge 1){
            # Check if the certificate subject is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[0].Subject))){
                # Set the certificate subject to the variable
                $CertDetails.ReturnCertSubject = $chainCerts[0].Subject 
                # Check the certificate using Test-Certificate, to check if the certificate is trusted for SSL
                # Check if the certificate is trusted for SSL
                if(Test-Certificate -Cert $chainCerts[0] -Policy SSL -ErrorAction SilentlyContinue -ErrorVariable certError -WarningAction SilentlyContinue){
                    # Certificate is valid for SSL
                    Write-Verbose "Certificate is trusted for SSL: $($CertDetails.ReturnCertSubject)"
                    # Check if the certificate is valid for the URL
                    if(Test-Certificate -Cert $chainCerts[0] -Policy SSL -DNSName (Get-DomainFromURL -url $url).Domain -ErrorAction SilentlyContinue -ErrorVariable certError -WarningAction SilentlyContinue){
                        # Certificate is a valid for URL
                        Write-Verbose "Certificate is a valid for endpoint: $url"
                    } else {
                        # Certificate is not valid for URL
                        Write-HostAzS "Certificate is not valid for endpoint: $url" -ForegroundColor Red
                        Write-HostAzS "Possible SSL Inspection detected, certificate is not trusted." -ForegroundColor Yellow
                        Write-HostAzS "Returned certificate subject: '$($CertDetails.ReturnCertSubject)'" -ForegroundColor Yellow
                        $CertDetails.Layer7Status = "Failed"
                        $CertDetails.ReturnLayer7Response = $CertDetails.ReturnLayer7Response + " - SSL Inspection detected"
                        $script:SSLInspectionDetected = $true
                        $script:SSLInspectedURLs.Add($url) | Out-Null
                    }
                } else {
                    # Test-Certificate failed. Distinguish two cases:
                    # (a) Chain is trusted locally but CRL/OCSP endpoint is unreachable -> CRL/OCSP offline (NOT SSL inspection)
                    # (b) Chain is not trusted by local root store -> SSL inspection (or legitimately untrusted cert)
                    # Perform a revocation-independent chain build against the captured leaf to tell them apart.
                    $isRevocationOffline = $false
                    $revNoneChain = $null
                    try {
                        $revNoneChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
                        $revNoneChain.ChainPolicy.RevocationMode = [System.Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck
                        $revNoneChain.ChainPolicy.RevocationFlag = [System.Security.Cryptography.X509Certificates.X509RevocationFlag]::EntireChain
                        $null = $revNoneChain.Build($chainCerts[0])
                        # If revocation-independent build succeeds, failure must be revocation-only
                        if ($revNoneChain.ChainStatus.Count -eq 0) {
                            # Confirm the original certError mentioned a revocation-offline token
                            $certErrorText = ($certError | Out-String)
                            foreach ($token in $script:CERT_CHAIN_STATUS_REVOCATION_OFFLINE) {
                                if ($certErrorText -match [regex]::Escape($token)) { $isRevocationOffline = $true; break }
                            }
                            # Also inspect the revocation-enabled chain's status tokens as a second source of truth
                            if (-not $isRevocationOffline) {
                                $revFullChain = $null
                                try {
                                    $revFullChain = [System.Security.Cryptography.X509Certificates.X509Chain]::new()
                                    $revFullChain.ChainPolicy.RevocationMode = [System.Security.Cryptography.X509Certificates.X509RevocationMode]::Online
                                    $revFullChain.ChainPolicy.RevocationFlag = [System.Security.Cryptography.X509Certificates.X509RevocationFlag]::EntireChain
                                    $null = $revFullChain.Build($chainCerts[0])
                                    foreach ($cs in $revFullChain.ChainStatus) {
                                        if ($script:CERT_CHAIN_STATUS_REVOCATION_OFFLINE -contains $cs.Status.ToString()) {
                                            $isRevocationOffline = $true; break
                                        }
                                    }
                                } catch {
                                    Write-Debug "Revocation-enabled chain build failed for '$url': $($_.Exception.Message)"
                                } finally {
                                    if ($revFullChain) { $revFullChain.Dispose() }
                                }
                            }
                        }
                    } catch {
                        Write-Debug "Revocation-independent chain build failed for '$url': $($_.Exception.Message)"
                    } finally {
                        if ($revNoneChain) { $revNoneChain.Dispose() }
                    }

                    if ($isRevocationOffline) {
                        # Chain is trusted locally but CRL/OCSP is unreachable — mark as Failed with a distinct response
                        Write-HostAzS "Certificate chain is trusted, but CRL/OCSP revocation check is offline for: $($CertDetails.ReturnCertSubject)" -ForegroundColor Yellow
                        Write-HostAzS "This is NOT SSL Inspection — a CRL/OCSP endpoint used by the CA is unreachable from this host." -ForegroundColor Yellow
                        $CertDetails.Layer7Status = "Failed"
                        $CertDetails.ReturnLayer7Response = $CertDetails.ReturnLayer7Response + " - CRL/OCSP unreachable"
                        if (-not ($script:CRLOfflineURLs -contains $url)) { $script:CRLOfflineURLs.Add($url) | Out-Null }

                        # Extract CRL Distribution Points + OCSP responders from the leaf and
                        # append (deduped) dependency rows to $script:Results so the existing
                        # remaining-URLs loop tests them as first-class endpoints.
                        try {
                            $revEndpoints = Get-CertRevocationEndpoints -Certificate $chainCerts[0]
                            $crlAdded = 0; $ocspAdded = 0
                            foreach ($crlUrl in $revEndpoints.CRL) {
                                if ($crlAdded -ge $script:CRL_MAX_DP_PER_CERT) { break }
                                Add-CrlDependencyRowToResults -Kind 'CRL' -DependencyURL $crlUrl -ParentURL $url
                                $crlAdded++
                            }
                            foreach ($ocspUrl in $revEndpoints.OCSP) {
                                if ($ocspAdded -ge $script:CRL_MAX_OCSP_PER_CERT) { break }
                                Add-CrlDependencyRowToResults -Kind 'OCSP' -DependencyURL $ocspUrl -ParentURL $url
                                $ocspAdded++
                            }
                            # Write the discovered revocation endpoints to the parent's Note so the
                            # HTML/CSV/JSON output clearly links parent -> child row(s).
                            $revSummaryParts = @()
                            if ($revEndpoints.CRL.Count -gt 0)  { $revSummaryParts += "CRL: $(($revEndpoints.CRL | Select-Object -First $script:CRL_MAX_DP_PER_CERT) -join ', ')" }
                            if ($revEndpoints.OCSP.Count -gt 0) { $revSummaryParts += "OCSP: $(($revEndpoints.OCSP | Select-Object -First $script:CRL_MAX_OCSP_PER_CERT) -join ', ')" }
                            if ($revSummaryParts.Count -gt 0) {
                                $revSummary = $revSummaryParts -join ' | '
                                $CertDetails.ReturnLayer7Response = $CertDetails.ReturnLayer7Response + " [$revSummary]"
                            } else {
                                Write-Debug "CRL/OCSP offline for '$url' but no revocation endpoints found in leaf certificate extensions"
                            }
                        } catch {
                            Write-Debug "Error extracting/adding CRL/OCSP dependency rows for '$url': $($_.Exception.Message)"
                        }
                    } else {
                        # Certificate is not valid for SSL
                        Write-HostAzS "Certificate is not trusted for SSL: $($CertDetails.ReturnCertSubject)" -ForegroundColor Red
                        # SSL inspection detected
                        Write-HostAzS "Possible SSL Inspection detected, certificate is not trusted." -ForegroundColor Yellow
                        $CertDetails.Layer7Status = "Failed"
                        $CertDetails.ReturnLayer7Response = $CertDetails.ReturnLayer7Response + " - SSL Inspection detected"
                        $script:SSLInspectionDetected = $true
                        $script:SSLInspectedURLs.Add($url) | Out-Null
                    }
                }
            } else {
                # No certificate subject found
                $CertDetails.ReturnCertSubject = "No certificate common name found"
            }
            
            # Check if the certificate issuer is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[0].Issuer))){
                # Set the certificate issuer to the variable
                $CertDetails.ReturnCertIssuer = $chainCerts[0].Issuer
            } else {
                # No certificate issuer found
                $CertDetails.ReturnCertIssuer = "No certificate issuer found"
            }
            
            # Check if the certificate thumbprint is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[0].Thumbprint))){
                # Set the certificate thumbprint to the variable
                $CertDetails.ReturnCertThumbprint = $chainCerts[0].Thumbprint
            } else {
                # No certificate thumbprint found
                $CertDetails.ReturnCertThumbprint = "No certificate thumbprint found"
            }
        } else {
            $CertDetails.ReturnCertSubject = "No leaf certificate found in chain"
            $CertDetails.ReturnCertIssuer = "No leaf certificate found in chain"
            $CertDetails.ReturnCertThumbprint = "No leaf certificate found in chain"
        }
        
        # Intermediate certificate (index 1) - only access if chain has at least 2 elements
        if($chainCount -ge 2){
            # Check if the intermediate certificate subject is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[1].Subject))){
                # Set the certificate issuer to the variable
                $CertDetails.ReturnCertIntSubject = $chainCerts[1].Subject
            } else {
                # No intermediate certificate Subject found
                $CertDetails.ReturnCertIntSubject = "No intermediate certificate common name found"
            }
            
            # Check if the intermediate certificate issuer is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[1].Issuer))){
                # Set the certificate issuer to the variable
                $CertDetails.ReturnCertIntIssuer = $chainCerts[1].Issuer
            } else {
                # No intermediate certificate issuer found
                $CertDetails.ReturnCertIntIssuer = "No intermediate certificate issuer found"
            }
            
            # Check if the intermediate certificate thumbprint is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[1].Thumbprint))){
                # Set the certificate thumbprint to the variable
                $CertDetails.ReturnCertIntThumbprint = $chainCerts[1].Thumbprint
            } else {
                # No intermediate certificate thumbprint found
                $CertDetails.ReturnCertIntThumbprint = "No intermediate certificate thumbprint found"
            }
        } else {
            $CertDetails.ReturnCertIntSubject = "No intermediate certificate in chain"
            $CertDetails.ReturnCertIntIssuer = "No intermediate certificate in chain"
            $CertDetails.ReturnCertIntThumbprint = "No intermediate certificate in chain"
        }
        
        # Root certificate (index 2) - only access if chain has at least 3 elements
        if($chainCount -ge 3){
            # Check if the root certificate subject is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[2].Subject))){
                # Set the certificate issuer to the variable
                $CertDetails.ReturnCertRootSubject = $chainCerts[2].Subject
            } else {
                # No root certificate Subject found
                $CertDetails.ReturnCertRootSubject = "No root certificate common name found"
            }
            
            # Check if the root certificate issuer is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[2].Issuer))){
                # Set the certificate issuer to the variable
                $CertDetails.ReturnCertRootIssuer = $chainCerts[2].Issuer
            } else {
                # No root certificate issuer found
                $CertDetails.ReturnCertRootIssuer = "No root certificate issuer found"
            }
            
            # Check if the root certificate thumbprint is not null
            if(-not([string]::IsNullOrWhiteSpace($chainCerts[2].Thumbprint))){
                # Set the certificate thumbprint to the variable
                $CertDetails.ReturnCertRootThumbprint = $chainCerts[2].Thumbprint
            } else {
                # No root certificate thumbprint found
                $CertDetails.ReturnCertRootThumbprint = "No root certificate thumbprint found"
            }
        } else {
            $CertDetails.ReturnCertRootSubject = "No root certificate in chain"
            $CertDetails.ReturnCertRootIssuer = "No root certificate in chain"
            $CertDetails.ReturnCertRootThumbprint = "No root certificate in chain"
        }
    } elseif($NoCertificatesRequired){
        # No certificate found, as the port is 80
        $CertDetails.ReturnCertIssuer = "Port 80 - SSL not required"
        $CertDetails.ReturnCertSubject = "Port 80 - SSL not required"
        $CertDetails.ReturnCertThumbprint = "Port 80 - SSL not required"
        $CertDetails.ReturnCertIntIssuer = "Port 80 - SSL not required"
        $CertDetails.ReturnCertIntSubject = "Port 80 - SSL not required"
        $CertDetails.ReturnCertIntThumbprint = "Port 80 - SSL not required"
        $CertDetails.ReturnCertRootIssuer = "Port 80 - SSL not required"
        $CertDetails.ReturnCertRootSubject = "Port 80 - SSL not required"
        $CertDetails.ReturnCertRootThumbprint = "Port 80 - SSL not required"
        Write-Verbose "Port 80: SSL certificate checks not required."
    } else {
        # No certificate found, but expected
        $CertDetails.ReturnCertIssuer = "Error retrieving certificates"
        $CertDetails.ReturnCertSubject = "Error retrieving certificates"
        $CertDetails.ReturnCertThumbprint = "Error retrieving certificates"
        $CertDetails.ReturnCertIntIssuer = "Error retrieving certificates"
        $CertDetails.ReturnCertIntSubject = "Error retrieving certificates"
        $CertDetails.ReturnCertIntThumbprint = "Error retrieving certificates"
        $CertDetails.ReturnCertRootIssuer = "Error retrieving certificates"
        $CertDetails.ReturnCertRootSubject = "Error retrieving certificates"
        $CertDetails.ReturnCertRootThumbprint = "Error retrieving certificates"
        Write-HostAzS "Error retrieving certificates..." -ForegroundColor Red            
    }

    } catch {
        # Catch any unexpected errors during certificate chain processing
        Write-HostAzS "Error processing certificate details for '$url': $($_.Exception.Message)" -ForegroundColor Red
        $CertDetails.ReturnCertIssuer = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertSubject = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertThumbprint = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertIntIssuer = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertIntSubject = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertIntThumbprint = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertRootIssuer = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertRootSubject = "Error: $($_.Exception.Message)"
        $CertDetails.ReturnCertRootThumbprint = "Error: $($_.Exception.Message)"
    }

    return $CertDetails
}


# ////////////////////////////////////////////////////////////////////////////
# Helper function to get certificate details for failed endpoints
# This is a private helper function for Test-Layer7Connectivity
Function Get-FailedEndpointCertificateDetails {
    param (
        [Parameter(Mandatory=$true)]
        [string]$url
    )

    # Initialize return hashtable
    $CertDetails = @{
        ReturnCertIssuer = ""
        ReturnCertSubject = ""
        ReturnCertThumbprint = ""
        ReturnCertIntIssuer = ""
        ReturnCertIntSubject = ""
        ReturnCertIntThumbprint = ""
        ReturnCertRootIssuer = ""
        ReturnCertRootSubject = ""
        ReturnCertRootThumbprint = ""
    }

    # Check if the URL is HTTPS
    if($url -match "https://"){
        # Do not attempt to check the certificate, as the Layer7Status is not "Success"
        Write-Debug "Unable to check certificates, as Layer7Status is 'Failed'"
        $CertDetails.ReturnCertIssuer = "Failed - Certificate not checked"
        $CertDetails.ReturnCertSubject = "Failed - Certificate not checked"
        $CertDetails.ReturnCertThumbprint = "Failed - Certificate not checked"
        $CertDetails.ReturnCertIntIssuer = "Failed - Certificate not checked"
        $CertDetails.ReturnCertIntSubject = "Failed - Certificate not checked"
        $CertDetails.ReturnCertIntThumbprint = "Failed - Certificate not checked"
        $CertDetails.ReturnCertRootIssuer = "Failed - Certificate not checked"
        $CertDetails.ReturnCertRootSubject = "Failed - Certificate not checked"
        $CertDetails.ReturnCertRootThumbprint = "Failed - Certificate not checked"
    } else {
        # No certificate required for HTTP (port 80)
        $CertDetails.ReturnCertIssuer = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertSubject = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertThumbprint = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertIntIssuer = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertIntSubject = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertIntThumbprint = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertRootIssuer = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertRootSubject = "Failed - (But Certificate not required for port 80)"
        $CertDetails.ReturnCertRootThumbprint = "Failed - (But Certificate not required for port 80)"
    }

    return $CertDetails
}


# ////////////////////////////////////////////////////////////////////////////
# Pure decision predicate for the Auto-mode HEAD->GET fallback in Test-Layer7Connectivity.
# Extracted so the fallback decision can be unit-tested deterministically without having to
# fabricate a live System.Net.WebException response graph (HttpWebResponse has no usable public
# constructor in PS 5.1, so the detection of $IsProtocolError stays inline in the caller and the
# resulting boolean is passed in here).
Function Test-HeadToGetFallbackRequired {
<#
    .SYNOPSIS
    Decides whether an Auto-mode HEAD attempt should be retried as GET.
 
    .DESCRIPTION
    Returns $true when ALL of the following hold:
      - RequestMethod is 'Auto' (HEAD-first with a GET safety net),
      - a HEAD->GET fallback has not already been attempted for this URL,
      - this is the first request (RedirectCount -eq 1), not a redirected hop,
    AND at least one of:
      - the HEAD attempt returned (405) Method Not Allowed,
      - the HEAD attempt returned (400) Bad Request,
      - the HEAD attempt was classified Failed AND came back with an actual HTTP response
        (IsProtocolError). A HEAD carries no body and frequently omits the Server header, so
        Get-HttpStatusInterpretation cannot disambiguate a 4xx such as 403 Forbidden; GET
        returns those, so a GET retry yields an authoritative result.
 
    Transport-level failures (connect / DNS / timeout / TLS) are NOT protocol errors and so never
    trigger a GET retry — GET would fail identically, and those retries are handled elsewhere.
 
    .OUTPUTS
    [bool]
#>

    [OutputType([bool])]
    param (
        [Parameter(Mandatory = $true)]
        [string]$RequestMethod,

        [Parameter(Mandatory = $true)]
        [bool]$HeadFallbackAlreadyTried,

        [Parameter(Mandatory = $true)]
        [int]$RedirectCount,

        [Parameter(Mandatory = $false)]
        [string]$Layer7Response,

        [Parameter(Mandatory = $false)]
        [string]$Layer7Status,

        [Parameter(Mandatory = $false)]
        [bool]$IsProtocolError
    )

    if ($RequestMethod -ne 'Auto') { return $false }
    if ($HeadFallbackAlreadyTried) { return $false }
    if ($RedirectCount -ne 1)      { return $false }

    if ($Layer7Response -eq '(405) Method Not Allowed') { return $true }
    if ($Layer7Response -eq '(400) Bad Request')        { return $true }
    if (($Layer7Status -eq 'Failed') -and $IsProtocolError) { return $true }

    return $false
}


# ////////////////////////////////////////////////////////////////////////////
# Helper function to interpret HTTP status codes and exception responses
# This is a private helper function for Test-Layer7Connectivity
# It determines whether a failed web request should be treated as "Success" (endpoint reachable)
# or "Failed" (endpoint unreachable) based on the response string, server headers, and endpoint URL.
# Documentation: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
Function Get-HttpStatusInterpretation {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Layer7Response,

        [Parameter(Mandatory=$false)]
        [object]$IwrError,

        [Parameter(Mandatory=$false)]
        [string]$OriginalURL
    )

    # Check if the response is a known value
    if($Layer7Response -eq "Unable to connect to the remote server"){
        # Overwrite the Layer7Status to "Failed".
        return "Failed"

    } elseif($Layer7Response -eq "The operation has timed out"){
        # Overwrite the Layer7Status to "Failed".
        return "Failed"

    } elseif($Layer7Response -like "The remote name could not be resolved*"){
        # Overwrite the Layer7Status to "Failed".
        return "Failed"

    } elseif($Layer7Response -eq "(400) Bad Request"){
        # Request was successful, but it was a bad request
        return "Success"

    } elseif($Layer7Response -eq "(401) Unauthorized"){
        # Request was successful, but the request was not authorized
        return "Success"

    } elseif($Layer7Response -eq "(404) Not Found"){
        # Request was successful, but the remote server returned no content from the root of the web server (404 page not found).
        return "Success"

    # Exception handling for 403 Forbidden responses
    } elseif($Layer7Response -eq "(403) Forbidden"){
        
        # Additional connectivity test for 403 Forbidden, to check if the URL is accessible
        if($($IwrError.ErrorRecord.Exception.Response.Server) -like "Microsoft-IIS*") {
                # Microsoft IIS Server detected, valid connection
                return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Server) -like "Microsoft-HTTPAPI*") {
                # Microsoft HTTPAPI Server detected, valid connection
                return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Server) -like "AkamaiGHost*") {
            # AkamaiGHost detected, valid connection
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Server) -like "AkamaiNetStorage*") {
            # AkamaiNetStorage detected, valid connection
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Server) -like "Qwilt*") {
            # Qwilt detected, valid connection
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Server) -like "AzureContainerRegistry") {
            # AzureContainerRegistry detected, valid connection
            return "Success"

        } elseif(($($IwrError.ErrorRecord.Exception.Response.Server) -eq "nginx") -and ($OriginalURL -eq "tlu.dl.delivery.mp.microsoft.com")) {
            # Windows Update endpoint 'tlu.dl.delivery.mp.microsoft.com', with Server "nginx" can intermittently return a 403 response
            # Set status to successful connection
            return "Success"

        } elseif(($($IwrError.ErrorRecord.Exception.Response.Server) -like "Amazon*") -and ($OriginalURL -eq "download.hitachivantara.com")) {
            # SBE endpoint: download.hitachivantara.com detected has Server "AmazonS3"
            # Set status to successful connection
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.StatusDescription) -eq "Forbidden - unexpected URL format") {
            # "Forbidden - unexpected URL format" detected, valid connection
            # Example URL: tlu.dl.delivery.mp.microsoft.com on port 80, which intermittently changes between "AkamaiGHost" and a null value for "$_.Exception.Response.Server"
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Headers) -contains "x-azure-ref") {
            # Azure Front Door response detected, valid connection
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Headers) -contains "X-MSEdge-Ref") {
            # Microsoft Edge response detected, valid connection
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Headers) -contains "x-ms-request-id") {
            # Microsoft Edge response detected, valid connection
            return "Success"
        
        } elseif($($IwrError.ErrorRecord.Exception.Response.Headers) -contains "Location") {
            # Additional check for "Location" header in the response
            # This is used by some Microsoft services to indicate a redirect
            if($($IwrError.ErrorRecord.Exception.Response.Headers["Location"]) -like "*mscom.errorpage.failover.com*") {
                # Microsoft web server response detected, valid connection
                return "Success"
            }
            # Location header present but not a known Microsoft redirect - fall through to default Failed
            return "Failed"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Server) -like "Zscaler*") {
            # Zscaler response detected, invalid connection
            # Known firewall / proxy device intercepting requests
            # Set status to Failed
            return "Failed"

        } elseif($IwrError.Message.ToString().Contains("You do not have permission to view this directory or page using the credentials that you supplied.")){
            # Expected response from a couple of endpoints
            # Response: "403 - Forbidden: Access is denied."
            # Server Error
            # Server example: 'https://azurewatsonanalysis-prod.core.windows.net' and key vaults
            # Response: "403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied."
            # You do not have permission to view this directory or page using the credentials that you supplied.
            return "Success"

        } else {

            # ////// All other 403 Forbidden responses ///////
            # Unknown, set Layer7Status to "Failed"
            return "Failed"

        }

    } elseif($Layer7Response -eq "(405) Method Not Allowed"){
        # Overwrite the Layer7Status to "Failed".
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
            
        if(($($IwrError.ErrorRecord.Exception.Response.Server) -like "Microsoft*")) {
            # https://dataonsbe.azurewebsites.net/download returns a 405, valid connection
            return "Success"

        } else {
            return "Failed"
        }

    } elseif($Layer7Response -eq "(408) Request Timeout"){
        # Overwrite the Layer7Status to "Failed".
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408
        return "Failed"

    } elseif($Layer7Response -eq "(429) Too Many Requests"){
        # Overwrite the Layer7Status to "Success", as this the server is responding with a "429" Too Many Requests
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
        return "Success"

    } elseif($Layer7Response -eq "(500) Internal Server Error"){
        # The server returned a 500 error, but connectivity to the endpoint was established successfully.
        # This indicates the endpoint is reachable (firewall/proxy rules are correct), even though the service has an internal error.
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500
        return "Success"

    } elseif($Layer7Response -eq "(502) Bad Gateway"){
        # Overwrite the Layer7Status to "Failed", another device can respond.
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502

        # Additional check for 502 Bad Gateway, to check for "Microsoft-Azure-Application-Gateway/v2" in the response
        if($($IwrError.ErrorRecord.Exception.Response.Server) -like 'Microsoft-Azure-Application-Gateway*') {
            Write-Verbose "Azure Application Gateway response detected, valid connection"
            return "Success"

        # Additional check for Arc Gateway response
        } elseif($IwrError.Message.ToString().Contains("Our services aren't available right now") -and (($OriginalURL -like "*.gw.arc.azure.com") -or ($OriginalURL -eq "dp.stackhci.azure.com"))) {
            Write-Verbose "Azure Front Door response detected, valid connection"
            return "Success"

        } elseif($($IwrError.ErrorRecord.Exception.Response.Headers) -contains "x-azure-ref") {
            # Azure Front Door response detected, valid connection even though the response is 502 Bad Gateway
            Write-Verbose "Azure Front Door response detected, valid connection"
            return "Success"
            
        } else {
            return "Failed"
        }
    
    } elseif($Layer7Response -eq "(503) Server Unavailable"){
        # Overwrite the Layer7Status to "Success".
        # 503 status code indicates that the server is not ready to handle the request.
        # This can be due to the server being overloaded or down for maintenance.
        # https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/503
        return "Success"

    # Could not 'Could not establish trust relationship for the SSL/TLS secure channel'
    } elseif($Layer7Response -like "*Could not establish trust relationship for the SSL/TLS secure channel"){
        # Overwrite the Layer7Status to "Failed"
        return "Failed"
        
    # ////// All other / unhandled exceptions treat as Failed //////
    } else {
        # Overwrite the Layer7Status to "Failed"
        return "Failed"

    }
}


# ////////////////////////////////////////////////////////////////////////////
# NOTE: A previous helper `Resolve-Layer7Redirect` was removed in v0.6.7 because:
# 1. It was never called anywhere in the module (dead code), and
# 2. It pushed raw STRINGS into $script:RedirectedResults, but the live redirect
# path uses Add-RedirectedUrlToResults (Connectivity.Helpers.ps1) which pushes
# properly-shaped [PSCustomObject] entries with .url / .Port / .RowID / etc.
# Mixing the two shapes would have broken Phase-4 redirect-URL processing, the
# RowID-keyed JSON output, and the parallel-fan-out merge dedupe added in v0.6.7
# (Merge-Layer7WorkerResult). Deleting the dead function eliminates that latent
# polymorphism bug. If a future change needs to centralise redirect handling,
# extend Add-RedirectedUrlToResults instead.
# ////////////////////////////////////////////////////////////////////////////


# SIG # Begin signature block
# MIInSQYJKoZIhvcNAQcCoIInOjCCJzYCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC7957t1WGpcHR+
# BHnKzbXfubLMo73+5c7hHrKvYUpda6CCDLowggX1MIID3aADAgECAhMzAAACHU0Z
# yE7XD1dIAAAAAAIdMA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNVBAYTAlVTMR4wHAYD
# VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBD
# b2RlIFNpZ25pbmcgUENBIDIwMjQwHhcNMjYwNDE2MTg1OTQzWhcNMjcwNDE1MTg1
# OTQzWjB0MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UE
# BxMHUmVkbW9uZDEeMBwGA1UEChMVTWlj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