From 619623dad3f913b539c992b3950877b6e315a61d Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:57:46 -0800 Subject: [PATCH 1/2] fix(release): bring the build scripts in line with the 2.0 standards Publish-Module.ps1 required PowerShell 7.4, which left support on 10 November 2026, and refused a package whose tags passed 4,000 characters. The PowerShell Gallery has no such limit on the list it shows, which carries two tags for every exported command, so the check could only refuse a release the Gallery would accept. The script now requires 7.6, counts a line break in ReleaseNotes and Description as two characters, and compares the staged module's exports with FunctionsToExport by name. It reads the API key from one vault, the default one or the one -VaultName names, as a SecureString that is converted to text only for the publish call. Build-Help.ps1 and Build-RuleReference.ps1 set strict mode, document every parameter and pass literal paths. The two PlatyPS commands that fail when strict mode is on in the calling scope run in a child scope with it off. The manifest drops its empty CompanyName; the packed metadata is the same without it. Closes #61 --- Build/Build-Help.ps1 | 165 ++++++++------ Build/Build-RuleReference.ps1 | 235 ++++++++++++++++--- Build/Publish-Module.ps1 | 260 ++++++++++++++-------- CHANGELOG.md | 17 ++ CLAUDE.md | 3 +- IntuneScriptLab.psd1 | 1 - Tests/Unit/Build/Publish-Module.Tests.ps1 | 228 +++++++++++++++++++ Tests/Unit/Module.Contract.Tests.ps1 | 27 +-- 8 files changed, 723 insertions(+), 213 deletions(-) create mode 100644 Tests/Unit/Build/Publish-Module.Tests.ps1 diff --git a/Build/Build-Help.ps1 b/Build/Build-Help.ps1 index 0dc18f0..5340fd8 100644 --- a/Build/Build-Help.ps1 +++ b/Build/Build-Help.ps1 @@ -18,7 +18,7 @@ A new public function has no Markdown yet: write its comment-based help first, run New-MarkdownCommandHelp for it into docs\, then replace the help block with .EXTERNALHELP - (see .github\instructions\platyps.instructions.md for why that order matters). + (see .github\instructions\powershell-platyps.instructions.md for why that order matters). Update-MarkdownCommandHelp adds an INPUTS heading for every pipeline parameter type it finds, with a placeholder body if the Markdown lacks it; the build stops on placeholders, @@ -28,11 +28,25 @@ Compile the Markdown as it is without folding in signature changes first. Useful when the Markdown was edited by hand and the module has not changed. + .PARAMETER ValidateOnly + Run the checks on the committed Markdown without folding signatures in and without + compiling: the pull request gate. Nothing is written. + + .PARAMETER ModuleRoot + The repository root, which is the module root. Defaults to the parent of the folder that + holds this script. + .EXAMPLE .\Build\Build-Help.ps1 Refreshes docs\ from the loaded module and rebuilds en-US\IntuneScriptLab-Help.xml. + .EXAMPLE + .\Build\Build-Help.ps1 -ValidateOnly + + Checks the committed Markdown for structure, placeholders and relative links, and writes + nothing. + .EXAMPLE .\Build\Build-Help.ps1 -SkipUpdate -Verbose @@ -59,122 +73,137 @@ #> [CmdletBinding()] param( + [Parameter()] [switch]$SkipUpdate, - # Run the checks on the committed Markdown without folding signatures in or compiling: the - # pull request gate + [Parameter()] [switch]$ValidateOnly, - # Repository root, the module root; the parent of the folder holding this script + [Parameter()] [ValidateNotNullOrEmpty()] - [string]$ModuleRoot = (Split-Path -Parent $PSScriptRoot) + [string]$ModuleRoot = (Split-Path -Path $PSScriptRoot -Parent) ) +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' -$moduleRoot = $ModuleRoot -if ($ValidateOnly) { $SkipUpdate = $true } -$docs = Join-Path $moduleRoot 'docs\IntuneScriptLab' -$culture = Join-Path $moduleRoot 'en-US' -$maml = Join-Path ([IO.Path]::GetTempPath()) "IntuneScriptLab-maml-$([guid]::NewGuid())" - -Import-Module (Join-Path $moduleRoot 'IntuneScriptLab.psd1') -Force -$module = Get-Module IntuneScriptLab - -function Export-IslMaml { - # Compiles docs\IntuneScriptLab\*.md into en-US\IntuneScriptLab-Help.xml - $null = Measure-PlatyPSMarkdown -Path "$docs\*.md" | - Where-Object Filetype -match 'CommandHelp' | - Import-MarkdownCommandHelp -Path { $_.FilePath } | - Export-MamlCommandHelp -OutputFolder $maml -Force - $built = Get-ChildItem $maml -Recurse -Filter 'IntuneScriptLab-Help.xml' | Select-Object -First 1 - if (-not $built) { - throw "Export-MamlCommandHelp produced no IntuneScriptLab-Help.xml under $maml" - } - $null = New-Item -ItemType Directory -Path $culture -Force - Copy-Item $built.FullName (Join-Path $culture 'IntuneScriptLab-Help.xml') -Force - Remove-Item $maml -Recurse -Force -} -if (-not $SkipUpdate) { +# -ValidateOnly reads the committed Markdown as it is, so it implies -SkipUpdate +$skipSignatureUpdate = $SkipUpdate -or $ValidateOnly +$docsRoot = Join-Path -Path $ModuleRoot -ChildPath 'docs' +$docs = Join-Path -Path $docsRoot -ChildPath 'IntuneScriptLab' +$markdownPattern = Join-Path -Path $docs -ChildPath '*.md' +$culture = Join-Path -Path $ModuleRoot -ChildPath 'en-US' +$shipped = Join-Path -Path $culture -ChildPath 'IntuneScriptLab-Help.xml' +$maml = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "IntuneScriptLab-maml-$([guid]::NewGuid())" +$manifestPath = Join-Path -Path $ModuleRoot -ChildPath 'IntuneScriptLab.psd1' + +Import-Module -Name $manifestPath -Force +$module = Get-Module -Name IntuneScriptLab + +if (-not $skipSignatureUpdate) { # A build that stopped on a validation error leaves the update's backups behind, and the next # update refuses to overwrite them - Get-ChildItem $docs -Filter '*.bak' -ErrorAction SilentlyContinue | Remove-Item -Force + Get-ChildItem -LiteralPath $docs -Filter '*.bak' -ErrorAction SilentlyContinue | Remove-Item -Force # Update-MarkdownCommandHelp merges every parameter description Get-Help returns, and Get-Help # renders the shipped MAML one sentence per line, so the text never equals the Markdown and # comes back appended under it on every run. Park the MAML during the update: with no help # to merge, the update touches only the syntax and metadata, which is all it is here for. - $shipped = Join-Path $culture 'IntuneScriptLab-Help.xml' $parked = "$shipped.updating" - if (Test-Path $shipped) { Move-Item $shipped $parked -Force } + if (Test-Path -LiteralPath $shipped) { + Move-Item -LiteralPath $shipped -Destination $parked -Force + } try { - Import-Module (Join-Path $moduleRoot 'IntuneScriptLab.psd1') -Force + Import-Module -Name $manifestPath -Force + # Update-MarkdownCommandHelp and New-MarkdownCommandHelp of Microsoft.PowerShell.PlatyPS + # 1.0.3 end with "The property 'defaultValue' cannot be found on this object" for a + # command that has parameters when strict mode is on in the scope that calls them. Each + # therefore runs in a child scope with strict mode off; the rest of the script keeps it. Write-Verbose 'Folding signature changes into docs\IntuneScriptLab\*.md' - $null = Measure-PlatyPSMarkdown -Path "$docs\*.md" | - Where-Object Filetype -match 'CommandHelp' | - Update-MarkdownCommandHelp -Path { $_.FilePath } + & { + Set-StrictMode -Off + $null = Measure-PlatyPSMarkdown -Path $markdownPattern | + Where-Object -Property Filetype -Match -Value 'CommandHelp' | + Update-MarkdownCommandHelp -Path { $_.FilePath } + } # Public functions added since the last run have no Markdown yet. Their comment-based # help is the seed, so they are generated with the MAML still parked - $documented = (Get-ChildItem $docs -Filter *.md).BaseName - $missing = $module.ExportedFunctions.Keys | Where-Object { $_ -notin $documented } - if ($missing) { + $documented = @(Get-ChildItem -LiteralPath $docs -Filter '*.md' | ForEach-Object { $_.BaseName }) + $missing = @($module.ExportedFunctions.Keys | Where-Object { $_ -notin $documented }) + if ($missing.Count -gt 0) { Write-Verbose "Generating first-time Markdown for: $($missing -join ', ')" - $markdownHelpSplat = @{ - CommandInfo = Get-Command $missing - OutputFolder = Split-Path $docs - Locale = 'en-US' + $markdownHelpParameters = @{ + CommandInfo = Get-Command -Name $missing + OutputFolder = $docsRoot + Locale = 'en-US' + } + & { + Set-StrictMode -Off + $null = New-MarkdownCommandHelp @markdownHelpParameters } - $null = New-MarkdownCommandHelp @markdownHelpSplat } Write-Verbose 'Refreshing the module page' - $null = Measure-PlatyPSMarkdown -Path "$docs\*.md" | - Where-Object Filetype -match 'CommandHelp' | + $null = Measure-PlatyPSMarkdown -Path $markdownPattern | + Where-Object -Property Filetype -Match -Value 'CommandHelp' | Import-MarkdownCommandHelp -Path { $_.FilePath } | - Update-MarkdownModuleFile -Path (Join-Path $docs 'IntuneScriptLab.md') - } - finally { - if (Test-Path $parked) { Move-Item $parked $shipped -Force } + Update-MarkdownModuleFile -Path (Join-Path -Path $docs -ChildPath 'IntuneScriptLab.md') + } finally { + if (Test-Path -LiteralPath $parked) { + Move-Item -LiteralPath $parked -Destination $shipped -Force + } } } Write-Verbose 'Validating the Markdown structure' -$invalid = Measure-PlatyPSMarkdown -Path "$docs\*.md" | - Where-Object Filetype -match 'CommandHelp' | - Test-MarkdownCommandHelp -Path { $_.FilePath } -DetailView | - Where-Object { -not $_.IsValid } -if ($invalid) { +$invalid = @(Measure-PlatyPSMarkdown -Path $markdownPattern | + Where-Object -Property Filetype -Match -Value 'CommandHelp' | + Test-MarkdownCommandHelp -Path { $_.FilePath } -DetailView | + Where-Object { -not $_.IsValid }) +if ($invalid.Count -gt 0) { throw "Markdown help failed validation: $(($invalid | ForEach-Object { $_.Path }) -join ', ')" } # A relative link passes Test-MarkdownCommandHelp and then breaks Get-Help at read time; only a # bare topic ([Name]()) or an absolute URL is allowed -$relative = Select-String -Path "$docs\*.md" -Pattern '^\s*-?\s*\[.+\]\((?!https?://|\))' -if ($relative) { - $where = ($relative | ForEach-Object { "$($_.Filename):$($_.LineNumber)" }) -join ', ' - throw "Relative link in help Markdown: $where" +$relative = @(Select-String -Path $markdownPattern -Pattern '^\s*-?\s*\[.+\]\((?!https?://|\))') +if ($relative.Count -gt 0) { + $places = ($relative | ForEach-Object { "$($_.Filename):$($_.LineNumber)" }) -join ', ' + throw "Relative link in help Markdown: $places" } -# "{{ Fill in the Description }}" for a new command, "{{ Fill Description }}" for a new parameter -$unfilled = Select-String -Path "$docs\*.md" -Pattern '\{\{\s*Fill' -List -if ($unfilled) { - throw "Help templates still contain placeholders: $(($unfilled.Path | Split-Path -Leaf) -join ', ')" +# Any placeholder in double braces: "{{ Fill in the Description }}" for a new command, +# "{{ Fill Description }}" for a new parameter +$unfilled = @(Select-String -Path $markdownPattern -Pattern '\{\{[^}]*\}\}' -List) +if ($unfilled.Count -gt 0) { + $names = ($unfilled | ForEach-Object { Split-Path -Path $_.Path -Leaf }) -join ', ' + throw "Help templates still contain placeholders: $names" } +$markdownCount = @(Get-ChildItem -LiteralPath $docs -Filter '*.md').Count if ($ValidateOnly) { - $count = (Get-ChildItem $docs -Filter *.md).Count Write-Information -InformationAction Continue -MessageData ( - "Help Markdown valid: $count files, no placeholders, no relative links") + "Help Markdown valid: $markdownCount files, no placeholders, no relative links") return } Write-Verbose 'Compiling MAML' -Export-IslMaml +$null = Measure-PlatyPSMarkdown -Path $markdownPattern | + Where-Object -Property Filetype -Match -Value 'CommandHelp' | + Import-MarkdownCommandHelp -Path { $_.FilePath } | + Export-MamlCommandHelp -OutputFolder $maml -Force +$built = Get-ChildItem -LiteralPath $maml -Recurse -Filter 'IntuneScriptLab-Help.xml' | Select-Object -First 1 +if ($null -eq $built) { + throw "Export-MamlCommandHelp produced no IntuneScriptLab-Help.xml under $maml" +} +$null = New-Item -ItemType Directory -Path $culture -Force +Copy-Item -LiteralPath $built.FullName -Destination $shipped -Force +Remove-Item -LiteralPath $maml -Recurse -Force # Backups from Update-MarkdownCommandHelp; git holds the previous version -Get-ChildItem $docs -Filter '*.bak' -ErrorAction SilentlyContinue | Remove-Item -Force +Get-ChildItem -LiteralPath $docs -Filter '*.bak' -ErrorAction SilentlyContinue | Remove-Item -Force Write-Information -InformationAction Continue -MessageData ( - "Help built: $((Get-ChildItem $docs -Filter *.md).Count) Markdown files, en-US\IntuneScriptLab-Help.xml") + "Help built: $markdownCount Markdown files, en-US\IntuneScriptLab-Help.xml") diff --git a/Build/Build-RuleReference.ps1 b/Build/Build-RuleReference.ps1 index 1e37503..4f98045 100644 --- a/Build/Build-RuleReference.ps1 +++ b/Build/Build-RuleReference.ps1 @@ -20,6 +20,10 @@ .PARAMETER PassThru Return the Markdown as a string instead of writing docs\Rules.md. + .PARAMETER ModuleRoot + The repository root, which is the module root. Defaults to the parent of the folder that + holds this script. + .EXAMPLE .\Build\Build-RuleReference.ps1 @@ -46,23 +50,65 @@ as its source text, so nothing is silently dropped. #> [CmdletBinding()] +[OutputType([string])] param( + [Parameter()] [switch]$PassThru, - # Repository root, the module root; the parent of the folder holding this script + [Parameter()] [ValidateNotNullOrEmpty()] - [string]$ModuleRoot = (Split-Path -Parent $PSScriptRoot) + [string]$ModuleRoot = (Split-Path -Path $PSScriptRoot -Parent) ) +Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' -$moduleRoot = $ModuleRoot -$rulesFolder = Join-Path -Path $moduleRoot -ChildPath 'Private\Rules' -$outputPath = Join-Path -Path $moduleRoot -ChildPath 'docs\Rules.md' -# A string expression folded to text: constants, expandable strings, "+" concatenations, -# parentheses and variables assigned earlier in the same file +$privateFolder = Join-Path -Path $ModuleRoot -ChildPath 'Private' +$rulesFolder = Join-Path -Path $privateFolder -ChildPath 'Rules' +$docsFolder = Join-Path -Path $ModuleRoot -ChildPath 'docs' +$outputPath = Join-Path -Path $docsFolder -ChildPath 'Rules.md' + + function Resolve-Text { - param($Ast, [object[]]$Assignments) + <# + .SYNOPSIS + Folds a string expression of a rule file to the text it produces. + + .DESCRIPTION + Resolves string constants, expandable strings, "+" concatenations, parentheses, and variables + assigned earlier in the same file. A value that is only known when the rule runs becomes a + placeholder, and an expression of any other kind is returned as its source text, so nothing + is dropped. A literal $ is marked with the character U+0001 so that ConvertTo-Placeholder + leaves it alone. + + .PARAMETER Ast + The expression to resolve. + + .PARAMETER Assignments + Every assignment to a variable in the rule file, in which the value of a variable is looked + up. + + .EXAMPLE + Resolve-Text -Ast $pair.Item2 -Assignments $assignments + + Resolves the value of one key of a finding hashtable. + + .INPUTS + None. + + .OUTPUTS + System.String. The resolved text. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter()] + [System.Management.Automation.Language.Ast]$Ast, + + [Parameter()] + [object[]]$Assignments + ) + if ($null -eq $Ast) { return '' } switch ($Ast.GetType().Name) { # A literal $ (single-quoted, or escaped in a double-quoted string) is text, not a value: @@ -74,15 +120,18 @@ function Resolve-Text { $index = $text.LastIndexOf($nested.Extent.Text) if ($index -ge 0) { $text = $text.Substring(0, $index) + '' + - $text.Substring($index + $nested.Extent.Text.Length) + $text.Substring($index + $nested.Extent.Text.Length) } } return $text.Replace('$', [string][char]1) } 'ParenExpressionAst' { - $inner = $Ast.Pipeline.PipelineElements[0] - if ($inner.PSObject.Properties['Expression']) { - return Resolve-Text -Ast $inner.Expression -Assignments $Assignments + # An assignment in parentheses has no pipeline elements to read + if ($Ast.Pipeline.PSObject.Properties['PipelineElements']) { + $inner = $Ast.Pipeline.PipelineElements[0] + if ($inner.PSObject.Properties['Expression']) { + return Resolve-Text -Ast $inner.Expression -Assignments $Assignments + } } return $Ast.Extent.Text } @@ -117,8 +166,7 @@ function Resolve-Text { if ($right -is [System.Management.Automation.Language.IfStatementAst]) { $bodies = @($right.Clauses | ForEach-Object { $_.Item2 }) if ($right.ElseClause) { $bodies += $right.ElseClause } - } - elseif ($right -is [System.Management.Automation.Language.SwitchStatementAst]) { + } elseif ($right -is [System.Management.Automation.Language.SwitchStatementAst]) { $bodies = @($right.Clauses | ForEach-Object { $_.Item2 }) if ($right.Default) { $bodies += $right.Default } $joiner = ' / ' @@ -132,9 +180,43 @@ function Resolve-Text { } } -# A statement block that yields one string expression, resolved; anything else, its constants + function Resolve-Body { - param($Body, [object[]]$Assignments) + <# + .SYNOPSIS + Resolves the text that one branch of an if or switch statement yields. + + .DESCRIPTION + A statement block that holds one string expression is resolved with Resolve-Text. For any + other block, the string constants in it are joined with spaces. + + .PARAMETER Body + The statement block of the branch. + + .PARAMETER Assignments + Every assignment to a variable in the rule file, passed on to Resolve-Text. + + .EXAMPLE + Resolve-Body -Body $ifStatement.ElseClause -Assignments $assignments + + Resolves the text of an else branch. + + .INPUTS + None. + + .OUTPUTS + System.String. The resolved text. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [System.Management.Automation.Language.StatementBlockAst]$Body, + + [Parameter()] + [object[]]$Assignments + ) + $statements = @($Body.Statements) if ($statements.Count -eq 1 -and $statements[0].PSObject.Properties['PipelineElements']) { $first = $statements[0].PipelineElements[0] @@ -148,29 +230,124 @@ function Resolve-Body { $constants -join ' ' } -# Run-time text in a message becomes a placeholder + function ConvertTo-Placeholder { - param([string]$Text) - $text = [regex]::Replace($Text, '\$\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\)', '') - $text = [regex]::Replace($text, '\$\{[^}]+\}', '') - $text = [regex]::Replace($text, '\$[A-Za-z_][\w:]*', '') - $text = $text.Replace([string][char]1, '$') - ($text -replace '\s+', ' ').Trim() + <# + .SYNOPSIS + Replaces the run-time values in a resolved message with the placeholder . + + .DESCRIPTION + A subexpression, a variable in braces, and a plain variable each become . The + character U+0001, which Resolve-Text writes for a literal $, becomes $ again, and runs of + white space become one space. + + .PARAMETER Text + The text that Resolve-Text returned. + + .EXAMPLE + ConvertTo-Placeholder -Text 'Found $($items.Count) items in $path' + + Returns 'Found items in '. + + .INPUTS + None. + + .OUTPUTS + System.String. The text with placeholders. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter()] + [string]$Text + ) + + $resolved = [regex]::Replace($Text, '\$\((?:[^()]|\((?:[^()]|\([^()]*\))*\))*\)', '') + $resolved = [regex]::Replace($resolved, '\$\{[^}]+\}', '') + $resolved = [regex]::Replace($resolved, '\$[A-Za-z_][\w:]*', '') + $resolved = $resolved.Replace([string][char]1, '$') + ($resolved -replace '\s+', ' ').Trim() } + function ConvertTo-Cell { - param([string]$Text) + <# + .SYNOPSIS + Converts a resolved message to the text of one Markdown table cell. + + .DESCRIPTION + Replaces run-time values with placeholders, as ConvertTo-Placeholder does, and escapes each + vertical bar so that it does not end the cell. + + .PARAMETER Text + The text that Resolve-Text returned. + + .EXAMPLE + ConvertTo-Cell -Text 'exit 0 | exit 1' + + Returns 'exit 0 \| exit 1'. + + .INPUTS + None. + + .OUTPUTS + System.String. The cell text. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter()] + [string]$Text + ) + (ConvertTo-Placeholder -Text $Text) -replace '\|', '\|' } + function Get-HelpText { - param([string]$Source, [string]$Keyword) + <# + .SYNOPSIS + Gets the text of one keyword from the comment-based help in a rule file. + + .DESCRIPTION + Reads the lines under the keyword up to the next keyword or the end of the help block, and + joins them into one line. The file is read as text and is not loaded, so the rule does not + run. + + .PARAMETER Source + The whole text of the rule file. + + .PARAMETER Keyword + The help keyword without its dot, such as SYNOPSIS or DESCRIPTION. + + .EXAMPLE + Get-HelpText -Source $source -Keyword 'SYNOPSIS' + + Returns the synopsis of the rule as one line, or an empty string when there is none. + + .INPUTS + None. + + .OUTPUTS + System.String. The help text on one line. + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory)] + [string]$Source, + + [Parameter(Mandatory)] + [string]$Keyword + ) + $match = [regex]::Match($Source, "(?s)\.$Keyword\s*\r?\n(.*?)(?=\r?\n\s*\.[A-Z]+|\r?\n\s*#>)") if (-not $match.Success) { return '' } - $lines = $match.Groups[1].Value -split "\r?\n" | ForEach-Object { $_.Trim() } - (($lines -join ' ') -replace '\s+', ' ').Trim() + $helpLines = $match.Groups[1].Value -split '\r?\n' | ForEach-Object { $_.Trim() } + (($helpLines -join ' ') -replace '\s+', ' ').Trim() } + $lines = [System.Collections.Generic.List[string]]::new() $lines.Add('# IntuneScriptLab rules, from the evidence') $lines.Add('') @@ -182,7 +359,7 @@ $lines.Add('experiment names in Validation\Experiments.psd1 and the rows of Vali $lines.Add('') $idPattern = '\b(?:REM|PS|W32|FLT|ESP|ASSIGN|PROBE)-[A-Z0-9]+(?:-[A-Z0-9]+)*\b' -foreach ($file in (Get-ChildItem -Path $rulesFolder -Filter 'Find-Isl*.ps1' | Sort-Object Name)) { +foreach ($file in (Get-ChildItem -LiteralPath $rulesFolder -Filter 'Find-Isl*.ps1' | Sort-Object -Property Name)) { $source = [System.IO.File]::ReadAllText($file.FullName) $tokens = $null $errors = $null @@ -236,6 +413,6 @@ foreach ($file in (Get-ChildItem -Path $rulesFolder -Filter 'Find-Isl*.ps1' | So $markdown = ($lines -join "`n") + "`n" if ($PassThru) { return $markdown } -$null = New-Item -ItemType Directory -Path (Split-Path -Path $outputPath -Parent) -Force +$null = New-Item -ItemType Directory -Path $docsFolder -Force [System.IO.File]::WriteAllText($outputPath, $markdown, [System.Text.UTF8Encoding]::new($false)) Write-Information -InformationAction Continue -MessageData "Rule reference written: $outputPath" diff --git a/Build/Publish-Module.ps1 b/Build/Publish-Module.ps1 index d018f2a..d40b2b8 100644 --- a/Build/Publish-Module.ps1 +++ b/Build/Publish-Module.ps1 @@ -1,4 +1,4 @@ -#Requires -Version 7.4 +#Requires -Version 7.6 #Requires -Modules @{ ModuleName = 'Microsoft.PowerShell.PSResourceGet'; ModuleVersion = '1.0.0' } <# @@ -10,7 +10,7 @@ Publish-PSResource packages the whole directory that contains the manifest. This repository IS the module root, so publishing from here directly would ship the entire working tree - the tests, the validation kit with its tenant-derived findings, the docs - source, Build, .github, the mirrored standards, and every object under .git. + source, Build, .github, the installed standards, and every object under .git. That matters more than package size. A Gallery version can never be deleted, only unlisted, and the .nupkg stays downloadable at its direct URL after unlisting. Anything @@ -40,6 +40,10 @@ Set-Secret -Name PSGallery-ApiKey -Secret '' +.PARAMETER VaultName + The SecretManagement vault that holds the secret. Left out, the default vault is read, + the one Get-SecretVault reports as IsDefault. No other vault is searched. + .PARAMETER Repository Target repository name. Defaults to PSGallery. @@ -78,6 +82,12 @@ OUTPUT: A .nupkg in the local repository folder USE CASE: Inspecting the real package contents without consuming a Gallery version +.INPUTS + None. + +.OUTPUTS + None. Progress is written to the information stream, and a failure is a terminating error. + .NOTES Author: Jeffrey Stuhr Blog: https://www.techbyjeff.net @@ -92,6 +102,10 @@ param( [ValidateNotNullOrEmpty()] [string]$SecretName = 'PSGallery-ApiKey', + [Parameter()] + [ValidateNotNullOrEmpty()] + [string]$VaultName, + [Parameter()] [ValidateNotNullOrEmpty()] [string]$Repository = 'PSGallery', @@ -108,8 +122,82 @@ param( [switch]$SkipHelpBuild ) -$ErrorActionPreference = 'Stop' Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + + +function Get-VaultApiKey { + <# + .SYNOPSIS + Gets the Gallery API key from a SecretManagement vault as a SecureString. + + .DESCRIPTION + Reads one secret from one named vault. When no vault is named, the default vault is read + and no other. The secret is returned as a SecureString and is never converted to text + here. A secret that is missing, a vault that cannot be read, and a missing default vault + each write a warning and return nothing, so that the caller can report every way a key + can be supplied. + + .PARAMETER SecretName + Name of the secret that holds the API key. + + .PARAMETER VaultName + Name of the vault to read. Left out, the vault that Get-SecretVault reports as the + default is read. + + .EXAMPLE + $key = Get-VaultApiKey -SecretName 'PSGallery-ApiKey' + + Reads the key from the default vault. $key is $null when the vault has no such secret. + + .INPUTS + None. + + .OUTPUTS + System.Security.SecureString. The API key, or nothing when it could not be read. + #> + [CmdletBinding()] + [OutputType([securestring])] + param( + [Parameter(Mandatory)] + [string]$SecretName, + + [Parameter()] + [string]$VaultName + ) + + $vault = $VaultName + if (-not $vault) { + $defaultVaults = @(Get-SecretVault | Where-Object -Property IsDefault -EQ -Value $true) + if ($defaultVaults.Count -eq 0) { + Write-Warning 'No default secret vault is registered. Name the vault with -VaultName.' + return + } + $vault = $defaultVaults[0].Name + } + + # try/catch, not -ErrorAction SilentlyContinue. A locked SecretStore throws from the vault + # extension and SilentlyContinue does not suppress it. + try { + $secret = Get-Secret -Name $SecretName -Vault $vault -ErrorAction Stop + } catch { + Write-Warning ("The secret '$SecretName' could not be read from the vault '$vault': " + + "$($_.Exception.Message) If the key is stored there, run Unlock-SecretStore and try again.") + return + } + + if ($secret -is [System.Management.Automation.PSCredential]) { + return $secret.Password + } + if ($secret -isnot [securestring]) { + Write-Warning ("The secret '$SecretName' in the vault '$vault' is not text. Store the key with " + + "Set-Secret -Name $SecretName -Secret ''.") + return + } + + $secret +} + $moduleName = 'IntuneScriptLab' @@ -141,66 +229,38 @@ if (-not $StagingPath) { # The key is never stored in this repository, and is kept off the command line where # possible: the environment variable first (what the release workflow sets), then the # SecretManagement vault, then the parameter as the override. -if (-not $WhatIfPreference -and -not $ApiKey) { - $vaultError = $null - +# +# A key that arrives as text, from the parameter or the environment variable, stays in +# $plainApiKey. A key from the vault stays a SecureString in $vaultApiKey until the publish +# call converts it for that one call. +$plainApiKey = $ApiKey +$vaultApiKey = $null +if (-not $WhatIfPreference -and -not $plainApiKey) { if ($env:PSGALLERY_API_KEY) { - $ApiKey = $env:PSGALLERY_API_KEY + $plainApiKey = $env:PSGALLERY_API_KEY Write-Information 'API key: $env:PSGALLERY_API_KEY.' -InformationAction Continue - } - elseif (Get-Module -ListAvailable Microsoft.PowerShell.SecretManagement) { - Import-Module Microsoft.PowerShell.SecretManagement - - # try/catch, not -ErrorAction SilentlyContinue. A locked SecretStore throws from - # the vault extension and SilentlyContinue does not suppress it. - try { - $stored = Get-Secret -Name $SecretName -AsPlainText -ErrorAction Stop - } - catch { - $vaultError = $_.Exception.Message - $stored = $null - } + } elseif (Get-Module -ListAvailable -Name Microsoft.PowerShell.SecretManagement) { + Import-Module -Name Microsoft.PowerShell.SecretManagement - if ($stored) { - $ApiKey = $stored + $vaultApiKey = Get-VaultApiKey -SecretName $SecretName -VaultName $VaultName + if ($null -ne $vaultApiKey) { Write-Information "API key: the '$SecretName' secret." -InformationAction Continue } } - if (-not $ApiKey) { - $lines = @( + if (-not $plainApiKey -and $null -eq $vaultApiKey) { + $keyHelp = @( 'No PowerShell Gallery API key found.' + 'Create a key at https://www.powershellgallery.com/account/apikeys, then supply it by any of:' + " Set-Secret -Name $SecretName -Secret '' (stored once, recommended)" + ' $env:PSGALLERY_API_KEY = '''' (this session only)' + " ./Build/Publish-Module.ps1 -ApiKey '' (one-off)" ) - if ($vaultError) { - $lines += "The secret vault could not be read: $vaultError" - $lines += 'If the key is already stored there, run Unlock-SecretStore and try again.' - $lines += '' - } - $lines += 'Create a key at https://www.powershellgallery.com/account/apikeys, then supply it by any of:' - $lines += " Set-Secret -Name $SecretName -Secret '' (stored once, recommended)" - $lines += ' $env:PSGALLERY_API_KEY = '''' (this session only)' - $lines += " ./Build/Publish-Module.ps1 -ApiKey '' (one-off)" - throw ($lines -join [Environment]::NewLine) + throw ($keyHelp -join [Environment]::NewLine) } } -# The tags the Gallery lists for a published module: the manifest's, then the ones the publish -# adds for the package kind, the editions and every exported function. -function Get-PublishedTag { - param([Parameter(Mandatory)]$Manifest) - $tags = [System.Collections.Generic.List[string]]::new() - foreach ($tag in @($Manifest.Tags)) { $tags.Add($tag) } - $tags.Add('PSModule') - foreach ($edition in @($Manifest.CompatiblePSEditions)) { $tags.Add("PSEdition_$edition") } - foreach ($name in @($Manifest.ExportedFunctions.Keys | Sort-Object)) { - $tags.Add("PSFunction_$name") - $tags.Add("PSCommand_$name") - } - if ($Manifest.ExportedFunctions.Count) { $tags.Add('PSIncludes_Function') } - $tags -} - # --- 1. Help gates ---------------------------------------------------------------- # Before staging, because a stale-MAML failure should stop the release rather than leave a # staged tree that nobody notices is wrong. @@ -214,8 +274,7 @@ if (-not $SkipHelpBuild) { $WhatIfPreference = $false try { & (Join-Path $PSScriptRoot 'Build-Help.ps1') -ModuleRoot $ModuleRoot -SkipUpdate | Out-Null - } - finally { + } finally { $WhatIfPreference = $priorWhatIf } Write-Information 'Help gates passed and MAML rebuilt.' -InformationAction Continue @@ -242,50 +301,45 @@ if (-not $manifest.Description) { if (-not $manifest.Tags) { throw 'The manifest needs Tags for the module to be discoverable.' } -# The Gallery refuses the upload with a 400 when the notes pass this length (v0.27.0, the first -# attempt: 11,319 characters, every version since 0.1.0). Keep the newest few in the manifest; -# CHANGELOG.md ships in the package and holds the rest. -$releaseNotesLimit = 10600 -$releaseNotesLength = "$($manifest.ReleaseNotes)".Length -if ($releaseNotesLength -gt $releaseNotesLimit) { - throw ("The manifest's ReleaseNotes is $releaseNotesLength characters; the Gallery accepts at most " + - "$releaseNotesLimit. Move the older versions out, CHANGELOG.md has them.") -} - -# NuGet's limit on a package description, which the Gallery applies. -$descriptionLimit = 4000 -$descriptionLength = "$($manifest.Description)".Length -if ($descriptionLength -gt $descriptionLimit) { - throw ("The manifest's Description is $descriptionLength characters; the Gallery accepts at most " + - "$descriptionLimit.") -} - -# The Gallery refuses a package whose tags pass 4,000 characters ("A nuget package's Tags property -# may not be more than 4000 characters long"), and the tags it measures are not the manifest's -# alone: the publish adds PSModule, one PSEdition_ tag per compatible edition, PSFunction_ and -# PSCommand_ for every exported function, and PSIncludes_Function. That is the list the Gallery -# shows for 0.27.0 (61 tags, 1,935 characters for 27 commands), so every new command costs about -# twice its name. Measured here the way the Gallery sees it. -$tagsLimit = 4000 -$publishedTags = Get-PublishedTag -Manifest $manifest -$tagsLength = ($publishedTags -join ' ').Length -if ($tagsLength -gt $tagsLimit) { - throw ("The package's tags come to $tagsLength characters once the publish adds its own for " + - "$($manifest.ExportedFunctions.Count) commands; the Gallery accepts at most $tagsLimit. Drop " + - 'manifest tags, or fewer commands.') +# The Gallery refuses the upload with a 400 when the release notes pass 10,600 characters +# (v0.27.0, the first attempt: 11,319 characters, every version since 0.1.0). Keep the newest +# few in the manifest; CHANGELOG.md ships in the package and holds the rest. The description +# carries NuGet's limit of 4,000, which the Gallery applies. +# +# A line break is counted as two characters, the larger of the two possible counts: the publish +# writes the release notes into the package with the line endings of the system that publishes, +# whatever the manifest has. +# +# The tags are not measured. The publish writes only the manifest's own tags and PSModule; the +# Gallery adds the PSEdition_, PSFunction_, PSCommand_ and PSIncludes_ tags it lists, and that +# list has no 4,000-character limit. +$measurements = @( + @{ Field = 'Description'; Text = $manifest.Description; Limit = 4000 } + @{ Field = 'ReleaseNotes'; Text = $manifest.ReleaseNotes; Limit = 10600 } +) +$measured = foreach ($measurement in $measurements) { + $length = ([string]$measurement.Text).Replace("`r`n", "`n").Replace("`n", "`r`n").Length + if ($length -gt $measurement.Limit) { + $problem = "The manifest's $($measurement.Field) is $length characters." + $advice = if ($measurement.Field -eq 'ReleaseNotes') { + ' Move the older versions out, CHANGELOG.md has them.' + } else { + '' + } + throw "$problem The PowerShell Gallery accepts at most $($measurement.Limit).$advice" + } + "$($measurement.Field) $length/$($measurement.Limit)" } -$metadataSummary = ("Gallery metadata: Description $descriptionLength/$descriptionLimit, Tags " + - "$tagsLength/$tagsLimit, ReleaseNotes $releaseNotesLength/$releaseNotesLimit characters.") -Write-Information $metadataSummary -InformationAction Continue +Write-Information "Gallery metadata: $($measured -join ', ') characters." -InformationAction Continue # --- 3. Already published? -------------------------------------------------------- # A version number is consumed forever on first publish. Learning that from a rejected # upload is worse than a check costing one request. if (-not $WhatIfPreference) { $findSplat = @{ - Name = $moduleName - Repository = $Repository - Version = "$version" + Name = $moduleName + Repository = $Repository + Version = "$version" ErrorAction = 'SilentlyContinue' } if (Find-PSResource @findSplat) { @@ -299,7 +353,7 @@ if (-not $WhatIfPreference) { # propagates $WhatIfPreference to each of them, so an unpinned -WhatIf run would copy # nothing and then fail on the empty folder. Staging is not the destructive step and always # runs for real; only the publish at the end is gated by ShouldProcess. -if (Test-Path $StagingPath) { +if (Test-Path -LiteralPath $StagingPath) { Remove-Item -LiteralPath $StagingPath -Recurse -Force -WhatIf:$false } $stageModule = Join-Path $StagingPath $moduleName @@ -339,14 +393,18 @@ $staged | # no description. The analysis is exercised too, on a detection script with the return-before- # exit mistake, because a module that imports can still be missing the rule that does the work. $stagedManifest = Join-Path $stageModule "$moduleName.psd1" -$expectedCount = @($manifest.ExportedFunctions.Keys).Count +# The exported names are compared with FunctionsToExport of the staged manifest, name by name: a +# count that matches can hide one command missing and another exported by mistake. $check = @" `$ErrorActionPreference = 'Stop' Import-Module '$stagedManifest' -Force -`$commands = @((Get-Module $moduleName).ExportedFunctions.Keys) | Sort-Object -if (`$commands.Count -ne $expectedCount) { - throw "Staged module exported `$(`$commands.Count) command(s); the manifest declares $expectedCount." +`$commands = @((Get-Module $moduleName).ExportedFunctions.Keys | Sort-Object) +`$declared = @((Import-PowerShellDataFile -LiteralPath '$stagedManifest').FunctionsToExport | Sort-Object) +`$difference = @(Compare-Object -ReferenceObject `$declared -DifferenceObject `$commands) +if (`$difference.Count -gt 0) { + `$names = (`$difference | ForEach-Object { "`$(`$_.InputObject) (`$(`$_.SideIndicator))" }) -join ', ' + throw "Staged module's exports differ from the manifest's FunctionsToExport: `$names" } `$sample = Join-Path ([System.IO.Path]::GetTempPath()) "isl-staged-`$([guid]::NewGuid().ToString('N'))" `$null = New-Item -ItemType Directory -Path (Join-Path `$sample 'Remediations\Widget') -Force @@ -386,7 +444,19 @@ if (-not $PSCmdlet.ShouldProcess("$moduleName $version -> $Repository", 'Publish return } -Publish-PSResource -Path $stageModule -Repository $Repository -ApiKey $ApiKey -SkipDependenciesCheck +$publishParameters = @{ + Path = $stageModule + Repository = $Repository + SkipDependenciesCheck = $true +} +if ($null -ne $vaultApiKey) { + # Publish-PSResource takes the key as text. The vault's SecureString is converted here, for + # this call only, and the text is kept in no variable. + $keyHolder = [System.Net.NetworkCredential]::new('', $vaultApiKey) + Publish-PSResource @publishParameters -ApiKey $keyHolder.Password +} else { + Publish-PSResource @publishParameters -ApiKey $plainApiKey +} Write-Information "Published $moduleName $version to $Repository." -InformationAction Continue $next = "Indexing takes a few minutes, then: Install-PSResource -Name $moduleName" diff --git a/CHANGELOG.md b/CHANGELOG.md index 4dfce8f..44907af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,23 @@ entries are carried over from the manifest's release notes. ARM64 stays a host survey until a Pro or Enterprise ARM64 device is available. The LAPS settings-catalog policy failed on every node with `0x86000011` on Home, as the CSP's edition list says. +- `Build/Publish-Module.ps1` requires PowerShell 7.6, since 7.4 left support on 10 November 2026. It + reads the Gallery API key from one vault, the default one or the one the new `-VaultName` + parameter names, where it searched every registered vault, and it keeps the key a `SecureString` + until the publish call. The staged module's exported commands are compared with the manifest's + `FunctionsToExport` by name, where only the counts were compared. +- The release script and the contract test count a line break in the manifest's `ReleaseNotes` and + `Description` as two characters, the larger of the two counts the Gallery could apply. +- `Build/Build-Help.ps1` and `Build/Build-RuleReference.ps1` run under strict mode, and the help + build refuses any placeholder in double braces, where it looked for `{{ Fill` only. +- The manifest no longer sets `CompanyName` to an empty string. The package's metadata is the same + without the key. + +### Removed + +- The 4,000-character limit on the package's tags, from the release script and the contract test. + The PowerShell Gallery has no such limit on the list it shows, which carries two tags for every + exported command, so the check could only ever refuse a release the Gallery would accept. ## [0.34.0] - 2026-10-15 diff --git a/CLAUDE.md b/CLAUDE.md index 468f3f3..4f050a0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -152,7 +152,8 @@ section must exist and must not be empty, or the job fails; a dry run checks it already exists for the tag is left as written. The API key is the `PSGALLERY_API_KEY` repository secret, passed as an environment variable. Locally the script resolves `-ApiKey`, then `$env:PSGALLERY_API_KEY`, then a SecretManagement -secret named `PSGallery-ApiKey`. +secret named `PSGallery-ApiKey` in the default vault, or in the vault `-VaultName` names. No other +vault is searched, and the secret stays a `SecureString` until the publish call. ## Checks diff --git a/IntuneScriptLab.psd1 b/IntuneScriptLab.psd1 index 3a92157..0b1fcbd 100644 --- a/IntuneScriptLab.psd1 +++ b/IntuneScriptLab.psd1 @@ -4,7 +4,6 @@ ModuleVersion = '0.34.0' GUID = '3f6b2c9e-7d41-4a8f-9c2b-5e0d8a1f4b76' Author = 'Jeffrey Stuhr' - CompanyName = '' Copyright = '(c) 2026 Jeffrey Stuhr. All rights reserved.' # Two lines, within the repository's 115-character limit; the README carries the long form Description = @' diff --git a/Tests/Unit/Build/Publish-Module.Tests.ps1 b/Tests/Unit/Build/Publish-Module.Tests.ps1 new file mode 100644 index 0000000..af4cc30 --- /dev/null +++ b/Tests/Unit/Build/Publish-Module.Tests.ps1 @@ -0,0 +1,228 @@ +#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '6.2.0' } + +<# + The release script's reading of the Gallery API key from a secret vault, tested without a vault. + Publish-Module.ps1 requires PowerShell 7.6 and stages a package when it runs, so its function is + lifted out through the AST into a file under TestDrive and dot-sourced from there. Get-Secret and + Get-SecretVault are stubbed, because Microsoft.PowerShell.SecretManagement is not installed on a + CI runner, and then mocked. +#> + +BeforeAll { + $repositoryRoot = Split-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -Parent + $buildFolder = Join-Path -Path $repositoryRoot -ChildPath 'Build' + $script:releaseScript = Join-Path -Path $buildFolder -ChildPath 'Publish-Module.ps1' + + $tokens = $null + $parseErrors = $null + $script:releaseAst = [System.Management.Automation.Language.Parser]::ParseFile( + $script:releaseScript, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors) { + throw "Publish-Module.ps1 does not parse: $($parseErrors[0].Message)" + } + $definition = $script:releaseAst.Find({ + param($node) + $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and + $node.Name -eq 'Get-VaultApiKey' + }, $false) + if ($null -eq $definition) { + throw 'Publish-Module.ps1 no longer defines Get-VaultApiKey.' + } + $lifted = Join-Path -Path $TestDrive -ChildPath 'Get-VaultApiKey.ps1' + [System.IO.File]::WriteAllText($lifted, $definition.Extent.Text) + + function Get-SecretVault { + <# + .SYNOPSIS + Stands in for Get-SecretVault of Microsoft.PowerShell.SecretManagement. + + .DESCRIPTION + Exists so that the command can be mocked where the module is not installed. It returns + nothing; each test supplies the vaults through a mock. + + .EXAMPLE + Mock -CommandName Get-SecretVault -MockWith { [PSCustomObject]@{ Name = 'Main'; IsDefault = $true } } + + Replaces the stand-in with one default vault. + + .INPUTS + None. + + .OUTPUTS + None. + #> + [CmdletBinding()] + param() + } + + function Get-Secret { + <# + .SYNOPSIS + Stands in for Get-Secret of Microsoft.PowerShell.SecretManagement. + + .DESCRIPTION + Exists so that the command can be mocked where the module is not installed, with the + parameters the release script passes. It returns nothing; each test supplies the secret + through a mock. + + .PARAMETER Name + Name of the secret. + + .PARAMETER Vault + Name of the vault. + + .PARAMETER AsPlainText + Asks for the secret as text. The release script must not pass it. + + .EXAMPLE + Mock -CommandName Get-Secret -MockWith { $script:storedSecret } + + Replaces the stand-in with one that returns a SecureString. + + .INPUTS + None. + + .OUTPUTS + None. + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute( + 'PSReviewUnusedParameter', '', Justification = 'A stand-in that is mocked; it has no body.')] + [CmdletBinding()] + param( + [Parameter()] + [string]$Name, + + [Parameter()] + [string]$Vault, + + [Parameter()] + [switch]$AsPlainText + ) + } + + . $lifted + + # NetworkCredential converts between text and a SecureString in both directions. PSScriptAnalyzer + # reports ConvertTo-SecureString -AsPlainText, and the text here is not a secret. + $script:storedText = 'value-from-the-vault' + $script:storedSecret = [System.Net.NetworkCredential]::new('', $script:storedText).SecurePassword +} + +Describe 'Get-VaultApiKey' -Tag 'Unit', 'Build' { + Context 'Parameter Validation' { + It 'Declares SecretName as a mandatory string and VaultName as an optional one' { + $command = Get-Command -Name Get-VaultApiKey + + $command | Should-HaveParameter -ParameterName 'SecretName' -Type ([string]) -Mandatory + $command | Should-HaveParameter -ParameterName 'VaultName' -Type ([string]) + $command.Parameters['VaultName'].Attributes.Where({ $_ -is [Parameter] }).Mandatory | + Should-BeFalse + } + } + + Context 'Core Functionality' { + BeforeEach { + Mock -CommandName Get-SecretVault -MockWith { + [PSCustomObject]@{ Name = 'Other'; IsDefault = $false } + [PSCustomObject]@{ Name = 'Main'; IsDefault = $true } + } + Mock -CommandName Get-Secret -MockWith { $script:storedSecret } + } + + It 'Reads the named vault, and no other, when a vault is named' { + $key = Get-VaultApiKey -SecretName 'Gallery' -VaultName 'Named' + + $key | Should-HaveType ([securestring]) + [System.Net.NetworkCredential]::new('', $key).Password | Should-Be $script:storedText + Should-Invoke -CommandName Get-Secret -Times 1 -Exactly -ParameterFilter { + $Name -eq 'Gallery' -and $Vault -eq 'Named' + } + Should-Invoke -CommandName Get-SecretVault -Times 0 -Exactly + } + + It 'Reads the default vault when no vault is named' { + $key = Get-VaultApiKey -SecretName 'Gallery' + + [System.Net.NetworkCredential]::new('', $key).Password | Should-Be $script:storedText + Should-Invoke -CommandName Get-Secret -Times 1 -Exactly -ParameterFilter { $Vault -eq 'Main' } + } + + It 'Does not ask the vault for plain text' { + $null = Get-VaultApiKey -SecretName 'Gallery' -VaultName 'Named' + + Should-Invoke -CommandName Get-Secret -Times 1 -Exactly -ParameterFilter { -not $AsPlainText } + } + + It 'Returns the password of a secret that is stored as a credential' { + Mock -CommandName Get-Secret -MockWith { + [System.Management.Automation.PSCredential]::new('gallery', $script:storedSecret) + } + + $key = Get-VaultApiKey -SecretName 'Gallery' -VaultName 'Named' + + $key | Should-HaveType ([securestring]) + [System.Net.NetworkCredential]::new('', $key).Password | Should-Be $script:storedText + } + } + + Context 'Error Handling' { + It 'Warns and returns nothing when no default vault is registered' { + Mock -CommandName Get-SecretVault -MockWith { [PSCustomObject]@{ Name = 'Other'; IsDefault = $false } } + Mock -CommandName Get-Secret -MockWith { $script:storedSecret } + + $quiet = @{ WarningVariable = 'warnings'; WarningAction = 'SilentlyContinue' } + $key = Get-VaultApiKey -SecretName 'Gallery' @quiet + + $key | Should-BeNull + $warnings | Should-BeCollection -Count 1 + "$($warnings[0])" | Should-BeLikeString '*No default secret vault*-VaultName*' + Should-Invoke -CommandName Get-Secret -Times 0 -Exactly + } + + It 'Warns with the vault and the reason, and returns nothing, when the vault cannot be read' { + Mock -CommandName Get-Secret -MockWith { throw 'A valid password is required to access the store.' } + + $quiet = @{ WarningVariable = 'warnings'; WarningAction = 'SilentlyContinue' } + $key = Get-VaultApiKey -SecretName 'Gallery' -VaultName 'Named' @quiet + + $key | Should-BeNull + $warnings | Should-BeCollection -Count 1 + "$($warnings[0])" | Should-BeLikeString "*'Gallery'*'Named'*A valid password is required*" + } + + It 'Warns and returns nothing when the secret is not text' { + Mock -CommandName Get-Secret -MockWith { @{ Key = 'value' } } + + $quiet = @{ WarningVariable = 'warnings'; WarningAction = 'SilentlyContinue' } + $key = Get-VaultApiKey -SecretName 'Gallery' -VaultName 'Named' @quiet + + $key | Should-BeNull + $warnings | Should-BeCollection -Count 1 + "$($warnings[0])" | Should-BeLikeString '*is not text*' + } + } +} + +Describe 'Publish-Module.ps1 secret handling' -Tag 'Unit', 'Build' { + BeforeAll { + $script:secretCalls = @($script:releaseAst.FindAll({ + param($node) + $node -is [System.Management.Automation.Language.CommandAst] -and + $node.GetCommandName() -eq 'Get-Secret' + }, $true)) + } + + It 'Names the vault on every Get-Secret call and never asks for plain text' { + $script:secretCalls | Should-BeCollection -Count 1 + $parameterNames = @($script:secretCalls[0].CommandElements | + Where-Object { $_ -is [System.Management.Automation.Language.CommandParameterAst] } | + ForEach-Object { $_.ParameterName }) + + $parameterNames | Should-ContainCollection @('Vault') + $parameterNames | Should-NotContainCollection @('AsPlainText') + } + + It 'Requires a PowerShell version that is still supported' { + $script:releaseAst.ScriptRequirements.RequiredPSVersion | Should-BeGreaterThanOrEqual ([version]'7.6') + } +} diff --git a/Tests/Unit/Module.Contract.Tests.ps1 b/Tests/Unit/Module.Contract.Tests.ps1 index a20d338..908ad25 100644 --- a/Tests/Unit/Module.Contract.Tests.ps1 +++ b/Tests/Unit/Module.Contract.Tests.ps1 @@ -29,28 +29,17 @@ Describe 'IntuneScriptLab module contract' -Tag 'Unit', 'Contract' { It 'keeps the Gallery metadata within the limits the Gallery enforces: ' -ForEach @( @{ Field = 'ReleaseNotes'; Limit = 10600 } @{ Field = 'Description'; Limit = 4000 } - @{ Field = 'Tags'; Limit = 4000 } ) { # The Gallery refused 0.27.0's first upload: "A package's ReleaseNotes property extracted from - # the PowerShell manifest may not be more than 10600 characters long". Description and Tags - # carry NuGet's 4,000. The tags it measures include the ones the publish adds, PSModule, a - # PSEdition_ tag per edition, PSFunction_ and PSCommand_ per exported function and - # PSIncludes_Function: the list the Gallery shows for 0.27.0. Build/Publish-Module.ps1 checks - # the same three; this fails the pull request instead of the tag-driven release. + # the PowerShell manifest may not be more than 10600 characters long". Description carries + # NuGet's 4,000. A line break is counted as two characters, the larger of the two possible + # counts, because the publish writes the notes with the line endings of the system that + # publishes. Build/Publish-Module.ps1 makes the same two measurements; this fails the pull + # request instead of the tag-driven release. The tags are not measured: the list the Gallery + # shows, with a tag for every exported function, has no 4,000-character limit. $manifest = Test-ModuleManifest -Path $script:ManifestPath - $text = switch ($Field) { - 'ReleaseNotes' { "$($manifest.ReleaseNotes)" } - 'Description' { "$($manifest.Description)" } - 'Tags' { - $tags = @($manifest.Tags) + 'PSModule' - $tags += @($manifest.CompatiblePSEditions | ForEach-Object { "PSEdition_$_" }) - foreach ($name in @($manifest.ExportedFunctions.Keys | Sort-Object)) { - $tags += "PSFunction_$name", "PSCommand_$name" - } - ($tags + 'PSIncludes_Function') -join ' ' - } - } - $text.Length | Should-BeLessThanOrEqual $Limit + $text = if ($Field -eq 'ReleaseNotes') { "$($manifest.ReleaseNotes)" } else { "$($manifest.Description)" } + $text.Replace("`r`n", "`n").Replace("`n", "`r`n").Length | Should-BeLessThanOrEqual $Limit } It 'has a format view for every output type an exported command declares' { From 99e05accd310dbc8f6446db6350d31e16d0f039d Mon Sep 17 00:00:00 2001 From: Jeffrey Stuhr <110697945+fadwen@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:09:03 -0800 Subject: [PATCH 2/2] refactor(release): name the parameters of every Join-Path call Ten Join-Path calls in Publish-Module.ps1 still passed both paths by position, three of them inside the script that verifies the staged module in a new process. They name -Path and -ChildPath now, like the other calls in the build scripts (STY-14, STY-30). The staged paths are the same as before. --- Build/Publish-Module.ps1 | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/Build/Publish-Module.ps1 b/Build/Publish-Module.ps1 index d40b2b8..6e6c5ca 100644 --- a/Build/Publish-Module.ps1 +++ b/Build/Publish-Module.ps1 @@ -219,7 +219,7 @@ $shipFolders = @( ) if (-not $StagingPath) { - $StagingPath = Join-Path $ModuleRoot 'out' + $StagingPath = Join-Path -Path $ModuleRoot -ChildPath 'out' } # --- 0. Resolve the API key ------------------------------------------------------- @@ -272,8 +272,9 @@ if (-not $WhatIfPreference -and -not $plainApiKey) { if (-not $SkipHelpBuild) { $priorWhatIf = $WhatIfPreference $WhatIfPreference = $false + $helpBuild = Join-Path -Path $PSScriptRoot -ChildPath 'Build-Help.ps1' try { - & (Join-Path $PSScriptRoot 'Build-Help.ps1') -ModuleRoot $ModuleRoot -SkipUpdate | Out-Null + & $helpBuild -ModuleRoot $ModuleRoot -SkipUpdate | Out-Null } finally { $WhatIfPreference = $priorWhatIf } @@ -281,7 +282,7 @@ if (-not $SkipHelpBuild) { } # --- 2. Manifest ------------------------------------------------------------------ -$manifestPath = Join-Path $ModuleRoot "$moduleName.psd1" +$manifestPath = Join-Path -Path $ModuleRoot -ChildPath "$moduleName.psd1" $manifest = Test-ModuleManifest -Path $manifestPath $version = $manifest.Version @@ -356,11 +357,11 @@ if (-not $WhatIfPreference) { if (Test-Path -LiteralPath $StagingPath) { Remove-Item -LiteralPath $StagingPath -Recurse -Force -WhatIf:$false } -$stageModule = Join-Path $StagingPath $moduleName +$stageModule = Join-Path -Path $StagingPath -ChildPath $moduleName New-Item -Path $stageModule -ItemType Directory -Force -WhatIf:$false | Out-Null foreach ($file in $shipFiles) { - $source = Join-Path $ModuleRoot $file + $source = Join-Path -Path $ModuleRoot -ChildPath $file if (-not (Test-Path -LiteralPath $source)) { throw "Shipping file '$file' is missing from the repository root." } @@ -368,7 +369,7 @@ foreach ($file in $shipFiles) { } foreach ($folder in $shipFolders) { - $source = Join-Path $ModuleRoot $folder + $source = Join-Path -Path $ModuleRoot -ChildPath $folder if (-not (Test-Path -LiteralPath $source)) { throw "Shipping folder '$folder' is missing from the repository root." } @@ -392,7 +393,7 @@ $staged | # fall back on, so a missing or misnamed IntuneScriptLab-Help.xml shows up as a command with # no description. The analysis is exercised too, on a detection script with the return-before- # exit mistake, because a module that imports can still be missing the rule that does the work. -$stagedManifest = Join-Path $stageModule "$moduleName.psd1" +$stagedManifest = Join-Path -Path $stageModule -ChildPath "$moduleName.psd1" # The exported names are compared with FunctionsToExport of the staged manifest, name by name: a # count that matches can hide one command missing and another exported by mistake. @@ -406,9 +407,11 @@ if (`$difference.Count -gt 0) { `$names = (`$difference | ForEach-Object { "`$(`$_.InputObject) (`$(`$_.SideIndicator))" }) -join ', ' throw "Staged module's exports differ from the manifest's FunctionsToExport: `$names" } -`$sample = Join-Path ([System.IO.Path]::GetTempPath()) "isl-staged-`$([guid]::NewGuid().ToString('N'))" -`$null = New-Item -ItemType Directory -Path (Join-Path `$sample 'Remediations\Widget') -Force -`$detect = Join-Path `$sample 'Remediations\Widget\Detect.ps1' +`$sampleName = "isl-staged-`$([guid]::NewGuid().ToString('N'))" +`$sample = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath `$sampleName +`$widget = Join-Path -Path `$sample -ChildPath 'Remediations\Widget' +`$null = New-Item -ItemType Directory -Path `$widget -Force +`$detect = Join-Path -Path `$widget -ChildPath 'Detect.ps1' Set-Content -Path `$detect -Value "if (Test-Path C:\x) { return 'issue' }`r`nexit 1" -Encoding UTF8 `$findings = @(Test-IntuneScript -Path `$detect) Remove-Item -Path `$sample -Recurse -Force