-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFMRegJump.Tests.ps1
More file actions
484 lines (428 loc) · 20.2 KB
/
Copy pathFMRegJump.Tests.ps1
File metadata and controls
484 lines (428 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
using namespace System.IO
using namespace System.Management.Automation.Language
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - PESTER TESTS FOR FMRegJump.ps1
# ─────────────────────────────────────────────────────────────────────────────────────────────
#
# Covers Layer 1 (validation branches) and Layer 2 (key resolution) from the test plan.
# Does NOT launch RegEdit or Registry Finder. See Run-LaunchTests.ps1 for interactive
# Layer 3 coverage.
#
# Usage:
# Invoke-Pester -Path .\FMRegJump.Tests.ps1 -Output Detailed
#
# Requirements:
# - Pester 5.x: Install-Module Pester -Force -SkipPublisherCheck
# - PowerShell 7.4+
#
# EndRegion
BeforeAll {
$script:OriginalScript = Join-Path $PSScriptRoot 'FMRegJump.ps1'
if (-not (Test-Path -LiteralPath $script:OriginalScript)) {
throw "FMRegJump.ps1 not found at $script:OriginalScript"
}
# ── Build the testable copy via AST source-rewrite ───────────
# 1. Replace `Invoke-InternalMessageBox` function body with a stub that appends
# each call to a JSON log file named by the FMREGJUMP_TEST_LOG env var.
# 2. Prepend a `Start-Process` override that captures splatted params to the
# same log, then returns a fake Process with a non-zero MainWindowHandle
# so the 10-second wait-loop exits immediately.
$src = [File]::ReadAllText($script:OriginalScript)
$parseErrors = $null
$ast = [Parser]::ParseInput($src, [ref]$null, [ref]$parseErrors)
if ($parseErrors) {
throw "FMRegJump.ps1 has parse errors: $($parseErrors | Out-String)"
}
$msgBoxFunc = $ast.FindAll({
param($n) $n -is [FunctionDefinitionAst] -and
$n.Name -eq 'Invoke-InternalMessageBox'
}, $true) | Select-Object -First 1
if (-not $msgBoxFunc) {
throw "Could not locate Invoke-InternalMessageBox in the script."
}
$paramBlock = $ast.ParamBlock
if (-not $paramBlock) {
throw "Script has no top-level param block — cannot locate injection point."
}
$stubFunction = @'
function Invoke-InternalMessageBox {
[CmdletBinding()]
[OutputType([string])]
param (
[Parameter(Position = 0, Mandatory)]
[string] $Prompt,
[string] $Title = 'FMRegJump',
[string] $Icon = 'Information',
[string] $BoxType = 'OKOnly',
[int] $DefaultButton = 1,
[switch] $NonTopMost
)
$logFile = $env:FMREGJUMP_TEST_LOG
if ($logFile) {
$entry = [pscustomobject]@{
Kind = 'MessageBox'
Prompt = $Prompt
Title = $Title
Icon = $Icon
}
Add-Content -LiteralPath $logFile -Value ($entry | ConvertTo-Json -Compress)
}
return 'Ok'
}
'@
$startProcessOverride = @'
function Start-Process {
[CmdletBinding()]
param(
[Parameter(ValueFromRemainingArguments)]
$Args,
[string] $FilePath,
[string] $Verb,
[switch] $PassThru,
[object] $ArgumentList,
[object] $WindowStyle
)
$logFile = $env:FMREGJUMP_TEST_LOG
if ($logFile) {
$entry = [pscustomobject]@{
Kind = 'Launch'
FilePath = $FilePath
Verb = $Verb
ArgumentList = @($ArgumentList)
}
Add-Content -LiteralPath $logFile -Value ($entry | ConvertTo-Json -Compress)
}
return [pscustomobject]@{ MainWindowHandle = [IntPtr]::new(1) }
}
function Set-ItemProperty {
[CmdletBinding()]
param(
[Parameter(ValueFromRemainingArguments)] $Args,
[string] $LiteralPath,
[string] $Name,
[object] $Value,
[string] $Type,
[switch] $Force
)
$logFile = $env:FMREGJUMP_TEST_LOG
if ($logFile -and $LiteralPath -like '*\Regedit*' -and $Name -eq 'LastKey') {
$entry = [pscustomobject]@{
Kind = 'LastKey'
Value = $Value
}
Add-Content -LiteralPath $logFile -Value ($entry | ConvertTo-Json -Compress)
}
}
# Intercept Get-Command so that `& $cmdRf $rfArgs` (the Registry Finder launch
# pattern) goes through a capturing scriptblock instead of spawning the real
# binary. Returns a closure that logs the exe path and arg list when invoked.
function Get-Command {
[CmdletBinding()]
param(
[Parameter(Position = 0)]
[string] $Name,
$CommandType,
[Parameter(ValueFromRemainingArguments)] $RemainingArgs
)
$capturedPath = $Name
return {
$logFile = $env:FMREGJUMP_TEST_LOG
# `& $cmdRf $rfArgs` can arrive as either one array arg or splatted args,
# depending on whether the target is a scriptblock (single) or a real
# CommandInfo (splatted). Normalize both to a flat list.
$captured = if ($args.Count -eq 1 -and $args[0] -is [array]) {
@($args[0])
} else {
@($args)
}
if ($logFile) {
$entry = [pscustomobject]@{
Kind = 'Launch'
FilePath = $capturedPath
ArgumentList = $captured
}
Add-Content -LiteralPath $logFile -Value ($entry | ConvertTo-Json -Compress)
}
}.GetNewClosure()
}
'@
# Two-step splice. Do the LATER-in-file edit first so earlier offsets stay valid.
# Step 1: replace Invoke-InternalMessageBox function body with the logging stub.
$step1 = $src.Substring(0, $msgBoxFunc.Extent.StartOffset) +
$stubFunction +
$src.Substring($msgBoxFunc.Extent.EndOffset)
# Step 2: inject Start-Process/Set-ItemProperty overrides AFTER the param block,
# so `using namespace` directives remain first in the file (PowerShell requires
# them before any other statement).
$injectAt = $paramBlock.Extent.EndOffset
$step2 = $step1.Substring(0, $injectAt) +
"`n`n" + $startProcessOverride + "`n" +
$step1.Substring($injectAt)
# Step 3: strip `[Process]` type casts from Start-Process assignments. Our stub
# returns a PSCustomObject, and PowerShell can't coerce it into a real Process
# (MainWindowHandle is readonly). Dropping the cast lets the var hold the stub.
$step3 = $step2 -replace '\[Process\]\s+(\$\w+\s*=\s*Start-Process\s*@\w+)', '$1'
# Step 4: remove the entire SELF-ELEVATION region. In production, the script
# relaunches itself elevated via Start-Process -Verb RunAs if it isn't admin;
# during Pester runs we'd either trigger UAC prompts per-test (fatal for CI) or
# spawn orphaned elevated pwsh processes. Stripping the region means the script
# always proceeds straight to validation as if already elevated. Lazy `.*?` is
# critical — it matches only up to the FIRST `# EndRegion`, not the last.
$rewritten = $step3 -replace '(?ms)# Region - SELF-ELEVATION.*?# EndRegion', ''
$script:TestableScript = Join-Path $TestDrive 'FMRegJump.ps1'
[File]::WriteAllText($script:TestableScript, $rewritten)
# ── Copy config + create a dummy Registry Finder .exe ────────
# Script now accepts both .exe (preferred) and .com. Fixture uses .exe to mirror
# the recommended default config; a separate negative test covers rejection of
# other extensions.
$toml = @"
[FMRegJumpConfig]
RegistryFinderPath = '$(($TestDrive -replace '\\','/'))/FakeRegistryFinder.exe'
"@
Set-Content -LiteralPath (Join-Path $TestDrive 'FMRegJumpConfig.toml') -Value $toml
Set-Content -LiteralPath (Join-Path $TestDrive 'FakeRegistryFinder.exe') -Value ''
# ── Helper: run testable script, return parsed log entries ───
function script:Invoke-Testable {
param([hashtable] $Params = @{})
$logPath = Join-Path $TestDrive "log-$(New-Guid).jsonl"
$env:FMREGJUMP_TEST_LOG = $logPath
try {
& $script:TestableScript @Params *> $null
} finally {
$env:FMREGJUMP_TEST_LOG = $null
}
if (-not (Test-Path -LiteralPath $logPath)) {
return @()
}
$lines = Get-Content -LiteralPath $logPath
return $lines | ForEach-Object { $_ | ConvertFrom-Json }
}
}
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - VALIDATION TESTS (Layer 1)
# ─────────────────────────────────────────────────────────────────────────────────────────────
Describe 'Validation' {
It 'errors when neither InputFile nor PresetDestination is provided' {
$log = Invoke-Testable
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match 'No input provided'
($log | Where-Object Kind -EQ 'Launch') | Should -BeNullOrEmpty
}
It 'errors when both InputFile and PresetDestination are provided' {
$log = Invoke-Testable @{
InputFile = 'C:\Windows\notepad.exe'
PresetDestination = 'Folder'
AppToUse = 'RegEdit'
}
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match 'mutually'
($log | Where-Object Kind -EQ 'Launch') | Should -BeNullOrEmpty
}
It 'errors when InputFile does not exist' {
$log = Invoke-Testable @{
InputFile = 'C:\definitely-not-a-real-path-xyz\nothing.txt'
AppToUse = 'RegEdit'
}
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match 'does not exist'
($log | Where-Object Kind -EQ 'Launch') | Should -BeNullOrEmpty
}
It 'errors when TOML config is missing for RegistryFinder' {
$tomlPath = Join-Path $TestDrive 'FMRegJumpConfig.toml'
Rename-Item -LiteralPath $tomlPath -NewName 'FMRegJumpConfig.toml.bak'
try {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegistryFinder'
}
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match 'Configuration file not found'
} finally {
Rename-Item -LiteralPath "$tomlPath.bak" -NewName 'FMRegJumpConfig.toml'
}
}
It 'errors when TOML lacks RegistryFinderPath' {
$tomlPath = Join-Path $TestDrive 'FMRegJumpConfig.toml'
$backup = Get-Content -LiteralPath $tomlPath -Raw
Set-Content -LiteralPath $tomlPath -Value "[FMRegJumpConfig]`n"
try {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegistryFinder'
}
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match "Missing 'RegistryFinderPath'"
} finally {
Set-Content -LiteralPath $tomlPath -Value $backup -NoNewline
}
}
It 'errors when RegistryFinderPath extension is not .exe or .com' {
$tomlPath = Join-Path $TestDrive 'FMRegJumpConfig.toml'
$backup = Get-Content -LiteralPath $tomlPath -Raw
# .bat is not a permitted target — should be rejected by the extension check
$fakeBat = (Join-Path $TestDrive 'FakeRegistryFinder.bat') -replace '\\','/'
Set-Content -LiteralPath $tomlPath -Value @"
[FMRegJumpConfig]
RegistryFinderPath = '$fakeBat'
"@
Set-Content -LiteralPath (Join-Path $TestDrive 'FakeRegistryFinder.bat') -Value ''
try {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegistryFinder'
}
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match 'must point to a \.exe or \.com file'
} finally {
Set-Content -LiteralPath $tomlPath -Value $backup -NoNewline
}
}
It 'errors when the Registry Finder executable is missing' {
$exePath = Join-Path $TestDrive 'FakeRegistryFinder.exe'
Remove-Item -LiteralPath $exePath -Force
try {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegistryFinder'
}
$msg = $log | Where-Object Kind -EQ 'MessageBox' | Select-Object -First 1
$msg.Icon | Should -Be 'Critical'
$msg.Prompt | Should -Match 'Registry Finder not found'
} finally {
Set-Content -LiteralPath $exePath -Value ''
}
}
}
# EndRegion
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - KEY RESOLUTION TESTS (Layer 2)
# ─────────────────────────────────────────────────────────────────────────────────────────────
Describe 'Key Resolution via PresetDestination' {
BeforeDiscovery {
$script:PresetCases = @(
@{ Preset = 'DirectoryBackground' ; Expect = 'HKCR\Directory\Background\shell' }
@{ Preset = 'Directory' ; Expect = 'HKCR\Directory\shell' }
@{ Preset = 'Folder' ; Expect = 'HKCR\Folder' }
@{ Preset = 'DesktopBackground' ; Expect = 'HKCR\DesktopBackground\shell' }
@{ Preset = 'AllFileSystemObjects' ; Expect = 'HKCR\AllFileSystemObjects\shell' }
@{ Preset = 'AllFiles' ; Expect = 'HKCR\*\shell' }
@{ Preset = 'Drive' ; Expect = 'HKCR\Drive\shell' }
@{ Preset = 'MyComputer' ; Expect = 'HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\shell' }
@{ Preset = 'EnvVariablesSystem' ; Expect = 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' }
)
}
It 'resolves -PresetDestination <Preset> to <Expect>' -TestCases $script:PresetCases {
param($Preset, $Expect)
$log = Invoke-Testable @{
PresetDestination = $Preset
AppToUse = 'RegistryFinder'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch | Should -Not -BeNullOrEmpty
# Registry Finder must NOT be launched via ShellExecuteEx's runas verb:
# comfile\shell has no 'runas' entry on Windows 10/11, so that path fails
# with ERROR_NO_ASSOCIATION. Direct CreateProcess (no Verb) is required.
$launch.Verb | Should -BeNullOrEmpty
$launch.ArgumentList -contains $Expect | Should -BeTrue -Because "arg list was: $($launch.ArgumentList -join ' | ')"
}
It 'resolves EnvVariablesCurrentUser to the current user''s SID-scoped path' {
$expectedSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$expectedKey = "HKU\$expectedSid\Environment"
$log = Invoke-Testable @{
PresetDestination = 'EnvVariablesCurrentUser'
AppToUse = 'RegistryFinder'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains $expectedKey | Should -BeTrue
}
}
Describe 'Key Resolution via InputFile' {
BeforeAll {
$script:SampleFile = Join-Path $TestDrive 'sample.txt'
Set-Content -LiteralPath $script:SampleFile -Value 'hello'
$script:SampleFolder = Join-Path $TestDrive 'sample-folder'
New-Item -ItemType Directory -Path $script:SampleFolder | Out-Null
}
It 'defaults to SystemFileAssociations\<ext>\Shell' {
$log = Invoke-Testable @{
InputFile = $script:SampleFile
AppToUse = 'RegistryFinder'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains 'HKCR\SystemFileAssociations\.txt\Shell' |
Should -BeTrue
}
It 'resolves to HKCR\<ext>\Shell when -InputFileRoot HKEY_CLASSES_ROOT is used' {
$log = Invoke-Testable @{
InputFile = $script:SampleFile
InputFileRoot = 'HKEY_CLASSES_ROOT'
AppToUse = 'RegistryFinder'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains 'HKCR\.txt\Shell' | Should -BeTrue
}
It 'resolves a folder InputFile to HKCR\Directory\shell' {
$log = Invoke-Testable @{
InputFile = $script:SampleFolder
AppToUse = 'RegistryFinder'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains 'HKCR\Directory\shell' | Should -BeTrue
}
}
# EndRegion
# ─────────────────────────────────────────────────────────────────────────────────────────────
# Region - LAUNCH ARGUMENT TESTS
# ─────────────────────────────────────────────────────────────────────────────────────────────
Describe 'Launch arguments' {
It 'passes --multiInst to Registry Finder by default' {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegistryFinder'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains '--multiInst' | Should -BeTrue
}
It 'omits --multiInst when -SingleInstance is set (RegistryFinder)' {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegistryFinder'
SingleInstance = $true
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains '--multiInst' | Should -BeFalse
}
It 'writes LastKey to the Regedit HKCU key when using -AppToUse RegEdit' {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegEdit'
}
$lastKey = $log | Where-Object Kind -EQ 'LastKey' | Select-Object -First 1
$lastKey.Value | Should -Be 'HKEY_CLASSES_ROOT\Folder'
}
It 'passes -m to regedit by default (multi-instance)' {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegEdit'
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.FilePath | Should -Be 'regedit'
$launch.ArgumentList -contains '-m' | Should -BeTrue
}
It 'omits -m from regedit when -SingleInstance is set' {
$log = Invoke-Testable @{
PresetDestination = 'Folder'
AppToUse = 'RegEdit'
SingleInstance = $true
}
$launch = $log | Where-Object Kind -EQ 'Launch' | Select-Object -First 1
$launch.ArgumentList -contains '-m' | Should -BeFalse
}
}
# EndRegion