Public/Authentication.ps1

## Ensure prismSessions folder exists
$prismSessionsFolderPath = Join-Path -Path $userPaths.credentials -ChildPath '.prismSessions'
if (-not (Test-Path -Path $prismSessionsFolderPath -PathType Container)) {
    $null = New-Item -Path $prismSessionsFolderPath -ItemType Directory
}

## Define a PrismSessions Variable to store connection details in
New-Variable -Scope Global -Name 'PrismSessions' -Value @{ } -ErrorAction SilentlyContinue
New-Variable -Scope Global -Name 'PrismSessionsPath' -Value (Join-Path -Path $userPaths.credentials -ChildPath '.prismSessions') -ErrorAction SilentlyContinue

## API versions to probe during discovery, in order of preference.
$script:ApiVersions = @('4.2', '4.3', '4.4', '4.5')
## Format the validation endpoint with the API version selected for each session.
$script:PrismValidationPath = 'prism/v{0}/config/tasks?$limit=1'

function Lock-FileMutex {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Path,
        [int]$TimeoutSeconds = 15
    )

    begin {
        Write-Verbose "LOCK: Attempting [$Path]"
        $stopWatch = [Diagnostics.Stopwatch]::StartNew()
    }

    process {
        while ($stopWatch.Elapsed -lt [TimeSpan]::FromSeconds($TimeoutSeconds)) {
            try {
                $fs = [IO.File]::Open(
                    $Path, 'OpenOrCreate', 'ReadWrite', 'None'
                )

                Write-Verbose "LOCK: Acquired [$Path]"
                return $fs
            }
            catch [IO.IOException] {
                Write-Verbose "LOCK: Busy, retrying..."
                Start-Sleep -Milliseconds 88
            }
        }

        throw "LOCK: Timeout acquiring [$Path]"
    }
}

function New-PrismSession {
    <#
    .SYNOPSIS
    Creates a connection to a Nutanix Prism Central instance.
 
    .DESCRIPTION
    This function creates an authenticated session to the specified Prism Central
    instance using the provided credentials. Prism Central v4 APIs authenticate with
    HTTP Basic authentication; the resulting Internet Gateway session cookie is cached
    in the session's WebSession. The created session can be used when calling other
    functions within the Prism module. Sessions are named after the server and
    cached as <server>.json. Each server has one session; reconnecting replaces it.
 
    .PARAMETER Server
    The host name or IP address of the Prism Central instance to connect to.
    HTTP/HTTPS URLs are accepted; only the lowercase host is used for the session name.
    URL paths and embedded ports are ignored. Use -Port to select the connection port.
 
    .PARAMETER Port
    The port the Prism Central API listens on. Defaults to 9440.
 
    .PARAMETER Credential
    The credentials to be used when connecting to Prism Central.
 
    .PARAMETER ApiVersion
    API version to validate against the server, for example '4.2'. When omitted for
    a new connection, probes the versions in $script:ApiVersions in collection
    order and uses the first successful tasks request. Only HTTP 404 advances
    discovery; other failures stop it.
 
    .PARAMETER AllowInsecureSSL
    Switch indicating whether or not an insecure SSL connection is allowed (skips
    certificate validation).
 
    .PARAMETER Force
    Forces creation of a brand new session even if a valid cached session exists.
 
    .PARAMETER Passthru
    Returns the created PrismSession object.
 
    .EXAMPLE
    $Session = @{
        Server = 'pc.lab.local'
        Credential = (Get-StoredCredential -Name 'pc.lab.local')
    }
    New-PrismSession @Session
 
    .OUTPUTS
    None, or a PrismSession when -Passthru is supplied.
    #>


    [CmdletBinding()]
    [Alias('Connect-PrismServer')]
    param(
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true)]
        [string]$Server,

        [Parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [int]$Port = 9440,

        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true)]
        [pscredential]$Credential,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiVersion,

        [Parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [switch]$AllowInsecureSSL,

        [Parameter(
            DontShow = $true,
            Mandatory = $false)]
        [switch]$Force,

        [Parameter(
            Mandatory = $false)]
        [switch]$Passthru
    )

    process {
        $Instance = Resolve-PrismServerName -Server $Server
        $SessionName = $Instance
        # Read cached metadata without Get-PrismSession: that function can refresh
        # sessions, which would hide a failed probe and restart discovery here.
        $savedSession = $null
        if (-not $Force.IsPresent -and -not $PSBoundParameters.ContainsKey('ApiVersion')) {
            try {
                $savedSession = $Global:PrismSessions[$SessionName]
                if (-not $savedSession) {
                    $cachedPath = Join-Path $PrismSessionsPath "$SessionName.json"
                    $savedSession = Read-PrismSessionCache -Path $cachedPath
                }
            } catch {
                $savedSession = $null
                Write-Verbose "No Prism Session found for [$Server]"
            }
        }

        $reuseSavedSession = $savedSession -and -not [string]::IsNullOrEmpty($savedSession.ApiVersion) -and
            $savedSession.PrismServer -eq $Instance -and
            $savedSession.PrismPort -eq $Port -and
            $savedSession.AllowInsecureSSL -eq $AllowInsecureSSL.IsPresent -and
            (-not $savedSession.ExpirationDate -or $savedSession.ExpirationDate.ToUniversalTime() -gt [datetime]::UtcNow)

        ## Create a session object for this new connection
        $NewPrismSession = if ($reuseSavedSession) { $savedSession } else {
            [PrismSession]::new($SessionName, $Instance, $Port, $AllowInsecureSSL.IsPresent)
        }

        ## Build the Basic Authorization header from the supplied credential
        $plainPair = '{0}:{1}' -f $Credential.UserName, $Credential.GetNetworkCredential().Password
        $basicToken = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($plainPair))

        $RequestHeaders = @{
            'Authorization' = $basicToken
            'Content-Type'  = 'application/json'
            'Accept'        = 'application/json'
            'Cache-Control' = 'no-cache'
        }

        $WebRequestSplat = @{
            Method                          = 'GET'
            Headers                         = $RequestHeaders
            SessionVariable                 = 'PrismWebSession'
            PreserveAuthorizationOnRedirect = $true
            ProgressAction                  = 'SilentlyContinue'
            SkipCertificateCheck            = $AllowInsecureSSL.IsPresent
            SkipHttpErrorCheck              = $true
            ErrorAction                     = 'Stop'
            TimeoutSec                      = 100
            Verbose                         = $false
        }

        ## Attempt Login
        if ($VerbosePreference -eq 'Continue') {
            Write-Host 'Logging into Prism Central instance [ ' -NoNewline
            Write-Host $Instance -ForegroundColor Cyan -NoNewline
            Write-Host ' ] as [ ' -NoNewline
            Write-Host $Credential.UserName -ForegroundColor Cyan -NoNewline
            Write-Host ' ]'
        }

        $discoverVersion = -not $PSBoundParameters.ContainsKey('ApiVersion') -and -not $reuseSavedSession
        if ($discoverVersion) {
            $candidateVersions = $script:ApiVersions
            Write-Warning "-ApiVersion not specified. Attempting to discover the API version using: $($candidateVersions -join ', ')."
        } elseif ($reuseSavedSession) {
            # Validate cached versions using the credentials from this invocation.
            $candidateVersions = @($savedSession.ApiVersion)
        } else {
            $candidateVersions = @($ApiVersion)
        }

        $selectedVersion = $null
        foreach ($candidateVersion in $candidateVersions) {
            $validationPath = $script:PrismValidationPath -f $candidateVersion
            $WebRequestSplat.Uri = 'https://{0}:{1}/api/{2}' -f $Instance, $Port, $validationPath
            Write-Verbose "Checking Prism API version $candidateVersion on [$Instance]"
            try {
                # HTTP errors are handled below; communication failures terminate
                # immediately and must never trigger another version probe.
                $Response = Invoke-WebRequest @WebRequestSplat
            } catch {
                throw [System.InvalidOperationException]::new(
                    "Unable to communicate with Prism Central [$Instance] while checking API version $candidateVersion. API discovery stopped. $($_.Exception.Message)",
                    $_.Exception)
            }

            $statusCode = [int]$Response.StatusCode
            if ($statusCode -eq 200) {
                $selectedVersion = $candidateVersion
                break
            }
            if ($statusCode -eq 401) {
                throw "Prism Central [$Instance] rejected the supplied credentials (HTTP 401) at API version $candidateVersion. Discovery stopped; authentication may occur before API version validation."
            }
            if ($statusCode -eq 403) {
                throw "Prism Central [$Instance] denied access to the task endpoint (HTTP 403) at API version $candidateVersion. Check the supplied user's permissions. Discovery stopped; API version support could not be confirmed."
            }
            if ($statusCode -eq 404 -and $discoverVersion) {
                continue
            }
            throw "Prism Central [$Instance] returned HTTP $statusCode for API version $candidateVersion. No other API versions will be attempted."
        }
        if (-not $selectedVersion) {
            throw "No supported Prism task API endpoint found on [$Instance] for versions $($candidateVersions -join ', ') (all returned HTTP 404). Specify -ApiVersion explicitly."
        }

        ## Persist the Basic Authorization header so subsequent requests authenticate
        ## even after the IGW session cookie expires.
        $PrismWebSession.Headers['Authorization'] = $basicToken

        Write-Verbose ' NEW: Populating NewPrismSession'
        $NewPrismSession.PrismWebSession = $PrismWebSession
        $NewPrismSession.ApiVersion = $selectedVersion
        # Use the earliest expiry of the authentication session cookies returned
        # for this endpoint. Refresh tokens and unrelated cookies do not define
        # the session lifetime. CookieContainer parses Expires/Max-Age for us.
        $sessionCookieNames = @('NTNX_IAM_SESSION', 'NTNX_MERCURY_IAM_SESSION', 'NTNX_IGW_SESSION')
        $expiringSessionCookies = @($PrismWebSession.Cookies.GetCookies([uri]$WebRequestSplat.Uri) |
            Where-Object { $_.Name -in $sessionCookieNames -and $_.Expires -ne [datetime]::MinValue } |
            Sort-Object { $_.Expires.ToUniversalTime() })
        $NewPrismSession.ExpirationDate = if ($expiringSessionCookies.Count) {
            $expiringSessionCookies[0].Expires.ToUniversalTime()
        } else {
            # No server-provided expiry: rely on Test-PrismSession's API check.
            $null
        }

        $sessionPath = Join-Path -Path $PrismSessionsPath -ChildPath "$SessionName.json" -ErrorAction Stop
        $NewPrismSession | ConvertTo-Json -Depth 10 | Out-File -FilePath $sessionPath -Force
        Write-Verbose ' NEW: Exported NewPrismSession, adding to Global:PrismSessions'
        $Global:PrismSessions[$SessionName] = $NewPrismSession

        ## Return the session if requested
        if ($Passthru.IsPresent) {
            return $NewPrismSession
        }
    }
}

function Get-PrismSession {
    <#
    .SYNOPSIS
    Gets a PrismSession by Name, Server or ApiVersion.
 
    .PARAMETER Name
    One or more server/FQDN session names to get. Defaults to '*' to list all.
    An empty name selects the sole available session and throws if several exist.
 
    .PARAMETER Server
    One or more Prism Central servers for which a PrismSession has been created.
 
    .PARAMETER Credential
    The credential to use when a cached session needs to be refreshed.
 
    .PARAMETER ApiVersion
    One or more Prism API versions for which a PrismSession has been created.
 
    .PARAMETER PrismSession
    A PrismSession object to look up.
 
    .EXAMPLE
    Get-PrismSession -Name 'pc.lab.local'
 
    .EXAMPLE
    Get-PrismSession -Server '*.lab.local'
 
    .OUTPUTS
    One PrismSession, or an array of PrismSessions depending on the number of sessions
    to return.
    #>


    [CmdletBinding(DefaultParameterSetName = 'ByName')]
    param(
        [Parameter(
            Mandatory = $false,
            Position = 0,
            ParameterSetName = 'ByName',
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [Alias('SessionName')]
        [AllowNull()][AllowEmptyString()][string[]]$Name = '*',

        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'ByServer',
            ValueFromPipelineByPropertyName = $true)]
        [Parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [string]$Server,

        [Parameter(
            Mandatory = $false,
            ValueFromPipelineByPropertyName = $true)]
        [pscredential]$Credential,

        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'ByVersion',
            ValueFromPipelineByPropertyName = $true)]
        [string[]]$ApiVersion,

        [Parameter(
            Mandatory = $false,
            Position = 0,
            ParameterSetName = 'ByObject')]
        [PrismSession]$PrismSession
    )

    process {
        # Combine memory and disk metadata before selecting the requested server.
        # A missing selector is safe only when exactly one session is available.
        $sessions = @{}
        foreach ($session in $Global:PrismSessions.Values) {
            $sessions[$session.Name] = $session
        }
        foreach ($file in Get-ChildItem -LiteralPath $PrismSessionsPath -Filter '*.json' -File) {
            if ($sessions.ContainsKey($file.BaseName)) { continue }
            try {
                $session = Read-PrismSessionCache -Path $file.FullName
                if ($file.BaseName -ne $session.PrismServer) { continue }
                $sessions[$session.Name] = $session
            } catch {
                Write-Verbose "GET: Unable to read cached session [$($file.FullName)]: $_"
            }
        }

        $selectSingle = $PSCmdlet.ParameterSetName -eq 'ByName' -and
            ($Name.Count -eq 0 -or ($Name.Count -eq 1 -and [string]::IsNullOrWhiteSpace($Name[0])))
        $matches = @(switch ($PSCmdlet.ParameterSetName) {
            'ByObject' {
                $sessions.Values | Where-Object {
                    $_.Name -eq $PrismSession.Name -and
                    $_.PrismServer -eq $PrismSession.PrismServer -and
                    $_.ApiVersion -eq $PrismSession.ApiVersion
                }
            }
            'ByName' {
                $sessions.Values | Where-Object {
                    $sessionName = $_.Name
                    $selectSingle -or @($Name | Where-Object { $sessionName -like $_ }).Count -gt 0
                }
            }
            'ByServer' { $sessions.Values | Where-Object PrismServer -Like $Server }
            'ByVersion' {
                $sessions.Values | Where-Object {
                    $sessionApiVersion = $_.ApiVersion
                    @($ApiVersion | Where-Object { $sessionApiVersion -like $_ }).Count -gt 0
                }
            }
        })
        if ($selectSingle -and $matches.Count -gt 1) {
            throw 'Multiple Prism sessions are available. Specify the server/FQDN with -PrismSession (or -Name for Get-PrismSession).'
        }
        if ($matches.Count -eq 0) {
            $selectors = switch ($PSCmdlet.ParameterSetName) {
                'ByName' { $Name }
                'ByServer' { $Server }
                'ByVersion' { $ApiVersion }
            }
            if (@($selectors | Where-Object { [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($_) }).Count) { return }
            throw 'No matching Prism session was found. Use New-PrismSession to connect to the requested server.'
        }

        foreach ($session in $matches) {
            if (Test-PrismSession -PrismSession $session) {
                $Global:PrismSessions[$session.Name] = $session
                $session
                continue
            }

            $newSessionSplat = @{
                Server           = $session.PrismServer
                Port             = $session.PrismPort
                Credential       = $Credential
                AllowInsecureSSL = $session.AllowInsecureSSL
            }
            if (-not [string]::IsNullOrEmpty($session.ApiVersion)) {
                $newSessionSplat.ApiVersion = $session.ApiVersion
            }
            if (-not ($newSessionSplat.Credential -is [pscredential])) {
                $newSessionSplat.Credential = Get-StoredCredential -Name $session.PrismServer -ErrorAction Stop
            }

            $sessionPath = Join-Path $PrismSessionsPath "$($session.Name).json"
            $lockPath = Join-Path $PrismSessionsPath ('{0}_{1}.lock' -f $session.PrismServer, $session.PrismPort)
            $lock = $null
            try {
                $lock = Lock-FileMutex -Path $lockPath
                # Another process may have refreshed this server while we waited.
                if (Test-Path -LiteralPath $sessionPath) {
                    $retrySession = Read-PrismSessionCache -Path $sessionPath
                    if (Test-PrismSession -PrismSession $retrySession) {
                        $Global:PrismSessions[$retrySession.Name] = $retrySession
                        $retrySession
                        continue
                    }
                }
                New-PrismSession @newSessionSplat -Force -Passthru
            } finally {
                if ($lock) { $lock.Dispose() }
            }
        }
    }
}
function Test-PrismSession {
    <#
    .SYNOPSIS
    Tests whether a PrismSession is currently valid.
 
    .PARAMETER PrismSession
    The PrismSession to test.
 
    .PARAMETER Server
    Test with the Server name only (loads the matching session file from disk).
    Accepts a hostname, IP address, or HTTP/HTTPS URL and uses its lowercase host.
 
    .EXAMPLE
    Test-PrismSession -PrismSession (Get-PrismSession -Name 'pc.lab.local')
 
    .OUTPUTS
    [bool]
    #>


    [CmdletBinding()]
    param(
        [AllowNull()][Parameter(
            Mandatory = $false,
            Position = 0,
            ValueFromPipeline = $true,
            ParameterSetName = 'PrismSessionObject')]
        [pscustomobject]$PrismSession,

        [Parameter(
            Mandatory = $true,
            ParameterSetName = 'PrismSessionServer')]
        [string]$Server
    )

    process {
        if ($PSCmdlet.ParameterSetName -eq 'PrismSessionServer') {
            Write-Verbose ' TST: PSN=PrismSessionServer'
            $serverName = Resolve-PrismServerName -Server $Server
            $sessionPath = Join-Path -Path $PrismSessionsPath -ChildPath "$serverName.json"
            if (Test-Path -Path $sessionPath -ErrorAction SilentlyContinue) {
                $NewPrismSession = Read-PrismSessionCache -Path $sessionPath
                return Test-PrismSession -PrismSession $NewPrismSession
            } else {
                Write-Verbose ' TST: FALSE bc no sessionPath'
                return $false
            }
        }

        if ($null -eq $PrismSession) {
            Write-Verbose " TST: FALSE bc null = PrismSession"
            return $false
        }

        # Older caches have no selected API version and must be recreated.
        if ([string]::IsNullOrEmpty($PrismSession.ApiVersion)) {
            Write-Verbose ' TST: No ApiVersion in cached session'
            return $false
        }

        if ($PrismSession.PrismWebSession) {
            Write-Verbose " TST: Testing Prism Session [$($PrismSession.Name)] on server [$($PrismSession.PrismServer)]"
            $expirationDateTime = $PrismSession.ExpirationDate
            if ($expirationDateTime -and ([datetime]::UtcNow -ge $expirationDateTime.ToUniversalTime())) {
                Write-Verbose " TST: it is expired: expirationDate = $expirationDateTime"
                return $false
            }
            $testSplat = @{
                Method               = 'GET'
                Uri                  = 'https://{0}:{1}/api/{2}' -f $PrismSession.PrismServer, $PrismSession.PrismPort, ($script:PrismValidationPath -f $PrismSession.ApiVersion)
                WebSession           = $PrismSession.PrismWebSession
                SkipCertificateCheck = $PrismSession.AllowInsecureSSL
                StatusCodeVariable   = 'statusCode'
                ProgressAction       = 'SilentlyContinue'
                ErrorAction          = 'Stop'
                TimeoutSec           = 100
                Verbose              = $false
            }
            try {
                $null = Invoke-RestMethod @testSplat
                if ($statusCode -eq 200) {
                    Write-Verbose " TST: Prism Session [$($PrismSession.Name)] on server [$($PrismSession.PrismServer)] is valid"
                    return $true
                } else {
                    Write-Verbose " TST: Prism Session [$($PrismSession.Name)] is not valid, status code: $statusCode"
                    return $false
                }
            } catch {
                Write-Verbose " TST: Error: $_"
                return $false
            }
        } else {
            Write-Verbose " TST: No Prism Web Session found for server [$($PrismSession.PrismServer)]"
            return $false
        }
    }
}