diff --git a/README.md b/README.md index e88073b..a824c54 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,23 @@ the Windows edition and able to reach its configured sources. ## Onboard a machine To bootstrap directly from the web, replace `example-desktop` with the machine -manifest to use and run this in Windows PowerShell: +manifest to use and run this in Windows PowerShell. The script is staged to a +temporary file because administrator relaunch cannot work from an in-memory +script block: ```powershell -& ([scriptblock]::Create((irm 'https://proxy.dandaedre.com/gitea/Beffroi/config-central/raw/branch/main/bootstrap.ps1'))) ` - -Repository 'https://proxy.dandaedre.com/gitea/Beffroi/config-central.git' ` - -Branch main ` - -Machine example-desktop +$bootstrap = Join-Path $env:TEMP "config-central-bootstrap-$([guid]::NewGuid().ToString('N')).ps1" +try { + irm 'https://proxy.dandaedre.com/gitea/Beffroi/config-central/raw/branch/main/bootstrap.ps1' -OutFile $bootstrap + powershell.exe -NoProfile -ExecutionPolicy Bypass -File $bootstrap ` + -Repository 'https://proxy.dandaedre.com/gitea/Beffroi/config-central.git' ` + -Branch main ` + -Machine example-desktop + if ($LASTEXITCODE -ne 0) { throw "Bootstrap failed with exit code $LASTEXITCODE." } +} +finally { + Remove-Item -LiteralPath $bootstrap -Force -ErrorAction SilentlyContinue +} ``` Download `bootstrap.ps1` from a trusted revision of this repository, inspect it, @@ -50,6 +60,10 @@ machine selection, adds `cc` to the user PATH, and performs the first apply. It is safe to rerun after a failed prerequisite installation. Use `-SkipApply` when you only want to establish the checkout and launcher. +A UAC prompt appears only when administrator work is pending and the current +terminal is not already elevated. The prompt covers WinGet repair or the batch +of machine-scope packages and machine configuration changes. + Open a new terminal after bootstrap so the updated user PATH is visible, then check the installation: diff --git a/TASKS.md b/TASKS.md index 6af0045..1df44c6 100644 --- a/TASKS.md +++ b/TASKS.md @@ -72,6 +72,7 @@ open until it is run on disposable machines with the required account setups. modification; handle concurrent user sessions. - [x] Implement PowerShell 5.1 bootstrap to check or establish WinGet, Git, and PowerShell 7, with explicit handling of missing WinGet registration. +- [x] Stage web bootstrap as a file and use absolute PowerShell paths for elevation. - [x] Clone the repository, save machine selection, install the launcher, and perform the first apply. - [ ] Verify bootstrap can resume after interrupted prerequisite installation. diff --git a/bootstrap.ps1 b/bootstrap.ps1 index acaa712..1a88615 100644 --- a/bootstrap.ps1 +++ b/bootstrap.ps1 @@ -12,6 +12,11 @@ param( Set-StrictMode -Version 2.0 $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$script:BootstrapScriptPath = if ($MyInvocation.MyCommand.PSObject.Properties['Path']) { [string]$MyInvocation.MyCommand.Path } else { $null } + +if ([string]::IsNullOrWhiteSpace($script:BootstrapScriptPath)) { + throw 'bootstrap.ps1 must be downloaded and run as a file so administrator relaunch can work.' +} function Test-Administrator { $identity = [Security.Principal.WindowsIdentity]::GetCurrent() @@ -25,6 +30,14 @@ function Invoke-BootstrapWingetInstall { if ($LASTEXITCODE -ne 0) { throw "WinGet failed to install '$Id' (exit $LASTEXITCODE)." } } +function Get-PowerShell7Path { + $command = Get-Command pwsh.exe -ErrorAction SilentlyContinue + if ($command) { return $command.Source } + $installedPath = Join-Path $env:ProgramFiles 'PowerShell\7\pwsh.exe' + if (Test-Path -LiteralPath $installedPath -PathType Leaf) { return $installedPath } + throw 'PowerShell 7 was installed but pwsh.exe could not be located. Open a new terminal and rerun bootstrap.ps1.' +} + function Ensure-WinGet { if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return } try { @@ -34,7 +47,7 @@ function Ensure-WinGet { if (Get-Command winget.exe -ErrorAction SilentlyContinue) { return } if (-not (Test-Administrator)) { - $arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -RepairWinGetOnly" + $arguments = "-NoLogo -NoProfile -ExecutionPolicy Bypass -File `"$script:BootstrapScriptPath`" -RepairWinGetOnly" $repair = Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $arguments -Wait -PassThru if ($repair.ExitCode -ne 0) { throw "Elevated WinGet repair failed (exit $($repair.ExitCode))." } if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { @@ -66,6 +79,7 @@ Write-Host 'Checking WinGet...' Ensure-WinGet if (-not (Get-Command git.exe -ErrorAction SilentlyContinue)) { Invoke-BootstrapWingetInstall -Id 'Git.Git' } if (-not (Get-Command pwsh.exe -ErrorAction SilentlyContinue)) { Invoke-BootstrapWingetInstall -Id 'Microsoft.PowerShell' } +$powerShell7 = Get-PowerShell7Path $git = (Get-Command git.exe -ErrorAction Stop).Source if (Test-Path -LiteralPath (Join-Path $Checkout '.git')) { @@ -120,6 +134,6 @@ if (($userPath -split ';') -notcontains $launcherDirectory) { Write-Host "Config Central configured for '$Machine'." if (-not $SkipApply) { - & pwsh.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Checkout 'cc.ps1') apply -Machine $Machine -DataRoot $dataRoot -RepositoryRoot $Checkout + & $powerShell7 -NoLogo -NoProfile -ExecutionPolicy Bypass -File (Join-Path $Checkout 'cc.ps1') apply -Machine $Machine -DataRoot $dataRoot -RepositoryRoot $Checkout exit $LASTEXITCODE } diff --git a/src/Elevation.psm1 b/src/Elevation.psm1 index cbb2e28..e5c9760 100644 --- a/src/Elevation.psm1 +++ b/src/Elevation.psm1 @@ -32,7 +32,7 @@ function Invoke-ElevatedPackageBatch { 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 } + try { $process = Start-Process -FilePath (Join-Path $PSHOME '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)." } $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json -Depth 16 @@ -59,7 +59,7 @@ function Invoke-ElevatedConfigOperation { $worker = Join-Path $RepositoryRoot 'src/elevated-worker.ps1' foreach ($path in @($requestPath, $resultPath, $RepositoryRoot, $worker)) { if ($path.Contains('"')) { throw 'Elevation paths contain unsupported quote characters.' } } $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 } + try { $process = Start-Process -FilePath (Join-Path $PSHOME '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 hosts worker failed with exit code $($process.ExitCode)." } $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json -Depth 16 diff --git a/tests/Bootstrap.Tests.ps1 b/tests/Bootstrap.Tests.ps1 new file mode 100644 index 0000000..6832e8d --- /dev/null +++ b/tests/Bootstrap.Tests.ps1 @@ -0,0 +1,13 @@ +Describe 'Bootstrap invocation' { + It 'rejects in-memory execution because elevation requires a script file' { + $source = Get-Content "$PSScriptRoot/../bootstrap.ps1" -Raw + $bootstrap = [scriptblock]::Create($source) + $previousLocalAppData = $env:LOCALAPPDATA + try { + $env:LOCALAPPDATA = $TestDrive + { & $bootstrap -Repository 'https://example.invalid/config-central.git' -Machine test } | + Should -Throw '*must be downloaded and run as a file*' + } + finally { $env:LOCALAPPDATA = $previousLocalAppData } + } +} diff --git a/tests/Elevation.Tests.ps1 b/tests/Elevation.Tests.ps1 new file mode 100644 index 0000000..9047246 --- /dev/null +++ b/tests/Elevation.Tests.ps1 @@ -0,0 +1,26 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../src/Elevation.psm1" -Force +} + +Describe 'Elevation host selection' { + It 'uses the current PowerShell installation instead of PATH' { + InModuleScope Elevation -Parameters @{ Working = $TestDrive } { + Mock Test-IsAdministrator { $false } + Mock Protect-ElevationFile {} + Mock Start-Process { + $script:startedFile = $FilePath + $match = [regex]::Match($ArgumentList, '-ResultPath\s+"([^"]+)"') + '{"succeeded":true,"results":[]}' | Set-Content -LiteralPath $match.Groups[1].Value + [pscustomobject]@{ ExitCode = 0 } + } + + $paths = [pscustomobject]@{ Root = $Working } + $operation = [pscustomobject]@{ + kind = 'package'; name = 'Example.App'; action = 'Install'; reason = 'Missing' + package = [pscustomobject]@{ id = 'Example.App'; source = 'winget'; scope = 'machine'; update = 'latest' } + } + [void](Invoke-ElevatedPackageBatch -Operations @($operation) -RepositoryRoot $Working -Paths $paths) + $script:startedFile | Should -Be (Join-Path $PSHOME 'pwsh.exe') + } + } +}