跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

windows-evaluation.tests.ps1

195 行 · 12.7 KB历史下载
1#requires -Version 5.1
2$ErrorActionPreference = 'Stop'
3. (Join-Path $PSScriptRoot 'windows-guest-media.ps1')
4$setupPath = Join-Path $PSScriptRoot 'start-windows-evaluation-setup.ps1'
5$errors = $null
6$ast = [Management.Automation.Language.Parser]::ParseFile($setupPath, [ref]$null, [ref]$errors)
7if ($errors.Count) { throw $errors[0] }
8$null = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'initialize-windows-test-accounts.ps1'), [ref]$null, [ref]$errors)
9if ($errors.Count) { throw $errors[0] }
10foreach ($name in @('New-EvaluationAnswer', 'Get-EvaluationImage')) {
11 $fn = $ast.Find({ param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -eq $name }, $true)
12 . ([scriptblock]::Create($fn.Extent.Text))
13}
14function Assert-Check([bool]$condition, [string]$message) { if (!$condition) { throw $message } }
15function Expect-Error([scriptblock]$run, [string]$contains) {
16 try { $null = & $run } catch {
17 if ($_.Exception.Message.Contains($contains)) { return }
18 throw
19 }
20 throw "Expected failure: $contains"
21}
22$template = [IO.File]::ReadAllText((Join-Path $PSScriptRoot 'windows-evaluation-autounattend.xml'))
23$interactive = [xml](New-EvaluationAnswer $template 3 64GB $false)
24Assert-Check ($interactive.SelectSingleNode("//*[local-name()='AcceptEula']").InnerText -eq 'false') 'Native license acceptance page suppressed'
25Expect-Error { New-EvaluationAnswer $template 0 64GB $true } 'Invalid evaluation image'
26Expect-Error { New-EvaluationAnswer $template 1 32GB $true } 'Invalid evaluation image'
27$doc = [xml](New-EvaluationAnswer $template 3 64GB $true)
28$ns = [Xml.XmlNamespaceManager]::new($doc.NameTable)
29$ns.AddNamespace('u','urn:schemas-microsoft-com:unattend')
30function Value([string]$xpath) { return $doc.SelectSingleNode($xpath, $ns).InnerText }
31Assert-Check ((Value '//u:WillWipeDisk') -eq 'false') 'Disk wipe enabled'
32Assert-Check ((Value '//u:AcceptEula') -eq 'true') 'Missing recorded consent'
33Assert-Check ((Value '//u:InstallTo/u:DiskID') -eq '0' -and (Value '//u:InstallTo/u:PartitionID') -eq '3') 'Wrong Windows partition'
34Assert-Check ((Value '//u:InstallFrom/u:MetaData/u:Value') -eq '3') 'Selected image index lost'
35Assert-Check ((Value '//u:CreatePartition[u:Order="3"]/u:Size') -eq '63722') 'Wrong partition geometry'
36Assert-Check ((Value '//u:CreatePartition[u:Order="4"]/u:Extend') -eq 'true') 'Missing recovery partition'
37Assert-Check ($doc.SelectNodes('//u:AutoLogon | //u:UserAccounts | //u:RunSynchronous | //u:HideOnlineAccountScreens | //u:SkipMachineOOBE | //u:ProductKey', $ns).Count -eq 0) 'Unexpected setup bypass or embedded credential'
38
39# Exercise multi-index WIM detection while preserving a pre-existing ISO mount.
40$temp = New-Item -ItemType Directory -Path (Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N')))
41try {
42 $null = New-PSDrive -Name CAGEQA -PSProvider FileSystem -Root $temp.FullName
43 $null = New-Item -Path 'CAGEQA:\sources' -ItemType Directory
44 $null = New-Item -Path 'CAGEQA:\sources\install.wim' -ItemType File
45 $script:ownMount = $false
46 $script:dismounted = 0
47 $script:ambiguous = $false
48 function Get-DiskImage { param($ImagePath) [pscustomobject]@{Attached = !$script:ownMount} }
49 function Get-Volume { process { [pscustomobject]@{DriveLetter='CAGEQA'} } }
50 function Mount-DiskImage { param($ImagePath,$Access,$StorageType) Assert-Check ($Access -eq 'ReadOnly') 'ISO was mounted writable' }
51 function Dismount-DiskImage { param($ImagePath) $script:dismounted++ }
52 function Get-WindowsImage {
53 param($ImagePath,$Index)
54 if (!$Index) { return @([pscustomobject]@{ImageIndex=1}, [pscustomobject]@{ImageIndex=2}) }
55 $edition = if ($Index -eq 2 -or $script:ambiguous) { 'EnterpriseEval' } else { 'Professional' }
56 return [pscustomobject]@{ImageIndex=$Index; EditionId=$edition; Architecture=9; Languages=@('en-US')}
57 }
58 Assert-Check ((Get-EvaluationImage 'test.iso').ImageIndex -eq 2) 'Incorrect edition selected'
59 Assert-Check ($script:dismounted -eq 0) 'Existing ISO mount was disconnected'
60 $script:ownMount = $true
61 $script:ambiguous = $true
62 Expect-Error { Get-EvaluationImage 'test.iso' } 'exactly one'
63 Assert-Check ($script:dismounted -eq 1) 'Failed to release our ISO mount on error'
64} finally {
65 Remove-PSDrive -Name CAGEQA -ErrorAction SilentlyContinue
66 Remove-Item -LiteralPath $temp.FullName -Recurse
67}
68Write-Output 'Passed evaluation image selection, answer-file consent, GPT layout, reserved recovery capacity, original OOBE and ISO mount cleanup.'
69
70# Run the production orchestration starting at target validation. Host services
71# are simulated here, while media/receipt publishing uses the real filesystem.
72$steps = $ast.EndBlock.Statements
73$first = @($steps | Where-Object { $_.Extent.Text.StartsWith('$root = Get-Item') })[0].Extent.StartOffset
74$testScriptDirectory = $PSScriptRoot
75$orchestration = [scriptblock]::Create($ast.Extent.Text.Substring($first).Replace('$PSScriptRoot', '$testScriptDirectory'))
76$temp = New-Item -ItemType Directory -Path (Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N')))
77try {
78 $VMId = [guid]::NewGuid()
79 $InstanceDirectory = $temp.FullName
80 $script:testVM = [pscustomobject]@{Id=$VMId; ConfigurationLocation=$temp.FullName; State='Off'; Generation=2}
81 $disk = Join-Path $temp.FullName 'system.vhdx'
82 $iso = Join-Path $temp.FullName 'setup.iso'
83 $PowerShellZip = Join-Path $temp.FullName 'fixture.zip'
84 [IO.File]::WriteAllText($PowerShellZip, 'package fixture')
85 $GuestPowerShellSHA256 = (Get-FileHash -LiteralPath $PowerShellZip).Hash
86 [IO.File]::WriteAllText($disk,'qa-placeholder')
87 [IO.File]::WriteAllText($iso,'simulated official media')
88 $ExpectedIsoSha256 = (Get-FileHash -LiteralPath $iso).Hash
89 $script:testDrive = [pscustomobject]@{Path=$disk}
90 $script:testDVDs = @([pscustomobject]@{Path=$iso})
91 $script:failSectorWrite = $true
92 $script:failFirmware = $false
93 $script:partitionStyle = 'RAW'
94 $script:mounts = 0
95 $script:answerAttachments = 0
96 $Start = $false
97 [switch]$AcceptEvaluationTerms = $false
98 function Get-VM { param($Id) $script:testVM }
99 function Get-VMFirmware { param($VM) [pscustomobject]@{SecureBoot='On'; SecureBootTemplate='MicrosoftWindows'} }
100 function Get-VMNetworkAdapter { param($VM) }
101 function Get-VMSnapshot { param($VM) }
102 function Get-VMSecurity { param($VM) [pscustomobject]@{TpmEnabled=$true} }
103 function Get-VMHardDiskDrive { process { $script:testDrive } }
104 function Get-VMDvdDrive { param($VM) $script:testDVDs }
105 function Get-VHD { param($Path) [pscustomobject]@{VhdType='Dynamic';ParentPath=$null;Attached=$false;Size=64GB} }
106 function Get-EvaluationImage { param($Path) [pscustomobject]@{EditionId='EnterpriseEval';ImageIndex=3} }
107 function Mount-VHD { param($Path,[switch]$ReadOnly,[switch]$NoDriveLetter) Assert-Check ($ReadOnly -and $NoDriveLetter) 'Writable host mount';$script:mounts++ }
108 function Get-Disk { process { [pscustomobject]@{ IsReadOnly=$true; PartitionStyle=$script:partitionStyle } } }
109 function Dismount-VHD { param($Path) $script:mounts-- }
110 function Write-AnswerISO {
111 param($Source,$Output)
112 $xml = Join-Path $Source 'Autounattend.xml'
113 $answer = [xml][IO.File]::ReadAllText($xml)
114 $runs = @($answer.SelectNodes('//*[local-name()="RunSynchronousCommand"]'))
115 Assert-Check ($runs.Count -eq 1 -and $runs[0].ParentNode.ParentNode.ParentNode.pass -eq 'specialize') 'Expected one system setup action'
116 $path = $runs[0].SelectSingleNode('*[local-name()="Path"]').InnerText
117 $cmd = Join-Path $Source 'install.cmd'
118 $hash = (Get-FileHash -LiteralPath $cmd).Hash
119 Assert-Check ($path.Length -le 259 -and $path -match $hash) 'Boot command did not pin its installer or exceeds the Windows Setup length limit'
120 Assert-Check ((Get-FileHash -LiteralPath (Join-Path $Source 'PowerShell.zip')).Hash -eq $GuestPowerShellSHA256) 'Guest package is absent or incorrect'
121 Assert-Check ([IO.File]::ReadAllText($cmd) -match $GuestPowerShellSHA256) 'Guest did not receive the trusted package digest'
122 [IO.File]::Copy($xml, $Output)
123 if ($script:failSectorWrite) { throw 'injected media-write failure' }
124 }
125 function Grant-VMAnswerReadAccess { param($ISO,$Id) }
126 function Add-VMDvdDrive {
127 param($VM,$Path,[switch]$Passthru)
128 $script:answerAttachments++
129 $added = [pscustomobject]@{Path=$Path}
130 $script:testDVDs += $added
131 $added
132 }
133 function Set-VMDvdDrive {
134 param($VMDvdDrive,$Path,[switch]$Passthru)
135 $VMDvdDrive.Path = $Path
136 $VMDvdDrive
137 }
138 function Set-VMFirmware {
139 param($VM,$BootOrder)
140 if ($script:failFirmware) { throw 'injected firmware failure' }
141 Assert-Check ($BootOrder[0].Path -eq $script:testDrive.Path) 'Blank disk must precede setup media in boot order'
142 }
143
144 Expect-Error { & $orchestration } 'injected media-write failure'
145 $answerRoot = Join-Path $temp.FullName 'evaluation-setup'
146 Assert-Check (!(Test-Path (Join-Path $answerRoot 'native-pwsh7'))) 'Incomplete answer was published'
147 Assert-Check ($script:testDVDs.Count -eq 1) 'DVD attached before media was complete'
148 $script:failSectorWrite = $false
149 $script:failFirmware = $true
150 Expect-Error { & $orchestration } 'injected firmware failure'
151 Assert-Check ($script:testDVDs.Count -eq 2) 'Did not exercise partially attached DVD'
152 $script:failFirmware = $false
153 $ready = & $orchestration
154 Assert-Check ($ready.LicenseUI -eq 'native' -and !$ready.PSObject.Properties['EvaluationTermsAcceptedUtc']) 'Native setup receipt claimed acceptance'
155 Assert-Check ($script:answerAttachments -eq 1) 'Reused VM received duplicate DVD'
156 $AcceptEvaluationTerms = $true
157 $ready = & $orchestration
158 Assert-Check ($ready.LicenseUI -eq 'accepted' -and [bool]$ready.EvaluationTermsAcceptedUtc) 'Explicit acceptance not recorded'
159 Assert-Check ($script:answerAttachments -eq 1 -and $script:testDVDs.Count -eq 2) 'Changing license mode added another drive'
160 # A newly created VM already has a generic answer DVD. Evaluation setup
161 # must replace it, otherwise Windows can discover two answer documents.
162 $script:testDVDs[1].Path = Join-Path $InstanceDirectory 'windows-guest-tools.iso'
163 $ready = & $orchestration
164 Assert-Check ($script:testDVDs.Count -eq 2 -and $script:testDVDs[1].Path -eq $ready.AnswerISO -and $script:answerAttachments -eq 1) 'Generic setup DVD was not replaced'
165 $script:partitionStyle = 'GPT'
166 $AcceptEvaluationTerms = $false
167 Expect-Error { & $orchestration } 'not empty and RAW'
168 Assert-Check ($script:testDVDs[1].Path -eq $ready.AnswerISO -and $script:mounts -eq 0) 'Retry modified a partitioned VM or leaked a mount'
169
170 # Exercise the generic-media reuse path with no download, then confirm its
171 # mount is released even if the payload has been damaged.
172 $genericISO = Join-Path $temp.FullName 'generic.iso'
173 [IO.File]::WriteAllText($genericISO, 'simulated Cage DVD')
174 $null = New-PSDrive -Name CAGEMEDIA -PSProvider FileSystem -Root $temp.FullName
175 $onDisc = Join-Path 'CAGEMEDIA:\' 'PowerShell.zip'
176 Copy-Item -LiteralPath $PowerShellZip -Destination $onDisc
177 $generic = '<unattend xmlns="urn:schemas-microsoft-com:unattend"><settings pass="specialize"/></unattend>'
178 function Get-DiskImage { param($ImagePath) [pscustomobject]@{Attached=$false} }
179 function Get-Volume { process { [pscustomobject]@{DriveLetter='CAGEMEDIA'; FileSystemLabel='CAGE_ANSWER'} } }
180 function Mount-DiskImage { param($ImagePath,$Access,$StorageType) Assert-Check ($Access -eq 'ReadOnly') 'Writable optical source'; $script:mounts++ }
181 function Dismount-DiskImage { param($ImagePath) $script:mounts-- }
182 function Invoke-WebRequest { throw 'Downloaded an existing offline package' }
183 $output = Join-Path $temp.FullName 'readback.iso'
184 New-WindowsGuestAnswerISO $output ([xml]$generic) '' $genericISO
185 $raw = [xml][IO.File]::ReadAllText($output)
186 Assert-Check (!$raw.SelectSingleNode('//*[local-name()="AcceptEula" or local-name()="DiskConfiguration" or local-name()="UserAccounts"]')) 'Generic media changed the interactive Windows setup'
187 Remove-Item -LiteralPath $output
188 Set-Content -LiteralPath $onDisc -Value 'damaged package'
189 Expect-Error { New-WindowsGuestAnswerISO $output ([xml]$generic) '' $genericISO } 'SHA-256'
190 Assert-Check (!(Test-Path $output) -and $script:mounts -eq 0) 'Corrupt guest tools were published or the optical image remained mounted'
191} finally {
192 Remove-PSDrive -Name CAGEMEDIA -ErrorAction SilentlyContinue
193 Remove-Item -LiteralPath $temp.FullName -Recurse
194}
195Write-Output 'Passed injected media-write and firmware failures, retry with DVD attached, explicit/native license selection and refusal to touch a partitioned guest disk.'