Repository navigation
fix(module): run under strict mode and fail the import on a load error - #84
Conversation
The root module set no strict mode, so a read of a member that was not there gave $null with no error anywhere in the module. Its loader dot-sourced each file without a try and read the folders with -ErrorAction SilentlyContinue: a file that did not parse wrote an error and the module still imported, without the commands of that file, and a missing Private or Public folder was not an error at all. The root module now sets Set-StrictMode -Version Latest and loads Private, Private/Rules and Public in one loop that fails on a missing folder and rethrows when a file fails to load. With strict mode on, 415 of the 998 unit tests failed, for a small number of causes, all of them reads of a member that is optional: - Hashtables that the module's caller writes (a settings table, a directive, a detection rule, a -DependsOn entry) are read with an index, which gives $null for a key that is not there. - Data from outside is read through Get-IslPropertyValue, a new private accessor that returns nothing for a missing input, key or property and takes a dictionary and an object alike: Graph replies in Test-IntuneDeployedScript, Compare-IntuneDeployedScript, Get-IntuneScriptHealth, Get-IslExportReport and Invoke-IslGraphRequest, the result of a CIM method in Get-IslLogonSession, and the two shapes of finding that Export-IntuneFindingSarif takes. - Find-IslModuleDependency no longer reads the required modules of a script that has no #Requires line, and the event table of Get-IslAgentLogEvent is assigned before its first read. The tests needed three kinds of change. Fakes of a run result named only the members their test was about; they go through ConvertTo-FakeRunResult, which adds the rest. The Graph mock of the health tests matched a run summary URI with two patterns and returned two objects, which member enumeration had hidden. Test code inside InModuleScope runs under the module's strict mode and reads no variable that was never set. Tests/Invoke-Tests.ps1 still turns strict mode off around the Pester run, for the suites and the validation kit. The module no longer depends on that. Refs #63
fadwen
left a comment
There was a problem hiding this comment.
Notes on the lines whose reason the diff does not show.
| try { | ||
| Write-Verbose "Loading $($functionFile.FullName)" | ||
| . $functionFile.FullName | ||
| } catch { |
There was a problem hiding this comment.
The catch that only rethrows is what makes a file that does not parse fail the import. Dot-sourcing such a file raises an error that ends only that statement, so without the try the loop went on and the module imported without the commands of the file. Rethrown from catch, the error ends the root module. Module.Contract.Tests.ps1 imports a copy with such a file in a new process and checks that the module is not loaded afterwards.
| if ($Table.MinimumSeverity -and "$($Table.MinimumSeverity)" -notin $validSeverities) { | ||
| # Every key is optional. An index reads a key that is not there as $null, where member | ||
| # access is an error under strict mode | ||
| $minimumSeverity = $Table['MinimumSeverity'] |
There was a problem hiding this comment.
An index here, not Get-IslPropertyValue: $Table is typed [hashtable], so the question of dictionary or object does not arise, and an index reads a key that is not there as $null. The accessor is for data whose shape the module does not control.
| 'detectionScriptPending' | ||
| 'detectionScriptNotApplicable' | ||
| ) | ||
| foreach ($counter in $counters) { |
There was a problem hiding this comment.
Eight reads of the same shape, so they are made in one loop. [int] of a value that is not there is 0 on PowerShell 7 and on Windows PowerShell 5.1, which is what [int]$run.noIssueDetectedDeviceCount gave before for a summary that was absent or lacked the counter.
| $tenant.runSummaries[$Matches[1]] | ||
| } | ||
| '^/beta/deviceManagement/deviceHealthScripts/([^?/]+)' { | ||
| '^/beta/deviceManagement/deviceHealthScripts/([^?/]+)(\?|$)' { |
There was a problem hiding this comment.
Without the end of the pattern this clause also matched a .../runSummary address, and switch -Regex runs every clause that matches, so the mock answered a run summary request with two objects: the summary and the policy. The command read the counters from that pair by member enumeration, which took them from the element that had them. Read through the accessor, the pair has no counters, so three tests failed until the mock returned one object, as Graph does.
| Mock Invoke-IslScriptRun -ModuleName IntuneScriptLab -ParameterFilter { $Phase -eq 'detect' } { | ||
| if (Test-Path (Join-Path (Split-Path $Path -Parent) 'fixed.marker')) { | ||
| [pscustomobject]@{ ExitCode = 0; TimedOut = $false; StdOut = 'present'; StdErr = '' } | ||
| ConvertTo-FakeRunResult @{ ExitCode = 0; TimedOut = $false; StdOut = 'present'; StdErr = '' } |
There was a problem hiding this comment.
The commands these fakes feed are unchanged. A real run result always has RunAs, Host, ScriptPath and Duration; the fakes did not, and the commands' reads of them were a silent $null until strict mode made them errors. Completing the fake keeps the commands free of guards against a shape they never receive. The helper can be called here because a mock body runs in the scope of the test file, not in the module's.
| if ($null -ne $Settings) { $parameters.Settings = $Settings } | ||
| # Settings is always passed, as $null when the test gives none: the block below runs under | ||
| # the module's strict mode, where a variable that was never set cannot be read | ||
| $parameters = @{ Path = (Join-Path $script:Tree $Relative); Cache = $Cache; Settings = $Settings } |
There was a problem hiding this comment.
The block passed to InModuleScope runs under the module's strict mode. $Settings existed in it only when the test gave settings, so the $null -ne $Settings below read a variable that had never been set.
| # written for strict mode (#63, #70, #71), so it is off for the run and on again after it. | ||
| # mode. The module sets its own in its root module and does not depend on this one, but the | ||
| # suites and the validation kit are not yet written for strict mode (#70, #71), so it is off for | ||
| # the run and on again after it. |
fadwen
left a comment
There was a problem hiding this comment.
Verdict: approve. One should-fix (small), and nits.
Reviewed against ai-powershell-standards (ERR-02, ERR-03, MOD-05, FUN-26). Checked in a Linux sandbox with pwsh 7.6.0 and Pester 6.2.0.
Verified
- No regressions (differential run): I ran the full unit suites (
Tests/UnitandValidation/Tests/Unit, shuffle seed 12345) on #82 and on this branch.- The set of failures is identical: 135 tests, all Linux-only (HKLM, icacls, CIM, Windows hosts).
- This branch has 21 more passing tests (849 → 870): the new tests in Module.Contract and
Get-IslPropertyValue.Tests.ps1, all passing.
IntuneScriptLab.psm1: sets strict mode at the top and loads the folders with-LiteralPath. A missing folder throws, and a load failure is rethrown. Thetry { . $file } catch { throw }is needed: without it, a statement-terminating error in a module script lets the import go on.Get-IslPropertyValue: returns nothing for$null, for a missing key and for a missing property. It works with a Hashtable, an ordered dictionary and a PSCustomObject, and is case-insensitive for Hashtables and objects, as member access was.- Script content: the policies' script content is a base64 string, so the accessor unrolling its output doesn't touch it (
Test-PolicyScripttakes[string]$Content). - Lists: every list read I found goes through
@(...): assignments,value,detectionRules,requirementRules.
Unverified (needs Windows, a tenant or a lab device): the tenant output being byte-identical, the run as SYSTEM on the lab device, and CI run 45137082728. This PR has no checks because its base isn't main.
Should-fix: Private/Get-IslPropertyValue.ps1 line 55, $InputObject.Contains($Name)
- On a generic
Dictionary[string,object]this throws "Cannot find an overload for Contains". That type implementsIDictionary.Containsexplicitly, so PowerShell doesn't bind it. Reproduced. - Nothing passes such a dictionary today: Graph replies are Hashtables, and JSON gives ordered hashtables or objects. But the help says the function takes any dictionary.
- Fix:
([System.Collections.IDictionary]$InputObject).Contains($Name), plus one test case.
Nits
- Loader: a one-line comment on the
try/catchsaying why it's there would stop someone from removing it as dead code. - Accessor output: it unrolls a collection on the way out (documented). A future caller that reads a
byte[]or a one-element array without@()getsobject[]or a scalar.Write-Output -NoEnumeratewould remove that trap, if no caller relies on the unrolling.
Get-IslPropertyValue called Contains on the dictionary itself. A generic Dictionary[string, object] implements that method of IDictionary explicitly, so PowerShell does not find it there and the call failed with "Cannot find an overload for Contains" for a key that is present and for one that is not. Nothing passes such a dictionary today, but the help says the function takes any dictionary. The method is now called through the interface, and a test covers the type. The catch in the root module's loader gets a comment that says why it only rethrows, so that it is not removed as dead code. Refs #63
|
The should-fix and the first nit are addressed in 35fd3e7. The second nit is not taken, for the reason below.
Comment on the loader's
The checks that could not be made in the sandbox
|
Summary
The root module set no strict mode, and its loader carried on when a function file failed to load: a file that did not parse wrote an error and the module still imported, without the commands of that file. ai-powershell-standards 2.0.0 requires strict mode in the root module (ERR-02), code that runs without errors under it (ERR-03), and an import that fails when a file fails to load (MOD-05). This change sets strict mode, replaces the loader, and fixes every read the suites then reported. Closes #63.
This pull request is stacked on #82 (
ci/line-endings) and merges after it.Changes
IntuneScriptLab.psm1setsSet-StrictMode -Version Latestand loadsPrivate,Private/RulesandPublicin one loop that builds each path withJoin-Path, fails on a missing folder and rethrows when a file fails to load.Get-IslPropertyValue: returns a named value from a dictionary or an object, and nothing for a missing input, key or property. It is the one accessor for data with optional members (FUN-26).Test-IntuneDeployedScript,Compare-IntuneDeployedScript,Get-IntuneScriptHealth,Get-IslExportReportandInvoke-IslGraphRequest. So are the result of a CIM method inGet-IslLogonSessionand the two shapes of finding thatExport-IntuneFindingSariftakes.$nullfor a key that is not there: the settings table inGet-IslSetting, the directive inGet-IslScriptContext, a rule inConvertFrom-IslRuleSpec, and the-DependsOnand-Supersedesentries ofInvoke-IntuneWin32AppTest.Find-IslModuleDependencyno longer reads the required modules of a script that has no#Requiresline, and the event table ofGet-IslAgentLogEventis assigned before its first read.ConvertTo-FakeRunResulthelper, which gives them every member the real result has. The Graph mock of the health tests no longer answers a run summary URI with two objects.Module.Contract.Tests.ps1checks that the module's functions run under strict mode and that the import fails for a file that throws, a file that does not parse, and a missingPrivate\RulesorPublicfolder.Get-IslPropertyValue.Tests.ps1covers the accessor against a hashtable, an ordered dictionary and an object.CLAUDE.mdrecords the invariant, andCHANGELOG.mdhas the two entries under Changed.Verification
./Tests/Invoke-Tests.ps1 -CodeCoverageon PowerShell 7.6.10, shuffled: 1,062 passed, 3 failed, 8 skipped, coverage 95.19 percent. The three failures are the ones that fail on that computer before this change and pass in CI: two because its code pages are 65001 (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75), one because its Windows build has a module the in-box table lacks (In-box module table does not list UOPProviders, present on Windows 11 26H2 #76).powershell -NoProfile -File ./Tests/Invoke-Tests.ps1 -TestType Uniton Windows PowerShell 5.1.26100, shuffled: 979 passed, 2 failed, 38 skipped. The two failures are Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75 and In-box module table does not list UOPProviders, present on Windows 11 26H2 #76 again. The integration suites on 5.1: 47 passed, 1 failed (Repair-IntuneScript corrupts an ANSI script on a host with a UTF-8 system code page #75), 6 skipped.Invoke-ScriptAnalyzerwith-Severity Error, Warning -ExcludeRule PSAvoidLongLines, and with-Settings ScriptSecurity, on the 26 changed script files: no findings.Test-StandardsCompliance.ps1of ai-powershell-standards 2.0.0 reports no finding in the two new files, and no file has more findings than before../Build/Publish-Module.ps1 -WhatIf: the staged module imports in a new process, exports the declared commands and serves its help; nothing was published.quality-gates.yml, dispatched on this branch because it triggers only for pull requests intomain: all five jobs passed (run 45137082728).Against a tenant, read-only, on PowerShell 7.6.10:
Test-IntuneDeployedScript,Compare-IntuneDeployedScriptandGet-IntuneScriptHealthreturn the same output from the base branch and from this one, byte for byte as JSON: 1,027 findings, 183 drift results and 151 health reports.On a lab device, as
NT AUTHORITY\SYSTEMunder Windows PowerShell 5.1.26100.9818, every suite of this branch: 1,022 passed, 0 failed, 51 skipped. The user-context suite ran there with the harness account, which no hosted runner does. Of the skipped, 47 are tests that need PowerShell 7 or PSScriptAnalyzer, which the device does not have.The other four skipped tests are skipped on every machine, by a defect in their skip condition that this change does not touch (Four tests never run: their -Skip condition reads a variable that BeforeAll sets after discovery #83). Three of them are the SYSTEM-context suite, so a copy of that file with the condition evaluated at discovery was run on the same device against this branch: 3 passed. They launch a script through a scheduled task as SYSTEM, time one out and remove the task.
Not verified: the tenant comparison under Windows PowerShell 5.1, because Microsoft.Graph.Authentication is not installed for it on the computer that ran the checks.
Get-IntuneScriptHealthwas run with-SkipRunStatefor Win32 apps, because their install counts come from an export job, which is a write to the tenant;Get-IslExportReportis covered by its unit tests only.Notes
Tests/Invoke-Tests.ps1still turns strict mode off around the Pester run. The module no longer depends on that, but the suites (Tests reload the module in every file and run longer than the limits (TST-05, TST-47) #70) and the validation kit (Validation kit scripts lack strict mode, help and terminating errors (ERR-01, ERR-11, DOC-01, FUN-01) #71) are not strict-clean yet.throwstatements in the functions touched here are unchanged; Advanced functions end with throw instead of ThrowTerminatingError (ERR-10, ERR-11, ERR-14) #64 replaces them with$PSCmdlet.ThrowTerminatingError().Data/RuleOrder.psd1(MOD-20). It is unchanged here.