Restore managed registry values after failed writes
Config Central CI Config Central passed all CI integrity checks.
Beffroi/config-central/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-10-19 16:04:49 +02:00
parent 087609fb5b
commit f59ce6bf8f
6 changed files with 176 additions and 8 deletions

View File

@ -144,3 +144,4 @@ open until it is run on disposable machines with the required account setups.
- [x] Hide Ontime clock seconds and slow background blink to a three-second fade with a steady reduced-motion fallback.
- [x] Explain first-launch/registry-mode steps for missing MPC-HC capture settings and key-creation failures without suppressing the underlying error.
- [x] Continue MPC-HC registry writes after individual failures, warn with key names on partial success, and fail only when no values were written; preserve diagnostics and retry state.
- [x] Back up registry value types and presence; restore failed writes or the full managed declaration on operation failure, and report incomplete rollback; verified with mocked rollback and state-failure tests.

View File

@ -157,5 +157,14 @@ cc apply -ForceConfigs
Forced file and hosts updates are backed up under
`%LOCALAPPDATA%\ConfigCentral\backups`. Registry backups contain only the values
managed by the declaration. Inspect and commit each source file separately so no
managed by the declaration, including each value's original type and whether it
existed. Failed individual writes are restored from that backup; successful
writes remain applied when the result is a warning. If the registry operation
fails, all its managed values are restored, including removal of values that
were originally absent. Unrelated values and key containers are left alone.
Rollback errors are reported explicitly with the retained backup path.
This automatic failure recovery is separate from the manual `cc restore`
command, which still does not support registry backups.
Inspect and commit each source file separately so no
history, credentials, tokens, or machine-specific paths enter Git.

View File

@ -190,6 +190,48 @@ function Get-AdapterPlan {
[pscustomobject]@{ action = $action; reason = $reason; desired = $desired; desiredHash = $desiredHash; currentHash = $current.hash; requiresAdmin = ($Config.mode -eq 'hosts-block') }
}
function Get-RegistryBackup {
param([string]$Root, $Declaration)
$entries = foreach ($entry in $Declaration.values) {
$path = if ($entry.path) { Join-Path $Root $entry.path } else { $Root }
$key = if (Test-Path -LiteralPath $path -ErrorAction Stop) { Get-Item -LiteralPath $path -ErrorAction Stop } else { $null }
try {
$exists = $null -ne $key -and ($key.GetValueNames() -contains $entry.name)
$originalValue = $null
if ($exists) { $originalValue = $key.GetValue($entry.name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) }
[pscustomobject]@{
path = $entry.path; name = $entry.name; exists = $exists
type = if ($exists) { [string]$key.GetValueKind($entry.name) } else { $null }
value = $originalValue
}
}
finally { if ($null -ne $key) { $key.Close() } }
}
[pscustomobject]@{ schemaVersion = 1; root = $Root; values = @($entries) }
}
function Restore-RegistryDeclaration {
param([string]$Root, $Backup, $Only = $null)
$errors = [Collections.Generic.List[string]]::new()
foreach ($entry in $Backup.values) {
if ($null -ne $Only -and -not @($Only | Where-Object { $_.path -eq $entry.path -and $_.name -eq $entry.name }).Count) { continue }
try {
$path = if ($entry.path) { Join-Path $Root $entry.path } else { $Root }
$current = Get-RegistryBackup -Root $Root -Declaration ([pscustomobject]@{ values = @($entry) })
$actual = $current.values[0]
if (-not $entry.exists) {
if ($actual.exists) { Remove-ItemProperty -LiteralPath $path -Name $entry.name -ErrorAction Stop }
}
elseif (-not $actual.exists -or $actual.type -ne $entry.type -or (Get-ObjectHash $actual.value) -ne (Get-ObjectHash $entry.value)) {
$result = Set-RegistryDeclaration -Root $Root -Declaration ([pscustomobject]@{ values = @($entry) })
if ($result.failures.Count) { throw $result.failures[0].error }
}
}
catch { $errors.Add("$($entry.path)\$($entry.name): $($_.Exception.Message)") }
}
if ($errors.Count) { throw "Registry rollback incomplete: $($errors -join '; ')" }
}
function Set-RegistryDeclaration {
param([string]$Root, $Declaration)
# Standard x86 and x64 MPC-HC share this HKCU settings store.
@ -205,8 +247,9 @@ function Set-RegistryDeclaration {
$value = switch ($entry.type) {
'DWord' { if ($entry.value -lt 0) { [int32]$entry.value } else { [uint32]$entry.value } }
'QWord' { if ($entry.value -lt 0) { [int64]$entry.value } else { [uint64]$entry.value } }
'Binary' { [byte[]]@($entry.value) }
'MultiString' { [string[]]@($entry.value) }
'Binary' { ,([byte[]]@($entry.value)) }
'None' { ,([byte[]]@($entry.value)) }
'MultiString' { ,([string[]]@($entry.value)) }
default { [string]$entry.value }
}
[void](New-ItemProperty -LiteralPath $path -Name $entry.name -PropertyType $entry.type -Value $value -Force -ErrorAction Stop)
@ -240,4 +283,4 @@ function Set-HostsBlockContent {
(($output -join [Environment]::NewLine) + [Environment]::NewLine)
}
Export-ModuleMember -Function Get-ObjectHash, Read-IniValues, Get-IniSnapshot, Merge-IniFile, Read-RegistryDeclaration, Get-RegistrySnapshot, Get-HostsDeclaration, Get-HostsBlock, Get-AdapterPlan, Set-RegistryDeclaration, Set-HostsBlockContent
Export-ModuleMember -Function Get-ObjectHash, Read-IniValues, Get-IniSnapshot, Merge-IniFile, Read-RegistryDeclaration, Get-RegistrySnapshot, Get-RegistryBackup, Restore-RegistryDeclaration, Get-HostsDeclaration, Get-HostsBlock, Get-AdapterPlan, Set-RegistryDeclaration, Set-HostsBlockContent

View File

@ -236,6 +236,9 @@ function Invoke-ConfigOperation {
$backup = $null
$temporary = $null
$registryWarning = $null
$registryTouched = $false
$registryBackup = $null
$previousRecord = if ($State.Contains('configs') -and $State.configs.Contains($Operation.name)) { $State.configs[$Operation.name] } else { $null }
$deployedHash = $Operation.sourceHash
try {
if ($Operation.action -ne 'Adopt') {
@ -243,7 +246,9 @@ function Invoke-ConfigOperation {
$folder = Join-Path $Paths.Backups $Operation.name
[void](New-Item -ItemType Directory -Path $folder -Force)
$backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).json"
(Get-RegistrySnapshot -Root $Operation.target -Declaration $Operation.desired).values | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $backup -Encoding utf8NoBOM
$registryBackup = Get-RegistryBackup -Root $Operation.target -Declaration $Operation.desired
Write-JsonAtomic -Path $backup -Value $registryBackup
$registryTouched = $true
$writes = Set-RegistryDeclaration -Root $Operation.target -Declaration $Operation.desired
if ($writes.failures.Count -gt 0) {
# Keep detailed causes beside the backup; the terminal gets only key names.
@ -251,6 +256,7 @@ function Invoke-ConfigOperation {
$failedKeys = @($writes.failures | ForEach-Object { if ($_.path) { "$($_.path)\$($_.name)" } else { $_.name } })
$registryWarning = "Could not write registry key(s): $($failedKeys -join ', ')"
if ($writes.written -eq 0) { throw $registryWarning }
Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup -Only $writes.failures
$deployedHash = (Get-RegistrySnapshot -Root $Operation.target -Declaration $Operation.desired).hash
}
}
@ -280,7 +286,20 @@ function Invoke-ConfigOperation {
return [pscustomobject]@{ name = $Operation.name; status = 'Succeeded'; message = if ($Operation.action -eq 'Adopt') { 'Adopted matching managed values' } elseif ($backup) { "Deployed; backup: $backup" } else { 'Deployed' } }
}
catch {
return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; message = $_.Exception.Message }
$message = $_.Exception.Message
if ($registryTouched) {
if ($null -ne $previousRecord) { $State.configs[$Operation.name] = $previousRecord }
elseif ($State.Contains('configs')) { $State.configs.Remove($Operation.name) }
try {
Restore-RegistryDeclaration -Root $Operation.target -Backup $registryBackup
Write-JsonAtomic -Path $Paths.State -Value $State
$message += '; previous managed registry values restored'
}
catch {
$message += "; rollback incomplete. Backup: $backup. $($_.Exception.Message)"
}
}
return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; message = $message }
}
finally { if ($temporary) { Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue } }
}

View File

@ -174,3 +174,68 @@ Describe 'Partial registry writes' {
}
}
}
Describe 'Registry rollback' {
It 'restores original types selectively and removes originally absent values' {
InModuleScope Adapters {
$backup = @{ values = @(
@{ path = ''; name = 'Volume'; exists = $true; type = 'DWord'; value = -1 },
@{ path = ''; name = 'NewValue'; exists = $false; type = $null; value = $null },
@{ path = ''; name = 'Successful'; exists = $true; type = 'String'; value = 'old' }
) }
Mock Get-RegistryBackup { @{ values = @(@{ exists = $true; type = 'String'; value = 'changed' }) } }
Mock Set-RegistryDeclaration { @{ written = 1; failures = @() } }
Mock Remove-ItemProperty {}
Restore-RegistryDeclaration -Root TestRoot -Backup $backup -Only @($backup.values[0], $backup.values[1])
Should -Invoke Set-RegistryDeclaration -Times 1 -Exactly -ParameterFilter { $Declaration.values[0].name -eq 'Volume' -and $Declaration.values[0].type -eq 'DWord' -and $Declaration.values[0].value -eq -1 }
Should -Invoke Remove-ItemProperty -Times 1 -Exactly -ParameterFilter { $Name -eq 'NewValue' }
}
}
It 'avoids rewriting unchanged values after a denied write' {
InModuleScope Adapters {
$entry = @{ path = ''; name = 'HWAcceleration'; exists = $true; type = 'DWord'; value = 1 }
Mock Get-RegistryBackup { @{ values = @(@{ exists = $true; type = 'DWord'; value = 1 }) } }
Mock Set-RegistryDeclaration { throw 'Access denied' }
Restore-RegistryDeclaration -Root TestRoot -Backup @{ values = @($entry) }
Should -Invoke Set-RegistryDeclaration -Times 0 -Exactly
}
}
It 'continues restoring remaining values when one rollback fails' {
InModuleScope Adapters {
$backup = @{ values = @(
@{ path = ''; name = 'First'; exists = $true; type = 'String'; value = 'old' },
@{ path = ''; name = 'Second'; exists = $true; type = 'String'; value = 'old' }
) }
Mock Get-RegistryBackup { @{ values = @(@{ exists = $false }) } }
Mock Set-RegistryDeclaration { @{ written = 0; failures = @(@{ error = 'Access denied' }) } }
{ Restore-RegistryDeclaration -Root TestRoot -Backup $backup } | Should -Throw '*rollback incomplete*'
Should -Invoke Set-RegistryDeclaration -Times 2 -Exactly
}
}
It 'backs up unexpanded values with their original types and presence' {
InModuleScope Adapters {
Mock Test-Path { $true }
Mock Get-Item {
$key = [pscustomobject]@{}
$key | Add-Member ScriptMethod GetValueNames { @('Existing') }
$key | Add-Member ScriptMethod GetValueKind { param($name) 'ExpandString' }
$key | Add-Member ScriptMethod GetValue {
param($name, $default, $options)
if ($options -ne [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) { throw 'Expanded value' }
'%USERPROFILE%\original'
}
$key | Add-Member ScriptMethod Close {}
$key
}
$backup = Get-RegistryBackup -Root TestRoot -Declaration @{ values = @(
@{ path = ''; name = 'Existing' }, @{ path = ''; name = 'Missing' }
) }
$backup.values[0].type | Should -Be 'ExpandString'
$backup.values[0].value | Should -Be '%USERPROFILE%\original'
$backup.values[1].exists | Should -BeFalse
}
}
}

View File

@ -110,7 +110,7 @@ Describe 'Configuration deployment' {
}
It 'keeps the original registry failure when no temporary file was created' {
Mock Get-RegistrySnapshot { throw 'Registry access denied' } -ModuleName Configs
Mock Get-RegistryBackup { throw 'Registry access denied' } -ModuleName Configs
$operation = [pscustomobject]@{
name = 'registry-test'; action = 'Update'; mode = 'registry'
target = 'HKCU:\Software\Test'; sourceHash = 'new'; desired = @{ values = @() }
@ -132,6 +132,8 @@ Describe 'Configuration deployment' {
}
It 'reports partial registry writes as warnings and records actual deployed state' {
Mock Get-RegistryBackup { @{ values = @(); schemaVersion = 1 } } -ModuleName Configs
Mock Restore-RegistryDeclaration {} -ModuleName Configs
Mock Get-RegistrySnapshot { [pscustomobject]@{ values = @{ Volume = 80 }; hash = 'partial-state' } } -ModuleName Configs
Mock Set-RegistryDeclaration {
[pscustomobject]@{ written = 1; failures = @([pscustomobject]@{ path = ''; name = 'HWAcceleration'; error = 'Access denied' }) }
@ -140,6 +142,7 @@ Describe 'Configuration deployment' {
$result = Invoke-ConfigOperation -Operation $operation -Paths $paths -State $state
$result.status | Should -Be 'Warning'
$result.message | Should -Be 'Could not write registry key(s): HWAcceleration'
Should -Invoke Restore-RegistryDeclaration -ModuleName Configs -Times 1 -Exactly -ParameterFilter { $Only.Count -eq 1 -and $Only[0].name -eq 'HWAcceleration' }
$state.configs['mpc-hc-settings'].deployedHash | Should -Be 'partial-state'
$state.configs['mpc-hc-settings'].sourceHash | Should -Be 'desired-state'
$details = Get-Content ($state.configs['mpc-hc-settings'].lastBackup + '.write-results.json') -Raw | ConvertFrom-Json
@ -147,6 +150,8 @@ Describe 'Configuration deployment' {
}
It 'fails when no registry values could be written and leaves deployment state untouched' {
Mock Get-RegistryBackup { @{ values = @(); schemaVersion = 1 } } -ModuleName Configs
Mock Restore-RegistryDeclaration {} -ModuleName Configs
Mock Get-RegistrySnapshot { [pscustomobject]@{ values = @{}; hash = 'old-state' } } -ModuleName Configs
Mock Set-RegistryDeclaration {
[pscustomobject]@{ written = 0; failures = @([pscustomobject]@{ path = ''; name = 'HWAcceleration'; error = 'Access denied' }) }
@ -154,10 +159,36 @@ Describe 'Configuration deployment' {
$operation = [pscustomobject]@{ name = 'mpc-hc-settings'; action = 'Update'; mode = 'registry'; target = 'TestRoot'; sourceHash = 'desired-state'; desired = @{ values = @() } }
$result = Invoke-ConfigOperation -Operation $operation -Paths $paths -State $state
$result.status | Should -Be 'Failed'
$result.message | Should -Be 'Could not write registry key(s): HWAcceleration'
$result.message | Should -Be 'Could not write registry key(s): HWAcceleration; previous managed registry values restored'
Should -Invoke Restore-RegistryDeclaration -ModuleName Configs -Times 1 -Exactly -ParameterFilter { $null -eq $Only }
$state.configs.ContainsKey('mpc-hc-settings') | Should -BeFalse
}
It 'rolls back all values and prior state when saving deployment state fails' {
Mock Get-RegistryBackup { @{ values = @(); schemaVersion = 1 } } -ModuleName Configs
Mock Set-RegistryDeclaration { @{ written = 2; failures = @() } } -ModuleName Configs
Mock Restore-RegistryDeclaration {} -ModuleName Configs
Mock Write-JsonAtomic { throw 'Disk full' } -ModuleName Configs -ParameterFilter { $Path -like '*state.json' }
$state.configs['mpc-hc-settings'] = @{ deployedHash = 'original' }
$operation = [pscustomobject]@{ name = 'mpc-hc-settings'; action = 'Update'; mode = 'registry'; target = 'TestRoot'; sourceHash = 'desired'; desired = @{ values = @() } }
$result = Invoke-ConfigOperation -Operation $operation -Paths $paths -State $state
$result.status | Should -Be 'Failed'
$result.message | Should -Match 'Disk full'
Should -Invoke Restore-RegistryDeclaration -ModuleName Configs -Times 1 -Exactly -ParameterFilter { $null -eq $Only }
$state.configs['mpc-hc-settings'].deployedHash | Should -Be 'original'
}
It 'reports incomplete rollback with the retained backup path' {
Mock Get-RegistryBackup { @{ values = @(); schemaVersion = 1 } } -ModuleName Configs
Mock Set-RegistryDeclaration { throw 'Write failed' } -ModuleName Configs
Mock Restore-RegistryDeclaration { throw 'Access denied' } -ModuleName Configs
$operation = [pscustomobject]@{ name = 'mpc-hc-settings'; action = 'Update'; mode = 'registry'; target = 'TestRoot'; sourceHash = 'desired'; desired = @{ values = @() } }
$result = Invoke-ConfigOperation -Operation $operation -Paths $paths -State $state
$result.status | Should -Be 'Failed'
$result.message | Should -Match 'rollback incomplete. Backup: .*json.*Access denied'
$result.message | Should -Not -Match 'values restored'
}
It 'refuses unsafe automatic restoration of registry and hosts backups' {
$registryState = @{ configs = @{ 'mpc-hc-settings' = @{ mode = 'registry'; target = 'HKCU:\Software\MPC-HC\MPC-HC' } } }
{ Restore-ConfigBackup -Name mpc-hc-settings -Paths $paths -State $registryState } | Should -Throw '*not supported for registry*'