diff --git a/.ci/ci.yml b/.ci/ci.yml deleted file mode 100644 index 6180132..0000000 --- a/.ci/ci.yml +++ /dev/null @@ -1,141 +0,0 @@ -name: $(BuildDefinitionName)-$(date:yyMM).$(date:dd)$(rev:rrr) -trigger: - # Batch merge builds together while a merge build is running - batch: true - branches: - include: - - master -pr: - branches: - include: - - master - -resources: - repositories: - - repository: ComplianceRepo - type: github - endpoint: ComplianceGHRepo - name: PowerShell/compliance - -stages: -- stage: Build - displayName: Build SecretManagement Module Package - jobs: - - job: BuildPkg - displayName: Build Package - pool: - vmImage: windows-latest - - steps: - - - pwsh: | - Get-ChildItem -Path env: - displayName: Capture environment for build - condition: succeededOrFailed() - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - if (Test-Path -Path $modulePath) { - Write-Verbose -Verbose "Deleting existing temp module path: $modulePath" - Remove-Item -Path $modulePath -Recurse -Force -ErrorAction Ignore - } - if (! (Test-Path -Path $modulePath)) { - Write-Verbose -Verbose "Creating new temp module path: $modulePath" - $null = New-Item -Path $modulePath -ItemType Directory - } - displayName: Create temporary module path - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - Write-Verbose -Verbose "Install PowerShellGet V3 to temp module path" - Save-Module -Name PowerShellGet -Path $modulePath -MinimumVersion 3.0.18-beta18 -AllowPrerelease -Force - displayName: Install PowerShellGetV3 - - - pwsh: | - Get-ChildItem -Path $(Build.SourcesDirectory)/src/code -Recurse - displayName: Capture source code for build - condition: succeededOrFailed() - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release - displayName: Build module - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $(Build.SourcesDirectory)/build.ps1 -Publish - displayName: Publish module nuget package and upload package artifact - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - $config = Get-BuildConfiguration - # - $srcModulePath = Resolve-Path -Path "$($config.BuildOutputPath)/$($config.ModuleName)" - Get-ChildItem $srcModulePath - $artifactName = "$($config.ModuleName)" - Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$srcModulePath" - # # - # $refAssemblyNuGetPath = Resolve-Path -Path "$($config.BuildOutputPath)/Microsoft.PowerShell.SecretManagement.Library*.nupkg" - # Get-ChildItem $refAssemblyNuGetPath - # $artifactName = "RefAssemblyNuGet" - # Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$refAssemblyNuGetPath" - displayName: Upload module artifact - -- stage: Compliance - displayName: Compliance - dependsOn: Build - jobs: - - job: ComplianceJob - pool: - vmImage: windows-latest - steps: - - checkout: self - clean: true - - checkout: ComplianceRepo - clean: true - - download: current - artifact: 'Microsoft.PowerShell.SecretManagement' - - template: ci-compliance.yml@ComplianceRepo - parameters: - # credscan - suppressionsFile: '' - -- stage: Test - displayName: Test Package - dependsOn: Build - jobs: - - template: test.yml - parameters: - jobName: TestPkgWin - displayName: PowerShell Core on Windows - imageName: windows-latest - - - template: test.yml - parameters: - jobName: TestPkgWinPS - displayName: Windows PowerShell on Windows - imageName: windows-latest - powershellExecutable: powershell - - - template: test.yml - parameters: - jobName: TestPkgUbuntu16 - displayName: PowerShell Core on Ubuntu 16.04 - imageName: ubuntu-latest - - - template: test.yml - parameters: - jobName: TestPkgWinMacOS - displayName: PowerShell Core on macOS - imageName: macOS-latest diff --git a/.ci/ci_auto.yml b/.ci/ci_auto.yml deleted file mode 100644 index e48fa09..0000000 --- a/.ci/ci_auto.yml +++ /dev/null @@ -1,200 +0,0 @@ -name: $(BuildDefinitionName)-$(date:yyMM).$(date:dd)$(rev:rrr) -trigger: none -pr: none - -schedules: -# Use https://crontab.guru/#0_8_*_*_* to compute crontab expression -# Run signed build, with limited signing cert, every day at 9 am -- cron: 0 9 * * * - branches: - include: - - refs/heads/master - always: true - -variables: - - group: ESRP - # Prevents auto-injection of nuget-security-analysis (not needed for open source projects) - - name: skipNugetSecurityAnalysis - value: true - -resources: - repositories: - - repository: ComplianceRepo - type: github - endpoint: ComplianceGHRepo - name: PowerShell/compliance - -stages: -- stage: Build - displayName: Build SecretManagement Module Package - jobs: - - job: BuildPkg - displayName: Build Package - pool: - name: 1ES - demands: - - ImageOverride -equals PSMMS2019-Secure - - steps: - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - if (Test-Path -Path $modulePath) { - Write-Verbose -Verbose "Deleting existing temp module path: $modulePath" - Remove-Item -Path $modulePath -Recurse -Force -ErrorAction Ignore - } - if (! (Test-Path -Path $modulePath)) { - Write-Verbose -Verbose "Creating new temp module path: $modulePath" - $null = New-Item -Path $modulePath -ItemType Directory - } - displayName: Create temporary module path - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - Write-Verbose -Verbose "Install PowerShellGet V3 to temp module path" - Save-Module -Name PowerShellGet -Path $modulePath -MinimumVersion 3.0.18-beta18 -AllowPrerelease -Force - displayName: Install PowerShellGetV3 - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release - displayName: Build module - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $config = Get-BuildConfiguration - $signSrcPath = "$($config.BuildOutputPath)\$($config.ModuleName)" - $signOutPath = "$($config.SignedOutputPath)\$($config.ModuleName)" - if (! (Test-Path -Path $signOutPath)) { - $null = New-Item -Path $signOutPath -ItemType Directory - } - - # Set signing src path variable - $vstsCommandString = "vso[task.setvariable variable=signSrcPath]${signSrcPath}" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - - # Set signing out path variable - $vstsCommandString = "vso[task.setvariable variable=signOutPath]${signOutPath}" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - displayName: Set signing path variables for module code signing - - - pwsh: | - Get-ChildItem -Path env: - Get-ChildItem -Path . -Recurse -Directory - displayName: Capture environment for build - condition: succeededOrFailed() - - - template: EsrpSign.yml@ComplianceRepo - parameters: - buildOutputPath: $(signSrcPath) - signOutputPath: $(signOutPath) - certificateId: "CP-460906" - shouldSign: $(ShouldSign) - pattern: | - *.dll - *.psd1 - *.ps1xml - useMinimatch: true - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - if ($env:ShouldSign -ne 'True') - { - $(Build.SourcesDirectory)/build.ps1 -Publish - } - else - { - $(Build.SourcesDirectory)/build.ps1 -Publish -Signed - } - displayName: Publish module nuget package and upload package artifact - condition: succeeded() - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $config = Get-BuildConfiguration - $srcModulePath = Resolve-Path -Path "$($config.SignedOutputPath)/$($config.ModuleName)" - Get-ChildItem $srcModulePath - $artifactName = "$($config.ModuleName)" - Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$srcModulePath" - displayName: Upload the module artifact - condition: succeeded() - -- stage: Compliance - displayName: Compliance - dependsOn: Build - jobs: - - job: ComplianceJob - pool: - name: 1ES - demands: - - ImageOverride -equals PSMMS2019-Secure - steps: - - checkout: self - clean: true - - checkout: ComplianceRepo - clean: true - - download: current - artifact: 'Microsoft.PowerShell.SecretManagement' - - template: assembly-module-compliance.yml@ComplianceRepo - parameters: - # binskim - AnalyzeTarget: '$(Pipeline.Workspace)/Microsoft.PowerShell.SecretManagement/*.dll' - AnalyzeSymPath: 'SRV*' - # component-governance - sourceScanPath: '$(Build.SourcesDirectory)' - # credscan - suppressionsFile: '' - # TermCheck - optionsRulesDBPath: '' - optionsFTPath: '' - # tsa-upload - codeBaseName: 'PSSecretsManagement_202001' - # selections - APIScan: false # set to false when not using Windows APIs - -- stage: Test - displayName: Test Package - dependsOn: Build - jobs: - - template: test.yml - parameters: - jobName: TestPkgWin - displayName: PowerShell Core on Windows - imageName: windows-latest - - - template: test.yml - parameters: - jobName: TestPkgWinPS - displayName: Windows PowerShell on Windows - imageName: windows-latest - powershellExecutable: powershell - - - template: test.yml - parameters: - jobName: TestPkgUbuntu16 - displayName: PowerShell Core on Ubuntu - imageName: ubuntu-latest - - - template: test.yml - parameters: - jobName: TestPkgWinMacOS - displayName: PowerShell Core on macOS - imageName: macOS-latest diff --git a/.ci/ci_release.yml b/.ci/ci_release.yml deleted file mode 100644 index 234487e..0000000 --- a/.ci/ci_release.yml +++ /dev/null @@ -1,256 +0,0 @@ -name: $(BuildDefinitionName)-$(date:yyMM).$(date:dd)$(rev:rrr) -trigger: none -pr: none - -variables: - - group: ESRP - # Prevents auto-injection of nuget-security-analysis (not needed for open source projects) - - name: skipNugetSecurityAnalysis - value: true - -resources: - repositories: - - repository: ComplianceRepo - type: github - endpoint: ComplianceGHRepo - name: PowerShell/compliance - -stages: -- stage: Build - displayName: Build SecretManagement Module Package - jobs: - - job: BuildPkg - displayName: Build Package - pool: - name: 1ES - demands: - - ImageOverride -equals PSMMS2019-Secure - - steps: - - pwsh: | - Get-ChildItem -Path env: - Get-ChildItem -Path . -Recurse -Directory - displayName: Capture environment for build - condition: succeededOrFailed() - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - if (Test-Path -Path $modulePath) { - Write-Verbose -Verbose "Deleting existing temp module path: $modulePath" - Remove-Item -Path $modulePath -Recurse -Force -ErrorAction Ignore - } - if (! (Test-Path -Path $modulePath)) { - Write-Verbose -Verbose "Creating new temp module path: $modulePath" - $null = New-Item -Path $modulePath -ItemType Directory - } - displayName: Create temporary module path - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - Write-Verbose -Verbose "Install PowerShellGet V3 to temp module path" - Save-Module -Name PowerShellGet -Path $modulePath -MinimumVersion 3.0.18-beta18 -AllowPrerelease -Force - displayName: Install PowerShellGetV3 - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release - displayName: Build module - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $config = Get-BuildConfiguration - $signSrcPath = "$($config.BuildOutputPath)\$($config.ModuleName)" - $signOutPath = "$($config.SignedOutputPath)\$($config.ModuleName)" - if (! (Test-Path -Path $signOutPath)) { - $null = New-Item -Path $signOutPath -ItemType Directory - } - - # Set signing src path variable - $vstsCommandString = "vso[task.setvariable variable=signSrcPath]${signSrcPath}" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - - # Set signing out path variable - $vstsCommandString = "vso[task.setvariable variable=signOutPath]${signOutPath}" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - displayName: Set signing path variables for module code signing - - - pwsh: | - Get-ChildItem -Path env: - Get-ChildItem -Path . -Recurse -Directory - displayName: Capture environment for module code signing - condition: and(and(succeeded(), eq(variables['Build.Reason'], 'Manual')), ne(variables['SkipSigning'], 'True')) - - - template: EsrpSign.yml@ComplianceRepo - parameters: - buildOutputPath: $(signSrcPath) - signOutputPath: $(signOutPath) - certificateId: "CP-230012" - pattern: | - *.dll - *.psd1 - *.ps1xml - useMinimatch: true - - - ${{ if ne(variables.SkipSigning, 'True') }}: - - template: Sbom.yml@ComplianceRepo - parameters: - BuildDropPath: $(signOutPath) - Build_Repository_Uri: 'https://github.com/powershell/secretmanagement' - PackageName: 'Microsoft.PowerShell.SecretManagement' - PackageVersion: '1.1.2' - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - if ($env:SkipSigning -eq 'True') - { - $(Build.SourcesDirectory)/build.ps1 -Publish - } - else - { - $(Build.SourcesDirectory)/build.ps1 -Publish -Signed - } - displayName: Publish module nuget package and upload package artifact - condition: succeeded() - - - pwsh: | -# $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' -# $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath -# Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" -# Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force -# # -# $config = Get-BuildConfiguration -# $signSrcPath = Resolve-Path -Path "$($config.BuildOutputPath)" -# $signOutPath = "$($config.SignedOutputPath)\RefAssemblyNuGet" -# if (! (Test-Path -Path $signOutPath)) { -# $null = New-Item -Path $signOutPath -ItemType Directory -# } -# # Set signing src path variable -# $vstsCommandString = "vso[task.setvariable variable=signSrcPath]${signSrcPath}" -# Write-Host "sending " + $vstsCommandString -# Write-Host "##$vstsCommandString" -# # Set signing out path variable -# $vstsCommandString = "vso[task.setvariable variable=signOutPath]${signOutPath}" -# Write-Host "sending " + $vstsCommandString -# Write-Host "##$vstsCommandString" -# displayName: Set signing variables for possible ref assembly nuget package signing - -# - pwsh: | -# Get-ChildItem -Path env: -# displayName: Capture environment for ref assembly nuget file signing -# condition: and(and(succeeded(), eq(variables['Build.Reason'], 'Manual')), ne(variables['SkipSigning'], 'True')) - -# - template: EsrpSign.yml@ComplianceRepo -# parameters: -# buildOutputPath: $(signSrcPath) -# signOutputPath: $(signOutPath) -# certificateId: "CP-401405" -# pattern: | -# *.nupkg -# useMinimatch: true - - - pwsh: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force - # - $config = Get-BuildConfiguration - if ($env:SkipSigning -eq 'True') - { - $srcModulePath = Resolve-Path -Path "$($config.BuildOutputPath)/$($config.ModuleName)" - # $refAssemblyNuGetPath = Resolve-Path -Path "$($config.BuildOutputPath)/Microsoft.PowerShell.SecretManagement.Library*.nupkg" - } - else - { - $srcModulePath = Resolve-Path -Path "$($config.SignedOutputPath)/$($config.ModuleName)" - # $refAssemblyNuGetPath = Resolve-Path -Path "$($config.SignedOutputPath)/RefAssemblyNuGet/Microsoft.PowerShell.SecretManagement.Library*.nupkg" - } - Get-ChildItem $srcModulePath - # Get-ChildItem $refAssemblyNuGetPath - $artifactName = "$($config.ModuleName)" - Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$srcModulePath" - # $artifactName = "RefAssemblyNuGet" - # Write-Host "##vso[artifact.upload containerfolder=$artifactName;artifactname=$artifactName;]$refAssemblyNuGetPath" - displayName: Create and upload the module and ref assembly NuGet package artifacts - -- stage: Compliance - displayName: Compliance - dependsOn: Build - jobs: - - job: ComplianceJob - pool: - name: 1ES - demands: - - ImageOverride -equals PSMMS2019-Secure - steps: - - checkout: self - clean: true - - checkout: ComplianceRepo - clean: true - - download: current - artifact: 'Microsoft.PowerShell.SecretManagement' - - template: assembly-module-compliance.yml@ComplianceRepo - parameters: - # binskim - AnalyzeTarget: '$(Pipeline.Workspace)/Microsoft.PowerShell.SecretManagement/*.dll' - AnalyzeSymPath: 'SRV*' - # component-governance - sourceScanPath: '$(Build.SourcesDirectory)' - # credscan - suppressionsFile: '' - # TermCheck - optionsRulesDBPath: '' - optionsFTPath: '' - # tsa-upload - codeBaseName: 'PSSecretsManagement_202001' - # selections - APIScan: false # set to false when not using Windows APIs - -- stage: Test - displayName: Test Package - dependsOn: Build - jobs: - - template: test.yml - parameters: - jobName: TestPkgWin - displayName: PowerShell Core on Windows - imageName: windows-latest - - - template: test.yml - parameters: - jobName: TestPkgWinPS - displayName: Windows PowerShell on Windows - imageName: windows-latest - powershellExecutable: powershell - - - template: test.yml - parameters: - jobName: TestPkgUbuntu16 - displayName: PowerShell Core on Ubuntu - imageName: ubuntu-latest - - - template: test.yml - parameters: - jobName: TestPkgWinMacOS - displayName: PowerShell Core on macOS - imageName: macOS-latest - -- stage: Release - displayName: Release Package to PSGallery - condition: and(and(succeeded(), eq(variables['Build.Reason'], 'Manual')), eq(variables['Publish'], 'True')) - jobs: - - template: release.yml diff --git a/.ci/release.yml b/.ci/release.yml deleted file mode 100644 index 9511219..0000000 --- a/.ci/release.yml +++ /dev/null @@ -1,44 +0,0 @@ -parameters: - jobName: release - displayName: 'Release Microsoft.PowerShell.SecretManagement to PSGallery' - -jobs: -- job: ${{ parameters.jobName }} - pool: - name: 1ES - demands: - - ImageOverride -equals PSMMS2019-Secure - displayName: ${{ parameters.displayName }} - - steps: - - - task: DownloadPipelineArtifact@2 - displayName: 'Download SecretManagement module artifacts' - inputs: - artifact: nupkg - patterns: '**/*.nupkg' - downloadPath: '$(Pipeline.Workspace)/nuget' - - - powershell: | - $package = (Get-ChildItem '$(Pipeline.Workspace)/nuget/Microsoft.PowerShell.SecretManagement.*.nupkg').FullName - $package - $vstsCommandString = "vso[task.setvariable variable=NugetPkgPath]${package}" - Write-Host "sending " + $vstsCommandString - Write-Host "##$vstsCommandString" - displayName: 'Capture SecretManagement NuGet package path and set environment variable' - - - task: NuGetCommand@2 - displayName: 'Push Microsoft.PowerShell.SecretManagement module artifacts to PSGallery feed' - inputs: - command: push - packagesToPush: '$(NugetPkgPath)' - nuGetFeedType: external - publishFeedCredentials: PSGalleryPush - - #- task: NuGetCommand@2 - # displayName: 'Push Microsoft.PowerShell.SecretManagement.Library reference assembly nuget package to NuGet' - # inputs: - # command: push - # packagesToPush: '$(System.ArtifactsDirectory)/RefAssemblyNuGet/Microsoft.PowerShell.SecretManagement.Library*.nupkg' - # nuGetFeedType: external - # publishFeedCredentials: PowerShellNuGetOrgPush diff --git a/.ci/test.yml b/.ci/test.yml deleted file mode 100644 index 1f91ea6..0000000 --- a/.ci/test.yml +++ /dev/null @@ -1,67 +0,0 @@ -parameters: - jobName: TestPkgWin - imageName: windows-latest - displayName: PowerShell Core on Windows - powershellExecutable: pwsh - buildDirectory: '.' - -jobs: -- job: ${{ parameters.jobName }} - pool: - vmImage: ${{ parameters.imageName }} - displayName: ${{ parameters.displayName }} - steps: - - task: DownloadBuildArtifacts@0 - displayName: 'Download artifacts' - inputs: - buildType: current - downloadType: specific - itemPattern: '**/*.nupkg' - downloadPath: '$(System.ArtifactsDirectory)' - - - ${{ parameters.powershellExecutable }}: | - Get-ChildItem -Path "$(System.ArtifactsDirectory)" -Recurse - displayName: Capture artifacts directory - - - ${{ parameters.powershellExecutable }}: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - if (Test-Path -Path $modulePath) { - Write-Verbose -Verbose "Deleting existing temp module path: $modulePath" - Remove-Item -Path $modulePath -Recurse -Force -ErrorAction Ignore - } - if (! (Test-Path -Path $modulePath)) { - Write-Verbose -Verbose "Creating new temp module path: $modulePath" - $null = New-Item -Path $modulePath -ItemType Directory - } - displayName: Create temporary module path - - - ${{ parameters.powershellExecutable }}: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - Write-Verbose -Verbose "Install PowerShellGet V3 to temp module path" - Save-Module -Name PowerShellGet -Path $modulePath -MinimumVersion 3.0.18-beta18 -AllowPrerelease -Force - Write-Verbose -Verbose "Install Pester 4.X to temp module path" - Save-Module -Name "Pester" -MaximumVersion 4.99 -Path $modulePath -Force - displayName: Install PowerShellGetV3 and Pester - - - ${{ parameters.powershellExecutable }}: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name (Join-Path -Path '${{ parameters.buildDirectory }}' -ChildPath 'buildtools.psd1') -Force - # - Install-ModulePackageForTest -PackagePath "$(System.ArtifactsDirectory)" - displayName: Install module for test from downloaded artifact - workingDirectory: ${{ parameters.buildDirectory }} - - - ${{ parameters.powershellExecutable }}: | - $modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules' - $env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath - $modPath = Join-Path -Path $modulePath -ChildPath PSPackageProject - Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" - Import-Module -Name (Join-Path -Path '${{ parameters.buildDirectory }}' -ChildPath 'buildtools.psd1') -Force - # - Invoke-ModuleTests -Type Functional - displayName: Execute functional tests - workingDirectory: ${{ parameters.buildDirectory }} - errorActionPreference: continue - condition: succeededOrFailed() diff --git a/.github/workflows/ci-test.yml b/.github/workflows/ci-test.yml index e011fb7..ccfc216 100644 --- a/.github/workflows/ci-test.yml +++ b/.github/workflows/ci-test.yml @@ -4,7 +4,6 @@ on: push: branches: [ main ] pull_request: - # The branches below must be a subset of the branches above branches: [ main ] merge_group: types: [ checks_requested ] @@ -18,24 +17,43 @@ jobs: runs-on: ${{ matrix.os }} env: DOTNET_NOLOGO: true - DOTNET_CLI_TELEMETRY_OPTOUT: true DOTNET_GENERATE_ASPNET_CERTIFICATE: false steps: - - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v4 + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Install dotnet + uses: actions/setup-dotnet@v4 with: + cache: true + cache-dependency-path: '**/*.csproj' dotnet-version: 8.x - - run: ./tools/installPSResources.ps1 + + - name: Install PSResources + run: ./tools/installPSResources.ps1 shell: pwsh - - run: ./build.ps1 -Build && Invoke-ModuleTests -Type Functional + + - name: Build and test + run: Invoke-Build -Configuration Release -Task Build, Package, Test shell: pwsh - - uses: actions/upload-artifact@v4 + + - name: Test Windows PowerShell + run: | + Install-Module Pester -Scope CurrentUser -Force -SkipPublisherCheck + Invoke-Pester Test + if: matrix.os == 'windows-latest' + shell: powershell + + - name: Upload build artifacts + uses: actions/upload-artifact@v4 if: always() with: name: SecretManagement-package-${{ matrix.os }} path: out/**/*.nupkg - - uses: actions/upload-artifact@v4 + + - name: Upload test results + uses: actions/upload-artifact@v4 if: always() with: name: SecretManagement-tests-${{ matrix.os }} - path: test/result.pester.xml + path: testResults.xml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index 0f09187..0000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: CodeQL - -on: - push: - branches: [ main ] - pull_request: - branches: [ main ] - schedule: - - cron: '32 15 * * 6' - -jobs: - analyze: - name: Analyze (${{ matrix.language }}) - runs-on: ubuntu-latest - permissions: - security-events: write - packages: read - actions: read - contents: read - strategy: - fail-fast: false - matrix: - include: - - language: csharp - build-mode: autobuild - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - build-mode: ${{ matrix.build-mode }} - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 - with: - category: '/language:${{matrix.language}}' diff --git a/.gitignore b/.gitignore index cce595a..2889050 100644 --- a/.gitignore +++ b/.gitignore @@ -1,23 +1,6 @@ -_site/ -_themes/ -.DS_Store -.openpublishing.build.mdproj -.openpublishing.buildcore.ps1 -.optemp/ -*.orig -**/.ignore/** -dependentPackages/ -log/ -maml/ -**/obj/** -packages.config -packages/ -SecretManagement.sln -Tools/NuGet/ -test/result.pester.xml -updatablehelp/ -xhtml/ -**/settings.json -**/.vscode/** -**/out/** -**/bin/** +artifacts/ +module/ +bin/ +obj/ +out/ +testResults.xml diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 1fa0f37..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "cSpell.ignoreWords": [ - "cmdlet", - "pscustomobject" - ], - "powershell.codeFormatting.addWhitespaceAroundPipe": true -} \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..d8a8aa8 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,7 @@ + + + + true + 1.1.2 + + 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/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 b/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 index 90c4b7a..0a271ff 100644 --- a/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 +++ b/ExtensionModules/CredManStore/Tests/Microsoft.PowerShell.CredManStore.Tests.ps1 @@ -1,42 +1,25 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { - +Describe "Test Microsoft.PowerShell.CredManStore module" -Skip:(-Not $IsWindows) { BeforeAll { - - if (! $IsWindows) - { - $defaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:Skip"] = $true - } - else - { - if ((Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore) -eq $null) - { - Import-Module -Name Microsoft.PowerShell.SecretManagement - } - - if ((Get-Module -Name Microsoft.PowerShell.CredManStore -ErrorAction Ignore) -eq $null) - { - Import-Module -Name ..\Microsoft.PowerShell.CredManStore.psd1 - } - } + $ProjectRoot = Split-Path $PSScriptRoot | Split-Path | Split-Path + $ModuleRoot = Join-Path $ProjectRoot "artifacts/publish/Microsoft.PowerShell.CredManStore/release" + Import-Module -Force -Name $ProjectRoot/module/Microsoft.PowerShell.SecretManagement.psd1 + Import-Module -Force -Name $ModuleRoot/Microsoft.PowerShell.CredManStore.psd1 } AfterAll { - - if (! $IsWindows) - { - $global:PSDefaultParameterValues = $defaultParameterValues - } + Remove-Module -Name Microsoft.PowerShell.CredManStore -Force -ErrorAction Ignore + Remove-Module -Name Microsoft.PowerShell.SecretManagement -Force -ErrorAction Ignore } 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 +37,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 +49,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,17 +60,18 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } } 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 +89,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 +101,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,18 +112,19 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } } 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 +142,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 +154,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,17 +165,18 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } } 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 +195,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 +208,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,18 +219,19 @@ Describe "Test Microsoft.PowerShell.CredManStore module" -tags CI { $success = [Microsoft.PowerShell.CredManStore.LocalCredManStore]::DeleteObject( $secretName, [ref] $errorCode) - + $success | Should -BeTrue $errorCode | Should -Be 0 } } 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 +256,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 +272,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 +283,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/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/ExtensionModules/CredManStore/src/Microsoft.PowerShell.CredManStore.psd1 b/ExtensionModules/CredManStore/src/Microsoft.PowerShell.CredManStore.psd1 index 87d596e..ab38679 100644 --- a/ExtensionModules/CredManStore/src/Microsoft.PowerShell.CredManStore.psd1 +++ b/ExtensionModules/CredManStore/src/Microsoft.PowerShell.CredManStore.psd1 @@ -9,7 +9,7 @@ NestedModules = @('.\Microsoft.PowerShell.CredManStore.Extension') ModuleVersion = '1.0.0' # Supported PSEditions -CompatiblePSEditions = @('Core') +CompatiblePSEditions = @('Desktop', 'Core') # ID used to uniquely identify this module GUID = '4b4bc3ec-190a-493f-a869-5ebdb239895d' diff --git a/ExtensionModules/CredManStore/src/code/Microsoft.PowerShell.CredManStore.csproj b/ExtensionModules/CredManStore/src/code/Microsoft.PowerShell.CredManStore.csproj index f6e6ca3..7524982 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..8b4cf9f --- /dev/null +++ b/SecretManagement.build.ps1 @@ -0,0 +1,112 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +[CmdletBinding()] +param( + [ValidateSet("Debug", "Release")] + [string]$Configuration = "Debug" +) + +#Requires -Modules @{ ModuleName = "InvokeBuild"; ModuleVersion = "5.0.0" } + +$ProjectName = "SecretManagement" +$FullModuleName = "Microsoft.PowerShell.SecretManagement" +$CSharpSource = Join-Path $PSScriptRoot src/code +$CSharpPublish = Join-Path $PSScriptRoot artifacts/publish/$FullModuleName/$($Configuration.ToLower()) +$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", + "$FullModuleName.xml", + "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 ./artifacts, $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 { Test-Path -LiteralPath $HelpSource } { + New-ExternalHelp -Path $HelpSource -OutputPath $HelpOut + foreach ($aboutTopic in $HelpAboutTopics) { + New-ExternalHelp -Path "$HelpSource\$aboutTopic.md" -OutputPath $HelpOut + } +} + +task BuildModule { + New-Item -ItemType Directory -Force $ModuleOut | Out-Null + + Invoke-BuildExec { dotnet publish $CSharpSource --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 $_ + 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 +} + +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 -Verbose + } finally { + Unregister-PSResourceRepository -Name $ProjectName + } +} + +# AKA Microsoft.PowerShell.SecretManagement.Library +task PackageLibrary -If { $Configuration -eq "Release" } { + Invoke-BuildExec { dotnet pack $CSharpSource --no-build --configuration $Configuration --output $PackageOut } +} + +task Test { + Invoke-Pester -CI -Output Diagnostic +} + +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/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/global.json b/global.json new file mode 100644 index 0000000..ee4995e --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "8.0.300", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} 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 }} diff --git a/nuget.config b/nuget.config index 6548586..f003b0f 100644 --- a/nuget.config +++ b/nuget.config @@ -2,9 +2,6 @@ - + - - - 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" -} diff --git a/src/Microsoft.PowerShell.SecretManagement.psd1 b/src/Microsoft.PowerShell.SecretManagement.psd1 index 552e40f..c6c986f 100644 --- a/src/Microsoft.PowerShell.SecretManagement.psd1 +++ b/src/Microsoft.PowerShell.SecretManagement.psd1 @@ -4,13 +4,13 @@ @{ # Script module or binary module file associated with this manifest. -RootModule = '.\Microsoft.PowerShell.SecretManagement.dll' +RootModule = 'Microsoft.PowerShell.SecretManagement.dll' # Version number of this module. -ModuleVersion = '1.1.2' +ModuleVersion = '{{ModuleVersion}}' # Supported PSEditions -CompatiblePSEditions = @('Core') +CompatiblePSEditions = @('Desktop', 'Core') # ID used to uniquely identify this module GUID = 'a5c858f6-4a8e-41f1-b1ee-0ff8f6ad69d3' @@ -31,7 +31,7 @@ stored in registered extension vaults. An extension vault can store secrets loca SecretManagement coordinates access to the secrets through the registered vaults. Go to GitHub for more information about the module and to submit issues: -https://github.com/powershell/SecretManagement +https://github.com/PowerShell/SecretManagement " # Minimum version of the PowerShell engine required by this module @@ -65,10 +65,10 @@ PrivateData = @{ # Tags = @() # A URL to the license for this module. - LicenseUri = 'https://github.com/PowerShell/SecretManagement/blob/master/LICENSE' + LicenseUri = 'https://github.com/PowerShell/SecretManagement/blob/main/LICENSE' # A URL to the main website for this project. - ProjectUri = 'https://github.com/powershell/secretmanagement' + ProjectUri = 'https://github.com/PowerShell/SecretManagement' # A URL to an icon representing this module. # IconUri = '' diff --git a/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec b/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec index ec3176b..5c69723 100644 --- a/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec +++ b/src/code/Microsoft.PowerShell.SecretManagement.Library.nuspec @@ -2,11 +2,12 @@ Microsoft.PowerShell.SecretManagement.Library - 1.1.2 + $version$ Microsoft.PowerShell.SecretManagement.Library Microsoft Microsoft,PowerShell https://github.com/PowerShell/SecretManagement + README.md images\PowerShell_64.png MIT false @@ -15,9 +16,8 @@ PowerShell, SecretManagement, reference en-US - - - + + @@ -28,7 +28,9 @@ - - + + + + diff --git a/src/code/Microsoft.PowerShell.SecretManagement.csproj b/src/code/Microsoft.PowerShell.SecretManagement.csproj index b8c3943..a95be7b 100644 --- a/src/code/Microsoft.PowerShell.SecretManagement.csproj +++ b/src/code/Microsoft.PowerShell.SecretManagement.csproj @@ -5,18 +5,23 @@ 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 - net461 + $(ModuleVersion).0 + $(ModuleVersion) + $(ModuleVersion) + net462 + true - - + + + + + diff --git a/src/code/SecretManagement.cs b/src/code/SecretManagement.cs index 5c00cc1..2e9b6db 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] @@ -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(); @@ -266,7 +272,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 +393,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 +565,25 @@ 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)] + /// + /// Gets or sets the secret vault to unregister. + /// + [Parameter( + ParameterSetName = SecretVaultParameterSet, + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public SecretVaultInfo SecretVault { get; set; } @@ -591,7 +602,7 @@ protected override void ProcessRecord() case NameParameterSet: vaultNames = Name; break; - + case SecretVaultParameterSet: vaultNames = new string[] { SecretVault.Name }; break; @@ -657,7 +668,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 +695,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 +707,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; } @@ -713,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")) @@ -726,7 +742,7 @@ protected override void EndProcessing() case NameParameterSet: vaultName = Name; break; - + case SecretVaultParameterSet: vaultName = SecretVault.Name; break; @@ -763,6 +779,9 @@ protected override void EndProcessing() #region SecretCmdlet + /// + /// Base type for Secret cmdlets. + /// public abstract class SecretCmdlet : PSCmdlet { /// @@ -814,7 +833,7 @@ public IEnumerable CompleteArgument( args: new object[] {}, psToUse: ps, out ErrorRecord error); - + _secretNames = new List(); foreach (var secretInfo in results) { @@ -828,7 +847,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)) @@ -856,8 +875,8 @@ 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; } @@ -866,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[] { "*" }; @@ -928,8 +950,8 @@ 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,13 +959,16 @@ 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 #region Overrides + /// + /// Performs clean-up after the command execution. + /// protected override void EndProcessing() { var extensionModule = GetExtensionVault(Name); @@ -974,7 +999,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 +1007,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; } @@ -990,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)) @@ -1021,7 +1052,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 +1132,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,30 +1141,39 @@ 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)] + /// + /// Gets or sets the secret to set. + /// + [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = InfoParameterSet)] public SecretInformation InputObject { get; set; } #endregion #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")) @@ -1211,10 +1251,10 @@ 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 +1262,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; } @@ -1256,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) @@ -1300,7 +1346,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 +1373,7 @@ private InvokeResult TryInvokeAndWrite(ExtensionVaultModule extensionModule) name: Name, vaultName: extensionModule.VaultName, cmdlet: this); - + if (result != null) { WriteSecret(result); @@ -1413,11 +1459,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 +1483,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 +1497,47 @@ 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)] + /// + /// Gets or sets the secret to set. + /// + [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; } /// @@ -1489,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")) @@ -1521,7 +1588,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 +1598,7 @@ protected override void ProcessRecord() this)); return; } - + // Set secret to specified vault name. destExtensionModule.InvokeSetSecret( name: SecretInfo.Name, @@ -1592,7 +1659,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( @@ -1632,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 { @@ -1648,10 +1715,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,23 +1727,31 @@ 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)] + /// + /// Gets or sets the secret to be removed. + /// + [Parameter( + Position = 0, + Mandatory = true, + ValueFromPipeline = true, + ParameterSetName = InfoParameterSet)] public SecretInformation InputObject { get; set; } #endregion #region Overrides + /// + /// Performs execution of the command. + /// protected override void ProcessRecord() { if (!ShouldProcess(Vault, "Remove secret by name from vault")) @@ -1713,9 +1789,13 @@ public sealed class TestSecretVaultCommand : SecretCmdlet { #region Parameters - [Parameter(Position=0, - ValueFromPipeline=true, - ValueFromPipelineByPropertyName=true)] + /// + /// Gets or sets the secret name. + /// + [Parameter( + Position = 0, + ValueFromPipeline = true, + ValueFromPipelineByPropertyName = true)] [ArgumentCompleter(typeof(VaultNameCompleter))] [SupportsWildcards] public string[] Name { get; set; } @@ -1724,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 21f54b2..3fba6e7 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); } @@ -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,16 +231,19 @@ public PasswordRequiredException(string msg) #region SecretInformation class + /// + /// Represents a secret from a secret vault. + /// public sealed class SecretInformation { #region Properties - + /// /// Gets the name of the secret. /// public string Name { - get; + get; } /// @@ -351,7 +384,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 +414,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 +448,7 @@ internal class ExtensionVaultModule internal const string VaultParametersStr = "VaultParameters"; internal const string DescriptionStr = "Description"; internal const string SetSecretSupportsMetadataStr = "SetSecretSupportsMetadata"; - + #endregion #region Properties @@ -442,7 +475,7 @@ internal class ExtensionVaultModule /// /// Additional vault parameters. - /// + /// public IReadOnlyDictionary VaultParameters { get; } /// @@ -464,7 +497,7 @@ internal class ExtensionVaultModule #region Constructor - private ExtensionVaultModule() + private ExtensionVaultModule() { } @@ -483,7 +516,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 +590,7 @@ public void InvokeSetSecret( script: RunCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, SetSecretCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -574,7 +607,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 +622,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 +651,7 @@ public bool InvokeUnlockSecretVault( script: RunConditionalCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, UnlockVaultCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -647,7 +680,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 +689,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 +721,7 @@ public bool InvokeSetSecretMetadata( script: RunConditionalCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, SetSecretInfoCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -717,7 +750,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 +761,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 +793,7 @@ public object InvokeGetSecret( script: RunCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, GetSecretCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -824,7 +857,7 @@ public object InvokeGetSecret( case Hashtable hashTableValue: return hashTableValue; - + default: cmdlet.WriteError( new ErrorRecord( @@ -904,7 +937,7 @@ public SecretInformation[] InvokeGetSecretInfo( script: RunCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, GetSecretInfoCmd, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -979,7 +1012,7 @@ public void InvokeUnregisterVault( script: RunIfCommandScript, args: new object[] { ModuleName, ModulePath, ModuleExtensionName, UnregisterSecretVaultCommand, parameters }, out Exception terminatingError); - + if (terminatingError != null) { ThrowPasswordRequiredException(terminatingError); @@ -987,7 +1020,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 +1036,7 @@ public ExtensionVaultModule Clone() { return new ExtensionVaultModule(this); } - + #endregion #region Private methods @@ -1027,17 +1060,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 +1133,7 @@ internal static class RegisteredVaultCache /// public static SortedDictionary VaultExtensions { - get + get { lock (_syncObject) { @@ -1170,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. @@ -1187,7 +1248,7 @@ public static bool Add( { return false; } - + vaultItems.Remove(keyName); } @@ -1195,7 +1256,7 @@ public static bool Add( WriteSecretVaultRegistry( vaultInfo: vaultItems, defaultVaultName: defaultVault ? keyName : _defaultVaultName); - + return true; } @@ -1283,7 +1344,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 +1371,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], @@ -1396,13 +1457,12 @@ private static void DeleteSecretVaultRegistryFile() /// /// Hashtable containing registered vault information. /// The default vault name. - /// private static void WriteSecretVaultRegistry( Hashtable vaultInfo, 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 +1517,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 +1596,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 +1607,7 @@ public static Collection InvokeScriptWithHost( { ps.Commands.AddArgument(arg); } - + try { // Invoke the script. @@ -1579,7 +1639,7 @@ public static Collection InvokeScriptWithHost( case InformationRecord info: cmdlet.WriteInformation(info); break; - + case T result: returnCollection.Add(result); break; diff --git a/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 b/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 index 5c69693..43d35f3 100644 --- a/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 +++ b/test/Microsoft.PowerShell.SecretManagement.Tests.ps1 @@ -1,52 +1,37 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { +Describe "Test Microsoft.PowerShell.SecretManagement module" { + BeforeDiscovery { + $TestCases = 'ByteArray', 'String', 'SecureString', 'PSCredential', 'Hashtable' + } BeforeAll { + $ProjectRoot = Split-Path $PSScriptRoot + $ModulePath = Join-Path $ProjectRoot "module" + $ManifestPath = Join-Path $ModulePath "Microsoft.PowerShell.SecretManagement.psd1" - if ((Get-Module -Name Microsoft.PowerShell.SecretManagement -ErrorAction Ignore) -eq $null) - { - Import-Module -Name ..\..\Microsoft.PowerShell.SecretManagement - } + $BasePath = Join-Path $TestDrive "SecretManagementStorePath" + New-Item -ItemType Directory -Path $BasePath -Force - 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 + $scriptModulePath = Join-Path $TestDrive $scriptModuleName New-Item -ItemType Directory $scriptModulePath -Force - $script:scriptModuleFilePath = Join-Path $scriptModulePath "${scriptModuleName}.psd1" + + $scriptModuleFilePath = Join-Path $scriptModulePath "${scriptModuleName}.psd1" "@{{ ModuleVersion = '1.0' NestedModules = @('.\{0}') - FunctionsToExport = @() - }}" -f $implementingModuleName | Out-File -FilePath $script: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 + FunctionsToExport = @() + }}" -f $implementingModuleName | Out-File -FilePath $scriptModuleFilePath - $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 +167,7 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { [hashtable] $AdditionalParameters ) - + RemoveStore $Name RemoveMetaStore $Name }} @@ -284,7 +269,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 +285,191 @@ 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)) - { - 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 -Force -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]::ZeroFreeBSTR($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 + Remove-Module -Name Microsoft.PowerShell.SecretManagement -Force -ErrorAction Ignore } - 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 + AfterAll { + Get-SecretVault ScriptTestVault | Unregister-SecretVault } - 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 + It "Verifies writing <_> type to script vault" { + Set-Secret -Name $SecretTestInfo['Name'] -Secret $SecretTestInfo['Value'] -Vault $SecretTestInfo['Vault'] -ErrorAction Stop } - It "Verifies removing PSCredential type from $Title vault" { - Remove-Secret -Name BinVaultCred -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultCred -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' + It "Verifies reading <_> type from script vault" { + $result = Get-Secret -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorAction Stop + $secretString = & $SecretTestInfo['Stringifier'] $SecretTestInfo['Value'] + $resultString = & $SecretTestInfo['Stringifier'] $result + $resultString | Should -BeExactly $secretString } - } - 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 - $err.Count | Should -Be 0 + It "Verifies enumerating <_> type from script vault" { + $blobInfo = Get-SecretInfo -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorAction Stop + $blobInfo.Name | Should -BeExactly $SecretTestInfo['Name'] + $blobInfo.Type | Should -BeExactly $SecretTestInfo['Kind'] + $blobInfo.VaultName | Should -BeExactly $SecretTestInfo['Vault'] } - 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 - } - - It "Verifies enumerating Hashtable type from $Title vault" { - $htInfo = Get-SecretInfo -Name BinVaultHT -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - $htInfo.Name | Should -BeExactly "BinVaultHT" - $htInfo.Type | Should -BeExactly "Hashtable" - $htInfo.VaultName | Should -BeExactly $VaultName - } - - It "Verifies removing Hashtable type from $Title vault" { - Remove-Secret -Name BinVaultHT -Vault $VaultName -ErrorVariable err - $err.Count | Should -Be 0 - { Get-Secret -Name BinVaultHT -Vault $VaultName -ErrorAction Stop } | Should -Throw ` - -ErrorId 'GetSecretNotFound,Microsoft.PowerShell.SecretManagement.GetSecretCommand' + It "Verifies removing <_> type from script vault" { + Remove-Secret -Name $SecretTestInfo['Name'] -Vault $SecretTestInfo['Vault'] -ErrorAction Stop + { 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,20 +488,23 @@ 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 } -ErrorAction Stop } | + 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 - $err.Count | Should -Be 0 + Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath -VaultParameters $additionalParameters -ErrorAction Stop } It "Verifies Test-SecretVault fails with errors" { - Test-SecretVault -Name ScriptTestVault 2>$null | Should -BeFalse + { Test-SecretVault -Name ScriptTestVault -ErrorAction Stop } | + Should -Throw -ErrorId 'Microsoft.PowerShell.Commands.WriteErrorException,Microsoft.PowerShell.SecretManagement.TestSecretVaultCommand' } It "Verifies the only script vault extension is designated as the default vault" { @@ -566,19 +513,17 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { } It "Verifies that a secret item added with default vault designated results in no error" { - { Set-Secret -Name TestDefaultItem -Secret $randomSecretD } | Should -Not -Throw + Set-Secret -Name TestDefaultItem -Secret $randomSecretD -ErrorAction Stop } It "Should successfully unregister script vault extension" { - { Unregister-SecretVault -Name ScriptTestVault -ErrorVariable err } | Should -Not -Throw - $err.Count | Should -Be 0 + Unregister-SecretVault -Name ScriptTestVault -ErrorAction Stop } It "Should register the script vault extension successfully" { $additionalParameters = @{ AccessId = "AccessAT"; SubscriptionId = "1234567890" } - { Register-SecretVault -Name ScriptTestVault -ModuleName $script:scriptModuleFilePath -VaultParameters $additionalParameters ` - -Description 'ScriptTestVaultDescription' -ErrorVariable err } | Should -Not -Throw - $err.Count | Should -Be 0 + Register-SecretVault -Name ScriptTestVault -ModuleName $scriptModuleFilePath -VaultParameters $additionalParameters ` + -Description 'ScriptTestVaultDescription' -ErrorAction Stop } It "Verifies description field for registered test vault" { @@ -587,7 +532,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" { @@ -604,45 +550,45 @@ Describe "Test Microsoft.PowerShell.SecretManagement module" -tags CI { # Metadata is set through extension vault 'Set-SecretInfo' command, and not via a Metadata # parameter on 'Set-Secret' command. It "Verifies Set-Secret with metadata succeeds" { - { Set-Secret -Name TestDefaultMeta -Secret $randomSecretD -Metadata @{ Fail = $false } -ErrorVariable err } | Should -Not -Throw - $err.Count | Should -Be 0 + Set-Secret -Name TestDefaultMeta -Secret $randomSecretD -Metadata @{ Fail = $false } -ErrorAction Stop $info = Get-SecretInfo -Name TestDefaultMeta $info.Metadata | Should -Not -BeNullOrEmpty $info.Metadata["Fail"] | Should -BeFalse } It "Verifes Set-SecretInfo function" { - { Set-SecretInfo -Name TestDefaultMeta -Metadata @{ Fail = $false; Data = "MyData" } -ErrorVariable err } | Should -Not -Throw - $err.Count | Should -Be 0 + Set-SecretInfo -Name TestDefaultMeta -Metadata @{ Fail = $false; Data = "MyData" } -ErrorAction Stop $info = Get-SecretInfo -Name TestDefaultMeta $info.Metadata | Should -Not -BeNullOrEmpty $info.Metadata["Data"] | Should -BeExactly "MyData" } It "Verifies unsupported Set-SecretInfo fails with error" { - Set-SecretInfo -Name TestDefaultMeta -Metadata @{ Fail = $true } -ErrorVariable err 2>$null - $err | Should -HaveCount 1 - $err[0].FullyQualifiedErrorId | Should -BeExactly 'SetSecretMetadataInvalidOperation,Microsoft.PowerShell.SecretManagement.SetSecretInfoCommand' + { Set-SecretInfo -Name TestDefaultMeta -Metadata @{ Fail = $true } -ErrorAction Stop } | + Should -Throw -ErrorId 'SetSecretMetadataInvalidOperation,Microsoft.PowerShell.SecretManagement.SetSecretInfoCommand' } 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 + Unlock-SecretVault -Name ScriptTestVault -Password (ConvertTo-SecureString -String $randomSecretD -AsPlainText -Force) -ErrorAction Stop # 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 +609,15 @@ 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 + Unregister-SecretVault -Name ScriptTestVault -ErrorAction Stop - $store = Import-Clixml -Path $storePath + $store = Import-Clixml -Path $StorePath $store['UnRegisterSecretVaultCalled'] | Should -BeTrue <# diff --git a/tools/installPSResources.ps1 b/tools/installPSResources.ps1 index 7a0d003..3872045 100644 --- a/tools/installPSResources.ps1 +++ b/tools/installPSResources.ps1 @@ -9,5 +9,7 @@ if ($PSVersionTable.PSVersion.Major -lt 6) { } # TODO: Switch to Install-PSResource when CI uses PowerShell 7.4 -Install-Module -Name PowerShellGet -AllowPrerelease -Scope CurrentUser -Force -Install-Module -Name Pester -RequiredVersion 4.10.1 -Scope CurrentUser -Force -SkipPublisherCheck +Install-Module -Name InvokeBuild -Scope CurrentUser +Install-Module -Name platyPS -Scope CurrentUser +Install-Module -Name Microsoft.PowerShell.PSResourceGet -Scope CurrentUser +Install-Module -Name Pester -Scope CurrentUser diff --git a/tools/updateVersion.ps1 b/tools/updateVersion.ps1 new file mode 100644 index 0000000..be75435 --- /dev/null +++ b/tools/updateVersion.ps1 @@ -0,0 +1,24 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory)] + [semver]$Version, + + [Parameter(Mandatory)] + [string]$Changes +) + +git diff --staged --quiet --exit-code +if ($LASTEXITCODE -ne 0) { + throw "There are staged changes in the repository. Please commit or reset them before running this script." +} + +$Path = "Directory.Build.props" +$f = Get-Content -Path $Path +$f = $f -replace '^(?\s+)(.+)(?)$', "`${prefix}${Version}`${suffix}" +$f | Set-Content -Path $Path +git add $Path + +git commit --edit --message v${Version}: $Changes" +"