From 2fe1e520b025c995cfcdd9302ba3e88c02251e68 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Wed, 26 Jun 2024 14:50:17 -0400 Subject: [PATCH 01/10] Remove unneeded usage of `dynamic` --- src/code/Utils.cs | 103 +++++++++++++++++++++++++++++----------------- 1 file changed, 65 insertions(+), 38 deletions(-) diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 21f54b2..8e7498b 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -118,13 +118,13 @@ public static SecureString ConvertToSecureString(string secret) script: @"param([string] $value) Microsoft.PowerShell.Security\ConvertTo-SecureString -String $value -AsPlainText -Force", args: new object[] { secret }, error: out ErrorRecord _); - + return (results.Count > 0) ? results[0] : null; } public static string GetModuleExtensionName(string moduleName) { - return string.Format(CultureInfo.InvariantCulture, + return string.Format(CultureInfo.InvariantCulture, @"{0}.{1}", moduleName, ImplementingExtension); } @@ -204,13 +204,13 @@ public PasswordRequiredException(string msg) public sealed class SecretInformation { #region Properties - + /// /// Gets the name of the secret. /// public string Name { - get; + get; } /// @@ -351,7 +351,7 @@ internal class ExtensionVaultModule [string] $Command, [hashtable] $Params ) - + $verboseEnabled = $Params.AdditionalParameters.ContainsKey('Verbose') -and ($Params.AdditionalParameters['Verbose'] -eq $true) $module = Microsoft.PowerShell.Core\Get-Module -Name $ModuleName -ErrorAction Ignore if ($null -eq $module) { @@ -381,7 +381,7 @@ internal class ExtensionVaultModule [string] $Command, [hashtable] $Params ) - + $verboseEnabled = $Params.AdditionalParameters.ContainsKey('Verbose') -and ($Params.AdditionalParameters['Verbose'] -eq $true) $module = Microsoft.PowerShell.Core\Get-Module -Name $ModuleName -ErrorAction Ignore if ($null -eq $module) { @@ -415,7 +415,7 @@ internal class ExtensionVaultModule internal const string VaultParametersStr = "VaultParameters"; internal const string DescriptionStr = "Description"; internal const string SetSecretSupportsMetadataStr = "SetSecretSupportsMetadata"; - + #endregion #region Properties @@ -464,7 +464,7 @@ internal class ExtensionVaultModule #region Constructor - private ExtensionVaultModule() + private ExtensionVaultModule() { } @@ -483,7 +483,7 @@ public ExtensionVaultModule( ModuleExtensionName = Utils.GetModuleExtensionName(ModuleName); ModulePath = (string) vaultInfo[ModulePathStr]; Description = vaultInfo.ContainsKey(DescriptionStr) ? (string) vaultInfo[DescriptionStr] : string.Empty; - SetSecretSupportsMetadata = vaultInfo.ContainsKey(SetSecretSupportsMetadataStr) ? + SetSecretSupportsMetadata = vaultInfo.ContainsKey(SetSecretSupportsMetadataStr) ? (bool) vaultInfo[SetSecretSupportsMetadataStr] : false; // Additional parameters. @@ -557,7 +557,7 @@ public void InvokeSetSecret( script: RunCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, SetSecretCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -574,7 +574,7 @@ public void InvokeSetSecret( return; } - // If metadata is provided but not supported through Set-Secret parameter, then attempt to call + // If metadata is provided but not supported through Set-Secret parameter, then attempt to call // the separate vault Set-SecretInfo function as an alternative. if (metadata?.Count > 0 && !SetSecretSupportsMetadata && !InvokeSetSecretMetadata( @@ -589,10 +589,10 @@ public void InvokeSetSecret( name: name, vaultName: vaultName, cmdlet: cmdlet); - + return; } - + cmdlet.WriteVerbose( string.Format(CultureInfo.InvariantCulture, "Secret {0} was successfully added to vault {1}.", name, VaultName)); } @@ -618,7 +618,7 @@ public bool InvokeUnlockSecretVault( script: RunConditionalCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, UnlockVaultCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -647,7 +647,7 @@ public bool InvokeUnlockSecretVault( cmdlet.WriteError( new ErrorRecord( new PSInvalidOperationException( - message: string.Format(CultureInfo.InvariantCulture, "Cannot unlock extension vault '{0}': Extension module could not load.", + message: string.Format(CultureInfo.InvariantCulture, "Cannot unlock extension vault '{0}': Extension module could not load.", vaultName)), "UnlockSecretVaultCommandModuleLoadFail", ErrorCategory.InvalidOperation, @@ -656,7 +656,7 @@ public bool InvokeUnlockSecretVault( case 2: cmdlet.WriteWarning( - string.Format(CultureInfo.InvariantCulture, + string.Format(CultureInfo.InvariantCulture, "Cannot unlock extension vault '{0}': The vault does not support the Unlock-SecretVault function.", vaultName)); break; @@ -688,7 +688,7 @@ public bool InvokeSetSecretMetadata( script: RunConditionalCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, SetSecretInfoCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -717,7 +717,7 @@ public bool InvokeSetSecretMetadata( cmdlet.WriteError( new ErrorRecord( new PSInvalidOperationException( - message: string.Format(CultureInfo.InvariantCulture, "Cannot add secret metadata '{0}' to vault '{1}': Extension module could not load.", + message: string.Format(CultureInfo.InvariantCulture, "Cannot add secret metadata '{0}' to vault '{1}': Extension module could not load.", name, VaultName)), "SetSecretMetaDataCommandModuleLoadFail", ErrorCategory.InvalidOperation, @@ -728,7 +728,7 @@ public bool InvokeSetSecretMetadata( cmdlet.WriteError( new ErrorRecord( new PSNotSupportedException( - message: string.Format(CultureInfo.InvariantCulture, "Cannot add secret metadata '{0}' to vault '{1}: The vault does not support the Set-SecretInfo function.", + message: string.Format(CultureInfo.InvariantCulture, "Cannot add secret metadata '{0}' to vault '{1}: The vault does not support the Set-SecretInfo function.", name, VaultName)), "SetSecretMetadataCommandNotSupported", ErrorCategory.NotImplemented, @@ -760,7 +760,7 @@ public object InvokeGetSecret( script: RunCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, GetSecretCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -824,7 +824,7 @@ public object InvokeGetSecret( case Hashtable hashTableValue: return hashTableValue; - + default: cmdlet.WriteError( new ErrorRecord( @@ -904,7 +904,7 @@ public SecretInformation[] InvokeGetSecretInfo( script: RunCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, GetSecretInfoCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -979,7 +979,7 @@ public void InvokeUnregisterVault( script: RunIfCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, UnregisterSecretVaultCommand, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -987,7 +987,7 @@ public void InvokeUnregisterVault( cmdlet.WriteError( new ErrorRecord( new PSInvalidOperationException( - message: string.Format(CultureInfo.InvariantCulture, "An error occurred while running Unregister-SecretVault on vault {0}, Error: {1}", + message: string.Format(CultureInfo.InvariantCulture, "An error occurred while running Unregister-SecretVault on vault {0}, Error: {1}", VaultName, terminatingError.Message), innerException: terminatingError), "UnregisterSecretVaultInvalidOperation", @@ -1003,7 +1003,7 @@ public ExtensionVaultModule Clone() { return new ExtensionVaultModule(this); } - + #endregion #region Private methods @@ -1027,17 +1027,44 @@ private Hashtable GetAdditionalParams(PSCmdlet cmdlet) value: item.Value); } - bool verboseEnabled = cmdlet.MyInvocation.BoundParameters.TryGetValue("Verbose", out dynamic verbose) - ? verbose.IsPresent : false; + bool verboseEnabled = cmdlet.MyInvocation.BoundParameters.TryGetValue("Verbose", out object verbose) + ? GetPropertyValue(verbose, nameof(SwitchParameter.IsPresent), false) + : false; + if (additionalParams.ContainsKey("Verbose")) { additionalParams.Remove("Verbose"); } + additionalParams.Add("Verbose", verboseEnabled); return additionalParams; } + private static T GetPropertyValue(object value, string propertyName, T defaultValue = default) + { + if (value is null) + { + return defaultValue; + } + + PSObject pso = PSObject.AsPSObject(value); + PSPropertyInfo property = pso.Properties[propertyName]; + if (property is null) + { + return defaultValue; + } + + try + { + return LanguagePrimitives.ConvertTo(property.Value); + } + catch + { + return defaultValue; + } + } + #endregion } @@ -1073,7 +1100,7 @@ internal static class RegisteredVaultCache /// public static SortedDictionary VaultExtensions { - get + get { lock (_syncObject) { @@ -1187,7 +1214,7 @@ public static bool Add( { return false; } - + vaultItems.Remove(keyName); } @@ -1195,7 +1222,7 @@ public static bool Add( WriteSecretVaultRegistry( vaultInfo: vaultItems, defaultVaultName: defaultVault ? keyName : _defaultVaultName); - + return true; } @@ -1283,7 +1310,7 @@ private static void CheckFilePath() { if (!_isLocationPathValid) { - var msg = _isWindows ? + var msg = _isWindows ? "Unable to find a Local Application Data folder location for the current user, which is needed to store vault registry information.\nWindows built-in accounts do not provide the Location Application Data folder and are not currently supported." : "Unable to find a 'HOME' path location for the current user, which is needed to store vault registry information."; throw new InvalidOperationException(msg); @@ -1310,7 +1337,7 @@ private static void RefreshCache() foreach (string vaultKey in _vaultInfoCache.Keys) { _vaultCache.Add( - key: vaultKey, + key: vaultKey, value: new ExtensionVaultModule( vaultName: vaultKey, vaultInfo: (Hashtable) _vaultInfoCache[vaultKey], @@ -1402,7 +1429,7 @@ private static void WriteSecretVaultRegistry( string defaultVaultName) { // SecretManagement vault registry relies on LocalApplicationData or HOME user context - // file locations. Some Windows accounts do not support this and we surface the error here. + // file locations. Some Windows accounts do not support this and we surface the error here. CheckFilePath(); var registryInfo = new Hashtable() @@ -1457,7 +1484,7 @@ internal static class PowerShellInvoker { #region Members - private static System.Management.Automation.PowerShell _powershell = + private static System.Management.Automation.PowerShell _powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace); private static bool _isHostDefault = false; private const string DefaultHost = "Default Host"; @@ -1536,8 +1563,8 @@ public static Collection InvokeScriptWithHost( ps.Runspace = _runspace; var cmd = new Command( - command: script, - isScript: true, + command: script, + isScript: true, useLocalScope: true); cmd.MergeMyResults( myResult: PipelineResultTypes.Error | PipelineResultTypes.Warning | PipelineResultTypes.Verbose | PipelineResultTypes.Debug | PipelineResultTypes.Information, @@ -1547,7 +1574,7 @@ public static Collection InvokeScriptWithHost( { ps.Commands.AddArgument(arg); } - + try { // Invoke the script. @@ -1579,7 +1606,7 @@ public static Collection InvokeScriptWithHost( case InformationRecord info: cmdlet.WriteInformation(info); break; - + case T result: returnCollection.Add(result); break; From 5604bcdff854230f53d0d8a6ceb41cf36836d3a8 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 14:43:52 -0400 Subject: [PATCH 02/10] Remove old build scripts --- build.ps1 | 93 -------------------- buildtools.psd1 | 51 ----------- buildtools.psm1 | 200 -------------------------------------------- doBuild.ps1 | 138 ------------------------------ nuget.config | 10 --- package.config.json | 9 -- 6 files changed, 501 deletions(-) delete mode 100644 build.ps1 delete mode 100644 buildtools.psd1 delete mode 100644 buildtools.psm1 delete mode 100644 doBuild.ps1 delete mode 100644 nuget.config delete mode 100644 package.config.json diff --git a/build.ps1 b/build.ps1 deleted file mode 100644 index 630e413..0000000 --- a/build.ps1 +++ /dev/null @@ -1,93 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")] -param ( - [Parameter(ParameterSetName="build")] - [switch] - $Clean, - - [Parameter(ParameterSetName="build")] - [switch] - $Build, - - [Parameter(ParameterSetName="publish")] - [switch] - $Publish, - - [Parameter(ParameterSetName="publish")] - [switch] - $Signed, - - [ValidateSet("Debug", "Release")] - [string] $BuildConfiguration = "Debug", - - [ValidateSet("net461")] - [string] $BuildFramework = "net461" -) - -Import-Module -Name "$PSScriptRoot/buildtools.psd1" -Force - -$config = Get-BuildConfiguration -ConfigPath $PSScriptRoot - -$script:ModuleName = $config.ModuleName -$script:SrcPath = $config.SourcePath -$script:OutDirectory = $config.BuildOutputPath -$script:SignedDirectory = $config.SignedOutputPath -$script:TestPath = $config.TestPath - -$script:ModuleRoot = $PSScriptRoot -$script:Culture = $config.Culture -$script:HelpPath = $config.HelpPath - -$script:BuildConfiguration = $BuildConfiguration -$script:BuildFramework = $BuildFramework - -if ($env:TF_BUILD) { - $vstsCommandString = "vso[task.setvariable variable=BUILD_OUTPUT_PATH]$OutDirectory" - Write-Host ("sending " + $vstsCommandString) - Write-Host "##$vstsCommandString" - - $vstsCommandString = "vso[task.setvariable variable=SIGNED_OUTPUT_PATH]$SignedDirectory" - Write-Host ("sending " + $vstsCommandString) - Write-Host "##$vstsCommandString" -} - -. $PSScriptRoot/doBuild.ps1 - -if ($Clean -and (Test-Path $OutDirectory)) -{ - Remove-Item -Path $OutDirectory -Force -Recurse -ErrorAction Stop -Verbose - - if (Test-Path "${SrcPath}/code/bin") - { - Remove-Item -Path "${SrcPath}/code/bin" -Recurse -Force -ErrorAction Stop -Verbose - } - - if (Test-Path "${SrcPath}/code/obj") - { - Remove-Item -Path "${SrcPath}/code/obj" -Recurse -Force -ErrorAction Stop -Verbose - } -} - -if (-not (Test-Path $OutDirectory)) -{ - $script:OutModule = New-Item -ItemType Directory -Path (Join-Path $OutDirectory $ModuleName) - $script:OutReferencePath = New-Item -ItemType Directory -Path (Join-Path $OutDirectory "Ref") -} -else -{ - $script:OutModule = Join-Path $OutDirectory $ModuleName - $script:OutReferencePath = Join-Path $OutDirectory "Ref" -} - -if ($Build.IsPresent) -{ - $sb = (Get-Item Function:DoBuild).ScriptBlock - Invoke-ModuleBuild -BuildScript $sb -} - -if ($Publish.IsPresent) -{ - Publish-ModulePackage -Signed:$Signed.IsPresent -} diff --git a/buildtools.psd1 b/buildtools.psd1 deleted file mode 100644 index 6542e45..0000000 --- a/buildtools.psd1 +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -@{ - # Script module or binary module file associated with this manifest. - RootModule = '.\buildtools.psm1' - - # Version number of this module. - ModuleVersion = '1.0.0' - - # Supported PSEditions - CompatiblePSEditions = @('Core') - - # ID used to uniquely identify this module - GUID = 'fcdd259e-1163-4da2-8bfa-ce36a839f337' - - # Author of this module - Author = 'Microsoft Corporation' - - # Company or vendor of this module - CompanyName = 'Microsoft Corporation' - - # Copyright statement for this module - Copyright = '(c) Microsoft Corporation. All rights reserved.' - - # Description of the functionality provided by this module - Description = "Build utilties." - - # Modules that must be imported into the global environment prior to importing this module - #RequiredModules = @( - # @{ ModuleName = 'platyPS'; ModuleVersion = '0.14.0' }, - # @{ ModuleName = 'Pester'; ModuleVersion = '4.8.1' }, - # @{ ModuleName = 'PSScriptAnalyzer'; ModuleVersion = '1.18.0' } - #) - - # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '5.1' - - # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. - CmdletsToExport = @() - - # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = @( - 'Get-BuildConfiguration', 'Invoke-ModuleBuild', 'Publish-ModulePackage', 'Install-ModulePackageForTest', 'Invoke-ModuleTests') - - # Variables to export from this module - VariablesToExport = '*' - - # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. - AliasesToExport = @() -} diff --git a/buildtools.psm1 b/buildtools.psm1 deleted file mode 100644 index cbae0f2..0000000 --- a/buildtools.psm1 +++ /dev/null @@ -1,200 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -$ConfigurationFileName = 'package.config.json' -# TODO: Update to PSResourceGet. -Import-Module -Name PowerShellGet -MinimumVersion 3.0.18 - -function Get-BuildConfiguration { - [CmdletBinding()] - param ( - [Parameter()] - [string] $ConfigPath = '.' - ) - - $resolvedPath = Resolve-Path $ConfigPath - - if (Test-Path $resolvedPath -PathType Container) { - $fileNamePath = Join-Path -Path $resolvedPath -ChildPath $ConfigurationFileName - } - else { - $fileName = Split-Path -Path $resolvedPath -Leaf - if ($fileName -ne $ConfigurationFileName) { - throw "$ConfigurationFileName not found in provided pathname: $resolvedPath" - } - $fileNamePath = $resolvedPath - } - - if (! (Test-Path -Path $fileNamePath -PathType Leaf)) { - throw "$ConfigurationFileName not found at path: $resolvedPath" - } - - $configObj = Get-Content -Path $fileNamePath | ConvertFrom-Json - - # Expand config paths to full paths - $projectRoot = Split-Path $fileNamePath - $configObj.SourcePath = Join-Path $projectRoot -ChildPath $configObj.SourcePath - $configObj.TestPath = Join-Path $projectRoot -ChildPath $configObj.TestPath - $configObj.HelpPath = Join-Path $projectRoot -ChildPath $configObj.HelpPath - $configObj.BuildOutputPath = Join-Path $projectRoot -ChildPath $configObj.BuildOutputPath - if ($configObj.SignedOutputPath) { - $configObj.SignedOutputPath = Join-Path $projectRoot -ChildPath $configObj.SignedOutputPath - } - else { - $configObj | Add-Member -MemberType NoteProperty -Name SignedOutputPath -Value (Join-Path $projectRoot -ChildPath 'signed') - } - - return $configObj -} - -function Invoke-ModuleBuild { - [CmdletBinding()] - param ( - [Parameter(Mandatory=$true)] - [ScriptBlock] $BuildScript - ) - - Write-Verbose -Verbose -Message "Invoking build script" - - $BuildScript.Invoke() - - Write-Verbose -Verbose -Message "Finished invoking build script" -} - -function Publish-ModulePackage -{ - [CmdletBinding()] - param ( - [Parameter()] - [Switch] $Signed - ) - - Write-Verbose -Verbose -Message "Creating new local package repo" - $localRepoName = 'packagebuild-local-repo' - $localRepoLocation = Join-Path -Path ([System.io.path]::GetTempPath()) -ChildPath $localRepoName - if (Test-Path -Path $localRepoLocation) { - Remove-Item -Path $localRepoLocation -Recurse -Force -ErrorAction Ignore - } - $null = New-Item -Path $localRepoLocation -ItemType Directory -Force - - Write-Verbose -Verbose -Message "Registering local package repo: $localRepoName" - Register-PSResourceRepository -Name $localRepoName -Uri $localRepoLocation -Trusted -Force - - Write-Verbose -Verbose -Message "Publishing package to local repo: $localRepoName" - $config = Get-BuildConfiguration - if (! $Signed.IsPresent) { - $modulePath = Join-Path -Path $config.BuildOutputPath -ChildPath $config.ModuleName - } else { - $modulePath = Join-Path -Path $config.SignedOutputPath -ChildPath $config.ModuleName - } - Publish-PSResource -Path $modulePath -Repository $localRepoName -SkipDependenciesCheck -Confirm:$false -Verbose - - if ($env:TF_BUILD) { - Write-Verbose -Verbose -Message "Uploading module nuget package artifact to AzDevOps" - $artifactName = "nupkg" - $artifactPath = (Get-ChildItem -Path $localRepoLocation -Filter "$($config.ModuleName)*.nupkg").FullName - $artifactPath = Resolve-Path -Path $artifactPath - Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$artifactPath" - } - - Write-Verbose -Verbose -Message "Unregistering local package repo: $localRepoName" - Unregister-PSResourceRepository -Name $localRepoName -Confirm:$false -} - -function Install-ModulePackageForTest { - [CmdletBinding()] - param ( - [Parameter(Mandatory=$true)] - [string] $PackagePath - ) - - $config = Get-BuildConfiguration - - $localRepoName = 'packagebuild-local-repo' - Write-Verbose -Verbose -Message "Registering local package repo: $localRepoName to path: $PackagePath" - Register-PSResourceRepository -Name $localRepoName -Uri $PackagePath -Trusted -Force - - $installationPath = $config.BuildOutputPath - if ( !(Test-Path $installationPath)) { - Write-Verbose -Verbose -Message "Creating module directory location for tests: $installationPath" - $null = New-Item -Path $installationPath -ItemType Directory -Verbose - } - Write-Verbose -Verbose -Message "Installing module $($config.ModuleName) to build output path $installationPath" - Save-PSResource -Name $config.ModuleName -Repository $localRepoName -Path $installationPath -SkipDependencyCheck -Prerelease -Confirm:$false - - Write-Verbose -Verbose -Message "Unregistering local package repo: $localRepoName" - Unregister-PSResourceRepository -Name $localRepoName -Confirm:$false -} - -function Invoke-ModuleTests { - [CmdletBinding()] - param ( - [ValidateSet("Functional", "StaticAnalysis")] - [string[]] $Type = "Functional" - ) - - Write-Verbose -Verbose -Message "Starting module Pester tests..." - - # Run module Pester tests. - $config = Get-BuildConfiguration - $tags = 'CI' - $testResultFileName = 'result.pester.xml' - $testPath = $config.TestPath - $moduleToTest = Join-Path -Path $config.BuildOutputPath -ChildPath $config.ModuleName - $command = "Import-Module -Name ${moduleToTest} -Force -Verbose; Set-Location -Path ${testPath}; Invoke-Pester -Path . -OutputFile ${testResultFileName} -Tags '${tags}'" - $pwshExePath = (Get-Process -Id $pid).Path - try { - $output = & $pwshExePath -NoProfile -NoLogo -Command $command - } - catch { - Write-Error -Message "Error invoking module Pester tests." - } - $output | Foreach-Object { Write-Warning -Message "$_" } - $testResultsFilePath = Join-Path -Path $testPath -ChildPath $testResultFileName - - # Examine Pester test results. - if (! (Test-Path -Path $testResultsFilePath)) { - throw "Module test result file not found: '$testResultsFilePath'" - } - $xmlDoc = [xml] (Get-Content -Path $testResultsFilePath -Raw) - if ([int] ($xmlDoc.'test-results'.failures) -gt 0) { - $failures = [System.Xml.XmlDocumentXPathExtensions]::SelectNodes($xmlDoc."test-results", './/test-case[@result = "Failure"]') - } - else { - $failures = $xmlDoc.SelectNodes('.//test-case[@result = "Failure"]') - } - foreach ($testfailure in $failures) { - Show-PSPesterError -TestFailure $testfailure - } - - # Publish test results to AzDevOps - if ($env:TF_BUILD) { - Write-Verbose -Verbose -Message "Uploading test results to AzDevOps" - $powerShellName = if ($PSVersionTable.PSEdition -eq 'Core') { 'PowerShell Core' } else { 'Windows PowerShell' } - $TestType = 'NUnit' - $Title = "Functional Tests - $env:AGENT_OS - $powershellName Results" - $ArtifactPath = (Resolve-Path -Path $testResultsFilePath).ProviderPath - $FailTaskOnFailedTests = 'true' - $message = "vso[results.publish type=$TestType;mergeResults=true;runTitle=$Title;publishRunAttachments=true;resultFiles=$ArtifactPath;failTaskOnFailedTests=$FailTaskOnFailedTests;]" - Write-Host "##$message" - } - - Write-Verbose -Verbose -Message "Module Pester tests complete." -} - -function Show-PSPesterError { - [CmdletBinding()] - param ( - [Parameter(Mandatory)] - [Xml.XmlElement]$testFailure - ) - - $description = $testFailure.description - $name = $testFailure.name - $message = $testFailure.failure.message - $stackTrace = $testFailure.failure."stack-trace" - - $fullMsg = "`n{0}`n{1}`n{2}`n{3}`{4}" -f ("Description: " + $description), ("Name: " + $name), "message:", $message, "stack-trace:", $stackTrace - - Write-Error $fullMsg -} diff --git a/doBuild.ps1 b/doBuild.ps1 deleted file mode 100644 index 02fc926..0000000 --- a/doBuild.ps1 +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -<# -.DESCRIPTION -Implement build and packaging of the package and place the output $OutDirectory/$ModuleName -#> -function DoBuild -{ - Write-Verbose -Verbose -Message "Starting DoBuild with configuration: $BuildConfiguration, framework: $BuildFramework" - - # Module build out path - $BuildOutPath = "${OutDirectory}/${ModuleName}" - Write-Verbose -Verbose -Message "Module output file path: '$BuildOutPath'" - - # Module build source path - $BuildSrcPath = "bin/${BuildConfiguration}/${BuildFramework}/publish" - Write-Verbose -Verbose -Message "Module build source path: '$BuildSrcPath'" - - # Reference assembly source path - $RefSrcPath = "bin/${BuildConfiguration}/${BuildFramework}/ref" - - # Copy psd1 file - Write-Verbose -Verbose "Copy-Item ${SrcPath}/${ModuleName}.psd1 to $BuildOutPath" - Copy-Item "${SrcPath}/${ModuleName}.psd1" "$BuildOutPath" - - # Copy format files here - Write-Verbose -Verbose "Copy-Item ${SrcPath}/${ModuleName}.format.ps1xml to $BuildOutPath" - Copy-Item "${SrcPath}/${ModuleName}.format.ps1xml" "$BuildOutPath" - - # Copy help - Write-Verbose -Verbose -Message "Copying help files to '$BuildOutPath'" - Copy-Item -Recurse "${HelpPath}/${Culture}" "$BuildOutPath" - - # Copy license - Write-Verbose -Verbose -Message "Copying LICENSE file to '$BuildOutPath'" - Copy-Item -Path "./LICENSE" -Dest "$BuildOutPath" - - # Copy notice - Write-Verbose -Verbose -Message "Copying ThirdPartyNotices.txt to '$BuildOutPath'" - Copy-Item -Path "./ThirdPartyNotices.txt" -Dest "$BuildOutPath" - - if ( Test-Path "${SrcPath}/code" ) { - Write-Verbose -Verbose -Message "Building assembly and copying to '$BuildOutPath'" - # build code and place it in the staging location - Push-Location "${SrcPath}/code" - try { - # Get dotnet.exe command path. - $dotnetCommand = Get-Command -Name 'dotnet' -ErrorAction Ignore - - # Check for dotnet for Windows (we only build on Windows platforms). - if ($null -eq $dotnetCommand) { - Write-Verbose -Verbose -Message "dotnet.exe cannot be found in current path. Looking in ProgramFiles path." - $dotnetCommandPath = Join-Path -Path $env:ProgramFiles -ChildPath "dotnet\dotnet.exe" - $dotnetCommand = Get-Command -Name $dotnetCommandPath -ErrorAction Ignore - if ($null -eq $dotnetCommand) { - throw "Dotnet.exe cannot be found: $dotnetCommandPath is unavailable for build." - } - } - - Write-Verbose -Verbose -Message "dotnet.exe command found in path: $($dotnetCommand.Path)" - - # Check dotnet version - Write-Verbose -Verbose -Message "DotNet version: $(& ($dotnetCommand) --version)" - - # Build source - Write-Verbose -Verbose -Message "Building location: PSScriptRoot: $PSScriptRoot, PWD: $pwd" - $buildCommand = "$($dotnetCommand.Name) publish --configuration $BuildConfiguration --framework $BuildFramework --output $BuildSrcPath" - Write-Verbose -Verbose -Message "Starting dotnet build command: $buildCommand" - Invoke-Expression -Command $buildCommand - - # Dump build source output directory - # $outResultsPath = (Resolve-Path -Path ".").ProviderPath - # Write-Verbose -Verbose -Message "Dumping expected results output path: $outResultsPath" - # $outResults = Get-ChildItem -Path $outResultsPath -Recurse | Out-String - # Write-Verbose -Verbose -Message $outResults - - # Place build results - if (! (Test-Path -Path "$BuildSrcPath/${ModuleName}.dll")) - { - throw "Expected binary was not created: $BuildSrcPath/${ModuleName}.dll" - } - - Write-Verbose -Verbose -Message "Copying implementation assembly $BuildSrcPath/${ModuleName}.dll to $BuildOutPath" - Copy-Item "$BuildSrcPath/${ModuleName}.dll" -Dest "$BuildOutPath" - - if (Test-Path -Path "$BuildSrcPath/${ModuleName}.pdb") - { - Write-Verbose -Verbose -Message "Copying implementation pdb $BuildSrcPath/${ModuleName}.pdb to $BuildOutPath" - Copy-Item -Path "$BuildSrcPath/${ModuleName}.pdb" -Dest "$BuildOutPath" - } - - Write-Verbose -Verbose "$BuildSrcPath/System.Runtime.InteropServices.RuntimeInformation.dll to $BuildOutPath" - Copy-Item -Path "$BuildSrcPath/System.Runtime.InteropServices.RuntimeInformation.dll" -Dest "$BuildOutPath" - - if (! (Test-Path -Path "$RefSrcPath/${ModuleName}.dll")) - { - # throw "Expected ref binary was not created: $RefSrcPath/${ModuleName}.dll" - Write-Verbose -Verbose -Message "Cannot find reference assembly $RefSrcPath/${ModuleName}.dll" - Write-Verbose -Verbose -Message "Copying implementation assembly as reference assembly $RefSrcPath/${ModuleName}.dll to $script:OutReferencePath" - Copy-Item -Path "$BuildSrcPath/${ModuleName}.dll" -Dest $script:OutReferencePath - } - else - { - Write-Verbose -Verbose -Message "Copying reference assembly $RefSrcPath/${ModuleName}.dll to $script:OutReferencePath" - Copy-Item -Path "$RefSrcPath/${ModuleName}.dll" -Dest $script:OutReferencePath - } - - # Create nuget package for reference assembly based on Microsoft.PowerShell.SecretManagement.Library.nuspec file. - & ($dotnetCommand) pack --no-build --configuration $BuildConfiguration --no-restore - - # Copy ref assembly nuget package to out. - $NuGetSrcPath = "bin/${BuildConfiguration}/Microsoft.PowerShell.SecretManagement.Library*.nupkg" - if (!(Test-Path -Path $NuGetSrcPath)) - { - Write-Verbose -Verbose -Message "Expected Nuget package was not created: $NuGetSrcPath" - } - else - { - Write-Verbose -Verbose -Message "Copying reference nuget package $NuGetSrcPath to $OutDirectory" - Copy-Item -Path $NuGetSrcPath -Dest $OutDirectory - } - } - catch { - Write-Verbose -Verbose -Message "dotnet build failed with error: $_" - Write-Error "dotnet build failed with error: $_" - } - finally { - Pop-Location - } - } - else { - Write-Verbose -Verbose -Message "No code to build in '${SrcPath}/code'" - } - - ## Add build and packaging here - Write-Verbose -Verbose -Message "Ending DoBuild" -} diff --git a/nuget.config b/nuget.config deleted file mode 100644 index 6548586..0000000 --- a/nuget.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/package.config.json b/package.config.json deleted file mode 100644 index 6e4e247..0000000 --- a/package.config.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ModuleName": "Microsoft.PowerShell.SecretManagement", - "Culture": "en-US", - "BuildOutputPath": "out", - "SignedOutputPath": "signed", - "HelpPath": "help", - "TestPath": "test", - "SourcePath": "src" -} From 026856cfc21d80cf32cddc68707132970bcc94c8 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 14:44:32 -0400 Subject: [PATCH 03/10] Remove build artifact from git and also unfinished about topic --- ...t.PowerShell.SecretManagement.dll-Help.xml | 2191 ----------------- ...osoft.PowerShell.SecretManagement.help.txt | 52 - ...t_Microsoft.PowerShell.SecretManagement.md | 57 - 3 files changed, 2300 deletions(-) delete mode 100644 help/en-US/Microsoft.PowerShell.SecretManagement.dll-Help.xml delete mode 100644 help/en-US/about_Microsoft.PowerShell.SecretManagement.help.txt delete mode 100644 help/en-US/about_Microsoft.PowerShell.SecretManagement.md diff --git a/help/en-US/Microsoft.PowerShell.SecretManagement.dll-Help.xml b/help/en-US/Microsoft.PowerShell.SecretManagement.dll-Help.xml deleted file mode 100644 index c22a01a..0000000 --- a/help/en-US/Microsoft.PowerShell.SecretManagement.dll-Help.xml +++ /dev/null @@ -1,2191 +0,0 @@ - - - - - Get-Secret - Get - Secret - - Finds and returns a secret by name from registered vaults. - - - - This cmdlet finds and returns the first secret that matches the provided name. If a vault name is specified, then only that vault will be searched. Otherwise, all vaults are searched and the first found result is returned. If a 'Default' vault is specified, then that vault is searched before any other registered vault. Secrets that are string or SecureString types are returned as SecureString objects by default. Unless the '-AsPlainText' parameter switch is used, in which case the secret is returned as a String type in plain text. - - - - Get-Secret - - InputObject - - SecretInformation object that describes a vault secret. - - SecretInformation - - SecretInformation - - - None - - - AsPlainText - - Switch parameter that when used returns either a string or SecureString secret type as a String type (in plain text). If the secret being retrieved is not of string or SecureString type, this switch parameter has no effect. - - - SwitchParameter - - - False - - - - Get-Secret - - Name - - Name of the secret to be retrieved. Wild card characters are not allowed. - - String - - String - - - None - - - Vault - - Optional name of the registered vault to retrieve the secret from. If no vault name is specified, then all registered vaults are searched. - - String - - String - - - None - - - AsPlainText - - Switch parameter that when used returns either a string or SecureString secret type as a String type (in plain text). If the secret being retrieved is not of string or SecureString type, this switch parameter has no effect. - - - SwitchParameter - - - False - - - - - - AsPlainText - - Switch parameter that when used returns either a string or SecureString secret type as a String type (in plain text). If the secret being retrieved is not of string or SecureString type, this switch parameter has no effect. - - SwitchParameter - - SwitchParameter - - - False - - - InputObject - - SecretInformation object that describes a vault secret. - - SecretInformation - - SecretInformation - - - None - - - Name - - Name of the secret to be retrieved. Wild card characters are not allowed. - - String - - String - - - None - - - Vault - - Optional name of the registered vault to retrieve the secret from. If no vault name is specified, then all registered vaults are searched. - - String - - String - - - None - - - - - - System.String - - - - - - - - Microsoft.PowerShell.SecretManagement.SecretInformation - - - - - - - - - - System.Object - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Get-Secret -Name Secret1 -Vault CredMan -System.Security.SecureString - -PS C:\> Get-Secret -Name Secret1 -Vault CredMan -AsPlainText -PlainTextSecretString - - This example searches for a secret with the name 'Secret1', which is a String type secret. The first time returns the secret as a SecureString object. The second time uses the '-AsPlainText' and so the secret string is returned as a string object, and is displayed in plain text. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Get-SecretInfo -Name Secret2 -Vault SecretStore | Get-Secret -AsPlainText - - This example retrieves secret information for the secret named 'Secret2' and then pipe the result to 'Get-Secret'. The secret is then looked up in the SecretStore vault and returned as plain text. - - - - - - - - Get-SecretInfo - Get - SecretInfo - - Finds and returns secret metadata information of one or more secrets. - - - - This cmdlet finds and returns secret metadata for secrets with names that match the provided 'Name'. The 'Name' parameter argument can include wildcards for the search. If no 'Name' parameter argument is provided then metadata for all secrets is returned. The search is performed over all registered vaults, unless a specific vault name is specified. Secret metadata consists of the secret name, secret type, vault name, and optional additional user data if supported by the extension vault. - - - - Get-SecretInfo - - Name - - This parameter takes a String argument, including wildcard characters. It is used to filter the search results that match on secret names the provided name pattern. If no 'Name' parameter argument is provided, then all stored secret metadata is returned. - - String - - String - - - None - - - Vault - - Optional parameter which takes a String argument that specifies a single vault to search. - - String - - String - - - None - - - - - - Name - - This parameter takes a String argument, including wildcard characters. It is used to filter the search results that match on secret names the provided name pattern. If no 'Name' parameter argument is provided, then all stored secret metadata is returned. - - String - - String - - - None - - - Vault - - Optional parameter which takes a String argument that specifies a single vault to search. - - String - - String - - - None - - - - - - None - - - - - - - - - - Microsoft.PowerShell.SecretManagement.SecretInformation - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Get-SecretInfo -Name * - -Name Type VaultName ----- ---- --------- -Secret1 String LocalStore -Secret2 ByteArray LocalStore -Secret3 SecureString LocalStore -Secret4 PSCredential LocalStore -Secret5 Hashtable LocalStore -Secret6 ByteArray CredMan - - This example runs the command with the 'Name' parameter argument being a single wildcard character. So all metadata for all stored secrets is returned. There are two registered vaults, LocalStore and CredMan. There are six secrets metadata information returned over the two vaults. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Get-SecretInfo -Name APIKey | Select-Object Name,VaultName,Metadata - -Name VaultName Metadata ----- --------- -------- -APIKey SecretStore {[Target, PSGallery]} - - This example runs the command for a single secret name and displays the secret name, the vault name, and any metadata associated with the secret. - - - - - - - - Get-SecretVault - Get - SecretVault - - Finds and returns registered vault information. - - - - This cmdlet finds and returns information of registered vaults. It takes an array of vault name strings, which can contain wildcard characters. If no 'Name' parameter is specified, all registered vault information is returned. The registered vault information includes the vault name, vault implementing module name, and optional default parameters. - - - - Get-SecretVault - - Name - - This parameter takes a String argument, including wildcard characters. It is used to filter the search results on vault names that match the provided name pattern. - - String[] - - String[] - - - None - - - - - - Name - - This parameter takes a String argument, including wildcard characters. It is used to filter the search results on vault names that match the provided name pattern. - - String[] - - String[] - - - None - - - - - - None - - - - - - - - - - Microsoft.PowerShell.SecretManagement.SecretVaultInfo - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False -LocalStore Microsoft.PowerShell.SecretStore True - - This example runs the command without any parameter arguments, and so returns information on all registered vaults. The 'LocalStore' vault is shown to be set as the default vault. - - - - - - - - Register-SecretVault - Register - SecretVault - - Registers a SecretManagement extension vault module for the current user. - - - - This cmdlet adds a provided SecretManagement extension vault module to the current user vault registry. An extension vault module is a PowerShell module that conforms to the required extension vault format. This cmdlet will first verify that the provided module meets conformance requirements, and then add it to the extension vault registry. Extension vaults are registered to the current user and do not affect other user vault registrations. - - - - Register-SecretVault - - Name - - Name of the extension vault to be registered. If no name is provide, the module name will be used. - - String - - String - - - None - - - ModuleName - - Name of the PowerShell module that implements the extension vault. It can be a simple name, in which case PowerShell will search for it in its known module paths. Alternatively, a pathname can be provided and PowerShell will look in the specific path for the module. - - String - - String - - - None - - - AllowClobber - - When used this parameter will overwrite an existing registered extension vault with the same name. - - - SwitchParameter - - - False - - - DefaultVault - - This parameter switch makes the new extension vault the default vault for the current user. - - - SwitchParameter - - - False - - - Description - - This parameter takes a description string that is included in the vault registry information. - - String - - String - - - None - - - PassThru - - When used this parameter will return the SecretVaultInfo object for the successfully registered extension vault. - - - SwitchParameter - - - False - - - VaultParameters - - This takes a hashtable object that contains optional parameter name-value pairs needed by the extension vault. These optional parameters are provided to the extension vault when invoked. - - Hashtable - - Hashtable - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - AllowClobber - - When used this parameter will overwrite an existing registered extension vault with the same name. - - SwitchParameter - - SwitchParameter - - - False - - - DefaultVault - - This parameter switch makes the new extension vault the default vault for the current user. - - SwitchParameter - - SwitchParameter - - - False - - - Description - - This parameter takes a description string that is included in the vault registry information. - - String - - String - - - None - - - ModuleName - - Name of the PowerShell module that implements the extension vault. It can be a simple name, in which case PowerShell will search for it in its known module paths. Alternatively, a pathname can be provided and PowerShell will look in the specific path for the module. - - String - - String - - - None - - - Name - - Name of the extension vault to be registered. If no name is provide, the module name will be used. - - String - - String - - - None - - - PassThru - - When used this parameter will return the SecretVaultInfo object for the successfully registered extension vault. - - SwitchParameter - - SwitchParameter - - - False - - - VaultParameters - - This takes a hashtable object that contains optional parameter name-value pairs needed by the extension vault. These optional parameters are provided to the extension vault when invoked. - - Hashtable - - Hashtable - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - - None - - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Register-SecretVault -Name LocalStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault -PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False -LocalStore Microsoft.PowerShell.SecretStore True - - This example registers the Microsoft.PowerShell.SecretStore extension vault module for the current user. The 'Microsoft.PowerShell.SecretStore' is installed in a known PowerShell module path, so just the module name is needed. It uses the 'DefaultVault' parameter switch to make it the default module for the user. The 'Get-SecretVault' command is run next to list all registered vaults for the user, and verifies the vault was registered and set as the default vault. - - - - - - - - Remove-Secret - Remove - Secret - - Removes a secret from a specified registered extension vault. - - - - This cmdlet will remove a secret by name from a registered extension vault. Both the secret name and extension vault name must be provided. - - - - Remove-Secret - - InputObject - - SecretInformation object that describes a vault secret. - - SecretInformation - - SecretInformation - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Remove-Secret - - Name - - Name of the secret to remove. - - String - - String - - - None - - - Vault - - Name of the vault from which the secret is to be removed. - - String - - String - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - InputObject - - SecretInformation object that describes a vault secret. - - SecretInformation - - SecretInformation - - - None - - - Name - - Name of the secret to remove. - - String - - String - - - None - - - Vault - - Name of the vault from which the secret is to be removed. - - String - - String - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - - System.String - - - - - - - - Microsoft.PowerShell.SecretManagement.SecretInformation - - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Remove-Secret -Name secretTest -Vault CredMan -PS C:\> Get-Secret -Name secretTest -Vault CredMan -Get-Secret: The secret secretTest was not found. - - This example runs the command to remove the secret 'secretTest' from the CredMan vault. The 'Get-Secret' command is next run to verify the secret no longer exists in the vault. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Get-SecretInfo -Name Secret2 -Vault CredMan | Remove-Secret -PS C:\> Get-Secret -Name Secret2 -Vault CredMan -Get-Secret: The secret Secret2 was not found. - - This example first obtains secret information for the 'Secret2' secret and pipes the results to this command. Remove-Secret then removes the secret from the vault using the piped in secret information. - - - - - - - - Set-Secret - Set - Secret - - Adds a secret to a SecretManagement registered vault. - - - - This cmdlet adds a secret value by name to SecretManagement. If no vault name is specified, then the secret will be added to the default vault. If an existing secret by the same name exists, it will be overwritten with the new value unless the 'NoClobber' parameter switch is used. Additional data can be included with the secret through the '-Metadata' parameter, if supported by the extension vault. If the extension vault does not support metadata then an error will be generated and the operation will fail. Metadata is not required to be stored securely, and should not contain sensitive information. The secret value must be one of five supported types: - - byte[] - - String - - SecureString - - PSCredential - - Hashtable - - The default parameter set takes a SecureString object. So if the command is run without specifying the secret value, the user will be safely prompted to enter a SecureString which cannot be seen on the console. - - - - Set-Secret - - Name - - Name of secret for which the metadata is added - - String - - String - - - None - - - Metadata - - Hashtable containing Name/Value pair that are stored in the vault. The specified extension vault may not support secret metadata, in which case the operation will fail. The metadata Name/Value value type must be one of the following: - string - - int - - DateTime - - Hashtable - - Hashtable - - - None - - - Vault - - Optional name of vault to which the secret is added. If omitted, the secret will be added to the default vault. - - String - - String - - - None - - - NoClobber - - When true, this command will not overwrite an existing secret and emit an error instead. - - - SwitchParameter - - - False - - - SecureStringSecret - - A secret SecretString object to be added. - - SecureString - - SecureString - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Set-Secret - - Name - - Name of secret for which the metadata is added - - String - - String - - - None - - - Metadata - - Hashtable containing Name/Value pair that are stored in the vault. The specified extension vault may not support secret metadata, in which case the operation will fail. The metadata Name/Value value type must be one of the following: - string - - int - - DateTime - - Hashtable - - Hashtable - - - None - - - Vault - - Optional name of vault to which the secret is added. If omitted, the secret will be added to the default vault. - - String - - String - - - None - - - NoClobber - - When true, this command will not overwrite an existing secret and emit an error instead. - - - SwitchParameter - - - False - - - Secret - - A secret value to be added. The object type must be one of the supported types. - - Object - - Object - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Set-Secret - - Vault - - Optional name of vault to which the secret is added. If omitted, the secret will be added to the default vault. - - String - - String - - - None - - - NoClobber - - When true, this command will not overwrite an existing secret and emit an error instead. - - - SwitchParameter - - - False - - - SecretInfo - - A SecretInformation object describing a stored secret returned by 'Get-SecretInfo'. This allows moving secrets from one extension vault to another. - - SecretInformation - - SecretInformation - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - Metadata - - Hashtable containing Name/Value pair that are stored in the vault. The specified extension vault may not support secret metadata, in which case the operation will fail. The metadata Name/Value value type must be one of the following: - string - - int - - DateTime - - Hashtable - - Hashtable - - - None - - - Name - - Name of secret for which the metadata is added - - String - - String - - - None - - - NoClobber - - When true, this command will not overwrite an existing secret and emit an error instead. - - SwitchParameter - - SwitchParameter - - - False - - - Secret - - A secret value to be added. The object type must be one of the supported types. - - Object - - Object - - - None - - - SecretInfo - - A SecretInformation object describing a stored secret returned by 'Get-SecretInfo'. This allows moving secrets from one extension vault to another. - - SecretInformation - - SecretInformation - - - None - - - SecureStringSecret - - A secret SecretString object to be added. - - SecureString - - SecureString - - - None - - - Vault - - Optional name of vault to which the secret is added. If omitted, the secret will be added to the default vault. - - String - - String - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - - System.Collections.Hashtable - - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Set-Secret -Name Secret1 -Secret "SecretValue" -PS C:\> Get-Secret -Name Secret1 -System.Security.SecureString - - This example adds a secret named 'Secret1' with a plain text value of 'SecretValue'. Since no vault name was specified, the secret is added to the current default vault. Next, the 'Get-Secret' command is run to verify the added secret. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Set-Secret -Name Secret2 -Vault LocalStore - -cmdlet Set-Secret at command pipeline position 1 -Supply values for the following parameters: -SecureStringSecret: *********** - -PS C:\> Get-Secret -Name Secret2 -System.Security.SecureString - - This example adds a secret named 'Secret2' to the LocalStore vault. Since no secret value was provided, the user is prompted for a SecureString value. The console hides the string value as it is typed. Next, the 'Get-Secret' command is run to verify the secret was added. - - - - -------------------------- Example 3 -------------------------- - PS C:\> Set-Secret -Name TargetSecret -Secret $targetToken -Vault LocalStore -Metadata @{ Expiration = ([datetime]::new(2022, 5, 1)) } -PS C:\> Get-SecretInfo -Name TargetSecret | Select-Object Name,Metadata - -Name Metadata ----- -------- -TargetSecret {[Expiration, 5/1/2022 12:00:00 AM]} - - This example adds a secret named 'TargetSecret' to the LocalStore vault, along with extra metadata indicating the secret expiration date. The metadata is retrieved using the 'Get-SecretInfo' cmdlet. - - - - -------------------------- Example 4 -------------------------- - PS C:\> Set-Secret -Name PublishSecret -Secret $targetToken -Vault LocalStore2 -Metadata @{ Expiration = ([datetime]::new(2022, 5, 1)) } -Set-Secret: Cannot store secret PublishSecret. Vault LocalStore2 does not support secret metadata. - - This example adds a secret named 'PublishSecret' to the LocalStore2 vault, along with extra metadata. However, vault LocalStore2 does not support secret metadata and the operation fails with error. - - - - - - - - Set-SecretInfo - Set - SecretInfo - - Adds or replaces additional secret metadata to a secret currently stored in a vault. - - - - This cmdlet adds additional secret metadata to an existing secret. Metadata support is an optional feature for an extension vault. An error will be thrown if a vault does not support secret metadata. Metadata is a Hashtable object containing Name/Value pairs. The value type is restricted to the following: - - string - - int - - DateTime - - Metadata is not stored securely in a vault. Metadata should not contain sensitive information. - - - - Set-SecretInfo - - Metadata - - Hashtable containing Name/Value pair that are stored in the vault. The specified extension vault may not support secret metadata, in which case the operation will fail. The metadata Name/Value value type must be one of the following: - string - - int - - DateTime - - Hashtable - - Hashtable - - - None - - - InputObject - - This parameter takes a SecretInformation object that defines the secret to be updated. - - SecretInformation - - SecretInformation - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Set-SecretInfo - - Name - - Name of secret for which the metadata is added. - - String - - String - - - None - - - Metadata - - Hashtable containing Name/Value pair that are stored in the vault. The specified extension vault may not support secret metadata, in which case the operation will fail. The metadata Name/Value value type must be one of the following: - string - - int - - DateTime - - Hashtable - - Hashtable - - - None - - - Vault - - Optional name of vault to which the secret is added. If omitted, the secret will be added to the default vault. - - String - - String - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - InputObject - - This parameter takes a SecretInformation object that defines the secret to be updated. - - SecretInformation - - SecretInformation - - - None - - - Metadata - - Hashtable containing Name/Value pair that are stored in the vault. The specified extension vault may not support secret metadata, in which case the operation will fail. The metadata Name/Value value type must be one of the following: - string - - int - - DateTime - - Hashtable - - Hashtable - - - None - - - Name - - Name of secret for which the metadata is added. - - String - - String - - - None - - - Vault - - Optional name of vault to which the secret is added. If omitted, the secret will be added to the default vault. - - String - - String - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - - System.Collections.Hashtable - - - - - - - - - - System.Object - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Set-SecretInfo -Name Secret1 -Vault Vault1 -Metadata @{ Expiration = ([datetime]::new(2022, 5, 1)) } -PS C:\> Get-SecretInfo -Name Secret1 -Vault Vault1 | Select-Object Name,Metadata - -Name Metadata ----- -------- -Secret1 {[Expiration, 5/1/2022 12:00:00 AM]} - - This example adds metadata to the 'Secret1' secret stored in 'Vault1' vault. The metadata is then retrieved for 'Secret1' using the 'Get-SecretInfo' command. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Set-SecretInfo -Name Secret2 -Vault Vault2 -Metadata @{ Expiration = ([datetime]::new(2022, 5, 1)) } -Set-SecretInfo: Cannot set secret metadata Secret2. Vault Vault2 does not support secret metadata. - - This example adds metadata to the 'Secret2' secret stored in 'Vault2' vault. However, Vault2 does not support metadata and an error is generated. - - - - -------------------------- Example 3 -------------------------- - PS C:\> Get-SecretInfo -Name Secret3 | Set-SecretInfo -Metadata @{ Created = (Get-Date) } - - This example pipes a SecretInformation object to the 'Set-SecretInfo' command and adds metadata to the associated secret. - - - - - - - - Set-SecretVaultDefault - Set - SecretVaultDefault - - Sets the provided vault name as the default vault for the current user. - - - - This cmdlet updates the vault registry to designate the provided vault name as the default vault. Only one registered vault can be the default vault. If this cmdlet is run without specifying the 'Name' parameter, then no registered vault is designated as the default vault. - - - - Set-SecretVaultDefault - - ClearDefault - - Makes no registered vault the default vault. - - - SwitchParameter - - - False - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Set-SecretVaultDefault - - Name - - Name of registered vault to be made the default vault. - - String - - String - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Set-SecretVaultDefault - - SecretVault - - A SecretVaultInfo object that represents the registered vault to be made the default vault. - - SecretVaultInfo - - SecretVaultInfo - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - ClearDefault - - Makes no registered vault the default vault. - - SwitchParameter - - SwitchParameter - - - False - - - Name - - Name of registered vault to be made the default vault. - - String - - String - - - None - - - SecretVault - - A SecretVaultInfo object that represents the registered vault to be made the default vault. - - SecretVaultInfo - - SecretVaultInfo - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - - None - - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False -LocalStore Microsoft.PowerShell.SecretStore True - -PS C:\> Set-SecretVaultDefault -Name CredMan -PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore True -LocalStore Microsoft.PowerShell.SecretStore False - -PS C:\> Set-SecretVaultDefault -PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False -LocalStore Microsoft.PowerShell.SecretStore False - - This cmdlet first runs 'Get-SecretVault' command to get all registered vault information, and shows that the 'LocalStore' is currently the default vault for the user. Next, the 'Set-SecretVaultDefault' command is run to make the 'CredMan' vault the default vault. The 'Get-SecretVault' command is run a second time to verify 'CredMan' vault is now default, and 'LocalStore' vault is no longer default. Finally, the 'Set-SecretVaultDefault' command is run with no 'Name' parameter, to remove the default designation from any registered vault. The 'Get-SecretVault' is run once again to verify there is no default vault. - - - - - - - - Test-SecretVault - Test - SecretVault - - Runs an extension vault self test. - - - - This cmdlet runs an extension vault self test, by running the internal vault 'Test-SecretVault' command. It will return 'True' if all tests succeeded, and 'False' otherwise. Information on failing tests will be written to the error stream as error records. For more information during the test run use the -Verbose command switch. - - - - Test-SecretVault - - Name - - Name of vault to run self tests on. - - String[] - - String[] - - - None - - - - - - Name - - Name of vault to run self tests on. - - String[] - - String[] - - - None - - - - - - None - - - - - - - - - - System.Boolean - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Test-SecretVault -Name CredMan -Verbose -VERBOSE: Invoking command Test-SecretVault on module Microsoft.PowerShell.CredManStore.Extension -VERBOSE: Vault CredMan succeeded validation test -True - - This example runs self tests on the 'CredMan' extension vault. All tests succeeded so no errors are written and 'True' is returned. - - - - - - - - Unlock-SecretVault - Unlock - SecretVault - - Unlocks an extension vault so that it can be access in the current session. - - - - This cmdlet unlocks an extension vault using the provided Password parameter argument. This allows a vault that requires password authentication to operate without first having to prompt the user. Not all extension vaults require password authentication, in which case this command has no effect. A warning will be emitted if the extension vault does not support unlocking via password. - - - - Unlock-SecretVault - - Name - - Name of the vault to unlock. - - String - - String - - - None - - - Password - - Password used to unlock the vault. - - SecureString - - SecureString - - - None - - - - - - Name - - Name of the vault to unlock. - - String - - String - - - None - - - Password - - Password used to unlock the vault. - - SecureString - - SecureString - - - None - - - - - - None - - - - - - - - - - System.Object - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Unlock-SecretVault -Name SecretStore -Password $SecurePassword -PS C:\> Get-SecretInfo -Vault SecretStore - -Name Type VaultName ----- ---- --------- -Secret1 SecureString SecretStore -Secret2 SecureString SecretStore - - This example uses the command to unlock the SecretStore vault. It then runs the 'Get-SecretInfo' command on the vault without being prompted for the vault password. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Unlock-SecretVault -Name CredMan -Password $SecurePassword -WARNING: Cannot unlock extension vault 'CredMan': The vault does not support the Unlock-SecretVault function. -PS C:\> - - This example uses the command to unlock the CredMan vault. But the vault does not support unlocking so the command has no effect. A warning is displayed informing that CredMan vault does not support unlocking. - - - - - - - - Unregister-SecretVault - Unregister - SecretVault - - Un-registers an extension vault from SecretManagement for the current user. - - - - This cmdlet un-registers the specified extension vault. Once un-registered, the vault is no longer available to SecretManagement, for the current user. - - - - Unregister-SecretVault - - Name - - Name of the vault to un-register. - - String[] - - String[] - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - Unregister-SecretVault - - SecretVault - - SecretVaultInfo object, returned by 'Get-SecretVault' cmdlet. This can alternately be used to indicate a vault to be un-registered. - - SecretVaultInfo - - SecretVaultInfo - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - - SwitchParameter - - - False - - - - - - Name - - Name of the vault to un-register. - - String[] - - String[] - - - None - - - SecretVault - - SecretVaultInfo object, returned by 'Get-SecretVault' cmdlet. This can alternately be used to indicate a vault to be un-registered. - - SecretVaultInfo - - SecretVaultInfo - - - None - - - Confirm - - Prompts you for confirmation before running the cmdlet. - - SwitchParameter - - SwitchParameter - - - False - - - WhatIf - - Shows what would happen if the cmdlet runs. The cmdlet is not run. - - SwitchParameter - - SwitchParameter - - - False - - - - - - Microsoft.PowerShell.SecretManagement.SecretVaultInfo - - - - - - - - - - - - - - - -------------------------- Example 1 -------------------------- - PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False -LocalStore Microsoft.PowerShell.SecretStore True - -PS C:\> Unregister-SecretVault LocalStore -PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False - -PS C:\> Get-Secret -Name Secret5 -Get-Secret: The secret Secret5 was not found. - -PS C:\> Register-SecretVault -Name SecretStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault -PS C:\> Get-SecretVault - -VaultName ModuleName IsDefaultVault ---------- ---------- -------------- -CredMan Microsoft.PowerShell.CredManStore False -SecretStore Microsoft.PowerShell.SecretStore True - -PS C:\> Get-Secret -Name Secret5 -System.Security.SecureString - - In this example, 'Get-SecretVault' command is run to see what vaults are registered for the current user. Next, the 'LocalStore' vault is un-registered. 'Get-SecretVault' command is run again to verify the vault no longer appears in the registry. An attempt is made to retrieve 'Secret5', but it is not found since its vault was un-registered. The vault is re-registered, under a different name, and set to be the default vault. 'Get-SecretVault' is run again to verify the newly registered vault. Finally, the 'Secret5' secret is retrieved successfully from the new default vault. - - - - -------------------------- Example 2 -------------------------- - PS C:\> Get-SecretVault | Unregister-SecretVault -PS C:\> Get-SecretVault -PS C:\> - - In this example, 'Get-SecretVault' output is piped to this 'Unregister-SecretVault' cmdlet to un-register all extension vaults for the current user. Next, 'Get-SecretVault' is run again to show that no vaults are registered. - - - - - - \ No newline at end of file diff --git a/help/en-US/about_Microsoft.PowerShell.SecretManagement.help.txt b/help/en-US/about_Microsoft.PowerShell.SecretManagement.help.txt deleted file mode 100644 index 2397820..0000000 --- a/help/en-US/about_Microsoft.PowerShell.SecretManagement.help.txt +++ /dev/null @@ -1,52 +0,0 @@ -TOPIC - about_microsoft.powershell.secretmanagement - - ABOUT TOPIC NOTE: - The first header of the about topic should be the topic name. - The second header contains the lookup name used by the help system. - - IE: - # Some Help Topic Name - ## SomeHelpTopicFileName - - This will be transformed into the text file - as `about_SomeHelpTopicFileName`. - Do not include file extensions. - The second header should have no spaces. - -SHORT DESCRIPTION - {{ Short Description Placeholder }} - - ABOUT TOPIC NOTE: - About topics can be no longer than 80 characters wide when rendered to text. - Any topics greater than 80 characters will be automatically wrapped. - The generated about topic will be encoded UTF-8. - -LONG DESCRIPTION - {{ Long Description Placeholder }} - -Optional Subtopics - {{ Optional Subtopic Placeholder }} - -EXAMPLES - {{ Code or descriptive examples of how to leverage the functions described. - }} - -NOTE - {{ Note Placeholder - Additional information that a user needs to know.}} - -TROUBLESHOOTING NOTE - {{ Troubleshooting Placeholder - Warns users of bugs}} - {{ Explains behavior that is likely to change with fixes }} - -SEE ALSO - {{ See also placeholder }} - {{ You can also list related articles, blogs, and video URLs. }} - -KEYWORDS - {{List alternate names or titles for this topic that readers might use.}} - - {{ Keyword Placeholder }} - - {{ Keyword Placeholder }} - - {{ Keyword Placeholder }} - - {{ Keyword Placeholder }} - diff --git a/help/en-US/about_Microsoft.PowerShell.SecretManagement.md b/help/en-US/about_Microsoft.PowerShell.SecretManagement.md deleted file mode 100644 index 1d7eeb1..0000000 --- a/help/en-US/about_Microsoft.PowerShell.SecretManagement.md +++ /dev/null @@ -1,57 +0,0 @@ -# Microsoft.PowerShell.SecretManagement -## about_Microsoft.PowerShell.SecretManagement - -``` -ABOUT TOPIC NOTE: -The first header of the about topic should be the topic name. -The second header contains the lookup name used by the help system. - -IE: -# Some Help Topic Name -## SomeHelpTopicFileName - -This will be transformed into the text file -as `about_SomeHelpTopicFileName`. -Do not include file extensions. -The second header should have no spaces. -``` - -# SHORT DESCRIPTION -{{ Short Description Placeholder }} - -``` -ABOUT TOPIC NOTE: -About topics can be no longer than 80 characters wide when rendered to text. -Any topics greater than 80 characters will be automatically wrapped. -The generated about topic will be encoded UTF-8. -``` - -# LONG DESCRIPTION -{{ Long Description Placeholder }} - -## Optional Subtopics -{{ Optional Subtopic Placeholder }} - -# EXAMPLES -{{ Code or descriptive examples of how to leverage the functions described. }} - -# NOTE -{{ Note Placeholder - Additional information that a user needs to know.}} - -# TROUBLESHOOTING NOTE -{{ Troubleshooting Placeholder - Warns users of bugs}} - -{{ Explains behavior that is likely to change with fixes }} - -# SEE ALSO -{{ See also placeholder }} - -{{ You can also list related articles, blogs, and video URLs. }} - -# KEYWORDS -{{List alternate names or titles for this topic that readers might use.}} - -- {{ Keyword Placeholder }} -- {{ Keyword Placeholder }} -- {{ Keyword Placeholder }} -- {{ Keyword Placeholder }} From c892b7e26030a8cd359e1683d7d0d042103be2c9 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 14:46:39 -0400 Subject: [PATCH 04/10] Update git ignore --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index cce595a..b03f1f5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +artifacts/ +module/ + _site/ _themes/ .DS_Store @@ -12,7 +15,6 @@ maml/ **/obj/** packages.config packages/ -SecretManagement.sln Tools/NuGet/ test/result.pester.xml updatablehelp/ From 933f481f555a24358ab199741d5db7bd212728e2 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 14:47:06 -0400 Subject: [PATCH 05/10] Add new build scripts --- Directory.Build.props | 10 ++ .../CredManStore/Directory.Build.props | 8 ++ ...oft.PowerShell.CredManStore.Extension.psd1 | 2 +- .../Microsoft.PowerShell.CredManStore.csproj | 11 +- SecretManagement.build.ps1 | 104 ++++++++++++++++++ SecretManagement.sln | 27 +++++ ...Microsoft.PowerShell.SecretManagement.psd1 | 2 +- ...PowerShell.SecretManagement.Library.nuspec | 7 +- ...crosoft.PowerShell.SecretManagement.csproj | 10 +- 9 files changed, 166 insertions(+), 15 deletions(-) create mode 100644 Directory.Build.props create mode 100644 ExtensionModules/CredManStore/Directory.Build.props create mode 100644 SecretManagement.build.ps1 create mode 100644 SecretManagement.sln diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..ddab759 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,10 @@ + + + + + 1.1.2 + + $(MSBuildThisFileDirectory)artifacts + + + diff --git a/ExtensionModules/CredManStore/Directory.Build.props b/ExtensionModules/CredManStore/Directory.Build.props new file mode 100644 index 0000000..b5ed0b0 --- /dev/null +++ b/ExtensionModules/CredManStore/Directory.Build.props @@ -0,0 +1,8 @@ + + + + + $(MSBuildThisFileDirectory)artifacts + + + diff --git a/ExtensionModules/CredManStore/Microsoft.PowerShell.CredManStore.Extension/Microsoft.PowerShell.CredManStore.Extension.psd1 b/ExtensionModules/CredManStore/Microsoft.PowerShell.CredManStore.Extension/Microsoft.PowerShell.CredManStore.Extension.psd1 index d1ea873..379ec26 100644 --- a/ExtensionModules/CredManStore/Microsoft.PowerShell.CredManStore.Extension/Microsoft.PowerShell.CredManStore.Extension.psd1 +++ b/ExtensionModules/CredManStore/Microsoft.PowerShell.CredManStore.Extension/Microsoft.PowerShell.CredManStore.Extension.psd1 @@ -1,5 +1,5 @@ @{ ModuleVersion = '1.0' - RootModule = '..\Microsoft.PowerShell.CredManStore.dll' + RootModule = './Microsoft.PowerShell.CredManStore.dll' FunctionsToExport = @('Set-Secret','Get-Secret','Remove-Secret','Get-SecretInfo','Test-SecretVault') } diff --git a/ExtensionModules/CredManStore/src/code/Microsoft.PowerShell.CredManStore.csproj b/ExtensionModules/CredManStore/src/code/Microsoft.PowerShell.CredManStore.csproj index f6e6ca3..6760376 100644 --- a/ExtensionModules/CredManStore/src/code/Microsoft.PowerShell.CredManStore.csproj +++ b/ExtensionModules/CredManStore/src/code/Microsoft.PowerShell.CredManStore.csproj @@ -16,10 +16,13 @@ - - - - + + + + + + + diff --git a/SecretManagement.build.ps1 b/SecretManagement.build.ps1 new file mode 100644 index 0000000..7e47a6c --- /dev/null +++ b/SecretManagement.build.ps1 @@ -0,0 +1,104 @@ +[CmdletBinding()] +param( + [ValidateSet("Debug", "Release")] + [string]$Configuration = "Debug" +) + +$ProjectName = "SecretManagement" +$FullModuleName = 'Microsoft.PowerShell.SecretManagement' +$CSharpSource = Join-Path $PSScriptRoot src/code +$CSharpPublish = Join-Path $PSScriptRoot artifacts/publish +$ModuleOut = Join-Path $PSScriptRoot module +$PackageOut = Join-Path $PSScriptRoot out +$HelpSource = Join-Path $PSScriptRoot help +$HelpOut = Join-Path $ModuleOut en-US + +$CSharpArtifacts = @( + "$FullModuleName.dll", + "$FullModuleName.pdb", + "System.Runtime.InteropServices.RuntimeInformation.dll") + +$BaseArtifacts = @( + "src/$FullModuleName.format.ps1xml", + "README.md", + "LICENSE", + "ThirdPartyNotices.txt") + +$ManifestPath = Join-Path $PSScriptRoot "src/$FullModuleName.psd1" + +$HelpAboutTopics = @() + +task FindDotNet -Before Clean, Build { + Assert (Get-Command dotnet -ErrorAction SilentlyContinue) "The dotnet CLI was not found, please install it: https://aka.ms/dotnet-cli" + $DotnetVersion = dotnet --version + Assert ($?) "The required .NET SDK was not found, please install it: https://aka.ms/dotnet-cli" + Write-Host "Using dotnet $DotnetVersion at path $((Get-Command dotnet).Source)" -ForegroundColor Green +} + +task Clean { + Remove-BuildItem $ModuleOut, $PackageOut + Invoke-BuildExec { dotnet clean $CSharpSource } + + Remove-BuildItem "$HelpOut/$FullModuleName.dll-Help.xml" + foreach ($aboutTopic in $HelpAboutTopics) { + Remove-BuildItem "$HelpSource/$aboutTopic.help.txt" + } +} + +task BuildDocs { + if (-not (Test-Path -LiteralPath $HelpSource)) { + return + } + + New-ExternalHelp -Path $HelpSource -OutputPath $HelpOut | Out-Null + foreach ($aboutTopic in $HelpAboutTopics) { + New-ExternalHelp -Path "$HelpSource\$aboutTopic.md" -OutputPath $HelpOut | Out-Null + } +} + +task BuildModule { + New-Item -ItemType Directory -Force $ModuleOut | Out-Null + + Invoke-BuildExec { dotnet publish $CSharpSource --configuration $Configuration --output $CSharpPublish } + + $CSharpArtifacts | ForEach-Object { + $item = Join-Path $CSharpPublish $_ + Copy-Item -Force -LiteralPath $item -Destination $ModuleOut + } + + $BaseArtifacts | ForEach-Object { + $itemToCopy = Join-Path $PSScriptRoot $_ + Copy-Item -Force -LiteralPath $itemToCopy -Destination $ModuleOut + } + + $propsContent = Get-Content $PSScriptRoot/Directory.Build.props -Raw + $props = [xml]$propsContent + $moduleVersion = $props.Project.PropertyGroup.ModuleVersion + $manifestContent = Get-Content -LiteralPath $ManifestPath -Raw + $newManifestContent = $manifestContent -replace '{{ModuleVersion}}', $moduleVersion + Set-Content -LiteralPath "$ModuleOut/$FullModuleName.psd1" -Encoding utf8 -Value $newManifestContent + + # New-ExternalHelp -Path docs/Microsoft.PowerShell.ConsoleGuiTools -OutputPath module/en-US -Force +} + +task PackageModule { + New-Item -ItemType Directory -Force $PackageOut | Out-Null + + try { + Register-PSResourceRepository -Name $ProjectName -Uri $PackageOut -ErrorAction Stop + $registerSuccessful = $true + Publish-PSResource -Path $ModuleOut -Repository $ProjectName + } finally { + Unregister-PSResourceRepository -Name $ProjectName + } +} + +task PackageLibrary { + Invoke-BuildExec { dotnet pack $CSharpSource --no-build --configuration $Configuration --no-restore --output $PackageOut } +} + +task Build BuildModule, BuildDocs + +task Package PackageModule, PackageLibrary + +task . Clean, Build diff --git a/SecretManagement.sln b/SecretManagement.sln new file mode 100644 index 0000000..1af931a --- /dev/null +++ b/SecretManagement.sln @@ -0,0 +1,27 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E65CF2A7-C44A-491E-989D-8EAFAC4497C8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.PowerShell.SecretManagement", "src\code\Microsoft.PowerShell.SecretManagement.csproj", "{90AF98C9-E305-4B37-945E-D79E14E1E8B3}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {90AF98C9-E305-4B37-945E-D79E14E1E8B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {90AF98C9-E305-4B37-945E-D79E14E1E8B3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {90AF98C9-E305-4B37-945E-D79E14E1E8B3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {90AF98C9-E305-4B37-945E-D79E14E1E8B3}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {90AF98C9-E305-4B37-945E-D79E14E1E8B3} = {E65CF2A7-C44A-491E-989D-8EAFAC4497C8} + EndGlobalSection +EndGlobal diff --git a/src/Microsoft.PowerShell.SecretManagement.psd1 b/src/Microsoft.PowerShell.SecretManagement.psd1 index 552e40f..0e08617 100644 --- a/src/Microsoft.PowerShell.SecretManagement.psd1 +++ b/src/Microsoft.PowerShell.SecretManagement.psd1 @@ -7,7 +7,7 @@ RootModule = '.\Microsoft.PowerShell.SecretManagement.dll' # Version number of this module. -ModuleVersion = '1.1.2' +ModuleVersion = '{{ModuleVersion}}' # Supported PSEditions CompatiblePSEditions = @('Core') diff --git a/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec b/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec index ec3176b..af4dfc3 100644 --- a/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec +++ b/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec @@ -2,7 +2,7 @@ Microsoft.PowerShell.SecretManagement.Library - 1.1.2 + $version$ Microsoft.PowerShell.SecretManagement.Library Microsoft Microsoft,PowerShell @@ -16,7 +16,6 @@ en-US - @@ -28,7 +27,7 @@ - - + + diff --git a/src/code/Microsoft.PowerShell.SecretManagement.csproj b/src/code/Microsoft.PowerShell.SecretManagement.csproj index b8c3943..854e418 100644 --- a/src/code/Microsoft.PowerShell.SecretManagement.csproj +++ b/src/code/Microsoft.PowerShell.SecretManagement.csproj @@ -5,18 +5,18 @@ true true ./Microsoft.PowerShell.SecretManagement.Library.nuspec + id=$(AssemblyName);version=$(ModuleVersion);artifacts=$(ArtifactsPath) Library Microsoft.PowerShell.SecretManagement Microsoft.PowerShell.SecretManagement - 1.1.2.0 - 1.1.2 - 1.1.2 + $(ModuleVersion).0 + $(ModuleVersion) + $(ModuleVersion) net461 - + - From 236d39550fff328d2b9fd926fb99ffe5493d34c3 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 14:47:51 -0400 Subject: [PATCH 06/10] Update tests for Pester 5 --- ...icrosoft.PowerShell.CredManStore.Tests.ps1 | 99 ++-- ...soft.PowerShell.SecretManagement.Tests.ps1 | 483 ++++++++---------- 2 files changed, 257 insertions(+), 325 deletions(-) diff --git a/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 b/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 index 90c4b7a..a715fc2 100644 --- a/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 +++ b/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 @@ -2,25 +2,24 @@ # Licensed under the MIT License. Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { - BeforeAll { - - if (! $IsWindows) + $ModuleRoot = Split-Path $PSScriptRoot | Join-Path -ChildPath 'artifacts/publish/Microsoft.PowerShell.CredManStore/Release' + $ProjectRoot = Split-Path $PSScriptRoot | Split-Path | Split-Path + if (-not $IsWindows) { $defaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:Skip"] = $true + $PSDefaultParameterValues["It:Skip"] = $true + return } - else + + if (-not (Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore)) { - if ((Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore) -eq $null) - { - Import-Module -Name Microsoft.PowerShell.SecretManagement - } + Import-Module -Name Microsoft.PowerShell.SecretManagement + } - if ((Get-Module -Name Microsoft.PowerShell.CredManStore -ErrorAction Ignore) -eq $null) - { - Import-Module -Name ..\Microsoft.PowerShell.CredManStore.psd1 - } + if (-not (Get-Module -Name Microsoft.PowerShell.CredManStore -ErrorAction Ignore)) + { + Import-Module -Name $ModuleRoot\Microsoft.PowerShell.CredManStore.psd1 } } @@ -34,9 +33,11 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { Context "CredMan Store Vault Byte[] type" { - $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) - $bytesToWrite = [System.Text.Encoding]::UTF8.GetBytes('TestStringForBytes') - $errorCode = 0 + BeforeAll { + $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) + $bytesToWrite = [System.Text.Encoding]::UTF8.GetBytes('TestStringForBytes') + $errorCode = 0 + } It "Verifies byte[] write to store" { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::WriteObject( @@ -54,7 +55,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outBytes, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 [System.Text.Encoding]::UTF8.GetString($outBytes) | Should -BeExactly 'TestStringForBytes' @@ -66,7 +67,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outInfo, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outInfo.Key | Should -BeExactly $secretName @@ -77,7 +78,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } @@ -85,9 +86,11 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { Context "CredMan Store Vault String type" { - $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) - $stringToWrite = 'TestStringForString' - $errorCode = 0 + BeforeAll { + $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) + $stringToWrite = 'TestStringForString' + $errorCode = 0 + } It "Verifes string write to store" { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::WriteObject( @@ -105,7 +108,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outString, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outString | Should -BeExactly 'TestStringForString' @@ -117,7 +120,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outInfo, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outInfo.Key | Should -BeExactly $secretName @@ -128,7 +131,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } @@ -136,10 +139,12 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { Context "CredMan Store Vault SecureString type" { - $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) - $randomSecret = [System.IO.Path]::GetRandomFileName() - $secureStringToWrite = ConvertTo-SecureString -String $randomSecret -AsPlainText -Force - $errorCode = 0 + BeforeAll { + $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) + $randomSecret = [System.IO.Path]::GetRandomFileName() + $secureStringToWrite = ConvertTo-SecureString -String $randomSecret -AsPlainText -Force + $errorCode = 0 + } It "Verifies SecureString write to store" { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::WriteObject( @@ -157,7 +162,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outSecureString, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 [System.Net.NetworkCredential]::new('',$outSecureString).Password | Should -BeExactly $randomSecret @@ -169,7 +174,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outInfo, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outInfo.Key | Should -BeExactly $secretName @@ -180,7 +185,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } @@ -188,9 +193,11 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { Context "CredMan Store Vault PSCredential type" { - $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) - $randomSecret = [System.IO.Path]::GetRandomFileName() - $errorCode = 0 + BeforeAll { + $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) + $randomSecret = [System.IO.Path]::GetRandomFileName() + $errorCode = 0 + } It "Verifies PSCredential type write to store" { $cred = [pscredential]::new('UserL', (ConvertTo-SecureString $randomSecret -AsPlainText -Force)) @@ -209,7 +216,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outCred, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outCred.UserName | Should -BeExactly "UserL" @@ -222,7 +229,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outInfo, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outInfo.Key | Should -BeExactly $secretName @@ -233,7 +240,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } @@ -241,10 +248,12 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { Context "CredMan Store Vault Hashtable type" { - $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) - $randomSecretA = [System.IO.Path]::GetRandomFileName() - $randomSecretB = [System.IO.Path]::GetRandomFileName() - $errorCode = 0 + BeforeAll { + $secretName = [System.IO.Path]::GetFileNameWithoutExtension([System.IO.Path]::GetRandomFileName()) + $randomSecretA = [System.IO.Path]::GetRandomFileName() + $randomSecretB = [System.IO.Path]::GetRandomFileName() + $errorCode = 0 + } It "Verifies Hashtable type write to store" { $ht = @{ @@ -269,7 +278,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outHT, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outHT.Blob.Count | Should -Be 2 @@ -285,7 +294,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $secretName, [ref] $outInfo, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 $outInfo.Key | Should -BeExactly $secretName @@ -296,7 +305,7 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } diff --git a/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 b/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 index 5c69693..e0db49f 100644 --- a/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 +++ b/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 @@ -2,51 +2,38 @@ # Licensed under the MIT License. Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { + BeforeDiscovery { + $TestCases = 'ByteArray', 'String', 'SecureString', 'PSCredential', 'Hashtable' + } BeforeAll { + $ProjectRoot = Split-Path $PSScriptRoot + $ModulePath = Join-Path $ProjectRoot $ModulePath + $ManifestPath = Join-Path $ModulePath 'Microsoft.PowerShell.SecretManagement.psd1' - if ((Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore) -eq $null) + $BasePath = Join-Path ([IO.Path]::GetTempPath()) "SecretManagementStorePath" + if (-not (Test-Path -Path $BasePath)) { - Import-Module -Name ..\..\Microsoft.PowerShell.SecretManagement + New-Item -ItemType Directory -Path $BasePath | Out-Null } - Get-SecretVault | Unregister-SecretVault + $StorePath = Join-Path $BasePath "StorePath.xml" + $MetaStorePath = Join-Path $BasePath "MetaStorePath.xml" # Script extension module $scriptModuleName = "TVaultScript" $implementingModuleName = "TVaultScript.Extension" $scriptModulePath = Join-Path $testdrive $scriptModuleName - New-Item -ItemType Directory $scriptModulePath -Force - $script:scriptModuleFilePath = Join-Path $scriptModulePath "${scriptModuleName}.psd1" + New-Item -ItemType Directory $scriptModulePath -Force | Out-Null + $scriptModuleFilePath = Join-Path $scriptModulePath "${scriptModuleName}.psd1" "@{{ ModuleVersion = '1.0' NestedModules = @('.\{0}') - FunctionsToExport = @() - }}" -f $implementingModuleName | Out-File -FilePath $script:scriptModuleFilePath + FunctionsToExport = @() + }}" -f $implementingModuleName | Out-File -FilePath $scriptModuleFilePath - # Store Paths - if ($isWindows) - { - $bPath = $env:TEMP - } - else - { - $bPath = [System.Environment]::GetEnvironmentVariable("HOME") - } - if ($bPath -eq $null -or !(Test-Path -Path $bPath)) - { - $bPath = $PSScriptRoot - } - $basePath = Join-Path $bPath "SecretManagementStorePath" - if (! (Test-Path -Path $basePath)) - { - [System.IO.Directory]::CreateDirectory($basePath) - } - $storePath = Join-Path $basePath "StorePath.xml" - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - - $metaStorePath = Join-Path $basePath "MetaStorePath.xml" - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $StorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $MetaStorePath $scriptImplementationTemplate = @' $storePath = "{0}" @@ -182,7 +169,7 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { [hashtable] $AdditionalParameters ) - + RemoveStore $Name RemoveMetaStore $Name }} @@ -284,7 +271,8 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { }} }} '@ - $scriptImplementation = $scriptImplementationTemplate -f $storePath,$metaStorePath + + $scriptImplementation = $scriptImplementationTemplate -f $StorePath, $MetaStorePath $implementingModulePath = Join-Path $scriptModulePath $implementingModuleName New-Item -ItemType Directory $implementingModulePath -Force @@ -299,233 +287,202 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { $manifestInfo | Out-File -FilePath $implementingManifestFilePath $implementingModuleFilePath = Join-Path $implementingModulePath "${implementingModuleName}.psm1" $scriptImplementation | Out-File -FilePath $implementingModuleFilePath - } - - AfterAll { - Unregister-SecretVault -Name ScriptTestVault -ErrorAction Ignore - Remove-Module -Name TVaultScript -Force -ErrorAction Ignore - if ($basePath -ne $null -and (Test-Path -Path $basePath)) + if (-not (Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore)) { - Remove-Item -Path $basePath -Recurse -Force -ErrorAction SilentlyContinue - } - } - - function VerifyByteArrayType - { - param ( - [string] $Title, - [string] $VaultName - ) - - It "Verifies writing byte[] type to $Title vault" { - $bytes = [System.Text.Encoding]::UTF8.GetBytes("BinVaultHelloStr") - Set-Secret -Name BinVaultBlob -Secret $bytes -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - } - - It "Verifies reading byte[] type from $Title vault" { - $blob = Get-Secret -Name BinVaultBlob -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - [System.Text.Encoding]::UTF8.GetString($blob) | Should -BeExactly "BinVaultHelloStr" - } - - It "Verifies enumerating byte[] type from $Title vault" { - $blobInfo = Get-SecretInfo -Name BinVaultBlob -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - $blobInfo.Name | Should -BeExactly "BinVaultBlob" - $blobInfo.Type | Should -BeExactly "ByteArray" - $blobInfo.VaultName | Should -BeExactly $VaultName - } - - It "Verifies removing byte[] type from $Title vault" { - Remove-Secret -Name BinVaultBlob -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultBlob -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' - } - } - - function VerifyStringType - { - param ( - [string] $Title, - [string] $VaultName - ) - - It "Verifies writing string type to $Title vault" { - Set-Secret -Name BinVaultStr -Secret "HelloBinVault" -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - } - - It "Verifies reading string type from $Title vault" { - $str = Get-Secret -Name BinVaultStr -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - ($str -is [SecureString]) | Should -BeTrue - - $str = Get-Secret -Name BinVaultStr -Vault $VaultName -AsPlainText -ErrorVariable err - $err.Count | Should -Be 0 - $str | Should -BeExactly "HelloBinVault" - } - - It "Verifies enumerating string type from $Title vault" { - $strInfo = Get-SecretInfo -Name BinVaultStr -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - $strInfo.Name | Should -BeExactly "BinVaultStr" - $strInfo.Type | Should -BeExactly "String" - $strInfo.VaultName | Should -BeExactly $VaultName - } - - It "Verifies removing string type from $Title vault" { - Remove-Secret -Name BinVaultStr -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultStr -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' + Import-Module -Name $ManifestPath + } + + $PreviousSecretVaults = Get-SecretVault + $PreviousSecretVaults | Unregister-SecretVault + + $StoreTypes = @{ + ByteArray = @{ + Kind = 'ByteArray' + Title = 'script' + Vault = 'ScriptTestVault' + Name = 'BinVaultBlob' + Value = [System.Text.Encoding]::UTF8.GetBytes('BinVaultHelloStr') + Stringifier = { + param([byte[]] $Blob) + + $sb = [System.Text.StringBuilder]::new() + $null = & { + $sb = $sb + foreach ($byte in $Blob) { + $sb.AppendFormat('{0:X2}', $byte) + } + } + + return $sb.ToString() + } + } + String = @{ + Kind = 'String' + Title = 'script' + Vault = 'ScriptTestVault' + Name = 'BinVaultStr' + Value = 'HelloBinVault' + Stringifier = { + if ($args[0] -is [securestring]) { + return & $StoreTypes['SecureString']['Stringifier'] $args[0] + } + + return $args[0] + } + } + SecureString = @{ + Kind = 'SecureString' + Title = 'script' + Vault = 'ScriptTestVault' + Name = 'BinVaultSecureStr' + Value = ConvertTo-SecureString ([System.IO.Path]::GetRandomFileName()) -AsPlainText -Force + Stringifier = { + $ptr = [IntPtr]::Zero + try { + $ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($args[0]) + $value = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) + return $value + } finally { + [System.Runtime.InteropServices.Marshal]::FreeHGlobal($ptr) + } + } + } + PSCredential = @{ + Kind = 'PSCredential' + Title = 'script' + Vault = 'ScriptTestVault' + Name = 'BinVaultCred' + Value = [pscredential]::new('UserName', (ConvertTo-SecureString ([System.IO.Path]::GetRandomFileName()) -AsPlainText -Force)) + Stringifier = { + $networkCred = ([pscredential]$args[0]).GetNetworkCredential() + return "u:$($networkCred.UserName)p:$($networkCred.Password)" + } + } + Hashtable = @{ + Kind = 'Hashtable' + Title = 'script' + Vault = 'ScriptTestVault' + Name = 'BinVaultStr' + Value = @{ + Blob = ([byte[]] @(1,2)) + Str = "Hello" + SecureString = (ConvertTo-SecureString ([System.IO.Path]::GetRandomFileName()) -AsPlainText -Force) + Cred = ([pscredential]::New("UserA", (ConvertTo-SecureString ([System.IO.Path]::GetRandomFileName()) -AsPlainText -Force))) + } + Stringifier = { + param([hashtable] $ht) + end { + $sb = [System.Text.StringBuilder]::new('{') + $null = & { + $sb = $sb + $first = $true + foreach ($entry in $ht.GetEnumerator() | Sort-Object Key) { + if ($first) { + $first = $false + } else { + $sb.Append('|') + } + $sb.Append($entry.Key).Append(':') + if ($entry.Value -is [hashtable]) { + $sb.Append((& $StoreTypes['Hashtable']['Stringifier'] $entry.Value)) + continue + } + + if ($entry.Value -is [securestring]) { + $sb.Append((& $StoreTypes['SecureString']['Stringifier'] $entry.Value)) + continue + } + + if ($entry.Value -is [byte[]] -or $entry.Value -is [object[]]) { + $sb.Append((& $StoreTypes['ByteArray']['Stringifier'] $entry.Value)) + continue + } + + if ($entry.Value -is [pscredential]) { + $sb.Append((& $StoreTypes['PSCredential']['Stringifier'] $entry.Value)) + continue + } + + $sb.Append([string]$entry.Value) + } + + $sb.Append('}') + } + + return $sb.ToString() + } + } + } } } - function VerifySecureStringType - { - param ( - [string] $Title, - [string] $VaultName - ) - - $randomSecret = [System.IO.Path]::GetRandomFileName() - $secureStringToWrite = ConvertTo-SecureString $randomSecret -AsPlainText -Force - - It "Verifies writing SecureString type to $Title vault" { - Set-Secret -Name BinVaultSecureStr -Secret $secureStringToWrite ` - -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - } - - It "Verifies reading SecureString type from $Title vault" { - $ss = Get-Secret -Name BinVaultSecureStr -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - [System.Net.NetworkCredential]::new('',$ss).Password | Should -BeExactly $randomSecret - } - - It "Verifies enumerating SecureString type from $Title vault" { - $ssInfo = Get-SecretInfo -Name BinVaultSecureStr -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - $ssInfo.Name | Should -BeExactly "BinVaultSecureStr" - $ssInfo.Type | Should -BeExactly "SecureString" - $ssInfo.VaultName | Should -BeExactly $VaultName - } - - It "Verifies removing SecureString type from $Title vault" { - Remove-Secret -Name BinVaultSecureStr -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultSecureStr -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' - } + AfterAll { + Unregister-SecretVault -Name ScriptTestVault -ErrorAction Ignore + foreach ($vault in $PreviousSecretVaults) { + $params = @{ + ModuleName = $vault.ModuleName + DefaultVault = $vault.IsDefault + } - It "Verifies SecureString write with alternate parameter set" { - Set-Secret -Name BinVaultSecureStrA -SecureStringSecret $secureStringToWrite ` - -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - } + if ($vault.VaultParameters -and $vault.VaultParameters.Count -gt 0) { + $params['VaultParameters'] = $vault.VaultParameters + } - It "Verifies SecureString read from alternate parameter set" { - $ssRead = Get-Secret -Name BinVaultSecureStrA -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - [System.Net.NetworkCredential]::new('',$ssRead).Password | Should -BeExactly $randomSecret + Register-SecretVault @params } - It "Verifes SecureString remove from alternate parameter set" { - { Remove-Secret -Name BinVaultSecureStrA -Vault $VaultName -ErrorVariable err } | Should -Not -Throw - $err.Count | Should -Be 0 + Remove-Module -Name TVaultScript -Force -ErrorAction Ignore + if ($basePath -ne $null -and (Test-Path -Path $basePath)) + { + Remove-Item -Path $basePath -Recurse -Force -ErrorAction SilentlyContinue } } - function VerifyPSCredentialType - { - param ( - [string] $Title, - [string] $VaultName - ) - - $randomSecret = [System.IO.Path]::GetRandomFileName() + Context "Script extension vault <_> type tests" -ForEach $TestCases { + BeforeAll { + $SecretTestInfo = $StoreTypes[$_] - It "Verifies writing PSCredential to $Title vault" { - $cred = [pscredential]::new('UserName', (ConvertTo-SecureString $randomSecret -AsPlainText -Force)) - Set-Secret -Name BinVaultCred -Secret $cred -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 + Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $StorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $MetaStorePath } - It "Verifies reading PSCredential type from $Title vault" { - $cred = Get-Secret -Name BinVaultCred -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - $cred.UserName | Should -BeExactly "UserName" - [System.Net.NetworkCredential]::new('', ($cred.Password)).Password | Should -BeExactly $randomSecret - } - - It "Verifies enumerating PSCredential type from $Title vault" { - $credInfo = Get-SecretInfo -Name BinVaultCred -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - $credInfo.Name | Should -BeExactly "BinVaultCred" - $credInfo.Type | Should -BeExactly "PSCredential" - $credInfo.VaultName | Should -BeExactly $VaultName + AfterAll { + Get-SecretVault ScriptTestVault | Unregister-SecretVault } - It "Verifies removing PSCredential type from $Title vault" { - Remove-Secret -Name BinVaultCred -Vault $VaultName -ErrorVariable err + It "Verifies writing <_> type to script vault" { + Set-Secret -Name $SecretTestInfo['Name'] -Secret $SecretTestInfo['Value'] -Vault $SecretTestInfo['Vault'] -ErrorVariable err $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultCred -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' } - } - function VerifyHashType - { - param ( - [string] $Title, - [string] $VaultName - ) - - $randomSecretA = [System.IO.Path]::GetRandomFileName() - $randomSecretB = [System.IO.Path]::GetRandomFileName() - - It "Verifies writing Hashtable type to $Title vault" { - $ht = @{ - Blob = ([byte[]] @(1,2)) - Str = "Hello" - SecureString = (ConvertTo-SecureString $randomSecretA -AsPlainText -Force) - Cred = ([pscredential]::New("UserA", (ConvertTo-SecureString $randomSecretB -AsPlainText -Force))) - } - Set-Secret -Name BinVaultHT -Vault $VaultName -Secret $ht -ErrorVariable err + It "Verifies reading <_> type from script vault" { + $result = Get-Secret -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorVariable err $err.Count | Should -Be 0 - } - It "Verifies reading Hashtable type from $Title vault" { - $ht = Get-Secret -Name BinVaultHT -Vault $VaultName -AsPlainText -ErrorVariable err - $err.Count | Should -Be 0 - $ht.Blob.Count | Should -Be 2 - $ht.Str | Should -BeExactly "Hello" - [System.Net.NetworkCredential]::new('', $ht.SecureString).Password | Should -BeExactly $randomSecretA - $ht.Cred.UserName | Should -BeExactly "UserA" - [System.Net.NetworkCredential]::new('', $ht.Cred.Password).Password | Should -BeExactly $randomSecretB + $secretString = & $SecretTestInfo['Stringifier'] $SecretTestInfo['Value'] + $resultString = & $SecretTestInfo['Stringifier'] $result + $resultString | Should -BeExactly $secretString } - It "Verifies enumerating Hashtable type from $Title vault" { - $htInfo = Get-SecretInfo -Name BinVaultHT -Vault $VaultName -ErrorVariable err + It "Verifies enumerating <_> type from script vault" { + $blobInfo = Get-SecretInfo -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorVariable err $err.Count | Should -Be 0 - $htInfo.Name | Should -BeExactly "BinVaultHT" - $htInfo.Type | Should -BeExactly "Hashtable" - $htInfo.VaultName | Should -BeExactly $VaultName + $blobInfo.Name | Should -BeExactly $SecretTestInfo['Name'] + $blobInfo.Type | Should -BeExactly $SecretTestInfo['Kind'] + $blobInfo.VaultName | Should -BeExactly $SecretTestInfo['Vault'] } - It "Verifies removing Hashtable type from $Title vault" { - Remove-Secret -Name BinVaultHT -Vault $VaultName -ErrorVariable err + It "Verifies removing <_> type from script vault" { + Remove-Secret -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorVariable err $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultHT -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' + { Get-Secret -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorAction Stop } | + Should -Throw -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' } } Context "API Tests" { - It "Verifies the SecretInformation constructor" { $metadata = @{ Name='Name1'; Target='Target1' } $secretInfo = [Microsoft.PowerShell.SecretManagement.SecretInformation]::new( @@ -544,15 +501,17 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { Context "Script extension (non-default) vault tests" { - $randomSecretD = [System.IO.Path]::GetRandomFileName() + BeforeAll { + $randomSecretD = [System.IO.Path]::GetRandomFileName() + } It "Verifies reserved 'Verbose' keyword in VaultParameters throws expected error" { - { Register-SecretVault -Name ScriptTestVault -ModuleName $script:scriptModuleFilePath -VaultParameters @{ Verbose = $true } } | Should -Throw -ErrorId 'RegisterSecretVaultCommandCannotUseReservedName,Microsoft.PowerShell.SecretManagement.RegisterSecretVaultCommand' + { Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath -VaultParameters @{ Verbose = $true } } | Should -Throw -ErrorId 'RegisterSecretVaultCommandCannotUseReservedName,Microsoft.PowerShell.SecretManagement.RegisterSecretVaultCommand' } It "Should register the script vault extension successfully but with invalid parameters" { $additionalParameters = @{ Hello = "There" } - { Register-SecretVault -Name ScriptTestVault -ModuleName $script:scriptModuleFilePath -VaultParameters $additionalParameters -ErrorVariable err } | Should -Not -Throw + { Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath -VaultParameters $additionalParameters -ErrorVariable err } | Should -Not -Throw $err.Count | Should -Be 0 } @@ -576,7 +535,7 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { It "Should register the script vault extension successfully" { $additionalParameters = @{ AccessId = "AccessAT"; SubscriptionId = "1234567890" } - { Register-SecretVault -Name ScriptTestVault -ModuleName $script:scriptModuleFilePath -VaultParameters $additionalParameters ` + { Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath -VaultParameters $additionalParameters ` -Description 'ScriptTestVaultDescription' -ErrorVariable err } | Should -Not -Throw $err.Count | Should -Be 0 } @@ -587,7 +546,8 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { It "Should throw error when registering existing registered vault extension" { $additionalParameters = @{ AccessId = "AccessAT"; SubscriptionId = "1234567890" } - { Register-SecretVault -Name ScriptTestVault -ModuleName $script:scriptModuleFilePath -VaultParameters $additionalParameters } | Should -Throw -ErrorId 'RegisterSecretVaultInvalidVaultName' + { Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath -VaultParameters $additionalParameters } | + Should -Throw -ErrorId 'RegisterSecretVaultInvalidVaultName,Microsoft.PowerShell.SecretManagement.RegisterSecretVaultCommand' } It "Verifies Test-SecretVault succeeds" { @@ -626,23 +586,26 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { } It "Verifies Unlock-SecretVault command" { - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $StorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $MetaStorePath Unlock-SecretVault -Name ScriptTestVault -Password (ConvertTo-SecureString -String $randomSecretD -AsPlainText -Force) -ErrorVariable err 2>$null # Verify vault 'Unlock-SecretVault' function was called. - $dict = Import-Clixml -Path $storePath + $dict = Import-Clixml -Path $StorePath $dict['UnlockState'] | Should -BeExactly '0x11580' } } Context "Set-SecretVaultDefault cmdlet tests" { - $randomSecretE = [System.IO.Path]::GetRandomFileName() + BeforeAll { + $randomSecretE = [System.IO.Path]::GetRandomFileName() + } It "Should throw error when setting non existent vault as default" { - { Set-SecretVaultDefault -Name NoSuchVault } | Should -Throw -ErrorId 'VaultNotFound,Microsoft.PowerShell.SecretManagement.SetSecretVaultDefaultCommand' + { Set-SecretVaultDefault -Name NoSuchVault } | + Should -Throw -ErrorId 'VaultNotFound,Microsoft.PowerShell.SecretManagement.SetSecretVaultDefaultCommand' } It "Verifies cmdlet successfully sets default vault" { @@ -663,56 +626,16 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { } } - Context "Script extension vault byte[] type tests" { - - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath - - VerifyByteArrayType -Title "script" -VaultName "ScriptTestVault" - } - - Context "Script extension vault String type tests" { - - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath - - VerifyStringType -Title "script" -VaultName "ScriptTestVault" - } - - Context "Script extension vault SecureString type tests" { - - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath - - VerifySecureStringType -Title "script" -VaultName "ScriptTestVault" - } - - Context "Script extension vault PSCredential type tests" { - - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath - - VerifyPSCredentialType -Title "script" -VaultName "ScriptTestVault" - } - - Context "Script extension vault Hashtable type tests" { - - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath - - VerifyHashType -Title "script" -VaultName "ScriptTestVault" - } - Context "Unregister-SecretVault cmdlet tests" { It "Verifies unregister operation calls the extension 'Unregister-SecretVault' function before unregistering" { - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $storePath - [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-CliXml -Path $metaStorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $StorePath + [System.Collections.Generic.Dictionary[[string],[object]]]::new() | Export-Clixml -Path $MetaStorePath { Unregister-SecretVault -Name ScriptTestVault -ErrorVariable err } | Should -Not -Throw $err.Count | Should -Be 0 - $store = Import-Clixml -Path $storePath + $store = Import-Clixml -Path $StorePath $store['UnRegisterSecretVaultCalled'] | Should -BeTrue <# From 051a60fd0f601d92413926adf8cf24d6f51bee6e Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 15:21:31 -0400 Subject: [PATCH 07/10] Change attribute formatting --- src/code/SecretManagement.cs | 186 +++++++++++++++++++---------------- 1 file changed, 103 insertions(+), 83 deletions(-) diff --git a/src/code/SecretManagement.cs b/src/code/SecretManagement.cs index 5c00cc1..2a7d8a4 100644 --- a/src/code/SecretManagement.cs +++ b/src/code/SecretManagement.cs @@ -97,7 +97,7 @@ public IEnumerable CompleteArgument( var wordToCompletePattern = WildcardPattern.Get( pattern: string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", options: WildcardOptions.IgnoreCase); - + foreach (var vaultName in _vaultExtensions.Keys) { if (wordToCompletePattern.IsMatch(vaultName)) @@ -110,7 +110,7 @@ public IEnumerable CompleteArgument( } #endregion - + #region Register-SecretVault /// @@ -125,7 +125,7 @@ public sealed class RegisterSecretVaultCommand : PSCmdlet /// /// Gets or sets the module name or file path of the vault extension module to register. /// - [Parameter(Position=0, Mandatory=true)] + [Parameter(Position = 0, Mandatory = true)] [ValidateNotNullOrEmpty] public string ModuleName { get; set; } @@ -134,13 +134,13 @@ public sealed class RegisterSecretVaultCommand : PSCmdlet /// The name must be unique. /// If no Name is provided then the ModuleName is used as the friendly name. /// - [Parameter(Position=1)] + [Parameter(Position = 1)] [ValidateNotNullOrEmpty] public string Name { get; set; } /// /// Gets or sets an optional Hashtable of parameters by name/value pairs. - /// The hashtable is stored securely in the local store, and is made available to the + /// The hashtable is stored securely in the local store, and is made available to the /// extension implementing module script functions. /// [Parameter] @@ -266,7 +266,7 @@ protected override void EndProcessing() error: out ErrorRecord moduleLoadError); if (moduleInfo == null) { - var msg = string.Format(CultureInfo.InvariantCulture, + var msg = string.Format(CultureInfo.InvariantCulture, "Could not load and retrieve module information for module: {0} with error : {1}.", ModuleName, moduleLoadError?.ToString() ?? string.Empty); @@ -387,8 +387,8 @@ private static bool CheckForImplementingModule( if (moduleInfo == null) { error = new ItemNotFoundException( - string.Format(CultureInfo.InvariantCulture, - @"Implementing script module could not be found or loaded at : {0} with error : {1}.", + string.Format(CultureInfo.InvariantCulture, + @"Implementing script module could not be found or loaded at : {0} with error : {1}.", implementingModulePath, moduleLoadError?.ToString() ?? string.Empty)); return false; } @@ -559,20 +559,22 @@ public sealed class UnregisterSecretVaultCommand : PSCmdlet /// /// Gets or sets a name of the secret vault to unregister. /// - [Parameter(ParameterSetName = NameParameterSet, - Position = 0, - Mandatory = true, - ValueFromPipeline = true)] + [Parameter( + ParameterSetName = NameParameterSet, + Position = 0, + Mandatory = true, + ValueFromPipeline = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] [SupportsWildcards] [ValidateNotNullOrEmpty] public string[] Name { get; set; } - [Parameter(ParameterSetName = SecretVaultParameterSet, - Position = 0, - Mandatory = true, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] + [Parameter( + ParameterSetName = SecretVaultParameterSet, + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public SecretVaultInfo SecretVault { get; set; } @@ -591,7 +593,7 @@ protected override void ProcessRecord() case NameParameterSet: vaultNames = Name; break; - + case SecretVaultParameterSet: vaultNames = new string[] { SecretVault.Name }; break; @@ -657,7 +659,7 @@ private void RemoveVault(string vaultName) RegisteredVaultCache.Remove(vaultName); WriteVerbose( - string.Format(CultureInfo.InvariantCulture, + string.Format(CultureInfo.InvariantCulture, "Removed vault {0} from registry.", extensionVault.VaultName) ); } @@ -684,10 +686,11 @@ public sealed class SetSecretVaultDefaultCommand : PSCmdlet /// /// Gets or sets a name of the secret vault to unregister. /// - [Parameter(ParameterSetName = NameParameterSet, - Position = 0, - Mandatory = true, - ValueFromPipeline = true)] + [Parameter( + ParameterSetName = NameParameterSet, + Position = 0, + Mandatory = true, + ValueFromPipeline = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] [ValidateNotNullOrEmpty] public string Name { get; set; } @@ -695,11 +698,12 @@ public sealed class SetSecretVaultDefaultCommand : PSCmdlet /// /// Gets or sets a SecretVaultInfo object that describes a vault that will be made the default vault /// - [Parameter(ParameterSetName = SecretVaultParameterSet, - Position = 0, - Mandatory = true, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true)] + [Parameter( + ParameterSetName = SecretVaultParameterSet, + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public SecretVaultInfo SecretVault { get; set; } @@ -726,7 +730,7 @@ protected override void EndProcessing() case NameParameterSet: vaultName = Name; break; - + case SecretVaultParameterSet: vaultName = SecretVault.Name; break; @@ -814,7 +818,7 @@ public IEnumerable CompleteArgument( args: new object[] {}, psToUse: ps, out ErrorRecord error); - + _secretNames = new List(); foreach (var secretInfo in results) { @@ -828,7 +832,7 @@ public IEnumerable CompleteArgument( var wordToCompletePattern = WildcardPattern.Get( pattern: string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", options: WildcardOptions.IgnoreCase); - + foreach (var secretName in _secretNames) { if (wordToCompletePattern.IsMatch(secretName)) @@ -857,7 +861,7 @@ public sealed class GetSecretVaultCommand : SecretCmdlet /// /// Gets or sets an optional name of the secret vault to return. /// - [Parameter (Position=0)] + [Parameter(Position = 0)] [ArgumentCompleter(typeof(VaultNameCompleter))] [SupportsWildcards] public string[] Name { get; set; } @@ -929,7 +933,7 @@ public sealed class UnlockSecretVaultCommand : SecretCmdlet /// /// Gets or sets the name of the secret vault to unlock. /// - [Parameter (Position=0, Mandatory=true)] + [Parameter(Position = 0, Mandatory = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] [ValidateNotNullOrEmpty] public string Name { get; set; } @@ -937,7 +941,7 @@ public sealed class UnlockSecretVaultCommand : SecretCmdlet /// /// Gets or sets a password for unlocking a vault. /// - [Parameter (Position=1, Mandatory=true)] + [Parameter(Position = 1, Mandatory = true)] public SecureString Password { get; set; } #endregion @@ -974,7 +978,7 @@ public sealed class GetSecretInfoCommand : SecretCmdlet /// /// Gets or sets a name used to match and return secret information. /// - [Parameter(Position=0)] + [Parameter(Position = 0)] [ArgumentCompleter(typeof(SecretNameCompleter))] [SupportsWildcards] public string Name { get; set; } @@ -982,7 +986,7 @@ public sealed class GetSecretInfoCommand : SecretCmdlet /// /// Gets or sets an optional name of the vault to retrieve the secret from. /// - [Parameter(Position=1)] + [Parameter(Position = 1)] [ArgumentCompleter(typeof(VaultNameCompleter))] public string Vault { get; set; } @@ -1021,7 +1025,7 @@ protected override void EndProcessing() // Then search through all other extension vaults. foreach (var extensionModule in RegisteredVaultCache.VaultExtensions.Values) { - if (extensionModule.VaultName.Equals(RegisteredVaultCache.DefaultVaultName, + if (extensionModule.VaultName.Equals(RegisteredVaultCache.DefaultVaultName, StringComparison.OrdinalIgnoreCase)) { continue; @@ -1101,7 +1105,7 @@ public sealed class SetSecretInfoCommand : SecretCmdlet /// /// Gets or sets a name of the secret to which metadata is applied. /// - [Parameter(Position=0, Mandatory=true, ParameterSetName=NameParameterSet)] + [Parameter(Position = 0, Mandatory = true, ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(SecretNameCompleter))] [ValidateNotNullOrEmpty] public string Name { get; set; } @@ -1110,18 +1114,18 @@ public sealed class SetSecretInfoCommand : SecretCmdlet /// Gets or sets the metadata Hashtable to be applied to the secret name. /// If value is an empty Hashtable, then any previous secret metadata is removed. /// - [Parameter(Position=1, Mandatory=true, ValueFromPipeline=true, ParameterSetName=NameParameterSet)] - [Parameter(Position=0, Mandatory=true, ParameterSetName=InfoParameterSet)] + [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = NameParameterSet)] + [Parameter(Position = 0, Mandatory = true, ParameterSetName = InfoParameterSet)] public Hashtable Metadata { get; set; } /// /// Gets or sets an optional extension vault name. /// - [Parameter(Position=2, ParameterSetName=NameParameterSet)] + [Parameter(Position = 2, ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(VaultNameCompleter))] public string Vault { get; set; } - [Parameter(Mandatory=true, ValueFromPipeline=true, ParameterSetName=InfoParameterSet)] + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = InfoParameterSet)] public SecretInformation InputObject { get; set; } #endregion @@ -1212,9 +1216,9 @@ public sealed class GetSecretCommand : SecretCmdlet /// /// Gets or sets a name of secret to retrieve. /// - [Parameter(Position=0, - Mandatory=true, - ValueFromPipeline=true, + [Parameter(Position = 0, + Mandatory = true, + ValueFromPipeline = true, ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(SecretNameCompleter))] public string Name { get; set; } @@ -1222,15 +1226,15 @@ public sealed class GetSecretCommand : SecretCmdlet /// /// Gets or sets an optional name of the vault to retrieve the secret from. /// - [Parameter(Position=1, ParameterSetName = NameParameterSet)] + [Parameter(Position = 1, ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(VaultNameCompleter))] public string Vault { get; set; } /// /// Gets or sets a SecretInformation object that describes the secret to be retrieved. /// - [Parameter(Mandatory=true, - ValueFromPipeline=true, + [Parameter(Mandatory = true, + ValueFromPipeline = true, ParameterSetName = InfoParameterSet)] public SecretInformation InputObject { get; set; } @@ -1300,7 +1304,7 @@ protected override void ProcessRecord() // Then search through all other extension vaults. foreach (var extensionModule in RegisteredVaultCache.VaultExtensions.Values) { - if (extensionModule.VaultName.Equals(RegisteredVaultCache.DefaultVaultName, + if (extensionModule.VaultName.Equals(RegisteredVaultCache.DefaultVaultName, StringComparison.OrdinalIgnoreCase)) { continue; @@ -1327,7 +1331,7 @@ private InvokeResult TryInvokeAndWrite(ExtensionVaultModule extensionModule) name: Name, vaultName: extensionModule.VaultName, cmdlet: this); - + if (result != null) { WriteSecret(result); @@ -1413,11 +1417,14 @@ private void WriteNotFoundError() #region Set-Secret /// - /// Adds a provided secret to the specified extension vault, + /// Adds a provided secret to the specified extension vault, /// or the built-in default store if an extension vault is not specified. /// - [Cmdlet(VerbsCommon.Set, "Secret", SupportsShouldProcess = true, - DefaultParameterSetName = SecureStringParameterSet)] + [Cmdlet( + VerbsCommon.Set, + "Secret", + SupportsShouldProcess = true, + DefaultParameterSetName = SecureStringParameterSet)] public sealed class SetSecretCommand : SecretCmdlet { #region Members @@ -1434,8 +1441,8 @@ public sealed class SetSecretCommand : SecretCmdlet /// /// Gets or sets a name of the secret to be added. /// - [Parameter(ParameterSetName = ObjectParameterSet, Position=0, Mandatory=true)] - [Parameter(ParameterSetName = SecureStringParameterSet, Position=0, Mandatory=true)] + [Parameter(ParameterSetName = ObjectParameterSet, Position = 0, Mandatory = true)] + [Parameter(ParameterSetName = SecureStringParameterSet, Position = 0, Mandatory = true)] [ValidateNotNullOrEmpty] public string Name { get; set; } @@ -1448,35 +1455,44 @@ public sealed class SetSecretCommand : SecretCmdlet /// Hashtable /// byte[] /// - [Parameter(Position=1, Mandatory=true, ValueFromPipeline=true, - ParameterSetName = ObjectParameterSet)] + [Parameter( + Position = 1, + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = ObjectParameterSet)] public object Secret { get; set; } /// /// Gets or sets a SecureString value to be added to a vault. /// - [Parameter(Position=1, Mandatory=true, ValueFromPipeline=true, - ParameterSetName = SecureStringParameterSet)] + [Parameter( + Position = 1, + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = SecureStringParameterSet)] public SecureString SecureStringSecret { get; set; } - [Parameter(Position=1, Mandatory=true, ValueFromPipeline=true, - ParameterSetName = SecretInfoParameterSet)] + [Parameter( + Position = 1, + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = SecretInfoParameterSet)] public SecretInformation SecretInfo { get; set; } /// /// Gets or sets an optional extension vault name. /// - [Parameter(Position=2, ParameterSetName = ObjectParameterSet)] - [Parameter(Position=2, ParameterSetName = SecureStringParameterSet)] - [Parameter(ParameterSetName = SecretInfoParameterSet, Mandatory=true)] + [Parameter(Position = 2, ParameterSetName = ObjectParameterSet)] + [Parameter(Position = 2, ParameterSetName = SecureStringParameterSet)] + [Parameter(ParameterSetName = SecretInfoParameterSet, Mandatory = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] public string Vault { get; set; } /// /// Gets or sets optional secret metadata /// - [Parameter(Position=3, ParameterSetName = ObjectParameterSet)] - [Parameter(Position=3, ParameterSetName = SecureStringParameterSet)] + [Parameter(Position = 3, ParameterSetName = ObjectParameterSet)] + [Parameter(Position = 3, ParameterSetName = SecureStringParameterSet)] public Hashtable Metadata { get; set; } /// @@ -1521,7 +1537,7 @@ protected override void ProcessRecord() extensionModule: destExtensionModule, name: SecretInfo.Name)) { - var msg = string.Format(CultureInfo.InvariantCulture, + var msg = string.Format(CultureInfo.InvariantCulture, SecretExistsError, SecretInfo.Name, destExtensionModule.VaultName); WriteError( new ErrorRecord( @@ -1531,7 +1547,7 @@ protected override void ProcessRecord() this)); return; } - + // Set secret to specified vault name. destExtensionModule.InvokeSetSecret( name: SecretInfo.Name, @@ -1592,7 +1608,7 @@ private void WriteSecret( extensionModule: extensionModule, name: Name)) { - var msg = string.Format(CultureInfo.InvariantCulture, + var msg = string.Format(CultureInfo.InvariantCulture, SecretExistsError, Name, extensionModule.VaultName); ThrowTerminatingError( new ErrorRecord( @@ -1648,10 +1664,11 @@ public sealed class RemoveSecretCommand : SecretCmdlet /// /// Gets or sets a name of the secret to be removed. /// - [Parameter(Position=0, - Mandatory=true, - ValueFromPipeline=true, - ParameterSetName=NameParameterSet)] + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(SecretNameCompleter))] [ValidateNotNullOrEmpty] public string Name { get; set; } @@ -1659,17 +1676,19 @@ public sealed class RemoveSecretCommand : SecretCmdlet /// /// Gets or sets an optional extension vault name. /// - [Parameter(Position=1, - Mandatory=true, - ParameterSetName=NameParameterSet)] + [Parameter( + Position = 1, + Mandatory = true, + ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(VaultNameCompleter))] [ValidateNotNullOrEmpty] public string Vault { get; set; } - [Parameter(Position=0, - Mandatory=true, - ValueFromPipeline=true, - ParameterSetName=InfoParameterSet)] + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = InfoParameterSet)] public SecretInformation InputObject { get; set; } #endregion @@ -1713,9 +1732,10 @@ public sealed class TestSecretVaultCommand : SecretCmdlet { #region Parameters - [Parameter(Position=0, - ValueFromPipeline=true, - ValueFromPipelineByPropertyName=true)] + [Parameter( + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] [SupportsWildcards] public string[] Name { get; set; } From f419463fd259f62f7fe553dce531b3f01e637900 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 15:58:55 -0400 Subject: [PATCH 08/10] Fix C# xml docs --- SecretManagement.build.ps1 | 3 +- ...PowerShell.SecretManagement.Library.nuspec | 1 + ...crosoft.PowerShell.SecretManagement.csproj | 7 +- src/code/SecretManagement.cs | 71 +++++++++++++++++-- src/code/Utils.cs | 41 +++++++++-- 5 files changed, 112 insertions(+), 11 deletions(-) diff --git a/SecretManagement.build.ps1 b/SecretManagement.build.ps1 index 7e47a6c..4a5363a 100644 --- a/SecretManagement.build.ps1 +++ b/SecretManagement.build.ps1 @@ -16,6 +16,7 @@ $HelpOut = Join-Path $ModuleOut en-US $CSharpArtifacts = @( "$FullModuleName.dll", "$FullModuleName.pdb", + "$FullModuleName.xml", "System.Runtime.InteropServices.RuntimeInformation.dll") $BaseArtifacts = @( @@ -77,8 +78,6 @@ task BuildModule { $manifestContent = Get-Content -LiteralPath $ManifestPath -Raw $newManifestContent = $manifestContent -replace '{{ModuleVersion}}', $moduleVersion Set-Content -LiteralPath "$ModuleOut/$FullModuleName.psd1" -Encoding utf8 -Value $newManifestContent - - # New-ExternalHelp -Path docs/Microsoft.PowerShell.ConsoleGuiTools -OutputPath module/en-US -Force } task PackageModule { diff --git a/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec b/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec index af4dfc3..dcb7bd8 100644 --- a/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec +++ b/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec @@ -29,5 +29,6 @@ + diff --git a/src/code/Microsoft.PowerShell.SecretManagement.csproj b/src/code/Microsoft.PowerShell.SecretManagement.csproj index 854e418..682d86d 100644 --- a/src/code/Microsoft.PowerShell.SecretManagement.csproj +++ b/src/code/Microsoft.PowerShell.SecretManagement.csproj @@ -13,10 +13,15 @@ $(ModuleVersion) $(ModuleVersion) net461 + true - + + + + + diff --git a/src/code/SecretManagement.cs b/src/code/SecretManagement.cs index 2a7d8a4..2e9b6db 100644 --- a/src/code/SecretManagement.cs +++ b/src/code/SecretManagement.cs @@ -174,6 +174,9 @@ public sealed class RegisterSecretVaultCommand : PSCmdlet #region Overrides + /// + /// Performs initialization of command execution. + /// protected override void BeginProcessing() { // Disallow 'Verbose' in VaultParameters because it is reserved. @@ -224,6 +227,9 @@ protected override void BeginProcessing() } } + /// + /// Performs clean-up after the command execution. + /// protected override void EndProcessing() { var vaultInfo = new Hashtable(); @@ -569,6 +575,9 @@ public sealed class UnregisterSecretVaultCommand : PSCmdlet [ValidateNotNullOrEmpty] public string[] Name { get; set; } + /// + /// Gets or sets the secret vault to unregister. + /// [Parameter( ParameterSetName = SecretVaultParameterSet, Position = 0, @@ -717,6 +726,9 @@ public sealed class SetSecretVaultDefaultCommand : PSCmdlet #region Overrides + /// + /// Performs clean-up after the command execution. + /// protected override void EndProcessing() { if (!ShouldProcess(Name, "Set vault as default")) @@ -767,6 +779,9 @@ protected override void EndProcessing() #region SecretCmdlet + /// + /// Base type for Secret cmdlets. + /// public abstract class SecretCmdlet : PSCmdlet { /// @@ -860,7 +875,7 @@ public sealed class GetSecretVaultCommand : SecretCmdlet /// /// Gets or sets an optional name of the secret vault to return. - /// + /// [Parameter(Position = 0)] [ArgumentCompleter(typeof(VaultNameCompleter))] [SupportsWildcards] @@ -870,6 +885,9 @@ public sealed class GetSecretVaultCommand : SecretCmdlet #region Overrides + /// + /// Performs clean-up after the command execution. + /// protected override void EndProcessing() { Name = Name ?? new string[] { "*" }; @@ -932,7 +950,7 @@ public sealed class UnlockSecretVaultCommand : SecretCmdlet /// /// Gets or sets the name of the secret vault to unlock. - /// + /// [Parameter(Position = 0, Mandatory = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] [ValidateNotNullOrEmpty] @@ -948,6 +966,9 @@ public sealed class UnlockSecretVaultCommand : SecretCmdlet #region Overrides + /// + /// Performs clean-up after the command execution. + /// protected override void EndProcessing() { var extensionModule = GetExtensionVault(Name); @@ -994,12 +1015,18 @@ public sealed class GetSecretInfoCommand : SecretCmdlet #region Overrides + /// + /// Performs initialization of command execution. + /// protected override void BeginProcessing() { base.BeginProcessing(); Utils.CheckForRegisteredVaults(this); } + /// + /// Performs clean-up after the command execution. + /// protected override void EndProcessing() { if (string.IsNullOrEmpty(Name)) @@ -1125,6 +1152,9 @@ public sealed class SetSecretInfoCommand : SecretCmdlet [ArgumentCompleter(typeof(VaultNameCompleter))] public string Vault { get; set; } + /// + /// Gets or sets the secret to set. + /// [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = InfoParameterSet)] public SecretInformation InputObject { get; set; } @@ -1132,12 +1162,18 @@ public sealed class SetSecretInfoCommand : SecretCmdlet #region Overrides + /// + /// Performs initialization of command execution. + /// protected override void BeginProcessing() { base.BeginProcessing(); Utils.CheckForRegisteredVaults(this); } + /// + /// Performs execution of the command. + /// protected override void ProcessRecord() { if (!ShouldProcess(Vault, "Write secret metadata to vault and override any existing metadata associated with the secret")) @@ -1215,7 +1251,7 @@ public sealed class GetSecretCommand : SecretCmdlet /// /// Gets or sets a name of secret to retrieve. - /// + /// [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, @@ -1260,12 +1296,18 @@ enum InvokeResult #region Overrides + /// + /// Performs initialization of command execution. + /// protected override void BeginProcessing() { base.BeginProcessing(); Utils.CheckForRegisteredVaults(this); } + /// + /// Performs execution of the command. + /// protected override void ProcessRecord() { if (ParameterSetName == InfoParameterSet) @@ -1472,6 +1514,9 @@ public sealed class SetSecretCommand : SecretCmdlet ParameterSetName = SecureStringParameterSet)] public SecureString SecureStringSecret { get; set; } + /// + /// Gets or sets the secret to set. + /// [Parameter( Position = 1, Mandatory = true, @@ -1505,12 +1550,18 @@ public sealed class SetSecretCommand : SecretCmdlet #region Overrides + /// + /// Performs initialization of command execution. + /// protected override void BeginProcessing() { base.BeginProcessing(); Utils.CheckForRegisteredVaults(this); } + /// + /// Performs execution of the command. + /// protected override void ProcessRecord() { if (!ShouldProcess(Vault, "Write secret to vault and override any existing secret of the same name")) @@ -1648,7 +1699,7 @@ private bool SecretExistsInVault( /// /// Removes a secret by name from the local default vault. - /// + /// [Cmdlet(VerbsCommon.Remove, "Secret", SupportsShouldProcess = true)] public sealed class RemoveSecretCommand : SecretCmdlet { @@ -1684,6 +1735,9 @@ public sealed class RemoveSecretCommand : SecretCmdlet [ValidateNotNullOrEmpty] public string Vault { get; set; } + /// + /// Gets or sets the secret to be removed. + /// [Parameter( Position = 0, Mandatory = true, @@ -1695,6 +1749,9 @@ public sealed class RemoveSecretCommand : SecretCmdlet #region Overrides + /// + /// Performs execution of the command. + /// protected override void ProcessRecord() { if (!ShouldProcess(Vault, "Remove secret by name from vault")) @@ -1732,6 +1789,9 @@ public sealed class TestSecretVaultCommand : SecretCmdlet { #region Parameters + /// + /// Gets or sets the secret name. + /// [Parameter( Position = 0, ValueFromPipeline = true, @@ -1744,6 +1804,9 @@ public sealed class TestSecretVaultCommand : SecretCmdlet #region Overrides + /// + /// Performs execution of the command. + /// protected override void ProcessRecord() { Name = Name ?? new string[] { "*" }; diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 8e7498b..3fba6e7 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -173,22 +173,52 @@ public static void CheckForRegisteredVaults(PSCmdlet cmdlet) /// public enum SecretType { + /// + /// Specifies the value is of an unknown type. + /// Unknown = 0, + + /// + /// Specifes the value is a . + /// ByteArray, + + /// + /// Specifes the value is a . + /// String, + + /// + /// Specifes the value is a . + /// SecureString, + + /// + /// Specifies the value is a . + /// PSCredential, - Hashtable - }; + + /// + /// Specifes the value is a . + /// + Hashtable, + } #endregion #region Exceptions + /// + /// Represents errors that occur due to a password not being specified when required. + /// public sealed class PasswordRequiredException : InvalidOperationException { #region Constructor + /// + /// Initializes a new instance of the class. + /// + /// The message that describes the error. public PasswordRequiredException(string msg) : base(msg) { @@ -201,6 +231,9 @@ public PasswordRequiredException(string msg) #region SecretInformation class + /// + /// Represents a secret from a secret vault. + /// public sealed class SecretInformation { #region Properties @@ -442,7 +475,7 @@ internal class ExtensionVaultModule /// /// Additional vault parameters. - /// + /// public IReadOnlyDictionary VaultParameters { get; } /// @@ -1197,6 +1230,7 @@ public static Hashtable GetAll() /// /// Add item to cache. /// + /// The key of the vault to add. /// Hashtable of vault information. /// When true, this vault is designated as the default vault. /// When true, this will overwrite an existing vault with the same name. @@ -1423,7 +1457,6 @@ private static void DeleteSecretVaultRegistryFile() /// /// Hashtable containing registered vault information. /// The default vault name. - /// private static void WriteSecretVaultRegistry( Hashtable vaultInfo, string defaultVaultName) From 73598edccc1a6a601cb8922e6e624885c9a90e0c Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Thu, 27 Jun 2024 18:23:58 -0400 Subject: [PATCH 09/10] Fix building credman for tests --- ExtensionModules/CredManStore/build.ps1 | 115 ------------------ ExtensionModules/CredManStore/doBuild.ps1 | 73 ----------- .../CredManStore/pspackageproject.json | 9 -- SecretManagement.build.ps1 | 5 +- 4 files changed, 3 insertions(+), 199 deletions(-) delete mode 100644 ExtensionModules/CredManStore/build.ps1 delete mode 100644 ExtensionModules/CredManStore/doBuild.ps1 delete mode 100644 ExtensionModules/CredManStore/pspackageproject.json diff --git a/ExtensionModules/CredManStore/build.ps1 b/ExtensionModules/CredManStore/build.ps1 deleted file mode 100644 index a6c65df..0000000 --- a/ExtensionModules/CredManStore/build.ps1 +++ /dev/null @@ -1,115 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -# Do NOT edit this file. Edit dobuild.ps1 -[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")] -param ( - [Parameter(ParameterSetName="build")] - [switch] - $Clean, - - [Parameter(ParameterSetName="build")] - [switch] - $Build, - - [Parameter(ParameterSetName="publish")] - [switch] - $Publish, - - [Parameter(ParameterSetName="publish")] - [switch] - $Signed, - - [Parameter(ParameterSetName="build")] - [switch] - $Test, - - [Parameter(ParameterSetName="build")] - [string[]] - [ValidateSet("Functional","StaticAnalysis")] - $TestType = @("Functional"), - - [Parameter(ParameterSetName="help")] - [switch] - $UpdateHelp, - - [ValidateSet("Debug", "Release")] - [string] $BuildConfiguration = "Debug", - - [ValidateSet("netstandard2.0")] - [string] $BuildFramework = "netstandard2.0" -) - -if ( ! ( Get-Module -ErrorAction SilentlyContinue PSPackageProject) ) { - Install-Module PSPackageProject -} - -$config = Get-PSPackageProjectConfiguration -ConfigPath $PSScriptRoot - -$script:ModuleName = $config.ModuleName -$script:SrcPath = $config.SourcePath -$script:OutDirectory = $config.BuildOutputPath -$script:SignedDirectory = $config.SignedOutputPath -$script:TestPath = $config.TestPath - -$script:ModuleRoot = $PSScriptRoot -$script:Culture = $config.Culture -$script:HelpPath = $config.HelpPath - -$script:BuildConfiguration = $BuildConfiguration -$script:BuildFramework = $BuildFramework - -if ($env:TF_BUILD) { - $vstsCommandString = "vso[task.setvariable variable=BUILD_OUTPUT_PATH]$OutDirectory" - Write-Host ("sending " + $vstsCommandString) - Write-Host "##$vstsCommandString" - - $vstsCommandString = "vso[task.setvariable variable=SIGNED_OUTPUT_PATH]$SignedDirectory" - Write-Host ("sending " + $vstsCommandString) - Write-Host "##$vstsCommandString" -} - -. $PSScriptRoot/doBuild.ps1 - -if ($Clean -and (Test-Path $OutDirectory)) -{ - Remove-Item -Path $OutDirectory -Force -Recurse -ErrorAction Stop -Verbose - - if (Test-Path "${SrcPath}/code/bin") - { - Remove-Item -Path "${SrcPath}/code/bin" -Recurse -Force -ErrorAction Stop -Verbose - } - - if (Test-Path "${SrcPath}/code/obj") - { - Remove-Item -Path "${SrcPath}/code/obj" -Recurse -Force -ErrorAction Stop -Verbose - } -} - -if (-not (Test-Path $OutDirectory)) -{ - $script:OutModule = New-Item -ItemType Directory -Path (Join-Path $OutDirectory $ModuleName) -} -else -{ - $script:OutModule = Join-Path $OutDirectory $ModuleName -} - -if ($Build.IsPresent) -{ - $sb = (Get-Item Function:DoBuild).ScriptBlock - Invoke-PSPackageProjectBuild -BuildScript $sb -SkipPublish -} - -if ($Publish.IsPresent) -{ - Invoke-PSPackageProjectPublish -Signed:$Signed.IsPresent -} - -if ( $Test.IsPresent ) { - Invoke-PSPackageProjectTest -Type $TestType -} - -if ($UpdateHelp.IsPresent) { - Add-PSPackageProjectCmdletHelp -ProjectRoot $ModuleRoot -ModuleName $ModuleName -Culture $Culture -} diff --git a/ExtensionModules/CredManStore/doBuild.ps1 b/ExtensionModules/CredManStore/doBuild.ps1 deleted file mode 100644 index f3ca6a1..0000000 --- a/ExtensionModules/CredManStore/doBuild.ps1 +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. - -<# -.DESCRIPTION -Implement build and packaging of the package and place the output $OutDirectory/$ModuleName -#> -function DoBuild -{ - Write-Verbose -Verbose -Message "Starting DoBuild with configuration: $BuildConfiguration, framework: $BuildFramework" - - # Module build out path - $BuildOutPath = "${OutDirectory}/${ModuleName}" - Write-Verbose -Verbose -Message "Module output file path: '$BuildOutPath'" - - # Module build source path - $BuildSrcPath = "bin/${BuildConfiguration}/${BuildFramework}/publish" - Write-Verbose -Verbose -Message "Module build source path: '$BuildSrcPath'" - - # Copy psd1 file - Write-Verbose -Verbose "Copy-Item ${SrcPath}/${ModuleName}.psd1 to ${OutDirectory}/${ModuleName}" - Copy-Item "${SrcPath}/${ModuleName}.psd1" "${OutDirectory}/${ModuleName}" - - # Copy format files here - Write-Verbose -Verbose "Copy-Item ${SrcPath}/${ModuleName}.format.ps1xml to ${OutDirectory}/${ModuleName}" - copy-item "${SrcPath}/${ModuleName}.format.ps1xml" "${OutDirectory}/${ModuleName}" - - # Copy help - Write-Verbose -Verbose -Message "Copying help files to '$BuildOutPath'" - copy-item -Recurse "${HelpPath}/${Culture}" "$BuildOutPath" - - if ( Test-Path "${SrcPath}/code" ) { - Write-Verbose -Verbose -Message "Building assembly and copying to '$BuildOutPath'" - # build code and place it in the staging location - Push-Location "${SrcPath}/code" - try { - # Build source - Write-Verbose -Verbose -Message "Building with configuration: $BuildConfiguration, framework: $BuildFramework" - Write-Verbose -Verbose -Message "Building location: PSScriptRoot: $PSScriptRoot, PWD: $pwd" - dotnet publish --configuration $BuildConfiguration --framework $BuildFramework --output $BuildSrcPath - - # Debug: Check - - # Place build results - if (! (Test-Path -Path "$BuildSrcPath/${ModuleName}.dll")) - { - throw "Expected binary was not created: $BuildSrcPath/${ModuleName}.dll" - } - - Write-Verbose -Verbose -Message "Copying $BuildSrcPath/${ModuleName}.dll to $BuildOutPath" - Copy-Item "$BuildSrcPath/${ModuleName}.dll" -Dest "$BuildOutPath" - - if (Test-Path -Path "$BuildSrcPath/${ModuleName}.pdb") - { - Write-Verbose -Verbose -Message "Copying $BuildSrcPath/${ModuleName}.pdb to $BuildOutPath" - Copy-Item -Path "$BuildSrcPath/${ModuleName}.pdb" -Dest "$BuildOutPath" - } - } - catch { - # Write-Error "dotnet build failed with error: $_" - Write-Verbose -Verbose -Message "dotnet build failed with error: $_" - } - finally { - Pop-Location - } - } - else { - Write-Verbose -Verbose -Message "No code to build in '${SrcPath}/code'" - } - - ## Add build and packaging here - Write-Verbose -Verbose -Message "Ending DoBuild" -} diff --git a/ExtensionModules/CredManStore/pspackageproject.json b/ExtensionModules/CredManStore/pspackageproject.json deleted file mode 100644 index 2f6779b..0000000 --- a/ExtensionModules/CredManStore/pspackageproject.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ModuleName": "Microsoft.PowerShell.CredManStore", - "Culture": "en-US", - "BuildOutputPath": "out", - "SignedOutputPath": "signed", - "HelpPath": "help", - "TestPath": "test", - "SourcePath": "src" -} diff --git a/SecretManagement.build.ps1 b/SecretManagement.build.ps1 index 4a5363a..49854a1 100644 --- a/SecretManagement.build.ps1 +++ b/SecretManagement.build.ps1 @@ -7,7 +7,7 @@ param( $ProjectName = "SecretManagement" $FullModuleName = 'Microsoft.PowerShell.SecretManagement' $CSharpSource = Join-Path $PSScriptRoot src/code -$CSharpPublish = Join-Path $PSScriptRoot artifacts/publish +$CSharpPublish = Join-Path $PSScriptRoot artifacts/publish/$FullModuleName/$Configuration $ModuleOut = Join-Path $PSScriptRoot module $PackageOut = Join-Path $PSScriptRoot out $HelpSource = Join-Path $PSScriptRoot help @@ -60,7 +60,8 @@ task BuildDocs { task BuildModule { New-Item -ItemType Directory -Force $ModuleOut | Out-Null - Invoke-BuildExec { dotnet publish $CSharpSource --configuration $Configuration --output $CSharpPublish } + Invoke-BuildExec { dotnet publish $CSharpSource --configuration $Configuration } + Invoke-BuildExec { dotnet publish $PSScriptRoot/ExtensionModules/CredManStore/src/code --configuration $Configuration } $CSharpArtifacts | ForEach-Object { $item = Join-Path $CSharpPublish $_ From 7da84e1752a3cc80768fe84c9763efff01c79216 Mon Sep 17 00:00:00 2001 From: Patrick Meinecke Date: Tue, 9 Jul 2024 17:16:05 -0400 Subject: [PATCH 10/10] Hard code release config for the test extension --- SecretManagement.build.ps1 | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/SecretManagement.build.ps1 b/SecretManagement.build.ps1 index 49854a1..907cd06 100644 --- a/SecretManagement.build.ps1 +++ b/SecretManagement.build.ps1 @@ -61,7 +61,10 @@ task BuildModule { New-Item -ItemType Directory -Force $ModuleOut | Out-Null Invoke-BuildExec { dotnet publish $CSharpSource --configuration $Configuration } - Invoke-BuildExec { dotnet publish $PSScriptRoot/ExtensionModules/CredManStore/src/code --configuration $Configuration } + + # Hard code building this in release config since we aren't actually developing it, + # it's only for tests. The tests also hard code the path assuming release config. + Invoke-BuildExec { dotnet publish $PSScriptRoot/ExtensionModules/CredManStore/src/code --configuration Release } $CSharpArtifacts | ForEach-Object { $item = Join-Path $CSharpPublish $_