internal/functions/authentication/Get-VaultSecret.ps1
|
function Get-VaultSecret { <# .SYNOPSIS Retrieve a secret from Azure Key Vault. .DESCRIPTION Retrieve a secret from Azure Key Vault. Works for both certificates and secrets. Requires one of ... - An established connection with the module's Key Vault service (the service named by the setting PSMicrosoftEntraID.Settings.DefaultServiceAzureKeyVault, by default PSMicrosoftEntraID.AzureKeyVault). Its identity needs list and get on the secrets of the vault. It is tried first. - An established AZ session via Az.Accounts with the Az.KeyVault module present. Used when there is no such connection, when that connection got its own secret from Key Vault, or when its read fails. The Az modules are looked for only then. A secret that is not found (or has no enabled version) is a terminating error, never an empty client secret. When the module's connection and Az both fail, the error names both causes. .PARAMETER VaultName Name of the Vault to query. .PARAMETER SecretName Name of the Secret to retrieve. .PARAMETER Cmdlet The $PSCmdlet object of the caller, enabling errors to happen within the scope of the caller. Defaults to the current command's $PSCmdlet .EXAMPLE PS C:\> Get-VaultSecret -VaultName myvault -SecretName mysecret Retrieves the latest enabled version of mysecret from myvault #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] # Options = 'None': with regard to case. The default (IgnoreCase) folds U+212A (Kelvin sign), U+0131 and U+0130 # into the ASCII letters K and I, and the name becomes part of the host the token goes to. [ValidatePattern('\A[A-Za-z0-9-]{3,24}\z', Options = 'None')] [string] $VaultName, [Parameter(Mandatory = $true)] # The name becomes part of the request path: letters, digits and hyphens, as Key Vault names a secret. [ValidatePattern('\A[A-Za-z0-9-]{1,127}\z', Options = 'None')] [string] $SecretName, $Cmdlet = $PSCmdlet ) process { #region Via EntraAuth # The Key Vault service under the name it is registered and connected with (PSMicrosoftEntraID.AzureKeyVault # unless the setting names another); the bare name 'AzureKeyVault' is not a service of this module. [string] $vaultService = Get-PSFConfigValue -FullName 'PSMicrosoftEntraID.Settings.DefaultServiceAzureKeyVault' -Fallback 'PSMicrosoftEntraID.AzureKeyVault' $vaultToken = Get-EntraToken -Service $vaultService | Select-Object -First 1 # A Key Vault connection whose own secret lives in Key Vault (Type KeyVault) is not used: renewing it reads the # secret, which would ask for its header, which would renew it - without end. That read goes through Az. [bool] $ownSecretInVault = $vaultToken -and $vaultToken.Type -eq 'KeyVault' [bool] $readByModule = $false $moduleFailure = $null if ($vaultToken -and -not $ownSecretInVault) { # A failure here is no warning of its own: Az may still read the secret; when it does not, both failures are # named in the error of this function. try { $secretVersion = Invoke-EntraRequest -Service $vaultService -Path "secrets/$SecretName/versions" -VaultName $VaultName -ErrorAction Stop -WarningAction SilentlyContinue | Where-Object { $_.attributes.enabled } | Sort-Object { $_.attributes.created } -Descending | Select-Object -First 1 if (-not $secretVersion) { # The module's own text: marked safe, so the error that quotes it keeps it (MessageFor). $noVersion = [System.InvalidOperationException]::new("Secret '$SecretName' has no enabled version in vault '$VaultName'.") $noVersion.Data[[PSMicrosoftEntraID.Security.ErrorSanitizer]::SafeMessageKey] = $true throw $noVersion } # The secret bundle ({ value, id, attributes }) is read as it is and its value taken by name, so # this does not depend on how the request layer unwraps an answer. $secretBundle = Invoke-EntraRequest -Service $vaultService -Path $secretVersion.id -VaultName $VaultName -Raw -ErrorAction Stop -WarningAction SilentlyContinue $secretData = $secretBundle.value $readByModule = $true } catch { $moduleFailure = $_ } } if ($readByModule) { if ($secretVersion.contentType) { $secretBytes = [convert]::FromBase64String($secretData) $certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($secretBytes) [PSCustomObject]@{ Type = 'Certificate' Certificate = $certificate ClientSecret = $null } } else { [PSCustomObject]@{ Type = 'ClientSecret' Certificate = $null ClientSecret = $secretData | ConvertTo-SecureString -AsPlainText -Force } } return } #endregion Via EntraAuth #region Via Az.KeyVault # Az is asked only here: when there is no Key Vault connection, when that connection got its own secret from Key # Vault, or when its read failed. A read the module's connection serves does not depend on the Az modules, and # a Get-AzContext that throws (a broken Az installation) means "no Az session", not a failed read. # -Debug:$false -Verbose:$false: run with the caller's -Debug, the Az cmdlets write their requests to the debug stream. [bool] $azAvailable = $false try { $azAvailable = (Get-Module Az.Accounts -ListAvailable) -and (Get-Module Az.KeyVault -ListAvailable) -and (Get-AzContext -Debug:$false -Verbose:$false -ErrorAction Stop) } catch { $azAvailable = $false } # The module's connection may lack access to this vault (it needs list and get on secrets) while the Az # session has it, as before this path was used: then Az reads the secret. Without Az, the failure stands. if ($moduleFailure -and -not $azAvailable) { Invoke-TerminatingException -Cmdlet $Cmdlet -ErrorRecord $moduleFailure -Message "Failed to retrieve secret '$SecretName' from '$VaultName'! $([PSMicrosoftEntraID.Security.ErrorSanitizer]::MessageFor($moduleFailure.Exception))" } if ($azAvailable) { $secret = $null $azFailure = $null # -ErrorAction Stop: a non-terminating error of Az left $secret empty and an empty client secret went out. try { $secret = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -Debug:$false -Verbose:$false -ErrorAction Stop } # Az.KeyVault's error (Azure.RequestFailedException) carries the answer's body and headers in its message: # only the safe record goes on, and the original leaves $Error. catch { $azFailure = ConvertTo-EntraSafeErrorRecord -ErrorRecord $_ } # Az.KeyVault answers a secret that does not exist (or has no enabled version) with nothing, not with an error. [string] $azMessage = '' $category = [System.Management.Automation.ErrorCategory]::NotSpecified if ($azFailure) { $azMessage = [PSMicrosoftEntraID.Security.ErrorSanitizer]::MessageFor($azFailure.Exception) } elseif (-not $secret -or -not $secret.SecretValue) { $azMessage = (Get-PSFLocalizedString -Module 'PSMicrosoftEntraID' -Name 'Identity.KeyVault.SecretNotFound') -f $SecretName, $VaultName $category = [System.Management.Automation.ErrorCategory]::ObjectNotFound } if ($azMessage) { # Both reads failed: the caller sees why the module's connection could not read the secret, too. [string] $message = if ($moduleFailure) { (Get-PSFLocalizedString -Module 'PSMicrosoftEntraID' -Name 'Identity.KeyVault.BothFailed') -f $SecretName, $VaultName, [PSMicrosoftEntraID.Security.ErrorSanitizer]::MessageFor($moduleFailure.Exception), $azMessage } elseif ($azFailure) { "Error accessing the secret '$SecretName' from Vault '$VaultName'. $azMessage" } else { $azMessage } if ($azFailure) { Invoke-TerminatingException -Cmdlet $Cmdlet -ErrorRecord $azFailure -Message $message -Category $category } Invoke-TerminatingException -Cmdlet $Cmdlet -Message $message -Category $category } $type = 'Certificate' if (-not $secret.ContentType) { $type = 'ClientSecret' } $certificate = $null $clientSecret = $secret.SecretValue if ($type -eq 'Certificate') { $certString = [PSCredential]::New("irrelevant", $secret.SecretValue).GetNetworkCredential().Password $bytes = [convert]::FromBase64String($certString) $certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes) $clientSecret = $null } [PSCustomObject]@{ Type = $type Certificate = $certificate ClientSecret = $clientSecret } return } #endregion Via Az.KeyVault # The connection is there, so "not connected" would send the caller the wrong way. if ($ownSecretInVault) { Invoke-TerminatingException -Cmdlet $Cmdlet -Message ((Get-PSFLocalizedString -Module 'PSMicrosoftEntraID' -Name 'Identity.KeyVault.OwnSecret') -f $vaultService) -Category ConnectionError } Invoke-TerminatingException -Cmdlet $Cmdlet -Message "Not connected to azure yet! Either use 'Connect-PSMicrosoftEntraID -Service PSMicrosoftEntraID.AzureKeyVault' or 'Connect-AzAccount' before trying to connect via KeyVault!" -Category ConnectionError } } |