跳到主要内容

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

浏览文件

maintain-windows-workbench.tests.ps1

140 行 · 9.5 KB历史下载
1#requires -Version 5.1
2param([string]$Implementation=(Join-Path $PSScriptRoot 'maintain-windows-workbench.ps1'))
3$ErrorActionPreference='Stop'
4$source=[IO.File]::ReadAllText($Implementation)
5$parseErrors=$null
6$ast=[Management.Automation.Language.Parser]::ParseInput($source,[ref]$null,[ref]$parseErrors)
7if ($parseErrors.Count) { throw $parseErrors[0] }
8$bindingStart=$source.IndexOf('$bindingPath=Join-Path')
9if ($bindingStart -lt 0) { throw 'Maintenance preflight entry missing.' }
10$prelude=$source.Substring(0,$bindingStart)
11$elevation=$ast.Find({param($node)
12 $node -is [Management.Automation.Language.IfStatementAst] -and $node.Clauses[0].Item1.Extent.Text.Contains('WindowsPrincipal')
13},$true)
14if (!$elevation) { throw 'Production elevation entry missing.' }
15$elevationBody=$elevation.Clauses[0].Item2.Extent.Text
16$elevationBody=$elevationBody.Substring(1,$elevationBody.Length-2).Replace('-ScriptPath $PSCommandPath','-ScriptPath $fixtureChild')
17$hostOnly=$ast.Find({param($node)
18 $node -is [Management.Automation.Language.IfStatementAst] -and $node.Clauses[0].Item1.Extent.Text -eq '$HostOnly'
19},$true)
20if (!$hostOnly -or !$hostOnly.Extent.Text.Contains('exit 0') -or $hostOnly.Extent.Text.Contains('New-PSSession') -or $hostOnly.Extent.StartOffset -gt $source.IndexOf('Get-Credential -Message')) { throw 'HostOnly must finish after host installation.' }
21
22function Assert-Stage([string]$Command,[int]$Code) {
23 $offset=$source.IndexOf($Command)
24 if ($offset -lt 0) { throw "Stage receiver missing $Command" }
25 $assignments=@($ast.FindAll({param($node)
26 if ($node -isnot [Management.Automation.Language.AssignmentStatementAst] -or $node.Left.Extent.Text -ne '$maintenanceExitCode' -or $node.Right.Extent.Text -notmatch '^\d+$') { return $false }
27 for ($parent=$node.Parent; $parent; $parent=$parent.Parent) {
28 if ($parent -is [Management.Automation.Language.TrapStatementAst] -or $parent -is [Management.Automation.Language.FunctionDefinitionAst]) { return $false }
29 }
30 $true
31 },$true) | Where-Object {$_.Extent.StartOffset -lt $offset} | Sort-Object {$_.Extent.StartOffset})
32 if (!$assignments.Count -or [int]$assignments[-1].Right.Extent.Text -ne $Code) { throw "Wrong production failure stage for $Command" }
33}
34Assert-Stage 'Get-FileHash -LiteralPath $ManifestPath' 41
35Assert-Stage "& (Join-Path `$kit 'install-windows-host-manager.ps1')" 42
36Assert-Stage 'Get-PinnedPackage $spec.Value $cache' 46
37Assert-Stage 'New-PSSession -VMId' 43
38Assert-Stage "Invoke-Command -Session `$session -FilePath (Join-Path `$kit 'update-windows-workbench-components.ps1')" 44
39Assert-Stage '[IO.File]::Replace' 45
40
41$shell=(Get-Process -Id $PID).Path
42$temporary=Join-Path ([IO.Path]::GetTempPath()) ('cage-maintenance-feedback-'+[guid]::NewGuid().ToString('N'))
43$null=New-Item -ItemType Directory -Path $temporary
44$encoding=[Text.UTF8Encoding]::new($true)
45function Quote-Literal([string]$Value) { "'"+$Value.Replace("'","''")+"'" }
46function Run-Script([string]$Path,[hashtable]$Parameters) {
47 $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Parameters|ConvertTo-Json -Compress)))
48 $command='$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};& '+(Quote-Literal $Path)+' @a;exit $LASTEXITCODE'
49 $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
50 $start=[Diagnostics.ProcessStartInfo]::new()
51 $start.FileName=$shell
52 $start.Arguments='-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '+$encoded
53 $start.UseShellExecute=$false
54 $start.RedirectStandardOutput=$true
55 $start.RedirectStandardError=$true
56 $process=[Diagnostics.Process]::new()
57 $process.StartInfo=$start
58 try {
59 if (!$process.Start()) { throw 'Fixture process did not start.' }
60 $stdout=$process.StandardOutput.ReadToEndAsync()
61 $stderr=$process.StandardError.ReadToEndAsync()
62 if (!$process.WaitForExit(15000)) { $process.Kill(); throw 'Fixture process timed out.' }
63 [pscustomobject]@{Code=$process.ExitCode;Output=$stdout.GetAwaiter().GetResult();Error=$stderr.GetAwaiter().GetResult()}
64 } finally { $process.Dispose() }
65}
66
67try {
68 $profile=Join-Path $temporary "profile's 中文"
69 $null=New-Item -ItemType Directory -Path $profile
70 $binding=Join-Path $profile 'windows-guest.json'
71 $manifest=Join-Path $temporary 'manifest.json'
72 [IO.File]::WriteAllText($binding,'{}',$encoding)
73 [IO.File]::WriteAllText($manifest,'{}',$encoding)
74 $parameters=@{Profile=$profile;ManifestPath=$manifest;ManifestSHA256=(Get-FileHash $manifest).Hash}
75 foreach ($name in @('binding','manifest')) {
76 $requestParameters=$parameters.Clone()
77 if ($name -eq 'binding') { $requestParameters.BindingSHA256='a'*64 } else { $requestParameters.ManifestSHA256='b'*64 }
78 $result=Run-Script $Implementation $requestParameters
79 if ($result.Code -ne 41 -or !$result.Error.Contains('CAGE_WINDOWS_MAINTENANCE_VALIDATION')) { throw "Real $name preflight lost its phase $($result | ConvertTo-Json -Compress)" }
80 }
81
82 # The production RunAs block launches real isolated PowerShell children.
83 # Only the OS elevation call is replaced, so these tests require no UAC,
84 # VM, administrator credential or protected Windows directory.
85 $mock=@'
86function Join-Path($Path,$ChildPath) {
87 if ($ChildPath -eq 'WindowsPowerShell/v1.0/powershell.exe') { return $fixtureShell }
88 Microsoft.PowerShell.Management\Join-Path -Path $Path -ChildPath $ChildPath
89}
90function Start-Process($FilePath,$ArgumentList,$Verb,[switch]$PassThru) {
91 if ($FilePath -ne $fixtureShell -or $Verb -ne 'RunAs' -or !$PassThru) { throw 'Incorrect elevation contract.' }
92 if ($fixtureCancel) { throw [InvalidOperationException]::new('synthetic nested launch error',[ComponentModel.Win32Exception]::new(1223)) }
93 if ($fixtureLaunchFailure) { throw [ComponentModel.Win32Exception]::new(5) }
94 Microsoft.PowerShell.Management\Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -PassThru -NoNewWindow
95}
96'@
97 $cases=@(
98 @{Name='regular-success';Code=0;Phase='';HostOnly=$false;Tools=$true},
99 @{Name='host-success';Code=0;Phase='';HostOnly=$true;Tools=$false},
100 @{Name='validation';Code=41;Phase='VALIDATION';HostOnly=$true},
101 @{Name='manager';Code=42;Phase='HOST_MANAGER';HostOnly=$true},
102 @{Name='guest-connection';Code=43;Phase='GUEST_CONNECTION';HostOnly=$false},
103 @{Name='guest-components';Code=44;Phase='GUEST_COMPONENTS';HostOnly=$false},
104 @{Name='host-relay';Code=45;Phase='HOST_RELAY';HostOnly=$false},
105 @{Name='prepare-tools';Code=46;Phase='PACKAGE_PREPARATION';HostOnly=$false;Tools=$true},
106 @{Name='launch-failed';Code=47;Phase='AUTHORIZATION';HostOnly=$true;LaunchFailure=$true},
107 @{Name='uac-canceled';Code=48;Phase='AUTHORIZATION_CANCELED';HostOnly=$true;Cancel=$true},
108 @{Name='legacy-failed';Code=1;Phase='FAILED';HostOnly=$true;Legacy=$true},
109 @{Name='unknown-exit';Code=1;Phase='FAILED';HostOnly=$false;Unknown=$true}
110 )
111 foreach ($case in $cases) {
112 $child=Join-Path $temporary ($case.Name+"-child's 中文.ps1")
113 $expectedHost=([bool]$case.HostOnly).ToString().ToLowerInvariant()
114 $expectedTools=([bool]$case.Tools).ToString().ToLowerInvariant()
115 $childBody="`nif ([bool]`$HostOnly -ne `$$expectedHost -or [bool]`$Tools -ne `$$expectedTools -or `$GuestAdministrator -or `$BindingSHA256 -ne ('c'*64)) { exit 92 }`n"
116 if ($case.Unknown) { $childBody+='exit 77' }
117 elseif ($case.Legacy) { $childBody+='throw ''synthetic legacy error''' }
118 elseif ($case.Code -eq 0) {
119 $childBody+=$hostOnly.Extent.Text+"`nWrite-Output 'synthetic regular success'`nexit 0"
120 } else { $childBody+="`$maintenanceExitCode=$($case.Code)`nthrow 'synthetic stage error'" }
121 if ($case.Legacy) {
122 [IO.File]::WriteAllText($child,$ast.ParamBlock.Extent.Text+$childBody,$encoding)
123 } else { [IO.File]::WriteAllText($child,$prelude+$childBody,$encoding) }
124 $parentScript=Join-Path $temporary ($case.Name+'-parent.ps1')
125 $config="`n`$fixtureShell="+(Quote-Literal $shell)+"`n`$fixtureChild="+(Quote-Literal $child)+"`n`$fixtureCancel=`$"+([bool]$case.Cancel).ToString().ToLowerInvariant()+"`n`$fixtureLaunchFailure=`$"+([bool]$case.LaunchFailure).ToString().ToLowerInvariant()+"`n`$bindingHash='c'*64`n`$maintenanceExitCode=47`n"
126 $config+="`$GuestAdministrator=[pscredential]::new('synthetic-maintenance-user',(ConvertTo-SecureString 'synthetic-credential' -AsPlainText -Force))`n"
127 [IO.File]::WriteAllText($parentScript,$prelude+$config+$mock+"`n"+$elevationBody,$encoding)
128 $requestParameters=$parameters.Clone()
129 $requestParameters.HostOnly=[bool]$case.HostOnly
130 $requestParameters.Tools=[bool]$case.Tools
131 $result=Run-Script $parentScript $requestParameters
132 if ($result.Code -ne $case.Code -or ($case.Code -ne 0 -and !$result.Error.Contains('CAGE_WINDOWS_MAINTENANCE_'+$case.Phase))) {
133 throw "RunAs stage lost for $($case.Name) $($result | ConvertTo-Json -Compress)"
134 }
135 Write-Output ("Passed {0} with exit {1}" -f $case.Name,$result.Code)
136 }
137 Write-Output 'Passed real binding/manifest preflight, production stage ownership, HostOnly, regular Tools, explicit child exits, legacy errors and nested UAC cancellation (isolated processes, simulated elevation).'
138} finally {
139 Remove-Item -LiteralPath $temporary -Recurse -Force
140}