Improve backup validation (#849)

This commit is contained in:
Jeffrey
2026-10-21 22:47:01 +02:00
committed by GitHub
parent 97f3f805ef
commit 039ef80a8b
18 changed files with 1504 additions and 46 deletions
+7
View File
@@ -340,14 +340,21 @@
"BackupMissingSelectedFeatures": "Backup must contain at least one feature ID in SelectedFeatures or SelectedUndoFeatures.",
"BackupAllowlistValidationFailed": "Failed to validate backup: {0}",
"BackupSnapshotMissingPath": "Backup validation failed: Registry key snapshot is missing Path.",
"BackupSnapshotInvalidExists": "Backup validation failed: Registry key snapshot '{0}' must define Exists as a Boolean.",
"BackupFeatureCatalogNotLoaded": "Unable to validate registry backup allowlist because feature definitions are not loaded.",
"BackupNoAllowedRegistryPaths": "Backup contains registry snapshots but no allowed registry paths were derived from the selected features.",
"BackupFeatureNotInCatalog": "Selected feature '{0}' was not found in the current feature catalog.",
"BackupUnsupportedRegistryPath": "Backup contains unsupported registry path '{0}'.",
"BackupUnexpectedRegistryPath": "Backup contains unexpected registry path '{0}' that is not allowed by SelectedFeatures.",
"BackupUnexpectedValue": "Backup contains unexpected value '{0}' under '{1}'.",
"BackupUnexpectedKeyDeletion": "Backup contains an unauthorized registry key deletion: '{0}'.",
"BackupUnsupportedValueKind": "Backup contains unsupported registry value kind '{0}' for '{1}'.",
"BackupInvalidValueData": "Backup contains invalid registry data for kind '{0}' at '{1}'.",
"BackupUnsafeExecutableValue": "Backup contains an untrusted command or DLL-loading value at '{0}'. Only empty values or exact matches to trusted feature data can be restored.",
"BackupExecutableConfirmationRequired": "Restoring unrecognized executable registry settings requires explicit confirmation.",
"BackupExecutableWarningTitle": "Restore unrecognized executable settings?",
"BackupExecutableWarningMessage": "This backup contains executable registry settings that do not match the script's files. These could cause Windows or applications to potentially load malicious code.\n\nDo not restore registry backups obtained from unofficial sources. Continue only if you created this backup yourself and have reviewed the settings below.\n\n{0}",
"BackupExecutableMismatchDetails": "Path: {0}\nValue name: {1}\nKind: {2}\nData: {3}",
"BackupValueMustNotDefineKind": "Backup value '{0}' must not define Kind when Exists is false.",
"StartMenuNoBackupFoundForUser": "No start menu backup file found for user {0}.",
@@ -48,6 +48,7 @@ function Get-RegistryBackupCapturePlans {
Path = $entry.Path
IncludeSubKeys = [bool]$entry.IncludeSubKeys
CaptureAllValues = [bool]$entry.CaptureAllValues
AllowDeleteKey = [bool]$entry.AllowDeleteKey
ValueNames = @($entry.ValueNames)
}
}
@@ -66,6 +67,7 @@ function Add-RegistryPlanOperation {
Path = $Operation.KeyPath
IncludeSubKeys = $false
CaptureAllValues = $false
AllowDeleteKey = $false
ValueNames = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
}
}
@@ -75,6 +77,7 @@ function Add-RegistryPlanOperation {
'DeleteKey' {
$plan.IncludeSubKeys = $true
$plan.CaptureAllValues = $true
$plan.AllowDeleteKey = $true
}
'SetValue' {
if (-not $plan.CaptureAllValues) {
@@ -127,7 +130,7 @@ function Get-RegistrySnapshotsForBackup {
$snapshots = @()
foreach ($plan in $plans) {
$snapshots += Get-RegistryKeySnapshot -KeyPath $plan.Path -CaptureAllValues:$plan.CaptureAllValues -ValueNames @($plan.ValueNames) -IncludeSubKeys:$plan.IncludeSubKeys
$snapshots += Get-RegistryKeySnapshot -KeyPath $plan.Path -CaptureAllValues:$plan.CaptureAllValues -ValueNames @($plan.ValueNames) -IncludeSubKeys:$plan.IncludeSubKeys -AllowDeleteKey:([bool]$plan.AllowDeleteKey)
}
return @($snapshots)
@@ -163,7 +166,8 @@ function Get-RegistryKeySnapshot {
[string]$KeyPath,
[bool]$CaptureAllValues = $false,
[string[]]$ValueNames = @(),
[bool]$IncludeSubKeys = $false
[bool]$IncludeSubKeys = $false,
[bool]$AllowDeleteKey = $false
)
$registryParts = Split-RegistryPath -path $KeyPath
@@ -179,10 +183,19 @@ function Get-RegistryKeySnapshot {
$subKeyPath = $registryParts.SubKey
$key = $rootKey.OpenSubKey($subKeyPath, $false)
if ($null -eq $key) {
# Value-only plans restore missing values, never the absence of the whole key.
# Preserve absence separately so trusted validation can authorize empty-key cleanup.
return @{
Path = $KeyPath
Exists = $false
Values = @()
Exists = -not $AllowDeleteKey
OriginallyAbsent = $true
Values = @(
if (-not $AllowDeleteKey) {
foreach ($valueName in @($ValueNames | Sort-Object -Unique)) {
@{ Name = $valueName; Exists = $false; Kind = $null; Data = $null }
}
}
)
SubKeys = @()
}
}
+267 -23
View File
@@ -101,9 +101,9 @@ function Get-NormalizedSelectedUndoFeatureIdsFromBackup {
Normalizes a raw registry key snapshot into a consistent shape, recursing into sub-keys.
.DESCRIPTION
Fills in defaults for optional properties (Exists, Values, SubKeys) so downstream
Fills in defaults for optional properties (Values, SubKeys) so downstream
validation can read a predictable shape regardless of what the backup file omitted.
Throws if Path is missing, since every snapshot must be anchored to a real key.
Requires Path and a Boolean Exists to avoid interpreting missing data as deletion.
#>
function Normalize-RegistryKeySnapshot {
param(
@@ -115,9 +115,8 @@ function Normalize-RegistryKeySnapshot {
throw (Get-Translation -Key 'BackupSnapshotMissingPath')
}
$exists = $false
if ($Snapshot.PSObject.Properties['Exists']) {
$exists = [bool]$Snapshot.Exists
if (-not $Snapshot.PSObject.Properties['Exists'] -or $Snapshot.Exists -isnot [bool]) {
throw (Get-Translation -Key 'BackupSnapshotInvalidExists' -FormatArgs @($Snapshot.Path))
}
$values = @()
@@ -146,7 +145,8 @@ function Normalize-RegistryKeySnapshot {
return [PSCustomObject]@{
Path = [string]$Snapshot.Path
Exists = $exists
Exists = $Snapshot.Exists
OriginallyAbsent = ($Snapshot.OriginallyAbsent -is [bool] -and $Snapshot.OriginallyAbsent)
Values = @($values)
SubKeys = @($subKeys)
}
@@ -161,6 +161,7 @@ function Normalize-RegistryKeySnapshot {
Builds an allow-list from the capture plans of the selected features, then checks
every snapshot against it. Returns an array of translated error strings; an empty
array means the backup is valid.
#>
function Test-RegistryBackupMatchesSelectedFeatures {
param(
@@ -179,33 +180,220 @@ function Test-RegistryBackupMatchesSelectedFeatures {
$errors = New-Object System.Collections.Generic.List[string]
if (-not $script:Features -or $script:Features.Count -eq 0) {
$errors.Add((Get-Translation -Key 'BackupFeatureCatalogNotLoaded'))
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds $SelectedFeatureIds -SelectedUndoFeatureIds $SelectedUndoFeatureIds -Target $Target -Errors $errors
if ($errors.Count -gt 0) {
return $errors.ToArray()
}
$selectedRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedFeatureIds) -IsUndoFeature:$false -Errors $errors)
$undoRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedUndoFeatureIds) -IsUndoFeature:$true -Errors $errors)
$useSysprepRegFiles = ($Target -eq 'DefaultUserProfile') -or ($Target -like 'User:*')
$capturePlans = @()
if ($errors.Count -eq 0 -and ($selectedRegistryFeatures.Count -gt 0 -or $undoRegistryFeatures.Count -gt 0)) {
$capturePlans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures @($selectedRegistryFeatures) -UndoRegistryFeatures @($undoRegistryFeatures) -UseSysprepRegFiles:$useSysprepRegFiles)
return Test-RegistryBackupAgainstAllowList -RegistryKeys $RegistryKeys -PlanMap $planMap
}
$planMap = New-RegistryBackupAllowListPlanMap -CapturePlans @($capturePlans)
<#
.SYNOPSIS
Validates registry snapshots against an already derived trusted allow-list.
if ($planMap.Count -eq 0 -and @($RegistryKeys).Count -gt 0) {
.DESCRIPTION
Internal helper shared by feature-based validation and the import workflow.
The plan map must come from Get-RegistryBackupValidationPlanMap, never backup data.
When ExecutableValueWarnings is supplied, executable content mismatches are collected
for confirmation instead of blocking import. All other validation errors remain blocking.
#>
function Test-RegistryBackupAgainstAllowList {
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[object[]]$RegistryKeys,
[Parameter(Mandatory)]
[hashtable]$PlanMap,
[AllowEmptyCollection()]
[System.Collections.Generic.List[object]]$ExecutableValueWarnings
)
$errors = New-Object System.Collections.Generic.List[string]
if ($PlanMap.Count -eq 0 -and @($RegistryKeys).Count -gt 0) {
$errors.Add((Get-Translation -Key 'BackupNoAllowedRegistryPaths'))
}
foreach ($rootSnapshot in @($RegistryKeys)) {
Test-RegistrySnapshotAgainstAllowList -Snapshot $rootSnapshot -PlanMap $planMap -Errors $errors
Test-RegistrySnapshotAgainstAllowList -Snapshot $rootSnapshot -PlanMap $PlanMap -Errors $errors -ExecutableValueWarnings $ExecutableValueWarnings
}
return $errors.ToArray()
}
<#
.SYNOPSIS
Derives trusted registry permissions once for backup conversion and validation.
#>
function Get-RegistryBackupValidationPlanMap {
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]]$SelectedFeatureIds,
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[string[]]$SelectedUndoFeatureIds,
[Parameter(Mandatory)]
[string]$Target,
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[System.Collections.Generic.List[string]]$Errors
)
if (-not $script:Features -or $script:Features.Count -eq 0) {
$Errors.Add((Get-Translation -Key 'BackupFeatureCatalogNotLoaded'))
return @{}
}
$selectedRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedFeatureIds) -IsUndoFeature:$false -Errors $Errors)
$undoRegistryFeatures = @(Get-SelectedRegistryFeaturesForBackupValidation -SelectedFeatureIds @($SelectedUndoFeatureIds) -IsUndoFeature:$true -Errors $Errors)
$useSysprepRegFiles = ($Target -eq 'DefaultUserProfile') -or ($Target -like 'User:*')
$capturePlans = @()
if ($Errors.Count -eq 0 -and ($selectedRegistryFeatures.Count -gt 0 -or $undoRegistryFeatures.Count -gt 0)) {
$capturePlans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures @($selectedRegistryFeatures) -UndoRegistryFeatures @($undoRegistryFeatures) -UseSysprepRegFiles:$useSysprepRegFiles)
}
$planMap = New-RegistryBackupAllowListPlanMap -CapturePlans @($capturePlans)
if ($planMap.Count -gt 0) {
# Catalog data supplies trusted content only; selected plans still authorize locations and operations.
$trustedValueMap = Get-RegistryBackupTrustedValueMap -Features @($script:Features.Values) -UseSysprepRegFiles:$useSysprepRegFiles
foreach ($plan in $planMap.Values) {
$plan | Add-Member -MemberType NoteProperty -Name TrustedValueMap -Value $trustedValueMap
}
}
return $planMap
}
<#
.SYNOPSIS
Reads trusted executable value data from both directions of catalog features.
.DESCRIPTION
This supplies data comparisons only; the selected operation's capture plan still
controls which paths and value names may be restored. Backup fields never supply trust.
#>
function Get-RegistryBackupTrustedValueMap {
param(
[object[]]$Features = @(),
[switch]$UseSysprepRegFiles
)
$trustedValueMap = @{}
$filePaths = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($feature in $Features) {
if (-not [string]::IsNullOrWhiteSpace([string]$feature.RegistryKey)) {
$null = $filePaths.Add((Get-RegistryFilePathForFeature -RegistryKey $feature.RegistryKey -UseSysprepRegFiles:$UseSysprepRegFiles))
}
$undoPath = Resolve-RegistryBackupUndoFilePath -Feature $feature
if (-not [string]::IsNullOrWhiteSpace($undoPath)) { $null = $filePaths.Add($undoPath) }
}
foreach ($filePath in $filePaths) {
# A missing counterpart cannot authorize data; the active direction is checked by capture planning.
if (-not (Test-Path -LiteralPath $filePath)) { continue }
foreach ($operation in @(Get-RegFileOperations -regFilePath $filePath)) {
if ($operation.OperationType -ne 'SetValue' -or
-not (Test-RegistryValueMayExecuteCode -Path $operation.KeyPath -ValueName $operation.ValueName -KindName $operation.ValueType)) { continue }
$pathKey = Get-NormalizedRegistryPathKey -Path $operation.KeyPath
if (-not $trustedValueMap.ContainsKey($pathKey)) { $trustedValueMap[$pathKey] = @{} }
$name = [string]$operation.ValueName
$trustedValueMap[$pathKey][$name] = @($trustedValueMap[$pathKey][$name]) + @($operation)
}
}
return $trustedValueMap
}
<#
.SYNOPSIS
Identifies command lines, COM server registrations, and executable indirections.
#>
function Test-RegistryValueMayExecuteCode {
param([string]$Path, [AllowEmptyString()][string]$ValueName, [string]$KindName = 'String')
$parts = Split-RegistryPath -path $Path
if (-not $parts) { return $false }
return $parts.SubKey -match '(?i)(?:^|\\)(?:Run|RunOnce|RunOnceEx|InprocServer(?:32)?|InprocHandler(?:32)?|LocalServer(?:32)?|TreatAs|AutoTreatAs|AutoConvertTo|ScriptletURL)(?:\\|$)' -or
$parts.SubKey -match '(?i)\\shell\\[^\\]+\\(?:command|ddeexec)(?:\\|$)' -or
($ValueName -eq '' -and $parts.SubKey -match '(?i)\\shellex\\ContextMenuHandlers\\[^\\]+$') -or
# COM activation can use string indirections outside InprocServer32. Numeric settings are not server paths.
($KindName -notin @('DWord', 'QWord') -and $parts.SubKey -match '(?i)(?:^|\\)CLSID\\[^\\]+(?:\\|$)') -or
$ValueName -match '^(?i:DelegateExecute|ExplorerCommandHandler|ScriptletURL|DllSurrogate|DllSurrogateExecutable)$'
}
function Test-RegistryExecutableValueDataAllowed {
param($Snapshot, [string]$Path, [hashtable]$TrustedValueMap)
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], [string]$Snapshot.Kind, $true)
if (-not (Test-RegistryValueMayExecuteCode -Path $Path -ValueName $Snapshot.Name -KindName $kind.ToString())) { return $true }
$stringKinds = @([Microsoft.Win32.RegistryValueKind]::String, [Microsoft.Win32.RegistryValueKind]::ExpandString)
if ($kind -notin ($stringKinds + @([Microsoft.Win32.RegistryValueKind]::DWord, [Microsoft.Win32.RegistryValueKind]::QWord))) { return $false }
# Empty executable registrations cannot supply a command or DLL path.
if ($kind -in $stringKinds -and ($null -eq $Snapshot.Data -or [string]$Snapshot.Data -ceq '')) { return $true }
$pathKey = Get-NormalizedRegistryPathKey -Path $Path
if ($null -eq $TrustedValueMap -or -not $TrustedValueMap.ContainsKey($pathKey)) { return $false }
foreach ($operation in @($TrustedValueMap[$pathKey][[string]$Snapshot.Name])) {
if ($null -eq $operation) { continue }
$trustedKind = if ($operation.ValueType -eq 'Hex2') { 'ExpandString' } else { $operation.ValueType }
if ($kind.ToString() -eq $trustedKind -and [string]$Snapshot.Data -ceq [string]$operation.ValueData) { return $true }
}
return $false
}
<#
.SYNOPSIS
Converts legacy absent value-only keys into scoped missing-value snapshots.
.DESCRIPTION
Uses only trusted feature plans. Empty absent-key snapshots at exact value-only
paths are converted in memory; authorized tree deletions and invalid snapshots
remain unchanged for subsequent validation. The input snapshots are not modified.
#>
function ConvertTo-CompatibleRegistryKeySnapshots {
param(
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[object[]]$RegistryKeys,
[Parameter(Mandatory)]
[hashtable]$PlanMap
)
foreach ($snapshot in $RegistryKeys) {
$normalizedPath = Get-NormalizedRegistryPathKey -Path $snapshot.Path
$plan = if ($normalizedPath) { $PlanMap[$normalizedPath] } else { $null }
$convertAbsentKey = $snapshot.Exists -is [bool] -and -not $snapshot.Exists -and
@($snapshot.Values).Count -eq 0 -and @($snapshot.SubKeys).Count -eq 0 -and
$null -ne $plan -and -not $plan.CaptureAllValues -and -not $plan.IncludeSubKeys -and
$plan.ValueNames.Count -gt 0 -and
-not (Test-RegistryKeyDeletionAllowed -NormalizedPath $normalizedPath -PlanMap $PlanMap)
$originallyAbsent = $convertAbsentKey -or ($snapshot.OriginallyAbsent -is [bool] -and $snapshot.OriginallyAbsent)
# Absence is backup data; permission to clean up comes from an exact, nonrecursive plan.
# RemoveEmptyKey is derived here and is deliberately not read by normalization.
$removeEmptyKey = $originallyAbsent -and ($snapshot.Exists -or $convertAbsentKey) -and
$null -ne $plan -and -not $plan.CaptureAllValues -and -not $plan.IncludeSubKeys -and
@($snapshot.SubKeys).Count -eq 0 -and
@($snapshot.Values | Where-Object { [bool]$_.Exists }).Count -eq 0
[PSCustomObject]@{
Path = $snapshot.Path
Exists = if ($convertAbsentKey) { $true } else { $snapshot.Exists }
OriginallyAbsent = $originallyAbsent
RemoveEmptyKey = $removeEmptyKey
Values = @(
if ($convertAbsentKey) {
foreach ($valueName in @($plan.ValueNames | Sort-Object)) {
[PSCustomObject]@{ Name = $valueName; Exists = $false; Kind = $null; Data = $null }
}
} else { $snapshot.Values }
)
SubKeys = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($snapshot.SubKeys) -PlanMap $PlanMap)
}
}
}
<#
.SYNOPSIS
Resolves selected feature IDs to their catalog entries, keeping only the ones with a
@@ -287,6 +475,7 @@ function New-RegistryBackupAllowListPlanMap {
NormalizedPath = $normalizedPath
IncludeSubKeys = [bool]$plan.IncludeSubKeys
CaptureAllValues = [bool]$plan.CaptureAllValues
AllowDeleteKey = [bool]$plan.AllowDeleteKey
ValueNames = ConvertTo-RegistryValueNameSet -ValueNames @($plan.ValueNames)
}
}
@@ -333,12 +522,14 @@ function Test-RegistrySnapshotAgainstAllowList {
[hashtable]$PlanMap,
[Parameter(Mandatory)]
[AllowEmptyCollection()]
[System.Collections.Generic.List[string]]$Errors
[System.Collections.Generic.List[string]]$Errors,
[AllowEmptyCollection()]
[System.Collections.Generic.List[object]]$ExecutableValueWarnings
)
$snapshotPath = [string]$Snapshot.Path
$normalizedPath = Get-NormalizedRegistryPathKey -Path $snapshotPath
if ([string]::IsNullOrWhiteSpace($normalizedPath)) {
if ([string]::IsNullOrWhiteSpace($normalizedPath) -or $snapshotPath.IndexOf([char]0) -ge 0) {
$Errors.Add((Get-Translation -Key 'BackupUnsupportedRegistryPath' -FormatArgs @($snapshotPath)))
return
}
@@ -349,11 +540,20 @@ function Test-RegistrySnapshotAgainstAllowList {
return
}
if (-not $Snapshot.PSObject.Properties['Exists'] -or $Snapshot.Exists -isnot [bool]) {
$Errors.Add((Get-Translation -Key 'BackupSnapshotInvalidExists' -FormatArgs @($snapshotPath)))
return
}
if (-not $Snapshot.Exists -and -not (Test-RegistryKeyDeletionAllowed -NormalizedPath $normalizedPath -PlanMap $PlanMap)) {
$Errors.Add((Get-Translation -Key 'BackupUnexpectedKeyDeletion' -FormatArgs @($snapshotPath)))
}
foreach ($valueSnapshot in @($Snapshot.Values)) {
$valueName = Get-NormalizedRegistryValueName -ValueName $valueSnapshot.Name
$valueExists = [bool]$valueSnapshot.Exists
if (-not (Test-RegistryValueAllowedByPlan -PlanMatch $planMatch -ValueName $valueName)) {
if ($valueName.IndexOf([char]0) -ge 0 -or -not (Test-RegistryValueAllowedByPlan -PlanMatch $planMatch -ValueName $valueName)) {
$Errors.Add((Get-Translation -Key 'BackupUnexpectedValue' -FormatArgs @($valueName, $snapshotPath)))
}
@@ -366,6 +566,19 @@ function Test-RegistrySnapshotAgainstAllowList {
elseif (-not (Test-RegistryValueDataMatchesKind -KindName $kindName -Data $valueSnapshot.Data)) {
$Errors.Add((Get-Translation -Key 'BackupInvalidValueData' -FormatArgs @($kindName, $valueReference)))
}
elseif (-not (Test-RegistryExecutableValueDataAllowed -Snapshot $valueSnapshot -Path $snapshotPath -TrustedValueMap $planMatch.TrustedValueMap)) {
if ($null -eq $ExecutableValueWarnings) {
$Errors.Add((Get-Translation -Key 'BackupUnsafeExecutableValue' -FormatArgs @($valueReference)))
}
else {
$ExecutableValueWarnings.Add([PSCustomObject]@{
Path = $snapshotPath
Name = $valueName
Kind = $kindName
Data = $valueSnapshot.Data
})
}
}
}
elseif (-not [string]::IsNullOrWhiteSpace($kindName)) {
$Errors.Add((Get-Translation -Key 'BackupValueMustNotDefineKind' -FormatArgs @($valueReference)))
@@ -373,7 +586,7 @@ function Test-RegistrySnapshotAgainstAllowList {
}
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
Test-RegistrySnapshotAgainstAllowList -Snapshot $subKeySnapshot -PlanMap $PlanMap -Errors $Errors
Test-RegistrySnapshotAgainstAllowList -Snapshot $subKeySnapshot -PlanMap $PlanMap -Errors $Errors -ExecutableValueWarnings $ExecutableValueWarnings
}
}
@@ -487,6 +700,34 @@ function Get-NormalizedRegistryValueName {
return [string]$ValueName
}
<#
.SYNOPSIS
Checks whether selected feature operations authorize deletion of a key tree.
.DESCRIPTION
Only DeleteKey operations grant this permission. Checks all plans so an exact
value-only plan cannot hide a recursive deletion allowed by an ancestor.
#>
function Test-RegistryKeyDeletionAllowed {
param(
[Parameter(Mandatory)]
[string]$NormalizedPath,
[Parameter(Mandatory)]
[hashtable]$PlanMap
)
foreach ($plan in $PlanMap.Values) {
if (-not $plan.AllowDeleteKey) { continue }
if ($NormalizedPath.Equals($plan.NormalizedPath, [System.StringComparison]::OrdinalIgnoreCase) -or
($plan.IncludeSubKeys -and $NormalizedPath.StartsWith("$($plan.NormalizedPath)\", [System.StringComparison]::OrdinalIgnoreCase))) {
return $true
}
}
return $false
}
function Find-RegistryAllowListPlanMatch {
param(
[Parameter(Mandatory)]
@@ -501,6 +742,7 @@ function Find-RegistryAllowListPlanMatch {
IsDescendant = $false
CaptureAllValues = [bool]$plan.CaptureAllValues
ValueNames = $plan.ValueNames
TrustedValueMap = $plan.TrustedValueMap
}
}
@@ -515,6 +757,7 @@ function Find-RegistryAllowListPlanMatch {
IsDescendant = $true
CaptureAllValues = $true
ValueNames = $plan.ValueNames
TrustedValueMap = $plan.TrustedValueMap
}
}
}
@@ -571,7 +814,8 @@ function Test-RegistryValueKindNameSupported {
try {
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
return $kind -notin @([Microsoft.Win32.RegistryValueKind]::Unknown, [Microsoft.Win32.RegistryValueKind]::None)
return [System.Enum]::IsDefined([Microsoft.Win32.RegistryValueKind], $kind) -and
$kind -notin @([Microsoft.Win32.RegistryValueKind]::Unknown, [Microsoft.Win32.RegistryValueKind]::None)
}
catch {
return $false
@@ -101,6 +101,27 @@ function Test-RegistryKeySnapshotCanBeRestored {
}
}
<#
.SYNOPSIS
Preflights every root snapshot before any registry changes or hive loading.
#>
function Test-RegistryBackupSnapshotsCanBeRestored {
param([Parameter(Mandatory)][AllowEmptyCollection()][object[]]$RegistryKeys)
$rootPaths = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
foreach ($snapshot in $RegistryKeys) {
$parts = Split-RegistryPath -path $snapshot.Path
if (-not $parts -or [string]::IsNullOrWhiteSpace($parts.SubKey) -or
$parts.Hive -notin @('HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE', 'HKEY_CLASSES_ROOT', 'HKEY_USERS', 'HKEY_CURRENT_CONFIG')) {
throw "Unsupported registry path in backup: $($snapshot.Path)"
}
if (-not $rootPaths.Add("$($parts.Hive)\$($parts.SubKey)")) {
throw "Backup contains duplicate registry root path: $($snapshot.Path)"
}
Test-RegistryKeySnapshotCanBeRestored -Snapshot $snapshot
}
}
<#
.SYNOPSIS
Returns a snapshot child's name only when it is directly below its parent.
@@ -145,6 +166,8 @@ function Get-DirectRegistrySnapshotChildName {
.DESCRIPTION
Writes only values and descendants represented by the backup. Existing keys are
retained so their security descriptors and unrelated data are not destroyed.
A key recorded as originally absent is removed only if trusted validation
authorized cleanup and no values or subkeys remain.
#>
function Restore-RegistryKeySnapshotAtPath {
param(
@@ -161,20 +184,37 @@ function Restore-RegistryKeySnapshotAtPath {
return
}
$onlyDeletesValues = @($Snapshot.SubKeys).Count -eq 0 -and
@($Snapshot.Values | Where-Object { [bool]$_.Exists }).Count -eq 0
if ($onlyDeletesValues -and (@($Snapshot.Values).Count -gt 0 -or $Snapshot.RemoveEmptyKey)) {
# An absent value-only key already has the requested state.
$key = $RootKey.OpenSubKey($SubKeyPath, $true)
if ($null -eq $key) { return }
}
else {
$key = $RootKey.CreateSubKey($SubKeyPath)
}
if ($null -eq $key) {
throw "Unable to create or open registry key '$($Snapshot.Path)'"
}
$removeEmptyKey = $false
try {
foreach ($valueSnapshot in @($Snapshot.Values)) {
Restore-RegistryValueSnapshot -RegistryKey $key -Snapshot $valueSnapshot
}
if ($Snapshot.RemoveEmptyKey -and $onlyDeletesValues) {
$removeEmptyKey = @($key.GetValueNames()).Count -eq 0 -and @($key.GetSubKeyNames()).Count -eq 0
}
}
finally {
$key.Close()
}
if ($removeEmptyKey) {
Remove-RegistryEmptyKeyIfExists -RootKey $RootKey -SubKeyPath $SubKeyPath
}
foreach ($subKeySnapshot in @($Snapshot.SubKeys)) {
$childName = Get-DirectRegistrySnapshotChildName -ParentPath $Snapshot.Path -ChildPath $subKeySnapshot.Path
@@ -244,7 +284,12 @@ function Convert-RegistryValueKindFromBackup {
}
try {
return [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
$kind = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $KindName, $true)
if (-not [System.Enum]::IsDefined([Microsoft.Win32.RegistryValueKind], $kind) -or
$kind -in @([Microsoft.Win32.RegistryValueKind]::Unknown, [Microsoft.Win32.RegistryValueKind]::None)) {
throw "Unsupported registry value kind in backup: $KindName"
}
return $kind
}
catch {
throw "Unsupported registry value kind in backup: $KindName"
+47 -4
View File
@@ -40,8 +40,9 @@ function Import-RegistryBackup {
.DESCRIPTION
Validates the structure and content of the supplied backup and converts
it into a normalized representation that can be safely consumed by the
restore workflow. Throws if validation fails.
it into a normalized representation for the restore workflow. Executable
content mismatches are returned in ExecutableValueWarnings for confirmation;
structural and authorization failures throw.
.PARAMETER Backup
The raw backup object (typically parsed from JSON) to normalize.
@@ -59,6 +60,7 @@ function ConvertTo-NormalizedRegistryBackup {
)
$errors = New-Object System.Collections.Generic.List[string]
$executableValueWarnings = New-Object 'System.Collections.Generic.List[object]'
if (-not $Backup.PSObject.Properties['Version']) {
$errors.Add((Get-Translation -Key 'BackupMissingProperty' -FormatArgs @('Version')))
@@ -137,7 +139,22 @@ function ConvertTo-NormalizedRegistryBackup {
}
else {
try {
$allowListValidationErrors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @($selectedFeatures) -SelectedUndoFeatureIds @($selectedUndoFeatures) -Target $normalizedTarget -RegistryKeys @($normalizedKeys))
$planErrors = New-Object System.Collections.Generic.List[string]
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @($selectedFeatures) -SelectedUndoFeatureIds @($selectedUndoFeatures) -Target $normalizedTarget -Errors $planErrors
foreach ($planError in $planErrors) {
$errors.Add($planError)
}
if ($planErrors.Count -eq 0) {
$normalizedKeys = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($normalizedKeys) -PlanMap $planMap)
$allowListValidationErrors = @(Test-RegistryBackupAgainstAllowList -RegistryKeys @($normalizedKeys) -PlanMap $planMap -ExecutableValueWarnings $executableValueWarnings)
if ($allowListValidationErrors.Count -eq 0) {
Test-RegistryBackupSnapshotsCanBeRestored -RegistryKeys @($normalizedKeys)
}
}
else {
$allowListValidationErrors = @()
}
foreach ($allowListValidationError in $allowListValidationErrors) {
$errors.Add([string]$allowListValidationError)
}
@@ -167,6 +184,7 @@ function ConvertTo-NormalizedRegistryBackup {
SelectedFeatures = @($selectedFeatures)
SelectedUndoFeatures = @($selectedUndoFeatures)
RegistryKeys = @($normalizedKeys)
ExecutableValueWarnings = @($executableValueWarnings.ToArray())
}
}
@@ -182,6 +200,10 @@ function ConvertTo-NormalizedRegistryBackup {
A normalized backup object (as produced by ConvertTo-NormalizedRegistryBackup) whose
RegistryKeys snapshots should be restored.
.PARAMETER ConfirmUntrustedValues
Receives the freshly validated executable mismatches before registry writes or hive
loading. Must return Boolean true after user confirmation; otherwise restore is canceled.
.OUTPUTS
PSCustomObject
Returns an object with a Result property set to $true when the restore
@@ -190,9 +212,13 @@ function ConvertTo-NormalizedRegistryBackup {
function Restore-RegistryBackupState {
param(
[Parameter(Mandatory)]
$Backup
$Backup,
# Return Boolean true only after the user explicitly accepts the displayed mismatches.
[scriptblock]$ConfirmUntrustedValues
)
# Recompute warnings and blocking validation; backup-provided flags cannot authorize restoration.
$Backup = ConvertTo-NormalizedRegistryBackup -Backup $Backup
$friendlyTarget = Get-FriendlyRegistryBackupTarget -Target ([string]$Backup.Target)
if ($script:Params.ContainsKey("WhatIf")) {
@@ -200,6 +226,23 @@ function Restore-RegistryBackupState {
return [PSCustomObject]@{ Result = $true }
}
if (@($Backup.ExecutableValueWarnings).Count -gt 0) {
Write-Host "Registry restore for $friendlyTarget requires confirmation of $(@($Backup.ExecutableValueWarnings).Count) unrecognized executable setting(s)." -ForegroundColor Yellow
foreach ($mismatch in $Backup.ExecutableValueWarnings) {
Write-Host "Unrecognized executable registry setting: $($mismatch | ConvertTo-Json -Compress -Depth 10)"
}
if (-not $ConfirmUntrustedValues) {
Write-Host 'Registry restore blocked: executable settings require explicit user confirmation.'
throw (Get-Translation -Key 'BackupExecutableConfirmationRequired')
}
$approved = & $ConfirmUntrustedValues $Backup.ExecutableValueWarnings
if ($approved -isnot [bool] -or -not $approved) {
Write-Host 'Registry restore canceled: user did not approve the unrecognized executable settings.'
return [PSCustomObject]@{ Result = $false }
}
Write-Host 'User approved restoring the unrecognized executable settings.'
}
$restoreAction = {
param($normalizedBackup)
+14 -2
View File
@@ -31,7 +31,10 @@ function Show-MessageBox {
[System.Windows.Window]$Owner = $null,
[Parameter(Mandatory=$false)]
[int]$Width = 0
[int]$Width = 0,
[ValidateSet('OK', 'Cancel', 'Yes', 'No')]
[string]$DefaultResult
)
Add-Type -AssemblyName PresentationFramework,PresentationCore,WindowsBase | Out-Null
@@ -91,7 +94,8 @@ function Show-MessageBox {
default { [System.Windows.MessageBoxImage]::None }
}
$nativeResult = [System.Windows.MessageBox]::Show($Message, $Title, $nativeButton, $nativeIcon)
$nativeDefault = if ($DefaultResult) { [System.Windows.MessageBoxResult]::$DefaultResult } else { [System.Windows.MessageBoxResult]::None }
$nativeResult = [System.Windows.MessageBox]::Show($Message, $Title, $nativeButton, $nativeIcon, $nativeDefault)
return [string]$nativeResult
}
$reader = [System.Xml.XmlReader]::Create([System.IO.StringReader]::new($xaml))
@@ -187,6 +191,14 @@ function Show-MessageBox {
}
}
if ($DefaultResult) {
$useSecondButton = $DefaultResult -in @('Cancel', 'No')
$button1.IsDefault = -not $useSecondButton
$button2.IsDefault = $useSecondButton
$defaultButton = if ($useSecondButton) { $button2 } else { $button1 }
$msgWindow.Add_ContentRendered({ $null = $defaultButton.Focus() })
}
# Title bar drag to move window
$titleBar.Add_MouseLeftButtonDown({
$msgWindow.DragMove()
+1
View File
@@ -331,6 +331,7 @@ function Show-RestoreBackupDialog {
}
}
catch {
Write-Error "Failed to load registry backup '$($openDialog.FileName)': $($_.Exception.Message)" -ErrorAction Continue
Show-MessageBox -Owner $window -Title (Get-Translation -Key 'RestoreInvalidBackupTitle') -Message (Get-Translation -Key 'RestoreInvalidBackupMessage' -FormatArgs @($_.Exception.Message)) -Button 'OK' -Icon 'Error' | Out-Null
return
}
+10 -1
View File
@@ -31,7 +31,16 @@ function Show-RestoreBackupWindow {
}
Write-Host "User confirmed registry restore for $($backup.Target)."
$restoreOpResult = Restore-RegistryBackupState -Backup $backup
$confirmUntrustedValues = {
param($mismatches)
$details = @($mismatches | ForEach-Object {
$valueName = if ([string]::IsNullOrEmpty($_.Name)) { '(Default)' } else { $_.Name }
Get-Translation -Key 'BackupExecutableMismatchDetails' -FormatArgs @($_.Path, $valueName, $_.Kind, ($_.Data | ConvertTo-Json -Compress -Depth 10))
}) -join "`n`n"
$message = Get-Translation -Key 'BackupExecutableWarningMessage' -FormatArgs @($details)
return (Show-MessageBox -Owner $Owner -Title (Get-Translation -Key 'BackupExecutableWarningTitle') -Message $message -Button 'OKCancel' -Icon 'Warning' -DefaultResult 'Cancel' -Width 700) -eq 'OK'
}
$restoreOpResult = Restore-RegistryBackupState -Backup $backup -ConfirmUntrustedValues $confirmUntrustedValues
if ($restoreOpResult -and $restoreOpResult.Result) {
$restoreResult.RestoredRegistry = $true
if ($script:Params.ContainsKey("WhatIf")) {
+43
View File
@@ -104,6 +104,49 @@ function Remove-RegistrySubKeyTreeIfExists {
}
}
<#
.SYNOPSIS
Calls Windows' empty-only registry deletion API.
#>
function Invoke-RegistryEmptyKeyDeletion {
param($RootKey, [string]$SubKeyPath)
if (-not ('Win11Debloat.RegistryEmptyKey' -as [type])) {
Add-Type -Namespace Win11Debloat -Name RegistryEmptyKey -MemberDefinition @'
[System.Runtime.InteropServices.DllImport("shlwapi.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, ExactSpelling = true)]
public static extern int SHDeleteEmptyKeyW(Microsoft.Win32.SafeHandles.SafeRegistryHandle hkey, string subKey);
'@
}
return [Win11Debloat.RegistryEmptyKey]::SHDeleteEmptyKeyW($RootKey.Handle, $SubKeyPath)
}
<#
.SYNOPSIS
Removes an empty key, retaining keys containing values or subkeys.
#>
function Remove-RegistryEmptyKeyIfExists {
param(
[Parameter(Mandatory)]$RootKey,
[Parameter(Mandatory)][string]$SubKeyPath
)
$status = Invoke-RegistryEmptyKeyDeletion -RootKey $RootKey -SubKeyPath $SubKeyPath
# Success, file not found, and path not found all satisfy cleanup.
if ($status -in @(0, 2, 3)) { return }
# A concurrent writer may have populated the key after the restore's initial check.
$key = $RootKey.OpenSubKey($SubKeyPath, $false)
if ($null -eq $key) { return }
try {
if (@($key.GetValueNames()).Count -gt 0 -or @($key.GetSubKeyNames()).Count -gt 0) { return }
}
finally {
$key.Close()
}
throw (New-Object System.ComponentModel.Win32Exception -ArgumentList ([int]$status))
}
<#
.SYNOPSIS
Returns a feature's registry-file path, using the Sysprep layout when targeting another profile.
+6 -2
View File
@@ -106,6 +106,7 @@ Describe 'Add-RegistryPlanOperation' {
$plan = $plans['hkey_current_user\software\example']
$plan.IncludeSubKeys | Should -BeTrue
$plan.CaptureAllValues | Should -BeTrue
$plan.AllowDeleteKey | Should -BeTrue
$plan.ValueNames | Should -HaveCount 1
}
@@ -156,6 +157,7 @@ Describe 'Get-RegistryBackupCapturePlans' {
$plans[0].ValueNames | Should -Contain 'Enabled'
$plans[0].ValueNames | Should -Contain 'Removed'
$plans[0].ValueNames | Should -Not -Contain 'Ignored'
$plans[0].AllowDeleteKey | Should -BeFalse
}
It 'passes Sysprep selection through to registry-file resolution' {
@@ -209,12 +211,14 @@ Describe 'Get-RegistrySnapshotsForBackup' {
It 'captures each plan directly for the current user' {
$plans = @(
[PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\One'; CaptureAllValues = $true; ValueNames = @(); IncludeSubKeys = $true }
[PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Two'; CaptureAllValues = $false; ValueNames = @('Value'); IncludeSubKeys = $false }
[PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\One'; CaptureAllValues = $true; ValueNames = @(); IncludeSubKeys = $true; AllowDeleteKey = $true }
[PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Two'; CaptureAllValues = $false; ValueNames = @('Value'); IncludeSubKeys = $false; AllowDeleteKey = $false }
)
@(Get-RegistrySnapshotsForBackup -CapturePlans $plans) | Should -HaveCount 2
Should -Invoke Get-RegistryKeySnapshot -Times 2 -Exactly
Should -Invoke Get-RegistryKeySnapshot -Times 1 -Exactly -ParameterFilter { $KeyPath -eq 'HKEY_CURRENT_USER\Software\One' -and $AllowDeleteKey }
Should -Invoke Get-RegistryKeySnapshot -Times 1 -Exactly -ParameterFilter { $KeyPath -eq 'HKEY_CURRENT_USER\Software\Two' -and -not $AllowDeleteKey }
Should -Invoke Invoke-WithLoadedBackupHive -Times 0 -Exactly
}
+819
View File
@@ -0,0 +1,819 @@
BeforeAll {
. (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-JsonFile.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\FileIO\Import-LanguageFile.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Registry-PathHelpers.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Get-RegFileOperations.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Resolve-UserProfilePath.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Test-TargetUserName.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Features\Invoke-Changes.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Features\Backup-RegistrySnapshotCapture.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Features\Registry-BackupValidation.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Features\Restore-RegistryApplyState.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Features\Restore-RegistryBackup.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Get-FriendlyRegistryBackupTarget.ps1')
$script:LanguagesPath = Join-Path $PSScriptRoot '..\Config\Languages'
$script:Lang = Import-LanguageFile -LanguageCode 'en-US'
$script:FeatureCatalog = Import-JsonFile -FilePath (Join-Path $PSScriptRoot '..\Config\Features.json')
}
Describe 'Registry backup deletion permissions' {
BeforeEach {
$script:Params = @{}
$script:RegfilesPath = Join-Path $PSScriptRoot '..\Regfiles'
$script:Features = @{}
foreach ($feature in $script:FeatureCatalog.Features) {
$script:Features[$feature.FeatureId] = $feature
}
}
It 'rejects deletion of a key that <FeatureId> only changes values under' -ForEach @(
@{ FeatureId = 'DisableAnimations'; Path = 'HKEY_USERS\Default\Control Panel\Desktop' }
@{ FeatureId = 'DisableLocationServices'; Path = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\LocationAndSensors' }
) {
$snapshot = [PSCustomObject]@{
Path = $Path; Exists = $false; Values = @(); SubKeys = @()
# An attacker-supplied permission must have no effect.
AllowDeleteKey = $true
}
$errors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @($FeatureId) -SelectedUndoFeatureIds @() -Target 'DefaultUserProfile' -RegistryKeys @($snapshot))
$errors | Should -HaveCount 1
$errors[0] | Should -Be "Backup contains an unauthorized registry key deletion: '$Path'."
}
It 'authorizes a tree deletion only for the selected undo operation' {
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Exists = $false; Values = @(); SubKeys = @()
}
$applyErrors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @('DisableGameBarIntegration') -SelectedUndoFeatureIds @() -Target 'DefaultUserProfile' -RegistryKeys @($snapshot))
$undoErrors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @() -SelectedUndoFeatureIds @('DisableGameBarIntegration') -Target 'DefaultUserProfile' -RegistryKeys @($snapshot))
$applyErrors | Should -HaveCount 1
$applyErrors[0] | Should -BeLike '*unauthorized registry key deletion*'
$undoErrors | Should -BeNullOrEmpty
}
It 'uses <Target> registry paths for deletion validation' -ForEach @(
@{ Target = 'DefaultUserProfile' }
@{ Target = 'User:Alice' }
@{ Target = 'CurrentUser:Alice' }
) {
$isOtherProfile = $Target -eq 'DefaultUserProfile' -or $Target -like 'User:*'
$path = if ($isOtherProfile) { 'HKEY_USERS\Default\Control Panel\Desktop' } else { 'HKEY_CURRENT_USER\Control Panel\Desktop' }
$snapshot = [PSCustomObject]@{ Path = $path; Exists = $false; Values = @(); SubKeys = @() }
$errors = @(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @('DisableAnimations') -SelectedUndoFeatureIds @() -Target $Target -RegistryKeys @($snapshot))
$errors | Should -HaveCount 1
$errors[0] | Should -BeLike '*unauthorized registry key deletion*'
}
It 'rejects the complete backup before restore can apply an earlier valid snapshot' {
$filePath = Join-Path $TestDrive 'unauthorized-deletion.json'
[PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @('DisableAnimations')
RegistryKeys = @(
[PSCustomObject]@{
Path = 'HKEY_USERS\Default\Control Panel\Desktop'; Exists = $true
Values = @([PSCustomObject]@{ Name = 'UserPreferencesMask'; Exists = $true; Kind = 'Binary'; Data = @(144, 18, 7, 128, 16, 0, 0, 0) })
SubKeys = @()
}
[PSCustomObject]@{
Path = 'HKEY_USERS\Default\Control Panel\Desktop'; Exists = $false
# Legacy absent keys had no values; this contradictory snapshot must be rejected.
Values = @([PSCustomObject]@{ Name = 'UserPreferencesMask'; Exists = $false })
SubKeys = @()
}
)
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $filePath -Encoding UTF8
Mock Restore-RegistryKeySnapshot {}
Mock Invoke-WithLoadedRestoreHive {}
Mock Write-Error {}
{ Restore-RegistryBackupState -Backup (Import-RegistryBackup -FilePath $filePath) } |
Should -Throw '*unauthorized registry key deletion*'
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'restores an authorized deletion through the existing tree-delete helper' {
$path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @(); SelectedUndoFeatures = @('DisableGameBarIntegration')
RegistryKeys = @([PSCustomObject]@{ Path = $path; Exists = $false; Values = @(); SubKeys = @() })
}
$root = [PSCustomObject]@{ DeletedTrees = [System.Collections.Generic.List[string]]::new() }
$root | Add-Member ScriptMethod DeleteSubKeyTree { param($subKey, $throwOnMissing) $this.DeletedTrees.Add($subKey) }
Mock Get-RegistryRootKey { $root }
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
Restore-RegistryKeySnapshot -Snapshot $normalized.RegistryKeys[0]
$root.DeletedTrees | Should -Be @('ms-gamebar\shell\open\command')
}
}
Describe 'Executable registry backup values' {
BeforeEach {
$script:Params = @{}
$script:RegfilesPath = Join-Path $PSScriptRoot '..\Regfiles'
$script:Features = @{}
foreach ($feature in $script:FeatureCatalog.Features) { $script:Features[$feature.FeatureId] = $feature }
Mock Write-Error {}
Mock Restore-RegistryKeySnapshot {}
Mock Invoke-WithLoadedRestoreHive {}
}
It 'requires confirmation or blocks a doctored <Case> before any restore calls' -ForEach @(
@{ Case = 'Game Bar command'; FeatureId = 'DisableGameBarIntegration'; Undo = $false; Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Name = ''; Kind = 'String'; Data = 'cmd.exe /c echo doctored' }
@{ Case = 'Game Bar services command'; FeatureId = 'DisableGameBarIntegration'; Undo = $false; Path = 'HKEY_CLASSES_ROOT\ms-gamebarservices\shell\open\command'; Name = ''; Kind = 'String'; Data = 'cmd.exe /c echo doctored' }
@{ Case = 'undo command'; FeatureId = 'DisableGameBarIntegration'; Undo = $true; Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Name = ''; Kind = 'String'; Data = 'cmd.exe /c echo doctored' }
@{ Case = 'RunOnce command'; FeatureId = 'RevertContextMenu'; Undo = $false; Path = 'HKEY_USERS\Default\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'; Name = 'RestoreWin10ContextMenu'; Kind = 'String'; Data = 'cmd.exe /c echo doctored' }
@{ Case = 'DLL path'; FeatureId = 'RevertContextMenu'; Undo = $false; Path = 'HKEY_USERS\Default\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32'; Name = ''; Kind = 'String'; Data = 'C:\Temp\doctored.dll' }
@{ Case = 'COM indirection'; FeatureId = 'RevertContextMenu'; Undo = $true; Path = 'HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\TreatAs'; Name = ''; Kind = 'String'; Data = '{00000000-0000-0000-0000-000000000001}' }
@{ Case = 'appended command arguments'; FeatureId = 'DisableGameBarIntegration'; Undo = $false; Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Name = ''; Kind = 'String'; Data = '%SystemRoot%/System32/systray.exe /doctored' }
@{ Case = 'changed command kind'; FeatureId = 'DisableGameBarIntegration'; Undo = $false; Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Name = ''; Kind = 'ExpandString'; Data = '%SystemRoot%/System32/systray.exe' }
@{ Case = 'undefined value kind'; FeatureId = 'DisableGameBarIntegration'; Undo = $false; Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Name = ''; Kind = '99'; Data = 'data' }
) {
$filePath = Join-Path $TestDrive 'doctored.json'
[PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @(if (-not $Undo) { $FeatureId })
SelectedUndoFeatures = @(if ($Undo) { $FeatureId })
RegistryKeys = @([PSCustomObject]@{
Path = $Path; Exists = $true; Values = @([PSCustomObject]@{ Name = $Name; Exists = $true; Kind = $Kind; Data = $Data }); SubKeys = @()
})
# Backup-provided trust information must have no effect.
TrustedValueMap = @{ Command = $Data }
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $filePath -Encoding UTF8
if ($Case -eq 'undefined value kind') {
{ Import-RegistryBackup -FilePath $filePath } | Should -Throw '*Validation failed*'
}
else {
$normalized = Import-RegistryBackup -FilePath $filePath
$normalized.ExecutableValueWarnings | Should -HaveCount 1
{ Restore-RegistryBackupState -Backup $normalized } | Should -Throw '*requires explicit confirmation*'
}
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'accepts <Case> without broadening the operation scope' -ForEach @(
@{ Case = 'a trusted command'; Undo = $false; Exists = $true; Data = '%SystemRoot%/System32/systray.exe' }
@{ Case = 'the trusted apply command when restoring undo'; Undo = $true; Exists = $true; Data = '%SystemRoot%/System32/systray.exe' }
@{ Case = 'an empty executable value'; Undo = $false; Exists = $true; Data = '' }
@{ Case = 'a missing executable value'; Undo = $false; Exists = $false; Data = $null }
) {
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @(if (-not $Undo) { 'DisableGameBarIntegration' })
SelectedUndoFeatures = @(if ($Undo) { 'DisableGameBarIntegration' })
RegistryKeys = @([PSCustomObject]@{
Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'; Exists = $true
Values = @([PSCustomObject]@{ Name = ''; Exists = $Exists; Kind = if ($Exists) { 'String' } else { $null }; Data = $Data }); SubKeys = @()
})
}
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
$normalized.RegistryKeys[0].Values[0].Data | Should -Be $Data
$normalized.RegistryKeys[0].Values[0].Exists | Should -Be $Exists
}
It 'accepts the actual trusted RunOnce command' {
$operation = @(Get-RegFileOperations -regFilePath (Join-Path $script:RegfilesPath 'Sysprep\Disable_Show_More_Options_Context_Menu.reg') | Where-Object ValueName -eq 'RestoreWin10ContextMenu')[0]
$snapshot = [PSCustomObject]@{ Path = $operation.KeyPath; Exists = $true; Values = @([PSCustomObject]@{ Name = $operation.ValueName; Exists = $true; Kind = 'String'; Data = $operation.ValueData }); SubKeys = @() }
@(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @('RevertContextMenu') -SelectedUndoFeatureIds @() -Target 'DefaultUserProfile' -RegistryKeys @($snapshot)) | Should -HaveCount 0
}
It 'keeps ordinary numeric COM visibility settings restorable' {
$snapshot = [PSCustomObject]@{
Path = 'HKEY_USERS\Default\Software\Classes\CLSID\{018D5C66-4533-4307-9B53-224DE2ED1FE6}'; Exists = $true
Values = @([PSCustomObject]@{ Name = 'System.IsPinnedToNameSpaceTree'; Exists = $true; Kind = 'DWord'; Data = 1 }); SubKeys = @()
}
@(Test-RegistryBackupMatchesSelectedFeatures -SelectedFeatureIds @('HideOnedrive') -SelectedUndoFeatureIds @() -Target 'DefaultUserProfile' -RegistryKeys @($snapshot)) | Should -HaveCount 0
}
It 'rejects misplaced children during import rather than starting restore' {
$desktop = [PSCustomObject]@{ Path = 'HKEY_USERS\Default\Control Panel\Desktop'; Exists = $true; Values = @(); SubKeys = @() }
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'; SelectedFeatures = @('DisableAnimations')
RegistryKeys = @($desktop, [PSCustomObject]@{
Path = 'HKEY_USERS\Default\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'; Exists = $true; Values = @(); SubKeys = @($desktop)
})
}
{ Restore-RegistryBackupState -Backup (ConvertTo-NormalizedRegistryBackup -Backup $backup) } | Should -Throw '*is not directly below parent*'
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
}
Describe 'Registry tree deletion scope' {
BeforeEach {
$script:DeletionPlanMap = New-RegistryBackupAllowListPlanMap -CapturePlans @(
[PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'; IncludeSubKeys = $true
CaptureAllValues = $true; AllowDeleteKey = $true; ValueNames = @()
}
[PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example\Child'; IncludeSubKeys = $false
CaptureAllValues = $false; AllowDeleteKey = $false; ValueNames = @('Enabled')
}
)
}
It 'validates deletion of <Path> as <Allowed>' -ForEach @(
@{ Path = 'hkey_current_user/Software/Example'; Allowed = $true }
@{ Path = 'HKEY_CURRENT_USER\Software\Example\Child'; Allowed = $true }
@{ Path = 'HKEY_CURRENT_USER\Software\Example\Child\Nested'; Allowed = $true }
@{ Path = 'HKEY_CURRENT_USER\Software'; Allowed = $false }
@{ Path = 'HKEY_CURRENT_USER\Software\ExampleSibling'; Allowed = $false }
@{ Path = 'HKEY_LOCAL_MACHINE\Software\Example'; Allowed = $false }
) {
Test-RegistryKeyDeletionAllowed -NormalizedPath (Get-NormalizedRegistryPathKey -Path $Path) -PlanMap $script:DeletionPlanMap |
Should -Be $Allowed
}
It 'accepts a nested deletion despite an exact value-only plan' {
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'; Exists = $true; Values = @()
SubKeys = @([PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Example\Child'; Exists = $false; Values = @(); SubKeys = @() })
}
$errors = New-Object 'System.Collections.Generic.List[string]'
Test-RegistrySnapshotAgainstAllowList -Snapshot $snapshot -PlanMap $script:DeletionPlanMap -Errors $errors
$errors | Should -BeNullOrEmpty
}
It 'does not grant deletion merely because all values and subkeys are captured' {
$script:DeletionPlanMap.Values | ForEach-Object { $_.AllowDeleteKey = $false }
Test-RegistryKeyDeletionAllowed -NormalizedPath (Get-NormalizedRegistryPathKey -Path 'HKEY_CURRENT_USER\Software\Example') -PlanMap $script:DeletionPlanMap |
Should -BeFalse
}
It 'preserves an authorized descendant deletion during compatibility conversion' {
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'; Exists = $true; Values = @()
SubKeys = @([PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Example\Child'; Exists = $false; Values = @(); SubKeys = @() })
}
$converted = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($snapshot) -PlanMap $script:DeletionPlanMap)
$converted[0].SubKeys[0].Exists | Should -BeFalse
$converted[0].SubKeys[0].Values | Should -HaveCount 0
}
}
Describe 'Legacy absent-key backup compatibility' {
BeforeEach {
$script:Params = @{}
$script:RegfilesPath = Join-Path $PSScriptRoot '..\Regfiles'
$script:Features = @{}
foreach ($feature in $script:FeatureCatalog.Features) {
$script:Features[$feature.FeatureId] = $feature
}
Mock Write-Error {}
}
It 'imports a legacy absent key for <FeatureId> as missing permitted values' -ForEach @(
@{ FeatureId = 'RevertContextMenu'; Path = 'HKEY_USERS\Default\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32'; ValueNames = @('') }
@{ FeatureId = 'DisableChromeAI'; Path = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome'; ValueNames = @('AIModeSettings', 'AutofillPredictionSettings', 'ChromeSuggestionsSettings', 'CreateThemesSettings', 'DevToolsGenAiSettings', 'FindAndFillWithGeminiSettings', 'GeminiSettings', 'GeminiSparkSettings', 'GenAILocalFoundationalModelSettings', 'HelpMeWriteSettings', 'HistorySearchSettings', 'SearchContentSharingSettings', 'SmartTabSharingSettings', 'TabCompareSettings', 'ThirdPartyAiChatSettings', 'VoiceTypingSettings') }
@{ FeatureId = 'DisableDVR'; Path = 'HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\GameDVR'; ValueNames = @('AllowGameDVR') }
) {
$filePath = Join-Path $TestDrive "$FeatureId-legacy.json"
[PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @($FeatureId)
RegistryKeys = @([PSCustomObject]@{ Path = $Path; Exists = $false; Values = @(); SubKeys = @() })
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $filePath -Encoding UTF8
$originalContent = Get-Content -LiteralPath $filePath -Raw
$normalized = Import-RegistryBackup -FilePath $filePath
$normalized.RegistryKeys[0].Exists | Should -BeTrue
$normalized.RegistryKeys[0].Values -is [array] | Should -BeTrue
$normalized.RegistryKeys[0].Values | Should -HaveCount $ValueNames.Count
@($normalized.RegistryKeys[0].Values | ForEach-Object { $_.Name } | Sort-Object) | Should -Be @($ValueNames | Sort-Object)
@($normalized.RegistryKeys[0].Values | Where-Object { $_.Exists -or $null -ne $_.Kind -or $null -ne $_.Data }) | Should -HaveCount 0
(Get-Content -LiteralPath $filePath -Raw) | Should -Be $originalContent
}
It 'rejects an unknown absent-key path instead of converting it' {
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @('DisableAnimations')
RegistryKeys = @([PSCustomObject]@{ Path = 'HKEY_USERS\Default\Software\NotAllowedHere'; Exists = $false; Values = @(); SubKeys = @() })
}
{ ConvertTo-NormalizedRegistryBackup -Backup $backup } | Should -Throw '*unexpected registry path*'
}
It 'imports a legacy value-only backup for <Target> using the correct profile paths' -ForEach @(
@{ Target = 'CurrentUser:Alice'; Hive = 'HKEY_CURRENT_USER' }
@{ Target = 'User:Alice'; Hive = 'HKEY_USERS\Default' }
) {
Mock Test-RunningAsSystem { $false }
Mock Test-UserNameMatch { $true }
Mock Test-TargetUserName { [PSCustomObject]@{ IsValid = $true } }
$path = "$Hive\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32"
$filePath = Join-Path $TestDrive 'legacy-profile.json'
[PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = $Target
SelectedFeatures = @('RevertContextMenu')
RegistryKeys = @([PSCustomObject]@{ Path = $path; Exists = $false; Values = @(); SubKeys = @() })
} | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $filePath -Encoding UTF8
$normalized = Import-RegistryBackup -FilePath $filePath
$normalized.Target | Should -Be $Target
$normalized.RegistryKeys | Should -HaveCount 1
$normalized.RegistryKeys[0].Path | Should -Be $path
$normalized.RegistryKeys[0].Exists | Should -BeTrue
$normalized.RegistryKeys[0].Values | Should -HaveCount 1
$normalized.RegistryKeys[0].Values[0].Name | Should -Be ''
$normalized.RegistryKeys[0].Values[0].Exists | Should -BeFalse
if ($Target -like 'User:*') {
Should -Invoke Test-TargetUserName -Times 1 -Exactly -ParameterFilter { $UserName -eq 'Alice' }
}
else {
Should -Invoke Test-UserNameMatch -Times 1 -Exactly -ParameterFilter { $UserNameA -eq 'Alice' -and $UserNameB -eq $env:USERNAME }
}
}
It 'preserves the input object when converting a legacy snapshot' {
$snapshot = [PSCustomObject]@{ Path = 'HKEY_USERS\Default\Control Panel\Desktop'; Exists = $false; Values = @(); SubKeys = @() }
$errors = New-Object 'System.Collections.Generic.List[string]'
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @('DisableAnimations') -SelectedUndoFeatureIds @() -Target 'DefaultUserProfile' -Errors $errors
$converted = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($snapshot) -PlanMap $planMap)
$converted[0].Exists | Should -BeTrue
$snapshot.Exists | Should -BeFalse
$snapshot.Values | Should -HaveCount 0
}
It 'derives capture plans once for conversion and final validation' {
Mock Get-RegistryBackupCapturePlans {
@([PSCustomObject]@{
Path = 'HKEY_USERS\Default\Control Panel\Desktop'; ValueNames = @('UserPreferencesMask')
AllowDeleteKey = $false; CaptureAllValues = $false; IncludeSubKeys = $false
})
}
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @('DisableAnimations')
RegistryKeys = @([PSCustomObject]@{ Path = 'HKEY_USERS\Default\Control Panel\Desktop'; Exists = $false; Values = @(); SubKeys = @() })
}
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
$normalized.RegistryKeys[0].Values[0].Name | Should -Be 'UserPreferencesMask'
Should -Invoke Get-RegistryBackupCapturePlans -Times 1 -Exactly
}
It 'rejects an absent value-only key containing subkeys' {
$path = 'HKEY_USERS\Default\Control Panel\Desktop'
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'DefaultUserProfile'
SelectedFeatures = @('DisableAnimations')
RegistryKeys = @([PSCustomObject]@{
Path = $path; Exists = $false; Values = @()
SubKeys = @([PSCustomObject]@{ Path = "$path\Child"; Exists = $true; Values = @(); SubKeys = @() })
})
}
{ ConvertTo-NormalizedRegistryBackup -Backup $backup } | Should -Throw '*Validation failed*'
Should -Invoke Write-Error -Times 1 -Exactly -ParameterFilter { $Message -like '*unauthorized registry key deletion*' }
}
}
Describe 'Absent keys in value-only backups' {
BeforeEach {
$script:Params = @{}
$script:RegfilesPath = Join-Path $PSScriptRoot '..\Regfiles'
$script:Features = @{ DisableAnimations = @($script:FeatureCatalog.Features | Where-Object FeatureId -eq 'DisableAnimations')[0] }
$script:FakeRoot = [PSCustomObject]@{ Key = $null; DeletedTrees = [System.Collections.Generic.List[string]]::new(); CreatedKeys = [System.Collections.Generic.List[string]]::new() }
$script:FakeRoot | Add-Member ScriptMethod OpenSubKey { param($path, $writable) $this.Key }
$script:FakeRoot | Add-Member ScriptMethod CreateSubKey { param($path) $this.CreatedKeys.Add($path); $this.Key }
$script:FakeRoot | Add-Member ScriptMethod DeleteSubKeyTree { param($path, $throwOnMissing) $this.DeletedTrees.Add($path) }
Mock Get-RegistryRootKey { $script:FakeRoot }
}
It 'captures missing values and preserves unrelated data that appears before restore' {
$plans = @(Get-RegistryBackupCapturePlans -SelectedRegistryFeatures @($script:Features.DisableAnimations))
$snapshots = @(Get-RegistrySnapshotsForBackup -CapturePlans $plans)
$snapshots | Should -HaveCount 1
$snapshots[0].Exists | Should -BeTrue
$snapshots[0].Values | Should -HaveCount 1
$snapshots[0].Values[0].Name | Should -Be 'UserPreferencesMask'
$snapshots[0].Values[0].Exists | Should -BeFalse
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = "CurrentUser:$env:USERNAME"
SelectedFeatures = @('DisableAnimations'); RegistryKeys = $snapshots
} | ConvertTo-Json -Depth 10 | ConvertFrom-Json
function Test-RunningAsSystem { $false }
function Test-UserNameMatch { $true }
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
$script:FakeRoot.Key = [PSCustomObject]@{
Values = @{ UserPreferencesMask = 'applied'; Wallpaper = 'keep' }
Children = @('UnrelatedChild')
}
$script:FakeRoot.Key | Add-Member ScriptMethod DeleteValue { param($name, $throwOnMissing) $this.Values.Remove($name) }
$script:FakeRoot.Key | Add-Member ScriptMethod Close {}
$script:FakeRoot.Key | Add-Member ScriptMethod GetValueNames { @($this.Values.Keys) }
$script:FakeRoot.Key | Add-Member ScriptMethod GetSubKeyNames { @($this.Children) }
Restore-RegistryKeySnapshot -Snapshot $normalized.RegistryKeys[0]
$script:FakeRoot.Key.Values.ContainsKey('UserPreferencesMask') | Should -BeFalse
$script:FakeRoot.Key.Values.Wallpaper | Should -Be 'keep'
$script:FakeRoot.Key.Children | Should -Be @('UnrelatedChild')
$script:FakeRoot.DeletedTrees | Should -HaveCount 0
}
It 'records missing default and named values without requesting a tree deletion' {
$snapshot = Get-RegistryKeySnapshot -KeyPath 'HKEY_CURRENT_USER\Software\Example' -ValueNames @('', 'Enabled')
$snapshot.Exists | Should -BeTrue
$snapshot.Values | Should -HaveCount 2
@($snapshot.Values | Where-Object { $_.Name -eq '' }) | Should -HaveCount 1
@($snapshot.Values | Where-Object { $_.Exists }) | Should -HaveCount 0
}
It 'does not create a still-absent key when restoring <Case> missing values' -ForEach @(
@{ Case = 'new'; Legacy = $false }
@{ Case = 'legacy'; Legacy = $true }
) {
$snapshot = if ($Legacy) {
$errors = New-Object 'System.Collections.Generic.List[string]'
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @('DisableAnimations') -SelectedUndoFeatureIds @() -Target 'CurrentUser' -Errors $errors
@(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @([PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Control Panel\Desktop'; Exists = $false; Values = @(); SubKeys = @()
}) -PlanMap $planMap)[0]
}
else {
Get-RegistryKeySnapshot -KeyPath 'HKEY_CURRENT_USER\Control Panel\Desktop' -ValueNames @('UserPreferencesMask')
}
Restore-RegistryKeySnapshot -Snapshot $snapshot
$script:FakeRoot.CreatedKeys | Should -HaveCount 0
$script:FakeRoot.DeletedTrees | Should -HaveCount 0
}
It 'restores legacy missing values without removing unrelated data' {
$errors = New-Object 'System.Collections.Generic.List[string]'
$planMap = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @('DisableAnimations') -SelectedUndoFeatureIds @() -Target 'CurrentUser' -Errors $errors
$snapshot = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @([PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Control Panel\Desktop'; Exists = $false; Values = @(); SubKeys = @()
}) -PlanMap $planMap)[0]
$script:FakeRoot.Key = [PSCustomObject]@{ Values = @{ UserPreferencesMask = 'applied'; Wallpaper = 'keep' }; Children = @('UnrelatedChild') }
$script:FakeRoot.Key | Add-Member ScriptMethod DeleteValue { param($name, $throwOnMissing) $this.Values.Remove($name) }
$script:FakeRoot.Key | Add-Member ScriptMethod Close {}
$script:FakeRoot.Key | Add-Member ScriptMethod GetValueNames { @($this.Values.Keys) }
$script:FakeRoot.Key | Add-Member ScriptMethod GetSubKeyNames { @($this.Children) }
Restore-RegistryKeySnapshot -Snapshot $snapshot
$script:FakeRoot.Key.Values.ContainsKey('UserPreferencesMask') | Should -BeFalse
$script:FakeRoot.Key.Values.Wallpaper | Should -Be 'keep'
$script:FakeRoot.Key.Children | Should -Be @('UnrelatedChild')
$script:FakeRoot.CreatedKeys | Should -HaveCount 0
$script:FakeRoot.DeletedTrees | Should -HaveCount 0
}
}
Describe 'Executable registry restore confirmation' {
BeforeAll {
function New-ExecutableTestBackup {
param($FeatureId = 'DisableGameBarIntegration', $Path = 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command', $Name = '', $Data = 'cmd.exe /c echo custom', $Kind = 'String', $Target = 'DefaultUserProfile')
[PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = $Target
SelectedFeatures = @($FeatureId); SelectedUndoFeatures = @()
RegistryKeys = @([PSCustomObject]@{
Path = $Path; Exists = $true; SubKeys = @()
Values = @([PSCustomObject]@{ Name = $Name; Exists = $true; Kind = $Kind; Data = $Data })
})
# These untrusted fields must never bypass validation or confirmation.
ExecutableValueWarnings = @(); Approved = $true
}
}
}
BeforeEach {
$script:Params = @{}
$script:RegfilesPath = Join-Path $PSScriptRoot '..\Regfiles'
$script:Features = @{}
foreach ($feature in $script:FeatureCatalog.Features) { $script:Features[$feature.FeatureId] = $feature }
Mock Write-Error {}
Mock Restore-RegistryKeySnapshot {}
Mock Invoke-WithLoadedRestoreHive {
param($Target, $ScriptBlock, $ArgumentObject)
& $ScriptBlock $ArgumentObject
}
}
It 'accepts the shipped <File> search command for a HideSearchTb backup' -ForEach @(
@{ File = 'Hide_Search_Taskbar.reg' }
@{ File = 'Show_Search_Icon.reg' }
@{ File = 'Show_Search_Icon_And_Label.reg' }
@{ File = 'Show_Search_Box.reg' }
) {
$op = @(Get-RegFileOperations -regFilePath (Join-Path $script:RegfilesPath "Sysprep\$File") | Where-Object ValueName -eq 'SetTaskbarSearchbox')[0]
$backup = New-ExecutableTestBackup -FeatureId 'HideSearchTb' -Path $op.KeyPath -Name $op.ValueName -Data $op.ValueData
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
$normalized.ExecutableValueWarnings | Should -HaveCount 0
(Restore-RegistryBackupState -Backup $normalized -ConfirmUntrustedValues { throw 'Unexpected prompt' }).Result | Should -BeTrue
}
It 'validates shipped and altered handlers for <FeatureId>' -ForEach @(
@{ FeatureId = 'HideShare' }
@{ FeatureId = 'HideGiveAccessTo' }
@{ FeatureId = 'HideIncludeInLibrary' }
) {
$file = Resolve-RegistryBackupUndoFilePath -Feature $script:Features[$FeatureId]
foreach ($op in @(Get-RegFileOperations -regFilePath $file | Where-Object OperationType -eq 'SetValue')) {
Test-RegistryValueMayExecuteCode -Path $op.KeyPath -ValueName $op.ValueName -KindName $op.ValueType | Should -BeTrue
$backup = New-ExecutableTestBackup -FeatureId $FeatureId -Path $op.KeyPath -Name $op.ValueName -Data $op.ValueData
(ConvertTo-NormalizedRegistryBackup -Backup $backup).ExecutableValueWarnings | Should -HaveCount 0
$backup.RegistryKeys[0].Values[0].Data = '{00000000-0000-0000-0000-000000000001}'
(ConvertTo-NormalizedRegistryBackup -Backup $backup).ExecutableValueWarnings | Should -HaveCount 1
}
}
It 'cancels without writes or hive loading when the callback returns <Response>' -ForEach @(
@{ Response = $false }
@{ Response = $null }
@{ Response = 'true' }
) {
Mock Write-Host {}
$backup = New-ExecutableTestBackup
(Restore-RegistryBackupState -Backup $backup -ConfirmUntrustedValues { $Response }).Result | Should -BeFalse
Should -Invoke Write-Host -Times 1 -Exactly -ParameterFilter { $Object -like 'Registry restore canceled:*' }
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'shows all mismatches before writes and restores only after explicit approval' {
Mock Write-Host {}
$backup = New-ExecutableTestBackup
$backup.RegistryKeys += (New-ExecutableTestBackup -Path 'HKEY_CLASSES_ROOT\ms-gamebarservices\shell\open\command' -Data 'custom.exe').RegistryKeys
$script:confirmationCount = 0
$confirm = {
param($mismatches)
$script:confirmationCount++
$mismatches | Should -HaveCount 2
$mismatches[0].Path | Should -Be 'HKEY_CLASSES_ROOT\ms-gamebar\shell\open\command'
$mismatches[0].Name | Should -Be ''
$mismatches[0].Kind | Should -Be 'String'
$mismatches[0].Data | Should -Be 'cmd.exe /c echo custom'
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
return $true
}
(Restore-RegistryBackupState -Backup $backup -ConfirmUntrustedValues $confirm).Result | Should -BeTrue
$script:confirmationCount | Should -Be 1
Should -Invoke Write-Host -Times 2 -Exactly -ParameterFilter { $Object -like 'Unrecognized executable registry setting:*' }
Should -Invoke Write-Host -Times 1 -Exactly -ParameterFilter { $Object -eq 'User approved restoring the unrecognized executable settings.' }
Should -Invoke Restore-RegistryKeySnapshot -Times 2 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 1 -Exactly
}
It 'requires fresh confirmation on every restore even when backup flags claim approval' {
$backup = ConvertTo-NormalizedRegistryBackup -Backup (New-ExecutableTestBackup)
$backup.ExecutableValueWarnings = @()
{ Restore-RegistryBackupState -Backup $backup } | Should -Throw '*requires explicit confirmation*'
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'does not permit overriding <Case>' -ForEach @(
@{ Case = 'an unauthorized path' }
@{ Case = 'an unauthorized value name' }
@{ Case = 'an unauthorized tree deletion' }
@{ Case = 'an invalid kind' }
@{ Case = 'a misplaced child' }
) {
$backup = New-ExecutableTestBackup
switch ($Case) {
'an unauthorized path' { $backup.RegistryKeys[0].Path = 'HKEY_LOCAL_MACHINE\Software\Unrelated' }
'an unauthorized value name' { $backup.RegistryKeys[0].Values[0].Name = 'Unrelated' }
'an unauthorized tree deletion' { $backup.RegistryKeys[0].Exists = $false }
'an invalid kind' { $backup.RegistryKeys[0].Values[0].Kind = '99' }
'a misplaced child' { $backup.RegistryKeys[0].SubKeys = (New-ExecutableTestBackup -Path 'HKEY_CLASSES_ROOT\ms-gamebarservices\shell\open\command').RegistryKeys }
}
{ Restore-RegistryBackupState -Backup $backup -ConfirmUntrustedValues { throw 'Confirmation must not be reached' } } | Should -Throw '*Validation failed*'
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'honors WhatIf without prompting, writes, or hive loading' {
$script:Params = @{ WhatIf = $true }
(Restore-RegistryBackupState -Backup (New-ExecutableTestBackup) -ConfirmUntrustedValues { throw 'Unexpected prompt' }).Result | Should -BeTrue
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
}
Describe 'Trusted empty-key cleanup' {
BeforeEach {
function Test-RunningAsSystem { $false }
Mock Test-TargetUserName { [PSCustomObject]@{ IsValid = $true } }
$script:Params = @{}
$script:RegfilesPath = Join-Path $PSScriptRoot '..\Regfiles'
$script:Features = @{}
foreach ($feature in $script:FeatureCatalog.Features) { $script:Features[$feature.FeatureId] = $feature }
$script:CleanupRoot = [PSCustomObject]@{
Key = $null
DeletedKeys = [System.Collections.Generic.List[string]]::new()
}
$script:CleanupRoot | Add-Member ScriptMethod OpenSubKey { param($path, $writable) $this.Key }
$script:CleanupRoot | Add-Member ScriptMethod DeleteSubKey { param($path, $throwOnMissing) $this.DeletedKeys.Add($path) }
$script:CleanupRoot | Add-Member ScriptMethod DeleteSubKeyTree { throw 'Recursive deletion must not be used' }
$script:CleanupRoot | Add-Member ScriptMethod CreateSubKey { throw 'Absent cleanup must not create keys' }
Mock Invoke-RegistryEmptyKeyDeletion {
param($RootKey, $SubKeyPath)
if ($RootKey.Key.Values.Count -gt 0 -or $RootKey.Key.Children) { return 145 }
$RootKey.DeletedKeys.Add($SubKeyPath)
return 0
}
Mock Get-RegistryRootKey { $script:CleanupRoot }
Mock Write-Error {}
}
It 'removes an originally absent context-menu key after JSON import and revalidation for <Target>' -ForEach @(
@{ Target = 'DefaultUserProfile'; Hive = 'HKEY_USERS\Default' }
@{ Target = 'User:Alice'; Hive = 'HKEY_USERS\Default' }
@{ Target = 'CurrentUser'; Hive = 'HKEY_CURRENT_USER' }
) {
$path = "$Hive\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32"
$snapshot = Get-RegistryKeySnapshot -KeyPath $path -ValueNames @('')
$snapshot.OriginallyAbsent | Should -BeTrue
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'
Target = if ($Target -eq 'CurrentUser') { "CurrentUser:$env:USERNAME" } else { $Target }
SelectedFeatures = @('RevertContextMenu'); RegistryKeys = @($snapshot)
} | ConvertTo-Json -Depth 10 | ConvertFrom-Json
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $normalized
$normalized.RegistryKeys[0].RemoveEmptyKey | Should -BeTrue
$script:CleanupRoot.Key = [PSCustomObject]@{ Values = @{ '' = '' } }
$script:CleanupRoot.Key | Add-Member ScriptMethod DeleteValue { param($name, $throwOnMissing) $this.Values.Remove($name) }
$script:CleanupRoot.Key | Add-Member ScriptMethod GetValueNames { @($this.Values.Keys) }
$script:CleanupRoot.Key | Add-Member ScriptMethod GetSubKeyNames { @() }
$script:CleanupRoot.Key | Add-Member ScriptMethod Close {}
Restore-RegistryKeySnapshot -Snapshot $normalized.RegistryKeys[0]
$script:CleanupRoot.Key.Values.Count | Should -Be 0
$script:CleanupRoot.DeletedKeys | Should -HaveCount 1
$script:CleanupRoot.DeletedKeys[0] | Should -BeLike '*\InprocServer32'
}
It 'preserves a key with <Case>' -ForEach @(
@{ Case = 'an unrelated value'; ExtraValue = $true; Child = $false }
@{ Case = 'an unrelated child'; ExtraValue = $false; Child = $true }
) {
$path = 'HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32'
$snapshot = Get-RegistryKeySnapshot -KeyPath $path -ValueNames @('')
$errors = New-Object 'System.Collections.Generic.List[string]'
$plans = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @('RevertContextMenu') -SelectedUndoFeatureIds @() -Target 'CurrentUser' -Errors $errors
$snapshot = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @([PSCustomObject]$snapshot) -PlanMap $plans)[0]
$script:CleanupRoot.Key = [PSCustomObject]@{ Values = @{ '' = '' }; Children = @(if ($Child) { 'KeepChild' }) }
if ($ExtraValue) { $script:CleanupRoot.Key.Values['KeepValue'] = 'keep' }
$script:CleanupRoot.Key | Add-Member ScriptMethod DeleteValue { param($name, $throwOnMissing) $this.Values.Remove($name) }
$script:CleanupRoot.Key | Add-Member ScriptMethod GetValueNames { @($this.Values.Keys) }
$script:CleanupRoot.Key | Add-Member ScriptMethod GetSubKeyNames { @($this.Children) }
$script:CleanupRoot.Key | Add-Member ScriptMethod Close {}
Restore-RegistryKeySnapshot -Snapshot $snapshot
$script:CleanupRoot.Key.Values.ContainsKey('') | Should -BeFalse
if ($ExtraValue) { $script:CleanupRoot.Key.Values['KeepValue'] | Should -Be 'keep' }
if ($Child) { $script:CleanupRoot.Key.Children | Should -Be 'KeepChild' }
$script:CleanupRoot.DeletedKeys | Should -HaveCount 0
}
It 'derives legacy absent-key cleanup from the trusted plan' {
$path = 'HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32'
$errors = New-Object 'System.Collections.Generic.List[string]'
$plans = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @('RevertContextMenu') -SelectedUndoFeatureIds @() -Target 'CurrentUser' -Errors $errors
$snapshot = [PSCustomObject]@{ Path = $path; Exists = $false; Values = @(); SubKeys = @() }
$normalized = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($snapshot) -PlanMap $plans)[0]
$normalized.RemoveEmptyKey | Should -BeTrue
$normalized.OriginallyAbsent | Should -BeTrue
}
It 'does not trust a backup-supplied cleanup flag for an originally existing key' {
$path = 'HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32'
$snapshot = [PSCustomObject]@{
Path = $path; Exists = $true; RemoveEmptyKey = $true
Values = @([PSCustomObject]@{ Name = ''; Exists = $false }); SubKeys = @()
}
$backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = "CurrentUser:$env:USERNAME"
SelectedFeatures = @('RevertContextMenu'); RegistryKeys = @($snapshot)
}
$normalized = ConvertTo-NormalizedRegistryBackup -Backup $backup
$normalized.RegistryKeys[0].RemoveEmptyKey | Should -BeFalse
$script:CleanupRoot.Key = [PSCustomObject]@{ Values = @{} }
$script:CleanupRoot.Key | Add-Member ScriptMethod DeleteValue { param($name, $throwOnMissing) $this.Values.Remove($name) }
$script:CleanupRoot.Key | Add-Member ScriptMethod Close {}
Restore-RegistryKeySnapshot -Snapshot $normalized.RegistryKeys[0]
$script:CleanupRoot.DeletedKeys | Should -HaveCount 0
}
It 'does not authorize cleanup for a descendant of a recursive plan' {
$path = 'HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\TreatAs'
$snapshot = [PSCustomObject]@{ Path = $path; Exists = $true; OriginallyAbsent = $true; Values = @(); SubKeys = @() }
$errors = New-Object 'System.Collections.Generic.List[string]'
$plans = Get-RegistryBackupValidationPlanMap -SelectedFeatureIds @() -SelectedUndoFeatureIds @('RevertContextMenu') -Target 'CurrentUser' -Errors $errors
$normalized = @(ConvertTo-CompatibleRegistryKeySnapshots -RegistryKeys @($snapshot) -PlanMap $plans)[0]
$normalized.RemoveEmptyKey | Should -BeFalse
}
}
Describe 'Empty-key cleanup when registry contents change' {
BeforeEach {
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Registry-PathHelpers.ps1')
$script:ConcurrentKey = [PSCustomObject]@{ Values = @{}; Children = @(); Closed = $false }
$script:ConcurrentKey | Add-Member ScriptMethod GetValueNames { @($this.Values.Keys) }
$script:ConcurrentKey | Add-Member ScriptMethod GetSubKeyNames { @($this.Children) }
$script:ConcurrentKey | Add-Member ScriptMethod DeleteValue { param($name, $missing) $this.Values.Remove($name) }
$script:ConcurrentKey | Add-Member ScriptMethod Close { $this.Closed = $true }
$script:ConcurrentRoot = [PSCustomObject]@{ Key = $script:ConcurrentKey }
$script:ConcurrentRoot | Add-Member ScriptMethod OpenSubKey { param($path, $writable) $this.Key }
$script:ConcurrentRoot | Add-Member ScriptMethod DeleteSubKey { throw 'Unconditional key deletion must not be used' }
Mock Invoke-RegistryEmptyKeyDeletion { 0 }
}
It 'retains a value added after the restore emptiness check' {
$script:ConcurrentKey.Values[''] = 'applied'
$script:ConcurrentKey | Add-Member ScriptMethod Close { $this.Values['KeepValue'] = 'concurrent data' } -Force
Mock Invoke-RegistryEmptyKeyDeletion {
$script:ConcurrentKey.Values['KeepValue'] | Should -Be 'concurrent data'
return 145
}
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'; Exists = $true; RemoveEmptyKey = $true
Values = @([PSCustomObject]@{ Name = ''; Exists = $false }); SubKeys = @()
}
Restore-RegistryKeySnapshotAtPath -Snapshot $snapshot -RootKey $script:ConcurrentRoot -SubKeyPath 'Software\Example'
$script:ConcurrentKey.Values['KeepValue'] | Should -Be 'concurrent data'
Should -Invoke Invoke-RegistryEmptyKeyDeletion -Times 1 -Exactly
}
It 'retains a child key added before empty-only deletion' {
$script:ConcurrentKey.Children = @('KeepChild')
Mock Invoke-RegistryEmptyKeyDeletion { 145 }
{ Remove-RegistryEmptyKeyIfExists -RootKey $script:ConcurrentRoot -SubKeyPath 'Software\Example' } | Should -Not -Throw
$script:ConcurrentKey.Children | Should -Be 'KeepChild'
$script:ConcurrentKey.Closed | Should -BeTrue
}
It 'accepts native status <Status> without reopening the key' -ForEach @(
@{ Status = 0 }
@{ Status = 2 }
@{ Status = 3 }
) {
Mock Invoke-RegistryEmptyKeyDeletion { $Status }
$script:ConcurrentRoot | Add-Member ScriptMethod OpenSubKey { throw 'Key should not be reopened' } -Force
{ Remove-RegistryEmptyKeyIfExists -RootKey $script:ConcurrentRoot -SubKeyPath 'Software\Example' } | Should -Not -Throw
}
It 'does not hide a native error when the key is still empty' {
Mock Invoke-RegistryEmptyKeyDeletion { 5 }
{ Remove-RegistryEmptyKeyIfExists -RootKey $script:ConcurrentRoot -SubKeyPath 'Software\Example' } | Should -Throw
$script:ConcurrentKey.Closed | Should -BeTrue
}
It 'accepts a key that disappears after the native call' {
Mock Invoke-RegistryEmptyKeyDeletion { 145 }
$script:ConcurrentRoot.Key = $null
{ Remove-RegistryEmptyKeyIfExists -RootKey $script:ConcurrentRoot -SubKeyPath 'Software\Example' } | Should -Not -Throw
}
}
@@ -15,6 +15,7 @@ Describe 'Test-RegistryBackupMatchesSelectedFeatures' {
ApplyFeature = [PSCustomObject]@{ RegistryKey = 'apply.reg'; RegistryUndoKey = 'undo.reg' }
}
$script:CapturePlanCalls = [System.Collections.Generic.List[bool]]::new()
Mock Get-RegistryBackupTrustedValueMap { @{} }
Mock Get-RegistryBackupCapturePlans {
param($SelectedRegistryFeatures, $UndoRegistryFeatures, $UseSysprepRegFiles)
$script:CapturePlanCalls.Add([bool]$UseSysprepRegFiles)
@@ -30,6 +31,7 @@ Describe 'Test-RegistryBackupMatchesSelectedFeatures' {
It 'derives an allow list from selected features and accepts a matching snapshot' {
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'
Exists = $true
Values = @([PSCustomObject]@{ Name = 'Enabled'; Exists = $true; Kind = 'DWord'; Data = 1 })
SubKeys = @()
}
+28
View File
@@ -153,6 +153,16 @@ Describe 'Get-NormalizedRegistryValueName' {
}
}
Describe 'Test-RegistryValueKindNameSupported' {
It 'rejects unsupported kind <KindName>' -ForEach @('99', '-2', 'Unknown', 'None', '') {
Test-RegistryValueKindNameSupported -KindName $_ | Should -BeFalse
}
It 'accepts defined kind <KindName>' -ForEach @('String', 'expandstring', 'Binary', 'DWord', 'QWord', 'MultiString', '1') {
Test-RegistryValueKindNameSupported -KindName $_ | Should -BeTrue
}
}
Describe 'Normalize-RegistryKeySnapshot' {
It 'normalizes nested snapshots and supplies value defaults' {
$snapshot = [PSCustomObject]@{
@@ -188,6 +198,19 @@ Describe 'Normalize-RegistryKeySnapshot' {
{ Normalize-RegistryKeySnapshot -Snapshot ([PSCustomObject]@{ Exists = $true }) } |
Should -Throw 'Backup validation failed: Registry key snapshot is missing Path.'
}
It 'rejects a <Case> key existence flag' -ForEach @(
@{ Case = 'missing'; Properties = @{} }
@{ Case = 'null'; Properties = @{ Exists = $null } }
@{ Case = 'string'; Properties = @{ Exists = 'false' } }
@{ Case = 'numeric'; Properties = @{ Exists = 0 } }
) {
$propertiesWithPath = @{ Path = 'HKEY_CURRENT_USER\Software\Example' }
foreach ($entry in $Properties.GetEnumerator()) { $propertiesWithPath[$entry.Key] = $entry.Value }
{ Normalize-RegistryKeySnapshot -Snapshot ([PSCustomObject]$propertiesWithPath) } |
Should -Throw '*must define Exists as a Boolean*'
}
}
Describe 'Test-RegistrySnapshotAgainstAllowList' {
@@ -223,6 +246,7 @@ Describe 'Test-RegistrySnapshotAgainstAllowList' {
$errors = New-Object 'System.Collections.Generic.List[string]'
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'
Exists = $true
Values = @([PSCustomObject]@{ Name = 'Enabled'; Exists = $true; Kind = 'DWord'; Data = 1 })
SubKeys = @()
}
@@ -244,6 +268,7 @@ Describe 'Test-RegistrySnapshotAgainstAllowList' {
$errors = New-Object 'System.Collections.Generic.List[string]'
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'
Exists = $true
Values = @([PSCustomObject]@{ Name = 'Bytes'; Exists = $true; Kind = 'Binary'; Data = @(1, 256) })
SubKeys = @()
}
@@ -266,6 +291,7 @@ Describe 'Test-RegistrySnapshotAgainstAllowList' {
$errors = New-Object 'System.Collections.Generic.List[string]'
$snapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example\Child'
Exists = $true
Values = @([PSCustomObject]@{ Name = 'Unlisted'; Exists = $true; Kind = 'String'; Data = 'value' })
SubKeys = @()
}
@@ -287,11 +313,13 @@ Describe 'Test-RegistrySnapshotAgainstAllowList' {
$errors = New-Object 'System.Collections.Generic.List[string]'
$unexpectedPathSnapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Unexpected'
Exists = $true
Values = @()
SubKeys = @()
}
$unexpectedValueSnapshot = [PSCustomObject]@{
Path = 'HKEY_CURRENT_USER\Software\Example'
Exists = $true
Values = @([PSCustomObject]@{ Name = 'Unexpected'; Exists = $true; Kind = 'String'; Data = 'value' })
SubKeys = @()
}
+67
View File
@@ -0,0 +1,67 @@
BeforeAll {
. (Join-Path $PSScriptRoot '..\Scripts\Helpers\Registry-PathHelpers.ps1')
function Initialize-EmptyKeyCleanupTest {
param([scriptblock]$Setup = {})
$script:testSubKey = "Software\Win11Debloat\Tests\RegistryEmptyKeyCleanup-$([guid]::NewGuid().ToString('N'))"
$script:testRoot = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($script:testSubKey)
$candidate = $script:testRoot.CreateSubKey('Candidate')
try {
& $Setup $candidate
}
finally {
$candidate.Close()
}
# Exercise the real P/Invoke and status handling, without mocks.
Remove-RegistryEmptyKeyIfExists -RootKey $script:testRoot -SubKeyPath 'Candidate'
$script:remainingKey = $script:testRoot.OpenSubKey('Candidate', $false)
}
}
Describe 'Native empty-key cleanup' {
BeforeEach {
$script:testRoot = $null
$script:remainingKey = $null
}
AfterEach {
if ($null -ne $script:remainingKey) { $script:remainingKey.Close() }
if ($null -ne $script:testRoot) {
$script:testRoot.Close()
[Microsoft.Win32.Registry]::CurrentUser.DeleteSubKeyTree($script:testSubKey, $false)
}
}
It 'deletes an empty key' {
Initialize-EmptyKeyCleanupTest
$script:remainingKey | Should -BeNullOrEmpty
}
It 'retains a key containing <Case> and its value' -ForEach @(
@{ Case = 'a named value'; ValueName = 'KeepValue' }
@{ Case = 'a default value'; ValueName = '' }
) {
Initialize-EmptyKeyCleanupTest -Setup {
param($Candidate)
$Candidate.SetValue($ValueName, 'keep', [Microsoft.Win32.RegistryValueKind]::String)
}
$script:remainingKey | Should -Not -BeNullOrEmpty
@($script:remainingKey.GetValueNames()) | Should -HaveCount 1
$script:remainingKey.GetValue($ValueName) | Should -BeExactly 'keep'
}
It 'retains a key containing a child key' {
Initialize-EmptyKeyCleanupTest -Setup {
param($Candidate)
$child = $Candidate.CreateSubKey('KeepChild')
$child.Close()
}
$script:remainingKey | Should -Not -BeNullOrEmpty
@($script:remainingKey.GetSubKeyNames()) | Should -Be @('KeepChild')
}
}
+2 -2
View File
@@ -133,12 +133,12 @@ Describe 'Get-RegistryKeySnapshot' {
Mock Split-RegistryPath { [PSCustomObject]@{ Hive = 'HKEY_CURRENT_USER'; SubKey = 'Software\Example' } }
}
It 'returns an explicit non-existent snapshot when the key is absent' {
It 'returns an explicit non-existent snapshot when key deletion is allowed' {
$root = [PSCustomObject]@{}
$root | Add-Member ScriptMethod OpenSubKey { $null }
Mock Get-RegistryRootKey { $root }
$snapshot = Get-RegistryKeySnapshot -KeyPath 'HKEY_CURRENT_USER\Software\Example'
$snapshot = Get-RegistryKeySnapshot -KeyPath 'HKEY_CURRENT_USER\Software\Example' -AllowDeleteKey:$true
$snapshot.Exists | Should -BeFalse
$snapshot.Values | Should -HaveCount 0
}
@@ -11,6 +11,9 @@ Describe 'Convert-RegistryValueKindFromBackup' {
It '<Case>' -ForEach @(
@{ Case = 'parses registry kinds case-insensitively'; KindName = 'dword'; Expected = [Microsoft.Win32.RegistryValueKind]::DWord; ExpectedError = $null }
@{ Case = 'rejects an invalid registry kind'; KindName = 'NotARegistryValueKind'; Expected = $null; ExpectedError = 'Unsupported registry value kind in backup: NotARegistryValueKind' }
@{ Case = 'rejects an undefined numeric kind'; KindName = '99'; Expected = $null; ExpectedError = 'Unsupported registry value kind in backup: 99' }
@{ Case = 'rejects Unknown'; KindName = 'Unknown'; Expected = $null; ExpectedError = 'Unsupported registry value kind in backup: Unknown' }
@{ Case = 'rejects None'; KindName = 'None'; Expected = $null; ExpectedError = 'Unsupported registry value kind in backup: None' }
) {
if ($ExpectedError) {
{ Convert-RegistryValueKindFromBackup -KindName $KindName } | Should -Throw $ExpectedError
+93 -6
View File
@@ -26,7 +26,8 @@ Describe 'Import-RegistryBackup' {
It 'parses and normalizes registry snapshots from a real backup structure' {
Mock Test-UserNameMatch { $true }
Mock Test-RegistryBackupMatchesSelectedFeatures { @() }
Mock Get-RegistryBackupValidationPlanMap { @{} }
Mock Test-RegistryBackupAgainstAllowList { @() }
$result = Import-RegistryBackup -FilePath (Join-Path $script:JsonFixturePath 'RegistryBackup.RealStructure.json')
@@ -42,7 +43,7 @@ Describe 'Import-RegistryBackup' {
$result.RegistryKeys[1].Values[0].Name | Should -Be 'EnableTransparency'
$result.RegistryKeys[1].Values[0].Kind | Should -Be 'DWord'
$result.RegistryKeys[1].Values[0].Data | Should -Be 0
Should -Invoke Test-RegistryBackupMatchesSelectedFeatures -Times 1 -Exactly
Should -Invoke Test-RegistryBackupAgainstAllowList -Times 1 -Exactly
}
It 'rejects <Case>' -ForEach @(
@@ -59,7 +60,8 @@ Describe 'Import-RegistryBackup' {
Describe 'ConvertTo-NormalizedRegistryBackup' {
BeforeEach {
$script:Features = @{ Example = [PSCustomObject]@{ FeatureId = 'Example'; RegistryKey = 'Example.reg' } }
Mock Test-RegistryBackupMatchesSelectedFeatures { @() }
Mock Get-RegistryBackupValidationPlanMap { @{} }
Mock Test-RegistryBackupAgainstAllowList { @() }
Mock Write-Error {}
}
@@ -76,7 +78,7 @@ Describe 'ConvertTo-NormalizedRegistryBackup' {
$result.SelectedFeatures -is [array] | Should -BeTrue
$result.SelectedFeatures | Should -Be 'Example'
$result.SelectedUndoFeatures | Should -BeNullOrEmpty
Should -Invoke Test-RegistryBackupMatchesSelectedFeatures -Times 1 -Exactly
Should -Invoke Test-RegistryBackupAgainstAllowList -Times 1 -Exactly
}
It 'aggregates invalid metadata and does not attempt allow-list validation without feature IDs' {
@@ -85,7 +87,7 @@ Describe 'ConvertTo-NormalizedRegistryBackup' {
{ ConvertTo-NormalizedRegistryBackup -Backup $backup } | Should -Throw 'Validation failed with * errors. See console output for details.'
Should -Invoke Write-Error -Times 1 -Exactly
Should -Invoke Test-RegistryBackupMatchesSelectedFeatures -Times 0 -Exactly
Should -Invoke Test-RegistryBackupAgainstAllowList -Times 0 -Exactly
}
It 'reports an invalid user target as a validation failure' {
@@ -117,7 +119,17 @@ Describe 'Restore-RegistryBackupState' {
Mock Restore-RegistryKeySnapshot {}
Mock Invoke-WithLoadedRestoreHive {}
Mock Write-Host {}
$script:backup = [PSCustomObject]@{ Target = 'CurrentUser:Tester'; RegistryKeys = @([PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\One' }, [PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Two' }) }
Mock Test-UserNameMatch { $true }
Mock Write-Error {}
Mock Get-RegistryBackupValidationPlanMap { @{} }
Mock Test-RegistryBackupAgainstAllowList { @() }
$script:backup = [PSCustomObject]@{
Version = '1.0'; BackupType = 'RegistryState'; Target = 'CurrentUser:Tester'; SelectedFeatures = @('Example')
RegistryKeys = @(
[PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\One'; Exists = $true; Values = @(); SubKeys = @() }
[PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Two'; Exists = $true; Values = @(); SubKeys = @() }
)
}
}
It 'restores every root snapshot directly for the current user' {
@@ -148,4 +160,79 @@ Describe 'Restore-RegistryBackupState' {
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'rejects a malformed later root before any writes or hive loading for <Target>' -ForEach @(
@{ Target = 'CurrentUser:Tester'; InvalidKind = $false; ExpectedError = '*is not directly below parent*' }
@{ Target = 'DefaultUserProfile'; InvalidKind = $false; ExpectedError = '*is not directly below parent*' }
@{ Target = 'User:Alice'; InvalidKind = $false; ExpectedError = '*is not directly below parent*' }
@{ Target = 'DefaultUserProfile'; InvalidKind = $true; ExpectedError = '*Unsupported registry value kind*' }
) {
Mock Test-TargetUserName { [PSCustomObject]@{ IsValid = $true } }
$first = [PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\One'; Exists = $true; Values = @(); SubKeys = @() }
$second = [PSCustomObject]@{ Path = 'HKEY_CURRENT_USER\Software\Two'; Exists = $true; Values = @(); SubKeys = @() }
if ($InvalidKind) {
$second.Values = @([PSCustomObject]@{ Name = 'Setting'; Exists = $true; Kind = '99'; Data = 'data' })
}
else {
$second.SubKeys = @([PSCustomObject]@{ Path = $first.Path; Exists = $true; Values = @(); SubKeys = @() })
}
$script:backup.Target = $Target
$script:backup.RegistryKeys = @($first, $second)
{ Restore-RegistryBackupState -Backup $script:backup } | Should -Throw $ExpectedError
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
Should -Invoke Invoke-WithLoadedRestoreHive -Times 0 -Exactly
}
It 'rejects conflicting duplicate root snapshots before restore' {
$script:backup.RegistryKeys = @($script:backup.RegistryKeys[0], $script:backup.RegistryKeys[0])
{ Restore-RegistryBackupState -Backup $script:backup } | Should -Throw '*duplicate registry root path*'
Should -Invoke Restore-RegistryKeySnapshot -Times 0 -Exactly
}
}
Describe 'Restore executable warning dialog' {
BeforeAll {
Add-Type -AssemblyName PresentationFramework
. (Join-Path $PSScriptRoot '..\Scripts\GUI\Show-MessageBox.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\GUI\Show-RestoreBackupDialog.ps1')
. (Join-Path $PSScriptRoot '..\Scripts\GUI\Show-RestoreBackupWindow.ps1')
}
BeforeEach {
$script:Params = @{}
Mock Write-Host {}
Mock Show-RestoreBackupDialog {
@{ Result = 'RestoreRegistry'; Backup = [PSCustomObject]@{ Target = 'DefaultUserProfile' } }
}
Mock Restore-RegistryBackupState {
param($Backup, $ConfirmUntrustedValues)
$approved = & $ConfirmUntrustedValues @(
[PSCustomObject]@{ Path = 'HKEY_CLASSES_ROOT\test\shell\open\command'; Name = ''; Kind = 'String'; Data = 'custom.exe /argument' }
)
[PSCustomObject]@{ Result = $approved }
}
}
It 'offers cancellation by default and includes source and executable details' {
Mock Show-MessageBox { 'Cancel' }
$result = Show-RestoreBackupWindow
$result.RestoredRegistry | Should -BeFalse
Should -Invoke Show-MessageBox -Times 1 -Exactly -ParameterFilter {
$DefaultResult -eq 'Cancel' -and $Button -eq 'OKCancel' -and $Icon -eq 'Warning' -and
$Message -like '*Do not restore registry backups obtained from unofficial sources*' -and
$Message -like '*HKEY_CLASSES_ROOT\test\shell\open\command*' -and
$Message -like '*String*' -and $Message -like '*custom.exe /argument*'
}
}
It 'continues only when the warning is explicitly accepted' {
Mock Show-MessageBox { 'OK' }
$result = Show-RestoreBackupWindow
$result.RestoredRegistry | Should -BeTrue
Should -Invoke Show-MessageBox -Times 1 -Exactly -ParameterFilter { $DefaultResult -eq 'Cancel' }
}
}
@@ -0,0 +1,31 @@
{
"Version": "1.0",
"BackupType": "RegistryState",
"CreatedAt": "2026-10-21T12:00:00+02:00",
"CreatedBy": "Win11Debloat warning prompt test",
"ComputerName": "TOMAHAWK-V2",
"Target": "CurrentUser:jeffr",
"SelectedFeatures": [
"DisableGameBarIntegration"
],
"SelectedUndoFeatures": [
],
"RegistryKeys": [
{
"Path": "HKEY_CLASSES_ROOT\\ms-gamebar\\shell\\open\\command",
"Exists": true,
"Values": [
{
"Name": "",
"Exists": true,
"Kind": "String",
"Data": "cmd.exe /d /c echo Win11Debloat restore warning test"
}
],
"SubKeys": [
]
}
]
}