From 08b6ddde9ed57ed4dbdabff5c5fb21583f0923c8 Mon Sep 17 00:00:00 2001 From: Jeffrey <9938813+Raphire@users.noreply.github.com> Date: Tue, 27 Oct 2026 23:08:46 +0100 Subject: [PATCH] fix: update RunOnce command handling to avoid & enforce length limits (#866) --- Scripts/AppRemoval/Remove-SelectedApps.ps1 | 27 ++++--- Scripts/GUI/Show-ApplyModal.ps1 | 3 +- Scripts/Helpers/Get-RebootFeatureLabels.ps1 | 24 +++++- Tests/Get-RebootFeatureLabels.Tests.ps1 | 55 ++++++++++++++ Tests/Remove-SelectedApps.Tests.ps1 | 82 +++++++++++++++++++-- 5 files changed, 172 insertions(+), 19 deletions(-) diff --git a/Scripts/AppRemoval/Remove-SelectedApps.ps1 b/Scripts/AppRemoval/Remove-SelectedApps.ps1 index 98c08b1..94fb791 100644 --- a/Scripts/AppRemoval/Remove-SelectedApps.ps1 +++ b/Scripts/AppRemoval/Remove-SelectedApps.ps1 @@ -211,6 +211,10 @@ function Remove-WinGetApp { else { "user $($runOnceTarget.UserName)" } Write-Host "Adding RunOnce uninstall for $app for $targetDescription..." $scheduleSucceeded = Set-RunOnceWingetTask -appId $app -Target $runOnceTarget + if ($scheduleSucceeded) { + if (-not $script:WingetDeferredRemovals) { $script:WingetDeferredRemovals = @{} } + $script:WingetDeferredRemovals[$app] = $runOnceTarget.UserName + } } if ($null -ne $SchedulingFailed) { $SchedulingFailed.Value = -not $scheduleSucceeded } @@ -549,10 +553,9 @@ function Get-RunOnceWingetTargetUserNames { which handles hive loading and HKEY_USERS\Default → SID remapping. Used instead of static .reg files to avoid file dependency for each WinGet app. - The winget command is Base64-encoded and invoked via powershell.exe -EncodedCommand - rather than interpolated directly into cmd.exe /c. This prevents shell metacharacters - (such as &, |, <, >, ^, ") in the app ID from being interpreted as command syntax, - even if future catalog updates introduce IDs containing those characters. + Invokes winget.exe directly with a quoted app ID, without a shell wrapper. + Escapes embedded quotes and trailing backslashes for native argument parsing, + and rejects commands exceeding RunOnce's 260-character limit. .PARAMETER appId The winget package ID to schedule for uninstall (e.g. 'XP9CXNGPPJ97XX'). @@ -584,18 +587,20 @@ function Set-RunOnceWingetTask { $taskName = "Uninstall_$safeAppId" - # Escape single quotes in appId, then wrap in single quotes so cmd/pwsh metacharacters - # like & | < > ^ " are treated as literals. Base64-encode the whole command so the - # RunOnce value contains only [A-Za-z0-9+/=] — safe in any shell parser. - $escapedAppId = $appId.Replace("'", "''") - $wingetCommand = "winget uninstall --accept-source-agreements --disable-interactivity --id '$escapedAppId'" - $encodedWingetCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($wingetCommand)) + # Preserve the ID as one native argument. No cmd.exe or PowerShell interprets its contents. + $escapedAppId = $appId -replace '(\\*)"', '$1$1\"' + $escapedAppId = $escapedAppId -replace '(\\+)$', '$1$1' + $wingetCommand = "winget.exe uninstall --accept-source-agreements --disable-interactivity --id `"$escapedAppId`"" + if ($wingetCommand.Length -gt 260) { + Write-Error "Failed to schedule uninstall task for $($appId): the RunOnce command exceeds 260 characters." + return $false + } $operation = [PSCustomObject]@{ KeyPath = 'HKEY_USERS\Default\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce' ValueName = $taskName ValueType = 'String' - ValueData = "powershell.exe -NoProfile -EncodedCommand $encodedWingetCommand" + ValueData = $wingetCommand OperationType = 'SetValue' } diff --git a/Scripts/GUI/Show-ApplyModal.ps1 b/Scripts/GUI/Show-ApplyModal.ps1 index 86f6889..a7c75f0 100644 --- a/Scripts/GUI/Show-ApplyModal.ps1 +++ b/Scripts/GUI/Show-ApplyModal.ps1 @@ -185,9 +185,8 @@ function Show-ApplyModal { } } if ($script:WingetDeferredRemovals -and $script:WingetDeferredRemovals.Count -gt 0) { - foreach ($appId in @($script:WingetDeferredRemovals.Keys | Sort-Object)) { + foreach ($appName in @(Get-DeferredAppRemovalLabels)) { $tb = [System.Windows.Controls.TextBlock]::new() - $appName = Get-Translation -Key $appId -Field 'FriendlyName' -Section 'Apps' $label = Get-Translation -Key 'ApplyRebootRequiredWingetDeferred' -FormatArgs @($appName) $tb.Text = "$([char]0x2022) $label" $tb.FontSize = 12 diff --git a/Scripts/Helpers/Get-RebootFeatureLabels.ps1 b/Scripts/Helpers/Get-RebootFeatureLabels.ps1 index 756b724..f03fa22 100644 --- a/Scripts/Helpers/Get-RebootFeatureLabels.ps1 +++ b/Scripts/Helpers/Get-RebootFeatureLabels.ps1 @@ -24,4 +24,26 @@ function Get-RebootFeatureLabels { } return $rebootFeatureLabels -} \ No newline at end of file +} + +<# + .SYNOPSIS + Resolves one deferred-removal display label per catalog app, grouping its package IDs. +#> +function Get-DeferredAppRemovalLabels { + if (-not $script:WingetDeferredRemovals -or $script:WingetDeferredRemovals.Count -eq 0) { return } + + $catalog = Import-JsonFile -filePath $script:AppsListFilePath + $primaryIds = @{} + foreach ($app in $catalog.Apps) { + $ids = @($app.AppId) + foreach ($id in $ids) { $primaryIds[$id] = $ids[0] } + } + + $deferredPrimaryIds = foreach ($appId in $script:WingetDeferredRemovals.Keys) { + if ($primaryIds.ContainsKey($appId)) { $primaryIds[$appId] } else { $appId } + } + foreach ($appId in @($deferredPrimaryIds | Sort-Object -Unique)) { + Get-Translation -Key $appId -Field 'FriendlyName' -Section 'Apps' + } +} diff --git a/Tests/Get-RebootFeatureLabels.Tests.ps1 b/Tests/Get-RebootFeatureLabels.Tests.ps1 index 6290515..fa96dbe 100644 --- a/Tests/Get-RebootFeatureLabels.Tests.ps1 +++ b/Tests/Get-RebootFeatureLabels.Tests.ps1 @@ -1,6 +1,7 @@ BeforeAll { $rebootFeatureLabelsScriptPath = Join-Path $PSScriptRoot '..\Scripts\Helpers\Get-RebootFeatureLabels.ps1' . $rebootFeatureLabelsScriptPath + . (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-JsonFile.ps1') . (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-LanguageFile.ps1') # Builds a $script:Lang fixture whose Features section mirrors $script:Features exactly, @@ -26,6 +27,60 @@ BeforeAll { } } +Describe 'Get-DeferredAppRemovalLabels' { + BeforeEach { + $script:AppsListFilePath = Join-Path $PSScriptRoot '..\Config\Apps.json' + $script:Lang = Import-LanguageFile -LanguageCode 'en-US' -LanguagesPath (Join-Path $PSScriptRoot '..\Config\Languages') + $script:WingetDeferredRemovals = @{} + } + + It 'returns one Edge label for ' -ForEach @( + @{ Ids = @('Microsoft.Edge', 'XPFFTQ037JWMHS') } + @{ Ids = @('XPFFTQ037JWMHS') } + ) { + foreach ($id in $Ids) { $script:WingetDeferredRemovals[$id] = 'Alice' } + + $labels = @(Get-DeferredAppRemovalLabels) + + $labels | Should -HaveCount 1 + $labels[0] | Should -BeExactly 'Microsoft Edge' + } + + It 'retains other apps and unknown IDs alongside a grouped app' { + $script:WingetDeferredRemovals = @{ 'Microsoft.Edge' = 'Alice'; 'XPFFTQ037JWMHS' = 'Alice'; 'Microsoft.OneDrive' = 'Alice'; 'Unknown.App' = 'Alice' } + + $labels = @(Get-DeferredAppRemovalLabels) + + $labels | Should -HaveCount 3 + $labels | Should -Contain 'Microsoft Edge' + $labels | Should -Contain 'Unknown.App' + $labels | Should -Contain (Get-Translation -Key 'Microsoft.OneDrive' -Field 'FriendlyName' -Section 'Apps') + } + + It 'keeps distinct catalog apps even when their translated names match' { + Mock Import-JsonFile { + [PSCustomObject]@{ Apps = @( + [PSCustomObject]@{ AppId = @('First.App', 'First.Alias') } + [PSCustomObject]@{ AppId = 'Second.App' } + ) } + } + $script:Lang.Apps = [PSCustomObject]@{ + 'First.App' = [PSCustomObject]@{ FriendlyName = 'Shared name' } + 'Second.App' = [PSCustomObject]@{ FriendlyName = 'Shared name' } + } + $script:WingetDeferredRemovals = @{ 'First.App' = 'Alice'; 'First.Alias' = 'Alice'; 'Second.App' = 'Alice' } + + $labels = @(Get-DeferredAppRemovalLabels) + + $labels | Should -HaveCount 2 + @($labels | Where-Object { $_ -eq 'Shared name' }).Count | Should -Be 2 + } + + It 'returns no labels without deferred removals' { + @(Get-DeferredAppRemovalLabels) | Should -HaveCount 0 + } +} + Describe 'Get-RebootFeatureLabels' { BeforeEach { $script:Params = @{ diff --git a/Tests/Remove-SelectedApps.Tests.ps1 b/Tests/Remove-SelectedApps.Tests.ps1 index 2cde2c4..2aad9ca 100644 --- a/Tests/Remove-SelectedApps.Tests.ps1 +++ b/Tests/Remove-SelectedApps.Tests.ps1 @@ -231,6 +231,7 @@ Describe 'Remove-WinGetApp' { Remove-WinGetApp -app 'One.App' Should -Invoke Invoke-NonBlocking -Times 1 -Exactly -ParameterFilter { $ArgumentList -eq 'One.App' } Should -Invoke Set-RunOnceWingetTask -Times $Scheduled -Exactly -ParameterFilter { $appId -eq 'One.App' } + $script:WingetDeferredRemovals.ContainsKey('One.App') | Should -Be ([bool]$Scheduled) } It 'limits a foreground winget uninstall to two minutes' { @@ -293,6 +294,7 @@ Describe 'Remove-WinGetApp' { Mock Set-RunOnceWingetTask { $false } Remove-WinGetApp -app 'One.App' | Should -BeFalse + $script:WingetDeferredRemovals.ContainsKey('One.App') | Should -BeFalse } } @@ -580,6 +582,11 @@ Describe 'Remove-AppxApp' { } Describe 'Set-RunOnceWingetTask' { + BeforeAll { + $captureScript = Join-Path $TestDrive 'Capture native arguments.ps1' + '$args | ConvertTo-Json -Compress' | Set-Content -LiteralPath $captureScript -Encoding UTF8 + } + BeforeEach { $script:Params = @{ User = 'Alice' } Mock Invoke-WithTargetUserHive { @@ -593,7 +600,7 @@ Describe 'Set-RunOnceWingetTask' { } } - It 'encodes shell metacharacters and writes a safe RunOnce operation' { + It 'writes a direct WinGet command with shell metacharacters kept as literals' { Set-RunOnceWingetTask -appId "Vendor.App&'Test" Should -Invoke Invoke-WithTargetUserHive -Times 1 -Exactly -ParameterFilter { $TargetUserName -eq 'Alice' } Should -Invoke Invoke-RegistryOperation -Times 1 -Exactly -ParameterFilter { @@ -601,10 +608,58 @@ Describe 'Set-RunOnceWingetTask' { $RegFilePath -eq '' } - $script:runOnceOperation.ValueData | Should -Match '^powershell\.exe -NoProfile -EncodedCommand [A-Za-z0-9+/=]+$' - $encodedCommand = $script:runOnceOperation.ValueData -replace '^powershell\.exe -NoProfile -EncodedCommand ', '' - $decodedCommand = [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encodedCommand)) - $decodedCommand | Should -Be "winget uninstall --accept-source-agreements --disable-interactivity --id 'Vendor.App&''Test'" + $script:runOnceOperation.ValueData | Should -BeExactly "winget.exe uninstall --accept-source-agreements --disable-interactivity --id `"Vendor.App&'Test`"" + } + + It 'quotes as one native argument' -ForEach @( + @{ AppId = 'Vendor.App" --all'; QuotedId = '"Vendor.App\" --all"' } + @{ AppId = 'Vendor.App\"Test'; QuotedId = '"Vendor.App\\\"Test"' } + @{ AppId = 'Vendor.App\'; QuotedId = '"Vendor.App\\"' } + @{ AppId = 'Vendor.App & | < > ^ %PATH%'; QuotedId = '"Vendor.App & | < > ^ %PATH%"' } + ) { + Set-RunOnceWingetTask -appId $AppId | Should -BeTrue + $script:runOnceOperation.ValueData | Should -BeExactly "winget.exe uninstall --accept-source-agreements --disable-interactivity --id $QuotedId" + + # Exercise native parsing with a harmless capture script instead of running WinGet. + $process = [System.Diagnostics.Process]::new() + $process.StartInfo.FileName = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' + $nativeArguments = $script:runOnceOperation.ValueData.Substring('winget.exe '.Length) + $process.StartInfo.Arguments = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$captureScript`" $nativeArguments" + $process.StartInfo.UseShellExecute = $false + $process.StartInfo.CreateNoWindow = $true + $process.StartInfo.RedirectStandardOutput = $true + $process.StartInfo.RedirectStandardError = $true + try { + $null = $process.Start() + if (-not $process.WaitForExit(15000)) { + $process.Kill() + throw 'Native argument capture timed out.' + } + $output = $process.StandardOutput.ReadToEnd() + $stderr = $process.StandardError.ReadToEnd() + $process.ExitCode | Should -Be 0 -Because $stderr + $stderr | Should -BeNullOrEmpty + $captured = $output | ConvertFrom-Json + $captured | Should -HaveCount 5 + $captured[3] | Should -BeExactly '--id' + $captured[4] | Should -BeExactly $AppId + } + finally { $process.Dispose() } + } + + It 'keeps a typical command within the RunOnce limit' { + Set-RunOnceWingetTask -appId 'Microsoft.Edge' | Should -BeTrue + $script:runOnceOperation.ValueData.Length | Should -Be 93 + } + + It 'accepts the RunOnce length limit and rejects longer commands without writing to a hive' { + Set-RunOnceWingetTask -appId ('A' * 181) | Should -BeTrue + $script:runOnceOperation.ValueData.Length | Should -Be 260 + + Mock Write-Error {} + Set-RunOnceWingetTask -appId ('A' * 182) | Should -BeFalse + Should -Invoke Invoke-WithTargetUserHive -Times 1 -Exactly + Should -Invoke Write-Error -Times 1 -Exactly -ParameterFilter { $Message -like '*exceeds 260 characters*' } } It 'schedules every resolved target but reports incomplete profile enumeration' { @@ -665,6 +720,23 @@ Describe 'AllUsers deferred WinGet profile enumeration' { Mock Test-AppInWingetList { $false } } + It 'defers both Edge IDs after successful Sysprep scheduling without immediate verification or a force-removal prompt' { + $script:Params = @{ Sysprep = $true; AppRemovalTarget = 'AllUsers' } + Mock Invoke-NonBlocking { [PSCustomObject]@{ ExitCode = 1; Output = @() } } + Mock Set-RunOnceWingetTask { $true } + Mock Request-EdgeForceRemove {} + Mock Test-AppInWingetList { $true } + + Remove-SelectedApps -appsList @('Microsoft.Edge', 'XPFFTQ037JWMHS') | Should -BeTrue + + $script:WingetDeferredRemovals.ContainsKey('Microsoft.Edge') | Should -BeTrue + $script:WingetDeferredRemovals.ContainsKey('XPFFTQ037JWMHS') | Should -BeTrue + $script:AppRemovalFailures | Should -Be 0 + Should -Invoke Set-RunOnceWingetTask -Times 2 -Exactly -ParameterFilter { $Target.AllUsers } + Should -Invoke Get-WingetInstalledApps -Times 0 -Exactly + Should -Invoke Request-EdgeForceRemove -Times 0 -Exactly + } + It 'keeps resolved profiles and Default while returning a SID translation failure' { $result = Get-RunOnceWingetTargetUserNames