From b63765a11de08117fe088fc4ddd2aa85440e525a Mon Sep 17 00:00:00 2001 From: Justin Grote Date: Sun, 22 Aug 2021 09:17:17 -0700 Subject: [PATCH] =?UTF-8?q?=E2=AC=86=EF=B8=8F=20SecretManagement=201.1.0?= =?UTF-8?q?=20Compatibility=20(#55)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SecretManagement 1.1.0 moves the vault extension into its own runspace and adds a new Unlock-SecretVault mechanism. This adds support for that new operating model. --- .config/RequiredModules.psd1 | 6 +- .github/workflows/press.yml | 40 ++--- PSModule.build.ps1 | 40 ++++- .../PoshKeePass/PoShKeePass.psm1 | 144 +++++++++--------- .../Public/Unlock-KeePassSecretVault.ps1 | 7 +- .../Private/VaultError.ps1 | 5 +- .../Public/Connect-KeepassDatabase.ps1 | 4 +- .../Public/Get-Secret.Tests.ps1 | 32 ++-- .../Public/Get-Secret.ps1 | 15 +- .../Public/Get-SecretInfo.ps1 | 16 +- .../Public/Remove-Secret.Tests.ps1 | 17 +-- .../Public/Remove-Secret.ps1 | 9 +- .../Public/Set-Secret.ps1 | 76 ++++++--- .../Public/Test-SecretVault.Tests.ps1 | 48 +++--- .../Public/Test-SecretVault.ps1 | 44 +++--- .../Public/Unlock-SecretVault.ps1 | 18 ++- .../Public/Unregister-SecretVault.ps1 | 2 +- .../SecretManagement.KeePass.Extension.psd1 | 5 +- .../SecretManagement.KeePass.Extension.psm1 | 3 - .../TestSecretVault-CommonTests.include.ps1 | 15 +- .../SecretManagement.KeePass.psd1 | Bin 3442 -> 3484 bytes .../Tests/SecretManagementVault.Tests.ps1 | 51 ++++--- 22 files changed, 342 insertions(+), 255 deletions(-) diff --git a/.config/RequiredModules.psd1 b/.config/RequiredModules.psd1 index f2f0353..21c53b9 100644 --- a/.config/RequiredModules.psd1 +++ b/.config/RequiredModules.psd1 @@ -1,3 +1,5 @@ @{ - 'Microsoft.Powershell.SecretManagement' = '1.0.0' -} \ No newline at end of file + 'Microsoft.Powershell.SecretManagement' = '1.1.0' + 'PowerConfig' = '0.1.3' + 'PSFramework' = '1.6.205' +} diff --git a/.github/workflows/press.yml b/.github/workflows/press.yml index ddddf00..26650f9 100644 --- a/.github/workflows/press.yml +++ b/.github/workflows/press.yml @@ -9,8 +9,8 @@ on: - production tags: - '*' - release: - types: + release: + types: - published pull_request: branches: @@ -46,7 +46,7 @@ jobs: ~/.local/share/Press ~/AppData/Local/Press ~/.nuget/packages/gitversion.tool - key: build-${{ hashFiles('Source/.config/Requirements.psd1') }} + key: build-${{ hashFiles('.config/RequiredModules.psd1') }} - if: steps.debugStatus.outputs.stepDebug name: ๐Ÿ”ฌ Powershell Environment Information @@ -93,7 +93,7 @@ jobs: - if: always() && runner.os != 'Windows' && steps.debugStatus.outputs.runnerDebug name: ๐Ÿ› Debug via SSH if ACTIONS_RUNNER_DEBUG secret is set uses: lhotari/action-upterm@v1 - + #TODO: Move to dedicated function - name: ๐Ÿ“ฆ Update Draft Github Release if: startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' || github.ref == 'refs/heads/ci' @@ -111,14 +111,14 @@ jobs: fail-fast: true matrix: os: - - ubuntu-latest + # - ubuntu-latest - ubuntu-20.04 - ubuntu-18.04 - - ubuntu-16.04 - - windows-latest + # - ubuntu-16.04 + # - windows-latest - windows-2019 - - windows-2016 - - macos-latest + # - windows-2016 + # - macos-latest - macos-11.0 - macos-10.15 steps: @@ -141,7 +141,6 @@ jobs: ~/.nuget/packages/gitversion.tool key: test-${{ matrix.os }}-${{ hashFiles('Source/.config/RequiredModules.psd1') }} - #Meta: We don't test on 5.1 for using the module - name: โž• Restore Built Powershell Module uses: actions/download-artifact@v2 with: @@ -149,7 +148,6 @@ jobs: #TODO: Pull this from environment setup path: BuildOutput/${{ github.event.repository.name }} - #TODO: Remove redundancy when https://github.com/actions/runner/issues/444 is implemented - name: ๐Ÿงช Test Powershell 7+ shell: pwsh run: | @@ -161,18 +159,6 @@ jobs: . ./build.ps1 'Test' - #Meta: We don't test on 5.1 for using the module for Press - # - if: runner.os == 'Windows' && github.repository != 'JustinGrote/Press' - # name: ๐Ÿงช Test Windows Powershell - # shell: powershell - # run: | - # if ('${{secrets.ACTIONS_STEP_DEBUG}}') {$verbosePreference = 'continue'} - # #Press Meta - # if ('${{ github.event.repository.name }}' -eq 'Press') { - # $GLOBAL:PressModulePath = Resolve-Path ./BuildOutput/Press/Press.psd1 - # } - # . ./build.ps1 'Test' - deployPrerelease: name: ๐Ÿš€ Deploy Prelease Module if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' @@ -192,7 +178,8 @@ jobs: shell: pwsh run: | if (-not '${{ secrets.PS_GALLERY_KEY }}') {throw 'You need to configure a PS_GALLERY_KEY secret for this environment with your Powershell Gallery API Key'} - Install-Module Microsoft.Powershell.SecretManagement -MinimumVersion 1.0.0 -Force + Install-Module Microsoft.Powershell.SecretManagement -RequiredVersion 1.1.0 -Force + Install-Module PSFramework -RequiredVersion 1.6.205 -Force -AllowClobber Publish-Module -Verbose -Name $PWD/BuildOutput/${{ github.event.repository.name }} -NugetApiKey ${{ secrets.PS_GALLERY_KEY }} deploy: @@ -214,5 +201,6 @@ jobs: shell: pwsh run: | if (-not '${{ secrets.PS_GALLERY_KEY }}') {throw 'You need to configure a PS_GALLERY_KEY secret for this environment with your Powershell Gallery API Key'} - Install-Module Microsoft.Powershell.SecretManagement -MinimumVersion 1.0.0 -Force - Publish-Module -Verbose -Name $PWD/BuildOutput/${{ github.event.repository.name }} -NugetApiKey ${{ secrets.PS_GALLERY_KEY }} \ No newline at end of file + Install-Module Microsoft.Powershell.SecretManagement -RequiredVersion 1.1.0 -Force + Install-Module PSFramework -RequiredVersion 1.6.205 -Force -AllowClobber + Publish-Module -Verbose -Name $PWD/BuildOutput/${{ github.event.repository.name }} -NugetApiKey ${{ secrets.PS_GALLERY_KEY }} diff --git a/PSModule.build.ps1 b/PSModule.build.ps1 index 9dd8839..f75e42c 100644 --- a/PSModule.build.ps1 +++ b/PSModule.build.ps1 @@ -1,15 +1,41 @@ + +if (-not (Get-Module PowerConfig -ErrorAction SilentlyContinue)) { + try { + Import-Module PowerConfig -ErrorAction Stop + } catch { + Install-Module PowerConfig -AllowPrerelease -Force + Import-Module PowerConfig -ErrorAction Stop + } +} if (-not (Get-Module Press -ErrorAction SilentlyContinue)) { try { Import-Module Press -ErrorAction Stop } catch { - Install-Module Press -AllowPrerelease -Force + Install-Module Press -Force Import-Module Press -ErrorAction Stop } } +if (-not (Get-Module 'Microsoft.Powershell.SecretManagement' -ErrorAction SilentlyContinue)) { + try { + Import-Module 'Microsoft.Powershell.SecretManagement' -ErrorAction Stop + } catch { + Install-Module 'Microsoft.Powershell.SecretManagement' -AllowPrerelease -RequiredVersion '1.1.0' -Force + Import-Module 'Microsoft.Powershell.SecretManagement' -ErrorAction Stop + } +} +if (-not (Get-Module 'PSFramework' -ErrorAction SilentlyContinue)) { + try { + Import-Module 'PSFramework' -ErrorAction Stop + } catch { + Install-Module 'PSFramework' -AllowPrerelease -RequiredVersion '1.6.205' -Force -AllowClobber + Import-Module 'PSFramework' -ErrorAction Stop + } +} + . Press.Tasks Task Press.CopyModuleFiles @{ - Inputs = { + Inputs = { Get-ChildItem -File -Recurse $PressSetting.General.SrcRootDir $SCRIPT:IncludeFiles = ( (Get-ChildItem -File -Recurse "$($PressSetting.General.SrcRootDir)\SecretManagement.KeePass.Extension") | @@ -17,9 +43,9 @@ Task Press.CopyModuleFiles @{ ) $IncludeFiles } - Outputs = { + Outputs = { $buildItems = Get-ChildItem -File -Recurse $PressSetting.Build.ModuleOutDir - if ($buildItems) { $buildItems } else { 'EmptyBuildOutputFolder' } + if ($buildItems) { $buildItems } else { 'EmptyBuildOutputFolder' } } Jobs = { Remove-BuildItem $PressSetting.Build.ModuleOutDir @@ -45,4 +71,8 @@ Task CopyPoshKeePass -After Press.CopyModuleFiles { Copy-Item $PKPExtensionPath -Recurse -Force -Exclude '*.Tests.ps1' -Destination $PressSetting.Build.ModuleOutDir -Container } -Task Package Press.Package.Zip \ No newline at end of file +Task Package Press.Package.Zip + +Task Press.Test.Pester.WindowsPowershell { + Write-Warning 'Windows Powershell Tests cannot currently be run due to a bug. Run the tests manually. Remove when https://github.com/pester/Pester/issues/1974 is closed' +} diff --git a/SecretManagement.KeePass/PoshKeePass/PoShKeePass.psm1 b/SecretManagement.KeePass/PoshKeePass/PoShKeePass.psm1 index b1959f9..6f4eb57 100644 --- a/SecretManagement.KeePass/PoshKeePass/PoShKeePass.psm1 +++ b/SecretManagement.KeePass/PoshKeePass/PoShKeePass.psm1 @@ -228,7 +228,7 @@ function Get-KeePassDatabaseConfiguration } else { - Write-Warning 'The specified KeePass Configuration does not exist.' + Write-PSFMessage -Level Warning 'The specified KeePass Configuration does not exist.' } } } @@ -383,7 +383,7 @@ function Get-KeePassGroup begin { if($AsPlainText) - { Write-Warning -Message 'The -AsPlainText switch parameter is deprecated and will be removed by end of year 2018!' } + { Write-PSFMessage -Level Warning -Message 'The -AsPlainText switch parameter is deprecated and will be removed by end of year 2018!' } } process { @@ -561,8 +561,8 @@ function New-KeePassDatabaseConfiguration { if($PSCmdlet.ParameterSetName -eq 'Network' -and -not $UseNetworkAccount) { - Write-Warning -Message '[BEGIN] Please Specify a valid Credential Combination.' - Write-Warning -Message '[BEGIN] You can not have a only a database file with no authentication options.' + Write-PSFMessage -Level Warning -Message '[BEGIN] Please Specify a valid Credential Combination.' + Write-PSFMessage -Level Warning -Message '[BEGIN] You can not have a only a database file with no authentication options.' Throw 'Please Specify a valid Credential Combination.' } } @@ -570,7 +570,7 @@ function New-KeePassDatabaseConfiguration { if (-not (Test-Path -Path $SCRIPT:KeePassConfigurationFile)) { - Write-Verbose -Message '[PROCESS] A KeePass Configuration File does not exist. One will be generated now.' + Write-PSFMessage -Level Verbose -Message '[PROCESS] A KeePass Configuration File does not exist. One will be generated now.' New-KPConfigurationFile } else @@ -580,7 +580,7 @@ function New-KeePassDatabaseConfiguration if($CheckIfProfileExists) { - Write-Warning -Message ('[PROCESS] A KeePass Database Configuration Profile Already exists with the specified name: {0}.' -f $DatabaseProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] A KeePass Database Configuration Profile Already exists with the specified name: {0}.' -f $DatabaseProfileName) Throw '[PROCESS] A KeePass Database Configuration Profile Already exists with the specified name: {0}.' -f $DatabaseProfileName } else @@ -643,8 +643,8 @@ function New-KeePassDatabaseConfiguration } catch { - Write-Warning -Message ('[PROCESS] An Exception Occured while trying to add a new KeePass database configuration ({0}) to the configuration file.' -f $DatabaseProfileName) - Write-Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) + Write-PSFMessage -Level Warning -Message ('[PROCESS] An Exception Occured while trying to add a new KeePass database configuration ({0}) to the configuration file.' -f $DatabaseProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) Throw $_ } } @@ -1137,7 +1137,7 @@ function New-KeePassPassword if(-not $PasswordProfileObject) { - Write-Error -Message ('No KPPasswordProfile could be found with the specified Name: ' + $PasswordProfileName) -TargetObject $PasswordProfileName -Category ObjectNotFound -ErrorAction Stop + Write-PSFMessage -Level Error -Message ('No KPPasswordProfile could be found with the specified Name: ' + $PasswordProfileName) -TargetObject $PasswordProfileName -Category ObjectNotFound -ErrorAction Stop } $PassProfile.CharSet.Add($PasswordProfileObject.CharacterSet) @@ -1156,16 +1156,16 @@ function New-KeePassPassword ## Check if Password Generation was successful if($ResultMessage -ne 'Success') { - Write-Warning -Message '[PROCESS] Failure while attempting to generate a password with the specified settings or profile.' - Write-Warning -Message ('[PROCESS] Password Generation Failed with the Result Text: {0}.' -f $ResultMessage) + Write-PSFMessage -Level Warning -Message '[PROCESS] Failure while attempting to generate a password with the specified settings or profile.' + Write-PSFMessage -Level Warning -Message ('[PROCESS] Password Generation Failed with the Result Text: {0}.' -f $ResultMessage) if($ResultMessage -eq 'TooFewCharacters') { - Write-Warning -Message ('[PROCESS] Result Text {0}, typically means that you specified a length that is longer than the possible generated outcome.' -f $ResultMessage) + Write-PSFMessage -Level Warning -Message ('[PROCESS] Result Text {0}, typically means that you specified a length that is longer than the possible generated outcome.' -f $ResultMessage) $ExcludeCharacterCount = if($PassProfile.ExcludeCharacters){($PassProfile.ExcludeCharacters -split ',').Count}else{0} if($PassProfile.NoRepeatingCharacters -and $PassProfile.Length -gt ($PassProfile.CharSet.Size - $ExcludeCharacterCount)) { - Write-Warning -Message "[PROCESS] Checked for the invalid specification. `n`tSpecified Length: $($PassProfile.Length). `n`tCharacterSet Count: $($PassProfile.CharSet.Size). `n`tNo Repeating Characters is set to: $($PassProfile.NoRepeatingCharacters). `n`tExclude Character Count: $ExcludeCharacterCount." - Write-Warning -Message '[PROCESS] Specify More characters, shorten the length, remove the no repeating characters option, or removed excluded characters.' + Write-PSFMessage -Level Warning -Message "[PROCESS] Checked for the invalid specification. `n`tSpecified Length: $($PassProfile.Length). `n`tCharacterSet Count: $($PassProfile.CharSet.Size). `n`tNo Repeating Characters is set to: $($PassProfile.NoRepeatingCharacters). `n`tExclude Character Count: $ExcludeCharacterCount." + Write-PSFMessage -Level Warning -Message '[PROCESS] Specify More characters, shorten the length, remove the no repeating characters option, or removed excluded characters.' } } @@ -1186,8 +1186,8 @@ function New-KeePassPassword } catch { - Write-Warning -Message '[PROCESS] An exception occured while trying to convert the KeePassLib.Securtiy.ProtectedString to a SecureString.' - Write-Warning -Message ('[PROCESS] Exception Message: {0}' -f $_.Exception.Message) + Write-PSFMessage -Level Warning -Message '[PROCESS] An exception occured while trying to convert the KeePassLib.Securtiy.ProtectedString to a SecureString.' + Write-PSFMessage -Level Warning -Message ('[PROCESS] Exception Message: {0}' -f $_.Exception.Message) Throw $_ } } @@ -1238,8 +1238,8 @@ function Remove-KeePassDatabaseConfiguration } catch { - Write-Warning -Message ('[PROCESS] An exception occured while attempting to remove a KeePass Database Configuration Profile ({0}).' -f $DatabaseProfileName) - Write-Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) + Write-PSFMessage -Level Warning -Message ('[PROCESS] An exception occured while attempting to remove a KeePass Database Configuration Profile ({0}).' -f $DatabaseProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) Throw $_ } } @@ -1301,7 +1301,7 @@ function Remove-KeePassEntry $KPEntry = Get-KPEntry -KeePassConnection $KeePassConnectionObject -KeePassUuid $KeePassEntry.Uuid if(-not $KPEntry) { - Write-Warning -Message '[PROCESS] The Specified KeePass Entry does not exist or cannot be found.' + Write-PSFMessage -Level Warning -Message '[PROCESS] The Specified KeePass Entry does not exist or cannot be found.' Throw 'The Specified KeePass Entry does not exist or cannot be found.' } @@ -1381,8 +1381,8 @@ function Remove-KeePassGroup if($KeePassGroupObject.Count -gt 1) { - Write-Warning -Message '[PROCESS] Found more than one group with the same path, name and creation time. Stoping Removal.' - Write-Warning -Message ('[PROCESS] Found: ({0}) number of matching groups.' -f $KeePassGroupObject.Count) + Write-PSFMessage -Level Warning -Message '[PROCESS] Found more than one group with the same path, name and creation time. Stoping Removal.' + Write-PSFMessage -Level Warning -Message ('[PROCESS] Found: ({0}) number of matching groups.' -f $KeePassGroupObject.Count) Throw 'Found more than one group with the same path, name and creation time. Stoping Removal.' } @@ -1486,8 +1486,8 @@ function Update-KeePassDatabaseConfiguration { if($PSCmdlet.ParameterSetName -eq 'Network' -and -not $UseNetworkAccount) { - Write-Warning -Message '[BEGIN] Please Specify a valid Credential Combination.' - Write-Warning -Message '[BEGIN] You can not have only a database file with no authentication options.' + Write-PSFMessage -Level Warning -Message '[BEGIN] Please Specify a valid Credential Combination.' + Write-PSFMessage -Level Warning -Message '[BEGIN] You can not have only a database file with no authentication options.' throw 'Please Specify a valid Credential Combination.' } } @@ -1497,7 +1497,7 @@ function Update-KeePassDatabaseConfiguration if (-not (Test-Path -Path $SCRIPT:KeePassConfigurationFile)) { - Write-Verbose -Message '[PROCESS] A KeePass Configuration File does not exist. One will be generated now.' + Write-PSFMessage -Level Verbose -Message '[PROCESS] A KeePass Configuration File does not exist. One will be generated now.' New-KPConfigurationFile } else @@ -1507,7 +1507,7 @@ function Update-KeePassDatabaseConfiguration if(-not $CheckIfProfileExists) { - Write-Warning -Message ('[PROCESS] A KeePass Database Configuration Profile does not exists with the specified name: {0}.' -f $DatabaseProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] A KeePass Database Configuration Profile does not exists with the specified name: {0}.' -f $DatabaseProfileName) throw '[PROCESS] A KeePass Database Configuration Profile does not exists with the specified name: {0}.' -f $DatabaseProfileName } else @@ -1580,8 +1580,8 @@ function Update-KeePassDatabaseConfiguration } catch { - Write-Warning -Message ('[PROCESS] An Exception Occured while trying to add a new KeePass database configuration ({0}) to the configuration file.' -f $NewDatabaseProfileName) - Write-Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) + Write-PSFMessage -Level Warning -Message ('[PROCESS] An Exception Occured while trying to add a new KeePass database configuration ({0}) to the configuration file.' -f $NewDatabaseProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) Throw $_ } } @@ -1714,7 +1714,7 @@ function Update-KeePassEntry $KPEntry = Get-KPEntry -KeePassConnection $KeePassConnectionObject -KeePassUuid $KeePassEntry.Uuid if(-not $KPEntry) { - Write-Warning -Message '[PROCESS] The Specified KeePass Entry does not exist or cannot be found.' + Write-PSFMessage -Level Warning -Message '[PROCESS] The Specified KeePass Entry does not exist or cannot be found.' Throw 'The Specified KeePass Entry does not exist or cannot be found.' } @@ -1861,8 +1861,8 @@ function Update-KeePassGroup if($KeePassGroupObject.Count -gt 1) { - Write-Warning -Message '[PROCESS] Found more than one group with the same path, name and creation time. Stoping Update.' - Write-Warning -Message ('[PROCESS] Found: ({0}) number of matching groups' -f $KeePassGroupObject.Count) + Write-PSFMessage -Level Warning -Message '[PROCESS] Found more than one group with the same path, name and creation time. Stoping Update.' + Write-PSFMessage -Level Warning -Message ('[PROCESS] Found: ({0}) number of matching groups' -f $KeePassGroupObject.Count) Throw 'Found more than one group with the same path, name and creation time.' } @@ -1971,8 +1971,8 @@ function Add-KPEntry } catch { - Write-Warning -Message '[BEGIN] An error occured while creating a new KeePassLib.PwEntry Object.' - Write-Error -ErrorRecord $_ -ea Stop + Write-PSFMessage -Level Warning -Message '[BEGIN] An error occured while creating a new KeePassLib.PwEntry Object.' + Write-PSFMessage -Level Error -ErrorRecord $_ -ea Stop } } process @@ -2119,8 +2119,8 @@ function Add-KPGroup } catch { - Write-Warning -Message '[BEGIN] An error occured while creating a new KeePassLib.PwGroup Object.' - Write-Error -ErrorRecord $_ -ea Stop + Write-PSFMessage -Level Warning -Message '[BEGIN] An error occured while creating a new KeePassLib.PwGroup Object.' + Write-PSFMessage -Level Error -ErrorRecord $_ -ea Stop } } process @@ -2360,8 +2360,8 @@ function Get-KPGroup } catch { - Write-Warning -Message 'An error occured while getting a KeePassLib.PwGroup Object.' - Write-Error -ErrorRecord $_ -ea Stop + Write-PSFMessage -Level Warning -Message 'An error occured while getting a KeePassLib.PwGroup Object.' + Write-PSFMessage -Level Error -ErrorRecord $_ -ea Stop } } process @@ -2401,7 +2401,7 @@ function Get-KPGroup if($Stop -and $foundCount -eq 0) { - Write-Warning -Message ('[PROCESS] The Specified KeePass Entry Group Path ({0}) does not exist.' -f $KeePassGroupParentPath) + Write-PSFMessage -Level Warning -Message ('[PROCESS] The Specified KeePass Entry Group Path ({0}) does not exist.' -f $KeePassGroupParentPath) Throw 'The Specified KeePass Entry Group Path ({0}) does not exist.' -f $KeePassGroupParentPath } } @@ -2452,7 +2452,7 @@ function Get-KPPasswordProfile } else { - Write-Verbose 'No KeePass Configuration files exist, please create one to continue: New-KeePassDatabasConfiguration.' + Write-PSFMessage -Level Verbose 'No KeePass Configuration files exist, please create one to continue: New-KeePassDatabasConfiguration.' } } } @@ -2496,8 +2496,8 @@ function New-KPConfigurationFile { if((Test-Path -Path $SCRIPT:KeePassConfigurationFile) -and -not $Force) { - Write-Warning -Message '[PROCESS] A KeePass Configuration File already exists. Please rerun with -force to overwrite the existing configuration.' - Write-Error -Message 'A KeePass Configuration File already exists.' -ea Stop + Write-PSFMessage -Level Warning -Message '[PROCESS] A KeePass Configuration File already exists. Please rerun with -force to overwrite the existing configuration.' + Write-PSFMessage -Level Error -Message 'A KeePass Configuration File already exists.' -ea Stop } else { @@ -2523,8 +2523,8 @@ function New-KPConfigurationFile } catch { - Write-Warning -Message 'An exception occured while trying to create a new keepass configuration file.' - Write-Error -ErrorRecord $_ -ea Stop + Write-PSFMessage -Level Warning -Message 'An exception occured while trying to create a new keepass configuration file.' + Write-PSFMessage -Level Error -ErrorRecord $_ -ea Stop } } } @@ -2578,14 +2578,14 @@ function New-KPConnection } catch { - Write-Error -Message 'Unable to Create KeepassLib.PWDatabase to open a connection.' -Exception $_.Exception -ea Stop + Write-PSFMessage -Level Error -Message 'Unable to Create KeepassLib.PWDatabase to open a connection.' -Exception $_.Exception -ea Stop } $CompositeKey = New-Object -TypeName KeepassLib.Keys.CompositeKey if(($MasterKey -isnot [PSCredential]) -and ($MasterKey -isnot [SecureString]) -and $MasterKey) { - Write-Error -Message ('[PROCESS] The MasterKey of type: ({0}). Is not Supported Please supply a MasterKey of Types (SecureString or PSCredential).' -f $($MasterKey.GetType().Name)) -Category InvalidType -TargetObject $MasterKey -RecommendedAction 'Provide a MasterKey of Type PSCredential or SecureString' + Write-PSFMessage -Level Error -Message ('[PROCESS] The MasterKey of type: ({0}). Is not Supported Please supply a MasterKey of Types (SecureString or PSCredential).' -f $($MasterKey.GetType().Name)) -Category InvalidType -TargetObject $MasterKey -RecommendedAction 'Provide a MasterKey of Type PSCredential or SecureString' } if($PSCmdlet.ParameterSetName -eq 'Profile' -or $PSCmdlet.ParameterSetName -eq '__None') @@ -2635,7 +2635,7 @@ function New-KPConnection } catch { - Write-Warning ('Could not read the specfied Key file [{0}].' -f $KeyPathItem.FullName) + Write-PSFMessage -Level Warning ('Could not read the specfied Key file [{0}].' -f $KeyPathItem.FullName) } } @@ -2695,7 +2695,7 @@ function New-KPPasswordProfile $CheckIfExists = Get-KPPasswordProfile -PasswordProfileName $KeePassPasswordObject.ProfileName if($CheckIfExists) { - Write-Warning -Message ('[PROCESS] A Password Profile with the specified name ({0}) already exists.' -f $KeePassPasswordObject.ProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] A Password Profile with the specified name ({0}) already exists.' -f $KeePassPasswordObject.ProfileName) Throw 'A Password Profile with the specified name ({0}) already exists.' -f $KeePassPasswordObject.ProfileName } @@ -2734,7 +2734,7 @@ function New-KPPasswordProfile } else { - Write-Output 'No KeePass Database Configuration file exists. You can create one with the New-KeePassDatabaseConfiguration function.' + Write-PSFMessage -Level Host 'No KeePass Database Configuration file exists. You can create one with the New-KeePassDatabaseConfiguration function.' } } } @@ -2769,14 +2769,14 @@ function Remove-KPConnection } else { - Write-Warning -Message '[PROCESS] The KeePass Database Specified is already closed or does not exist.' - Write-Error -Message 'The KeePass Database Specified is already closed or does not exist.' -ea Stop + Write-PSFMessage -Level Warning -Message '[PROCESS] The KeePass Database Specified is already closed or does not exist.' + Write-PSFMessage -Level Error -Message 'The KeePass Database Specified is already closed or does not exist.' -ea Stop } } catch [Exception] { - Write-Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) - Write-Error -ErrorRecord $_ -ea Stop + Write-PSFMessage -Level Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) + Write-PSFMessage -Level Error -ErrorRecord $_ -ea Stop } } } @@ -2866,7 +2866,7 @@ function Remove-KPEntry $KeePassEntry.ParentGroup.Entries.Remove($KeePassEntry) > $null ## Save again $KeePassConnection.Save($null) - Write-Verbose -Message "[PROCESS] Group has been Recycled." + Write-PSFMessage -Level Verbose -Message "[PROCESS] Group has been Recycled." } else { @@ -2877,12 +2877,12 @@ function Remove-KPEntry if(-not $IsRemoved) { - Write-Warning -Message "[PROCESS] Unknown Error has occured. Failed to Remove Entry ($($EntryDisplayName))" + Write-PSFMessage -Level Warning -Message "[PROCESS] Unknown Error has occured. Failed to Remove Entry ($($EntryDisplayName))" Throw "Failed to Remove Entry $($EntryDisplayName)" } else { - Write-Verbose -Message "[PROCESS] Entry ($($EntryDisplayName)) has been Removed." + Write-PSFMessage -Level Verbose -Message "[PROCESS] Entry ($($EntryDisplayName)) has been Removed." $KeePassConnection.Save($null) } } @@ -2970,7 +2970,7 @@ function Remove-KPGroup $KeePassConnection.Save($null) $KeePassGroup.ParentGroup.Groups.Remove($KeePassGroup) > $null $KeePassConnection.Save($null) - Write-Verbose -Message '[PROCESS] Group has been Recycled.' + Write-PSFMessage -Level Verbose -Message '[PROCESS] Group has been Recycled.' } else { @@ -2980,12 +2980,12 @@ function Remove-KPGroup $IsRemoved = $KeePassGroup.ParentGroup.Groups.Remove($KeePassGroup) if(-not $IsRemoved) { - Write-Warning -Message ('[PROCESS] Unknown Error has occured. Failed to Remove Group ({0})' -f $KeePassGroup.GetFullPath('/', $true)) + Write-PSFMessage -Level Warning -Message ('[PROCESS] Unknown Error has occured. Failed to Remove Group ({0})' -f $KeePassGroup.GetFullPath('/', $true)) Throw 'Failed to Remove Group ({0})' -f $KeePassGroup.GetFullPath('/', $true) } else { - Write-Verbose -Message ('[PROCESS] Group ({0}) has been Removed.' -f $KeePassGroup.GetFullPath('/', $true)) + Write-PSFMessage -Level Verbose -Message ('[PROCESS] Group ({0}) has been Removed.' -f $KeePassGroup.GetFullPath('/', $true)) $KeePassConnection.Save($null) } } @@ -3029,7 +3029,7 @@ function Remove-KPPasswordProfile { if(-not (Test-Path -Path $SCRIPT:KeePassConfigurationFile)) { - Write-Verbose -Message '[PROCESS] A KeePass Configuration File does not exist.' + Write-PSFMessage -Level Verbose -Message '[PROCESS] A KeePass Configuration File does not exist.' } else { @@ -3044,8 +3044,8 @@ function Remove-KPPasswordProfile } catch [exception] { - Write-Warning -Message ('[PROCESS] An exception occured while attempting to remove a KeePass Password Profile ({0}).' -f $PasswordProfileName) - Write-Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) + Write-PSFMessage -Level Warning -Message ('[PROCESS] An exception occured while attempting to remove a KeePass Password Profile ({0}).' -f $PasswordProfileName) + Write-PSFMessage -Level Warning -Message ('[PROCESS] {0}' -f $_.Exception.Message) Throw $_ } } @@ -3076,20 +3076,20 @@ function Restore-KPConfigurationFile $ReturnStatus = $false $Path = Resolve-Path -Path ('{0}\..' -f $PSScriptRoot) - Write-Verbose -Message ('[PROCESS] Checking if there is a previous KeePassConfiguration.xml file to be loaded from: {0}.' -f $Path.Path ) + Write-PSFMessage -Level Verbose -Message ('[PROCESS] Checking if there is a previous KeePassConfiguration.xml file to be loaded from: {0}.' -f $Path.Path ) $PreviousVersion = ((Get-ChildItem $Path.Path).Name | Sort-Object -Descending | Select-Object -First 2)[1] - Write-Verbose -Message ('PreviousVersion: {0}.' -f $PreviousVersion) + Write-PSFMessage -Level Verbose -Message ('PreviousVersion: {0}.' -f $PreviousVersion) $PreviousVersionConfigurationFile = Resolve-Path -Path ('{0}\..\{1}\KeePassConfiguration.xml' -f $PSScriptRoot, $PreviousVersion) -ErrorAction SilentlyContinue -ErrorVariable GetPreviousConfigurationFileError if(-not $GetPreviousConfigurationFileError -and $PreviousVersion) { - Write-Verbose -Message ('[PROCESS] Copying last Configuration file from the previous version ({0}).' -f $PreviousVersion) + Write-PSFMessage -Level Verbose -Message ('[PROCESS] Copying last Configuration file from the previous version ({0}).' -f $PreviousVersion) Copy-Item -Path $PreviousVersionConfigurationFile -Destination "$PSScriptRoot" -ErrorAction SilentlyContinue -ErrorVariable RestorePreviousConfigurationFileError if($RestorePreviousConfigurationFileError) { - Write-Warning -Message '[PROCESS] Unable to restore previous KeePassConfiguration.xml file. You will need to copy your previous file from your previous module version folder or create a new one.' + Write-PSFMessage -Level Warning -Message '[PROCESS] Unable to restore previous KeePassConfiguration.xml file. You will need to copy your previous file from your previous module version folder or create a new one.' } else { @@ -3484,8 +3484,8 @@ function Test-KPConnection else { $false - Write-Warning -Message 'The KeePass Connection Sepcified is not open or does not exist.' - Write-Error -Message 'The KeePass Connection Sepcified is not open or does not exist.' -ea Stop + Write-PSFMessage -Level Warning -Message 'The KeePass Connection Sepcified is not open or does not exist.' + Write-PSFMessage -Level Error -Message 'The KeePass Connection Sepcified is not open or does not exist.' -ea Stop } } function Test-KPPasswordValue @@ -3513,9 +3513,9 @@ function Test-KPPasswordValue else { $false - Write-Warning -Message '[PROCESS] Please provide a KeePassPassword of Type SecureString or KeePassLib.Security.ProtectedString.' - Write-Warning -Message ('[PROCESS] The Value supplied ({0}) is of Type {1}.' -f $KeePassPassword, $KeePassPassword.GetType().Name) - Write-Error -Message 'Please provide a KeePassPassword of Type SecureString or KeePassLib.Security.ProtectedString.' -ea Stop + Write-PSFMessage -Level Warning -Message '[PROCESS] Please provide a KeePassPassword of Type SecureString or KeePassLib.Security.ProtectedString.' + Write-PSFMessage -Level Warning -Message ('[PROCESS] The Value supplied ({0}) is of Type {1}.' -f $KeePassPassword, $KeePassPassword.GetType().Name) + Write-PSFMessage -Level Error -Message 'Please provide a KeePassPassword of Type SecureString or KeePassLib.Security.ProtectedString.' -ea Stop } } @@ -3544,7 +3544,7 @@ Import-KPLibrary function Get-KeePassConfigFile { if (-not(Test-Path -Path $SCRIPT:KeePassConfigurationFile)) { - Write-Warning -Message '**IMPORTANT NOTE:** Please always keep an up-to-date backup of your keepass database files and key files if used.' + Write-PSFMessage -Level Warning -Message '**IMPORTANT NOTE:** Please always keep an up-to-date backup of your keepass database files and key files if used.' $Versions = ((Get-ChildItem "$PSScriptRoot\..").Name | Sort-Object -Descending) @@ -3556,10 +3556,10 @@ function Get-KeePassConfigFile { $CurrentVersion = $Versions[0] if($previousVersion -lt 2124) { - Write-Warning -Message ('**BREAKING CHANGES:** This new version of the module {0} contains BREAKING CHANGES, please review the changelog or readme for details!' -f $CurrentVersion) + Write-PSFMessage -Level Warning -Message ('**BREAKING CHANGES:** This new version of the module {0} contains BREAKING CHANGES, please review the changelog or readme for details!' -f $CurrentVersion) } - Write-Warning -Message 'This message will not show again on next import.' + Write-PSFMessage -Level Warning -Message 'This message will not show again on next import.' } } else diff --git a/SecretManagement.KeePass/Public/Unlock-KeePassSecretVault.ps1 b/SecretManagement.KeePass/Public/Unlock-KeePassSecretVault.ps1 index bc1ce8d..c903a3b 100644 --- a/SecretManagement.KeePass/Public/Unlock-KeePassSecretVault.ps1 +++ b/SecretManagement.KeePass/Public/Unlock-KeePassSecretVault.ps1 @@ -1,7 +1,7 @@ function Unlock-KeePassSecretVault { <# .SYNOPSIS - Enables the entry of a master password prior to vault activities for unattended scenarios. + Enables the entry of a master password prior to vault activities for unattended scenarios. If registering a vault for the first time unattended, be sure to use the -SkipValidate parameter of Register-KeepassSecretVault .EXAMPLE Get-SecretVault 'MyKeepassVault' | Unlock-KeePassSecretVault -Password $MySecureString @@ -12,6 +12,7 @@ function Unlock-KeePassSecretVault { [Parameter(Mandatory)][SecureString]$Password, [Parameter(Mandatory,ValueFromPipelineByPropertyName)][String]$Name ) - - Unlock-SecretVault -Password $Password -Name $Name + + Write-PSFMessage -Level Warning 'DEPRECATED: This command has been deprecated. Please use the SecretManagement command Unlock-SecretVault instead.' + Microsoft.PowerShell.SecretManagement\Unlock-SecretVault -Password $Password -Name $Name } \ No newline at end of file diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Private/VaultError.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Private/VaultError.ps1 index 8deccb7..2448cb8 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Private/VaultError.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Private/VaultError.ps1 @@ -5,7 +5,6 @@ function VaultError ([String]$Message) { #> #FIXME: Use regular errors if https://github.com/PowerShell/SecretManagement/issues/102 is resolved - $ErrorActionPreference = 'Continue' - Write-Error "Vault ${VaultName}: $Message" - $ErrorActionPreference = 'Stop' + Write-PSFMessage -Level Error "Vault ${VaultName}: $Message" + throw "Vault ${VaultName}: $Message" } \ No newline at end of file diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Connect-KeepassDatabase.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Connect-KeepassDatabase.ps1 index 5b07f99..322b5c1 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Connect-KeepassDatabase.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Connect-KeepassDatabase.ps1 @@ -29,7 +29,7 @@ function Connect-KeePassDatabase { $DBCompositeKey = [CompositeKey]::new() if (-not $MasterPassword -and -not $KeyPath -and -not $UseWindowsAccount) { - Write-Verbose "No vault authentication mechanisms specified. Assuming you wanted to prompt for the Master Password" + Write-PSFMessage -Level Verbose "No vault authentication mechanisms specified. Assuming you wanted to prompt for the Master Password" $UseMasterPassword = $true } @@ -69,7 +69,7 @@ function Connect-KeePassDatabase { Resolve-Path $KeyPath } } else { - Write-Verbose "A keepass key file was already found at $KeyPath. Reusing this key for safety. Please manually delete this key if you wish to use a new one" + Write-PSFMessage -Level Verbose "A keepass key file was already found at $KeyPath. Reusing this key for safety. Please manually delete this key if you wish to use a new one" } $resolvedKeyPath = Resolve-Path $KeyPath diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.Tests.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.Tests.ps1 index 513824e..df11c29 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.Tests.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.Tests.ps1 @@ -29,7 +29,9 @@ Describe 'Get-Secret' { BeforeAll { $SCRIPT:FunctionName = 'Get-Secret' } - + It 'has one parameter set' { + (Get-Command -Module $ExtModuleName -Name $FunctionName).ParameterSets.Count | Should -BeExactly 1 + } It 'has a parameter ""' { $allParameterNames = (Get-Command -Module $ExtModuleName -Name $FunctionName).Parameters.Keys $Name | Should -BeIn $AllParameterNames @@ -40,27 +42,23 @@ Describe 'Get-Secret' { ) It 'has the mandatory value of parameter "" set to ""' { - $testAttribute = ((Get-Command -Module $ExtModuleName -Name $FunctionName).Parameters[$Name].Attributes | + $testAttribute = ((Get-Command -Module $ExtModuleName -Name $FunctionName).Parameters[$Name].Attributes | Where-Object { $PSItem -is [System.Management.Automation.ParameterAttribute] }).Mandatory $testAttribute | Should -Be $Mandatory } -TestCases @( @{Name = 'Name'; Mandatory = $False } @{Name = 'VaultName'; Mandatory = $False } @{Name = 'AdditionalParameters'; Mandatory = $False } - ) + ) It 'has parameter of type ' { - ((Get-Command -Module $ExtModuleName -Name $FunctionName).Parameters[$Name].ParameterType) | + ((Get-Command -Module $ExtModuleName -Name $FunctionName).Parameters[$Name].ParameterType) | Should -BeExactly $Type } -TestCases @( @{Name = 'Name'; Type = 'string' } @{Name = 'VaultName'; Type = 'string' } @{Name = 'AdditionalParameters'; Type = 'hashtable' } ) - - It 'has one parameter set' { - (Get-Command -Module $ExtModuleName -Name $FunctionName).ParameterSets.Count | Should -BeExactly 1 - } } Context 'Get Secret information from MasterPassword protected KeePass' { @@ -84,7 +82,7 @@ Describe 'Get-Secret' { } It 'should return a for entry ' -Tag CurrentTest { - $Secret = Get-Secret @vaultParams -Name $SecretName + $Secret = Get-Secret @vaultParams -Name $SecretName $Secret | Should -BeOfType $PSType } -TestCases @( @{SecretName = 'New Entry 1';PSType = 'System.Management.Automation.PSCredential' } @@ -101,11 +99,11 @@ Describe 'Get-Secret' { ) It 'should throw when multiple secrets are returned' { - { . Get-Secret @vaultParams -Name 'double entry' 2>$null } | + { Get-Secret @vaultParams -Name 'double entry' -ErrorAction Stop } | Should -Throw -ExpectedMessage $DoubleEntryExceptionMessage } It 'should return nothing when entry is not found in the KeePass DB' { - . Get-Secret @vaultParams -Name 'not present' | Should -BeNullOrEmpty + Get-Secret @vaultParams -Name 'not present' | Should -BeNullOrEmpty } } @@ -142,17 +140,17 @@ Describe 'Get-Secret' { It 'should return for ' { $secretResult = Get-Secret @vaultParams -Name $SecretName $secretResult.UserName | Should -BeExactly $UserName - } -TestCases @( + } -TestCases @( @{SecretName = 'New Entry 1';UserName = 'myusername 1' } @{SecretName = 'New Entry 2';UserName = 'Some Administrator account' } ) It 'should throw when multiple secrets are returned' { - { Get-Secret @vaultParams -Name 'double entry' 2>$null } | + { Get-Secret @vaultParams -Name 'double entry' -ErrorAction Stop } | Should -Throw -ExpectedMessage $DoubleEntryExceptionMessage } It 'should return nothing when entry is not found in the KeePass DB' { - Get-Secret @vaultParams -Name 'not present' | + Get-Secret @vaultParams -Name 'not present' | Should -BeNullOrEmpty } } @@ -183,7 +181,7 @@ Describe 'Get-Secret' { } It 'should return a for entry ' { - $Secret = Get-Secret @vaultParams -Name $SecretName + $Secret = Get-Secret @vaultParams -Name $SecretName $Secret | Should -BeOfType $PSType } -TestCases @( @{SecretName = 'New Entry 1';PSType = 'System.Management.Automation.PSCredential' } @@ -200,10 +198,10 @@ Describe 'Get-Secret' { ) It 'should throw when multiple secrets are returned' { - { Get-Secret @vaultParams -Name 'double entry' 2>$null } | + { Get-Secret @vaultParams -Name 'double entry' -ErrorAction Stop } | Should -Throw -ExpectedMessage $DoubleEntryExceptionMessage } - + It 'should return nothing when entry is not found in the KeePass DB' { Get-Secret @vaultParams -Name 'not present' | Should -BeNullOrEmpty } diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.ps1 index a92e482..94bf4f5 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-Secret.ps1 @@ -5,24 +5,27 @@ function Get-Secret { [Alias('Vault')][string]$VaultName, [Alias('VaultParameters')][hashtable]$AdditionalParameters = (Get-SecretVault -Name $VaultName).VaultParameters ) - trap { - VaultError $PSItem - throw $PSItem - } if ($AdditionalParameters.Verbose) {$VerbosePreference = 'continue'} if (-not (Test-SecretVault -VaultName $vaultName -AdditionalParameters $AdditionalParameters)) { + Write-PSFMessage -Level Error 'There appears to be an issue with the vault (Test-SecretVault returned false)' throw 'There appears to be an issue with the vault (Test-SecretVault returned false)' } - if (-not $Name) {throw "You must specify a secret Name"} + if (-not $Name) { + Write-PSFMessage -Level Error 'You must specify a secret Name' + throw 'You must specify a secret Name' + } $KeepassParams = GetKeepassParams $VaultName $AdditionalParameters if ($Name) { $KeePassParams.Title = $Name } $keepassGetResult = Get-SecretInfo -Vault $vaultName -Filter $Name -AsKPPSObject - if ($keepassGetResult.count -gt 1) { throw "Multiple ambiguous entries found for $Name, please remove the duplicate entry or specify the full path of the secret" } + if ($keepassGetResult.count -gt 1) { + Write-PSFMessage -Level Error "Multiple ambiguous entries found for $Name, please remove the duplicate entry or specify the full path of the secret" + throw "Multiple ambiguous entries found for $Name, please remove the duplicate entry or specify the full path of the secret" + } $result = if (-not $keepassGetResult.Username) { $keepassGetResult.Password } else { diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-SecretInfo.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-SecretInfo.ps1 index 865bf9f..b8f670e 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-SecretInfo.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Get-SecretInfo.ps1 @@ -9,12 +9,10 @@ function Get-SecretInfo { [Switch]$AsKPPSObject ) if ($AdditionalParameters.Verbose) {$VerbosePreference = 'continue'} - trap { - VaultError $PSItem - throw $PSItem - } + if (-not (Test-SecretVault -VaultName $vaultName)) { - throw 'There appears to be an issue with the vault (Test-SecretVault returned false)' + Write-PSFMessage -Level Error 'There appears to be an issue with the vault (Test-SecretVault returned false)' + return $false } $KeepassParams = GetKeepassParams -VaultName $VaultName -AdditionalParameters $AdditionalParameters @@ -50,7 +48,7 @@ function Get-SecretInfo { if ($Filter) { $KeepassGetResult = $KeepassGetResult | Where-Object { (Get-KPSecretName $PSItem) -like $Filter - } + } } #Used by internal commands like Get-Secret @@ -60,7 +58,7 @@ function Get-SecretInfo { [Object[]]$secretInfoResult = $KeepassGetResult | Foreach-Object { if (-not $PSItem.Title) { - Write-Warning "Keepass Entry with blank title found at $($PSItem.FullPath). These are not currently supported and will be omitted" + Write-PSFMessage -Level Warning "Keepass Entry with blank title found at $($PSItem.FullPath). These are not currently supported and will be omitted" return } @@ -94,8 +92,8 @@ function Get-SecretInfo { [Object[]]$sortedInfoResult = $secretInfoResult | Sort-Object -Unique -Property Name if ($sortedInfoResult.count -lt $secretInfoResult.count) { $nonUniqueFilteredRecords = Compare-Object $sortedInfoResult $secretInfoResult -Property Name | Where-Object SideIndicator -eq '=>' - Write-Warning "Vault ${VaultName}: Entries with non-unique titles were detected, the duplicates were filtered out. $(if (-not $additionalParameters.ShowFullTitle) {'Consider adding the ShowFullTitle VaultParameter to your vault registration'})" - Write-Warning "Vault ${VaultName}: Filtered Non-Unique Titles: $($nonUniqueFilteredRecords.Name -join ', ')" + Write-PSFMessage -Level Error "Vault ${VaultName}: Entries with non-unique titles were detected, the duplicates were filtered out. $(if (-not $additionalParameters.ShowFullTitle) {'Consider adding the ShowFullTitle VaultParameter to your vault registration'})" + Write-PSFMessage -Level Error "Vault ${VaultName}: Filtered Non-Unique Titles: $($nonUniqueFilteredRecords.Name -join ', ')" } $sortedInfoResult } \ No newline at end of file diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.Tests.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.Tests.ps1 index ec9344e..aef3277 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.Tests.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.Tests.ps1 @@ -1,4 +1,3 @@ - Describe 'Remove-Secret' { BeforeAll { #Setup Testing Environment and mock calls to/from parent SecretManagement Module @@ -48,9 +47,9 @@ Describe 'Remove-Secret' { Name = $TestSecretName } } - + It 'Fails if name not specified' { - { Remove-Secret @vaultParams -Name $null} | + { Remove-Secret @vaultParams -Name $null } | Should -Throw -ErrorId 'ParameterArgumentValidationError*' } It 'Removes predefined secret' { @@ -59,13 +58,13 @@ Describe 'Remove-Secret' { } It 'Fails on removing already removed secret' { Remove-Secret @vaultParams -Name $TestSecretName - #TODO: Figure out this weird error behavior where stop doesnt send a terminating error - Remove-Secret @vaultParams -Name $TestSecretName -ErrorVariable err 2>$null - $err | Should -BeLike "Vault * No Keepass Entry named $TestSecretName found" + { + Remove-Secret @vaultParams -Name $TestSecretName -ErrorVariable err 2>$null + } | Should -Throw "Vault * No Keepass Entry named $TestSecretName found" } It 'Fails on duplicate secrets' { - #TODO: Figure out this weird error behavior where stop doesnt send a terminating error - Remove-Secret @vaultParams -Name 'Double Entry' -ErrorVariable err 2>$null - $err | Should -BeLike 'Vault * There are multiple entries*' + { + Remove-Secret @vaultParams -Name 'Double Entry' -ErrorVariable err 2>$null + } | Should -Throw 'Vault * There are multiple entries*' } } \ No newline at end of file diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.ps1 index 18cf948..524d622 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Remove-Secret.ps1 @@ -5,13 +5,10 @@ function Remove-Secret { [Alias('Vault')][string]$VaultName, [Alias('VaultParameters')][hashtable]$AdditionalParameters = (Get-SecretVault -Name $VaultName).VaultParameters ) - trap { - VaultError $PSItem - throw $PSItem - } if ($AdditionalParameters.Verbose) {$VerbosePreference = 'continue'} if (-not (Test-SecretVault -VaultName $vaultName)) { - throw 'There appears to be an issue with the vault (Test-SecretVault returned false)' + VaultError 'There appears to be an issue with the vault (Test-SecretVault returned false)' + return $false } $KeepassParams = GetKeepassParams $VaultName $AdditionalParameters @@ -20,7 +17,7 @@ function Remove-Secret { VaultError "There are multiple entries with the name $Name and Remove-Secret will not proceed for safety." return $false } - if (-not $GetKeePassResult) { + if (-not $GetKeePassResult) { VaultError "No Keepass Entry named $Name found" return $false } diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Set-Secret.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Set-Secret.ps1 index b73b3ac..c6daaee 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Set-Secret.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Set-Secret.ps1 @@ -7,27 +7,20 @@ function Set-Secret { [Alias('Vault')][string]$VaultName, [Alias('VaultParameters')][hashtable]$AdditionalParameters = (Get-SecretVault -Name $VaultName).VaultParameters ) - trap { - VaultError $PSItem - throw $PSItem - } - if ($AdditionalParameters.Verbose) {$VerbosePreference = 'continue'} + if ($AdditionalParameters.Verbose) { $VerbosePreference = 'continue' } - if (-not $Name) {throw [NotSupportedException]'The -Name parameter is mandatory for the KeePass vault'} - if (-not (Test-SecretVault -VaultName $vaultName)) { - throw throw 'There appears to be an issue with the vault (Test-SecretVault returned false)' + if (-not $Name) { + Write-PSFMessage -Level Error ([NotSupportedException]'The -Name parameter is mandatory for the KeePass vault') + return $false } - $KeepassParams = GetKeepassParams $VaultName $AdditionalParameters - - if (Get-SecretInfo -Name $Name -Vault $VaultName) { - Write-Warning "Vault ${VaultName}: A secret with the title $Name already exists. This vault currently does not support overwriting secrets. Please remove the secret with Remove-Secret first." + if (-not (Test-SecretVault -VaultName $vaultName)) { + Write-PSFMessage -Level Error 'There appears to be an issue with the vault (Test-SecretVault returned false)' return $false } + $KeepassParams = GetKeepassParams $VaultName $AdditionalParameters - #Set default group - #TODO: Support Creating Secrets with paths - $KeepassParams.KeePassGroup = (Get-Variable "VAULT_$VaultName").Value.RootGroup - + + switch ($Secret.GetType()) { ([String]) { $KeepassParams.Username = $null @@ -45,14 +38,57 @@ function Set-Secret { break } default { - throw [NotImplementedException]'This vault provider only accepts string, securestring, and PSCredential secrets' + Write-PSFMessage -Level Error ([NotImplementedException]'This vault provider only accepts string, securestring, and PSCredential secrets') + return $false } } - - $KPEntry = Add-KPEntry @KeepassParams -Title $Name -PassThru + + if (Get-SecretInfo -Name $Name -Vault $VaultName) { + Write-PSFMessage "Updating Keepass Entry" -Target $Name -Tag Update + + try { + # $KeepassEntry = Get-SecretInfo -Name $Name -Vault $VaultName -AsKPPSObject + # Need to get the original KPEntry Object for modification + $KeepassParamsGetKPEntry = GetKeepassParams $VaultName $AdditionalParameters + # ToDo Sherlock: Got an array but need just one Object + $KeepassResults = Get-KPEntry @KeepassParamsGetKPEntry -Title $Name + # $fullPathes = $KeepassResults|Foreach-Object { + # $path=$_.ParentGroup.GetFullPath('/', $true) + # $title = $_.Strings.ReadSafe('Title') + # "Title= $title; Fullpath= $Path;" + # } + # Write-PSFMessage -level Host -Tag Sherlock "fullPathes=$fullPathes" + if ($KeepassResults.count -gt 1){ + Write-PSFMessage -Level Error "Retrieved $($KeepassResults.count) Keepass-Entries, narrow down the criteria" + return + } + $KeepassEntry = $KeepassResults #[1] + # $KeepassEntry = Get-KPEntry -KeePassConnection $KeepassParams.KeepassConnection -Title $Title + Write-PSFMessage "Found KeepassEntry=$KeepassEntry" -Level Debug + # Write-PSFMessage "`$KeepassEntry.getType()=$($KeepassEntry.GetType())" -tag "Sherlock" + } + catch { + Write-PSFMessage -Level Error "Fehler bei Get-KPEntry, $_" + } + # Write-PSFMessage -Level Warning "Vault ${VaultName}: A secret with the title $Name already exists. This vault currently does not support overwriting secrets. Please remove the secret with Remove-Secret first." + # return $false + + $KPEntry = Set-KPEntry @KeepassParams -Title $Name -PassThru -KeePassEntry $KeepassEntry -Confirm:$False + + # Write-PSFMessage -Level Warning "Vault ${VaultName}: A secret with the title $Name already exists. This vault currently does not support overwriting secrets. Please remove the secret with Remove-Secret first." + # return $false + } + else { + #Set default group + #TODO: Support Creating Secrets with paths + Write-PSFMessage "Adding Keepass Entry" -Target $Name -Tag Add + $KeepassParams.KeePassGroup = (Get-Variable "VAULT_$VaultName").Value.RootGroup + $KPEntry = Add-KPEntry @KeepassParams -Title $Name -PassThru + } + #Save the changes immediately #TODO: Consider making this optional as a vault parameter $KeepassParams.KeepassConnection.Save($null) - + return [Bool]($KPEntry) } diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.Tests.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.Tests.ps1 index 4aef757..663862f 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.Tests.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.Tests.ps1 @@ -6,7 +6,7 @@ Describe 'Test-SecretVault' { #Remove SecretManagement Parent Module if Present Get-Module 'SecretManagement.KeePass' | Remove-Module -Force Get-Module 'Microsoft.Powershell.SecretManagement' | Remove-Module -Force - + $ExtensionModule = Import-Module "$PSScriptRoot/../*.psd1" -Force -PassThru $Mocks = Join-Path $PSScriptRoot '../Tests/Mocks' | Resolve-Path @@ -18,7 +18,7 @@ Describe 'Test-SecretVault' { Mock -ModuleName $ExtModuleName 'Get-SecretVault' { @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $vaultPath } @@ -32,6 +32,12 @@ Describe 'Test-SecretVault' { $FunctionName = 'Test-SecretVault' $ParameterCount = 2 } + + It 'has a parameter vaultname' { + $Name = 'vaultname' + $AllParameterNames = (Get-Command -Module $ExtModuleName -Name $FunctionName).Parameters.Keys + $Name | Should -BeIn $AllParameterNames + } It 'has a parameter ""' -TestCases @( @{Name = 'VaultName' } @{Name = 'AdditionalParameters' } @@ -68,7 +74,7 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeePassDatabaseFileName) -Destination $VaultPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $vaultPath } @@ -92,7 +98,7 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeePassDatabaseFileName) -Destination $VaultPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $vaultPath } @@ -115,9 +121,9 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeePassDatabaseFileName) -Destination $VaultPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ - Path = $vaultPath + Path = $vaultPath UseMasterPassword = $true } } @@ -138,16 +144,16 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeePassDatabaseFileName) -Destination $VaultPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ - Path = $vaultPath + Path = $vaultPath UseMasterPassword = $true } } Mock -Verifiable -ModuleName $ExtModuleName -CommandName 'Get-Credential' -MockWith { $VaultMasterKey } } - . $CommonTests -Invalid -Credential + . $CommonTests -Invalid -Credential } Context 'Validating with correct Keyfile' { @@ -163,9 +169,9 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ - Path = $vaultPath + Path = $vaultPath KeyPath = $KeyPath } } @@ -186,9 +192,9 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ - Path = $vaultPath + Path = $vaultPath KeyPath = $KeyPath } } @@ -209,9 +215,9 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ - Path = $vaultPath + Path = $vaultPath KeyPath = $KeyPath } } @@ -235,7 +241,7 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $VaultPath UseMasterPassword = $true @@ -262,7 +268,7 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $VaultPath UseMasterPassword = $true @@ -273,7 +279,7 @@ Describe 'Test-SecretVault' { . $CommonTests -Credential -Invalid } - + Context 'Validating with incorrect Keyfile and correct master password' { BeforeAll { $KeyFileName = 'TestdbKeyFile.key' @@ -290,7 +296,7 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $VaultPath UseMasterPassword = $true @@ -317,7 +323,7 @@ Describe 'Test-SecretVault' { Copy-Item -Path (Join-Path $Mocks $KeyFileName) -Destination $KeyPath $vaultParams = @{ - VaultName = $VaultName + VaultName = $VaultName VaultParameters = @{ Path = $VaultPath UseMasterPassword = $true @@ -327,4 +333,4 @@ Describe 'Test-SecretVault' { } . $CommonTests -Credential -Invalid } -} \ No newline at end of file +} diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.ps1 index c8344d3..58dee25 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Test-SecretVault.ps1 @@ -8,40 +8,45 @@ function Test-SecretVault { [Parameter(ValueFromPipelineByPropertyName)] [Alias('VaultParameters')][hashtable]$AdditionalParameters = (get-secretvault $VaultName).VaultParameters ) - trap { - VaultError $PSItem - return $false - } if ($AdditionalParameters.Verbose) {$VerbosePreference = 'continue'} - Write-Verbose "SecretManagement: Testing Vault ${VaultName}" + Write-PSFMessage -Level Verbose "SecretManagement: Testing Vault ${VaultName}" #TODO: Hash vault parameter settings and reset vault state if they change. May be a bug if user changes vault parameters in same session #Test if connection already open, no need to do further testing if so try { $DBConnection = (Get-Variable -Name "Vault_$VaultName" -Scope Script -ErrorAction Stop).Value - if (-not $DBConnection.isOpen) {throw 'Connection closed, starting a new connection'} + if (-not $DBConnection.isOpen) { + Write-PSFMessage -Level Error 'Connection closed, starting a new connection' + return $false + } if (Test-DBChanged $DBConnection) { $dbConnection.close() - throw 'Database file on disk has changed, starting a new connection' + Write-PSFMessage -Level Error 'Database file on disk has changed, starting a new connection' + return $false } - Write-Verbose "Vault ${VaultName}: Connection already open, using existing connection" + Write-PSFMessage -Level Verbose "Vault ${VaultName}: Connection already open, using existing connection" return $dbConnection.isOpen } catch { - Write-Verbose "${VaultName}: $PSItem" + Write-PSFMessage -Level Verbose "${VaultName}: $PSItem" } #Basic Sanity Checks - if (-not $VaultName) { throw 'Keepass: You must specify a Vault Name to test' } + if (-not $VaultName) { + Write-PSFMessage -Level Error 'Keepass: You must specify a Vault Name to test' + return $false + } if (-not $AdditionalParameters.Path) { #TODO: Create a default vault if path isn't supplied #TODO: Add ThrowUser to throw outside of module scope - throw "You must specify the Path vault parameter as a path to your KeePass Database" + Write-PSFMessage -Level Error 'You must specify the Path vault parameter as a path to your KeePass Database' + return $false } - + if (-not (Test-Path $AdditionalParameters.Path)) { - throw "Could not find the keepass database $($AdditionalParameters.Path). Please verify the file exists or re-register the vault" + Write-PSFMessage -Level Error "Could not find the keepass database $($AdditionalParameters.Path). Please verify the file exists or re-register the vault" + return $false } #3 Scenarios Supported: Master PW, Keyfile, PW + Keyfile @@ -54,11 +59,16 @@ function Test-SecretVault { [SecureString]$vaultMasterPassword = Get-Variable -Name "Vault_${VaultName}_MasterPassword" -ValueOnly -ErrorAction SilentlyContinue if ($vaultMasterPassword) { - Write-Verbose "Cached Master Password Found for $VaultName" + Write-PSFMessage -Level Verbose "Cached Master Password Found for $VaultName" $ConnectKPDBParams.MasterPassword = $vaultMasterPassword } - $DBConnection = Connect-KeePassDatabase @ConnectKPDBParams + try { + $DBConnection = Connect-KeePassDatabase @ConnectKPDBParams + } catch { + Write-PSFMessage -Level Error $PSItem + } + if ($DBConnection.IsOpen) { Set-Variable -Name "Vault_$VaultName" -Scope Script -Value $DBConnection @@ -66,7 +76,7 @@ function Test-SecretVault { } #If we get this far something went wrong - Write-Error "Unable to open connection to the database" + Write-PSFMessage -Level Error "Unable to open connection to the database" return $false # if (-not $AdditionalParameters.Keypath -or $AdditionalParameters.UseMasterKey) { @@ -74,7 +84,7 @@ function Test-SecretVault { # } # if (-not (Get-KeePassDatabaseConfiguration -DatabaseProfileName $VaultName)) { # New-KeePassDatabaseConfiguration @KeePassDBConfigParams - # Write-Verbose "Vault ${VaultName}: A PoshKeePass database configuration was not found but was created." + # Write-PSFMessage -Level Verbose "Vault ${VaultName}: A PoshKeePass database configuration was not found but was created." # return $true # } # try { diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unlock-SecretVault.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unlock-SecretVault.ps1 index 5aac2da..383a169 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unlock-SecretVault.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unlock-SecretVault.ps1 @@ -1,14 +1,24 @@ function Unlock-SecretVault { param ( [Parameter(Mandatory)][SecureString]$Password, - [Parameter(Mandatory)][String]$Name + [Parameter(Mandatory)][Alias('Vault')][Alias('Name')][String]$VaultName, + [Alias('VaultParameters')][hashtable]$AdditionalParameters ) - $vault = Get-SecretVault -Name $Name -ErrorAction Stop + Write-PSFMessage "Unlocking SecretVault $VaultName" + $vault = Get-SecretVault -Name $VaultName -ErrorAction Stop $vaultName = $vault.Name - if ($vault.ModuleName -ne 'SecretManagement.KeePass') {throw "$vaultName was found but is not a Keepass Vault."} + if ($vault.ModuleName -ne 'SecretManagement.KeePass') { + Write-PSFMessage -Level Error "$vaultName was found but is not a Keepass Vault." + return $false + } Set-Variable -Name "Vault_${vaultName}_MasterPassword" -Scope Script -Value $Password -Force #Force a reconnection Remove-Variable -Name "Vault_${vaultName}" -Scope Script -Force -ErrorAction SilentlyContinue - if (-not (Microsoft.Powershell.SecretManagement\Test-SecretVault -Name $vaultName)) {throw "${vaultName}: Failed to unlock the vault"} + if (-not (Test-SecretVault -Name $vaultName -AdditionalParameters $AdditionalParameters)) { + Write-PSFMessage -Level Error "${vaultName}: Failed to unlock the vault" + return $false + } + Write-PSFMessage "SecretVault $vault unlocked successfull" + return $true } \ No newline at end of file diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unregister-SecretVault.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unregister-SecretVault.ps1 index 5848c15..321e912 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unregister-SecretVault.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Public/Unregister-SecretVault.ps1 @@ -9,6 +9,6 @@ function Unregister-SecretVault { try { Remove-Variable -Name "Vault_$VaultName" -Scope Script -Force -ErrorAction Stop } catch [ItemNotFoundException] { - Write-Verbose "Vault ${VaultName}: Vault was not loaded at time of deregistration" + Write-PSFMessage -Level Verbose "Vault ${VaultName}: Vault was not loaded at time of deregistration" } } \ No newline at end of file diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psd1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psd1 index dfe5d06..6dc5ec1 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psd1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psd1 @@ -2,7 +2,10 @@ ModuleVersion = '0.9.1.3' RootModule = 'SecretManagement.KeePass.Extension.psm1' FunctionsToExport = @('Set-Secret','Get-Secret','Remove-Secret','Get-SecretInfo','Test-SecretVault','Unregister-SecretVault','Connect-KeepassDatabase','Unlock-SecretVault') - NestedModules = @( + RequiredModules = @( + @{ ModuleName = 'PSFramework'; ModuleVersion = '1.6.205' } + ) + NestedModules = @( '../PoshKeePass/PoShKeePass.psd1' ) } diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psm1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psm1 index 21cb459..331eb9d 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psm1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/SecretManagement.KeePass.Extension.psm1 @@ -1,9 +1,6 @@ using namespace Microsoft.PowerShell.SecretManagement -#Avoid unpredictable behavior from external $ErrorActionPreference -$ErrorActionPreference = 'Stop' - Get-ChildItem "$PSScriptRoot/Private" -Exclude "*.Tests.ps1" | Foreach-Object { . $PSItem.FullName } diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Tests/TestSecretVault-CommonTests.include.ps1 b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Tests/TestSecretVault-CommonTests.include.ps1 index 05295f8..bda5c8d 100644 --- a/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Tests/TestSecretVault-CommonTests.include.ps1 +++ b/SecretManagement.KeePass/SecretManagement.KeePass.Extension/Tests/TestSecretVault-CommonTests.include.ps1 @@ -8,7 +8,7 @@ It "should not have a vault variable by default" { { InModuleScope $ExtensionModule { param($vaultName) - Get-Variable "Vault_$vaultName" + Get-Variable "Vault_$vaultName" -ErrorAction 'Stop' } @{ vaultName = $vaultParams.VaultName } @@ -18,6 +18,7 @@ It "should not have a vault variable by default" { if (-not $Invalid) { if ($KeyFile) { It 'Should not request a credential' { + Set-ItResult -Skipped -Because 'Broken by SecretManagement 1.1.0 new runspace behavior' Test-SecretVault @vaultParams Should -Invoke -CommandName 'Get-Credential' -Exactly 0 -Scope Context } @@ -26,7 +27,6 @@ if (-not $Invalid) { if ($Credential) { It 'should request a credential on the first pass' { Mock -Verifiable -ModuleName $ExtModuleName -CommandName 'Get-Credential' -MockWith { $VaultMasterKey } - Test-SecretVault @vaultParams Should -ModuleName $ExtModuleName -Invoke -CommandName 'Get-Credential' -Exactly 1 -Scope Context } @@ -37,7 +37,7 @@ if (-not $Invalid) { } } - It "should have a Vault variable upon unlock" { + It 'should have a Vault variable upon unlock' { Test-SecretVault @vaultParams | Should -BeTrue $vaultVars = InModuleScope $ExtensionModule { (Get-Variable -Name Vault_*).Name @@ -45,17 +45,16 @@ if (-not $Invalid) { "Vault_$($vaultParams.VaultName)" | Should -BeIn $vaultVars } - It 'should return true' { + It 'should return true' { Test-SecretVault @vaultParams | Should -BeTrue } } else { It 'Detects Invalid Composite Key and does not set a vault variable' { + $infoString = Get-Module microsoft.powershell.secretmanagement | Format-Table | Out-String + Write-PSFMessage -Level Verbose -Message "$infoString" $result = Test-SecretVault @vaultParams -ErrorVariable myerr 2>$null - $myerr[-1] | Should -BeLike $KeePassMasterKeyError + $myerr[-2] | Should -BeLike $KeePassMasterKeyError $result | Should -BeFalse } } - - - diff --git a/SecretManagement.KeePass/SecretManagement.KeePass.psd1 b/SecretManagement.KeePass/SecretManagement.KeePass.psd1 index 3a3b3f79f3fafb7c671e856dbe1221cfa183031c..66cc85f3670b73140e13caa21621fe9ec4496eea 100644 GIT binary patch delta 109 zcmew)HAi|w5)-4z=47V5tdrMpa4oefk8*2irI)Mo_LY098J`8CJt&F46mFarR~ C9vV0R delta 73 zcmbOu{Yh#=5)-5G=47V5tdlQsNlez^$e8THD>7MzQ%%r-L65&1 + [String]$DuplicateSecretWarning = Set-Secret -Name $secretName -Vault $VaultName -Secret $secret -WarningAction Continue *>&1 [String]$DuplicateSecretWarning | Should -BeLike "*A secret with the title $secretName already exists*" } + It 'Should update an existing entry with Set-Secret' { + # Set-ItResult -Skipped -Because 'Broken by 1.1.0 - https://github.com/PowerShell/SecretManagement/issues/151' + $secretName="New-Secret ToBeUpdated" + $secretPassword = 'PesterPassword' + $secretPasswordAfterUpdate = 'PesterPasswordWasUpdated' + $secret = [PSCredential]::new('PesterUser',($secretPassword | ConvertTo-SecureString -AsPlainText -Force)) + Set-Secret -Name $secretName -Vault $VaultName -Secret $secret + Get-Secret -Name $secretName -Vault $VaultName | Should -Not -BeNullOrEmpty + + $secret = [PSCredential]::new('PesterUser', ($secretPasswordAfterUpdate | ConvertTo-SecureString -AsPlainText -Force)) + Set-Secret -Name $secretName -Vault $VaultName -Secret $secret + $secretAfterUpdate = Get-Secret -Name $secretName -Vault $VaultName + $secretAfterUpdate | Should -Not -BeNullOrEmpty + Write-PSFMessage "`$secretAfterUpdate=$($secretAfterUpdate.Username):$($secretAfterUpdate.GetNetworkCredential().password)" + $secretAfterUpdate.GetNetworkCredential().password | Should -Be $secretPasswordAfterUpdate + if ($secretAfterUpdate) { + } + # [String]$DuplicateSecretWarning = Set-Secret -Name $secretName -Vault $VaultName -Secret $secret -WarningAction Continue *>&1 + # [String]$DuplicateSecretWarning | Should -BeLike "*A secret with the title $secretName already exists*" + } It 'Register-SecretVault -AllowClobber' { $RegisterSecretVaultParams.VaultParameters.Pester = $true @@ -167,4 +178,4 @@ Describe 'SecretManagement.Keepass' { $newVault.VaultParameters.Pester | Should -BeTrue } } -} \ No newline at end of file +}