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 transient Invoke-WebRequest send-failure retries.
Function Test-SendFailureRetryRequired {
    [OutputType([bool])]
    param (
        [Parameter(Mandatory = $false)]
        [string]$Layer7Response,

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

        [Parameter(Mandatory = $false)]
        [bool]$IsSendFailureStatus,

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

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

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

    if ($Layer7Status -ne 'Failed') { return $false }
    if ($RedirectCount -ne 1) { return $false }
    if ($RetryAttempts -ge ($MaxAttempts - 1)) { return $false }

    if ($IsSendFailureStatus) { return $true }
    return ($Layer7Response -eq 'The underlying connection was closed: An unexpected error occurred on a send.')
}


# ////////////////////////////////////////////////////////////////////////////
# Pure decision predicate for transient Invoke-WebRequest connection-failure retries.
Function Test-ConnectFailureRetryRequired {
    [OutputType([bool])]
    param (
        [Parameter(Mandatory = $false)]
        [string]$Layer7Response,

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

        [Parameter(Mandatory = $false)]
        [bool]$IsConnectFailureStatus,

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

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

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

    if ($Layer7Status -ne 'Failed') { return $false }
    if ($RedirectCount -ne 1) { return $false }
    if ($RetryAttempts -ge ($MaxAttempts - 1)) { return $false }

    if ($IsConnectFailureStatus) { return $true }
    return ($Layer7Response -eq 'Unable to connect to the remote server')
}


# ////////////////////////////////////////////////////////////////////////////
# 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
# MIInRAYJKoZIhvcNAQcCoIInNTCCJzECAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCTI5ezwfWVG5gh
# 5gjKRC0eLSlJOLfe+adOUs1QEL1tMaCCDLowggX1MIID3aADAgECAhMzAAACHU0Z
# yE7XD1dIAAAAAAIdMA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNVBAYTAlVTMR4wHAYD
# VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBD
# b2RlIFNpZ25pbmcgUENBIDIwMjQwHhcNMjYwNDE2MTg1OTQzWhcNMjcwNDE1MTg1
# OTQzWjB0MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UE
# BxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYD
# VQQDExVNaWNyb3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IB
# DwAwggEKAoIBAQDQvewXxx9gZZFC6Ys1WBay8BJ8kGA4JQnH5CMafqOASlTpK9H8
# o5ZXTXt0caVQTNMUP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