ps/Modules/Alkami.PowerShell.Common/Public/Get-SecureString.tests.ps1

54 lines
2.4 KiB
PowerShell
Raw Normal View History

2023-05-30 22:51:22 -07:00
. $PSScriptRoot\..\..\Load-PesterModules.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.tests\.', '.'
$functionPath = Join-Path -Path $here -ChildPath $sut
Write-Host "Overriding SUT: $functionPath"
Import-Module $functionPath -Force
$moduleForMock = ""
## https://stackoverflow.com/questions/4502676/c-sharp-compare-two-securestrings-for-equality
## SecureStringToBSTR has a SecurityCriticalAttribute so it requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.
## https://referencesource.microsoft.com/#mscorlib/system/security/attributes.cs,29a3d687a50338b1
function Compare-TwoSecureStrings($secureString1, $secureString2)
{
$bstr1 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString1);
$bstr2 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString2);
$result = $false;
try
{
$tValue1 = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr1)
$tValue2 = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr2)
## This function can literally deconvert passwords, use this knowledge with extreme care
## Write-Host $tValue1
## Write-Host $tValue2
$result = $tValue1 -eq $tValue2
}
finally
{
[Runtime.InteropServices.Marshal]::FreeBSTR($bstr1);
[Runtime.InteropServices.Marshal]::FreeBSTR($bstr2);
}
return $result
}
Describe 'Get-SecureString' {
Context 'Ensure value returned matches default implementation' {
It 'Use naive password "password"' {
$defaultString = "password"
$builtinValue = ConvertTo-SecureString -String $defaultString -AsPlainText -Force
$testValue = Get-SecureString -String $defaultString
$testResult = (Compare-TwoSecureStrings $builtinValue $testValue)
$testResult | Should -Be $true
}
It 'Use two different passwords to ensure this is broken when doing so' {
$defaultString1 = "password1"
$defaultString2 = "password2"
$builtinValue = ConvertTo-SecureString -String $defaultString1 -AsPlainText -Force
$testValue = Get-SecureString -String $defaultString2
$testResult = (Compare-TwoSecureStrings $builtinValue $testValue)
$testResult | Should -Be $false
}
}
}