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' ## Get-PrismSession runs before every API request (often twice: once in the public ## wrapper and once in Invoke-PrismRequest). A session that Prism accepted within this ## many seconds is reused without sending another validation request. $script:PrismSessionValidationTtlSeconds = 60 ## After an inconclusive validation (throttling, server error, unreachable) the session ## is kept and not probed again for this many seconds, so a struggling server is not ## sent a validation request ahead of every API request. A 401 on a real request ## clears it (Invoke-PrismRequest), so an invalid session is still recovered. $script:PrismSessionInconclusiveCooldownSeconds = 15 ## Session name -> the WebSession last checked, when (UTC) and for how long the result ## is reused. Keyed to the WebSession instance, so a re-login (which creates a new ## WebSession) invalidates it. $script:PrismSessionValidations = @{} function Register-PrismSessionValidation { [CmdletBinding()] param( [Parameter(Mandatory)]$PrismSession, [int]$TtlSeconds = $script:PrismSessionValidationTtlSeconds ) if ([string]::IsNullOrEmpty($PrismSession.Name) -or -not $PrismSession.PrismWebSession) { return } $script:PrismSessionValidations[$PrismSession.Name] = [pscustomobject]@{ WebSession = $PrismSession.PrismWebSession ValidatedAt = [datetime]::UtcNow TtlSeconds = $TtlSeconds } } function Unregister-PrismSessionValidation { [CmdletBinding()] param([Parameter(Mandatory)]$PrismSession) if ([string]::IsNullOrEmpty($PrismSession.Name)) { return } $script:PrismSessionValidations.Remove($PrismSession.Name) } function Test-PrismSessionValidationCache { [CmdletBinding()] [OutputType([bool])] param([Parameter(Mandatory)]$PrismSession) if ([string]::IsNullOrEmpty($PrismSession.Name)) { return $false } $entry = $script:PrismSessionValidations[$PrismSession.Name] if (-not $entry -or -not [object]::ReferenceEquals($entry.WebSession, $PrismSession.PrismWebSession)) { return $false } $age = [datetime]::UtcNow - $entry.ValidatedAt return $age -ge [TimeSpan]::Zero -and $age.TotalSeconds -lt $entry.TtlSeconds } function Lock-FileMutex { [CmdletBinding()] param( [Parameter(Mandatory)] [string]$Path, [int]$TimeoutSeconds = 15, [Parameter(DontShow)][Nullable[DateTimeOffset]]$Deadline ) begin { Write-Verbose "LOCK: Attempting [$Path]" $stopWatch = [Diagnostics.Stopwatch]::StartNew() } process { while ($stopWatch.Elapsed -lt [TimeSpan]::FromSeconds($TimeoutSeconds)) { if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline } try { $fs = [IO.File]::Open( $Path, 'OpenOrCreate', 'ReadWrite', 'None' ) Write-Verbose "LOCK: Acquired [$Path]" return $fs } catch [IO.IOException] { Write-Verbose "LOCK: Busy, retrying..." $sleepMilliseconds = 88 if ($null -ne $Deadline) { $sleepMilliseconds = [math]::Min(88, [math]::Max(0, ($Deadline - [DateTimeOffset]::UtcNow).TotalMilliseconds)) } Start-Sleep -Milliseconds ([int]$sleepMilliseconds) } } 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, [Parameter(DontShow)][Nullable[DateTimeOffset]]$Deadline ) 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) { if ($null -ne $Deadline) { $WebRequestSplat.TimeoutSec = Get-PrismRequestTimeout -Deadline $Deadline } $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 { if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline -InnerException $_.Exception } throw [System.InvalidOperationException]::new( "Unable to communicate with Prism Central [$Instance] while checking API version $candidateVersion. API discovery stopped. $($_.Exception.Message)", $_.Exception) } if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline } $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 # The login request above just confirmed this WebSession. Register-PrismSessionValidation -PrismSession $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, [Parameter(DontShow)][Nullable[DateTimeOffset]]$Deadline ) process { $deadlineSplat = @{} if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline $deadlineSplat.Deadline = $Deadline } # 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) { # -ForRequest reuses a recent validation and re-logs in only when Prism # definitely rejects the session, not when it is throttled or unreachable. if (Test-PrismSession -PrismSession $session -ForRequest @deadlineSplat) { $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 @deadlineSplat # 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 -ForRequest @deadlineSplat) { $Global:PrismSessions[$retrySession.Name] = $retrySession $retrySession continue } } New-PrismSession @newSessionSplat @deadlineSplat -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. .PARAMETER ForRequest Internal; used by Get-PrismSession before API requests. Reuses a successful validation from the last $script:PrismSessionValidationTtlSeconds seconds for the same WebSession, and treats only HTTP 401, 403 or 404 as invalid. Throttling (429), server errors and connection failures keep the session, so the real request reports the problem instead of a re-login adding more requests; the session is then not probed again for $script:PrismSessionInconclusiveCooldownSeconds seconds. Without this switch, every call sends a validation request and any failure returns false. .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, [Parameter(DontShow)][Nullable[DateTimeOffset]]$Deadline, [Parameter(DontShow)][switch]$ForRequest ) process { $deadlineSplat = @{} if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline $deadlineSplat.Deadline = $Deadline } 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 -ForRequest:$ForRequest @deadlineSplat } 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" Unregister-PrismSessionValidation -PrismSession $PrismSession return $false } if ($ForRequest.IsPresent -and (Test-PrismSessionValidationCache -PrismSession $PrismSession)) { Write-Verbose " TST: Prism Session [$($PrismSession.Name)] was validated recently; skipping the API check" return $true } $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 } if ($null -ne $Deadline) { $testSplat.TimeoutSec = Get-PrismRequestTimeout -Deadline $Deadline } $failure = $null $failureStatus = $null try { $null = Invoke-RestMethod @testSplat if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline } if ($statusCode -eq 200) { Write-Verbose " TST: Prism Session [$($PrismSession.Name)] on server [$($PrismSession.PrismServer)] is valid" Register-PrismSessionValidation -PrismSession $PrismSession return $true } $failureStatus = $statusCode $failure = "status code: $statusCode" } catch { if ($null -ne $Deadline) { $null = Get-PrismRequestTimeout -Deadline $Deadline -InnerException $_.Exception } # HTTP errors carry the response; connection failures do not. $response = $_.Exception.Response if ($response -and $response.StatusCode) { $failureStatus = [int]$response.StatusCode } $failure = "Error: $_" } if ($ForRequest.IsPresent -and $failureStatus -notin 401, 403, 404) { # Not a definite rejection (throttled, server error or unreachable). # Keep the session and let the real request report the problem; a # re-login would only add requests. Skip probing again for a short # cooldown so each API request does not repeat this check. Write-Verbose " TST: Keeping Prism Session [$($PrismSession.Name)] despite inconclusive validation ($failure)" Register-PrismSessionValidation -PrismSession $PrismSession -TtlSeconds $script:PrismSessionInconclusiveCooldownSeconds return $true } Write-Verbose " TST: Prism Session [$($PrismSession.Name)] is not valid, $failure" Unregister-PrismSessionValidation -PrismSession $PrismSession return $false } else { Write-Verbose " TST: No Prism Web Session found for server [$($PrismSession.PrismServer)]" return $false } } } |