| 1 | #requires -Version 5.1 |
| 2 | $ErrorActionPreference = 'Stop' |
| 3 | . (Join-Path $PSScriptRoot 'windows-host-image.ps1') |
| 4 | function Assert-Check([bool]$Condition, [string]$Message) { if (!$Condition) { throw $Message } } |
| 5 | $credential = [pscredential]::new('CageAdmin', (ConvertTo-SecureString 'Test-only<&>"Account!123' -AsPlainText -Force)) |
| 6 | $answer = New-CageISOAnswer $credential |
| 7 | $ns = [Xml.XmlNamespaceManager]::new($answer.NameTable) |
| 8 | $ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend') |
| 9 | $roundtrip = [xml]$answer.OuterXml |
| 10 | Assert-Check ($roundtrip.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText -ceq 'CageAdmin') 'Initial account name changed.' |
| 11 | Assert-Check ($roundtrip.SelectSingleNode('//u:LocalAccount/u:Password/u:Value', $ns).InnerText -ceq $credential.GetNetworkCredential().Password) 'Password XML escaping changed the credential.' |
| 12 | Assert-Check ($answer.SelectSingleNode('//u:LocalAccount/u:Group', $ns).InnerText -ceq 'Administrators') 'PowerShell Direct needs the initial administrator.' |
| 13 | foreach ($setting in @('HideOnlineAccountScreens', 'HideWirelessSetupInOOBE')) { |
| 14 | Assert-Check ($answer.SelectSingleNode('//u:OOBE/u:'+$setting, $ns).InnerText -ceq 'true') 'Offline OOBE settings are missing.' |
| 15 | } |
| 16 | Assert-Check ($answer.SelectNodes('//u:DiskConfiguration | //u:ImageInstall | //u:HideEULAPage | //u:AcceptEula | //u:ProductKey | //u:AutoLogon | //u:UILanguage | //u:SkipMachineOOBE', $ns).Count -eq 0) 'Manual ISO choices or administrator sign-in were overridden.' |
| 17 | foreach ($name in @('Administrator', 'cagesetup', 'host\user', '[email protected]', 'abcdefghijklmnopqrstu')) { |
| 18 | try { |
| 19 | $null = New-CageISOAnswer ([pscredential]::new($name, $credential.Password)) |
| 20 | throw 'Invalid account accepted' |
| 21 | } catch { if ($_.Exception.Message -eq 'Invalid account accepted') { throw } } |
| 22 | } |
| 23 | |
| 24 | # Execute the production branch which chooses the answer before creating a disk. |
| 25 | $errors = $null |
| 26 | $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'new-windows-test-vm.ps1'), [ref]$null, [ref]$errors) |
| 27 | Assert-Check ($errors.Count -eq 0) 'VM creation script failed to parse.' |
| 28 | $selection = @($ast.EndBlock.Statements | Where-Object { $_.Extent.Text.StartsWith('if ($fromHost) {') })[0] |
| 29 | Assert-Check ($null -ne $selection) 'Missing production answer selection.' |
| 30 | $createAnswer = [scriptblock]::Create($selection.Extent.Text) |
| 31 | $script:prompts = 0 |
| 32 | function Get-Credential { param($UserName, $Message); $script:prompts++; return $credential } |
| 33 | $fromHost = $false |
| 34 | $GuestAdministrator = $null |
| 35 | . $createAnswer |
| 36 | Assert-Check ($script:prompts -eq 1 -and $answer.SelectNodes('//u:LocalAccount', $ns).Count -eq 1) 'The manual route did not collect an offline account.' |
| 37 | . $createAnswer |
| 38 | Assert-Check ($script:prompts -eq 1) 'An explicit credential prompted again.' |
| 39 | $fromHost = $true |
| 40 | $GuestAdministrator = [pscredential]::new('cagesetup', $credential.Password) |
| 41 | $ImageLanguage = 'zh-CN' |
| 42 | . $createAnswer |
| 43 | Assert-Check ($answer.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText -ceq 'cagesetup') 'Clone setup account changed.' |
| 44 | Assert-Check ($answer.SelectSingleNode('//u:UILanguage', $ns).InnerText -ceq 'zh-CN') 'Clone locale changed.' |
| 45 | |
| 46 | # The owner's progress reader accepts only known stages and reads the final |
| 47 | # stage after process exit. Arbitrary child output never becomes UI content. |
| 48 | $ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'setup-windows-guest.ps1'), [ref]$null, [ref]$errors) |
| 49 | Assert-Check ($errors.Count -eq 0) 'Setup orchestration failed to parse.' |
| 50 | $wait = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Wait-CageWindowsInstaller' }, $true) |
| 51 | . ([scriptblock]::Create($wait.Extent.Text)) |
| 52 | $progressFile = [IO.Path]::GetTempFileName() |
| 53 | $heldProgress = [IO.File]::Open($progressFile, 'Open', 'ReadWrite', 'ReadWrite') |
| 54 | $writer = [IO.File]::Open($progressFile, 'Open', 'Write', 'ReadWrite') |
| 55 | try { |
| 56 | $process = [pscustomobject]@{ Position = 0; Writer = $writer; Stages = @('CAGE_GUEST_STAGE windows-11 account', 'private diagnostic fixture', 'CAGE_GUEST_STAGE windows-11 media', 'CAGE_GUEST_STAGE windows-11 tools', 'CAGE_GUEST_STAGE windows-11 services', 'CAGE_GUEST_STAGE windows-11 oobe') } |
| 57 | $process | Add-Member -MemberType ScriptMethod -Name WaitForExit -Value { |
| 58 | param($Timeout) |
| 59 | $bytes = [Text.Encoding]::UTF8.GetBytes($this.Stages[$this.Position]) |
| 60 | $this.Writer.Position = 0 |
| 61 | $this.Writer.SetLength(0) |
| 62 | $this.Writer.Write($bytes, 0, $bytes.Length) |
| 63 | $this.Writer.Flush() |
| 64 | $this.Position++ |
| 65 | return $this.Position -eq $this.Stages.Count |
| 66 | } |
| 67 | $stages = @(Wait-CageWindowsInstaller $process $progressFile) |
| 68 | Assert-Check ($stages.Count -eq 5 -and $stages[-1] -ceq 'CAGE_GUEST_STAGE windows-11 oobe') 'Final progress or stage filtering failed.' |
| 69 | $writer.Dispose() |
| 70 | |
| 71 | # Execute the exact encoded wrapper in a real child PowerShell process. |
| 72 | # UAC itself is covered by native acceptance, while file sharing is exercised here. |
| 73 | $wrapper = $ast.Find({ param($node) $node -is [Management.Automation.Language.AssignmentStatementAst] -and $node.Left.Extent.Text -eq '$command' -and $node.Right.Extent.Text.StartsWith("@'") }, $true) |
| 74 | $literal = $wrapper.Right.Find({ param($node) $node -is [Management.Automation.Language.StringConstantExpressionAst] }, $true) |
| 75 | $command = $literal.Value |
| 76 | $fixtureScript = $progressFile+'.ps1' |
| 77 | $stdout = $progressFile+'.stdout' |
| 78 | $stderr = $progressFile+'.stderr' |
| 79 | try { |
| 80 | [IO.File]::WriteAllText($fixtureScript, "Write-Output 'CAGE_GUEST_STAGE windows-11 account'`nWrite-Output 'private diagnostic fixture'`nWrite-Output 'CAGE_GUEST_STAGE windows-11 oobe'") |
| 81 | $payload = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((@{ProgressFile=$progressFile}|ConvertTo-Json -Compress))) |
| 82 | $scriptPath = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($fixtureScript)) |
| 83 | $command = $command.Replace('__PARAMETERS__', $payload).Replace('__SCRIPT__', $scriptPath) |
| 84 | $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) |
| 85 | $child = Start-Process -FilePath (Get-Process -Id $PID).Path -ArgumentList @('-NoLogo','-NoProfile','-NonInteractive','-EncodedCommand',$encoded) -RedirectStandardOutput $stdout -RedirectStandardError $stderr -PassThru |
| 86 | try { |
| 87 | $null = $child.Handle |
| 88 | $forwarded = @(Wait-CageWindowsInstaller $child $progressFile) |
| 89 | Assert-Check ($child.ExitCode -eq 0) ('Encoded installer wrapper failed. '+[IO.File]::ReadAllText($stderr)) |
| 90 | Assert-Check ($forwarded[-1] -ceq 'CAGE_GUEST_STAGE windows-11 oobe') 'The actual child could not publish its final stage.' |
| 91 | } finally { $child.Dispose() } |
| 92 | } finally { |
| 93 | foreach ($path in @($fixtureScript,$stdout,$stderr)) { [IO.File]::Delete($path) } |
| 94 | } |
| 95 | } finally { $writer.Dispose(); $heldProgress.Dispose(); [IO.File]::Delete($progressFile) } |
| 96 | |
| 97 | # An interrupted or unauthenticated guest retains its answer media. Successful |
| 98 | # cleanup only removes the fixed tools ISO and preserves the original disk. |
| 99 | $directory = Join-Path ([IO.Path]::GetTempPath()) ('cage-iso-answer-'+[guid]::NewGuid().ToString('N')) |
| 100 | $null = [IO.Directory]::CreateDirectory($directory) |
| 101 | try { |
| 102 | $iso = Join-Path $directory 'windows-guest-tools.iso' |
| 103 | $disk = Join-Path $directory 'system.vhdx' |
| 104 | [IO.File]::WriteAllText($iso, 'private answer fixture') |
| 105 | [IO.File]::WriteAllText($disk, 'existing personal disk fixture') |
| 106 | $vm = [pscustomobject]@{ Id = [guid]::NewGuid() } |
| 107 | $script:guestReady = $false |
| 108 | $script:removedDVDs = @() |
| 109 | function Invoke-Command { param($Session, $ArgumentList, $ScriptBlock); if (!$script:guestReady) { throw 'Guest setup incomplete' } } |
| 110 | function Hyper-V\Get-VMDvdDrive { process { @([pscustomobject]@{Path=$iso}, [pscustomobject]@{Path='original-windows.iso'}) } } |
| 111 | function Hyper-V\Remove-VMDvdDrive { process { $script:removedDVDs += $_.Path } } |
| 112 | try { Remove-CageISOAnswer $vm 'session' $directory; throw 'Incomplete setup was accepted' } |
| 113 | catch { if ($_.Exception.Message -cne 'Guest setup incomplete') { throw } } |
| 114 | Assert-Check ((Test-Path -LiteralPath $iso) -and $script:removedDVDs.Count -eq 0) 'Unfinished setup lost its answer media.' |
| 115 | $script:guestReady = $true |
| 116 | Remove-CageISOAnswer $vm 'session' $directory |
| 117 | Assert-Check (!(Test-Path -LiteralPath $iso) -and $script:removedDVDs.Count -eq 1 -and $script:removedDVDs[0] -eq $iso) 'Cleanup touched the wrong DVD.' |
| 118 | Assert-Check ([IO.File]::ReadAllText($disk) -ceq 'existing personal disk fixture') 'Cleanup changed the retained disk.' |
| 119 | } finally { [IO.Directory]::Delete($directory, $true) } |
| 120 | Write-Output 'Passed manual ISO account/OOBE XML, retained manual choices, clone parity and elevated installer progress forwarding.' |