config-central/src/Configs.psm1

297 lines
18 KiB
PowerShell

Set-StrictMode -Version Latest
function Get-UserPathMap {
param($Settings)
$map = [ordered]@{}
$stored = if ($null -ne $Settings -and $Settings.Contains('userPaths')) { $Settings.userPaths } else { @{} }
foreach ($name in @('APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PROGRAMDATA', 'SYSTEMROOT')) {
$value = if ($stored.Contains($name)) { [string]$stored[$name] } else { [Environment]::GetEnvironmentVariable($name) }
if (-not [string]::IsNullOrWhiteSpace($value)) { $map[$name] = $value }
}
return $map
}
function Resolve-ConfigTarget {
param([Parameter(Mandatory)][string]$Target, [Parameter(Mandatory)]$PathMap)
$unknown = [regex]::Matches($Target, '%([^%]+)%') | ForEach-Object { $_.Groups[1].Value } | Where-Object { $_ -notin $PathMap.Keys }
if ($unknown) { throw "Unsupported path variable(s) in '$Target': $($unknown -join ', ')." }
$resolved = $Target
foreach ($name in $PathMap.Keys) { $resolved = $resolved.Replace("%$name%", [string]$PathMap[$name], [System.StringComparison]::OrdinalIgnoreCase) }
$full = [System.IO.Path]::GetFullPath($resolved)
if (-not [System.IO.Path]::IsPathFullyQualified($full)) { throw "Config target must be absolute: '$Target'." }
return $full
}
function Resolve-ConfigSource {
param([Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)][string]$Source)
if ([System.IO.Path]::IsPathFullyQualified($Source)) { throw "Config source must be repository-relative: '$Source'." }
$configRoot = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot 'configs'))
$candidate = [System.IO.Path]::GetFullPath((Join-Path $RepositoryRoot $Source))
$prefix = $configRoot.TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar) + [System.IO.Path]::DirectorySeparatorChar
if (-not $candidate.StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)) { throw "Config source escapes configs/: '$Source'." }
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { throw "Config source does not exist: '$Source'." }
return $candidate
}
function Get-FileHashValue {
param([Parameter(Mandatory)][string]$Path)
(Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
function Get-ConfigPlan {
param([Parameter(Mandatory)]$Configs, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$State, [Parameter(Mandatory)]$Settings)
if (-not $State.Contains('configs')) { $State.configs = [ordered]@{} }
$pathMap = Get-UserPathMap -Settings $Settings
$destinations = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$plan = [System.Collections.Generic.List[object]]::new()
foreach ($config in @($Configs)) {
$source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source
$target = if ($config.mode -eq 'registry') { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap }
if (-not $destinations.Add($target)) { throw "Multiple configs resolve to '$target'." }
$record = if ($State.configs.Contains($config.name)) { $State.configs[$config.name] } else { $null }
if ($config.mode -eq 'copy') {
$sourceHash = Get-FileHashValue -Path $source
$targetExists = Test-Path -LiteralPath $target -PathType Leaf
$targetHash = if ($targetExists) { Get-FileHashValue -Path $target } else { $null }
if (-not $targetExists -and $null -eq $record) { $action = 'Create'; $reason = 'Destination is absent' }
elseif ($null -eq $record) { $action = 'Conflict'; $reason = 'Existing destination is not managed' }
elseif (-not $targetExists) { $action = 'Conflict'; $reason = 'Managed destination was deleted locally' }
elseif ($targetHash -ne [string]$record.deployedHash) { $action = 'Conflict'; $reason = 'Managed destination was edited locally' }
elseif ($targetHash -eq $sourceHash) { $action = 'None'; $reason = 'Content is current' }
else { $action = 'Update'; $reason = 'Repository content changed' }
$desired = $null
$requiresAdmin = $false
}
else {
$adapterPlan = Get-AdapterPlan -Config $config -Source $source -Target $target -Record $record
$sourceHash = $adapterPlan.desiredHash
$targetHash = $adapterPlan.currentHash
$action = $adapterPlan.action
$reason = $adapterPlan.reason
$desired = $adapterPlan.desired
$requiresAdmin = [bool]$adapterPlan.requiresAdmin
}
$plan.Add([pscustomobject]@{
kind = 'config'; name = $config.name; action = $action; reason = $reason
source = $source; target = $target; sourceHash = $sourceHash; targetHash = $targetHash
mode = $config.mode; desired = $desired; requiresAdmin = $requiresAdmin
requiresPackage = if ($config.PSObject.Properties['requiresPackage']) { [string]$config.requiresPackage } else { $null }
})
}
return @($plan)
}
function Get-ConfigLocations {
param(
[Parameter(Mandatory)]$Configs,
[Parameter(Mandatory)][string]$RepositoryRoot,
[Parameter(Mandatory)]$Settings,
[string]$Name
)
$pathMap = Get-UserPathMap -Settings $Settings
$selected = @($Configs)
if (-not [string]::IsNullOrWhiteSpace($Name)) {
$selected = @($selected | Where-Object { $_.name -eq $Name })
if ($selected.Count -eq 0) { throw "Unknown config '$Name'." }
}
$locations = [System.Collections.Generic.List[object]]::new()
foreach ($config in $selected) {
$source = Resolve-ConfigSource -RepositoryRoot $RepositoryRoot -Source $config.source
$target = if ($config.mode -eq 'registry') { [string]$config.target } else { Resolve-ConfigTarget -Target $config.target -PathMap $pathMap }
$targetExists = [bool](Test-Path -LiteralPath $target -ErrorAction SilentlyContinue)
$locations.Add([pscustomobject]@{
kind = 'config'; name = [string]$config.name
status = if ($targetExists) { 'Present' } else { 'Missing' }
message = "Repository: $source | Computer: $target"
mode = [string]$config.mode; source = $source; target = $target
sourceExists = $true; targetExists = $targetExists
})
}
return @($locations)
}
function Export-ConfigCapture {
param(
[Parameter(Mandatory)]$Configs,
[Parameter(Mandatory)][string]$RepositoryRoot,
[Parameter(Mandatory)]$Settings,
[Parameter(Mandatory)][string]$Machine,
[string]$Name,
[string]$OutputPath
)
if ([string]::IsNullOrWhiteSpace($OutputPath)) {
$documents = [Environment]::GetFolderPath([Environment+SpecialFolder]::MyDocuments)
if ([string]::IsNullOrWhiteSpace($documents)) {
$pathMap = Get-UserPathMap -Settings $Settings
if (-not $pathMap.Contains('USERPROFILE')) { throw 'The Documents directory could not be resolved.' }
$documents = Join-Path $pathMap.USERPROFILE 'Documents'
}
$captureName = "$Machine-$([DateTimeOffset]::Now.ToString('yyyyMMdd-HHmmss'))"
$OutputPath = Join-Path (Join-Path $documents 'ConfigCentral\captures') $captureName
}
$captureRoot = [IO.Path]::GetFullPath($OutputPath)
if (Test-Path -LiteralPath $captureRoot) { throw "Capture destination already exists: '$captureRoot'." }
[void](New-Item -ItemType Directory -Path $captureRoot -Force)
$selectedConfigs = @($Configs)
if (-not [string]::IsNullOrWhiteSpace($Name)) {
$selectedConfigs = @($selectedConfigs | Where-Object name -eq $Name)
if ($selectedConfigs.Count -eq 0) { throw "Unknown config '$Name'." }
}
$locations = @(Get-ConfigLocations -Configs $selectedConfigs -RepositoryRoot $RepositoryRoot -Settings $Settings)
$operations = [Collections.Generic.List[object]]::new()
foreach ($config in $selectedConfigs) {
$location = $locations | Where-Object name -eq $config.name | Select-Object -First 1
if (-not $location.targetExists) {
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Missing'; message = "Computer source is absent: $($location.target)" })
continue
}
if ($config.mode -eq 'copy') {
$relative = ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar)
$destination = Join-Path $captureRoot $relative
$status = 'Captured'
}
elseif ($config.mode -eq 'registry' -and $config.name -eq 'mpc-hc-settings') {
$destination = Join-Path $captureRoot 'review\mpc-hc-settings\settings.json'
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force)
& (Join-Path $RepositoryRoot 'tools\Export-MpcHcSettings.ps1') -OutputPath $destination
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Review'; message = $destination })
continue
}
elseif ($config.name -eq 'nextcloud-settings') {
$desired = Read-IniValues -Path $location.source
$desiredCount = @($desired.Keys | ForEach-Object { $desired[$_].Count } | Measure-Object -Sum).Sum
if (-not $desiredCount) {
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Excluded'; message = 'No allowlisted Nextcloud keys are declared; complete account config was not captured.' })
continue
}
$snapshot = Get-IniSnapshot -Path $location.target -Desired $desired
$relative = ([string]$config.source).Replace('/', [IO.Path]::DirectorySeparatorChar)
$destination = Join-Path $captureRoot $relative
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force)
$lines = [Collections.Generic.List[string]]::new()
$lines.Add('; Allowlisted Nextcloud preferences captured without account data.')
foreach ($section in $desired.Keys) {
$presentKeys = @($desired[$section].Keys | Where-Object { $null -ne $snapshot.values[$section][$_] })
if ($presentKeys.Count -eq 0) { continue }
if ($section) { $lines.Add("[$section]") }
foreach ($key in $presentKeys) { $lines.Add("$key=$($snapshot.values[$section][$key])") }
}
[IO.File]::WriteAllLines($destination, $lines, [Text.UTF8Encoding]::new($false))
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = 'Captured'; message = "$destination ($($snapshot.present) allowlisted values; account data excluded)" })
continue
}
else {
$fileName = if ($config.mode -eq 'hosts-block') { 'hosts' } else { [IO.Path]::GetFileName($location.target) }
$destination = Join-Path $captureRoot "review\$($config.name)\$fileName"
$status = 'Review'
}
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $destination) -Force)
Copy-Item -LiteralPath $location.target -Destination $destination
$operations.Add([pscustomobject]@{ kind = 'config'; name = $config.name; status = $status; message = $destination })
}
$readme = @(
'Config Central configuration capture',
'',
'Files below configs/ retain their repository-relative paths.',
'Files below review/ are raw exports and must be curated before committing.',
'The complete Nextcloud configuration is never captured because it may contain credentials.'
) -join [Environment]::NewLine
[IO.File]::WriteAllText((Join-Path $captureRoot 'README.txt'), $readme + [Environment]::NewLine, [Text.UTF8Encoding]::new($false))
$manifest = [ordered]@{
schemaVersion = 1
machine = $Machine
capturedAt = [DateTimeOffset]::Now.ToString('o')
repositoryRevision = Get-RepositoryRevision -RepositoryRoot $RepositoryRoot
operations = @($operations)
}
[IO.File]::WriteAllText((Join-Path $captureRoot 'capture.json'), ($manifest | ConvertTo-Json -Depth 8), [Text.UTF8Encoding]::new($false))
return [pscustomobject]@{ path = $captureRoot; operations = @($operations) }
}
function Backup-ConfigTarget {
param($Operation, $Paths)
if (-not (Test-Path -LiteralPath $Operation.target -PathType Leaf)) { return $null }
$folder = Join-Path $Paths.Backups $Operation.name
[void](New-Item -ItemType Directory -Path $folder -Force)
$backup = Join-Path $folder "$([DateTimeOffset]::UtcNow.ToString('yyyyMMddTHHmmssfffZ')).bak"
Copy-Item -LiteralPath $Operation.target -Destination $backup -Force
return $backup
}
function Invoke-ConfigOperation {
param([Parameter(Mandatory)]$Operation, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State, [switch]$Force)
if ($Operation.action -eq 'None') {
return [pscustomobject]@{ name = $Operation.name; status = 'Unchanged'; message = $Operation.reason }
}
if ($Operation.action -eq 'Conflict' -and -not $Force) {
return [pscustomobject]@{ name = $Operation.name; status = 'Conflict'; message = "$($Operation.reason); use -ForceConfigs to back up and replace it" }
}
$backup = $null
$temporary = $null
try {
if ($Operation.action -ne 'Adopt') {
if ($Operation.mode -eq 'registry') {
$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
Set-RegistryDeclaration -Root $Operation.target -Declaration $Operation.desired
}
else {
$backup = Backup-ConfigTarget -Operation $Operation -Paths $Paths
$directory = Split-Path -Parent $Operation.target
[void](New-Item -ItemType Directory -Path $directory -Force)
$temporary = Join-Path $directory ".$([System.IO.Path]::GetFileName($Operation.target)).$([guid]::NewGuid().ToString('N')).tmp"
if ($Operation.mode -eq 'copy') { Copy-Item -LiteralPath $Operation.source -Destination $temporary -Force }
elseif ($Operation.mode -eq 'ini-overlay') { [IO.File]::WriteAllText($temporary, (Merge-IniFile -Target $Operation.target -Desired $Operation.desired), [Text.UTF8Encoding]::new($false)) }
elseif ($Operation.mode -eq 'hosts-block') { [IO.File]::WriteAllText($temporary, (Set-HostsBlockContent -Target $Operation.target -Name $Operation.name -Lines $Operation.desired), [Text.UTF8Encoding]::new($false)) }
else { throw "Unsupported config mode '$($Operation.mode)'." }
[System.IO.File]::Move($temporary, $Operation.target, $true)
}
}
if (-not $State.Contains('configs')) { $State.configs = [ordered]@{} }
$State.configs[$Operation.name] = [ordered]@{
target = $Operation.target
deployedHash = $Operation.sourceHash
sourceHash = $Operation.sourceHash
mode = $Operation.mode
deployedAt = [DateTimeOffset]::UtcNow.ToString('o')
lastBackup = $backup
}
Write-JsonAtomic -Path $Paths.State -Value $State
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 }
}
finally { Remove-Item -LiteralPath $temporary -Force -ErrorAction SilentlyContinue }
}
function Restore-ConfigBackup {
param([Parameter(Mandatory)][string]$Name, [Parameter(Mandatory)]$Paths, [Parameter(Mandatory)]$State)
if (-not $State.Contains('configs') -or -not $State.configs.Contains($Name)) { throw "No managed state exists for config '$Name'." }
$mode = if ($State.configs[$Name].Contains('mode')) { [string]$State.configs[$Name].mode } else { 'copy' }
if ($mode -eq 'registry') { throw "Automatic restore is not supported for registry config '$Name'; inspect its JSON backup and restore selected values deliberately." }
if ($mode -eq 'hosts-block') { throw "Automatic restore is not supported for hosts config '$Name'; restore its backup from an administrator shell." }
$folder = Join-Path $Paths.Backups $Name
$backup = Get-ChildItem -LiteralPath $folder -Filter '*.bak' -File -ErrorAction SilentlyContinue | Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1
if ($null -eq $backup) { throw "No backup exists for config '$Name'." }
$target = [string]$State.configs[$Name].target
$current = [pscustomobject]@{ name = $Name; target = $target }
[void](Backup-ConfigTarget -Operation $current -Paths $Paths)
[void](New-Item -ItemType Directory -Path (Split-Path -Parent $target) -Force)
Copy-Item -LiteralPath $backup.FullName -Destination $target -Force
$hash = Get-FileHashValue -Path $target
$State.configs[$Name].deployedHash = $hash
$State.configs[$Name].sourceHash = $hash
$State.configs[$Name].deployedAt = [DateTimeOffset]::UtcNow.ToString('o')
Write-JsonAtomic -Path $Paths.State -Value $State
[pscustomobject]@{ name = $Name; status = 'Restored'; message = "Restored $($backup.FullName)" }
}
Export-ModuleMember -Function Get-UserPathMap, Resolve-ConfigTarget, Resolve-ConfigSource, Get-FileHashValue, Get-ConfigPlan, Get-ConfigLocations, Export-ConfigCapture, Invoke-ConfigOperation, Restore-ConfigBackup