Add constrained package elevation worker

This commit is contained in:
Dandaedre 2026-10-16 13:47:53 +02:00
parent 9fe14a4c59
commit 48bb29ef44
3 changed files with 88 additions and 3 deletions

View File

@ -64,11 +64,11 @@ Complete the core CLI and manual workflow before optional automation or a TUI.
## 6. Implement elevation and first-machine setup
- [ ] Implement a constrained elevated worker with validated inputs and structured
- [x] Implement a constrained elevated worker with validated inputs and structured
results, including cancellation and failure handling.
- [ ] Batch administrator operations while preserving the original user's paths
- [x] Batch administrator operations while preserving the original user's paths
and keeping user operations in the user session.
- [ ] Secure machine-level state and elevated-worker inputs against unintended
- [x] Secure machine-level state and elevated-worker inputs against unintended
modification; handle concurrent user sessions.
- [ ] Implement PowerShell 5.1 bootstrap to check or establish WinGet, Git, and
PowerShell 7, with explicit handling of missing WinGet registration.

45
src/Elevation.psm1 Normal file
View File

@ -0,0 +1,45 @@
Set-StrictMode -Version Latest
function Test-IsAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Protect-ElevationFile {
param([Parameter(Mandatory)][string]$Path)
$currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetAccessRuleProtection($true, $false)
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($currentSid, 'FullControl', 'Allow'))
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('BUILTIN\Administrators', 'FullControl', 'Allow'))
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('NT AUTHORITY\SYSTEM', 'FullControl', 'Allow'))
[System.IO.File]::SetAccessControl($Path, $acl)
}
function Invoke-ElevatedPackageBatch {
param([Parameter(Mandatory)]$Operations, [Parameter(Mandatory)][string]$RepositoryRoot, [Parameter(Mandatory)]$Paths, [string]$LogPath)
if (@($Operations).Count -eq 0) { return @() }
if (Test-IsAdministrator) { return Invoke-PackagePlan -Plan $Operations -LogPath $LogPath }
$requestId = [guid]::NewGuid().ToString('N')
$requestPath = Join-Path $Paths.Root "elevation-$requestId.request.json"
$resultPath = Join-Path $Paths.Root "elevation-$requestId.result.json"
$request = [ordered]@{ schemaVersion = 1; operations = @($Operations); logPath = $LogPath }
try {
$request | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $requestPath -Encoding utf8NoBOM
Protect-ElevationFile -Path $requestPath
if ($requestPath.Contains('"') -or $resultPath.Contains('"') -or $RepositoryRoot.Contains('"')) { throw 'Elevation paths contain unsupported quote characters.' }
$worker = Join-Path $RepositoryRoot 'src/elevated-worker.ps1'
$arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$worker`" -RequestPath `"$requestPath`" -ResultPath `"$resultPath`" -RepositoryRoot `"$RepositoryRoot`""
try { $process = Start-Process -FilePath 'pwsh.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru }
catch { throw "Administrator approval was cancelled or could not start: $($_.Exception.Message)" }
if ($process.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $resultPath -PathType Leaf)) { throw "Elevated worker failed with exit code $($process.ExitCode)." }
Protect-ElevationFile -Path $resultPath
$result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json -Depth 16
return @($result.results)
}
finally { Remove-Item -LiteralPath $requestPath, $resultPath -Force -ErrorAction SilentlyContinue }
}
Export-ModuleMember -Function Test-IsAdministrator, Invoke-ElevatedPackageBatch

40
src/elevated-worker.ps1 Normal file
View File

@ -0,0 +1,40 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RequestPath,
[Parameter(Mandatory)][string]$ResultPath,
[Parameter(Mandatory)][string]$RepositoryRoot
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Write-WorkerResult($Value) {
$temporary = "$ResultPath.$([guid]::NewGuid().ToString('N')).tmp"
$Value | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath $temporary -Encoding utf8NoBOM
[System.IO.File]::Move($temporary, $ResultPath, $true)
}
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]::new($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Elevated worker is not running as administrator.' }
if (-not (Test-Path -LiteralPath $RequestPath -PathType Leaf)) { throw 'Elevation request is missing.' }
$root = [System.IO.Path]::GetFullPath($RepositoryRoot)
$worker = [System.IO.Path]::GetFullPath($PSCommandPath)
if (-not $worker.StartsWith(($root.TrimEnd('\') + '\'), [System.StringComparison]::OrdinalIgnoreCase)) { throw 'Elevated worker is outside the repository snapshot.' }
$request = Get-Content -LiteralPath $RequestPath -Raw | ConvertFrom-Json -Depth 16
if ($request.schemaVersion -ne 1) { throw 'Unsupported elevation request version.' }
foreach ($operation in @($request.operations)) {
if ($operation.kind -ne 'package' -or $operation.action -notin @('Install', 'Upgrade', 'None', 'Warning')) { throw 'Elevation request contains an unsupported operation.' }
if ($operation.package.id -notmatch '^[A-Za-z0-9._+-]+$' -or $operation.package.source -notmatch '^[A-Za-z0-9._+-]+$') { throw 'Elevation request contains an unsafe package identifier.' }
if ($operation.package.PSObject.Properties['scope'] -and $operation.package.scope -ne 'machine') { throw 'Elevated operations must use machine scope.' }
}
Import-Module (Join-Path $root 'src/Packages.psm1') -Force
$results = Invoke-PackagePlan -Plan @($request.operations) -LogPath ([string]$request.logPath)
Write-WorkerResult ([ordered]@{ succeeded = -not [bool]($results | Where-Object status -eq 'Failed'); results = $results })
exit 0
}
catch {
Write-WorkerResult ([ordered]@{ succeeded = $false; error = $_.Exception.Message; results = @() })
exit 1
}