diff --git a/.github/workflows/lint-caller.yml b/.github/workflows/lint-caller.yml index 4fee7390..61ae4632 100644 --- a/.github/workflows/lint-caller.yml +++ b/.github/workflows/lint-caller.yml @@ -27,6 +27,8 @@ jobs: mise-version: "2026.10.19" # renovate: datasource=github-releases depName=golangci/golangci-lint # golangci-lint-version: "v2.12.2" + # renovate: datasource=nuget depName=PSScriptAnalyzer registryUrl=https://www.powershellgallery.com/api/v2/ + psscriptanalyzer-version: "1.25.0" lint-config-dir: config-sync/files # config-sync/templates holds a root biome.json for other repositories, # which Biome rejects as a second root config in this one. @@ -48,6 +50,8 @@ jobs: with: # renovate: datasource=github-releases depName=jdx/mise mise-version: "2026.10.19" + # renovate: datasource=nuget depName=PSScriptAnalyzer registryUrl=https://www.powershellgallery.com/api/v2/ + psscriptanalyzer-version: "1.25.0" lint-config-dir: config-sync/files lint-biome-exclude: config-sync/templates/* # See the job above. lint-job-mode: single diff --git a/.github/workflows/lint-include.yml b/.github/workflows/lint-include.yml index 9b0a69b1..654dbe67 100644 --- a/.github/workflows/lint-include.yml +++ b/.github/workflows/lint-include.yml @@ -26,6 +26,12 @@ on: required: false type: string default: "go.mod" + psscriptanalyzer-version: + description: "PSScriptAnalyzer version to install from the PowerShell Gallery. Without it, PSScriptAnalyzer skips + the repository's PowerShell files with a warning" + required: false + type: string + default: "" lint-config-dir: description: "Directory containing optional linter config files" required: false @@ -124,6 +130,12 @@ on: required: false type: boolean default: false + lint-psscriptanalyzer: + description: "Run PSScriptAnalyzer (PowerShell linting) when the repository has *.ps1, *.psm1 or *.psd1 files — uploads + SARIF" + required: false + type: boolean + default: false lint-config-drift: description: "Check local config files match central DevSecNinja/.github repo" required: false @@ -140,8 +152,8 @@ on: type: boolean default: false upload-sarif: - description: "Upload checkov/trivy/zizmor/ruff/biome results to GitHub code scanning (requires GitHub Advanced Security). - Set false for private repos without GHAS to gate on exit codes with console output instead." + description: "Upload checkov/trivy/zizmor/ruff/biome/psscriptanalyzer results to GitHub code scanning (requires GitHub + Advanced Security). Set false for private repos without GHAS to gate on exit codes with console output instead." required: false type: boolean default: true @@ -173,6 +185,7 @@ jobs: mise-version: ${{ inputs.mise-version }} golangci-lint-version: ${{ inputs.golangci-lint-version }} go-version-file: ${{ inputs.go-version-file }} + psscriptanalyzer-version: ${{ inputs.psscriptanalyzer-version }} lint-config-dir: ${{ inputs.lint-config-dir }} lint-fail-on-error: ${{ inputs.lint-fail-on-error }} lint-dprint: ${{ inputs.lint-dprint }} @@ -192,6 +205,7 @@ jobs: lint-biome: ${{ inputs.lint-biome }} lint-biome-exclude: ${{ inputs.lint-biome-exclude }} lint-biome-with-eslint: ${{ inputs.lint-biome-with-eslint }} + lint-psscriptanalyzer: ${{ inputs.lint-psscriptanalyzer }} lint-config-drift: ${{ inputs.lint-config-drift }} lint-inline-scripts: ${{ inputs.lint-inline-scripts }} lint-inline-scripts-blocking: ${{ inputs.lint-inline-scripts-blocking }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 9a24123f..d73e8698 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -18,6 +18,12 @@ on: required: false type: string default: "go.mod" + psscriptanalyzer-version: + description: "PSScriptAnalyzer version to install from the PowerShell Gallery. Without it, PSScriptAnalyzer skips + the repository's PowerShell files with a warning" + required: false + type: string + default: "" lint-config-dir: description: "Directory containing optional linter config files" required: false @@ -116,6 +122,12 @@ on: required: false type: boolean default: false + lint-psscriptanalyzer: + description: "Run PSScriptAnalyzer (PowerShell linting) when the repository has *.ps1, *.psm1 or *.psd1 files — uploads + SARIF" + required: false + type: boolean + default: true lint-config-drift: description: "Check local config files match central DevSecNinja/.github repo" required: false @@ -135,8 +147,8 @@ on: type: boolean default: false upload-sarif: - description: "Upload checkov/trivy/zizmor/ruff/biome results to GitHub code scanning (requires GitHub Advanced Security). - Set false for private repos without GHAS to gate on exit codes with console output instead." + description: "Upload checkov/trivy/zizmor/ruff/biome/psscriptanalyzer results to GitHub code scanning (requires GitHub + Advanced Security). Set false for private repos without GHAS to gate on exit codes with console output instead." required: false type: boolean default: true @@ -822,6 +834,61 @@ jobs: sarif_file: ${{ runner.temp }}/biome.sarif category: biome + psscriptanalyzer: + name: psscriptanalyzer + if: ${{ inputs.lint-psscriptanalyzer && (inputs.lint-job-mode == 'parallel' || (inputs.lint-job-mode == 'auto' && !github.event.repository.private)) + }} + continue-on-error: ${{ ! inputs.lint-fail-on-error }} + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + security-events: write + steps: + - name: Checkout lint scripts + # The linter scripts ship with this reusable workflow: fetch them from + # the same commit of DevSecNinja/.github that the caller pinned. + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: .devsecninja-lint + sparse-checkout: |- + scripts/lint/ + scripts/lint-inline-scripts.py + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Move lint scripts out of the workspace + # Outside the workspace the caller's linters don't scan them, and the + # code checkout doesn't delete them. + run: mv .devsecninja-lint "${RUNNER_TEMP}/devsecninja-lint" + + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Find PowerShell files + # Repositories without them skip PSScriptAnalyzer. + id: powershell-files + run: bash "${RUNNER_TEMP}/devsecninja-lint/scripts/lint/detect-language.sh" powershell + + - name: Run PSScriptAnalyzer + id: psscriptanalyzer + if: ${{ steps.powershell-files.outputs.found == 'true' }} + env: + PSSCRIPTANALYZER_VERSION: ${{ inputs.psscriptanalyzer-version }} + UPLOAD_SARIF: ${{ inputs.upload-sarif }} + run: bash "${RUNNER_TEMP}/devsecninja-lint/scripts/lint/psscriptanalyzer.sh" + + - name: Upload SARIF report + if: ${{ !cancelled() && steps.psscriptanalyzer.outputs.sarif == 'true' }} + uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + with: + sarif_file: ${{ runner.temp }}/psscriptanalyzer.sarif + category: psscriptanalyzer + config-drift: name: config drift if: ${{ inputs.lint-config-drift && (inputs.lint-job-mode == 'parallel' || (inputs.lint-job-mode == 'auto' && !github.event.repository.private)) @@ -960,6 +1027,12 @@ jobs: STEP_ASIDE_FOR: ${{ !inputs.lint-biome-with-eslint && 'eslint' || '' }} run: bash "${RUNNER_TEMP}/devsecninja-lint/scripts/lint/detect-language.sh" web + - name: Find PowerShell files + # Repositories without them skip PSScriptAnalyzer. + id: powershell-files + if: ${{ inputs.lint-psscriptanalyzer }} + run: bash "${RUNNER_TEMP}/devsecninja-lint/scripts/lint/detect-language.sh" powershell + - name: Install mise if: >- ${{ inputs.lint-dprint || inputs.lint-yamlfmt || inputs.lint-yamllint || inputs.lint-actionlint || inputs.lint-gitleaks @@ -1183,6 +1256,24 @@ jobs: sarif_file: ${{ runner.temp }}/biome.sarif category: biome + - name: Run PSScriptAnalyzer + id: psscriptanalyzer + if: ${{ steps.powershell-files.outputs.found == 'true' }} + continue-on-error: true + env: + PSSCRIPTANALYZER_VERSION: ${{ inputs.psscriptanalyzer-version }} + UPLOAD_SARIF: ${{ inputs.upload-sarif }} + run: bash "${RUNNER_TEMP}/devsecninja-lint/scripts/lint/psscriptanalyzer.sh" + + - name: Upload PSScriptAnalyzer SARIF report + id: psscriptanalyzer-sarif + if: ${{ !cancelled() && steps.psscriptanalyzer.outputs.sarif == 'true' }} + continue-on-error: true + uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + with: + sarif_file: ${{ runner.temp }}/psscriptanalyzer.sarif + category: psscriptanalyzer + - name: Check config drift against central repo id: config-drift if: ${{ inputs.lint-config-drift }} diff --git a/.renovate/customManagers.json5 b/.renovate/customManagers.json5 index c6fc60f4..c90c3ccd 100644 --- a/.renovate/customManagers.json5 +++ b/.renovate/customManagers.json5 @@ -20,12 +20,16 @@ "/workflow-templates/.+\\.ya?ml$/", ], matchStrings: [ - "# renovate: datasource=(?\\S+)(?: depName=(?\\S+))?\\n\\s+[\\w-]*version: \\[?\"?(?[^\\s\"\\[\\],]+)\"?\\]?[ \\t]*(?:#[^\\n]*)?(?:\\r?\\n|$)", + "# renovate: datasource=(?\\S+)(?: depName=(?\\S+))?(?: registryUrl=(?\\S+))?\\n\\s+[\\w-]*version: \\[?\"?(?[^\\s\"\\[\\],]+)\"?\\]?[ \\t]*(?:#[^\\n]*)?(?:\\r?\\n|$)", ], datasourceTemplate: "{{{datasource}}}", // `depName=` may be omitted for the runtime datasources, e.g. // # renovate: datasource=python-version // python-version: [3.14] + // and `registryUrl=` names a registry other than the datasource's + // default, e.g. the PowerShell Gallery for a module: + // # renovate: datasource=nuget depName=PSScriptAnalyzer registryUrl=https://www.powershellgallery.com/api/v2/ + // psscriptanalyzer-version: "1.25.0" // A single-element matrix list is tracked like a scalar; a list with // more entries is not tracked at all (the match must end the line; // Renovate's RE2 engine has no lookahead, so the line end is consumed). Without diff --git a/config-sync/templates/PSScriptAnalyzerSettings.psd1 b/config-sync/templates/PSScriptAnalyzerSettings.psd1 new file mode 100644 index 00000000..da5dd671 --- /dev/null +++ b/config-sync/templates/PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,56 @@ +@{ + # Template - adapt per repo. Settings for PSScriptAnalyzer, which the shared + # Lint workflow (lint-psscriptanalyzer) runs on the repository's *.ps1, *.psm1 + # and *.psd1 files. Errors and warnings fail the check; information findings + # are annotated only. Based on DevSecNinja/windows-iso-maker's settings. + + # Start from the full built-in rule set, then tighten a few rules. + IncludeDefaultRules = $true + + # ParseError must stay listed: without it, a script that doesn't parse passes. + Severity = @('ParseError', 'Error', 'Warning', 'Information') + + ExcludeRules = @( + # Files are UTF-8 without a BOM (.editorconfig), the same on Linux and + # Windows; non-ASCII characters in comments would trip this rule. + 'PSUseBOMForUnicodeEncodedFile', + + # PSScriptAnalyzer bug (as of 1.25.0): when a command has no parameter + # set, this rule throws a NullReferenceException that aborts the whole + # run, not just the finding. Re-enable it once + # https://github.com/PowerShell/PSScriptAnalyzer/issues/1708 is fixed. + 'PSUseCorrectCasing' + ) + + Rules = @{ + PSUseApprovedVerbs = @{ + Enable = $true + } + + # Comment-based help on every exported function. + PSProvideCommentHelp = @{ + Enable = $true + ExportedOnly = $true + BlockComment = $true + VSCodeSnippetCorrection = $false + Placement = 'begin' + } + + # No aliases: full command names only. + PSAvoidUsingCmdletAliases = @{ + Enable = $true + AllowList = @() + } + + # Honour -WhatIf in functions that change state. + PSUseShouldProcessForStateChangingFunctions = @{ + Enable = $true + } + + # Syntax that runs on both Windows PowerShell 5.1 and PowerShell 7. + PSUseCompatibleSyntax = @{ + Enable = $true + TargetVersions = @('5.1', '7.0') + } + } +} diff --git a/config-sync/templates/README.md b/config-sync/templates/README.md index e597551b..11be0897 100644 --- a/config-sync/templates/README.md +++ b/config-sync/templates/README.md @@ -118,3 +118,16 @@ usual template header. Config-sync doesn't add it to a repo that has `biome.jsonc`. The `customManagers:biomeVersions` Renovate preset, part of the shared Renovate config, keeps its `$schema` version in step with the pinned Biome. + +## PSScriptAnalyzerSettings.psd1 + +Settings for PSScriptAnalyzer, which the shared Lint workflow runs when the +repo has `*.ps1`, `*.psm1` or `*.psd1` files (`lint-psscriptanalyzer`, with the +`psscriptanalyzer-version` input). It starts from DevSecNinja/windows-iso-maker's +settings: every default rule plus approved verbs, comment-based help on +exported functions, no aliases, `ShouldProcess` for state changes and syntax +that runs on Windows PowerShell 5.1 and PowerShell 7. It skips the BOM rule +(files are UTF-8 without a BOM) and `PSUseCorrectCasing`, which crashes whole +runs until +[PowerShell/PSScriptAnalyzer#1708](https://github.com/PowerShell/PSScriptAnalyzer/issues/1708) +is fixed. diff --git a/docs/architecture.md b/docs/architecture.md index 77353210..28347868 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,7 @@ workflow, so it calls `scripts/apm-materialize/` from its own checkout. ### Lint (`lint.yml`) -Runs up to fifteen linters. By default, linter failures are reported without +Runs up to sixteen linters. By default, linter failures are reported without failing the workflow; set `lint-fail-on-error` to `true` to make lint failures fail the workflow. Toggle individual linters on/off with boolean inputs; all linter toggles default to `true`. @@ -201,6 +201,19 @@ APM-deployed agent files, `node_modules`, `.venv*`). Biome steps aside in repositories that configure ESLint (`eslint.config.*`, `.eslintrc*`), which lint in their own CI with their plugins; set `lint-biome-with-eslint` to run both. dprint formats only Markdown. +- **PSScriptAnalyzer** (`lint-psscriptanalyzer`, PowerShell, after v4.5.0) + analyzes the `*.ps1`, `*.psm1` and `*.psd1` files with the runner's `pwsh`. + It needs no mise: pass `psscriptanalyzer-version` instead, with a Renovate + annotation (see the [workflow template](../workflow-templates/lint.yml)). + Without it, a repository with PowerShell files gets a warning that names the + fix, and the linter skips instead of failing. Once the version is set, + findings fail as below. That version is installed from the PowerShell + Gallery unless the runner has it already. The repository's + `PSScriptAnalyzerSettings.psd1` configures it; config-sync's + [template](../config-sync/templates/PSScriptAnalyzerSettings.psd1) is a + starting point. Errors and warnings fail the linter, information findings + are only annotated. Findings are annotated on the PR, and with `upload-sarif` + they also go to code scanning (category `psscriptanalyzer`). **Inline scripts.** Code in a `run:` block is out of reach of linters, formatters and tests, so a `run:` step may hold exactly one line with one @@ -240,10 +253,11 @@ runner's system Python, which ships PyYAML (`ubuntu-24.04`). | `mise-version` | **Required.** mise version to install. | | `golangci-lint-version` | **Required.** golangci-lint version to install. | | `go-version-file` | Go version file for setup-go. Default: `go.mod`. | +| `psscriptanalyzer-version` | PSScriptAnalyzer version; skips with a warning if unset. After v4.5.0. | | `lint-config-dir` | Optional linter config directory. Default: `""`. | | `lint-fail-on-error` | Fail when a linter fails. Default: `false`. | | `lint-job-mode` | `auto`, `single`, or `parallel` (see above). Default: `auto`. v3.3.0+. | -| `upload-sarif` | Upload SARIF (checkov, trivy, zizmor, ruff, biome). Default: `true`. | +| `upload-sarif` | Upload SARIF (checkov, trivy, zizmor, language linters). Default: on. | | `lint-dprint` | Markdown formatting (dprint). Default: `true`. | | `lint-yamlfmt` | YAML formatting (yamlfmt). Default: `true`. | | `lint-yamllint` | YAML linting (yamllint). Default: `true`. | @@ -259,6 +273,7 @@ runner's system Python, which ships PyYAML (`ubuntu-24.04`). | `lint-biome` | JS/TS/JSON/CSS linting (Biome). Default: `true`. After v4.5.0. | | `lint-biome-exclude` | Bash pattern of paths Biome skips. Default: `""`. After v4.5.0. | | `lint-biome-with-eslint` | Run Biome next to ESLint. Default: `false`. After v4.5.0. | +| `lint-psscriptanalyzer` | PowerShell linting (PSScriptAnalyzer). Default: `true`. After v4.5.0. | | `lint-config-drift` | Config-drift check. Default: `false`. | | `lint-inline-scripts` | Inline-script check (see above). Default: `true`. After v4.4.0. | | `lint-inline-scripts-blocking` | Report inline scripts as errors. Default: `false`. After v4.4.0. | diff --git a/docs/design-decisions/0001-reusable-workflow-version-inputs.md b/docs/design-decisions/0001-reusable-workflow-version-inputs.md index 8f3f816c..bc54fcd1 100644 --- a/docs/design-decisions/0001-reusable-workflow-version-inputs.md +++ b/docs/design-decisions/0001-reusable-workflow-version-inputs.md @@ -46,6 +46,20 @@ It does **not** apply to: - Non-version configuration inputs (file paths, feature toggles, labels, …). These may and should have sensible defaults to keep callers terse. +**Conditional version inputs.** A version input for a tool that runs only when +the calling repository has matching files (Go code, PowerShell scripts, …) MAY +be declared `required: false`, so repositories without those files need no +version. It MUST still have no version default (`default: ""`): the workflow +never picks a version for the caller. When the tool would run and the caller +passed no version, the workflow MUST either fail with guidance, or skip the +tool with a `::warning` that names the input to set. The caller then owns the +version exactly as with `required: true`. In `lint.yml`, +`golangci-lint-version` (with `go.mod`) fails, and `psscriptanalyzer-version` +(with `*.ps1`, `*.psm1` or `*.psd1` files) skips with a warning, the rule +chosen for the language linters (#539): adopting a linter must not +turn a caller's lint red before it has picked a version. Once the version is +set, findings fail as usual. + ## Consequences ### Pros @@ -129,7 +143,8 @@ It does **not** apply to: ## Compliance -- `lint.yml` — `mise-version` and `golangci-lint-version` required ✅ +- `lint.yml` — `mise-version` required ✅; `golangci-lint-version` and + `psscriptanalyzer-version` conditional, no default (see the Decision) ✅ - `release.yml` — `mise-version` required ✅ - `autofix.yml` — `mise-version` required ✅ - `config-sync.yml`, `label-sync.yml`, `labeler.yml`, `todo-to-issue.yml` — diff --git a/scripts/lint/language-files.sh b/scripts/lint/language-files.sh index dc6014cb..e0e13e8d 100755 --- a/scripts/lint/language-files.sh +++ b/scripts/lint/language-files.sh @@ -20,6 +20,7 @@ web) ;; # ESLint configs: Biome steps aside for repositories that lint with ESLint. eslint) patterns=('**/eslint.config.*' '**/.eslintrc' '**/.eslintrc.*') ;; +powershell) patterns=('**/*.ps1' '**/*.psm1' '**/*.psd1') ;; *) echo "::error::language-files.sh: unknown language '$1'" >&2 exit 2 diff --git a/scripts/lint/psscriptanalyzer.ps1 b/scripts/lint/psscriptanalyzer.ps1 new file mode 100644 index 00000000..cf2f9a7a --- /dev/null +++ b/scripts/lint/psscriptanalyzer.ps1 @@ -0,0 +1,99 @@ +#Requires -Version 7.4 +<# +.SYNOPSIS + Runs PSScriptAnalyzer on the given files for scripts/lint/psscriptanalyzer.sh. +.DESCRIPTION + Installs the pinned PSScriptAnalyzer from the PowerShell Gallery unless that + version is present, then analyzes each file with the repository's + PSScriptAnalyzerSettings.psd1, when present. Findings are annotated on the + PR and, with -SarifFile, written as SARIF. Errors and warnings fail the run; + information findings are reported only. +.PARAMETER Version + The exact PSScriptAnalyzer version to use. +.PARAMETER SarifFile + Also write the findings to this SARIF file. +.PARAMETER PathList + A file listing the repository-relative files to analyze, NUL-separated. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [string] $Version, + + [Parameter(Mandatory)] + [string] $PathList, + + [string] $SarifFile +) + +$ErrorActionPreference = 'Stop' +$Path = [IO.File]::ReadAllText($PathList).Split([char] 0, [StringSplitOptions]::RemoveEmptyEntries) + +if (-not (Get-Module -ListAvailable -Name PSScriptAnalyzer | Where-Object { $_.Version -eq [version] $Version })) { + Install-PSResource -Name PSScriptAnalyzer -Version $Version -Repository PSGallery -TrustRepository -Scope CurrentUser -Quiet +} +Import-Module -Name PSScriptAnalyzer -RequiredVersion $Version + +$analyzerArgs = @{} +if (Test-Path -LiteralPath PSScriptAnalyzerSettings.psd1) { + $analyzerArgs.Settings = (Resolve-Path -LiteralPath PSScriptAnalyzerSettings.psd1).Path +} +# -Path expands wildcards: escape them, so deploy[1].ps1 means that file. +$findings = @(foreach ($file in $Path) { + Invoke-ScriptAnalyzer -Path ([WildcardPattern]::Escape($file)) @analyzerArgs + }) + +# SARIF levels by PSScriptAnalyzer severity, and workflow commands by level. +$levels = @{ ParseError = 'error'; Error = 'error'; Warning = 'warning'; Information = 'note' } +$commands = @{ error = 'error'; warning = 'warning'; note = 'notice' } + +function ConvertTo-CommandValue { + param([string] $Value, [switch] $Property) + $escaped = $Value.Replace('%', '%25').Replace("`r", '%0D').Replace("`n", '%0A') + if ($Property) { $escaped = $escaped.Replace(':', '%3A').Replace(',', '%2C') } + $escaped +} + +$annotations = [Collections.Generic.List[string]]::new() +$results = foreach ($finding in $findings) { + $file = [IO.Path]::GetRelativePath($PWD.Path, $finding.ScriptPath).Replace('\', '/') + # SARIF wants a URI: percent-encode each segment (# or % in a file name). + $uri = ($file.Split('/') | ForEach-Object { [Uri]::EscapeDataString($_) }) -join '/' + $level = $levels["$($finding.Severity)"] + $line = [Math]::Max(1, $finding.Line) + $column = [Math]::Max(1, $finding.Column) + $properties = "file=$(ConvertTo-CommandValue $file -Property),line=$line,col=$column," + + "title=$(ConvertTo-CommandValue $finding.RuleName -Property)" + $annotations.Add("::$($commands[$level]) ${properties}::$(ConvertTo-CommandValue $finding.Message)") + [ordered]@{ + ruleId = $finding.RuleName + level = $level + message = @{ text = $finding.Message } + locations = @(@{ physicalLocation = @{ + artifactLocation = @{ uri = $uri } + region = @{ startLine = $line; startColumn = $column } + } + }) + } +} +$annotations + +if ($SarifFile) { + $rules = @($findings | ForEach-Object RuleName | Sort-Object -Unique | ForEach-Object { @{ id = $_ } }) + $driver = [ordered]@{ + name = 'PSScriptAnalyzer' + version = $Version + informationUri = 'https://github.com/PowerShell/PSScriptAnalyzer' + rules = $rules + } + $sarif = [ordered]@{ + '$schema' = 'https://json.schemastore.org/sarif-2.1.0.json' + version = '2.1.0' + runs = @(@{ tool = @{ driver = $driver }; results = @($results) }) + } + $sarif | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $SarifFile -Encoding utf8NoBOM +} + +$failing = @($findings | Where-Object { $levels["$($_.Severity)"] -ne 'note' }) +Write-Output "PSScriptAnalyzer $Version checked $($Path.Count) file(s): $($findings.Count) finding(s), $($failing.Count) failing." +exit [int] ($failing.Count -gt 0) diff --git a/scripts/lint/psscriptanalyzer.sh b/scripts/lint/psscriptanalyzer.sh new file mode 100755 index 00000000..d508e6d6 --- /dev/null +++ b/scripts/lint/psscriptanalyzer.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# +# Lints the repository's PowerShell files with PSScriptAnalyzer, through +# psscriptanalyzer.ps1 (pwsh is preinstalled on the ubuntu runners). +# A step of .github/workflows/lint.yml, run the same way in both lint modes. +# The repository's PSScriptAnalyzerSettings.psd1, when present, configures it. +# Env: PSSCRIPTANALYZER_VERSION (psscriptanalyzer-version): the module version +# to install; without it the linter skips with a warning naming the fix. +# UPLOAD_SARIF: also write the findings as SARIF for code scanning, and +# sarif=true to GITHUB_OUTPUT. + +set -eo pipefail + +lint_dir="$(dirname "${BASH_SOURCE[0]}")" +mapfile -d '' files < <(bash "${lint_dir}/language-files.sh" powershell) +if [ "${#files[@]}" -eq 0 ]; then + echo "::notice::No PowerShell files found; skipping PSScriptAnalyzer" + exit 0 +fi +# Like an unpinned ruff or Biome: adopting the linter must not turn a +# caller's lint red before it has picked a version. +if [ -z "${PSSCRIPTANALYZER_VERSION}" ]; then + echo "::warning::Skipping PSScriptAnalyzer: this repository has PowerShell files but passes no psscriptanalyzer-version. To lint them, pass psscriptanalyzer-version (Renovate-managed, see workflow-templates/lint.yml in DevSecNinja/.github) and add a PSScriptAnalyzerSettings.psd1 (config-sync's template is a starting point), or set lint-psscriptanalyzer: false." + exit 0 +fi + +args=(-Version "${PSSCRIPTANALYZER_VERSION}" -PathList "${RUNNER_TEMP}/psscriptanalyzer-files") +if [ "${UPLOAD_SARIF}" = "true" ]; then + args+=(-SarifFile "${RUNNER_TEMP}/psscriptanalyzer.sarif") +fi +# A list file, not arguments: pwsh -File would read a path such as -x.ps1 as a +# parameter name. +printf '%s\0' "${files[@]}" >"${RUNNER_TEMP}/psscriptanalyzer-files" + +status=0 +pwsh -NoProfile -NonInteractive -File "${lint_dir}/psscriptanalyzer.ps1" "${args[@]}" || status=1 +if [ "${UPLOAD_SARIF}" = "true" ] && [ -f "${RUNNER_TEMP}/psscriptanalyzer.sarif" ]; then + echo "sarif=true" >>"${GITHUB_OUTPUT}" +fi +exit "${status}" diff --git a/tests/lint-job-modes-contract.sh b/tests/lint-job-modes-contract.sh index ddbd5c32..ef32cb98 100755 --- a/tests/lint-job-modes-contract.sh +++ b/tests/lint-job-modes-contract.sh @@ -14,7 +14,7 @@ set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" workflow="${repo_root}/.github/workflows/lint.yml" combined_job="all-linters" -linter_jobs=(dprint yamlfmt yamllint actionlint gitleaks go shellcheck shfmt checkov trivy zizmor ruff biome config-drift inline-scripts) +linter_jobs=(dprint yamlfmt yamllint actionlint gitleaks go shellcheck shfmt checkov trivy zizmor ruff biome psscriptanalyzer config-drift inline-scripts) parallel_guard="(inputs.lint-job-mode == 'parallel' || (inputs.lint-job-mode == 'auto' && !github.event.repository.private))" fail() { diff --git a/tests/lint-scripts.sh b/tests/lint-scripts.sh index bcb05cd7..87004047 100755 --- a/tests/lint-scripts.sh +++ b/tests/lint-scripts.sh @@ -20,6 +20,8 @@ fail() { } command -v jq >/dev/null 2>&1 || fail "jq is not installed" +# The real pwsh, before the stand-ins below shadow it. +real_pwsh="$(command -v pwsh || true)" # `mise which ` succeeds for the tools in $FAKE_TOOLS. `mise exec -- ` # records the working directory and command in $MISE_LOG, and exits $FAKE_EXIT. @@ -309,6 +311,86 @@ expect_status 0 "Biome without its files" expect_out "::notice::No JavaScript, TypeScript, JSON or CSS files found; skipping Biome" "Biome without its files" [ -z "${log}" ] || fail "Biome must not run without its files: ${log}" +# PSScriptAnalyzer runs psscriptanalyzer.ps1 with pwsh, which is not a mise +# tool. The stand-in pwsh logs its arguments and the files of -PathList. +cat >"${tmp_dir}/bin/pwsh" <<'EOF' +#!/usr/bin/env bash +printf 'pwsh %s\n' "${*##*/scripts/lint/}" >>"${MISE_LOG}" +while [ "$#" -gt 0 ]; do + [ "$1" != -PathList ] || printf 'files: %s\n' "$(tr '\0' ' ' <"$2")" >>"${MISE_LOG}" + shift +done +[ -z "${FAKE_WRITES:-}" ] || touch "${FAKE_WRITES}" +exit "${FAKE_EXIT:-0}" +EOF +chmod +x "${tmp_dir}/bin/pwsh" +touch "${code}/a.ps1" "${code}/sub/b.psm1" "${code}/sub/c.psd1" "${code}/.specify/d.ps1" +git -C "${code}" add -f -- a.ps1 sub/b.psm1 sub/c.psd1 .specify/d.ps1 +run_in "${code}" psscriptanalyzer +expect_status 0 "PowerShell files without psscriptanalyzer-version" +expect_out "::warning::Skipping PSScriptAnalyzer: this repository has PowerShell files but passes no psscriptanalyzer-version." \ + "PowerShell files without psscriptanalyzer-version" +expect_out "To lint them, pass psscriptanalyzer-version" "the skip warning must name the fix" +[ -z "${log}" ] || fail "PSScriptAnalyzer must not run without a version: ${log}" +[ -z "${outputs}" ] || fail "a skipped PSScriptAnalyzer must not report a SARIF report: ${outputs}" +export PSSCRIPTANALYZER_VERSION=1.25.0 +pssa_call="pwsh -NoProfile -NonInteractive -File psscriptanalyzer.ps1 -Version 1.25.0" +pssa_call+=" -PathList ${RUNNER_TEMP}/psscriptanalyzer-files" +run_in "${code}" psscriptanalyzer FAKE_WRITES="${RUNNER_TEMP}/psscriptanalyzer.sarif" +expect_status 0 "PSScriptAnalyzer with SARIF" +expect_log "${pssa_call} -SarifFile ${RUNNER_TEMP}/psscriptanalyzer.sarif" "PSScriptAnalyzer with SARIF" +expect_log "files: a.ps1 sub/b.psm1 sub/c.psd1 " "PSScriptAnalyzer must get the PowerShell files, minus the excludes" +[ "${outputs}" = sarif=true ] || fail "PSScriptAnalyzer must report its SARIF report; got: ${outputs}" +run_in "${code}" psscriptanalyzer FAKE_EXIT=1 UPLOAD_SARIF=false +expect_status 1 "a failing PSScriptAnalyzer" +[[ "${log}" == "${pssa_call}"$'\n'* ]] || fail "PSScriptAnalyzer without SARIF: ${log}" +[ -z "${outputs}" ] || fail "PSScriptAnalyzer must not report a SARIF report it didn't write: ${outputs}" +git -C "${code}" rm -q --cached a.ps1 sub/b.psm1 sub/c.psd1 +run_in "${code}" psscriptanalyzer PSSCRIPTANALYZER_VERSION= +expect_status 0 "PSScriptAnalyzer without PowerShell files" +expect_out "::notice::No PowerShell files found; skipping PSScriptAnalyzer" "PSScriptAnalyzer without PowerShell files" +[ -z "${log}" ] || fail "PSScriptAnalyzer must not run without PowerShell files: ${log}" + +# The real psscriptanalyzer.ps1, when pwsh and PSScriptAnalyzer are installed +# (ubuntu-24.04 runners ship both): it analyzes file names with wildcard +# characters literally, and the template's settings keep parse errors. +pssa_version="" +if [ -n "${real_pwsh}" ]; then + pssa_version="$("${real_pwsh}" -NoProfile -Command \ + '(Get-Module -ListAvailable PSScriptAnalyzer | Sort-Object Version | Select-Object -Last 1).Version.ToString()' | + tr -d '\r')" || true +fi +if [ -z "${pssa_version}" ]; then + echo "::notice::pwsh or PSScriptAnalyzer is not installed; skipping the psscriptanalyzer.ps1 run" +else + ps_dir="${tmp_dir}/powershell" + mkdir -p "${ps_dir}" + printf 'gci\n' >"${ps_dir}/deploy[1].ps1" + printf 'Get-ChildItem\n' >"${ps_dir}/deploy1.ps1" + printf 'function Get-X {\n' >"${ps_dir}/broken.ps1" + cp "${repo_root}/config-sync/templates/PSScriptAnalyzerSettings.psd1" "${ps_dir}/" + ps1="${scripts}/psscriptanalyzer.ps1" + if command -v cygpath >/dev/null 2>&1; then ps1="$(cygpath -w "${ps1}")"; fi + # Analyzes the files $@ of ${ps_dir}; sets status and out. + run_pssa() { + printf '%s\0' "$@" >"${ps_dir}/files" + status=0 + out="$(cd "${ps_dir}" && + "${real_pwsh}" -NoProfile -NonInteractive -File "${ps1}" -Version "${pssa_version}" -PathList files 2>&1)" || + status=$? + out="${out//$'\r'/}" + } + run_pssa 'deploy[1].ps1' deploy1.ps1 + expect_status 1 "PSScriptAnalyzer on deploy[1].ps1" + expect_out "::warning file=deploy[1].ps1,line=1,col=1,title=PSAvoidUsingCmdletAliases::" \ + "deploy[1].ps1 must be analyzed, not deploy1.ps1 twice" + run_pssa deploy1.ps1 + expect_status 0 "PSScriptAnalyzer on a clean file" + run_pssa broken.ps1 + expect_status 1 "a script that doesn't parse, with the template settings" + expect_out "::error file=broken.ps1," "a script that doesn't parse, with the template settings" +fi + # The SARIF filter drops checkov's skipped checks (level none) and tolerates a # missing report. run checkov-sarif-filter diff --git a/tests/renovate-annotation-managers.sh b/tests/renovate-annotation-managers.sh index a6726f5e..04785c51 100644 --- a/tests/renovate-annotation-managers.sh +++ b/tests/renovate-annotation-managers.sh @@ -3,8 +3,9 @@ # Checks the annotation-driven Renovate custom managers in # .renovate/customManagers.json5: # -# - "Process tool versions in GitHub Actions workflows": depName= is optional -# and a single-element matrix list (`python-version: [3.14]`) is tracked; +# - "Process tool versions in GitHub Actions workflows": depName= and +# registryUrl= are optional and a single-element matrix list +# (`python-version: [3.14]`) is tracked; # - "Process versions in Ansible inventory YAML files": any datasource, an # optional registryUrl and any key on the annotated line. # @@ -88,6 +89,18 @@ for text, want in workflow_cases.items(): if got != want: errors.append(f"workflow manager: {text!r}: want {want}, got {got}") +# An optional registryUrl, e.g. the PowerShell Gallery for a module. +psgallery = "https://www.powershellgallery.com/api/v2/" +for text, want in { + f' # renovate: datasource=nuget depName=PSScriptAnalyzer registryUrl={psgallery}\n psscriptanalyzer-version: "1.25.0"': + ("nuget", "PSScriptAnalyzer", "1.25.0", psgallery), + ' # renovate: datasource=github-releases depName=jdx/mise\n mise-version: "2026.10.19"': + ("github-releases", "jdx/mise", "2026.10.19", None), +}.items(): + got = fields(workflow.search(text), names + ("registryUrl",)) + if got != want: + errors.append(f"workflow manager: {text!r}: want {want}, got {got}") + deb_url = "https://download.docker.com/linux/debian?suite=trixie&components=stable&binaryArch=amd64" ansible_cases = { f' # renovate: datasource=deb depName=docker-ce registryUrl={deb_url}\n docker_ce: "5:29.6.2-1~debian.13~trixie"': diff --git a/tests/workflow-job-conditions.py b/tests/workflow-job-conditions.py index e47c831d..b540da59 100755 --- a/tests/workflow-job-conditions.py +++ b/tests/workflow-job-conditions.py @@ -422,6 +422,7 @@ def lint_context(*, mode="auto", private=False, has_repository=True, event_name= "zizmor", "ruff", "biome", + "psscriptanalyzer", "inline-scripts", ) } @@ -447,6 +448,7 @@ def lint_context(*, mode="auto", private=False, has_repository=True, event_name= "zizmor", "ruff", "biome", + "psscriptanalyzer", "inline-scripts", } SINGLE = {"all-linters"} diff --git a/workflow-templates/lint.yml b/workflow-templates/lint.yml index b815ee5e..e1f3c7cf 100644 --- a/workflow-templates/lint.yml +++ b/workflow-templates/lint.yml @@ -69,6 +69,12 @@ jobs: # repository has JavaScript, TypeScript, JSON or CSS files and no ESLint # config. Pin biome in your mise config. # lint-biome: true + # Optional: needs a lint.yml release after v4.5.0; runs only when the + # repository has *.ps1, *.psm1 or *.psd1 files. Without this version + # (installed from the PowerShell Gallery) it skips with a warning. + # lint-psscriptanalyzer: true + # renovate: datasource=nuget depName=PSScriptAnalyzer registryUrl=https://www.powershellgallery.com/api/v2/ + # psscriptanalyzer-version: "1.25.0" # lint-config-drift: false # Optional: report inline scripts in run: steps. Needs a lint.yml release # after v4.4.0; bump the pin above before uncommenting.